File size: 17,322 Bytes
fac4d07 36fe364 fac4d07 18de23f fac4d07 e8f30e4 fac4d07 18de23f fac4d07 36fe364 18de23f fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 18de23f 36fe364 18de23f 36fe364 18de23f fac4d07 afb65d1 fac4d07 36fe364 fac4d07 2109241 fac4d07 18de23f fac4d07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | # Rust training and inference
The native implementation uses **tch-rs 0.22.0 and LibTorch 2.9.0**. Training,
evaluation and inference run without a Python interpreter. The Python code is
retained as a numerical reference and as the original synthetic-data generator.
The current repository weights remain loadable by both implementations.
The original Python artifact lives in `python-reference/`; numerical parity
fixtures refer to that archive even when a later artifact is selected at root.
Run commands below from the repository root. `infer` prints proposals. The
explicit `task-benchmark` command executes validated actions through a fixed
dispatcher in isolated Emacs fixtures; it never evaluates model-generated Lisp.
For a reusable agent workflow, see [`$lispm-train`](../skills/lispm-train/SKILL.md).
To install it in Codex, copy the `skills/lispm-train` folder into your configured
Codex skills directory (normally `~/.codex/skills/`), preserving any existing
installation you have customized. Invoke `$lispm-train` from a model checkout.
## Build
Install Rust and a matching LibTorch 2.9.0 CPU distribution, then set `LIBTORCH`
to the directory containing `include/` and `lib/`. Do not bypass the version check.
See [tch-rs](https://github.com/LaurentMazare/tch-rs) for native platform support.
On macOS Apple Silicon, the included helper downloads a pinned official PyTorch
archive, verifies its SHA-256 and extracts only C++ headers and shared libraries:
```sh
bash scripts/setup-libtorch.sh
export LIBTORCH="$PWD/.libtorch/2.9.0/torch"
cargo build --release --locked
```
The helper does not install or execute Python. `build.rs` embeds this library
directory as a runtime search path. Keep the libraries at that location or set
the platform's dynamic-library search path when moving the executable.
The archive and native build outputs are excluded from published model files.
The tested target is CPU on macOS arm64; GPU performance is not claimed here.
## Infer
```sh
cargo run --release --locked -- infer --model . 'save the current buffer'
cargo run --release --locked -- infer --model . 'open file "notes.el"' --format json
cargo run --release --locked -- infer --model . 'open file "notes.el" then search forward for "TODO"'
```
The artifact is still `config.json` plus `model.safetensors`. All tensors must be
finite CPU float32 values with the exact expected names and shapes. The loader
also validates label order, vocabulary IDs, architecture and admission settings.
Unrecognized words retain their hashed character features; there is no runtime
phrase whitelist. Invalid syntax, unsupported intent and uncertain predictions
are refused. Other runtime failures are reported separately.
## Train from scratch
```sh
cargo run --release --locked -- train --data data/training.json --output experiments/my-rust-model --steps 3200 --seed 42
cargo run --release --locked -- evaluate --model experiments/my-rust-model --data data/benchmark.json --output experiments/my-rust-evaluation.json
```
The output directory must be new. `data/training.json` includes all 16,404
original training rows, 1,182 calibration rows, hard-example membership and the
immutable selection reference. `data/semantic-training.json` appends 593 reviewed
training examples, giving 16,997 rows with exactly the same calibration and
reference data. `data/refined-semantic-training.json` is a further append-only
training input with 235 more contrast examples and 17,232 training rows for the
final candidate. Calibration remains unchanged; the earlier datasets are preserved.
Rust validates their identities before training. The
trainer does not read command benchmarks, execution tasks or the numerical test
fixtures. `data/benchmark.json` is the default command evaluation input; the
original single-action `data/evaluation.json` remains available for reproducing
historical reports.
Training uses balanced action sampling, hard positive/negative examples, word
dropout, label smoothing, AdamW, gradient clipping and a cosine learning-rate
schedule. Checkpoints and thresholds are selected using calibration only, with
the original supported-coverage/error constraints and confidence ceilings.
If no checkpoint qualifies, the run fails without replacing an existing model.
Rust and Python use different sampling RNGs and different LibTorch versions.
An identical seed does not imply identical initialization, batches or trained
weights. The archived Python checkpoint and an independently retrained
Rust model must therefore be evaluated and reported separately.
To reproduce the expanded-data scratch-run settings in a new directory:
```sh
cargo run --release --locked -- --threads 2 train --data data/semantic-training.json --output experiments/my-semantic-scratch --steps 6400 --seed 42
```
The training process reads only the selected training input. Existing command
regressions, task fixtures and independently authored blind cases remain
evaluation inputs, never training or checkpoint-selection inputs.
## Fine-tune an explicit artifact
The native CLI can initialize from an existing configuration and SafeTensors
pair. Both `--init-model` and `--learning-rate` are required together:
```sh
cargo run --release --locked -- --threads 2 train --data data/semantic-training.json --output experiments/my-semantic-finetune --steps 3200 --seed 42 --init-model python-reference --learning-rate 0.0002
```
Here `0.0002` is an explicit example setting, not a generally optimal learning
rate. The rate must be finite, positive and below `0.002`; the cosine schedule
ends at one twentieth of the initial rate (`0.00001` in this example).
Fine-tuning retains the source vocabulary, architecture and character-feature
dimensions exactly. It does not add vocabulary entries from the new dataset.
New spellings still use the existing unknown-word and hashed character features.
AdamW starts with fresh optimizer state; this is not an interrupted-run resume.
The implementation remains CPU based.
The trainer loads private copies of the exact source `config.json` and
`model.safetensors` bytes. Their hashes appear in the training report's
`initialization` metadata, separately from the new output artifact's identity.
It rechecks the original files before publication and fails if they changed.
Training data, calibration constraints and output-directory isolation are the
same as for from-scratch training.
Calibration also considers the unmodified initial tensors at step zero. A report
with `selected_step: 0` means **no optimizer-updated checkpoint was selected**;
it does not demonstrate learning from the added examples. Always compare the
selected artifact against the source on the same frozen benchmarks.
Omitting both flags retains from-scratch training. The Emacs project and C FFI
training workflow also continue to initialize from scratch; these CLI flags do
not change that workflow or add optimizer-resume or GPU support.
## Recorded native retraining
The included [`rust-trained/`](../rust-trained) candidate used seed 42, two CPU
threads and 3,200 optimizer steps. Training took **317.76 seconds** on this run;
calibration-only selection retained step **1,000**, with probability 0.8 and
margin 0.0. This is a recorded run duration, not a cross-language speed benchmark.
| Frozen cohort | Python reference correct / wrong / refused | Rust candidate correct / wrong / refused |
| --- | ---: | ---: |
| Historical Emacs, supported (187) | 173 / 2 / 12 | 169 / 5 / 13 |
| Historical LispM, supported (182) | 176 / 0 / 6 | 178 / 0 / 4 |
| Robustness, supported (286) | 266 / 6 / 14 | 257 / 4 / 25 |
| Robustness, novel-word subset (49) | 44 / 1 / 4 | 41 / 1 / 7 |
For unsupported robustness requests, the Python reference falsely accepted 11 of 126;
the native candidate accepted 10. The candidate has lower supported coverage,
so it is **not the default checkpoint**. No threshold or checkpoint was tuned
after these results. Use `--model rust-trained` to select it explicitly.
Complete results and artifact identities are in
[`rust-evaluation.json`](../rust-evaluation.json),
[`rust-training-evaluation.json`](../rust-training-evaluation.json) and
[`training-report.json`](../rust-trained/training-report.json).
## Expanded-data scratch run
`semantic-from-scratch/` retains the first expanded-data candidate and its
training report. It used seed 42, two CPU threads and 6,400 optimizer updates.
The recorded duration was **531.124 seconds**; calibration selected step
**4,700**. It has **189,425 parameters**, with the same admission thresholds as
the reference: probability **0.8**, margin **0.0**.
| Existing evaluation cohort | Python reference correct / wrong / refused | Expanded-data scratch correct / wrong / refused |
| --- | ---: | ---: |
| Ordered two-action programs (2,256) | 2,028 / 19 / 209 | 2,078 / 8 / 170 |
| Robustness supported requests (286) | 266 / 6 / 14 | 272 / 6 / 8 |
Unsupported robustness acceptance fell from **11/126 to 8/126**, and real Emacs
task execution remained **30/30**. However, false acceptance in the two
historical unsupported cohorts rose from **0 to 1** and **1 to 2**. This candidate
was **not promoted**: aggregate improvements do not override a failed historical
nonregression check. These are existing regression cohorts, not fresh blind
evidence, and thresholds were not raised to obtain the supported improvements.
The bound reports are
[`semantic-from-scratch-evaluation.json`](../semantic-from-scratch-evaluation.json),
[`semantic-from-scratch-benchmark-evaluation.json`](../semantic-from-scratch-benchmark-evaluation.json)
and [`semantic-from-scratch-task-evaluation.json`](../semantic-from-scratch-task-evaluation.json).
The archived fine-tuning attempt uses `semantic-warm-start/` and
`semantic-warm-start-evaluation.json`,
`semantic-warm-start-benchmark-evaluation.json` and
`semantic-warm-start-task-evaluation.json`. It starts from the historical model
on the same `data/semantic-training.json` input. It was also not promoted because
supported errors and refusals regressed.
The final candidate uses `semantic-trained/` and the separate
`semantic-evaluation.json`, `semantic-benchmark-evaluation.json` and
`semantic-task-evaluation.json` reports, with the additional contrast examples in
`data/refined-semantic-training.json`. Each artifact remains bound to its own
training bytes; none changes the earlier `rust-trained/` input.
## Final refined candidate: optional only
`semantic-trained/` fine-tuned `semantic-from-scratch/` on the 17,232-row refined
input, using seed 42, two CPU threads, 1,600 updates and an initial learning rate
of **0.0001**. Calibration selected step **400**. The run took **128.661 seconds**
and retained **189,425 parameters**, probability **0.8** and margin **0.0**.
Reproduce its settings in a new directory:
```sh
cargo run --release --locked -- --threads 2 train --data data/refined-semantic-training.json --output experiments/my-refined-model --steps 1600 --seed 42 --init-model semantic-from-scratch --learning-rate 0.0001
```
Existing two-action results improved from **2,028 / 19 / 209** to
**2,071 / 8 / 177** correct / wrong / refused. Robustness supported results
improved from **266 / 6 / 14** to **271 / 6 / 9**, and unsupported acceptance
fell from **11/126 to 6/126**. Real Emacs tasks remained **30/30**.
The final independent blind audit also improved: supported singles went from
**107 / 1 / 10** to **114 / 1 / 3**, pairs from **54 / 2 / 15** to **62 / 0 / 9**,
and unsupported acceptance from **2/88 to 1/88**. This did not satisfy every
historical gate: LispM single/pair refusals increased, historical Emacs false
acceptance rose from **0/56 to 1/56**, and the existing duplicate-tab family rose
from **3/24 to 4/24**. The root therefore remains `python-reference/`; select the
candidate explicitly with `--model semantic-trained`.
See the [benchmark methods and full comparison](benchmarks.md),
[candidate training report](../semantic-trained/training-report.json),
[baseline blind report](../blind-baseline-evaluation.json) and
[candidate blind report](../blind-semantic-evaluation.json). No training,
threshold or checkpoint changes followed the blind audit.
## Command composition and execution benchmarks
The expanded benchmark adds all 2,256 ordered pairs of distinct actions to the
three original command cohorts. Rust regenerates it into a fresh path with
`prepare-benchmark`; `evaluate` measures exact full-program agreement, including
operation order and literal arguments. The original datasets and reports keep
their historical identities. The new compositions use filtered historical
wording, so their scores must be measured separately from the older Python
recombination report.
The separate `task-benchmark` operation predicts each reviewed instruction,
starts a clean batch Emacs child, and measures final-state success in disposable
core Emacs fixtures. Reports distinguish success, wrong state, refusal,
execution error and blocked actions, with step-count and scenario breakdowns.
It measures neither external LispM applications nor long-horizon planning.
See the [benchmark guide](benchmarks.md) for reproducible commands and bounds.
Reports identify the selected root separately from the archived Python reference
and independently retrained candidate:
| Evidence | Root model | Python reference | Earlier Rust candidate |
| --- | --- | --- | --- |
| Expanded command benchmark | [benchmark-evaluation.json](../benchmark-evaluation.json) | [python-reference/benchmark-evaluation.json](../python-reference/benchmark-evaluation.json) | [benchmark-rust-training-evaluation.json](../benchmark-rust-training-evaluation.json) |
| Real Emacs task execution | [emacs-task-evaluation.json](../emacs-task-evaluation.json) | [python-reference/emacs-task-evaluation.json](../python-reference/emacs-task-evaluation.json) | [emacs-task-rust-training-evaluation.json](../emacs-task-rust-training-evaluation.json) |
For ongoing retraining, the [Emacs/C FFI workflow](training-workflow.md) freezes
both suites and runs both models against identical inputs. Task-enabled projects
require both command and execution nonregression before finalization. A failed
runner or missing task report cannot become an accepted model.
## Validate the migration
```sh
cargo fmt --all --check
cargo clippy --workspace --all-targets --all-features -- -D warnings -D clippy::unwrap_used -D clippy::expect_used -D clippy::panic -D clippy::todo -D clippy::unimplemented -D clippy::indexing_slicing
cargo test --workspace --all-targets --all-features -- --nocapture
cargo run --release --locked -- evaluate --model . --data data/evaluation.json --output experiments/my-regression-report.json
```
`tests/fixtures/` contains frozen Python 2.8 references for tokens, logits,
accepted/refused decisions, all legal one/two-action renderings, gradients and a
clipped AdamW update. Those tests use fixed weights and disabled dropout, with
explicit float32 tolerances. They run entirely in Rust. The frozen evaluation
corpora were already exposed during prior development; migration evaluation is
a regression measurement, not a newly blind benchmark.
The recorded macOS arm64 CPU run passed 40 unit tests, 3 integration tests and
strict Clippy checks. All 914 frozen decisions and 2,304 legal program renderings
matched Python. The fixed-batch maximum absolute differences for logits,
gradients and the AdamW-updated parameters were zero on this machine; tests keep
explicit tolerances for float32 operations on other hardware. The additional
parser/argument witnesses cover 1,767 and 1,553 cases. The optional Python
reference suite passed 98 tests. See
[`rust-migration-validation.json`](../rust-migration-validation.json).
Regenerating references is an explicit development operation requiring Python:
```sh
uv run --python 3.11 --with-requirements requirements.txt python scripts/export_rust_reference.py
```
Review regenerated data and fixture changes before accepting them. Tests compare
against the archived `python-reference/` artifact, not whichever candidate is at
root. Promoting a new default does not require changing the numerical oracle.
Fixtures must not be silently regenerated to hide a changed Rust prediction or
gradient.
## Module boundaries
| Module | Responsibility |
| --- | --- |
| `actions` | Parsed instructions, validated action arguments and fixed Lisp rendering |
| `config`, `tokenizer` | Artifact invariants, word IDs and BLAKE2b character fragments |
| `model` | Registered Transformer parameters, forward/backward graph and artifact I/O |
| `inference` | Confidence admission and proposal construction |
| `metrics`, `training` | Calibration selection, sampling, optimizer and new checkpoints |
| `runtime` | Shared LibTorch thread configuration and training RNG ownership |
| `dataset`, `workflow` | Authored examples, run snapshots, comparisons and explicit activation |
| `native-api`, `emacs-module` | C ABI jobs and Emacs native adapter |
| `evaluation` | Fixed-cohort outcomes, concrete mistakes and refusals |
| `composition` | Reproducible ordered-pair cohorts with typed expected programs |
| `task_benchmark` | Isolated Emacs execution, goal-state outcomes and bound comparisons |
| CLI | Explicit filesystem and terminal effects |
|