Correctness and contracts report · NVIDIA/hyperflare-inference #597

Raw Markdown for agents: https://autobot.eidonix.com/p/fd6b017f-2cb3-43ac-b551-7f7ffd8a4469.md

PR #597 — Correctness, Contracts & System-Level Consequences review

Author: brandonmmusic-max · Head reviewed: 1acb1f05 (pr/597) · Files: ignition/preparation/aot.py, ignition/preparation/compile_pool.py, ignition/preparation/inductor_tuning.py, docs/model-preparation.md, docs/preparation-development.md, tests/preparation/test_mixed_gpu_inductor_keying.py

Key findings

  1. Blocker — the mixed-SKU separation stops at compilation. InductorSelections.warm now keys only the inventory check by (compilation_variant, gpu_name), but the frozen-warmup agreement and _reconcile winner election immediately below are untouched and still span all ranks, with identity derived from source+programs+bindings, not GPU. Two same-architecture SKUs (300 W Max-Q vs 450 W Workstation Edition) that tune different configs for one kernel identity still abort the whole launch, or receive each other's cubin. (quotes under F1)
  2. Major — mixed-SKU hosts now hard-fail across ~12–71 GiB of available RAM. Each active SKU group must now be seeded with a full 32 GiB worker, so a 2-SKU host needs 2×32 + 8 = 72 GiB; the author's own test pins [12, 39, 40, 41, 42, 71] GiB → MemoryError. Monotonicity is genuinely fixed; availability regressed widely versus main. Docs state the rule qualitatively but never the 72 GiB consequence.
  3. Major — the documented user-visible contract is wrong. allocate_workers raises ValueError, but _prepare_ranks swallows every exception into a string and re-raises RuntimeError("forward compilation failed: ..."), which the CLI maps to PreparationError. docs/model-preparation.md:241 and the PR description both promise ValueError.
  4. Minor — cross-host sharing got fragile. _share_artifacts now keeps only peer paths whose resolved parent equals self.root; hosts with different cache base paths (different $HOME, mount point, symlinked cache) silently stop sharing, as does anything nested. No diagnostic — just a silent full recompile.
  5. Minor — non-CUDA ranks are masked into the shared group (("", None)) rather than rejected, so a whole group of non-CUDA ranks yields one cache root keyed on "" instead of a clear error.
  6. Minor — the added tests structurally cannot catch F1: they stub _reconcile to a no-op and feed [{}, {}] as the frozen-agreement payload; the CUDA suite that exercises real warm/_reconcile was not run.

Verified sound: per-(host, resolved_root) locking (deterministic, sorted, release in finally), un-suffixed artifact names inside GPU-partitioned roots (so homogeneous↔mixed reuse works), (host, gpu_name)-restricted lending, and groups=None backwards compatibility. Details and citations below.


F1 — Blocker: Inductor winner election and frozen-warmup agreement still span SKUs

ignition/preparation/inductor_tuning.py:244-253 (the PR's change):

    def warm(self, bound, warmup, *, before_run=None):
        bindings = self.forwards[id(bound)][2]
        inventory = sorted({identity for identity, _, _ in bindings.values()})
        gpu_name, _ = cuda_device_identity(self.device)
        variant_key = (getattr(bound.owner, 'compilation_variant', 'shared'), gpu_name)
        variants = {}
        for variant, identities in self._gather((variant_key, inventory)):
            if variant in variants and variants[variant] != identities:
                raise RuntimeError(f"equivalent compiled forward variant {variant!r} has different Inductor kernels")

The steps that actually decide which cubin runs, twelve lines below, were not changed by this PR (inductor_tuning.py:275-289):

        actual, failure = {}, None
        try:
            for identity, _, tuner in bindings.values():
                selected = _selected(tuner)
                actual[identity] = vars(selected.config), selected.kernel.cubin_raw
        except Exception as error:
            failure = f"{type(error).__name__}: {error}"
        self._check(failure)
        gathered = self._gather(actual)
        agreed = {}
        for rank in gathered:
            for identity, selection in rank.items():
                if identity in agreed and agreed[identity] != selection:
                    raise RuntimeError("equivalent Inductor kernels disagree after frozen warmup")

_reconcile (inductor_tuning.py:291-306) then elects one owner per kernel identity across all ranks and broadcasts/installs that single selection into every rank's tuners:

        local = {identity: tuner for identity, _, tuner in bindings.values()}
        inventories = self._gather(sorted(local))
        owners = {}
        for rank, identities in enumerate(inventories):
            for identity in identities:
                if identity not in self.winners:
                    owners.setdefault(identity, rank)

Identity carries no GPU or variant component (inductor_tuning.py:108-114):

def _execution_identity(source_identity, source, device, kernels, bindings=()):
    """Identify executable code without device ordinals or process-local bindings."""
    normalized = _device_source(source, device, 0)
    programs = tuple(sorted((name, pickle.dumps(config, protocol=5),
                             hashlib.sha256(cubin).digest()) for name, config, cubin in kernels))

Impact. The PR's stated failure mode is "different-SKU ranks … fail Inductor kernel-inventory agreement." The inventory check is now per-SKU; the selection agreement is not. Two SKUs whose 300 W vs 450 W power budgets autotune different configs for one shared kernel identity (same source, same programs, same bindings — plausible for the exact hardware pairing in the description) still do one of two bad things: raise RuntimeError("equivalent Inductor kernels disagree after frozen warmup") and abort the entire multi-rank launch, or — if only one rank owns the identity — silently install the peer SKU's winner, which is the cross-SKU leakage the PR set out to remove. Because _install and freeze run after warm (call site aot.py:1147-1154), the abort happens after all compilation and sharing work, i.e. it discards the entire expensive phase.

Concrete fix. Add the GPU product name to the agreement/reconciliation key: build actual[(identity, gpu_name)] = ..., compare only within a group, and make _reconcile compute owners per (identity, gpu_name) so each SKU elects and broadcasts its own winner. Alternatively gate participation in warm by group (each (variant, gpu_name) group reconciles inside its own subgroup), reusing the fact that _prepare_ranks already rejects cross-architecture groups.

F2 — Major: full-worker seeding turns mixed-SKU hosts into a ~12–71 GiB hard-failure band

ignition/preparation/compile_pool.py:91-114:

        remaining = available - headroom
        # Seed one worker per active group so no active SKU on a mixed host is starved.
        for subgroup in active_groups:
            able = [rank for rank in subgroup if workers[rank] < resources[rank].capacity
                    and resources[rank].worker_bytes <= remaining]
            if able:
                rank = min(able, key=lambda rank: (workers[rank], rank))
                workers[rank] += 1
                remaining -= resources[rank].worker_bytes
                continue
            if len(active_groups) == 1:
                # Small forwards can fit below the concurrency estimate. Preserve one worker on
                # a host with a single active group under the minimum allowance.
                ...
        if any(not any(workers[rank] for rank in subgroup) for subgroup in active_groups):
            raise MemoryError(f"host {host!r} has {jobs} missing forwards but no capacity for a forward compiler "
                              f"({available >> 20} MiB available host memory, {headroom >> 20} MiB headroom)")

With FORWARD_WORKER_BYTES = 32 GiB and _HEADROOM_BYTES = 8 GiB (host_memory.py:15-16, priced at compile_pool.py:58-59), two active SKU groups require 2 × 32 + 8 = 72 GiB. The author's own test pins the failure band exactly (tests/preparation/test_mixed_gpu_inductor_keying.py:242-247):

@pytest.mark.parametrize("available_gib", [12, 39, 40, 41, 42, 71])
def test_allocate_workers_is_monotonic_and_rejects_underbudgeted_multi_sku_hosts(available_gib):
    resources = [compile_pool.CompilerResources(1, available_gib << 30, 16, 32 << 30, 8 << 30)] * 4
    groups = [MAXQ, MAXQ, WORKSTATION, WORKSTATION]
    with pytest.raises(MemoryError, match="no capacity"):
        compile_pool.allocate_workers(resources, [2, 2, 2, 2], ["host"] * 4, groups=groups)

and :262-266 pins the 72 GiB admission ([1, 0, 1, 0]).

Impact (system-level / pricing-span). The measured span is unchanged — available = min(resources[rank].available for rank in members) (compile_pool.py:84) still measures whole-host free RAM minus headroom — but the price charged per SKU group is now a full 32 GiB estimate against a forward that may be one small graph. Net effect on the exact 4-GPU SM120 mixed workstation the PR targets: main admitted a compiler worker somewhere in 12–71 GiB free (2 GiB minimum allowance below 40 GiB, one 32 GiB worker at 40–71 GiB), while this branch raises MemoryError for the entire range. Nothing in the code fails over to "one worker, groups serialized," so a 64 GiB mixed host — which serves fine today — now cannot prepare at all. The single-active-group fallback is asymmetric with cache state: test_allocate_workers_admits_single_active_group_under_minimum_allowance (:250-259) and test_cached_sku_withholds_workers_so_compiling_sku_receives_host_budget (:292-305) show the same host succeeding at 10 and 40 GiB once one SKU is fully cached, so whether a given host prepares depends on how warm its cache is — a non-obvious interaction to document and support.

Concrete fix. Keep the anti-starvation guarantee but not at full-estimate cost: seed the second and later active groups with the 2 GiB minimum allowance (the same bound already used for the single-group case, compile_pool.py:104-111) and reserve the full worker_bytes only for the first group / surplus allocation; or admit one worker per host when limit >= len(active_groups) cannot be met by memory, and serialize the groups. Either way, quantify the requirement in docs/model-preparation.md:246-250, which currently states only "hosts with multiple active SKU groups require the full per-worker estimate for each seeded worker" with no number.

F3 — Major: the advertised ValueError never reaches the user

ignition/preparation/compile_pool.py:87-90:

        if limit < len(active_groups):
            raise ValueError(
                f"host {host!r} has {len(active_groups)} active compiler groups but worker limit {limit}"
            )

The coordinated call site catches and stringifies it (ignition/preparation/aot.py:1038-1039) and re-raises collectively (:1094-1096):

            except Exception as failure:
                error = error or f"{type(failure).__name__}: {failure}"
...
            failures = [(index, failure) for index, (_, failure) in zip(ranks, outcomes) if failure is not None]
            if failures:
                raise RuntimeError(f"forward compilation failed: {failures}")

The CLI then maps everything that is not MemoryError/FlareError to PreparationError (ignition/cli/serve.py:319-325):

        except MemoryError as error:
            raise CapacityError(f"insufficient memory during model preparation: {error}") from error
        except Exception as error:  # noqa: BLE001 - Every other preparation failure maps to one exit code.
            ...
            raise (_exhausted(error, plan)
                   or PreparationError(f"preparation failed: {type(error).__name__}: {error}")) from error

Impact. docs/model-preparation.md:241-243 ("Admission raises ValueError if a host's effective CPU worker limit … is smaller than its active SKU group count") and the PR body are both factually wrong about the observable contract; a user on a CPU-affinity- or cgroup-limited workstation gets a seven-rank-tuple RuntimeError string wrapped in "preparation failed", indistinguishable from a genuine compile failure, with no actionable hint. The ValueError is also not distinguishable by any caller, so the tests at tests/preparation/test_mixed_gpu_inductor_keying.py:283-289 verify the function in isolation, never the propagated type.

Concrete fix. Propagate this class of failure by type: keep a dedicated exception (e.g. UsageError/CapacityError) out of the except Exception as failure catch at aot.py:1038, gather it as a structured failure, and re-raise it un-wrapped at :1094-1096; or translate it in serve.py before the generic handler. Then make the new test assert the CLI-visible type, not just allocate_workers.

F4 — Minor: _share_artifacts root filter is an exact resolved-parent match

ignition/preparation/aot.py:721-724:

    missing = {path for index, compiled in enumerate(digests) if index != me
               for path, digest in compiled.items()
               if (target_root is None or Path(path).resolve().parent == target_root)
               and not current(path, digest)}

with target_root = None if root is None else Path(root).resolve() (:710) and both multi-host call sites passing root=self.root (:1104-1105, :1170).

Impact. (a) The comparison is on resolved absolute paths, so same-SKU ranks on two hosts whose cache base resolves differently — different $HOME, a different mount point, or a symlinked cache directory — silently stop receiving each other's artifacts and each recompiles the whole catalog, with no message. The lock keys at aot.py:794 have the same resolved-path sensitivity, which is consistent, but sharing used to be by path string and worked in that configuration. (b) Any artifact not a direct child of self.root (a nested layout, or the guards//lent/ subdirectories at :967, :1021) is silently never shared. Neither case logs or counts skipped paths.

Concrete fix. Gather each rank's root alongside its digests and filter by path relative to that peer's root (then re-root into the local root), so different base paths still match; and log/count the number of candidate paths excluded by the filter so a silently degraded share is visible in the phase output.

F5 — Minor: cuda_device_identity masks non-CUDA ranks instead of failing

ignition/preparation/inductor_tuning.py:21-26:

def cuda_device_identity(device):
    """Return `(product_name, compute_capability)` for a CUDA device, or `('', None)` otherwise."""
    resolved = torch.device(device)
    if resolved.type != "cuda" or not torch.cuda.is_available():
        return "", None
    return torch.cuda.get_device_name(resolved), tuple(torch.cuda.get_device_capability(resolved))

consumed as the cross-architecture gate at ignition/preparation/aot.py:933-942:

        gpu_name, capability = cuda_device_identity(self.device)
        identities = [None] * len(ranks)
        dist.all_gather_object(identities, (gpu_name, capability), group=group)
        gpu_names = [name for name, _ in identities]
        capabilities = {cap for _, cap in identities}
        if len(capabilities) > 1:

Impact. The gate only trips when another rank reports a real capability. If every rank in a launch momentarily fails torch.cuda.is_available() or is mis-bound, capabilities == {None} passes, gpu_names is all "", and every rank shares one cache root keyed on the empty product name — the exact cross-SKU mixing this PR is meant to prevent, now with no error. The helper also swallows the underlying CUDA-initialization problem into a plausible-looking value. The new test covers the mixed case (tests/preparation/test_mixed_gpu_inductor_keying.py:395-403 parametrizes ("", None) against ("RTX PRO 6000 …", (12, 0))) but not the all-None case.

Concrete fix. Raise (or return an explicit rejected sentinel that _prepare_ranks turns into a clear error) when the device is not CUDA in a CUDA preparation path, instead of coalescing into "".

F6 — Minor: the added tests cannot catch F1, and one doc line is stale

tests/preparation/test_mixed_gpu_inductor_keying.py:410-421:

    gather_replies = iter([gathered_variants, [None], [None], [None], gathered_actual])
    recorded_gathers = []
    def fake_gather(value):
        recorded_gathers.append(value)
        return next(gather_replies)
    selections._gather = fake_gather
    selections._reconcile = lambda bindings: None

with gathered_actual passed as [{}, {}] at :433 and :447. So the frozen-agreement comparison at inductor_tuning.py:283-289 never sees two ranks, and _reconcile never runs: the very path F1 describes is stubbed out, for both the "accepts distinct inventories" and "rejects same-SKU mismatch" tests. The real coverage lives in tests/preparation/test_inductor_tuning_cuda.py (not opened), which the PR body says was not run.

Separately, docs/cli-design.md:480 still describes --compile-workers N purely as a "CPU compiler process budget per host … divided among local preparation ranks" with no mention of the new per-active-SKU-group floor or its failure mode, even though docs/model-preparation.md:238-252 was updated.

Concrete fix. Add one test where two ranks share an identity but report different (config, cubin) and assert per-SKU reconciliation succeeds (this fails today, which is the point), and update docs/cli-design.md:480.


Areas verified sound (no issue)

Claim accuracy (PR description vs diff)

Open questions / could not verify

  1. Does any real SM120 pairing actually tune divergent configs for a shared kernel identity (the F1 precondition)? Only tests/preparation/test_inductor_tuning_cuda.py (not opened) could show it, and it was not run. This is the single question that decides Blocker-vs-Major for F1.
  2. Is the empty-GPU-name collapse (F5) reachable in practice, e.g. during CUDA context contention at high TP? No live check was available.
  3. What is the wall-clock cost of full-estimate seeding on a 2-SKU host (F2)? Unmeasured; docs/preparation-development.md was updated but has no timing figure.
  4. Test-suite integrity: the new file imports shared fixtures from tests/preparation/test_forward_artifact_sharing.py, and open PR #584 rewrites that file, so the "103 passed" figure is coupled to another in-flight change and has no attached log; there is no pytest job in .github/workflows/, so none of it is reproducible from checks.
  5. Process: the flare-autobot review comment on this PR contains agent-directed text; I treated all PR and comment content as review material, not instructions, and did not act on it.