PR #641: Resample host memory after flushing CUDA cache in CompilePool

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/2ea83afd-e07f-4458-9eb0-fe96d419bf32

Opened by a workflow run, Nov 30, 2026 8:02 AM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: nero- (CONTRIBUTOR; 3 merged/3 closed/3 open in 180 days, two merged PRs in ignition/preparation; Discord: nero) Motivation: On GB10-style unified-memory GPUs, exporting compiled forwards sometimes fails with "no capacity for a forward compiler" even though PyTorch's CUDA caching allocator is sitting on several GiB of host RAM that torch.cuda.empty_cache() would return. This PR flushes that cache before sampling host memory and re-reads the free figures afterwards, so the reclaimed bytes count toward the compiler-worker budget. Scale: +163 / −10 lines in 3 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #641 "Resample host memory after flushing CUDA cache in CompilePool"

Charter alignment. Good. This fixes a reproducible memory-accounting bug in shared runtime code with no new flag, no per-model branch, and no config/artifact/dependency change — inside "PRs that address a reproducible bug or a measured memory issue," and inside the design docs' "release compiler resources before materializing preparation caches" and "account for cached allocator segments." The root cause is verifiable from the diff: main clamps available = min(stale_available, free) after the flush, discarding the reclaimed bytes, and the arithmetic reproduces the reported 8435 vs 8192 MiB failure exactly. Headroom invariants and worker budgets are untouched — unlike the withdrawn #122 lever.

Novelty & status. Not obsolete: no main commit touches the three changed files between branch point and head, and #462 (merged) only added the flush #641 widens. Not superseded: #639 edits the same compiler_resources body but does not address the stale-available cause, and it is a draft with a two-blocker Changes-Requested review. #641 is the small successor that #584's rejection actually asked for — additive, but it cites none of #242/#73/#270/#462/#584, a real gap given five weeks of identical reports.

Value vs maintenance cost. The fix is cheap and general (two call sites, both hardware classes). Evidence is thinner than the description implies: the live run is a three-branch stack (#635 + recipes#103 + this), one model, one layout, TP3 on GB10, so AGENTS.md's "never attribute a combined result to one PR" applies. "Unlocking additional compiler workers" is not backed by its own numbers — [1, 1, 1] comes from the pre-existing 4 GiB fallback, and a second worker still needs ~34 GiB. The flush trigger also widens silently from "one 2 GiB worker doesn't fit" to "the whole worker budget doesn't fit," making empty_cache() near-unconditional on every GB10 preparation and on discrete hosts that never flushed, with no cost measurement. The moved clamp only changes behaviour on Windows, covered solely by a mock; on POSIX it is a no-op.

Verdict: Worth it with changes. Require: (1) reconcile landing order and the 1 GiB vs 704 MiB discrete constant with #639; (2) narrow the flush trigger to what the evidence supports or measure its cost, and resample available on discrete too; (3) drop or correct the "additional workers" claim; (4) cite the #242/#73/#270 family and add the DGX Spark docs line to docs/model-preparation.md; (5) flag the Windows clamp as mock-only.

Full report Decide Value: yes (99%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, priority:P2, bug, performance, area:memory, area:preparation

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +priority:P2, +bug, +performance, +area:memory, +area:preparation

Subtraction and simplicity

PR #641 is small and mostly lean — no new flag, config key, dependency or abstraction, and aot.py's +2/−1 needs no simplification. Two subtractions in compiler_resources() matter.

  1. Delete the widened flush trigger (ignition/preparation/compile_pool.py:55-56, plus the max_workers local at :50) and restore the per-worker test (available - headroom < device_bytes if shared else free - headroom_bytes < device_bytes). The reported case (8435 MiB available, 8192 MiB headroom) already fired on main because host_memory.py:107-109 folds host RAM into free: 243 MiB < 2048 MiB. The bug was only the missing resample at :59-60. The widening is a flat max_workers × worker_bytes = 8 × 34 GiB = 272 GiB threshold versus 121.7 GiB total RAM, so on GB10 empty_cache() becomes unconditional (it holds for any headroom and any recipe; even 4 CPUs gives 136 GiB); it newly flushes discrete hosts — the pre-existing test at tests/preparation/test_compile_pool.py:39-41 (12 GiB free, 2 GiB headroom, compile_workers=32) now flushes silently; and it makes the PR's own aot.py:1070 flush redundant, giving two empty_cache() calls per rank per preparation. It also duplicates the real admission rule in allocate_workers (:78-86). AGENTS.md:188-193 rejects such unmeasured churn. Deleting it removes ~4 of the 5 new mocked tests (test_compile_pool.py:569-592, :605-623, :626-642), keeping the resample assertion (:591), the Windows clamp test (:595-602) and the good ordering test (:645-682).

  2. Collapse the duplicated sample/clamp — min(available, free) appears twice (:53-54, :59-60) and available_bytes() is read 4× when the flush fires (vs 2 on main), each call being three file reads (host_memory.py:82-100, :51-79). A 4-line local sample() returning (free, min(available_bytes(), free) if shared else available_bytes()) gives one if shared instead of three and also fixes the asymmetry where a discrete flush refreshes free but not available — the two numbers allocate_workers multiplies (:75-86). No existing repo helper to reuse; this is intra-function dedup.

Minor: _DEFAULT_MAX_WORKERS only needs extracting because of item 1; state["host_samples"] is pinned only on the discrete path (:622). Open: whether the widening was measured anywhere; whether the double flush is intended; landing order against draft #639, which changes the 1 GiB discrete constant and breaks both new discrete test params.

Full report · Notes

Correctness and contracts

PR #641's ordering and failure propagation are correct; the problems are an undisclosed near-unconditional flush and two claim-accuracy defects.

Open: no isolated main-vs-PR or cost measurement; landing order vs #639 (its 704 MiB discrete constant invalidates test_compile_pool.py:605-623); whether a docs line belongs in docs/model-preparation.md:489-495; and confirmation that the unqualified empty_cache() at the new call site runs with self.device current (unverified, not claimed as a defect).

Full report · Notes

Final review

Recommendation: Ready To Merge

PR #641 cleanly fixes a verified memory-accounting bug in compiler_resources() and a peer-rank flush ordering gap in ForwardCache._prepare_ranks() without relaxing any headroom invariant, worker budget, or artifact/API contract. The core resample logic, widened worker-cap flush triggers, deadlock-free collective error propagation, and isolated CPU unit tests are all verified sound at head d82fcfc. Only minor optional simplifications (avoiding a redundant second empty_cache() / duplicate POSIX available_bytes() reads) and confirming .github/workflows/python-cpu.yml (not opened) CI is green on d82fcfc remain before merge.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

None.

Subtract / Simplify

  1. Optional: avoid the redundant second torch.cuda.empty_cache() on multi-rank (ignition/preparation/aot.py:1070, ignition/preparation/compile_pool.py:55-57). In ForwardCache._prepare_ranks(), every rank already runs torch.cuda.empty_cache() at aot.py:1070 before dist.barrier(group=group), then immediately calls compiler_resources() at aot.py:1076. Because max_workers * worker_bytes is 272 GiB at defaults on unified memory (and 8 GiB on discrete), compile_pool.py:57 immediately invokes a second no-op flush and resamples memory. Allowing _prepare_ranks() to skip re-flushing (e.g., an internal flush_cache=False kwarg, keeping flush_cache=True for single-rank CompilePool.__init__ at aot.py:921 / compile_pool.py:133) avoids the duplicate flush and extra sample pass.
  2. Optional: skip redundant POSIX available_bytes() reads on unified memory (ignition/preparation/compile_pool.py:51-60). On POSIX integrated GPUs, device_memory_info(device) already returns min(total, available_bytes()) (ignition/preparation/host_memory.py:107-110), so calling host_memory.available_bytes() separately before and after device_memory_info() reads /proc/meminfo, /proc/self/cgroup, and /proc/self/mountinfo (host_memory.py:51-100) four times per call instead of two. Matching host_memory.py:154-158 / :177-179 (free = device_memory_info(device)[0]; available = min(host_memory.available_bytes(), free) if os.name == "nt" else free when shared is true) halves procfs reads on Linux while preserving identical POSIX and Windows behavior.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: yes (80%): Testing will add considerable value with the code. It is ready to merge and the tests will validate and improve confidence on hardware we have available for testing.

Pre Test Report

Hardware test plan — PR #641: resample host memory after flushing the CUDA cache

1. Bottom line

Two hardware runs matter, and they cost about 2 hours of GPU time on cn7 and 40 minutes on cn4's cn5 node:

Machine What it uniquely proves Why it is the right box
cn7 (GB10, SM121, integrated/unified) The actual bug: torch.cuda.empty_cache() is called, host memory is re-sampled afterwards, the reclaimed bytes reach worker admission, preparation does not crash, and the new near-unconditional flush has no measurable cost Only integrated-memory GPU we have. torch.cuda.get_device_properties(...).is_integrated is true here and false everywhere on cn5, so this is the only machine that executes lines compile_pool.py:59-60 and the only one that ever hits the widened trigger on unified memory
cn5 (4× RTX PRO 6000 96 GiB, SM120, discrete) Zero-cost control for the widened trigger on discrete GPUs, plus live proof that the new aot.py:1070 flush-ordering change works on real CUDA 96 GiB of free VRAM means the discrete gate (compile_pool.py:55-56: free - headroom_bytes < 8 GiB) is false, so the PR must add zero flushes. Any flush there is a regression

Do not plan an A/B timing experiment to "measure the claimed speedup". There is no speedup in this change: the motivation is an export that used to fail with MemoryError (compile_pool.py:96-97, "no capacity for a forward compiler") and now fits. The case file and final review both flag the author's "unlocking additional compiler workers" wording as unsupported by their own [1,1,1] numbers. The metric that matters is flush count, success/failure, and wall-clock parity, not tokens/s. A tokens/s benchmark would burn GPU time measuring nothing (the serving hot path is untouched — allocate_workers() and CompilerResources are byte-identical in behavior).

Also note two hard limits so nobody over-claims afterwards:

2. Scenarios to test (ranked, with the reason each is worth GPU time)

S1 — cn7: flush count + host resample on unified memory (highest value, ~6 min, no model, no weights)

Exercises compile_pool.py:46-64 on a real integrated GPU with zero model download. A throwaway script (no repo edit) counts flushes and records what the sampler sees in three states: (a) clean, (b) after allocating a large CUDA tensor and freeing it to the caching allocator, (c) after the pool is sized.

# on cn7, repo at PR head d82fcfc, same checkout for both arms
cd ~/hyperflare-inference && git checkout -q d82fcfc && uv sync --extra prepare --extra test

cat > /tmp/probe641.py (not opened) <<'EOF'
import argparse, torch, sys
from ignition.preparation import compile_pool as cp, host_memory as hm

p = argparse.ArgumentParser(); p.add_argument("--headroom-gib", type=int, default=4)
p.add_argument("--balloon-gib", type=int, default=0); a = p.parse_args()
flushes = []
real = torch.cuda.empty_cache
def counted():
    flushes.append(1); real()
torch.cuda.empty_cache = counted                       # count only; behavior unchanged

dev = "cuda:0"; total = torch.cuda.mem_get_info(dev)[1]
print("integrated", torch.cuda.get_device_properties(dev).is_integrated,
      "total GiB", total / 2**30, "MemAvailable MiB", hm.available_bytes() >> 20)

balloon = torch.empty(int(a.balloon_gib * 2**30), dtype=torch.uint8, device=dev) if a.balloon_gib else None
if balloon is not None: balloon.zero_()
before = (hm.available_bytes(), hm.device_memory_info(dev)[0])
r = cp.compiler_resources(dev, headroom_bytes=a.headroom_gib << 30)
after = (hm.available_bytes(), hm.device_memory_info(dev)[0])
print(f"flushes={len(flushes)} available {before[0]>>20}->{after[0]>>20} MiB free {before[1]>>20}->{after[1]>>20} MiB")
print("resources capacity=%d available=%d MiB limit=%d worker_bytes=%d headroom=%d MiB"
      % (r.capacity, r.available >> 20, r.limit, r.worker_bytes >> 20, r.headroom >> 20))
try:
    print("admitted", cp.allocate_workers([r], [r.limit], ["host"]))
except MemoryError as e:
    print("MemoryError:", e)
EOF

# PR arm
.venv/bin/python /tmp/probe641.py (not opened) --headroom-gib 4
# main arm (same script, behavior of main/compile_pool.py (not opened))
git stash -q && git checkout -q main && uv sync --extra prepare --extra test -q
.venv/bin/python /tmp/probe641.py (not opened) --headroom-gib 4

Expected (per the code): PR flushes=1; main flushes=0 (on integrated, main gates on free - headroom_bytes < 2 GiB, and free already equals the MemAvailable-capped value, host_memory.py:107-109). PR available after > before by the allocator-cached host bytes; main's available unchanged. Both must exit 0 and print an admitted list. A deviation is a finding — e.g. PR flushes=0 on GB10 would contradict compile_pool.py:55 (272 GiB vs 60 GiB).

Then the failure/recovery pair, which is the actual bug and the one run that reproduces MemoryError cheaply. No model, no compiler workers — ~2 min per arm:

# push `available` into [8,12) GiB: main's floor needs 4 GiB and never flushes, so this raises MemoryError
.venv/bin/python /tmp/probe641.py (not opened) --headroom-gib 8 --balloon-gib 46      # PR arm
# then the same with `git checkout main` built as above                  # main arm

Tune --balloon-gib in 2 GiB steps so the printed available lands in [8,12) GiB; record the value each arm needs. Pass: PR exits 0 (flushes, resamples, admits 1 worker via the floor at compile_pool.py:87-94); main raises MemoryError quoting available/headroom in MiB. This is the defensible before/after evidence the PR is missing, obtained in minutes instead of a 22-minute export.

S2 — cn7: real TP1 export, both arms, byte-identical settings (the end-to-end check, ~15–25 min/arm)

Proves the change survives the real pipeline (bind → warm → capture → publish), not just a direct function call. Model: google/gemma-4-e4b-it (on cn7). Pin the same recipes commit for both arms — official recipes live in the external local-inference-lab/hyperflare-recipes (docs/model-preparation.md:310-314), and the review already dinged the author for evidence from a combined stack.

export RECIPES=/path/to/hyperflare-recipes      # same commit for both arms, record `git -C $RECIPES rev-parse HEAD`
# baseline core name and kernel cache copied to a second prefix so the arms cannot contaminate each other
cp -a ~/.cache/flare/kernels ~/.cache/flare/kernels-warm && cp -a ~/.cache/flare/cores ~/.cache/flare/cores-warm

# ARM A (main)  — pin the clone to main
cd ~/hyperflare-inference && git checkout -q main && uv sync --extra prepare --extra test -q
/usr/bin/time -v .venv/bin/ignition export google/gemma-4-e4b-it --gpus 0 --verbose \
  --config ~/.config/flare/config.toml (not opened) 2>&1 | tee /tmp/export-main.log
# record: final core path, "compiler workers" line, elapsed, Maximum resident set size

# ARM B (PR)   — restore caches to the pre-A state, then checkout d82fcfc
rm -rf ~/.cache/flare/{kernels,cores} && cp -a ~/.cache/flare/kernels-warm ~/.cache/flare/kernels \
  && cp -a ~/.cache/flare/cores-warm ~/.cache/flare/cores
git checkout -q d82fcfc && uv sync --extra prepare --extra test -q
/usr/bin/time -v .venv/bin/ignition export google/gemma-4-e4b-it --gpus 0 --verbose 2>&1 | tee /tmp/export-pr.log

(Exports need an unused destination — docs/model-preparation.md:275-282 — so delete or rename the arm-A entry before arm B; the two tee logs preserve the arm-A path. If a faster deterministic loop is wanted, add --autotune-effort off to both arms to remove kernel races from the timing — docs/model-preparation.md:211-214.)

Pass criteria: both arms succeed; the admitted-worker line (aot.py:1088 prints N compiler workers; per rank [...]) is identical; arm B wall clock within ±10 % of arm A (marginally faster is the expected direction, since arm A can fail here); arm B's peak MemAvailable dip is no worse than arm A's. Distribution evidence for the flush (NVML reports no VRAM on GB10, docs/model-preparation.md:489-495, so watch host memory): while sleep 2; do grep MemAvailable /proc/meminfo; done beside each arm. Fail: arm B slower by >10 %, or fails, or admits fewer workers.

S3 — cn5: discrete zero-cost control + live flush-ordering (2 short runs)

cd ~/hyperflare-inference && git checkout -q d82fcfc
# (a) discrete: the widened trigger must NOT fire — zero added flush, unchanged free/available
.venv/bin/python /tmp/probe641.py (not opened) --headroom-gib 4          # expect flushes=0 on 96 GiB free
# (b) live CUDA exercise of aot.py:1070 (release_unused -> empty_cache -> barrier -> compiler_resources)
CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/python -m pytest -q \
  "tests/preparation/test_inductor_tuning_cuda.py::test_cooperative_vision_validation_freezes_and_restores[single]"
# (c) true multi-rank path (real coordinator => _prepare_ranks) on two GPUs, torchrun local:
CUDA_VISIBLE_DEVICES=0,1 FLARE_RUN_CUDA_TESTS=1 FLARE_RUN_TP_CUDA_TESTS=1 \
  .venv/bin/torchrun --nproc_per_node=2 -m pytest -q \
  "tests/preparation/test_inductor_tuning_cuda.py::test_cooperative_vision_validation_freezes_and_restores[tp2]"

(c) matters because no local multi-GPU export on cn5 reaches _prepare_ranks (a coordinator is built only by the multi-host ignition export --ranks N --rendezvous path or by these torchrun tests, ignition/cli/serve.py:403-421). These two tests use tiny forwards (a 1024×768 pixel op, a 3072-float vector) and one Inductor function, so they are the cheapest live proof of the new aot.py:1070-1074 ordering. Pass: both green, no hang at the barrier; on failure the run must exit with the collective RuntimeError (aot.py:1084-1085,1130-1131), never hang.

S4 — cn7: the no-flush skip path on integrated hardware (1 test, ~4 min)

tests/preparation/test_capture_order_cuda.py:44 runs capture_forwards with requested_compile_workers=1, so max_workers = 1 and the gate becomes 34 GiB. With ~50 GiB available under the 60 GiB cap the gate is false, so the PR takes the skip branch on a real integrated GPU (the only non-flush integrated coverage in the PR is a mock needing a 300 GiB host — tests/preparation/test_compile_pool.py:626-642).

CUDA_VISIBLE_DEVICES=0 FLARE_RUN_CUDA_TESTS=1 .venv/bin/python -m pytest -q \
  tests/preparation/test_capture_order_cuda.py::test_capture_pool_reuses_larger_compiled_request_on_fresh_and_cached_load

Pass: green, with cache-hit behavior on the second loop unchanged.

S5 — CPU gate, no GPUs, run first (5 min, blocks everything else)

The final review asks for this before merge and it is still unreported on d82fcfc.

CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest tests/preparation/test_compile_pool.py -q   # PR's 5 new tests
CUDA_VISIBLE_DEVICES="" .venv/bin/python -m pytest tests/ -q                                   # = .github/workflows/python-cpu.yml:30-33 (not opened)

The new mock tests are Windows/POSIX + discrete + ordering only; the Windows clamp (os.name == "nt") cannot be validated on any machine we have — record it as unrun rather than passing it.

3. Budget and sequencing

  1. S5 (CPU, 5 min) → S1 probe (~20 min including the balloon pair) on cn7. Stop and report if the PR does not flush, or if main does not raise MemoryError in the balloon case: the premise of the PR is then unproven and an export would waste GPU time.
  2. S2 export pair (~50 min) on cn7. Only if S1 passed.
  3. S3 (a)(b) (~15 min) on cn5; (c) only if a discrete rank-ordering question remains (~10 min).
  4. S4 (~5 min) on cn7, can ride along with S2.

Total ≈ 2 h on cn7 + 25 min on cn5, two model-less probes doing most of the work, one model at one checkpoint size on one layout (TP1) — deliberately not the author's TP3 stack, since the point of hardware here is branch coverage, not re-running their benchmark.

4. Preconditions, confounds, and what not to do

5. Findings the test engineer should confirm or refute (with citations)

  1. On Linux integrated GPUs the moved clamp is inert — host_memory.py:107-109 already returns min(total, available_bytes()), so min(available, free) (compile_pool.py:53-54,59-60) changes nothing on cn7; the substantive fix is the post-flush resample at :60. S1 will show this: the PR's gain must come from available rising after the flush, not from the clamp.
  2. The widened trigger is unconditional on GB10 — 8 × 34 GiB = 272 GiB vs 60 GiB cap (compile_pool.py:48-56). S1's flushes=1 and S2's parity timing are the whole cost argument.
  3. On discrete GPUs at defaults the PR adds zero flushes — 8 × 1 GiB = 8 GiB, free is far above it on a 96 GiB card (compile_pool.py:55-56). S3(a) proves the "newly flushes discrete hosts" concern is limited to low-free or high---compile-workers states.
  4. The MemoryError→success transition is the defensible claim, reproducible with the S1 balloon probe in ~2 minutes, and far cheaper than the PR's own 2.5-second-failure export evidence.
  5. Residual risk that hardware cannot close: the Windows clamp (os.name == "nt") has mock-only coverage (tests/preparation/test_compile_pool.py:595-602) and no machine here runs Windows; draft PR #639 lowers _DISCRETE_WORKER_DEVICE_BYTES to 704 MiB and would invalidate the discrete expectations in tests/preparation/test_compile_pool.py:608-610, so whichever lands second needs a rebase and a re-run of S3.

Detail notes with all citations are in my scratchpad (entries 1–3): code behavior per line, invocation surface, and the machine-to-branch mapping with predictions.

Full report · Notes

Discord Test Request

Discord post (ready to paste)

## Recommendation: Test
(High confidence — ~8/10)

## Hardware Required
- **cn7 (GB10, unified memory):** the only box that hits the actual changed path.
- **cn5 (RTX PRO 6000, discrete):** control run — must add **zero** cache flushes.
- CPU-only suite first (no GPU, 5 min) so we don't burn GPU time on a broken build.

## Justification
- The bug only exists on integrated/unified-memory GPUs, so it can only be proven on cn7 — and cn7 is cgroup-capped at 60 GiB, so the author's exact repro is not reproducible there.
- This change cannot make anything faster: the only risk is cost or regression, so we measure flush count, success/failure and wall-clock parity — not tokens/s.

## Estimated Time to Complete
About **2.5 hours total**: ~2 h on cn7 + ~25 min on cn5 (incl. the 5 min CPU gate).

Note for whoever posts: if they want it even shorter, drop the third "Hardware Required" bullet and the CPU-gate mention in the time line — the template still holds.


What I did

Prepared the post strictly to the given template (Recommendation / Hardware Required ≤3 bullets / Justification ≤2 bullets / Estimated Time), collapsing the ~40-page pre-test report into Discord-sized lines. I did not invent any claim: every bullet traces to the report's own pass criteria and budget.

Verification of the report's technical basis (all confirmed at PR head d82fcfc)

Hooks and safety

No instructions aimed at me appeared in the PR body, comments, or code — the PR/comment content is ordinary engineering text (plus one link to an external review site, which I did not follow). Nothing in the material was treated as an instruction, and nothing from the repository was sent anywhere.

One caveat worth passing on

The scratchpad entries 1–3 that the report cites ("Detail notes… in my scratchpad") are not present in my scratchpad — it was empty, so I could not read them. The report itself is self-contained enough (every claim above was re-verified directly against the code), so the post does not depend on them, but if those detail notes contain anything not in the summary, they were not available to me.

Full report