PANDUAN Teknikal

Tukar Ganti Pengiraan Semula Pengaktifan

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.

Dengar panduan iniAI-diceritakan · ~8 min

Pada halaman ini9 min dibaca
  1. Gambaran keseluruhan
  2. Pengambilan utama
  3. Menyelam dalam
  4. Estimate activation memory for one GPT-3-sized layer
  5. Pelaksanaan Dunia Sebenar
  6. Masa Depan Tukar Ganti Pengiraan Semula Pengaktifan
  7. Mempraktikkannya
  8. Sumber dan bacaan lanjut
  9. Teruskan Meneroka
  10. Soalan lazim

Gambaran keseluruhan

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.

Pengambilan utama

  1. Activation recomputation stores only some forward-pass activations and recomputes the rest during the backward pass, trading extra compute for lower memory.
  2. Chen and colleagues showed in 2016 that checkpointing every square root of n layers reduces activation memory to order square root of n.
  3. Full recomputation added 30 to 40 percent execution time in NVIDIA's 2022 measurements on large transformer models.
  4. Selective recomputation of attention operations cut activation memory about five times with sequence parallelism and recovered about 30 percent throughput.
  5. Recomputation must reproduce the forward pass exactly, so dropout random state must be restored and nondeterministic code can corrupt gradients.

Menyelam dalam

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 dikerjakan

Estimate activation memory for one GPT-3-sized layer

  1. Take a configuration with sequence length s = 2,048, microbatch b = 1, hidden size h = 12,288 and a = 96 attention heads.

  2. 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.

  3. With no recomputation, per-layer memory is sbh x (34 + 80) = about 2.87 billion bytes, or roughly 2.9 GB.

  4. With selective recomputation of attention, the attention term drops out: sbh x 34 = about 0.86 GB per layer.

  5. With full recomputation, only the layer input is kept: 2sbh = about 50 MB per layer.

  6. Multiply each figure by 96 layers to compare totals of about 275 GB, 82 GB and 4.8 GB.

Apa yang ditunjukkan

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.

Pelaksanaan Dunia Sebenar

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.

Masa Depan Tukar Ganti Pengiraan Semula Pengaktifan

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.

Mempraktikkannya

Mengapa ia penting

  • Kos dan bajet. Keputusan seni bina memacu prestasi dan kos operasi selama bertahun-tahun.
  • Keputusan yang lebih jelas. Pendidikan teknikal membantu pasukan memilih timbunan yang betul, bukan hanya yang terbaharu.
  • Kawalan kualiti. Pilihan kejuruteraan yang lebih baik mengurangkan insiden kebolehpercayaan dalam pengeluaran.

Berhati-hati untuk

  • Mengoptimumkan satu penanda aras boleh menyembunyikan kelemahan sistem yang lebih luas.
  • Kos infrastruktur dan penyelenggaraan sering dipandang remeh.
  • Jurang keselamatan dan pemerhatian boleh berkembang apabila sistem menjadi lebih kompleks.

Langkah seterusnya

  1. Tentukan sasaran kependaman, kualiti dan kos sebelum pelaksanaan.
  2. Penanda aras di bawah beban realistik dan keadaan data.
  3. Pemantauan instrumen untuk ralat, drift dan kesan pengguna.
  4. Sediakan laluan balik dan tindak balas insiden sebelum penskalaan.

Sumber dan bacaan lanjut

  1. arXiv (Chen, Xu, Zhang, Guestrin)Training Deep Nets with Sublinear Memory Cost
  2. arXiv (NVIDIA)Reducing Activation Recomputation in Large Transformer Models
  3. arXiv / MLSys 2020Checkmate: Breaking the Memory Wall with Optimal Tensor Rematerialization
  4. arXiv (Dao et al.)FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
  5. PyTorch documentationtorch.utils.checkpoint
  6. JAX documentationGradient checkpointing with jax.checkpoint (jax.remat)

Teruskan Meneroka

Newsletter percuma

Dapatkan taklimat AI harian

Tiga cerita AI yang disahkan setiap pagi hari bekerja, ditulis dalam Bahasa Inggeris biasa. Percuma selamanya, tiada iklan.

Satu e-mel setiap hari bekerja. Berhenti melanggan dalam satu klik. Kami tidak pernah menjual atau berkongsi alamat anda.

Uji diri anda

Take the Activation Recomputation Tradeoffs quiz

Maklum balas segera pada setiap jawapan, dan sijil yang boleh dikongsi dengan ID yang boleh disahkan sebaik sahaja anda lulus kursus.

Mulakan kuiz

Sokong pendidikan AI percuma. AI Understanding ialah pertubuhan bukan keuntungan 501(c)(3) — tiada iklan, tiada bayaran dinding, selamanya. Buat derma

Soalan lazim

What is Activation Recomputation Tradeoffs?

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.

Apakah yang diperdagangkan oleh pengiraan semula pengaktifan untuk menjimatkan memori?

Pengiraan semula membuang pengaktifan yang disimpan dan menjananya semula dalam pas ke belakang, membelanjakan pengiraan tambahan untuk mengurangkan penggunaan memori.

Mengapakah pengaktifan laluan ke hadapan biasanya disimpan sama sekali?

Hantaran ke belakang menggunakan pengaktifan ke hadapan untuk mengira kecerunan, jadi secara lalai ia disimpan dalam ingatan sehingga hantaran ke belakang berjalan.

Why should activation checkpointing overhead be measured on the actual model?

Recomputation spends additional compute, but the observed runtime depends on the selected operations and system.

For an idealized N-layer chain with comparable activations, what storage scaling can square-root checkpoint placement achieve?

The theoretical square-root result concerns activation checkpointing in an appropriate chain model, not every category of training memory.

Apakah idea di sebalik pengiraan semula terpilih (tidak penuh)?

Pengiraan semula terpilih menyasarkan operasi yang menggunakan banyak memori tetapi sedikit pengiraan (seperti softmax atau layernorm), sambil menyimpan cache hasil GEMM yang mahal untuk meminimumkan FLOP yang sia-sia.