Review — PR #641 "Resample host memory after flushing CUDA cache in CompilePool"
Lens: Correctness, Contracts & System-Level Consequences. All line numbers verified at head d82fcfc; main behaviour read from the diff in pr_diff.
Key findings
- The flush is now effectively unconditional on unified memory (Major). The new trigger compares host memory against the whole worker budget:
max_workers * worker_bytes= 8 × (32 GiB + 2 GiB) = 272 GiB, which no GB10 (the PR's own 121.7 GiB unified-memory part) can ever satisfy.torch.cuda.empty_cache()therefore runs on every integrated preparation, forever. The author's own "skip" test needs a 300 GiB host to exercise the non-flush branch (tests/preparation/test_compile_pool.py:626-642). The description never says the trigger became near-unconditional, and no cost is measured. - Flush frequency is now a function of host CPU count, not memory demand (Minor, coupled to #1).
limitderives fromcompile_threads = min(16, cpu_count); on discrete GPUs the threshold ismax_workers * 1 GiB— 8 GiB at defaults, 12 GiB when a user asks for 12 workers, 2 GiB on a 2-core host. - "Unlocking additional compiler workers" is contradicted by the PR's own numbers (Major, claim accuracy). With the reported after-state (~13.3 GiB available, 8192 MiB headroom) a real worker still needs 34 GiB; the
[1, 1, 1]result comes from the pre-existing 4 GiB minimum-allowance fallback atcompile_pool.py:87-94, which this PR does not touch. - The reordered
available = min(available, free)clamp only changes behaviour on Windows (Major, platform parity/claim accuracy). On POSIX integrated GPUsdevice_memory_info()already returnsmin(total, available_bytes())(host_memory.py:107-110), i.e. the platform all live evidence comes from. The only affected path is Windows, covered solely by a mock — whichAGENTS.md:194-199says cannot establish runtime correctness. - Ordering and failure propagation are correct — say so plainly. flush →
dist.barrier→compiler_resources→all_gather_objectis right, and a flush failure is folded intoerrorwhile every rank still reaches the barrier and the gathering collectives. Now covered by a real ordering test. - Minor items: a redundant second flush seconds later; a
release_unused()failure silently skips the new flush while the reworded comment still asserts it; the flush runs inside the retained/transient storage scope with no reseal of the sealed low-address window until retention exit.
1. Correctness, Safety & Platform Parity
F1 — Minor: a release_unused() failure silently skips the new flush, contrary to the reworded comment
ignition/preparation/aot.py:1068-1073:
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 and flushed CUDA caches in host memory admission.
Both calls share one try. If release_unused() raises, empty_cache() never runs, yet the comment asserts flushed caches. Diagnostic only — the stored error aborts preparation later at aot.py:1130-1131 — but the comment is not guaranteed true. Fix: separate try blocks, or soften the comment to "attempt to flush".
F2 — Minor: min(available, free) is a no-op on the platform the evidence comes from (see Key finding 4)
ignition/preparation/host_memory.py:107-110:
free, total = torch.cuda.mem_get_info(device)
if os.name != "nt" and torch.cuda.get_device_properties(device).is_integrated:
free = min(total, available_bytes())
return free, total
compile_pool.py:53-54 clamps available = min(available, free) before the flush and :59-60 after. On POSIX integrated free already is min(total, available_bytes()), so both clamps only cap available by device total. The behaviour the PR describes as newly fixed is unchanged on GB10; only os.name == "nt" differs, and tests/preparation/test_compile_pool.py:595-602 covers it with a monkeypatched host_memory.os. Impact: the description overstates the platform span of the fix. Fix: say so in the description, or defer the Windows-specific clamp until a live Windows run exists.
F3 — Minor (owner to confirm): flush inside the retained storage scope with no reseal
ignition/preparation/core_storage.py:160-165:
def seal_low_window(self):
"""Reserve every span below EXTERNAL_FLOOR that is free now, including spans frees reopened.
Storage occupied when the window was first reserved and freed later would otherwise let
an external allocation land below the floor, where a serving context's own storage lies.
"""
Reseals happen only at core_storage.py:248-250 (retention finish, and only when retired_pool) and :288-292 (non-shared transient pool exit: del pool; torch.cuda.empty_cache(); ... self.seal_low_window()). The new flush at aot.py:1070 runs inside capture.py:131-132's retention scope and returns cached segments to the driver before the later capture allocations, with no seal_low_window() in between; placement was verified only once at setup (core_storage.py:134-140). Impact: on integrated export, library allocations after the flush could land below EXTERNAL_FLOOR — exactly the hazard the seal exists to prevent. Fix: confirm with the storage owner that a cached-segment free needs no reseal, or reseal immediately after the flush.
Verified sound here: _DEFAULT_MAX_WORKERS = 8 (compile_pool.py:26) replaces min(8, capacity) at :62-63 with identical behaviour; CompilerResources fields and allocate_workers (:67-98) are unchanged, so headroom invariants and worker budgets are not relaxed, as claimed; zero-job hosts still skip admission (:73-74); no config, artifact, cache-key, or wire-format change, so existing cores still load.
2. Unintended System-Level Consequences
F4 — Major: the flush is loop-invariant on unified memory
ignition/preparation/compile_pool.py:48-57:
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()
On integrated GPUs the operand is min(host available, free) ≤ physical RAM, while the threshold is 8 × 34 GiB = 272 GiB. No GB10/DGX Spark run can satisfy it, so empty_cache() fires on every preparation. main flushed only when a single 2 GiB worker did not fit. Proof from the author's own suite, tests/preparation/test_compile_pool.py:626-642:
[
(False, 512, 16, 96),
(True, 300, 300, 512),
],
The only integrated non-flush case requires 300 GiB of host RAM. Impact: on GB10 the segments dropped by the flush are re-allocated via cudaMalloc by the immediately following bind/warm/capture phase (aot.py:1098-1101 CompilePool, then capture), on hardware where large-segment cudaMalloc is expensive; the PR reports 1204.2s for its after-run and no isolated timing, so the cost is unmeasured and undisclosed. The flush also now runs per rank twice (see F6), on the critical path immediately before a barrier that all ranks must reach. Fix: gate on one worker's need, or flush-and-resample only when the reclaimed bytes actually change admission (e.g. available - headroom < worker_bytes), and publish a GB10 before/after wall-clock measurement.
F5 — Minor: flush frequency scales with host CPU count, not memory demand
ignition/preparation/compile_pool.py:43-45:
limit = min(cpu_workers(compile_workers), cpu_workers())
if compile_workers is None:
limit = min(limit, options['compile_threads'])
with ignition/preparation/compilation.py:30 'compile_threads': min(16, os.cpu_count() or 1). On discrete GPUs the threshold free - headroom_bytes < max_workers * device_bytes is 8 GiB at defaults but 12 GiB when the user requests 12 workers — the PR's own case (9, 4, 12, 13) at tests/preparation/test_compile_pool.py:608-610 flushes a 96 GiB card that has 9 GiB free — and collapses to 2 GiB on a 2-core host. Impact: discrete SM103/SM120/SM121 exports that never flushed now do, with frequency set by core count rather than by this rank's missing-forward demand. Fix: derive the trigger from the workers actually needed for missing forwards, not the CPU-derived limit.
F6 — Minor: redundant back-to-back flush per rank
aot.py:1069-1070 flushes; aot.py:1076 then calls compiler_resources, whose compile_pool.py:57 flush fires on integrated unconditionally (F4). Nothing is allocated in between, so one of the two is pure overhead on every rank of every multi-host export. Fix: let compiler_resources own the flush, or drop the new call site.
Verified sound here: the synchronization order is correct and race-free — aot.py:1070 flush → :1074 dist.barrier(group=group) → :1076 compiler_resources → :1081 all_gather_object(demand, ...), so no rank samples host memory before its peers have flushed, which is precisely the peer-rank hazard the description names. Failure blast radius is contained: a flush exception is folded into error (aot.py:1071-1072), every rank still executes the barrier and both gathers, and the failure surfaces through the collective list at aot.py:1083-1085 / :1130-1131 rather than deadlocking peers.
3. Architecture, Contracts & Charter Compliance
- No wire, artifact, captured-graph, or public-API contract change; no new flag, env var, dependency, or per-model branch.
CompilerResourceskeeps its five fields and semantics. Nothing here needs owner sign-off for a new op contract. - The change is in the right layer (
ignition/preparation), followsdocs/design-review.md:81-84(not opened) anddocs/preparation-development.md:305-318(account for cached allocator segments; budget against available system RAM), and extends the flush added by #462 without reversingc8d4c324's per-host budget. - Charter tension is the evidence span, not the design: one model (DeepSeek V4.1 Flash), one layout (TP3, one rank/host), one hardware class (SM121 GB10), produced on a three-branch stack (#635 + hyperflare-recipes#103 + this), which
AGENTS.md:96-112says must not be attributed to one PR. The discrete and Windows paths are mock-only, whichAGENTS.md:194-199says cannot establish runtime correctness.
4. Tests & Claim Accuracy
- Tests are additive-only (+147) and live in
tests/preparation/test_compile_pool.py, which the CPU workflow runs, so "not covered by CI" is not a finding. The new ordering test (:645-682) genuinely pinsevents[:4] == ["release_unused", "empty_cache", "barrier", "compiler_resources"]and the failure case; the resample tests do pin the arithmetic on both POSIX andos.name == "nt". - What the tests cannot show: every new test monkeypatches
torch.cuda.empty_cache,host_memory.available_bytes,torch.cuda.mem_get_info,get_device_propertiesanddist.*(:538-566), so "resampled exactly once" is arithmetic, not real reclamation. - Claim accuracy (F2 above, Major): the description's "unlocking additional compiler workers when cached segments would otherwise cap admission" is not supported by its own evidence.
compile_pool.py:87-94:
if not any(workers[rank] for rank in members):
able = [rank for rank in members if resources[rank].capacity
and resources[rank].worker_bytes - host_memory.FORWARD_WORKER_BYTES
+ host_memory._WORKER_BYTES <= remaining]
if able:
workers[able[0]] = 1
The loop at :79-86 needs the full worker_bytes = 34 GiB per worker; the fallback needs 34 − 32 + 2 = 4 GiB. The reported after-state leaves ~5.3 GiB, so only the fallback can fire: [1, 1, 1] is the restored one-worker-per-host floor, not extra workers. The "before" state (8435 MiB − 8192 MiB = 243 MiB remaining) fails that same 4 GiB floor and produces the reported MemoryError. Fix: reword the claimed benefit to "avoids the spurious MemoryError / restores one worker per host", or supply a case where a second worker actually appears.
- Metric/span check: the admission metric is
CompilerResources.available, and this PR moves its sampling point from pre-flush to post-flush on integrated GPUs. Traced downstream, resolution is unchanged (allocate_workersatcompile_pool.py:75-78takesmin(available)per host, then subtractsmax(headroom)), so the pricing formula is untouched — but on POSIX the resampled value is identical to the old one (F2), so the metric change is inert on the evidenced platform and the only measurable metric shift iscapacityon discrete GPUs, which grows post-flush whileavailableis deliberately left unsampled (tests/preparation/test_compile_pool.py:622). That asymmetry is substantively right (a discrete flush returns device memory, not host RAM) and should simply be stated.
Open questions / could not verify
- No isolated
main-vs-PR measurement and no wall-clock A/B for the extra flushes; the "before" run failed in 2.5 s and the "after" run spent 1204.2 s compiling, so the two are not comparable. - Whether
availableshould be resampled after a discrete flush for consistency withcapacity(I judge no, but the description should say why). - Landing order versus #639, which rewrites
compiler_resourcesand changes_DISCRETE_WORKER_DEVICE_BYTESto 704 MiB — that would invalidatetests/preparation/test_compile_pool.py:605-623((2, 4, None, 6)becomes 8,(9, 4, 12, 13)becomes 18). Whichever lands second must rebase. - Whether a docs line belongs in
docs/model-preparation.md:489-495, as the comparable PRs #597 and #122 did; nothing currently documented becomes wrong. - Unverified, deliberately not claimed as a finding: the new
torch.cuda.empty_cache()ataot.py:1070names no device, so it clears whichever device is current. I did not verify that_prepare_rankssets the current device toself.devicebefore that line; the same unqualified call already exists incompiler_resourcesonmain, so this is a pre-existing pattern rather than a new one, but it is worth one line of confirmation from the author since the call site is new. - Not found: any linked issue (
Fixes #absent), any review, label, CI run, or maintainer statement of intent on thecompiler_resourceslanding order.
Verdict: the ordering/failure-propagation work in aot.py and the resample logic are correct; the blocking concerns are the undisclosed near-unconditional flush on unified memory (F4), the CPU-count-coupled trigger frequency (F5), and two claim-accuracy defects (the "additional workers" benefit and the Windows-only clamp) that a charter-compliant description must correct before merge.