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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +71 -0
- data/Cargo.lock +539 -0
- data/Cargo.toml +6 -0
- data/LICENSE +21 -0
- data/README.md +259 -0
- data/config/ops.yml +230 -0
- data/docs/plan.md +3982 -0
- data/docs/vendoring.md +656 -0
- data/engine/Cargo.toml +35 -0
- data/engine/build.rs +253 -0
- data/engine/src/checkpoint.rs +513 -0
- data/engine/src/executor.rs +257 -0
- data/engine/src/export.rs +431 -0
- data/engine/src/fixtures.rs +518 -0
- data/engine/src/graph.rs +115 -0
- data/engine/src/init.rs +65 -0
- data/engine/src/interp.rs +985 -0
- data/engine/src/lib.rs +62 -0
- data/engine/src/main.rs +97 -0
- data/engine/src/memory.rs +109 -0
- data/engine/src/mlxc/array.rs +454 -0
- data/engine/src/mlxc/error.rs +205 -0
- data/engine/src/mlxc/fast.rs +46 -0
- data/engine/src/mlxc/handle.rs +155 -0
- data/engine/src/mlxc/io.rs +268 -0
- data/engine/src/mlxc/memory.rs +56 -0
- data/engine/src/mlxc/metal.rs +24 -0
- data/engine/src/mlxc/mod.rs +55 -0
- data/engine/src/mlxc/nn.rs +38 -0
- data/engine/src/mlxc/ops.rs +477 -0
- data/engine/src/mlxc/quantized.rs +405 -0
- data/engine/src/mlxc/random.rs +161 -0
- data/engine/src/mlxc/transforms.rs +439 -0
- data/engine/src/op.rs +745 -0
- data/engine/src/optimizer.rs +650 -0
- data/engine/src/plan.rs +1638 -0
- data/engine/src/runtime.rs +377 -0
- data/engine/src/session.rs +1523 -0
- data/engine/src/state.rs +1007 -0
- data/engine/src/tensor.rs +331 -0
- data/ext/torobi/Cargo.toml +21 -0
- data/ext/torobi/extconf.rb +42 -0
- data/ext/torobi/src/gvl.rs +182 -0
- data/ext/torobi/src/lib.rs +1037 -0
- data/lib/torobi/adapter_file.rb +184 -0
- data/lib/torobi/batch.rb +55 -0
- data/lib/torobi/checkpoint.rb +60 -0
- data/lib/torobi/dsl/builder.rb +414 -0
- data/lib/torobi/dsl/handle.rb +156 -0
- data/lib/torobi/dsl/layers.rb +82 -0
- data/lib/torobi/dsl.rb +35 -0
- data/lib/torobi/errors.rb +88 -0
- data/lib/torobi/export.rb +534 -0
- data/lib/torobi/freeze.rb +24 -0
- data/lib/torobi/freshness.rb +57 -0
- data/lib/torobi/grad_cache.rb +143 -0
- data/lib/torobi/graph_config.rb +301 -0
- data/lib/torobi/hooks.rb +439 -0
- data/lib/torobi/ir/dimensions.rb +26 -0
- data/lib/torobi/ir/dtype.rb +28 -0
- data/lib/torobi/ir/graph/check.rb +116 -0
- data/lib/torobi/ir/graph.rb +52 -0
- data/lib/torobi/ir/input_spec.rb +39 -0
- data/lib/torobi/ir/json.rb +45 -0
- data/lib/torobi/ir/node_spec.rb +52 -0
- data/lib/torobi/ir/parameter_spec.rb +67 -0
- data/lib/torobi/ir/ref.rb +52 -0
- data/lib/torobi/ir/source.rb +65 -0
- data/lib/torobi/ir.rb +23 -0
- data/lib/torobi/journal.rb +310 -0
- data/lib/torobi/lora.rb +190 -0
- data/lib/torobi/memory.rb +50 -0
- data/lib/torobi/metallib.rb +50 -0
- data/lib/torobi/mlx_prebuilt.json +24 -0
- data/lib/torobi/mlx_prebuilt.rb +378 -0
- data/lib/torobi/models/build.rb +37 -0
- data/lib/torobi/models/description.rb +59 -0
- data/lib/torobi/models/gemma3.rb +273 -0
- data/lib/torobi/models/llama.rb +381 -0
- data/lib/torobi/models/modern_bert.rb +513 -0
- data/lib/torobi/models/padding.rb +27 -0
- data/lib/torobi/models/windows.rb +53 -0
- data/lib/torobi/ops.rb +81 -0
- data/lib/torobi/preflight.rb +136 -0
- data/lib/torobi/provenance.rb +75 -0
- data/lib/torobi/quantization.rb +151 -0
- data/lib/torobi/replay.rb +229 -0
- data/lib/torobi/runner.rb +419 -0
- data/lib/torobi/session.rb +855 -0
- data/lib/torobi/shape.rb +438 -0
- data/lib/torobi/tensor_data.rb +178 -0
- data/lib/torobi/version.rb +5 -0
- data/lib/torobi/weights.rb +108 -0
- data/lib/torobi.rb +67 -0
- data/licenses/MLX.txt +21 -0
- data/licenses/README.md +16 -0
- data/licenses/gguflib.txt +21 -0
- data/licenses/mlx-c.txt +21 -0
- data/licenses/mlx-rs.txt +27 -0
- metadata +229 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
module Models
|
|
5
|
+
# ModernBERT, as a GraphConfig.
|
|
6
|
+
#
|
|
7
|
+
# The first architecture Torobi describes, and the one its first target
|
|
8
|
+
# is made of: ruri-v3 is a ModernBERT encoder, and the reranker being
|
|
9
|
+
# distilled is another (docs/plan.md section 3).
|
|
10
|
+
#
|
|
11
|
+
# Written against the published configuration rather than a fixed set
|
|
12
|
+
# of numbers, so `from_config_file` reads a checkpoint's `config.json`
|
|
13
|
+
# and this builds what that says. What the file calls a thing, this
|
|
14
|
+
# calls it too: the parameter paths are the checkpoint's own names, so
|
|
15
|
+
# a model imports with `weights_file:` and no renaming
|
|
16
|
+
# (`Session.open(config, weights_file: "model.safetensors")`).
|
|
17
|
+
#
|
|
18
|
+
# What it is not: a training recipe, a tokenizer, or a pooler. Those
|
|
19
|
+
# are the caller's, and keeping them out is what makes this a
|
|
20
|
+
# description rather than a framework inside a framework.
|
|
21
|
+
module ModernBERT
|
|
22
|
+
# What a ModernBERT config says, with the defaults the reference
|
|
23
|
+
# implementation uses when a file leaves one out.
|
|
24
|
+
Config = Data.define(
|
|
25
|
+
:vocab_size, :hidden_size, :intermediate_size, :num_hidden_layers,
|
|
26
|
+
:num_attention_heads, :norm_eps, :global_attn_every_n_layers,
|
|
27
|
+
:global_rope_theta, :local_rope_theta, :local_attention, :pad_token_id,
|
|
28
|
+
:num_labels, :classifier_pooling, :classifier_bias
|
|
29
|
+
) do
|
|
30
|
+
def head_dim = hidden_size / num_attention_heads
|
|
31
|
+
|
|
32
|
+
# Layer 0 attends globally, and every nth after it; the rest are
|
|
33
|
+
# local. The reference counts from zero, so layer 0 is global.
|
|
34
|
+
def global?(layer) = (layer % global_attn_every_n_layers).zero?
|
|
35
|
+
|
|
36
|
+
def theta(layer) = global?(layer) ? global_rope_theta : local_rope_theta
|
|
37
|
+
|
|
38
|
+
# Whether any layer is local. A configuration small enough to have
|
|
39
|
+
# none needs no window, and asking for one it never reads would be
|
|
40
|
+
# a batch field with nothing to do.
|
|
41
|
+
def any_local? = num_hidden_layers.times.any? { |i| !global?(i) }
|
|
42
|
+
|
|
43
|
+
def check!
|
|
44
|
+
unless (hidden_size % num_attention_heads).zero?
|
|
45
|
+
raise ConfigError,
|
|
46
|
+
"hidden_size #{hidden_size} does not divide into " \
|
|
47
|
+
"#{num_attention_heads} heads"
|
|
48
|
+
end
|
|
49
|
+
self
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
module_function
|
|
54
|
+
|
|
55
|
+
# Reads a checkpoint's `config.json`.
|
|
56
|
+
def from_config_file(path)
|
|
57
|
+
require "json"
|
|
58
|
+
from_hash(JSON.parse(File.read(path.to_s)))
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def from_hash(raw)
|
|
62
|
+
Config.new(
|
|
63
|
+
vocab_size: raw.fetch("vocab_size"),
|
|
64
|
+
hidden_size: raw.fetch("hidden_size"),
|
|
65
|
+
intermediate_size: raw.fetch("intermediate_size"),
|
|
66
|
+
num_hidden_layers: raw.fetch("num_hidden_layers"),
|
|
67
|
+
num_attention_heads: raw.fetch("num_attention_heads"),
|
|
68
|
+
norm_eps: raw.fetch("norm_eps", 1e-5),
|
|
69
|
+
global_attn_every_n_layers: raw.fetch("global_attn_every_n_layers", 3),
|
|
70
|
+
global_rope_theta: raw.fetch("global_rope_theta", 160_000.0),
|
|
71
|
+
local_rope_theta: raw.fetch("local_rope_theta", 10_000.0),
|
|
72
|
+
local_attention: raw.fetch("local_attention", 128),
|
|
73
|
+
pad_token_id: raw.fetch("pad_token_id", 0),
|
|
74
|
+
num_labels: raw.fetch("num_labels", 1),
|
|
75
|
+
classifier_pooling: raw.fetch("classifier_pooling", "cls").to_sym,
|
|
76
|
+
classifier_bias: raw.fetch("classifier_bias", false)
|
|
77
|
+
).check!
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# A sequence classifier: token ids in, one logit per label out.
|
|
81
|
+
#
|
|
82
|
+
# What the published rerankers are (`ModernBertForSequenceClassification`),
|
|
83
|
+
# and what this project is distilling: a cross-encoder scores a
|
|
84
|
+
# (query, text) pair with one number. The encoder sits under
|
|
85
|
+
# `model.`, as the checkpoint has it, with a pooled head above.
|
|
86
|
+
#
|
|
87
|
+
# The score a caller compares against is the sigmoid of this logit,
|
|
88
|
+
# which is what a CrossEncoder reports for a one-label model. Whether
|
|
89
|
+
# to distil against the logit or its sigmoid is the recipe's, so this
|
|
90
|
+
# emits the logit and stops.
|
|
91
|
+
# `encoder_prefix:` is where the encoder's parameters sit. Published
|
|
92
|
+
# classifiers keep it under `model.`; a classifier built on a bare
|
|
93
|
+
# encoder checkpoint (ruri-v3-130m holds `embeddings.*` at the root)
|
|
94
|
+
# wants none, and its head is `fresh:` because no file has one.
|
|
95
|
+
# `adapter:` is a `Torobi::LoRA`, and adapts the linears it names
|
|
96
|
+
# rather than this description having to know about it. The head is
|
|
97
|
+
# inside it, so a classifier adapted this way trains its adapter
|
|
98
|
+
# and nothing else; a head that has to be trained too is a
|
|
99
|
+
# `fresh:` head on an unadapted model.
|
|
100
|
+
def classifier(config, seq:, encoder_prefix: "model", rows: nil, adapter: nil,
|
|
101
|
+
dtype: :f32)
|
|
102
|
+
config.check!
|
|
103
|
+
build = Build.new(seq:, rows:, dtype:)
|
|
104
|
+
Torobi.graph do |g|
|
|
105
|
+
Describe.new(g, config, build, encoder_prefix:).classify(adapter)
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# A sentence embedder: token ids in, one vector per row out.
|
|
110
|
+
#
|
|
111
|
+
# What a sentence-transformers checkpoint is, as a graph: the
|
|
112
|
+
# encoder, a pooling, and the normalization that turns a dot product
|
|
113
|
+
# into a cosine. ruri-v3 is this, and `Torobi::Export` writes the
|
|
114
|
+
# `modules.json` and `1_Pooling/config.json` that say so.
|
|
115
|
+
#
|
|
116
|
+
# The vector is named, so a tap reads it without a second graph:
|
|
117
|
+
# "embedding" is what a gradient cache back-propagates through
|
|
118
|
+
# (`Torobi::GradCache`), and "hidden" is what it was pooled from.
|
|
119
|
+
#
|
|
120
|
+
# No loss. A contrastive objective reads across the batch, which
|
|
121
|
+
# makes it the recipe's rather than the model's; this stops at the
|
|
122
|
+
# vector. `rows:` is for the objective that does read across, which
|
|
123
|
+
# cannot be written against a dimension nothing knows.
|
|
124
|
+
# `adapter:` is a `Torobi::LoRA`, and adapts the linears it names
|
|
125
|
+
# rather than this description having to know about it. An adapted
|
|
126
|
+
# embedder starts as the embedder it adapts (LoRA's `B` is zero),
|
|
127
|
+
# so it is what a fine-tune that means to keep the model it started
|
|
128
|
+
# from asks for.
|
|
129
|
+
def embedder(config, seq:, pooling: :mean, encoder_prefix: "", rows: nil,
|
|
130
|
+
normalize: true, dtype: :f32, adapter: nil)
|
|
131
|
+
config.check!
|
|
132
|
+
build = Build.new(seq:, rows:, dtype:)
|
|
133
|
+
Torobi.graph do |g|
|
|
134
|
+
Describe.new(g, config, build, encoder_prefix:)
|
|
135
|
+
.embed(adapter, pooling:, normalize:)
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# The same embedder, applied to several named sets of rows.
|
|
140
|
+
#
|
|
141
|
+
# One model and one set of weights, in a graph that embeds each side
|
|
142
|
+
# at the length that side actually is. A contrastive run wants that:
|
|
143
|
+
# its queries are eighteen tokens and its documents are 192, and
|
|
144
|
+
# padding the queries out to the documents' length is nine tenths of
|
|
145
|
+
# that work spent on padding (docs/plan.md 15.62).
|
|
146
|
+
#
|
|
147
|
+
# Two things make it possible, and both are new: `g.sharing` makes
|
|
148
|
+
# the second application read the first's parameters rather than
|
|
149
|
+
# declare its own, and the graph is built for no particular
|
|
150
|
+
# sequence at all (`seq: nil`), so each side's batch says how long
|
|
151
|
+
# it is (docs/plan.md 15.63).
|
|
152
|
+
#
|
|
153
|
+
# graph = ModernBERT.towers(config, queries: 8, documents: 24)
|
|
154
|
+
# batch = ModernBERT.batch(config, qs, seq: 48, pooling: :mean,
|
|
155
|
+
# fields: "queries.")
|
|
156
|
+
# .merge(ModernBERT.batch(config, ds, seq: 192, pooling: :mean,
|
|
157
|
+
# fields: "documents."))
|
|
158
|
+
#
|
|
159
|
+
# It answers one embedding per side, "queries.embedding" and
|
|
160
|
+
# "documents.embedding", which is what the objective reads.
|
|
161
|
+
#
|
|
162
|
+
# `sides` is name => how many rows that side has, nil where the
|
|
163
|
+
# count does not matter. It is named because an objective that reads
|
|
164
|
+
# across the batch cannot be written against a dimension nothing
|
|
165
|
+
# knows.
|
|
166
|
+
def towers(config, sides, pooling: :mean, encoder_prefix: "", normalize: true,
|
|
167
|
+
dtype: :f32, adapter: nil)
|
|
168
|
+
config.check!
|
|
169
|
+
raise ConfigError, "towers needs at least one side" if sides.empty?
|
|
170
|
+
|
|
171
|
+
Torobi.graph do |g|
|
|
172
|
+
# One description per side, because each reads its own fields at
|
|
173
|
+
# its own length; one builder, because they are one graph.
|
|
174
|
+
g.adapting adapter do
|
|
175
|
+
sides.each do |side, rows|
|
|
176
|
+
build = Build.new(seq: nil, rows:, dtype:, fields: "#{side}.")
|
|
177
|
+
Describe.new(g, config, build, encoder_prefix:)
|
|
178
|
+
.tower(side, pooling:, normalize:)
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# The encoder as a graph: token ids in, hidden states out.
|
|
185
|
+
#
|
|
186
|
+
# `build.seq` is the sequence length this graph is declared for,
|
|
187
|
+
# and may be nil: since the head split keeps the dimensions it does
|
|
188
|
+
# not know (docs/plan.md 15.63), nothing here needs a concrete one,
|
|
189
|
+
# and each batch says how long it is.
|
|
190
|
+
#
|
|
191
|
+
# Two additive fields arrive from the batch, zero where a position
|
|
192
|
+
# may be attended to and a large negative where it may not:
|
|
193
|
+
#
|
|
194
|
+
# mask [batch, 1, 1, seq] which positions are padding
|
|
195
|
+
# window [1, 1, seq, seq] how far back a local layer sees
|
|
196
|
+
#
|
|
197
|
+
# Global layers read the padding alone and local ones read the sum,
|
|
198
|
+
# which the graph adds once rather than each layer (`Describe#encode`).
|
|
199
|
+
# They are separate inputs because they vary over different things:
|
|
200
|
+
# the padding is this batch's and the window is the configuration's
|
|
201
|
+
# (`Config#local_attention`), so there is one window however many
|
|
202
|
+
# rows there are. A configuration with no local layer asks for no
|
|
203
|
+
# window at all. `ModernBERT.masks` builds what a batch must carry.
|
|
204
|
+
def graph(config, seq:, rows: nil, dtype: :f32)
|
|
205
|
+
config.check!
|
|
206
|
+
build = Build.new(seq:, rows:, dtype:)
|
|
207
|
+
Torobi.graph do |g|
|
|
208
|
+
# Named as well as declared an output, so a tap can read it: an
|
|
209
|
+
# output is what the objective consumes, and a tap is how a
|
|
210
|
+
# caller sees a value without a second graph to see it with.
|
|
211
|
+
Describe.new(g, config, build, encoder_prefix: "").hidden
|
|
212
|
+
end
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# The description itself: the builder, the config and what it is
|
|
216
|
+
# built for are held once (`Models::Description`), so what a method
|
|
217
|
+
# takes is the value flowing through it.
|
|
218
|
+
#
|
|
219
|
+
# `encoder_prefix` is where the encoder's parameters sit, which is
|
|
220
|
+
# the only thing that differs between the graphs above.
|
|
221
|
+
class Describe < Description
|
|
222
|
+
def initialize(g, config, build, encoder_prefix:)
|
|
223
|
+
super(g, config, build)
|
|
224
|
+
@encoder_prefix = encoder_prefix
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# One vector per row, named so a tap reads it without a second
|
|
228
|
+
# graph, and declared as this side's output.
|
|
229
|
+
def embed(adapter, pooling:, normalize:)
|
|
230
|
+
adapting adapter do
|
|
231
|
+
emit_embedding(:embedding, pooling:, normalize:)
|
|
232
|
+
end
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
# The same, as one of several sides sharing one set of weights.
|
|
236
|
+
def tower(side, pooling:, normalize:)
|
|
237
|
+
sharing side do
|
|
238
|
+
emit_embedding(:"#{side}.embedding", pooling:, normalize:)
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# The bare encoder, with its hidden state named and declared.
|
|
243
|
+
def hidden
|
|
244
|
+
output :hidden, encode.named("hidden")
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
# The classifier's body, so that `adapting` has something to wrap.
|
|
248
|
+
def classify(adapter)
|
|
249
|
+
adapting adapter do
|
|
250
|
+
x = body
|
|
251
|
+
pooled = pool(x)
|
|
252
|
+
# ModernBERT's head: a dense, gelu, a norm, then the classifier.
|
|
253
|
+
pooled = scope "head" do
|
|
254
|
+
norm(linear(pooled, @config.hidden_size, name: "dense", bias: false).gelu,
|
|
255
|
+
name: "norm")
|
|
256
|
+
end
|
|
257
|
+
# `linear` names the node after the parameter scope, so this is
|
|
258
|
+
# already called "classifier"; the output name is separate.
|
|
259
|
+
output :logits, linear(pooled, @config.num_labels, name: "classifier",
|
|
260
|
+
bias: @config.classifier_bias)
|
|
261
|
+
end
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
# The encoder under wherever its parameters sit. Published
|
|
265
|
+
# classifiers keep them under `model.` and bare encoders at the root,
|
|
266
|
+
# and that is the only difference between the two graphs above.
|
|
267
|
+
def body
|
|
268
|
+
return encode if @encoder_prefix.to_s.empty?
|
|
269
|
+
|
|
270
|
+
scope @encoder_prefix do
|
|
271
|
+
encode
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
# A vector of length one, so a dot product is a cosine.
|
|
276
|
+
def normalized(x)
|
|
277
|
+
x / sum(x.square, axes: [-1], keepdims: true).sqrt
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# One vector per row, the way `mode` asks for.
|
|
281
|
+
#
|
|
282
|
+
# `cls` is the first position, which for these tokenizers is the
|
|
283
|
+
# sentence-start token: [batch, seq, hidden] keeping only seq 0.
|
|
284
|
+
#
|
|
285
|
+
# `mean` is over the tokens a row actually has. Padding is weighed
|
|
286
|
+
# out of both the sum and the count, so a row's vector does not
|
|
287
|
+
# depend on how much padding followed it, and two batches that
|
|
288
|
+
# differ only in their longest row give the same answer for every
|
|
289
|
+
# other row. The weights arrive as `:tokens` rather than being
|
|
290
|
+
# derived from the attention mask: what a mask holds is whatever the
|
|
291
|
+
# caller built it from, and a weight that must be exactly one or
|
|
292
|
+
# exactly zero should not be read out of a large negative number.
|
|
293
|
+
def pool(x, mode: @config.classifier_pooling)
|
|
294
|
+
case mode
|
|
295
|
+
when :cls
|
|
296
|
+
x.slice(axis: 1, start: 0, length: 1).reshape(shape: [-1, @config.hidden_size])
|
|
297
|
+
when :mean
|
|
298
|
+
# Cast to what it is weighing: a batch carries f32, and the
|
|
299
|
+
# model may be held in something narrower.
|
|
300
|
+
weights = cast(input(@build.field(:tokens), [@build.rows, @build.seq, 1]), x.dtype)
|
|
301
|
+
sum(x * weights, axes: [1]) / sum(weights, axes: [1])
|
|
302
|
+
else
|
|
303
|
+
raise ConfigError, "unknown pooling #{mode.inspect}"
|
|
304
|
+
end
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
# The encoder body, so the bare model and the classifier are one
|
|
308
|
+
# description rather than two that must be kept in step.
|
|
309
|
+
#
|
|
310
|
+
# What it is being built for arrives as one value (`Models::Build`):
|
|
311
|
+
# the sequence, the rows, the precision, and which batch fields to
|
|
312
|
+
# read. `@build.rows` is normally nil, because the batch is the
|
|
313
|
+
# dimension that varies between steps and everything here works
|
|
314
|
+
# without knowing it; naming it is for an objective that reads
|
|
315
|
+
# across the batch rather than down it, which a contrastive loss
|
|
316
|
+
# does (its negatives are the other rows), and which cannot be
|
|
317
|
+
# written against a dimension nothing knows.
|
|
318
|
+
def encode
|
|
319
|
+
ids = input(@build.field(:input_ids), [@build.rows, @build.seq], dtype: :i32)
|
|
320
|
+
# The masks arrive as f32, which is what a batch carries, and are
|
|
321
|
+
# cast to what the model is held in. Nothing is cast when there is
|
|
322
|
+
# nothing to cast to (`cast`).
|
|
323
|
+
padding = cast(input(@build.field(:mask), [@build.rows, 1, 1, @build.seq]),
|
|
324
|
+
@build.dtype)
|
|
325
|
+
# Summed once, not in each of the local layers: both are the same
|
|
326
|
+
# for every one of them. Only when there is a local layer to read
|
|
327
|
+
# it, so a configuration with none asks for no window.
|
|
328
|
+
local = if @config.any_local?
|
|
329
|
+
padding + cast(input(@build.field(:window),
|
|
330
|
+
[1, 1, @build.seq, @build.seq]), @build.dtype)
|
|
331
|
+
else
|
|
332
|
+
padding
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
x = scope "embeddings" do
|
|
336
|
+
table = embedding(ids, vocab: @config.vocab_size, dim: @config.hidden_size,
|
|
337
|
+
name: "tok_embeddings", dtype: @build.dtype)
|
|
338
|
+
norm(table, name: "norm")
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
@config.num_hidden_layers.times do |i|
|
|
342
|
+
mask = @config.global?(i) ? padding : local
|
|
343
|
+
x = scope "layers.#{i}" do
|
|
344
|
+
layer(x, i, mask)
|
|
345
|
+
end
|
|
346
|
+
end
|
|
347
|
+
norm(x, name: "final_norm")
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
# One encoder block: attention with a residual, then the MLP with
|
|
351
|
+
# another. Layer 0 has no attention norm, which is the reference's
|
|
352
|
+
# own asymmetry and not a mistake here.
|
|
353
|
+
def layer(x, index, mask)
|
|
354
|
+
normed = index.zero? ? x : norm(x, name: "attn_norm")
|
|
355
|
+
x += attention(normed, index, mask)
|
|
356
|
+
x + mlp(norm(x, name: "mlp_norm"))
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
def attention(x, index, mask)
|
|
360
|
+
heads = @config.num_attention_heads
|
|
361
|
+
theta = @config.theta(index)
|
|
362
|
+
# One projection to three times the width, cut into q, k and v:
|
|
363
|
+
# ModernBERT fuses them where the decoders keep three.
|
|
364
|
+
scope "attn" do
|
|
365
|
+
q, k, v = linear(x, @config.hidden_size * 3, name: "Wqkv",
|
|
366
|
+
bias: false).split(3, axis: -1)
|
|
367
|
+
attended = sdpa(q.split_heads(heads).rope(theta:),
|
|
368
|
+
k.split_heads(heads).rope(theta:),
|
|
369
|
+
v.split_heads(heads),
|
|
370
|
+
mask:)
|
|
371
|
+
linear(attended.merge_heads, @config.hidden_size, name: "Wo", bias: false)
|
|
372
|
+
end
|
|
373
|
+
end
|
|
374
|
+
|
|
375
|
+
# GeGLU: one projection to twice the width, gelu on the first half,
|
|
376
|
+
# gated by the second, then back down.
|
|
377
|
+
def mlp(x)
|
|
378
|
+
scope "mlp" do
|
|
379
|
+
wide = linear(x, @config.intermediate_size * 2, name: "Wi", bias: false)
|
|
380
|
+
gate, up = wide.split(2, axis: -1)
|
|
381
|
+
linear(gate.gelu * up, @config.hidden_size, name: "Wo", bias: false)
|
|
382
|
+
end
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
# Every norm here is a LayerNorm with a gain and no bias, which is
|
|
386
|
+
# what `norm_bias: false` in the published configs means.
|
|
387
|
+
def norm(x, name:)
|
|
388
|
+
layer_norm(x, name:, bias: false, eps: @config.norm_eps)
|
|
389
|
+
end
|
|
390
|
+
|
|
391
|
+
private
|
|
392
|
+
|
|
393
|
+
def emit_embedding(as, pooling:, normalize:)
|
|
394
|
+
x = body.named("hidden")
|
|
395
|
+
pooled = pool(x, mode: pooling)
|
|
396
|
+
pooled = normalized(pooled) if normalize
|
|
397
|
+
output as, pooled.named("embedding")
|
|
398
|
+
end
|
|
399
|
+
end
|
|
400
|
+
|
|
401
|
+
# One batch, from token ids.
|
|
402
|
+
#
|
|
403
|
+
# Where the line falls: **what the model's config determines is
|
|
404
|
+
# Torobi's, and what is upstream of that is not.** The pad token, the
|
|
405
|
+
# sliding window and the vocabulary all come out of the same
|
|
406
|
+
# `config.json` this already reads, so leaving the caller to look
|
|
407
|
+
# them up would be withholding what is in hand. Tokenizing is
|
|
408
|
+
# upstream: it is decided by `tokenizer.json`, a different artifact
|
|
409
|
+
# with a different lifecycle, and owning it would mean a second
|
|
410
|
+
# native dependency for something the caller can do (docs/plan.md
|
|
411
|
+
# section 15.19).
|
|
412
|
+
#
|
|
413
|
+
# ids = tokenizer.encode_batch(texts).map(&:ids) # yours
|
|
414
|
+
# batch = ModernBERT.batch(config, ids, seq: 128) # this
|
|
415
|
+
# session.step!(batch)
|
|
416
|
+
#
|
|
417
|
+
# Rows are padded to `seq`, and a row longer than that is refused
|
|
418
|
+
# rather than truncated, because which end to drop is a decision
|
|
419
|
+
# about the data and not about the model.
|
|
420
|
+
#
|
|
421
|
+
# `seq` is the graph's own length where it was built for one. A
|
|
422
|
+
# graph built for no particular sequence (`towers`, `seq: nil`) is
|
|
423
|
+
# told by each batch how long that batch is, which is the point of
|
|
424
|
+
# it: a side whose rows are eighteen tokens is not padded out to the
|
|
425
|
+
# length of a side whose rows are 192 (docs/plan.md 15.62).
|
|
426
|
+
# `pooling:` is what the graph this feeds pools like, and adds the
|
|
427
|
+
# per-token weights a mean over real tokens needs (`tokens`). It is
|
|
428
|
+
# the same word `embedder` and `pool` take.
|
|
429
|
+
def batch(config, rows, seq:, pooling: nil, fields: "")
|
|
430
|
+
lengths = rows.map(&:size)
|
|
431
|
+
ids = Padding.ids(rows, seq:, pad: config.pad_token_id)
|
|
432
|
+
carried = { input_ids: TensorData.from_a([rows.size, seq], ids, dtype: :i32) }
|
|
433
|
+
.merge(masks(config, seq:, lengths:))
|
|
434
|
+
carried = carried.merge(tokens: tokens(seq:, lengths:)) if pooling.to_s == "mean"
|
|
435
|
+
return carried if fields.to_s.empty?
|
|
436
|
+
|
|
437
|
+
carried.to_h { |name, value| [:"#{fields}#{name}", value] }
|
|
438
|
+
end
|
|
439
|
+
|
|
440
|
+
# Which positions are tokens and which are padding, [rows, seq, 1]:
|
|
441
|
+
# one where a position is real and zero where it is not.
|
|
442
|
+
#
|
|
443
|
+
# What a mean over the real tokens weighs with, shaped to multiply a
|
|
444
|
+
# [rows, seq, hidden] hidden state as it stands. Only a graph that
|
|
445
|
+
# pools that way declares it, and a field nothing reads is refused
|
|
446
|
+
# at the boundary rather than ignored, so `batch` is told which
|
|
447
|
+
# pooling it is feeding rather than guessing.
|
|
448
|
+
#
|
|
449
|
+
# Public for a caller who has already padded its own ids.
|
|
450
|
+
def tokens(seq:, lengths:)
|
|
451
|
+
empty = lengths.index(0)
|
|
452
|
+
if empty
|
|
453
|
+
raise ConfigError,
|
|
454
|
+
"row #{empty} has no tokens, and a mean over no tokens is not a vector"
|
|
455
|
+
end
|
|
456
|
+
|
|
457
|
+
TensorData.runs([lengths.size, seq, 1],
|
|
458
|
+
lengths.flat_map { |length| [[length, 1.0], [seq - length, 0.0]] })
|
|
459
|
+
end
|
|
460
|
+
|
|
461
|
+
# What a batch must carry for the attention, ready to go in:
|
|
462
|
+
# `{mask:}`, and `{mask:, window:}` where the configuration has a
|
|
463
|
+
# local layer to read one. `batch` calls this; it is public for a
|
|
464
|
+
# caller who has already padded its own ids.
|
|
465
|
+
#
|
|
466
|
+
# `lengths` is how many real tokens each row has; the rest is
|
|
467
|
+
# padding, which nothing may attend to.
|
|
468
|
+
#
|
|
469
|
+
# Neither is built as an Array of Floats. A mask is runs of the same
|
|
470
|
+
# number, so both are written as bytes directly (`TensorData.runs`);
|
|
471
|
+
# at sequence 512 and batch 32 that is the difference between a few
|
|
472
|
+
# hundred kilobytes and building 16.8 million Ruby Floats to throw
|
|
473
|
+
# away.
|
|
474
|
+
#
|
|
475
|
+
# A large negative rather than -Infinity: a row that can attend to
|
|
476
|
+
# nothing would otherwise softmax to NaN, and a finite floor keeps a
|
|
477
|
+
# padded row's arithmetic finite even though its output is discarded.
|
|
478
|
+
NEGATIVE = -1.0e9
|
|
479
|
+
|
|
480
|
+
def masks(config, seq:, lengths:)
|
|
481
|
+
padding = TensorData.runs(
|
|
482
|
+
[lengths.size, 1, 1, seq],
|
|
483
|
+
lengths.flat_map { |length| [[length, 0.0], [seq - length, NEGATIVE]] }
|
|
484
|
+
)
|
|
485
|
+
return { mask: padding } unless config.any_local?
|
|
486
|
+
|
|
487
|
+
{ mask: padding, window: window(config, seq:) }
|
|
488
|
+
end
|
|
489
|
+
|
|
490
|
+
# What a shape's window is kept in, bounded (`Models::Windows`).
|
|
491
|
+
WINDOWS = Windows.new
|
|
492
|
+
|
|
493
|
+
# The sliding window the local layers see, [1, 1, seq, seq].
|
|
494
|
+
#
|
|
495
|
+
# It depends on the sequence length and the configured width and on
|
|
496
|
+
# nothing in the batch, so there is one of it however many rows
|
|
497
|
+
# there are, and it is built once per shape and handed out again.
|
|
498
|
+
def window(config, seq:)
|
|
499
|
+
half = config.local_attention / 2
|
|
500
|
+
WINDOWS.fetch([seq, half]) do
|
|
501
|
+
TensorData.runs(
|
|
502
|
+
[1, 1, seq, seq],
|
|
503
|
+
(0...seq).flat_map do |i|
|
|
504
|
+
first = [i - half, 0].max
|
|
505
|
+
last = [i + half, seq - 1].min
|
|
506
|
+
[[first, NEGATIVE], [last - first + 1, 0.0], [seq - 1 - last, NEGATIVE]]
|
|
507
|
+
end
|
|
508
|
+
)
|
|
509
|
+
end
|
|
510
|
+
end
|
|
511
|
+
end
|
|
512
|
+
end
|
|
513
|
+
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
module Models
|
|
5
|
+
# A row longer than the padding is a decision about the data rather
|
|
6
|
+
# than about the model, so it is refused rather than cut; where to
|
|
7
|
+
# drop tokens is the caller's to decide. What the row is too long for
|
|
8
|
+
# is the padding it was handed, which for a graph built for no
|
|
9
|
+
# particular length (`ModernBERT.towers`) is the batch's own number.
|
|
10
|
+
module Padding
|
|
11
|
+
module_function
|
|
12
|
+
|
|
13
|
+
def ids(rows, seq:, pad:)
|
|
14
|
+
too_long = rows.each_with_index.find { |row, _| row.size > seq }
|
|
15
|
+
if too_long
|
|
16
|
+
row, at = too_long
|
|
17
|
+
raise ConfigError,
|
|
18
|
+
"row #{at} has #{row.size} tokens and this batch pads to #{seq}. " \
|
|
19
|
+
"Tokenize to at most #{seq}, or pad to more; where to cut a long " \
|
|
20
|
+
"text is the caller's to decide."
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
rows.flat_map { |row| row + Array.new(seq - row.size, pad) }
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
module Models
|
|
5
|
+
# The masks that depend on a shape and on nothing else.
|
|
6
|
+
#
|
|
7
|
+
# A sliding window is the same bytes at every step of a run: what a
|
|
8
|
+
# position may see is decided by the sequence length and the
|
|
9
|
+
# architecture's width, and a batch has no say in it. So it is built
|
|
10
|
+
# once per shape and handed out again, which is worth doing (0.21 ms
|
|
11
|
+
# at sequence 192 and 0.62 ms at 512, against a step measured in
|
|
12
|
+
# seconds) and worth bounding.
|
|
13
|
+
#
|
|
14
|
+
# **Bounded, because the shapes are no longer few.** A graph used to
|
|
15
|
+
# be built for one length and a run saw one window. Now a batch is
|
|
16
|
+
# padded to its own longest row (docs/plan.md 15.63), so a run sees a
|
|
17
|
+
# different length most steps, and a window is seq*seq*4 bytes: a
|
|
18
|
+
# megabyte each at 512. Holding every one a run ever meets is a leak
|
|
19
|
+
# with a shape. What falls out is rebuilt, which costs what building
|
|
20
|
+
# costs.
|
|
21
|
+
#
|
|
22
|
+
# Least recently used, because a run's lengths cluster: the sorted
|
|
23
|
+
# batches of a mining pass walk through lengths in order and come back
|
|
24
|
+
# to the long ones.
|
|
25
|
+
#
|
|
26
|
+
# Not synchronised. Batches are built on the thread that drives the
|
|
27
|
+
# session, and a session is one conversation, so there is one writer;
|
|
28
|
+
# sharing one of these across threads would need a lock.
|
|
29
|
+
class Windows
|
|
30
|
+
LIMIT = 8
|
|
31
|
+
|
|
32
|
+
def initialize(limit: LIMIT)
|
|
33
|
+
raise ArgumentError, "a cache holds at least one" unless limit.positive?
|
|
34
|
+
|
|
35
|
+
@limit = Integer(limit)
|
|
36
|
+
@held = {}
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def size = @held.size
|
|
40
|
+
|
|
41
|
+
# What is held for `key`, or what the block builds.
|
|
42
|
+
#
|
|
43
|
+
# Ruby's Hash keeps insertion order, so re-inserting on a hit is
|
|
44
|
+
# what makes the first key the least recently used one.
|
|
45
|
+
def fetch(key)
|
|
46
|
+
held = @held.delete(key)
|
|
47
|
+
@held[key] = held || yield
|
|
48
|
+
@held.delete(@held.keys.first) while @held.size > @limit
|
|
49
|
+
@held.fetch(key)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
data/lib/torobi/ops.rb
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "yaml"
|
|
4
|
+
|
|
5
|
+
module Torobi
|
|
6
|
+
# The operation vocabulary, loaded from config/ops.yml, the single source
|
|
7
|
+
# of truth. The DSL asks it which ops exist and what they accept; the
|
|
8
|
+
# inventory tests hold it against the shape rules and the handle methods;
|
|
9
|
+
# the engine's dispatch table will be generated from the same file.
|
|
10
|
+
module Ops
|
|
11
|
+
ATTRIBUTE_TYPES = {
|
|
12
|
+
"int" => ->(v) { v.is_a?(Integer) },
|
|
13
|
+
"number" => ->(v) { v.is_a?(Numeric) },
|
|
14
|
+
"number_or_null" => ->(v) { v.nil? || v.is_a?(Numeric) },
|
|
15
|
+
"bool" => ->(v) { [true, false].include?(v) },
|
|
16
|
+
"string" => ->(v) { v.is_a?(String) },
|
|
17
|
+
# A dtype by name, from the IR's own small vocabulary.
|
|
18
|
+
"dtype" => ->(v) { IR::Dtype::ALL.include?(v.to_s.to_sym) },
|
|
19
|
+
"int_list" => ->(v) { v.is_a?(Array) && v.all?(Integer) },
|
|
20
|
+
"int_list_or_null" => ->(v) { v.nil? || (v.is_a?(Array) && v.all?(Integer)) },
|
|
21
|
+
"number_list_or_null" => ->(v) { v.nil? || (v.is_a?(Array) && v.all?(Numeric)) }
|
|
22
|
+
}.freeze
|
|
23
|
+
|
|
24
|
+
# One manifest entry.
|
|
25
|
+
class Spec < Data.define(:name, :input_range, :params, :attributes, :shape_rule, :handle)
|
|
26
|
+
def self.from_manifest(entry)
|
|
27
|
+
inputs = entry.fetch("inputs")
|
|
28
|
+
input_range = inputs.is_a?(Array) ? (inputs[0]..inputs[1]) : (inputs..inputs)
|
|
29
|
+
attributes = (entry["attributes"] || {}).each do |key, type|
|
|
30
|
+
ATTRIBUTE_TYPES.fetch(type) do
|
|
31
|
+
raise ConfigError, "ops.yml: #{entry["name"]}.#{key} has unknown type #{type.inspect}"
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
new(name: entry.fetch("name"), input_range:, params: entry["params"] || 0,
|
|
35
|
+
attributes:, shape_rule: entry.fetch("shape_rule").to_sym,
|
|
36
|
+
handle: entry["handle"] || false)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Checks arity and attributes for one emission; the caller names the site.
|
|
40
|
+
def check!(inputs:, params:, attrs:, where:)
|
|
41
|
+
unless input_range.cover?(inputs)
|
|
42
|
+
raise ConfigError,
|
|
43
|
+
"#{where}: #{name} takes #{input_range} input(s), got #{inputs}"
|
|
44
|
+
end
|
|
45
|
+
unless params == self.params
|
|
46
|
+
raise ConfigError, "#{where}: #{name} takes #{self.params} parameter(s), got #{params}"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
attrs.each_key do |key|
|
|
50
|
+
unless attributes.key?(key)
|
|
51
|
+
raise ConfigError, "#{where}: #{name} has no attribute #{key.inspect}"
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
attributes.each do |key, type|
|
|
55
|
+
value = attrs[key]
|
|
56
|
+
next if ATTRIBUTE_TYPES.fetch(type).call(value)
|
|
57
|
+
|
|
58
|
+
raise ConfigError,
|
|
59
|
+
"#{where}: #{name} attribute #{key} must be #{type}, got #{value.inspect}"
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
MANIFEST_PATH = File.expand_path("../../config/ops.yml", __dir__)
|
|
65
|
+
|
|
66
|
+
REGISTRY = YAML.safe_load_file(MANIFEST_PATH).to_h do |entry|
|
|
67
|
+
spec = Spec.from_manifest(entry)
|
|
68
|
+
[spec.name, spec]
|
|
69
|
+
end.freeze
|
|
70
|
+
|
|
71
|
+
module_function
|
|
72
|
+
|
|
73
|
+
def fetch(name, where:)
|
|
74
|
+
REGISTRY.fetch(name.to_s) do
|
|
75
|
+
raise ConfigError, "#{where}: unknown op #{name.inspect}"
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def handle_ops = REGISTRY.each_value.select(&:handle)
|
|
80
|
+
end
|
|
81
|
+
end
|