diff --git a/docs/preparation-development.md b/docs/preparation-development.md index e877cd20a..0da40a7bd 100644 --- a/docs/preparation-development.md +++ b/docs/preparation-development.md @@ -88,7 +88,10 @@ before the session's capture guard forbids further kernel resolution. When `capture_forwards` receives `warmup_storage`, the preparation's `CoreStorage` (`ignition/preparation/core_storage.py`), eager warmups allocate from its transient pools and release them before capture, so - their workspaces do not coexist with retained graph intermediates. Ranks + their workspaces do not coexist with retained graph intermediates, while + cuBLAS warmup workspaces are seeded into `CoreStorage.warmup_pool()` so they + stay outside transient and graph pools while remaining inside declared core + mappings. Ranks synchronize before each warmup and each capture. Retain compiled kernel owners until native replay has drained. Compiled forwards retain Inductor memory-pool planning, storage reuse, and default peak-memory operation reordering; callers diff --git a/ignition/preparation/capture.py b/ignition/preparation/capture.py index eb6585147..ff9aca6e9 100644 --- a/ignition/preparation/capture.py +++ b/ignition/preparation/capture.py @@ -49,22 +49,26 @@ def _warmup_stream(device): return stream -def _seed_warmup_workspaces(stream, device): +def _seed_warmup_workspaces(stream, device, pool=None): """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. + later call could reuse it. When ``pool`` is omitted, seeding uses a + module-level pool outside transient storage, caller-owned pools, and + the exported graph pool. When an export storage supplies + ``warmup_pool()``, seeding uses that persistent pool instead so the + backing stays mapped outside transient storage, ``storage.pool``, and + ``storage.graph_pool`` while remaining inside declared core mappings. """ 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() + 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)) @@ -112,7 +116,12 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, graphs, compiled = {}, {} warmup = nullcontext if warmup_storage is None else warmup_storage.transient warm = _warmup_stream(device) - _seed_warmup_workspaces(warm, device) + warmup_pool = warmup_storage.warmup_pool() if hasattr(warmup_storage, "warmup_pool") else None + if warmup_pool is not None: + _seed_warmup_workspaces(warm, device, warmup_pool) + else: + # Keep the 2-argument call for non-export callers and existing test stubs. + _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), diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 85d222c8a..43ff890ae 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -71,6 +71,7 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window self._persistent_total_bytes = min(properties.total_memory, self.RESERVATION_BYTES // 4) self._retention_scope = False self._retention_pool = None + self._warmup_pool = None window = (self.DEVICE_BASE, self.RESERVATION_BYTES) self.DEVICE_BASE += rank * self.RESERVATION_BYTES self.cuda = _Cuda() @@ -297,6 +298,17 @@ def scratch_pool(self): self._preparation_pools.add(pool.pool.id) return pool + def warmup_pool(self): + """Own a persistent pool for cuBLAS warmup workspaces inside core mappings.""" + import torch + + pool = getattr(self, "_warmup_pool", None) + if pool is None: + pool = torch.cuda.MemPool(self._allocator.allocator()) + self._warmup_pool = pool + self._preparation_pools.add(pool.id) + return pool + def packed_weights(self): """Own aligned immutable weight storage until graph users have drained.""" from .packed_weights import PackedWeights diff --git a/tests/preparation/test_capture_cublas_workspace_cuda.py b/tests/preparation/test_capture_cublas_workspace_cuda.py index b92a602e9..1be31db4b 100644 --- a/tests/preparation/test_capture_cublas_workspace_cuda.py +++ b/tests/preparation/test_capture_cublas_workspace_cuda.py @@ -118,3 +118,137 @@ def capture(stream, before_run=None): graph.reset() finally: torch.backends.cuda.preferred_blas_library(previous_blas) + + +def test_export_warmup_pool_seeds_workspace_inside_core_storage(tmp_path): + """Run export warmup seeding in an isolated subprocess against real CoreStorage. + + Subprocess isolation avoids both process-singleton CoreStorage arena reuse + and cross-test sharing of capture._warmup_streams[0] / cuBLASLt cache state. + """ + from pathlib import Path + import subprocess + import sys + + subprocess.run( + [ + sys.executable, + "-c", + "from pathlib import Path; import sys; " + "from tests.preparation.test_capture_cublas_workspace_cuda import check_export_warmup_pool; " + "check_export_warmup_pool(Path(sys.argv[1]))", + str(tmp_path), + ], + check=True, + timeout=120, + cwd=Path(__file__).resolve().parents[2], + ) + + +def check_export_warmup_pool(tmp_path): + from ignition.preparation import capture as _capture + from ignition.preparation.capture import capture_forwards + from ignition.preparation.core_storage import CoreStorage + from ignition.preparation.execution import GraphSignature, PreparedExecution + from ignition.preparation.module_images import ModuleImages + from ignition.preparation.runtime_core import Allocation, RuntimeCore + + with ModuleImages() as images: + torch.cuda.set_device(0) + previous_blas = torch.backends.cuda.preferred_blas_library() + torch.backends.cuda.preferred_blas_library("cublaslt") + try: + storage = CoreStorage() + with storage: + source = torch.randn((512, 512), device="cuda", dtype=torch.bfloat16) + weight = torch.randn((512, 512), device="cuda", dtype=torch.bfloat16) + output = torch.empty_like(source) + frame = torch.zeros(1, device="cuda", dtype=torch.int32) + sequence = torch.zeros(1, device="cuda", dtype=torch.int64) + records = torch.zeros((2, 1, 24), device="cuda", dtype=torch.int64) + + def forward(): + torch.mm(source, weight, out=output) + + stream = torch.cuda.Stream() + graphs, _ = capture_forwards( + {"decode": forward}, + {"decode": GraphSignature("decode", 1, 1)}, + session=SimpleNamespace(capture=nullcontext), + device=0, + stream=stream, + pool=storage.graph_pool.id, + warmup_storage=storage, + retain_graphs=True, + compile_decoder=False, + ) + try: + # Export seeding must use CoreStorage.warmup_pool(), not the unmanaged module pool. + assert not _capture._warmup_pools + warmup_pool = storage.warmup_pool() + assert warmup_pool.id in storage._preparation_pools + assert _active_pool_blocks(warmup_pool.id), ( + "seeded cuBLASLt workspace did not land inside CoreStorage.warmup_pool()" + ) + warmup_segments = torch.cuda.memory_snapshot( + warmup_pool.id, include_traces=False + ) + assert warmup_segments + mappings = list(storage.mappings.values()) + for segment in warmup_segments: + addr = segment["address"] + size = segment["total_size"] + assert any( + m.address <= addr and addr + size <= m.address + m.nbytes + for m in mappings + ), f"warmup segment {addr:#x}+{size} fell outside CoreStorage.mappings" + assert _active_pool_blocks(storage.graph_pool.id), ( + "captured graph did not bind cuBLASLt workspace in storage.graph_pool" + ) + buffers = dict( + source=source, + weight=weight, + output=output, + frame_index=frame, + submission_sequence=sequence, + completion_records=records, + ) + bundle = PreparedExecution( + device=0, + graphs=graphs, + buffers=buffers, + max_active=1, + signatures={"decode": GraphSignature("decode", 1, 1, ("source",))}, + ) + allocations = [ + Allocation(name, tensor.data_ptr(), tensor.nbytes) + for name, tensor in buffers.items() + ] + allocations.extend( + Allocation( + f"graph-pool-{index}", + segment["address"], + segment["total_size"], + ) + for index, segment in enumerate( + storage.graph_pool.snapshot(include_traces=False) + ) + ) + package = RuntimeCore( + allocations=allocations, + modules={}, + kernels=(), + recorder=images.native, + owners=(bundle, storage), + ) + package.write( + tmp_path / "rank.json", + bundle.graphs, + execution=bundle.export_manifest(), + sources=True, + ) + finally: + for graph in graphs.values(): + graph.reset() + finally: + torch.backends.cuda.preferred_blas_library(previous_blas) diff --git a/tests/preparation/test_core_storage.py b/tests/preparation/test_core_storage.py index ed77d9c61..36eefc966 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -78,3 +78,28 @@ def test_windows_host_range_stays_below_stalling_wddm_addresses(): # RTX Spark's driver stalls on host-address hints at 16 TiB and 32 TiB. assert CoreStorage.DEVICE_BASE + CoreStorage.RESERVATION_BYTES <= CoreStorage.HOST_BASE assert CoreStorage.HOST_BASE + CoreStorage.HOST_RESERVATION_BYTES <= 16 << 40 + + +def test_warmup_pool_reuses_one_core_allocator_pool(monkeypatch): + from types import SimpleNamespace + + created = [] + + class FakeMemPool: + def __init__(self, allocator): + self.allocator = allocator + self.id = (0, 99 + len(created)) + created.append(self) + + sentinel_alloc = object() + storage = CoreStorage.__new__(CoreStorage) + storage._allocator = SimpleNamespace(allocator=lambda: sentinel_alloc) + storage._preparation_pools = set() + monkeypatch.setattr(torch.cuda, "MemPool", FakeMemPool) + + first = storage.warmup_pool() + second = storage.warmup_pool() + assert first is second + assert len(created) == 1 + assert first.allocator is sentinel_alloc + assert first.id in storage._preparation_pools