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
data/engine/Cargo.toml ADDED
@@ -0,0 +1,35 @@
1
+ [package]
2
+ name = "torobi-engine"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "Torobi's execution engine: interprets GraphConfig on MLX"
6
+ license = "MIT"
7
+
8
+ [dependencies]
9
+ serde = { version = "1", features = ["derive"] }
10
+ serde_json = "1"
11
+ anyhow = "1"
12
+ # The config digest a checkpoint records, computed over the same bytes
13
+ # the Ruby side hashed.
14
+ sha2 = "0.10"
15
+
16
+ # MLX is reached through mlx-c, bound in this crate (src/mlxc/) from the
17
+ # headers and archives of the prefix build.rs is pointed at. No Rust crate
18
+ # stands between the engine and mlx-c; docs/vendoring.md ("mlx-c, bound
19
+ # here") says why.
20
+ [target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies]
21
+ # dladdr, for finding this object and refusing a missing runtime artifact
22
+ # before MLX fails less clearly (src/runtime.rs): the metallib on Apple,
23
+ # which MLX aborts over, and NVIDIA's JIT headers on Linux, which MLX only
24
+ # fails the first kernel over.
25
+ libc = "0.2"
26
+
27
+ [build-dependencies]
28
+ # The bindings for mlx-c, generated from the headers in the prefix that is
29
+ # linked. docs/vendoring.md ("mlx-c, bound here") says why they are
30
+ # generated here.
31
+ bindgen = "0.72"
32
+
33
+ [dev-dependencies]
34
+ # Checkpoint tests write real directories; nothing here mocks a filesystem.
35
+ tempfile = "3"
data/engine/build.rs ADDED
@@ -0,0 +1,253 @@
1
+ //! Records what this engine is built against, so a run can say so, and
2
+ //! puts MLX's kernels where a test binary can find them.
3
+
4
+ use std::path::{Path, PathBuf};
5
+ use std::{env, fs};
6
+
7
+ fn main() {
8
+ println!("cargo:rerun-if-env-changed=TOROBI_MLX_PREFIX");
9
+ let prefix = env::var_os("TOROBI_MLX_PREFIX").map(PathBuf::from);
10
+ record_mlx_version(prefix.as_deref());
11
+ bind_mlx_c(prefix.as_deref());
12
+ link_metallib_beside_test_binaries(prefix.as_deref());
13
+ link_jit_headers_beside_test_binaries(prefix.as_deref());
14
+ }
15
+
16
+ /// The four functions whose declarations mlx-c gates on the architecture
17
+ /// (`mlx/c/half.h`), and the two types they take. Excluding them is what
18
+ /// lets one set of bindings serve both platforms. They read fp16 into a
19
+ /// host variable, which x86_64 has no type for; computing in fp16 is
20
+ /// untouched, and the engine converts at its boundary anyway.
21
+ const APPLE_ONLY: [&str; 6] = [
22
+ "mlx_array_item_float16",
23
+ "mlx_array_item_bfloat16",
24
+ "mlx_array_data_float16",
25
+ "mlx_array_data_bfloat16",
26
+ "float16_t",
27
+ "bfloat16_t",
28
+ ];
29
+
30
+ /// mlx-c, bound here (docs/vendoring.md, "mlx-c, bound here").
31
+ ///
32
+ /// Nothing is compiled: the prefix `TOROBI_MLX_PREFIX` names already holds
33
+ /// `libmlxc.a` and the headers bindgen reads.
34
+ ///
35
+ /// Refused outright without one. There is no other MLX to fall back to,
36
+ /// and a build that went ahead would fail at `include!` with a message
37
+ /// about a missing file rather than about the missing prefix.
38
+ fn bind_mlx_c(prefix: Option<&Path>) {
39
+ let prefix = prefix.unwrap_or_else(|| {
40
+ panic!(
41
+ "TOROBI_MLX_PREFIX is not set. `rake` and `rake compile` set it to the \
42
+ pre-built MLX they fetch (lib/torobi/mlx_prebuilt.rb); a plain cargo \
43
+ build needs it pointed at an MLX install prefix that holds mlx-c"
44
+ )
45
+ });
46
+ let include = prefix.join("include");
47
+ let umbrella = include.join("mlx/c/mlx.h");
48
+ assert!(umbrella.is_file(), "{} holds no mlx-c headers", include.display());
49
+
50
+ println!("cargo:rustc-link-search=native={}", prefix.join("lib").display());
51
+ for archive in ["mlx", "mlxc", "gguflib"] {
52
+ println!("cargo:rustc-link-lib=static={archive}");
53
+ }
54
+ if env::var("CARGO_CFG_TARGET_VENDOR").as_deref() == Ok("apple") {
55
+ for library in ["c++", "dylib=objc", "framework=Foundation", "framework=Metal", "framework=Accelerate"] {
56
+ println!("cargo:rustc-link-lib={library}");
57
+ }
58
+ } else {
59
+ println!("cargo:rustc-link-lib=stdc++");
60
+ link_cpu_linux();
61
+ link_cuda();
62
+ }
63
+
64
+ println!("cargo:rerun-if-changed={}", umbrella.display());
65
+ let mut builder = bindgen::Builder::default()
66
+ .header(umbrella.to_string_lossy())
67
+ .clang_arg(format!("-I{}", include.display()))
68
+ .allowlist_item("mlx_.*")
69
+ .allowlist_item("MLX_.*")
70
+ // The layout queries mlx-c marks private with a leading underscore.
71
+ // `as_slice` needs `_mlx_array_is_row_contiguous`, as mlx-rs does.
72
+ .allowlist_item("_mlx_array_.*")
73
+ .layout_tests(false)
74
+ .generate_comments(false);
75
+ for name in APPLE_ONLY {
76
+ builder = builder.blocklist_item(name);
77
+ }
78
+ let out = PathBuf::from(env::var("OUT_DIR").expect("cargo sets OUT_DIR"));
79
+ builder
80
+ .generate()
81
+ .expect("mlx-c's headers should describe themselves")
82
+ .write_to_file(out.join("bindings.rs"))
83
+ .expect("the bindings should be writable");
84
+ }
85
+
86
+ /// MLX's CPU backend on Linux calls BLAS and LAPACK (`cblas_sgemm`,
87
+ /// `sgetrf_`, `ssyevd_` and the rest), and a static `libmlx.a` leaves them
88
+ /// to whoever links it. MLX's own CMake package names OpenBLAS for both
89
+ /// (`share/cmake/MLX/MLXTargets.cmake`, which is what the archive was
90
+ /// built against), so this names it too: `libopenblas-dev` on Ubuntu.
91
+ fn link_cpu_linux() {
92
+ println!("cargo:rustc-link-lib=openblas");
93
+ }
94
+
95
+ /// A static MLX built for CUDA leaves these to whoever links it. `stubs`
96
+ /// carries the `libcuda.so` a machine with no driver links against.
97
+ fn link_cuda() {
98
+ println!("cargo:rerun-if-env-changed=CUDA_HOME");
99
+ println!("cargo:rerun-if-env-changed=CUDA_PATH");
100
+ let root = env::var_os("CUDA_HOME")
101
+ .or_else(|| env::var_os("CUDA_PATH"))
102
+ .map(PathBuf::from)
103
+ .unwrap_or_else(|| PathBuf::from("/usr/local/cuda"));
104
+ for leaf in ["lib64", "lib64/stubs", "lib", "lib/stubs"] {
105
+ let dir = root.join(leaf);
106
+ if dir.is_dir() {
107
+ println!("cargo:rustc-link-search=native={}", dir.display());
108
+ }
109
+ }
110
+ for library in ["cudart", "cublasLt", "cufft", "nvrtc", "cuda", "cudnn"] {
111
+ println!("cargo:rustc-link-lib={library}");
112
+ }
113
+ }
114
+
115
+ /// The vendoring ledger asks that every artifact report which MLX it is
116
+ /// built against (docs/vendoring.md). The prefix knows: a pre-built
117
+ /// archive carries `MANIFEST.txt` beside its prefix, naming the MLX
118
+ /// release and the mlx-c commit it was built from. A prefix built by hand
119
+ /// may carry none, and then the build says so rather than guessing.
120
+ fn record_mlx_version(prefix: Option<&Path>) {
121
+ let manifest = prefix.and_then(|prefix| {
122
+ [prefix.join("MANIFEST.txt"), prefix.parent()?.join("MANIFEST.txt")]
123
+ .into_iter()
124
+ .find(|path| path.is_file())
125
+ });
126
+ let said = manifest.as_deref().and_then(|path| {
127
+ println!("cargo:rerun-if-changed={}", path.display());
128
+ fs::read_to_string(path).ok()
129
+ });
130
+ for (key, var) in [("mlx", "TOROBI_MLX_VERSION"), ("mlx-c", "TOROBI_MLX_C_REVISION")] {
131
+ let value = said
132
+ .as_deref()
133
+ .and_then(|text| {
134
+ text.lines().find_map(|line| {
135
+ let mut words = line.split_whitespace();
136
+ (words.next() == Some(key)).then(|| words.next()).flatten()
137
+ })
138
+ })
139
+ .unwrap_or("unstated: the MLX prefix carries no MANIFEST.txt");
140
+ println!("cargo:rustc-env={var}={value}");
141
+ }
142
+ }
143
+
144
+ /// MLX finds its Metal kernels through dladdr, so mlx.metallib has to sit
145
+ /// beside whichever binary loaded it: `target/<profile>/torobi-engine`
146
+ /// for the command line, and `target/<profile>/deps/` for the test
147
+ /// binaries cargo puts there. Without it every one of those aborts with
148
+ /// "Failed to load the default metallib" (and it aborts, so nothing can
149
+ /// even report it).
150
+ ///
151
+ /// The metallib is in the prefix that is linked, at `lib/mlx.metallib`,
152
+ /// which is where the pre-built archive puts it. Only Apple's MLX has
153
+ /// one: CUDA compiles its kernels at run time.
154
+ ///
155
+ /// Symlinks rather than copies: the file is 105MB.
156
+ fn link_metallib_beside_test_binaries(prefix: Option<&Path>) {
157
+ if env::var("CARGO_CFG_TARGET_VENDOR").as_deref() != Ok("apple") {
158
+ return;
159
+ }
160
+ let (Some(profile_dir), Some(prefix)) = (profile_dir(), prefix) else {
161
+ return;
162
+ };
163
+ let named = prefix.join("lib").join("mlx.metallib");
164
+ if !named.exists() {
165
+ // The print is the point: silently having no metallib means the
166
+ // binaries abort rather than fail, which reports nothing at all.
167
+ println!("cargo:warning=no mlx.metallib at {}", named.display());
168
+ return;
169
+ }
170
+ // Beside the binary the command line runs...
171
+ let binary_side = profile_dir.join("mlx.metallib");
172
+ if named != binary_side {
173
+ link(&named, &binary_side);
174
+ }
175
+ // ...and beside the test binaries.
176
+ let deps = profile_dir.join("deps");
177
+ if deps.is_dir() {
178
+ link(&named, &deps.join("mlx.metallib"));
179
+ }
180
+ }
181
+
182
+ /// Linux's counterpart to the metallib: MLX compiles the CUDA kernels it
183
+ /// did not build ahead of time at run time, and reads NVIDIA's headers
184
+ /// (`cccl`, `cute`, `cutlass`) from one directory above the object that
185
+ /// loads them. The prefix holds them under `include/`; point the two
186
+ /// places a binary looks - `target/<profile>/include` for the test
187
+ /// binaries, `target/include` for the command line - at that directory.
188
+ ///
189
+ /// A symlink to the whole `include`, not a copy: the tree is tens of
190
+ /// megabytes, and MLX reads only the three directories out of it.
191
+ fn link_jit_headers_beside_test_binaries(prefix: Option<&Path>) {
192
+ if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") {
193
+ return;
194
+ }
195
+ let (Some(profile_dir), Some(prefix)) = (profile_dir(), prefix) else {
196
+ return;
197
+ };
198
+ let include = prefix.join("include");
199
+ if !include.join("cccl").is_dir() {
200
+ // The print is the point: without these, the first JIT-compiled
201
+ // kernel fails a long way from here.
202
+ println!("cargo:warning=no cccl headers at {}", include.display());
203
+ return;
204
+ }
205
+ link(&include, &profile_dir.join("include"));
206
+ if let Some(target) = profile_dir.parent() {
207
+ link(&include, &target.join("include"));
208
+ }
209
+ }
210
+
211
+ /// Creates `link` pointing at `named`, replacing whatever is there.
212
+ ///
213
+ /// **Replaced rather than left alone when it exists.** MLX matches its
214
+ /// kernels to the library by name, and after the MLX under it moves
215
+ /// versions an old link still loads and then cannot find the kernel a step
216
+ /// asks for (`Unable to load kernel ...`). That is what a stale link from
217
+ /// the previous dependency did: the tests that did not need the moved
218
+ /// kernel passed and one did not. A link already pointing at `named` is
219
+ /// kept, so the common case still does nothing.
220
+ fn link(named: &Path, link: &Path) {
221
+ if fs::read_link(link).is_ok_and(|target| target == named) {
222
+ return;
223
+ }
224
+ if link.symlink_metadata().is_ok() {
225
+ if let Err(e) = fs::remove_file(link) {
226
+ println!("cargo:warning=could not replace {}: {e}", link.display());
227
+ return;
228
+ }
229
+ }
230
+ if let Err(e) = symlink(named, link) {
231
+ println!("cargo:warning=could not link {}: {e}", named.display());
232
+ }
233
+ }
234
+
235
+ #[cfg(unix)]
236
+ fn symlink(original: &Path, link: &Path) -> std::io::Result<()> {
237
+ std::os::unix::fs::symlink(original, link)
238
+ }
239
+
240
+ #[cfg(not(unix))]
241
+ fn symlink(original: &Path, link: &Path) -> std::io::Result<()> {
242
+ fs::copy(link.parent().unwrap().join(original), link).map(|_| ())
243
+ }
244
+
245
+ /// `target/<triple>/<profile>`, walked back out of OUT_DIR. Cargo gives
246
+ /// build scripts no direct way to ask.
247
+ fn profile_dir() -> Option<PathBuf> {
248
+ let out = PathBuf::from(env::var("OUT_DIR").ok()?);
249
+ // .../target/<profile>/build/<pkg>-<hash>/out, and since cargo 1.100
250
+ // .../target/<profile>/build/<pkg>/<hash>/out: the profile directory is
251
+ // what the `build` directory is in, however deep OUT_DIR is under it.
252
+ out.ancestors().find(|dir| dir.file_name().is_some_and(|name| name == "build"))?.parent().map(Path::to_path_buf)
253
+ }