Subtraction, Simplicity & Conventions review — PR #641 "Resample host memory after flushing CUDA cache in CompilePool"
Head d82fcfc, base 0a8c20f, +163/−10 in 3 files (ignition/preparation/compile_pool.py, ignition/preparation/aot.py, tests/preparation/test_compile_pool.py).
Key findings
The diff is genuinely small and structurally clean: no new flag, config key, env var, dependency, abstraction, dataclass field, artifact or cache-key change; CompilerResources keeps its shape (compile_pool.py:29-35); allocate_workers() is untouched (:67-98); and ignition/preparation/aot.py (+2/−1) needs no simplification at all. There are two things worth subtracting, both inside compiler_resources(), plus a handful of minor notes.
- S1 (high value): the widened flush trigger (
compile_pool.py:55-56) is unmeasured extra scope that the reported defect does not need — the old one-line trigger already fired in the reported case. On unified memory it is unconditionally true (272 GiB threshold vs 121.7 GiB of physical RAM), soempty_cache()goes from rare to every-preparation; it newly flushes discrete hosts that never flushed; and it makes the PR's own newaot.py:1070flush immediately redundant, i.e. twoempty_cache()calls per rank per preparation. Replacing:55-56with the narrow per-worker form and deleting:50removes ~4 of the 5 new mocked tests and keeps the actual fix (the resample at:59-60) intact. - S2 (high value):
host_memory.available_bytes()and theif shared: available = min(available, free)clamp are expressed twice (:51-54and:58-60), with oneif sharedtoo many and a discrete/shared asymmetry (discrete resamplesfreebut notavailable, the two numbersallocate_workersmultiplies). A 4-line localsample()helper collapses all of it and cutsavailable_bytes()calls from 4 back to 2 per invocation (each call =/proc/meminfo+/proc/self/cgroup+/proc/self/mountinfo). - Minor:
_DEFAULT_MAX_WORKERS(:26) only earns its extraction frommain's literal because of S1;state["host_samples"]is pinned only on the discrete path; the only structuralAGENTS.mdconcern is the same unmeasured churn.
S1 — Delete the widened flush trigger at ignition/preparation/compile_pool.py:55-56 (and the max_workers local at :50)
Current head, ignition/preparation/compile_pool.py:46-63 (verbatim):
shared = torch.cuda.get_device_properties(device).is_integrated
device_bytes = _WORKER_DEVICE_BYTES if shared else _DISCRETE_WORKER_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)
main's line this replaced (compile_pool.py:49 on base):
if free - headroom_bytes < device_bytes:
torch.cuda.empty_cache()
free = device_memory_info(device)[0]
Concrete simplification
- Replace
:55-56with:
if (available - headroom < device_bytes if shared
else free - headroom_bytes < device_bytes):
- Delete
:50(max_workers = ...) entirely;_DEFAULT_MAX_WORKERSis still used at:63.
The reported memory is still reclaimed in the reported case: on POSIX integrated GPUs host_memory.device_memory_info() folds host RAM into free —
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())
(ignition/preparation/host_memory.py:107-109)
— so the PR's own before-number, 8435 MiB available with 8192 MiB headroom, gives 8435 − 8192 = 243 MiB < 2048 MiB (_WORKER_DEVICE_BYTES, compile_pool.py:23) and the flush fires under both old and narrow triggers. The defect this PR names is the missing resample of available, and only :59-60 fixes it. The widened trigger therefore buys nothing for the stated bug.
Why the widening is a subtraction, not a refinement
- It makes the flush unconditional on the target hardware.
limitis capped by'compile_threads': min(16, os.cpu_count() or 1)(ignition/preparation/compilation.py:30) and then bymin(limit, _DEFAULT_MAX_WORKERS)at:50, somax_workers = 8on any host with ≥8 visible CPUs.worker_bytes = FORWARD_WORKER_BYTES (32 GiB, host_memory.py:15) + 2 GiB = 34 GiB, so the unified-memory threshold is8 × 34 = 272 GiB. On GB10available = min(available_bytes(), free) ≤ total = 121.7 GiB, andheadroom ≥ 0, soavailable - headroom < 272 GiBholds for every headroom and every recipe. Even with only 4 visible CPUs the threshold is 136 GiB > 121.7 GiB.torch.cuda.empty_cache()consequently runs on every GB10 preparation, not "when a worker does not fit". - It newly flushes discrete GPUs. The discrete branch's threshold moves from
free - headroom_bytes < 1 GiB(one_DISCRETE_WORKER_DEVICE_BYTES) tofree - headroom_bytes < max_workers × 1 GiB= 8 GiB at defaults. This is not hypothetical: the pre-existing testtests/preparation/test_compile_pool.py:39-41sets 12 GiB free and 2 GiB headroom withcompile_workers=32, so10 GiB < 32 GiBnow takes the flush path wheremaintook none — silently, because the test's expectation still passes. No cost measurement for the added flushes appears anywhere in the description. - It double-flushes every rank, making the PR's own
aot.pychange redundant.ignition/preparation/aot.py:1067-1076(verbatim):
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 and flushed CUDA caches in host memory admission.
dist.barrier(group=group)
try:
resources = compiler_resources(self.device, headroom_bytes=self.headroom_bytes,
options=self.options, compile_workers=self.compile_workers)
The barrier guarantees every rank released its cache before any rank samples; with the 272 GiB threshold, compiler_resources at :1076 then flushes a second time on the same rank, microseconds later. Keeping :1070 and narrowing compile_pool.py:55-56 is the coherent design; keeping both as-is is a duplicated flush.
- It is a second, less accurate copy of admission arithmetic that already exists.
allocate_workers()(compile_pool.py:67-98) is the real rule: per host,remaining = available - headroom(:78), decremented once per admitted worker (:86), bounded byjobs= missing forwards and by each rank'scapacity(:72,:77,:80-81), with a documented minimum-allowance fallback at:87-94. The new pre-check replaces all of that with a flatmax_workers × worker_byteson one rank's reading — a host with a single missing forward is now required to clear 272 GiB. (This is also why the description's "unlocks additional compiler workers" does not follow: the admitted[1, 1, 1]comes from the fallback at:87-94, not from the widened trigger.) - Convention.
AGENTS.md:188-193: "Reject unsupported abstractions and churn. … Refactoring must directly support the requested behavior or remove a demonstrated source of defect or cost." The widening changes behaviour on both hardware classes, beyond the defect, without a measurement.
Tests to delete with it (all purely additive, +147 lines, tests/preparation/test_compile_pool.py:538-681):
:569-592— the three parametrized unified-memory cases exist to pin the wide threshold:(7, 8, 5, 1)and(5, 9.5, 4, 1)both pass under the narrow trigger too, but(8, 44, 34, 2)("reclaimed cached segments unlock a second forward compiler worker",:578-579) is the widening's claim and is contradicted by the PR's own live numbers. Keep one case and its resample assertion (:591).:605-623— discrete capacity recovery; the second param(9, 4, 12, 13)(:610) needscompile_workers=12 > 8purely to make the wide trigger fire on a host with 9 GiB free, which the old trigger would skip by design.:626-642—test_compiler_resources_skips_empty_cache_when_memory_already_covers_max_workers; the assertionstate["flushes"] == 0only has a subject while the threshold ismax_workers-scaled.
Keep: the single resample assertion at :591, the Windows clamp test at :595-602 (the one path where the moved clamp changes behaviour), and the _prepare_ranks() ordering test at :645-682, which is a real contract and is well written (parametrized over flush failure, asserts events[:4] == ["release_unused", "empty_cache", "barrier", "compiler_resources"], :682).
Mock concern (secondary, structural): _patch_compiler_memory (:538-566) monkeypatches torch.cuda.empty_cache, host_memory.available_bytes, torch.cuda.mem_get_info, torch.cuda.get_device_properties and os, so assert state["flushes"] == 1/0 pins the arithmetic of a trigger rather than the reclamation the PR describes; AGENTS.md:194-199 says "mocks that bypass the behavior cannot establish runtime correctness". That is acceptable for the narrow resample contract (it is pure arithmetic over samples that cannot be observed otherwise) and is another reason not to spend 100+ test lines pinning a threshold that should be re-derived.
S2 — Collapse the duplicated sample/clamp into one helper in the same function
Current head, ignition/preparation/compile_pool.py:51-60 (verbatim):
available = host_memory.available_bytes()
free = device_memory_info(device)[0]
if shared:
available = min(available, free)
if (...):
torch.cuda.empty_cache()
free = device_memory_info(device)[0]
if shared:
available = min(host_memory.available_bytes(), free)
Concrete simplification (also absorbs S1's trigger line):
def sample():
free = device_memory_info(device)[0]
return free, (min(host_memory.available_bytes(), free) if shared
else host_memory.available_bytes())
free, available = sample()
if (available - headroom < device_bytes if shared
else free - headroom_bytes < device_bytes):
torch.cuda.empty_cache()
free, available = sample()
Three concrete gains:
- One
if sharedinstead of three, onedevice_memory_info(...)[0]call site instead of two. The twomin(...)clamps become a single expression used at both sample points; the discrete path stops having a different resampling policy from the shared path. - It removes the discrete/shared asymmetry. Today, after a discrete flush,
freeis refreshed (:58) whileavailablekeeps its pre-flush value (:51) — and those are exactly the two numbersallocate_workersmultiplies/decrements together (compile_pool.py:75-86). Refreshing both is the direction the PR argues for everywhere else; the helper makes it the default instead of a special case. - It cuts host sampling from 4 reads to 2.
available_bytes()reads/proc/meminfoand calls_cgroup_available_bytes(), which reads/proc/self/cgroupand/proc/self/mountinfo(host_memory.py:82-100,:51-79) — three file reads per call.mainmade 2 calls per invocation (compile_pool.py:45plus the one insidedevice_memory_infoat:46); head makes 4 when the flush fires (:51, inside:52, inside:58,:60), which per S1 is the normal path on GB10. Moreover, on POSIX integrated the recomputation is provably redundant:device_memory_infoalready returnsmin(total, available_bytes())(host_memory.py:107-109), somin(host_memory.available_bytes(), free) == freealways — the clamp only does work on the Windows path (os.name == "nt"skips the fold), whose only coverage is a mock, and theif shared:at:59is therefore the one place that matters and theif shared:at:53is not needed at all iffreeis used for the POSIX decision.
Note, to keep the review honest: there is no existing repo helper for "flush then resample". ignition/preparation/tuning.py:598-603 flushes device memory plus empty_host_cache() for the tuning subsystem, core_storage.py:254-292 flushes at pool retirement, ignition/direct/executor.py:114 (not opened) is unrelated, and memory_inventory.py only samples. S2 is intra-function deduplication, not reuse of an existing abstraction — do not overclaim it as duplication of a repo primitive.
Already lean — do not touch
ignition/preparation/aot.py:1067-1074(+2/−1). One call inside the existingtry/except, beforedist.barrier(group=group)(:1074); a failure is folded intoerrorand reported through the collective failure list at:1083-1085, so barrier progress and error reporting are preserved. No wrapper, no flag, no helper needed; the comment reword at:1073is a consequence of the change, not comment churn. The cross-rank bug it fixes ("peers sample before other ranks return cached segments") is solved entirely here plus the resample.- Hoisting
worker_bytes(:48) andheadroom(:49) out of the return tuple (base:57-59): both are now consumed twice (trigger + return), so the locals are justified — no duplication introduced. CompilerResourcesshape unchanged (:29-35),allocate_workers()untouched (:67-98), no docs/schema/config surface touched, so nothing documented becomes wrong.- No new flag, env var, dependency, fallback layer or extension point anywhere in the diff — the PR is not speculative generality, it is one over-widened condition and one duplicated sampling block.
Minor notes (not blockers)
_DEFAULT_MAX_WORKERS(compile_pool.py:26) is used twice today (:50,:63); after S1 it has a single use at:63, i.e. it becomes an extraction frommain's literalmin(8, capacity)performed purely to serve the widening. Consequence of S1, not a separate ask; keeping it is harmless.assert state["host_samples"] == 1exists only in the discrete test (tests/preparation/test_compile_pool.py:622), so "resampled exactly once" is not actually pinned on the shared path where the behaviour changes. If S1/S2 land, that assertion (or its absence) is worth one line._patch_compiler_memory(tests/preparation/test_compile_pool.py:538-566) re-does monkeypatch boilerplate that the existing tests above it already write inline (:21-24,:33-37); folding the older two onto the new helper would be a net reduction, but it is test tidying the PR is not obliged to do.- No docs line is added, while comparable PRs in this area (#597, #122) touched
docs/model-preparation.md(not opened) /docs/preparation-development.md;docs/model-preparation.md:489-495(not opened) (DGX Spark) is the natural home for "cached allocator segments are reclaimed before admission". Optional, and consistent with S1's "keep it minimal" direction.
Open questions
- Was the widening measured anywhere (compiler wall-clock, flush cost) on a non-GB10 host, or on a discrete SM103/SM120 layout? The description reports none, and after the change the flush is unconditional on GB10 and new on discrete.
- If the widening is kept, is the double flush (
aot.py:1070thencompile_pool.py:57) intended, and shouldaot.py:1070be dropped instead? The two changes solve the same problem twice. - Should
availablebe resampled after a discrete flush for consistency with thecapacitythat does grow (compile_pool.py:58vs:56/:61)? S2 assumes yes. - Landing order against draft #639, which rewrites the same
compiler_resourcesbody and changes_DISCRETE_WORKER_DEVICE_BYTESfrom 1 GiB to 704 MiB —tests/preparation/test_compile_pool.py:608((2, 4, None, 6)⇒ capacity 6) and:610((9, 4, 12, 13)) both break under 704 MiB. Whichever lands second must rebase; deleting the widening's tests (S1) removes most of the conflict surface. - No isolated
main-vs-PR or A/B measurement exists; the live evidence is a three-branch stack (#635 +local-inference-lab/hyperflare-recipes#103+ this), so no number here can be attributed to #641 alone.