Cutting GRPO Loss VRAM by 67% with Fused Triton Kernels
How online Softmax tiling, activation recomputation, and a custom torch.autograd.Function eliminated [B, S, V] log_softmax materialization during LLM post-training—cutting peak loss VRAM from 7.1 GB to 2.4 GB with a 2.96× speedup on an NVIDIA A100.
7.1 GB → 2.4 GB (Qwen2.5-152k)
16.4 ms → 5.6 ms on A100-40GB
Zero [B, S, V] log_softmax alloc
01 / The Memory Bottleneck in GRPO Rollouts
In Group Relative Policy Optimization (GRPO), every prompt generates a group of G completions and scores each token's log-probability against a frozen reference policy. With modern vocabularies like Qwen2.5-1.5B (V = 151,936), calling eager PyTorch logits.log_softmax(dim=-1) followed by torch.gather forces PyTorch to allocate three full [B, S, V] tensors in HBM across forward and backward: log_probs (saved for backward), d_log_probs, and d_logits.
At B=4, S=1024, V=151,936 in fp32, a single [B, S, V] tensor consumes 2.37 GB—so eager PyTorch burns 7.12 GB of extra VRAM just in the log-probability loss step, triggering CUDA OOM on 15 GB T4 GPUs during rollout training.
02 / Online Softmax Tiling + Activation Recomputation
Each Triton program instance handles one token row (grid = (B · S,)) and streams across the vocabulary in BLOCK_SIZE = 1024 chunks, maintaining a numerically stable running max and exponential sum. In the backward pass, instead of loading a gigabyte-scale log_probs tensor from HBM, the kernel reloads logits per tile and recomputes softmax probabilities on-chip in registers/SRAM.
03 / Interactive A100 Benchmarks
NVIDIA A100-SXM4-40GB Benchmarks
PyTorch 2.14.1+cu130 · Triton 3.8.0 · fp32 · 20 CUDA-event runs post-warmup
log_probs [B, S, V]; ggrpo allocates 0 MB of [B, S, V] activations (storing only [B·S] lse_max & lse_sum).04 / Numerical & Autograd Verification
Both forward and backward kernels are wrapped in a custom FusedGetPerTokenLogps(torch.autograd.Function) with a CPU fallback path and verified via two layers of tests:
- Finite-difference gradient check: Passes
torch.autograd.gradcheckinfloat64(eps=1e-6, atol=1e-4) to validate the analytical backward kernel. - Eager parity on A100: Forward log-probabilities and backward
d_logitsmatch PyTorch eager withinatol=1e-5, rtol=1e-5.