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,273 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module Models
5
+ # Gemma 3, as a GraphConfig (docs/plan.md section 15.54).
6
+ #
7
+ # Not one of the Llama-shaped family (`Models::Llama`), and worth
8
+ # saying why, because the tensor names look almost the same. Five
9
+ # things differ, and every one of them is the kind that leaves a model
10
+ # that runs, trains, and is not the published one:
11
+ #
12
+ # 1. **four norms a layer**, not two: each block is wrapped rather
13
+ # than preceded, so the attention output is normalized before it
14
+ # is added back
15
+ # 2. **q and k are normalized per head** before they are rotated
16
+ # 3. **the norms scale by `1 + w`**, so Gemma's norm weights sit
17
+ # around zero where everyone else's sit around one
18
+ # 4. **the gate is the tanh approximation of GELU**, which is a
19
+ # different function from the exact one
20
+ # 5. **the embeddings are scaled by the square root of the width**
21
+ #
22
+ # And one that is structure rather than arithmetic: most layers attend
23
+ # only within a window of the recent past, with a different rotary
24
+ # base from the few that see everything. ModernBERT alternates that
25
+ # way too (`Models::ModernBERT`), which is where the machinery came
26
+ # from.
27
+ #
28
+ # No KV cache and no sampling loop, as everywhere else here: what
29
+ # Torobi does with a decoder is fine-tune it (docs/plan.md section 14).
30
+ module Gemma3
31
+ # What a Gemma 3 text config says.
32
+ Config = Data.define(
33
+ :vocab_size, :hidden_size, :intermediate_size, :num_hidden_layers,
34
+ :num_attention_heads, :num_key_value_heads, :head_dim, :rms_norm_eps,
35
+ :rope_theta, :rope_local_base_freq, :sliding_window, :layer_types,
36
+ :query_pre_attn_scalar, :tie_word_embeddings, :pad_token_id
37
+ ) do
38
+ # Whether this layer sees only the recent past. The config lists
39
+ # them one by one, which is more honest than a pattern: what the
40
+ # model does is the list.
41
+ def sliding?(layer) = layer_types.fetch(layer) == "sliding_attention"
42
+
43
+ def any_sliding? = layer_types.include?("sliding_attention")
44
+
45
+ # The local layers rotate at a lower base than the global ones, so
46
+ # a window of 512 and a context of 32k are addressed differently.
47
+ def theta(layer) = sliding?(layer) ? rope_local_base_freq : rope_theta
48
+
49
+ # Gemma names the number the scores are divided by rather than
50
+ # deriving it from the head width. They are the same here and were
51
+ # not in Gemma 2, so it is read rather than computed.
52
+ def scale = 1.0 / Math.sqrt(query_pre_attn_scalar)
53
+
54
+ # What the heads take up, which is not the width of the model:
55
+ # Gemma 3 270m is 4 heads of 256 over a hidden state of 640.
56
+ def attention_size = num_attention_heads * head_dim
57
+
58
+ def check!
59
+ unless layer_types.size == num_hidden_layers
60
+ raise ConfigError,
61
+ "#{layer_types.size} layer types for #{num_hidden_layers} layers"
62
+ end
63
+ unless (num_attention_heads % num_key_value_heads).zero?
64
+ raise ConfigError,
65
+ "#{num_attention_heads} query heads do not divide into " \
66
+ "#{num_key_value_heads} key heads"
67
+ end
68
+ self
69
+ end
70
+ end
71
+
72
+ module_function
73
+
74
+ def from_config_file(path)
75
+ require "json"
76
+ from_hash(JSON.parse(File.read(path.to_s)))
77
+ end
78
+
79
+ # Reads a `config.json`, or the `text_config` inside one: the
80
+ # multimodal Gemmas wrap the language model in a config of their
81
+ # own, and what this builds is the language model.
82
+ def from_hash(raw)
83
+ raw = raw.fetch("text_config") if raw.key?("text_config")
84
+ layers = raw.fetch("num_hidden_layers")
85
+ Config.new(
86
+ vocab_size: raw.fetch("vocab_size"),
87
+ hidden_size: raw.fetch("hidden_size"),
88
+ intermediate_size: raw.fetch("intermediate_size"),
89
+ num_hidden_layers: layers,
90
+ num_attention_heads: raw.fetch("num_attention_heads"),
91
+ num_key_value_heads: raw.fetch("num_key_value_heads"),
92
+ head_dim: raw.fetch("head_dim"),
93
+ rms_norm_eps: raw.fetch("rms_norm_eps", 1e-6),
94
+ rope_theta: raw.fetch("rope_theta", 1_000_000.0),
95
+ rope_local_base_freq: raw.fetch("rope_local_base_freq", 10_000.0),
96
+ sliding_window: raw.fetch("sliding_window", 512),
97
+ layer_types: raw["layer_types"] || alternating(raw, layers),
98
+ query_pre_attn_scalar: raw.fetch("query_pre_attn_scalar", raw.fetch("head_dim")),
99
+ # Gemma ties, where Llama does not: the default is the other way
100
+ # round from `Models::Llama` and it matters, because a tied
101
+ # checkpoint holds no `lm_head.weight` at all.
102
+ tie_word_embeddings: raw.fetch("tie_word_embeddings", true),
103
+ pad_token_id: raw["pad_token_id"] || raw.fetch("eos_token_id", 0)
104
+ ).check!
105
+ end
106
+
107
+ # Which layers see everything, for a config that gives the pattern
108
+ # rather than the list: every nth, counting so that the last of each
109
+ # run of n is the one.
110
+ def alternating(raw, layers)
111
+ every = raw["sliding_window_pattern"] || raw["_sliding_window_pattern"] || 6
112
+ Array.new(layers) { |i| ((i + 1) % every).zero? ? "full_attention" : "sliding_attention" }
113
+ end
114
+
115
+ # The language model: token ids in, one score per token of the
116
+ # vocabulary out, at every position. The loss is the recipe's
117
+ # (`Models::Llama#causal_lm` says what that looks like).
118
+ def causal_lm(config, seq:, rows: nil, adapter: nil, dtype: :f32, quantization: nil)
119
+ config.check!
120
+ build = Build.new(seq:, rows:, dtype:)
121
+ Torobi.graph { |g| Describe.new(g, config, build).causal_lm(adapter, quantization) }
122
+ end
123
+
124
+ # The description itself: the builder, the config and what it is
125
+ # built for are held once (`Models::Description`), so what a method
126
+ # takes is the value flowing through it.
127
+ class Describe < Description
128
+ def causal_lm(adapter, quantization = nil)
129
+ quantized quantization do
130
+ hidden = adapting adapter do
131
+ encoded = scope "model" do
132
+ encode
133
+ end
134
+ encoded.named("hidden")
135
+ end
136
+ output :logits, head(hidden)
137
+ end
138
+ end
139
+
140
+ def head(hidden)
141
+ unless @config.tie_word_embeddings
142
+ return linear(hidden, @config.vocab_size, name: "lm_head", bias: false)
143
+ end
144
+
145
+ matmul(hidden, parameter("model.embed_tokens.weight").transpose(axes: [1, 0]))
146
+ end
147
+
148
+ def encode
149
+ ids = input(@build.field(:input_ids), [@build.rows, @build.seq], dtype: :i32)
150
+ x = embedding(ids, vocab: @config.vocab_size, dim: @config.hidden_size,
151
+ name: "embed_tokens", dtype: @build.dtype)
152
+ # Gemma scales its embeddings by the square root of the width.
153
+ # Part of the model rather than an initialization detail: leave
154
+ # it out and every layer sees something 25 times too small.
155
+ x *= Math.sqrt(@config.hidden_size)
156
+ # One mask for every local layer, and none for the global ones,
157
+ # which say what they need with `causal:`. It depends on nothing
158
+ # in the batch, so there is one of it however many rows there are.
159
+ window = if @config.any_sliding?
160
+ cast(input(@build.field(:window),
161
+ [1, 1, @build.seq, @build.seq]), @build.dtype)
162
+ end
163
+
164
+ @config.num_hidden_layers.times do |i|
165
+ x = scope "layers.#{i}" do
166
+ layer(x, i, window)
167
+ end
168
+ end
169
+ norm(x, name: "norm")
170
+ end
171
+
172
+ # One block, wrapped rather than preceded: normalized going in, and
173
+ # normalized again on the way out before the residual takes it.
174
+ def layer(x, index, window)
175
+ attended = attention(norm(x, name: "input_layernorm"), index, window)
176
+ x += norm(attended, name: "post_attention_layernorm")
177
+ fed = mlp(norm(x, name: "pre_feedforward_layernorm"))
178
+ x + norm(fed, name: "post_feedforward_layernorm")
179
+ end
180
+
181
+ # Attention over fewer keys than queries, normalized per head
182
+ # before it is rotated, and looking back no further than this
183
+ # layer may.
184
+ def attention(x, index, window)
185
+ heads = @config.num_attention_heads
186
+ kv = @config.num_key_value_heads
187
+ dim = @config.head_dim
188
+ theta = @config.theta(index)
189
+ scope "self_attn" do
190
+ q = linear(x, heads * dim, name: "q_proj", bias: false).split_heads(heads)
191
+ k = linear(x, kv * dim, name: "k_proj", bias: false).split_heads(kv)
192
+ v = linear(x, kv * dim, name: "v_proj", bias: false).split_heads(kv)
193
+ # Normalized per head, which is why it happens after the split
194
+ # and before the rotation.
195
+ q = norm(q, name: "q_norm").rope(theta:)
196
+ k = norm(k, name: "k_norm").rope(theta:)
197
+
198
+ attended =
199
+ if @config.sliding?(index)
200
+ # The window is already a triangle: what a position may see
201
+ # is the recent past, and the past is the causal part of it.
202
+ sdpa(q, k, v, mask: window, scale: @config.scale)
203
+ else
204
+ sdpa(q, k, v, causal: true, scale: @config.scale)
205
+ end
206
+ # `merge_heads` lands on the heads times their width, which for
207
+ # Gemma is not the hidden size: 270m is four heads of 256 over a
208
+ # hidden state of 640. The projection that follows says the rest.
209
+ linear(attended.merge_heads, @config.hidden_size, name: "o_proj", bias: false)
210
+ end
211
+ end
212
+
213
+ # GeGLU with the tanh approximation, which is the function Gemma
214
+ # was trained with.
215
+ def mlp(x)
216
+ scope "mlp" do
217
+ gate = linear(x, @config.intermediate_size, name: "gate_proj", bias: false)
218
+ up = linear(x, @config.intermediate_size, name: "up_proj", bias: false)
219
+ linear(gate.gelu_tanh * up, @config.hidden_size, name: "down_proj", bias: false)
220
+ end
221
+ end
222
+
223
+ # Every norm here scales by `1 + w`, which is Gemma's own
224
+ # convention and the reason its norm weights are stored around zero.
225
+ def norm(x, name:)
226
+ rms_norm(x, name:, eps: @config.rms_norm_eps, offset: 1.0)
227
+ end
228
+ end
229
+
230
+ # A large negative rather than -Infinity, for the reason
231
+ # `Models::ModernBERT` gives: a row that could attend to nothing
232
+ # would softmax to NaN, and a finite floor keeps the arithmetic
233
+ # finite even where the answer is discarded.
234
+ NEGATIVE = -1.0e9
235
+
236
+ # One batch, from token ids.
237
+ #
238
+ # Rows are padded on the right, so a real position never attends to
239
+ # a padded one and no padding mask is needed. What the local layers
240
+ # do need is the window, which depends on the sequence length and
241
+ # nothing else.
242
+ def batch(config, rows, seq:)
243
+ ids = Padding.ids(rows, seq:, pad: config.pad_token_id)
244
+ fields = { input_ids: TensorData.from_a([rows.size, seq], ids, dtype: :i32) }
245
+ return fields unless config.any_sliding?
246
+
247
+ fields.merge(window: window(config, seq:))
248
+ end
249
+
250
+ # What a local layer may see: itself, and at most `sliding_window`
251
+ # positions back. Causal and windowed in one, because a mask is
252
+ # additive and there is no reason to hand over two.
253
+ #
254
+ # Built once per shape and handed out again: it is the same bytes at
255
+ # every step, and at sequence 512 it is a megabyte.
256
+ # What a shape's window is kept in, bounded (`Models::Windows`).
257
+ WINDOWS = Windows.new
258
+
259
+ def window(config, seq:)
260
+ width = config.sliding_window
261
+ WINDOWS.fetch([seq, width]) do
262
+ TensorData.runs(
263
+ [1, 1, seq, seq],
264
+ (0...seq).flat_map do |i|
265
+ first = [i - width + 1, 0].max
266
+ [[first, NEGATIVE], [i - first + 1, 0.0], [seq - 1 - i, NEGATIVE]]
267
+ end
268
+ )
269
+ end
270
+ end
271
+ end
272
+ end
273
+ end
@@ -0,0 +1,381 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Torobi
4
+ module Models
5
+ # The Llama-shaped decoder, as a GraphConfig.
6
+ #
7
+ # Llama itself, and everything built to its shape: Qwen2, sarashina2.2,
8
+ # Mistral without its sliding window. One description rather than one
9
+ # per name, because they are one architecture and the differences
10
+ # between them are things their configs already say (docs/plan.md
11
+ # section 15.53). The tensor names are identical, which is the
12
+ # strongest evidence that this is so.
13
+ #
14
+ # ModernBERT reads a sequence; this continues one, which changes four
15
+ # things and nothing else: attention only looks backwards, the key
16
+ # heads are fewer than the query heads, the MLP is gated with SiLU
17
+ # rather than GELU, and the output projection is sometimes the
18
+ # embedding table read a second time.
19
+ #
20
+ # Written against the published configuration, and named the way the
21
+ # checkpoint names things, so a model imports with no renaming:
22
+ # `pretrained: { m: "Qwen2.5-0.5B/model.safetensors" }`.
23
+ #
24
+ # What it is not: a tokenizer, a training recipe, or a way to generate
25
+ # text. **There is no KV cache and no sampling loop here**, and there
26
+ # is not going to be: a decoder in Torobi is a decoder being
27
+ # fine-tuned, and what serves the result is llama.cpp or vLLM
28
+ # (docs/plan.md section 14). One forward is `Session#forward`.
29
+ module Llama
30
+ # How Llama 3.1 and 3.2 scale their rotary embedding.
31
+ #
32
+ # A rope turns position `p` in dimension pair `i` by `p * inv[i]`,
33
+ # where `inv[i] = 1 / theta^(2i/head_dim)`. This divides the slow
34
+ # turns by `factor`, leaves the fast ones alone, and interpolates
35
+ # across the band between. Which is which is said in wavelengths:
36
+ # `original_context / low_freq_factor` and the same over
37
+ # `high_freq_factor`.
38
+ #
39
+ # **It is not something that happens once a sequence gets long.**
40
+ # The frequencies themselves move, so position 1 of a scaled model
41
+ # is not position 1 of an unscaled one. That is why a file saying
42
+ # this cannot be read as though it did not: what would be built runs
43
+ # and trains and is a different model (docs/plan.md section 15.53).
44
+ RopeScaling = Data.define(:factor, :low_freq_factor, :high_freq_factor,
45
+ :original_context) do
46
+ # What `rope_scaling` holds, when it holds this. The reference
47
+ # names the type twice over its versions (`rope_type`, `type`),
48
+ # and the rest of the keys have no defaults worth guessing.
49
+ def self.read(scaling)
50
+ new(factor: Float(scaling.fetch("factor")),
51
+ low_freq_factor: Float(scaling.fetch("low_freq_factor")),
52
+ high_freq_factor: Float(scaling.fetch("high_freq_factor")),
53
+ original_context: Float(scaling.fetch("original_max_position_embeddings")))
54
+ end
55
+
56
+ # One angular frequency per pair of dimensions, which is what the
57
+ # `rope` op turns by.
58
+ def frequencies(theta:, dim:)
59
+ (0...(dim / 2)).map do |i|
60
+ scale(1.0 / (theta**(2.0 * i / dim)))
61
+ end
62
+ end
63
+
64
+ private
65
+
66
+ # The three bands, by the wavelength a frequency turns at.
67
+ def scale(inv)
68
+ wavelength = 2 * Math::PI / inv
69
+ return inv if wavelength < original_context / high_freq_factor
70
+ return inv / factor if wavelength > original_context / low_freq_factor
71
+
72
+ share = ((original_context / wavelength) - low_freq_factor) /
73
+ (high_freq_factor - low_freq_factor)
74
+ ((1 - share) * (inv / factor)) + (share * inv)
75
+ end
76
+ end
77
+
78
+ # What one of these configs says, with the defaults the reference
79
+ # uses when a file leaves one out.
80
+ Config = Data.define(
81
+ :vocab_size, :hidden_size, :intermediate_size, :num_hidden_layers,
82
+ :num_attention_heads, :num_key_value_heads, :head_dim, :rms_norm_eps,
83
+ :rope_theta, :rope_scaling, :tie_word_embeddings, :attention_bias, :pad_token_id
84
+ ) do
85
+ # How many query heads share one key head. Grouped-query
86
+ # attention: 14 heads over 2 in Qwen2.5-0.5B, so seven of them
87
+ # read the same keys and the checkpoint carries a seventh of the
88
+ # keys it otherwise would.
89
+ def group = num_attention_heads / num_key_value_heads
90
+
91
+ # What the rotary embedding is told: the base, and the
92
+ # frequencies only where the file scales them.
93
+ #
94
+ # **Absent rather than null** when it does not. An attribute that
95
+ # is emitted is part of the graph's digest, and a description
96
+ # nobody changed should go on producing the digest it always did.
97
+ def rope
98
+ return { theta: rope_theta } unless rope_scaling
99
+
100
+ { theta: rope_theta,
101
+ freqs: rope_scaling.frequencies(theta: rope_theta, dim: head_dim) }
102
+ end
103
+
104
+ def check!
105
+ unless head_dim * num_attention_heads == hidden_size
106
+ raise ConfigError,
107
+ "#{num_attention_heads} heads of #{head_dim} is not " \
108
+ "hidden_size #{hidden_size}"
109
+ end
110
+ unless (num_attention_heads % num_key_value_heads).zero?
111
+ raise ConfigError,
112
+ "#{num_attention_heads} query heads do not divide into " \
113
+ "#{num_key_value_heads} key heads"
114
+ end
115
+ self
116
+ end
117
+ end
118
+
119
+ module_function
120
+
121
+ def from_config_file(path)
122
+ require "json"
123
+ from_hash(JSON.parse(File.read(path.to_s)))
124
+ end
125
+
126
+ # Reads one of these configs, whichever of the family it is.
127
+ #
128
+ # Two things differ between them and neither is optional to get
129
+ # right. **Qwen2 puts a bias on q, k and v and says so nowhere**:
130
+ # its config has no `attention_bias` because the implementation
131
+ # hardcodes it, while Llama's says false and means it. And whether
132
+ # the output projection is the embedding table is `tie_word_embeddings`,
133
+ # which decides whether the checkpoint holds an `lm_head.weight` at
134
+ # all. So the family is read off `model_type` and the rest is read
135
+ # off the file.
136
+ def from_hash(raw)
137
+ family = raw.fetch("model_type", "llama")
138
+ refuse_what_is_not_built(raw, family)
139
+ heads = raw.fetch("num_attention_heads")
140
+ Config.new(
141
+ vocab_size: raw.fetch("vocab_size"),
142
+ hidden_size: raw.fetch("hidden_size"),
143
+ intermediate_size: raw.fetch("intermediate_size"),
144
+ num_hidden_layers: raw.fetch("num_hidden_layers"),
145
+ num_attention_heads: heads,
146
+ num_key_value_heads: raw.fetch("num_key_value_heads", heads),
147
+ head_dim: raw["head_dim"] || (raw.fetch("hidden_size") / heads),
148
+ rms_norm_eps: raw.fetch("rms_norm_eps", 1e-6),
149
+ rope_theta: raw.fetch("rope_theta", 10_000.0),
150
+ rope_scaling: rope_scaling(raw, family),
151
+ tie_word_embeddings: raw.fetch("tie_word_embeddings", false),
152
+ attention_bias: raw.fetch("attention_bias", family == "qwen2"),
153
+ # A decoder is trained on what it should say next, and the
154
+ # positions it should say nothing at are dropped by the
155
+ # objective rather than attended around. What pads them only has
156
+ # to be a token id, and the end-of-text one is the one to hand.
157
+ pad_token_id: raw["pad_token_id"] || raw.fetch("eos_token_id", 0)
158
+ ).check!
159
+ end
160
+
161
+ # How this file scales its rotary embedding, if it does.
162
+ #
163
+ # `llama3` is what Llama 3.1, 3.2 and 3.3 say, and it is the one
164
+ # built here (`RopeScaling`). The others are refused rather than
165
+ # approximated by it: `linear` and `dynamic` are different
166
+ # arithmetic, and `yarn` also changes the scale attention is read
167
+ # at, so building any of them as this one would be a model that runs
168
+ # and is not the file's.
169
+ def rope_scaling(raw, family)
170
+ scaling = raw["rope_scaling"]
171
+ return nil unless scaling
172
+
173
+ type = scaling["rope_type"] || scaling["type"]
174
+ return RopeScaling.read(scaling) if type == "llama3"
175
+
176
+ raise ConfigError,
177
+ "#{family}: rope_scaling #{type.inspect} is not implemented here " \
178
+ "(llama3 is), and a rotary embedding scaled by the wrong " \
179
+ "arithmetic is a different model"
180
+ end
181
+
182
+ # What this family does that this description does not.
183
+ #
184
+ # Refused rather than ignored. A window that should have been slid
185
+ # and was not is a model that runs, trains, and is not the model the
186
+ # file names; nothing downstream would notice.
187
+ def refuse_what_is_not_built(raw, family)
188
+ return unless raw["use_sliding_window"] || (family == "mistral" && raw["sliding_window"])
189
+
190
+ raise ConfigError,
191
+ "#{family}: sliding window attention is not implemented here; " \
192
+ "this builds a decoder that attends to everything before it"
193
+ end
194
+
195
+ # The language model: token ids in, one score per token of the
196
+ # vocabulary out, at every position.
197
+ #
198
+ # The loss is not here. What to predict (the next token, or the
199
+ # answer and not the question), which positions count and how they
200
+ # are weighed is the recipe's, and it is a `cross_entropy` and a
201
+ # weighted mean away:
202
+ #
203
+ # objective = Torobi.objective(m: model) do |g|
204
+ # logits = g.from_model(:m, :logits)
205
+ # targets = g.from_batch(:targets, [nil, seq], dtype: :i32)
206
+ # kept = g.from_batch(:kept, [nil, seq])
207
+ # at = g.cross_entropy(logits, targets) * kept
208
+ # g.output :loss, g.sum(at) / g.sum(kept)
209
+ # end
210
+ #
211
+ # `rows:` fixes how many rows a batch has, and is normally left
212
+ # alone; it is for an objective that reads across the batch rather
213
+ # than down it.
214
+ # `adapter:` is a `Torobi::LoRA`, and adapts the linears it names
215
+ # rather than this description having to know about it.
216
+ # `dtype:` is what the model is held in. bf16 halves it, which is
217
+ # what a published checkpoint is stored in anyway; the loss is read
218
+ # as f32, so an objective over a bf16 model says where it comes
219
+ # back (`g.cast(logits, :f32)`).
220
+ # `quantization:` is a `Torobi::Quantization`, and holds the linears
221
+ # it names packed at a few bits a weight (docs/qlora.md). The
222
+ # embedding stays in `dtype:`, tied head included.
223
+ def causal_lm(config, seq:, rows: nil, adapter: nil, dtype: :f32, quantization: nil)
224
+ config.check!
225
+ build = Build.new(seq:, rows:, dtype:)
226
+ Torobi.graph { |g| Describe.new(g, config, build).causal_lm(adapter, quantization) }
227
+ end
228
+
229
+ # The description itself: the builder, the config and what it is
230
+ # built for are held once (`Models::Description`), so what a method
231
+ # takes is the value flowing through it.
232
+ class Describe < Description
233
+ def causal_lm(adapter, quantization = nil)
234
+ @tokens = adapter if adapter&.tokens?
235
+ quantized quantization do
236
+ hidden = adapting adapter do
237
+ encoded = scope "model" do
238
+ encode
239
+ end
240
+ encoded.named("hidden")
241
+ end
242
+ # Not named: an untied head is a `linear`, which names its own
243
+ # node after its parameters, and `forward` reaches an output by
244
+ # the name the output has.
245
+ output :logits, head(hidden)
246
+ end
247
+ end
248
+
249
+ # The output projection, which is usually not a parameter of its
250
+ # own.
251
+ #
252
+ # **Tied weights are one parameter read twice**, not two that are
253
+ # kept equal: the table that turns an id into a vector turns a
254
+ # vector back into scores over ids, transposed. Qwen2.5-0.5B holds
255
+ # no `lm_head.weight` at all for that reason, and a graph that
256
+ # declared one would be asking a checkpoint for something it does
257
+ # not have.
258
+ def head(hidden)
259
+ scores =
260
+ if @config.tie_word_embeddings
261
+ table = parameter("model.embed_tokens.weight")
262
+ matmul(hidden, table.transpose(axes: [1, 0]))
263
+ else
264
+ linear(hidden, @config.vocab_size, name: "lm_head", bias: false)
265
+ end
266
+ @tokens ? scores + trained_scores(hidden) : scores
267
+ end
268
+
269
+ # What the trained rows change in the scores: the rows of the table, read as the output
270
+ # layer, when the two are one table (the one parameter, read twice), and the output
271
+ # layer's own rows when they are not.
272
+ def trained_scores(hidden)
273
+ delta =
274
+ if @config.tie_word_embeddings
275
+ parameter("model.embed_tokens.#{LoRA.rows_name}")
276
+ else
277
+ @g.param("lm_head.#{LoRA.rows_name}", [@tokens.tokens.size, @config.hidden_size],
278
+ dtype: :f32, init: { "type" => "zeros" })
279
+ end
280
+ columns = input(@build.field(:token_columns), [@config.vocab_size], dtype: :f32)
281
+ @tokens.token_scores(@g, hidden, columns, delta)
282
+ end
283
+
284
+ # The decoder body: ids in, hidden states out, under `model.` as
285
+ # the checkpoint has it.
286
+ def encode
287
+ ids = input(@build.field(:input_ids), [@build.rows, @build.seq], dtype: :i32)
288
+ x = embedding(ids, vocab: @config.vocab_size, dim: @config.hidden_size,
289
+ name: "embed_tokens", dtype: @build.dtype)
290
+ if @tokens
291
+ x += @tokens.token_embeddings(@g, ids, dim: @config.hidden_size, name: "embed_tokens",
292
+ dtype: @build.dtype)
293
+ end
294
+ @config.num_hidden_layers.times do |i|
295
+ x = scope "layers.#{i}" do
296
+ layer(x)
297
+ end
298
+ end
299
+ norm(x, name: "norm")
300
+ end
301
+
302
+ # One block: attention with a residual, then the MLP with another,
303
+ # each normalized before rather than after (pre-norm).
304
+ def layer(x)
305
+ x += attention(norm(x, name: "input_layernorm"))
306
+ x + mlp(norm(x, name: "post_attention_layernorm"))
307
+ end
308
+
309
+ # Attention that only looks backwards, over fewer keys than queries.
310
+ #
311
+ # `causal: true` rather than a mask in the batch: the triangle
312
+ # depends on nothing but the sequence length, and handing over
313
+ # [1, 1, seq, seq] of the same number every step is megabytes to say
314
+ # what the attention already knows.
315
+ #
316
+ # There is no padding mask either, and that is a claim rather than
317
+ # an omission: rows are padded on the right, so a real position is
318
+ # never after a padded one and never attends to it. What the padded
319
+ # positions themselves produce is discarded by the objective.
320
+ #
321
+ # Whether q, k and v carry biases is the family's own asymmetry:
322
+ # Qwen2 has them and Llama does not. The output projection has none
323
+ # either way.
324
+ def attention(x)
325
+ heads = @config.num_attention_heads
326
+ kv = @config.num_key_value_heads
327
+ dim = @config.head_dim
328
+ rope = @config.rope
329
+ bias = @config.attention_bias
330
+ scope "self_attn" do
331
+ q = linear(x, heads * dim, name: "q_proj", bias:)
332
+ k = linear(x, kv * dim, name: "k_proj", bias:)
333
+ v = linear(x, kv * dim, name: "v_proj", bias:)
334
+ # The key heads are fewer and stay that way: the backend takes
335
+ # them untiled, which is the whole saving.
336
+ attended = sdpa(q.split_heads(heads).rope(**rope),
337
+ k.split_heads(kv).rope(**rope),
338
+ v.split_heads(kv),
339
+ causal: true)
340
+ linear(attended.merge_heads, @config.hidden_size, name: "o_proj", bias: false)
341
+ end
342
+ end
343
+
344
+ # SwiGLU: one projection gated by another, through SiLU, then back
345
+ # down. SiLU is `x * sigmoid(x)`, which is two ops here rather than
346
+ # one; it is what the name means, and nothing is fused away.
347
+ def mlp(x)
348
+ scope "mlp" do
349
+ gate = linear(x, @config.intermediate_size, name: "gate_proj", bias: false)
350
+ up = linear(x, @config.intermediate_size, name: "up_proj", bias: false)
351
+ linear((gate * gate.sigmoid) * up, @config.hidden_size,
352
+ name: "down_proj", bias: false)
353
+ end
354
+ end
355
+
356
+ # Every norm here is an RMS norm with a gain and no bias.
357
+ def norm(x, name:)
358
+ rms_norm(x, name:, eps: @config.rms_norm_eps)
359
+ end
360
+ end
361
+
362
+ # One batch, from token ids.
363
+ #
364
+ # Ids and nothing else: a causal attention needs no mask, and what
365
+ # a position should have said next is the recipe's to decide (see
366
+ # `causal_lm`). Rows are padded on the right, which is what makes
367
+ # the missing padding mask sound.
368
+ # `adapter:` is the one the graph was built with: one that trains tokens' rows also reads
369
+ # their columns, which are the same for every batch, here in the one place.
370
+ def batch(config, rows, seq:, adapter: nil)
371
+ ids = Padding.ids(rows, seq:, pad: config.pad_token_id)
372
+ fields = { input_ids: TensorData.from_a([rows.size, seq], ids, dtype: :i32) }
373
+ if adapter&.tokens?
374
+ fields[:token_columns] =
375
+ TensorData.from_a([config.vocab_size], (0...config.vocab_size).map(&:to_f))
376
+ end
377
+ fields
378
+ end
379
+ end
380
+ end
381
+ end