diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index b90b764ef..8c5450a6a 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`. 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 764add13e..e19f6afd3 100644 --- a/tests/test_sync_lead_cap.py +++ b/tests/test_sync_lead_cap.py @@ -2,16 +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), 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 @@ -37,7 +43,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, @@ -60,6 +68,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)) @@ -115,63 +156,457 @@ 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 @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) @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 +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. + ``close_without_me`` stages a step this island never pushed (a quorum + below the island count, a soft deadline).""" + + 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): + 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_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) + 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.extend([_candidate(2, 1), _candidate(3, 1)]) # late, and the next window + if len(served) == 3: + 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, 2) + assert _pushed(role) == [1, 2] # step 3 was not pushed from cut 1 + pairing.local_round = 2 + pairing.submit_ready() + 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_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 + 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) + + +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)]) + 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() + 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.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, + # although a slot was free for it. + 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 +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 + 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,10 +1020,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 - # the slow island itself waited under the cap at a boundary while its - # push from an older cut completed the fast island's merge. - 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"] @@ -597,13 +1033,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 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 8c72560c6..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 tape.""" +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,26 +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] - # Without the cap the unpaced island would run hundreds of local rounds meanwhile. - 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 748ec988c..36c7ee8d2 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: @@ -249,7 +250,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 @@ -313,6 +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 + # 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. @@ -442,7 +449,7 @@ def submit_ready(self) -> dict[str, RoleProgress]: continue self._push_once(pair, observed, produced) capacity = self.profile.effective_pipeline_depth - len(self.inflight) - shared = sorted(set.intersection(*(set(keys) for keys in by_role.values()))) + 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. @@ -501,7 +508,8 @@ async def prepare_submissions(self) -> None: for role, stream in self.streams.items() } capacity = self.profile.effective_pipeline_depth - len(self.inflight) - shared = sorted(set.intersection(*(set(keys) for keys in by_role.values())) - set(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)]] @@ -922,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: @@ -940,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 @@ -951,35 +957,128 @@ 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 _step_window_rule(self) -> bool: + return self.profile.max_local_rounds_ahead == 1 + + 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) + + 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 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. + 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 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 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.""" - 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: @@ -993,13 +1092,11 @@ async def wait_for_lead(self, serve: Any = None) -> float: 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..28e494c1d 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -1480,11 +1480,19 @@ 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, 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( "--rl-sync-wait-timeout-s",