Choose a checkpoint interval that minimizes activation memory

Why it matters Checkpointing is the standard way to fit long sequences and large batches into GPU memory, at the cost of extra forward compute.

Activation checkpointing stores only every k-th layer's activations during the forward pass and recomputes the others during backward. Memory then has two parts: the stored checkpoints and the layers of one segment being recomputed.

Write best_checkpoint_interval(n_layers, act_bytes). For an interval k from 1 to n_layers, memory = ceil(n / k) checkpoints plus (k - 1) recomputed layers, all times act_bytes. Extra compute is the fraction of layers that must be recomputed, (n - ceil(n / k)) / n. Return (best_k, memory_bytes, recompute_frac) for the k with the smallest memory, ties to the smaller k.

Signaturedef best_checkpoint_interval(n_layers, act_bytes)

Example

n_layers 16, act_bytes 1 gives (4, 7, 0.75).

Understand the idea

Checkpointing is like taking photos at a few stops on a long road trip instead of filming the whole way. If you need to see a stretch again, you drive it again from the nearest photo. Few photos save space but mean long re-drives; many photos mean short re-drives but more storage. Worked example: 16 layers. With k = 4, you store 4 checkpoints and, when going backward through one segment, recompute up to 3 layers, so memory is 7 layers' worth instead of 16. You recompute 12 of 16 layers, an extra 75 percent of a forward pass. Rule: memory(k) = ceil(n / k) + k - 1, minimized near k = sqrt(n). Training frameworks expose this as a per-block option, and large-model runs usually checkpoint every transformer block.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplebest_checkpoint_interval(16, 1)
  • Sample 2: bytesbest_checkpoint_interval(10, 2e8)
  • Test 3: one layerbest_checkpoint_interval(1, 5)
  • Test 4: oddbest_checkpoint_interval(30, 1)