SelanjutnyaPanduan berikutnya
SmoothQuant dan Kuantisasi Aktivasi
Teknis
PANDUAN Teknis
Activation recomputation, also called activation or gradient checkpointing, saves GPU memory during neural network training by discarding intermediate results from the forward pass and recomputing them when the backward pass needs them.
Dengarkan panduan iniDiceritakan oleh AI · ~8 min
It typically costs 30 to 40 percent more compute when applied to every layer, and choosing what to recompute is a central lever for training large models.
Training a neural network with backpropagation has two phases. In the forward pass, the input flows through each layer and every layer produces an output, called an activation. In the backward pass, the training algorithm works from the loss back toward the input, computing a gradient for every weight. Most of those gradient calculations need the activations from the forward pass, so by default a framework such as PyTorch or JAX keeps every activation in memory until the backward pass uses it. Activation recomputation, also known as activation checkpointing, gradient checkpointing or rematerialization, changes that rule: it keeps only some activations, discards the rest, and recomputes the discarded ones from the nearest kept value when the backward pass needs them.
The reason this matters is that activation memory, unlike weight memory, grows with the size of each training batch and with sequence length. For large transformers it often dominates. Korthikanti and colleagues at NVIDIA give a formula for a single transformer layer with no model parallelism: activation memory in bytes is roughly s times b times h times (34 + 5as/h), where s is sequence length, b is microbatch size, h is hidden size and a is the number of attention heads. The 5as/h part comes from attention, which builds a score for every pair of tokens, so it grows with the square of the sequence length. For a GPT-3-sized configuration that term equals 80, larger than the 34 from everything else. Multiplied across nearly a hundred layers, the stored activations can exceed the memory of any single GPU even before the weights are counted.
The mechanism is simple to state. Pick a set of checkpoints, usually the inputs to certain layers or blocks. During the forward pass, save only those checkpoints and throw away everything computed between them. During the backward pass, when gradients reach a block, rerun that block's forward computation from its saved input to rebuild its internal activations, use them to compute gradients, and free them again before moving to the previous block. Only one block's worth of full activations needs to be in memory at a time, plus the checkpoints. The price is that most forward computation is done twice.
The idea was brought into mainstream deep learning practice by Tianqi Chen, Bing Xu, Chiyuan Zhang and Carlos Guestrin in the April 2016 paper Training Deep Nets with Sublinear Memory Cost. They showed that for a network of n layers, placing a checkpoint every square root of n layers cuts activation memory from proportional to n to proportional to the square root of n, at the cost of roughly one extra forward pass per mini-batch. They also showed a more extreme version that reduces memory to proportional to log n at the cost of order n log n extra forward computation. Their headline example reduced the memory for a 1,000-layer residual network from 48 GB to 7 GB with about 30 percent more running time. In 2019, the Checkmate paper by Paras Jain and colleagues at Berkeley, published at MLSys 2020, framed checkpoint selection as a mixed integer linear program that finds an optimal recomputation schedule for a given memory budget in under an hour with off-the-shelf solvers, and reported training with up to 5.1 times larger inputs.
For large language models, the key refinement is selective recomputation. Korthikanti and colleagues observed in May 2022 that not all activations are equally expensive to recompute. The attention operations, meaning the query-key product, the softmax, softmax dropout and the weighted sum over values, create large activations but require relatively few floating point operations per element. The large matrix multiplications in the feed-forward layers are the opposite. By recomputing only the attention pieces and storing everything else, combined with sequence parallelism, which splits certain layer operations across GPUs along the sequence dimension, they reduced activation memory by about five times and cut the time overhead of recomputation by more than 90 percent. For a single 22-billion-parameter layer, they measured full recomputation adding 39 percent execution time and the combined approach only 4 percent. End to end, training throughput rose by about 30 percent across models from 22 billion to 1 trillion parameters.
Recomputation competes with several alternatives, and real systems mix them. Doing nothing is fastest when memory allows. Shrinking the microbatch reduces activation memory linearly but hurts GPU efficiency. Offloading moves activations to CPU memory and back, trading compute for data transfer; PyTorch's selective checkpointing API and JAX's policies both include offload options. Model parallelism splits activations across GPUs at the cost of communication. Fused kernels such as FlashAttention, posted in May 2022 by Tri Dao and colleagues, never write the full attention matrix to GPU memory: they store the softmax normalization statistics and recompute attention blocks on-chip during the backward pass. The paper reports this makes memory linear in sequence length and speeds up the backward pass despite the extra arithmetic, because reading and writing GPU high-bandwidth memory was the real bottleneck.
The limitations are mostly about cost and correctness. Full recomputation adds roughly 30 to 40 percent of execution time in the NVIDIA measurements, which translates directly into training cost. Placing checkpoints poorly saves little memory: the JAX documentation notes that checkpointing the entire differentiated function, or only its last stage, saves nothing and wastes compute. Recomputation must also reproduce the forward pass exactly. Layers that use randomness, such as dropout, need the random number generator state restored, which PyTorch does by default through preserve_rng_state at some performance cost. The PyTorch documentation warns that if a checkpointed function behaves differently on the second run, for example because it reads a global variable, the result can be an error or silently incorrect gradients.
In practice, using recomputation requires little code but careful measurement. In PyTorch, wrapping each transformer block with torch.utils.checkpoint.checkpoint and passing use_reentrant=False, which the documentation recommends, is the usual starting point; selective policies can then save specific operations such as matrix multiplies. In JAX, jax.checkpoint with a policy does the same, and the documentation notes that under jax.jit the XLA compiler often makes these choices automatically. The right setting is found by profiling peak memory and step time together: the goal is the largest batch or sequence length that fits, at the lowest recomputation overhead, since every percent of overhead is paid on every training step.
04Contoh yang berhasil
Take a configuration with sequence length s = 2,048, microbatch b = 1, hidden size h = 12,288 and a = 96 attention heads.
Compute sbh = 2,048 x 1 x 12,288 = 25,165,824, and the attention term 5as/h = 5 x 96 x 2,048 / 12,288 = 80.
With no recomputation, per-layer memory is sbh x (34 + 80) = about 2.87 billion bytes, or roughly 2.9 GB.
With selective recomputation of attention, the attention term drops out: sbh x 34 = about 0.86 GB per layer.
With full recomputation, only the layer input is kept: 2sbh = about 50 MB per layer.
Multiply each figure by 96 layers to compare totals of about 275 GB, 82 GB and 4.8 GB.
Apa yang ditunjukkannya
The learner sees why selective recomputation is the usual middle ground: it removes about 70 percent of activation memory, matching the reduction NVIDIA reports for GPT-3, while full recomputation saves far more memory but repeats almost the whole forward pass. The arithmetic can be checked against the formulas in the 2022 NVIDIA paper.
Chen and colleagues reported in 2016 that recomputation cut the memory needed to train a 1,000-layer residual network on ImageNet from 48 GB to 7 GB, at the cost of about 30 percent more running time.
NVIDIA researchers used selective recomputation with sequence parallelism to train a 530-billion-parameter GPT-3-style model on 2,240 A100 GPUs, raising model FLOPs utilization from 42.1 to 54.2 percent.
PyTorch exposes the technique as torch.utils.checkpoint, where wrapping a block such as a transformer layer makes autograd store only its inputs and rerun the block during backward.
JAX offers jax.checkpoint with named policies such as dots_with_no_batch_dims_saveable, which keeps expensive matrix-multiply results and recomputes cheaper elementwise operations.
FlashAttention (2022) avoids storing the full attention matrix and recomputes it on-chip in the backward pass, which its authors report makes the backward pass faster, not slower, because it reduces memory traffic.
Recent work treats recomputation as one decision in a joint plan with parallelism, offloading and kernel fusion rather than a switch. Checkmate (2019) showed optimal schedules can be solved for a memory budget, and the 2022 NVIDIA work showed that choosing operations by memory per FLOP recovers most of the lost throughput. Framework APIs have followed: PyTorch's documentation describes selective activation checkpointing with per-operation save, recompute and CPU offload policies, and says that omitting the use_reentrant argument raises an exception starting in version 2.9, pushing users to the newer non-reentrant implementation. JAX documents named policies that save matrix multiplies or offload them to host memory. Open problems include automatic policies that adapt to sequence length during training, interactions with compilers that already rematerialize values on their own, and long-context training, where the attention term that grows with the square of sequence length makes the choice of what to store more important. FlashAttention's 2022 result, that recomputation can be faster than storage when memory bandwidth is the bottleneck, suggests that the cost model for these decisions depends on hardware and will keep shifting as GPU memory and bandwidth change.
Buletin gratis
Tiga cerita AI terverifikasi setiap pagi hari kerja, ditulis dalam bahasa Inggris sederhana. Gratis selamanya, tanpa iklan.
Satu email setiap hari kerja. Berhenti berlangganan dalam satu klik. Kami tidak pernah menjual atau membagikan alamat Anda.
Uji diri Anda sendiri
Umpan balik instan untuk setiap jawaban, dan sertifikat yang dapat dibagikan dengan ID yang dapat diverifikasi setelah Anda lulus kursus.
Mendukung pendidikan AI gratis. AI Understanding adalah organisasi nirlaba 501(c)(3) — tanpa iklan, tanpa paywall, selamanya. Berikan sumbangan
Activation recomputation, also called activation or gradient checkpointing, saves GPU memory during neural network training by discarding intermediate results from the forward pass and recomputing them when the backward pass needs them. It typically costs 30 to 40 percent more compute when applied to every layer, and choosing what to recompute is a central lever for training large models.
Komputasi ulang membuang aktivasi yang tersimpan dan membuatnya kembali dalam proses backward pass, sehingga menghabiskan komputasi ekstra untuk mengurangi penggunaan memori.
Jalur mundur menggunakan aktivasi maju untuk menghitung gradien, jadi secara default, gradien disimpan dalam memori hingga jalur mundur berjalan.
Recomputation spends additional compute, but the observed runtime depends on the selected operations and system.
The theoretical square-root result concerns activation checkpointing in an appropriate chain model, not every category of training memory.
Komputasi ulang selektif menargetkan operasi yang menggunakan banyak memori tetapi sedikit komputasi (seperti softmax atau layernorm), sambil menyimpan hasil GEMM yang mahal untuk meminimalkan FLOP yang terbuang.
Teruslah belajar
Panduan lainnya dipilih untuk topik ini
SelanjutnyaPanduan berikutnya
SmoothQuant dan Kuantisasi Aktivasi
Teknis