기술 가이드

활성화 재계산 장단점

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.

이 가이드를 들어보세요AI 내레이션 · ~8 min

이 페이지에서9분 읽기
  1. 개요
  2. 주요 시사점
  3. 심층 분석
  4. Estimate activation memory for one GPT-3-sized layer
  5. 실제 구현
  6. 활성화 재계산 트레이드오프의 미래
  7. 실천에 옮기기
  8. 출처 및 추가 자료
  9. 계속 탐색하세요
  10. 자주 묻는 질문

개요

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.

주요 시사점

  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.

심층 분석

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.

04실제 사례

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.

그것이 보여주는 것

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.

실천에 옮기기

왜 중요한가요?

  • 비용 및 예산. 아키텍처 결정은 수년 동안 성능과 운영 비용을 결정합니다.
  • 더 명확한 결정들. 기술 교육은 팀이 최신 스택뿐만 아니라 올바른 스택을 선택하는 데 도움이 됩니다.
  • 품질 관리. 더 나은 엔지니어링 선택은 생산 시 신뢰성 사고를 줄입니다.

조심하세요

  • 하나의 벤치마크를 최적화하면 더 광범위한 시스템 약점을 숨길 수 있습니다.
  • 인프라 및 유지 관리 비용은 종종 과소평가됩니다.
  • 시스템이 더욱 복잡해짐에 따라 보안 및 관찰 가능성의 격차가 커질 수 있습니다.

다음 단계

  1. 구현하기 전에 지연 시간, 품질, 비용 목표를 정의하세요.
  2. 현실적인 로드 및 데이터 조건에서 벤치마킹합니다.
  3. 오류, 드리프트 및 사용자 영향에 대한 계측기 모니터링.
  4. 확장하기 전에 롤백 및 사고 대응 경로를 준비하세요.

출처 및 추가 자료

  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 documentation토치.utils.체크포인트
  6. JAX documentationGradient checkpointing with jax.checkpoint (jax.remat)

계속 탐색하세요

무료 뉴스레터

일일 AI 브리핑 받기

매주 평일 아침마다 3개의 검증된 AI 스토리를 일반 영어로 작성합니다. 무료이며, 광고 없음.

매주 평일마다 한 번 이메일을 받습니다. 한 번 클릭으로 구독 해지. 주소를 판매하거나 공유하지 않습니다.

자신을 테스트해 보세요

Take the Activation Recomputation Tradeoffs quiz

모든 답변에 즉각적인 피드백과, 과정을 통과하면 검증 가능한 ID가 있는 공유 가능한 인증서를 제공합니다.

퀴즈 시작

무료 AI 교육을 지원합니다. AI Understanding는 501(c)(3) 비영리 단체입니다 — 광고 없음, 유료 장벽 없음, 영원히. 기부하기

자주 묻는 질문

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.

메모리를 절약하기 위해 활성화 재계산은 무엇을 교환합니까?

재계산은 저장된 활성화를 삭제하고 역방향 패스에서 다시 생성하므로 추가 계산을 사용하여 메모리 사용량을 줄입니다.

정방향 통과 활성화가 일반적으로 저장되는 이유는 무엇입니까?

역방향 패스는 순방향 활성화를 사용하여 그래디언트를 계산하므로 기본적으로 역방향 패스가 실행될 때까지 메모리에 유지됩니다.

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.

선택적(전체가 아님) 재계산의 기본 개념은 무엇입니까?

선택적 재계산은 메모리는 많이 사용하지만 컴퓨팅은 거의 사용하지 않는 작업(예: 소프트맥스 또는 레이어놈)을 대상으로 하며, 비용이 많이 드는 GEMM 결과를 캐싱하여 낭비되는 FLOP를 최소화합니다.