torobi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +71 -0
  3. data/Cargo.lock +539 -0
  4. data/Cargo.toml +6 -0
  5. data/LICENSE +21 -0
  6. data/README.md +259 -0
  7. data/config/ops.yml +230 -0
  8. data/docs/plan.md +3982 -0
  9. data/docs/vendoring.md +656 -0
  10. data/engine/Cargo.toml +35 -0
  11. data/engine/build.rs +253 -0
  12. data/engine/src/checkpoint.rs +513 -0
  13. data/engine/src/executor.rs +257 -0
  14. data/engine/src/export.rs +431 -0
  15. data/engine/src/fixtures.rs +518 -0
  16. data/engine/src/graph.rs +115 -0
  17. data/engine/src/init.rs +65 -0
  18. data/engine/src/interp.rs +985 -0
  19. data/engine/src/lib.rs +62 -0
  20. data/engine/src/main.rs +97 -0
  21. data/engine/src/memory.rs +109 -0
  22. data/engine/src/mlxc/array.rs +454 -0
  23. data/engine/src/mlxc/error.rs +205 -0
  24. data/engine/src/mlxc/fast.rs +46 -0
  25. data/engine/src/mlxc/handle.rs +155 -0
  26. data/engine/src/mlxc/io.rs +268 -0
  27. data/engine/src/mlxc/memory.rs +56 -0
  28. data/engine/src/mlxc/metal.rs +24 -0
  29. data/engine/src/mlxc/mod.rs +55 -0
  30. data/engine/src/mlxc/nn.rs +38 -0
  31. data/engine/src/mlxc/ops.rs +477 -0
  32. data/engine/src/mlxc/quantized.rs +405 -0
  33. data/engine/src/mlxc/random.rs +161 -0
  34. data/engine/src/mlxc/transforms.rs +439 -0
  35. data/engine/src/op.rs +745 -0
  36. data/engine/src/optimizer.rs +650 -0
  37. data/engine/src/plan.rs +1638 -0
  38. data/engine/src/runtime.rs +377 -0
  39. data/engine/src/session.rs +1523 -0
  40. data/engine/src/state.rs +1007 -0
  41. data/engine/src/tensor.rs +331 -0
  42. data/ext/torobi/Cargo.toml +21 -0
  43. data/ext/torobi/extconf.rb +42 -0
  44. data/ext/torobi/src/gvl.rs +182 -0
  45. data/ext/torobi/src/lib.rs +1037 -0
  46. data/lib/torobi/adapter_file.rb +184 -0
  47. data/lib/torobi/batch.rb +55 -0
  48. data/lib/torobi/checkpoint.rb +60 -0
  49. data/lib/torobi/dsl/builder.rb +414 -0
  50. data/lib/torobi/dsl/handle.rb +156 -0
  51. data/lib/torobi/dsl/layers.rb +82 -0
  52. data/lib/torobi/dsl.rb +35 -0
  53. data/lib/torobi/errors.rb +88 -0
  54. data/lib/torobi/export.rb +534 -0
  55. data/lib/torobi/freeze.rb +24 -0
  56. data/lib/torobi/freshness.rb +57 -0
  57. data/lib/torobi/grad_cache.rb +143 -0
  58. data/lib/torobi/graph_config.rb +301 -0
  59. data/lib/torobi/hooks.rb +439 -0
  60. data/lib/torobi/ir/dimensions.rb +26 -0
  61. data/lib/torobi/ir/dtype.rb +28 -0
  62. data/lib/torobi/ir/graph/check.rb +116 -0
  63. data/lib/torobi/ir/graph.rb +52 -0
  64. data/lib/torobi/ir/input_spec.rb +39 -0
  65. data/lib/torobi/ir/json.rb +45 -0
  66. data/lib/torobi/ir/node_spec.rb +52 -0
  67. data/lib/torobi/ir/parameter_spec.rb +67 -0
  68. data/lib/torobi/ir/ref.rb +52 -0
  69. data/lib/torobi/ir/source.rb +65 -0
  70. data/lib/torobi/ir.rb +23 -0
  71. data/lib/torobi/journal.rb +310 -0
  72. data/lib/torobi/lora.rb +190 -0
  73. data/lib/torobi/memory.rb +50 -0
  74. data/lib/torobi/metallib.rb +50 -0
  75. data/lib/torobi/mlx_prebuilt.json +24 -0
  76. data/lib/torobi/mlx_prebuilt.rb +378 -0
  77. data/lib/torobi/models/build.rb +37 -0
  78. data/lib/torobi/models/description.rb +59 -0
  79. data/lib/torobi/models/gemma3.rb +273 -0
  80. data/lib/torobi/models/llama.rb +381 -0
  81. data/lib/torobi/models/modern_bert.rb +513 -0
  82. data/lib/torobi/models/padding.rb +27 -0
  83. data/lib/torobi/models/windows.rb +53 -0
  84. data/lib/torobi/ops.rb +81 -0
  85. data/lib/torobi/preflight.rb +136 -0
  86. data/lib/torobi/provenance.rb +75 -0
  87. data/lib/torobi/quantization.rb +151 -0
  88. data/lib/torobi/replay.rb +229 -0
  89. data/lib/torobi/runner.rb +419 -0
  90. data/lib/torobi/session.rb +855 -0
  91. data/lib/torobi/shape.rb +438 -0
  92. data/lib/torobi/tensor_data.rb +178 -0
  93. data/lib/torobi/version.rb +5 -0
  94. data/lib/torobi/weights.rb +108 -0
  95. data/lib/torobi.rb +67 -0
  96. data/licenses/MLX.txt +21 -0
  97. data/licenses/README.md +16 -0
  98. data/licenses/gguflib.txt +21 -0
  99. data/licenses/mlx-c.txt +21 -0
  100. data/licenses/mlx-rs.txt +27 -0
  101. metadata +229 -0
@@ -0,0 +1,257 @@
1
+ //! Running a plan: forward, and forward-with-gradients.
2
+ //!
3
+ //! Nothing here is stateful. Every function takes the plan, the current
4
+ //! parameters and the step's bound inputs, and returns values; what to do
5
+ //! with them is [`crate::state::TrainState`]'s business. Keeping the two
6
+ //! apart is what makes the transaction in `advance` reviewable: this file
7
+ //! decides what the numbers are, that one decides when they become real.
8
+
9
+ use std::collections::BTreeMap;
10
+
11
+ use anyhow::Result;
12
+ use crate::mlxc::error::Exception;
13
+ use crate::mlxc::transforms::{eval, value_and_grad_with_argnums};
14
+ use crate::mlxc::Array;
15
+
16
+ use crate::interp::{self, Taps, Tapped, Watch};
17
+ use crate::op::{Program, OBJECTIVE};
18
+ use crate::plan::{Model, Plan};
19
+ use crate::state::Pass;
20
+
21
+ /// What the models produced, by model and output name.
22
+ pub type Produced = BTreeMap<(String, String), Array>;
23
+
24
+ /// Runs the models and hands back what they produced.
25
+ ///
26
+ /// The objective does not run: what it produces is the loss, and this is
27
+ /// for a caller that wants a model's own output (an embedding, a set of
28
+ /// logits). No randomness, so it is the evaluation pass that `evaluate`
29
+ /// is, and nothing here is stateful, so nothing about the run moves.
30
+ ///
31
+ /// The taps report it, as they report any pass, except the objective's:
32
+ /// what did not run has nothing to say.
33
+ pub fn produce(
34
+ plan: &Plan,
35
+ params: &[Array],
36
+ fields: &BTreeMap<String, Array>,
37
+ watch: &mut Watch<'_>,
38
+ ) -> Result<Produced> {
39
+ Ok(models(plan, params, fields, None, watch)?.0)
40
+ }
41
+
42
+ /// Every model, in order, each reading what the ones before it produced.
43
+ ///
44
+ /// The one loop both passes are made of. `rng` is the step's randomness
45
+ /// and the mode with it: a key means a training pass, and the key that
46
+ /// comes back is what is left for the objective. No key means an
47
+ /// evaluation, where the random ops stand aside.
48
+ fn models(
49
+ plan: &Plan,
50
+ params: &[Array],
51
+ fields: &BTreeMap<String, Array>,
52
+ rng: Option<&Array>,
53
+ watch: &mut Watch<'_>,
54
+ ) -> std::result::Result<(Produced, Option<Array>), Exception> {
55
+ let mut produced = Produced::new();
56
+ // One key per graph, split from the step's, so a model and the
57
+ // objective never draw the same numbers.
58
+ let mut key = rng.cloned();
59
+ for Model {
60
+ name,
61
+ program,
62
+ slice,
63
+ } in &plan.models
64
+ {
65
+ let inputs = resolve(program, fields, &produced, name)?;
66
+ let mine = match &key {
67
+ Some(current) => {
68
+ let (next, mine) = crate::mlxc::random::split(current, 2)?;
69
+ key = Some(next);
70
+ Some(mine)
71
+ }
72
+ None => None,
73
+ };
74
+ let values = interp::evaluate_tapped(
75
+ program,
76
+ &params[slice.clone()],
77
+ &inputs,
78
+ mine.as_ref(),
79
+ name,
80
+ watch,
81
+ )?;
82
+ for (output, value) in values {
83
+ produced.insert((name.clone(), output), value);
84
+ }
85
+ }
86
+ Ok((produced, key))
87
+ }
88
+
89
+ /// Runs every model, then the objective over their outputs.
90
+ ///
91
+ /// `rng` is both the randomness and the mode: a key means a training pass,
92
+ /// and no key means an evaluation, where the random ops stand aside (see
93
+ /// [`crate::interp::evaluate_tapped`]).
94
+ pub fn forward(
95
+ plan: &Plan,
96
+ params: &[Array],
97
+ fields: &BTreeMap<String, Array>,
98
+ rng: Option<&Array>,
99
+ watch: &mut Watch<'_>,
100
+ ) -> std::result::Result<Array, Exception> {
101
+ let fail = |what: String| Exception::custom(what);
102
+ let (outputs, key) = models(plan, params, fields, rng, watch)?;
103
+
104
+ let Some(objective) = plan.objective.as_ref() else {
105
+ // No objective: a single model's only output is the loss.
106
+ let mut values = outputs.into_values();
107
+ return values
108
+ .next()
109
+ .ok_or_else(|| fail("the model produced no output".into()));
110
+ };
111
+
112
+ let inputs = resolve(objective, fields, &outputs, OBJECTIVE)?;
113
+ let produced =
114
+ interp::evaluate_tapped(objective, &[], &inputs, key.as_ref(), OBJECTIVE, watch)?;
115
+ produced
116
+ .into_values()
117
+ .next()
118
+ .ok_or_else(|| fail("the objective produced no output".into()))
119
+ }
120
+
121
+ /// One graph's inputs, each read from its declared source.
122
+ fn resolve(
123
+ program: &Program,
124
+ fields: &BTreeMap<String, Array>,
125
+ outputs: &BTreeMap<(String, String), Array>,
126
+ where_: &str,
127
+ ) -> std::result::Result<BTreeMap<String, Array>, Exception> {
128
+ program
129
+ .inputs
130
+ .iter()
131
+ .map(|spec| {
132
+ let value = if let Some(field) = spec.batch_field() {
133
+ fields
134
+ .get(field)
135
+ .cloned()
136
+ .ok_or_else(|| Exception::custom(format!("{where_}: no batch field {field:?}")))?
137
+ } else {
138
+ let (model, output) = spec.model_output().ok_or_else(|| {
139
+ Exception::custom(format!("{where_}: input {:?} has no source", spec.name))
140
+ })?;
141
+ outputs
142
+ .get(&(model.to_string(), output.to_string()))
143
+ .cloned()
144
+ .ok_or_else(|| {
145
+ Exception::custom(format!(
146
+ "{where_}: {model}.{output} has not been produced; \
147
+ a model must be declared before what reads it"
148
+ ))
149
+ })?
150
+ };
151
+ Ok((spec.name.clone(), value))
152
+ })
153
+ .collect()
154
+ }
155
+
156
+ /// The loss and its gradients, and what the taps saw on the way.
157
+ ///
158
+ /// The taps are collected from a forward pass of their own rather than
159
+ /// from inside `value_and_grad`: a traced pass produces values that
160
+ /// belong to the trace, and reading them out is not what a tap means.
161
+ /// The cost is one forward per step while a tap is on, which is why
162
+ /// taps are opt-in.
163
+ pub fn differentiate(
164
+ plan: &Plan,
165
+ pass: Pass<'_>,
166
+ fields: &BTreeMap<String, Array>,
167
+ taps: &Taps,
168
+ ) -> Result<(Array, Vec<Array>, Tapped)> {
169
+ let rng = pass.rng;
170
+ let fun = |ps: &[Array]| -> std::result::Result<Vec<Array>, Exception> {
171
+ let mut inner = Tapped::new();
172
+ forward(plan, ps, fields, Some(rng), &mut Watch::none(&mut inner)).map(|loss| vec![loss])
173
+ };
174
+ let mut vg = value_and_grad_with_argnums(fun, pass.argnums);
175
+ let (mut values, grads) = vg(pass.params)?;
176
+ let loss = values.remove(0);
177
+ eval(std::iter::once(&loss).chain(grads.iter()))?;
178
+
179
+ let mut collected = Tapped::new();
180
+ if !taps.is_empty() {
181
+ forward(
182
+ plan,
183
+ pass.params,
184
+ fields,
185
+ Some(rng),
186
+ &mut Watch::new(taps, &mut collected),
187
+ )?;
188
+ eval(collected.values())?;
189
+ }
190
+ Ok((loss, grads, collected))
191
+ }
192
+
193
+ /// The loss and its gradients with respect to named batch fields, rather
194
+ /// than to the parameters.
195
+ ///
196
+ /// What a gradient cache is defined in terms of: the loss over
197
+ /// representations that were computed elsewhere, differentiated with
198
+ /// respect to those representations, so the parts that produced them can
199
+ /// be re-run with the answer as their seed.
200
+ ///
201
+ /// No randomness, for the same reason [`evaluate`] draws none: this is
202
+ /// read as a value, and a draw would make it a sample of one. Taps are not
203
+ /// collected either; a caller that wants to watch this pass evaluates it.
204
+ pub fn differentiate_fields(
205
+ plan: &Plan,
206
+ params: &[Array],
207
+ fields: &BTreeMap<String, Array>,
208
+ of: &[String],
209
+ ) -> Result<(Array, Vec<Array>)> {
210
+ let mut missing = of.iter().filter(|name| !fields.contains_key(*name));
211
+ if let Some(name) = missing.next() {
212
+ anyhow::bail!(
213
+ "{name:?} is not in this batch, so there is nothing to differentiate by \
214
+ (this batch has {:?})",
215
+ fields.keys().collect::<Vec<_>>()
216
+ );
217
+ }
218
+
219
+ let given: Vec<Array> = of.iter().map(|name| fields[name].clone()).collect();
220
+ let fun = |xs: &[Array]| -> std::result::Result<Vec<Array>, Exception> {
221
+ let mut all = fields.clone();
222
+ for (name, x) in of.iter().zip(xs) {
223
+ all.insert(name.clone(), x.clone());
224
+ }
225
+ let mut inner = Tapped::new();
226
+ forward(plan, params, &all, None, &mut Watch::none(&mut inner)).map(|loss| vec![loss])
227
+ };
228
+ let argnums: Vec<i32> = (0..of.len() as i32).collect();
229
+ let mut vg = value_and_grad_with_argnums(fun, &argnums);
230
+ let (mut values, grads) = vg(&given)?;
231
+ let loss = values.remove(0);
232
+ eval(std::iter::once(&loss).chain(grads.iter()))?;
233
+ Ok((loss, grads))
234
+ }
235
+
236
+ /// The loss for one batch, without gradients and without randomness.
237
+ ///
238
+ /// What a validation set is read with. Running `differentiate` and throwing
239
+ /// the gradients away would pay for a backward pass nobody asked for, and
240
+ /// would sample dropout, which would make the number noise.
241
+ pub fn evaluate(
242
+ plan: &Plan,
243
+ params: &[Array],
244
+ fields: &BTreeMap<String, Array>,
245
+ taps: &Taps,
246
+ ) -> Result<(Array, Tapped)> {
247
+ let mut collected = Tapped::new();
248
+ let loss = forward(
249
+ plan,
250
+ params,
251
+ fields,
252
+ None,
253
+ &mut Watch::new(taps, &mut collected),
254
+ )?;
255
+ eval(std::iter::once(&loss).chain(collected.values()))?;
256
+ Ok((loss, collected))
257
+ }
@@ -0,0 +1,431 @@
1
+ //! A model's parameters in the layout a published checkpoint has, for a
2
+ //! serving consumer (docs/plan.md section 15.44).
3
+ //!
4
+ //! Not a checkpoint. A checkpoint is the run's record: optimizer state, the
5
+ //! RNG and the counters, under the run's own names. This is one model's
6
+ //! parameters under the names the published model uses, in fp32, with the
7
+ //! header a loader looks for, and nothing about the run. It reads the
8
+ //! parameters and touches nothing else, which is why it is not the
9
+ //! training state's business.
10
+ //!
11
+ //! Two things a published model does not have are folded away on the way
12
+ //! out (docs/qlora.md section 3.6). A weight held packed (`u32`, with its
13
+ //! scales and biases) is written as the numbers it stands for, and the
14
+ //! scales and biases are not written. An adapter (`lora_A`, `lora_B`
15
+ //! beside a weight) is merged into that weight, `W + scale · B A`, when
16
+ //! the caller says what the scale is, and refused otherwise: the base of
17
+ //! an adapted run never moved, and writing it alone would be a model that
18
+ //! looks trained and is not. [`write_adapter`] is the other shape a
19
+ //! fine-tune through an adapter produces: the adapter alone, named as
20
+ //! PEFT names it.
21
+
22
+ use std::collections::BTreeMap;
23
+ use std::path::Path;
24
+
25
+ use anyhow::{Context, Result};
26
+
27
+ use crate::mlxc::quantized::dequantize;
28
+ use crate::mlxc::transforms::eval;
29
+ use crate::mlxc::{Array, Dtype};
30
+ use crate::plan::{Model, Plan};
31
+
32
+ /// What an adapter's two matrices are called beside the weight they
33
+ /// adapt, as PEFT spells them and as `Torobi::LoRA` declares them.
34
+ const LORA_A: &str = ".lora_A.weight";
35
+ const LORA_B: &str = ".lora_B.weight";
36
+ /// The rows an adapter trains of an embedding table or an output layer (`trainable_token_indices`
37
+ /// in PEFT's terms). They are written into the table by whoever merges, before the model is
38
+ /// written, and are not a tensor of the published model.
39
+ const TOKEN_DELTA: &str = ".trainable_tokens_delta";
40
+
41
+ /// Where PEFT puts a module's path when it saves an adapter: under the
42
+ /// model it wraps.
43
+ const PEFT_PREFIX: &str = "base_model.model.";
44
+
45
+ /// Writes one model's parameters to `dir` as an HF-compatible fp32
46
+ /// safetensors checkpoint (or as bf16 or f16: [`write_as`]). The GraphConfig model name is stripped from
47
+ /// each qualified path, so a model declared with `encoder_prefix:`
48
+ /// keeps that prefix and the file's keys match the published layout.
49
+ ///
50
+ /// `merge` is the adapter's scale (`alpha / rank`), when the run holds
51
+ /// one and the caller wants it folded into the weights; without it, an
52
+ /// adapted run is refused. A packed weight is written as its numbers
53
+ /// either way.
54
+ ///
55
+ /// Returns the (old, new) path pairs so the caller can write metadata
56
+ /// that names what was saved. Parameters folded away (an adapter's
57
+ /// matrices, a packed weight's scales and biases) are not in it.
58
+ pub fn write(plan: &Plan, params: &[Array], model: &str, dir: &str, merge: Option<f32>) -> Result<Vec<(String, String)>> {
59
+ write_as(plan, params, model, dir, merge, Dtype::Float32)
60
+ }
61
+
62
+ /// [`write`], with the weights stored as `dtype` (f32, bf16 or f16). A merge is computed in f32 and
63
+ /// rounded once, to what the file holds: a checkpoint published in bf16 is read back as bf16, at
64
+ /// half the size of the f32 it would otherwise be (7B parameters: 15 GB against 30).
65
+ pub fn write_as(
66
+ plan: &Plan,
67
+ params: &[Array],
68
+ model: &str,
69
+ dir: &str,
70
+ merge: Option<f32>,
71
+ dtype: Dtype,
72
+ ) -> Result<Vec<(String, String)>> {
73
+ anyhow::ensure!(
74
+ matches!(dtype, Dtype::Float32 | Dtype::Bfloat16 | Dtype::Float16),
75
+ "a model is written as f32, bf16 or f16, not {dtype:?}"
76
+ );
77
+ let model = find(plan, model)?;
78
+ let mut owned = published(plan, params, model, merge)?;
79
+ if dtype != Dtype::Float32 {
80
+ for (_, _, array) in owned.iter_mut() {
81
+ *array = array.as_dtype(dtype)?;
82
+ }
83
+ eval(owned.iter().map(|(_, _, a)| a))?;
84
+ }
85
+ save(dir, "model.safetensors", owned)
86
+ }
87
+
88
+ /// A dtype by the name Ruby gives it.
89
+ pub fn dtype_named(name: &str) -> Result<Dtype> {
90
+ Ok(match name {
91
+ "f32" => Dtype::Float32,
92
+ "bf16" => Dtype::Bfloat16,
93
+ "f16" => Dtype::Float16,
94
+ other => anyhow::bail!("a model is written as f32, bf16 or f16, not {other:?}"),
95
+ })
96
+ }
97
+
98
+ /// Writes one model's adapter alone, as PEFT saves one: the `lora_A` and
99
+ /// `lora_B` of every adapted linear under `base_model.model.`, in fp32,
100
+ /// in `adapter_model.safetensors`. The `adapter_config.json` beside it
101
+ /// is the caller's (docs/qlora.md section 3.6): it says what the graph
102
+ /// said (`r`, `lora_alpha`, `target_modules`), and the graph is Ruby's.
103
+ ///
104
+ /// Refused when the model holds no adapter: a file with no tensors
105
+ /// would load as an adapter that changes nothing.
106
+ pub fn write_adapter(plan: &Plan, params: &[Array], model: &str, dir: &str) -> Result<Vec<(String, String)>> {
107
+ let model = find(plan, model)?;
108
+ let prefix = format!("{}.", model.name);
109
+ let owned: Vec<(String, String, Array)> = plan.paths[model.slice.clone()]
110
+ .iter()
111
+ .zip(&params[model.slice.clone()])
112
+ .filter(|(path, _)| path.ends_with(LORA_A) || path.ends_with(LORA_B))
113
+ .map(|(path, array)| {
114
+ let own = path.strip_prefix(&prefix).unwrap_or(path);
115
+ Ok((path.clone(), format!("{PEFT_PREFIX}{own}"), f32s(array)?))
116
+ })
117
+ .collect::<Result<_>>()?;
118
+ anyhow::ensure!(
119
+ !owned.is_empty(),
120
+ "model {:?} holds no adapter (no parameter ends in {LORA_A} or {LORA_B}), so there \
121
+ is no adapter to write; export_model writes the model itself",
122
+ model.name
123
+ );
124
+ eval(owned.iter().map(|(_, _, a)| a))?;
125
+ save(dir, "adapter_model.safetensors", owned)
126
+ }
127
+
128
+ fn find<'a>(plan: &'a Plan, model: &str) -> Result<&'a Model> {
129
+ plan.models.iter().find(|m| m.name == model).with_context(|| {
130
+ format!(
131
+ "no model named {model:?} (this run has {:?})",
132
+ plan.models.iter().map(|m| &m.name).collect::<Vec<_>>()
133
+ )
134
+ })
135
+ }
136
+
137
+ fn f32s(array: &Array) -> Result<Array> {
138
+ Ok(if array.dtype() == Dtype::Float32 {
139
+ array.clone()
140
+ } else {
141
+ array.as_dtype(Dtype::Float32)?
142
+ })
143
+ }
144
+
145
+ /// Writes `owned` ((old path, new path, array)) to `dir/name` with the
146
+ /// header a loader looks for, reads it back, and returns the renaming.
147
+ fn save(dir: &str, name: &str, owned: Vec<(String, String, Array)>) -> Result<Vec<(String, String)>> {
148
+ let dir = Path::new(dir);
149
+ std::fs::create_dir_all(dir)
150
+ .with_context(|| format!("creating {}", dir.display()))?;
151
+ // `{"format": "pt"}`, which is what a published checkpoint carries
152
+ // and what a loader looks for: transformers reads the metadata and
153
+ // refuses a file whose format it does not recognize. The bytes are
154
+ // plain little-endian f32 in reading order, which is what "pt"
155
+ // describes; the word names a layout, not a framework that wrote
156
+ // it.
157
+ let metadata = std::collections::HashMap::from([
158
+ ("format".to_string(), "pt".to_string()),
159
+ ]);
160
+ let file = dir.join(name);
161
+ Array::save_safetensors(
162
+ owned.iter().map(|(_, path, array)| (path.as_str(), array)),
163
+ &metadata,
164
+ &file,
165
+ )
166
+ .with_context(|| format!("writing {name}"))?;
167
+
168
+ // Read back before saying it is written, for the reason a
169
+ // checkpoint does (docs/plan.md section 15.27): a file that does
170
+ // not load is worse than no file, and finding out here costs one
171
+ // read of what was just written.
172
+ let read = Array::load_safetensors(&file)
173
+ .context("the export just written does not read back")?;
174
+ for (_, path, _) in &owned {
175
+ anyhow::ensure!(
176
+ read.contains_key(path.as_str()),
177
+ "the export just written has no {path:?}"
178
+ );
179
+ }
180
+ anyhow::ensure!(
181
+ read.len() == owned.len(),
182
+ "the export just written holds {} tensors and {} were saved",
183
+ read.len(),
184
+ owned.len()
185
+ );
186
+ Ok(owned.into_iter().map(|(old, new, _)| (old, new)).collect())
187
+ }
188
+
189
+ /// One model's parameters under the names a published checkpoint uses,
190
+ /// in fp32, with what a published model does not have folded away.
191
+ ///
192
+ /// Pure: it decides what would be written and touches no disk, so what
193
+ /// goes in a file can be looked at without making one. The model's own
194
+ /// name is stripped, so a model declared with `encoder_prefix:` keeps
195
+ /// that prefix and the keys line up with the published layout.
196
+ ///
197
+ /// A packed weight becomes the numbers it stands for, and its scales and
198
+ /// biases are left out. An adapter's `B A`, times `merge`, is added to
199
+ /// the weight it sits beside, and its two matrices are left out; an
200
+ /// adapter with no `merge` is refused.
201
+ fn published(plan: &Plan, params: &[Array], model: &Model, merge: Option<f32>) -> Result<Vec<(String, String, Array)>> {
202
+ let prefix = format!("{}.", model.name);
203
+ let slice = model.slice.clone();
204
+ let index_of = |path: &str| plan.index_of(path).filter(|i| slice.contains(i));
205
+
206
+ // The adapters, by the weight each one sits beside.
207
+ let mut adapters: BTreeMap<String, (usize, usize)> = BTreeMap::new();
208
+ for path in &plan.paths[slice.clone()] {
209
+ let Some(name) = path.strip_suffix(LORA_A) else {
210
+ continue;
211
+ };
212
+ let b = index_of(&format!("{name}{LORA_B}"))
213
+ .with_context(|| format!("{path:?} has no {name}{LORA_B} beside it: half an adapter"))?;
214
+ adapters.insert(format!("{name}.weight"), (index_of(path).expect("its own path"), b));
215
+ }
216
+ if let (Some((path, _)), None) = (adapters.iter().next(), merge) {
217
+ anyhow::bail!(
218
+ "model {:?} was trained through an adapter ({} weights like {path:?} have lora_A and \
219
+ lora_B beside them), and its base weights have not moved. Writing them alone would be \
220
+ a model that looks trained and is not: say the adapter's scale to merge it in, or \
221
+ write the adapter by itself (export_adapter)",
222
+ model.name,
223
+ adapters.len()
224
+ );
225
+ }
226
+
227
+ // What a packed weight's scales and biases are read by, so they can
228
+ // be left out: every one of them belongs to a weight in `packed`.
229
+ let folded: std::collections::HashSet<usize> = plan
230
+ .packed
231
+ .iter()
232
+ .filter(|(weight, _)| slice.contains(weight))
233
+ .flat_map(|(_, packed)| std::iter::once(packed.scales).chain(packed.biases))
234
+ .collect();
235
+
236
+ let mut owned = Vec::new();
237
+ for (i, path) in plan.paths[slice.clone()].iter().enumerate() {
238
+ let index = slice.start + i;
239
+ if path.ends_with(LORA_A) || path.ends_with(LORA_B) || path.ends_with(TOKEN_DELTA) || folded.contains(&index) {
240
+ continue;
241
+ }
242
+ let array = &params[index];
243
+ let mut value = if array.dtype() == Dtype::Uint32 {
244
+ let packed = plan.packed.get(&index).with_context(|| {
245
+ format!("parameter {path:?} is a packed u32 weight that no quantized_matmul reads")
246
+ })?;
247
+ dequantize(
248
+ array,
249
+ &params[packed.scales],
250
+ packed.biases.map(|b| &params[b]),
251
+ packed.quantization,
252
+ Some(Dtype::Float32),
253
+ )?
254
+ } else {
255
+ f32s(array)?
256
+ };
257
+ if let (Some(&(a, b)), Some(scale)) = (adapters.get(path), merge) {
258
+ // W + scale · B A, in f32: A is [rank, d_in], B is [d_out, rank],
259
+ // so B A is the weight's own [d_out, d_in].
260
+ let delta = f32s(&params[b])?.matmul(f32s(&params[a])?)?.multiply(Array::from_f32(scale)?)?;
261
+ value = value.add(&delta)?;
262
+ }
263
+ owned.push((path.clone(), path.strip_prefix(&prefix).unwrap_or(path).to_string(), value));
264
+ }
265
+ eval(owned.iter().map(|(_, _, a)| a))?;
266
+ Ok(owned)
267
+ }
268
+
269
+ #[cfg(test)]
270
+ mod tests {
271
+ use super::*;
272
+ use crate::fixtures;
273
+ use crate::plan::Weights;
274
+ use crate::tensor::{to_tensor, Values};
275
+
276
+ /// A quantized base is exported as the numbers its words stand for,
277
+ /// in the weight's own shape, and its scales and biases stay behind:
278
+ /// what comes out is a model a plain loader reads.
279
+ #[test]
280
+ fn a_quantized_model_exports_the_numbers_its_weights_stand_for() {
281
+ use fixtures::quantized::{weight, D_IN, D_OUT};
282
+ let dir = tempfile::tempdir().unwrap();
283
+ let files = std::collections::BTreeMap::from([("m".to_string(), fixtures::quantized::file(dir.path(), false))]);
284
+ let (plan, params) =
285
+ Plan::open(&fixtures::quantized::config(), Weights::Pretrained { files: &files, fresh: &[] }).unwrap();
286
+ let out = dir.path().join("out");
287
+ let renamed = write(&plan, &params, "m", out.to_str().unwrap(), None).unwrap();
288
+ assert_eq!(
289
+ renamed,
290
+ vec![
291
+ ("m.proj.weight".to_string(), "proj.weight".to_string()),
292
+ ("m.emb.weight".to_string(), "emb.weight".to_string()),
293
+ ("m.head.weight".to_string(), "head.weight".to_string()),
294
+ ]
295
+ );
296
+ let arrays = Array::load_safetensors(out.join("model.safetensors")).unwrap();
297
+ assert_eq!(arrays.len(), 3, "no scales, no biases");
298
+ let proj = &arrays["proj.weight"];
299
+ assert_eq!(proj.dtype(), Dtype::Float32);
300
+ assert_eq!(proj.shape(), &[D_OUT as i32, D_IN as i32]);
301
+ for (got, want) in values(proj).iter().zip(weight(D_OUT)) {
302
+ assert!((got - want).abs() <= 2.0 / 15.0, "{got} for {want}");
303
+ }
304
+ }
305
+
306
+ /// An adapted run is refused without a scale, and with one its
307
+ /// adapter is folded into the weight it sits beside: `W + scale · B A`,
308
+ /// the matrices themselves left out. Hand arithmetic: W = [0.5, -1],
309
+ /// A = [1, 2], B = [3], scale 2 gives [6.5, 11].
310
+ #[test]
311
+ fn an_adapter_is_merged_into_its_weight_when_the_scale_is_said() {
312
+ let (plan, params) = open(fixtures::adapted());
313
+ let dir = tempfile::tempdir().unwrap();
314
+ let out = dir.path().join("out");
315
+
316
+ let said = write(&plan, &params, "m", out.to_str().unwrap(), None).unwrap_err().to_string();
317
+ assert!(said.contains("trained through an adapter"), "{said}");
318
+ assert!(said.contains("\"m.l.weight\""), "{said}");
319
+ assert!(!out.join("model.safetensors").exists());
320
+
321
+ let renamed = write(&plan, &params, "m", out.to_str().unwrap(), Some(2.0)).unwrap();
322
+ assert_eq!(renamed, vec![("m.l.weight".to_string(), "l.weight".to_string())]);
323
+ let arrays = Array::load_safetensors(out.join("model.safetensors")).unwrap();
324
+ assert_eq!(arrays.len(), 1);
325
+ assert_eq!(values(&arrays["l.weight"]), vec![6.5, 11.0]);
326
+ }
327
+
328
+ /// The same weights stored as bf16 or f16: the dtype the file says, and the numbers rounded
329
+ /// once. 6.5 is exact in both; 0.1 is not, and comes back as what the type holds.
330
+ #[test]
331
+ fn a_model_is_written_as_the_dtype_asked_for() {
332
+ let (plan, params) = open(fixtures::adapted());
333
+ let dir = tempfile::tempdir().unwrap();
334
+ for (name, dtype, exact) in [("bf16", Dtype::Bfloat16, true), ("f16", Dtype::Float16, true), ("f32", Dtype::Float32, true)] {
335
+ let out = dir.path().join(name);
336
+ write_as(&plan, &params, "m", out.to_str().unwrap(), Some(2.0), dtype_named(name).unwrap()).unwrap();
337
+ let arrays = Array::load_safetensors(out.join("model.safetensors")).unwrap();
338
+ assert_eq!(arrays["l.weight"].dtype(), dtype, "{name}");
339
+ let back = arrays["l.weight"].as_dtype(Dtype::Float32).unwrap();
340
+ assert_eq!(values(&back), vec![6.5, 11.0], "{name}: 6.5 and 11 are exact in it ({exact})");
341
+ }
342
+ assert!(dtype_named("f64").is_err());
343
+ assert!(dtype_named("int8").is_err());
344
+ }
345
+
346
+ /// The adapter alone, as PEFT saves one: both matrices of every
347
+ /// adapted linear, under `base_model.model.`, and nothing of the
348
+ /// base. A model with no adapter has none to write.
349
+ #[test]
350
+ fn an_adapter_is_written_as_peft_names_it() {
351
+ let (plan, params) = open(fixtures::adapted());
352
+ let dir = tempfile::tempdir().unwrap();
353
+ let out = dir.path().join("adapter");
354
+ let renamed = write_adapter(&plan, &params, "m", out.to_str().unwrap()).unwrap();
355
+ assert_eq!(
356
+ renamed,
357
+ vec![
358
+ ("m.l.lora_A.weight".to_string(), "base_model.model.l.lora_A.weight".to_string()),
359
+ ("m.l.lora_B.weight".to_string(), "base_model.model.l.lora_B.weight".to_string()),
360
+ ]
361
+ );
362
+ let arrays = Array::load_safetensors(out.join("adapter_model.safetensors")).unwrap();
363
+ assert_eq!(arrays.len(), 2);
364
+ assert_eq!(values(&arrays["base_model.model.l.lora_A.weight"]), vec![1.0, 2.0]);
365
+ assert_eq!(values(&arrays["base_model.model.l.lora_B.weight"]), vec![3.0]);
366
+
367
+ let (plan, params) = open(fixtures::scaled_mean());
368
+ let said = write_adapter(&plan, &params, "m", out.to_str().unwrap()).unwrap_err().to_string();
369
+ assert!(said.contains("holds no adapter"), "{said}");
370
+ }
371
+
372
+ fn open(which: (String, String)) -> (Plan, Vec<Array>) {
373
+ let (config, weights) = which;
374
+ Plan::open(&config, Weights::Inline(&weights)).unwrap()
375
+ }
376
+
377
+ fn values(array: &Array) -> Vec<f32> {
378
+ match to_tensor(array).unwrap().values {
379
+ Values::F32(v) => v,
380
+ Values::I32(v) => v.iter().map(|&i| i as f32).collect(),
381
+ }
382
+ }
383
+
384
+ #[test]
385
+ fn one_models_parameters_are_written_with_its_name_stripped() {
386
+ // student.scale exports as "scale": the GraphConfig model name is
387
+ // the one thing a serving consumer does not carry.
388
+ let (plan, params) = open(fixtures::teacher_and_student());
389
+ let dir = tempfile::tempdir().unwrap();
390
+ let export_to = dir.path().join("out").display().to_string();
391
+
392
+ let renamed = write(&plan, &params, "student", &export_to, None).unwrap();
393
+ assert_eq!(renamed, vec![("student.scale".to_string(), "scale".to_string())]);
394
+
395
+ let file = std::path::Path::new(&export_to).join("model.safetensors");
396
+ let arrays = Array::load_safetensors(&file).unwrap();
397
+ assert_eq!(arrays.len(), 1, "only the student's parameter is exported");
398
+ let array = &arrays["scale"];
399
+ assert_eq!(array.dtype(), Dtype::Float32);
400
+ assert_eq!(to_tensor(array).unwrap().shape, vec![2]);
401
+ let held = &params[plan.index_of("student.scale").unwrap()];
402
+ let (exported, held) = (values(array), values(held));
403
+ for (got, want) in exported.iter().zip(&held) {
404
+ assert!((got - want).abs() < 1e-6, "{exported:?} against {held:?}");
405
+ }
406
+ }
407
+
408
+ #[test]
409
+ fn an_export_says_what_format_it_is_in() {
410
+ // A loader reads this before the tensors, and refuses a file whose
411
+ // format it cannot name. A published checkpoint carries the same.
412
+ let (plan, params) = open(fixtures::teacher_and_student());
413
+ let dir = tempfile::tempdir().unwrap();
414
+ let out = dir.path().join("out");
415
+ write(&plan, &params, "student", &out.display().to_string(), None).unwrap();
416
+
417
+ let bytes = std::fs::read(out.join("model.safetensors")).unwrap();
418
+ let length = u64::from_le_bytes(bytes[0..8].try_into().unwrap()) as usize;
419
+ let header: serde_json::Value = serde_json::from_slice(&bytes[8..8 + length]).unwrap();
420
+
421
+ assert_eq!(header["__metadata__"]["format"], "pt");
422
+ }
423
+
424
+ #[test]
425
+ fn a_model_name_this_run_does_not_have_is_refused() {
426
+ let (plan, params) = open(fixtures::scaled_mean());
427
+ let dir = tempfile::tempdir().unwrap();
428
+ let e = write(&plan, &params, "elsewhere", &dir.path().display().to_string(), None).unwrap_err();
429
+ assert!(e.to_string().contains("no model named"), "{e}");
430
+ }
431
+ }