MLCrack

    DEEP LEARNING Β· INTERVIEW QUESTION

    What is gradient checkpointing? When and why would you use it?

    πŸ”΄ advanced Β· Training & Optimization

    Hint: Trade compute for memory by recomputing activations during backward pass.

    Answer

    Backward needs certain tensors from the forward computation; they must be saved or recomputed, rather than necessarily storing every intermediate.

    For large models, this activation memory can exceed GPU capacity. Gradient checkpointing: only store activations at certain 'checkpoint' layers. During backward pass, recompute the intermediate activations from the nearest checkpoint (requires an extra forward pass for those segments).

    Tradeoff: recomputation reduces saved activation memory at added compute cost. Under simplified equal-layer assumptions, a particular square-root checkpoint schedule reduces activation storage from O(L)O(L) to O(L)O(\sqrt{L}). General schedules have different tradeoffs; measure actual peak memory and runtime rather than assuming a fixed 33% overhead.

    When to use:

    1. Training models that don't fit in GPU memory.

    2. When you want larger batch sizes.

    3. Essential for training billion-parameter models.

    Implementation: PyTorch's torch.utils.checkpoint.checkpoint(), DeepSpeed activation checkpointing. Selective checkpointing: only checkpoint specific layers (e.g., attention layers which have large activations). Combined with mixed precision and gradient accumulation for maximum memory efficiency.