WorkCase study
Machine learning · Open source · 2026
forge-lm
A small language model I wrote from scratch: tokenizer, transformer and training loop, plus an inference engine in Rust.
$ cargo run --release -- generate ../models/shakespeare.flm \ --prompt "First Citizen:" --tokens 120 --seed 7 First Citizen: We will, as he are, at all the filliful. CORIOLANUS: Sir, we will go Alack their consentsession. BRUTUS: Come, come, you almost well fly. MENENIUS: One friends, I'll depose him. 120 tokens in 0.06s (2000 tokens/s)
- Role
- Everything: the BPE tokenizer, the transformer and trainer in PyTorch, the model file format and the Rust engine.
- Team
- Solo
- Stack
- Python, PyTorch, Rust, GitHub Actions
- Status
- Open source, 2026
Problem
I'd used model libraries without really knowing what goes on inside them. So I wrote each piece myself: bytes to tokens, tokens to logits, weights to a file, and then a second program that reads the file and gets the same numbers.
The rules I set:
- Nothing pretrained. The tokenizer learns from the training text and the model starts from random weights.
- No shortcuts like
nn.MultiheadAttention. Attention, the norm and the feed forward block are all written out. - The inference engine is in Rust with no dependencies.
- It has to train on a normal machine. The released model takes about 11 minutes on 2 CPU cores.
It's a tiny model, 857,216 parameters trained on about a megabyte of Shakespeare. It's not meant to be useful as a chatbot. The point was to build the whole pipeline.
What I built
- Tokenizer
- Byte level BPE. It starts from the 256 byte values and learns 256 merges from the text. It can encode anything and decodes back exactly.
- Model
- A decoder only transformer in PyTorch with RMSNorm, rotary position embeddings and SwiGLU, no biases, and the output layer tied to the embedding.
- Trainer
- AdamW, linear warmup into a cosine schedule, gradient clipping, and a held out validation split.
- Model file
- One
.flmfile: a 32 byte header, the merge table, then all the weights as little endian 32 bit floats. - Engine
- The forward pass again in Rust: embedding, RMSNorm, rotary attention with a key value cache, SwiGLU and sampling.
- Shared tests
- The trainer writes fixture files that the Rust tests read, so the two implementations are checked against each other.
Why I wrote it twice
- BytesTiny Shakespeare, 1.1 MB, last 10% held out
- Tokenizer512 tokens
- Transformer4 layers, 4 heads, width 128, context 128
- model.flmOne 3.4 MB file
- Rust engineHas to match PyTorch
I could've gotten inference outside Python by binding to libtorch or exporting to ONNX. Both would work, but I wouldn't learn much, and they're big dependencies for a model this small.
So I wrote the forward pass a second time in Rust and added a test that compares the two. The trainer saves the logits PyTorch produces for a reference prompt. The Rust engine loads the same model file, runs the same tokens and compares every value. The tokenizer gets the same treatment, with a set of awkward inputs (empty strings, tabs, accented text, Japanese, an emoji) that have to produce the same ids in both languages.
The downside is that any change to the model has to be made in two places. The upside is that if either version is wrong, a test fails with a number I can look at.
The parity test
engine/tests/parity.rs#[test] fn logits_match_pytorch_at_every_position() { let model = load(); let (ids, expected) = reference(); assert_eq!(expected.len(), ids.len()); let mut session = model.session(); let mut worst = 0.0f32; for (&id, want) in ids.iter().zip(&expected) { let got = session.feed(id).unwrap(); assert_eq!(got.len(), want.len()); for (g, w) in got.iter().zip(want) { worst = worst.max((g - w).abs()); } assert_eq!( argmax(got), argmax(want), "the most likely next token differs" ); } println!( "largest difference from PyTorch over {} logits: {worst:e}", ids.len() * expected[0].len() ); assert!(worst < 5e-4, "largest difference from PyTorch is {worst}"); }
$ cargo test --release --test parity logits_match -- --nocapture largest difference from PyTorch over 4608 logits: 1.1570752e-5 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 10 filtered out; finished in 0.01s
Results
| Step | Training loss | Validation loss | Seconds |
|---|---|---|---|
| 0 | 6.270 | 6.274 | 1 |
| 250 | 3.203 | 3.524 | 59 |
| 500 | 2.733 | 3.096 | 121 |
| 1,000 | 2.446 | 3.003 | 297 |
| 1,500 | 2.218 | 3.060 | 412 |
| 2,000 | 2.045 | 3.058 | 526 |
| 2,500 | 1.976 | 3.109 | 639 |
Loss is in nats per token. Random guessing over 512 tokens is about 6.24, which is where it starts.
Validation loss bottoms out around step 1,000 while training loss keeps dropping. After that the model is memorizing the text. The file I released is from the last step, which isn't the best one.
There are 45 Python tests and 20 Rust tests. A few of the things they check: a later token can't change an earlier prediction, the rotary embeddings only depend on relative position, and the model can overfit a tiny text, which tells me the optimizer works. CI runs the Python tests on 3.10 and 3.12 and the Rust tests on Linux and Windows.
Limits
- The model is tiny and so is the training text. The pipeline works end to end, but the output isn't good.
- The engine is plain single threaded 32 bit float math. No SIMD, batching or quantization. It's only fast because the model is small.
- When the context fills up, the engine keeps the second half and starts over from position zero. PyTorch slides the window one token at a time, so the two differ past 128 tokens. The parity test only covers one context.
- Training is CPU only for now.
What's next
Train on a bigger dataset, since more steps on the same megabyte won't help, and release the checkpoint with the best validation loss. On the Rust side I want a sliding context so long generations match PyTorch too.
Have a question about this project?