Model pipeline — train in Julia, run in Rust, prove they agree
The model is defined twice — once in Julia for training, once in Rust for real-time inference — and the two are kept equal by a file format and tests, not by a shared runtime. (ADR-0003, proposed)
Why not a general model runtime in the plugin
- ONNX looks like the obvious bridge, but Julia’s ONNX export is thin (ONNX.jl and ONNXNaiveNASflux.jl cover common layers, not scans or custom SSM kernels), and the Rust runtimes are made for batches, not for one sample at a time on the audio thread:
ortwraps ONNX Runtime (C++, its own threads and allocations),tractis pure Rust but still does per-call graph work. - An SSM at inference is tiny and recurrent: per sample
x ← Ā x + B̄ u,y = C x + D u, plus a few nonlinearities. Hand-written Rust with preallocatedf32arrays is shorter than any runtime integration, has no allocations, and can be SIMD-vectorised (diagonalAas in S5/Mamba makes the update elementwise). - Burn and candle (Rust ML frameworks) can load safetensors directly and are an option for offline checks, but they bring the same real-time concerns.
The hand-off
models/<instrument>/<version>/
manifest.toml # architecture name + version, hyperparameters, sample-rate handling,
# tensor list with shapes ([tensors], generated), training commit,
# dataset hash, license + sources (ADR-0007)
model.safetensors # all weights, f32, little-endian, named "layers.0.A_log" etc.
golden.safetensors # inputs and expected outputs (and optionally states) for tests
LICENSE, ATTRIBUTION.md # from the manifest's license and sources
- safetensors: a JSON header plus raw tensor bytes. No pickle, no code execution, memory-mappable. Rust reads it with the
safetensorscrate incrates/model-format(instruments-model-format; the piano’s schema there and inInstrumentsTraining.PianoModelFile, Piano model file). Writer:write_model(dir; tensors, manifest, golden)intraining/(packageInstrumentsTraining), built on SafeTensors.jl (SafeTensors.serialize);read_model(dir)reads a directory back. It also writesLICENSEandATTRIBUTION.mdand refuses a manifest withoutlicenseandsources(ADR-0007). - Column-major vs row-major — the rule: a Julia array of size
(m, n, …)is stored with safetensors shape[m, n, …](the Julia shape, not reversed) and its elements in row-major order, i.e. the bytes ofpermutedims(A, ndims(A):-1:1). So indices survive: JuliaA[i, j]isA[i-1][j-1]in Rust or NumPy, and a JuliaWwithy = W * xis a[out, in]row-major matrix in Rust. (Reversing the shape and permuting the bytes would garble every non-square tensor; reversing the shape without permuting is the zero-copy alternative, rejected because Rust would see every matrix transposed.) Tested by hand against the raw bytes of a 2×3 and a 3×2 matrix intraining/test/runtests.jl. - Names and shapes are the contract. The Rust loader checks every tensor’s presence, shape and dtype against what the architecture version expects and refuses anything else.
- Versioning: the manifest names
architecture = "s5-v1". A change of the Rust inference code that changes outputs bumps the version.
Sample rate: export continuous, discretise in Rust
Hosts run at 44.1, 48, 88.2, 96 kHz and more. A model trained at 48 kHz and run at 96 kHz is wrong unless its time constants are rescaled. Continuous-time SSMs (S4/S5 style) solve this elegantly: export the continuous parameters (Λ, B, C, D, log Δ as learned at the training rate) and discretise in Rust in initialize for the host’s sample rate (zero-order hold: Ā = exp(Λ Δ'), B̄ = Λ⁻¹(Ā − I) B, with Δ' = Δ · f_train / f_host). Non-linear parts that are not rate-aware may still need resampling or training at several rates; see Problem log.
Julia side
- Lux.jl (explicit parameters as a nested
NamedTuple— trivially walked into named tensors on export) with Zygote or Enzyme for gradients; Optimisers.jl; CUDA.jl/Reactant.jl for GPU. Flux.jl works too; Lux makes export cleaner. - A Julia reference recurrence (the same per-sample loop Rust runs, not the parallel scan used for training) produces the golden vectors. That catches scan-vs-recurrence mismatches before Rust is involved.
training/Project.toml+Manifest.tomlare committed;JULIA_PROJECT=@.is set by the dev shell.
Agreement tests
- Golden vectors (Rust):
cargo testloadsgolden.safetensors, runs the Rust inference at the training rate and compares within a tolerance (e.g. max abs error < 1e-4 forf32). - Optional, the other direction (Julia → Rust via C ABI):
crates/dspalso builds as acdylibwith a tinyextern "C"API; Juliaccalls it and compares with its own model on random inputs during training. That turns any drift into a failing Julia test immediately. - Block-size independence: the same input in blocks of 1, 64, 513 samples gives the same output.
- Real-time: a benchmark of
processper block (criterion), andassert_no_allocin debug builds.