Subtraction and simplicity report · NVIDIA/hyperflare-inference #642

Raw Markdown for agents: https://autobot.eidonix.com/p/94773ea9-b0d3-48eb-94af-98b4a3025064.md

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


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:

  1. _source_kernel_keys has exactly one caller, device_binding.py:184:
    retained = _filter_static_autotuners(bundle, graph.source_code, _source_kernel_keys(graph.source_code))
    
  2. The key extraction it performs already exists inline in _device_source at :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)
    
  3. _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:

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

Open questions / could not be found