Skip to content

Commit d2b1f3a

Browse files
xiaoyao0115claude
andcommitted
Free slot-memory arenas once every graphed callable is reset
Every callable returned with _graph_memory_slots holds the shared allocator pool and the saved, offload and user-gradient arenas as attributes, and reset() left them in place, so a caller that kept reset callables also kept their GPU and pinned host memory. reset() now drops the callable's own references, the arenas before the pool because the pool's destructor returns only blocks that are already free; peers keep their references, so the memory is freed once every callable that shares it has been reset. The staging matcher referred to itself, a cycle that kept staging buffers allocated in the pool alive until gc ran; it is now deleted after use. The new test keeps the handles, resets one callable and checks that its peer still replays correctly, then resets the other with gc disabled and checks that the arena storages are gone and that the pool holds no device segment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Tailai Ma <tailaim@nvidia.com>
1 parent c3d3d0d commit d2b1f3a

2 files changed

Lines changed: 95 additions & 6 deletions

File tree

‎tests/pytorch/test_cuda_graphs.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,67 @@ def forward(self, inp):
172172
reset_graphs(graphs)
173173

174174

175+
def test_slot_memory_reset_releases_arenas_of_retained_callables():
176+
"""Resetting every callable frees the slot pool, without gc, while the handles are kept."""
177+
178+
class Module(torch.nn.Module):
179+
def forward(self, inp):
180+
with te_graph._graph_memory_offload_context(lambda tensor: tensor.is_cuda):
181+
return inp.sin().square()
182+
183+
arena_names = (
184+
"_te_cuda_graph_saved_arenas",
185+
"_te_cuda_graph_offload_arenas",
186+
"_te_cuda_graph_user_grad_arenas",
187+
)
188+
# Both graphs share one sample input, so the second one stages its input in the pool.
189+
shared = torch.ones(4096, device="cuda", requires_grad=True)
190+
gc_was_enabled = gc.isenabled()
191+
gc.disable()
192+
try:
193+
graphed = make_graphed_callables(
194+
(Module().cuda(),),
195+
((shared,), (shared,)),
196+
num_warmup_iters=2,
197+
_order=[1, 1, -1, -1],
198+
_num_layers_per_chunk=[1],
199+
_reuse_graph_input_output_buffers=True,
200+
_graph_memory_slots=(_slot(0, 0, 0, warmup=0), _slot(1, 1, 1, warmup=0)),
201+
)
202+
pool_id = graphed[0]._te_cuda_graph_allocator_pool.id
203+
assert all(getattr(graphed[0], name) for name in arena_names)
204+
storages = [
205+
weakref.ref(arena.untyped_storage())
206+
for name in arena_names
207+
for arena in getattr(graphed[0], name).values()
208+
]
209+
210+
graphed[0].reset()
211+
assert all(storage() is not None for storage in storages)
212+
213+
# The peer keeps the shared memory and still replays correctly.
214+
inp = torch.randn(4096, device="cuda", requires_grad=True)
215+
output = graphed[1](inp)
216+
output.sum().backward()
217+
torch.testing.assert_close(inp.grad, 2 * inp.detach().sin() * inp.detach().cos())
218+
del inp, output # Replay outputs and gradients alias the arenas.
219+
220+
graphed[1].reset()
221+
assert not any(
222+
hasattr(graph, name) for graph in graphed for name in te_graph._SLOT_MEMORY_ATTRIBUTES
223+
)
224+
assert all(storage() is None for storage in storages)
225+
pool_segments = [
226+
segment
227+
for segment in torch.cuda.memory_snapshot()
228+
if tuple(segment["segment_pool_id"]) == tuple(pool_id)
229+
]
230+
assert not pool_segments
231+
finally:
232+
if gc_was_enabled:
233+
gc.enable()
234+
235+
175236
def nvfp4_vanilla():
176237
nvfp4_recipe = recipe.NVFP4BlockScaling()
177238
nvfp4_recipe.fp4_quant_fwd_inp = recipe.QParams()

‎transformer_engine/pytorch/graph.py‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,17 @@ def release(self, graph_idx):
106106
del self._owners[key]
107107

108108

109+
# Attributes through which each graphed callable exposes the slot memory it shares with its
110+
# peers. The pool comes last so that reset drops it after the arenas: the pool's destructor
111+
# returns only blocks that are already free to the device.
112+
_SLOT_MEMORY_ATTRIBUTES = (
113+
"_te_cuda_graph_saved_arenas",
114+
"_te_cuda_graph_offload_arenas",
115+
"_te_cuda_graph_user_grad_arenas",
116+
"_te_cuda_graph_allocator_pool",
117+
)
118+
119+
109120
class _AllocatorSettingsGuard:
110121
"""Restore temporary allocator settings even when graph capture fails."""
111122

@@ -1740,6 +1751,8 @@ def match_staging_group(group_idx, seen_storages):
17401751
),
17411752
):
17421753
match_staging_group(group_idx, set())
1754+
# The recursive matcher refers to itself; delete it so its state is freed without gc.
1755+
del match_staging_group
17431756

17441757
for group_idx, group in enumerate(staging_groups):
17451758
input_target = staging_targets.get(group_idx)
@@ -3089,14 +3102,16 @@ def release_static_state():
30893102
)
30903103
return functionalized, helpers
30913104

3092-
def make_graphed_attribute_functions(graph_idx, helpers):
3105+
def make_graphed_attribute_functions(graph_idx, helpers, owner):
30933106
# Snapshot per-callable state so returned closures do not retain the outer lists.
30943107
fwd_graph = fwd_graphs[graph_idx]
30953108
bwd_graph = bwd_graphs[graph_idx]
30963109
bwd_dw_graph = bwd_dw_graphs[graph_idx]
30973110
need_bwd_dw = need_bwd_dw_graph.get(graph_idx, False)
30983111
te_modules = visited_te_modules.get(graph_idx, set())
30993112
static_wgrads = per_callable_static_wgrads[graph_idx]
3113+
# A weak reference keeps ``owner.reset`` from forming a cycle with ``owner``.
3114+
owner_ref = weakref.ref(owner)
31003115

31013116
# Attach backward_dw as an attribute to the graphed callable.
31023117
def backward_dw():
@@ -3136,6 +3151,12 @@ def reset():
31363151
static_wgrads = ()
31373152
helpers.release_static_state()
31383153

3154+
# Drop this callable's references to the slot memory; peers keep their own.
3155+
current_owner = owner_ref()
3156+
if current_owner is not None:
3157+
for name in _SLOT_MEMORY_ATTRIBUTES:
3158+
vars(current_owner).pop(name, None)
3159+
31393160
return backward_dw, reset
31403161

31413162
# Put together the final graphed callables
@@ -3234,14 +3255,19 @@ def new_fwd(*user_args, **user_kwargs):
32343255
backward_dw_func, reset_func = make_graphed_attribute_functions(
32353256
i,
32363257
helpers,
3258+
ret[-1],
32373259
)
32383260
setattr(ret[-1], "backward_dw", backward_dw_func)
32393261
setattr(ret[-1], "reset", reset_func)
32403262
if slot_allocator_pool is not None:
3241-
setattr(ret[-1], "_te_cuda_graph_allocator_pool", slot_allocator_pool)
3242-
setattr(ret[-1], "_te_cuda_graph_saved_arenas", slot_saved_arenas)
3243-
setattr(ret[-1], "_te_cuda_graph_offload_arenas", slot_offload_arenas)
3244-
setattr(ret[-1], "_te_cuda_graph_user_grad_arenas", slot_user_grad_arenas)
3263+
slot_memory = (
3264+
slot_saved_arenas,
3265+
slot_offload_arenas,
3266+
slot_user_grad_arenas,
3267+
slot_allocator_pool,
3268+
)
3269+
for name, value in zip(_SLOT_MEMORY_ATTRIBUTES, slot_memory):
3270+
setattr(ret[-1], name, value)
32453271

32463272
if just_one_callable:
32473273
return ret[0]
@@ -3374,7 +3400,9 @@ def make_graphed_callables(
33743400
gradients before any such overwrite can occur.
33753401
_graph_memory_slots: sequence of 7-int tuples, default = None
33763402
Private. Lets mutually exclusive graph variants, for example one per context-parallel
3377-
size, share one memory pool. One ``(saved_arena, io_slot, branch, chunk, layer,
3403+
size, share one memory pool. Resetting a returned callable drops its references to the
3404+
pool and arenas, which are freed once every callable has been reset and the outputs and
3405+
gradients returned by replays are gone. One ``(saved_arena, io_slot, branch, chunk, layer,
33783406
warmup_group, grad_arena)`` tuple per graph input, in ``sample_args`` order.
33793407
``saved_arena`` holds the tensors the forward saves for backward and its public outputs;
33803408
``grad_arena`` holds the gradients returned for user inputs. Graph inputs may share an

0 commit comments

Comments
 (0)