Subtraction, Simplicity & Conventions review — PR #639
Key findings
The diff is lean in structure (+58/−18, 4 files, no new function, class, parameter, CLI flag, plan field, env var, or dead code left behind), but it is not lean in knobs. Each of its three code hunks adds a hardcoded number or a defensive branch, and one of them silently overrides a configured setting. Four suggestions, ranked — #1 is the one to drop outright rather than merge:
- Delete the 1 GiB discrete
compile_reservecap (ignition/preparation/compile_pool.py:48-55). It buys a temp variable used in exactly the two places that wereheadroom_bytes, overrides the caller's configured headroom, and the 704 MiB estimate alone already delivers most of the worker-count win. Delete-not-patch: main's four lines come back verbatim. - Collapse the thread-policy block to
cpu_workers() // self.workers(compile_pool.py:137-144): it re-derives a count the file already imports a helper for, and carries two provably dead defences (hasattr(os, "cpu_count"),max(1, self.workers)). Six lines → three. - One
compile_threadsauthority, not four (aot.py:903can useself.options['compile_threads'];aot.py:688still says1and the PR leaves it there without a word).aot.pyshould not ship two conflicting policies. - Two test assertions re-implement the implementation formula (
test_compile_pool.py:28,test_forward_compile_options.py:282), so they pass for any formula; both parametrizations are 8. The new 9-lineprepare_manytest collapses to one assertion once #3 lands.
Everything else in the diff is idiomatic and should be left alone (listed at the end); the if os.name != "nt": platform branch is legitimate, and the 704 << 20 constant matches the module's byte-constant style.
Suggestion 1 (highest value) — delete the 1 GiB cap; don't ship a fallback layer over a configured setting
ignition/preparation/compile_pool.py:48-55, verbatim at head:
device_bytes = _WORKER_DEVICE_BYTES if shared else _DISCRETE_WORKER_DEVICE_BYTES
# Integrated GPUs share physical memory with the host; discrete compile workers exit before
# runtime allocations, so cap their device-side reserve at 1 GiB.
compile_reserve = headroom_bytes if shared else min(headroom_bytes, 1024 << 20)
if free - compile_reserve < device_bytes:
torch.cuda.empty_cache()
free = device_memory_info(device)[0]
capacity = max(0, (free - compile_reserve) // device_bytes)
Main's block (the − lines of the diff) is the same code with headroom_bytes in both places and no temp variable:
if free - headroom_bytes < device_bytes:
torch.cuda.empty_cache()
free = device_memory_info(device)[0]
capacity = max(0, (free - headroom_bytes) // device_bytes)
Concretely: delete the compile_reserve variable and its two-line comment; restore headroom_bytes at both uses. Keep _DISCRETE_WORKER_DEVICE_BYTES = 704 << 20 and the whole thread/start-method change — those are separable and defensible.
Why this is the one to drop:
- The variable buys nothing.
compile_reserveis read in exactly the two expressions on:52and:55, both of which wereheadroom_byteson main. Theif/elseonsharedalready exists one line above fordevice_bytes(:48), so the cap adds a second device-class conditional to a five-line function. - It silently overrides the only declared runtime reserve.
headroom_bytesis the caller's configured runtime/KV headroom (bootstrap.py:35(not opened) defaults4 << 30;:134passesplan.headroom_bytes + plan.reserve_bytes).AGENTS.md:456-460: "A setting has one of three homes: the recipe declaration, the configuration file, or a command-line flag … so the plan, its printed report, and its recorded measurements describe what was prepared." A hardcoded1024 << 20that wins over that setting is recorded nowhere.AGENTS.md:182-186("Reject weakened guarantees … do not … silently substitute execution paths … or relax … bounds") is directly on point, and:188-190bars "fallback layers … without a concrete requirement." - It creates a device/host asymmetry inside one function.
:62deliberately leaves the host side alone —max(host_memory._HEADROOM_BYTES, headroom_bytes if shared else 0)— so the same configured number is capped on the device side and floored at 8 GiB on the host side. If the host-RAM side is out of scope (dossier finding 7), so is the device-side cap for the same reason. - The worker-count win mostly survives without it. With
device_bytes = 704 MiB: 12 GiB free / 2 GiB headroom →(12288−2048)//704 = 14workers vs main's 10; at the 4 GiB default → 11 vs main's 8. The cap turns 14 into 16. That is the entire delta, and it is the change that forces the if/else rewrite oftest_compilation_preserves_configured_headroom(tests/preparation/test_compile_pool.py:440-452) — a test whose whole job was to pin that a configured headroom is honoured.
Related, and worth saying in the same review comment: hunk 1 is also the hunk that makes this three PRs in one (device estimate + reserve cap + thread/start-method policy). AGENTS.md:198: "Keep each PR focused on one coherent outcome."
Suggestion 2 — collapse the thread block; it duplicates host_memory.cpu_workers() and carries two dead defences
ignition/preparation/compile_pool.py:137-144, verbatim at head:
# Partition CPU compile threads across admitted workers and use Inductor's subprocess
# pool on POSIX because CompilePool workers run inside spawned SubprocPool processes.
cpu_count = os.cpu_count() if hasattr(os, "cpu_count") else None
inner_threads = max(1, min(8, (cpu_count or 1) // max(1, self.workers)))
worker_options = dict(options, compile_threads=inner_threads)
if os.name != "nt":
worker_options["worker_start_method"] = "subprocess"
self.options = worker_options
Replacement (6 lines → 3):
# Inductor's parallel compile worker needs a subprocess start method inside our spawned pool.
threads = max(1, min(8, cpu_workers() // self.workers))
self.options = dict(options, compile_threads=threads)
if os.name != "nt":
self.options["worker_start_method"] = "subprocess"
Four separate reductions, each with its proof:
hasattr(os, "cpu_count")is a fallback with no consumer.os.cpu_countexists on every platform CPython supports. It exists solely sotests/preparation/test_compile_pool.py:470—monkeypatch.setattr(compile_pool, "os", SimpleNamespace(name="nt")), aSimpleNamespacewith nocpu_count— keeps asserting(pool.workers, pool.options["compile_threads"]) == (1, 1)at:476. That is a mock shaping production code, whichAGENTS.md:194-196rejects: "mocks that bypass the behavior cannot establish runtime correctness." Delete the guard and fix or drop the mock; Windows thread partitioning is untested either way (the assertion still passes through the fallback).max(1, self.workers)is unreachable.:134-135already raised:if type(workers) is not int or workers < 1: raise ValueError("forward compiler pool requires a positive admitted worker count"). Six lines above it.(cpu_count or 1)re-derives an existing helper.cpu_workers()is already imported in this very file —compile_pool.py:20:from .host_memory import cpu_workers, device_memory_info— and is already used for the worker budget at:42:limit = min(cpu_workers(compile_workers), cpu_workers()).ignition/preparation/host_memory.py:31,35already does the affinity mask, thehasattrfallback, theor 1, and themax(1, ...):
Using rawavailable = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() or 1 ... return max(1, budget // pools)os.cpu_count()here budgets processes from the affinity mask and threads from the whole machine — exactly the divergence thattest_explicit_forward_workers_are_bounded_by_cpu_affinityexists to prevent (dossier finding 5). Deleting the raw call also removes the need for themonkeypatch.setattr(compile_pool.os, "cpu_count", ...)lines attests/preparation/test_compile_pool.py:25,382,398,548; those become patches ofhost_memory.os.sched_getaffinity, the pattern already used intests/preparation/test_host_memory.py.- The
worker_start_methodoverride restates an existing option key. It is not a new key —ignition/preparation/compilation.py:31-32already sets_OPTIONS['worker_start_method'] = 'spawn'onnt, anddict(options, ...)inherits it everywhere else. So the non-Windows branch is the only live case, and it can be one line. Not worth its own comment beyond noting the duplication: the point is that this block is 8 lines for what is genuinelycpu_workers() // workersplus one POSIX flag.
The min(8, ...) cap itself is a fifth hardcoded number and worth a sentence in review — 8 is the worker cap at :57 reused as a thread cap with no comment saying why 8.
Suggestion 3 — one compile_threads authority, not four; and resolve the site the PR left at 1
ignition/preparation/aot.py:901-903, verbatim at head:
# Allow fallback/binding compilation to parallelize up to the host CPU budget.
lock = nullcontext() if _locked else self._publication_lock(coordinator)
with lock, torch._inductor.config.patch(compile_threads=min(24, os.cpu_count() or 1)):
compile_threads now has four authorities in ignition/preparation/ (plus a fifth in scripts/inspect_forward_kernels.py:83 (not opened)):
| site | value |
|---|---|
compilation.py:30 |
min(16, os.cpu_count() or 1) — the configured default carried into every worker via _OPTIONS |
compile_pool.py:140 |
max(1, min(8, cpu_count // workers)) |
aot.py:903 (this PR) |
min(24, os.cpu_count() or 1) |
aot.py:688 (not touched) |
1 |
scripts/inspect_forward_kernels.py:83 (not opened) |
1 |
Concretely: the cache already holds the configured value and always has the key — aot.py:823: self.options = MappingProxyType(_compile_options(options)), and compilation.py:35-36 guarantees _compile_options returns {**_OPTIONS, **options}. So:
with lock, torch._inductor.config.patch(compile_threads=self.options['compile_threads']):
That deletes the fourth cap, the raw os.cpu_count(), and the standalone 24. (Note aot.py:825 strips compile_threads from the cache key, so no compiled forwards are invalidated by this choice either way.)
The PR leaves the sibling policy behind, and that is a structural problem, not a nitpick. aot.py:687-688:
def materialize_for_capture(self):
with _guard_code_cache(self.cache.root / 'guards'), torch._inductor.config.patch(compile_threads=1):
That is the same binding/load path the new comment on :901 says should "parallelize up to the host CPU budget". Shipping =1 and =min(24, cpus) in one file, with neither comment mentioning the other, leaves a reader unable to say what the file's policy is. Pick one: either materialize_for_capture takes self.cache.options['compile_threads'], or the 24 is withdrawn. The PR describes the prepare_many change but not the one it declined to make, so this reads as an oversight.
Follow-on doc drift (structural, per AGENTS.md:188-192 — don't leave stale claims): docs/preparation-development.md:317-318 still says
compilation uses memory-bounded parallel workers on both integrated and discrete
GPUs; artifact binding starts no additional compiler pool.
which describes main's =1 policy and is contradicted by :903 starting up to 24 in-process Inductor threads during binding and warmup. Also relevant to the shape of the new formula: docs/preparation-development.md:314-316 states the principle "Detects integrated GPUs and budgets compiler workers and tuning races against available system RAM" — the new per-worker thread formula is bounded by CPU count only, with no memory term, departing from the module's own rule (and from f9aec99c/468415d1, which bound Inductor threads by the RAM workers leave).
Suggestion 4 — two test assertions mirror the implementation formula
tests/preparation/test_compile_pool.py:28:
assert pool.options["compile_threads"] == min(8, 16 // expected)
tests/preparation/test_forward_compile_options.py:282:
assert pool.options['compile_threads'] == max(1, min(8, (os.cpu_count() or 1) // max(1, pool.workers)))
Both recompute the production expression, so they pass for any formula of the same shape and pin nothing. In the first, expected is 2 or 1 (the parametrization at :16), so 16 // expected is 8 or 16 and both clamp to 8; in the second the value is also 8. Replace both with == 8 (or a literal measured against a comment), which is what the changed parametrization at :374-377 already does correctly — [(None, 95, 8, 8), (None, 3, 4, 8), (32, 95, 32, 2), (32, 3, 4, 8)] pins literals with the arithmetic in a comment. That is the convention to follow.
And tests/preparation/test_forward_compile_options.py:333-341, the new 9-line test:
def test_prepare_many_scales_inductor_compile_threads_with_cpu_count(caches, monkeypatch):
observed = []
monkeypatch.setattr(aot.os, 'cpu_count', lambda: 64)
monkeypatch.setattr(
aot.ForwardCache,
'_prepare_many',
lambda self, *args, **kwargs: observed.append(torch._inductor.config.compile_threads) or {},
)
caches().prepare_many({}, {})
assert observed == [24]
Under suggestion 3 the value under test is self.options['compile_threads'], already asserted at :282; this becomes one line next to it (or disappears). As written it also hard-codes 24, so it must change with suggestion 3 regardless.
What is already lean — do not flag
_DISCRETE_WORKER_DEVICE_BYTES = 704 << 20(compile_pool.py:25) matches the module's byte-constant style (_WORKER_DEVICE_BYTES = 2 << 30,:23) and replaces a comment that was already stale ("about 0.7 GiB … next to a1 << 30value). No wrapper, no flag, no accessor. Keep. (Whether 672 MiB is a safe measurement is a claims question, not a simplicity one.)- No new API surface anywhere: no function, class, parameter, CLI flag, plan field, or environment variable, so there is nothing to reject under
AGENTS.md:180-181. - The
if os.name != "nt":platform branch itself is legitimate — it mirrors existing branches atcompile_pool.py:157-160andcompilation.py:31-32. Only its unconditional-ness and duplication are worth a mention inside suggestion 2. test_compile_pool.py:43-45and:374-377pin literals with the arithmetic in a comment — correct convention.- The test rewrite at
test_compile_pool.py:545-551(monkeypatch.setattr(compile_pool.os, "cpu_count", lambda: 8);== 4) is a clean, literal assertion.
Conventions invoked (structural only)
AGENTS.md:182-186— reject weakened guarantees (suggestion 1).AGENTS.md:188-190— no fallback layers or configuration switches without a concrete requirement (suggestions 1, 2).AGENTS.md:194-196— mocks that bypass behaviour cannot establish runtime correctness (thehasattrguard grown fortest_compile_pool.py:470).AGENTS.md:198— keep each PR to one coherent outcome (hunk 1 is a third concern).AGENTS.md:456-460— a setting has one of three homes and must be described in the plan (the 1 GiB and 24 caps are recorded nowhere; the same "unrecorded switch" objection Autobot raised on #509).
Out of scope for this lens
Deliberately not raised here (other lenses own them): the absent artifact for the 672 MiB figure, CI failing on 3400e3a, the missing main baseline for 359.8 s, the 10→16 silent worker-count rise, the affinity divergence as a correctness defect (cited above only as the reason to use the existing helper), and Windows being untested.
Open questions
- Why was
DeferredCompiledForward.materialize_for_capture'scompile_threads=1(aot.py:688) left alone — is=1still the intended policy for the capture path? If yes, the 24 on:903needs a comment saying why binding and binding-for-capture differ. - Is the 8 GiB host headroom floor on discrete hosts (
compile_pool.py:62) still deliberate? If so, the device-side 1 GiB cap is an unexplained asymmetry in one function. - What is the intended single authority for
compile_threads— the configured_OPTIONSvalue (compilation.py:30), or the pool-derived partition? Suggestion 3 assumes the former; the PR's owncompile_pool.py:42-44uses the configured value only as a worker-count cap. - Does #597's
groups=work inallocate_workersassume the one-thread-per-worker world that #639 changes? Whichever lands second rebases.