torobi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +71 -0
  3. data/Cargo.lock +539 -0
  4. data/Cargo.toml +6 -0
  5. data/LICENSE +21 -0
  6. data/README.md +259 -0
  7. data/config/ops.yml +230 -0
  8. data/docs/plan.md +3982 -0
  9. data/docs/vendoring.md +656 -0
  10. data/engine/Cargo.toml +35 -0
  11. data/engine/build.rs +253 -0
  12. data/engine/src/checkpoint.rs +513 -0
  13. data/engine/src/executor.rs +257 -0
  14. data/engine/src/export.rs +431 -0
  15. data/engine/src/fixtures.rs +518 -0
  16. data/engine/src/graph.rs +115 -0
  17. data/engine/src/init.rs +65 -0
  18. data/engine/src/interp.rs +985 -0
  19. data/engine/src/lib.rs +62 -0
  20. data/engine/src/main.rs +97 -0
  21. data/engine/src/memory.rs +109 -0
  22. data/engine/src/mlxc/array.rs +454 -0
  23. data/engine/src/mlxc/error.rs +205 -0
  24. data/engine/src/mlxc/fast.rs +46 -0
  25. data/engine/src/mlxc/handle.rs +155 -0
  26. data/engine/src/mlxc/io.rs +268 -0
  27. data/engine/src/mlxc/memory.rs +56 -0
  28. data/engine/src/mlxc/metal.rs +24 -0
  29. data/engine/src/mlxc/mod.rs +55 -0
  30. data/engine/src/mlxc/nn.rs +38 -0
  31. data/engine/src/mlxc/ops.rs +477 -0
  32. data/engine/src/mlxc/quantized.rs +405 -0
  33. data/engine/src/mlxc/random.rs +161 -0
  34. data/engine/src/mlxc/transforms.rs +439 -0
  35. data/engine/src/op.rs +745 -0
  36. data/engine/src/optimizer.rs +650 -0
  37. data/engine/src/plan.rs +1638 -0
  38. data/engine/src/runtime.rs +377 -0
  39. data/engine/src/session.rs +1523 -0
  40. data/engine/src/state.rs +1007 -0
  41. data/engine/src/tensor.rs +331 -0
  42. data/ext/torobi/Cargo.toml +21 -0
  43. data/ext/torobi/extconf.rb +42 -0
  44. data/ext/torobi/src/gvl.rs +182 -0
  45. data/ext/torobi/src/lib.rs +1037 -0
  46. data/lib/torobi/adapter_file.rb +184 -0
  47. data/lib/torobi/batch.rb +55 -0
  48. data/lib/torobi/checkpoint.rb +60 -0
  49. data/lib/torobi/dsl/builder.rb +414 -0
  50. data/lib/torobi/dsl/handle.rb +156 -0
  51. data/lib/torobi/dsl/layers.rb +82 -0
  52. data/lib/torobi/dsl.rb +35 -0
  53. data/lib/torobi/errors.rb +88 -0
  54. data/lib/torobi/export.rb +534 -0
  55. data/lib/torobi/freeze.rb +24 -0
  56. data/lib/torobi/freshness.rb +57 -0
  57. data/lib/torobi/grad_cache.rb +143 -0
  58. data/lib/torobi/graph_config.rb +301 -0
  59. data/lib/torobi/hooks.rb +439 -0
  60. data/lib/torobi/ir/dimensions.rb +26 -0
  61. data/lib/torobi/ir/dtype.rb +28 -0
  62. data/lib/torobi/ir/graph/check.rb +116 -0
  63. data/lib/torobi/ir/graph.rb +52 -0
  64. data/lib/torobi/ir/input_spec.rb +39 -0
  65. data/lib/torobi/ir/json.rb +45 -0
  66. data/lib/torobi/ir/node_spec.rb +52 -0
  67. data/lib/torobi/ir/parameter_spec.rb +67 -0
  68. data/lib/torobi/ir/ref.rb +52 -0
  69. data/lib/torobi/ir/source.rb +65 -0
  70. data/lib/torobi/ir.rb +23 -0
  71. data/lib/torobi/journal.rb +310 -0
  72. data/lib/torobi/lora.rb +190 -0
  73. data/lib/torobi/memory.rb +50 -0
  74. data/lib/torobi/metallib.rb +50 -0
  75. data/lib/torobi/mlx_prebuilt.json +24 -0
  76. data/lib/torobi/mlx_prebuilt.rb +378 -0
  77. data/lib/torobi/models/build.rb +37 -0
  78. data/lib/torobi/models/description.rb +59 -0
  79. data/lib/torobi/models/gemma3.rb +273 -0
  80. data/lib/torobi/models/llama.rb +381 -0
  81. data/lib/torobi/models/modern_bert.rb +513 -0
  82. data/lib/torobi/models/padding.rb +27 -0
  83. data/lib/torobi/models/windows.rb +53 -0
  84. data/lib/torobi/ops.rb +81 -0
  85. data/lib/torobi/preflight.rb +136 -0
  86. data/lib/torobi/provenance.rb +75 -0
  87. data/lib/torobi/quantization.rb +151 -0
  88. data/lib/torobi/replay.rb +229 -0
  89. data/lib/torobi/runner.rb +419 -0
  90. data/lib/torobi/session.rb +855 -0
  91. data/lib/torobi/shape.rb +438 -0
  92. data/lib/torobi/tensor_data.rb +178 -0
  93. data/lib/torobi/version.rb +5 -0
  94. data/lib/torobi/weights.rb +108 -0
  95. data/lib/torobi.rb +67 -0
  96. data/licenses/MLX.txt +21 -0
  97. data/licenses/README.md +16 -0
  98. data/licenses/gguflib.txt +21 -0
  99. data/licenses/mlx-c.txt +21 -0
  100. data/licenses/mlx-rs.txt +27 -0
  101. metadata +229 -0
@@ -0,0 +1,855 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Torobi
6
+ # A loaded graph and its state, held by the engine, driven from here.
7
+ #
8
+ # The division of labour is the one in docs/plan.md: the engine owns the
9
+ # step, Ruby owns the data and the decisions between spans. Every step is
10
+ # given its batch (section 5A.2) - the session holds parameters and
11
+ # counters, never a dataset - and between spans the window is open, where
12
+ # the listed operations apply (read metrics, turn knobs, copy tensors by
13
+ # name). No tensor handle and no Ruby block ever crosses into a
14
+ # computation.
15
+ #
16
+ # A session is a single conversation, so it is not thread-safe: one
17
+ # session per thread, or a pool.
18
+ #
19
+ # What it raises: ArgumentError for a call that is malformed here,
20
+ # Torobi::StepError for what the engine refused (the session survives),
21
+ # and Torobi::EngineUnavailable before opening if the engine cannot run
22
+ # at all (docs/plan.md section 5A.4).
23
+ class Session
24
+ # The update rule a session takes when none is named: plain SGD, which
25
+ # has no state to restore and is the right default for a spike.
26
+ #
27
+ # This is the one a Ruby caller gets. The engine has its own for its
28
+ # command-line tool, and Ruby never reads it: every open from here
29
+ # states the rule and the seed, so the two cannot disagree about a
30
+ # run that actually happened.
31
+ DEFAULT_OPTIMIZER = { kind: :sgd, lr: 0.1 }.freeze
32
+
33
+ # Where a run's randomness starts when the caller names no seed. Zero
34
+ # rather than something drawn: a run that did not choose its seed
35
+ # should still be the same run twice.
36
+ DEFAULT_SEED = 0
37
+
38
+ # A value that says "this knob was not named". `adjust` needs it for
39
+ # `clip` alone: lr and seed treat nil as "leave it", but nil is also
40
+ # the answer that means "no cap", so clip has to be able to say both.
41
+ NOT_GIVEN = Object.new.freeze
42
+
43
+ # Opens a session over `config` (a GraphConfig).
44
+ #
45
+ # Where the parameters come from is said by keyword, because there is
46
+ # more than one answer:
47
+ #
48
+ # weights: values, {params: {path => {shape:, data:}}}. For
49
+ # spikes and tests. Not for a real model: 130M
50
+ # parameters as JSON numbers is gigabytes of text.
51
+ # weights_file: one safetensors file holding every model's
52
+ # parameters under their qualified paths, which is how
53
+ # a checkpoint writes them, so a run can start from
54
+ # what another run reached.
55
+ # pretrained: {model_name => path}, one published checkpoint per
56
+ # model. A model published on its own does not know
57
+ # what this run will call it, so its tensors carry no
58
+ # model prefix; naming a file per model is what lets
59
+ # ruri-v3 or a reranker be imported with no renaming,
60
+ # and it is the shape a distillation wants anyway:
61
+ #
62
+ # pretrained: { student: "ruri-130m/model.safetensors",
63
+ # teacher: "reranker-310m/model.safetensors" }
64
+ #
65
+ # `fresh:` goes with `pretrained:` and names the parameters that are
66
+ # meant to be in no file, built from the initializers the graph
67
+ # declares instead. A classification head put on a published encoder
68
+ # is the case: it exists in no checkpoint. Patterns, as freezing uses
69
+ # them. Everything they do not name must be in its file, so a mistyped
70
+ # parameter is still an error rather than a quietly random one:
71
+ #
72
+ # pretrained: { student: "ruri-130m/model.safetensors" },
73
+ # fresh: ["student.head.*", "student.classifier.*"]
74
+ #
75
+ # A file in another precision is converted: importing is starting
76
+ # somewhere, not resuming.
77
+ #
78
+ # A third will follow: the GraphConfig already declares an initializer
79
+ # per parameter, so a run that starts from those and a seed needs no
80
+ # weights at all.
81
+ #
82
+ # `optimizer` is data, so that a journal and a checkpoint can record
83
+ # exactly what ran: {kind: :adamw, lr: 1e-3, weight_decay: 0.01}.
84
+ #
85
+ # `seed:` is where every draw this run makes comes from: the parameters
86
+ # a `fresh:` pattern builds here, and the ops that draw at each step.
87
+ # It is the axis an experiment varies to ask whether a result was the
88
+ # method or the luck, so it belongs at open, where the first draw
89
+ # happens. `adjust(seed:)` moves it afterwards, which is a different
90
+ # question (docs/plan.md section 11.1).
91
+ #
92
+ # `journal:` records what happened, for the replay of docs/plan.md
93
+ # section 8.6. Pass a Journal, or `io:` to have one made against this
94
+ # config's provenance; without either, nothing is recorded and the
95
+ # session is exactly as fast.
96
+ #
97
+ # `observer:` is where `observe` is reported as well as recorded, for
98
+ # a caller that wants every observation the run makes, whoever makes
99
+ # it - the driving program or a policy firing in the window. It is
100
+ # anything answering `call(step:, values:)`, and it is how a
101
+ # deterministic rerun collects what it will hold the run to
102
+ # (`Torobi::Replay::Rerun`). Without one, observations are only
103
+ # journalled.
104
+ #
105
+ # `dataset:` is anything about the data that a later reader would need
106
+ # and cannot work out from here. It goes verbatim into the journal's
107
+ # provenance and into every checkpoint's record, and nothing
108
+ # interprets it.
109
+ #
110
+ # **What belongs there above all is the tokenizer.** Torobi is handed
111
+ # token ids and does not know what produced them; a run whose record
112
+ # does not say cannot be repeated, however exactly its parameters are
113
+ # restored. Convention rather than a requirement, because a spike has
114
+ # nothing to say and should not be made to say it:
115
+ #
116
+ # dataset: { name: "jaqket-train", rows: 12_000,
117
+ # tokenizer: "cl-nagoya/ruri-v3-130m",
118
+ # tokenizer_revision: "e3114c6...", max_seq_length: 512 }
119
+ def self.open(config, weights: nil, weights_file: nil, pretrained: nil, fresh: [],
120
+ optimizer: DEFAULT_OPTIMIZER, seed: DEFAULT_SEED,
121
+ journal: nil, io: nil, dataset: nil, observer: nil)
122
+ source = Weights.of(weights:, weights_file:, pretrained:, fresh:).check_fresh!(config)
123
+ Preflight.check!
124
+ native = source.open(config, optimizer, seed)
125
+ # Gathered whether or not anything is journalling: a checkpoint
126
+ # records it too, so that what it holds can be identified later
127
+ # (docs/plan.md section 11.2).
128
+ provenance = Provenance.of(config, dataset:, optimizer:, seed:)
129
+ journal ||= Journal.new(provenance, io:) if io
130
+ session = new(native, journal:, provenance:, loss: config.loss?,
131
+ random: config.random?, observer:)
132
+ # What it was opened with is the header's provenance; this marks when.
133
+ journal&.note(step: 0, event: "opened")
134
+ return session unless block_given?
135
+
136
+ begin
137
+ yield session
138
+ ensure
139
+ # The block form owns the session's lifetime, so its device memory
140
+ # goes when the block does, rather than when the GC gets to it.
141
+ session.close
142
+ end
143
+ end
144
+
145
+ def initialize(native, journal: nil, provenance: nil, loss: true, random: false, observer: nil)
146
+ @native = native
147
+ @random = random
148
+ @journal = journal
149
+ @provenance = provenance
150
+ @loss = loss
151
+ @observer = observer
152
+ @hooks = Hooks.new(self)
153
+ end
154
+
155
+ # Whether this run has a loss. A config that trains nothing and
156
+ # declares no objective has none, and everything that would move
157
+ # something refuses rather than inventing one (`GraphConfig#loss?`).
158
+ def loss? = @loss
159
+
160
+ # Whether a graph of this run draws randomness (a `dropout`), so that
161
+ # two passes over one batch differ. What a gradient cache refuses.
162
+ def random? = @random
163
+
164
+ # What this session is recording into, if anything.
165
+ attr_reader :journal
166
+
167
+ # What this run is: the config's digest, the dataset it was opened
168
+ # against, the build. Written into every checkpoint.
169
+ attr_reader :provenance
170
+
171
+ # Registers a hook. Sugar for the window and nothing more: a hook can
172
+ # do what the window can do, because it fires in one (docs/plan.md
173
+ # section 8.4).
174
+ #
175
+ # s.on(:step, every: 200) { |e| bar.update(e.step, e.loss) }
176
+ def on(event, every: 1, &)
177
+ @hooks.on(event, every:, &)
178
+ self
179
+ end
180
+
181
+ # Registers a policy object: anything answering #call(event). The
182
+ # standard ones are in Torobi::Policies.
183
+ def use(policy, event: :step, every: 1)
184
+ @hooks.use(policy, event:, every:)
185
+ self
186
+ end
187
+
188
+ # One step on `batch`, a Hash of input name => {shape:, data:}. Returns
189
+ # the loss. The GVL is released for the step, so other Ruby threads
190
+ # proceed.
191
+ def step!(batch)
192
+ needs_loss!("a step")
193
+ batch = Batch.of(batch)
194
+ loss = atomically do
195
+ value = @native.run_step(batch.to_native)
196
+ @journal&.span(step: @native.step, loss: value, batches_digest: batch.digest)
197
+ value
198
+ end
199
+ # Outside the fence: a hook runs the caller's own code, and that
200
+ # should be interruptible like any other Ruby.
201
+ @hooks.fire(:step, step: @native.step, loss:)
202
+ loss
203
+ end
204
+
205
+ # Adds one batch's gradients to what is waiting, and returns its loss.
206
+ # No step is taken and no counter moves.
207
+ #
208
+ # What this is for is a batch too large to hold: train it as several
209
+ # that fit, then `apply!`. The gradients of a sum are the sum of the
210
+ # gradients, so the step lands where one over the whole batch would
211
+ # have. It is also what a gradient cache is built on, where the parts
212
+ # are re-run with a cotangent the caller worked out in between.
213
+ #
214
+ # **The weighting is the caller's.** A loss that is a mean over its
215
+ # rows means each part carries the share of the rows it holds; the
216
+ # engine sums what it is given and does not guess what the loss was a
217
+ # mean of.
218
+ #
219
+ # parts.each { |part| s.accumulate(part) }
220
+ # s.apply!
221
+ #
222
+ # Freezing and `checkpoint!` refuse while parts are waiting, because
223
+ # one moves what a gradient is for and the other does not hold them.
224
+ def accumulate(batch)
225
+ needs_loss!("accumulating")
226
+ batch = Batch.of(batch)
227
+ atomically do
228
+ loss = @native.accumulate(batch.to_native)
229
+ @journal&.accumulate(step: @native.step, parts: @native.accumulated, loss:,
230
+ batches_digest: batch.digest)
231
+ loss
232
+ end
233
+ end
234
+
235
+ # Takes the step the accumulated gradients ask for, and returns the
236
+ # mean of the losses they came from. Refuses when nothing is waiting.
237
+ def apply!
238
+ parts = @native.accumulated
239
+ loss = atomically do
240
+ value = @native.apply
241
+ @journal&.span(step: @native.step, loss: value, parts:)
242
+ value
243
+ end
244
+ @hooks.fire(:step, step: @native.step, loss:)
245
+ loss
246
+ end
247
+
248
+ # How many parts are waiting for a step.
249
+ def accumulated = @native.accumulated
250
+
251
+ # Throws away what is waiting. Returns how many parts went.
252
+ def discard = @native.discard
253
+
254
+ # A span: one step per batch, driven from here.
255
+ #
256
+ # One native call per step, not one per span. The boundary costs a
257
+ # fraction of a percent of a step (bench/boundary.rb), and driving it
258
+ # from Ruby is what makes the span interruptible: Ctrl-C, Thread#raise
259
+ # and Timeout all land between steps rather than after the last one.
260
+ # It also means an enumerable is consumed as it goes, so an endless one
261
+ # trains rather than exhausting memory first.
262
+ #
263
+ # Returns the last loss. Yields it per step if a block is given, which
264
+ # is where a caller records or decides.
265
+ def run(batches)
266
+ raise ArgumentError, "this session is closed" if closed?
267
+
268
+ empty = true
269
+
270
+ if @hooks.firing?
271
+ raise Error, "a hook cannot run a span (hooks fire in the window, not around it)"
272
+ end
273
+
274
+ started = @native.step
275
+ batches.each do |batch|
276
+ empty = false
277
+ loss = step!(batch)
278
+ yield loss if block_given?
279
+ end
280
+ raise ArgumentError, "a span needs at least one batch" if empty
281
+
282
+ @journal&.note(step: @native.step, event: "span", steps: @native.step - started,
283
+ loss: @native.loss)
284
+ @hooks.fire(:span_end, step: @native.step, loss: @native.loss)
285
+ @native.loss
286
+ end
287
+
288
+ # The loss for `batch` without taking a step.
289
+ #
290
+ # What a validation set is read with. It costs a forward rather than a
291
+ # forward and a backward, and it runs with the random ops standing
292
+ # aside, so the number is the model's rather than a sample of it.
293
+ # Nothing about the run moves: not the parameters, not the counters, not
294
+ # what `loss` reports.
295
+ #
296
+ # validation.sum { |b| s.evaluate(b) } / validation.size
297
+ #
298
+ # Not journalled. An evaluation changes nothing, so a replay has nothing
299
+ # to apply; `observe` is how a decision made on one gets recorded.
300
+ def evaluate(batch)
301
+ needs_loss!("evaluate")
302
+ @native.evaluate(Batch.of(batch).to_native)
303
+ end
304
+
305
+ # What the models produce for `batch`, by qualified output name.
306
+ #
307
+ # The forward `evaluate` runs, stopping before the objective: what
308
+ # comes back is what a model produced rather than the loss over it.
309
+ # This is how a fine-tuned model is used to look at something, which
310
+ # is what it was fine-tuned for.
311
+ #
312
+ # s.forward(batch) # => {"m.embedding" => TensorData}
313
+ # s.forward(batch, outputs: ["m.logits"]) # only that one
314
+ #
315
+ # No gradients, no randomness (dropout stands aside), and nothing
316
+ # about the run moves: not the parameters, not the counters, not what
317
+ # `loss` reports. Not journalled, for the same reason `evaluate` is
318
+ # not: nothing happened that a replay would apply.
319
+ #
320
+ # The batch needs what the models read and no more. A run that trains
321
+ # against labels does not need them to be asked what it thinks.
322
+ #
323
+ # The taps report it, as they report any pass, except any on the
324
+ # objective: it does not run here, so it has nothing to say.
325
+ #
326
+ # Every value is a TensorData, whatever its shape. What an output is
327
+ # for is its shape, and a caller that wants the number out of a
328
+ # scalar can say `.to_a.first`.
329
+ def forward(batch = nil, outputs: nil, **fields)
330
+ # `forward(x: ids)` is the batch written the way it reads, and in
331
+ # Ruby 3 it is keywords, so the batch arrives as nothing at all.
332
+ # Caught here because what Ruby says about it ("unknown keyword",
333
+ # or an argument count) is true and no help.
334
+ if batch.nil? || !fields.empty?
335
+ raise ArgumentError,
336
+ "forward takes its batch as one argument: forward({x: ...}), not " \
337
+ "forward(x: ...). The braces are what keep it from being keywords."
338
+ end
339
+
340
+ wanted = Array(outputs).map(&:to_s)
341
+ values_of(@native.forward(Batch.of(batch).to_native, wanted))
342
+ end
343
+
344
+ # The same batch for `steps` steps. For fixed-data spikes and tests;
345
+ # real training passes different batches.
346
+ #
347
+ # One `step!` per step, not a shortcut past it: a step that the journal
348
+ # does not hold is a step a replay cannot follow, and hooks fire here
349
+ # like anywhere else.
350
+ def repeat(batch, steps:)
351
+ raise ArgumentError, "steps must be positive" unless steps.positive?
352
+
353
+ last = nil
354
+ steps.times { last = step!(batch) }
355
+ last
356
+ end
357
+
358
+ def step = @native.step
359
+ def loss = @native.loss
360
+ def lr = @native.lr
361
+
362
+ # The L2 norm of the last step's gradients, before any clipping: how
363
+ # far past the cap the run went, or how close it came. NaN before the
364
+ # first step and on a step that was skipped.
365
+ def grad_norm = @native.grad_norm
366
+
367
+ # The largest gradient norm a step may carry, or nil for no cap. Set at
368
+ # open through the optimizer, `{ kind: :adamw, lr:, clip: }`, or by
369
+ # `adjust(clip:)`.
370
+ def clip = @native.clip
371
+
372
+ # The L2 norm of every parameter, over the whole model (frozen ones
373
+ # included). Unlike `grad_norm` this is not kept up to date: it is a
374
+ # reduction over all the weights, computed when asked, so it reaches
375
+ # MLX and can raise Busy while a step is in flight. A hook, which runs
376
+ # at a step boundary, is the place to call it.
377
+ def param_norm = @native.param_norm
378
+
379
+ # The seed the RNG runs from. Explicit state, not a global: the draws a
380
+ # step makes are a function of this and the step count, which is what
381
+ # lets a resumed run take the same ones (docs/plan.md section 11.1).
382
+ def seed = @native.seed
383
+
384
+ # Knobs take effect from the next step, and are recorded: a journal
385
+ # that holds the decisions is what a replay applies (docs/plan.md 8.6).
386
+ def adjust(lr: nil, seed: nil, clip: NOT_GIVEN)
387
+ atomically do
388
+ turned = {}
389
+ if lr
390
+ @native.lr = lr
391
+ turned[:lr] = lr
392
+ end
393
+ if seed
394
+ @native.seed = seed
395
+ turned[:seed] = seed
396
+ end
397
+ unless clip.equal?(NOT_GIVEN)
398
+ @native.clip = clip
399
+ turned[:clip] = clip
400
+ end
401
+ @journal&.adjust(step: @native.step, **turned) unless turned.empty?
402
+ end
403
+ self
404
+ end
405
+
406
+ # Records what the window read. A policy that reads and then decides
407
+ # has the reading as its input, so a deterministic rerun is held to it
408
+ # (docs/plan.md section 8.5).
409
+ #
410
+ # Every observation goes through here, whether the driving program
411
+ # makes it or a policy firing in the window does, so an `observer`
412
+ # sees them all (`Session.open`).
413
+ def observe(**values)
414
+ @journal&.observe(step: @native.step, **values)
415
+ @observer&.call(step: @native.step, values:)
416
+ values
417
+ end
418
+
419
+ # Writes one model as a checkpoint somebody else can load: its
420
+ # parameters as fp32 safetensors, and the files that say what they are.
421
+ #
422
+ # `from:` is the published model this run started from. Everything
423
+ # except its weights is still true of the result (the tokenizer, the
424
+ # vocabulary, the sequence length, how the pooling was configured), so
425
+ # it is copied rather than reinvented. **Without it the export holds no
426
+ # tokenizer, and sentence-transformers cannot load a directory that has
427
+ # none**, whatever else is in it. Fine-tuning always has a source; a
428
+ # model trained from nothing does not, and has to be given a tokenizer
429
+ # by hand.
430
+ #
431
+ # `model:` is which model of the GraphConfig to write, needed only when
432
+ # the run has more than one. The model's own name is stripped from each
433
+ # parameter path, so a model declared with `encoder_prefix:` keeps that
434
+ # prefix and the keys match the published layout.
435
+ #
436
+ # `pooling:` (:cls or :mean) and `pooling_dim:` override what the
437
+ # source said, for an export that pools differently from what it
438
+ # started as. Left out, the source's own pooling configuration travels
439
+ # unchanged, including keys this code knows nothing about.
440
+ #
441
+ # s.export_model!("out/ruri-ft", from: "ruri-v3-130m")
442
+ # s.export_model!("out/mean", from: "ruri-v3-130m", pooling: :mean)
443
+ #
444
+ # `merge:` is the adapter (`Torobi::LoRA`) an adapted run was trained
445
+ # through, and folds it into the weights it adapted: `W + scale * BA`,
446
+ # the matrices themselves dropped. Without it an adapted run is
447
+ # refused, since its base never moved (`Export.refuse_adapted!`). A
448
+ # quantized base is written as the numbers it stands for either way,
449
+ # scales and biases left behind (docs/qlora.md section 3.6).
450
+ #
451
+ # This is not a checkpoint: no optimizer state, no RNG, no counters.
452
+ # It is the shape a run produces for serving, and `checkpoint!` is the
453
+ # shape it produces for itself.
454
+ def export_model!(dir, from: nil, model: nil, pooling: nil, pooling_dim: nil, merge: nil,
455
+ dtype: :f32)
456
+ dtype = Export.dtype_named(dtype)
457
+ paths = @native.parameter_paths
458
+ model = (model || Export.sole_model(paths)).to_s
459
+ scale = merge && Export.scale_of(merge)
460
+ Export.refuse_adapted!(model, paths) unless scale
461
+ atomically do
462
+ originals = merge_token_rows(model, paths, merge)
463
+ begin
464
+ written = @native.export_model(model, dir.to_s, scale, dtype)
465
+ ensure
466
+ # The run goes on as it was: the rows are in the file, and are not in the run twice.
467
+ originals.each { |path, table| put(path, table) }
468
+ end
469
+ carried = Export.new(dir, from:, pooling:, pooling_dim:).publish
470
+ # Last, so that a record of an export is a record of one that is
471
+ # on disk whole.
472
+ @journal&.note(step: @native.step, event: "exported", model:,
473
+ paths: written.map(&:last), carried:)
474
+ written.to_h
475
+ end
476
+ end
477
+
478
+ # Writes the adapter alone, as PEFT saves one (docs/qlora.md section
479
+ # 3.6): `adapter_model.safetensors` holding every `lora_A` and `lora_B`
480
+ # under `base_model.model.`, and `adapter_config.json` saying what
481
+ # they are (`Export.adapter_config`). What a fine-tune through an
482
+ # adapter actually produces, and the one thing of it worth passing on
483
+ # when the base is a published model everyone already has.
484
+ #
485
+ # s.export_adapter!("out/adapter", adapter:, base: "Qwen/Qwen2.5-0.5B",
486
+ # task_type: "CAUSAL_LM")
487
+ #
488
+ # `adapter:` is the `Torobi::LoRA` the graph was built with; the engine
489
+ # knows the matrices, and this knows what they were declared to be.
490
+ def export_adapter!(dir, adapter:, model: nil, base: nil, task_type: nil)
491
+ paths = @native.parameter_paths
492
+ model = (model || Export.sole_model(paths)).to_s
493
+ rows = Export.token_rows(paths, model)
494
+ modules = rows.map(&:first)
495
+ config = Export.adapter_config(adapter, base:, task_type:, token_modules: modules)
496
+ atomically do
497
+ written = @native.export_adapter(model, dir.to_s)
498
+ add_token_rows(dir, adapter, rows)
499
+ Export.write_adapter_config(dir, adapter, base:, task_type:, token_modules: modules)
500
+ @journal&.note(step: @native.step, event: "exported_adapter", model:,
501
+ paths: written.map(&:last), config:)
502
+ written.to_h
503
+ end
504
+ end
505
+
506
+ # Reads an adapter PEFT saved (`export_adapter!` is one, so is any
507
+ # PEFT's) into the run's own: the other half of passing one on.
508
+ #
509
+ # Session.open(config, pretrained: { m: base }, fresh: adapter.fresh(config)) do |s|
510
+ # s.import_adapter!("out/adapter", adapter:)
511
+ #
512
+ # The run has declared its adapter (`adapter:` is the `Torobi::LoRA`
513
+ # the graph was built with) and `fresh:` made the matrices from their
514
+ # initializers; this puts the saved ones in their place. **The adapter
515
+ # given is held to what the file says**: the scale `alpha / rank` is in
516
+ # the graph, so a file trained at another rank or alpha, or on other
517
+ # linears, would load and compute something else. A matrix the file
518
+ # lacks, or one it has that the graph does not, is refused with its
519
+ # name, and nothing is written until every name has been checked.
520
+ #
521
+ # Returns the paths written. The dropout is not compared: it is how an
522
+ # adapter was trained, not what it is.
523
+ def import_adapter!(dir, adapter:, model: nil)
524
+ unless adapter.is_a?(LoRA)
525
+ raise ArgumentError,
526
+ "adapter: is the Torobi::LoRA the graph was built with, got #{adapter.inspect}"
527
+ end
528
+
529
+ paths = @native.parameter_paths
530
+ model = (model || Export.sole_model(paths)).to_s
531
+ file = AdapterFile.read(dir)
532
+ Export.check_same_adapter!(adapter, file.lora, dir)
533
+
534
+ declared = paths.select { |path| path.start_with?("#{model}.") && LoRA.adapted?(path) }
535
+ .to_h { |path| [path.delete_prefix("#{model}."), path] }
536
+ Export.check_same_matrices!(declared.keys, file.tensors.keys, dir)
537
+ # Every shape before any write, so that a refusal leaves the run as it was.
538
+ file.tensors.each do |name, tensor|
539
+ held = fetch(declared.fetch(name)).shape
540
+ next if held == tensor.shape
541
+
542
+ raise ConfigError,
543
+ "#{name} in #{dir} is #{tensor.shape.inspect}, and this run's is #{held.inspect}"
544
+ end
545
+
546
+ atomically do
547
+ file.tensors.map do |name, tensor|
548
+ if name.end_with?(".#{LoRA.rows_name}")
549
+ tensor = rows_as_difference(declared.fetch(name), tensor,
550
+ adapter)
551
+ end
552
+ put(declared.fetch(name), tensor)
553
+ declared.fetch(name)
554
+ end
555
+ end
556
+ end
557
+
558
+ # Writes the run's state to `dir`, atomically: parameters, optimizer
559
+ # slots, the step counts, the description they belong to, and this
560
+ # run's provenance. Returns the `Torobi::Checkpoint` written.
561
+ # Interrupting it leaves no half-checkpoint.
562
+ #
563
+ # `at:` is where in the data the run is - epoch, batch, whatever a
564
+ # sampler needs to carry on. Torobi is handed batches and never fetches
565
+ # them (docs/plan.md section 5A.2), so it cannot work this out; it
566
+ # records what it is told, verbatim, and hands it back on restore.
567
+ #
568
+ # s.checkpoint!("run/000200", at: { epoch: 2, batch: 1_400 })
569
+ #
570
+ # `light: true` writes the trained parameters and the optimizer's state
571
+ # for them, and not the rest: a LoRA run's checkpoint is its adapter's
572
+ # few megabytes, not the model again. `restore` puts those back and
573
+ # leaves every other parameter as this session was opened with, so the
574
+ # session must be opened on the same weights; the shape and type of
575
+ # each left out is still checked. Whether a checkpoint is light is in
576
+ # its manifest (`parameters[].saved`).
577
+ def checkpoint!(dir, at: nil, light: false)
578
+ record = { "provenance" => @provenance&.to_h, "position" => stringify(at) }.compact
579
+ written = atomically do
580
+ path = @native.save(dir.to_s, JSON.generate(record), light)
581
+ @journal&.checkpoint(path:, step: @native.step)
582
+ Checkpoint.new(path)
583
+ end
584
+ @hooks.fire(:checkpoint_written, step: @native.step, loss: @native.loss)
585
+ written
586
+ end
587
+
588
+ # Restores what `checkpoint!` wrote. Refuses a checkpoint from another
589
+ # description, another optimizer, or another shape, rather than
590
+ # absorbing the difference.
591
+ #
592
+ # Returns the position that was recorded with it (or nil), so that
593
+ # whoever owns the data can put its sampler back where it was. The
594
+ # whole record, provenance included, is `Torobi::Checkpoint#manifest`.
595
+ def restore(dir)
596
+ recorded = atomically do
597
+ state = JSON.parse(@native.restore(dir.to_s))
598
+ @journal&.note(step: @native.step, event: "restored", path: dir.to_s)
599
+ state
600
+ end
601
+ recorded.is_a?(Hash) ? recorded["position"] : nil
602
+ end
603
+
604
+ # Releases the engine and its device memory. Idempotent; afterwards
605
+ # every call refuses rather than pretending. Returns whether this call
606
+ # was the one that closed it.
607
+ def close
608
+ # Read the counter before closing: afterwards the session refuses,
609
+ # which is the point of closing.
610
+ last_step = @native.closed? ? nil : @native.step
611
+ closed = @native.close
612
+ if closed
613
+ @journal&.note(step: last_step, event: "closed")
614
+ @journal&.close
615
+ end
616
+ closed
617
+ end
618
+
619
+ def closed? = @native.closed?
620
+
621
+ # Whether the engine panicked under this session. A poisoned session
622
+ # cannot be trusted to hold consistent state, so nothing more is
623
+ # attempted with it; open a new one, from a checkpoint if there is one.
624
+ def poisoned? = @native.poisoned?
625
+
626
+ # Stops training what matches `pattern`: a path, or a prefix ending in
627
+ # `*` ("student.layers.3.*"). Returns the paths that moved.
628
+ #
629
+ # Not a scalar knob (docs/plan.md 5A.1): it changes what autodiff
630
+ # differentiates, so the optimizer's slots follow - kept for what
631
+ # stays, dropped for what freezes, started at zero for what thaws. It
632
+ # takes effect from the next step, like every knob, and is recorded.
633
+ def freeze!(pattern) = set_frozen(pattern, true)
634
+
635
+ # The reverse: gradual unfreezing is the usual reason.
636
+ def unfreeze!(pattern) = set_frozen(pattern, false)
637
+
638
+ # What is being trained right now, by qualified path.
639
+ def trainable = @native.trainable
640
+
641
+ # Writes one parameter from a copy: {shape:, data:, dtype:}. The
642
+ # window's writing half, and recorded by digest rather than by value -
643
+ # a journal names what was written without holding it.
644
+ def put(path, tensor)
645
+ tensor = TensorData.from(tensor, where: path.to_s)
646
+ atomically do
647
+ @native.put(path.to_s, tensor.to_native)
648
+ @journal&.put(step: @native.step, path: path.to_s,
649
+ digest: Provenance.digest_of(tensor.bytes))
650
+ end
651
+ self
652
+ end
653
+
654
+ # Watches a named value inside the graph, read-only (docs/plan.md
655
+ # section 8.3, capability B+). `stat` reduces it on the device:
656
+ #
657
+ # :norm the L2 norm, which is how an activation is usually watched
658
+ # :mean its mean
659
+ # :extent its smallest and largest
660
+ # :full the tensor itself, which is for debugging and costs it
661
+ #
662
+ # A tap adds an output; it never changes one. What it costs is a
663
+ # forward pass per step (a traced pass produces values that belong to
664
+ # the trace, not to the caller), so taps are opt-in and a standing one
665
+ # should reduce.
666
+ def tap(name, stat: :norm)
667
+ @native.tap_node(name.to_s, stat.to_s)
668
+ self
669
+ end
670
+
671
+ def untap(name) = @native.untap(name.to_s)
672
+
673
+ # What is being watched.
674
+ def taps = @native.taps
675
+
676
+ # Every name a tap could ask for, qualified by the model it is in
677
+ # ("student.hidden"). Settled at open, like `parameter_paths`.
678
+ def node_names = @native.node_names
679
+
680
+ # Every output `forward` could ask for, qualified by the model that
681
+ # declares it ("student.embedding"). Settled at open, like the rest of
682
+ # the names.
683
+ def output_names = @native.output_names
684
+
685
+ # What the last step's taps saw, by tap name. A scalar tap (a loss,
686
+ # say) comes back as a Float, since a caller compares it or writes it
687
+ # down; anything with a shape comes back as a TensorData.
688
+ #
689
+ # Read-only, so it needs no journal entry of its own; `observe` is
690
+ # how a decision made on one gets recorded.
691
+ def tapped
692
+ values_of(@native.tapped).transform_values do |data|
693
+ data.shape.empty? ? data.to_a.first : data
694
+ end
695
+ end
696
+
697
+ # What the run is made of: every parameter by qualified path, every
698
+ # batch field it reads, and every name a tap may ask for.
699
+ #
700
+ # Settled when the session opened and answered from there, so a
701
+ # watching thread gets them while a span is in flight, and they still
702
+ # answer after `close`. What is being trained right now is not one of
703
+ # these: freezing moves it, so `trainable` asks the engine.
704
+ def parameter_paths = @native.parameter_paths
705
+ def input_names = @native.input_names
706
+
707
+ # A copy of one parameter, as a TensorData. Copies, never handles.
708
+ #
709
+ # The copy is bytes rather than numbers, and stays that way until a
710
+ # caller asks for `to_a`: ruri-v3's embedding table is 200 MB of bytes
711
+ # and was 600 MB of resident memory as a Ruby Array, for a value most
712
+ # callers save or compare rather than read.
713
+ def fetch(path)
714
+ TensorData.from_native(*@native.fetch(path.to_s))
715
+ end
716
+
717
+ # The gradients of the loss with respect to named batch fields, by
718
+ # field name. Does not update anything and does not differentiate the
719
+ # parameters.
720
+ #
721
+ # What this is for is a loss over values computed elsewhere. A gradient
722
+ # cache encodes its parts without gradients, works out the loss over
723
+ # all of the representations at once, and needs that loss
724
+ # differentiated **by the representations** so each part can be re-run
725
+ # with the answer as its seed:
726
+ #
727
+ # d = loss_session.field_gradients(batch, of: %i[queries documents])
728
+ #
729
+ # The fields must be in the batch, and the answer has their shapes.
730
+ def field_gradients(batch, of:)
731
+ needs_loss!("a gradient")
732
+ names = Array(of).map(&:to_s)
733
+ values_of(@native.field_gradients(Batch.of(batch).to_native, names))
734
+ end
735
+
736
+ # The gradients for `batch`, by parameter path. Does not update anything.
737
+ def gradients(batch)
738
+ needs_loss!("a gradient")
739
+ values_of(@native.gradients(Batch.of(batch).to_native))
740
+ end
741
+
742
+ private
743
+
744
+ # What the engine answers with, as values by name.
745
+ #
746
+ # Four calls come back the same way, because the boundary carries
747
+ # one shape of answer: the name, the dtype and shape readable, the
748
+ # payload packed. How to read that is one fact and lives once.
749
+ def values_of(answered)
750
+ answered.to_h do |name, dtype, shape, bytes|
751
+ [name, TensorData.from_native(dtype, shape, bytes)]
752
+ end
753
+ end
754
+
755
+ # What a run without a loss cannot do.
756
+ #
757
+ # Refused here rather than at the boundary, because what is missing is
758
+ # a fact about the config: nothing is trained and no output is a
759
+ # scalar, so there is nothing to differentiate or report. `forward` is
760
+ # what such a run is for.
761
+ def needs_loss!(what)
762
+ return if @loss
763
+
764
+ raise ConfigError,
765
+ "#{what} needs a loss, and this run has none: nothing is trained and " \
766
+ "no model output is an f32 scalar. That is what a config opened for " \
767
+ "inference looks like, and `forward` is what it can do."
768
+ end
769
+
770
+ # Runs an engine change and the journal's record of it as one, so an
771
+ # asynchronous interrupt cannot land between them.
772
+ #
773
+ # Without this the engine takes a step and Ruby is interrupted before
774
+ # writing it down, leaving a record one operation behind what actually
775
+ # happened. A replay follows the record, so that difference is not
776
+ # cosmetic (notes/SESSION_CONCURRENCY_SPEC.md section 10).
777
+ #
778
+ # What it costs in responsiveness is bounded by one step, which is the
779
+ # granularity a span is interruptible at anyway.
780
+ # An adapter that trains rows of a table writes them into the adapter file as PEFT does:
781
+ # the table's rows with the difference added, which is what PEFT's
782
+ # `trainable_tokens_delta` holds.
783
+ def add_token_rows(dir, adapter, rows)
784
+ return if rows.empty?
785
+
786
+ unless adapter.tokens?
787
+ raise ConfigError,
788
+ "the model trains rows (#{rows.map(&:first).join(", ")}) and the adapter given " \
789
+ "trains none"
790
+ end
791
+
792
+ written = rows.map do |name, delta_path, table_path|
793
+ delta = fetch(delta_path)
794
+ trained = Export.with_rows_added(fetch(table_path), adapter.tokens, delta)
795
+ [name, delta.shape, Export.rows_of(trained, adapter.tokens).flatten]
796
+ end
797
+ Export.add_token_rows_to_adapter(dir, written)
798
+ end
799
+
800
+ # PEFT's file holds the rows themselves, and this run holds them as a difference from the
801
+ # table's.
802
+ def rows_as_difference(delta_path, tensor, adapter)
803
+ table = fetch("#{delta_path.delete_suffix(".#{LoRA.rows_name}")}.weight")
804
+ original = Export.rows_of(table, adapter.tokens).flatten
805
+ saved = tensor.bytes.unpack("e*")
806
+ TensorData.new(tensor.shape, saved.each_with_index.map { |v, i| v - original[i] }.pack("e*"))
807
+ end
808
+
809
+ # Writes what an adapter's rows are into the tables they are rows of, for a merged export,
810
+ # and returns the tables as they were, to be put back.
811
+ def merge_token_rows(model, paths, merge)
812
+ rows = Export.token_rows(paths, model)
813
+ return {} if rows.empty?
814
+
815
+ unless merge.is_a?(LoRA) && merge.tokens?
816
+ raise ConfigError,
817
+ "model #{model.inspect} trains rows of a table, which a merge needs the adapter " \
818
+ "for " \
819
+ "(merge: the Torobi::LoRA, not its scale): it is what knows which rows they are"
820
+ end
821
+
822
+ rows.to_h do |_, delta_path, table_path|
823
+ table = fetch(table_path)
824
+ put(table_path, Export.with_rows_added(table, merge.tokens, fetch(delta_path)))
825
+ [table_path, table]
826
+ end
827
+ end
828
+
829
+ def atomically(&)
830
+ Thread.handle_interrupt(Object => :never, &)
831
+ end
832
+
833
+ def set_frozen(pattern, frozen)
834
+ pattern = pattern.to_s
835
+ atomically do
836
+ moved = @native.set_frozen(pattern, frozen)
837
+ @journal&.freezing(step: @native.step, pattern:, frozen:, moved:) unless moved.empty?
838
+ moved
839
+ end
840
+ end
841
+
842
+ # A position travels as JSON, so its keys are strings by the time it
843
+ # comes back. Convert on the way in, so that what a caller reads after
844
+ # a restore is what it wrote.
845
+ def stringify(value)
846
+ case value
847
+ when nil then nil
848
+ when Hash then value.to_h { |k, v| [k.to_s, stringify(v)] }
849
+ when Array then value.map { |v| stringify(v) }
850
+ when Symbol then value.to_s
851
+ else value
852
+ end
853
+ end
854
+ end
855
+ end