Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #597

Raw Markdown for agents: https://autobot.eidonix.com/p/2d1c24ad-153a-48d9-94e6-8f2a0bf02255.md

#1 [high] S1: duplicate cross-architecture gate in InductorSelections.warm is dead code

InductorSelections is constructed with a coordinator in exactly ONE place: ignition/preparation/aot.py:1122 (selections = InductorSelections(self.device, coordinator=coordinator, ...)), inside ForwardCache._prepare_ranks, ~185 lines AFTER aot.py:933-938 already gathered and rejected cross-architecture groups. The other two construction sites pass no coordinator (aot.py:835, aot.py:1256), so self._gather returns [value] and no cross-rank check is possible there. Verified by search of all InductorSelections( sites (aot.py 835/1122/1256, scripts/inspect_forward_kernels.py:93, tests).

So this block (inductor_tuning.py:247-255) is unreachable-by-construction duplication:

        gpu_name, capability = _cuda_device_identity(self.device)
        variant_key = (getattr(bound.owner, 'compilation_variant', 'shared'), gpu_name)
        gathered_variants = self._gather((variant_key, capability, inventory))
        capabilities = {cap for _, cap, _ in gathered_variants}
        if len(capabilities) > 1:
            ordered = sorted(capabilities, key=lambda cap: (cap is None, cap))
            raise RuntimeError(
                f"Inductor warmup spans incompatible CUDA architectures: {ordered}"
            )

It verbatim duplicates the sort key at aot.py:935 ordered = sorted(capabilities, key=lambda cap: (cap is None, cap)) — copy-paste evidence.

Simplification: keep variant_key = (variant, gpu_name) for grouping, gather (variant_key, inventory) (2-tuple, as the loop at :257 expects for variant, identities in ...), drop capability from the payload and delete the 6-line check. The one group-wide architecture gate stays in _prepare_ranks. Nothing in tests breaks semantically except test_mixed_gpu_inductor_keying.py:326-340 (test_inductor_warm_rejects_cross_architecture_ranks), which must be deleted along with it — it asserts a path that no real call can take; the same rejection is already covered by test_cross_architecture_ranks_are_rejected_before_forward_sharing (:266-274).

Also removes 3 shimmed gather-payload elements from _stub_inductor_warm (:277-292) and the (12, 0) capability tuple from every reply list.

#2 [high] S2: allocate_workers keeps an ungrouped branch and a redundant admitted counter

ignition/preparation/compile_pool.py:75-85 keeps two code paths where one suffices:

        if groups is None:
            active_groups = [members]
        else:
            active_groups = [
                subgroup
                for subgroup in (
                    [rank for rank in members if groups[rank] == group]
                    for group in dict.fromkeys(groups[rank] for rank in members)
                )
                if any(counts[rank] for rank in subgroup)
            ]

With groups = hosts (the default), the else branch produces exactly [members]: dict.fromkeys(groups[rank] for rank in members) collapses to the one host name and the comprehension yields members. So replace both with:

        groups = hosts if groups is None else groups
        active_groups = [[rank for rank in members if groups[rank] == name]
                         for name in dict.fromkeys(groups[rank] for rank in members)]
        active_groups = [subgroup for subgroup in active_groups if any(counts[rank] for rank in subgroup)]

(one branch deleted). Existing callers unaffected: CompilePool.__init__ passes none (compile_pool.py:165, single "local" host) and the six test_compile_pool.py:449-517 call sites pass hosts only; behaviour is identical because a host's own group partition is that host.

Second subtraction in the same function: admitted (lines 94, 103, 115) is always len(active_groups) once line 116-118 has passed — the seeding loop increments it at most once per subgroup and raises if a subgroup got nothing. So for _ in range(limit - admitted): (:120) is for _ in range(limit - len(active_groups)):, and the three admitted += 1 statements plus the admitted = 0 initialiser go. The limit < len(active_groups) guard at :89-92 makes the range non-negative.

Also: the fallback branch at :107-115 assigns workers[rank] = 1 instead of += 1 while the first branch uses += 1 — an inconsistency that only holds because a rank appears in exactly one subgroup. Worth making += 1 if kept.

#3 [high] S3: one 'same GPU' rule encoded twice, plus 3x duplicated getattr

The PR invents one grouping concept twice, with two different encodings:

        heterogeneous = len(set(gpu_names)) > 1
        gpu_tag = "".join(ch if ch.isalnum() else "_" for ch in gpu_name).strip("_").lower()

        def _variant(forward):
            base = getattr(forward, "compilation_variant", "shared")
            return f"{base}.{gpu_tag}" if heterogeneous else base
        gpu_name, capability = _cuda_device_identity(self.device)
        variant_key = (getattr(bound.owner, 'compilation_variant', 'shared'), gpu_name)

Two problems, one simplification.

(a) The getattr(forward, "compilation_variant", "shared") idiom is duplicated in three places (aot.py:943, inductor_tuning.py:248, and the pre-existing uses the PR edited at aot.py:1112/1131/1154 which now all route through _variant). Only two raw reads remain; give the forward one home, e.g. a module-level

def forward_variant(forward, gpu_tag=None):
    base = getattr(forward, "compilation_variant", "shared")
    return base if gpu_tag is None else f"{base}.{gpu_tag}"

in inductor_tuning.py next to _cuda_device_identity, and call it from both modules (_variant = partial(forward_variant, gpu_tag=gpu_tag if heterogeneous else None)). That deletes the local closure and makes the two layers visibly share one rule.

(b) Because the two layers encode "same GPU" differently (normalised tag vs raw name), the two equivalence relations can diverge on a name pair that normalises identically. Using the same key on both sides — pass _variant(forward) (already suffixed) into warm via bound.owner or a variant_key argument instead of reconstructing (variant, gpu_name) — removes the second encoding entirely and, with it, the seventh getattr. This is the same edit as scratchpad entry 1: once the capability check is gone, warm needs only one key, and the natural one is the artifact variant name (which is what "equivalent compiled forward variant" already means in the error message at inductor_tuning.py:259).

Note: passing the suffixed name into warm also makes InductorSelections.warm testable without monkeypatching _cuda_device_identity (test file lines 51, 278).

#4 [medium] S4: new test harness duplicates _lending_rank and re-derives gpu_tag

tests/preparation/test_mixed_gpu_inductor_keying.py:23-95 (_prepare_rank) is a second copy of tests/preparation/test_forward_artifact_sharing.py:171-252 (_lending_rank), in a file that already imports four private fixtures from that module (:17).

Duplicated verbatim or near-verbatim (cache + stubs + coordinator):

          aot.ForwardCache._path = recording_path
          aot.ForwardCache._load = lambda self, forward, path, required=False, before_run=None: aot.BoundForward(
              _Artifact(lambda owner: None), forward, True
          )
          aot.ForwardCache._allocation_sizes = lambda self, path: ()

vs test_forward_artifact_sharing.py:224-226:

          aot.ForwardCache._load = lambda self, forward, path, required=False, before_run=None: aot.BoundForward(
              _Artifact(lambda owner: None), forward, True)
          aot.ForwardCache._allocation_sizes = lambda self, path: ()

and the cache = aot.ForwardCache.__new__(...) five-attribute assignment (mixed:58-61 vs sharing:228-231), the coordinator = SimpleNamespace(...) block (mixed:72-79 vs sharing:236-238), and the process spawn/queue/terminate block (_run_prepare mixed:97-121 vs sharing:281-298 / 336-370).

Also a third copy of the production normalization rule inside the test, mixed:65-70:

          if gpu_name in precached_skus:
              heterogeneous = len({name for name, _ in identities}) > 1
              gpu_tag = "".join(ch if ch.isalnum() else "_" for ch in gpu_name).strip("_").lower()
              variant = f"shared.{gpu_tag}" if heterogeneous else "shared"

Duplicating aot.py:940 means the test re-implements the thing it is checking; len(artifacts) == 8 + "max_q" in name already assert the real naming, so the pre-cache only needs the path from the production _variant.

Simplification: add the GPU-identity/precache parameters to the existing _lending_rank (or move the shared harness into test_forward_artifact_sharing.py and import it, as the file already does for _Pool/_Artifact/_replace_gpu_preparation), and drop _prepare_rank + _run_prepare. This also matters mechanically: #584 rewrites test_forward_artifact_sharing.py wholesale, and a second harness built on its private fixtures has to be rebased twice.

#5 [medium] S5: replaced behavior still described in docs/preparation-development.md and model-preparation.md

The PR changes documented behavior in three places and updates none of the documents (AGENTS.md:165-166 makes "inaccurate documentation" a valid contribution basis, and AGENTS.md:226 points TP-preparation changes at docs/preparation-development.md):

Convention finding: the PR adds behavior operators hit at export time (a new ValueError, a narrowed MemoryError, two RuntimeErrors) and no document or docs/TODO.txt entry records it. Either update those three passages or say in the PR why the docs stay as-is.