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
data/engine/src/lib.rs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
//! Torobi's execution engine.
|
|
2
|
+
//!
|
|
3
|
+
//! A [`Session`] owns one graph, its parameters and its bound inputs, and
|
|
4
|
+
//! runs training steps against MLX. It is the whole of what the Ruby side
|
|
5
|
+
//! can reach: no tensors cross the boundary (only copies, by name), no
|
|
6
|
+
//! callbacks come back in, and the model never leaves this crate.
|
|
7
|
+
|
|
8
|
+
// What escapes this crate, and nothing else.
|
|
9
|
+
//
|
|
10
|
+
// **The gate is the whole design, so the compiler should hold it.** Every
|
|
11
|
+
// public route to MLX goes through `runtime::execute` (`crate::runtime`),
|
|
12
|
+
// and that was true of `Session` while `state`, `executor`, `interp` and
|
|
13
|
+
// `op` were public beside it: a caller could build a `TrainState` and
|
|
14
|
+
// differentiate with it, off the gate, and the failure that follows is
|
|
15
|
+
// two threads on one command queue, which ends the process rather than
|
|
16
|
+
// returning. Enforced by convention is enforced until somebody is in a
|
|
17
|
+
// hurry.
|
|
18
|
+
//
|
|
19
|
+
// What is public is what the Ruby extension and the command-line tool
|
|
20
|
+
// actually use: a session, the values that cross to it, where its
|
|
21
|
+
// parameters come from, the allocator's numbers, and a checkpoint's
|
|
22
|
+
// manifest.
|
|
23
|
+
pub mod checkpoint;
|
|
24
|
+
pub(crate) mod executor;
|
|
25
|
+
pub(crate) mod export;
|
|
26
|
+
#[cfg(test)]
|
|
27
|
+
mod fixtures;
|
|
28
|
+
pub(crate) mod graph;
|
|
29
|
+
pub mod init;
|
|
30
|
+
pub(crate) mod interp;
|
|
31
|
+
pub mod memory;
|
|
32
|
+
pub(crate) mod mlxc;
|
|
33
|
+
pub(crate) mod op;
|
|
34
|
+
pub(crate) mod optimizer;
|
|
35
|
+
pub(crate) mod plan;
|
|
36
|
+
pub mod runtime;
|
|
37
|
+
pub mod session;
|
|
38
|
+
pub(crate) mod state;
|
|
39
|
+
pub mod tensor;
|
|
40
|
+
|
|
41
|
+
pub use optimizer::Config as Optimizer;
|
|
42
|
+
pub use plan::Weights;
|
|
43
|
+
pub use runtime::{initialize, set_metallib_path, RuntimeError};
|
|
44
|
+
pub use session::Session;
|
|
45
|
+
|
|
46
|
+
/// What this engine was built from. The vendoring ledger (docs/vendoring.md)
|
|
47
|
+
/// says every artifact must be able to report its revisions; a journal
|
|
48
|
+
/// records this so a run can say which build produced it.
|
|
49
|
+
///
|
|
50
|
+
/// The MLX release and the mlx-c commit, as the pre-built archive's
|
|
51
|
+
/// manifest names them (read by build.rs). Those two are the whole of the
|
|
52
|
+
/// native code under the engine now that no Rust crate stands between it
|
|
53
|
+
/// and mlx-c.
|
|
54
|
+
pub fn build_info() -> serde_json::Value {
|
|
55
|
+
serde_json::json!({
|
|
56
|
+
"torobi_engine": env!("CARGO_PKG_VERSION"),
|
|
57
|
+
"mlx": env!("TOROBI_MLX_VERSION"),
|
|
58
|
+
"mlx_c": env!("TOROBI_MLX_C_REVISION"),
|
|
59
|
+
"profile": if cfg!(debug_assertions) { "debug" } else { "release" },
|
|
60
|
+
"target": std::env::consts::ARCH,
|
|
61
|
+
})
|
|
62
|
+
}
|
data/engine/src/main.rs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
//! torobi-engine: the command-line face of the engine, for spikes and
|
|
2
|
+
//! debugging. The Ruby extension uses the same [`Session`] in-process.
|
|
3
|
+
//!
|
|
4
|
+
//! torobi-engine grad <graph.json> <bindings.json>
|
|
5
|
+
//! torobi-engine train <graph.json> <bindings.json> <steps> <lr>
|
|
6
|
+
//!
|
|
7
|
+
//! `bindings.json` holds `{"inputs": {...}, "params": {...}}`: the CLI is a
|
|
8
|
+
//! one-batch tool, so it feeds the same batch to every step. A real caller
|
|
9
|
+
//! gives each step its own (docs/plan.md section 5A.2).
|
|
10
|
+
|
|
11
|
+
use anyhow::{bail, Result};
|
|
12
|
+
use torobi_engine::tensor::{Batch, Tensor, Values};
|
|
13
|
+
use torobi_engine::{Session, Weights};
|
|
14
|
+
|
|
15
|
+
use serde::Deserialize;
|
|
16
|
+
|
|
17
|
+
/// The CLI's own JSON shape for a batch. The library's boundary carries a
|
|
18
|
+
/// dtype and packed bytes (an embedding reads i32); this is the readable
|
|
19
|
+
/// form a spike file is written in, and it is f32.
|
|
20
|
+
#[derive(Deserialize)]
|
|
21
|
+
struct JsonTensor {
|
|
22
|
+
shape: Vec<i32>,
|
|
23
|
+
data: Vec<f32>,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
#[derive(Deserialize)]
|
|
27
|
+
struct Bindings {
|
|
28
|
+
inputs: std::collections::BTreeMap<String, JsonTensor>,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fn to_batch(inputs: std::collections::BTreeMap<String, JsonTensor>) -> Batch {
|
|
32
|
+
inputs
|
|
33
|
+
.into_iter()
|
|
34
|
+
.map(|(name, t)| {
|
|
35
|
+
(
|
|
36
|
+
name,
|
|
37
|
+
Tensor {
|
|
38
|
+
shape: t.shape,
|
|
39
|
+
values: Values::F32(t.data),
|
|
40
|
+
},
|
|
41
|
+
)
|
|
42
|
+
})
|
|
43
|
+
.collect()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
fn main() -> Result<()> {
|
|
47
|
+
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
48
|
+
match args.first().map(String::as_str) {
|
|
49
|
+
Some("grad") if args.len() == 3 => grad(&args[1], &args[2]),
|
|
50
|
+
Some("train") if args.len() == 5 => {
|
|
51
|
+
train(&args[1], &args[2], args[3].parse()?, args[4].parse()?)
|
|
52
|
+
}
|
|
53
|
+
_ => bail!(
|
|
54
|
+
"usage: torobi-engine grad <graph> <bindings> | \
|
|
55
|
+
train <graph> <bindings> <steps> <lr>"
|
|
56
|
+
),
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
fn open(graph_path: &str, bindings_path: &str) -> Result<(Session, Batch)> {
|
|
61
|
+
let graph_json = std::fs::read_to_string(graph_path)?;
|
|
62
|
+
let bindings_json = std::fs::read_to_string(bindings_path)?;
|
|
63
|
+
let session = Session::open(&graph_json, Weights::Inline(&bindings_json))?;
|
|
64
|
+
let bindings: Bindings = serde_json::from_str(&bindings_json)?;
|
|
65
|
+
Ok((session, to_batch(bindings.inputs)))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fn grad(graph_path: &str, bindings_path: &str) -> Result<()> {
|
|
69
|
+
let (mut session, batch) = open(graph_path, bindings_path)?;
|
|
70
|
+
let loss = session.evaluate(&batch)?;
|
|
71
|
+
let grads = session
|
|
72
|
+
.gradients(&batch)?
|
|
73
|
+
.into_iter()
|
|
74
|
+
.map(|(path, t)| {
|
|
75
|
+
let data = match t.values {
|
|
76
|
+
Values::F32(v) => serde_json::json!(v),
|
|
77
|
+
Values::I32(v) => serde_json::json!(v),
|
|
78
|
+
};
|
|
79
|
+
(path, serde_json::json!({ "shape": t.shape, "data": data }))
|
|
80
|
+
})
|
|
81
|
+
.collect::<serde_json::Map<_, _>>();
|
|
82
|
+
println!("{}", serde_json::json!({ "loss": loss, "grads": grads }));
|
|
83
|
+
Ok(())
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
fn train(graph_path: &str, bindings_path: &str, steps: usize, lr: f32) -> Result<()> {
|
|
87
|
+
let (mut session, batch) = open(graph_path, bindings_path)?;
|
|
88
|
+
session.set_lr(lr)?;
|
|
89
|
+
while session.step()? < steps {
|
|
90
|
+
let loss = session.run_step(&batch)?;
|
|
91
|
+
if session.step()? % 10 == 0 {
|
|
92
|
+
println!("{}", serde_json::json!({ "step": session.step()?, "loss": loss }));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
println!("{}", serde_json::json!({ "final_loss": session.loss()? }));
|
|
96
|
+
Ok(())
|
|
97
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
//! What the device is holding.
|
|
2
|
+
//!
|
|
3
|
+
//! Ruby's GC does not see device memory, so a long run needs numbers it can
|
|
4
|
+
//! watch and a limit it can set (docs/plan.md section 11.3). MLX's
|
|
5
|
+
//! allocator is process-wide, which is why these are free functions rather
|
|
6
|
+
//! than methods on a session: two sessions share one pool, and that is a
|
|
7
|
+
//! fact to report, not to hide.
|
|
8
|
+
//!
|
|
9
|
+
//! Being process-wide is also why they go through the runtime. They reach
|
|
10
|
+
//! the same allocator every running session is using, so they take their
|
|
11
|
+
//! turn like a step does. [`Memory`] is the way in; the functions under it
|
|
12
|
+
//! are crate-private, or a caller could reach the allocator around the
|
|
13
|
+
//! gate.
|
|
14
|
+
|
|
15
|
+
use anyhow::{Context, Result};
|
|
16
|
+
|
|
17
|
+
use crate::mlxc;
|
|
18
|
+
|
|
19
|
+
use crate::runtime::{runtime, RuntimeError};
|
|
20
|
+
|
|
21
|
+
/// The process's device memory, through the one runtime.
|
|
22
|
+
pub struct Memory;
|
|
23
|
+
|
|
24
|
+
impl Memory {
|
|
25
|
+
/// A reading, in bytes: active, cache, peak and the limit in force.
|
|
26
|
+
pub fn report() -> Result<serde_json::Value, RuntimeError> {
|
|
27
|
+
runtime().execute(report)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Frees what the allocator holds but is not using. Returns
|
|
31
|
+
/// [before, after].
|
|
32
|
+
pub fn clear_cache() -> Result<(usize, usize), RuntimeError> {
|
|
33
|
+
runtime().execute(clear_cache)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// Caps what this process may allocate on the device, in bytes; 0
|
|
37
|
+
/// lifts the cap. Returns the cap now in force.
|
|
38
|
+
pub fn set_limit(bytes: usize) -> Result<usize, RuntimeError> {
|
|
39
|
+
runtime().execute(|| set_limit(bytes))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// Forgets the high-water mark, so the next span is measured on its
|
|
43
|
+
/// own.
|
|
44
|
+
pub fn reset_peak() -> Result<(), RuntimeError> {
|
|
45
|
+
runtime().execute(reset_peak)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// A reading of the process's device memory, in bytes.
|
|
50
|
+
fn report() -> Result<serde_json::Value> {
|
|
51
|
+
Ok(serde_json::json!({
|
|
52
|
+
"active": mlxc::memory::active()?,
|
|
53
|
+
"cache": mlxc::memory::cache()?,
|
|
54
|
+
"peak": mlxc::memory::peak()?,
|
|
55
|
+
"limit": mlxc::memory::limit()?,
|
|
56
|
+
}))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Frees what the allocator is holding but not using. Returns the cache
|
|
60
|
+
/// size before and after, so a caller can see whether it helped.
|
|
61
|
+
fn clear_cache() -> Result<(usize, usize)> {
|
|
62
|
+
let before = mlxc::memory::cache()?;
|
|
63
|
+
mlxc::memory::clear_cache().context("clearing the cache failed")?;
|
|
64
|
+
Ok((before, mlxc::memory::cache()?))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// Caps what the process may allocate on the device, and returns the cap
|
|
68
|
+
/// now in force. Zero means no cap.
|
|
69
|
+
///
|
|
70
|
+
/// (mlx-c writes the new limit into its out-parameter, not the old one, so
|
|
71
|
+
/// a caller that wants to restore a limit reads it first.)
|
|
72
|
+
fn set_limit(bytes: usize) -> Result<usize> {
|
|
73
|
+
Ok(mlxc::memory::set_limit(bytes).context("setting the memory limit failed")?)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// Forgets the high-water mark, so a later reading is about what follows.
|
|
77
|
+
fn reset_peak() -> Result<()> {
|
|
78
|
+
Ok(mlxc::memory::reset_peak().context("resetting the peak failed")?)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
#[cfg(test)]
|
|
82
|
+
mod tests {
|
|
83
|
+
use super::*;
|
|
84
|
+
use crate::fixtures;
|
|
85
|
+
use crate::plan::Weights;
|
|
86
|
+
use crate::session::Session;
|
|
87
|
+
|
|
88
|
+
/// Clearing gives back everything the allocator was holding.
|
|
89
|
+
///
|
|
90
|
+
/// The claim belongs here rather than above, because the reading that
|
|
91
|
+
/// shows the cache empty has to be taken inside the same gated call as
|
|
92
|
+
/// the clear. Anything dropped puts its buffers back into the cache,
|
|
93
|
+
/// and in Ruby it is the GC that decides when a session that was never
|
|
94
|
+
/// closed is dropped: a reading taken from there is about when a
|
|
95
|
+
/// collection happened to run (test/lifecycle_test.rb).
|
|
96
|
+
#[test]
|
|
97
|
+
fn clearing_empties_the_cache() {
|
|
98
|
+
let (config, weights) = fixtures::scaled_mean();
|
|
99
|
+
let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
|
|
100
|
+
session.run_step(&fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0])).unwrap();
|
|
101
|
+
// A step's working buffers, and then the session's own.
|
|
102
|
+
drop(session);
|
|
103
|
+
|
|
104
|
+
let (before, after) = Memory::clear_cache().unwrap();
|
|
105
|
+
|
|
106
|
+
assert!(before > 0, "a step and a drop leave the allocator holding buffers");
|
|
107
|
+
assert_eq!(after, 0, "and clearing gives all of them back");
|
|
108
|
+
}
|
|
109
|
+
}
|