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,518 @@
|
|
|
1
|
+
//! Small graphs for the engine's own tests.
|
|
2
|
+
//!
|
|
3
|
+
//! The Ruby side builds a GraphConfig through the DSL; a Rust test wants
|
|
4
|
+
//! one without that machinery, and wants it small enough to reason about.
|
|
5
|
+
//! These are hand-written, which is also the point: they pin the JSON the
|
|
6
|
+
//! engine actually accepts, independently of what the DSL happens to emit.
|
|
7
|
+
|
|
8
|
+
use serde_json::{json, Value};
|
|
9
|
+
|
|
10
|
+
/// An input reading a batch field.
|
|
11
|
+
pub fn input(id: usize, name: &str, shape: Value, dtype: &str) -> Value {
|
|
12
|
+
json!({
|
|
13
|
+
"id": id,
|
|
14
|
+
"name": name,
|
|
15
|
+
"source": {"batch": name},
|
|
16
|
+
"shape": shape,
|
|
17
|
+
"dtype": dtype,
|
|
18
|
+
})
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// An input reading another model's output.
|
|
22
|
+
pub fn from_model(id: usize, name: &str, model: &str, output: &str, shape: Value) -> Value {
|
|
23
|
+
json!({
|
|
24
|
+
"id": id,
|
|
25
|
+
"name": name,
|
|
26
|
+
"source": {"model": model, "output": output},
|
|
27
|
+
"shape": shape,
|
|
28
|
+
"dtype": "f32",
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
pub fn parameter(id: usize, path: &str, shape: Value, trainable: bool) -> Value {
|
|
33
|
+
json!({
|
|
34
|
+
"id": id,
|
|
35
|
+
"path": path,
|
|
36
|
+
"shape": shape,
|
|
37
|
+
"dtype": "f32",
|
|
38
|
+
"initializer": {"type": "zeros"},
|
|
39
|
+
"trainable": trainable,
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
pub fn node(id: usize, op: &str, inputs: Value, parameters: Value) -> Value {
|
|
44
|
+
json!({
|
|
45
|
+
"id": id,
|
|
46
|
+
"op": op,
|
|
47
|
+
"inputs": inputs,
|
|
48
|
+
"parameters": parameters,
|
|
49
|
+
"attributes": {},
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// The same, with a name a tap can ask for.
|
|
54
|
+
pub fn named(id: usize, op: &str, inputs: Value, parameters: Value, name: &str) -> Value {
|
|
55
|
+
let mut node = node(id, op, inputs, parameters);
|
|
56
|
+
node["name"] = json!(name);
|
|
57
|
+
node
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
pub fn config(models: Value, objective: Value, train: Value) -> String {
|
|
61
|
+
json!({
|
|
62
|
+
"schema_version": 1,
|
|
63
|
+
"semantics_version": 3,
|
|
64
|
+
"models": models,
|
|
65
|
+
"objective": objective,
|
|
66
|
+
"train": train,
|
|
67
|
+
})
|
|
68
|
+
.to_string()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// `loss = mean(x * w)`, with `w` a two-element trainable parameter.
|
|
72
|
+
///
|
|
73
|
+
/// Small enough that its gradient is arithmetic: d(loss)/dw is the column
|
|
74
|
+
/// mean of x, so a test can say what a step must produce.
|
|
75
|
+
pub fn scaled_mean() -> (String, String) {
|
|
76
|
+
let graph = json!({
|
|
77
|
+
"inputs": [input(0, "x", json!([null, 2]), "f32")],
|
|
78
|
+
"parameters": [parameter(0, "w", json!([2]), true)],
|
|
79
|
+
"nodes": [
|
|
80
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
81
|
+
named(1, "mul", json!(["input:0", "node:0"]), json!([]), "scaled"),
|
|
82
|
+
node(2, "mean", json!(["node:1"]), json!([])),
|
|
83
|
+
],
|
|
84
|
+
"outputs": {"loss": "node:2"},
|
|
85
|
+
});
|
|
86
|
+
let config = config(json!({"m": graph}), Value::Null, json!(["m"]));
|
|
87
|
+
let weights = json!({"params": {"m.w": {"shape": [2], "data": [1.0, 2.0]}}}).to_string();
|
|
88
|
+
(config, weights)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// Two models and an objective over them: a frozen teacher, a trained
|
|
92
|
+
/// student, and a loss that reads both. What the parameter ordering, the
|
|
93
|
+
/// freeze window and the checkpoint contract are all about.
|
|
94
|
+
pub fn teacher_and_student() -> (String, String) {
|
|
95
|
+
let body = |path: &str| {
|
|
96
|
+
json!({
|
|
97
|
+
"inputs": [input(0, "x", json!([null, 2]), "f32")],
|
|
98
|
+
"parameters": [parameter(0, path, json!([2]), true)],
|
|
99
|
+
"nodes": [
|
|
100
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
101
|
+
// Named, and named the same in both models, which is what
|
|
102
|
+
// two models of one architecture look like.
|
|
103
|
+
named(1, "mul", json!(["input:0", "node:0"]), json!([]), "scaled"),
|
|
104
|
+
],
|
|
105
|
+
"outputs": {"out": "node:1"},
|
|
106
|
+
})
|
|
107
|
+
};
|
|
108
|
+
let objective = json!({
|
|
109
|
+
"inputs": [
|
|
110
|
+
from_model(0, "s", "student", "out", json!([null, 2])),
|
|
111
|
+
from_model(1, "t", "teacher", "out", json!([null, 2])),
|
|
112
|
+
],
|
|
113
|
+
"parameters": [],
|
|
114
|
+
"nodes": [
|
|
115
|
+
node(0, "sub", json!(["input:0", "input:1"]), json!([])),
|
|
116
|
+
node(1, "square", json!(["node:0"]), json!([])),
|
|
117
|
+
node(2, "mean", json!(["node:1"]), json!([])),
|
|
118
|
+
],
|
|
119
|
+
"outputs": {"loss": "node:2"},
|
|
120
|
+
});
|
|
121
|
+
let config = config(
|
|
122
|
+
json!({"student": body("scale"), "teacher": body("scale")}),
|
|
123
|
+
objective,
|
|
124
|
+
json!(["student"]),
|
|
125
|
+
);
|
|
126
|
+
let weights = json!({"params": {
|
|
127
|
+
"student.scale": {"shape": [2], "data": [1.0, 1.0]},
|
|
128
|
+
"teacher.scale": {"shape": [2], "data": [3.0, 4.0]},
|
|
129
|
+
}})
|
|
130
|
+
.to_string();
|
|
131
|
+
(config, weights)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// `loss = mean(x / w)` with `w` starting at zero: the first step divides
|
|
135
|
+
/// by zero, so the loss and its gradients are not finite. What the guard in
|
|
136
|
+
/// `TrainState::advance` is for.
|
|
137
|
+
pub fn divides_by_zero() -> (String, String) {
|
|
138
|
+
let graph = json!({
|
|
139
|
+
"inputs": [input(0, "x", json!([null, 2]), "f32")],
|
|
140
|
+
"parameters": [parameter(0, "w", json!([2]), true)],
|
|
141
|
+
"nodes": [
|
|
142
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
143
|
+
node(1, "div", json!(["input:0", "node:0"]), json!([])),
|
|
144
|
+
node(2, "mean", json!(["node:1"]), json!([])),
|
|
145
|
+
],
|
|
146
|
+
"outputs": {"loss": "node:2"},
|
|
147
|
+
});
|
|
148
|
+
let config = config(json!({"m": graph}), Value::Null, json!(["m"]));
|
|
149
|
+
let weights = json!({"params": {"m.w": {"shape": [2], "data": [0.0, 0.0]}}}).to_string();
|
|
150
|
+
(config, weights)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// One model with dropout in the middle, so a training pass and an
|
|
154
|
+
/// evaluation differ.
|
|
155
|
+
pub fn with_dropout(p: f64) -> (String, String) {
|
|
156
|
+
let mut dropout = node(1, "dropout", json!(["input:0"]), json!([]));
|
|
157
|
+
dropout["attributes"] = json!({"p": p});
|
|
158
|
+
let graph = json!({
|
|
159
|
+
"inputs": [input(0, "x", json!([null, 2]), "f32")],
|
|
160
|
+
"parameters": [parameter(0, "w", json!([2]), true)],
|
|
161
|
+
"nodes": [
|
|
162
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
163
|
+
dropout,
|
|
164
|
+
named(2, "mul", json!(["node:1", "node:0"]), json!([]), "scaled"),
|
|
165
|
+
node(3, "mean", json!(["node:2"]), json!([])),
|
|
166
|
+
],
|
|
167
|
+
"outputs": {"loss": "node:3"},
|
|
168
|
+
});
|
|
169
|
+
let config = config(json!({"m": graph}), Value::Null, json!(["m"]));
|
|
170
|
+
let weights = json!({"params": {"m.w": {"shape": [2], "data": [1.0, 1.0]}}}).to_string();
|
|
171
|
+
(config, weights)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/// One model that is a single named op over the batch, so a test can hold
|
|
175
|
+
/// its arithmetic against a number worked out by hand.
|
|
176
|
+
///
|
|
177
|
+
/// `shape` is the input's, `attributes` the op's. The parameter is a
|
|
178
|
+
/// scalar the run can differentiate, because a plan needs something to
|
|
179
|
+
/// train; the op under test does not read it.
|
|
180
|
+
pub fn one_op(op: &str, shape: Value, attributes: Value, extra_inputs: usize) -> (String, String) {
|
|
181
|
+
let mut inputs = vec![input(0, "x", shape.clone(), "f32")];
|
|
182
|
+
for i in 0..extra_inputs {
|
|
183
|
+
inputs.push(input(i + 1, &format!("v{i}"), shape.clone(), "f32"));
|
|
184
|
+
}
|
|
185
|
+
let mut under_test = node(
|
|
186
|
+
1,
|
|
187
|
+
op,
|
|
188
|
+
json!((0..=extra_inputs).map(|i| format!("input:{i}")).collect::<Vec<_>>()),
|
|
189
|
+
json!([]),
|
|
190
|
+
);
|
|
191
|
+
under_test["attributes"] = attributes;
|
|
192
|
+
under_test["name"] = json!("seen");
|
|
193
|
+
let graph = json!({
|
|
194
|
+
"inputs": inputs,
|
|
195
|
+
"parameters": [parameter(0, "w", json!([1]), true)],
|
|
196
|
+
"nodes": [
|
|
197
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
198
|
+
under_test,
|
|
199
|
+
node(2, "mean", json!(["node:1"]), json!([])),
|
|
200
|
+
node(3, "mul", json!(["node:2", "node:0"]), json!([])),
|
|
201
|
+
node(4, "mean", json!(["node:3"]), json!([])),
|
|
202
|
+
],
|
|
203
|
+
"outputs": {"loss": "node:4"},
|
|
204
|
+
});
|
|
205
|
+
let config = config(json!({"m": graph}), Value::Null, json!(["m"]));
|
|
206
|
+
let weights = json!({"params": {"m.w": {"shape": [1], "data": [1.0]}}}).to_string();
|
|
207
|
+
(config, weights)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/// A named batch field of any shape.
|
|
211
|
+
pub fn field(name: &str, shape: &[i32], data: &[f32]) -> (String, crate::tensor::Tensor) {
|
|
212
|
+
(
|
|
213
|
+
name.to_string(),
|
|
214
|
+
crate::tensor::Tensor {
|
|
215
|
+
shape: shape.to_vec(),
|
|
216
|
+
values: crate::tensor::Values::F32(data.to_vec()),
|
|
217
|
+
},
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/// A batch of two rows for the graphs above.
|
|
222
|
+
pub fn batch_x(rows: &[f32]) -> crate::tensor::Batch {
|
|
223
|
+
let n = rows.len() as i32 / 2;
|
|
224
|
+
[(
|
|
225
|
+
"x".to_string(),
|
|
226
|
+
crate::tensor::Tensor {
|
|
227
|
+
shape: vec![n, 2],
|
|
228
|
+
values: crate::tensor::Values::F32(rows.to_vec()),
|
|
229
|
+
},
|
|
230
|
+
)]
|
|
231
|
+
.into_iter()
|
|
232
|
+
.collect()
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/// Two models where the one that reads runs first: "reader" sorts before
|
|
236
|
+
/// "source", and models run in name order. What the ordering rule refuses.
|
|
237
|
+
pub fn reader_before_producer() -> (String, String) {
|
|
238
|
+
let source = json!({
|
|
239
|
+
"inputs": [input(0, "x", json!([null, 2]), "f32")],
|
|
240
|
+
"parameters": [parameter(0, "w", json!([2]), true)],
|
|
241
|
+
"nodes": [
|
|
242
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
243
|
+
node(1, "mul", json!(["input:0", "node:0"]), json!([])),
|
|
244
|
+
],
|
|
245
|
+
"outputs": {"out": "node:1"},
|
|
246
|
+
});
|
|
247
|
+
let reader = json!({
|
|
248
|
+
"inputs": [from_model(0, "s", "source", "out", json!([null, 2]))],
|
|
249
|
+
"parameters": [parameter(0, "w", json!([2]), true)],
|
|
250
|
+
"nodes": [
|
|
251
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
252
|
+
node(1, "mul", json!(["input:0", "node:0"]), json!([])),
|
|
253
|
+
node(2, "mean", json!(["node:1"]), json!([])),
|
|
254
|
+
],
|
|
255
|
+
"outputs": {"loss": "node:2"},
|
|
256
|
+
});
|
|
257
|
+
let config = config(
|
|
258
|
+
json!({"reader": reader, "source": source}),
|
|
259
|
+
Value::Null,
|
|
260
|
+
json!(["reader"]),
|
|
261
|
+
);
|
|
262
|
+
let weights = json!({"params": {
|
|
263
|
+
"reader.w": {"shape": [2], "data": [1.0, 1.0]},
|
|
264
|
+
"source.w": {"shape": [2], "data": [1.0, 1.0]},
|
|
265
|
+
}})
|
|
266
|
+
.to_string();
|
|
267
|
+
(config, weights)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/// A linear with an adapter beside it (`Torobi::LoRA`): `l.weight` is
|
|
271
|
+
/// frozen, `l.lora_A.weight` ([rank 1, d_in 2]) and `l.lora_B.weight`
|
|
272
|
+
/// ([d_out 1, rank 1]) train. Small enough that a merge is arithmetic:
|
|
273
|
+
/// W = [0.5, -1], A = [1, 2], B = [3].
|
|
274
|
+
pub fn adapted() -> (String, String) {
|
|
275
|
+
let graph = json!({
|
|
276
|
+
"inputs": [input(0, "x", json!([null, 2]), "f32")],
|
|
277
|
+
"parameters": [
|
|
278
|
+
parameter(0, "l.weight", json!([1, 2]), false),
|
|
279
|
+
parameter(1, "l.lora_A.weight", json!([1, 2]), true),
|
|
280
|
+
parameter(2, "l.lora_B.weight", json!([1, 1]), true),
|
|
281
|
+
],
|
|
282
|
+
"nodes": [
|
|
283
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
284
|
+
node(1, "parameter", json!([]), json!([1])),
|
|
285
|
+
node(2, "parameter", json!([]), json!([2])),
|
|
286
|
+
node(3, "mul", json!(["input:0", "node:1"]), json!([])),
|
|
287
|
+
node(4, "mul", json!(["node:3", "node:2"]), json!([])),
|
|
288
|
+
node(5, "mean", json!(["node:4"]), json!([])),
|
|
289
|
+
],
|
|
290
|
+
"outputs": {"loss": "node:5"},
|
|
291
|
+
});
|
|
292
|
+
let config = config(json!({"m": graph}), Value::Null, json!(["m"]));
|
|
293
|
+
let weights = json!({"params": {
|
|
294
|
+
"m.l.weight": {"shape": [1, 2], "data": [0.5, -1.0]},
|
|
295
|
+
"m.l.lora_A.weight": {"shape": [1, 2], "data": [1.0, 2.0]},
|
|
296
|
+
"m.l.lora_B.weight": {"shape": [1, 1], "data": [3.0]},
|
|
297
|
+
}})
|
|
298
|
+
.to_string();
|
|
299
|
+
(config, weights)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/// A linear held quantized (docs/qlora.md), and the file it is read from.
|
|
303
|
+
///
|
|
304
|
+
/// `proj` is three frozen parameters (a packed u32 weight, scales and
|
|
305
|
+
/// biases, 4 bits in groups of 32 over a width of 64) read by one
|
|
306
|
+
/// `quantized_matmul`; `emb` is declared as f32 numbers; `head` is the
|
|
307
|
+
/// one trainable parameter, so a step has something to move and the
|
|
308
|
+
/// base something to be left alone against.
|
|
309
|
+
pub mod quantized {
|
|
310
|
+
use super::*;
|
|
311
|
+
use crate::mlxc::quantized::{quantize, Mode, Quantization};
|
|
312
|
+
use crate::mlxc::Array;
|
|
313
|
+
|
|
314
|
+
pub const D_IN: usize = 64;
|
|
315
|
+
pub const D_OUT: usize = 8;
|
|
316
|
+
pub const EMB_ROWS: usize = 4;
|
|
317
|
+
pub const QUANTIZATION: Quantization = Quantization { group_size: 32, bits: 4, mode: Mode::Affine };
|
|
318
|
+
|
|
319
|
+
fn typed(id: usize, path: &str, shape: Value, dtype: &str, trainable: bool) -> Value {
|
|
320
|
+
let mut spec = parameter(id, path, shape, trainable);
|
|
321
|
+
spec["dtype"] = json!(dtype);
|
|
322
|
+
spec
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
pub fn config() -> String {
|
|
326
|
+
config_sized(D_OUT, D_IN)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/// The same model at another width, for a measurement that needs
|
|
330
|
+
/// more than a kilobyte to be about anything.
|
|
331
|
+
pub fn config_sized(d_out: usize, d_in: usize) -> String {
|
|
332
|
+
let graph = json!({
|
|
333
|
+
"inputs": [input(0, "x", json!([null, d_in]), "f32")],
|
|
334
|
+
"parameters": [
|
|
335
|
+
typed(0, "proj.weight", json!([d_out, d_in * 4 / 32]), "u32", false),
|
|
336
|
+
typed(1, "proj.scales", json!([d_out, d_in / 32]), "f32", false),
|
|
337
|
+
typed(2, "proj.biases", json!([d_out, d_in / 32]), "f32", false),
|
|
338
|
+
typed(3, "emb.weight", json!([EMB_ROWS, d_in]), "f32", false),
|
|
339
|
+
parameter(4, "head.weight", json!([d_out]), true),
|
|
340
|
+
],
|
|
341
|
+
"nodes": [
|
|
342
|
+
node(0, "parameter", json!([]), json!([0])),
|
|
343
|
+
node(1, "parameter", json!([]), json!([1])),
|
|
344
|
+
node(2, "parameter", json!([]), json!([2])),
|
|
345
|
+
node(3, "parameter", json!([]), json!([3])),
|
|
346
|
+
node(4, "parameter", json!([]), json!([4])),
|
|
347
|
+
{
|
|
348
|
+
"id": 5, "op": "quantized_matmul", "name": "projected",
|
|
349
|
+
"inputs": ["input:0", "node:0", "node:1", "node:2"], "parameters": [],
|
|
350
|
+
"attributes": {"group_size": 32, "bits": 4, "mode": "affine"},
|
|
351
|
+
},
|
|
352
|
+
node(6, "mul", json!(["node:5", "node:4"]), json!([])),
|
|
353
|
+
node(7, "mean", json!(["node:6"]), json!([])),
|
|
354
|
+
],
|
|
355
|
+
"outputs": {"loss": "node:7"},
|
|
356
|
+
});
|
|
357
|
+
super::config(json!({"m": graph}), Value::Null, json!(["m"]))
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/// The numbers `proj` stands for, before quantization: row r in
|
|
361
|
+
/// `[-(r + 1) / D_OUT, (r + 1) / D_OUT]`, off the grid.
|
|
362
|
+
pub fn weight(rows: usize) -> Vec<f32> {
|
|
363
|
+
weight_sized(rows, D_IN)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
pub fn weight_sized(rows: usize, cols: usize) -> Vec<f32> {
|
|
367
|
+
(0..rows * cols)
|
|
368
|
+
.map(|i| {
|
|
369
|
+
let (r, c) = (i / cols, i % cols);
|
|
370
|
+
(r + 1) as f32 / rows as f32 * ((c as f32 * 0.37 + r as f32 * 1.3).sin())
|
|
371
|
+
})
|
|
372
|
+
.collect()
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/// Writes the file a published checkpoint of this model would be:
|
|
376
|
+
/// `proj` quantized, `head` as numbers, and `emb` as numbers or, as
|
|
377
|
+
/// mlx-lm publishes an embedding, quantized too. Returns the path.
|
|
378
|
+
pub fn file(dir: &std::path::Path, embedding_packed: bool) -> std::path::PathBuf {
|
|
379
|
+
let proj = Array::from_slice(&weight(D_OUT), &[D_OUT as i32, D_IN as i32]).unwrap();
|
|
380
|
+
let proj = quantize(proj, QUANTIZATION).unwrap();
|
|
381
|
+
let emb = Array::from_slice(&weight(EMB_ROWS), &[EMB_ROWS as i32, D_IN as i32]).unwrap();
|
|
382
|
+
let mut named = vec![
|
|
383
|
+
("proj.weight", proj.weight),
|
|
384
|
+
("proj.scales", proj.scales),
|
|
385
|
+
("proj.biases", proj.biases.unwrap()),
|
|
386
|
+
("head.weight", Array::from_slice(&[1.0f32; D_OUT], &[D_OUT as i32]).unwrap()),
|
|
387
|
+
];
|
|
388
|
+
if embedding_packed {
|
|
389
|
+
let packed = quantize(emb, QUANTIZATION).unwrap();
|
|
390
|
+
named.push(("emb.weight", packed.weight));
|
|
391
|
+
named.push(("emb.scales", packed.scales));
|
|
392
|
+
named.push(("emb.biases", packed.biases.unwrap()));
|
|
393
|
+
} else {
|
|
394
|
+
named.push(("emb.weight", emb));
|
|
395
|
+
}
|
|
396
|
+
let path = dir.join("model.safetensors");
|
|
397
|
+
Array::save_safetensors(named.iter().map(|(n, a)| (*n, a)), None, &path).unwrap();
|
|
398
|
+
path
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/// The file a bf16 checkpoint of this model is: `proj.weight` as
|
|
402
|
+
/// numbers, in bf16, with no scales beside it. Returns the path and
|
|
403
|
+
/// the array written, for what quantizing it should give.
|
|
404
|
+
pub fn file_bf16(dir: &std::path::Path) -> (std::path::PathBuf, Array) {
|
|
405
|
+
file_bf16_sized(dir, D_OUT, D_IN)
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
pub fn file_bf16_sized(dir: &std::path::Path, d_out: usize, d_in: usize) -> (std::path::PathBuf, Array) {
|
|
409
|
+
let proj = Array::from_slice(&weight_sized(d_out, d_in), &[d_out as i32, d_in as i32])
|
|
410
|
+
.unwrap()
|
|
411
|
+
.as_dtype(crate::mlxc::Dtype::Bfloat16)
|
|
412
|
+
.unwrap();
|
|
413
|
+
let emb = Array::from_slice(&weight_sized(EMB_ROWS, d_in), &[EMB_ROWS as i32, d_in as i32]).unwrap();
|
|
414
|
+
let named = [
|
|
415
|
+
("proj.weight", proj.clone()),
|
|
416
|
+
("head.weight", Array::from_slice(&vec![1.0f32; d_out], &[d_out as i32]).unwrap()),
|
|
417
|
+
("emb.weight", emb),
|
|
418
|
+
];
|
|
419
|
+
let path = dir.join("model.safetensors");
|
|
420
|
+
Array::save_safetensors(named.iter().map(|(n, a)| (*n, a)), None, &path).unwrap();
|
|
421
|
+
(path, proj)
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/// `n` linears of `[d_out, d_in]`, each held quantized and read by its
|
|
425
|
+
/// own `quantized_matmul`, summed, and a trainable head: a model with
|
|
426
|
+
/// enough weights that how a run opens it can be measured. Returns
|
|
427
|
+
/// the config and a bf16 file of it, quantized as it is read.
|
|
428
|
+
pub fn stack(dir: &std::path::Path, n: usize, d_out: usize, d_in: usize) -> (String, std::path::PathBuf) {
|
|
429
|
+
let mut parameters = Vec::new();
|
|
430
|
+
let mut nodes = Vec::new();
|
|
431
|
+
let mut sums: Option<usize> = None;
|
|
432
|
+
for i in 0..n {
|
|
433
|
+
let at = parameters.len();
|
|
434
|
+
parameters.push(typed(at, &format!("l{i}.weight"), json!([d_out, d_in * 4 / 32]), "u32", false));
|
|
435
|
+
parameters.push(typed(at + 1, &format!("l{i}.scales"), json!([d_out, d_in / 32]), "f32", false));
|
|
436
|
+
parameters.push(typed(at + 2, &format!("l{i}.biases"), json!([d_out, d_in / 32]), "f32", false));
|
|
437
|
+
for k in 0..3 {
|
|
438
|
+
nodes.push(node(nodes.len(), "parameter", json!([]), json!([at + k])));
|
|
439
|
+
}
|
|
440
|
+
let read = nodes.len() - 3;
|
|
441
|
+
nodes.push(json!({
|
|
442
|
+
"id": nodes.len(), "op": "quantized_matmul",
|
|
443
|
+
"inputs": ["input:0", format!("node:{read}"), format!("node:{}", read + 1), format!("node:{}", read + 2)],
|
|
444
|
+
"parameters": [], "attributes": {"group_size": 32, "bits": 4, "mode": "affine"},
|
|
445
|
+
}));
|
|
446
|
+
let product = nodes.len() - 1;
|
|
447
|
+
sums = Some(match sums {
|
|
448
|
+
None => product,
|
|
449
|
+
Some(so_far) => {
|
|
450
|
+
nodes.push(node(nodes.len(), "add", json!([format!("node:{so_far}"), format!("node:{product}")]), json!([])));
|
|
451
|
+
nodes.len() - 1
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
let head = parameters.len();
|
|
456
|
+
parameters.push(parameter(head, "head.weight", json!([d_out]), true));
|
|
457
|
+
nodes.push(node(nodes.len(), "parameter", json!([]), json!([head])));
|
|
458
|
+
let read_head = nodes.len() - 1;
|
|
459
|
+
nodes.push(node(nodes.len(), "mul", json!([format!("node:{}", sums.unwrap()), format!("node:{read_head}")]), json!([])));
|
|
460
|
+
let scaled = nodes.len() - 1;
|
|
461
|
+
nodes.push(node(nodes.len(), "mean", json!([format!("node:{scaled}")]), json!([])));
|
|
462
|
+
let loss = nodes.len() - 1;
|
|
463
|
+
let graph = json!({
|
|
464
|
+
"inputs": [input(0, "x", json!([null, d_in]), "f32")],
|
|
465
|
+
"parameters": parameters,
|
|
466
|
+
"nodes": nodes,
|
|
467
|
+
"outputs": {"loss": format!("node:{loss}")},
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
let weights: Vec<(String, Array)> = (0..n)
|
|
471
|
+
.map(|i| {
|
|
472
|
+
let w = Array::from_slice(&weight_sized(d_out, d_in), &[d_out as i32, d_in as i32])
|
|
473
|
+
.unwrap()
|
|
474
|
+
.as_dtype(crate::mlxc::Dtype::Bfloat16)
|
|
475
|
+
.unwrap();
|
|
476
|
+
(format!("l{i}.weight"), w)
|
|
477
|
+
})
|
|
478
|
+
.chain(std::iter::once((
|
|
479
|
+
"head.weight".to_string(),
|
|
480
|
+
Array::from_slice(&vec![1.0f32; d_out], &[d_out as i32]).unwrap(),
|
|
481
|
+
)))
|
|
482
|
+
.collect();
|
|
483
|
+
let path = dir.join("model.safetensors");
|
|
484
|
+
Array::save_safetensors(weights.iter().map(|(n, a)| (n.as_str(), a)), None, &path).unwrap();
|
|
485
|
+
(super::config(json!({"m": graph}), Value::Null, json!(["m"])), path)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/// The same, with `proj.weight` replaced by `proj`: a file that holds
|
|
489
|
+
/// the weight as numbers of some other shape.
|
|
490
|
+
pub fn file_with_proj(dir: &std::path::Path, proj: Array) -> std::path::PathBuf {
|
|
491
|
+
let emb = Array::from_slice(&weight(EMB_ROWS), &[EMB_ROWS as i32, D_IN as i32]).unwrap();
|
|
492
|
+
let named = [
|
|
493
|
+
("proj.weight", proj),
|
|
494
|
+
("head.weight", Array::from_slice(&[1.0f32; D_OUT], &[D_OUT as i32]).unwrap()),
|
|
495
|
+
("emb.weight", emb),
|
|
496
|
+
];
|
|
497
|
+
let path = dir.join("model.safetensors");
|
|
498
|
+
Array::save_safetensors(named.iter().map(|(n, a)| (*n, a)), None, &path).unwrap();
|
|
499
|
+
path
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/// The same file with `emb` replaced: what a file that is wrong in
|
|
503
|
+
/// one way looks like.
|
|
504
|
+
pub fn file_with(dir: &std::path::Path, emb: Vec<(&str, Array)>) -> std::path::PathBuf {
|
|
505
|
+
let proj = Array::from_slice(&weight(D_OUT), &[D_OUT as i32, D_IN as i32]).unwrap();
|
|
506
|
+
let proj = quantize(proj, QUANTIZATION).unwrap();
|
|
507
|
+
let mut named = vec![
|
|
508
|
+
("proj.weight", proj.weight),
|
|
509
|
+
("proj.scales", proj.scales),
|
|
510
|
+
("proj.biases", proj.biases.unwrap()),
|
|
511
|
+
("head.weight", Array::from_slice(&[1.0f32; D_OUT], &[D_OUT as i32]).unwrap()),
|
|
512
|
+
];
|
|
513
|
+
named.extend(emb);
|
|
514
|
+
let path = dir.join("model.safetensors");
|
|
515
|
+
Array::save_safetensors(named.iter().map(|(n, a)| (*n, a)), None, &path).unwrap();
|
|
516
|
+
path
|
|
517
|
+
}
|
|
518
|
+
}
|
data/engine/src/graph.rs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
//! The engine's view of a GraphConfig: exactly the canonical JSON the Ruby
|
|
2
|
+
//! side emits, deserialized with serde. The engine trusts the structural
|
|
3
|
+
//! validation done at build time and re-checks only what execution needs.
|
|
4
|
+
|
|
5
|
+
use std::collections::BTreeMap;
|
|
6
|
+
|
|
7
|
+
use serde::Deserialize;
|
|
8
|
+
|
|
9
|
+
#[derive(Deserialize)]
|
|
10
|
+
pub struct GraphConfig {
|
|
11
|
+
#[allow(dead_code)]
|
|
12
|
+
pub schema_version: u32,
|
|
13
|
+
/// Which meaning of the ops this was written against. Recorded in a
|
|
14
|
+
/// checkpoint, so a restore into a later engine can say what it is
|
|
15
|
+
/// reading rather than guess (docs/plan.md section 11.2).
|
|
16
|
+
#[serde(default)]
|
|
17
|
+
pub semantics_version: u32,
|
|
18
|
+
pub models: BTreeMap<String, Graph>,
|
|
19
|
+
pub objective: Option<Graph>,
|
|
20
|
+
/// Which models are differentiated. Everything else is frozen.
|
|
21
|
+
pub train: Vec<String>,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
#[derive(Deserialize)]
|
|
25
|
+
pub struct Graph {
|
|
26
|
+
pub inputs: Vec<InputSpec>,
|
|
27
|
+
pub parameters: Vec<ParameterSpec>,
|
|
28
|
+
pub nodes: Vec<NodeSpec>,
|
|
29
|
+
/// Named: {"logits": "node:12"}.
|
|
30
|
+
pub outputs: BTreeMap<String, String>,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
#[derive(Deserialize)]
|
|
34
|
+
pub struct InputSpec {
|
|
35
|
+
pub name: String,
|
|
36
|
+
/// Where the data comes from: {"batch": field} or
|
|
37
|
+
/// {"model": name, "output": name}.
|
|
38
|
+
pub source: BTreeMap<String, String>,
|
|
39
|
+
/// A null dimension is symbolic: it may differ from batch to batch.
|
|
40
|
+
pub shape: Vec<Option<i32>>,
|
|
41
|
+
#[allow(dead_code)]
|
|
42
|
+
pub dtype: String,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
impl InputSpec {
|
|
46
|
+
/// The batch field this input reads, if it reads one.
|
|
47
|
+
pub fn batch_field(&self) -> Option<&str> {
|
|
48
|
+
self.source.get("batch").map(String::as_str)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// The model and output this input reads, if it reads one.
|
|
52
|
+
pub fn model_output(&self) -> Option<(&str, &str)> {
|
|
53
|
+
match (self.source.get("model"), self.source.get("output")) {
|
|
54
|
+
(Some(model), Some(output)) => Some((model, output)),
|
|
55
|
+
_ => None,
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
#[derive(Deserialize)]
|
|
61
|
+
pub struct ParameterSpec {
|
|
62
|
+
pub path: String,
|
|
63
|
+
pub shape: Vec<i32>,
|
|
64
|
+
/// What the graph says this parameter is. An imported file may hold
|
|
65
|
+
/// another precision; this is the one the run trains in.
|
|
66
|
+
pub dtype: String,
|
|
67
|
+
/// How it starts when it comes from no file: {"type": "zeros"},
|
|
68
|
+
/// {"type": "normal", "std": 0.02}, and so on (`crate::init`).
|
|
69
|
+
pub initializer: serde_json::Map<String, serde_json::Value>,
|
|
70
|
+
pub trainable: bool,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#[derive(Deserialize)]
|
|
74
|
+
pub struct NodeSpec {
|
|
75
|
+
pub id: usize,
|
|
76
|
+
pub op: String,
|
|
77
|
+
/// A stable path a tap can ask for ("layers.3.attn"), or none.
|
|
78
|
+
pub name: Option<String>,
|
|
79
|
+
pub inputs: Vec<String>,
|
|
80
|
+
pub parameters: Vec<usize>,
|
|
81
|
+
pub attributes: serde_json::Map<String, serde_json::Value>,
|
|
82
|
+
/// What the graph says this node produces. The Ruby side always
|
|
83
|
+
/// writes it; a hand-written graph may leave it out, and then nothing
|
|
84
|
+
/// is checked.
|
|
85
|
+
#[serde(default)]
|
|
86
|
+
pub dtype: Option<String>,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// "input:3" -> (Input, 3); "node:7" -> (Node, 7).
|
|
90
|
+
/// The digest a run is known by: SHA-256 of the description's bytes, as
|
|
91
|
+
/// the Ruby side sent them. One function, because a plan records it and a
|
|
92
|
+
/// checkpoint is checked against it, and the two must never disagree about
|
|
93
|
+
/// which bytes they hashed.
|
|
94
|
+
pub fn digest(graph_json: &str) -> String {
|
|
95
|
+
use sha2::{Digest, Sha256};
|
|
96
|
+
format!("{:x}", Sha256::digest(graph_json.as_bytes()))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
#[derive(Clone, Copy, Debug)]
|
|
100
|
+
pub enum Ref {
|
|
101
|
+
Input(usize),
|
|
102
|
+
Node(usize),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
pub fn parse_ref(text: &str) -> anyhow::Result<Ref> {
|
|
106
|
+
let (kind, id) = text
|
|
107
|
+
.split_once(':')
|
|
108
|
+
.ok_or_else(|| anyhow::anyhow!("bad reference {text:?}"))?;
|
|
109
|
+
let id: usize = id.parse()?;
|
|
110
|
+
match kind {
|
|
111
|
+
"input" => Ok(Ref::Input(id)),
|
|
112
|
+
"node" => Ok(Ref::Node(id)),
|
|
113
|
+
other => anyhow::bail!("bad reference kind {other:?}"),
|
|
114
|
+
}
|
|
115
|
+
}
|