From ccb9f5bc92fb644b422e29d71eb132be862972e2 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Wed, 2 Dec 2026 13:41:40 -0800 Subject: [PATCH] Share local tuning candidates across TP ranks in tuning replicas and reconcile serving selections When exporting a tensor-parallel model with local tuning replicas (--tuning-gpus covering multiple complete TP replicas), each TP rank previously sharded local candidate races only across its corresponding ranks in other replicas (states[rank::tensor_parallel]) with configure_tuning_shard(replica, range(replicas)), and RecordedPreparationSession.tune skipped post-tuning reconcile_selections and agree_selections whenever _replica_coordinator was active. On TP=8 with 2 replicas (16 GPUs), all 8 ranks in each replica redundantly benchmarked the same candidate half, could pick different winners due to measurement jitter (such as attention.gqa plans with distinct scratch layouts), and then failed rank-local AOT forward binding with BindingMismatch after compilation. Changes: - ignition/preparation/tuning_replicas.py: added share_across_ranks to authorization() and ReplicaPreparation so local cache (ready_cache) and candidate-race (ready_tuning) exchanges span all replica*tensor_parallel processes when homogeneous, while keeping collective exchanges (ready_collectives and ready_collective_tuning) scoped to each replica's local TP group. - ignition/preparation/tuning.py: - RecordedPreparationSession.tune gathers (device.identity, _local_tuning_catalog(requests)) across all tuning-replica processes. When tensor_parallel > 1 and all processes report identical device identities and local tuning catalogs, it enables share_across_ranks, sets _sharded, and shards local candidates across all replica*tensor_parallel processes (shard rank replica * tensor_parallel + rank). Otherwise it retains corresponding-rank sharding across replicas. - Post-tuning reconcile_selections and agree_selections now run on serving replica 0 (self.tuning_replica is None or self.tuning_replica.index == 0) instead of being skipped whenever _replica_coordinator is set; any reconciliation replay temporarily resets configure_tuning_shard(0, (0,)) and restores the configured shard afterward. Non-serving replicas (index > 0) skip reconciliation and exit via TuningComplete as before. - tests/preparation/test_tuning_replicas.py: added CPU unit tests for authorization() (shared and corresponding-rank modes, mixed local/collective interleaving, mismatched race rejection), a 4-process (2 replicas x TP2) Gloo spawn test of ReplicaPreparation.prepare(), and RecordedPreparationSession.tune() tests covering homogeneous cross-rank sharding, unequal-catalog fallback with serving-replica reconciliation, and non-serving replica exit. Expected benefit: Prevents cross-rank kernel selection divergence (BindingMismatch during AOT forward loading) when using --tuning-gpus on TP models, and scales local candidate sharding from R-way to (R * TP)-way when all tuning GPUs and local catalogs match (eliminating TP-way duplicate local races). Evidence: - pytest tests/preparation/test_tuning_replicas.py tests/preparation/test_tuning_shards.py tests/preparation/test_tuning_jobs.py tests/preparation/test_dcp_selection_groups.py tests/cli/ -q: 167 passed. - Full tests/preparation/ run under the sibling recipes venv: 1,170 passed, 74 skipped (GPU-gated), 3 unrelated environment failures (test_inspect_forward_kernels, test_runtime_static_triton, test_source_identity due to mismatched workspace/venv heliopause build). - Limitations: multi-GPU end-to-end --tuning-gpus export has not yet been re-run on this commit. Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b --- ignition/preparation/tuning.py | 35 +- ignition/preparation/tuning_replicas.py | 24 +- tests/preparation/test_tuning_replicas.py | 482 ++++++++++++++++++++++ 3 files changed, 526 insertions(+), 15 deletions(-) create mode 100644 tests/preparation/test_tuning_replicas.py diff --git a/ignition/preparation/tuning.py b/ignition/preparation/tuning.py index 973bd3604..fe9864be1 100644 --- a/ignition/preparation/tuning.py +++ b/ignition/preparation/tuning.py @@ -418,6 +418,7 @@ def tune(self, *, progress=None, show_progress=False, console=None): requests = tuple(self._recorded_requests.values()) partial_shards = False shard_rank = None + shard_ranks = None if self.tuning_replica is not None: import torch.distributed as dist from .tuning_replicas import ReplicaPreparation @@ -427,12 +428,27 @@ def tune(self, *, progress=None, show_progress=False, console=None): ranks = (0,) if self._coordinator is None else self._coordinator.ranks rank = 0 if self._coordinator is None else ranks.index(dist.get_rank()) self._replica_coordinator = ReplicaPreparation(self.tuning_replica, rank, ranks=ranks) - identities = self._replica_coordinator.gather(self.device.identity) + reports = self._replica_coordinator.gather( + (self.device.identity, _local_tuning_catalog(requests)) + ) + identities = [item[0] for item in reports] corresponding = identities[rank::self.tuning_replica.tensor_parallel] if any(identity != corresponding[0] for identity in corresponding[1:]): raise ValueError("corresponding tuning GPUs must have identical hardware geometry") if self.autotune: - self.configure_tuning_shard(self.tuning_replica.index, tuple(range(self.tuning_replica.replicas))) + 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) elif self.autotune and self._coordinator is not None: import torch.distributed as dist @@ -446,7 +462,8 @@ def tune(self, *, progress=None, show_progress=False, console=None): self._coordinator.share_selections(self.selection_cache()) if self._sharded: shard_rank = dist.get_rank() - self.configure_tuning_shard(shard_rank, self._coordinator.ranks) + shard_ranks = self._coordinator.ranks + self.configure_tuning_shard(shard_rank, shard_ranks) else: partial_shards = True scratch_arena = self._reserve_scratch(requests) @@ -502,10 +519,10 @@ def update(status): if self.is_cancelled(): raise RuntimeError("b12x tuning was cancelled before serving preparation completed") if (self._coordinator is not None and len(self._coordinator.ranks) > 1 - and self._replica_coordinator is None): + and (self.tuning_replica is None or self.tuning_replica.index == 0)): configs, changed = self._coordinator.reconcile_selections(requests) if changed: - if self._sharded: + if shard_ranks is not None: self.configure_tuning_shard(0, (0,)) try: for job in self._jobs(requests): @@ -514,8 +531,8 @@ def update(status): autotune=self.autotune, selected_configs={plan: config for plan, config in configs.items() if plan in plans})) finally: - if self._sharded: - self.configure_tuning_shard(shard_rank, self._coordinator.ranks) + if shard_ranks is not None: + self.configure_tuning_shard(shard_rank, shard_ranks) selections = [] coverage = {name: value for result in results for name, value in result.coverage.items()} for request in requests: @@ -526,7 +543,9 @@ def update(status): "source": selection.source, "config": request.plan.contract.config_payload(selection.config).to_dict(), "coverage": FrozenMapping(coverage.get(request.name, {})).to_dict()}) - if self._coordinator is not None and (self._sharded or self._coordinator.spans_hosts): + if (self._coordinator is not None + and (self.tuning_replica is None or self.tuning_replica.index == 0) + and (self._sharded or self._coordinator.spans_hosts)): self._coordinator.agree_selections(selections) self._tune_status = "finalizing" if self._scratch_arena is not None: diff --git a/ignition/preparation/tuning_replicas.py b/ignition/preparation/tuning_replicas.py index a14ed0b67..330c6c298 100644 --- a/ignition/preparation/tuning_replicas.py +++ b/ignition/preparation/tuning_replicas.py @@ -29,9 +29,9 @@ class TuningComplete(BaseException): """A preparation-only replica finished tuning and may release its model.""" -def authorization(states, *, replica, rank, tensor_parallel, ranks): - """Release replica-local collectives and corresponding-rank candidate exchanges.""" - peers = states[rank::tensor_parallel] +def authorization(states, *, replica, rank, tensor_parallel, ranks, share_across_ranks=False): + """Release replica-local collectives and local candidate exchanges across replicas or all ranks.""" + peers = states if share_across_ranks else states[rank::tensor_parallel] if all(item[3] is not None for item in peers): return {"cache": tuple(item[3] for item in peers)} if all(item[4] for item in peers): @@ -39,11 +39,19 @@ def authorization(states, *, replica, rank, tensor_parallel, ranks): 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("corresponding tuning ranks declared different candidate races") + raise RuntimeError( + "tuning ranks declared different candidate races" + if share_across_ranks + else "corresponding tuning ranks declared different candidate races" + ) results = _tuning_results(value for item in peers for value in item[4]) return {"tuning": results[0] if len(results) == 1 else results} 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 replica finished before its corresponding rank") + raise RuntimeError( + "a tuning rank finished before its peers" + if share_across_ranks + else "a tuning replica finished before its corresponding rank" + ) local = states[replica * tensor_parallel:(replica + 1) * tensor_parallel] if all(item[5] is not None for item in local): if any(item[5].ranks != tuple(ranks) for item in local): @@ -63,10 +71,11 @@ def authorization(states, *, replica, rank, tensor_parallel, ranks): class ReplicaPreparation: - def __init__(self, role, rank, *, ranks): + 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 self.store = dist.FileStore(role.rendezvous, role.processes) # This group is independent of torch.distributed's default TP group. self.group = dist.ProcessGroupGloo(self.store, role.index * role.tensor_parallel + rank, @@ -112,7 +121,8 @@ def prepare(self, session, requests, *, progress, autotune): if all(item[0] for item in states): return job.result() allowed = authorization(states, replica=self.role.index, rank=self.rank, - tensor_parallel=self.role.tensor_parallel, ranks=self.ranks) + tensor_parallel=self.role.tensor_parallel, ranks=self.ranks, + share_across_ranks=self.share_across_ranks) except BaseException as failure: if job is not None: try: diff --git a/tests/preparation/test_tuning_replicas.py b/tests/preparation/test_tuning_replicas.py new file mode 100644 index 000000000..410d67276 --- /dev/null +++ b/tests/preparation/test_tuning_replicas.py @@ -0,0 +1,482 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Local tuning replica coordination and cross-rank selection agreement.""" + +from contextlib import nullcontext +from types import SimpleNamespace + +import pytest +import torch +from b12x._lib.compile_pool import CompileJob +from b12x._lib.scratch import ScratchBufferSpec +from b12x.preparation import DetectedDevice, DeviceIdentity, Knob, MemoryRequirements, Plan, TuningContract + +from ignition.preparation.tuning import RecordedPreparationSession, _local_tuning_catalog +from ignition.preparation.tuning_replicas import ReplicaPreparation, TuningComplete, TuningReplica, authorization + + +DEVICE_A = DetectedDevice(0, DeviceIdentity("nvidia", (12, 0), 188, "RTX PRO 6000 Blackwell")) +DEVICE_B = DetectedDevice(1, DeviceIdentity("nvidia", (12, 0), 170, "RTX 5090")) + + +def _request(name, size): + contract = TuningContract( + component_id="test.attention", + query_schema_version=1, + config_schema_version=1, + query_fields=frozenset({"size"}), + config_fields=frozenset({"width"}), + encode_query=lambda q: {"size": q}, + encode_config=lambda c: {"width": c}, + decode_config=lambda d: d["width"], + validate_query=lambda q, d: None, + validate_config=lambda q, c, d: None, + default_config=lambda q, d: 1, + knobs=(Knob(name="width", values=(1, 2)),), + ) + plan = Plan( + contract=contract, + query=size, + _compile_jobs=lambda c, d: (CompileJob.create("example:compile", size, c),), + _memory_requirements=lambda c, d: MemoryRequirements( + scratch=( + ScratchBufferSpec( + name="tiles", + shape=(size * c,), + dtype=torch.uint8, + device=torch.device("cuda", d.ordinal), + ), + ) + ), + _materialize=lambda s, d: s.config, + ) + return plan.request(name=name, prepare_call=lambda s: None, benchmark_call=lambda s: None) + + +def _contribution(key, candidate_index, latency_us, assignment="cfg"): + return SimpleNamespace( + key=key, + candidate_index=candidate_index, + latency_us=latency_us, + assignment=assignment, + ) + + +def _state(*, done=False, pending=(), error=None, cache=None, tuning=(), collective_tuning=None): + return (done, pending, error, cache, tuning, collective_tuning) + + +def test_authorization_shares_local_tuning_across_all_ranks_when_enabled(): + # 2 replicas x TP2 = 4 processes. + # Cache exchange waits for all 4 processes when share_across_ranks=True. + partial_cache = [ + _state(cache="c0"), + _state(), + _state(cache="c2"), + _state(), + ] + assert authorization( + partial_cache, replica=0, rank=0, tensor_parallel=2, ranks=(0, 1), share_across_ranks=True + ) == {"collective_key": None} + + full_cache = [_state(cache=f"c{i}") for i in range(4)] + assert authorization( + full_cache, replica=0, rank=0, tensor_parallel=2, ranks=(0, 1), share_across_ranks=True + ) == {"cache": ("c0", "c1", "c2", "c3")} + + # Local tuning selects one global winner across all 4 processes. + tuning_states = [ + _state(tuning=(_contribution("gqa", 0, 320.0, "cfg0"),)), + _state(tuning=(_contribution("gqa", 1, 315.0, "cfg1"),)), + _state(tuning=(_contribution("gqa", 2, 318.0, "cfg2"),)), + _state(tuning=(_contribution("gqa", 3, 305.0, "cfg3"),)), + ] + for replica in range(2): + for rank in range(2): + allowed = authorization( + tuning_states, + replica=replica, + rank=rank, + tensor_parallel=2, + ranks=(0, 1), + share_across_ranks=True, + ) + assert allowed["tuning"].candidate_index == 3 + assert allowed["tuning"].assignment == "cfg3" + + # While replica 0 waits at a local race, replica 1 still advances its replica-local collective. + mixed_states = [ + _state(tuning=(_contribution("gqa", 0, 320.0, "cfg0"),)), + _state(tuning=(_contribution("gqa", 1, 315.0, "cfg1"),)), + _state(pending=(("ar0", (0, 1)),)), + _state(pending=(("ar0", (0, 1)),)), + ] + assert authorization( + mixed_states, replica=0, rank=0, tensor_parallel=2, ranks=(0, 1), share_across_ranks=True + ) == {"collective_key": None} + assert authorization( + mixed_states, replica=1, rank=0, tensor_parallel=2, ranks=(0, 1), share_across_ranks=True + ) == {"collective_key": "ar0"} + + # Mismatched race keys across TP ranks raise explicitly. + mismatched = [ + _state(tuning=(_contribution("gqa", 0, 320.0),)), + _state(tuning=(_contribution("other", 1, 315.0),)), + _state(tuning=(_contribution("gqa", 2, 318.0),)), + _state(tuning=(_contribution("gqa", 3, 305.0),)), + ] + with pytest.raises(RuntimeError, match="tuning ranks declared different candidate races"): + authorization(mismatched, replica=0, rank=0, tensor_parallel=2, ranks=(0, 1), share_across_ranks=True) + + +def test_authorization_corresponding_rank_mode_scopes_to_replica_peers(): + # Rank 0 peers (processes 0 and 2) can exchange while rank 1 peers (1 and 3) are busy. + states = [ + _state(tuning=(_contribution("gqa", 0, 320.0, "cfg0"),)), + _state(), + _state(tuning=(_contribution("gqa", 1, 310.0, "cfg1"),)), + _state(), + ] + allowed = authorization(states, replica=0, rank=0, tensor_parallel=2, ranks=(0, 1), share_across_ranks=False) + assert allowed["tuning"].candidate_index == 1 + assert authorization( + states, replica=0, rank=1, tensor_parallel=2, ranks=(0, 1), share_across_ranks=False + ) == {"collective_key": None} + + +def _gloo_replica_worker(replica, rank, store_path, queue): + role = TuningReplica(store_path, replica, replicas=2, tensor_parallel=2) + coord = ReplicaPreparation(role, rank, ranks=(0, 1), share_across_ranks=True) + global_idx = replica * 2 + rank + latencies = (320.0, 315.0, 318.0, 302.5) + received = {} + + class _FakeJob: + def __init__(self): + self.step = 0 + + def advance(self, **allowed): + if self.step == 0: + self.step = 1 + return SimpleNamespace( + done=False, + ready_collectives=(), + ready_cache=f"cache-{global_idx}", + ready_tuning=(), + ready_collective_tuning=None, + ) + if self.step == 1: + if "cache" not in allowed: + return SimpleNamespace( + done=False, + ready_collectives=(), + ready_cache=f"cache-{global_idx}", + ready_tuning=(), + ready_collective_tuning=None, + ) + received["cache"] = allowed["cache"] + self.step = 2 + return SimpleNamespace( + done=False, + ready_collectives=(), + ready_cache=None, + ready_tuning=(_contribution("gqa", global_idx, latencies[global_idx], f"cfg-{global_idx}"),), + ready_collective_tuning=None, + ) + if self.step == 2: + if "tuning" not in allowed: + return SimpleNamespace( + done=False, + ready_collectives=(), + ready_cache=None, + ready_tuning=( + _contribution("gqa", global_idx, latencies[global_idx], f"cfg-{global_idx}"), + ), + ready_collective_tuning=None, + ) + received["tuning"] = (allowed["tuning"].candidate_index, allowed["tuning"].assignment) + self.step = 3 + return SimpleNamespace( + done=False, + ready_collectives=(SimpleNamespace(key="ar-0", ranks=(0, 1)),), + ready_cache=None, + ready_tuning=(), + ready_collective_tuning=None, + ) + if self.step == 3: + if allowed.get("collective_key") != "ar-0": + return SimpleNamespace( + done=False, + ready_collectives=(SimpleNamespace(key="ar-0", ranks=(0, 1)),), + ready_cache=None, + ready_tuning=(), + ready_collective_tuning=None, + ) + received["collective"] = allowed["collective_key"] + self.step = 4 + return SimpleNamespace( + done=True, + ready_collectives=(), + ready_cache=None, + ready_tuning=(), + ready_collective_tuning=None, + ) + raise AssertionError(f"unexpected step {self.step}") + + def result(self): + return received + + def close(self): + pass + + class _FakeSession: + def begin(self, requests, *, autotune): + return _FakeJob() + + try: + out = coord.prepare(_FakeSession(), (), progress=None, autotune=True) + queue.put((global_idx, ("ok", out))) + except BaseException as exc: + queue.put((global_idx, ("err", repr(exc)))) + raise + + +def test_replica_preparation_over_gloo_shares_single_winner_across_all_ranks(tmp_path): + ctx = torch.multiprocessing.get_context("spawn") + queue = ctx.Queue() + store = tmp_path / "replica_gloo_store" + procs = [ + ctx.Process(target=_gloo_replica_worker, args=(replica, rank, str(store), queue)) + for replica in range(2) + for rank in range(2) + ] + for p in procs: + p.start() + for p in procs: + p.join(timeout=30) + assert [p.exitcode for p in procs] == [0, 0, 0, 0] + results = dict(queue.get(timeout=5) for _ in range(4)) + for idx in range(4): + status, payload = results[idx] + assert status == "ok", payload + assert payload["cache"] == ("cache-0", "cache-1", "cache-2", "cache-3") + assert payload["tuning"] == (3, "cfg-3") + assert payload["collective"] == "ar-0" + + +def _make_replica_session( + monkeypatch, + *, + req, + replica_index, + rank, + gathered_reports, + reconcile_return, + events, + shard_calls, + replica_holder, +): + import torch.distributed as dist + + class _FakeCoordinator: + ranks = (0, 1) + local_ranks = 2 + spans_hosts = False + group = object() + + def prepare(self, session, job, *, progress=None, autotune=None, selected_configs=None): + events.append(("coordinator.prepare", bool(selected_configs), shard_calls[-1] if shard_calls else None)) + if selected_configs: + for plan, config in selected_configs.items(): + object.__setattr__( + plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=config)), + ) + return SimpleNamespace( + coverage={}, + cache_hits=0, + benchmarked_candidates=0, + restored_candidates=0, + rejected_candidates=0, + elapsed_seconds=0.0, + parent_cute_compilations=0, + parent_triton_compilations=0, + close=lambda: None, + ) + + def reconcile_selections(self, requests): + events.append(("reconcile_selections", len(requests))) + return reconcile_return + + def agree_selections(self, selections): + events.append(("agree_selections", [item["config"] for item in selections])) + + def barrier(self, name, ranks): + events.append(("barrier", name, tuple(ranks))) + + class _FakeReplicaPreparation: + def __init__(self, role, r, *, ranks, share_across_ranks=False): + self.role = role + self.rank = r + self.ranks = tuple(ranks) + self.share_across_ranks = share_across_ranks + replica_holder.append(self) + + def gather(self, value): + if isinstance(value, tuple): + return gathered_reports + return [value] * self.role.processes + + def prepare(self, session, requests, *, progress=None, autotune=None): + events.append(("replica.prepare", self.share_across_ranks, shard_calls[-1] if shard_calls else None)) + return SimpleNamespace( + coverage={}, + cache_hits=0, + benchmarked_candidates=0, + restored_candidates=0, + rejected_candidates=0, + elapsed_seconds=0.0, + parent_cute_compilations=0, + parent_triton_compilations=0, + close=lambda: None, + ) + + monkeypatch.setattr(dist, "get_rank", lambda: rank) + monkeypatch.setattr( + torch.cuda, + "get_device_properties", + lambda ordinal: SimpleNamespace(name="RTX PRO 6000 Blackwell", is_integrated=False, major=12, minor=0), + ) + monkeypatch.setattr("ignition.preparation.tuning_replicas.ReplicaPreparation", _FakeReplicaPreparation) + monkeypatch.setattr(torch.cuda, "device", lambda ordinal: nullcontext()) + monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None) + monkeypatch.setattr(torch.accelerator.memory, "empty_host_cache", lambda: None) + monkeypatch.setattr("ignition.preparation.tuning.release_unused", lambda: None) + monkeypatch.setattr("ignition.preparation.tuning.tuning_limits", lambda *a, **kw: (1, 1 << 20)) + monkeypatch.setattr("ignition.preparation.tuning.cpu_workers", lambda *a, **kw: 1) + + object.__setattr__( + req.plan, + "_prepared", + SimpleNamespace(closed=False, selection=SimpleNamespace(source="autotuned", config=1)), + ) + + 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.autotune = True + session._coordinator = _FakeCoordinator() + session.device = DEVICE_A + session.configure_tuning_shard = lambda r, rs: shard_calls.append((r, tuple(rs))) + session._reserve_scratch = lambda reqs: {} + session.requested_compile_workers = None + session.compile_workers = 1 + session.configure_compile_workers = lambda count: None + session.headroom_bytes = 0 + session.race_budget = None + session.lock_gpu_clocks = False + session._scratch_arena = None + session._finalizers = [] + session.synchronize = lambda: None + session._workload_schema = 1 + session.namespace = SimpleNamespace(to_dict=lambda: {}) + session.autotune_effort = "default" + session.native_dense_activations = False + session._benchmark_resources = {} + session._benchmark_restorers = {} + session._restore_benchmark_resources = lambda: None + session._search_limits = {} + session.close = lambda: events.append(("close",)) + return session + + +def test_recorded_session_tune_with_homogeneous_replicas_shards_across_all_processes(monkeypatch): + req = _request("prefill4096.layer0.attention", 32) + catalog = _local_tuning_catalog((req,)) + events, shard_calls, holder = [], [], [] + session = _make_replica_session( + monkeypatch, + req=req, + replica_index=0, + rank=1, + gathered_reports=[(DEVICE_A.identity, catalog)] * 4, + reconcile_return=({}, False), + events=events, + shard_calls=shard_calls, + replica_holder=holder, + ) + + session.tune() + + assert holder[0].share_across_ranks is True + assert shard_calls == [(1, (0, 1, 2, 3))] + assert ("replica.prepare", True, (1, (0, 1, 2, 3))) in events + assert ("reconcile_selections", 1) in events + assert ("agree_selections", [{"width": 1}]) in events + + +def test_recorded_session_tune_with_unequal_replica_catalogs_reconciles_serving_replica(monkeypatch): + req = _request("prefill4096.layer0.attention", 32) + other = _request("prefill4096.layer0.attention", 64) + cat0 = _local_tuning_catalog((req,)) + cat1 = _local_tuning_catalog((other,)) + events, shard_calls, holder = [], [], [] + session = _make_replica_session( + monkeypatch, + req=req, + replica_index=0, + rank=0, + # Corresponding ranks match (0==2, 1==3), but TP rank 0 != TP rank 1. + gathered_reports=[ + (DEVICE_A.identity, cat0), + (DEVICE_B.identity, cat1), + (DEVICE_A.identity, cat0), + (DEVICE_B.identity, cat1), + ], + reconcile_return=({req.plan: 2}, True), + events=events, + shard_calls=shard_calls, + replica_holder=holder, + ) + + session.tune() + + assert holder[0].share_across_ranks is False + # Sharded across replicas (0, 1), temporarily reset to (0, (0,)) for reconciliation replay, then restored. + assert shard_calls == [(0, (0, 1)), (0, (0,)), (0, (0, 1))] + assert ("replica.prepare", False, (0, (0, 1))) in events + assert ("reconcile_selections", 1) in events + assert ("coordinator.prepare", True, (0, (0,))) in events + assert all(ev[0] != "agree_selections" for ev in events) + + +def test_recorded_session_tune_non_serving_replica_skips_reconcile_and_raises_tuning_complete(monkeypatch): + req = _request("prefill4096.layer0.attention", 32) + catalog = _local_tuning_catalog((req,)) + events, shard_calls, holder = [], [], [] + session = _make_replica_session( + monkeypatch, + req=req, + replica_index=1, + rank=1, + gathered_reports=[(DEVICE_A.identity, catalog)] * 4, + reconcile_return=({req.plan: 2}, True), + events=events, + shard_calls=shard_calls, + replica_holder=holder, + ) + + with pytest.raises(TuningComplete): + session.tune() + + assert holder[0].share_across_ranks is True + assert shard_calls == [(3, (0, 1, 2, 3))] + assert all(ev[0] not in ("reconcile_selections", "agree_selections") for ev in events) + assert ("barrier", "tuning_complete", (0, 1)) in events + assert ("close",) in events