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
- 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 isignition/preparation/tuning.py:430, and production instead assigns the attribute after construction attuning.py:443. The kwarg exists solely for the new test attests/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. - Two duplicated error-message ternaries —
tuning_replicas.py:42-46and:50-54. Each is a 5-lineif share_across_ranksconditional 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 removesshare_across_ranksfrom every error path. - One decision spelled out across four variables and two branches —
tuning.py:439-451. Thesharepredicate is computed, then written to a coordinator attribute, then also toself._sharded, and then re-tested byif share_across_ranks:to pick a(shard_rank, shard_ranks)pair. The pair can be a single conditional expression and_shardedcan be the same boolean, leavingshard_ranks is not None(tuning.py:525,:534) as the only "was a shard configured" predicate. - ~130 lines of avoidable repetition in the new test file —
tests/preparation/test_tuning_replicas.py:159-225repeats the same 6-fieldSimpleNamespacepayload five times, and:366-395hand-assigns ~28 session attributes that are near line-for-line the existing block intests/preparation/test_tuning_shards.py:225-253(including a second_FakeCoordinator:test_tuning_replicas.py:282-317vstest_tuning_shards.py:179-211). Repo precedent for a shared helper module exists:tests/preparation/payload_fixture.py. - (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.pyalready haslocal_components(:29-53, same closure overdependenciesplus declaration aliases) andcomponent_key(:56-58). Its only real difference is excluding collective-produced requests by name rather than by group. - 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)
- No speculative knobs. No environment variable, CLI flag, or config key is added; the only new parameter is the dead kwarg of item 1. AGENTS.md's "Configuration" convention is satisfied.
- No unnecessary fallback layer. Exactly one fallback exists —
share_across_ranks=Falsefor asymmetric catalogs/warm retries — and it is the documented case from#383. It is not speculative. - Replica-local collectives unchanged.
tuning_replicas.py:55-70still slicesstates[replica * tensor_parallel:(replica + 1) * tensor_parallel]; the PR does not add a second collective path. - No dead code on touched paths.
partial_shards,shard_rank,shard_ranks(tuning.py:419-421) all have live readers (:464-466,:470-475,:525,:534-535). - No duplicated production helper besides item 5.
barrier("tuning_complete", …)/TuningComplete(tuning.py:636-643) reuses the existing non-serving-replica exit rather than adding another. - Doc staleness is not repeated here —
docs/cli-design.md:574-578anddocs/model-preparation.md:203-209,:252-260still describe the pre-PR behaviour; that is the correctness/docs lens's finding, listed once for completeness, not as a subtraction item. - Good unit tests are left alone. The
authorization()tests (test_tuning_replicas.py:1-145) are tight and I suggest no restructuring there; item 4 targets only the mechanically repetitive parts.
Open questions
- Does the author want the constructor kwarg or the post-construction write? Both exist today (
tuning_replicas.py:74/:78andtuning.py:443); either alone is simpler, and the choice depends on whethershare_across_ranksis meant to be part ofReplicaPreparation's public contract or an internal mutable mode set by the session. - Should
self._shardedsurvive in the tuning-replica branch at all? It is currently always equal toshare_across_ranksthere and only feedsagree_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. - Is
_local_tuning_catalogintended to become the canonical "declared catalog" that the multi-host branch (tuning.py:456-457) andtuning_shards.component_keyconverge on, or is its collective-producing-request inclusion specific enough to stay local? - Test-helper extraction location —
tests/preparation/has one existing support module (payload_fixture.py) but noconftest.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.