Building a GPU Memory Budget for LLM Fine-Tuning
Machine LearningModel answerLast updated
Work out how much accelerator memory a language-model fine-tuning job needs, covering weights, gradients, optimizer state, activations, buffers, and parallelism, for both full and LoRA-style tuning.
Building a GPU Memory Budget for LLM Fine-Tuning
A teammate wants to fine-tune a transformer language model and asks whether it will fit on the GPUs you have. Describe how you would estimate the per-device memory the job needs.
Your answer should:
- Give a formula (or ledger) with explicitly named assumptions, instead of quoting one universal "bytes per parameter" figure.
- Cover each component: parameters, gradients, optimizer states, activations, temporary buffers, numeric precision, and sequence/batch shape.
- Show how the choice of data, tensor, or pipeline parallelism (and sharding) changes the per-device numbers.
- Contrast full fine-tuning with parameter-efficient adaptation.
- Reason about peak memory, not only the steady-state allocation, since peak decides whether the job runs out of memory.
Before estimating, say which clarifying questions you would ask (for example: which optimizer and numeric formats, how many parameters are trainable, and what batch size, sequence length, checkpointing and parallel layout are planned).
Hints
Hint 1
Start with the model-state ledger: bytes per parameter for weights, gradients, master weights, and optimizer moments, expressed in terms of the precision and optimizer you assume.
Hint 2
Activation memory grows roughly with layers x tokens per microbatch x hidden size, and attention scores can add a term that grows with sequence length squared unless fused kernels are used. Think about what checkpointing trades away.
Hint 3
Sharding and parallelism move memory around rather than always removing it: ask what each strategy splits (states, weights, activations) and what extra buffers or replicated pieces it introduces. Then add headroom for fragmentation and validate with a profiler.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach: a memory ledger
Per-device memory is the sum of a few buckets, each of which I would write as a function of stated assumptions:
M_peak ≈ M_model_state + M_activations + M_temp/comm + M_overhead
Let Ψ be the total parameter count and Ψ_t the trainable count.
1. Model state (depends on trainable parameters)
Mixed-precision full fine-tuning with Adam is the common baseline:
| Item | Bytes per parameter |
|---|---|
| bf16/fp16 weights | 2 |
| bf16/fp16 gradients | 2 |
| fp32 master weights | 4 |
| Adam first moment (fp32) | 4 |
| Adam second moment (fp32) | 4 |
| Total | ~16 |
So a 7B model needs about 7e9 x 16 ≈ 112 GB of state before a single activation is stored. Variations matter: pure bf16 training without master weights drops to about 8 bytes per parameter, 8-bit optimizers cut the moments to about 2 bytes, and SGD with momentum keeps only one moment. This is why the answer must be stated against the optimizer and formats, not as a fixed "16 bytes".
2. Parameter-efficient tuning (LoRA / adapters)
The frozen base is stored once, usually in bf16 (2 bytes per parameter) or quantized to 4 or 8 bits (QLoRA-style, about 0.5 to 1 byte per parameter plus small quantization constants). Gradients and optimizer state exist only for the Ψ_t adapter parameters, typically 0.1% to 2% of Ψ:
M_state ≈ Ψ·b_base + Ψ_t·(b_w + b_g + b_master + b_opt)
For a 7B model in bf16 with about 40M LoRA parameters: base 14 GB plus adapters at about 16 bytes each ≈ 0.6 GB. State becomes small, which makes activations the dominant term. Gradients still flow through the frozen layers, so activation memory is not reduced by LoRA itself.
3. Activations
Activation memory scales roughly as:
M_act ≈ L · (b · s) · h · c · bytes
where L is the number of layers, b the microbatch size, s the sequence length, h the hidden size, and c a constant that depends on the architecture (often around 10 to 34 stored tensors' worth per layer per token, depending on MLP width, dropout masks and precision). Attention scores add a term proportional to b · heads · s² unless a fused kernel (FlashAttention-style) avoids materializing them, which turns that term into something linear in s.
Levers:
- Activation checkpointing: store only layer boundaries and recompute the rest. Memory falls from about
Llayers' worth to about√Lor one layer plus boundaries, at the cost of roughly 30% extra compute. - Smaller microbatch plus gradient accumulation: reduces activations linearly while keeping the effective batch.
- Shorter or packed sequences, and avoiding padding waste.
- Logits: the output layer produces
b · s · Vvalues (V = vocabulary size), often in fp32 for the loss. For V of 128k and 8k tokens this is about 4 GB and is a common surprise peak.
4. Parallelism and sharding: what actually moves
- Plain data parallel (DDP): every rank holds the full state. Memory per device does not shrink; only throughput scales.
- ZeRO / FSDP: stage 1 shards optimizer state, stage 2 also gradients, stage 3 also parameters. With
Nranks the 16-byte ledger becomes roughly16/Nper parameter at stage 3, plus the transient all-gathered weights for the layer currently executing. Activations are not sharded, so they still scale with the local microbatch. - Tensor parallel (degree
T): weights, gradients, optimizer state and many activations split by aboutT, but some tensors (layer norms, residual-stream activations) are replicated unless sequence parallelism is also used, and communication buffers are added. - Pipeline parallel (degree
P): each stage holds aboutL/Players, so state is divided byP, but to keep the pipeline busy each stage holds activations for several in-flight microbatches (up to aboutPfor 1F1B schedules), and the first stage is typically the heaviest.
So parallelism redistributes memory and adds its own costs. It does not make the total vanish.
5. Temporary buffers and overhead
- All-gather and reduce-scatter buckets, NCCL workspace, gradient bucket copies.
- Fused-kernel workspaces and cuBLAS handles.
- The CUDA context (about 0.5 to 1 GB) and allocator fragmentation (budget 5% to 15% headroom).
- The optimizer step can briefly hold extra copies (for example, casting gradients to fp32), and checkpoint saving can create a CPU or GPU spike.
6. Peak versus steady state
Peak usually occurs at the end of the forward pass or start of backward (activations fully built, logits and loss alive), or during the optimizer step in unsharded setups. Estimating from the steady state after one step underestimates it. Validate with torch.cuda.max_memory_allocated() and the memory snapshot tool, run a few steps at the real maximum sequence length, and compare against the ledger.
Worked example
7B model, full fine-tune, bf16 with fp32 Adam, FSDP full sharding on 8 GPUs, checkpointing on, microbatch 4 x 4096 tokens:
- State: 112 GB / 8 = 14 GB
- All-gathered layer weights and buckets: about 2 to 3 GB
- Activations with checkpointing: layer boundaries 32 x 16k tokens x 4096 x 2 bytes ≈ 4.3 GB, plus one layer's recompute working set of a few GB
- Logits with V=128k: about 4 to 8 GB depending on precision and chunking
- Overhead and fragmentation: about 10%
Total is roughly 30 to 40 GB, which fits on an 80 GB card with room to raise the microbatch. Without sharding, 112 GB of state alone would not fit.
Common mistakes
- Quoting "16 bytes per parameter" without stating optimizer and precision.
- Assuming LoRA removes the activation cost.
- Forgetting the logits tensor and the transient all-gathered weights.
- Assuming data parallelism reduces per-GPU memory.
- Ignoring fragmentation and sizing to 100% of capacity.
- Never measuring: the ledger is a plan, the profiler is the verdict.