4. Transformers Overview
We’ll dive deeper into the transformer architecture, calculating FLOPs, bytes, and math in general.
At the lowest level, everything boils down to simple dot products: multiplying 2 lists of numbers. So, the computer needs to take 2 numbers, multiply them together, and add them to the running sum. This is called a MAC operation: Multiply-Accumulate.
-
1 Multiply = 1 FLOP
-
1 Add = 1 FLOP
So basically every equation we talk about here starts with a 2. For Matrices and , we get steps, so we get FLOPs. Basic rule of thumb.
In higher dimensions, we can look at an example like:
which just describes a massive, multi-dimensional tensor. To calculate the FLOPs required for any matmul, just multiply all the unique letters together and then multiply by 2. Those brackets include all the contracting dimensions, batching dimensions, and free dimensions.
Memory vs Math Requirements
Assuming perfectly square matrix multiplications where are all size (same size), compute and memory scale differently:
-
Compute FLOPs take operations, meaning compute grows cubically: .
-
Data (memory) concerns loading Matrix , Matrix , and writing Matrix , so the memory footprint grows quadratically: .
So our math requirements outscale our memory requirements. Which makes TPUs uniquely suited (super fast math, but bad at loading memory (HBM)). Just by scaling up the size of our matrices, we move from a memory-bound regime to compute-bound.
So we’ve established that during simple forward passes, like inference, standard matrix multiplications take FLOPs. During inference, all we pay is 2 FLOPs per parameter, per token. Training, however, involves calculating 2 separate derivatives that each have its own big matmuls:
-
The Weight Gradient tells you how to adjust the weights by multiplying the input activations () by the incoming error; full matmul = 2 FLOPs.
-
The Activation Gradient passes the error backwards to the previous layer so it can also learn, by multiplying the incoming error by the transposed weights (). Also 2 FLOPs.
So, during training, we have:
While training, the golden rule is just to figure out how much hardware we need to buy or rent out.
Transformer Accounting
The following section covers transformer accounting, which can be found in more detail in a previous breakdown of transformers, but for reference, memorizing these variables makes reading research infinitely easier:
-
: Batch size (number of sequences processed at once; for local models, 1 = just you)
-
(or ): Sequence Length (4096 or 8192 tokens, etc)
-
: Model dimension (core width of the network)
-
: Feed forward dimension (the expanded width inside the MLP, usually )
-
: Number of query heads
-
: Number of K/V (Key value heads)
-
: Head dimension (usually )
But you can skip this if you understand the transformer decoder architecture flows. Modern transformers today use pre-norm architectures that are worth touching up on, where the norm occurs before the residual connection, used by models like Llama 3. I’ll go over these briefly:
-
Gating Einsums (SwiGLU): Originally, for the MLP (multi layer perceptron), we used 2 matrices: 1 to expand the dimension , and one to shrink it back . This approach uses 3 matrices instead, adding a ‘Gating’ matrix to act as a filter, element-wise multiplying against the first matrix. This causes MLP params to increase from to , but greatly enhances learning.
-
Pre-norm vs Post-norm: Models used to add residual connections and then normalize the data. This proved to be unstable at training larger scale models, so now we normalize data before going into the MLP/attention blocks.
-
Attention Variants (MHA vs GQA vs MQA): This is about saving memory. In standard MHA (Multi head attention), every query head gets its own key and value head (). This takes up a ton of memory for the KV cache during inference. MQA (Multi query attention) is when all query heads share 1 KV head (). GQA is another compromise where query heads are split into groups, and each group takes a KV head.
FLOPs and Param Calculations
This is basically the ‘accounting’ of the model. We know the abstract rule, but we’ll now apply it precisely to the matrices in our model to see where exactly the compute budget is going.
A rule we want to remember is , which explains why long-context models are an engineering challenge, and why that challenge gets even worse for smaller models.
Starting with:
1. The MLP Budget
The MLP (feed forward) block contains the vast majority of parameters in a transformer. Assuming the modern ‘Gating’ architecture, using 3 matrices, the math is simple:
-
Parameters: 3 Matrices of size , so total.
-
Train FLOPs: Applying the rule to a batch of sequences of length , we get FLOPs.
2. Attention Budget (Projections vs Dot Products)
Attention has 2 separate costs: projection (setup) and the actual matching (dot products).
-
Projections: Linear cost in . , and make the queries, keys and values, and maps the result back to width . Q and O are , K and V are , so parameters and train FLOPs. For plain MHA ( and ) that’s just parameters and FLOPs.
-
Dot Products: Quadratic cost in . Every query gets scored against every key, then we take a softmax-weighted sum of the values: 2 matmuls of each in training, so with self-attention (). No parameters, pure compute.
As a note, the transformer diagram shows the shape of each einsum.
3. Other Operations
-
Layernorms: 2 per layer, FLOPs and parameters. A rounding error, so we ignore them.
-
Unembedding: A matrix at the end scores every token in the vocab: parameters and train FLOPs, once, not per layer. The embedding table is another parameters, but it’s a lookup, not a matmul.
4. General rule of thumb for Transformer FLOPs
Ignoring the dot products (fine for short contexts), the MLP and projections across layers add up to:
The bracket is one layer’s parameter count and is the number of tokens, so we land right back on . Divide by 3 for inference.
5. Fractional cost of attention with context length
With the typical , and , the MLP is , the projections are , and the dot products are :
This is where comes from: the dot products only take over once the context passes 8 times the model width, 65,536 tokens for but only 36,864 for Gemma 27B (). The MLP and projections scale with and the dot products only with , so smaller models hit the wall sooner.
Miscellaneous Math
Sparsity and Mixture-of-Experts
An MoE (Mixture of Experts) model swaps each layer’s MLP for experts, and a router picks of them per token. Parameters grow with but FLOPs only with , so the rule uses the activated parameters. is the sparsity, typically 8 to 64 (DeepSeek v3 has and , so 32). The price is 2 AllToAlls around every MoE block to route tokens to their experts and back, each about of an AllGather.
Gradient checkpointing
The backward pass needs the forward pass’s activations. Saving all of them for a 4M token batch (), , and around 20 activations per layer in bf16:
Insanely expensive, so we save some and recompute (rematerialize) the rest:
- Block remat: 1 checkpoint per layer instead of 20, so 4.2 TB. But we basically redo the forward pass, so training goes from to roughly .
- Big matmuls only: Keep the large matmul outputs and recompute the cheap stuff. Around 7 per layer, about 29 TB.
In JAX, this is jax.checkpoint (also called jax.remat).
Key-Value (KV) caching
Prefill runs the prompt once and saves every layer’s keys and values, then generation samples 1 token at a time and reuses them. That’s the KV cache, per sequence, so in int8:
With , and , that’s 8 GiB per sequence (1 MiB per token). GQA () shrinks it by a factor of .
What Should You Take Away from this Section?
- Per layer in training (MHA), the MLP is parameters and FLOPs, and attention is and . The MLP dominates, which is why works so well.
- The dot products only take over once .
- The KV cache is bytes per sequence in int8, and unlike the weights, it isn’t shared across the batch.
A Few Problems to Work
Question 1 [counting parameters]: A model has , , and . How many parameters is that? What fraction of them belong to attention? And how large is the KV cache per token? Assume , multi-head attention (), and int8 KVs.
-
How many parameters?
-
With , each layer has in the MLP, in attention and in layernorms. That’s 268,443,648 per layer. Plus for the embedding and unembedding:
-
So around 17.4B parameters. The solution says 16B because it rounds the dims first.
-
-
What fraction are attention parameters?
-
Ignoring the tiny terms:
-
-
How large are the KV caches per token?
-
1 key and 1 value vector per layer, each wide, at 1 byte per element:
-
Meaning, an 8192 token context costs 4 GiB of HBM per sequence.
-
Question 2 [sharded matmul FLOPs]: We run on the mesh {'X': 4, 'Y': 8, 'Z': 4}. How many FLOPs does that take in total, and how many does each TPU perform?
-
How many FLOPs does each TPU perform?
-
Each chip just multiplies by :
-
-
How many total FLOPs?
-
Nothing is sharded over
Z, so like Question 1 in Chapter 3, each of the 4Zlayers does the full matmul by itself. With chips: -
So the unused axis burns the FLOPs we need, on top of the HBM.
-
Question 3 [einsum FLOPs]: How many FLOPs does the contraction take?
-
The ‘unique letters’ rule. and are in both inputs but not the output, so they’re contracting. Nothing is in all three, so no batching dimensions. Every letter counts once, times 2 since we contract:
Question 4 [attention intensity]: Ignoring the Q/K/V/O projections, what is the arithmetic intensity of grouped multi-query attention as a function of query length , KV length and query heads per KV head ()? At what context length is attention FLOPs-bound? Then plot the effective cost of attention relative to the FFW block as the context grows. Hint: assume no unnecessary reads or writes, and look at both and . Assume TPU v5e numbers: bf16 FLOPs/s and of HBM bandwidth.
- The Chapter 1 intensity question again, for the dot product half of attention in bf16. ‘Efficient’ means the score matrix never touches HBM.
-
What is the arithmetic intensity?
-
FLOPs: and then the multiply by are each, so . Bytes: read (), and ( each), and write an output shaped like , so :
-
cancels, so a bigger batch doesn’t help. Every sequence brings its own keys and values.
-
-
At what context length is attention FLOPs-bound?
-
For prefill or training, , so the intensity is . The v5e needs :
-
For plain MHA () that’s tokens. The solution says 240 because it drops the factor.
-
For generation, and the intensity tends to , so with MHA we’re permastuck at . Never FLOPs-bound.
-
-
How does the cost of attention compare to the FFW block as context grows?
-
No published answer for this part. Effective cost is , and with and , the FFW forward pass is FLOPs against for the dot products.
-
Prefill (): The ratio is , with a floor below the critical context, where attention waits on HBM:
-
Attention passes the FFW block at tokens for .
-
Generation (): Attention reads about bytes of KV cache per layer, while the FFW block reads bytes of weights shared by the batch, taking :
-
Past , attention passes the FFW block at only around 100 tokens of context, which is why a larger matters so much for serving.
-
Question 5 [dot products vs projections]: For self-attention, at what sequence length do the dot product FLOPs equal the QKVO projection FLOPs?
-
Just set the 2 attention costs from the notes equal. With MHA:
-
For , that’s 8192 tokens.
Question 6 [remat FLOPs]: If the forward pass only saves the outputs of the 7 main matmuls in each transformer layer (Q, K, V, O, plus the 3 FFW matrices), how many extra FLOPs does the backward pass need to ‘rematerialize’ everything else?
-
Each weight gradient needs that matmul’s input, so which inputs can’t we rebuild cheaply?
-
Q, K, V and the 2 FFW input matrices: The normalized residual stream, just a layernorm, so .
-
FFW output matrix: The gated product of the 2 saved FFW activations, elementwise, so .
-
O: , which we didn’t save. So we redo both attention matmuls, forward only, each:
-
Ignoring the small leftovers, that’s about 6.7% extra on the whole layer for and , against about 33% for block remat.
Question 7 [DeepSeek utilization]: DeepSeek v3 reports 2.79M H800 hours of training on 14.8T tokens (source), with 37B activated parameters. Roughly what hardware utilization is that? Hint: they trained with FP8 FLOPs and no structured sparsity. Assume the H800 rate from this spec sheet: 3,026 TFLOPs/s of FP8 with sparsity, so half of that, , without.
-
Utilization is the FLOPs the model needed over the FLOPs the hardware could produce. Needed, using the activated parameters since it’s an MoE:
-
Available: GPU-seconds at the non-sparse rate:
-
Then we just divide:
-
So roughly 21.6% of peak FP8, about 1/5. The rule ignores the attention dot products, so the real number is a bit higher.
Question 8 [MoE batch size]: An MoE layer holds copies of the dense MLP block, and every token gets routed through of them. With int8 weights on a TPU v5e, how many tokens do we need in a batch to be compute-bound? What about DeepSeek, with 256 (routed) experts and ? Assume of HBM bandwidth and bf16 math at .
-
This is Question 2 from Chapter 1 again (int8 weights, bf16 compute, ), except we now load all experts ( bytes) and each token only uses of them ( FLOPs). Ignoring the activations like before:
-
The v5e needs around , so:
-
For DeepSeek:
-
Meaning, the dense threshold of 120 just gets multiplied by the sparsity (32 here), assuming the router spreads tokens evenly. Fine for training, but a massive batch for generation.