torobi 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +71 -0
- data/Cargo.lock +539 -0
- data/Cargo.toml +6 -0
- data/LICENSE +21 -0
- data/README.md +259 -0
- data/config/ops.yml +230 -0
- data/docs/plan.md +3982 -0
- data/docs/vendoring.md +656 -0
- data/engine/Cargo.toml +35 -0
- data/engine/build.rs +253 -0
- data/engine/src/checkpoint.rs +513 -0
- data/engine/src/executor.rs +257 -0
- data/engine/src/export.rs +431 -0
- data/engine/src/fixtures.rs +518 -0
- data/engine/src/graph.rs +115 -0
- data/engine/src/init.rs +65 -0
- data/engine/src/interp.rs +985 -0
- data/engine/src/lib.rs +62 -0
- data/engine/src/main.rs +97 -0
- data/engine/src/memory.rs +109 -0
- data/engine/src/mlxc/array.rs +454 -0
- data/engine/src/mlxc/error.rs +205 -0
- data/engine/src/mlxc/fast.rs +46 -0
- data/engine/src/mlxc/handle.rs +155 -0
- data/engine/src/mlxc/io.rs +268 -0
- data/engine/src/mlxc/memory.rs +56 -0
- data/engine/src/mlxc/metal.rs +24 -0
- data/engine/src/mlxc/mod.rs +55 -0
- data/engine/src/mlxc/nn.rs +38 -0
- data/engine/src/mlxc/ops.rs +477 -0
- data/engine/src/mlxc/quantized.rs +405 -0
- data/engine/src/mlxc/random.rs +161 -0
- data/engine/src/mlxc/transforms.rs +439 -0
- data/engine/src/op.rs +745 -0
- data/engine/src/optimizer.rs +650 -0
- data/engine/src/plan.rs +1638 -0
- data/engine/src/runtime.rs +377 -0
- data/engine/src/session.rs +1523 -0
- data/engine/src/state.rs +1007 -0
- data/engine/src/tensor.rs +331 -0
- data/ext/torobi/Cargo.toml +21 -0
- data/ext/torobi/extconf.rb +42 -0
- data/ext/torobi/src/gvl.rs +182 -0
- data/ext/torobi/src/lib.rs +1037 -0
- data/lib/torobi/adapter_file.rb +184 -0
- data/lib/torobi/batch.rb +55 -0
- data/lib/torobi/checkpoint.rb +60 -0
- data/lib/torobi/dsl/builder.rb +414 -0
- data/lib/torobi/dsl/handle.rb +156 -0
- data/lib/torobi/dsl/layers.rb +82 -0
- data/lib/torobi/dsl.rb +35 -0
- data/lib/torobi/errors.rb +88 -0
- data/lib/torobi/export.rb +534 -0
- data/lib/torobi/freeze.rb +24 -0
- data/lib/torobi/freshness.rb +57 -0
- data/lib/torobi/grad_cache.rb +143 -0
- data/lib/torobi/graph_config.rb +301 -0
- data/lib/torobi/hooks.rb +439 -0
- data/lib/torobi/ir/dimensions.rb +26 -0
- data/lib/torobi/ir/dtype.rb +28 -0
- data/lib/torobi/ir/graph/check.rb +116 -0
- data/lib/torobi/ir/graph.rb +52 -0
- data/lib/torobi/ir/input_spec.rb +39 -0
- data/lib/torobi/ir/json.rb +45 -0
- data/lib/torobi/ir/node_spec.rb +52 -0
- data/lib/torobi/ir/parameter_spec.rb +67 -0
- data/lib/torobi/ir/ref.rb +52 -0
- data/lib/torobi/ir/source.rb +65 -0
- data/lib/torobi/ir.rb +23 -0
- data/lib/torobi/journal.rb +310 -0
- data/lib/torobi/lora.rb +190 -0
- data/lib/torobi/memory.rb +50 -0
- data/lib/torobi/metallib.rb +50 -0
- data/lib/torobi/mlx_prebuilt.json +24 -0
- data/lib/torobi/mlx_prebuilt.rb +378 -0
- data/lib/torobi/models/build.rb +37 -0
- data/lib/torobi/models/description.rb +59 -0
- data/lib/torobi/models/gemma3.rb +273 -0
- data/lib/torobi/models/llama.rb +381 -0
- data/lib/torobi/models/modern_bert.rb +513 -0
- data/lib/torobi/models/padding.rb +27 -0
- data/lib/torobi/models/windows.rb +53 -0
- data/lib/torobi/ops.rb +81 -0
- data/lib/torobi/preflight.rb +136 -0
- data/lib/torobi/provenance.rb +75 -0
- data/lib/torobi/quantization.rb +151 -0
- data/lib/torobi/replay.rb +229 -0
- data/lib/torobi/runner.rb +419 -0
- data/lib/torobi/session.rb +855 -0
- data/lib/torobi/shape.rb +438 -0
- data/lib/torobi/tensor_data.rb +178 -0
- data/lib/torobi/version.rb +5 -0
- data/lib/torobi/weights.rb +108 -0
- data/lib/torobi.rb +67 -0
- data/licenses/MLX.txt +21 -0
- data/licenses/README.md +16 -0
- data/licenses/gguflib.txt +21 -0
- data/licenses/mlx-c.txt +21 -0
- data/licenses/mlx-rs.txt +27 -0
- metadata +229 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
//! Writing and reading a run's state.
|
|
2
|
+
//!
|
|
3
|
+
//! The format is the one docs/plan.md section 11.2 specifies:
|
|
4
|
+
//!
|
|
5
|
+
//! ```text
|
|
6
|
+
//! checkpoint/000042/
|
|
7
|
+
//! ├── manifest.json
|
|
8
|
+
//! ├── graph.json
|
|
9
|
+
//! ├── parameters.safetensors
|
|
10
|
+
//! ├── random.safetensors
|
|
11
|
+
//! └── optimizer.safetensors (absent for an optimizer with no slots)
|
|
12
|
+
//! ```
|
|
13
|
+
//!
|
|
14
|
+
//! Three rules give it its value. It is written to a temporary directory
|
|
15
|
+
//! and renamed into place, so an interrupted write leaves no
|
|
16
|
+
//! half-checkpoint. It is read back against the manifest (the config's
|
|
17
|
+
//! digest, every parameter's path, shape and dtype, the optimizer's kind)
|
|
18
|
+
//! so a mismatch is refused rather than silently absorbed. And it carries
|
|
19
|
+
//! the description itself, not only its digest: a digest names a
|
|
20
|
+
//! GraphConfig, it does not reconstruct one, and a checkpoint nobody can
|
|
21
|
+
//! read without the run that wrote it is a run checkpoint in name only.
|
|
22
|
+
//!
|
|
23
|
+
//! What the engine does not know is carried opaquely. Epoch, batch
|
|
24
|
+
//! position, sampler state and dataset identity belong to whoever owns the
|
|
25
|
+
//! data, which is never this crate (docs/plan.md section 5A.2); they
|
|
26
|
+
//! travel in `run`, which is written verbatim and handed back verbatim.
|
|
27
|
+
|
|
28
|
+
use std::collections::HashMap;
|
|
29
|
+
use std::path::{Path, PathBuf};
|
|
30
|
+
|
|
31
|
+
use anyhow::{Context, Result};
|
|
32
|
+
use crate::mlxc::Array;
|
|
33
|
+
use serde::{Deserialize, Serialize};
|
|
34
|
+
|
|
35
|
+
use crate::optimizer::{Config as OptimizerConfig, Moments, Optimizer};
|
|
36
|
+
use crate::plan::Plan;
|
|
37
|
+
use crate::tensor::dtype_spelling;
|
|
38
|
+
|
|
39
|
+
pub const SCHEMA_VERSION: u32 = 2;
|
|
40
|
+
|
|
41
|
+
/// The file the GraphConfig is written to, beside the manifest.
|
|
42
|
+
pub const GRAPH_FILE: &str = "graph.json";
|
|
43
|
+
|
|
44
|
+
/// What a checkpoint claims about itself. Everything here is checked on the
|
|
45
|
+
/// way back in.
|
|
46
|
+
#[derive(Serialize, Deserialize)]
|
|
47
|
+
pub struct Manifest {
|
|
48
|
+
pub schema_version: u32,
|
|
49
|
+
/// The GraphConfig this state belongs to. A checkpoint restored into a
|
|
50
|
+
/// different description is not a resumed run.
|
|
51
|
+
pub config_digest: String,
|
|
52
|
+
/// Which meaning of the ops the description was written against.
|
|
53
|
+
pub semantics_version: u32,
|
|
54
|
+
pub step: usize,
|
|
55
|
+
pub optimizer: OptimizerConfig,
|
|
56
|
+
/// Steps the optimizer has taken, which is not the same as `step` once
|
|
57
|
+
/// a run resumes: bias correction depends on it.
|
|
58
|
+
pub optimizer_steps: u64,
|
|
59
|
+
/// The seed the RNG was started from. The key itself is a tensor, and
|
|
60
|
+
/// lives in random.safetensors.
|
|
61
|
+
pub seed: u64,
|
|
62
|
+
pub parameters: Vec<ParameterEntry>,
|
|
63
|
+
pub build: serde_json::Value,
|
|
64
|
+
/// The machine this was written on.
|
|
65
|
+
pub platform: serde_json::Value,
|
|
66
|
+
/// Whatever the caller wanted recorded: epoch, batch position, sampler
|
|
67
|
+
/// state, dataset identity, the Ruby side's own versions. Not
|
|
68
|
+
/// interpreted here, and handed back unchanged on the way out.
|
|
69
|
+
#[serde(default)]
|
|
70
|
+
pub run: serde_json::Value,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#[derive(Serialize, Deserialize)]
|
|
74
|
+
pub struct ParameterEntry {
|
|
75
|
+
pub path: String,
|
|
76
|
+
pub shape: Vec<i32>,
|
|
77
|
+
/// Checked on the way back in: a parameter restored at another
|
|
78
|
+
/// precision is not the parameter that was saved.
|
|
79
|
+
pub dtype: String,
|
|
80
|
+
pub trained: bool,
|
|
81
|
+
/// Whether the parameter's values are in parameters.safetensors. A light
|
|
82
|
+
/// checkpoint keeps only the trained ones; the rest are what the
|
|
83
|
+
/// session was opened with, and restoring leaves them as they are.
|
|
84
|
+
#[serde(default = "saved_by_default")]
|
|
85
|
+
pub saved: bool,
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
fn saved_by_default() -> bool {
|
|
89
|
+
true
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// The state a checkpoint holds, on its way in or out.
|
|
93
|
+
pub struct State<'a> {
|
|
94
|
+
pub config_digest: &'a str,
|
|
95
|
+
/// The GraphConfig itself, as the caller handed it over. Its digest
|
|
96
|
+
/// must be `config_digest`, which the read-back check confirms.
|
|
97
|
+
pub graph_json: &'a str,
|
|
98
|
+
pub semantics_version: u32,
|
|
99
|
+
pub step: usize,
|
|
100
|
+
pub optimizer: &'a OptimizerConfig,
|
|
101
|
+
pub optimizer_steps: u64,
|
|
102
|
+
/// Every parameter, by qualified path, in declaration order.
|
|
103
|
+
pub parameters: Vec<(String, &'a Array)>,
|
|
104
|
+
/// Which of them are differentiated, as positions into `parameters`.
|
|
105
|
+
pub argnums: &'a [i32],
|
|
106
|
+
/// The optimizer's slots, parallel to `argnums`.
|
|
107
|
+
pub slots: Option<(&'a [Array], &'a [Array])>,
|
|
108
|
+
/// The RNG key, so a resumed run draws what a continuous one would.
|
|
109
|
+
pub rng: &'a Array,
|
|
110
|
+
pub seed: u64,
|
|
111
|
+
/// The caller's own record, written verbatim.
|
|
112
|
+
pub run: serde_json::Value,
|
|
113
|
+
/// Write only the trained parameters (and the optimizer's slots, which
|
|
114
|
+
/// are for those alone). What a LoRA run changes is a few megabytes of
|
|
115
|
+
/// a model of gigabytes, and every other parameter is the one it was
|
|
116
|
+
/// opened with: written again at every checkpoint, it is the cost.
|
|
117
|
+
pub light: bool,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
impl Manifest {
|
|
121
|
+
/// What a checkpoint claims, read off the state it is being written
|
|
122
|
+
/// from.
|
|
123
|
+
fn of(state: &State<'_>) -> Result<Self> {
|
|
124
|
+
Ok(Self {
|
|
125
|
+
schema_version: SCHEMA_VERSION,
|
|
126
|
+
config_digest: state.config_digest.to_string(),
|
|
127
|
+
semantics_version: state.semantics_version,
|
|
128
|
+
step: state.step,
|
|
129
|
+
optimizer: state.optimizer.clone(),
|
|
130
|
+
optimizer_steps: state.optimizer_steps,
|
|
131
|
+
seed: state.seed,
|
|
132
|
+
parameters: state
|
|
133
|
+
.parameters
|
|
134
|
+
.iter()
|
|
135
|
+
.enumerate()
|
|
136
|
+
.map(|(i, (path, array))| {
|
|
137
|
+
let dtype = dtype_spelling(array.dtype()).with_context(|| {
|
|
138
|
+
format!(
|
|
139
|
+
"parameter {path:?} holds {:?}, which the graph vocabulary \
|
|
140
|
+
cannot name; a checkpoint that recorded it could not be \
|
|
141
|
+
read back into any graph",
|
|
142
|
+
array.dtype()
|
|
143
|
+
)
|
|
144
|
+
})?;
|
|
145
|
+
Ok(ParameterEntry {
|
|
146
|
+
path: path.clone(),
|
|
147
|
+
shape: array.shape().to_vec(),
|
|
148
|
+
dtype: dtype.to_string(),
|
|
149
|
+
trained: state.argnums.contains(&(i as i32)),
|
|
150
|
+
saved: !state.light || state.argnums.contains(&(i as i32)),
|
|
151
|
+
})
|
|
152
|
+
})
|
|
153
|
+
.collect::<Result<_>>()?,
|
|
154
|
+
build: crate::build_info(),
|
|
155
|
+
platform: platform(),
|
|
156
|
+
run: state.run.clone(),
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// Writes a checkpoint, atomically. Returns where it landed.
|
|
162
|
+
///
|
|
163
|
+
/// Three steps, and the order is the point: lay the whole thing out
|
|
164
|
+
/// somewhere it does not yet count, read it back, and only then let it
|
|
165
|
+
/// take the name.
|
|
166
|
+
pub fn write(dir: impl AsRef<Path>, state: State<'_>) -> Result<PathBuf> {
|
|
167
|
+
let dir = dir.as_ref();
|
|
168
|
+
let staging = dir.with_extension("writing");
|
|
169
|
+
if staging.exists() {
|
|
170
|
+
std::fs::remove_dir_all(&staging).ok();
|
|
171
|
+
}
|
|
172
|
+
std::fs::create_dir_all(&staging)
|
|
173
|
+
.with_context(|| format!("creating {}", staging.display()))?;
|
|
174
|
+
|
|
175
|
+
lay_out(&staging, &state)?;
|
|
176
|
+
// Nothing claims the name before it reads back: the manifest parses,
|
|
177
|
+
// every tensor loads, and each one is what the manifest says.
|
|
178
|
+
read(&staging).context("the checkpoint just written does not read back")?;
|
|
179
|
+
publish(&staging, dir)?;
|
|
180
|
+
Ok(dir.to_path_buf())
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// Writes the five files into a directory that does not count yet.
|
|
184
|
+
fn lay_out(staging: &Path, state: &State<'_>) -> Result<()> {
|
|
185
|
+
std::fs::write(staging.join(GRAPH_FILE), state.graph_json).context("writing the graph")?;
|
|
186
|
+
|
|
187
|
+
Array::save_safetensors(
|
|
188
|
+
state
|
|
189
|
+
.parameters
|
|
190
|
+
.iter()
|
|
191
|
+
.enumerate()
|
|
192
|
+
.filter(|(i, _)| !state.light || state.argnums.contains(&(*i as i32)))
|
|
193
|
+
.map(|(_, (path, array))| (path, *array)),
|
|
194
|
+
None,
|
|
195
|
+
staging.join("parameters.safetensors"),
|
|
196
|
+
)
|
|
197
|
+
.context("writing parameters")?;
|
|
198
|
+
|
|
199
|
+
if let Some((m, v)) = state.slots {
|
|
200
|
+
let named: Vec<(String, &Array)> = state
|
|
201
|
+
.argnums
|
|
202
|
+
.iter()
|
|
203
|
+
.enumerate()
|
|
204
|
+
.flat_map(|(slot, &i)| {
|
|
205
|
+
let path = &state.parameters[i as usize].0;
|
|
206
|
+
[(format!("m/{path}"), &m[slot]), (format!("v/{path}"), &v[slot])]
|
|
207
|
+
})
|
|
208
|
+
.collect();
|
|
209
|
+
Array::save_safetensors(
|
|
210
|
+
named.iter().map(|(k, a)| (k, *a)),
|
|
211
|
+
None,
|
|
212
|
+
staging.join("optimizer.safetensors"),
|
|
213
|
+
)
|
|
214
|
+
.context("writing optimizer state")?;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
Array::save_safetensors([("key", state.rng)], None, staging.join("random.safetensors"))
|
|
218
|
+
.context("writing the RNG state")?;
|
|
219
|
+
|
|
220
|
+
std::fs::write(
|
|
221
|
+
staging.join("manifest.json"),
|
|
222
|
+
serde_json::to_vec_pretty(&Manifest::of(state)?)?,
|
|
223
|
+
)
|
|
224
|
+
.context("writing the manifest")
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/// Lets a finished directory take the name, and makes that durable.
|
|
228
|
+
///
|
|
229
|
+
/// A rename over an existing directory is not atomic on this platform: the
|
|
230
|
+
/// old one has to go first, and a stop in between would leave neither. So
|
|
231
|
+
/// the previous checkpoint is moved aside, the new one takes the name in
|
|
232
|
+
/// one rename, and only then is the old one dropped.
|
|
233
|
+
fn publish(staging: &Path, dir: &Path) -> Result<()> {
|
|
234
|
+
sync_dir(staging)?;
|
|
235
|
+
|
|
236
|
+
let displaced = if dir.exists() {
|
|
237
|
+
let aside = dir.with_extension("replaced");
|
|
238
|
+
if aside.exists() {
|
|
239
|
+
std::fs::remove_dir_all(&aside).ok();
|
|
240
|
+
}
|
|
241
|
+
std::fs::rename(dir, &aside)
|
|
242
|
+
.with_context(|| format!("moving {} aside", dir.display()))?;
|
|
243
|
+
Some(aside)
|
|
244
|
+
} else {
|
|
245
|
+
None
|
|
246
|
+
};
|
|
247
|
+
std::fs::rename(staging, dir)
|
|
248
|
+
.with_context(|| format!("renaming {} into place", staging.display()))?;
|
|
249
|
+
if let Some(aside) = displaced {
|
|
250
|
+
std::fs::remove_dir_all(aside).ok();
|
|
251
|
+
}
|
|
252
|
+
if let Some(parent) = dir.parent() {
|
|
253
|
+
sync_dir(parent).ok();
|
|
254
|
+
}
|
|
255
|
+
Ok(())
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/// Asks the filesystem to make a directory's entries durable, so that a
|
|
259
|
+
/// checkpoint that exists after a crash is one that reads back.
|
|
260
|
+
fn sync_dir(dir: &Path) -> Result<()> {
|
|
261
|
+
let handle = std::fs::File::open(dir).with_context(|| format!("opening {}", dir.display()))?;
|
|
262
|
+
handle
|
|
263
|
+
.sync_all()
|
|
264
|
+
.with_context(|| format!("syncing {}", dir.display()))
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/// The machine, for a checkpoint carried between them.
|
|
268
|
+
fn platform() -> serde_json::Value {
|
|
269
|
+
serde_json::json!({
|
|
270
|
+
"os": std::env::consts::OS,
|
|
271
|
+
"arch": std::env::consts::ARCH,
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// What a checkpoint says about itself, as JSON: for a caller deciding
|
|
276
|
+
/// which one to resume from, without opening it into a session.
|
|
277
|
+
pub fn read_manifest_json(dir: &str) -> Result<String> {
|
|
278
|
+
Ok(serde_json::to_string(&read_manifest(dir)?)?)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
pub fn read_manifest(dir: impl AsRef<Path>) -> Result<Manifest> {
|
|
282
|
+
let path = dir.as_ref().join("manifest.json");
|
|
283
|
+
let text = std::fs::read_to_string(&path)
|
|
284
|
+
.with_context(|| format!("reading {}", path.display()))?;
|
|
285
|
+
let manifest: Manifest = serde_json::from_str(&text)
|
|
286
|
+
.with_context(|| format!("parsing {}", path.display()))?;
|
|
287
|
+
anyhow::ensure!(
|
|
288
|
+
manifest.schema_version == SCHEMA_VERSION,
|
|
289
|
+
"checkpoint schema {} is not {}",
|
|
290
|
+
manifest.schema_version,
|
|
291
|
+
SCHEMA_VERSION
|
|
292
|
+
);
|
|
293
|
+
Ok(manifest)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/// What a checkpoint holds, read back.
|
|
297
|
+
pub struct Loaded {
|
|
298
|
+
pub manifest: Manifest,
|
|
299
|
+
pub parameters: HashMap<String, Array>,
|
|
300
|
+
/// (m, v) by parameter path. Empty when the optimizer has no slots.
|
|
301
|
+
pub slots: HashMap<String, (Array, Array)>,
|
|
302
|
+
pub rng: Option<Array>,
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/// The run a checkpoint is being restored into: what it has to match.
|
|
306
|
+
pub struct Run<'a> {
|
|
307
|
+
pub plan: &'a Plan,
|
|
308
|
+
pub params: &'a [Array],
|
|
309
|
+
pub argnums: &'a [i32],
|
|
310
|
+
pub optimizer: &'a Optimizer,
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/// A checkpoint that has been read and found to belong to the run.
|
|
314
|
+
///
|
|
315
|
+
/// Exists only after every check has passed, which is what makes
|
|
316
|
+
/// `TrainState::restore` a commit rather than a sequence of hopes.
|
|
317
|
+
pub struct Accepted {
|
|
318
|
+
pub params: Vec<Array>,
|
|
319
|
+
pub moments: Moments,
|
|
320
|
+
pub rng: Array,
|
|
321
|
+
pub seed: u64,
|
|
322
|
+
pub step: usize,
|
|
323
|
+
pub optimizer_steps: u64,
|
|
324
|
+
/// What the caller recorded alongside, handed back unchanged.
|
|
325
|
+
pub run: String,
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/// Whether a checkpoint belongs to a run is a question about the
|
|
329
|
+
/// checkpoint's contents, asked here beside the code that writes and reads
|
|
330
|
+
/// them; the training state only commits what passes.
|
|
331
|
+
impl Loaded {
|
|
332
|
+
/// Checks all of this checkpoint against the run that would restore
|
|
333
|
+
/// it, and hands back what it would restore. Touches nothing.
|
|
334
|
+
pub fn accept(&self, run: &Run<'_>) -> Result<Accepted> {
|
|
335
|
+
let (plan, manifest) = (run.plan, &self.manifest);
|
|
336
|
+
anyhow::ensure!(
|
|
337
|
+
manifest.config_digest == plan.config_digest,
|
|
338
|
+
"this checkpoint belongs to another graph (digest {}, not {})",
|
|
339
|
+
&manifest.config_digest[..12.min(manifest.config_digest.len())],
|
|
340
|
+
&plan.config_digest[..12]
|
|
341
|
+
);
|
|
342
|
+
anyhow::ensure!(
|
|
343
|
+
&manifest.optimizer == run.optimizer.config(),
|
|
344
|
+
"this checkpoint was written by a different optimizer ({:?})",
|
|
345
|
+
manifest.optimizer
|
|
346
|
+
);
|
|
347
|
+
anyhow::ensure!(
|
|
348
|
+
manifest.parameters.len() == plan.paths.len(),
|
|
349
|
+
"this checkpoint has {} parameters, this session has {}",
|
|
350
|
+
manifest.parameters.len(),
|
|
351
|
+
plan.paths.len()
|
|
352
|
+
);
|
|
353
|
+
|
|
354
|
+
let mut params = Vec::with_capacity(run.params.len());
|
|
355
|
+
for (i, path) in plan.paths.iter().enumerate() {
|
|
356
|
+
let entry = &manifest.parameters[i];
|
|
357
|
+
anyhow::ensure!(
|
|
358
|
+
&entry.path == path,
|
|
359
|
+
"parameter {i} is {:?} here and {:?} in the checkpoint",
|
|
360
|
+
path,
|
|
361
|
+
entry.path
|
|
362
|
+
);
|
|
363
|
+
if !entry.saved {
|
|
364
|
+
// A light checkpoint: this one is the session's own. What it
|
|
365
|
+
// recorded must still be what the session holds.
|
|
366
|
+
anyhow::ensure!(
|
|
367
|
+
entry.shape == run.params[i].shape()
|
|
368
|
+
&& Some(entry.dtype.as_str()) == dtype_spelling(run.params[i].dtype()),
|
|
369
|
+
"parameter {path:?} was not saved in this checkpoint, and the session's \
|
|
370
|
+
is not the shape and type it was written beside"
|
|
371
|
+
);
|
|
372
|
+
anyhow::ensure!(
|
|
373
|
+
!run.argnums.contains(&(i as i32)),
|
|
374
|
+
"parameter {path:?} is trained here and was not saved in this checkpoint"
|
|
375
|
+
);
|
|
376
|
+
params.push(run.params[i].clone());
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
let array = self
|
|
380
|
+
.parameters
|
|
381
|
+
.get(path)
|
|
382
|
+
.with_context(|| format!("the checkpoint has no parameter {path:?}"))?;
|
|
383
|
+
anyhow::ensure!(
|
|
384
|
+
array.shape() == run.params[i].shape(),
|
|
385
|
+
"parameter {path:?}: checkpoint shape {:?} is not {:?}",
|
|
386
|
+
array.shape(),
|
|
387
|
+
run.params[i].shape()
|
|
388
|
+
);
|
|
389
|
+
anyhow::ensure!(
|
|
390
|
+
array.dtype() == run.params[i].dtype(),
|
|
391
|
+
"parameter {path:?}: checkpoint dtype {:?} is not {:?}",
|
|
392
|
+
array.dtype(),
|
|
393
|
+
run.params[i].dtype()
|
|
394
|
+
);
|
|
395
|
+
params.push(array.clone());
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
let moments = self.moments_for(run)?;
|
|
399
|
+
Ok(Accepted {
|
|
400
|
+
params,
|
|
401
|
+
moments,
|
|
402
|
+
rng: self.rng.clone().context("the checkpoint has no RNG state")?,
|
|
403
|
+
seed: manifest.seed,
|
|
404
|
+
step: manifest.step,
|
|
405
|
+
optimizer_steps: manifest.optimizer_steps,
|
|
406
|
+
run: serde_json::to_string(&manifest.run)?,
|
|
407
|
+
})
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/// The optimizer's slots, all of them or none.
|
|
411
|
+
///
|
|
412
|
+
/// An AdamW session restored without moments used to index past the
|
|
413
|
+
/// end of an empty vector on its next step, which is why this refuses
|
|
414
|
+
/// rather than filling in.
|
|
415
|
+
fn moments_for(&self, run: &Run<'_>) -> Result<Moments> {
|
|
416
|
+
if !run.optimizer.wants_slots() {
|
|
417
|
+
anyhow::ensure!(
|
|
418
|
+
self.slots.is_empty(),
|
|
419
|
+
"this checkpoint carries optimizer state, and {} has none",
|
|
420
|
+
run.optimizer.config().name()
|
|
421
|
+
);
|
|
422
|
+
return Ok(Moments::None);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
anyhow::ensure!(
|
|
426
|
+
!self.slots.is_empty(),
|
|
427
|
+
"this checkpoint has no optimizer state, and {} needs it",
|
|
428
|
+
run.optimizer.config().name()
|
|
429
|
+
);
|
|
430
|
+
let (mut m, mut v) = (Vec::new(), Vec::new());
|
|
431
|
+
for &i in run.argnums {
|
|
432
|
+
let path = &run.plan.paths[i as usize];
|
|
433
|
+
let (slot_m, slot_v) = self
|
|
434
|
+
.slots
|
|
435
|
+
.get(path)
|
|
436
|
+
.with_context(|| format!("the checkpoint has no optimizer state for {path:?}"))?;
|
|
437
|
+
anyhow::ensure!(
|
|
438
|
+
slot_m.shape() == run.params[i as usize].shape()
|
|
439
|
+
&& slot_v.shape() == run.params[i as usize].shape(),
|
|
440
|
+
"optimizer state for {path:?} has the wrong shape"
|
|
441
|
+
);
|
|
442
|
+
m.push(slot_m.clone());
|
|
443
|
+
v.push(slot_v.clone());
|
|
444
|
+
}
|
|
445
|
+
Ok(Moments::Adam { m, v })
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
pub fn read(dir: impl AsRef<Path>) -> Result<Loaded> {
|
|
450
|
+
let dir = dir.as_ref();
|
|
451
|
+
let manifest = read_manifest(dir)?;
|
|
452
|
+
// Read to be checked against the manifest, not to be handed on: what
|
|
453
|
+
// the description says is the graph's business, and a caller that
|
|
454
|
+
// wants it reads the file (Torobi::Checkpoint.graph_json).
|
|
455
|
+
let graph_json = std::fs::read_to_string(dir.join(GRAPH_FILE))
|
|
456
|
+
.with_context(|| format!("reading {}", dir.join(GRAPH_FILE).display()))?;
|
|
457
|
+
{
|
|
458
|
+
let digest = crate::graph::digest(&graph_json);
|
|
459
|
+
anyhow::ensure!(
|
|
460
|
+
digest == manifest.config_digest,
|
|
461
|
+
"{GRAPH_FILE} is not the description this manifest claims \
|
|
462
|
+
(digest {}, manifest says {})",
|
|
463
|
+
&digest[..12],
|
|
464
|
+
&manifest.config_digest[..12.min(manifest.config_digest.len())]
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
let parameters = Array::load_safetensors(dir.join("parameters.safetensors"))
|
|
468
|
+
.context("reading parameters")?;
|
|
469
|
+
for entry in manifest.parameters.iter().filter(|entry| entry.saved) {
|
|
470
|
+
let array = parameters
|
|
471
|
+
.get(&entry.path)
|
|
472
|
+
.with_context(|| format!("the manifest lists {:?}, the file has none", entry.path))?;
|
|
473
|
+
anyhow::ensure!(
|
|
474
|
+
array.shape() == entry.shape,
|
|
475
|
+
"parameter {:?}: the file holds {:?}, the manifest says {:?}",
|
|
476
|
+
entry.path,
|
|
477
|
+
array.shape(),
|
|
478
|
+
entry.shape
|
|
479
|
+
);
|
|
480
|
+
let dtype = dtype_spelling(array.dtype()).unwrap_or("(unnameable)");
|
|
481
|
+
anyhow::ensure!(
|
|
482
|
+
dtype == entry.dtype,
|
|
483
|
+
"parameter {:?}: the file holds {dtype}, the manifest says {}",
|
|
484
|
+
entry.path,
|
|
485
|
+
entry.dtype
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
let optimizer_path = dir.join("optimizer.safetensors");
|
|
490
|
+
let mut slots = HashMap::new();
|
|
491
|
+
if optimizer_path.exists() {
|
|
492
|
+
let arrays =
|
|
493
|
+
Array::load_safetensors(&optimizer_path).context("reading optimizer state")?;
|
|
494
|
+
for (key, array) in &arrays {
|
|
495
|
+
let Some(path) = key.strip_prefix("m/") else {
|
|
496
|
+
continue;
|
|
497
|
+
};
|
|
498
|
+
let v = arrays
|
|
499
|
+
.get(&format!("v/{path}"))
|
|
500
|
+
.with_context(|| format!("optimizer state has m/{path} but no v/{path}"))?;
|
|
501
|
+
slots.insert(path.to_string(), (array.clone(), v.clone()));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
let rng = Array::load_safetensors(dir.join("random.safetensors"))
|
|
505
|
+
.context("reading the RNG state")?
|
|
506
|
+
.remove("key");
|
|
507
|
+
Ok(Loaded {
|
|
508
|
+
manifest,
|
|
509
|
+
parameters,
|
|
510
|
+
slots,
|
|
511
|
+
rng,
|
|
512
|
+
})
|
|
513
|
+
}
|