# The Compute and Memory Ledger of Training: FLOPs, MFU and Memory Budgets

> How many FLOPs, GPU hours and bytes of memory does training a model need? This page works out where 6ND comes from, what MFU measures, why model states cost 16 bytes per parameter, how activation memory scales, and how to sanity-check reported GPU hours.

- URL: https://dmxsf.com/en/wiki/pretraining/compute-and-memory/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-11
- Tags: Pretraining, Scaling laws, Distributed training

## After this page you will be able to

- Derive where training FLOPs ≈ 6ND come from, and say which parameters count in N.
- Explain what MFU means, convert FLOPs into GPU hours with it, and check the numbers reported in papers.
- Work out the memory of model states (16 bytes per parameter) and of activations, and explain how recomputation trades compute for memory.
- Combine the compute, time and memory accounts into one full training estimate, and diagnose the usual symptoms.

Training a dense Transformer costs about $6N$ FLOPs per token, where $N$ is the number of parameters that take part in matrix multiplications, so $6ND$ for $D$ tokens. Divide that by the useful compute of each GPU (the hardware peak times the [MFU](https://dmxsf.com/en/glossary/#mfu)) and you get GPU hours. Memory splits into two parts: the **model states**, which do not depend on the batch (16 bytes per parameter with mixed-precision AdamW), and the **activations**, which grow linearly with batch size and sequence length. This page works out all three ledgers and checks them against numbers from published papers.

## The ledgers at a glance

| Ledger | Question | Core formula | Llama 2 7B as an example |
| --- | --- | --- | --- |
| Compute | How many floating-point operations in total? | $C \approx 6ND$ | $6 \times 6.74\times10^{9} \times 2.0\times10^{12} \approx 8.09\times10^{22}$ FLOPs |
| Time | How many GPU hours? | $\dfrac{C}{\text{peak}\times\text{MFU}\times3600}$ | The paper reports 184,320 A100 hours, which implies an MFU of about 39% |
| Memory | Does it fit on one card? | Model states $16N$ bytes, plus activations | Model states about 100 GiB, activations for 4096 tokens about 19 GiB |

The three ledgers constrain each other. Compute decides how long a run takes, memory decides whether it can run at all, and they meet at recomputation: trading compute for memory costs about a third more compute. We will do compute first, then time, then memory.

## The compute ledger: why 6N

### Three matrix multiplications per linear layer

Start with the smallest unit. A linear layer $Y = XW$ turns one token's $d_{in}$-dimensional vector into a $d_{out}$-dimensional one, which takes $d_{in}\times d_{out}$ multiplications and about as many additions. Counting a multiply-add as 2 FLOPs, the forward cost per token is $2\,d_{in}d_{out}$, that is 2 FLOPs per parameter.

Backpropagation computes two gradients: the gradient with respect to the input, $dX = dY\,W^\top$ (handed to the previous layer), and the gradient with respect to the weights, $dW = X^\top dY$ (used to update them). Each is a matrix multiplication of the same size as the forward one, so the backward pass costs twice the forward pass. In total, every parameter costs $2 + 4 = 6$ FLOPs per token.

*Figure: Figure 1: the training cost of a linear layer Y = X·W (W is d_in × d_out). One matrix multiplication forward, two more backward (for the input and for the weights), each costing 2·d_in·d_out FLOPs (a multiply-add counts as 2 FLOPs), so training costs 3 times the forward pass.*

Almost all of a Transformer's computation is linear layers like this: the q, k, v and o projections of attention and the three matrices of the FFN. Add up their parameters as $N$, and the training compute for $D$ tokens is

$$
C \approx 6\,N\,D
$$

Kaplan et al. (2020) derived this in their work on [scaling laws](https://dmxsf.com/en/wiki/pretraining/scaling-laws/), and the compute accounting in PaLM and Megatron-LM uses it too.

### Which parameters count toward N

Precisely, $N$ is the **number of parameters that take part in matrix multiplications**, not the total parameter count:

| Parameters | Counted in N? | Why |
| --- | --- | --- |
| q, k, v, o projections and the three FFN matrices | Yes | Every token goes through a matrix multiplication |
| Output layer (lm_head) | Yes | It maps the hidden state to the vocabulary, again a matrix multiplication |
| Input embedding table | No | It is a lookup by token id, with no multiplication |
| RMSNorm scales | No | Element-wise, only $O(h)$ of them, negligible |
| Experts in a mixture of experts (MoE) | Only the active ones | Each token passes through only its top-$k$ experts |

How much it matters depends on the vocabulary. Llama 2 7B has 6.74B parameters in total and 6.61B take part in matrix multiplications (98.1%), a 2% gap. Llama 3 8B has 8.03B in total, but its 128,256 × 4,096 input embedding table is 0.53B, so only 7.50B (93.5%) take part, and multiplying the total by 6 would overestimate the compute by about 7%. For a mixture of experts the gap is larger: DeepSeek-V3 has 671B parameters in total but activates 37B per token ([paper](https://arxiv.org/abs/2412.19437)), so compute should be estimated from 37B; see [Mixture of Experts](https://dmxsf.com/en/wiki/architecture/mixture-of-experts/).

### The attention-matrix term: the part that grows with sequence length

$6N$ leaves out the $QK^\top$ and $AV$ products of attention because they have no parameters: every token takes dot products with the $s$ tokens before it. With $H$ heads of dimension $d_h$, one layer costs $4\,H d_h s$ FLOPs in the forward pass (half for $QK^\top$, half for $AV$), and training multiplies that by 3. A more complete per-token training cost is therefore

$$
\text{FLOPs/token} \approx 6N + 12\,L\,H\,d_h\,s
$$

where $L$ is the number of layers and $s$ the sequence length. This is the convention of PaLM ([Chowdhery et al., 2022](https://arxiv.org/abs/2204.02311), Appendix B), Megatron-LM and FlashAttention-2. It counts the full $s\times s$ matrix, while a causal mask needs only the lower triangle, about half; the FlashAttention-2 paper says explicitly that it does not halve the second term, to stay consistent with the literature. The table shows the attention term as a share of the per-token training FLOPs (full-matrix convention, with the lower-triangle share in parentheses):

| Sequence length $s$ | Llama 2 7B shape | Llama 3 405B shape |
| --- | --- | --- |
| 4,096 | 14.0% (7.5%) | 4.0% (2.1%) |
| 8,192 | 24.5% (14.0%) | 7.7% (4.0%) |
| 32,768 | 56.5% (39.4%) | 25.1% (14.4%) |
| 131,072 | 83.9% (72.2%) | 57.3% (40.1%) |

For short sequences the term is negligible, but it takes over quickly as sequences grow: under the full-matrix convention the attention term equals the linear term at a sequence length of about 25,200 for the 7B shape and about 97,800 for the 405B shape, and twice that under the causal convention. This is why long-context training needs [context parallelism](https://dmxsf.com/en/glossary/#context-parallelism) and efficient attention kernels; see [Long Context](https://dmxsf.com/en/wiki/architecture/long-context/) and [Efficient Attention](https://dmxsf.com/en/wiki/architecture/efficient-attention/).

### Recomputation, kernels and element-wise operations

6ND is a clean baseline. Real training deviates from it in a few places:

| Factor | Effect |
| --- | --- |
| Full activation recomputation | One more forward pass before backward, so the hardware executes $8ND$, which is $4/3$ of $6ND$ |
| FlashAttention backward | The backward kernel recomputes the attention scores, so the attention part of backward costs about 2.5 times its forward (FlashAttention-2's counting convention); MFU does not count this kind of recomputation in its numerator |
| Mixture of experts | Count active parameters only; routing, expert communication and load imbalance lower utilization but do not change the formula |
| Element-wise operations | RMSNorm, the element-wise product in SwiGLU, RoPE and softmax cost few FLOPs but read and write memory repeatedly, which is why MFU stays low, not a reason for extra FLOPs |
| Optimizer update | It runs once per step, and a step processes millions of tokens, so it is negligible next to $6ND$ |

### Check it in code: count the FLOPs of a tiny Llama

You do not have to trust the derivation, because PyTorch's `FlopCounterMode` can count for you (it counts matrix-multiplication-like operators). The snippet below runs one forward and backward pass of a very small Llama (4 layers, hidden size 256) and compares the counts with the formulas above; it needs `transformers`:

```python
import torch
from torch.utils.flop_counter import FlopCounterMode
from transformers import LlamaConfig, LlamaForCausalLM

cfg = LlamaConfig(hidden_size=256, intermediate_size=688, num_hidden_layers=4, num_attention_heads=4,
                  num_key_value_heads=2, vocab_size=1000, tie_word_embeddings=False, attn_implementation="eager")
model = LlamaForCausalLM(cfg)
B, S = 2, 128
ids = torch.randint(0, cfg.vocab_size, (B, S))

# Parameters that take part in matrix multiplications: the 2-D weights of every layer plus the output layer;
# the input embedding is only a lookup, so it does not count
n_matmul = sum(p.numel() for p in model.model.layers.parameters() if p.dim() == 2) + model.lm_head.weight.numel()

counter = FlopCounterMode(display=False)
with counter:
    loss = model(ids, labels=ids).loss
    forward = counter.get_total_flops()
    loss.backward()
backward = counter.get_total_flops() - forward

T = B * S
attention = cfg.num_hidden_layers * 4 * cfg.hidden_size * S * S * B   # QKᵀ and AV on the full S×S matrix
print(f"forward, measured         {forward:,}")
print(f"2·N·T + attention         {2 * n_matmul * T + attention:,}")
print(f"backward / forward        {backward / forward:.3f}")
print(f"measured total / (6·N·T)  {(forward + backward) / (6 * n_matmul * T):.3f}")
# forward, measured         1,750,081,536
# 2·N·T + attention         1,750,073,344
# backward / forward        2.000
# measured total / (6·N·T)  1.083
```

The measured forward count differs from $2NT$ plus the attention term by only 8,192 FLOPs (one small matrix multiplication that builds the RoPE rotation table in the Hugging Face implementation), and the backward pass is exactly twice the forward pass. The total is 8.3% above $6NT$, all of it from the attention term: this tiny model has a hidden size of only 256, so attention weighs relatively more.

The whole-network formula in the appendix of the Megatron-LM paper, $F = 96\,Bsl h^2\left(1 + \frac{s}{6h} + \frac{V}{16lh}\right)$, is the same accounting: each layer costs $24Bsh^2 + 4Bs^2h$ in the forward pass, multiplied by 4 (forward, recomputation and a doubled backward), plus $6BshV$ for the output layer. Plugging in the GPT-3 175B shape gives identical results for both forms.

## The time ledger: MFU and GPU hours

### What MFU measures

FLOPs alone are not enough; you also need to know how fast each card really runs. **MFU** (Model FLOPs Utilization) was introduced in the PaLM paper: the measured tokens per second divided by the throughput a system would reach at peak FLOPs, where both numerator and denominator count only the operations the model needs for forward and backward, **without recomputation**.

$$
\text{MFU} = \frac{\text{tokens per second} \times \left(6N + 12\,L\,H\,d_h\,s\right)}{\text{number of GPUs} \times \text{peak FLOPs per GPU}}
$$

Its counterpart **HFU** (Hardware FLOPs Utilization) also counts the recomputation in the numerator and shows how busy the hardware is. PaLM 540B used recomputation, with an MFU of 46.2% and an HFU of 57.8%. MFU does not depend on the implementation, so it is the right number for comparing systems; HFU flatters a run that recomputes more. The two examples below come from PaLM's Appendix B (attention term ignored):

```python
def mfu(tokens_per_s, n_params, n_gpus, peak_flops):
    return tokens_per_s * 6 * n_params / (n_gpus * peak_flops)

print(f"{mfu(65.43e3, 530e9, 2240, 312e12):.3f}")   # Megatron-Turing NLG 530B, 2240 A100 → 0.298 (the paper rounds down to 29.7%)
print(f"{mfu(238.3e3, 540e9, 6144, 275e12):.3f}")   # PaLM 540B, 6144 TPU v4 (peak 275 TFLOP/s) → 0.457
```

Reported MFU values make a good frame of reference:

| System | Hardware | MFU | Source |
| --- | --- | --- | --- |
| GPT-3 175B | V100 | 21.3% | PaLM, Table 3 |
| Gopher 280B | 4096 TPU v3 | 32.5% | PaLM, Table 3 |
| Megatron-Turing NLG 530B | 2240 A100 | 30.2% | PaLM, Table 3 |
| PaLM 540B | 6144 TPU v4 | 46.2% (HFU 57.8%) | PaLM, Table 3 |
| Megatron-LM 530B, selective recomputation | 2240 A100 | 54.2% (42.1% with full recomputation) | Korthikanti et al., 2022 |
| Llama 3 405B | 8,192 to 16,384 H100 | 38% to 43% | Llama 3 paper, Table 4 |

Utilization stays below 100% for several reasons: element-wise operations, normalization and softmax are limited by memory bandwidth; communication and synchronization (gradient reduction, tensor-parallel all-reduce, pipeline bubbles) are not fully hidden behind computation; small batches give matrices too small to keep the compute units busy; and data loading, checkpointing and restarts after failures take time. The Llama 3 paper gives one example: MFU on 16K GPUs is 41%, two points below the 43% on 8K GPUs, because the global batch is held at 16 million tokens, so with more GPUs each data-parallel group gets a smaller batch.

### GPU hours, days and per-GPU throughput

Divide $6ND$ by the useful compute and every quantity you need falls out:

$$
\text{GPU hours} = \frac{6ND}{\text{peak}\times\text{MFU}\times3600},\qquad
\text{days} = \frac{\text{GPU hours}}{\text{GPUs}\times24},\qquad
\text{tokens/s per GPU} = \frac{\text{peak}\times\text{MFU}}{6N}
$$

Use the dense BF16 peak: 312 TFLOPs for the A100, 989 TFLOPs for the H100 SXM (the 1,979 you often see in [NVIDIA's specifications](https://www.nvidia.com/en-us/data-center/h100/) is the figure with sparsity, twice the dense one), and 275 TFLOPs for a TPU v4 (PaLM, Appendix B).

Things to try:

1. **Keep the defaults: Llama 3 405B, H100, 40% utilization, 16,384 GPUs.** The hardware executes $3.79\times10^{25}$ FLOPs (the paper reports $3.8\times10^{25}$), about 26.62 million GPU hours and 67.7 days, roughly 163 tokens per second per GPU and about 2.67 million tokens per second for the whole cluster. The MFU is 40%, inside the 38% to 43% of the paper's Table 4.
2. **Load the DeepSeek-V3 preset.** The FLOPs drop to $3.29\times10^{24}$, about 1/11.5 of Llama 3 405B: its 671B total parameters exceed 405B, but only 37B are active per token, and $N$ in 6ND is 37B.
3. **Load Llama 2 7B, pick the A100 and 40% utilization.** About 187 thousand GPU hours against the 184,320 the paper reports, and about 2,971 tokens per second per GPU against 3,014 implied by the paper's numbers.
4. **Go back to Llama 3 405B and tick "Full activation recomputation".** GPU hours rise from 26.62 million to 35.49 million, a third more, and the MFU tile drops to 30.0%: at the same hardware utilization, MFU counted on 6ND is only 75%.
5. **Look at the chart.** At a fixed utilization, every 4× in GPUs divides the days by 4, a straight line of slope −1 on log-log axes; the dashed line is 10 points lower utilization, a third more days (40% against 30%). On a real cluster utilization falls with scale, so the real curve sits slightly above this line.

### Check against published numbers

With $6ND$ and the GPU hours a paper reports, you can back out the useful compute per GPU and test whether the number is plausible:

| Model | $6ND$ (FLOPs) | Reported GPU hours | Useful compute per GPU | Share of A100 peak |
| --- | --- | --- | --- | --- |
| Llama 2 7B | $8.09\times10^{22}$ | 184,320 | 121.9 TFLOPs | 39.1% |
| Llama 2 13B | $1.56\times10^{23}$ | 368,640 | 117.7 TFLOPs | 37.7% |
| Llama 2 34B | $4.05\times10^{23}$ | 1,038,336 | 108.3 TFLOPs | 34.7% |
| Llama 2 70B | $8.28\times10^{23}$ | 1,720,320 | 133.7 TFLOPs | 42.8% |
| DeepSeek-V3 (37B active) | $3.29\times10^{24}$ | 2,664K (H800) | 342.6 TFLOPs | not converted |

The four Llama 2 models were trained on A100-80GB GPUs with 2.0T tokens each, with $N$ taken as the actual parameter count (6.74B, 13.02B, 33.74B, 68.98B); the implied utilizations all land between 35% and 43%, in line with the MFU table above. DeepSeek-V3 was trained on H800 GPUs with FP8 mixed precision for its main matrix multiplications, so its peak is not the BF16 peak; the table therefore gives only the useful compute per GPU and does not convert it to an MFU. Another figure from the paper is consistent with it: 180K GPU hours per trillion tokens, which is 3.7 days on 2048 GPUs.

The same back-calculation catches implausible claims. If someone says they trained a 7B model on 2T tokens in 10,000 A100 hours, $6ND$ is about $8.1\times10^{22}$ while the peak compute of 10,000 A100 hours is only $1.1\times10^{22}$, more than 7 times too little, so the claim cannot be right.

## The memory ledger: model states

### 16 bytes per parameter

The things that sit in memory regardless of the batch are called the **model states**. For mixed-precision AdamW each parameter stores:

| Item | Precision | Bytes per parameter |
| --- | --- | --- |
| Weights (used in forward and backward) | BF16 | 2 |
| Gradients | BF16 | 2 |
| Master weights (used for the update) | FP32 | 4 |
| AdamW first moment $m$ | FP32 | 4 |
| AdamW second moment $v$ | FP32 | 4 |
| Total |  | 16 |

The master weights and moments are kept in FP32 because BF16 has only 8 significant bits, so adding a small update to a weight would round it away (see [Optimizers and Training Stability](https://dmxsf.com/en/wiki/foundations/optimizers-and-training-stability/) for the reasoning, and the [Mixed Precision Training](https://arxiv.org/abs/1710.03740) paper for the master-copy idea). Another common layout is PyTorch's `autocast`: parameters and gradients stay in FP32 (4 plus 4 bytes) and the two FP32 moments add 8 bytes, again 16 bytes. You can count it directly:

```python
import torch

model = torch.nn.Linear(4096, 4096, bias=False)           # 16.8M parameters
opt = torch.optim.AdamW(model.parameters())
model(torch.randn(8, 4096)).sum().backward()
opt.step()                                                  # AdamW creates its state on the first step

nbytes = lambda t: t.numel() * t.element_size()
weights = sum(nbytes(p) for p in model.parameters())
grads = sum(nbytes(p.grad) for p in model.parameters())
states = sum(nbytes(v) for s in opt.state.values() for v in s.values() if torch.is_tensor(v) and v.dim() > 0)
n = sum(p.numel() for p in model.parameters())
print((weights + grads + states) / n)                       # 16.0
```

So the model states of Llama 2 7B (6.74B parameters) take $16 \times 6.74\times10^{9} = 107.8$ GB, about 100.4 GiB, more than one 80 GB card holds. ZeRO ([Rajbhandari et al., 2019](https://arxiv.org/abs/1910.02054)) shards these states across $N_d$ data-parallel GPUs:

| Scheme | Model states per GPU | 8 GPUs | 64 GPUs |
| --- | --- | --- | --- |
| ZeRO-0 (no sharding) | $16N$ | 100.4 GiB | 100.4 GiB |
| ZeRO-1 (shard optimizer states) | $4N + 12N/N_d$ | 34.5 GiB | 26.3 GiB |
| ZeRO-2 (also shard gradients) | $2N + 14N/N_d$ | 23.5 GiB | 13.9 GiB |
| ZeRO-3 or FSDP (also shard parameters) | $16N/N_d$ | 12.6 GiB | 1.6 GiB |

Figure 1 of the ZeRO paper applies the same formulas (Ψ = 7.5B, 64 GPUs) and gets 120, 31.4, 16.6 and 1.9 GB, matching the formulas in the table. This part is always resident and does not depend on the batch; beyond it you still have to leave room for communication buffers, fragmentation and framework overhead.

## The memory ledger: activations

### What activations are and why they grow with tokens

**Activations** are the intermediate tensors produced in the forward pass that the backward pass still needs. For example $dW = X^\top dY$ needs the forward input $X$, so each linear layer's input, each normalization's input, attention's q, k and v and so on must be kept until backward. Their number is proportional to the number of tokens (batch size times sequence length) and to the number of layers. PyTorch's `saved_tensors_hooks` lets you count exactly how many bytes backward keeps; the snippet below counts a SwiGLU FFN (hidden size 512, intermediate size 1376, BF16):

```python
import torch
import torch.nn.functional as F

h, f, tokens = 512, 1376, 4096
w_gate, w_up = (torch.randn(f, h, dtype=torch.bfloat16, requires_grad=True) for _ in range(2))
w_down = torch.randn(h, f, dtype=torch.bfloat16, requires_grad=True)
x = torch.randn(tokens, h, dtype=torch.bfloat16, requires_grad=True)

weights = {w.untyped_storage().data_ptr() for w in (w_gate, w_up, w_down)}   # weights are not activations
saved = {}

def pack(t):
    ptr = t.untyped_storage().data_ptr()
    if ptr not in weights:
        saved[ptr] = t.untyped_storage().nbytes()       # count each block of memory once
    return t

with torch.autograd.graph.saved_tensors_hooks(pack, lambda t: t):
    y = F.linear(F.silu(F.linear(x, w_gate)) * F.linear(x, w_up), w_down)

print(sum(saved.values()) / tokens, 2 * h + 8 * f, len(saved))   # 12032.0 12032 5
```

Five tensors are saved: the input $x$ ($2h$ bytes per token), the outputs of gate and up, SiLU(gate), and the product of the two ($2f$ bytes per token each), exactly $2h + 8f$.

### How much one Transformer layer keeps

List everything a whole layer keeps:

| Saved tensor (per token, BF16) | Bytes |
| --- | --- |
| Input of the RMSNorm before attention (the residual stream) | $2h$ |
| RMSNorm output (shared by the q, k, v projections) | $2h$ |
| q (after RoPE) | $2h$ |
| k and v (k after RoPE, and v) | $4\,G\,d_h$ |
| Attention output (kept by FlashAttention for backward) | $2h$ |
| Input of the RMSNorm before the FFN | $2h$ |
| RMSNorm output (shared by gate and up) | $2h$ |
| gate, up, SiLU(gate) and their product | $8f$ |
| Total | $12h + 4\,G\,d_h + 8f$ |

Here $h$ is the hidden size, $G$ the number of KV heads, $d_h$ the head dimension and $f$ the FFN intermediate size. Counting a whole layer the same way (fused RMSNorm kernel, FlashAttention attention), the measurement comes out 1% to 2% above this formula; the extra is the FP32 statistics of RMSNorm, attention's logsumexp and the RoPE tables, and the share shrinks as models get larger.

Korthikanti et al. (2022) give the number for a GPT-style layer (no FlashAttention, with dropout): $sbh\left(34 + 5\,a s / h\right)$ bytes per layer, where $s$ is the sequence length, $b$ the batch size and $a$ the number of attention heads. The $5as/h$ term inside the parentheses comes from the $s\times s$ attention scores, the softmax and the dropout mask, and grows with the square of the sequence length; FlashAttention never stores that matrix (it recomputes it block by block during backward), so the Llama-style formula has no such term.

| Model | $h$ | $G\,d_h$ | $f$ | Layers | Per token per layer | Per token, whole model | 4,096 tokens |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Llama 2 7B | 4096 | 4096 | 11008 | 32 | 150.0 KiB | 4.69 MiB | 18.75 GiB |
| Llama 3 8B | 4096 | 1024 | 14336 | 32 | 164.0 KiB | 5.12 MiB | 20.50 GiB |

Activations grow linearly with the number of tokens: double the batch or the sequence and they double (with FlashAttention there is no quadratic term). The activations of 4,096 tokens (18.75 GiB) are already larger than the model states under 8-way ZeRO-3 (12.6 GiB).

The output logits need their own accounting, with shape $(b\cdot s,\ V)$. Llama 3 has a vocabulary of 128,256, so the FP32 logits of 4,096 tokens alone take $4096\times128256\times4$ bytes $=1.96$ GiB; with the BF16 copy and the gradient in backward the total reaches several GiB, which is most noticeable when the vocabulary is large and the model is small. Some implementations compute the loss in chunks so that the whole logits tensor never sits in memory at once.

### Activation recomputation: trading compute for memory

Full recomputation keeps only each layer's input ($2h$ bytes per token per layer). When backward reaches a layer, it redoes that layer's forward pass from the saved input, gets the activations it needs, and discards them right after use. For Llama 2 7B and 4,096 tokens, the inputs of 32 layers take 1.00 GiB and the working set of the one layer being recomputed adds 0.59 GiB, 1.59 GiB in total, about 1/11.8 of the 18.75 GiB without recomputation. The price is one extra forward pass per step: the hardware executes $8ND$ instead of $6ND$, a third more, and at the same hardware utilization the MFU counted on $6ND$ drops to 75%.

Selective recomputation recomputes only the parts that "take a lot of memory and are cheap to redo", mainly the inside of attention. Korthikanti et al. combine it with sequence parallelism, cutting activation memory to about a fifth and removing more than 90% of the time overhead of recomputation; training a 530B model on 2240 A100 GPUs, MFU rises from 42.1% with full recomputation to 54.2%. FlashAttention already contains the same idea: it stores no attention matrix and recomputes it in backward.

| Strategy | Activation memory | Extra compute |
| --- | --- | --- |
| No recomputation | Largest | None |
| Selective recomputation (inside attention only) | Much lower | Small |
| Full recomputation | Smallest, about $2h$ bytes per token per layer | A third more |

## Putting the ledgers together: a worked example

Take Llama 2 7B on 8 cards of 80 GiB, sequence length 4096, BF16 activations and ZeRO-3, compare three configurations, and add unsharded data parallelism for reference:

*Figure: Figure 2: memory estimate for Llama 2 7B (6.74B parameters), sequence length 4096, BF16 activations and mixed-precision AdamW. Model states are 16 bytes per parameter; activations are (12h + 4·G·d_h + 8f) bytes per token per layer over 32 layers; logits count a BF16 tensor plus an FP32 copy, 6 bytes per element; full recomputation keeps only each layer's input plus one layer's working set. This is a lower-bound estimate that leaves out communication buffers, fragmentation and framework overhead.*

| Item (GiB per GPU) | Micro-batch 1, no recompute | Micro-batch 3, no recompute | Micro-batch 1, full recompute |
| --- | --- | --- | --- |
| Model states (ZeRO-3, 8 GPUs) | 12.55 | 12.55 | 12.55 |
| Activations | 18.75 | 56.25 | 1.59 |
| Output logits | 0.73 | 2.20 | 0.73 |
| Total | 32.03 | 71.00 | 14.87 |

How to read it: without sharding nothing fits; ZeRO-3 fixes the model states, and the bottleneck moves to activations. A micro-batch of 3 is already close to 80 GiB, and a fourth sequence (about 90 GiB) does not fit. Full recomputation cuts each sequence's activations to about a twelfth, so the same card holds twenty or more, at the price of a third more compute per step. Whether it pays off depends on the bottleneck: skip it when memory is enough, and use it when you need a larger micro-batch or a longer sequence.

All of these are lower-bound estimates that leave out communication buffers, fragmentation, the CUDA context and temporary tensors. Before a real launch, measure with `torch.cuda.max_memory_allocated()` and tune from the measurement.

## Symptoms and what to check

| Symptom | Common cause | What to do first |
| --- | --- | --- |
| Out of memory right at startup | The model states do not fit | Compute $16N$; use ZeRO-3 or FSDP, or add GPUs |
| Out of memory after a few steps, or after switching to longer sequences | Activations grow linearly with tokens and logits grow with the vocabulary | Reduce the micro-batch or the sequence; turn on recomputation; compute the loss in chunks |
| MFU of only 10% to 20% | Communication not overlapped with computation, slow data loading, tiny micro-batches, pipeline bubbles | Use a profiler to see where the GPU idles; enlarge the micro-batch |
| MFU falls after adding GPUs | With a fixed global batch each group gets a smaller batch and communication weighs more | Llama 3: 43% on 8K GPUs, 41% on 16K |
| Each token gets slower as the sequence grows | The attention term takes a larger share | Use a FlashAttention kernel; use context parallelism for very long sequences |
| Reported GPU hours do not add up | $N$ was the total parameter count, a mixture of experts was not counted by active parameters, or the sparse peak was used | Recompute with the conventions on this page |

## Summary and exercises

**Key points:**

1. Per parameter and token: 2 FLOPs forward, 4 FLOPs backward, 6 in total; training compute is about $6ND$, where $N$ counts the parameters that take part in matrix multiplications (not the input embedding; active parameters for a mixture of experts).
2. Long sequences add the attention term $12\,L\,H\,d_h\,s$; full activation recomputation adds another third.
3. GPU hours equal $6ND$ divided by peak times MFU; you can back out MFU from reported GPU hours to check them, and 30% to 45% is a common range.
4. Model states cost 16 bytes per parameter and ZeRO shards them across GPUs; activations cost about $12h + 4\,G\,d_h + 8f$ bytes per token per layer and grow linearly with tokens; full recomputation trades a third more compute for about twelve times more room for activations.

**1. About how many times the forward FLOPs does the backward pass of the matrix multiplications cost?**

- [ ] 1 time
- [x] 2 times
- [ ] 3 times
- [ ] 4 times

> The backward pass runs two matrix multiplications, one for the gradient with respect to the input and one for the gradient with respect to the weights, each the same size as the forward one, so 2 times. Forward plus backward is 3 times the forward pass, which is 6 FLOPs per parameter per token.

**2. What should $N$ be when you estimate the training compute of Llama 3 8B?**

- [ ] 8.03B, the total parameter count
- [x] 7.50B, without the input embedding table
- [ ] 6.98B, leaving out the output layer too and counting only the weights inside the layers
- [ ] 0.53B, only the embedding table

> The input embedding is a lookup by token id with no matrix multiplication, so it does not count; the output layer is a matrix multiplication from the hidden size to the vocabulary that every token goes through, so it does. The 128,256 × 4,096 input embedding table is 0.53B, and subtracting it from the 8.03B total leaves 7.50B.

**3. With full activation recomputation, about how many FLOPs does the hardware execute compared with no recomputation, for the same model and data?**

- [ ] 1 time
- [ ] 1.17 times
- [x] 4/3 times
- [ ] 2 times

> Recomputation adds one more forward pass: 2 for forward, 2 for recomputation and 4 for backward make 8 FLOPs per parameter per token, which is 4/3 of the original 6.

**4. With mixed-precision AdamW and no sharding, how many bytes of model state does each parameter take?**

- [ ] 4
- [ ] 8
- [ ] 12
- [x] 16

> BF16 weights 2 plus BF16 gradients 2, plus an FP32 master copy 4, a first moment 4 and a second moment 4, 16 bytes in total.

**5. A report says it trained a 7B model on 2T tokens in 10,000 A100 GPU hours. What do you make of it?**

- [ ] Plausible, a 7B model is small
- [x] Implausible: it needs about $8.1\times10^{22}$ FLOPs, while the peak compute of 10,000 A100 hours is only about $1.1\times10^{22}$
- [ ] Plausible as long as MFU is above 50%
- [ ] Cannot tell without the number of GPUs

> The peak compute is $10^{4}\times3600\times312\times10^{12}\approx1.1\times10^{22}$ FLOPs, less than a seventh of what is needed; even 100% MFU could not do it. GPU hours already include the number of cards, so you do not need the GPU count.

**6. Which of these lower the real MFU of a training setup? (select all that apply)**

- [x] Gradient reduction that is not overlapped with backward computation
- [x] Pipeline-parallel bubbles
- [ ] Using a FlashAttention kernel
- [ ] Enlarging the micro-batch (as long as it fits in memory)

> Communication exposed outside computation and idle pipeline time leave the GPU waiting and pull MFU down. FlashAttention reduces memory traffic and usually raises MFU; a larger micro-batch gives bigger matrices that keep the compute units busier and usually raises it too.

**Exercises:**

1. Use $6ND$ to estimate the training compute of Llama 3 405B (15.6T tokens) and compare it with the $3.8\times10^{25}$ FLOPs the paper reports.
2. A 13B model is trained on 1T tokens with H100 GPUs (BF16 dense peak 989 TFLOPs), 40% MFU and 512 GPUs. How many days does it take?
3. How much memory do the model states of a 13B model need? How much per card with ZeRO-3 on 8 GPUs?
4. Suppose the Llama 2 7B shape is used on 8192-token sequences (micro-batch still 1). How do activation memory and the training FLOPs per token change?

<details>
<summary>Reference answers</summary>

1. $6\times405\times10^{9}\times15.6\times10^{12}=3.79\times10^{25}$ FLOPs, in agreement with the paper's $3.8\times10^{25}$ (about 0.2% apart).
2. $C=6\times13\times10^{9}\times10^{12}=7.8\times10^{22}$ FLOPs; useful compute $989\times10^{12}\times0.4=3.956\times10^{14}$ FLOPs/s; GPU hours $=7.8\times10^{22}/(3.956\times10^{14}\times3600)\approx54{,}769$; divided by 512 cards and by 24, about 4.5 days.
3. $16\times13\times10^{9}=208$ GB, about 193.7 GiB; with ZeRO-3 on 8 GPUs about 24.2 GiB per card.
4. Activations are proportional to the number of tokens and, with FlashAttention, have no quadratic term, so they double from 18.75 GiB to 37.5 GiB. For the FLOPs per token, the linear term $3.964\times10^{10}$ is unchanged while the attention term grows from $6.44\times10^{9}$ to $1.29\times10^{10}$ (from 14.0% to 24.5% of the total), so the total goes from $4.61\times10^{10}$ to $5.25\times10^{10}$, about 14% more.

</details>

## Further reading

- Chowdhery et al., [PaLM: Scaling Language Modeling with Pathways](https://arxiv.org/abs/2204.02311) (2022); Appendix B defines MFU and works through examples
- Narayanan et al., [Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM](https://arxiv.org/abs/2104.04473) (2021); the appendix gives the whole-network FLOPs formula
- Korthikanti et al., [Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/abs/2205.05198) (2022); per-layer activation memory, selective recomputation and sequence parallelism
- Rajbhandari et al., [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://arxiv.org/abs/1910.02054) (2019)
- Micikevicius et al., [Mixed Precision Training](https://arxiv.org/abs/1710.03740) (2017)
- Kaplan et al., [Scaling Laws for Neural Language Models](https://arxiv.org/abs/2001.08361) (2020); Section 2.1 derives $C\approx6NBS$
- Dao, [FlashAttention-2](https://arxiv.org/abs/2307.08691) (2023); how attention FLOPs are counted
- Touvron et al., [Llama 2: Open Foundation and Fine-Tuned Chat Models](https://arxiv.org/abs/2307.09288) (2023); GPU hours in Table 2
- Llama Team, [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) (2024); parallelism configurations and MFU in Table 4
- DeepSeek-AI, [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) (2024); training cost and FP8 training

## Companion code

[Training compute and memory: 6ND, MFU, model state and activations](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/compute-and-memory): Every formula on the page checked against a measurement: PyTorch's FLOP counter, the tensors autograd saves for the backward pass, and the optimizer's state; then MFU, GPU hours and a full Llama 2 7B account on 8 x 80 GiB.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/compute-and-memory`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/compute-and-memory/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/compute-and-memory/README.en.md)
- [`accounting.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/pretraining/accounting.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#compute-and-memory)

## FAQ

### Why does training a large model cost about 6ND FLOPs?

When a linear layer processes one token, every weight takes part in one multiplication and one addition, which is about 2 FLOPs per parameter in the forward pass. The backward pass runs two more matrix multiplications of the same size, one for the gradient with respect to the input and one for the gradient with respect to the weights, about 4 FLOPs per parameter. That adds up to roughly 6N FLOPs per token, where N counts the parameters that take part in matrix multiplications, and 6ND for D training tokens. The attention matrix, activation recomputation and mixture-of-experts layers move the real number away from this baseline.

### What is MFU, and what counts as a high value?

MFU (model FLOPs utilization) is the useful FLOPs implied by the measured training throughput divided by the hardware's peak FLOPs. The numerator counts only the operations the model needs for its forward and backward passes, not recomputation. Reported values include about 21% for GPT-3, about 46% for PaLM 540B and 38% to 43% for Llama 3 405B. Between 30% and 45% is a common range for large runs, and well-tuned systems can pass 50%. Communication that is not overlapped, small batches or slow data loading push it much lower.

### How much memory does it take to train a 7B model?

With mixed-precision AdamW the model states (BF16 weights and gradients plus an FP32 master copy and two FP32 moments) cost 16 bytes per parameter. For 6.74B parameters that is about 100 GiB, which does not fit on one 80 GB card, so the states must be sharded across GPUs with ZeRO or FSDP; with ZeRO-3 on 8 GPUs each card holds about 12.6 GiB. Activations come on top and grow with batch size and sequence length, about 19 GiB for 4096 tokens without recomputation, plus the output logits and communication buffers.

### How much memory does activation recomputation save, and what does it cost?

Full recomputation keeps only each layer's input and redoes the forward pass layer by layer during backward. For Llama 2 7B and 4096 tokens it cuts activations from 18.75 GiB to about 1.6 GiB, roughly one twelfth. The price is an extra forward pass per step, so the hardware executes 8ND instead of 6ND FLOPs and, at the same hardware utilization, training takes about a third longer.

### How can I tell whether a reported number of GPU hours is plausible?

Divide 6ND by the GPU hours and the hardware peak to get the implied utilization. A value between 30% and 50% means the order of magnitude is plausible, and anything above 100% means the numbers cannot be right. Llama 2 7B reports 184,320 A100 hours for 2.0T tokens, which implies about 39%. Use the parameters that take part in matrix multiplications, the active parameters for a mixture of experts, the dense peak, and a separate peak for FP8 mixed precision.
