Key takeaways
- Parameters: the bulk of each layer is like 12 square D×D matrices (4 for attention, 8 for the FFN), so the total is P≈2VD+12LD2, and most of it sits in the FFN.
- Compute: one matrix multiplication costs 2mnp floating-point operations (FLOPs). The forward pass costs about 2P per token, plus 4LSD for attention when the context is long.
- The backward pass costs about twice the forward, so training costs about 6P per token.
- Inference memory = weights + KV cache + peak activations. The KV cache stores 2LKH numbers per token.
- Training memory = weights + gradients + optimizer state + activations. With mixed precision and Adam that's about 18 bytes per parameter, plus activations that grow with the number of tokens.
What does "7B" actually mean?
You've probably heard that some model has "7 billion parameters", or 7B for short; Meta's openly released Llama 2 7B is a classic example. Those 7 billion numbers are everything the model learned from its data. But where do they live inside the model? Where does 7 billion come from? How many calculations does training take, how much GPU memory do you need to run it, and how much to train it?
These sound like engineering details, but if you can count the numbers in a matrix and do a little multiplication, you can work out every one of them with pen and paper. Whether a model will run out of memory, how much compute training needs, whether a model fits on a GPU: all of it comes from a handful of back-of-the-envelope formulas.
So in this episode we play accountant. Using one real model, we keep three ledgers, for parameters, compute and memory, and work through them line by line.
Meet the model we're accounting for
A quick reminder of the Transformer: each token goes through the embedding and becomes a D-dimensional vector; then it passes through L identical layers, each doing "RMSNorm → attention" and then "RMSNorm → feed-forward network (FFN)"; after the last layer comes one final RMSNorm; and finally the output layer (the LM head, also called the unembedding) turns the vector into a score for every token in the vocabulary.
The sizes we need (with Llama 2 7B's values):
| Symbol |
Meaning |
Llama 2 7B |
| V |
vocabulary size |
32,000 |
| D |
hidden dimension |
4096 |
| L |
number of layers |
32 |
| F |
FFN hidden dim |
11,008 |
| N |
query heads |
32 |
| H |
dims per head |
128 |
| K |
key/value heads |
32 |
N×H=D. In ordinary multi-head attention K=N; Llama 2 7B's K is also 32, so it uses plain multi-head attention. For activations and compute we'll also use B (sequences per batch) and S (sequence length).
Warm-up: count a tiny model
Warm up on a tiny model: V=10, D=6, L=2, F=16.
- Embedding: just a table, one row per token, each row holding that token's 6-dimensional vector. 10 rows by 6 columns is 60 numbers, every one of them a parameter learned during training.
- Attention: four matrices. Wq,Wk,Wv turn the input into queries, keys and values; Wo mixes the results from all the heads. Each is 6×6, 36 numbers, so 144 for the four.
- FFN (SwiGLU): three matrices. Up and gate widen 6 dimensions to 16, down squeezes 16 back to 6. Each holds 6×16=96, so 288 for the three: the FFN is twice the size of attention.
- Two RMSNorms: each has a single scaling vector γ, one number per dimension, so 2×6=12.
- RoPE, softmax and the residual connections are fixed operations with no parameters.
One layer is 144+288+12=444; two layers make 888. Add the final RMSNorm (6) and the output layer (6×10=60):
| Part |
Params |
| Embedding |
60 |
| 2 layers × 444 |
888 |
| Final RMSNorm |
6 |
| Output layer |
60 |
| Total |
1,014 |
Watch out: The matrix multiplications in models like this have no bias terms, so counting the matrices is all we need.
A real large model has exactly the same structure; it just scales these sizes up.
Swap the numbers for letters
Now in letters:
- Embedding (V,D): VD. The output layer turns D dimensions into V scores: also VD.
- Attention: Wq and Wo are D×D; Wk and Wv are D×KH, for 2D2+2DKH. With grouped-query attention (GQA) there are fewer key-value heads than query heads (K<N), so those two get smaller. In plain multi-head attention KH=D, and attention is 4D2.
- FFN: up and gate are D×F, down is F×D: 3DF.
- Two RMSNorms per layer: 2D. The final RMSNorm: D.
Adding up the ledger:
P=2VD+L(4D2+3DF+2D)+D
We can simplify further. Last episode we saw that SwiGLU's hidden dimension F is usually about 38D, so 3DF≈8D2. Then 4D2+8D2=12D2: the bulk of each layer is like 12 square D×D matrices, 4 for attention and 8 for the FFN. Terms like 2D and D are tiny next to D2, which leaves a formula that's easy to remember:
P≈2VD+12LD2
Check it on the tiny model: 2VD=120 and 12LD2=864, so 984. That's 30 short of the exact 1,014, and the missing 30 are exactly the RMSNorms (2×12+6). The bigger the model, the less that gap matters.
In PyTorch, counting a model's parameters is a one-liner:
num_params = sum(p.numel() for p in model.parameters())
Plug in Llama 2 7B
| Part |
Formula |
About |
| Embedding |
32000×4096 |
131M |
| Attention / layer |
4×40962 |
67M |
| FFN / layer |
3×4096×11008 |
135M |
| 2 RMSNorms / layer |
2×4096 |
8,192 |
| One layer |
|
202M |
| 32 layers |
|
6.48B |
| Final RMSNorm |
|
4,096 |
| Output layer |
4096×32000 |
131M |
Add it all up, down to the last digit, and you get 6,738,415,616: exactly the official parameter count of Llama 2 7B. That's about 6.74 billion; round it off and you get 7B.
The shortcut 2VD+12LD2 gives just over 6.7 billion, off by only half a percent. The gap comes from Llama's F of 11,008 being a little bigger than 38D≈10,923.
Where do the parameters go?
- FFN: about 64.2%
- Attention: about 31.9%
- Embedding + output layer: about 3.9%
- RMSNorm: barely registers
Intuition: In a big model nearly all the parameters live in the matrices inside each layer, especially the FFN. But in a smaller model with a big vocabulary, the embedding and output layer take a noticeably bigger share.
The unit of compute: the FLOP
Compute is measured in FLOPs (floating-point operations): one multiplication or one addition is one FLOP.
Dot product: [1,2,3]⋅[4,5,6] takes 3 multiplications (1×4, 2×5, 3×6) and 2 additions to sum them, 5 in all. A dot product of length n takes n multiplications plus n−1 additions, about 2n FLOPs. Modern chips usually fuse a multiplication and the addition right after it into one multiply-add instruction, so we keep it simple: every multiply-add pair counts as two FLOPs.
Matrix multiplication: an m×n matrix times an n×p matrix gives an m×p matrix. Each number in the result is a row on the left dotted with a column on the right (e.g. 1×1+2×2+3×0=5), costing 2n operations, and there are mp of them:
FLOPs=mp(2n−1)≈2mnp
Remember 2mnp. Every compute estimate from here on is built on it.
The forward pass: about 2P per token
Take one token: its vector is 1×D, multiplied by a D×D weight matrix. With m=1 the cost is 2D2, and the matrix holds exactly D2 parameters.
Intuition: When one token passes through a weight matrix, every parameter is used for exactly one multiply and one add: two operations per parameter.
So the forward cost per token, per layer:
| Part |
FLOPs |
| Q/K/V/O projections |
8D2 |
| FFN's three matrices |
6DF≈16D2 |
| QK⊤ and AV |
4SD |
Attention also has two matrix multiplications with no parameters: dotting the query with every key, then using those weights to sum up the values. With S tokens of context each costs 2SD, so 4SD in total. Finally the output layer costs 2DV. The embedding is just a lookup by token ID, with no multiplications, so it costs no compute.
Plug in F≈38D and the matrix part comes out to roughly twice the parameter count. That's the famous rule of thumb:
forward FLOPs≈2P per token
The attention term (4LSD) compares to the matrix part (24LD2) at a ratio of about S:6D, so it only matters once the context gets really long.
For Llama 2 7B: the matrix part is about 13.2 billion operations, and with a 4096-token context the attention scores add about 2.15 billion more, for about 15.36 billion FLOPs per token.
For a batch of B sequences of S tokens each, multiply by BS. Swap F for 38D and tidy up:
forward FLOPs≈2BSD(12LD+2LS+V)
Deep dive: the notes' term-by-term FLOPs for a whole batch (prefill, S = T)
- Attention, per layer 8BSD2+4BS2D: the Q/K/V/O projections are 2BSD2 each (K and V when K=N); QK⊤ is (B,N,S,H)×(B,N,H,S), costing 2BNS2H=2BS2D since D=NH; AV is another 2BS2D.
- FFN, per layer 6BSDF≈16BSD2: up, gate and down are 2BSDF each.
- Per layer: 8BSD2+4BS2D+16BSD2=2BSD(12D+2S).
- Output layer (B,S,D)×(D,V): 2BSDV.
- Full forward pass: 2LBSD(12D+2S)+2BSDV≈2BSD(12LD+2LS+V).
Backward pass: twice the forward, so training ≈ 6P
The backward pass costs about twice the forward. Why? Take one linear layer Y=XW, with X of size m×n and W of size n×p.
The forward pass is one matrix multiplication: 2mnp.
In the backward pass we already have the gradient of the loss with respect to Y, and we use it to compute two things:
- The gradient for W, used to update the parameters: ∂W∂L=X⊤∂Y∂L.
- The gradient for X, which keeps flowing back to the previous layer as its incoming gradient (the backpropagation of episode 3): ∂X∂L=∂Y∂LW⊤.
Both multiplications are exactly the size of the forward one, 2mnp each, so the backward pass is 4mnp: twice the forward. Hence:
training FLOPs≈forward2P+backward4P=6P per token
You'll see this 6 again and again when we get to scaling laws.
How long does it take to train a 7B?
Llama 2 7B was pre-trained on about 2 trillion (2×1012) tokens:
6×6.74×109×2×1012≈8.1×1022 FLOPs
A single A100 GPU running in BF16 peaks at 312 trillion (3.12×1014) operations per second.
Watch out: FLOPs as a total count and operations per second (a speed) are different things.
Even with one GPU running flat out the whole time, that's about 260 million seconds, more than 8 years. In reality Meta used lots of GPUs together: their paper reports about 184,000 GPU hours in total, while running at peak speed would have taken only 72,000. Compare the two and the GPUs delivered only about 39% of their peak compute on average. That ratio is called model FLOPs utilization (MFU). The rest of the time went to things like moving data around and communication between GPUs; how to push utilization higher is the topic of episodes 14 and 17.
From parameters to bytes
For memory, first we need bytes per number (1 byte = 8 bits):
- FP32 (32-bit float): 4 bytes;
- BF16 (16-bit): 2 bytes.
So Llama 2 7B's weights take about 6.74×109×2≈ 13.5 GB in BF16, and 27 GB in FP32. Squeeze each parameter to 4 bits (half a byte) and you need only about 3.4 GB. Numerical precision and quantization get their own episode, episode 16.
Activations: what the backward pass needs
The other big chunk of memory is activations: all the intermediate results computed during the forward pass.
During inference, as soon as the next step is computed, the previous intermediate results can be thrown away. Not during training: the backward pass needs them to compute gradients. Take ∂W∂L=X⊤∂Y∂L: without X you can't compute it. So every layer's intermediate results must be kept from the forward pass until the backward pass is done with them.
What does each layer store?
- Attention side: RMSNorm's input and output, Q, K, V, and the attention output, each B×S×D (strictly, K and V are B×S×KH, which equals BSD in plain multi-head attention): 6BSD.
- Attention scores: one S×S matrix per sequence per head: BNS2.
- FFN side: RMSNorm's input and down's output, 2BSD; the outputs of gate and up, 2BSF.
All together, per layer:
8BSD+2BSF+BNS2
F is about 2.7 times D, so the linear part comes to around 13 or 14 BSD (the notes write it as 14BSD+BNS2 per layer).
For Llama 2 7B, one sequence of 4096 tokens, 32 layers, stored in BF16: the linear part is about 14.4 GB, but the attention scores take a whopping 34.4 GB.
Watch out: The S2 term grows with the square of the context length: double the context and it gets four times bigger. That's one of the big headaches of long contexts.
FlashAttention computes in tiles and never stores the full S×S matrix, so this term almost disappears (from BNS2 down to BNS), and activations grow linearly with S instead of quadratically. We'll see how in episode 14.
Even so, activations still grow in proportion to the total number of tokens in a batch (BS). Another trick is gradient checkpointing: store only each layer's input, and recompute the other intermediate results during the backward pass. The price is roughly one extra forward pass, so training costs about 8P per token instead of 6P; in exchange you save a big chunk of memory. It trades compute for memory.
Deep dive: how many checkpoints? (from episode 3's notes)
Checkpointing stores only a subset of the activations (the "checkpoints") and recomputes the rest from the nearest checkpoint when needed. Split N layers into K segments and memory drops from O(N) to O(K+N/K). The best choice is K=N, giving O(N) memory for roughly 2× the backward compute.
Inference memory: weights + KV cache
Inference memory has three parts: model weights + KV cache + peak activations.
What's the KV cache? A model generates text one token at a time, and every new token's attention needs the keys and values of all the tokens before it. Those keys and values never change once computed, so we store them and reuse them: that's the KV cache (episode 12 explains how it works; here we only want its size).
For every token, each layer stores one key and one value, each with KH numbers:
per token: 2LKH numbers,total: 2BSLKH
(The 2 is for K and V.) For Llama 2 7B: 2×32×32×128≈262,000 numbers, at 2 bytes each in BF16, about 0.52 MB per token. A 4096-token sequence takes about 2.15 GB; generating B sequences at once multiplies that by B.
Try it: a GPU with 24 GB. The weights take 13.5 GB right away, and every full-length sequence takes 2.15 GB. With the fourth sequence you're at about 22 GB, and a fifth won't fit, and you still need room for activations and the framework itself.
That's one reason newer models widely switched to grouped-query attention. Llama 3 8B, for example, has only 8 key-value heads, which cuts the KV cache to a quarter.
Inference activations can be thrown away as soon as a layer is done (under torch.inference_mode() the memory is freed immediately), so only the peak within a single layer matters: the layer input BSD, Q/K/V about 3BSD, the attention matrix BNS2 (without FlashAttention), and the FFN intermediate BSF. In big-O terms:
- reading a long prompt all at once (prefill): O(BNS2+BSF), where the S2 attention matrix can get huge;
- generating new tokens one by one (decode): O(BNS+BF), which stays small.
Intuition: With small batches and short sequences, the weights dominate. With very long prompts, the S2 term dominates. With very large batches, the KV cache and activations both grow.
Training memory: 18 bytes per parameter
Training memory has four parts: model weights + gradients + optimizer state + activations. The standard approach today is mixed-precision training, and each parameter's bill looks like this:
| Item |
Precision |
Bytes |
| Master weights |
FP32 |
4 |
| Temporary forward copy |
BF16 |
2 |
| Gradient (accumulated) |
FP32 |
4 |
| Adam 1st + 2nd moments |
FP32 |
8 |
| Total |
|
18 |
- Gradients are computed in BF16 but accumulated in FP32.
- The Adam optimizer (episode 4) keeps two extra numbers per parameter: the first and second moments.
Watch out: Why must master weights and gradient accumulation be FP32? Because a single gradient is usually tiny compared with the weight. BF16 can represent a small gradient like 0.0001, but not the updated weight 1.0001: it rounds back to 1.0000, and the update is lost.
18 bytes per parameter is 9 times the 2 bytes needed for inference. Frameworks differ a little, but that's the right ballpark.
Llama 2 7B: master weights 27 GB + copy 13.5 GB + gradients 27 GB + Adam 53.9 GB ≈ 121 GB, before counting activations. Add the activations for one 4096-token sequence, over 14 GB even with FlashAttention, and the total is about 136 GB. A single A100 has only 80 GB.
There's no way that fits on one GPU. So large models are trained by splitting the weights, gradients and optimizer state into pieces spread across many GPUs: that's ZeRO and the various kinds of parallelism in episode 17.
Recap
| Ledger |
Result |
| Parameters |
P≈2VD+12LD2, mostly FFN |
| Matrix multiply |
2mnp FLOPs |
| Forward |
~2P per token, +4LSD for long context |
| Training |
~6P per token |
| Inference memory |
weights + KV cache (2LKH numbers/token) + peak activations |
| Training memory |
~18 bytes/param + activations |
With these ledgers you can judge for yourself whether a model will fit and how long it will take to train. Next time we get back to generation itself: once the model hands us a table of probabilities, how do we actually pick the next word?