From a2a48eae56cf1ace85305cbec7457f2602479a92 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 00:46:33 +0800 Subject: [PATCH 1/4] fix(lead cap): a K = 1 lead wait opens no pair that would hold the wait itself The lead wait pushed every PULL that arrived while it polled from the cut the island had already pushed. With K = 1 that pair is itself a lead blocker, so each such PULL held the wait one more merge. On a slow island this chained: its pushes complete the merges a fast island already pushed to, each merge opens a round whose PULL the slow island answers from inside its wait, and the fast island trains a round per merge meanwhile. The fast island's lead was unbounded; the verl parity lead cap case failed on CI with 11 fast rounds against 8. A lead wait poll now opens a new pair only where it cannot block the wait (K >= 2) or for the push the wait waits for (lead_unpushed). Held PULLs are answered at the next boundary from the newer cut. Replays, harvests, broadcast applies and peer snapshots are unchanged; the cap off (default) is unchanged. Co-Authored-By: Claude Opus 5.5 --- tests/test_sync_lead_cap.py | 96 ++++++++++++++++++++++++--- tests/test_verl_miles_parity.py | 7 +- yeto/rl/engine/full_parameter_sync.py | 53 ++++++++++++--- 3 files changed, 134 insertions(+), 22 deletions(-) diff --git a/tests/test_sync_lead_cap.py b/tests/test_sync_lead_cap.py index 764add13e..71316a4e0 100644 --- a/tests/test_sync_lead_cap.py +++ b/tests/test_sync_lead_cap.py @@ -8,7 +8,8 @@ broadcast overwrites and whose c_steps inflate its tokens^2/steps merge weight. Covered here: the pairing rule on fakes (who blocks, the half-timeout escape, -the terminal phase, peer snapshots during the wait), the profile and the +the terminal phase, peer snapshots during the wait, no push during a wait that +would hold the wait itself), the profile and the launcher/island wiring (default off, hashes unchanged), and two islands of the real pairing and session (:class:`FullParameterSync`) against the real Rust syncer: a fast island and a slow island, with and without the cap. @@ -172,6 +173,78 @@ async def test_the_wait_for_a_late_pull_gives_up_at_half_the_wait_timeout(): assert pairing.lead_wait_escapes == 2 +class _PeerPacedRole(_PairedRole): + """A role whose broadcast of a step arrives only once the peer island + pushed that step too (``peer_pushed``): a fixed roster's merge.""" + + def __init__(self, candidates): + super().__init__("actor", candidates, [], release_broadcasts=False) + self.peer_pushed: set[int] = set() + + async def stage_available_broadcasts(self): + for step in [step for step in self._queued_steps if step in self.peer_pushed]: + self._queued_steps.remove(step) + self._staged_steps.append(step) + return await super().stage_available_broadcasts() + + +@pytest.mark.asyncio +async def test_with_k_1_the_wait_opens_no_pair_that_would_hold_it(): + """A PULL that arrives during a K = 1 wait is not pushed from the cut the + island already pushed: that push would block the wait itself, so each + PULL arriving while the wait's pushes merge held the island one merge + longer (a slow island sat at its boundary while a fast island trained a + round per merge). The wait ends when the pushes it waited for merged; the + held PULL goes out at the next boundary, from the newer cut.""" + role = _PeerPacedRole([_candidate(1, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1, wait_timeout=2.0) + pairing.local_round = 1 + pairing.submit_ready() + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + role.candidates.append(_candidate(2, 1)) # the next round opens during the wait + if len(served) == 3: + role.peer_pushed.add(1) # the peer pushed step 1: it merges + return 0 + + assert await pairing.wait_for_lead(serve) > 0 + assert (pairing.lead_waits, pairing.lead_wait_escapes) == (1, 0) + assert pairing.inflight == {} and role.fragment_versions == (1, 0) + assert [step for _, step, _ in role.events] == [1] # step 2 was not pushed from cut 1 + pairing.local_round = 2 + pairing.submit_ready() + assert [(key[0], pair.local_round) for key, pair in pairing.inflight.items()] == [(2, 2)] + + +@pytest.mark.asyncio +async def test_with_k_2_the_wait_still_pushes_a_pull_that_cannot_hold_it(): + """With K = 2 a pair from the current cut does not block this wait (one + round may train on top of it), so the wait keeps answering PULLs.""" + role = _PeerPacedRole([_candidate(1, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=2, wait_timeout=2.0) + pairing.local_round = 1 + pairing.submit_ready() + pairing.local_round = 2 # a round on top of the unmerged step 1: the next one waits + assert len(pairing.lead_blockers()) == 1 + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + role.candidates.append(_candidate(2, 2)) + if len(served) == 3: + role.peer_pushed.add(1) + return 0 + + assert await pairing.wait_for_lead(serve) > 0 + assert (pairing.lead_waits, pairing.lead_wait_escapes) == (1, 0) + assert [step for _, step, _ in role.events] == [1, 2] + assert [(key[0], pair.local_round) for key, pair in pairing.inflight.items()] == [(2, 2)] + + @pytest.mark.asyncio async def test_no_wait_in_the_terminal_phase_or_without_blockers(): role = _PairedRole("actor", [_candidate(1, 1)], [], release_broadcasts=False) @@ -585,9 +658,12 @@ def test_real_syncer_fast_island_stays_within_the_cap_and_both_islands_join_ever assert not unmerged, (value, unmerged) # ... and only after it pushed from its newest cut (round r). assert value == 1 or value - 1 in fast_pushes.values(), (value, fast_pushes) - # So it stays close to the slow island: one round ahead, or two when - # the slow island itself waited under the cap at a boundary while its - # push from an older cut completed the fast island's merge. + # So it stays close to the slow island: one round ahead, or two when a + # PULL reached the fast island only after its boundary and the slow + # island's push of it, from the same cut as the round before, completed + # a second merge of the fast island. A K = 1 wait never pushes from the + # cut it already pushed, so a slow island's wait cannot chain such + # pushes (test_with_k_1_the_wait_opens_no_pair_that_would_hold_it). assert _max_lead(capped.log) <= 2 waits = [fields for _, kind, who, (name, fields) in ((t, k, w, v) for t, k, w, v in capped.log if k == "event") @@ -597,13 +673,11 @@ def test_real_syncer_fast_island_stays_within_the_cap_and_both_islands_join_ever # Not checked: that a second run with the same inputs gives the same bits. # Which local round a push carries depends on wall-clock order. One slow # boundary closes two rounds a few ms apart (the syncer writes a checkpoint - # before each broadcast). The fast island's lead wait polls every - # LEAD_WAIT_POLL_S and pushes before it applies broadcasts, and a pair - # holds a pipeline slot until its broadcast is applied. If one poll sees - # both broadcasts, the wait ends and the next push carries one more local - # round (c_steps 2). If a poll falls between them, the freed slot takes - # the next PULL from the current cut (c_steps 1) and the island waits a - # slow round longer. Both schedules keep the cap. The syncer orders a + # before each broadcast), and the syncer paces the PULLs of new rounds, so + # whether a PULL is visible at the fast island's boundary or arrives during + # its lead wait (then it is pushed at the next boundary, from the newer + # cut: a K = 1 wait pushes nothing from the cut it already pushed) depends + # on wall-clock order. Both schedules keep the cap. The syncer orders a # round's pushes by learner id (server.rs), so arrival order inside a # round does not change the merge. _check_merges instead checks that the # result equals, up to float32 rounding, the merge of this run's pushes. diff --git a/tests/test_verl_miles_parity.py b/tests/test_verl_miles_parity.py index 8c72560c6..674a74969 100644 --- a/tests/test_verl_miles_parity.py +++ b/tests/test_verl_miles_parity.py @@ -570,7 +570,7 @@ def drain_and_leave(): @needs_cargo def test_the_lead_cap_holds_a_fast_verl_island_to_the_slow_one(syncer_binary, tmp_path, monkeypatch): """K = 1 with a fixed roster (quorum 2): the fast island waits at its - boundaries for the slow island's pushes; the cap fields reach its tape.""" + boundaries for the slow island's pushes; the cap fields reach its events.""" monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", "verl-parity-lead-cap-key") monkeypatch.setenv("TOKIO_WORKER_THREADS", "4") rounds, fragments = 4, len(_layout(matrix_merge="rda").fragments.fragments) @@ -602,7 +602,12 @@ def test_the_lead_cap_holds_a_fast_verl_island_to_the_slow_one(syncer_binary, tm slow_rounds = [f for e, f in slow["events"] if e == "rl_full_parameter_round"] assert all(f["sync/max_local_rounds_ahead"] == 1 for f in fast_rounds) assert fast_rounds[-1]["sync/lead_waits"] > 0, fast_rounds[-1] + assert fast_rounds[-1]["sync/lead_wait_escapes"] == 0, fast_rounds[-1] # no wait gave up and trained on # Without the cap the unpaced island would run hundreds of local rounds meanwhile. + # This bound once failed on a loaded host (11 rounds against 8): the slow island's + # lead wait pushed each PULL arriving during the wait from the cut it had already + # pushed and so held itself at its boundary while the fast island trained a round + # per merge. A K = 1 wait no longer pushes from that cut (RolePairing.wait_for_lead). assert len(fast_rounds) <= len(slow_rounds) + 2, (len(fast_rounds), len(slow_rounds)) assert fast["final_ack"] == slow["final_ack"] == [{"acknowledged": True}] diff --git a/yeto/rl/engine/full_parameter_sync.py b/yeto/rl/engine/full_parameter_sync.py index 748ec988c..0bfa07937 100644 --- a/yeto/rl/engine/full_parameter_sync.py +++ b/yeto/rl/engine/full_parameter_sync.py @@ -313,6 +313,9 @@ def __init__(self, streams: Mapping[str, RoleStream], profile: FullParameterSync self.lead_waits = 0 self.lead_wait_seconds = 0.0 self.lead_wait_escapes = 0 + # Set while a lead wait polls and must not open a pair that would hold + # the wait itself (:meth:`_wait_opens_no_blocker`). + self._no_new_pairs = False # Background pushes, decided at the first submit (a role # knows whether it can encode ahead once it is initialized); None # keeps every push on this thread. @@ -441,7 +444,7 @@ def submit_ready(self) -> dict[str, RoleProgress]: # push is harvested, and is no replay. continue self._push_once(pair, observed, produced) - capacity = self.profile.effective_pipeline_depth - len(self.inflight) + capacity = self._new_pair_capacity() shared = sorted(set.intersection(*(set(keys) for keys in by_role.values()))) if self.profile.partial_quorum: # A round whose broadcast is staged or applied closed without @@ -468,6 +471,12 @@ def submit_ready(self) -> dict[str, RoleProgress]: raise return {role: RoleProgress(submissions=tuple(values)) for role, values in produced.items()} + def _new_pair_capacity(self) -> int: + """Pipeline slots for new pairs: none while a lead wait holds them.""" + if self._no_new_pairs: + return 0 + return self.profile.effective_pipeline_depth - len(self.inflight) + def _replay_permits( self, by_role: Mapping[str, Mapping[LogicalKey, Any]] ) -> dict[str, Mapping[LogicalKey, Any]]: @@ -500,7 +509,7 @@ async def prepare_submissions(self) -> None: role: _candidate_map(stream.ready_submission_candidates(include_deferred=True), role=role) for role, stream in self.streams.items() } - capacity = self.profile.effective_pipeline_depth - len(self.inflight) + capacity = self._new_pair_capacity() shared = sorted(set.intersection(*(set(keys) for keys in by_role.values())) - set(self.inflight)) if self.profile.partial_quorum: shared = [key for key in shared if not self._round_closed(key[1], key[0])] @@ -951,15 +960,34 @@ def lead_unpushed(self) -> bool: limit = self.profile.max_local_rounds_ahead return limit is not None and self.retained_round <= self.local_round - limit + def _wait_opens_no_blocker(self) -> bool: + """Whether a lead wait poll must open no new pair. + + A pair opened now is retained at :attr:`local_round`; it blocks this + wait when ``local_round <= local_round + 1 - K``, i.e. for K = 1. Such a + pair is opened only for the push the wait waits for + (:meth:`lead_unpushed`). Otherwise each PULL that arrives while the + wait's own pushes merge would add a push from the same, already pushed + cut and hold the wait one more merge: a slow island, whose pushes + complete the merges a fast island already pushed to, then sits at + its boundary while the fast island trains a round per merge, and the + fast island's lead grows without a bound. The held PULLs are answered + at the next boundary, from the newer cut.""" + + limit = self.profile.max_local_rounds_ahead + return limit is not None and self.local_round <= self.local_round + 1 - limit and not self.lead_unpushed() + async def wait_for_lead(self, serve: Any = None) -> float: """Lead cap: block at this boundary while :meth:`lead_blockers` is not empty or :meth:`lead_unpushed` holds. - The wait keeps the island's sync duties: every poll materializes and - pushes PULLs it has candidates for (from this boundary's cut), applies - arrived broadcasts, and runs ``serve`` (peer snapshots). It stops at - once when the terminal phase starts (``any_finalizing``): the terminal - barrier then waits instead. + The wait keeps the island's sync duties: every poll replays and + harvests its pushes, applies arrived broadcasts, and runs ``serve`` + (peer snapshots). It materializes and pushes new PULLs (from this + boundary's cut) only where such a push cannot hold the wait itself + (:meth:`_wait_opens_no_blocker`). It stops at once when the terminal + phase starts (``any_finalizing``): the terminal barrier then waits + instead. No new timer: each pair's wait timeout keeps running inside :meth:`submit_ready`, so a broadcast that never comes still fails @@ -968,7 +996,8 @@ async def wait_for_lead(self, serve: Any = None) -> float: ``wait_timeout`` since its last push, before that pair could time out. This also breaks a theoretical deadlock where each island waits for a push the other can make only after training (possible only when two - broadcasts reach the two islands in different orders). + broadcasts, or two PULLs a K = 1 wait holds, reach the two islands in + different orders). Returns the seconds this boundary waited.""" @@ -988,8 +1017,12 @@ async def wait_for_lead(self, serve: Any = None) -> float: f"(lead cap {self.profile.max_local_rounds_ahead})", file=sys.stderr, flush=True) while True: await asyncio.sleep(poll) - await self.prepare_submissions() - self.submit_ready() + self._no_new_pairs = self._wait_opens_no_blocker() + try: + await self.prepare_submissions() + self.submit_ready() + finally: + self._no_new_pairs = False await self.commit_staged_broadcasts() if serve is not None: await serve() From 10e61d1821d8db8c93902dba44a1da0b59b3f75e Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 01:28:06 +0800 Subject: [PATCH 2/4] tests: the lead wait give-up cases run on an injected clock, not wall-clock bounds test_the_wait_for_a_late_pull_gives_up_at_half_the_wait_timeout failed once on a loaded host (four parallel shards, load about 58): it and test_the_wait_gives_up_at_half_the_wait_timeout_and_never_times_out_itself asserted that a wait with real 50 ms polls ends within 0.4 s. A loaded host stretches real sleeps, so the upper bound fails while the give-up logic is right. The pairing module's clock is now replaceable as a whole: the one place that bound time.monotonic at class definition (PairedSubmission.retained_at) reads it at construction through the module's time, like every other call. The default clock stays time.monotonic and is read at the same moment, so production timing is unchanged. The tests install a clock that only the module's own sleeps (the wait's polls) advance and assert the give-up time exactly; the two new K = 1 / K = 2 wait cases use it too. Co-Authored-By: Claude Opus 5.5 --- tests/test_sync_lead_cap.py | 58 ++++++++++++++++++++++----- yeto/rl/engine/full_parameter_sync.py | 4 +- 2 files changed, 51 insertions(+), 11 deletions(-) diff --git a/tests/test_sync_lead_cap.py b/tests/test_sync_lead_cap.py index 71316a4e0..c78b099d2 100644 --- a/tests/test_sync_lead_cap.py +++ b/tests/test_sync_lead_cap.py @@ -38,7 +38,9 @@ from yeto.protocol import PullRequest from yeto.rl.adapters.miles.full_parameter.role_stream import RoleSubmissionCandidate +from yeto.rl.engine import full_parameter_sync as pairing_module from yeto.rl.engine.full_parameter_sync import ( + LEAD_WAIT_POLL_S, FullParameterSync, FullParameterSyncProfile, RolePairing, @@ -61,6 +63,39 @@ def _candidate(global_step: int, local_step: int) -> RoleSubmissionCandidate: payload_bytes=8, submission_cut=object(), anchor=object()) +class _ModuleShim: + """``module`` with some attributes replaced.""" + + def __init__(self, module, **replaced): + self._module = module + self.__dict__.update(replaced) + + def __getattr__(self, name): + return getattr(self._module, name) + + +@pytest.fixture +def lead_clock(monkeypatch): + """The pairing module's clock, advanced only by the module's own sleeps (the + lead wait's polls): give-up and timeout arithmetic without a wall-clock bound, + which a loaded host breaks by stretching real sleeps. Returns the clock.""" + now = [1024.0] + real_sleep = asyncio.sleep + + async def sleep(delay, result=None): + now[0] += delay + await real_sleep(0) + return result + + monkeypatch.setattr(pairing_module, "time", _ModuleShim(time, monotonic=lambda: now[0])) + monkeypatch.setattr(pairing_module, "asyncio", _ModuleShim(asyncio, sleep=sleep)) + return lambda: now[0] + + +# One poll of float error on either side of a computed give-up time. +_EPS = 1e-9 + + def _pairing(role, **profile): role.fragment_versions = (0, 0) return RolePairing({"actor": role}, _profile(**profile)) @@ -116,14 +151,16 @@ async def serve(): @pytest.mark.asyncio -async def test_the_wait_gives_up_at_half_the_wait_timeout_and_never_times_out_itself(): +async def test_the_wait_gives_up_at_half_the_wait_timeout_and_never_times_out_itself(lead_clock): role = _PairedRole("actor", [_candidate(1, 1)], [], release_broadcasts=False) pairing = _pairing(role, max_local_rounds_ahead=1, wait_timeout=0.4) pairing.local_round = 1 pairing.submit_ready() - started = time.monotonic() - await pairing.wait_for_lead() - assert 0.15 <= time.monotonic() - started < 0.4 # half of 0.4 s, before the pair's timeout + started = lead_clock() + waited = await pairing.wait_for_lead() + # The first poll at or past half of 0.4 s gives up, long before the pair's 0.4 s timeout. + assert 0.2 - _EPS <= lead_clock() - started < 0.2 + LEAD_WAIT_POLL_S + _EPS + assert waited == pytest.approx(lead_clock() - started) assert (pairing.lead_waits, pairing.lead_wait_escapes) == (1, 1) assert len(pairing.inflight) == 1 and pairing.failure is None @@ -157,19 +194,20 @@ async def serve(): @pytest.mark.asyncio -async def test_the_wait_for_a_late_pull_gives_up_at_half_the_wait_timeout(): +async def test_the_wait_for_a_late_pull_gives_up_at_half_the_wait_timeout(lead_clock): role = _PairedRole("actor", [_candidate(1, 1)], []) pairing = _pairing(role, max_local_rounds_ahead=1, wait_timeout=0.4) pairing.local_round = 1 pairing.submit_ready() await pairing.commit_staged_broadcasts() pairing.local_round = 2 - started = time.monotonic() + started = lead_clock() # the push of round 1 was retained at this time await pairing.wait_for_lead() - assert 0.1 <= time.monotonic() - started < 0.4 + assert 0.2 - _EPS <= lead_clock() - started < 0.2 + LEAD_WAIT_POLL_S + _EPS assert (pairing.lead_waits, pairing.lead_wait_escapes) == (1, 1) pairing.local_round = 3 - assert await pairing.wait_for_lead() > 0 # past the give-up time: one poll, then trains on + # Past the give-up time: one poll, then trains on. + assert await pairing.wait_for_lead() == pytest.approx(LEAD_WAIT_POLL_S) assert pairing.lead_wait_escapes == 2 @@ -189,7 +227,7 @@ async def stage_available_broadcasts(self): @pytest.mark.asyncio -async def test_with_k_1_the_wait_opens_no_pair_that_would_hold_it(): +async def test_with_k_1_the_wait_opens_no_pair_that_would_hold_it(lead_clock): """A PULL that arrives during a K = 1 wait is not pushed from the cut the island already pushed: that push would block the wait itself, so each PULL arriving while the wait's pushes merge held the island one merge @@ -220,7 +258,7 @@ async def serve(): @pytest.mark.asyncio -async def test_with_k_2_the_wait_still_pushes_a_pull_that_cannot_hold_it(): +async def test_with_k_2_the_wait_still_pushes_a_pull_that_cannot_hold_it(lead_clock): """With K = 2 a pair from the current cut does not block this wait (one round may train on top of it), so the wait keeps answering PULLs.""" role = _PeerPacedRole([_candidate(1, 1)]) diff --git a/yeto/rl/engine/full_parameter_sync.py b/yeto/rl/engine/full_parameter_sync.py index 0bfa07937..88f7aa5ec 100644 --- a/yeto/rl/engine/full_parameter_sync.py +++ b/yeto/rl/engine/full_parameter_sync.py @@ -249,7 +249,9 @@ class PairedSubmission: candidates: dict[str, Any] submissions: dict[str, Any] = field(default_factory=dict) - retained_at: float = field(default_factory=time.monotonic) + # Read at construction like every other time.monotonic() here, through the + # module's ``time`` (one clock a test can replace for the whole module). + retained_at: float = field(default_factory=lambda: time.monotonic()) # The island's local round (RolePairing.local_round) when it retained the # pair: the round whose cut the pair pushes (lead cap). local_round: int = 0 From 2eec841a5873cd46dc1b5ecd4e5914cab7e427db Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 04:37:58 +0800 Subject: [PATCH 3/4] fix(lead cap): K = 1 waits for a fixed window of global steps The K = 1 rule of the first fix (a wait opens no pair that would hold it) left two holes. Crossed PULL orders, as a sharded head delivers them, made two islands each wait for a push the other makes only after training (both waits escaped at half the wait timeout). PULLs that arrived in order but late were answered one boundary later, from a newer cut, so the lead grew with the run. K = 1 now cuts the global steps into fixed windows of P (the pipeline depth) steps. Each local round takes the window of the smallest open step, pushes every PULL of that window from its cut (also late and out-of-order ones, during the wait), holds the others, and trains the next round once the window closed. With a fixed roster every island pushes window b from a cut of round b or later, so a fast island stays at most one local round ahead of the slowest for any order and delay of PULLs and broadcasts, and no wait holds a step another island needs. A window closes without the island when its steps can (quorum below the island count, soft deadline, an island that left): no lock and no escape, but no lead bound then. A joining or relaunched process takes the window of its first open step. The terminal phase ends any wait and lifts the window, so the final cut answers every PULL left. K >= 2 and the cap off are unchanged. Tests: window, crossing, quorum, join, terminal, replay and held-PULL cases on fakes; the verl parity lead cap case under late broadcasts, late PULLs and crossed PULLs, with quorum 1 of 2, and with an island that leaves and catches up. The flag help and CLI reference state the bound and the cost (one window in flight per local round, also with several syncer shards). Co-Authored-By: Claude Opus 5.5 --- docs/CLI_REFERENCE.md | 1 + tests/test_sync_lead_cap.py | 362 ++++++++++++++++++++++---- tests/test_verl_miles_parity.py | 165 ++++++++++-- yeto/rl/engine/full_parameter_sync.py | 195 +++++++++----- yeto/rl/engine/run_flags.py | 15 +- 5 files changed, 593 insertions(+), 145 deletions(-) diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index b90b764ef..28d3b5160 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -676,6 +676,7 @@ injection and are omitted here. | `--rl-sync-push-dtype` | `f32` | full-parameter push dtype: `f32`, `bf16`, `int8`, `int4`, `int4-log` | | `--rl-sync-quorum` | — | islands whose pushes close a round | | `--rl-sync-max-base-lag` | `0` | rounds a push's base may lag | +| `--rl-sync-max-local-rounds-ahead` | off | full-parameter async rounds: lead cap K. K=1 pushes one window of `--rl-sync-fragment-pipeline` global steps per local round and starts the next round once the window merged. With a fixed roster a fast island then stays at most one local round ahead of the slowest. With a quorum below the island count, a soft deadline or islands leaving, the lead is not bounded. Cost: one window of steps in flight per local round, also with several `--syncer-shards` | | `--rl-sync-learner-weight` | `equal` | `equal` or `tokens2-over-steps` | | `--rl-sync-outer-lr`, `--rl-sync-outer-momentum` | — | outer Nesterov parameters (default from the preset) | diff --git a/tests/test_sync_lead_cap.py b/tests/test_sync_lead_cap.py index c78b099d2..92045618a 100644 --- a/tests/test_sync_lead_cap.py +++ b/tests/test_sync_lead_cap.py @@ -2,17 +2,22 @@ ``--rl-sync-max-local-rounds-ahead K`` (island ``--sweep-max-local-rounds-ahead``) makes an island wait at a boundary instead of training a K-th local round on -top of an unmerged push of its own. With a fixed roster (quorum 2 of 2) every -merge needs every island, so with K = 1 a fast island stays at most one local -round ahead of a slow one instead of training rounds whose progress the next -broadcast overwrites and whose c_steps inflate its tokens^2/steps merge weight. - -Covered here: the pairing rule on fakes (who blocks, the half-timeout escape, -the terminal phase, peer snapshots during the wait, no push during a wait that -would hold the wait itself), the profile and the -launcher/island wiring (default off, hashes unchanged), and two islands of -the real pairing and session (:class:`FullParameterSync`) against the real -Rust syncer: a fast island and a slow island, with and without the cap. +top of an unmerged push of its own. K = 1 cuts the global steps into windows +of P (the pipeline depth) steps: each local round pushes one window from its +cut and the next round starts once the window merged. With a fixed roster +(quorum 2 of 2) every step needs every island, so a fast island stays at most +one local round ahead of a slow one instead of training rounds whose progress +the next broadcast overwrites and whose c_steps inflate its tokens^2/steps +merge weight. + +Covered here: the pairing rule on fakes (who blocks, the step window: late and +crossed PULLs of the window, the next window held, steps closed without the +island, a caught-up island, the last window, replays, deferred capture; the +half-timeout escape, the terminal phase, peer snapshots during the wait), the +profile and the launcher/island wiring (default off, hashes unchanged), and +two islands of the real pairing and session (:class:`FullParameterSync`) +against the real Rust syncer: a fast island and a slow island, with and +without the cap. """ from __future__ import annotations @@ -166,30 +171,30 @@ async def test_the_wait_gives_up_at_half_the_wait_timeout_and_never_times_out_it @pytest.mark.asyncio -async def test_the_wait_also_covers_rounds_trained_before_the_next_pull_arrives(): - """After a merge and before the syncer's next PULL nothing is in flight, +async def test_the_wait_also_covers_rounds_trained_before_the_next_pull_arrives(lead_clock): + """After a merge and before the syncer's next PULLs nothing is in flight, but a round trained then lands in the next push all the same: with K = 1 - the island waits until it pushed from its current cut and that merged.""" - role = _PairedRole("actor", [_candidate(1, 1)], []) + the island waits until the next window, pushed from its current cut, merged.""" + role = _PairedRole("actor", [_candidate(1, 1), _candidate(2, 1)], []) pairing = _pairing(role, max_local_rounds_ahead=1) pairing.local_round = 1 pairing.submit_ready() await pairing.commit_staged_broadcasts() - assert pairing.inflight == {} and role.fragment_versions == (1, 0) - assert await pairing.wait_for_lead() == 0.0 # pushed from this round's cut - pairing.local_round = 2 # trained one more round; the next PULL is late - assert pairing.lead_blockers() == [] and pairing.lead_unpushed() + assert pairing.inflight == {} and role.fragment_versions == (1, 2) + assert await pairing.wait_for_lead() == 0.0 # window 1..2 pushed from this round's cut and merged + pairing.local_round = 2 # trained one more round; the PULLs of window 3..4 are late + assert pairing.lead_window() == (3, 4) and pairing.lead_window_open() served = [] async def serve(): - served.append(time.monotonic()) + served.append(lead_clock()) if len(served) == 3: - role.candidates.append(_candidate(3, 2)) # the next PULL arrives + role.candidates.extend([_candidate(3, 2), _candidate(4, 2)]) # the next PULLs arrive return 0 assert await pairing.wait_for_lead(serve) > 0 - assert len(served) >= 4 and ("actor", 3, True) in role.events - assert pairing.inflight == {} and role.fragment_versions == (3, 0) + assert len(served) >= 4 and ("actor", 3, True) in role.events and ("actor", 4, True) in role.events + assert pairing.inflight == {} and role.fragment_versions == (3, 4) assert (pairing.lead_waits, pairing.lead_wait_escapes) == (1, 0) @@ -213,48 +218,307 @@ async def test_the_wait_for_a_late_pull_gives_up_at_half_the_wait_timeout(lead_c class _PeerPacedRole(_PairedRole): """A role whose broadcast of a step arrives only once the peer island - pushed that step too (``peer_pushed``): a fixed roster's merge.""" + pushed that step too (``peer_pushed``): a fixed roster's merge. + ``close_without_me`` stages a step this island never pushed (a quorum + below the island count, a soft deadline).""" - def __init__(self, candidates): + def __init__(self, candidates, *, roster=None, learner=0): super().__init__("actor", candidates, [], release_broadcasts=False) self.peer_pushed: set[int] = set() + self.roster = roster # a shared _Roster: a step merges once every island pushed it + self.learner = learner + + def push_candidate(self, candidate): + submission = super().push_candidate(candidate) + if self.roster is not None and submission is not None: + self.roster.pushed.setdefault(candidate.permit.global_step, set()).add(self.learner) + return submission + + def close_without_me(self, step): + self._staged_steps.append(step) async def stage_available_broadcasts(self): - for step in [step for step in self._queued_steps if step in self.peer_pushed]: + def merged(step): + if self.roster is not None: + return self.roster.pushed.get(step, set()) >= self.roster.islands + return step in self.peer_pushed + + for step in [step for step in self._queued_steps if merged(step)]: self._queued_steps.remove(step) self._staged_steps.append(step) return await super().stage_available_broadcasts() +class _Roster: + """A fixed roster on fakes: every island must push a step before it merges.""" + + def __init__(self, islands): + self.islands = set(islands) + self.pushed: dict[int, set[int]] = {} + + +def _pushed(role): + return [step for _, step, _ in role.events] + + @pytest.mark.asyncio -async def test_with_k_1_the_wait_opens_no_pair_that_would_hold_it(lead_clock): - """A PULL that arrives during a K = 1 wait is not pushed from the cut the - island already pushed: that push would block the wait itself, so each - PULL arriving while the wait's pushes merge held the island one merge - longer (a slow island sat at its boundary while a fast island trained a - round per merge). The wait ends when the pushes it waited for merged; the - held PULL goes out at the next boundary, from the newer cut.""" +async def test_with_k_1_the_wait_answers_its_window_late_and_holds_the_next_window(lead_clock): + """The window of round 1 is steps 1..2 (P = 2). Step 2's PULL arrives during + the wait: it is still pushed from cut 1 (a fast island absorbs a late PULL of + its window instead of pushing it from its next cut, where it would merge at + once with the slow island's push from an older cut). Step 3's PULL (the next + window) is held: pushing it from cut 1 would hold the wait one more merge, and + a slow island would sit at its boundary while a fast island trained a round + per merge. The held PULL goes out at the next boundary, from cut 2.""" role = _PeerPacedRole([_candidate(1, 1)]) - pairing = _pairing(role, max_local_rounds_ahead=1, wait_timeout=2.0) + pairing = _pairing(role, max_local_rounds_ahead=1) pairing.local_round = 1 pairing.submit_ready() + assert pairing.lead_window() == (1, 2) served = [] async def serve(): served.append(len(served)) if len(served) == 1: - role.candidates.append(_candidate(2, 1)) # the next round opens during the wait + role.candidates.extend([_candidate(2, 1), _candidate(3, 1)]) # late, and the next window if len(served) == 3: - role.peer_pushed.add(1) # the peer pushed step 1: it merges + role.peer_pushed.update({1, 2}) # the peer pushed window 1..2: it merges return 0 assert await pairing.wait_for_lead(serve) > 0 assert (pairing.lead_waits, pairing.lead_wait_escapes) == (1, 0) - assert pairing.inflight == {} and role.fragment_versions == (1, 0) - assert [step for _, step, _ in role.events] == [1] # step 2 was not pushed from cut 1 + assert pairing.inflight == {} and role.fragment_versions == (1, 2) + assert _pushed(role) == [1, 2] # step 3 was not pushed from cut 1 pairing.local_round = 2 pairing.submit_ready() - assert [(key[0], pair.local_round) for key, pair in pairing.inflight.items()] == [(2, 2)] + assert pairing.lead_window() == (3, 4) + assert [(key[0], pair.local_round) for key, pair in pairing.inflight.items()] == [(3, 2)] + + +@pytest.mark.asyncio +async def test_with_k_1_a_wait_entered_before_any_pull_answers_each_pull_of_its_window(lead_clock): + """The window is decided once per round: a wait entered with nothing pushed + pushes the first PULL of its window, keeps answering the window's PULLs as + they come, and still holds the next window's.""" + role = _PeerPacedRole([]) + pairing = _pairing(role, max_local_rounds_ahead=1) + pairing.local_round = 1 + pairing.submit_ready() + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + role.candidates.append(_candidate(1, 1)) + if len(served) == 2: + role.candidates.append(_candidate(3, 1)) # next window: held + if len(served) == 3: + role.candidates.append(_candidate(2, 1)) # still this window: pushed + if len(served) == 4: + cuts.extend(sorted((key[0], pair.local_round) for key, pair in pairing.inflight.items())) + role.peer_pushed.update({1, 2}) + return 0 + + cuts: list[tuple[int, int]] = [] + assert await pairing.wait_for_lead(serve) > 0 + assert _pushed(role) == [1, 2] and pairing.lead_wait_escapes == 0 + assert cuts == [(1, 1), (2, 1)] # both from cut 1 + + +@pytest.mark.asyncio +async def test_with_k_1_crossed_pull_orders_do_not_lock_two_islands(lead_clock): + """Island A sees only step 2 at its boundary, island B only step 1; each one's + missing PULL arrives during its wait. Both are of the window, so each island + pushes it and both windows merge: no island waits for a step the other holds + (a sharded head merges PULLs of several shards in no fixed order).""" + roster = _Roster({0, 1}) + a = _PeerPacedRole([_candidate(2, 1)], roster=roster, learner=0) + b = _PeerPacedRole([_candidate(1, 1)], roster=roster, learner=1) + pa, pb = _pairing(a, max_local_rounds_ahead=1), _pairing(b, max_local_rounds_ahead=1) + for pairing in (pa, pb): + pairing.local_round = 1 + pairing.submit_ready() + assert (_pushed(a), _pushed(b)) == ([2], [1]) + + def late(role, step): + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + role.candidates.append(_candidate(step, 1)) + return 0 + return serve + + await asyncio.gather(pa.wait_for_lead(late(a, 1)), pb.wait_for_lead(late(b, 2))) + assert (pa.lead_wait_escapes, pb.lead_wait_escapes) == (0, 0) + assert sorted(_pushed(a)) == sorted(_pushed(b)) == [1, 2] + assert a.fragment_versions == b.fragment_versions == (1, 2) + + +@pytest.mark.asyncio +async def test_with_k_1_a_step_closed_without_the_island_closes_its_window(lead_clock): + """A quorum below the island count or a soft deadline closes a step without + this island: the window closes all the same (no wait, no escape), and the + next round takes the window of the smallest open step.""" + role = _PeerPacedRole([_candidate(1, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1) + pairing.local_round = 1 + pairing.submit_ready() + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 2: + role.peer_pushed.add(1) + role.close_without_me(2) # step 2 closed before its PULL reached this island + return 0 + + assert await pairing.wait_for_lead(serve) > 0 + assert pairing.lead_wait_escapes == 0 and _pushed(role) == [1] + assert role.fragment_versions == (1, 2) + pairing.local_round = 2 + assert pairing.lead_window() == (3, 4) + + +def test_with_k_1_a_caught_up_island_takes_the_window_of_its_first_open_step(): + """A joining or relaunched process starts from the syncer's fragments: its + first window is the one of the smallest step they leave open.""" + role = _PeerPacedRole([_candidate(7, 1), _candidate(9, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1) + role.fragment_versions = (5, 8) # steps 5 and 8 merged last: step 7 (fragment 0) is open + pairing.local_round = 1 + assert pairing.lead_window() == (7, 8) + pairing.submit_ready() + assert _pushed(role) == [7] # step 9 belongs to the next window + role.fragment_versions = (7, 8) + pairing.local_round = 2 + assert pairing.lead_window() == (9, 10) + + +@pytest.mark.asyncio +async def test_with_k_1_the_last_window_ends_at_the_last_step_and_the_terminal_phase_ends_a_wait(lead_clock): + role = _PeerPacedRole([_candidate(1, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1, total_fragment_steps=5) + role.fragment_versions = (3, 4) + pairing.local_round = 1 + assert pairing.lead_window() == (5, 5) # 5 steps, P = 2: the last window has one step + role.candidates[:] = [_candidate(5, 1)] + pairing.submit_ready() + assert pairing.lead_window_open() + pairing.terminal_seen = True # the data ended or the last rounds are ready mid-window + assert await pairing.wait_for_lead() == 0.0 + pairing.terminal_seen = False + + async def serve(): + pairing.terminal_seen = True # the terminal phase starts during the wait + return 0 + + assert await pairing.wait_for_lead(serve) == pytest.approx(LEAD_WAIT_POLL_S) + assert pairing.lead_wait_escapes == 0 + + +@pytest.mark.asyncio +async def test_with_k_1_the_terminal_phase_lifts_the_window_so_the_final_cut_answers_every_pull(lead_clock): + """The last rounds' PULLs (steps 5 and 6 of 6) arrive while a wait holds + window 3..4. They start the terminal phase, so no round trains after this + cut: the wait ends and the final cut answers them although they are past its + window (a window filter kept here leaves both islands waiting on each other).""" + role = _PeerPacedRole([_candidate(3, 2), _candidate(4, 2)]) + pairing = _pairing(role, max_local_rounds_ahead=1, total_fragment_steps=6) + role.fragment_versions = (1, 2) + pairing.local_round = 2 + pairing.submit_ready() + assert pairing.lead_window() == (3, 4) and _pushed(role) == [3, 4] + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + role.peer_pushed.update({3, 4}) + role.candidates.extend([_candidate(5, 2), _candidate(6, 2)]) + return 0 + + await pairing.wait_for_lead(serve) + assert pairing.any_finalizing and pairing.lead_wait_escapes == 0 + assert pairing.lead_window() == (3, 4) # still this round's window ... + pairing.submit_ready() + assert _pushed(role) == [3, 4, 5, 6] # ... but the final cut answers every PULL + + +@pytest.mark.asyncio +async def test_with_k_1_a_replayed_pull_of_a_pair_in_flight_is_answered_during_the_wait(lead_clock): + """After a redial (or a restarted syncer) the syncer re-sends the PULL of a + round the island already pushed: the retained pair replays its bytes at + once, the window does not hold it.""" + role = _PeerPacedRole([_candidate(1, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1) + pairing.local_round = 1 + pairing.submit_ready() + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + again = _candidate(1, 1) + role.candidates.append(replace(again, permit=PullRequest(0, 1, 2))) # attempt 2 + role.candidates.append(_candidate(2, 1)) + if len(served) == 3: + role.peer_pushed.update({1, 2}) + return 0 + + assert await pairing.wait_for_lead(serve) > 0 + assert _pushed(role) == [1, 1, 2] and pairing.lead_wait_escapes == 0 + assert role.fragment_versions == (1, 2) + + +class _DeferredRole(_PeerPacedRole): + """Deferred capture: a fragment is materialized only when planned for a push.""" + + def __init__(self, candidates, pairing_round): + super().__init__(candidates) + self.materialized: list[tuple[int, tuple[int, ...]]] = [] + self._round = pairing_round + + def ready_submission_candidates(self, include_deferred=False): + return super().ready_submission_candidates() + + async def materialize_submission(self, fragment_ids): + self.materialized.append((self._round(), tuple(fragment_ids))) + + +@pytest.mark.asyncio +async def test_with_k_1_a_held_pull_is_not_materialized_ahead(lead_clock): + holder = {} + role = _DeferredRole([_candidate(1, 1)], lambda: holder["pairing"].local_round) + pairing = holder["pairing"] = _pairing(role, max_local_rounds_ahead=1) + pairing.local_round = 1 + await pairing.prepare_submissions() + pairing.submit_ready() + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 1: + role.candidates.extend([_candidate(3, 1), _candidate(2, 1)]) # next window, this window + if len(served) == 3: + role.peer_pushed.update({1, 2}) + return 0 + + await pairing.wait_for_lead(serve) + # Cut 1 materialized fragment 0 (step 1) and fragment 1 (step 2), never step 3's. + assert role.materialized == [(1, (0,)), (1, (1,))] + pairing.local_round = 2 + await pairing.prepare_submissions() + assert role.materialized[-1] == (2, (0,)) + + +def test_a_pair_reads_the_injected_clock_when_it_is_retained(lead_clock): + from yeto.rl.engine.full_parameter_sync import PairedSubmission + + before = lead_clock() + pair = PairedSubmission({"actor": _candidate(1, 1)}) + assert pair.retained_at == before # read at construction, before any push @pytest.mark.asyncio @@ -696,13 +960,11 @@ def test_real_syncer_fast_island_stays_within_the_cap_and_both_islands_join_ever assert not unmerged, (value, unmerged) # ... and only after it pushed from its newest cut (round r). assert value == 1 or value - 1 in fast_pushes.values(), (value, fast_pushes) - # So it stays close to the slow island: one round ahead, or two when a - # PULL reached the fast island only after its boundary and the slow - # island's push of it, from the same cut as the round before, completed - # a second merge of the fast island. A K = 1 wait never pushes from the - # cut it already pushed, so a slow island's wait cannot chain such - # pushes (test_with_k_1_the_wait_opens_no_pair_that_would_hold_it). - assert _max_lead(capped.log) <= 2 + # So it never starts a round before the slow island completed as many: + # every island pushes window b of P steps from a cut of round b or later + # (RolePairing.lead_window), and the fast island starts round b + 1 only + # once window b merged. + assert _max_lead(capped.log) <= 0 waits = [fields for _, kind, who, (name, fields) in ((t, k, w, v) for t, k, w, v in capped.log if k == "event") if who == 0 and name == "rl_full_parameter_round"] @@ -712,10 +974,10 @@ def test_real_syncer_fast_island_stays_within_the_cap_and_both_islands_join_ever # Which local round a push carries depends on wall-clock order. One slow # boundary closes two rounds a few ms apart (the syncer writes a checkpoint # before each broadcast), and the syncer paces the PULLs of new rounds, so - # whether a PULL is visible at the fast island's boundary or arrives during - # its lead wait (then it is pushed at the next boundary, from the newer - # cut: a K = 1 wait pushes nothing from the cut it already pushed) depends - # on wall-clock order. Both schedules keep the cap. The syncer orders a + # whether a PULL of the next window is visible at the fast island's + # boundary or arrives during its lead wait (then it is pushed at the next + # boundary, from the newer cut: a K = 1 wait pushes only its own window) + # depends on wall-clock order. Both schedules keep the cap. The syncer orders a # round's pushes by learner id (server.rs), so arrival order inside a # round does not change the merge. _check_merges instead checks that the # result equals, up to float32 rounding, the merge of this run's pushes. diff --git a/tests/test_verl_miles_parity.py b/tests/test_verl_miles_parity.py index 674a74969..af433f25f 100644 --- a/tests/test_verl_miles_parity.py +++ b/tests/test_verl_miles_parity.py @@ -386,13 +386,15 @@ def train(self, learner_id: int, round_id: int) -> None: def _train_rounds(learner_id, plan, results, *, stop_after=None, pace_s=0.05, max_rounds=4000, - harness=_Fsdp2Harness, in_pool=None, hold=None): + harness=_Fsdp2Harness, in_pool=None, hold=None, trace=None): """One verl island process: train and sync until the final cut, or die (close its links, no LEAVE) after ``stop_after`` rounds. ``pace_s`` per local round: quorum 1 lets an island run far ahead of the syncer's steps. ``in_pool`` (an Event) is set once this process joined and cleared when it dies; ``hold()``, before each local round, may block until another island's - process is in the pool (events, never a wall-clock guess).""" + process is in the pool (events, never a wall-clock guess). ``trace(kind, + learner, round)`` logs each round's ``start`` and, once trained (before its + boundary pushes), ``trained``.""" trainer = harness() island = trainer.island sync, _policy_state, stream = vfs.build_full_parameter_sync(island, plan, backend_identity_sha256="c" * 64) @@ -415,7 +417,11 @@ def _train_rounds(learner_id, plan, results, *, stop_after=None, pace_s=0.05, ma return if hold is not None: hold() + if trace is not None: + trace("start", learner_id, round_id) trainer.train(learner_id, round_id) + if trace is not None: + trace("trained", learner_id, round_id) ids = (f"l{learner_id}-p{id(record)}-r{round_id}",) batch_hash = hashlib.sha256(ids[0].encode()).hexdigest() policy_hash = state.policy_tensor_hash() @@ -450,7 +456,7 @@ def test_a_restarted_verl_island_catches_up_from_the_running_pool_and_finishes(s def run_catch_up_case(syncer_binary, tmp_path, monkeypatch, *, harness=_Fsdp2Harness, layout=None, - plan_fn=None): + plan_fn=None): # returns the islands' records """Island 1 dies after 3 rounds and a new process of it joins the running pool (catch-up, no peer recovery) and finishes with island 0. ``harness``, ``layout`` and ``plan_fn`` give the island's trainer, its layout @@ -565,19 +571,86 @@ def drain_and_leave(): assert pushed == [1] and closed["arrived"] == 1 and 0 in closed["absent"], (step, closed) assert all(base < closed["base_version"] and carried.get((learner, step), step) < step for learner, base in older), (step, closed, carried) + return results -@needs_cargo -def test_the_lead_cap_holds_a_fast_verl_island_to_the_slow_one(syncer_binary, tmp_path, monkeypatch): - """K = 1 with a fixed roster (quorum 2): the fast island waits at its - boundaries for the slow island's pushes; the cap fields reach its events.""" +def _held(drain, delay, *, in_order=False): + """``drain`` handing out each PULL or broadcast only ``delay(item)`` s after it + arrived; ``in_order`` also holds every later item behind a held one.""" + pending: list = [] + lock = threading.Lock() + + def drained(): + with lock: + pending.extend(drain()) + now = time.monotonic() + if in_order: + out = [] + while pending and now >= pending[0].received_at + delay(pending[0]): + out.append(pending.pop(0)) + return out + out = [item for item in pending if now >= item.received_at + delay(item)] + pending[:] = [item for item in pending if now < item.received_at + delay(item)] + return out + return drained + + +def _inject(monkeypatch, injection): + """Delivery the lead cap must not depend on: the slow island's broadcasts + 60 ms late; every other PULL 50 ms late, in order; PULL pairs crossed (island + 0 gets each window's second step first, island 1 its first).""" + from yeto.rl.engine import full_parameter_stream as engine_stream + + real_client = engine_stream.SyncerClient + + def client_factory(*args, **kwargs): + client = real_client(*args, **kwargs) + learner = int(args[1]) + if injection == "late-broadcasts" and learner == 1: + client.drain_updates = _held(client.drain_updates, lambda update: 0.06) + elif injection == "late-pulls": + client.drain_pulls = _held(client.drain_pulls, lambda permit: 0.05 * (permit.global_step % 2 == 0), + in_order=True) + elif injection == "crossed-pulls": + client.drain_pulls = _held(client.drain_pulls, + lambda permit: 0.08 * (permit.global_step % 2 == (learner + 1) % 2)) + return client + + if injection != "none": + monkeypatch.setattr(engine_stream, "SyncerClient", client_factory) + + +def _lead(trace, fast=0, slow=1) -> int: + """Largest (rounds the fast island started) - (rounds the slow island trained) + at a start of the fast island. ``trained`` is logged before that round's + boundary pushes, so before any merge the push is part of.""" + trained = {fast: 0, slow: 0} + lead = 0 + for kind, learner, round_id in trace: + if kind == "trained": + trained[learner] = max(trained[learner], round_id + 1) + elif kind == "start" and learner == fast: + lead = max(lead, round_id + 1 - trained[slow]) + return lead + + +def run_lead_cap_case(syncer_binary, tmp_path, monkeypatch, *, injection="none", quorum=2, rounds=4): + """A fast (unpaced) and a slow island with K = 1; returns their records and the trace.""" monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", "verl-parity-lead-cap-key") monkeypatch.setenv("TOKIO_WORKER_THREADS", "4") - rounds, fragments = 4, len(_layout(matrix_merge="rda").fragments.fragments) + _inject(monkeypatch, injection) + fragments = len(_layout(matrix_merge="rda").fragments.fragments) process, port, profile = _start_syncer(syncer_binary, tmp_path, fragments=fragments, rounds=rounds, extra=( "--rl-sync-full-parameter-rounds", "async", "--rl-sync-final-cut", "download", - "--rl-sync-quorum", "2", "--rl-sync-max-local-rounds-ahead", "1")) + "--rl-sync-quorum", str(quorum), "--rl-sync-max-local-rounds-ahead", "1")) results: dict = {} + lock = threading.Lock() + trace: list = [] + + def log(kind, learner, round_id): + with lock: + trace.append((kind, learner, round_id)) + try: plans = [] for i in range(2): @@ -585,31 +658,77 @@ def test_the_lead_cap_holds_a_fast_verl_island_to_the_slow_one(syncer_binary, tm matrix_merge="rda", pipeline=2, final_cut="download") plan[vfs.PLAN_KEY]["max_local_rounds_ahead"] = 1 plans.append(plan) - threads = [threading.Thread(target=_train_rounds, args=(0, plans[0], results), kwargs={"pace_s": 0.0}), - threading.Thread(target=_train_rounds, args=(1, plans[1], results), kwargs={"pace_s": 0.3})] + threads = [threading.Thread(target=_train_rounds, args=(0, plans[0], results), + kwargs={"pace_s": 0.0, "trace": log}), + threading.Thread(target=_train_rounds, args=(1, plans[1], results), + kwargs={"pace_s": 0.3, "trace": log})] for thread in threads: thread.start() for thread in threads: thread.join(timeout=180) + assert not any(thread.is_alive() for thread in threads), "islands did not finish" assert process.wait(timeout=30) == 0 finally: if process.poll() is None: process.terminate() - log = process.communicate(timeout=10)[0] + log_text = process.communicate(timeout=10)[0] fast, slow = results[0][0], results[1][0] - assert "error" not in fast and "error" not in slow, (fast.get("error"), slow.get("error"), log[-2000:]) - fast_rounds = [f for e, f in fast["events"] if e == "rl_full_parameter_round"] - slow_rounds = [f for e, f in slow["events"] if e == "rl_full_parameter_round"] + assert "error" not in fast and "error" not in slow, (fast.get("error"), slow.get("error"), log_text[-2000:]) + assert fast["final_ack"] == slow["final_ack"] == [{"acknowledged": True}] + return fast, slow, trace + + +def _rounds(record): + return [f for e, f in record["events"] if e == "rl_full_parameter_round"] + + +@needs_cargo +@pytest.mark.parametrize("injection", ["none", "late-broadcasts", "late-pulls", "crossed-pulls"]) +def test_the_lead_cap_holds_a_fast_verl_island_to_the_slow_one(syncer_binary, tmp_path, monkeypatch, injection): + """K = 1 with a fixed roster (quorum 2): the fast island waits at its + boundaries for the slow island's pushes; the cap fields reach its events. + The bound holds whatever order and delay PULLs and broadcasts arrive with.""" + fast, slow, trace = run_lead_cap_case(syncer_binary, tmp_path, monkeypatch, injection=injection) + fast_rounds, slow_rounds = _rounds(fast), _rounds(slow) assert all(f["sync/max_local_rounds_ahead"] == 1 for f in fast_rounds) assert fast_rounds[-1]["sync/lead_waits"] > 0, fast_rounds[-1] - assert fast_rounds[-1]["sync/lead_wait_escapes"] == 0, fast_rounds[-1] # no wait gave up and trained on - # Without the cap the unpaced island would run hundreds of local rounds meanwhile. - # This bound once failed on a loaded host (11 rounds against 8): the slow island's - # lead wait pushed each PULL arriving during the wait from the cut it had already - # pushed and so held itself at its boundary while the fast island trained a round - # per merge. A K = 1 wait no longer pushes from that cut (RolePairing.wait_for_lead). - assert len(fast_rounds) <= len(slow_rounds) + 2, (len(fast_rounds), len(slow_rounds)) - assert fast["final_ack"] == slow["final_ack"] == [{"acknowledged": True}] + for record in (fast, slow): # no wait gave up and trained on: no island held a step the other waited for + assert _rounds(record)[-1]["sync/lead_wait_escapes"] == 0, _rounds(record)[-1] + # Each local round pushes one window of P steps and the next starts once it + # merged: the fast island starts round b + 1 only after the slow island + # trained b rounds. (Without the cap the unpaced island would run hundreds of + # local rounds meanwhile.) + assert _lead(trace) <= 1, trace + assert len(fast_rounds) <= len(slow_rounds) + 1, (len(fast_rounds), len(slow_rounds)) + + +@needs_cargo +def test_with_a_quorum_below_the_islands_the_lead_cap_neither_locks_nor_gives_up(syncer_binary, tmp_path, + monkeypatch): + """Quorum 1 closes a step with its first push, so a window closes without the + slow island: K = 1 then bounds no lead, but no island waits for a step it is + not needed for (no escape) and both reach the final cut.""" + fast, slow, _ = run_lead_cap_case(syncer_binary, tmp_path, monkeypatch, quorum=1) + for record in (fast, slow): + assert _rounds(record)[-1]["sync/lead_wait_escapes"] == 0, _rounds(record)[-1] + + +def _capped_pool_plan(learner_id, port, profile, *, rounds, fragments): + plan = _pool_plan(learner_id, port, profile, rounds=rounds, fragments=fragments) + plan[vfs.PLAN_KEY]["max_local_rounds_ahead"] = 1 + return plan + + +@needs_cargo +def test_the_lead_cap_lets_an_island_leave_and_a_new_process_of_it_catch_up(syncer_binary, tmp_path, monkeypatch): + """K = 1 in a pool: island 1 dies (its open steps close on island 0), a new + process of it joins the running pool, takes the window of the first step its + caught-up fragments leave open, and both finish without a wait giving up.""" + results = run_catch_up_case(syncer_binary, tmp_path, monkeypatch, plan_fn=_capped_pool_plan) + for record in (results[0][0], results[1][1]): + rounds = _rounds(record) + assert rounds and all(f["sync/max_local_rounds_ahead"] == 1 for f in rounds) + assert rounds[-1]["sync/lead_wait_escapes"] == 0, rounds[-1] # ----------------------------------------------------------------------------- syncer-only options diff --git a/yeto/rl/engine/full_parameter_sync.py b/yeto/rl/engine/full_parameter_sync.py index 88f7aa5ec..ccd23f000 100644 --- a/yeto/rl/engine/full_parameter_sync.py +++ b/yeto/rl/engine/full_parameter_sync.py @@ -175,7 +175,8 @@ class FullParameterSyncProfile: partial_quorum: bool = False # Lead cap K (streaming only; None = off, the old behaviour): an # island trains at most K - 1 local rounds on top of an unmerged push of - # its own; K = 1 starts no round while one is unmerged (RolePairing.wait_for_lead). + # its own; K = 1 pushes one window of P global steps per local round and + # starts the next round once the window merged (RolePairing.lead_window). max_local_rounds_ahead: int | None = None def __post_init__(self) -> None: @@ -315,9 +316,10 @@ def __init__(self, streams: Mapping[str, RoleStream], profile: FullParameterSync self.lead_waits = 0 self.lead_wait_seconds = 0.0 self.lead_wait_escapes = 0 - # Set while a lead wait polls and must not open a pair that would hold - # the wait itself (:meth:`_wait_opens_no_blocker`). - self._no_new_pairs = False + # Lead cap K = 1: the global steps this island pushes from its current + # cut (:meth:`lead_window`), and the local round it was taken at. + self._lead_window: tuple[int, int] = (1, 0) + self._lead_window_round: int | None = None # Background pushes, decided at the first submit (a role # knows whether it can encode ahead once it is initialized); None # keeps every push on this thread. @@ -446,8 +448,8 @@ def submit_ready(self) -> dict[str, RoleProgress]: # push is harvested, and is no replay. continue self._push_once(pair, observed, produced) - capacity = self._new_pair_capacity() - shared = sorted(set.intersection(*(set(keys) for keys in by_role.values()))) + capacity = self.profile.effective_pipeline_depth - len(self.inflight) + shared = self._in_lead_window(sorted(set.intersection(*(set(keys) for keys in by_role.values())))) if self.profile.partial_quorum: # A round whose broadcast is staged or applied closed without # this island: pushing would only upload a refused delta. @@ -473,12 +475,6 @@ def submit_ready(self) -> dict[str, RoleProgress]: raise return {role: RoleProgress(submissions=tuple(values)) for role, values in produced.items()} - def _new_pair_capacity(self) -> int: - """Pipeline slots for new pairs: none while a lead wait holds them.""" - if self._no_new_pairs: - return 0 - return self.profile.effective_pipeline_depth - len(self.inflight) - def _replay_permits( self, by_role: Mapping[str, Mapping[LogicalKey, Any]] ) -> dict[str, Mapping[LogicalKey, Any]]: @@ -511,8 +507,9 @@ async def prepare_submissions(self) -> None: role: _candidate_map(stream.ready_submission_candidates(include_deferred=True), role=role) for role, stream in self.streams.items() } - capacity = self._new_pair_capacity() - shared = sorted(set.intersection(*(set(keys) for keys in by_role.values())) - set(self.inflight)) + capacity = self.profile.effective_pipeline_depth - len(self.inflight) + shared = self._in_lead_window( + sorted(set.intersection(*(set(keys) for keys in by_role.values())) - set(self.inflight))) if self.profile.partial_quorum: shared = [key for key in shared if not self._round_closed(key[1], key[0])] fragment_ids = [key[1] for key in shared[: max(0, capacity)]] @@ -933,17 +930,15 @@ def _journal(self, pair: PairedSubmission) -> None: # -- local-round lead cap ----------------------------------------- def lead_blockers(self) -> list[PairedSubmission]: - """In-flight pairs that stop the next local round under the lead cap K. + """In-flight pairs that stop the next local round under the lead cap K >= 2. At a boundary after local round ``r`` the next round is ``r + 1``. A pair retained at local round ``p`` (its cut is round ``p``) blocks when ``p <= r + 1 - K``: training round ``r + 1`` would put ``K`` or more - rounds on top of that unmerged push. With a fixed roster a merge needs - every island's push, so with K = 1 an island starts a round only after - every island pushed everything it pushed: it stays at most one local - round ahead of the slowest island. A larger K allows K - 1 rounds on - top of an unmerged push; that bounds the island's c_steps per push, - not its absolute lead (pushes made one boundary late can repeat).""" + rounds on top of that unmerged push. K - 1 rounds on top of an + unmerged push bound the island's c_steps per push, not its absolute + lead (pushes made one boundary late can repeat). K = 1 waits for its + step window instead (:meth:`lead_window`).""" limit = self.profile.max_local_rounds_ahead if limit is None: @@ -951,7 +946,7 @@ def lead_blockers(self) -> list[PairedSubmission]: return [pair for pair in self.inflight.values() if pair.local_round <= self.local_round + 1 - limit] def lead_unpushed(self) -> bool: - """Lead cap K: the island trained K rounds since it last retained a pair. + """Lead cap K >= 2: the island trained K rounds since it last retained a pair. Between a merge and the syncer's next PULL the island has no pair in flight, so :meth:`lead_blockers` is empty, yet every round it trains @@ -962,55 +957,127 @@ def lead_unpushed(self) -> bool: limit = self.profile.max_local_rounds_ahead return limit is not None and self.retained_round <= self.local_round - limit - def _wait_opens_no_blocker(self) -> bool: - """Whether a lead wait poll must open no new pair. + def _step_window_rule(self) -> bool: + return self.profile.max_local_rounds_ahead == 1 - A pair opened now is retained at :attr:`local_round`; it blocks this - wait when ``local_round <= local_round + 1 - K``, i.e. for K = 1. Such a - pair is opened only for the push the wait waits for - (:meth:`lead_unpushed`). Otherwise each PULL that arrives while the - wait's own pushes merge would add a push from the same, already pushed - cut and hold the wait one more merge: a slow island, whose pushes - complete the merges a fast island already pushed to, then sits at - its boundary while the fast island trains a round per merge, and the - fast island's lead grows without a bound. The held PULLs are answered - at the next boundary, from the newer cut.""" + def _step_closed(self, step: int) -> bool: + """Global step ``step`` merged (applied or staged), with or without this island.""" + return self._round_closed((step - 1) % self.profile.fragments, step) - limit = self.profile.max_local_rounds_ahead - return limit is not None and self.local_round <= self.local_round + 1 - limit and not self.lead_unpushed() + def _first_open_step(self) -> int: + """The smallest global step not closed yet (``total + 1`` when none is open). + + Step ``t`` merges fragment ``(t - 1) mod F`` (also on a sharded head, whose + shards run this schedule restricted to their fragments), and a fragment's + version is the step that last merged it, so each fragment's next step + follows from its version; staged broadcasts close later steps too.""" + + total, fragments = self.profile.total_fragment_steps, self.profile.fragments + first = total + 1 + for fragment_id in range(fragments): + version = min(stream.fragment_versions[fragment_id] for stream in self.streams.values()) + step = version + fragments if version > 0 else fragment_id + 1 + while step <= total and self._round_closed(fragment_id, step): + step += fragments + first = min(first, step) + return first + + def lead_window(self) -> tuple[int, int] | None: + """Lead cap K = 1: the global steps ``(first, last)`` this island answers + from its current cut; None when the rule is off (no cap, or K >= 2). + + The steps ``1..total`` are cut into fixed windows of P (the pipeline + depth) consecutive steps. At each local round the island takes the + window of the smallest step not closed yet and keeps it for the round: + it pushes every PULL of that window from this cut (at the boundary and + while it waits, so a PULL that arrives late or out of order is still + answered from this cut), holds every other PULL until a later boundary, + and trains the next round only once every step of the window closed. + + With a fixed roster every step needs every island's push, so every + island pushes window ``b`` from its own ``b``-th cut: when an island + starts round ``b + 1``, every other island has pushed from cut ``b``, + i.e. trained at least ``b`` rounds. A fast island is at most one local + round ahead of the slowest, whatever order or delay PULLs and + broadcasts arrive with, and no wait can hold another island's step + (each island answers the same window). + + When a step can close without this island (a quorum below the number + of islands, a soft deadline, an island that left), the window closes + without it and the island moves on to the window of the smallest open + step: no wait blocks on an island that is not needed, but an island + that missed a window no longer pushes window ``b`` from cut ``b``, so + the cap bounds no lead across islands then. A joining or relaunched + process takes the window of the smallest step its caught-up fragments + leave open. The last window ends at the last step; the terminal phase + ends any wait (``any_finalizing``) and lifts the window, so the final + cut answers every PULL left. + + Cost: one window (P steps) is in flight per local round, also on a + sharded syncer head whose shards could run P steps each.""" + + if not self._step_window_rule(): + return None + if self._lead_window_round != self.local_round: + pipeline, total = self.profile.effective_pipeline_depth, self.profile.total_fragment_steps + first = (self._first_open_step() - 1) // pipeline * pipeline + 1 + self._lead_window = (first, min(first + pipeline - 1, total)) + self._lead_window_round = self.local_round + return self._lead_window + + def _in_lead_window(self, keys: list[LogicalKey]) -> list[LogicalKey]: + """K = 1: the keys of this round's window. Once the terminal phase + started (``any_finalizing``) no round trains after this cut, so the + final cut answers every PULL, also those after its window: the last + rounds' PULLs can arrive while a wait holds an earlier window.""" + window = self.lead_window() + if window is None or self.any_finalizing: + return keys + first, last = window + return [key for key in keys if first <= key[0] <= last] + + def lead_window_open(self) -> bool: + """K = 1: a step of this round's window has not closed yet.""" + window = self.lead_window() + return window is not None and any(not self._step_closed(step) for step in range(window[0], window[1] + 1)) + + def _lead_blocked(self) -> bool: + if self._step_window_rule(): + return self.lead_window_open() + return bool(self.lead_blockers()) or self.lead_unpushed() async def wait_for_lead(self, serve: Any = None) -> float: - """Lead cap: block at this boundary while :meth:`lead_blockers` is not - empty or :meth:`lead_unpushed` holds. + """Lead cap: block at this boundary while K = 1's step window is open + (:meth:`lead_window`), or, for K >= 2, while :meth:`lead_blockers` is + not empty or :meth:`lead_unpushed` holds. - The wait keeps the island's sync duties: every poll replays and - harvests its pushes, applies arrived broadcasts, and runs ``serve`` - (peer snapshots). It materializes and pushes new PULLs (from this - boundary's cut) only where such a push cannot hold the wait itself - (:meth:`_wait_opens_no_blocker`). It stops at once when the terminal - phase starts (``any_finalizing``): the terminal barrier then waits - instead. + The wait keeps the island's sync duties: every poll materializes and + pushes the PULLs it has candidates for (from this boundary's cut; with + K = 1 only those of the window), replays and harvests its pushes, + applies arrived broadcasts, and runs ``serve`` (peer snapshots). It + stops at once when the terminal phase starts (``any_finalizing``): the + terminal barrier then waits instead. No new timer: each pair's wait timeout keeps running inside :meth:`submit_ready`, so a broadcast that never comes still fails there. The lead wait gives up (and the island trains on, the old - behaviour) once the oldest blocking pair has waited half of - ``wait_timeout`` since its last push, before that pair could time out. - This also breaks a theoretical deadlock where each island waits for a - push the other can make only after training (possible only when two - broadcasts, or two PULLs a K = 1 wait holds, reach the two islands in - different orders). + behaviour) once the oldest pair in flight has waited half of + ``wait_timeout`` since its last push, or, with none in flight, half of + it since the island last retained a pair, before a pair could time + out. Returns the seconds this boundary waited.""" - blockers = self.lead_blockers() - unpushed = self.lead_unpushed() - if (not blockers and not unpushed) or self.any_finalizing or self.failure is not None: + if not self._lead_blocked() or self.any_finalizing or self.failure is not None: return 0.0 started = time.monotonic() poll = max(self.profile.poll_seconds, LEAD_WAIT_POLL_S) escaped = False - if blockers: + window = self.lead_window() + if window is not None: + reason = f"steps {window[0]}..{window[1]} of its window are not all merged" + elif self.lead_blockers(): + blockers = self.lead_blockers() oldest = min(pair.local_round for pair in blockers) reason = f"{len(blockers)} pair(s) pushed at local round {oldest}.. are unmerged" else: @@ -1019,22 +1086,16 @@ async def wait_for_lead(self, serve: Any = None) -> float: f"(lead cap {self.profile.max_local_rounds_ahead})", file=sys.stderr, flush=True) while True: await asyncio.sleep(poll) - self._no_new_pairs = self._wait_opens_no_blocker() - try: - await self.prepare_submissions() - self.submit_ready() - finally: - self._no_new_pairs = False + await self.prepare_submissions() + self.submit_ready() await self.commit_staged_broadcasts() if serve is not None: await serve() - blockers = self.lead_blockers() - unpushed = self.lead_unpushed() - if (not blockers and not unpushed) or self.any_finalizing: + if not self._lead_blocked() or self.any_finalizing: break - since = min(pair.retained_at for pair in blockers) if blockers else self.retained_round_at - give_up = since + self.profile.wait_timeout / 2 - if time.monotonic() >= give_up: + pending = list(self.inflight.values()) if window is not None else self.lead_blockers() + since = min(pair.retained_at for pair in pending) if pending else self.retained_round_at + if time.monotonic() >= since + self.profile.wait_timeout / 2: escaped = True break waited = time.monotonic() - started diff --git a/yeto/rl/engine/run_flags.py b/yeto/rl/engine/run_flags.py index 8e6efe844..395e9bf75 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -1480,11 +1480,16 @@ def rl_forward_pairs(*dests: str | tuple[str, str]) -> tuple[tuple[str, str], .. default=None, help="full-parameter async rounds only: lead cap K >= 1 (default off). At a " "boundary an island waits, still pushing and applying, instead of training a " - "K-th local round on top of an unmerged push of its own. K=1 starts no round " - "while one of its pushes is unmerged: with a fixed roster a fast island stays " - "at most one local round ahead of the slowest island. The wait gives up (and " - "trains on) after half of --rl-sync-wait-timeout-s since that push. Island-local: " - "the layout, syncer profile and training contract hashes do not change", + "K-th local round on top of an unmerged push of its own. K=1 cuts the global " + "steps into windows of --rl-sync-fragment-pipeline steps: each local round " + "pushes one window from its cut and the next round starts once that window " + "merged, so with a fixed roster a fast island stays at most one local round " + "ahead of the slowest island (with a quorum below the island count, a soft " + "deadline or islands leaving, a window can close without an island and the " + "lead is not bounded). Cost of K=1: one window of steps is in flight per local " + "round, also with several --syncer-shards. The wait gives up (and trains on) " + "after half of --rl-sync-wait-timeout-s since the island's last push. " + "Island-local: the layout, syncer profile and training contract hashes do not change", ), cli_flag( "--rl-sync-wait-timeout-s", From 838a0b4dea4a7975e350fed7148d8bbb06388d81 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 06:33:26 +0800 Subject: [PATCH 4/4] tests(lead cap): guard the K = 1 window wait, window alignment and K >= 2 Review follow-ups: - A fake test for the core K = 1 rule: step 1 merged, step 2's PULL comes late; the next round waits until step 2, pushed from this cut, merged. The K >= 2 blocker rule trains on there (the linear lead growth). - Versions (7, 6) give the fixed window 7..8, not 8..9. - K = 2 keeps the lead_unpushed case (rounds trained after the last retained push count once nothing is in flight). - The deferred-capture case frees two pipeline slots, so a missing window filter would materialize the held step. - The flag help, CLI reference and wait docstring state where the give-up clock starts and that the lead is no longer bounded after a give-up. Co-Authored-By: Claude Opus 5.5 --- docs/CLI_REFERENCE.md | 2 +- tests/test_sync_lead_cap.py | 64 ++++++++++++++++++++++++++- yeto/rl/engine/full_parameter_sync.py | 5 ++- yeto/rl/engine/run_flags.py | 5 ++- 4 files changed, 70 insertions(+), 6 deletions(-) diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 28d3b5160..8c5450a6a 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -676,7 +676,7 @@ injection and are omitted here. | `--rl-sync-push-dtype` | `f32` | full-parameter push dtype: `f32`, `bf16`, `int8`, `int4`, `int4-log` | | `--rl-sync-quorum` | — | islands whose pushes close a round | | `--rl-sync-max-base-lag` | `0` | rounds a push's base may lag | -| `--rl-sync-max-local-rounds-ahead` | off | full-parameter async rounds: lead cap K. K=1 pushes one window of `--rl-sync-fragment-pipeline` global steps per local round and starts the next round once the window merged. With a fixed roster a fast island then stays at most one local round ahead of the slowest. With a quorum below the island count, a soft deadline or islands leaving, the lead is not bounded. Cost: one window of steps in flight per local round, also with several `--syncer-shards` | +| `--rl-sync-max-local-rounds-ahead` | off | full-parameter async rounds: lead cap K. K=1 pushes one window of `--rl-sync-fragment-pipeline` global steps per local round and starts the next round once the window merged. With a fixed roster a fast island then stays at most one local round ahead of the slowest. With a quorum below the island count, a soft deadline or islands leaving, the lead is not bounded. Cost: one window of steps in flight per local round, also with several `--syncer-shards`. The wait gives up after half of `--rl-sync-wait-timeout-s` (from the last push of the oldest pair in flight, or with none in flight from the first retain of the island's last retaining round); after a give-up the lead is no longer bounded | | `--rl-sync-learner-weight` | `equal` | `equal` or `tokens2-over-steps` | | `--rl-sync-outer-lr`, `--rl-sync-outer-momentum` | — | outer Nesterov parameters (default from the preset) | diff --git a/tests/test_sync_lead_cap.py b/tests/test_sync_lead_cap.py index 92045618a..e19f6afd3 100644 --- a/tests/test_sync_lead_cap.py +++ b/tests/test_sync_lead_cap.py @@ -295,6 +295,31 @@ async def serve(): assert [(key[0], pair.local_round) for key, pair in pairing.inflight.items()] == [(3, 2)] +@pytest.mark.asyncio +async def test_with_k_1_the_next_round_waits_until_every_step_of_its_window_merged(lead_clock): + """Step 1 merged and nothing is in flight, but step 2 of the window has no + PULL yet: the island trains on only once step 2, pushed from this cut, merged. + The K >= 2 rule (no blocker, no unpushed round) would train on here and push + step 2 from the next cut, one round late: the lead then grows with the run.""" + role = _PeerPacedRole([_candidate(1, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1) + pairing.local_round = 1 + pairing.submit_ready() + role.peer_pushed.add(1) # step 1 merges first + served = [] + + async def serve(): + served.append(len(served)) + if len(served) == 4: # step 2's PULL arrives late; the peer pushes it too + role.candidates.append(_candidate(2, 1)) + role.peer_pushed.add(2) + return 0 + + assert await pairing.wait_for_lead(serve) > 0 + assert len(served) >= 4 and _pushed(role) == [1, 2] and role.fragment_versions == (1, 2) + assert pairing.lead_wait_escapes == 0 + + @pytest.mark.asyncio async def test_with_k_1_a_wait_entered_before_any_pull_answers_each_pull_of_its_window(lead_clock): """The window is decided once per round: a wait entered with nothing pushed @@ -396,6 +421,19 @@ def test_with_k_1_a_caught_up_island_takes_the_window_of_its_first_open_step(): assert pairing.lead_window() == (9, 10) +def test_with_k_1_windows_stay_aligned_to_multiples_of_the_pipeline_depth(): + """Versions (7, 6): step 7 merged, step 8 is the first open step. The window + is the fixed window 7..8 that holds it, not 8..9: every island cuts the same + windows, whichever of its steps closed first.""" + role = _PeerPacedRole([_candidate(8, 1), _candidate(9, 1)]) + pairing = _pairing(role, max_local_rounds_ahead=1) + role.fragment_versions = (7, 6) + pairing.local_round = 1 + assert pairing.lead_window() == (7, 8) + pairing.submit_ready() + assert _pushed(role) == [8] # step 9 belongs to window 9..10 + + @pytest.mark.asyncio async def test_with_k_1_the_last_window_ends_at_the_last_step_and_the_terminal_phase_ends_a_wait(lead_clock): role = _PeerPacedRole([_candidate(1, 1)]) @@ -495,18 +533,21 @@ async def test_with_k_1_a_held_pull_is_not_materialized_ahead(lead_clock): pairing.local_round = 1 await pairing.prepare_submissions() pairing.submit_ready() + role.peer_pushed.add(1) # step 1 merges at the first poll: two pipeline slots are free served = [] async def serve(): served.append(len(served)) if len(served) == 1: + assert pairing.inflight == {} role.candidates.extend([_candidate(3, 1), _candidate(2, 1)]) # next window, this window if len(served) == 3: - role.peer_pushed.update({1, 2}) + role.peer_pushed.add(2) return 0 await pairing.wait_for_lead(serve) - # Cut 1 materialized fragment 0 (step 1) and fragment 1 (step 2), never step 3's. + # Cut 1 materialized fragment 0 (step 1) and fragment 1 (step 2), never step 3's, + # although a slot was free for it. assert role.materialized == [(1, (0,)), (1, (1,))] pairing.local_round = 2 await pairing.prepare_submissions() @@ -521,6 +562,25 @@ def test_a_pair_reads_the_injected_clock_when_it_is_retained(lead_clock): assert pair.retained_at == before # read at construction, before any push +@pytest.mark.asyncio +async def test_with_k_2_rounds_trained_after_the_last_retained_push_still_count(): + """K >= 2 keeps the blocker rule: after a merge and before the next PULL + nothing is in flight, yet the rounds trained since the island last retained + a pair land in its next push, so K of them stop the next round.""" + role = _PairedRole("actor", [_candidate(1, 1)], []) + pairing = _pairing(role, max_local_rounds_ahead=2) + pairing.local_round = 1 + pairing.submit_ready() + await pairing.commit_staged_broadcasts() + assert pairing.inflight == {} and role.fragment_versions == (1, 0) + pairing.local_round = 2 # one round on top of the push: allowed + assert pairing.lead_blockers() == [] and not pairing.lead_unpushed() + assert await pairing.wait_for_lead() == 0.0 + pairing.local_round = 3 # a second one: the next round waits for a push + assert pairing.lead_blockers() == [] and pairing.lead_unpushed() + assert pairing.lead_window() is None + + @pytest.mark.asyncio async def test_with_k_2_the_wait_still_pushes_a_pull_that_cannot_hold_it(lead_clock): """With K = 2 a pair from the current cut does not block this wait (one diff --git a/yeto/rl/engine/full_parameter_sync.py b/yeto/rl/engine/full_parameter_sync.py index ccd23f000..36c7ee8d2 100644 --- a/yeto/rl/engine/full_parameter_sync.py +++ b/yeto/rl/engine/full_parameter_sync.py @@ -1063,8 +1063,9 @@ async def wait_for_lead(self, serve: Any = None) -> float: there. The lead wait gives up (and the island trains on, the old behaviour) once the oldest pair in flight has waited half of ``wait_timeout`` since its last push, or, with none in flight, half of - it since the island last retained a pair, before a pair could time - out. + it since the first pair the island retained in the last round it + retained one (``retained_round_at``), before a pair could time out. + After a give-up the lead is no longer bounded. Returns the seconds this boundary waited.""" diff --git a/yeto/rl/engine/run_flags.py b/yeto/rl/engine/run_flags.py index 395e9bf75..28e494c1d 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -1488,7 +1488,10 @@ def rl_forward_pairs(*dests: str | tuple[str, str]) -> tuple[tuple[str, str], .. "deadline or islands leaving, a window can close without an island and the " "lead is not bounded). Cost of K=1: one window of steps is in flight per local " "round, also with several --syncer-shards. The wait gives up (and trains on) " - "after half of --rl-sync-wait-timeout-s since the island's last push. " + "after half of --rl-sync-wait-timeout-s, counted from the last push of the " + "oldest pair in flight or, with none in flight, from the first pair the island " + "retained in the last round it retained one; after a give-up the lead is no " + "longer bounded. " "Island-local: the layout, syncer profile and training contract hashes do not change", ), cli_flag(