From d82fcfcaf09ca8c92bd55cd43a8da2197eb3ba62 Mon Sep 17 00:00:00 2001 From: Jonathan Gutierrez Date: Mon, 30 Nov 2026 03:00:55 -1000 Subject: [PATCH] Resample host memory after flushing CUDA cache in CompilePool MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before this change, `compiler_resources()` in `ignition/preparation/compile_pool.py` sampled `host_memory.available_bytes()` before calling `torch.cuda.empty_cache()`. On integrated/unified-memory GPUs (such as NVIDIA GB10), PyTorch's CUDA caching allocator pins physical host RAM, so flushing cached segments increases both `device_memory_info()` and `host_memory.available_bytes()`. Because `available` was never resampled after `torch.cuda.empty_cache()`, the subsequent `available = min(available, free)` discarded every byte reclaimed by the flush and kept the stale pre-flush host memory reading. In addition, the flush trigger only checked `free - headroom_bytes < device_bytes`, skipping `empty_cache()` both when unified-memory admission was bounded by the higher host compiler headroom/worker budget and when a discrete GPU's free memory fell below the admissible worker cap (`max_workers * device_bytes`). Finally, in `ForwardCache._prepare_ranks()`, `release_unused()` ran before the resource collection barrier without `torch.cuda.empty_cache()`, so peer ranks sharing a host could sample `available_bytes()` before other ranks returned cached CUDA segments. Flushing cached CUDA segments before sampling—and resampling both `free` and `available` after a flush on unified memory—solves the false `MemoryError` without relaxing memory budgets, headroom invariants, or worker sizing limits. In `ignition/preparation/compile_pool.py`, extracted `_DEFAULT_MAX_WORKERS = 8`, clamped `available = min(available, free)` once when `shared` is `True`, triggered `torch.cuda.empty_cache()` whenever `available - headroom < max_workers * worker_bytes` (on unified memory) or `free - headroom_bytes < max_workers * device_bytes` (on discrete GPUs), and resampled both `free` and `available` after flushing on unified memory (while leaving discrete GPUs to resample only `free`). In `ignition/preparation/aot.py`, added `torch.cuda.empty_cache()` immediately after `release_unused()` inside the existing `try/except` block preceding `dist.barrier(group=group)` in `ForwardCache._prepare_ranks()`. In `tests/preparation/test_compile_pool.py`, added CPU unit tests covering unified memory resampling across reclamation thresholds (POSIX and Windows), discrete GPU worker-capacity recovery (default and explicit `compile_workers > 8`), no-flush skips when memory already covers `max_workers`, and `_prepare_ranks()` flush-before-barrier ordering on both success and failure. Unified-memory and multi-rank preparations now account for freed PyTorch CUDA cache segments when budgeting forward compiler workers, preventing spurious `MemoryError` failures under tight physical memory and unlocking multi-worker admission when cached segments would otherwise cap worker counts. Validated with CPU unit tests (`CUDA_VISIBLE_DEVICES="" pytest -q tests/preparation/test_compile_pool.py tests/preparation/test_capture_order.py tests/preparation/test_forward_artifact_sharing.py tests/preparation/test_transient_retention.py tests/preparation/test_host_memory.py`: 160 passed, 0 failed). Validated end-to-end on 3x NVIDIA GB10 (121.7 GiB unified memory) exporting `DeepSeek-V4.1-Flash-1017` at TP3 (`--prefill-chunk-size 6144 --row-shard-prefill --row-shard-attention --image-concurrency 4 --max-concurrency 16 --mtp-draft-tokens 5 --vocabulary-parallel-sampling`): before this change, `Compile model forwards` failed in 2.5s with `MemoryError (8435 MiB available host memory, 8192 MiB headroom)`; after this change, the identical export admitted 3 compiler workers (`[1, 1, 1]`), compiled 51/51 forwards (1204.2s, 11.0-11.3 GiB `MemAvailable` with active compiler workers), captured all 193/193 CUDA graphs (804 MiB free at final graph), and passed `flare run` qualification (24/24 determinism 0.0000 nats KL, 23/24 top-1 vs TP4 0.0424 nats KL, -1.4593 NLL, 3.965s cold 32K needle pass, 61/61 concurrency, 4/4 concurrent image probe pass). Limitation: Windows unified-memory behavior is verified via CPU unit tests mocking `host_memory.os.name == "nt"` and `torch.cuda.mem_get_info` rather than live Windows hardware. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b Signed-off-by: Jonathan Gutierrez --- ignition/preparation/aot.py | 3 +- ignition/preparation/compile_pool.py | 23 ++-- tests/preparation/test_compile_pool.py | 147 +++++++++++++++++++++++++ 3 files changed, 163 insertions(+), 10 deletions(-) diff --git a/ignition/preparation/aot.py b/ignition/preparation/aot.py index a84b45eca..e2b44e824 100644 --- a/ignition/preparation/aot.py +++ b/ignition/preparation/aot.py @@ -1067,9 +1067,10 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi resources = None try: release_unused() + torch.cuda.empty_cache() except Exception as failure: error = error or f"{type(failure).__name__}: {failure}" - # Include every rank's retained cache-restoration owners in host memory admission. + # Include every rank's retained cache-restoration owners and flushed CUDA caches in host memory admission. dist.barrier(group=group) try: resources = compiler_resources(self.device, headroom_bytes=self.headroom_bytes, diff --git a/ignition/preparation/compile_pool.py b/ignition/preparation/compile_pool.py index 3e5106dd0..9310c88f3 100644 --- a/ignition/preparation/compile_pool.py +++ b/ignition/preparation/compile_pool.py @@ -23,6 +23,7 @@ _WORKER_DEVICE_BYTES = 2 << 30 # A discrete GPU's worker holds only device memory, about 0.7 GiB for Kimi K3's 93-layer forwards. _DISCRETE_WORKER_DEVICE_BYTES = 1 << 30 +_DEFAULT_MAX_WORKERS = 8 @dataclass(frozen=True) @@ -42,21 +43,25 @@ def compiler_resources(device, *, headroom_bytes=0, options=None, compile_worker limit = min(cpu_workers(compile_workers), cpu_workers()) if compile_workers is None: limit = min(limit, options['compile_threads']) - available = host_memory.available_bytes() - free = device_memory_info(device)[0] shared = torch.cuda.get_device_properties(device).is_integrated device_bytes = _WORKER_DEVICE_BYTES if shared else _DISCRETE_WORKER_DEVICE_BYTES - if free - headroom_bytes < device_bytes: + worker_bytes = host_memory.FORWARD_WORKER_BYTES + (device_bytes if shared else 0) + headroom = max(host_memory._HEADROOM_BYTES, headroom_bytes if shared else 0) + max_workers = limit if compile_workers is not None else min(limit, _DEFAULT_MAX_WORKERS) + available = host_memory.available_bytes() + free = device_memory_info(device)[0] + if shared: + available = min(available, free) + if (available - headroom < max_workers * worker_bytes if shared + else free - headroom_bytes < max_workers * device_bytes): torch.cuda.empty_cache() free = device_memory_info(device)[0] + if shared: + available = min(host_memory.available_bytes(), free) capacity = max(0, (free - headroom_bytes) // device_bytes) if compile_workers is None: - capacity = min(8, capacity) - if shared: - available = min(available, free) - return CompilerResources(capacity, available, limit, - host_memory.FORWARD_WORKER_BYTES + (device_bytes if shared else 0), - max(host_memory._HEADROOM_BYTES, headroom_bytes if shared else 0)) + capacity = min(_DEFAULT_MAX_WORKERS, capacity) + return CompilerResources(capacity, available, limit, worker_bytes, headroom) def allocate_workers(resources, counts, hosts): diff --git a/tests/preparation/test_compile_pool.py b/tests/preparation/test_compile_pool.py index 21e375f9c..d4b11beab 100644 --- a/tests/preparation/test_compile_pool.py +++ b/tests/preparation/test_compile_pool.py @@ -535,6 +535,153 @@ def test_admitted_pool_does_not_resample_resources(monkeypatch): assert pool.workers == 2 and pool.options["compile_threads"] == 1 +def _patch_compiler_memory(monkeypatch, *, integrated, available_gib, free_gib=None, total_gib=121, + reclaim_host_gib=0, reclaim_free_gib=0, cpu_limit=16, os_name=None): + from ignition.preparation import compile_pool, host_memory + + state = { + "available": int(available_gib * (1 << 30)), + "free": int((available_gib if free_gib is None else free_gib) * (1 << 30)), + "flushes": 0, + "host_samples": 0, + } + + def empty_cache(): + state["flushes"] += 1 + state["available"] += int(reclaim_host_gib * (1 << 30)) + state["free"] += int(reclaim_free_gib * (1 << 30)) + + def available_bytes(): + state["host_samples"] += 1 + return state["available"] + + monkeypatch.setitem(compile_pool._OPTIONS, "compile_threads", cpu_limit) + monkeypatch.setattr(compile_pool, "cpu_workers", lambda requested=None: requested or cpu_limit) + monkeypatch.setattr(torch.cuda, "get_device_properties", lambda device: SimpleNamespace(is_integrated=integrated)) + monkeypatch.setattr(torch.cuda, "empty_cache", empty_cache) + monkeypatch.setattr(host_memory, "available_bytes", available_bytes) + monkeypatch.setattr(torch.cuda, "mem_get_info", lambda device: (state["free"], int(total_gib * (1 << 30)))) + if os_name is not None: + monkeypatch.setattr(host_memory, "os", SimpleNamespace(name=os_name)) + return compile_pool, state + + +@pytest.mark.parametrize( + ("headroom_gib", "initial_gib", "reclaimed_gib", "expected_workers"), + [ + # Integrated GPU where device free - headroom_bytes < device_bytes (2 GiB): + # empty_cache() runs and must also update host available_bytes() before clamping. + (7, 8, 5, 1), + # Integrated GPU where free - headroom_bytes >= device_bytes (4.5 >= 2 GiB), yet + # host available - _HEADROOM_BYTES (1.5 GiB) is below the 4 GiB minimum worker allowance. + (5, 9.5, 4, 1), + # Integrated GPU where reclaimed cached segments unlock a second forward compiler worker. + (8, 44, 34, 2), + ], +) +def test_shared_memory_compiler_resources_resamples_host_available_after_empty_cache( + monkeypatch, headroom_gib, initial_gib, reclaimed_gib, expected_workers +): + compile_pool, state = _patch_compiler_memory( + monkeypatch, integrated=True, available_gib=initial_gib, + reclaim_host_gib=reclaimed_gib, reclaim_free_gib=reclaimed_gib, os_name="posix", + ) + resources = compile_pool.compiler_resources("cuda:0", headroom_bytes=headroom_gib << 30) + assert state["flushes"] == 1 + assert resources.available == int((initial_gib + reclaimed_gib) * (1 << 30)) + assert compile_pool.allocate_workers([resources], [16], ["host"]) == [expected_workers] + + +def test_windows_shared_memory_compiler_resources_resamples_host_available_after_empty_cache(monkeypatch): + compile_pool, state = _patch_compiler_memory( + monkeypatch, integrated=True, available_gib=10, free_gib=105, total_gib=110, + reclaim_host_gib=4, os_name="nt", + ) + pool = compile_pool.CompilePool("cuda:0", headroom_bytes=8 << 30) + assert state["flushes"] == 1 + assert pool.workers == 1 + + +@pytest.mark.parametrize( + ("free_gib", "reclaim_gib", "compile_workers", "expected_capacity"), + [ + (2, 4, None, 6), + # Explicit compile_workers > 8 flushes even when free >= 8 GiB if below requested workers. + (9, 4, 12, 13), + ], +) +def test_discrete_compiler_resources_flushes_cache_to_recover_device_worker_capacity( + monkeypatch, free_gib, reclaim_gib, compile_workers, expected_capacity +): + compile_pool, state = _patch_compiler_memory( + monkeypatch, integrated=False, available_gib=512, free_gib=free_gib, total_gib=96, + reclaim_free_gib=reclaim_gib, + ) + resources = compile_pool.compiler_resources("cuda:0", compile_workers=compile_workers) + assert state["flushes"] == 1 + assert state["host_samples"] == 1 + assert resources.capacity == expected_capacity + + +@pytest.mark.parametrize( + ("integrated", "available_gib", "free_gib", "total_gib"), + [ + (False, 512, 16, 96), + (True, 300, 300, 512), + ], +) +def test_compiler_resources_skips_empty_cache_when_memory_already_covers_max_workers( + monkeypatch, integrated, available_gib, free_gib, total_gib +): + compile_pool, state = _patch_compiler_memory( + monkeypatch, integrated=integrated, available_gib=available_gib, free_gib=free_gib, + total_gib=total_gib, os_name="posix", + ) + resources = compile_pool.compiler_resources("cuda:0") + assert state["flushes"] == 0 + assert resources.capacity == 8 + + +@pytest.mark.parametrize("fail_flush", [False, True]) +def test_prepare_ranks_flushes_cuda_cache_before_resource_barrier(monkeypatch, tmp_path, fail_flush): + import torch.distributed as dist + from ignition.preparation import aot, compile_pool + + events = [] + cache = aot.ForwardCache.__new__(aot.ForwardCache) + cache.root = tmp_path + cache.device = torch.device("cuda:0") + cache.headroom_bytes = 0 + cache.options = {} + cache.compile_workers = None + cache.lock_gpu_clocks = False + coordinator = SimpleNamespace(group=object(), ranks=(0,), hosts=("host-a",), spans_hosts=False) + + monkeypatch.setattr(dist, "get_rank", lambda group=None: 0) + monkeypatch.setattr(dist, "all_gather_object", lambda out, obj, group=None: out.__setitem__(0, obj)) + monkeypatch.setattr(dist, "barrier", lambda group=None: events.append("barrier")) + monkeypatch.setattr(aot, "release_unused", lambda *args, **kwargs: events.append("release_unused")) + + def empty_cache(): + events.append("empty_cache") + if fail_flush: + raise RuntimeError("cache flush failed") + + monkeypatch.setattr(torch.cuda, "empty_cache", empty_cache) + + def fake_resources(*args, **kwargs): + events.append("compiler_resources") + return compile_pool.CompilerResources(1, 64 << 30, 1, 32 << 30, 8 << 30) + + monkeypatch.setattr(compile_pool, "compiler_resources", fake_resources) + if fail_flush: + with pytest.raises(RuntimeError, match="cache flush failed"): + cache._prepare_ranks({}, {}, coordinator, progress=None, materialize=None, warmup=None, before_run=None) + else: + assert cache._prepare_ranks({}, {}, coordinator, progress=None, materialize=None, warmup=None, before_run=None) == {} + assert events[:4] == ["release_unused", "empty_cache", "barrier", "compiler_resources"] + + @pytest.mark.parametrize("recorded", [False, True]) def test_compiler_does_not_serialize_preparation_session_resources(recorded): from contextvars import ContextVar