diff --git a/ignition/preparation/capture.py b/ignition/preparation/capture.py index 20f80b5c2..e8ed91deb 100644 --- a/ignition/preparation/capture.py +++ b/ignition/preparation/capture.py @@ -18,6 +18,59 @@ from .runtime_core import capture_graph, instantiate_graph, record_export_graph +_warmup_streams = {} +_warmup_pools = {} + + +def _warmup_stream(device): + """Return the per-device stream that eager warmups run on. + + PyTorch caches one cuBLAS/cuBLASLt workspace per (handle, stream). + Warmups allocate inside transient storage, so their workspaces must + stay off the capture stream: the first capture then allocates the + stream's workspace inside the recording pool, and the cache retains + it for every graph the stream captures afterward. + """ + # The stream must be created outside PyTorch's round-robin pool: a + # caller's later torch.cuda.Stream can alias a pool stream, and + # workspaces are cached per CUDA stream, so an aliased capture stream + # would reuse a warmup workspace's transient address. The stream and + # its CUDA handle live for the life of the process. + with torch.cuda.device(device): + index = torch.cuda.current_device() + stream = _warmup_streams.get(index) + if stream is None: + from cuda.bindings import driver as cuda + + status, handle = cuda.cuStreamCreate(cuda.CUstream_flags.CU_STREAM_NON_BLOCKING) + if status != cuda.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"cannot create warmup stream: {status}") + stream = _warmup_streams[index] = torch.cuda.ExternalStream(int(handle), device=device) + return stream + + +def _seed_warmup_workspaces(stream, device): + """Seed the calling thread's warmup-stream workspace in a dedicated pool. + + Workspaces are cached per thread's cuBLAS handle, so seeding runs on + each capture call under the ambient BLAS backend, the backend the + warmups use. A workspace created inside transient storage keeps its + address in the cache after the transient backing is released, and a + later call could reuse it; a dedicated pool keeps the seed's backing + mapped for the life of the cache entry, outside transient storage, + any caller-owned pool, and the exported graph pool. + """ + with torch.cuda.device(device): + index = torch.cuda.current_device() + pool = _warmup_pools.get(index) + if pool is None: + pool = _warmup_pools[index] = torch.cuda.MemPool() + with torch.cuda.device(index), torch.cuda.stream(stream), torch.cuda.use_mem_pool(pool): + operand = torch.empty((512, 512), dtype=torch.bfloat16, device=device) + torch.mm(operand, operand, out=torch.empty_like(operand)) + stream.synchronize() + + def _capture_order(names, compiled, coordinator): sizes = {name: forward.capture_allocation_sizes for name, forward in compiled.items()} ranks = [(names, sizes)] @@ -49,6 +102,10 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, serving replays variants serially and may choose them in any order. All eager warmups precede capture so their transient workspaces do not coexist with retained graph intermediates. + Graphs captured on one stream share that stream's cached workspace; + resetting any of them frees the workspace the others still reference. + Callers must reset all of a capture stream's graphs together or keep + separately reset groups on separate streams. ``retain_graphs`` keeps templates and executables for export when ``warmup_storage`` supplies external CUDA pool owners. ``before_run`` restores caller-owned trial inputs outside compiled warmup @@ -70,6 +127,8 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, raise ValueError("grouped compilation requires a distinct name and selected compiled forwards") graphs, compiled = {}, {} warmup = nullcontext if warmup_storage is None else warmup_storage.transient + warm = _warmup_stream(device) + _seed_warmup_workspaces(warm, device) if compile_decoder: cache = ForwardCache(namespace=session.namespace.to_dict(), device=device, root=cache_root, headroom_bytes=getattr(session, "headroom_bytes", 0), @@ -84,10 +143,11 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, if any(type(forward) is not type(forwards[first]) or signatures[name] != signatures[first] for name, forward in forwards.items()): raise ValueError("grouped forwards require one type and graph signature") - stream.wait_stream(torch.cuda.current_stream(device)) + warm.wait_stream(torch.cuda.current_stream(device)) + warm.wait_stream(stream) retention = nullcontext() if warmup_storage is None else warmup_storage.retain_transient_backing() with retention, warmup_wait(collective, coordinator): - with torch.cuda.stream(stream): + with torch.cuda.stream(warm): if compile_group is None: compiled = cache.prepare_many(forwards, signatures, progress=progress, coordinator=coordinator, materialize=materialize, warmup=warmup, @@ -97,7 +157,7 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, template = cache.prepare_many(representative, {compile_group: signatures[first]}, progress=progress, coordinator=coordinator, materialize=materialize, warmup=warmup, before_run=None if before_run is None else lambda _: before_run(first)) - stream.synchronize() + warm.synchronize() if compile_group is not None: compiled = cache.bind_group(template[compile_group], forwards, signature=signatures[first], coordinator=coordinator) @@ -122,8 +182,9 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, function = functions[name] if coordinator is not None: coordinator.barrier(f"capture warmup {name}", coordinator.ranks) - stream.wait_stream(torch.cuda.current_stream(device)) - with warmup(), torch.cuda.stream(stream): + warm.wait_stream(torch.cuda.current_stream(device)) + warm.wait_stream(stream) + with warmup(), torch.cuda.stream(warm): if before_run is not None: before_run(name) if name in compiled: @@ -132,8 +193,9 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, function() else: function() - stream.synchronize() + warm.synchronize() stage.update(advance=1) + stream.wait_stream(warm) ordered_names = _capture_order(names, compiled, coordinator) with phase(progress, label, total=len(names)) as stage: for name in ordered_names: @@ -158,9 +220,10 @@ def memory_detail(): if progress is not None: progress(f"capturing {name}: {memory_detail()}") if before_run is not None: - with torch.cuda.stream(stream): + warm.wait_stream(stream) + with torch.cuda.stream(warm): before_run(name) - stream.synchronize() + stream.wait_stream(warm) with capture_consumers(session, graph), communication, session.capture(), torch.cuda.graph(graph, pool=pool, stream=stream): function() if exporting: diff --git a/tests/preparation/test_capture_cublas_workspace_cuda.py b/tests/preparation/test_capture_cublas_workspace_cuda.py new file mode 100644 index 000000000..b92a602e9 --- /dev/null +++ b/tests/preparation/test_capture_cublas_workspace_cuda.py @@ -0,0 +1,120 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Captured graphs bind their cuBLASLt workspace from recorded storage. + +Warmups and pre-capture callbacks run on a dedicated stream because +PyTorch caches one cuBLASLt workspace per (handle, stream). Keeping +their workspaces off the capture stream leaves the capture stream's +cache empty, so the first capture allocates its workspace inside the +recording pool and the cache retains it for every later call into the +pool. The test uses plain MemPools for transient storage and the +shared graph pool handle so it needs no package-export resources. +""" + +import os +from contextlib import nullcontext +from types import SimpleNamespace + +import pytest +import torch + +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", + reason="requires an explicitly assigned CUDA device") + + +def _active_pool_blocks(pool): + return {block["address"]: block + for segment in torch.cuda.memory_snapshot(pool, include_traces=False) + for block in segment["blocks"] + if block["state"] == "active_allocated"} + + +def test_first_capture_binds_workspace_from_the_recording_pool(): + from ignition.preparation import capture as _capture + from ignition.preparation.capture import capture_forwards + from ignition.preparation.execution import GraphSignature + + torch.cuda.set_device(0) + previous_blas = torch.backends.cuda.preferred_blas_library() + torch.backends.cuda.preferred_blas_library("cublaslt") + try: + source = torch.randn((512, 512), device="cuda").bfloat16() + weight = torch.randn((512, 512), device="cuda").bfloat16() + expected = torch.mm(source, weight) + output = torch.empty_like(source) + + def forward(): + torch.mm(source, weight, out=output) + + pool = torch.cuda.graph_pool_handle() + session = SimpleNamespace(capture=nullcontext) + + transients = [] + + def capture(stream, before_run=None): + # Each call owns a separate transient pool, matching the + # per-preparation lifetime of production transient storage. + transient = torch.cuda.MemPool() + transients.append(transient) + storage = SimpleNamespace( + transient=lambda: torch.cuda.use_mem_pool(transient)) + return capture_forwards( + {"decode": forward}, {"decode": GraphSignature("decode", 1, 1)}, + session=session, device=0, stream=stream, pool=pool, + warmup_storage=storage, compile_decoder=False, before_run=before_run) + + graphs = [] + stream = torch.cuda.Stream() + first_call, _ = capture(stream) + graphs.append(first_call) + try: + # The forward allocates nothing itself, so an active block in the + # shared graph pool can only be the captured cuBLASLt workspace. + # If warmups ran on the capture stream, the graph would keep the + # transient warmup workspace's address and the pool would stay + # empty. + first = _active_pool_blocks(pool) + assert first, ("no cuBLASLt workspace was recorded in " + "the captured graph pool") + + # Later calls into the same pool must not free the workspace + # earlier graphs still reference, whether they capture on the + # same or a different stream, and a before_run callback that + # invokes BLAS must not contaminate the capture stream. + same_stream, _ = capture(stream) + graphs.append(same_stream) + other_stream, _ = capture(torch.cuda.Stream(), + before_run=lambda _: torch.mm(source, weight, out=output)) + graphs.append(other_stream) + # Warmup workspaces are seeded in a dedicated pool owned by + # the capture module, so no transient pool may hold a live + # workspace allocation, and the seed must be verifiably + # resident there rather than in any caller's storage. + for transient in transients: + assert not _active_pool_blocks(transient.id), ( + "a warmup workspace remained in transient storage") + seeded = _active_pool_blocks(_capture._warmup_pools[0].id) + assert seeded, "no seeded workspace was recorded in the dedicated warmup pool" + # The warmup stream must be outside torch.cuda.Stream's + # round-robin pool: a later pool stream can alias an earlier + # one, and a capture stream aliasing the warmup stream would + # reintroduce the defect. + warm = _capture._warmup_stream(0) + pool_streams = [torch.cuda.Stream() for _ in range(40)] + assert warm.cuda_stream not in { + stream.cuda_stream for stream in pool_streams}, ( + "the warmup stream aliases a torch.cuda.Stream pool entry") + remaining = _active_pool_blocks(pool) + assert set(first) <= set(remaining), ( + "a later capture freed the workspace of an earlier graph") + output.zero_() + first_call["decode"].replay() + torch.cuda.synchronize() + torch.testing.assert_close(output, expected) + finally: + for call in graphs: + for graph in call.values(): + graph.reset() + finally: + torch.backends.cuda.preferred_blas_library(previous_blas) diff --git a/tests/preparation/test_capture_graph_metadata.py b/tests/preparation/test_capture_graph_metadata.py index d81b20004..fadc67833 100644 --- a/tests/preparation/test_capture_graph_metadata.py +++ b/tests/preparation/test_capture_graph_metadata.py @@ -177,6 +177,8 @@ def graph_scope(graph, **kwargs): mem_get_info=lambda device: (1024, 2048), memory_allocated=lambda device: 0, memory_reserved=lambda device: 0).items(): monkeypatch.setattr(torch.cuda, name, value) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) functions = {name: lambda name=name: calls.append((name, state["capturing"])) for name in ("first", "second")} graphs, compiled = capture.capture_forwards(functions, @@ -335,6 +337,8 @@ def graph_scope(graph, **kwargs): for name, value in dict(current_stream=lambda device: stream, stream=lambda stream: nullcontext(), synchronize=lambda device: None, graph=graph_scope).items(): monkeypatch.setattr(torch.cuda, name, value) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) graphs, _ = capture.capture_forwards({"decode": forward}, {"decode": SimpleNamespace(kind="decode")}, session=session, device="cpu", stream=stream, pool=storage.graph_pool.id, compile_decoder=False, retain_graphs=True, warmup_storage=storage) diff --git a/tests/preparation/test_capture_progress.py b/tests/preparation/test_capture_progress.py index 3165e0205..513fe364f 100644 --- a/tests/preparation/test_capture_progress.py +++ b/tests/preparation/test_capture_progress.py @@ -26,6 +26,8 @@ def capture_options(monkeypatch): "memory_reserved": lambda device: 0, }.items(): monkeypatch.setattr(capture.torch.cuda, name, value) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) monkeypatch.setattr(capture.torch.distributed, "is_initialized", lambda: False) session = SimpleNamespace(namespace=SimpleNamespace(to_dict=lambda: {}), capture=nullcontext) return dict(session=session, device="cpu", stream=stream, pool=None) diff --git a/tests/preparation/test_capture_rank_readiness.py b/tests/preparation/test_capture_rank_readiness.py index 2d41ba3f5..fe09f5834 100644 --- a/tests/preparation/test_capture_rank_readiness.py +++ b/tests/preparation/test_capture_rank_readiness.py @@ -52,6 +52,8 @@ def second(): stream = SimpleNamespace(wait_stream=lambda other: None, synchronize=lambda: None) capture.torch.cuda.current_stream = lambda device: stream + capture._warmup_stream = lambda device: stream + capture._seed_warmup_workspaces = lambda stream, device: None capture.torch.cuda.stream = lambda stream: nullcontext() capture.torch.cuda.synchronize = lambda device: None capture.torch.cuda.CUDAGraph = Graph diff --git a/tests/preparation/test_capture_roce_wait.py b/tests/preparation/test_capture_roce_wait.py index ebabab651..905fc3764 100644 --- a/tests/preparation/test_capture_roce_wait.py +++ b/tests/preparation/test_capture_roce_wait.py @@ -36,6 +36,9 @@ def prepare_many(self, functions, signatures, **kwargs): coordinator = SimpleNamespace(spans_hosts=True, ranks=(0, 1), barrier=lambda name, ranks: None) monkeypatch.setattr(capture, "ForwardCache", Cache) monkeypatch.setattr(capture.torch.cuda, "current_stream", lambda device: stream) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + monkeypatch.setattr(capture.torch.cuda, "stream", lambda stream: nullcontext()) monkeypatch.setattr(capture.torch.cuda, "synchronize", lambda device: None) monkeypatch.setattr(capture.torch.cuda, "CUDAGraph", lambda: "graph") diff --git a/tests/preparation/test_capture_selection.py b/tests/preparation/test_capture_selection.py index a613f784b..8ddc6aa6d 100644 --- a/tests/preparation/test_capture_selection.py +++ b/tests/preparation/test_capture_selection.py @@ -31,6 +31,9 @@ def prepare_many(self, functions, signatures, **kwargs): monkeypatch.setattr(capture, "ForwardCache", Cache) monkeypatch.setattr(capture.torch.cuda, "current_stream", lambda device: stream) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + monkeypatch.setattr(capture.torch.cuda, "stream", lambda stream: nullcontext()) monkeypatch.setattr(capture.torch.cuda, "synchronize", lambda device: None) monkeypatch.setattr(capture.torch.cuda, "CUDAGraph", lambda: "graph") @@ -67,6 +70,9 @@ def forward(): calls.append(("run", state["value"], state["capturing"])) monkeypatch.setattr(capture.torch.cuda, "current_stream", lambda device: stream) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + monkeypatch.setattr(capture.torch.cuda, "stream", lambda stream: nullcontext()) monkeypatch.setattr(capture.torch.cuda, "synchronize", lambda device: None) monkeypatch.setattr(capture.torch.cuda, "CUDAGraph", lambda: "graph") @@ -116,6 +122,9 @@ def bind_group(self, template, forwards, *, signature, coordinator): first, second = (lambda: None), (lambda: None) monkeypatch.setattr(capture, "ForwardCache", Cache) monkeypatch.setattr(capture.torch.cuda, "current_stream", lambda device: stream) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + monkeypatch.setattr(capture.torch.cuda, "stream", lambda stream: nullcontext()) monkeypatch.setattr(capture.torch.cuda, "synchronize", lambda device: None) monkeypatch.setattr(capture.torch.cuda, "CUDAGraph", lambda: "graph") diff --git a/tests/preparation/test_capture_stream_isolation.py b/tests/preparation/test_capture_stream_isolation.py new file mode 100644 index 000000000..78349aba2 --- /dev/null +++ b/tests/preparation/test_capture_stream_isolation.py @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Warmup execution must run on the dedicated warmup stream, never on the +capture stream. + +cuBLAS workspaces are cached per (handle, stream); a workspace-allocating +call on the capture stream before capture can seed that stream's cache +with transient-backed memory the first graph then records. These tests +distinguish the two streams and assert every stream context that wraps +warmup work — compiled preparation, serving warmups, and before_run — +enters the warmup stream, while graph capture keeps the capture stream. +""" + +from contextlib import contextmanager, nullcontext +from types import SimpleNamespace + +from ignition.preparation import capture + + +def _capture_streams(monkeypatch): + """Install stream mocks that record which stream each context used. + + Returns (capture_stream, warm_stream, entered, captured_on): + entered lists the stream passed to each torch.cuda.stream() context, + captured_on the stream= argument of each torch.cuda.graph() call. + """ + stream = SimpleNamespace(wait_stream=lambda value: None, synchronize=lambda: None) + warm = SimpleNamespace(wait_stream=lambda value: None, synchronize=lambda: None) + entered, captured_on = [], [] + + @contextmanager + def record_stream(value): + entered.append(value) + yield + + @contextmanager + def record_graph(graph, *, stream, **kwargs): + captured_on.append(stream) + yield + + monkeypatch.setattr(capture, "_warmup_stream", lambda device: warm) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + monkeypatch.setattr(capture.torch.cuda, "current_stream", lambda device: stream) + monkeypatch.setattr(capture.torch.cuda, "stream", record_stream) + monkeypatch.setattr(capture.torch.cuda, "synchronize", lambda device: None) + monkeypatch.setattr(capture.torch.cuda, "CUDAGraph", lambda: "graph") + monkeypatch.setattr(capture.torch.cuda, "graph", record_graph) + monkeypatch.setattr(capture.torch.distributed, "is_initialized", lambda: False) + return stream, warm, entered, captured_on + + +class _Forward: + cache_hit = False + capture_allocation_sizes = () + + def prepare_capture(self): + return 0 + + def retire_after_capture(self): + pass + + def __call__(self): + pass + + +def _session(): + return SimpleNamespace( + namespace=SimpleNamespace(to_dict=lambda: {}), capture=nullcontext) + + +def test_compiled_preparation_and_before_run_enter_the_warmup_stream(monkeypatch): + stream, warm, entered, captured_on = _capture_streams(monkeypatch) + + class Cache: + def __init__(self, **kwargs): + pass + + def prepare_many(self, functions, signatures, **kwargs): + # The caller wraps this in a stream context; the assertion + # below checks which one it was. + return {name: _Forward() for name in functions} + + monkeypatch.setattr(capture, "ForwardCache", Cache) + forward = _Forward() + graphs, compiled = capture.capture_forwards( + {"decode": forward}, {"decode": SimpleNamespace(kind="decode")}, + session=_session(), device="cuda:0", stream=stream, pool=None, + before_run=lambda name: None) + + assert entered and all(value is warm for value in entered), ( + "warmup work entered the capture stream's context") + assert captured_on and all(value is stream for value in captured_on), ( + "graph capture did not use the capture stream") + + +def test_serving_warmup_enters_the_warmup_stream_without_compilation(monkeypatch): + stream, warm, entered, captured_on = _capture_streams(monkeypatch) + forward = _Forward() + capture.capture_forwards( + {"decode": forward}, {"decode": SimpleNamespace(kind="decode")}, + session=_session(), device="cuda:0", stream=stream, pool=None, + compile_decoder=False) + + assert entered and all(value is warm for value in entered), ( + "the serving warmup did not run entirely on the warmup stream") + assert captured_on and all(value is stream for value in captured_on) diff --git a/tests/preparation/test_transient_retention.py b/tests/preparation/test_transient_retention.py index 7d5596467..27db26a46 100644 --- a/tests/preparation/test_transient_retention.py +++ b/tests/preparation/test_transient_retention.py @@ -127,6 +127,9 @@ def prepare_many(self, functions, signatures, **kwargs): synchronize=lambda: events.append('sync')) monkeypatch.setattr(capture, 'ForwardCache', Cache) monkeypatch.setattr(capture.torch.cuda, 'current_stream', lambda device: stream) + monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) + monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + monkeypatch.setattr(capture.torch.cuda, 'stream', lambda stream: nullcontext()) monkeypatch.setattr(capture.torch.cuda, 'synchronize', lambda device: None) monkeypatch.setattr(capture.torch.cuda, 'CUDAGraph', lambda: 'graph')