Skip to content
← writing

Modern AI: Autograd to Agents

Nov 6, 2026 · 39 min read · ml, from-scratch

contents
  1. 1Autograd
  2. 2Tokenization
  3. 3The transformer
  4. 4Training it
  5. 5GPUs
  6. 6Writing an attention kernel
  7. 7Running someone else's model
  8. 8Serving more than one person
  9. 9Making decoding faster
  10. 10Fine-tuning with LoRA
  11. 11Learning from its own answers
  12. 12Retrieval and a calculator
  13. 13Bonus: scaling laws
  14. 14Bonus: GPT-2 and Stable Diffusion

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.

tl;dr

  • 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.
1.8e−15gap to PyTorch's loss at step 1
1.399validation loss on TinyStories after 40,000 steps
6.7xfaster than MLX's unfused attention
Three results from the result files. Left, stackgrad's and PyTorch's losses on the same model. Middle, the story model's validation loss. Right, attention time at the training shape, my kernel in blue and MLX's in pink.

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 y=w⋅xy=w\cdot x. We want output 66 for input 22, so the loss is L=(wx−6)2L=(wx-6)^2, which at w=1w=1 is (2−6)2=16(2-6)^2=16. The gradient ∂L/∂w=2(wx−6)x\partial L/\partial w=2(wx-6)x, which is 2⋅(−4)⋅2=−162\cdot(-4)\cdot2=-16, is negative, so raising ww lowers the loss. One step with a learning rate of 0.10.1 gives w←1−0.1⋅(−16)=2.6w\leftarrow1-0.1\cdot(-16)=2.6, an output of 5.25.2 and a loss of 0.640.64, 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 2×4=82 \times 4 = 8 times as fast as the walker. Rates along a chain multiply: if zz depends on yy and yy on xx, then ∂z/∂x=(∂z/∂y)(∂y/∂x)\partial z/\partial x=(\partial z/\partial y)(\partial y/\partial x).

Take the loss from above at w=1w=1, x=2x=2 as three steps: u=wx=2u=wx=2, then e=u−6=−4e=u-6=-4, then L=e2=16L=e^2=16. Now walk back from the loss, starting from a gradient of 1. Squaring has slope 2e=−82e=-8, so ∂L/∂e=−8\partial L/\partial e=-8. Subtracting 6 doesn't change the slope, so ∂L/∂u=−8\partial L/\partial u=-8. Multiplying by xx multiplies the slope by xx, so ∂L/∂w=−8⋅2=−16\partial L/\partial w=-8\cdot2=-16, 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.

Expression

x = 2, w = -0.5, b = 3

The autograd engine on stackgrad's server, values in blue and gradients in pink. Pick an expression and run backward.

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 z=xyz=xy, if the gradient arriving at zz is gg, then xx gets g⋅yg\cdot y and yy gets g⋅xg\cdot x. Simplified from stackgrad/mlops.py:

python
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.x

Calling 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:

python
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 + g

All 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 hh, then down, and measure the slope:

∂f∂x≈f(x+h)−f(x−h)2h,h=10−5\frac{\partial f}{\partial x}\approx\frac{f(x+h)-f(x-h)}{2h},\qquad h=10^{-5}
Gradient checks, replayed from stackgrad's server at the pace they ran. A line passes when 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.

Training loss of the same model in stackgrad (thin blue) and PyTorch (wide pink), in 64-bit numbers (float64), 1.8e-15 apart at step 1. Switch to 32-bit (float32) to compare.

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.

python
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 each

An 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:

MergeWinning pairCountnewest after it
1e s9 (6 from newest, 3 from widest)n e w es t
2es t9n e w est
3l o7 (5 from low, 2 from lower)n e w est
4lo w7n 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.

Once430␣upon439␣a259␣time398,44␣a259␣curious1223␣little390␣robot2052␣found505␣a259␣shiny877␣gear3835.46

Merges for one pre-token

  1. ␣time
  2. ␣time
  3. ␣time
  4. ␣time
  5. ␣time

4 merges, from bytes to final tokens.

The tokenizer on stackgrad's server. Pick a text to see its tokens and ids, then a word to watch its bytes merge.

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: dd 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:

Attention(Q,K,V)=softmax(QK⊤d+M)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d}} + M\right)V

The mask MM holds −∞-\infty wherever a position would look ahead so nothing sees the future it is predicting (prevents cheating) and d\sqrt{d} 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.

Every head of the trained story model on one sentence. Bluer cells carry more weight (square-root scale).

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 pp turns its hands pp 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.

a fast pair
θ = 1 radian per position
score ∝ cos((p − k)θ) = −0.65
a slow pair
θ = 0.15 radian per position
score ∝ cos((p − k)θ) = 0.83
long hand: the queryshort hand: the key

gap p − k = 4

A query's and a key's pairs as clock hands. Move both positions together and the hands turn, but the angle between them and the score stay the same.

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 gg then turn single dimensions back up.

Two lines in stackgrad/gpt.py:

python
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 way
norm → logitsRMSNormattentionRMSNormSwiGLU feed-forwardtoken embedding× 4 layers(28 in Qwen3)
One layer. The residual stream runs up the middle, and attention and the feed-forward each read a normalized copy of it and add their output back.

Stack 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:

SettingStory model (CS336)Qwen3-0.6B
Vocabulary10,000151,936
Vector width dd5121,024
Layers428
Query heads / key-value heads16 / 1616 / 8
Width of one head32128
Parameters22,696,448596,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 −ln⁡0.25≈1.39-\ln 0.25 \approx 1.39. Random guessing among 10,000 tokens scores ln⁡(10,000)≈9.21\ln(\text{10,000}) \approx 9.21, 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):

python
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()                                                # AdamW

Plain 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.

The TinyStories run, train loss in blue and validation in pink, log scale. It ends at a validation loss of 1.399.

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:

text
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.

Temperature

Top-p 0.95, at most 120 new tokens

Stories from the trained checkpoint at three temperatures (top-p 0.95, at most 120 new tokens).

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.

ChangeLoss 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
devicepathfloatsµs per op
CPU (NumPy)raw1,0000.4
CPU (NumPy)sync every op1,0000.66
CPU (NumPy)stackgrad1,0003.09
CPU (NumPy)raw10,0000.9
CPU (NumPy)sync every op10,0001.3
CPU (NumPy)stackgrad10,0004.08
CPU (NumPy)raw100,0006.82
CPU (NumPy)sync every op100,0007.21
CPU (NumPy)stackgrad100,00010
CPU (NumPy)raw1,000,00064.07
CPU (NumPy)sync every op1,000,00064.33
CPU (NumPy)stackgrad1,000,00066.91
CPU (NumPy)raw10,000,000863.7
CPU (NumPy)sync every op10,000,000850.3
CPU (NumPy)stackgrad10,000,000863.1
Apple GPU (MLX)raw1,0007.07
Apple GPU (MLX)sync every op1,000139
Apple GPU (MLX)stackgrad1,0007.59
Apple GPU (MLX)raw10,0004.94
Apple GPU (MLX)sync every op10,000127.4
Apple GPU (MLX)stackgrad10,0007.63
Apple GPU (MLX)raw100,0006.46
Apple GPU (MLX)sync every op100,000152.2
Apple GPU (MLX)stackgrad100,0008.86
Apple GPU (MLX)raw1,000,00040.85
Apple GPU (MLX)sync every op1,000,000255.7
Apple GPU (MLX)stackgrad1,000,00043.62
Apple GPU (MLX)raw10,000,000775.2
Apple GPU (MLX)sync every op10,000,0001083
Apple GPU (MLX)stackgrad10,000,000777.5
NVIDIA GPU (CuPy)raw1,00011.34
NVIDIA GPU (CuPy)sync every op1,00034.96
NVIDIA GPU (CuPy)stackgrad1,00041.89
NVIDIA GPU (CuPy)raw10,00011.21
NVIDIA GPU (CuPy)sync every op10,00032.26
NVIDIA GPU (CuPy)stackgrad10,00039.48
NVIDIA GPU (CuPy)raw100,00011.23
NVIDIA GPU (CuPy)sync every op100,00032.29
NVIDIA GPU (CuPy)stackgrad100,00039.54
NVIDIA GPU (CuPy)raw1,000,00011.59
NVIDIA GPU (CuPy)sync every op1,000,00033.05
NVIDIA GPU (CuPy)stackgrad1,000,00039.96
NVIDIA GPU (CuPy)raw10,000,00097.71
NVIDIA GPU (CuPy)sync every op10,000,000120.1
NVIDIA GPU (CuPy)stackgrad10,000,00099.69
One elementwise multiply's cost against array size.

So a GPU pays off only when each kernel gets enough work to bury its launch cost.

Matrix multiplication gets plenty. Two n×nn \times n matrices hold 3n23n^2 numbers (the two inputs and the output) but take 2n32n^3 floating-point operations (FLOPs), so every number you load takes part in nn multiply-adds. Double nn 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
devicedtypenTFLOP/s
CPU (NumPy)float322561.365
CPU (NumPy)float325121.754
CPU (NumPy)float3210241.894
CPU (NumPy)float3220481.881
CPU (NumPy)float3240961.876
Apple GPU (MLX)float322560.181
Apple GPU (MLX)float325121.024
Apple GPU (MLX)float3210242.245
Apple GPU (MLX)float3220483.149
Apple GPU (MLX)float3240963.131
Apple GPU (MLX)bfloat162560.184
Apple GPU (MLX)bfloat165120.96
Apple GPU (MLX)bfloat1610242.375
Apple GPU (MLX)bfloat1620483.423
Apple GPU (MLX)bfloat1640963.623
NVIDIA GPU (CuPy)tf322560.91
NVIDIA GPU (CuPy)tf325127.247
NVIDIA GPU (CuPy)tf32102421.07
NVIDIA GPU (CuPy)tf32204830.11
NVIDIA GPU (CuPy)tf32409633.93
Square matmul throughput against matrix size. Dashed lines use lower-precision numbers: 16-bit on the Apple GPU, TF32 on the NVIDIA GPU.

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.

  • stackgrad on NVIDIA GPU (CuPy), tf3290,145 tok/s, 90.9 ms
  • plain MLX on Apple GPU (MLX)14,765 tok/s, 554.8 ms
  • stackgrad on Apple GPU (MLX)12,118 tok/s, 676 ms
  • stackgrad on CPU (NumPy)3,588 tok/s, 2283 ms
One training step of the story model on each device.

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 S=QK⊤/dS = QK^\top/\sqrt{d} 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.

keysqueriesmaskednowon-chip memory (small, fast)Q tileK tileV tilerunning max m, sum l, output oGPU main memory (large, slow)QKVoutput Oscores S: never written
One query tile sweeps the key tiles left to right, up to the diagonal. Only the current tiles and three running values sit on the chip. The score matrix never reaches main memory.

The catch is the softmax. It subtracts the row's largest score before exponentiating, so ese^s 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 mm and a running sum ll 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 emold−mnewe^{m_\text{old} - m_\text{new}}. For the scores 1, 3, 2:

Score arrivesRunning max mmRunning sum ll
11e0=1e^0 = 1
331⋅e1−3+e0=1.1351 \cdot e^{1-3} + e^0 = 1.135
231.135+e2−3=1.5031.135 + e^{2-3} = 1.503

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 es−me^{s-m}, convert that total at the same exchange rate whenever the max changes, and divide by ll 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:

ShapeFormatmaterialized scoresv1 thread per rowv2 threadgroup tilesv3 simdgroup matmulmx.fast.sdpa (oracle)
CS336 trainingfloat329.943.022.911.499.94
CS336 trainingbfloat1611.22.033.491.655.4
prefill 1kfloat322032.340.56.223.31
prefill 1kbfloat1622.228.243.27.552.74
Qwen3 prefill 2kfloat3226.332912418.87.19
Qwen3 prefill 2kbfloat1626.830312719.85.6
decode, 2k cachefloat327.631.55365.341.39
decode, 2k cachebfloat166.911.0233.96.010.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 PP 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 PP 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 onBiggest difference in any scoreSame next token
CPU, float325.1e-5100%
Apple GPU, float329.7e-5100%
Apple GPU, bfloat163.5e-1100%

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.

static batchingall donebatch slotsABidleCDEFGcontinuous batchingall donebatch slotsABCDEFGdecode steps
The same requests under each scheduler. Static batching leaves a slot idle until the longest reply finishes, and continuous batching fills it right away.

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.

Qwen3-0.6B served by stackgrad on the Apple GPU, replayed at the speed it streamed.

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.

64 weights in one groupsmallest weight(stored once per group)largestspacing = (largest − smallest) / 1516 marks: each weight stores the numberof its nearest mark (4 bits)
One group of 64 weights, rounded to the nearest of 16 marks. The group stores its smallest weight and the spacing, and each weight stores 4 bits.

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: WW becomes W+ΔWW + \Delta W. For one 1024 by 1024 matrix, ΔW\Delta W 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: AA, 1024 by 16, and BB, 16 by 1024. Their product ABAB is a full 1024 by 1024 matrix, made from 32,768 numbers instead of 1,048,576.

W1024 × 1024+A 1024 × 16×B 16 × 1024=AB1024 × 1024frozen1,048,576 numberstrained32,768 numbers
The frozen matrix and the two trained ones, drawn to scale.

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. ABAB is 16 such tables added up (16 is the rank). The bet is that fine-tuning needs a change about that simple.

WW stays frozen and only AA and BB train. BB starts at zero, so ABAB 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 ABAB into WW 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.

ModelSolvedAccuracyAverage replyHit the limit
Qwen3-0.6B as released152 of 25060.8%213 tokens45
after LoRA on GSM8K123 of 25049.2%92 tokens11

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.

The LoRA run's training loss on the solution tokens only. The eval in the table above is the validation curve here.

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:

text
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:**
#### 3

After LoRA, 28 tokens in GSM8K's house style, and the popcorn is gone:

text
Peter can buy 42/7 = 6 tickets.
So he can go to the movies 6 times.
#### 6

Learning 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:

Ai=Ri−mean⁡(R)std⁡(R)A_i = \frac{R_i - \operatorname{mean}(R)}{\operatorname{std}(R)}

RiR_i is reply ii's score. A reply that beat its group's average gets a positive advantage AiA_i 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 −0.58-0.58. The right reply gets pushed up three times as hard as each wrong one gets pushed down, so the pushes cancel: 1.73=3×0.581.73 = 3 \times 0.58. 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:

python
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 18\boxed{18}." 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.

Replies cut off at the 320-token limit, per step, under each reward. The first run stopped at step 143.

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.

Sampled replies that scored on the training problems, per step, at temperature 1.

The test set, under the same protocol as the LoRA eval:

ModelSolvedAccuracyAverage replyHit the limit
Qwen3-0.6B as released152 of 25060.8%213 tokens45
after LoRA on GSM8K123 of 25049.2%92 tokens11
after GRPO, reward ignores stopping154 of 25061.6%320 tokens250
after GRPO, reward requires stopping139 of 25055.6%216 tokens29
after RFT on its own correct replies155 of 25062.0%208 tokens37

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:

python
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 nearest

For 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:

PromptAnswer contains the referenceSeconds per answer
the question alone3%0.48
with the top 3 paragraphs55%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.

Retrieval, recorded through stackgrad's server. stackgrad compares your question with all 2,067 development paragraphs, and Qwen3-0.6B answers from the three nearest.

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.

The agent's loop on stackgrad's server, with the second run's prompt, so expect the calls before the reasoning.

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 3×10143 \times 10^{14} to 3×10153 \times 10^{15} operations, five sizes each.

Every run as a table
budgetd_modelparametersvalidation loss
3e14 FLOPs1282M2.377
3e14 FLOPs1923.7M2.386
3e14 FLOPs2565.8M2.405
3e14 FLOPs38411M2.528
3e14 FLOPs51218M2.696
1e15 FLOPs1282M2.033
1e15 FLOPs1923.7M1.966
1e15 FLOPs2565.8M1.946
1e15 FLOPs38411M1.971
1e15 FLOPs51218M2.083
3e15 FLOPs1282M1.825
3e15 FLOPs1923.7M1.77
3e15 FLOPs2565.8M1.723
3e15 FLOPs38411M1.709
3e15 FLOPs51218M1.76
IsoFLOP curves, darker for more compute. A ring marks each curve's lowest point.

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 onBiggest difference in any scoreSame 40 tokens
CPU1.4e-4yes
Apple GPU2.2e-4yes

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:

python
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))  # pixels

Each 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.

Stable Diffusion's image for "a watercolor painting of a lighthouse on a cliff at dusk", drawn by stackgradstackgrad
The same image drawn by diffusers on PyTorchdiffusers on PyTorch
"a watercolor painting of a lighthouse on a cliff at dusk", 25 DDIM steps, guidance 7.5, same noise, Apple GPU. Pixels differ by at most 3.4 of 255 levels, and a step takes 2.58 s in stackgrad, 1.16 s in diffusers.

Slower, 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.

reply by email

related