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,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # Low-rank adaptation (Hu et al., 2021), as something a graph is built
5
+ # with (docs/plan.md section 15.50).
6
+ #
7
+ # A fine-tune that moves every weight of a 0.5B model needs the
8
+ # gradients and the optimizer's two moments for every one of them,
9
+ # which is four copies of the model. LoRA trains a pair of small
10
+ # matrices beside each weight instead and leaves the weight alone:
11
+ #
12
+ # y = Wx + b + (alpha / rank) * B(Ax)
13
+ #
14
+ # `A` is [rank, d_in] and starts random; `B` is [d_out, rank] and
15
+ # **starts at zero**, so before any step the sum is exactly the base
16
+ # model. That is not a detail: it is what makes an adapted model safe
17
+ # to start from, and there is a test that it holds.
18
+ #
19
+ # What this holds is the decision, not the arithmetic:
20
+ #
21
+ # adapter = Torobi::LoRA.new(rank: 8, alpha: 16, on: %w[q_proj v_proj])
22
+ # model = Torobi::Models::Llama.causal_lm(config, seq: 512, adapter:)
23
+ #
24
+ # `on` names the linears to adapt by their last segment, which is how
25
+ # everyone else spells it (`target_modules` in PEFT) and is the only
26
+ # part of the path a model's author and its adapter agree about: the
27
+ # layer number is the model's business.
28
+ #
29
+ # `dropout:` is PEFT's `lora_dropout`: the input of the low-rank path is
30
+ # dropped out before `A` reads it, in training and not otherwise, each
31
+ # adapted linear drawing its own mask. It is 0 by default, and then adds
32
+ # nothing to the graph, so what was built before is the same graph
33
+ # (and has the same digest). A graph that draws randomness cannot be
34
+ # back-propagated twice, which is what a gradient cache does, so
35
+ # `Torobi::GradCache` refuses one.
36
+ LoRA = Data.define(:rank, :alpha, :on, :dropout, :tokens) do
37
+ # The two halves of the product, as a checkpoint spells them.
38
+ SUFFIXES = %w[lora_A.weight lora_B.weight].freeze
39
+
40
+ # What the rows of a table that are trained are called beside the table
41
+ # (`trainable_token_indices` in PEFT's terms). A constant in this block belongs to
42
+ # `Torobi`, so it is read as a method.
43
+ TOKENS = "trainable_tokens_delta"
44
+
45
+ def self.rows_name = TOKENS
46
+
47
+ def initialize(rank:, on:, alpha: nil, dropout: 0.0, tokens: [])
48
+ rank = Integer(rank)
49
+ raise ConfigError, "a LoRA rank must be positive, got #{rank}" unless rank.positive?
50
+
51
+ on = Array(on).map(&:to_s)
52
+ raise ConfigError, "a LoRA adapts something: on: names which linears" if on.empty?
53
+
54
+ # alpha defaults to the rank, which is a scale of one: what the
55
+ # rank changes is then capacity rather than step size.
56
+ dropout = Float(dropout)
57
+ unless dropout >= 0.0 && dropout < 1.0
58
+ raise ConfigError, "a LoRA dropout is a chance in 0...1, got #{dropout}"
59
+ end
60
+
61
+ tokens = Array(tokens).map { |id| Integer(id) }.uniq
62
+ if tokens.any?(&:negative?)
63
+ raise ConfigError,
64
+ "a token to train is an id of 0 or more, got #{tokens.inspect}"
65
+ end
66
+
67
+ super(rank:, alpha: Float(alpha || rank), on: on.freeze, dropout:, tokens: tokens.freeze)
68
+ end
69
+
70
+ # Whether the adapter trains rows of the embedding table (and of the output layer).
71
+ def tokens? = !tokens.empty?
72
+
73
+ # What the low-rank product is multiplied by before it is added.
74
+ def scale = alpha / rank
75
+
76
+ # Whether the linear at `path` is one of the ones being adapted.
77
+ # Matched on the last segment, so `q_proj` names the one in every
78
+ # layer and `layers.0.self_attn.q_proj` names one.
79
+ def wraps?(path)
80
+ path = path.to_s
81
+ on.any? { |target| path == target || path.end_with?(".#{target}") }
82
+ end
83
+
84
+ # What an adapter adds to a linear, by the names PEFT gives them.
85
+ def paths(name) = SUFFIXES.map { |suffix| "#{name}.#{suffix}" }
86
+
87
+ # Whether the parameter at `path` is trained while this adapter is in
88
+ # scope: only the adapter's own are. A base model left trainable by an
89
+ # oversight is not a LoRA fine-tune, and the window's `unfreeze!` moves
90
+ # only within what the graph declared trainable, so this is the
91
+ # declaration that matters.
92
+ def trains?(path) = adapted?(path)
93
+
94
+ # The adapter's own arithmetic, added to the linear `name` over `x`:
95
+ # `x` through a narrow matrix and back out to the width the linear
96
+ # has, scaled. Built through the graph's public vocabulary, with the
97
+ # names `paths` gives, which are the names every other part of Torobi
98
+ # reads them by.
99
+ #
100
+ # `B` starts at zero, so this contributes nothing until something has
101
+ # trained it. That is what makes an adapted model start as the model
102
+ # it adapts.
103
+ #
104
+ # **The two matrices are f32, whatever the model is held in**, and so
105
+ # is their arithmetic: `x` is widened on the way in and the result is
106
+ # narrowed back to `x`'s dtype on the way out, so the layers around
107
+ # it are as they were. They are the only parameters that train, and
108
+ # bf16 holds a value to about 0.4%: an Adam step of 1e-4 on an entry
109
+ # of A near 0.08 is a change of 0.1%, which rounds away. mlx-lm makes
110
+ # the same choice (`tuner/lora.py`: its matrices are made in MLX's
111
+ # default f32 and the result is `astype(x.dtype)`). On an f32 model
112
+ # neither cast is a node, and nothing changes.
113
+ def contribution(g, x, d_in:, d_out:, name:)
114
+ a_path, b_path = paths(name)
115
+ a = g.param(a_path, [rank, d_in], dtype: :f32, init: { "type" => "kaiming_uniform" })
116
+ b = g.param(b_path, [d_out, rank], dtype: :f32, init: { "type" => "zeros" })
117
+ wide = g.cast(x, :f32)
118
+ wide = wide.dropout(p: dropout) if dropout.positive?
119
+ down = g.matmul(wide, a.transpose(axes: [1, 0]))
120
+ g.cast(g.matmul(down, b.transpose(axes: [1, 0])) * scale, x.dtype)
121
+ end
122
+
123
+ # What `fresh:` should say when starting from a published checkpoint:
124
+ # the adapter's matrices are in no file, and everything else must be.
125
+ #
126
+ # Session.open(config, pretrained: { m: file },
127
+ # fresh: adapter.fresh(config))
128
+ #
129
+ # The paths themselves rather than a pattern. The engine's patterns
130
+ # are prefixes (`student.layers.3.*`), and what these have in common
131
+ # is how they end; asking for a wildcard in the middle would be
132
+ # asking for a query language to say something a list already says.
133
+ def fresh(config)
134
+ config.parameters.map(&:qualified_path).select { |path| adapted?(path) }
135
+ end
136
+
137
+ # Whether a parameter path is an adapter's own.
138
+ #
139
+ # A fact about the name rather than about any particular adapter, so
140
+ # it is asked of the class: `Session#export_model!` wants to know
141
+ # whether what it is about to write holds an adapter, and it has the
142
+ # paths rather than the LoRA that made them.
143
+ def self.adapted?(path)
144
+ path = path.to_s
145
+ SUFFIXES.any? { |suffix| path.end_with?(".#{suffix}") } || path.end_with?(".#{TOKENS}")
146
+ end
147
+
148
+ # The rows of an embedding table or an output layer that are trained, as what to add to
149
+ # what the table gives for them.
150
+ #
151
+ # PEFT trains these as the rows themselves, started from the table's. Held here as a
152
+ # difference from the table's, started at zero, so that nothing has to be copied out of a
153
+ # checkpoint to begin: what a row is, is the table's plus this. `Session#export_adapter!`
154
+ # translates at the boundary; `import_adapter!` does not yet read these rows.
155
+ #
156
+ # `ids` is what the model reads (`[rows, seq]`, i32) and the result is what is added to its
157
+ # embeddings. A token's rows are found in the graph from the ids (`relu(1 - |id - token|)`
158
+ # is 1 for the token and 0 for any other integer), so no field is added to a batch.
159
+ def token_embeddings(g, ids, dim:, name:, dtype:)
160
+ delta = g.param("#{name}.#{TOKENS}", [tokens.size, dim], dtype: :f32,
161
+ init: { "type" => "zeros" })
162
+ found = g.cast(ids, :f32)
163
+ extra = nil
164
+ tokens.each_with_index do |token, i|
165
+ match = (((found - token).abs * -1.0) + 1.0).relu.reshape(shape: [-1, ids.shape[1], 1])
166
+ row = match * delta.slice(axis: 0, start: i, length: 1)
167
+ extra = extra ? extra + row : row
168
+ end
169
+ g.cast(extra, dtype)
170
+ end
171
+
172
+ # What the output layer adds to its scores for the trained rows: each row's score is the
173
+ # hidden state's product with the row, so the difference is the product with the difference,
174
+ # in the token's column. `columns` is `[vocab]`, 0, 1, 2, ... (the batch's `token_columns`).
175
+ # `delta` is the same parameter the embeddings use when the table is tied to the output.
176
+ def token_scores(g, hidden, columns, delta)
177
+ wide = g.cast(hidden, :f32)
178
+ extra = nil
179
+ tokens.each_with_index do |token, i|
180
+ product = g.matmul(wide, delta.slice(axis: 0, start: i, length: 1).transpose(axes: [1, 0]))
181
+ column = (((columns - token).abs * -1.0) + 1.0).relu
182
+ scored = product * column
183
+ extra = extra ? extra + scored : scored
184
+ end
185
+ g.cast(extra, hidden.dtype)
186
+ end
187
+
188
+ def adapted?(path) = self.class.adapted?(path)
189
+ end
190
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ # What the device is holding.
5
+ #
6
+ # Ruby's GC does not see device memory: a session is one small object
7
+ # here and a hundred megabytes there, so a long run needs numbers it can
8
+ # watch and a limit it can set (docs/plan.md section 11.3).
9
+ #
10
+ # These are process-wide, because MLX's allocator is. Two sessions share
11
+ # one pool, which is a reason to run one training session per process
12
+ # rather than a reason to hide the sharing.
13
+ module Memory
14
+ module_function
15
+
16
+ # Bytes: what is in use, what the allocator is keeping, the high-water
17
+ # mark, and the cap (0 meaning none).
18
+ def report = Native.memory.transform_keys(&:to_sym)
19
+
20
+ def active = report.fetch(:active)
21
+ def cache = report.fetch(:cache)
22
+ def peak = report.fetch(:peak)
23
+ def limit = report.fetch(:limit)
24
+
25
+ # Frees what the allocator holds but is not using. Returns how many
26
+ # bytes went.
27
+ def clear_cache!
28
+ before, after = Native.clear_cache
29
+ before - after
30
+ end
31
+
32
+ # Tells MLX what this process should hold on the device; 0 lifts it.
33
+ # Read `limit` first if you mean to restore it: MLX reports the cap now
34
+ # in force, not the one it replaced.
35
+ #
36
+ # **Not a ceiling.** Measured: a 336 MB peak ran to completion under a
37
+ # 67 MB limit, and a step reaching 14.5 GB ran under a 9 GB one, thirteen
38
+ # times slower than usual. MLX reads this as pressure on its cache, so
39
+ # it reclaims earlier and keeps going. A run that must not pass a size
40
+ # wants `Torobi::Policies::MemoryGuard` as well, which reads `peak`
41
+ # between steps and stops.
42
+ def limit=(bytes)
43
+ Native.memory_limit = bytes
44
+ end
45
+
46
+ # Forgets the high-water mark, so a later reading is about what
47
+ # follows rather than about everything so far.
48
+ def reset_peak! = Native.reset_peak_memory
49
+ end
50
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "mlx_prebuilt"
4
+
5
+ module Torobi
6
+ # MLX finds its Metal kernels through dladdr: `mlx.metallib` must sit
7
+ # beside whichever library holds the MLX symbols, unless it is told where
8
+ # to look first. A source install puts it there (`ext/torobi/extconf.rb`,
9
+ # `rake metallib`); a platform gem cannot ship the 129 MB file, so on
10
+ # first use it is fetched into a writable cache and MLX is pointed at it
11
+ # (`mlx_metal_set_metallib_path`).
12
+ #
13
+ # macOS only. Linux compiles its CUDA kernels at run time and has no such
14
+ # file.
15
+ module Metallib
16
+ module_function
17
+
18
+ # Points MLX at the kernels and returns where they are.
19
+ #
20
+ # The copy a checkout put beside the bundle wins; otherwise they are
21
+ # fetched into the cache the pin names, which is writable, and MLX is
22
+ # told to look there (`mlx_metal_set_metallib_path`). That is what lets
23
+ # a platform gem work from a directory it cannot write: its own.
24
+ # Raises EngineUnavailable when they are missing and cannot be fetched,
25
+ # which is the same failure the probe below would find, said sooner.
26
+ def ensure!(io: $stderr)
27
+ path = resolved(io:)
28
+ Native.set_metallib_path(path)
29
+ path
30
+ rescue MlxPrebuilt::Refused => e
31
+ raise EngineUnavailable, "MLX's Metal kernels could not be obtained: #{e.message}"
32
+ end
33
+
34
+ # Where the kernels are, fetching them if a checkout did not leave a
35
+ # copy beside the bundle and none has been fetched before. The paths
36
+ # are parameters so the order can be held to without a filesystem.
37
+ def resolved(io: $stderr, beside: Preflight::METALLIB, cached: cached_path)
38
+ return beside if File.file?(beside)
39
+ return cached if File.file?(cached)
40
+
41
+ MlxPrebuilt.fetch_metallib(into: File.dirname(cached), io:)
42
+ end
43
+
44
+ # The cache the pin names, per release: one fetch, reused by every
45
+ # session after it, and never written beside a read-only gem.
46
+ def cached_path
47
+ File.join(MlxPrebuilt.cache_dir, "mlx.metallib")
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,24 @@
1
+ {
2
+ "repo": "takahashim/mlx-prebuilt",
3
+ "release": "v0.6.0.2",
4
+ "mlx": "0.32.2",
5
+ "mlx_c": "c74db5307cc8ce122f48d97ef951b30578674e7f",
6
+ "requires": {
7
+ "mlx": "0.32.2",
8
+ "mlx-c": "c74db5307cc8"
9
+ },
10
+ "platforms": {
11
+ "macos-arm64": {
12
+ "asset": "mlx-v0.32.2-mlxc-c74db5307cc8ce122f48d97ef951b30578674e7f-macos-arm64.tar.gz",
13
+ "digest": "290331d6dc848cbbf18453a5e3bbc095ec234c9dc528339d3dd4bfc7731dca97",
14
+ "metallib": {
15
+ "asset": "mlx-v0.32.2-mlxc-c74db5307cc8ce122f48d97ef951b30578674e7f-macos-arm64.metallib.tar.gz",
16
+ "digest": "20d3b7e10c90a5ce73fe53a8a1b780c11cc67fa04468a8d5d06c5dd4a0f5cf3b"
17
+ }
18
+ },
19
+ "linux-x86_64": {
20
+ "asset": "mlx-v0.32.2-mlxc-c74db5307cc8ce122f48d97ef951b30578674e7f-linux-x86_64-cuda12.tar.gz",
21
+ "digest": "060f2757a32c819e4bc67098f4000bc8c24a2fc3458f14c151da024fb01d8245"
22
+ }
23
+ }
24
+ }