Files
transformers/docs/source/en/model_memory_anatomy.md
陈赣 06f1fd69a6
Some checks failed
Self-hosted runner (nightly-past-ci-caller) / Get number (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.11 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.10 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.9 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.8 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.7 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.6 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.5 (push) Has been cancelled
Self-hosted runner (benchmark) / Benchmark (aws-g5-4xlarge-cache) (push) Has been cancelled
Build documentation / build (push) Has been cancelled
Build documentation / build_other_lang (push) Has been cancelled
CodeQL Security Analysis / CodeQL Analysis (push) Has been cancelled
New model PR merged notification / Notify new model (push) Has been cancelled
PR CI / pr-ci (push) Has been cancelled
Slow tests on important models (on Push - A10) / Get all modified files (push) Has been cancelled
Secret Leaks / trufflehog (push) Has been cancelled
Update Transformers metadata / build_and_package (push) Has been cancelled
Slow tests on important models (on Push - A10) / Model CI (push) Has been cancelled
Check Tiny Models / Check tiny models (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Model CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Pipeline CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Example CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / DeepSpeed CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI - Flash Attn / Setup (push) Has been cancelled
Nvidia CI - Flash Attn / Model CI (push) Has been cancelled
Nvidia CI / Setup (push) Has been cancelled
Nvidia CI / Model CI (push) Has been cancelled
Nvidia CI / Torch pipeline CI (push) Has been cancelled
Nvidia CI / Example CI (push) Has been cancelled
Nvidia CI / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI / DeepSpeed CI (push) Has been cancelled
Nvidia CI / Quantization CI (push) Has been cancelled
Nvidia CI / Kernels CI (push) Has been cancelled
Doctests / Setup (push) Has been cancelled
Doctests / Call doctest jobs (push) Has been cancelled
Doctests / Send results to webhook (push) Has been cancelled
Extras Smoke Test / Get supported Python versions (push) Has been cancelled
Extras Smoke Test / Test extras on Python ${{ matrix.python-version }} (push) Has been cancelled
Extras Smoke Test / Check Slack token availability (push) Has been cancelled
Extras Smoke Test / Notify failures to Slack (push) Has been cancelled
Self-hosted runner (AMD scheduled CI caller) / Trigger Scheduled AMD CI (push) Has been cancelled
Stale Bot / Close Stale Issues (push) Has been cancelled
first commit
2026-06-05 16:53:03 +08:00

6.1 KiB
Raw Permalink Blame History

GPU memory usage

Training a 4B parameter model in mixed precision on a batch size of 16 requires roughly 85GB of GPU memory. Understanding what occupies GPU memory and the compute operations that occur during training help identify where you can reduce your memory usage.

┌─────────────────────────── TENSORS ──────────────────────────────────┐
│                                                                      │
│  MODEL WEIGHTS       ████████████████████████  6 bytes/param         │
│  (mixed precision)   ├── fp16 copy (2B) — forward/backward pass      │
│                      └── fp32 copy (4B) — stable weight updates      │
│                                                                      │
│  OPTIMIZER STATES    ████████████████████████████████  8 bytes/param │
│  (Adam)              ├── fp32 momentum  (4B)                         │
│                      └── fp32 variance  (4B)                         │
│                      ↳ quantized Adam (bitsandbytes) → 2 bytes/param │
│                                                                      │
│  GRADIENTS           ████████████████  4 bytes/param  (fp32)         │
│                      └── computed in backward pass, per parameter    │
│                                                                      │
│  ACTIVATIONS         ████ varies — batch × seq_len × depth × hidden  │
│  (forward cache)     └── cached for backward; can OOM even if model  │
│                          fits (long seqs / large batches)            │
│                          bf16/fp16 if using mixed precision          │
│                                                                      │
│  TEMPORARY TENSORS   ▓ short-lived (softmax, matmul scratch)         │
│                      └── peak spikes can cause OOM                   │
│                                                                      │
│  OTHER OVERHEAD      ▒ beam search caches, large embedding tables    │
└──────────────────────────────────────────────────────────────────────┘

GPU memory holds two categories of things: stored tensors and the ops that process them.

Tensors

Training requires and produces many tensor types that need to be stored.

  • Model weights are stored on the GPU. In mixed precision training, two copies of the weights are required - one in fp16 for the forward/backward pass and one in fp32 as the "main copy" for stable weight updates. This equates to 6 bytes per parameter.

  • Optimizer states such as Adam store two extra tensors per parameter, the momentum and variance, which are both in fp32. That's an additional 8 bytes per parameter.

    You could use a different optimizer like a quantized version of Adam from bitsandbytes to compress it to 2 bytes per parameter.

  • Gradient tensors are computed for each parameter in the backward pass. This is kept in fp32 so that's 4 bytes per parameter.

  • Forward activations are computed in the forward pass and cached for the backward pass to compute the gradients. These activations vary in size with batch size, sequence length, model depth, and hidden size. This is why batch size or sequence length can exhaust GPU memory even if the model itself fits.

  • Temporary tensors are created by ops like softmax and matrix multiplications and released after each op. If the peak of a single op is very intensive, it can create a temporary spike that causes you to run out of memory.

  • Some features add their own overhead. For example, beam search maintains multiple outputs, and embedding tables for large vocabularies can be very large.

Ops

There are three main types of training ops.

  • Matrix multiplications (matmuls) are the main op type, covering linear layers, QKV projections, attention output projections, and FFN layers. The main memory hogs are the attention score matrices which grow with the square of the sequence length. This is why long sequences are so expensive and different attention backends exist to avoid materializing the full matrix in memory.

  • Reduction ops, like softmax and layer norm, read a full tensor, compute a statistic across a dimension, and then read the tensor again to apply it. This requires accessing memory multiple times per operation.

  • Element-wise ops, like activations and dropout, apply a function to each element independently and their memory usage is proportional to tensor size.

Next steps

  • See the Gradient accumulation guide to learn how to simulate training on a larger effective batch size without running out of GPU memory.
  • See the Gradient checkpointing guide to learn how to reduce memory usage by only storing some intermediate activations.
  • See the Mixed precision training guide to learn how to use lower precision data types to reduce memory and speed up training.
  • See the Kernels guide to learn how to speed up training with custom fused kernels.