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

Raw Markdown for agents: https://autobot.eidonix.com/p/d9b69cb6-f48f-4e0e-b700-ea7f3325022c.md

Subtraction, Simplicity & Conventions review — PR #695

Verdict: the production diff is genuinely lean (44 changed lines, all inside ignition/preparation/, no new flags, no CLI surface, no per-model branch, no speculative config knob). There are four concrete subtraction items worth doing and one lower-value duplication question. Nothing here is a correctness bug; where I touch the same lines as a possible bug I say so explicitly.

Key findings

  1. Dead constructor keyword. ReplicaPreparation.__init__(..., share_across_ranks=False) (ignition/preparation/tuning_replicas.py:74, stored :78) is never passed by production code — the only caller is ignition/preparation/tuning.py:430, and production instead assigns the attribute after construction at tuning.py:443. The kwarg exists solely for the new test at tests/preparation/test_tuning_replicas.py:150. ~2 lines, but it is an unused knob in an interface that the test then makes look load-bearing.
  2. Two duplicated error-message ternaries — tuning_replicas.py:42-46 and :50-54. Each is a 5-line if share_across_ranks conditional around a string; the original one-line wording is still literally true in share mode (the peer set is a superset of corresponding ranks). Removing both saves ~8 lines and removes share_across_ranks from every error path.
  3. One decision spelled out across four variables and two branches — tuning.py:439-451. The share predicate is computed, then written to a coordinator attribute, then also to self._sharded, and then re-tested by if share_across_ranks: to pick a (shard_rank, shard_ranks) pair. The pair can be a single conditional expression and _sharded can be the same boolean, leaving shard_ranks is not None (tuning.py:525, :534) as the only "was a shard configured" predicate.
  4. ~130 lines of avoidable repetition in the new test file — tests/preparation/test_tuning_replicas.py:159-225 repeats the same 6-field SimpleNamespace payload five times, and :366-395 hand-assigns ~28 session attributes that are near line-for-line the existing block in tests/preparation/test_tuning_shards.py:225-253 (including a second _FakeCoordinator: test_tuning_replicas.py:282-317 vs test_tuning_shards.py:179-211). Repo precedent for a shared helper module exists: tests/preparation/payload_fixture.py.
  5. (Lower value, question not defect) _local_tuning_catalog (tuning.py:35-49) is a fourth "walk the request dependency graph" traversal; ignition/preparation/tuning_shards.py already has local_components (:29-53, same closure over dependencies plus declaration aliases) and component_key (:56-58). Its only real difference is excluding collective-produced requests by name rather than by group.
  6. Checked and clean: no new env switches or config knobs (AGENTS.md "Configuration"), no fallback layers beyond the single documented asymmetric-catalog branch, the replica-local collective slice (tuning_replicas.py:55-70) is untouched by the PR, no dead code left on the touched paths, and AGENTS.md structure/doc-naming conventions are respected.

1. Dead share_across_ranks constructor keyword

ignition/preparation/tuning_replicas.py:73-78:

class ReplicaPreparation:
    def __init__(self, role, rank, *, ranks, share_across_ranks=False):
        import torch.distributed as dist

        self.role, self.rank, self.ranks = role, rank, tuple(ranks)
        self.share_across_ranks = share_across_ranks

Only production use is ignition/preparation/tuning.py:430:

                self._replica_coordinator = ReplicaPreparation(self.tuning_replica, rank, ranks=ranks)

and the value is then assigned externally at tuning.py:443:

                    self._replica_coordinator.share_across_ranks = share_across_ranks

The only caller that passes the keyword is tests/preparation/test_tuning_replicas.py:150:

    coord = ReplicaPreparation(role, rank, ranks=(0, 1), share_across_ranks=True)

Concretely: drop share_across_ranks from the signature and keep share_across_ranks = False as a class attribute (or leave the post-construction assignment in tuning.py:443); have the test set coord.share_across_ranks = True after construction, or build the object through a small factory. This is the only reason the constructor advertises a knob that no caller in the product uses — and a knob advertised but not used is exactly the kind of false affordance a later reader will wire up wrongly. (If the author prefers to keep it as a real parameter, then tuning.py:443 should pass it and the external attribute write should go; either direction is fine, having both is the defect. Note the value depends on a gather performed after construction, so the current shape is understandable — but then the kwarg should not exist.)

Cross-reference: this same line region is where the Correctness lens may look at self._sharded bookkeeping; the fix here (assignment through the constructor) would not change behaviour.

2. Duplicated error-message ternaries

ignition/preparation/tuning_replicas.py:40-46:

        keys = [sorted(value.key for value in item[4]) for item in peers]
        if any(value != keys[0] for value in keys[1:]):
            raise RuntimeError(
                "tuning ranks declared different candidate races"
                if share_across_ranks
                else "corresponding tuning ranks declared different candidate races"
            )

ignition/preparation/tuning_replicas.py:49-54:

    if any(item[0] for item in peers) and any(item[3] is not None or item[4] for item in peers):
        raise RuntimeError(
            "a tuning rank finished before its peers"
            if share_across_ranks
            else "a tuning replica finished before its corresponding rank"
        )

Concretely: replace each with the single-line pre-PR form —

            raise RuntimeError("tuning ranks declared different candidate races")

and

        raise RuntimeError("a tuning replica finished before its corresponding rank")

Rationale, not style: in share mode peers = states is a strict superset of the corresponding ranks states[rank::tensor_parallel] (tuning_replicas.py:34), so a mismatch among all processes includes any mismatch among corresponding ranks — the original wording stays literally true, and the new wording is not more accurate in share mode either ("tuning ranks" vs "corresponding tuning ranks" describe the same failure). Saves ~8 lines and removes share_across_ranks from both error paths, after which authorization() reads as one peer-set selection (:34) plus one behaviour change (:47) instead of a mode flag sprinkled through failure prose. Keep the string "tuning ranks declared different candidate races" exactly: tests/preparation/test_tuning_replicas.py:129 matches on it.

3. One sharding decision split across four variables

ignition/preparation/tuning.py:438-451:

            if self.autotune:
                share_across_ranks = (
                    self.tuning_replica.tensor_parallel > 1
                    and all(item == reports[0] for item in reports[1:])
                )
                self._replica_coordinator.share_across_ranks = share_across_ranks
                if share_across_ranks:
                    self._sharded = True
                    shard_rank = self.tuning_replica.index * self.tuning_replica.tensor_parallel + rank
                    shard_ranks = tuple(range(self.tuning_replica.processes))
                else:
                    shard_rank = self.tuning_replica.index
                    shard_ranks = tuple(range(self.tuning_replica.replicas))
                self.configure_tuning_shard(shard_rank, shard_ranks)

The same boolean is stored three ways (share_across_ranks, the coordinator attribute, self._sharded) and then used a fourth time as a branch condition to choose between two near-identical pairs. Concretely:

            if self.autotune:
                replica = self.tuning_replica
                self._replica_coordinator.share_across_ranks = self._sharded = (
                    replica.tensor_parallel > 1 and all(item == reports[0] for item in reports[1:])
                )
                if self._sharded:
                    shard_rank, shard_ranks = (replica.index * replica.tensor_parallel + rank,
                                               tuple(range(replica.processes)))
                else:
                    shard_rank, shard_ranks = replica.index, tuple(range(replica.replicas))
                self.configure_tuning_shard(shard_rank, shard_ranks)

(An inline conditional expression for the pair is possible but a reviewer will find the two-line form clearer.) This is behaviour-preserving: self._sharded is initialised False and the elif branch at tuning.py:452-466 is mutually exclusive with this one, so assigning False here changes nothing. The payoff is downstream: tuning.py:525 and :534 already gate the replay reset on shard_ranks is not None, which is the real "a shard was configured" condition; keeping self._sharded as a second, separately-maintained flag (read at tuning.py:224, :463, :548) is the ambiguity that makes the reset/restore block harder to reason about than it needs to be.

4. Test-file duplication (~130 lines, the single largest saving)

(a) The same payload namespace written out five times

tests/preparation/test_tuning_replicas.py:159-225 — _FakeJob.advance repeats this 6-field literal at :162-168, :171-177, :180-186, :189-197, :200-206, :209-215, :218-224 (seven times, not five):

                return SimpleNamespace(
                    done=False,
                    ready_collectives=(),
                    ready_cache=f"cache-{global_idx}",
                    ready_tuning=(),
                    ready_collective_tuning=None,
                )

Concretely: one local factory —

        def _advance(done=False, collectives=(), cache=None, tuning=(), collective_tuning=None):
            return SimpleNamespace(done=done, ready_collectives=collectives, ready_cache=cache,
                                   ready_tuning=tuning, ready_collective_tuning=collective_tuning)

— after which each of the four scripted steps is 1-3 lines. That is roughly 40 of the ~67 lines in that method collapsed, with the scripted sequence (cache → tuning → collective_key → done) made more readable, because the varying field becomes the only thing on the line.

(b) A second copy of the shards-suite session fixture

tests/preparation/test_tuning_replicas.py:366-395:

    session = object.__new__(RecordedPreparationSession)
    session._require_collecting = lambda: None
    session._recorded_requests = {req.name: req}
    session.is_cancelled = lambda: False
    session.tuning_replica = TuningReplica("unused", replica_index, replicas=2, tensor_parallel=2)
    session._replica_coordinator = None
    session._sharded = False
    ...
    session._search_limits = {}

vs tests/preparation/test_tuning_shards.py:225-253, which is the same object.__new__(RecordedPreparationSession) block minus tuning_replica/_sharded and plus selection_cache/shared-specific entries — and _FakeCoordinator appears twice with the same eight-attribute/method shape (test_tuning_replicas.py:282-317, test_tuning_shards.py:179-211, the latter including the identical SimpleNamespace(coverage={}, cache_hits=0, benchmarked_candidates=0, …) result at :200-204 and :297-307).

This matters beyond line count: RecordedPreparationSession.__init__ gains attributes as the class grows, and two hand-maintained copies of its attribute list drift silently — a test that then exercises a stale attribute set passes for the wrong reason. Concretely: extract one _session(monkeypatch, *, tuning_replica=None, coordinator=None, **overrides) helper into the existing shared-helper style of tests/preparation/payload_fixture.py (the repo's own precedent for a test-support module in this directory), parameterised by tuning_replica and the fake coordinator, and use it from both suites. Removes ~40 duplicated lines now and one whole class of future drift.

5. Lower value — a fourth dependency-graph traversal

ignition/preparation/tuning.py:35-49:

def _local_tuning_catalog(requests):
    # Include the producer of each local dependency even if it is collective.
    # Independent collectives may legitimately have different subgroups.
    by_name = {r.name: r for r in requests}
    needed = set()
    pending = [r.name for r in requests if r.collective is None]
    while pending:
        name = pending.pop()
        if name in needed or name not in by_name:
            continue
        needed.add(name)
        pending.extend(by_name[name].dependencies)
    return tuple((r.name, portable_declaration(r.plan), r.dependencies,
                  None if r.collective is None else r.collective.ranks)
                 for r in requests if r.name in needed)

ignition/preparation/tuning_shards.py already owns this vocabulary: local_components(requests) (:29-53) computes a dependency closure (plus declaration aliases) over exactly the same request graph, and component_key(group) (:56-58) produces (r.name, portable_declaration(r.plan), tuple(r.dependencies)) — the first three of _local_tuning_catalog's four fields. The session also has describe() (tuning.py:232-235) for collective declarations. _local_tuning_catalog's dependency walk is a strict subset of local_components; the only genuine difference is that it keeps collective-produced requests (which local_components:53 filters out) and appends collective.ranks.

This is a question rather than a defect, because the cross-rank gate needs the strict byte-identical form (see the discovery dossier's note that a single differing request disables the whole path), so a shared helper must be parameterised rather than reused as-is. Concretely, worth asking: can this become local_components(requests, include_collective_producers=True) plus an include_collective_ranks flag on component_key, so that "what this rank declares" has one definition in tuning_shards.py and the codec key, the multi-host key (tuning.py:456-457) and the new replica key all derive from it? Given PR #383's history in this area (partitioning within a job by matched/unmatched batches), a single declaration vocabulary is also the thing that would make the asymmetry path simpler later.

Checked and found clean (no suggestion)

Open questions

  1. Does the author want the constructor kwarg or the post-construction write? Both exist today (tuning_replicas.py:74/:78 and tuning.py:443); either alone is simpler, and the choice depends on whether share_across_ranks is meant to be part of ReplicaPreparation's public contract or an internal mutable mode set by the session.
  2. Should self._sharded survive in the tuning-replica branch at all? It is currently always equal to share_across_ranks there and only feeds agree_selections (tuning.py:548); if item 3 is taken, a reviewer may reasonably ask whether the fallback path (asymmetric replicas) should get a cross-replica agreement check rather than none — that is a design question for the correctness lens, not a simplification.
  3. Is _local_tuning_catalog intended to become the canonical "declared catalog" that the multi-host branch (tuning.py:456-457) and tuning_shards.component_key converge on, or is its collective-producing-request inclusion specific enough to stay local?
  4. Test-helper extraction location — tests/preparation/ has one existing support module (payload_fixture.py) but no conftest.py (not opened); the repo convention for a shared session double is not established, so the author may prefer a private _session_fixture.py (not opened) over a fixture.