perf(trainer): offload a tensor saved by several blocks once (#4277)
With IndexShare (GLM-5.3: 21 of 78 layers run the indexer), each index
tensor is passed into the next shared layers. Every checkpointed block
saves it again, and `OffloadActivations` made a new pinned CPU copy for
every save. So the same `[S, 2048]` int32 indices were copied to the
host up to 4 times, and copied back to the GPU up to 4 times. The same
happens to the full-sequence RoPE `cos`/`sin`, which every layer saves.
This PR makes a tensor that has already been offloaded reuse its CPU
copy:
- **Forward:** a contiguous activation whose storage, offset, numel and
dtype match an earlier offload reuses that CPU copy, if the GPU storage
is still alive (`StorageWeakRef`). No new D2H copy is made.
- **Backward:** the first unpack of a shared copy moves it to the GPU
once. Later unpacks reuse that GPU tensor. It is released after the last
unpack.
The dedupe key leaves out the version counter on purpose. In compiled
blocks, the indexer's saved output (version 128, from the chunked
in-place writes) and the view passed to the next layer (version 0) share
storage but report different versions. A saved tensor that is mutated
between two saves would already fail autograd's saved-tensor version
check without offloading.
## Measurements
1x8 H200. GLM-5.3 with all 78 layers (21 indexer + 57 shared layers, the
real IndexShare pattern) and EP8 + CP8. Random init, SFT on fixed-length
fake data, full AC + offload, compile on, bf16 params/grads, one
micro-batch per step. Routed experts were cut from 256 to 32 so the
model fits on one node. Top-8 routing, so per-token compute and
activation shapes are unchanged. Both arms: main 87ddbcf, and main with
this PR merged.
| seq (tokens/rank) | | node host peak | pinned/rank |
offloaded/micro-batch/rank | D2H+H2D time | step (median 2-6) | GPU peak
alloc |
|---|---|---|---|---|---|---|---|
| 64K (8K) | main | 196.1 GiB | 18.1 GiB | 15.4 GiB (317 copies) | 1.21
s | 8.63 s | 58.8 GiB |
| | #4277 | 160.2 GiB | 13.3 GiB | 10.6 GiB (106 copies) | 0.84 s | 8.25
s | 58.8 GiB |
| 128K (16K) | main | 331.9 GiB | 34.2 GiB | 29.0 GiB (317 copies) |
2.25 s | 17.20 s | 65.4 GiB |
| | #4277 | 251.9 GiB | 24.7 GiB | 19.4 GiB (106 copies) | 1.56 s |
16.40 s | 65.4 GiB |
| 512K (64K) | main | 1182.0 GiB | 138.8 GiB | 110.5 GiB (317 copies) |
9.55 s | 79.71 s | 105.6 GiB |
| | #4277 | 806.6 GiB | 92.7 GiB | 72.4 GiB (106 copies) | 5.50 s |
75.33 s | 105.6 GiB |
| 1M (128K) | both | host OOM | | | | | |
- Node host peak is MemTotal-MemAvailable over the run. Pinned is
`torch.cuda.host_memory_stats()` peak, which is about 1.25x the
offloaded bytes because the pinned allocator rounds up. Copy time comes
from a CUDA profile of one step on rank 0.
- The offloaded index tensors go from 78 to 21 copies, as expected: at
512K, 39.0 -> 10.5 GiB per rank. The rest of the saving is repeated
full-sequence saves such as RoPE `cos`/`sin`.
- The copies run on the compute stream (`use_streams = False`), so all
copy time is exposed (>99% not overlapped). The step time saving matches
the removed copy time: -4% at 64K, -5% at 128K, -5.5% at 512K.
- GPU peak is unchanged.
- At 1M (128K/rank), the PR arm still filled the node's 1.57 TiB of host
RAM and OOMed. Scaling the 512K numbers gives about 2.2 TB for main and
1.5 TB for this PR. Neither fits on a 1.6 TB node.
- Loss/grad-norm check, 128K with a nonzero init, 7 steps: step 1
matches exactly (loss 14.0931, grad norm 648). Later steps differ
between arms by no more than two runs of main differ from each other
(e.g. step 3: main 11.672 / 11.636, PR 11.651 / 11.635).
Overlap: #4238 (side-stream offload) and #3926 both rewrite
`act_offloading.py`. This change is small enough to port onto either.
Validation: `tests/unit/utils/test_act_offloading.py` (gpu) passes. The
new test checks that a tensor saved twice, once through a view, gets one
CPU copy, that the shared state is drained after backward, and that the
gradients are exact. `tests/unit/utils` and `tests/unit/test_configs.py
-m "not gpu"` (286 passed) and ruff also pass.
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes autograd saved-tensor pack/unpack behavior on the training hot
path when activation offloading is enabled; correctness depends on
storage-based deduping without the version counter, though autograd
would already catch in-place mutations between saves.
>
> **Overview**
> **Activation offloading now reuses one CPU copy when autograd saves
the same underlying storage more than once** (e.g. index tensors and
full-sequence RoPE `cos`/`sin` passed through many checkpointed layers).
>
> On **forward**, contiguous activations that match an existing offload
by storage pointer, offset, numel, and dtype skip a new D2H copy if the
GPU storage is still alive (`StorageWeakRef`). On **backward**, the
first unpack performs a single H2D transfer; later unpacks of that
shared CPU buffer reuse the same GPU tensor until the refcount drops to
zero. The dedupe map is cleared when backward starts.
>
> A GPU unit test asserts that a tensor saved twice (including via a
view) produces one offloaded copy, `shared_copies` is empty after
backward, and gradients stay correct.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e1cbee6285ea7fc9e4947f235e4eb373ec7235d2. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
This commit is contained in:
@@ -6,6 +6,7 @@ import psutil
|
||||
import torch
|
||||
from torch.autograd.graph import saved_tensors_hooks
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.multiprocessing.reductions import StorageWeakRef
|
||||
|
||||
from prime_rl.configs.trainer import ActivationOffloadingConfig
|
||||
|
||||
@@ -72,6 +73,8 @@ class OffloadActivations(saved_tensors_hooks):
|
||||
self.min_tensor_size_bytes = min_offload_size # we don't want to bother with small tensors
|
||||
self.param_slots = [(module, name) for module in model.modules() for name in module._parameters]
|
||||
self.tracker = {} # tensor_id => (new_tensor, if_modified) ---> track what saved/offloaded tensors are where
|
||||
self.cpu_copies = {}
|
||||
self.shared_copies = {}
|
||||
self.tensor_id: int = 0
|
||||
self.is_first_forward_call = True
|
||||
self.is_first_backward_call = True
|
||||
@@ -168,6 +171,20 @@ class OffloadActivations(saved_tensors_hooks):
|
||||
# Sync in, offload, and add an event to sync back later
|
||||
self.s1.wait_stream(self.s0)
|
||||
|
||||
key = (
|
||||
activation.untyped_storage()._cdata,
|
||||
activation.storage_offset(),
|
||||
activation.numel(),
|
||||
activation.dtype,
|
||||
)
|
||||
copy = self.cpu_copies.get(key) if activation.is_contiguous() else None
|
||||
if copy is not None and not copy[0].expired():
|
||||
cpu_tensor = copy[1]
|
||||
self.tracker[tensor_id] = (cpu_tensor.view(activation.shape), True)
|
||||
shared = self.shared_copies.setdefault(cpu_tensor.data_ptr(), [1, None])
|
||||
shared[0] += 1
|
||||
return tensor_id
|
||||
|
||||
stream = self.s1 if self.use_streams else self.s0
|
||||
with stream:
|
||||
try:
|
||||
@@ -179,6 +196,8 @@ class OffloadActivations(saved_tensors_hooks):
|
||||
cpu_tensor,
|
||||
True,
|
||||
) # True = (in future) modified
|
||||
if activation.is_contiguous():
|
||||
self.cpu_copies[key] = (StorageWeakRef(activation.untyped_storage()), cpu_tensor)
|
||||
|
||||
if self.use_streams:
|
||||
event = self.s1.record_event()
|
||||
@@ -204,12 +223,22 @@ class OffloadActivations(saved_tensors_hooks):
|
||||
|
||||
self.is_first_backward_call = False
|
||||
self.is_first_forward_call = True
|
||||
self.cpu_copies.clear()
|
||||
|
||||
assert unpack_tensor_id in self.tracker, f"untracked tensor with id {unpack_tensor_id}"
|
||||
|
||||
maybe_gpu_tensor, modified = self.tracker[unpack_tensor_id]
|
||||
if modified:
|
||||
gpu_tensor = maybe_gpu_tensor.to(torch.accelerator.current_accelerator(), non_blocking=True)
|
||||
shared = self.shared_copies.get(maybe_gpu_tensor.data_ptr())
|
||||
if shared is not None and shared[1] is not None:
|
||||
gpu_tensor = shared[1].view(maybe_gpu_tensor.shape)
|
||||
else:
|
||||
gpu_tensor = maybe_gpu_tensor.to(torch.accelerator.current_accelerator(), non_blocking=True)
|
||||
if shared is not None:
|
||||
shared[0] -= 1
|
||||
shared[1] = gpu_tensor
|
||||
if shared[0] == 0:
|
||||
del self.shared_copies[maybe_gpu_tensor.data_ptr()]
|
||||
maybe_gpu_tensor = gpu_tensor
|
||||
|
||||
# clear tensor from tracking
|
||||
|
||||
@@ -16,3 +16,17 @@ def test_parameter_views_stay_on_gpu():
|
||||
saved = [tensor for tensor, offloaded in offloader.tracker.values() if not offloaded]
|
||||
assert any(tensor.untyped_storage().data_ptr() == weight_storage for tensor in saved)
|
||||
loss.backward()
|
||||
|
||||
|
||||
def test_tensor_saved_twice_is_offloaded_once():
|
||||
model = nn.Linear(256, 256).cuda()
|
||||
x = torch.randn(4096, 256, device="cuda", requires_grad=True)
|
||||
shared = torch.randn(4096, 256, device="cuda")
|
||||
offloader = OffloadActivations(model)
|
||||
with offloader:
|
||||
loss = (x * shared).sum() + (x.sin() * shared.view(-1)[: 4096 * 256].view(4096, 256)).sum()
|
||||
copies = {tensor.data_ptr() for tensor, offloaded in offloader.tracker.values() if offloaded}
|
||||
assert len(copies) == 2
|
||||
loss.backward()
|
||||
assert not offloader.shared_copies
|
||||
assert torch.equal(x.grad, shared + x.detach().cos() * shared)
|
||||
|
||||
Reference in New Issue
Block a user