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,439 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Hooks: the window's sugar, and nothing more.
5
+ #
6
+ # A hook can do exactly what the window can do (docs/plan.md section
7
+ # 8.4), because it *is* the window: it fires between steps, never inside
8
+ # one, and it holds the session it was given. What it buys is not
9
+ # capability but separation - the experiment's main line stays a program
10
+ # you read top to bottom, while the crosscutting concerns (watching for
11
+ # NaN, keeping the best checkpoint, drawing a bar) live beside it.
12
+ #
13
+ # The fences, from the plan:
14
+ #
15
+ # - hooks fire in registration order, so a run is deterministic
16
+ # - a hook may not call `run` (no reentry)
17
+ # - an exception in a hook stops the span, which is safe because a window
18
+ # is a point where the state is consistent
19
+ # - what a hook adjusts goes through the same knobs, and is journalled
20
+ class Hooks
21
+ # Where a hook may fire. Closed on purpose: a name here is a promise.
22
+ EVENTS = %i[step span_end plateau nan checkpoint_written].freeze
23
+
24
+ # The losses a run has seen, kept the way anything asks about them.
25
+ #
26
+ # `plateaued?` asks two things: the last few readings, and the best of
27
+ # everything before them. An Array answers both and grows for the
28
+ # length of the run, which was fine until you notice that every window
29
+ # carried a copy of it: measured at 40,000 windows that was 10 us a
30
+ # step and rising. Nothing beside a training step, and unbounded all
31
+ # the same.
32
+ #
33
+ # So the recent readings are kept and the rest are folded into their
34
+ # minimum as they fall out, which is all anything asked of them.
35
+ class History
36
+ # How many readings are kept whole. Far past any patience anybody
37
+ # sets, so what falls out is only ever read as "the best before".
38
+ KEEP = 10_000
39
+
40
+ def initialize(keep: KEEP)
41
+ @keep = keep
42
+ @recent = []
43
+ @dropped = nil
44
+ @size = 0
45
+ end
46
+
47
+ # How many readings there have been, not how many are kept.
48
+ attr_reader :size
49
+
50
+ def <<(loss)
51
+ @size += 1
52
+ @recent << loss
53
+ return self if @recent.size <= @keep
54
+
55
+ gone = @recent.shift
56
+ @dropped = gone if number?(gone) && (@dropped.nil? || gone < @dropped)
57
+ self
58
+ end
59
+
60
+ # The last `count` readings, oldest first.
61
+ def last(count) = @recent.last(count)
62
+
63
+ # The best reading before the last `count`, or nil if there is none.
64
+ def best_before(count)
65
+ kept = @recent[0..-(count + 1)] || []
66
+ [@dropped, *kept.select { |loss| number?(loss) }].compact.min
67
+ end
68
+
69
+ def to_a = @recent.dup
70
+
71
+ private
72
+
73
+ def number?(loss) = loss.is_a?(Numeric) && loss.finite?
74
+ end
75
+
76
+ # What a hook is handed. A reading of the run, plus the session, whose
77
+ # window capabilities are the hook's capabilities.
78
+ Event = Data.define(:name, :session, :step, :loss, :readings) do
79
+ # The losses so far, as an Array. Built when something asks, which
80
+ # most events never are.
81
+ def history = readings.to_a
82
+
83
+ # Whether the loss has stopped falling: nothing in the last
84
+ # `patience` readings improved on the best before them, by more than
85
+ # `by`. Readings that are not numbers do not count as improvement.
86
+ def plateaued?(patience: 3, by: 1e-4)
87
+ return false if readings.size <= patience
88
+
89
+ best_before = readings.best_before(patience)
90
+ return false unless best_before
91
+
92
+ readings.last(patience)
93
+ .none? { |loss| loss.is_a?(Numeric) && loss.finite? && loss < best_before - by }
94
+ end
95
+
96
+ def finite? = loss&.finite?
97
+ end
98
+
99
+ def initialize(session)
100
+ @session = session
101
+ @registered = []
102
+ @history = History.new
103
+ @firing = false
104
+ end
105
+
106
+ def any? = !@registered.empty?
107
+
108
+ # `on(:step, every: 200) { |event| ... }`
109
+ def on(event, every: 1, &block)
110
+ unless EVENTS.include?(event)
111
+ raise ArgumentError, "#{event.inspect} is not a hook event (#{EVENTS.join(", ")})"
112
+ end
113
+ raise ArgumentError, "on(#{event.inspect}) needs a block" unless block
114
+
115
+ @registered << { event:, every: cadence(every), call: block }
116
+ self
117
+ end
118
+
119
+ # A policy object: anything answering `call(event)`. The standard ones
120
+ # are in Torobi::Policies.
121
+ def use(policy, event: :step, every: 1)
122
+ unless policy.respond_to?(:call)
123
+ raise ArgumentError, "a policy must respond to #call, and #{policy.class} does not"
124
+ end
125
+
126
+ @registered << { event:, every: cadence(every), call: policy }
127
+ self
128
+ end
129
+
130
+ # Called by the session at each window. Not part of the public API.
131
+ #
132
+ # Hooks do not nest: a hook that writes a checkpoint would otherwise
133
+ # fire :checkpoint_written inside itself, and the fence against
134
+ # reentry is about spans, not about that. The inner firing is skipped.
135
+ def fire(name, step:, loss:)
136
+ return if @registered.empty? || @firing
137
+
138
+ @history << loss if name == :step && loss
139
+ event = Event.new(name:, session: @session, step:, loss:, readings: @history)
140
+ @firing = true
141
+ @registered.each do |hook|
142
+ next unless hook[:event] == name
143
+ next unless (step % hook[:every]).zero?
144
+
145
+ hook[:call].call(event)
146
+ end
147
+ ensure
148
+ @firing = false
149
+ end
150
+
151
+ # Whether a span is currently inside a hook, which is how the session
152
+ # refuses reentry.
153
+ def firing? = @firing
154
+
155
+ private
156
+
157
+ # How many windows apart a hook fires.
158
+ #
159
+ # Checked where it is given rather than where it is divided by: a 0
160
+ # is a ZeroDivisionError at the first step, which arrives far from
161
+ # the call that caused it and says nothing about which knob it was.
162
+ def cadence(every)
163
+ every = Integer(every)
164
+ return every if every.positive?
165
+
166
+ raise ArgumentError,
167
+ "every: is how many windows apart a hook fires, so it is at least 1 " \
168
+ "(got #{every})"
169
+ end
170
+ end
171
+
172
+ # The standard policies: the crosscutting concerns worth writing once.
173
+ # Each is a plain object answering `call(event)`, so a caller's own is
174
+ # exactly as good.
175
+ module Policies
176
+ # Answers a loss that has stopped being a number.
177
+ #
178
+ # There are two of these and they want different answers.
179
+ #
180
+ # A bad batch: one step's numbers overflow, the parameters are fine.
181
+ # The engine does not take a step whose loss is not finite, so this
182
+ # costs that step and nothing else. Carrying on is the whole answer,
183
+ # and it works with no checkpoint at all.
184
+ #
185
+ # A divergence: the parameters themselves are somewhere the forward
186
+ # overflows. Then no step is taken either, which means lowering the
187
+ # rate moves nothing and the run is stuck rather than corrupt. Only
188
+ # going back somewhere else answers this, which is why `rollback` is
189
+ # still worth giving.
190
+ #
191
+ # So: lower the rate, go back if there is somewhere to go back to, and
192
+ # give up after `patience` consecutive non-finite steps, because by
193
+ # then whatever is being tried is not working.
194
+ class NaNGuard
195
+ def initialize(rollback: nil, lr_factor: 0.5, patience: 5)
196
+ @rollback = rollback
197
+ @lr_factor = lr_factor
198
+ @patience = patience
199
+ @consecutive = 0
200
+ end
201
+
202
+ # How many non-finite steps have arrived in a row.
203
+ attr_reader :consecutive
204
+
205
+ def call(event)
206
+ if event.finite?
207
+ @consecutive = 0
208
+ return
209
+ end
210
+
211
+ @consecutive += 1
212
+ session = event.session
213
+ session.observe(nan_at: event.step, consecutive: @consecutive)
214
+ if @consecutive >= @patience
215
+ raise Torobi::StepError,
216
+ "the loss has not been finite for #{@consecutive} steps " \
217
+ "(since step #{event.step - @consecutive + 1}); lowering the rate " \
218
+ "is not answering it"
219
+ end
220
+
221
+ session.restore(@rollback) if @rollback && File.exist?(@rollback.to_s)
222
+ session.adjust(lr: session.lr * @lr_factor)
223
+ end
224
+ end
225
+
226
+ # How the rate comes back down is the subclass's (`at`): the two here
227
+ # do not share that arithmetic, and a name would only hide the
228
+ # difference.
229
+ #
230
+ # `warmup` is a share of the run when it is below one, and a number of
231
+ # steps when it is not.
232
+ class Curve
233
+ def initialize(peak:, total:, warmup: 0.05, floor: 0.0)
234
+ raise ArgumentError, "a schedule needs a positive peak" unless peak.positive?
235
+ raise ArgumentError, "a schedule needs a positive length" unless total.positive?
236
+
237
+ @peak = Float(peak)
238
+ @total = Integer(total)
239
+ @warmup = warmup < 1 ? (total * warmup).round : Integer(warmup)
240
+ @floor = Float(floor)
241
+ end
242
+
243
+ attr_reader :peak, :total, :warmup, :floor
244
+
245
+ # Public so it can be looked at without a run: a schedule nobody can
246
+ # plot is a schedule nobody can check.
247
+ def at(step)
248
+ raise NotImplementedError, "#{self.class} must say how the rate decays"
249
+ end
250
+
251
+ def call(event)
252
+ event.session.adjust(lr: at(event.step))
253
+ end
254
+
255
+ private
256
+
257
+ def progress(step) = (step - @warmup).to_f / [@total - @warmup, 1].max
258
+ end
259
+
260
+ # The rate over the run, which every fine-tune has an opinion about.
261
+ #
262
+ # Warmup, then decay. Both halves are there for a reason a run shows
263
+ # rather than argues: the first steps of a fine-tune move a model
264
+ # that is already good, and moving it at full rate before AdamW has
265
+ # any idea of the gradient's scale is how a good model is spent. The
266
+ # decay is what lets the last steps settle instead of bouncing.
267
+ #
268
+ # s.use(Torobi::Policies::Schedule.new(peak: 1e-5, total: 3000), every: 10)
269
+ #
270
+ # `every:` is worth using and costs nothing in accuracy: over ten
271
+ # steps a cosine moves by a thousandth of its range, and the journal
272
+ # records a knob turn each time it is turned.
273
+ #
274
+ # It is not a scheduler in the framework's sense: it is an object
275
+ # that turns the same knob a caller could turn, which is what every
276
+ # policy here is (docs/plan.md section 8.4).
277
+ class Schedule < Curve
278
+ def at(step)
279
+ return @peak * (step + 1) / (@warmup + 1).to_f if step < @warmup
280
+
281
+ cosine = 0.5 * (1 + Math.cos(Math::PI * [progress(step), 1.0].min))
282
+ @floor + ((@peak - @floor) * cosine)
283
+ end
284
+ end
285
+
286
+ # The same warmup and decay, in straight lines.
287
+ #
288
+ # Schedule's sibling, for the runs whose reference decays linearly
289
+ # rather than by a cosine: Jev Local's `train.py` warms up over six
290
+ # percent of the run and then brings the rate to zero in a line, which
291
+ # is what the published `modernbert-ja-310m-jev` was trained with.
292
+ # Kept apart from Schedule rather than given a `shape:` because the two
293
+ # do not share their arithmetic: this reaches the peak at the end of
294
+ # warmup and decays by `peak * (1 - progress)`, where the cosine is
295
+ # `0.5 * (1 + cos(pi * progress))`.
296
+ #
297
+ # s.use(Torobi::Policies::Linear.new(peak: 3e-5, total: 5386), every: 10)
298
+ class Linear < Curve
299
+ def at(step)
300
+ return @peak * (step + 1) / [@warmup, 1].max.to_f if step < @warmup
301
+
302
+ @floor + ((@peak - @floor) * (1.0 - [progress(step), 1.0].min))
303
+ end
304
+ end
305
+
306
+ # Stops a run before the machine notices it.
307
+ #
308
+ # `Torobi::Memory.limit=` is not a refusal, which was measured rather
309
+ # than assumed: a 336 MB peak ran to completion under a 67 MB limit,
310
+ # and a step whose peak reached 14.5 GB ran under a 9 GB one (it took
311
+ # 41s where it usually takes 3, because the allocator was reclaiming
312
+ # rather than failing). MLX treats the limit as pressure on its cache,
313
+ # not as a ceiling.
314
+ #
315
+ # So the ceiling has to be Ruby's. This reads the high-water mark
316
+ # between steps and raises when it passes `bytes`, which the run's
317
+ # process reports as a failure and the parent reads from the journal.
318
+ # On unified memory the alternative is the machine stopping
319
+ # (docs/plan.md section 15.22), which no rescue sees.
320
+ #
321
+ # s.use(Torobi::Policies::MemoryGuard.new(10 * 1024**3), every: 10)
322
+ #
323
+ # **The peak, not what is held now.** Between steps a run holds its
324
+ # parameters and its optimizer; what it passes through in the middle
325
+ # of a step is several times that, and that is the number the machine
326
+ # reacts to. Measured on a small model: 101 MB held between steps
327
+ # against a 369 MB peak, and at ModernBERT sizes the gap is wider. A
328
+ # guard reading what is held would have watched a step touch 14.5 GB
329
+ # and said nothing.
330
+ #
331
+ # **It cannot stop a step in the middle.** No Ruby runs during one, so
332
+ # this fires at the first hook after the overshoot. Whether a shape
333
+ # fits at all is answered by running one step of it and reading the
334
+ # peak (bench/overfit.rb), not by this.
335
+ #
336
+ # `every:` is worth using: reading costs a call through the runtime's
337
+ # gate. The peak is a high-water mark and is not reset here, so a
338
+ # sparser check still sees an overshoot between two of them.
339
+ class MemoryGuard
340
+ # The high-water mark when this last looked.
341
+ attr_reader :seen
342
+
343
+ def initialize(bytes, on_limit: nil)
344
+ raise ArgumentError, "a guard needs a positive limit" unless bytes.positive?
345
+
346
+ @bytes = Integer(bytes)
347
+ @on_limit = on_limit
348
+ @seen = 0
349
+ end
350
+
351
+ def call(event)
352
+ @seen = Torobi::Memory.peak
353
+ return if @seen <= @bytes
354
+
355
+ event.session.observe(memory_at: event.step, peak: @seen, limit: @bytes)
356
+ return @on_limit.call(event) if @on_limit
357
+
358
+ raise Torobi::StepError,
359
+ "this run has passed through #{@seen / (1024**2)} MB on the device by " \
360
+ "step #{event.step}, past the #{@bytes / (1024**2)} MB it was given. " \
361
+ "Stopping here rather than letting the machine find out"
362
+ end
363
+ end
364
+
365
+ # Keeps a checkpoint of the best the run has been.
366
+ class BestCheckpoint
367
+ # The best value seen, and the `Torobi::Checkpoint` holding it.
368
+ attr_reader :best, :checkpoint
369
+
370
+ def initialize(dir, metric: nil)
371
+ @dir = dir
372
+ @metric = metric
373
+ @best = nil
374
+ @checkpoint = nil
375
+ end
376
+
377
+ def call(event)
378
+ value = @metric ? @metric.call(event) : event.loss
379
+ return if value.nil? || !value.finite?
380
+ return if @best && value >= @best
381
+
382
+ @best = value
383
+ @checkpoint = event.session.checkpoint!(@dir)
384
+ end
385
+ end
386
+
387
+ # Halves the learning rate when the loss stops falling.
388
+ class LrOnPlateau
389
+ def initialize(factor: 0.5, patience: 3, by: 1e-4, min_lr: 1e-6)
390
+ @factor = factor
391
+ @patience = patience
392
+ @by = by
393
+ @min_lr = min_lr
394
+ @last_change = 0
395
+ end
396
+
397
+ def call(event)
398
+ return unless event.plateaued?(patience: @patience, by: @by)
399
+ # One change per plateau, not one per step of it.
400
+ return if @last_change.positive? && event.step - @last_change < @patience
401
+
402
+ session = event.session
403
+ next_lr = [session.lr * @factor, @min_lr].max
404
+ return if next_lr >= session.lr
405
+
406
+ @last_change = event.step
407
+ session.observe(plateau_at: event.step, loss: event.loss)
408
+ session.adjust(lr: next_lr)
409
+ end
410
+ end
411
+
412
+ # Stops the run when it stops improving. Raises, which stops the span
413
+ # where the plan says a hook's exception stops it.
414
+ class EarlyStopping
415
+ class Stop < Torobi::Error; end
416
+
417
+ def initialize(patience: 5, by: 1e-4)
418
+ @patience = patience
419
+ @by = by
420
+ end
421
+
422
+ def call(event)
423
+ return unless event.plateaued?(patience: @patience, by: @by)
424
+
425
+ event.session.observe(early_stop_at: event.step, loss: event.loss)
426
+ raise Stop, "the loss has not improved for #{@patience} steps; stopping at #{event.step}"
427
+ end
428
+ end
429
+
430
+ # Anything that wants the numbers: a bar, a log, a tracker.
431
+ class Progress
432
+ def initialize(&block)
433
+ @block = block or raise ArgumentError, "Progress needs a block"
434
+ end
435
+
436
+ def call(event) = @block.call(event.step, event.loss)
437
+ end
438
+ end
439
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # What a shape in the IR may be: an array of positive integers, where a
6
+ # value that flows through the graph may leave a dimension nil
7
+ # (symbolic: batch, sequence) and storage may not. The one check the
8
+ # specs share, as Dtype is the one for dtypes.
9
+ module Dimensions
10
+ module_function
11
+
12
+ # Returns a frozen copy of +shape+, or raises ConfigError.
13
+ def check!(shape, where:, symbolic:)
14
+ return Freeze.deep(shape.dup) if valid?(shape, symbolic:)
15
+
16
+ allowed = symbolic ? "positive integers or nil (symbolic)" : "positive integers"
17
+ raise ConfigError, "#{where}: shape must be an array of #{allowed}, got #{shape.inspect}"
18
+ end
19
+
20
+ def valid?(shape, symbolic:)
21
+ shape.is_a?(Array) &&
22
+ shape.all? { |d| (symbolic && d.nil?) || (d.is_a?(Integer) && d.positive?) }
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # The dtypes the IR speaks. Deliberately few: what the target models
6
+ # need, not what MLX offers.
7
+ #
8
+ # `u32` is not a number a graph computes with. It is the packed form
9
+ # of a quantized weight (`Torobi::Quantization`, docs/qlora.md): 32 /
10
+ # bits values in one word, read only by `quantized_matmul`, and never
11
+ # the result of a `cast`.
12
+ module Dtype
13
+ ALL = %i[f32 bf16 i32 bool u32].freeze
14
+
15
+ # The dtypes a value can be cast to: everything but the packed one.
16
+ CASTABLE = (ALL - %i[u32]).freeze
17
+
18
+ module_function
19
+
20
+ def check!(dtype, where:)
21
+ return dtype if ALL.include?(dtype)
22
+
23
+ raise ConfigError,
24
+ "#{where}: unknown dtype #{dtype.inspect}; expected one of #{ALL.join(", ")}"
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ class Graph
6
+ # What makes a graph a graph, checked before one is made:
7
+ #
8
+ # - ids are consecutive from 0 within each kind
9
+ # - input names, parameter paths and node names are unique
10
+ # - a node references only inputs and earlier nodes (no forward references)
11
+ # - every node is reachable from an output (no dead nodes)
12
+ #
13
+ # Separate from Graph so that Graph is the value and its queries, and
14
+ # this is the one place the rules are read from.
15
+ class Check
16
+ def initialize(inputs:, parameters:, nodes:)
17
+ @inputs = inputs
18
+ @parameters = parameters
19
+ @nodes = nodes
20
+ end
21
+
22
+ # Checks everything and returns +outputs+ as the graph holds them:
23
+ # string names to Refs, sorted, frozen.
24
+ def call(outputs)
25
+ sequential!(@inputs, InputSpec, "input")
26
+ sequential!(@parameters, ParameterSpec, "parameter")
27
+ sequential!(@nodes, NodeSpec, "node")
28
+ unique!(@inputs.map(&:name), "input name")
29
+ unique!(@parameters.map(&:path), "parameter path")
30
+ unique!(@nodes.filter_map(&:name), "node name")
31
+ @nodes.each { |node| references!(node) }
32
+ outputs = outputs!(outputs)
33
+ reachable!(outputs)
34
+ outputs
35
+ end
36
+
37
+ private
38
+
39
+ def sequential!(specs, klass, kind)
40
+ specs.each_with_index do |spec, i|
41
+ unless spec.is_a?(klass)
42
+ raise ConfigError, "#{kind} at position #{i} is a #{spec.class}, expected #{klass}"
43
+ end
44
+ unless spec.id == i
45
+ raise ConfigError,
46
+ "#{kind} ids must be consecutive from 0: found id #{spec.id} at position #{i}"
47
+ end
48
+ end
49
+ end
50
+
51
+ def unique!(values, what)
52
+ values.tally.each do |value, count|
53
+ raise ConfigError, "duplicate #{what} #{value.inspect}" if count > 1
54
+ end
55
+ end
56
+
57
+ # Only earlier nodes are within reach, which is what forbids a
58
+ # forward reference.
59
+ def references!(node)
60
+ where = "node #{node.id} (#{node.op})"
61
+ node.inputs.each do |ref|
62
+ if ref.node? && ref.id >= node.id
63
+ raise ConfigError,
64
+ "#{where}: references #{ref}, which is not before it " \
65
+ "(forward references are not allowed)"
66
+ end
67
+ ref.resolve(inputs: @inputs, nodes: @nodes, where: "#{where}:")
68
+ end
69
+ node.parameters.each do |pid|
70
+ unless pid < @parameters.size
71
+ raise ConfigError, "#{where}: references unknown parameter #{pid}"
72
+ end
73
+ end
74
+ end
75
+
76
+ def outputs!(outputs)
77
+ unless outputs.is_a?(Hash) && !outputs.empty?
78
+ raise ConfigError, "a graph must declare at least one named output"
79
+ end
80
+
81
+ named = outputs.to_h do |name, ref|
82
+ name = name.to_s
83
+ raise ConfigError, "an output name must not be empty" if name.empty?
84
+
85
+ ref = Ref.parse(ref)
86
+ ref.resolve(inputs: @inputs, nodes: @nodes, where: "output #{name.inspect}")
87
+ [-name, ref]
88
+ end
89
+ named.sort.to_h.freeze
90
+ end
91
+
92
+ # Every node must contribute to an output. A dead node is almost
93
+ # always a mistake in the model definition, and silently keeping it
94
+ # would make the digest depend on code that does nothing.
95
+ def reachable!(outputs)
96
+ alive = []
97
+ queue = node_ids(outputs.values)
98
+ until queue.empty?
99
+ id = queue.pop
100
+ next if alive[id]
101
+
102
+ alive[id] = true
103
+ queue.concat(node_ids(@nodes[id].inputs))
104
+ end
105
+ dead = @nodes.reject { |n| alive[n.id] }
106
+ return if dead.empty?
107
+
108
+ names = dead.map { |n| "node #{n.id} (#{n.op})" }.join(", ")
109
+ raise ConfigError, "unreachable from any output: #{names}"
110
+ end
111
+
112
+ def node_ids(refs) = refs.filter_map { |ref| ref.id if ref.node? }
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module IR
5
+ # One computation graph: inputs, parameters, nodes in topological order,
6
+ # and its named outputs. Construction validates the structure
7
+ # ([`Graph::Check`]), so an invalid graph is never representable.
8
+ #
9
+ # Outputs are named because that is what an objective graph refers to
10
+ # (docs/plan.md section 5A.3): {"logits" => "node:12"}.
11
+ class Graph < Data.define(:inputs, :parameters, :nodes, :outputs)
12
+ def initialize(inputs:, parameters:, nodes:, outputs:)
13
+ outputs = Check.new(inputs:, parameters:, nodes:).call(outputs)
14
+ super(inputs: Freeze.deep(inputs.dup), parameters: Freeze.deep(parameters.dup),
15
+ nodes: Freeze.deep(nodes.dup), outputs:)
16
+ end
17
+
18
+ def to_h
19
+ {
20
+ "inputs" => inputs.map(&:to_h),
21
+ "parameters" => parameters.map(&:to_h),
22
+ "nodes" => nodes.map(&:to_h),
23
+ "outputs" => outputs.transform_values(&:to_s)
24
+ }
25
+ end
26
+
27
+ # The input or node +ref+ (a Ref, or one written out) points at.
28
+ def resolve(ref) = Ref.parse(ref).resolve(inputs:, nodes:, where: "this graph")
29
+
30
+ # The shape and dtype behind one named output, for whoever consumes it.
31
+ def output_signature(name)
32
+ ref = outputs.fetch(name.to_s) do
33
+ raise ConfigError,
34
+ "this graph has no output #{name.to_s.inspect}; it has " \
35
+ "#{outputs.keys.map(&:inspect).join(", ")}"
36
+ end
37
+ spec = resolve(ref)
38
+ [spec.shape, spec.dtype]
39
+ end
40
+
41
+ # Every name a tap could ask for.
42
+ def node_names = nodes.filter_map(&:name)
43
+
44
+ def self.from_h(h)
45
+ new(inputs: h.fetch("inputs").map { |x| InputSpec.from_h(x) },
46
+ parameters: h.fetch("parameters").map { |x| ParameterSpec.from_h(x) },
47
+ nodes: h.fetch("nodes").map { |x| NodeSpec.from_h(x) },
48
+ outputs: h.fetch("outputs"))
49
+ end
50
+ end
51
+ end
52
+ end