diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 865da8923..8fea8e679 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -111,9 +111,12 @@ granularity. Reservations without retained allocations are omitted. Only their live byte spans are considered for payload storage; page gaps are zero. Before copying, the exporter checks that each external allocation belongs to the serving context. On Linux integrated GPUs, preparation reserves the low address -window through 256 GiB without physical backing. Windows retains the driver's -low allocation pool. Export on either integrated platform rejects reachable -external device storage below 256 GiB, where context mappings can prevent replay. +window through its external device floor (`CoreStorage.EXTERNAL_FLOOR`: 256 GiB +by default, or 36 GiB for integrated GA10B / SM 8.7's default 128 GiB VMM layout +with a 72 GiB device base and 48 GiB reservation) without physical backing. +Windows retains the driver's low allocation pool. Export on either integrated +platform rejects reachable external device storage below that floor, where +context mappings can prevent replay. The model exporter retains allocations reachable from graph arguments, copy and memset endpoints, module globals, native execution buffers, and declared diff --git a/ignition/components/sampling.py b/ignition/components/sampling.py index 3aa780897..36f3414bb 100644 --- a/ignition/components/sampling.py +++ b/ignition/components/sampling.py @@ -28,6 +28,7 @@ ) from ignition.preparation.persistent import persistent_copy, persistent_empty from ignition.preparation.scratch import bind_scratch +from ignition.preparation.tensor_metadata import record_numeric_tensor EOS_CAPACITY = 8 INACTIVE, RUNNING, FINISHED, ERROR = 0, 1, 2, 3 @@ -128,7 +129,9 @@ def vocab_size(self) -> int: @cached_property def vocab_ids(self) -> torch.Tensor: - return persistent_copy(torch.arange(self.vocab_size, dtype=torch.int64, device=self.histogram.device)) + ids = persistent_copy(torch.arange(self.vocab_size, dtype=torch.int64, device=self.histogram.device)) + record_numeric_tensor(ids) + return ids def admit(self, slot: int, admission: RequestAdmission, prompt_ids, *, consumed_tokens: int = 0) -> None: """Bootstrap a slot outside replay; Rust admission uploads the same fields. diff --git a/ignition/preparation/capture.py b/ignition/preparation/capture.py index c36a904c5..9b1614f20 100644 --- a/ignition/preparation/capture.py +++ b/ignition/preparation/capture.py @@ -5,6 +5,7 @@ """Compile prepared model forwards and capture CUDA graphs for their shapes.""" from contextlib import ExitStack, nullcontext +import os from time import monotonic import torch @@ -67,7 +68,10 @@ def _seed_warmup_workspaces(stream, device): 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)) + bias = torch.empty((512,), dtype=torch.bfloat16, device=device) + out = torch.empty_like(operand) + torch.mm(operand, operand, out=out) + torch.addmm(bias, operand, operand, out=out) stream.synchronize() @@ -167,6 +171,19 @@ def capture_forwards(functions, signatures, *, session, device, stream, pool, warm.synchronize() stage.update(advance=1) stream.wait_stream(warm) + seal_low = os.name != "nt" and getattr(warmup_storage, "integrated", False) + if seal_low: + # On Linux unified-memory GPUs (e.g., Jetson SM87), the first CUDA graph capture trims + # CUDA's pre-init low allocation slab, reopening free spans below EXTERNAL_FLOOR. + # Trigger one minimal probe capture inside transient storage so exiting warmup() + # synchronizes, releases the transient pool, and reseals the low window before + # capturing any serving graph. + with warmup(): + probe_buf = torch.empty((1,), dtype=torch.int8, device=device) + probe_graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(probe_graph, stream=stream): + probe_buf.zero_() + del probe_graph, probe_buf ordered_names = _capture_order(names, compiled, coordinator) retired = False with phase(progress, label, total=len(names)) as stage: @@ -208,6 +225,8 @@ def memory_detail(): function() if exporting: graph = record_export_graph(graph, warmup_storage, owners=(function,)) + if seal_low: + warmup_storage.seal_low_window() elif retain_graphs: if progress is not None: progress(f"instantiating {name}: {memory_detail()}") diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 02bcb0b05..69b847b50 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -65,7 +65,10 @@ def __init__(self, *, rank=0, world=1, device=0, local_ranks=None, device_window self.integrated = properties.is_integrated if device_window is None and self.integrated and (properties.major, properties.minor) == (8, 7): # Jetson Orin (GA10B) exposes a 128 GiB CUDA VMM address window (below 0x20_0000_0000). - self.EXTERNAL_FLOOR = 0x300000000 + # Place EXTERNAL_FLOOR at 0x9_0000_0000 (36 GiB) so external library allocations lie in + # the 36 GiB [0x9_0000_0000, 0x12_0000_0000) band below DEVICE_BASE (72 GiB), above + # cuRAND precalc_xorwow_offset_matrix 64-bit words in [0x3_0000_0000, 0x3_0300_0000]. + self.EXTERNAL_FLOOR = 0x900000000 self.DEVICE_BASE = 0x1200000000 self.RESERVATION_BYTES = 48 << 30 self._persistent_total_bytes = min(properties.total_memory, self.RESERVATION_BYTES // 4) diff --git a/tests/preparation/test_capture_graph_metadata.py b/tests/preparation/test_capture_graph_metadata.py index aa85a1259..cf23b9257 100644 --- a/tests/preparation/test_capture_graph_metadata.py +++ b/tests/preparation/test_capture_graph_metadata.py @@ -320,21 +320,15 @@ def call(self, name, executable, out_flags): runtime_core._cuda_driver.cache_clear() -def test_capture_forwards_export_sets_node_priority_instantiation_flag(monkeypatch, recorder): - stream = SimpleNamespace(wait_stream=lambda other: None, synchronize=lambda: None) - storage = SimpleNamespace( - pool=SimpleNamespace(id=(0, 1)), - graph_pool=SimpleNamespace(id=(0, 2)), - transient=nullcontext, - retain_transient_backing=nullcontext, - ) - +def _patch_export_capture(monkeypatch, stream, *, on_graph=None): class ExportGraph(Graph): def pools(self): return [(0, 2)] @contextmanager def graph_scope(graph, **kwargs): + if on_graph is not None: + on_graph(graph, kwargs) yield graph.capture_end() @@ -346,6 +340,17 @@ def graph_scope(graph, **kwargs): monkeypatch.setattr(torch.cuda, name, value) monkeypatch.setattr(capture, "_warmup_stream", lambda device: stream) monkeypatch.setattr(capture, "_seed_warmup_workspaces", lambda stream, device: None) + + +def test_capture_forwards_export_sets_node_priority_instantiation_flag(monkeypatch, recorder): + stream = SimpleNamespace(wait_stream=lambda other: None, synchronize=lambda: None) + storage = SimpleNamespace( + pool=SimpleNamespace(id=(0, 1)), + graph_pool=SimpleNamespace(id=(0, 2)), + transient=nullcontext, + retain_transient_backing=nullcontext, + ) + _patch_export_capture(monkeypatch, stream) graphs, _ = capture.capture_forwards( {"prefill": lambda: None, "decode": lambda: None}, {"prefill": SimpleNamespace(kind="prefill"), "decode": SimpleNamespace(kind="decode")}, @@ -472,3 +477,119 @@ def test_export_resources_accept_recorded_graphs_and_executable_tuners(monkeypat recorded.reset() with pytest.raises(ValueError, match="released"): bundle._validate_resources(export_graphs=True) + + +def test_seed_warmup_workspaces_warms_both_mm_and_addmm(monkeypatch): + events = [] + stream = SimpleNamespace(synchronize=lambda: events.append("sync")) + + monkeypatch.setattr(capture, "_warmup_pools", {}) + monkeypatch.setattr(torch.cuda, "device", lambda value: nullcontext()) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + monkeypatch.setattr(torch.cuda, "MemPool", lambda: "pool") + monkeypatch.setattr(torch.cuda, "stream", lambda value: nullcontext()) + monkeypatch.setattr(torch.cuda, "use_mem_pool", lambda value: nullcontext()) + + real_mm, real_addmm = torch.mm, torch.addmm + + def record_mm(*args, **kwargs): + events.append("mm") + return real_mm(*args, **kwargs) + + def record_addmm(*args, **kwargs): + events.append("addmm") + return real_addmm(*args, **kwargs) + + monkeypatch.setattr(torch, "mm", record_mm) + monkeypatch.setattr(torch, "addmm", record_addmm) + + capture._seed_warmup_workspaces(stream, "cpu") + assert events == ["mm", "addmm", "sync"] + + +def test_capture_forwards_integrated_storage_probes_and_reseals_low_window(monkeypatch, recorder): + events = [] + stream = SimpleNamespace( + wait_stream=lambda other: None, + synchronize=lambda: events.append("stream_sync"), + ) + + @contextmanager + def transient(): + events.append("transient_enter") + yield + events.append("transient_exit") + storage.seal_low_window() + + storage = SimpleNamespace( + integrated=True, + pool=SimpleNamespace(id=(0, 1)), + graph_pool=SimpleNamespace(id=(0, 2)), + transient=transient, + retain_transient_backing=nullcontext, + seal_low_window=lambda: events.append("seal_low_window"), + ) + monkeypatch.setattr(capture, "os", SimpleNamespace(name="posix")) + _patch_export_capture( + monkeypatch, + stream, + on_graph=lambda _graph, kwargs: events.append( + "probe_capture" if "pool" not in kwargs else "serving_capture" + ), + ) + capture.capture_forwards( + {"prefill": lambda: None, "decode": lambda: None}, + {"prefill": SimpleNamespace(kind="prefill"), "decode": SimpleNamespace(kind="decode")}, + session=SimpleNamespace(capture=nullcontext), + device="cpu", + stream=stream, + pool=(0, 2), + compile_decoder=False, + retain_graphs=True, + warmup_storage=storage, + ) + # Probe capture runs inside transient storage, whose exit synchronizes and reseals before the + # first serving capture; each exported graph reseals again after record_export_graph. + capture_phase = events[events.index("probe_capture"):] + assert capture_phase == [ + "probe_capture", + "transient_exit", + "seal_low_window", + "serving_capture", + "seal_low_window", + "serving_capture", + "seal_low_window", + ] + + +def test_capture_forwards_integrated_storage_skips_probe_and_reseal_on_windows(monkeypatch, recorder): + events = [] + stream = SimpleNamespace(wait_stream=lambda other: None, synchronize=lambda: None) + storage = SimpleNamespace( + integrated=True, + pool=SimpleNamespace(id=(0, 1)), + graph_pool=SimpleNamespace(id=(0, 2)), + transient=nullcontext, + retain_transient_backing=nullcontext, + seal_low_window=lambda: events.append("seal_low_window"), + ) + monkeypatch.setattr(capture, "os", SimpleNamespace(name="nt")) + _patch_export_capture( + monkeypatch, + stream, + on_graph=lambda _graph, kwargs: events.append( + "probe_capture" if "pool" not in kwargs else "serving_capture" + ), + ) + capture.capture_forwards( + {"decode": lambda: None}, + {"decode": SimpleNamespace(kind="decode")}, + session=SimpleNamespace(capture=nullcontext), + device="cpu", + stream=stream, + pool=(0, 2), + compile_decoder=False, + retain_graphs=True, + warmup_storage=storage, + ) + assert events == ["serving_capture"] diff --git a/tests/preparation/test_core_storage.py b/tests/preparation/test_core_storage.py index ed77d9c61..5386deeac 100644 --- a/tests/preparation/test_core_storage.py +++ b/tests/preparation/test_core_storage.py @@ -78,3 +78,45 @@ 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_ga10b_integrated_window_places_external_floor_above_curand_table(monkeypatch): + from types import SimpleNamespace + from ignition.preparation import core_storage + + recorded = {} + + class StopAfterWindow(RuntimeError): + pass + + class FakeCuda: + def __init__(self): + recorded["called"] = True + raise StopAfterWindow + + monkeypatch.setattr( + torch.cuda, + "get_device_properties", + lambda device: SimpleNamespace(is_integrated=True, major=8, minor=7, total_memory=8 << 30), + ) + monkeypatch.setattr(core_storage, "_Cuda", FakeCuda) + owner = CoreStorage.__new__(CoreStorage) + with pytest.raises(StopAfterWindow): + CoreStorage.__init__(owner, rank=0, world=1, device=0) + assert recorded["called"] + assert owner.integrated is True + assert owner.EXTERNAL_FLOOR == 0x900000000 + assert owner.DEVICE_BASE == 0x1200000000 + assert owner.RESERVATION_BYTES == 48 << 30 + + +def test_device_request_state_vocab_ids_records_numeric_tensor(): + from ignition.components.sampling import DeviceRequestState + from ignition.preparation.tensor_metadata import NumericStorage + + state = DeviceRequestState.allocate("cpu", vocab_size=16, capacity=1) + with NumericStorage() as numeric: + ids = state.vocab_ids + assert numeric.ranges() == [(ids.data_ptr(), ids.data_ptr() + ids.nbytes)] + assert ids.dtype == torch.int64 + assert torch.equal(ids, torch.arange(16, dtype=torch.int64))