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