Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 71 additions & 8 deletions ignition/preparation/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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
Expand All @@ -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),
Expand All @@ -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,
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand Down
120 changes: 120 additions & 0 deletions tests/preparation/test_capture_cublas_workspace_cuda.py
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 4 additions & 0 deletions tests/preparation/test_capture_graph_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions tests/preparation/test_capture_progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions tests/preparation/test_capture_rank_readiness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions tests/preparation/test_capture_roce_wait.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
9 changes: 9 additions & 0 deletions tests/preparation/test_capture_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
Loading