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,414 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
module DSL
|
|
5
|
+
# The `g` inside Torobi.graph: everything that adds to the graph.
|
|
6
|
+
#
|
|
7
|
+
# The division of labour with Handle: a handle has the one-value ops
|
|
8
|
+
# the manifest marks `handle: true`, whose attributes are all keywords
|
|
9
|
+
# (`x.gelu`, `x.softmax(axis: -1)`, `x.dropout(p: 0.1)`), its
|
|
10
|
+
# operators, and the shape helpers built from them (`split_heads`).
|
|
11
|
+
# Everything else is here: what declares parameters (`param` and the
|
|
12
|
+
# layers in `Layers`), what joins several values (`matmul`, `sdpa`),
|
|
13
|
+
# and the ops whose call is more than keywords on one value: the
|
|
14
|
+
# reductions, whose axes default to all of them, and `cast`, which is
|
|
15
|
+
# no node at all when the dtype is already the one asked for.
|
|
16
|
+
class Builder
|
|
17
|
+
include Layers
|
|
18
|
+
|
|
19
|
+
# What a graph is built with when nothing is adapted: every parameter
|
|
20
|
+
# trains as declared, and no linear gains anything. The same two
|
|
21
|
+
# questions a `LoRA` answers, so the builder asks them without first
|
|
22
|
+
# asking whether there is an adapter at all.
|
|
23
|
+
module NoAdapter
|
|
24
|
+
def self.trains?(_path) = true
|
|
25
|
+
def self.wraps?(_path) = false
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# The same for how the base is held when nothing is quantized:
|
|
29
|
+
# every linear holds its weight as declared (`Torobi::Quantization`).
|
|
30
|
+
module NoQuantization
|
|
31
|
+
def self.wraps?(_path) = false
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# `models` is the set an objective may read outputs from; a model
|
|
35
|
+
# graph is built with none.
|
|
36
|
+
def initialize(models: {})
|
|
37
|
+
@models = models.to_h { |name, graph| [name.to_s, graph] }
|
|
38
|
+
@inputs = []
|
|
39
|
+
@parameters = []
|
|
40
|
+
@nodes = []
|
|
41
|
+
@outputs = {}
|
|
42
|
+
@scopes = []
|
|
43
|
+
@sharing = 0
|
|
44
|
+
@labels = []
|
|
45
|
+
@adapter = NoAdapter
|
|
46
|
+
@quantization = NoQuantization
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# --- graph boundary ---
|
|
50
|
+
|
|
51
|
+
# An input fed from the batch, by field name.
|
|
52
|
+
def input(name, shape, dtype: :f32) = from_batch(name, shape, dtype:)
|
|
53
|
+
|
|
54
|
+
# An input fed from the batch under a different field name than the
|
|
55
|
+
# one it is known by here.
|
|
56
|
+
def from_batch(name, shape, dtype: :f32, field: name)
|
|
57
|
+
declare_input(name, shape, dtype, IR::Source.batch(field))
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# An input fed from a model's named output. The shape and dtype come
|
|
61
|
+
# from that model's declaration, so the two halves cannot disagree.
|
|
62
|
+
def from_model(model, output, as: nil)
|
|
63
|
+
graph = @models.fetch(model.to_s) do
|
|
64
|
+
known = @models.keys.map(&:inspect).join(", ")
|
|
65
|
+
raise ConfigError,
|
|
66
|
+
"no model named #{model.to_s.inspect} here; this objective was " \
|
|
67
|
+
"given #{known.empty? ? "none" : known}"
|
|
68
|
+
end
|
|
69
|
+
shape, dtype = graph.output_signature(output)
|
|
70
|
+
declare_input(as || "#{model}.#{output}", shape, dtype,
|
|
71
|
+
IR::Source.model_output(model, output))
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Names one of this graph's outputs. An objective's loss and a model's
|
|
75
|
+
# logits are both named this way.
|
|
76
|
+
def output(name, handle)
|
|
77
|
+
own!(handle, where: "output #{name.to_s.inspect}")
|
|
78
|
+
name = name.to_s
|
|
79
|
+
raise ConfigError, "output #{name.inspect} is declared twice" if @outputs.key?(name)
|
|
80
|
+
|
|
81
|
+
@outputs[name] = handle.ref
|
|
82
|
+
handle
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def to_graph
|
|
86
|
+
IR::Graph.new(inputs: @inputs, parameters: @parameters, nodes: @nodes,
|
|
87
|
+
outputs: @outputs)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# --- naming ---
|
|
91
|
+
|
|
92
|
+
# Prefixes the paths of parameters created inside the block, so a
|
|
93
|
+
# component used in a loop yields "layers.3.wqkv.weight" and friends.
|
|
94
|
+
def scope(prefix)
|
|
95
|
+
@scopes.push(prefix.to_s)
|
|
96
|
+
yield
|
|
97
|
+
ensure
|
|
98
|
+
@scopes.pop
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# --- parameters ---
|
|
102
|
+
|
|
103
|
+
# A parameter this graph already declares, read again.
|
|
104
|
+
#
|
|
105
|
+
# Weight tying: a decoder whose output projection is its embedding
|
|
106
|
+
# table transposed is **one** parameter read twice, not two that are
|
|
107
|
+
# kept equal. Declaring it twice would be two, and a checkpoint
|
|
108
|
+
# would hold two copies of the same numbers.
|
|
109
|
+
#
|
|
110
|
+
# table = g.embedding(ids, vocab:, dim:, name: "embed")
|
|
111
|
+
# ...
|
|
112
|
+
# logits = g.matmul(h, g.parameter("embed.weight").transpose(axes: [1, 0]))
|
|
113
|
+
#
|
|
114
|
+
# The name is scoped like any other, so this reads the parameter of
|
|
115
|
+
# the scope it is called in.
|
|
116
|
+
def parameter(name)
|
|
117
|
+
path = scoped(name)
|
|
118
|
+
spec = declared(path)
|
|
119
|
+
unless spec
|
|
120
|
+
raise ConfigError,
|
|
121
|
+
"no parameter #{path.inspect} is declared yet (this graph has " \
|
|
122
|
+
"#{@parameters.map(&:path).inspect}); a shared parameter is read " \
|
|
123
|
+
"after whatever declares it"
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
emit("parameter", params: [spec.id])
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# The same weights, applied again.
|
|
130
|
+
#
|
|
131
|
+
# Inside this block a parameter that is already declared, in every
|
|
132
|
+
# respect, is **read** rather than declared a second time. So a
|
|
133
|
+
# component can be applied more than once and the applications are
|
|
134
|
+
# one set of weights: a query tower and a document tower that are
|
|
135
|
+
# the same tower, differentiated once and checkpointed once
|
|
136
|
+
# (docs/plan.md 15.63).
|
|
137
|
+
#
|
|
138
|
+
# %i[queries documents].each do |side|
|
|
139
|
+
# build = Build.new(seq: nil, dtype:, fields: "#{side}.")
|
|
140
|
+
# ModernBERT::Describe.new(g, config, build, encoder_prefix:)
|
|
141
|
+
# .tower(side, pooling:, normalize:)
|
|
142
|
+
# end
|
|
143
|
+
#
|
|
144
|
+
# `label` names the values rather than the weights: the parameters
|
|
145
|
+
# are one set with one set of names, and the nodes are "queries.x"
|
|
146
|
+
# and "documents.x", because a value computed twice from different
|
|
147
|
+
# rows is two values and a tap has to be able to ask for either.
|
|
148
|
+
# Without one, the second application collides on the first's node
|
|
149
|
+
# names, which is the error it should be.
|
|
150
|
+
#
|
|
151
|
+
# It is a block rather than the default because two declarations of
|
|
152
|
+
# one path are otherwise the mistake they have always been: a
|
|
153
|
+
# component built twice by accident would silently become one and
|
|
154
|
+
# nothing would say so. Asking for the same path with a *different*
|
|
155
|
+
# shape, dtype, initializer or trainability is refused here too.
|
|
156
|
+
# Two things that are not the same cannot be the same weights.
|
|
157
|
+
def sharing(label = nil)
|
|
158
|
+
@sharing += 1
|
|
159
|
+
@labels.push(label.to_s) if label
|
|
160
|
+
yield
|
|
161
|
+
ensure
|
|
162
|
+
@labels.pop if label
|
|
163
|
+
@sharing -= 1
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def param(name, shape, init:, dtype: :f32, trainable: true)
|
|
167
|
+
path = scoped(name)
|
|
168
|
+
# Whether it trains is the adapter's to say (`LoRA#trains?`). Asked
|
|
169
|
+
# before the sharing lookup, so that a second application is
|
|
170
|
+
# compared with what the first actually declared: an adapted base
|
|
171
|
+
# weight is frozen, and asking whether it is the same parameter
|
|
172
|
+
# has to ask about the same thing.
|
|
173
|
+
trainable &&= @adapter.trains?(path)
|
|
174
|
+
if @sharing.positive? && (already = declared(path))
|
|
175
|
+
return shared(already, shape:, dtype:, init:, trainable:)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
spec = IR::ParameterSpec.new(id: @parameters.size, path:, shape:,
|
|
179
|
+
dtype:, initializer: init, trainable:)
|
|
180
|
+
@parameters << spec
|
|
181
|
+
emit("parameter", params: [spec.id])
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# Builds a graph with an adapter in scope, so that every linear it
|
|
185
|
+
# names is trained through a pair of small matrices instead of
|
|
186
|
+
# being moved itself (`Torobi::LoRA`).
|
|
187
|
+
#
|
|
188
|
+
# A block rather than a keyword on `linear`, because what is being
|
|
189
|
+
# adapted is decided once, by whoever is doing the fine-tune, and a
|
|
190
|
+
# model description should not have to be rewritten to be adapted:
|
|
191
|
+
#
|
|
192
|
+
# Torobi.graph do |g|
|
|
193
|
+
# g.adapting(adapter) { ... the model ... }
|
|
194
|
+
# end
|
|
195
|
+
#
|
|
196
|
+
# `nil` adapts nothing, so a builder that always writes this reads
|
|
197
|
+
# the same either way.
|
|
198
|
+
def adapting(adapter)
|
|
199
|
+
return yield if adapter.nil?
|
|
200
|
+
raise ConfigError, "an adapter is already in scope" unless @adapter.equal?(NoAdapter)
|
|
201
|
+
|
|
202
|
+
@adapter = adapter
|
|
203
|
+
begin
|
|
204
|
+
yield
|
|
205
|
+
ensure
|
|
206
|
+
@adapter = NoAdapter
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# Builds a graph with the base held quantized, so that every linear
|
|
211
|
+
# the quantization names is three frozen parameters and a packed
|
|
212
|
+
# matmul rather than a weight (`Torobi::Quantization`,
|
|
213
|
+
# docs/qlora.md).
|
|
214
|
+
#
|
|
215
|
+
# Written outside `adapting`, as "how the base is held" comes
|
|
216
|
+
# before "what is trained", though either order builds the same
|
|
217
|
+
# graph: a quantized parameter is frozen by declaration, and the
|
|
218
|
+
# adapter's own parameters are not linears.
|
|
219
|
+
#
|
|
220
|
+
# Torobi.graph do |g|
|
|
221
|
+
# g.quantized(quant) do
|
|
222
|
+
# g.adapting(adapter) { ... the model ... }
|
|
223
|
+
# end
|
|
224
|
+
# end
|
|
225
|
+
#
|
|
226
|
+
# `nil` quantizes nothing, so a builder that always writes this
|
|
227
|
+
# reads the same either way.
|
|
228
|
+
def quantized(quantization)
|
|
229
|
+
return yield if quantization.nil?
|
|
230
|
+
unless @quantization.equal?(NoQuantization)
|
|
231
|
+
raise ConfigError, "a quantization is already in scope"
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
@quantization = quantization
|
|
235
|
+
begin
|
|
236
|
+
yield
|
|
237
|
+
ensure
|
|
238
|
+
@quantization = NoQuantization
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
# --- primitive joins ---
|
|
243
|
+
|
|
244
|
+
def matmul(a, b) = emit("matmul", inputs: [a, b])
|
|
245
|
+
|
|
246
|
+
# Attention. `mask` is an additive mask the caller builds (padding,
|
|
247
|
+
# a sliding window); `causal:` is the triangle every decoder wants,
|
|
248
|
+
# which the backend has a mode for, so it is asked for by name
|
|
249
|
+
# rather than handed over as megabytes of the same number.
|
|
250
|
+
def sdpa(q, k, v, mask: nil, scale: nil, causal: false)
|
|
251
|
+
if causal && mask
|
|
252
|
+
raise ConfigError,
|
|
253
|
+
"sdpa: causal: is a mask, so it does not go with another one. " \
|
|
254
|
+
"Add what the mask says to the causal triangle, or drop it."
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
emit("sdpa", inputs: [q, k, v, mask].compact, attrs: { scale:, causal: })
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
def mean(x, axes: nil, keepdims: false)
|
|
261
|
+
emit("mean", inputs: [x], attrs: { axes:, keepdims: })
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
def sum(x, axes: nil, keepdims: false)
|
|
265
|
+
emit("sum", inputs: [x], attrs: { axes:, keepdims: })
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
# The same numbers in another precision.
|
|
269
|
+
#
|
|
270
|
+
# g.cast(logits, :f32)
|
|
271
|
+
#
|
|
272
|
+
# Where a model is held in bf16 and its loss is read as f32, this is
|
|
273
|
+
# the seam. Written down rather than inserted: a precision change
|
|
274
|
+
# nobody asked for is how a run quietly stops matching what it is
|
|
275
|
+
# held to.
|
|
276
|
+
# Casting to what something already is is not a node: a graph
|
|
277
|
+
# should not carry a step that does nothing, and this is what lets
|
|
278
|
+
# a model be written once and built in either precision.
|
|
279
|
+
def cast(x, dtype)
|
|
280
|
+
dtype = dtype.to_sym
|
|
281
|
+
return x if x.dtype == dtype
|
|
282
|
+
|
|
283
|
+
emit("cast", inputs: [x], attrs: { dtype: dtype.to_s })
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
def max(x, axes: nil, keepdims: false)
|
|
287
|
+
emit("max", inputs: [x], attrs: { axes:, keepdims: })
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
# The loss at each position of a classification: what was scored,
|
|
291
|
+
# and the class each position should have had.
|
|
292
|
+
#
|
|
293
|
+
# loss = g.mean(g.cross_entropy(logits, g.input(:targets, [nil, seq], dtype: :i32)))
|
|
294
|
+
#
|
|
295
|
+
# It reduces nothing. Which positions count (a padded one does not,
|
|
296
|
+
# nor does the last, which has nothing after it to predict) and how
|
|
297
|
+
# they are weighed is the objective's to say, and saying it is a
|
|
298
|
+
# multiply and a sum.
|
|
299
|
+
def cross_entropy(logits, targets)
|
|
300
|
+
emit("cross_entropy", inputs: [logits, targets])
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# --- core ---
|
|
304
|
+
|
|
305
|
+
# Adds one node: checks ownership, arity and attributes against the
|
|
306
|
+
# manifest, infers shape and dtype, and returns the handle.
|
|
307
|
+
#
|
|
308
|
+
# Public because a handle adds its nodes through it. A model
|
|
309
|
+
# description does not reach it: `Models::Description::VOCABULARY`
|
|
310
|
+
# is what a description may say, and `emit` is left out of it on
|
|
311
|
+
# purpose, so a node no layer means cannot be put in a graph that
|
|
312
|
+
# way.
|
|
313
|
+
def emit(op, inputs: [], params: [], attrs: {}, name: nil)
|
|
314
|
+
where = "node #{@nodes.size} (#{op})"
|
|
315
|
+
spec = Ops.fetch(op, where:)
|
|
316
|
+
inputs.each { |handle| own!(handle, where:) }
|
|
317
|
+
attrs = attrs.transform_keys(&:to_s)
|
|
318
|
+
spec.check!(inputs: inputs.size, params: params.size, attrs:, where:)
|
|
319
|
+
|
|
320
|
+
shape, dtype = Shape.infer(spec.shape_rule, inputs:,
|
|
321
|
+
params: params.map { |id| @parameters.fetch(id) },
|
|
322
|
+
attrs:, where:)
|
|
323
|
+
node = IR::NodeSpec.new(id: @nodes.size, op:, name: name && unique_name(name),
|
|
324
|
+
inputs: inputs.map(&:ref), parameters: params,
|
|
325
|
+
attributes: attrs, shape:, dtype:)
|
|
326
|
+
@nodes << node
|
|
327
|
+
Handle.new(builder: self, ref: IR::Ref.node(node.id), shape:, dtype:)
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
# What `Handle#named` asks of the graph: the node behind `handle`,
|
|
331
|
+
# given a name no other value here has.
|
|
332
|
+
def named(handle, label)
|
|
333
|
+
own!(handle, where: "named #{label.to_s.inspect}")
|
|
334
|
+
ref = handle.ref
|
|
335
|
+
if ref.input?
|
|
336
|
+
raise ConfigError,
|
|
337
|
+
"only a computed value can be named, and #{ref} is an input"
|
|
338
|
+
end
|
|
339
|
+
|
|
340
|
+
node = @nodes[ref.id]
|
|
341
|
+
raise ConfigError, "#{handle.ref} is already named #{node.name.inspect}" if node.name
|
|
342
|
+
|
|
343
|
+
@nodes[ref.id] = node.with(name: unique_name(label))
|
|
344
|
+
handle
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
private
|
|
348
|
+
|
|
349
|
+
# A parameter an earlier application already declared, read again.
|
|
350
|
+
#
|
|
351
|
+
# The candidate is built rather than compared field by field, so
|
|
352
|
+
# the two go through the same normalizing: what is compared is what
|
|
353
|
+
# would have been declared.
|
|
354
|
+
def shared(already, shape:, dtype:, init:, trainable:)
|
|
355
|
+
wanted = IR::ParameterSpec.new(id: already.id, path: already.path, shape:, dtype:,
|
|
356
|
+
initializer: init, trainable:)
|
|
357
|
+
unless wanted == already
|
|
358
|
+
differs = %i[shape dtype initializer trainable]
|
|
359
|
+
.reject { |f| already.send(f) == wanted.send(f) }
|
|
360
|
+
said = differs.map { |f| "#{f} #{already.send(f).inspect} vs #{wanted.send(f).inspect}" }
|
|
361
|
+
raise ConfigError,
|
|
362
|
+
"#{already.path.inspect} is declared already and this asks for a " \
|
|
363
|
+
"different #{said.join(", ")}. Sharing is one parameter read twice, so " \
|
|
364
|
+
"the applications have to be the same model."
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
emit("parameter", params: [already.id])
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
def declared(path) = @parameters.find { |p| p.path == path }
|
|
371
|
+
|
|
372
|
+
def unique_name(label)
|
|
373
|
+
candidate = (@labels + [scoped(label)]).join(".")
|
|
374
|
+
if @nodes.any? { |n| n.name == candidate }
|
|
375
|
+
raise ConfigError, "two values are named #{candidate.inspect} in one graph"
|
|
376
|
+
end
|
|
377
|
+
|
|
378
|
+
candidate
|
|
379
|
+
end
|
|
380
|
+
|
|
381
|
+
def declare_input(name, shape, dtype, source)
|
|
382
|
+
spec = IR::InputSpec.new(id: @inputs.size, name: name.to_s, shape:, dtype:, source:)
|
|
383
|
+
@inputs << spec
|
|
384
|
+
Handle.new(builder: self, ref: IR::Ref.input(spec.id), shape: spec.shape,
|
|
385
|
+
dtype: spec.dtype)
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
def scoped(name) = (@scopes + [name.to_s]).join(".")
|
|
389
|
+
|
|
390
|
+
# The adapter in scope (`NoAdapter` when there is none), for a layer
|
|
391
|
+
# that may be adapted, and the quantization in scope
|
|
392
|
+
# (`NoQuantization` when there is none), for a layer that may be
|
|
393
|
+
# held packed.
|
|
394
|
+
attr_reader :adapter, :quantization
|
|
395
|
+
|
|
396
|
+
def own!(handle, where:)
|
|
397
|
+
unless handle.is_a?(Handle)
|
|
398
|
+
raise ConfigError, "#{where}: expected a graph value, got #{handle.inspect}"
|
|
399
|
+
end
|
|
400
|
+
return if handle.builder.equal?(self)
|
|
401
|
+
|
|
402
|
+
raise ConfigError,
|
|
403
|
+
"#{where}: #{handle.inspect} belongs to a different graph; " \
|
|
404
|
+
"values cannot cross graphs"
|
|
405
|
+
end
|
|
406
|
+
|
|
407
|
+
def concrete_last_dim!(x, where)
|
|
408
|
+
own!(x, where:)
|
|
409
|
+
x.shape.last or
|
|
410
|
+
raise ConfigError, "#{where}: the last dimension of #{x.inspect} must be concrete"
|
|
411
|
+
end
|
|
412
|
+
end
|
|
413
|
+
end
|
|
414
|
+
end
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
module DSL
|
|
5
|
+
# A symbolic value inside one graph under construction: it knows which
|
|
6
|
+
# builder owns it, what it references, and its inferred shape and dtype.
|
|
7
|
+
# Transformations live here (unary ops, operators, split); anything that
|
|
8
|
+
# creates parameters or joins several values lives on the builder.
|
|
9
|
+
class Handle
|
|
10
|
+
attr_reader :builder, :ref, :shape, :dtype
|
|
11
|
+
|
|
12
|
+
def initialize(builder:, ref:, shape:, dtype:)
|
|
13
|
+
@builder = builder
|
|
14
|
+
@ref = ref
|
|
15
|
+
@shape = shape
|
|
16
|
+
@dtype = dtype
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
{ :+ => "add", :- => "sub", :* => "mul", :/ => "div" }.each do |operator, op|
|
|
20
|
+
define_method(operator) do |other|
|
|
21
|
+
case other
|
|
22
|
+
when Handle then builder.emit(op, inputs: [self, other])
|
|
23
|
+
when Numeric then builder.emit("#{op}_scalar", inputs: [self], attrs: { value: other })
|
|
24
|
+
else raise ConfigError, "cannot #{operator} a #{other.class} to a graph value"
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Methods for every manifest op marked `handle: true`, e.g. `gelu`,
|
|
30
|
+
# `softmax(axis: -1)`, `rope(theta: 10_000)`.
|
|
31
|
+
Ops.handle_ops.each do |spec|
|
|
32
|
+
define_method(spec.name) do |**attrs|
|
|
33
|
+
builder.emit(spec.name, inputs: [self], attrs:)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Lets a number lead: `1.0 - x`, `2.0 * x`.
|
|
38
|
+
#
|
|
39
|
+
# Ruby asks the right-hand side to coerce when the left does not know
|
|
40
|
+
# what to do with it, and the pair it returns is sent the operator
|
|
41
|
+
# again. Returning `[Scalar.new(number), self]` puts the number in
|
|
42
|
+
# something that knows how to fold itself into the graph, which is
|
|
43
|
+
# what makes a loss read the way it is written on paper.
|
|
44
|
+
def coerce(other)
|
|
45
|
+
unless other.is_a?(Numeric)
|
|
46
|
+
raise ConfigError, "cannot combine a #{other.class} with a graph value"
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
[Scalar.new(self, other), self]
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# A number waiting to meet a graph value, and nothing else.
|
|
53
|
+
#
|
|
54
|
+
# It is what `coerce` returns, never something to build: it has no
|
|
55
|
+
# meaning apart from the operator Ruby is about to send it. Kept
|
|
56
|
+
# under Handle for that reason.
|
|
57
|
+
class Scalar
|
|
58
|
+
def initialize(handle, value)
|
|
59
|
+
@handle = handle
|
|
60
|
+
@value = value
|
|
61
|
+
freeze
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Addition and multiplication do not care which side they are on.
|
|
65
|
+
def +(other) = other + @value
|
|
66
|
+
def *(other) = other * @value
|
|
67
|
+
|
|
68
|
+
# Subtraction and division do, so these are the reversed forms:
|
|
69
|
+
# `1.0 - x` is `-(x - 1.0)`, and `1.0 / x` is its own op
|
|
70
|
+
# (`rdiv_scalar`), since spreading the number to x's shape through
|
|
71
|
+
# x itself would be NaN wherever x is infinite.
|
|
72
|
+
def -(other) = (other - @value) * -1.0
|
|
73
|
+
|
|
74
|
+
def /(other)
|
|
75
|
+
@handle.builder.emit("rdiv_scalar", inputs: [other], attrs: { value: @value })
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def inspect = "#<Torobi::DSL::Handle::Scalar #{@value}>"
|
|
79
|
+
alias to_s inspect
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The same numbers, read as `count` heads instead of one wide row:
|
|
83
|
+
# [batch, seq, width] -> [batch, count, seq, width / count].
|
|
84
|
+
#
|
|
85
|
+
# q = g.linear(x, heads * dim, name: "q_proj").split_heads(heads)
|
|
86
|
+
#
|
|
87
|
+
# Two nodes, and both of them are already here: the width is
|
|
88
|
+
# divided up (`reshape`) and the heads are moved in front of the
|
|
89
|
+
# sequence, which is the layout attention runs in (`transpose`).
|
|
90
|
+
# Named because `[0, 2, 1, 3]` says where the axes went and not what
|
|
91
|
+
# was meant, and every description that wrote it by hand wrote a
|
|
92
|
+
# comment underneath saying this sentence.
|
|
93
|
+
#
|
|
94
|
+
# The leading two dimensions are kept as they are, so a graph built
|
|
95
|
+
# for no particular batch or sequence splits heads the same way one
|
|
96
|
+
# built for both does (docs/plan.md 15.63).
|
|
97
|
+
def split_heads(count)
|
|
98
|
+
unless shape.size == 3
|
|
99
|
+
raise ConfigError,
|
|
100
|
+
"split_heads: expected [batch, seq, width], got #{dtype}#{shape.inspect}"
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
each = Shape.divide!(shape.last, count, into: "heads", where: "split_heads")
|
|
104
|
+
builder.emit("reshape", inputs: [self], attrs: { shape: [0, 0, Integer(count), each] })
|
|
105
|
+
.transpose(axes: [0, 2, 1, 3])
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# The inverse: [batch, count, seq, dim] -> [batch, seq, count * dim].
|
|
109
|
+
#
|
|
110
|
+
# linear(attended.merge_heads, hidden, name: "o_proj")
|
|
111
|
+
#
|
|
112
|
+
# The width it lands on is the heads times what each of them holds,
|
|
113
|
+
# which this reads off its own shape. A model whose attention is
|
|
114
|
+
# wider or narrower than its hidden state (Gemma 3 is: four heads of
|
|
115
|
+
# 256 over a hidden state of 640) therefore needs to say nothing
|
|
116
|
+
# here, and the projection that follows says the rest.
|
|
117
|
+
def merge_heads
|
|
118
|
+
unless shape.size == 4
|
|
119
|
+
raise ConfigError,
|
|
120
|
+
"merge_heads: expected [batch, heads, seq, dim], got #{dtype}#{shape.inspect}"
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
heads, dim = shape.values_at(1, 3)
|
|
124
|
+
unless heads && dim
|
|
125
|
+
raise ConfigError,
|
|
126
|
+
"merge_heads: the heads and their width must both be concrete, " \
|
|
127
|
+
"and this is #{shape.inspect}"
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
transpose(axes: [0, 2, 1, 3])
|
|
131
|
+
.then { |h| builder.emit("reshape", inputs: [h], attrs: { shape: [0, 0, heads * dim] }) }
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# Splits into `count` equal parts along `axis`, as slice nodes.
|
|
135
|
+
def split(count, axis: -1)
|
|
136
|
+
normalized = Shape.axis!(axis, shape.size, where: "split")
|
|
137
|
+
length = Shape.divide!(shape[normalized], count, into: "parts", where: "split")
|
|
138
|
+
Array.new(Integer(count)) do |i|
|
|
139
|
+
builder.emit("slice", inputs: [self],
|
|
140
|
+
attrs: { axis: normalized, start: i * length, length: })
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# Names this value, so a tap can ask for it later (docs/plan.md 6.4
|
|
145
|
+
# and 8.3). The name is taken under the scopes in force, so the same
|
|
146
|
+
# component in a loop yields "layers.0.attn", "layers.1.attn".
|
|
147
|
+
#
|
|
148
|
+
# h = g.sdpa(q, k, v).named("attn")
|
|
149
|
+
def named(label) = builder.named(self, label)
|
|
150
|
+
|
|
151
|
+
def inspect
|
|
152
|
+
"#<Torobi::DSL::Handle #{ref} #{dtype}#{shape.inspect}>"
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
end
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Torobi
|
|
4
|
+
module DSL
|
|
5
|
+
# The layers a model is written in: parameters plus their application,
|
|
6
|
+
# in one call (`g.linear(x, 512, name: "wo")` declares the weights and
|
|
7
|
+
# adds the nodes).
|
|
8
|
+
#
|
|
9
|
+
# Kept apart from `Builder` because they are the part of the DSL that
|
|
10
|
+
# grows: each is written in the builder's own vocabulary (`param`,
|
|
11
|
+
# `matmul`, `scope`, `emit`, and the handle's methods) and needs
|
|
12
|
+
# nothing else from it, so adding a layer is adding a method here and
|
|
13
|
+
# not reopening the class that owns the graph. Included into `Builder`,
|
|
14
|
+
# so a description still says `g.linear`.
|
|
15
|
+
module Layers
|
|
16
|
+
def linear(x, d_out, name:, bias: true)
|
|
17
|
+
d_in = concrete_last_dim!(x, "linear #{scoped(name).inspect}")
|
|
18
|
+
y = if quantization.wraps?(scoped(name))
|
|
19
|
+
# Three frozen parameters and a packed matmul
|
|
20
|
+
# (`Torobi::Quantization#apply`). The bias below and the
|
|
21
|
+
# adapter's contribution are untouched: neither is quantized.
|
|
22
|
+
quantization.apply(self, x, d_in:, d_out:, name:)
|
|
23
|
+
else
|
|
24
|
+
# PyTorch layout [d_out, d_in], so pretrained checkpoints map 1:1.
|
|
25
|
+
w = param("#{name}.weight", [d_out, d_in], dtype: x.dtype,
|
|
26
|
+
init: { "type" => "kaiming_uniform" })
|
|
27
|
+
matmul(x, w.transpose(axes: [1, 0]))
|
|
28
|
+
end
|
|
29
|
+
y += param("#{name}.bias", [d_out], dtype: x.dtype, init: { "type" => "zeros" }) if bias
|
|
30
|
+
y += adapter.contribution(self, x, d_in:, d_out:, name:) if adapter.wraps?(scoped(name))
|
|
31
|
+
y.named(name)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The table, and the lookup into it.
|
|
35
|
+
#
|
|
36
|
+
# `dtype:` is where a model's precision is decided: everything
|
|
37
|
+
# downstream takes its dtype from what it is given (`linear` and the
|
|
38
|
+
# norms use `x.dtype`), so a bf16 table makes a bf16 model.
|
|
39
|
+
def embedding(ids, vocab:, dim:, name:, dtype: :f32)
|
|
40
|
+
table = param("#{name}.weight", [vocab, dim], dtype:,
|
|
41
|
+
init: { "type" => "normal", "std" => 0.02 })
|
|
42
|
+
emit("take", inputs: [table, ids])
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def layer_norm(x, name:, bias: false, eps: 1.0e-5)
|
|
46
|
+
d = concrete_last_dim!(x, "layer_norm #{scoped(name).inspect}")
|
|
47
|
+
w = param("#{name}.weight", [d], dtype: x.dtype, init: { "type" => "ones" })
|
|
48
|
+
inputs = [x, w]
|
|
49
|
+
inputs << param("#{name}.bias", [d], dtype: x.dtype, init: { "type" => "zeros" }) if bias
|
|
50
|
+
emit("layer_norm", inputs:, attrs: { eps: })
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# `offset:` is added to the learned weight before it scales.
|
|
54
|
+
#
|
|
55
|
+
# Gemma stores its norms as `w` and applies `(1 + w)`, so its
|
|
56
|
+
# weights sit around zero where everyone else's sit around one.
|
|
57
|
+
# The op is the same op; what differs is what is handed to it, and
|
|
58
|
+
# that is a fact about the checkpoint rather than about norms.
|
|
59
|
+
def rms_norm(x, name:, eps: 1.0e-5, offset: 0.0)
|
|
60
|
+
d = concrete_last_dim!(x, "rms_norm #{scoped(name).inspect}")
|
|
61
|
+
w = param("#{name}.weight", [d], dtype: x.dtype,
|
|
62
|
+
init: { "type" => offset.zero? ? "ones" : "zeros" })
|
|
63
|
+
w += offset unless offset.zero?
|
|
64
|
+
emit("rms_norm", inputs: [x, w], attrs: { eps: })
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# GeGLU as ModernBERT uses it: one projection producing act and gate,
|
|
68
|
+
# gelu on the act half, a projection back down.
|
|
69
|
+
def geglu(x, d_hidden, name:)
|
|
70
|
+
d_in = concrete_last_dim!(x, "geglu #{scoped(name).inspect}")
|
|
71
|
+
scope name do
|
|
72
|
+
a, gate = linear(x, d_hidden * 2, name: "wi", bias: false).split(2, axis: -1)
|
|
73
|
+
linear(a.gelu * gate, d_in, name: "wo", bias: false)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# The mean squared difference: the loss a regression or a distillation
|
|
78
|
+
# reads.
|
|
79
|
+
def mse(a, b) = mean((a - b).square)
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
data/lib/torobi/dsl.rb
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "dsl/handle"
|
|
4
|
+
require_relative "dsl/layers"
|
|
5
|
+
require_relative "dsl/builder"
|
|
6
|
+
|
|
7
|
+
module Torobi
|
|
8
|
+
# Builds one model graph. The block runs exactly once, at definition time;
|
|
9
|
+
# `g` is the only way in, and the result is a frozen IR::Graph.
|
|
10
|
+
#
|
|
11
|
+
# model = Torobi.graph do |g|
|
|
12
|
+
# x = g.input :x, [nil, 4]
|
|
13
|
+
# g.output :logits, g.linear(x, 2, name: "linear")
|
|
14
|
+
# end
|
|
15
|
+
def self.graph
|
|
16
|
+
builder = DSL::Builder.new
|
|
17
|
+
yield builder
|
|
18
|
+
builder.to_graph
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Builds an objective graph: the same DSL, plus the ability to read a
|
|
22
|
+
# model's named outputs (docs/plan.md section 5A.3). It reaches a named
|
|
23
|
+
# scalar, conventionally "loss".
|
|
24
|
+
#
|
|
25
|
+
# objective = Torobi.objective(student: model) do |g|
|
|
26
|
+
# s = g.from_model :student, :logits
|
|
27
|
+
# t = g.from_batch :teacher, [nil, 2]
|
|
28
|
+
# g.output :loss, g.mse(s, t)
|
|
29
|
+
# end
|
|
30
|
+
def self.objective(models)
|
|
31
|
+
builder = DSL::Builder.new(models:)
|
|
32
|
+
yield builder
|
|
33
|
+
builder.to_graph
|
|
34
|
+
end
|
|
35
|
+
end
|