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,419 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Torobi
6
+ # A training run in a process of its own.
7
+ #
8
+ # Torobi asks for this rather than offering it as an option
9
+ # (notes/SESSION_CONCURRENCY_SPEC.md sections 2 and 9, docs/plan.md 11.4).
10
+ # A mutex inside a process is not fault isolation: MLX can end the process
11
+ # it runs in, and no `rescue` sees that happen. A long run therefore
12
+ # belongs somewhere its death is an exit status rather than the end of the
13
+ # caller. Which also settles the fork question: the child is exec'd, so it
14
+ # brings no Metal device with it.
15
+ #
16
+ # The two sides share a directory and nothing else. The child writes its
17
+ # journal and its checkpoints there; the parent reads both. No pipe to
18
+ # keep open, no protocol to version, and an interrupted run leaves exactly
19
+ # what a finished one would, minus the last entry.
20
+ #
21
+ # runner = Torobi::Runner.new(["ruby", "train.rb"], dir: "runs/001")
22
+ # runner.start
23
+ # runner.progress # => the last Journal::Span (step, loss, at)
24
+ # runner.stop # asks it to stop at the next step boundary
25
+ # runner.wait.finished? # => true
26
+ #
27
+ # And in train.rb:
28
+ #
29
+ # Torobi::Runner.child do |run|
30
+ # Torobi::Session.open(config, weights: weights, io: run.journal) do |s|
31
+ # s.run(batches) do
32
+ # s.checkpoint!(run.checkpoint) if (s.step % 200).zero?
33
+ # break if run.stopping?
34
+ # end
35
+ # end
36
+ # end
37
+ class Runner
38
+ # The run directory as both sides see it.
39
+ JOURNAL = "journal.jsonl"
40
+ CHECKPOINT = "checkpoint"
41
+
42
+ # How the child says which way it ended, in the variable it is started
43
+ # with. A directory rather than a pipe means the parent can also read
44
+ # this after the fact, from a run it did not start.
45
+ DIRECTORY_VARIABLE = "TOROBI_RUN_DIR"
46
+
47
+ # What the child is told it may allocate on the device, in bytes.
48
+ #
49
+ # MLX draws from the same memory the rest of the machine uses, so a run
50
+ # that asks for more than there is does not fail: the machine stops
51
+ # answering and its watchdog ends the session.
52
+ #
53
+ # This does not prevent that on its own, which was measured: a step
54
+ # whose peak reached 14.5 GB ran to completion under a 9 GB limit, at
55
+ # 41s where it usually takes 3. MLX reads the limit as pressure on its
56
+ # cache rather than as a ceiling, so what it buys is earlier
57
+ # reclaiming and a warning sign in the timings. The ceiling is
58
+ # `Torobi::Policies::MemoryGuard`, which reads what is held between
59
+ # steps and stops the run. Set both.
60
+ LIMIT_VARIABLE = "TOROBI_MEMORY_LIMIT"
61
+
62
+ # What the child exits with. A signal is not in here on purpose: that is
63
+ # the case this whole arrangement exists for, and it arrives as a signal
64
+ # rather than as a number.
65
+ EXIT_OK = 0
66
+ EXIT_FAILED = 70 # EX_SOFTWARE: the run raised
67
+ EXIT_UNAVAILABLE = 69 # EX_UNAVAILABLE: the engine cannot run here
68
+
69
+ # `memory_limit:` is bytes the child may hold on the device. Nil leaves
70
+ # MLX uncapped, which is what a spike wants and what a long run should
71
+ # not have: an uncapped run that asks for too much takes the machine
72
+ # with it (see LIMIT_VARIABLE).
73
+ def initialize(command, dir:, env: {}, memory_limit: nil)
74
+ @command = Array(command).map(&:to_s)
75
+ raise ArgumentError, "a runner needs a command" if @command.empty?
76
+
77
+ @dir = File.expand_path(dir.to_s)
78
+ @env = env.transform_keys(&:to_s).transform_values(&:to_s)
79
+ @env[LIMIT_VARIABLE] = Integer(memory_limit).to_s if memory_limit
80
+ @pid = nil
81
+ @outcome = nil
82
+ @read = Reading.new(journal_path)
83
+ end
84
+
85
+ attr_reader :dir, :pid, :outcome
86
+
87
+ def journal_path = File.join(@dir, JOURNAL)
88
+
89
+ # Where the run checkpoints, as a `Torobi::Checkpoint`: whether one is
90
+ # there to resume from, and what it says, is asked of it.
91
+ def checkpoint = Checkpoint.new(File.join(@dir, CHECKPOINT))
92
+
93
+ # Starts the run. The directory is made, but nothing in it is removed:
94
+ # a runner started against a directory that already holds a checkpoint
95
+ # is how a run resumes, and deleting that would be the wrong default.
96
+ def start
97
+ raise Error, "this runner has already been started" if @pid
98
+
99
+ require "fileutils"
100
+ FileUtils.mkdir_p(@dir)
101
+ @pid = Process.spawn(@env.merge(DIRECTORY_VARIABLE => @dir), *@command,
102
+ chdir: Dir.pwd, unsetenv_others: false)
103
+ self
104
+ end
105
+
106
+ # Whether the child is still going.
107
+ #
108
+ # Reaping is not free of consequence: asking this is the only chance to
109
+ # learn the exit status, so it is kept when it arrives rather than
110
+ # thrown away. A `running?` that discarded it left `wait` with nothing
111
+ # to report.
112
+ def running?
113
+ return false unless @pid && @outcome.nil?
114
+
115
+ pid, status = Process.waitpid2(@pid, Process::WNOHANG)
116
+ return true if pid.nil?
117
+
118
+ reap(status)
119
+ false
120
+ rescue Errno::ECHILD
121
+ false
122
+ end
123
+
124
+ # What the child has written down so far: the last step it recorded
125
+ # (a `Journal::Span`, with its step, loss and time). Nil before the
126
+ # first one.
127
+ #
128
+ # Read from the journal rather than asked of the child, because the
129
+ # child may be inside a step, or gone. A record on disk answers either
130
+ # way (the journal flushes per entry for exactly this).
131
+ def progress = last_entry(Journal::Span)
132
+
133
+ # Asks the run to stop at the next step boundary and waits for it.
134
+ #
135
+ # TERM rather than KILL: the child finishes the step it is in, writes a
136
+ # last checkpoint if it was asked to, and exits. `grace` is how long to
137
+ # allow for that before insisting, because a step that has wedged the
138
+ # GPU will not answer.
139
+ def stop(grace: 30)
140
+ return @outcome unless running?
141
+
142
+ signal("TERM")
143
+ deadline = now + grace
144
+ sleep(0.02) while running? && now < deadline
145
+ if running?
146
+ signal("KILL")
147
+ sleep(0.02) while running?
148
+ end
149
+ wait
150
+ end
151
+
152
+ # Blocks until the run ends, and says how.
153
+ def wait
154
+ return @outcome if @outcome
155
+ raise Error, "this runner has not been started" unless @pid
156
+
157
+ _, status = Process.waitpid2(@pid)
158
+ reap(status)
159
+ rescue Errno::ECHILD
160
+ @outcome ||= Outcome.new(status: nil, note: nil)
161
+ end
162
+
163
+ private
164
+
165
+ # The child has ended; read what it said on the way out.
166
+ def reap(status)
167
+ @outcome = Outcome.new(status:, note: last_entry(Journal::Note))
168
+ end
169
+
170
+ def signal(name)
171
+ Process.kill(name, @pid)
172
+ rescue Errno::ESRCH
173
+ nil
174
+ end
175
+
176
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
177
+
178
+ # The last journal entry of a kind, as of now.
179
+ def last_entry(kind) = @read.last(kind)
180
+
181
+ # The journal as the parent reads it: forwards, once.
182
+ #
183
+ # Progress is asked for over and over while a run goes, so what this
184
+ # has to be good at is being asked again. It keeps how far it has read
185
+ # and the last entry of each kind it saw, and a second call reads only
186
+ # what was appended since the first. A run that appends 180 bytes a
187
+ # step costs a poll 180 bytes, rather than the whole journal (which was
188
+ # 14 MB and 16 ms at a hundred thousand steps).
189
+ #
190
+ # Forwards rather than seeking to the end: a line can be half-written
191
+ # when a poll lands, and holding the incomplete tail until the rest
192
+ # arrives is one variable here and a special case in every backwards
193
+ # scheme. Reading from the start costs one pass, once.
194
+ class Reading
195
+ def initialize(path)
196
+ @path = path
197
+ @offset = 0
198
+ @partial = +""
199
+ @last = {}
200
+ end
201
+
202
+ # The last entry of `kind` (a `Journal` entry class) the journal
203
+ # holds, or nil.
204
+ def last(kind)
205
+ catch_up
206
+ @last[kind]
207
+ end
208
+
209
+ private
210
+
211
+ def catch_up
212
+ size = File.size?(@path) or return
213
+ # A journal is only ever appended to. Anything else (a directory
214
+ # reused, a file replaced) is a different journal, so start over
215
+ # rather than read from a position that means nothing now.
216
+ reset if size < @offset
217
+ return if size == @offset
218
+
219
+ File.open(@path) do |io|
220
+ io.seek(@offset)
221
+ @partial << io.read(size - @offset).to_s
222
+ @offset = size
223
+ end
224
+ consume
225
+ end
226
+
227
+ def reset
228
+ @offset = 0
229
+ @partial = +""
230
+ @last = {}
231
+ end
232
+
233
+ # Whole lines only. The last one is kept when it has no newline yet:
234
+ # the journal flushes per entry, but a poll can still land between
235
+ # the write and the newline.
236
+ #
237
+ # Every line is parsed, which is the price of reading forwards: what
238
+ # the last entry of a kind is cannot be known until the ones after
239
+ # it have been looked at. It is paid once, over what was already
240
+ # there when this started reading, and a run whose parent started it
241
+ # has nothing there at all.
242
+ def consume
243
+ lines = @partial.split("\n", -1)
244
+ @partial = lines.pop || +""
245
+ lines.each do |line|
246
+ h = begin
247
+ JSON.parse(line)
248
+ rescue JSON::ParserError
249
+ next
250
+ end
251
+ # The header has no kind, and is not an entry.
252
+ next unless h["kind"]
253
+
254
+ entry = begin
255
+ Journal::Entry.from_h(h)
256
+ rescue KeyError, ArgumentError
257
+ # A kind or a shape this version does not know: another
258
+ # writer's line, which says nothing about this run's progress.
259
+ next
260
+ end
261
+ @last[entry.class] = entry
262
+ end
263
+ end
264
+ end
265
+
266
+ # How a run ended, and what it said on the way out.
267
+ class Outcome
268
+ def initialize(status:, note:)
269
+ @status = status
270
+ @note = note
271
+ end
272
+
273
+ attr_reader :status, :note
274
+
275
+ # It ran to the end of what it was given.
276
+ def finished? = ok? && event == "finished"
277
+
278
+ # It was asked to stop and did.
279
+ def stopped? = ok? && event == "stopped"
280
+
281
+ # It raised. The journal's last note says what.
282
+ def failed? = !@status.nil? && !ok? && @status.exitstatus == EXIT_FAILED
283
+
284
+ # The engine could not run there at all.
285
+ def unavailable? = !@status.nil? && @status.exitstatus == EXIT_UNAVAILABLE
286
+
287
+ # The process was ended rather than ending: a signal, which for this
288
+ # library usually means MLX aborted. The last checkpoint still stands,
289
+ # because a checkpoint is written atomically.
290
+ def crashed? = @status&.signaled? == true
291
+
292
+ def ok? = !@status.nil? && @status.success?
293
+
294
+ # What the run said as it ended, if it said anything.
295
+ def message = @note&.[]("message")
296
+
297
+ def event = @note&.event
298
+
299
+ def to_s
300
+ return "not started" if @status.nil?
301
+ return "crashed (SIG#{Signal.signame(@status.termsig)})" if crashed?
302
+
303
+ "#{event || "exited"} (#{@status.exitstatus})"
304
+ end
305
+ end
306
+
307
+ # The child's half: where to write, and whether to stop.
308
+ #
309
+ # It owns two things and no more. The run directory, so both sides agree
310
+ # without being told twice. And the stop signals, because the parent's
311
+ # only way to ask is a signal, and a signal handler must set a flag
312
+ # rather than do work.
313
+ class Child
314
+ def initialize(dir, memory_limit: nil)
315
+ @dir = dir
316
+ @stopping = false
317
+ @journal = nil
318
+ @memory_limit = memory_limit
319
+ end
320
+
321
+ # Tells MLX what this run may hold on the device, if the parent said
322
+ # so, and answers what that is.
323
+ #
324
+ # Before anything opens a session, because the allocator should know
325
+ # before it starts. It is not a ceiling (see LIMIT_VARIABLE): a run
326
+ # that must not pass a size also wants a
327
+ # `Torobi::Policies::MemoryGuard` at that size, which is the half
328
+ # that raises.
329
+ def cap!
330
+ return unless @memory_limit && Torobi.const_defined?(:Memory)
331
+
332
+ Torobi::Memory.limit = @memory_limit
333
+ @memory_limit
334
+ end
335
+
336
+ # What the parent said this run may hold, or nil. What a
337
+ # `MemoryGuard` should be built with.
338
+ attr_reader :memory_limit
339
+
340
+ attr_reader :dir
341
+
342
+ def checkpoint = Checkpoint.new(File.join(@dir, CHECKPOINT))
343
+
344
+ # The journal to hand `Session.open(io:)`. Appended to, so a resumed
345
+ # run adds to the record rather than replacing it.
346
+ def journal
347
+ # Held open for the length of the run rather than opened around
348
+ # each write, so the block form is not what this wants.
349
+ @journal ||= File.open(File.join(@dir, JOURNAL), "a") # rubocop:disable Style/FileOpen
350
+ .tap { |io| io.sync = true }
351
+ end
352
+
353
+ # Whether the parent has asked this run to stop. The loop checks it
354
+ # between steps, which is the only place stopping is well defined
355
+ # (the spec, section 7).
356
+ def stopping? = @stopping
357
+
358
+ # Installs the handlers. A trap runs at an unspecified moment, so it
359
+ # does the smallest thing that can be done: set a flag.
360
+ def listen
361
+ %w[TERM INT].each { |name| Signal.trap(name) { @stopping = true } }
362
+ self
363
+ end
364
+
365
+ def close
366
+ @journal&.close
367
+ @journal = nil
368
+ end
369
+ end
370
+
371
+ class << self
372
+ # The child side. Runs `block` with a `Child`, and turns however it
373
+ # ends into an exit status the parent can read.
374
+ #
375
+ # The last thing written is always a note saying which way it went, so
376
+ # a parent that arrives after the fact learns the same thing a parent
377
+ # that waited would.
378
+ def child(dir = ENV.fetch(DIRECTORY_VARIABLE, nil))
379
+ raise ArgumentError, "no run directory (#{DIRECTORY_VARIABLE})" unless dir
380
+
381
+ limit = ENV.fetch(LIMIT_VARIABLE, nil)
382
+ run = Child.new(dir, memory_limit: limit && Integer(limit)).listen
383
+ run.cap!
384
+ begin
385
+ yield run
386
+ finish(run, run.stopping? ? "stopped" : "finished")
387
+ EXIT_OK
388
+ rescue EngineUnavailable => e
389
+ finish(run, "unavailable", e.message)
390
+ EXIT_UNAVAILABLE
391
+ rescue StandardError => e
392
+ finish(run, "failed", "#{e.class}: #{e.message}")
393
+ EXIT_FAILED
394
+ ensure
395
+ run.close
396
+ end
397
+ end
398
+
399
+ # The same, and exits with what it returns. What a training script
400
+ # ends with.
401
+ def child!(dir = ENV.fetch(DIRECTORY_VARIABLE, nil), &)
402
+ exit(child(dir, &))
403
+ end
404
+
405
+ private
406
+
407
+ # A note of its own, appended by hand: the session's journal may
408
+ # already be closed by the time a run ends, and this has to be the
409
+ # last line either way.
410
+ def finish(run, event, message = nil)
411
+ note = Journal::Note.new(event:, details: { message: }.compact)
412
+ run.journal.puts(note.to_json)
413
+ run.journal.flush
414
+ rescue IOError, Errno::EBADF
415
+ nil
416
+ end
417
+ end
418
+ end
419
+ end