Subtraction, Simplicity & Conventions — PR #642
PR: ignition(preparation): skip unreferenced epilogue candidates in relocate_inductor — jcartu, base main (0a8c20f), head 5f6e6a6, 3 files, +414/−10 (production: +64/−10 across two files).
Scope note: this lens covers removable complexity, duplication and structural convention only. Correctness of the exact-identifier matcher, fail-closed semantics, and the GPU-evidence gap are the Correctness & Contracts lens's material and are not re-litigated here.
Key findings
- Verdict: the production change is lean and should not be rejected on simplicity grounds. No new flags, config knobs, fallback branches, wrapper layers, or speculative generality were introduced. Both new helpers are
_-prefixed and module-private, matching the module's existing_device_source/_freeze_tuning_winnersconvention. One helper is however genuinely redundant (S1) and onereplace()/assignment pair is dead churn (S2). - S1 (high) — three AST walks where one would do.
_source_kernel_keys(device_binding.py:105-114) duplicates key collection already inline in_device_source(:75-82), is called exactly once (:184), and with_referenced_kernel_names(:92-102) forms two near-identicalast.walkpasses over the shared predicate at :98/:110/:75/inductor_tuning.py:149/scripts/inspect_forward_kernels.py:72. Folding both into one_source_references(source)and makingbound_keysoptional deletes both helpers (−24 lines), removes one full-module parse from every frozen single-load (main's equivalent path parsed nothing at all, main:141-144), and removes the third meaning of the singlebound_keysparameter. - S2 (medium) — a dead assignment and two
replace()calls that buy nothing.device_binding.py:196retained = retained_bundle.static_autotunersis dead:replace(bundle, static_autotuners=retained)passes the same list object and_freeze_tuning_winnersmutates it in place at :164, so the assertionretained is retained_bundle.static_autotunersholds. Bothreplace()blocks (:185-187, :194-196) only changegraph._triton_bundle's object identity on frozen loads — an undeclared behavior change. Mutatingstatic_autotuners[:]in place matches the two existing conventions (:164 andInductorSelections.freeze, inductor_tuning.py:325) and deletes four lines. - S3 (medium) — the 350 new test lines repeat their own scaffolding five to six times. The six-line
CompiledFxGraph.__new__skeleton appears at :250-259 (pre-existing), :348-356, :430-434, :506-511, :564-568, :640-648; therunner.__code__ = compile(...)trick three times (:444-449, :578-582, :650-654); four function-local torch imports in every test body. Two module-level_helpers — the established pattern in this test tree — remove roughly 50 lines. - S4 (minor) — convention.
inductor_tuning.py:166restatesdevice_binding.py:118-119almost verbatim; keep one. The PR description carries a helper-by-helper inventory out of proportion to a 64-line production diff (AGENTS.md:116-121"Avoid exhaustive inventories",:138-139"Scale length to the change"). - Do not "simplify"
InductorSelections.register'sdiscoveredlist. The +3 lines atinductor_tuning.py:146/165/169are load-bearing: two module globals can share onecache_keyand collapse insidebindings(:164), so iteratingbindings.values()would silently drop a tuner. The new test asserts exactly this (tests/preparation/test_inductor_prepared_winners.py:662).
S1 (high) — collapse three AST walks into one; delete _source_kernel_keys
ignition/preparation/device_binding.py:92-130:
def _referenced_kernel_names(source):
"""Collect module identifiers and async_compile.triton kernel names in generated Inductor code."""
names = set()
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.Name):
names.add(node.id)
elif (isinstance(node, ast.Call) and ast.unparse(node.func) == "async_compile.triton"
and node.args and isinstance(node.args[0], ast.Constant)
and isinstance(node.args[0].value, str)):
names.add(node.args[0].value)
return names
def _source_kernel_keys(source):
from torch._inductor.async_compile import CompiledTritonKernels
keys = set()
for node in ast.walk(ast.parse(source)):
if (isinstance(node, ast.Call) and ast.unparse(node.func) == "async_compile.triton"
and len(node.args) > 1 and isinstance(node.args[1], ast.Constant)
and isinstance(node.args[1].value, str)):
keys.add(CompiledTritonKernels.key(node.args[1].value))
return keys
Three facts make this removable rather than merely tidy:
_source_kernel_keyshas exactly one caller,device_binding.py:184:retained = _filter_static_autotuners(bundle, graph.source_code, _source_kernel_keys(graph.source_code))- The key extraction it performs already exists inline in
_device_sourceat:75-82:elif name == "async_compile.triton": from torch._inductor.async_compile import CompiledTritonKernels kernel = node.args[1] rebound = _device_source(kernel.value, original, target) if kernel_keys is not None: kernel_keys[CompiledTritonKernels.key(kernel.value)] = CompiledTritonKernels.key(rebound) _filter_static_autotuners(:117-130) then parses a third time lazily for names:referenced_names = None retained = [] for entry_kernel in bundle.static_autotuners: if entry_kernel.cache_key in bound_keys: retained.append(entry_kernel) continue if referenced_names is None: referenced_names = _referenced_kernel_names(source)
Cost: on the frozen/no-relocate path (:182-188) the source is parsed with _source_kernel_keys unconditionally at :184, and a second time whenever any unbound key is present. On main that path did no parsing whatsoever (main, device_binding.py:141-144):
if freeze_tuning and graph._triton_bundle is not None:
_freeze_tuning_winners(graph._triton_bundle)
if not relocate:
return
Neither the added parse nor its placement is mentioned in the PR description.
Concrete replacement — delete _referenced_kernel_names and _source_kernel_keys outright and reshape the filter so a single walk serves both needs:
def _source_references(source):
"""Kernel keys launchable from generated Inductor code, and the identifiers it names."""
from torch._inductor.async_compile import CompiledTritonKernels
keys, names = set(), set()
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.Name):
names.add(node.id)
elif (isinstance(node, ast.Call) and ast.unparse(node.func) == "async_compile.triton"
and len(node.args) > 1 and isinstance(node.args[1], ast.Constant)
and isinstance(node.args[1].value, str)):
keys.add(CompiledTritonKernels.key(node.args[1].value))
if isinstance(node.args[0], ast.Constant) and isinstance(node.args[0].value, str):
names.add(node.args[0].value)
return keys, names
def _filter_static_autotuners(bundle, source, bound_keys=None):
keys = names = None
retained = []
for entry_kernel in bundle.static_autotuners:
if keys is None and names is None:
keys, names = _source_references(source)
if entry_kernel.cache_key in (keys if bound_keys is None else bound_keys):
retained.append(entry_kernel)
elif entry_kernel.kernel_name in names:
raise ValueError("compiled forward has unbound static Inductor kernels")
return retained
Call site :184 becomes _filter_static_autotuners(bundle, graph.source_code); :192 and inductor_tuning.py:168 are unchanged. Net −24 lines, one AST parse instead of two on the frozen/no-relocate path, and the single bound_keys parameter stops carrying three different meanings (a bindings dict, a kernel_keys dict, and a set from _source_kernel_keys).
I deliberately do not recommend also factoring the ast.unparse(...) == "async_compile.triton" predicate into a shared constant across all five repo sites (device_binding.py:75, :98, :110, inductor_tuning.py:149, scripts/inspect_forward_kernels.py:72): the traversals genuinely differ (node.func vs node.value.func, different argument positions), and AGENTS.md:188-193 warns against refactoring that does not serve the behavior. S1 removes two of the five for free; stop there.
S2 (medium) — delete the dead assignment; stop replace()-ing the bundle
ignition/preparation/device_binding.py:182-196:
if not relocate:
if bundle := graph._triton_bundle:
retained = _filter_static_autotuners(bundle, graph.source_code, _source_kernel_keys(graph.source_code))
retained_bundle = replace(bundle, static_autotuners=retained)
_freeze_tuning_winners(retained_bundle)
graph._triton_bundle = retained_bundle
return
kernel_keys = {}
rebound_source = _device_source(graph.source_code, original.index, target.index, kernel_keys)
if bundle := graph._triton_bundle:
retained = _filter_static_autotuners(bundle, rebound_source, kernel_keys)
if freeze_tuning:
retained_bundle = replace(bundle, static_autotuners=retained)
_freeze_tuning_winners(retained_bundle)
retained = retained_bundle.static_autotuners
Two problems, both removal-shaped:
:196is dead code.replace(bundle, static_autotuners=retained)puts the same list object on the copy, and_freeze_tuning_winnersnever rebinds it — it mutates in place at:164:
Sobundle.static_autotuners[:] = entries.values()retained is retained_bundle.static_autotuners, always. The line exists only because the author forgot that.- The
replace()buys no isolation._freeze_tuning_winnersmutates each entry's kernel in place (:143-164,kernel.inductor_meta = ...,kernel.__dict__.pop(...)), and those kernel objects are shared with the pre-filter bundle. The only observable effect of bothreplace()calls is thatgraph._triton_bundlebecomes a different object on frozen loads — an undeclared behavior change (Discovery Dossier finding 3).
Concrete replacement, following the in-place convention already used at :164 and at InductorSelections.freeze (ignition/preparation/inductor_tuning.py:325):
if not relocate:
if bundle := graph._triton_bundle:
bundle.static_autotuners[:] = _filter_static_autotuners(bundle, graph.source_code)
_freeze_tuning_winners(bundle)
return
and in the relocate branch:
retained = _filter_static_autotuners(bundle, rebound_source, kernel_keys)
bundle.static_autotuners[:] = retained
if freeze_tuning:
_freeze_tuning_winners(bundle)
Deletes four lines, removes the dead assignment, preserves bundle identity across frozen single-loads, and leaves the correct final replace(bundle, ...) at :209-211 as the only bundle copy (which is genuine — it rewrites kernel_artifacts and the rebound cache_keys).
I considered and rejected making _freeze_tuning_winners a pure function returning a new list: it already mutates entry kernels in place regardless, so purity is unattainable without a far larger change.
S3 (medium) — de-duplicate the new test scaffolding (~50 of 350 added lines)
The six-line graph skeleton is repeated verbatim-in-shape across the file. Pre-existing at tests/preparation/test_inductor_prepared_winners.py:250-256:
graph = CompiledFxGraph.__new__(CompiledFxGraph)
graph.compiled_fn_runner = None
graph.device_idxs = OrderedSet((0,))
graph.source_code = ("torch.cuda.set_device(0)\n"
"stream = get_raw_stream(0)\n"
"kernel = async_compile.triton('reduction', " + repr(kernel_source) + ")\n")
graph.cache_key = code_hash(graph.source_code)
and again at :348-356, :430-434, :506-511, :564-568, :640-648. The launcher-stub trick is likewise repeated three times (:444-449, :578-582, :650-654):
def runner():
pass
runner.__code__ = compile("pass", f"/tmp/{graph.cache_key}.py", "exec")
fn = type(runner)(runner.__code__, {"triton_tem_fused_10": bound_tuner})
graph.current_callable = fn
Concrete replacement: add two module-level helpers next to the existing fixtures and call them from all six sites —
def _stored_graph(source_code, bundle):
graph = CompiledFxGraph.__new__(CompiledFxGraph)
graph.compiled_fn_runner = None
graph.device_idxs = OrderedSet((0,))
graph.source_code = source_code
graph.cache_key = code_hash(source_code)
graph._triton_bundle = bundle
return graph
def _generated_callable(graph, tuners):
def runner():
pass
runner.__code__ = compile("pass", f"/tmp/{graph.cache_key}.py", "exec")
graph.current_callable = type(runner)(runner.__code__, tuners)
That fits the tree's convention (module-level _-prefixed helpers, e.g. tests/preparation/test_aot_guards.py:32-50 (not opened), test_inductor_tuning_cuda.py:206, test_capture_order.py:95 (not opened)) and also serves the pre-existing test at :250.
Two things not to change: leave the function-local torch imports where they are (:320-326, :401-404, :473-476, :530-533, :607-610) — that is the file's existing convention (:231) and it keeps CPU collection from initialising torch._inductor; and do not cut the five test functions themselves, which are the only coverage of the peer-rank path.
S4 (minor) — one duplicated comment; a description out of proportion to the change
ignition/preparation/inductor_tuning.py:166-168:
# Epilogue-fusion benchmarking bundles template candidates that final code never names.
if graph._triton_bundle is not None:
_filter_static_autotuners(graph._triton_bundle, graph.source_code, bindings)
restates ignition/preparation/device_binding.py:118-119:
# Epilogue-fusion benchmarking bundles template candidates that final code never names;
# only static autotuners still named in the generated module require an async_compile binding.
Keep the full explanation at the helper (where the rule lives) and drop the copy at the call site, or reduce it to one line about the ordering guarantee it actually documents.
Separately, the PR description is a four-part body plus a helper-by-helper inventory for a 64-line production change, which AGENTS.md:116-121 ("Avoid exhaustive inventories of changed files, preserved properties, buffers, and tests") and :138-139 ("Scale length to the change: a small fix may need only a short paragraph and relevant validation") discourage. Worth a maintainer note, not a blocking one.
What I checked and found already lean
- No subtraction targets in
InductorSelections.register. The change is +3 lines (discovered = [],discovered.append(...), the deferred loop) and buys a testable no-partial-mutation invariant (inductor_tuning.py:146/165/169-175). It is load-bearing:bindings[cache_key] = identity, entries[cache_key], tunerat:164collapses two globals that share one source key, so thediscoveredlist is the only thing preserving both tuners; asserted attests/preparation/test_inductor_prepared_winners.py:662. Do not simplify it to iteratingbindings.values(). - No dead code, no speculative generality, no new configuration surface, no wrapper layer was added by this PR. The two ContextVars (
_DEVICE,_FREEZE_TUNING,device_binding.py:14-15) andbind_device'sfreeze_tuningargument are pre-existing, not introduced here. - No existing repo helper to reuse for the AST work: the only similar code is
ignition/runtime_patches/__init__.py:52(unrelated) andscripts/inspect_forward_kernels.py:70-75(a script, not an importable helper). - The double freeze on the frozen path is intentional, not removable churn.
aot._load_inductorcallsrelocate_inductor(..., freeze_tuning=frozen)atignition/preparation/aot.py:58, then freezes again at:72-76; the second freeze is documented as needed becausedeserialize_bundled_cache_entryat:66rebuilds launchers and adds config defaults ("Torch adds config defaults while rebuilding launchers from a static bundle",aot.py:75). Not a simplification target. - No
AGENTS.mdrule is violated by the production code (:188-193unsupported abstractions/churn;:194-199focused validation); the violations are limited to description scale (:116-121,:138-139).
Open questions / could not be found
- Whether
#597(open, also editsinductor_tuning.py) merges first; the expected conflict with S1/S3 is textual but trivial. - No maintainer reaction to the description length, and no CI on head
5f6e6a6, so the description-scale observation has no precedent ruling attached to it. - Not measured by the author (and not measurable from the diff): the wall-clock cost of the extra full-module AST parse S1 removes on frozen single-GPU loads — plausible per-load impact is small but it is pure addition relative to
main.