When I first used PyTorch, I was really impressed by it. It had everything you need for a deep learning framework, the documentation is insanely well written and you can actually hand-do the math behind every function and learn how every module works. In order to learn deep learning from scratch I wanted to know the math behind each function and that led me to writing each function by hand.. Around that time I remember reading Karpathy's micrograd and also George Hotz's tinygrad; of which I quickly became a fan.. This is just me trying to replicate and make PyTorch better.
- Trained side by side on the same model, stackgrad's loss matches PyTorch's to 1.8e-15.
- A 22.7M-parameter model reaches a validation loss of 1.399 on TinyStories in 71 minutes on one RTX 3090.
- My attention kernel runs 6.7x faster than MLX's built-in attention on the story model.
- Recording each decode step once and replaying it (capture) makes the per-token pass through Qwen3's layers 2.15x faster, with the same tokens out.
- Qwen3-0.6B, loaded from its published weights, gives the same outputs as Hugging Face's version to within 5.1e-5.
- Retrieval finds the right Wikipedia paragraph in its top three 91.5% of the time, and 55% of answers then contain the right answer.
- Four attempts at better grade-school math failed. Fine-tuning with LoRA solved 29 fewer of 250 problems, reinforcement learning with GRPO and training on its own correct answers changed nothing beyond chance, and a calculator tool solved 110 fewer.
The code is at github.com/samitmohan/stackgrad, and it ran on my Apple M4 laptop and one RTX 3090 (thank you, office).
Autograd
A neural network is a function with adjustable numbers inside it, the weights. Numbers go in (pixels, token ids), numbers come out, and a large language model has billions of weights. A new network starts random and gives useless answers. Learning means nudging the weights until the answers get good.
For that you need a loss, one number that says how wrong the network is (lower is better), and the gradient of the loss with respect to every weight: how much the loss moves if that weight moves a little. The gradient points uphill, so you step each weight a little downhill.
The smallest network is . We want output for input , so the loss is , which at is . The gradient , which is , is negative, so raising lowers the loss. One step with a learning rate of gives , an output of and a loss of , twenty-five times smaller.
Doing this for a billion weights across dozens of layers takes a program, and that program is the first piece of stackgrad. It starts where micrograd starts, with a number that computes its own gradient, and takes tinygrad's design: a short list of basic operations with known gradients, and everything else composed from them.
The chain rule as a program
Any computation is a chain of small steps (multiply, add, exponentiate), and calculus has a rule for chains. If a car goes twice as fast as a bike and the bike goes four times as fast as a walker, the car goes times as fast as the walker. Rates along a chain multiply: if depends on and on , then .
Take the loss from above at , as three steps: , then , then . Now walk back from the loss, starting from a gradient of 1. Squaring has slope , so . Subtracting 6 doesn't change the slope, so . Multiplying by multiplies the slope by , so , the number we got by hand.
That's backpropagation. The forward pass records each step and its inputs as a graph, and the backward pass walks the graph from the loss back, each step multiplying the gradient by its own slope. A value that feeds several steps sums the gradients that come back to it. One backward pass costs about two forward passes, however many weights there are.
x = 2, w = -0.5, b = 3
Nineteen operations
A stackgrad tensor remembers the operation that produced it. An operation is a small class whose forward computes the result and whose backward takes the result's gradient and returns one per input. For , if the gradient arriving at is , then gets and gets . Simplified from stackgrad/mlops.py:
class Mul(Function):
def forward(self, x, y):
self.x, self.y = x, y # kept for backward
return x * y
def backward(self, grad): # grad is dL/dz for z = x * y
return grad * self.y, grad * self.xCalling backward() on the loss sorts the graph so every tensor comes after its inputs, then walks it from the loss back, handing each operation the gradient at its output. Simplified from tensor.py:
def backward(self):
topo, visited = [], set()
def build(t):
if t not in visited:
visited.add(t)
if t._ctx:
for parent in t._ctx.parents:
build(parent)
topo.append(t)
build(self)
self.grad = ones_like(self.data) # dL/dL = 1
for t in reversed(topo): # from the loss back to the inputs
if t._ctx:
for parent, g in zip(t._ctx.parents, t._ctx.backward(t.grad)):
parent.grad = g if parent.grad is None else parent.grad + gAll of stackgrad's gradients live in mlops.py, in nineteen operations: add, multiply, exponential, logarithm, sum, max, reshape, broadcast, matrix multiplication and a few more. Everything else (subtraction, division, relu, softmax, layer norm, convolution) composes them, so it gets its gradient for free.
Checking the gradients
A wrong gradient doesn't crash anything. The model trains worse and nothing points you to the cause, so stackgrad checks its gradients two ways. The first is the definition of a derivative. Nudge an input up by a tiny , then down, and measure the slope:
backward() matches the measured slope for every input.The second is PyTorch. I trained the same 8.3M-parameter language model in both for 200 steps, with the same starting weights, batches and optimizer.
Laziness
Typing c = a @ b records the multiplication and returns a tensor that knows its shape and number type (dtype) but holds no numbers. Reading it through .numpy(), .item(), printing, .backward() or .realize() runs the graph.
c = a @ b # recorded: c.shape is known, nothing has run
y = layer(x) # recorded and returned: still nothing has run
y.numpy() # realize: every operation y depends on runs, inputs first, once eachAn operation nobody reads never runs. I took the idea from tinygrad (thanks, George). Each operation in mlops.py states its output's shape and dtype up front, so the next operation can be recorded before the last one has run. It doesn't buy me much yet: on the Apple GPU a lazy step takes 4.8 ms against 4.09 ms eager. Laziness pays off once something fuses the recorded graph into fewer kernels, which the decoding section does.
Tokenization
A language model reads integers, so a tokenizer cuts text into tokens from a fixed list (the vocabulary) and replaces each token with its position in that list. Letters make a tiny vocabulary, but sequences get long and the model has to learn spelling first. Whole words make sequences short, but the vocabulary explodes, and a typo or a new name gets no token at all. Subwords sit in between: a common word gets one token and a rare one gets a few pieces.
stackgrad uses byte-level byte-pair encoding (BPE), same as GPT-2, GPT-4, Qwen. It starts from the 256 possible bytes. Then it learns merges. Find the most frequent adjacent pair in the training text, add it to the vocabulary as a new symbol and repeat until the vocabulary is the size we gave it.
Say the training text has low 5 times, lower 2 times, newest 6 times and widest 3 times. Count every adjacent pair, weighted by how often its word appears, merge the winner, and count again:
| Merge | Winning pair | Count | newest after it |
|---|---|---|---|
| 1 | e s | 9 (6 from newest, 3 from widest) | n e w es t |
| 2 | es t | 9 | n e w est |
| 3 | l o | 7 (5 from low, 2 from lower) | n e w est |
| 4 | lo w | 7 | n e w est |
After four merges low is one token. You can watch this happen on a visualiser.
A 10,000-token vocabulary trains on TinyStories in 44.7 s and decodes its own encoding back to the text byte for byte.
14 tokens from 60 bytes with the tinystories-10k vocabulary.
Merges for one pre-token
- ␣time
- ␣time
- ␣time
- ␣time
- ␣time
4 merges, from bytes to final tokens.
With GPT-2's published merges, the tokenizer matches tiktoken, OpenAI's tokenizer library, id for id, and with Qwen3's it matches Hugging Face's. Qwen's tokenizer splits every digit into its own token so numbers stay easy to do arithmetic on (smart).
Chat models also reserve special tokens that ordinary text never produces. <|endoftext|> ends a document, <|im_start|> and <|im_end|> mark who is speaking.
The transformer
stackgrad's model is a decoder-only transformer (it predicts each token from the ones before it), the architecture behind GPT, Llama and Qwen, in the modern form Stanford's CS336 teaches. Let's follow one token through it.
The token id picks a row of a learned table: numbers (512 in the story model). Think of that vector as the model's notes on the token. Each layer reads the notes and adds a correction, and no layer erases what came before. The running sum, from the bottom layer to the top, is the residual stream.
Attention lets a position gather information from earlier ones. Each position computes a query ("what am I looking for?"), a key ("what do I contain?") and a value ("what do I pass on?"). In "Max wagged his tail", the query at "his" can ask for a name that came earlier, the key at "Max" matches, and Max's value flows into "his". Query dot key gives a score, softmax turns scores into weights that sum to 1 and the output is the weighted sum of values:
The mask holds wherever a position would look ahead so nothing sees the future it is predicting (prevents cheating) and keeps scores from growing with vector length. A layer runs several of these heads side by side. In grouped-query attention, several query heads share one set of keys and values to save memory during generation. A great visualisation is here.
Attention alone ignores word order: shuffle the earlier tokens and the weighted sum comes out the same. RoPE fixes this with rotation. Split each query and key into pairs of numbers and treat each pair as a clock hand. A token at position turns its hands ticks. A score is a dot product, and the dot product of two hands depends only on the angle between them, so a score sees how far apart two tokens are and not where they sit. Each pair turns at its own speed, like a clock's second, minute and hour hands: fast pairs tell neighbours apart and slow pairs track long distances.
gap p − k = 4
Then each position works on its notes alone, in a feed-forward network: widen the 512 numbers to 1,344, apply a nonlinearity, and shrink back to 512. SwiGLU makes two widened copies and multiplies them, so one acts as a dimmer on the other. SiLU sends a negative number in the first copy to near zero and lets a positive one through, and that decides how much of the matching number in the second copy survives. Before attention and before the feed-forward, RMSNorm rescales the notes to a standard size, a root mean square of 1, so no layer gets numbers too big or too small to work with. Learned gains then turn single dimensions back up.
Two lines in stackgrad/gpt.py:
def forward(self, x, cache=None, pad=None):
x = x + self.attn(self.attn_norm(x), cache, pad) # attention, added to the residual stream
return x + self.ffn(self.ffn_norm(x)) # feed-forward, added the same wayStack that and we have GPT. At the top, a final normalization and one more matrix give every vocabulary entry a score, its logit, and softmax turns those into probabilities. Qwen3-0.6B, loaded later, is the same design, bigger, so one class covers both models:
| Setting | Story model (CS336) | Qwen3-0.6B |
|---|---|---|
| Vocabulary | 10,000 | 151,936 |
| Vector width | 512 | 1,024 |
| Layers | 4 | 28 |
| Query heads / key-value heads | 16 / 16 | 16 / 8 |
| Width of one head | 32 | 128 |
| Parameters | 22,696,448 | 596,049,920 |
Training it
Training needs a loss. For next-token prediction it's cross-entropy, the negative log of the probability the model gave the token that came next. Probability 1 costs 0, and 0.25 costs . Random guessing among 10,000 tokens scores , and the untrained model's first step scores 9.23.
The data is TinyStories, millions of short children's stories GPT-4 wrote in a small child's vocabulary. A small model learns to write coherent stories from it in an hour on one GPU. Training repeats one step 40,000 times on 32 random windows of 256 tokens (train_gpt.py, condensed):
for step in range(1, steps + 1):
opt.lr = cosine_lr(step, max_lr, min_lr, warmup, steps) # warmup, then cosine decay
x, y = get_batch(train, batch, context) # y is x shifted by one token
loss = cross_entropy_loss(model(x), y)
opt.zero_grad()
loss.backward()
clip_grad_norm(params, 1.0)
opt.step() # AdamWPlain gradient descent moves every weight by the same multiple of its gradient. AdamW (Adam with decoupled weight decay) keeps two running averages per weight, of its gradient and of its squared gradient, and divides the first by the square root of the second. A weight whose gradient points the same way step after step gets a full step, even when that gradient is small. A weight whose gradient flips sign from batch to batch gets a small one. AdamW also pulls every weight a little toward zero on every step. The learning rate warms up over 1,000 steps while those averages are still noisy, then follows a cosine down to 0.0001 so the model settles. Clipping rescales any gradient longer than 1, so one odd batch can't wreck the weights. Every 500 steps we score held-out stories to catch memorizing.
Validation loss falls from 2.807 after the first 500 steps to 1.399, under CS336's target of 1.45, in 71 minutes. The two curves track each other the whole way so the model handles unseen stories about as well as its training ones. A sample from the final checkpoint, cut off at its length limit:
Once upon a time, there was a big dog named Max. Max liked to chew on his toys all day long. He lived in a small house with his friend, a little girl named Lily.
One day, Max and Lily were playing in the yard. Max found a shiny thing on the ground. He picked it up with his mouth and showed it to Lily. "Look, Lily! I found a shiny thing!" Max wagged his tail and barked.
Lily looked at the shiny thing and said, "Names, dialogue, a dog wagging its tail, all trained through the autograd engine from the start of this post.
When sampling, temperature divides the logits before the softmax: below 1 sharpens toward the likeliest token, above 1 flattens, and 0 always takes the likeliest, which is called greedy decoding. Top-p keeps the smallest set of likeliest tokens whose probabilities add up to p.
Which parts matter
Do the modern parts (RMSNorm before attention and the feed-forward, RoPE, SwiGLU) matter? CS336's ablations take each one out and retrain the story model for 10,000 steps, a quarter of the full run.
| Change | Loss added (as built: 1.524) |
|---|---|
| RMSNorm after attention and the feed-forward, where the original transformer put it | +0.013 |
| A plain SiLU layer instead of SwiGLU, same size | +0.03 |
| No position information at all | +0.085 |
The model with no position information still learns, because the causal mask leaks position: each token sees a different number of earlier tokens, and a head can count them (Haviv et al.).
Without RMSNorm nothing rescales the vectors between layers, and at the full learning rate of 0.001 the loss blew up and stopped being a number at step 627. At a lower rate, 0.0003, it trains but ends at 1.699.
One more switch, TransformerLM(..., attn_res=True), swaps the residual stream's plain sum for Block Attention Residuals, where each layer takes a learned, weighted mix of the earlier layers' outputs. My Attention Residuals post measures it on a small model.
GPUs
Most of a model's arithmetic is one operation over huge arrays. A CPU has a handful of fast cores that run complicated programs step by step. A GPU has thousands of simple cores running one small program, a kernel, on different pieces of an array at once.
stackgrad runs on three array libraries with NumPy's interface: NumPy on the CPU, MLX on the Apple laptop's GPU, and CuPy on an NVIDIA GPU. Each op in mlops.py gets a module, xp, with the same small set of functions, so one copy of every gradient runs everywhere.
A GPU does not win by default
Every kernel launch pays a fixed cost while the CPU describes the work and the GPU schedules it. Think of a bus that takes as long to leave the depot with one passenger as with fifty. For a small array that fixed cost is the whole cost. Multiplying a thousand numbers takes 3.1 µs with NumPy, 7.6 µs on the Apple GPU and 42 µs on the NVIDIA GPU. On ten million it's 863 µs, 778 µs and 99.7 µs, and the NVIDIA GPU wins by 8.7x.
The same chain through stackgrad Tensors, so it adds the framework's Python cost per op.
Every measurement as a table
| device | path | floats | µs per op |
|---|---|---|---|
| CPU (NumPy) | raw | 1,000 | 0.4 |
| CPU (NumPy) | sync every op | 1,000 | 0.66 |
| CPU (NumPy) | stackgrad | 1,000 | 3.09 |
| CPU (NumPy) | raw | 10,000 | 0.9 |
| CPU (NumPy) | sync every op | 10,000 | 1.3 |
| CPU (NumPy) | stackgrad | 10,000 | 4.08 |
| CPU (NumPy) | raw | 100,000 | 6.82 |
| CPU (NumPy) | sync every op | 100,000 | 7.21 |
| CPU (NumPy) | stackgrad | 100,000 | 10 |
| CPU (NumPy) | raw | 1,000,000 | 64.07 |
| CPU (NumPy) | sync every op | 1,000,000 | 64.33 |
| CPU (NumPy) | stackgrad | 1,000,000 | 66.91 |
| CPU (NumPy) | raw | 10,000,000 | 863.7 |
| CPU (NumPy) | sync every op | 10,000,000 | 850.3 |
| CPU (NumPy) | stackgrad | 10,000,000 | 863.1 |
| Apple GPU (MLX) | raw | 1,000 | 7.07 |
| Apple GPU (MLX) | sync every op | 1,000 | 139 |
| Apple GPU (MLX) | stackgrad | 1,000 | 7.59 |
| Apple GPU (MLX) | raw | 10,000 | 4.94 |
| Apple GPU (MLX) | sync every op | 10,000 | 127.4 |
| Apple GPU (MLX) | stackgrad | 10,000 | 7.63 |
| Apple GPU (MLX) | raw | 100,000 | 6.46 |
| Apple GPU (MLX) | sync every op | 100,000 | 152.2 |
| Apple GPU (MLX) | stackgrad | 100,000 | 8.86 |
| Apple GPU (MLX) | raw | 1,000,000 | 40.85 |
| Apple GPU (MLX) | sync every op | 1,000,000 | 255.7 |
| Apple GPU (MLX) | stackgrad | 1,000,000 | 43.62 |
| Apple GPU (MLX) | raw | 10,000,000 | 775.2 |
| Apple GPU (MLX) | sync every op | 10,000,000 | 1083 |
| Apple GPU (MLX) | stackgrad | 10,000,000 | 777.5 |
| NVIDIA GPU (CuPy) | raw | 1,000 | 11.34 |
| NVIDIA GPU (CuPy) | sync every op | 1,000 | 34.96 |
| NVIDIA GPU (CuPy) | stackgrad | 1,000 | 41.89 |
| NVIDIA GPU (CuPy) | raw | 10,000 | 11.21 |
| NVIDIA GPU (CuPy) | sync every op | 10,000 | 32.26 |
| NVIDIA GPU (CuPy) | stackgrad | 10,000 | 39.48 |
| NVIDIA GPU (CuPy) | raw | 100,000 | 11.23 |
| NVIDIA GPU (CuPy) | sync every op | 100,000 | 32.29 |
| NVIDIA GPU (CuPy) | stackgrad | 100,000 | 39.54 |
| NVIDIA GPU (CuPy) | raw | 1,000,000 | 11.59 |
| NVIDIA GPU (CuPy) | sync every op | 1,000,000 | 33.05 |
| NVIDIA GPU (CuPy) | stackgrad | 1,000,000 | 39.96 |
| NVIDIA GPU (CuPy) | raw | 10,000,000 | 97.71 |
| NVIDIA GPU (CuPy) | sync every op | 10,000,000 | 120.1 |
| NVIDIA GPU (CuPy) | stackgrad | 10,000,000 | 99.69 |
So a GPU pays off only when each kernel gets enough work to bury its launch cost.
Matrix multiplication gets plenty. Two matrices hold numbers (the two inputs and the output) but take floating-point operations (FLOPs), so every number you load takes part in multiply-adds. Double and each byte read does twice the work. The NVIDIA GPU peaks at 33.9 TFLOP/s (trillions of operations per second) using TF32, a lower-precision number format its matrix hardware runs fast, and the Apple GPU at 3.62 TFLOP/s.
Every measurement as a table
| device | dtype | n | TFLOP/s |
|---|---|---|---|
| CPU (NumPy) | float32 | 256 | 1.365 |
| CPU (NumPy) | float32 | 512 | 1.754 |
| CPU (NumPy) | float32 | 1024 | 1.894 |
| CPU (NumPy) | float32 | 2048 | 1.881 |
| CPU (NumPy) | float32 | 4096 | 1.876 |
| Apple GPU (MLX) | float32 | 256 | 0.181 |
| Apple GPU (MLX) | float32 | 512 | 1.024 |
| Apple GPU (MLX) | float32 | 1024 | 2.245 |
| Apple GPU (MLX) | float32 | 2048 | 3.149 |
| Apple GPU (MLX) | float32 | 4096 | 3.131 |
| Apple GPU (MLX) | bfloat16 | 256 | 0.184 |
| Apple GPU (MLX) | bfloat16 | 512 | 0.96 |
| Apple GPU (MLX) | bfloat16 | 1024 | 2.375 |
| Apple GPU (MLX) | bfloat16 | 2048 | 3.423 |
| Apple GPU (MLX) | bfloat16 | 4096 | 3.623 |
| NVIDIA GPU (CuPy) | tf32 | 256 | 0.91 |
| NVIDIA GPU (CuPy) | tf32 | 512 | 7.247 |
| NVIDIA GPU (CuPy) | tf32 | 1024 | 21.07 |
| NVIDIA GPU (CuPy) | tf32 | 2048 | 30.11 |
| NVIDIA GPU (CuPy) | tf32 | 4096 | 33.93 |
A training step is mostly large matmuls and there the NVIDIA GPU trains 25.1x faster than the laptop's CPU. On the Apple GPU stackgrad reaches 82% of the speed of the same model in plain MLX with its hand-tuned kernels.
Model FLOPs utilization (MFU) divides the arithmetic a step must do (about six operations per parameter per token) by what the chip can do at its rated peak. The full TinyStories run sustained a median 8.5 TFLOP/s, an MFU of 23.9%. Launch overhead and ops that move memory without much arithmetic eat the rest. Attention is full of those, so next we fuse it into one kernel.
Writing an attention kernel
Back in the transformer part, attention was four steps: scores for every pair of positions, a mask, a softmax, and a weighted average of the values. In stackgrad each is its own kernel.
A GPU computes far faster than it moves data. Picture a cook who chops fast but walks to a fridge in the next room for every ingredient. Composed attention walks to the fridge between every step: for 256 tokens and 16 heads it writes a million scores per sequence to GPU memory, and the next kernel reads them back. FlashAttention brings small tiles of queries, keys and values onto the chip (the cutting board), finishes attention for each tile there, and never writes the scores out.
The catch is the softmax. It subtracts the row's largest score before exponentiating, so can't overflow, and it divides by the row's sum. Both seem to need every score up front. The softmax in one pass, a trick I think everyone should know, keeps a running max and a running sum instead. The sum is counted relative to the max, like money counted in a currency pegged to it. When a bigger score arrives, you convert the sum so far at the exchange rate . For the scores 1, 3, 2:
| Score arrives | Running max | Running sum |
|---|---|---|
| 1 | 1 | |
| 3 | 3 | |
| 2 | 3 |
That's the same sum you get from all three scores at once. The output works the same way: keep a running total of each value times its , convert that total at the same exchange rate whenever the max changes, and divide by at the end. One pass over the keys gives the attention output.
I wrote three Metal kernels for the Apple GPU (with MLX's mx.fast.metal_kernel):
- v1 runs a thread per query position, and neighbouring threads re-read the same keys.
- v2 has 32 query positions share a tile of keys and values in on-chip memory, so each key leaves main memory 32 times less often.
- v3 keeps the tiles and uses the GPU's built-in 8 by 8 matrix multiply.
Times in milliseconds, lower is better:
| Shape | Format | materialized scores | v1 thread per row | v2 threadgroup tiles | v3 simdgroup matmul | mx.fast.sdpa (oracle) |
|---|---|---|---|---|---|---|
| CS336 training | float32 | 9.94 | 3.02 | 2.91 | 1.49 | 9.94 |
| CS336 training | bfloat16 | 11.2 | 2.03 | 3.49 | 1.65 | 5.4 |
| prefill 1k | float32 | 20 | 32.3 | 40.5 | 6.22 | 3.31 |
| prefill 1k | bfloat16 | 22.2 | 28.2 | 43.2 | 7.55 | 2.74 |
| Qwen3 prefill 2k | float32 | 26.3 | 329 | 124 | 18.8 | 7.19 |
| Qwen3 prefill 2k | bfloat16 | 26.8 | 303 | 127 | 19.8 | 5.6 |
| decode, 2k cache | float32 | 7.63 | 1.55 | 36 | 5.34 | 1.39 |
| decode, 2k cache | bfloat16 | 6.91 | 1.02 | 33.9 | 6.01 | 0.712 |
On the story model v3 runs 6.7x faster than MLX, which has no single-kernel attention for heads this narrow. At Qwen3's 128-wide heads MLX has one, and it runs 2.6x faster than v3. I later deleted v2, since v3 beat it at every shape in the table, and rewrote v1 for decoding, which the decoding section comes back to.
The backward in Triton
On the NVIDIA GPU I wrote FlashAttention-2's forward and backward in Triton, a Python dialect where you describe one tile's work and the compiler handles the threads. The backward needs the softmax weights again. Storing them would bring back the score-sized matrix, so the forward saves one number per row, the log of its softmax sum, and the backward rebuilds each tile of on-chip from it. Recomputing costs less than the trip to memory.
At the training shape, forward plus backward takes 0.764 ms against 6.48 ms composed, 8.5x faster.
Running someone else's model
A stronger test than my own model is someone else's, loaded from its published weights and checked against the reference library. Qwen3-0.6B is a small open chat model from Alibaba's Qwen team that can hold a conversation and do grade-school math.
The weights ship in bfloat16, the first half of a float32. It keeps the sign and the exponent (the scale) but only 7 of the 23 bits that hold the digits, so it has two to three significant digits instead of seven, over the same range, in half the memory. Converting to float32 appends 16 zero bits and loses nothing.
Qwen3 is the transformer from earlier, bigger, with 128-wide heads, an extra normalization on queries and keys, and an output layer that reuses the embedding table. The loader refuses to run on any mismatched tensor name or shape.
I gave stackgrad and Hugging Face's transformers library the same 17-token prompt and compared the score (logit) each one gives every possible next token. The largest score is 24.3:
| stackgrad on | Biggest difference in any score | Same next token |
|---|---|---|
| CPU, float32 | 5.1e-5 | 100% |
| Apple GPU, float32 | 9.7e-5 | 100% |
| Apple GPU, bfloat16 | 3.5e-1 | 100% |
In float32 the scores differ by rounding error. In bfloat16, the format people run the model in, the biggest difference grows to 1.4% of the largest score, and both still pick the same next token at every position. Greedy decoding reproduces Hugging Face's first 24 tokens.
The same layers also run GPT-2 (see the bonus section).
Serving more than one person
Generating a reply requires one forward pass for every new token. Without a cache, the model recomputes the keys and values of all previous tokens at every step, even though they have not changed. The KV cache avoids this by storing them, so each step only computes the keys and values for the new token. The trade-off is memory: every conversation needs to store its keys and values for every layer.
This memory usage limits how many users a GPU can serve at once. vLLM's PagedAttention solves part of this problem by allocating KV cache in small, fixed-size blocks as a sequence grows, rather than reserving memory for its maximum length upfront. stackgrad's block manager keeps the same books but stores each cache in one array, so I took the bookkeeping and skipped the paging.
The second idea is continuous batching. Static batching works like a bus that boards no one until every passenger reaches the last stop. Continuous batching opens the doors at every step. New requests join between any two steps, and each request leaves as soon as it finishes. When memory runs out, the scheduler pauses the newest request, and later rebuilds its cache from its prompt and the tokens it already wrote.
Batching is cheap because a decode step reads every weight once, whether it serves one chat or eight. With 8 chats arriving at once, each writing 128 tokens, one pass per chat produced 63.4 tokens per second in all, and one pass for all 8 produced 155.
Pick a message and send it.
Making decoding faster
Each reply in the chat above streams one token per decode step, and each step reads every weight from memory once, about 1.2 GB for a 0.6B-parameter model in bfloat16. At the laptop's 101.4 GB/s that read takes 11.8 ms, but the model's layers alone took 25.5 ms a step. The rest is overhead: every step, Python walks the recorded graph again and launches hundreds of small kernels. So there are three ways to go faster: pay less overhead per step, read fewer bytes per token, or get more tokens per read.
Capture
Every decode step runs the same operations on the same shapes; only the numbers change. So record the step once and replay the recording, like a macro. mx.compile does the recording. The KV cache stood in the way: it grew by one token every step, so every step had new shapes, and a recording only replays the shapes it saw. So the cache now grows 256 positions at a time, each step writes its keys and values at the next free position, and attention reads only the positions written so far, from a length it takes as an input. Every step between two growths has the same shapes, so the whole step, all 28 layers and the final norm, becomes one recording that later steps replay without Python running each operation. The recording is redone only when the cache grows.
The decoding attention kernel needed work too. v1 from the attention section ran one thread per query row, so a one-token step kept only 16 threads busy. It now gives each row a group of threads that score the keys together.
The pass through the layers goes from 25.5 ms to 11.9 ms a token, 2.15x faster. A full step with the output layer takes 14.4 ms against the 11.8 ms it takes to read every weight once, so decoding now runs at 82% of the memory's speed. The model writes the same tokens with capture on or off: rerunning the released model on the 250 math problems from the fine-tuning section below gives the same 250 replies, word for word. That 250-problem test now takes 14 minutes, against 38 before.
Fusion
Capture covers decode, and laziness can help the rest. Most of a layer's operations are elementwise: add, multiply, exp, where. Each one reads its inputs from GPU memory and writes its output back, and the arithmetic is trivial, so memory traffic sets the cost. Take y = (x * 2 + 1).relu() on N numbers. Run eagerly, that's three kernels, each reading N numbers and writing N, so 6N numbers move. Because stackgrad is lazy, realize sees the whole chain before anything runs and can run it as one kernel: read N, write N, 2N in all.
tinygrad does this with its own compiler. Its scheduler groups the recorded graph into kernels, reshapes and permutes become index math inside them, and it writes Metal or CUDA source for each kernel and compiles it. I took the shortcut: realize finds runs of elementwise operations that autograd isn't recording and hands each run to mx.compile, which merges it into one kernel. mlops.py stays the only place any math lives.
On a 512-token prompt, fusion takes Qwen3's forward pass from 217 ms to 213 ms, 1.02x, with identical outputs. A decode step's tensors are tiny (8 rows of 1,024 numbers), so there is no traffic to save, and stackgrad only fuses operations whose output has at least 65,536 elements. Training doesn't fuse yet: autograd keeps each operation's inputs for the backward pass, and a compiled trace can't hand them back.
Quantization reads fewer bytes. Take a group of 64 weights, find the smallest and the largest, and lay a ruler with 16 marks between them (4 bits count 16 marks). Store each weight as the number of its nearest mark, and store the ruler's start and spacing once per group.
The weights read per token drop from 1,192 MB to 335 MB, and the model's perplexity on math text (how unsure it is of the next token) rises 19.3%. With capture on, a full step drops from 14.4 ms to 12.1 ms. Reading the int4 weights takes 3.3 ms of that, and the rest is overhead the recording didn't remove.
Speculative decoding gets more tokens per read. A small draft model guesses the next few tokens, and the big model checks the whole guess in one pass, which costs about as much as writing one token, since the cost is reading the weights. The big model keeps the guesses it agrees with and replaces the first one it doesn't, so the text comes out as if the big model wrote it alone (Leviathan et al., Chen et al.). With Qwen3-0.6B drafting for Qwen3-1.7B, the big model kept 80% of the draft's one-token guesses. With capture the draft's step takes 42% as long as the big model's, yet the best setting reaches only 0.97x of the big model alone: checking several guessed tokens at once is a multi-token pass, and multi-token passes run on the general attention kernel (v3), not the one-token kernel that made single steps fast.
Capture saved more time than quantization or speculative decoding, because the step was mostly overhead, not weight reads.
Fine-tuning with LoRA
Fine-tuning trains a pretrained model a bit further on examples of the behaviour you want. It changes each weight matrix: becomes . For one 1024 by 1024 matrix, is another million numbers to train, and Adam keeps two more for each. LoRA bets the change is simple, and builds it from two thin matrices: , 1024 by 16, and , 16 by 1024. Their product is a full 1024 by 1024 matrix, made from 32,768 numbers instead of 1,048,576.
A multiplication table shows why two thin matrices can be enough. Its 100 entries come from two lists of 10 numbers, because every entry is a row number times a column number. is 16 such tables added up (16 is the rank). The bet is that fine-tuning needs a change about that simple.
stays frozen and only and train. starts at zero, so starts at zero and training starts from the unchanged model. Across Qwen3-0.6B that's 10,092,544 trainable numbers, 1.69% of the model. After training you add into once, and the fine-tuned model runs at the original's speed.
The task is GSM8K, grade-school word problems with worked solutions ending in #### answer, and the model trains on the 7,473 training problems. I fixed the evaluation before training: the first 250 test problems, greedy decoding, at most 320 new tokens, solved when the final number equals the reference. Here are the results on the Apple GPU in bfloat16, where "hit the limit" counts replies cut off at 320 tokens.
| Model | Solved | Accuracy | Average reply | Hit the limit |
|---|---|---|---|---|
| Qwen3-0.6B as released | 152 of 250 | 60.8% | 213 tokens | 45 |
| after LoRA on GSM8K | 123 of 250 | 49.2% | 92 tokens | 11 |
LoRA made the model worse at math, 60.8% down to 49.2%, while the training loss on the solution tokens fell from an average of 0.770 over the first 50 steps to 0.573 over the last 50. It got better at reproducing GSM8K's solutions and it learned their length along with their format, from 213 tokens per reply down to 92. The released model writes out its steps, and those steps were getting answers right.
Problem 56 shows the change. Peter buys a $7 ticket and $7 popcorn each time, with $42 to spend. The released model, in 83 tokens:
Step 1: Peter pays $7 for a movie ticket and $7 for popcorn.
So, each movie visit costs **$14**.
Step 2: He has **$42** for the week.
How many times can he go to the movies?
$$
\frac{42}{14} = 3
$$
**Final Answer:**
#### 3After LoRA, 28 tokens in GSM8K's house style, and the popcorn is gone:
Peter can buy 42/7 = 6 tickets.
So he can go to the movies 6 times.
#### 6Learning from its own answers
LoRA trained the model to copy solutions, and it got worse at the thing the table counts. So let's train on the count itself. In reinforcement learning the model writes its own replies, a checker scores each one (1 if the final number is right, 0 if not), and training makes the high scorers likelier. Nobody tells the model how to reason.
The simplest version is the policy gradient. Sample a reply, then nudge the weights to make it likelier in proportion to its score. That pushes every correct reply up by the same amount, even on a question the model never gets wrong. GRPO grades on a curve. For each question it samples a group of replies and scores each against its siblings:
is reply 's score. A reply that beat its group's average gets a positive advantage and becomes likelier, and one below the average becomes less likely. Say one reply of four is right, scores 1, 0, 0, 0. The mean is 0.25 and the standard deviation 0.433, so the right reply gets advantage 1.73 and each wrong one gets . The right reply gets pushed up three times as hard as each wrong one gets pushed down, so the pushes cancel: . A group where every reply scored the same has nothing to teach, so all its advantages are zero and stackgrad skips it. Each reply's push is divided by the same 320-token budget, not by its own length, so a long wrong reply can't dodge part of its push (Liu et al.). In code, condensed from policy_loss in train_grpo.py:
logp = log_softmax(logits, axis=-1)[rows, targets] # each reply token's log-probability
weight = np.repeat(advantages / budget / n_replies, reply_lengths) # A_i / (budget * replies), per token
loss = -(logp * weight).sum()Training starts from the released Qwen3-0.6B with a fresh LoRA adapter. Each step samples 8 replies to each of 8 training problems at temperature 1 and makes one update, averaging 39 s of sampling and 7.3 s of updating. All 64 replies go in one batch: on the 3090 a decode step takes 79 ms for one reply and 86.4 ms for 64.
The reward the model gamed
The first run rewarded the final number alone. From step 51 on, every reply it sampled ran to the 320-token limit: the model wrote its solution, then "The final answer is ." between rows of dashes, over and over. The number stayed right, and writing on cost nothing. That adapter solves 154 of 250 test problems against 152 before training, with all 250 replies hitting the limit. This is my favorite result in the project. The model optimized the reward I wrote, loophole included.
The fix makes stopping part of the answer: a reply earns 1 only if it ends with Qwen's end-of-turn token and its final number is right.
With the new reward the cut-off share fell from 27% over the first ten steps to 8% at the end. The reward on the training problems rose from 54% over the first 20 steps to 67% over the last 20.
The test set, under the same protocol as the LoRA eval:
| Model | Solved | Accuracy | Average reply | Hit the limit |
|---|---|---|---|---|
| Qwen3-0.6B as released | 152 of 250 | 60.8% | 213 tokens | 45 |
| after LoRA on GSM8K | 123 of 250 | 49.2% | 92 tokens | 11 |
| after GRPO, reward ignores stopping | 154 of 250 | 61.6% | 320 tokens | 250 |
| after GRPO, reward requires stopping | 139 of 250 | 55.6% | 216 tokens | 29 |
| after RFT on its own correct replies | 155 of 250 | 62.0% | 208 tokens | 37 |
Is 139 against 152 a real drop? Only the problems that changed can tell. The adapter fixed 25 and broke 38. If training had changed nothing, each of those 63 would be a coin flip, and a split at least this uneven comes up 13% of the time, so I can't call it a drop. LoRA fixed 23 and broke 52, a split that comes up 0.1% of the time, so that drop was real. The training reward went up and the model learned to stop, but the test score stayed inside the noise. A disappointment.
Training on its own correct answers
LoRA learned GSM8K's short solutions and dropped the worked steps that were getting answers right. GRPO trains on the model's own replies, but only nudges them by a score. A third option sits between the two: sample the model's own replies to the training problems, keep the ones that are right and finish, and fine-tune on those like ordinary examples. That's rejection-sampling fine-tuning (RFT), also called expert iteration. Every training example is the model's own writing, so its style can't drift toward GSM8K's.
I sampled 3 replies to each of the first 3,328 training problems at temperature 0.8, before the sampler ran out of GPU memory. 60% were right, and 5,991 right replies that ended on Qwen's end-of-turn token remained, averaging 180 tokens. A fresh LoRA adapter with the same settings as before trained on them (the RFT row in the table above).
The adapter solves 155 of 250 against 152, fixing 18 problems and breaking 15, a split chance produces 73% of the time. Its replies stay long, 208 tokens on average against 213, so the worked steps survive. But there was little left to learn: the training loss averaged 0.221 over the first 50 steps and 0.216 over the last 50, because the model already rates its own replies as likely.
Retrieval and a calculator
Most systems built on language models answer from documents or call tools. Both run here as programs talking to the server from the serving part, with stackgrad computing every number from the embedding to the last sampled token.
Retrieval
A small model knows few facts. Retrieval-augmented generation looks up passages that bear on the question and puts them in the prompt. The test is SQuAD v1.1, questions people wrote about Wikipedia paragraphs; its development set has 2,067 paragraphs.
Finding the right paragraph means comparing meanings. An embedding model maps a text to a vector so that texts about the same thing point the same way. Qwen3-Embedding-0.6B is Qwen3's architecture with its own weights, so stackgrad already runs it, and a text's embedding is the model's final vector at its last token, scaled to length 1. The index is a matrix with one row per paragraph, a question takes 61 ms to embed, and the search is a matrix product and a sort:
query = embed(model, tok, [INSTRUCT + question], device)[0] # 1,024 numbers, length 1
scores = index @ query # one dot product per paragraph
top = np.argsort(-scores)[:3] # the three nearestFor 200 random questions, the paragraph the question was written from ranks first 73.0% of the time and in the top 3 91.5% of the time, and the server answers with those top 3 in its prompt.
Qwen3 answers in full sentences ("The chloroplast double membrane is sometimes compared to the mitochondrial double membrane."), so an exact-match score would call a right answer wrong. I count an answer right when it contains the reference answer. Asking without the paragraphs sets a floor, and since SQuAD's questions assume you've read the paragraph, it's low. On 200 questions:
| Prompt | Answer contains the reference | Seconds per answer |
|---|---|---|
| the question alone | 3% | 0.48 |
| with the top 3 paragraphs | 55% | 1.53 |
Retrieval takes the answers that contain the reference from 3% to 55%, at 1.53 s per answer against 0.48 s. I'd pay that every time.
A calculator
GSM8K's problems take a few steps of arithmetic, and a 0.6B model slips on arithmetic, so give it a calculator. Qwen3 was trained to call tools: shown a function's description in its system prompt, it can stop mid-reply and write a JSON call between <tool_call> tags. A small program runs the ReAct loop. When a reply calls the tool, the program evaluates the expression and sends the value back, and the model continues until it answers without a call.
The first run kept the LoRA part's "Solve it step by step" prompt and offered the calculator in the system message. In 250 problems the model never called it, yet the offer changed the answers. Replies shrank from 213 tokens to 148, and the model solved 132 against 152, fixing 21 and breaking 41, a split chance produces 1.5% of the time.
So the second run asks for the calculator in the user's turn. The model called it 440 times, on 248 of 250 problems, and solved 42 against 152 without it. It fixed 7 and broke 117, a split chance produces less than 0.01% of the time. Replies averaged 27 tokens, little more than the calls. In the replies the model hands the calculator its arithmetic before working out what to compute, then answers with whatever number comes back.
With the plain prompt a reply averaged 213 tokens of worked steps, and those steps were getting problems right. Asking for the tool pushed them out.
Bonus: scaling laws
Was the story model the right size for its compute? With a fixed budget of arithmetic, a bigger model trains on fewer tokens and a smaller one on more. Too small a model can't hold what the data teaches, and too large a one sees too few tokens. Hoffmann et al. find the best size with IsoFLOP curves: fix a budget, train several sizes on it, and see which ends lowest. I ran three budgets, from to operations, five sizes each.
Every run as a table
| budget | d_model | parameters | validation loss |
|---|---|---|---|
| 3e14 FLOPs | 128 | 2M | 2.377 |
| 3e14 FLOPs | 192 | 3.7M | 2.386 |
| 3e14 FLOPs | 256 | 5.8M | 2.405 |
| 3e14 FLOPs | 384 | 11M | 2.528 |
| 3e14 FLOPs | 512 | 18M | 2.696 |
| 1e15 FLOPs | 128 | 2M | 2.033 |
| 1e15 FLOPs | 192 | 3.7M | 1.966 |
| 1e15 FLOPs | 256 | 5.8M | 1.946 |
| 1e15 FLOPs | 384 | 11M | 1.971 |
| 1e15 FLOPs | 512 | 18M | 2.083 |
| 3e15 FLOPs | 128 | 2M | 1.825 |
| 3e15 FLOPs | 192 | 3.7M | 1.77 |
| 3e15 FLOPs | 256 | 5.8M | 1.723 |
| 3e15 FLOPs | 384 | 11M | 1.709 |
| 3e15 FLOPs | 512 | 18M | 1.76 |
The best sizes came out at 3M, 5.5M and 8.2M parameters. At the full run's compute the fit asks for 24M parameters on 237M tokens. The story model has 17.6M (counting matrix weights only) and trained on 328M, so it was a little small.
Bonus: GPT-2 and Stable Diffusion
Two more models run on stackgrad's layers from published weights, one file each, like tinygrad's examples/. GPT-2 (124M parameters) against Hugging Face's transformers, on a 15-token prompt and 40 greedy tokens:
| stackgrad on | Biggest difference in any score | Same 40 tokens |
|---|---|---|
| CPU | 1.4e-4 | yes |
| Apple GPU | 2.2e-4 | yes |
Stable Diffusion v1.5 turns a sentence into a 512 by 512 image in three stages. CLIP's text encoder turns the prompt into vectors. The picture starts as pure noise in a 4 by 64 by 64 latent, a compressed sketch of the image. An 860M-parameter UNet looks at the noisy sketch and the prompt, predicts the noise, and removes part of it, 25 times over (DDIM steps). Classifier-free guidance runs the UNet with an empty prompt and with yours, and pushes each step further in the direction yours pulls. A VAE decoder then turns the sketch into pixels. Condensed from generate() in examples/stable_diffusion.py:
tok = ClipTokenizer(path / "tokenizer")
prompts = np.array([tok.encode(""), tok.encode(prompt)])
context = load_clip(path, device)(prompts) # 77 vectors per prompt
unet = load_unet(path, device)
for t, t_prev in zip(times, [*times[1:], -1]): # 25 DDIM steps
pair = Tensor(np.concatenate([x, x]), device=device)
noise = unet(pair, t, context).numpy()
noise = noise[:1] + guidance * (noise[1:] - noise[:1]) # guidance
x = ddim_step(x, noise, t, t_prev)
image = load_vae(path, device).decode(Tensor(x, device=device)) # pixelsEach of the three networks matches its reference library's output to within millionths of the output's size, on the CPU and on the Apple GPU.
stackgrad
diffusers on PyTorchSlower, but the same picture.
Check out the documentation and the repo for code, or run pip install stackgrad. Big shoutout to George Hotz 4 inspiring me.