Skip to content

Commit 6282d0d

Browse files
xiaoyao0115claude
andcommitted
Require slot branches to share arenas and document async offload copies
Branches with equal (io_slot, chunk, layer) are documented to share output and gradient storage, but output targets are carved from each branch's saved arena and returned gradients from its grad arena. make_graphed_callables now rejects branches of one slot that name different saved or grad arenas instead of silently giving them separate storage. Also document the d2h_stream and h2d_stream arguments of _graph_memory_offload_context and the snapshot copies that asynchronous offload keeps in the graph pool, and add docstrings to _CopyOverlappingOutput for pylint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Tailai Ma <tailaim@nvidia.com>
1 parent 321aa14 commit 6282d0d

2 files changed

Lines changed: 46 additions & 13 deletions

File tree

‎tests/pytorch/test_cuda_graphs.py‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2824,7 +2824,7 @@ def forward(self, inp):
28242824
reset_graphs(graphed)
28252825

28262826

2827-
@pytest.mark.parametrize("conflict", ("saved", "output"))
2827+
@pytest.mark.parametrize("conflict", ("cross_slot", "same_slot_branch"))
28282828
def test_slot_memory_debug_rejects_live_branch_reuse(conflict, monkeypatch) -> None:
28292829
"""An invalid branch forward must fail before corrupting the first branch's backward."""
28302830
monkeypatch.setenv("NVTE_CUDA_GRAPH_SLOT_DEBUG", "1")
@@ -2835,10 +2835,9 @@ def forward(self, inp):
28352835

28362836
module = Module().cuda()
28372837
samples = tuple((torch.ones(32, device="cuda", requires_grad=True),) for _ in range(2))
2838-
slots = (
2839-
_slot(0, 0, 0),
2840-
_slot(0 if conflict == "saved" else 1, 1, 1 if conflict == "saved" else 0),
2841-
)
2838+
# Both cases share saved arena 0: across two slots, or between two branches of one slot
2839+
# (which must also share their saved arena, so the saved-arena guard rejects it first).
2840+
slots = (_slot(0, 0, 0), _slot(0, 1, 1 if conflict == "cross_slot" else 0))
28422841
graphed = make_graphed_callables(
28432842
(module,) * 2,
28442843
samples,
@@ -3778,6 +3777,23 @@ def test_slot_memory_rejects_delayed_wgrad_order() -> None:
37783777
)
37793778

37803779

3780+
@pytest.mark.parametrize("arena", ("saved", "grad"))
3781+
def test_slot_memory_rejects_branches_with_different_arenas(arena) -> None:
3782+
"""Branches of one slot share output and gradient storage only through shared arenas."""
3783+
module = torch.nn.Linear(8, 8, device="cuda")
3784+
samples = tuple((torch.randn(4, 8, device="cuda", requires_grad=True),) for _ in range(2))
3785+
branch = _slot(1, 1, 0) if arena == "saved" else _slot(0, 1, 0, user_grad=1)
3786+
with pytest.raises(ValueError, match="same saved and gradient arenas"):
3787+
make_graphed_callables(
3788+
(module,) * 2,
3789+
samples,
3790+
_order=_variant_major_order([1, -1], 2),
3791+
_num_layers_per_chunk=[1, 1],
3792+
_reuse_graph_input_output_buffers=True,
3793+
_graph_memory_slots=(_slot(0, 0, 0), branch),
3794+
)
3795+
3796+
37813797
def test_slot_memory_fused_wgrad_without_main_grad_flag_accumulates_zeros() -> None:
37823798
"""Without grad_added_to_main_grad, every replay adds a zero gradient of its own to .grad."""
37833799
dtype = torch.bfloat16

‎transformer_engine/pytorch/graph.py‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -333,12 +333,14 @@ class _CopyOverlappingOutput(torch.autograd.Function):
333333
"""Preserve an overlapping public view while forwarding its logical gradient."""
334334

335335
@staticmethod
336-
def forward(ctx, source: torch.Tensor, target: torch.Tensor, size_bytes: int):
336+
def forward(_ctx, source: torch.Tensor, target: torch.Tensor, size_bytes: int):
337+
"""Copy the addressed storage span of ``source`` into ``target``."""
337338
_copy_tensor_storage_span(target, source, size_bytes)
338339
return target
339340

340341
@staticmethod
341-
def backward(ctx, grad_output: torch.Tensor):
342+
def backward(_ctx, grad_output: torch.Tensor):
343+
"""Pass the output gradient through to ``source``."""
342344
return grad_output, None, None
343345

344346

@@ -665,6 +667,17 @@ def _make_graphed_callables(
665667
for slot in _graph_memory_slots
666668
):
667669
raise TypeError("Each graph-memory slot must be a tuple of seven integers.")
670+
# Branches of one (io_slot, chunk, layer) share output and gradient storage only if
671+
# they name the same arenas, since those targets are carved from them.
672+
family_arenas = {}
673+
for slot in _graph_memory_slots:
674+
family, arenas = (slot[1], slot[3], slot[4]), (slot[0], slot[6])
675+
expected = family_arenas.setdefault(family, arenas)
676+
if arenas != expected:
677+
raise ValueError(
678+
f"Graph-memory slot branches of (io_slot, chunk, layer) {family} must "
679+
f"name the same saved and gradient arenas, got {expected} and {arenas}."
680+
)
668681
saved_tensor_arena_ids = [slot[0] for slot in _graph_memory_slots]
669682
slot_io_memory_alias_groups = [(slot[1], slot[2]) for slot in _graph_memory_slots]
670683
slot_io_liveness_groups = [(slot[3], slot[4]) for slot in _graph_memory_slots]
@@ -3368,16 +3381,20 @@ def make_graphed_callables(
33683381
``grad_arena`` holds the gradients returned for user inputs. Graph inputs may share an
33693382
arena only if their forward-to-backward lifetimes never overlap in any schedule the
33703383
caller replays. Graph inputs with equal ``(io_slot, chunk, layer)`` are branches of one
3371-
slot: they must expose identical output and gradient layouts, are told apart by
3372-
``branch``, and share output and gradient storage. Graph inputs with equal
3373-
``warmup_group`` share one warmup run.
3384+
slot: they must name the same ``saved_arena`` and ``grad_arena``, expose identical output
3385+
and gradient layouts, are told apart by ``branch``, and share output and gradient storage.
3386+
Graph inputs with equal ``warmup_group`` share one warmup run.
33743387
Only tensors saved for backward (``ctx.save_for_backward`` or saved-tensor hooks) are
33753388
protected between a forward replay and its backward replay. A tensor that backward reads
33763389
from a plain ``ctx`` attribute may be overwritten by another variant's replay, so delayed
33773390
weight-gradient ``_order`` entries are rejected.
3378-
Captured offload scopes may use the private ``_graph_memory_offload_context(checker)``
3379-
instead of nesting another saved-tensor hook. Selected saves use pinned CPU arenas with
3380-
the same saved-arena IDs; forward and backward graphs capture their D2H and H2D copies.
3391+
Captured offload scopes may use the private
3392+
``_graph_memory_offload_context(checker, d2h_stream=..., h2d_stream=...)`` instead of
3393+
nesting another saved-tensor hook. Selected saves use pinned CPU arenas with the same
3394+
saved-arena IDs; forward and backward graphs capture their D2H and H2D copies. When a
3395+
``d2h_stream`` other than the current stream is given, each offloaded save is first
3396+
copied on the current stream, so a later in-place write cannot change what is
3397+
offloaded; these copies stay in the graph pool until the end of that forward graph.
33813398
The caller owns the offload policy. Reconstructed saved views retain their aliases.
33823399
Requires the first positional sample argument of every graph input to be a plain CUDA
33833400
tensor. Plain

0 commit comments

Comments
 (0)