diff --git a/atom/kv_transfer/engine_step_hooks.py b/atom/kv_transfer/engine_step_hooks.py new file mode 100644 index 00000000000..51111c78692 --- /dev/null +++ b/atom/kv_transfer/engine_step_hooks.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""The engine step hooks KV transfer installs (`EngineCore.step_hooks`). + +A step hook has two methods: `before_schedule()`, called ahead of every +`schedule()` of the engine loop, and `on_forward_done(seconds)`, called after +every real or DP dummy forward with its wall time. The engine knows nothing +else of them. +""" + +from __future__ import annotations + + +def kv_transfer_step_hooks(engine, config) -> tuple: + """The step hooks for an engine with KV transfer configured.""" + from atom.kv_transfer.offload.load_wait import load_wait_hook + + hooks = (load_wait_hook(engine, config),) + return tuple(hook for hook in hooks if hook is not None) diff --git a/atom/kv_transfer/offload/_offload_common.py b/atom/kv_transfer/offload/_offload_common.py index fc8c6d623b6..febc7728393 100644 --- a/atom/kv_transfer/offload/_offload_common.py +++ b/atom/kv_transfer/offload/_offload_common.py @@ -24,6 +24,7 @@ import numpy as np import torch +from atom.kv_transfer import progress_doorbell from atom.kv_transfer.disaggregation.types import ( ConnectorCompletion, KVConnectorOutput, @@ -238,6 +239,26 @@ def build_offload_engine( return engine, cfg, meta +class LoadExecutor(ThreadPoolExecutor): + """The load pool: every job rings the KV progress doorbell when it ends + (`ATOM_OFFLOAD_LOAD_EVENT_WAIT`; a plain pool otherwise). + + A load job records its terminal result (`_done_load` / `_failed_load`) + before it returns, so the ring follows the record; `get_finished` rearms + the doorbell before it drains them. With no doorbell installed + (`progress_doorbell.install`) the ring is a no-op. + """ + + def submit(self, fn, /, *args, **kwargs): + future = super().submit(fn, *args, **kwargs) + future.add_done_callback(_ring_kv_progress) + return future + + +def _ring_kv_progress(_future) -> None: + progress_doorbell.ring() + + class OffloadWorkerMixin: """Executor plumbing + completion reporting shared by offload workers. @@ -290,7 +311,10 @@ def _init_worker_common( self._save_executor = ThreadPoolExecutor( max_workers=n_save, thread_name_prefix=f"{thread_name_prefix}-save" ) - self._load_executor = ThreadPoolExecutor( + load_pool = ( + LoadExecutor if envs.ATOM_OFFLOAD_LOAD_EVENT_WAIT else ThreadPoolExecutor + ) + self._load_executor = load_pool( max_workers=n_load, thread_name_prefix=f"{thread_name_prefix}-load" ) self._lock = threading.Lock() @@ -491,6 +515,9 @@ def _record_save_failure(self, req) -> None: self._done_save.add(self._save_completion_id(req)) def get_finished(self) -> KVConnectorOutput: + # Before the drain: a load recorded after this either is in this answer + # or rings the doorbell again (`progress_doorbell`). + progress_doorbell.rearm() with self._lock: dl, fl, ds = self._drain_common_completions_locked() completions = set(self._connector_completions) diff --git a/atom/kv_transfer/offload/hybrid/dsv4/connector.py b/atom/kv_transfer/offload/hybrid/dsv4/connector.py index a8245267e3c..92f03e152b9 100644 --- a/atom/kv_transfer/offload/hybrid/dsv4/connector.py +++ b/atom/kv_transfer/offload/hybrid/dsv4/connector.py @@ -36,6 +36,7 @@ import torch +from atom.kv_transfer import progress_doorbell from atom.kv_transfer.disaggregation.base import ( KVConnectorBase, KVConnectorSchedulerBase, @@ -1773,6 +1774,9 @@ def get_finished(self) -> KVConnectorOutput: # - finished_loading wakes successfully loaded requests. # - failed_loading wakes them for recompute using already allocated blocks. # - finished_saving releases blocks whose free was deferred during save. + # Rearm before the drain: a load recorded after this either is in this + # answer or rings the doorbell again (`progress_doorbell`). + progress_doorbell.rearm() with self._lock: dl, fl, ds = self._drain_common_completions_locked() dss = set(self._done_sidecar_save) diff --git a/atom/kv_transfer/offload/load_wait.py b/atom/kv_transfer/offload/load_wait.py new file mode 100644 index 00000000000..49d4af38e88 --- /dev/null +++ b/atom/kv_transfer/offload/load_wait.py @@ -0,0 +1,406 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Offload load wait: tier-load completions seen before `schedule()`. + +Without it a waiting request with a tier hit parks inside `schedule()`, its +load leaves with that step's batch and lands within milliseconds, but the +engine reads worker completions only through the query answered after a +forward: the request prefills one or two forwards later. + +`OffloadLoadWait` is the engine step hook (`EngineCore.step_hooks`) that fixes +this; nothing of it lives on the engine or the scheduler. Before each +`schedule()` it + +1. runs that tick's early tier load ahead of `schedule()` (`prestart_tier_loads`, + which `schedule()` then skips: `EarlyLoadState.take_tick_pass`) and ships + the loads it started at once; +2. when a load ended since the last answer -- a worker rang the KV progress + doorbell (`progress_doorbell`), which sets the engine's KV progress event -- + fetches one completion answer requested after that ring, so a landed load + is admitted by this `schedule()` (`ATOM_OFFLOAD_LOAD_EVENT_WAIT`, on); +3. with `ATOM_OFFLOAD_LOAD_WAIT_HOLD` (on by default, `0` turns it off): holds + the step for the loads it started while holding pays + (`LoadWaitState.budget_s` over `load_wait_tradeoff`), woken by the + doorbell, ending as soon as every started load landed. The hold delays + every DP peer at the forward collective; the bound charges that through + `cost * dp_size`, never exceeds one tick, and is 0 while any rank of the + DP group has a running decode (`DPEngineCoreProc.dp_group_decoding`, + carried on the existing per-step `_sync_dp_state` reduction). + +Installed only for a KV connector whose offload tier loads early +(`supports_early_load`: Mooncake Store); other connectors get no hook. No +collective runs here and the step count is unchanged, so DP lockstep holds. +""" + +from __future__ import annotations + +import logging +import time + +from atom.kv_transfer import progress_doorbell +from atom.kv_transfer.disaggregation.types import connector_metadata_has_work +from atom.model_engine.sequence import SequenceStatus +from atom.utils import envs + +logger = logging.getLogger("atom") + + +class LoadWaitState: + """The load wait's inputs and counters. + + `tick_s` is the wall time of the last forward this engine ran, a DP + dummy forward included (`OffloadLoadWait.on_forward_done`): the group's + step cadence the waits are measured against, not this rank's last real + (often long prefill) forward. 0 until a forward ran, so a cold engine + never waits. + """ + + LOG_INTERVAL_S = 60.0 + + def __init__(self, dp_size: int) -> None: + self.dp_size = max(1, int(dp_size)) + self.tick_s = 0.0 + self._last_log = time.monotonic() + self._reset() + + def budget_s(self, gain: int, cost: int, *, group_decoding: bool = False) -> float: + """How long holding this step for `gain` loading requests is worth. + + Each request that lands in time prefills one forward (`tick_s`) earlier; + each of the `cost` requests the step carries anyway is delayed by the + hold, and under DP so are the peers' (the forward is a collective, and + the router keeps the ranks alike, so the group carries about `dp_size` + times this rank's count). The hold pays while it stays under + `tick_s * gain / (cost * dp_size)`, and it is never longer than one + tick: past that the request is no later than without the hold. + + `group_decoding`: some rank of the DP group has a running decode + (`DPEngineCoreProc.dp_group_decoding`, reduced on the per-step state + sync). The hold would add to that decode's ITL at the next forward + collective, and this rank cannot count it, so nothing is worth + holding: 0. Without DP the engine's own decode stops the pre-phase + (`prestart_tier_loads`) before any hold. + """ + if gain <= 0 or self.tick_s <= 0.0 or group_decoding: + return 0.0 + return min(self.tick_s, self.tick_s * gain / (max(1, cost) * self.dp_size)) + + def _reset(self) -> None: + self.steps = 0 # steps that started at least one load ahead of schedule() + self.loads = 0 # loads started ahead of schedule() + self.fresh = 0 # answers fetched before schedule() for a doorbell + self.skipped = 0 # hold on: steps with nothing worth holding for + self.waits = 0 # hold on: steps that held + self.landed = 0 # held-for loads that landed (done or failed) in time + self.timed_out = 0 # held-for loads still in flight at the bound + self.wakes = 0 # doorbells taken while holding + self.wait_s = 0.0 + self.max_wait_s = 0.0 + self.budget_total_s = 0.0 + + def note_wait( + self, landed: int, timed_out: int, waited_s: float, budget_s: float + ) -> None: + self.waits += 1 + self.landed += landed + self.timed_out += timed_out + self.wait_s += waited_s + self.max_wait_s = max(self.max_wait_s, waited_s) + self.budget_total_s += budget_s + + def maybe_log(self, label: str) -> None: + now = time.monotonic() + if now - self._last_log < self.LOG_INTERVAL_S: + return + if self.steps or self.fresh: + logger.info( + "%s: [LOAD-WAIT] last %.0fs: steps=%d loads=%d fresh=%d " + "skipped=%d waits=%d landed=%d timed_out=%d wakes=%d " + "avg_wait=%.1fms max_wait=%.1fms avg_bound=%.1fms tick=%.1fms", + label, + now - self._last_log, + self.steps, + self.loads, + self.fresh, + self.skipped, + self.waits, + self.landed, + self.timed_out, + self.wakes, + 1e3 * self.wait_s / self.waits if self.waits else 0.0, + 1e3 * self.max_wait_s, + 1e3 * self.budget_total_s / self.waits if self.waits else 0.0, + 1e3 * self.tick_s, + ) + self._last_log = now + self._reset() + + +# -- scheduler-side passes (read the scheduler; no state of their own on it) ---- + + +def prestart_tier_loads(scheduler) -> list: + """Run this tick's early tier load ahead of `schedule()` and return the + requests it parked. + + Exactly the early load `Scheduler._schedule` runs (same lookup prefetch, + same `_early_load_tier_prefixes`, same KV-pressure bounds), only earlier, so + the loads can be shipped before the engine schedules. It *is* that tick's + pass: the `schedule()` that follows skips its own + (`EarlyLoadState.take_tick_pass`), so the per-tick bounds + (`_EARLY_LOAD_PER_TICK`, retry and prune cadence) stay per step. State loads + it queued are published now so a joint load leaves with the first metadata + build. + + Not while a decode is running: this pass allocates, and a running decode's + page reservation (`reserved_decode_blocks`) is installed only inside + `_schedule()`. That is an ordering requirement, not a tuning choice; the + pass inside `_schedule()`, behind the reservation, runs instead. + """ + if not scheduler.waiting or scheduler.has_running_decode(): + return [] + scheduler._prefetch_waiting_lookups() + early_load = scheduler._early_load + entries = early_load.entries + before = set(entries) + early_load.mark_tick_pass_ran() + if not scheduler._early_load_tier_prefixes(): + return [] + started = [ + seq + for seq_id, (seq, _) in entries.items() + if seq_id not in before and seq.status == SequenceStatus.WAITING_FOR_REMOTE_KVS + ] + if started: + scheduler._publish_state_loads() + return started + + +def load_wait_tradeoff(scheduler, loading: list) -> tuple[int, int]: + """(gain, cost) of holding this tick's forward for the tier loads of + `loading`. + + gain: requests of `loading` still in flight that this tick could admit if + their load landed now -- a free request slot each, and the prefill ahead of + them in `waiting` order (partial prefills, then admittable waiters with the + router's cached-prefix estimate) leaves token budget. Each one that lands + in time prefills one forward earlier. + + cost: requests this tick's forward carries anyway -- everything in + `running` (partial prefills and decodes) plus the admittable waiters that + fit ahead of the last admittable target. Each one is delayed by whatever + the engine waits. Requests further back are delayed too, but the next + forward no longer has to carry the loaded prefill, which hands them that + capacity back; to first order the two cancel, so they are not counted. + + Pure: no allocation, no collective, no state change. Best effort like the + delayer's fill signal; a wrong count costs at most the bounded wait or one + step of latency, never correctness. + """ + targets = {id(seq) for seq in loading if scheduler._still_loading(seq)} + cost = len(scheduler.running) + slots = scheduler.max_num_seqs - len(scheduler.running) + if not targets or slots <= 0: + return 0, cost + budget = scheduler.max_num_batched_tokens + ahead = scheduler._partial_prefill_remaining_tokens() + gain = 0 + carried = 0 # admittable non-target waiters seen so far + for seq in scheduler.waiting: + if ahead >= budget or slots <= 0: + break + if id(seq) in targets: + gain += 1 + slots -= 1 + cost += carried + carried = 0 + ahead += scheduler.pending_prefill_tokens(seq) + targets.discard(id(seq)) + if not targets: + break + elif scheduler._is_admittable_prefill(seq): + carried += 1 + slots -= 1 + ahead += scheduler.pending_prefill_tokens(seq, estimate=True) + return gain, cost + + +# -- the engine step hook ---------------------------------------------------------- + + +class OffloadLoadWait: + """Engine step hook (`EngineCore.step_hooks`): `before_schedule` ahead of + every `schedule()`, `on_forward_done` after every forward (real or DP + dummy). + + Reads the engine it serves (`scheduler`, `runner_mgr`, `label`, the KV + progress event, `_collect_kv_transfer_progress` and, under DP, + `dp_group_decoding`) and keeps everything else here. + """ + + def __init__(self, engine, dp_size: int, *, hold: bool) -> None: + self._engine = engine + self.hold = hold + self.state = LoadWaitState(dp_size) + # In this process a doorbell is rung by the KV output threads when a + # worker's marker arrives (`AsyncIOProcManager`) and by a Store lease + # renewal that finished or timed out (`AsyncStoreLookup.renew_async`). + # Either sets the engine's KV progress event; the ring count tells a + # ring from the event's other wakes (an answer's arrival, a request). + progress_doorbell.install(engine._wake_event.set, coalesce=False) + self._seen_rings = progress_doorbell.rings() + # When the completion query now outstanding was requested; -inf when + # it was requested outside this hook (taken as before any doorbell). + self._asked_at = float("-inf") + + # -- hooks --------------------------------------------------------------- + + def on_forward_done(self, seconds: float) -> None: + self.state.tick_s = seconds + + def before_schedule(self) -> None: + engine = self._engine + scheduler = engine.scheduler + state = self.state + self._asked_at = float("-inf") + started = prestart_tier_loads(scheduler) + held = False + if started: + self._ship_connector_meta() + state.steps += 1 + state.loads += len(started) + if self.hold: + budget = state.budget_s( + *load_wait_tradeoff(scheduler, started), + group_decoding=getattr(engine, "dp_group_decoding", False), + ) + if budget > 0.0: + t0 = time.monotonic() + pending = self._wait_for_loads(started, t0 + budget) + state.note_wait( + len(started) - pending, pending, time.monotonic() - t0, budget + ) + held = True + else: + state.skipped += 1 + if not held: + self._fetch_fresh_answer() + state.maybe_log(engine.label) + + # -- internals ------------------------------------------------------------- + + def _ship_connector_meta(self) -> None: + """Dispatch whatever loads the connector releases now, outside a batch + (the loads the pre-phase started; with `ATOM_STORE_ASYNC_RENEW`, a load + whose lease renewal just finished). No RPC when there is nothing.""" + engine = self._engine + meta = engine.scheduler.kv_connector.build_connector_meta() + if connector_metadata_has_work(meta): + engine.runner_mgr.call_func("process_kvconnector_output", meta) + + def _unread_doorbell(self) -> bool: + return progress_doorbell.rings() != self._seen_rings + + def _take_doorbell(self) -> float: + """Mark every ring so far read; returns when (engine clock).""" + self._seen_rings = progress_doorbell.rings() + return time.monotonic() + + def _collect_answer_after(self, rung_at: float) -> tuple[bool, bool]: + """Apply the outstanding completion answer if it is in (which requests + the next) and ship what it released. Returns `(answered, fresh)`: + an answer was applied, and it was requested after `rung_at`, so it + holds the completion that rang. An older answer can still have landed + loads (it may hold completions that rang before or with this ring).""" + engine = self._engine + asked_at = self._asked_at + now = time.monotonic() + answered = engine._collect_kv_transfer_progress() is not None + if answered: + # The next query went out inside that call, so not before `now`. + self._asked_at = now + # A load parked on its lease renewal leaves as soon as it is free. + self._ship_connector_meta() + return answered, answered and asked_at >= rung_at + + def _fetch_fresh_answer(self) -> None: + """A load ended since the last answer (an unread doorbell): fetch one + answer requested after that ring, so this `schedule()` sees it. Waits + for the query's round trip only, bounded by one tick; a cold engine + (no forward yet) leaves the ring for the next step.""" + if not self._unread_doorbell() or self.state.tick_s <= 0.0: + return + event = self._engine._wake_event + rung_at = self._take_doorbell() + deadline = rung_at + self.state.tick_s + self.state.fresh += 1 + while True: + # Cleared before the poll: an answer arriving after it wakes the wait. + event.clear() + if self._collect_answer_after(rung_at)[1]: + return + remaining = deadline - time.monotonic() + if remaining <= 0.0: + return + event.wait(remaining) + + def _wait_for_loads(self, loading, deadline: float) -> int: + """Block until every request of `loading` stopped loading or `deadline`; + returns how many still load. Woken by events only: the KV doorbell (a + load job ended on a worker, or a lease renewal here finished or reached + its timeout unfinished) and the arrival of a completion answer.""" + engine = self._engine + scheduler = engine.scheduler + event = engine._wake_event + # When the last unread doorbell was taken: an answer requested after it + # holds the completion that rang it. None: no unread doorbell. + rung_at = None + while True: + pending = sum(1 for seq in loading if scheduler._still_loading(seq)) + now = time.monotonic() + if not pending or now >= deadline: + return pending + if rung_at is None: + if not self._unread_doorbell(): + # Any other wake (an answer, a request) is not a ring. + event.clear() + if not self._unread_doorbell(): + event.wait(deadline - now) + continue + rung_at = self._take_doorbell() + self.state.wakes += 1 + # Cleared before the poll: an answer arriving after it wakes the wait. + event.clear() + answered, fresh = self._collect_answer_after(rung_at) + if fresh: + rung_at = None + continue + if answered: + # An answer requested before the ring can already hold every + # started load's completion: re-check `pending` before waiting + # for the next one (one query round trip). The ring stays + # unread until a fresh answer, so a load still pending is + # waited for exactly as before. + continue + # The outstanding answer (or the one just requested) is still out. + event.wait(max(0.0, deadline - time.monotonic())) + + +def load_wait_hook(engine, config) -> OffloadLoadWait | None: + """The offload load wait for `engine`, or None when it is off + (`ATOM_OFFLOAD_LOAD_EVENT_WAIT=0`) or the engine's KV connector has no + offload tier that loads early (`supports_early_load` False: no connector, + a P/D-only connector, dense or DSV4 offload). `LoadExecutor` rings the + doorbell on every offload tier, so without this gate a non-early tier + would wait for a fresh answer after each of its loads for nothing.""" + if not envs.ATOM_OFFLOAD_LOAD_EVENT_WAIT: + return None + connector = getattr(engine.scheduler, "kv_connector", None) + if connector is None or not connector.supports_early_load: + return None + return OffloadLoadWait( + engine, + config.parallel_config.data_parallel_size, + hold=envs.ATOM_OFFLOAD_LOAD_WAIT_HOLD, + ) diff --git a/atom/kv_transfer/offload/mooncake_store/async_lookup.py b/atom/kv_transfer/offload/mooncake_store/async_lookup.py index 0c7122314e7..dc41ba025bd 100644 --- a/atom/kv_transfer/offload/mooncake_store/async_lookup.py +++ b/atom/kv_transfer/offload/mooncake_store/async_lookup.py @@ -9,6 +9,8 @@ queued query, waiting only for the call in flight. """ +import heapq +import itertools import logging import queue import threading @@ -19,14 +21,77 @@ from contextlib import contextmanager from threading import Condition, RLock +from atom.kv_transfer import progress_doorbell from atom.kv_transfer.offload.lookup_client import LookupClient logger = logging.getLogger("atom") + +def _ring_kv_progress(_future) -> None: + progress_doorbell.ring() + + # How long the scheduler thread waits for its own advisory renewal RPC: a slow # Store RPC must not stall the scheduler and, through the DP lockstep, its peers. RENEW_TIMEOUT_S = 1.0 +# The alarm below sleeps on the real clock, as its condition wait does. +_monotonic = time.monotonic + + +class _RenewalExpiryAlarm: + """Rings the KV progress doorbell when an async renewal reaches its timeout + unfinished. + + A finished renewal rings it itself (`_ring_kv_progress`); a stalled one + rings nothing, yet from its timeout on its load may go out (`renew_async` + answers "timeout"). Without this ring an engine holding its step for that + load (`load_wait.OffloadLoadWait`) would sleep to the hold's bound. One + daemon thread for all renewals, started on first use. + """ + + def __init__(self) -> None: + self._cond = threading.Condition() + self._heap: list = [] # (expiry, seq no, future) + self._order = itertools.count() + self._thread = None + self._closed = False + + def arm(self, future, timeout_s: float) -> None: + with self._cond: + if self._closed: + return + expiry = _monotonic() + timeout_s + heapq.heappush(self._heap, (expiry, next(self._order), future)) + if self._thread is None: + self._thread = threading.Thread( + target=self._run, name="store-renew-alarm", daemon=True + ) + self._thread.start() + self._cond.notify() + + def _run(self) -> None: + while True: + expired = [] + with self._cond: + while not self._closed: + now = _monotonic() + while self._heap and self._heap[0][0] <= now: + expired.append(heapq.heappop(self._heap)[2]) + if expired: + break + self._cond.wait(self._heap[0][0] - now if self._heap else None) + if self._closed: + return + if any(not f.done() for f in expired): + progress_doorbell.ring() + + def close(self) -> None: + with self._cond: + self._closed = True + self._heap.clear() + self._cond.notify() + class DaemonExecutor: """One worker thread that cannot hold the interpreter's exit. @@ -133,6 +198,7 @@ def __init__(self, backend, capacity=4096): # polls; `_stuck_renewals` holds retired futures whose RPC still runs. self._renewals = {} self._stuck_renewals = [] + self._renewal_alarm = _RenewalExpiryAlarm() self.backend_slot = _BackendSlot() self.pending = {} # sid -> when its Store query was sent: the read lease the answer grants @@ -327,7 +393,13 @@ def renew_async(self, sid, ident, make_keys): future = self.renew_executor.submit(self._renew_keys, keys) if future is None or future.cancelled(): return "rejected" + # The load it holds back can leave now: wake an engine holding its + # step for it (`load_wait.OffloadLoadWait`); a no-op otherwise. + future.add_done_callback(_ring_kv_progress) ticket = self._renewals[sid] = (ident, future, time.monotonic()) + # A renewal stalled to its timeout releases the load too: wake + # the engine then as well. + self._renewal_alarm.arm(future, RENEW_TIMEOUT_S) _, future, submitted = ticket if future.done(): del self._renewals[sid] @@ -361,6 +433,7 @@ def close(self): # Daemon workers: a hung Store RPC does not hold engine exit. self.executor.shutdown() self.renew_executor.shutdown() + self._renewal_alarm.close() # And the backend's own workers (the Store's per-pool lookups). if self.backend is not None: self.backend.close() diff --git a/atom/kv_transfer/progress_doorbell.py b/atom/kv_transfer/progress_doorbell.py new file mode 100644 index 00000000000..e7aab0f3f84 --- /dev/null +++ b/atom/kv_transfer/progress_doorbell.py @@ -0,0 +1,89 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors +"""Worker -> engine doorbell for KV transfer progress. + +A worker answers the engine's completion query (`async_proc_aggregation`) only +when the engine asks, and the engine asks after each forward. A tier load that +lands while the engine is scheduling is therefore seen one forward late. The +doorbell lets the thread that finished the load say so at once: it pushes one +small marker on the worker's KV output channel, the engine's KV output thread +rings the engine's own doorbell, which sets the engine's KV progress event, and +the engine then asks for the completions as usual. The doorbell carries no +completion data; the aggregation protocol (one outstanding query, drain-once +replies, TP quorum in `KVOutputAggregator`) is unchanged. + +Rings coalesce in a worker: after one ring, the next one is sent only once the +worker has answered a completion query (`rearm`, called by the offload worker's +`get_finished` before it drains its completion sets), so a burst of completions +costs one message, and none is lost: a completion recorded after `rearm` either +is in that query's answer or rings again. + +Every worker process gets a sender (`AsyncIOProc`); only offload load pools +that use it ring (`LoadExecutor`, `ATOM_OFFLOAD_LOAD_EVENT_WAIT`). In the engine +process the offload load wait installs one (`load_wait.OffloadLoadWait`) and +counts the rings (`rings`). Uninstalled, `ring` is a no-op. +""" + +from __future__ import annotations + +import threading +from collections.abc import Callable + +# The marker sent on the KV output channel. A plain string so it pickles +# anywhere and can never be mistaken for a `KVConnectorOutput`. +KV_PROGRESS_DOORBELL = "ATOM_KV_PROGRESS_DOORBELL" + +_lock = threading.Lock() +_send: Callable[[], None] | None = None +_coalesce = True +_rung = False +_rings = 0 + + +def install(send: Callable[[], None] | None, *, coalesce: bool = True) -> None: + """Set (or with None clear) how this process sends the doorbell. + + `coalesce=False` where nothing calls `rearm` (the engine process, whose + doorbell is a local event set, cheap to repeat).""" + global _send, _coalesce, _rung + with _lock: + _send = send + _coalesce = coalesce + _rung = False + + +def ring() -> None: + """Announce progress (a load finished or failed); coalesced, never raises.""" + global _rung, _rings + with _lock: + if _send is None or _rung: + return + _rung = _coalesce + # Counted before the send: whoever is woken by it sees the count. + _rings += 1 + send = _send + try: + send() + except Exception: # noqa: BLE001 - a lost doorbell only costs latency + with _lock: + _rung = False + + +def rearm() -> None: + """Allow the next ring. Called before a completion query drains, so every + completion is either in that answer or rings again.""" + global _rung + with _lock: + _rung = False + + +def rings() -> int: + """How many rings this process has sent: a reader that remembers the count + it last saw can tell a ring from any other wake of the same event.""" + with _lock: + return _rings + + +def installed() -> bool: + return _send is not None diff --git a/atom/model_engine/async_proc.py b/atom/model_engine/async_proc.py index d1926ea20e2..e3180414277 100644 --- a/atom/model_engine/async_proc.py +++ b/atom/model_engine/async_proc.py @@ -30,7 +30,9 @@ from aiter.dist.shm_broadcast import MessageQueue from atom.config import local_device_index +from atom.kv_transfer import progress_doorbell from atom.kv_transfer.disaggregation import KVConnectorOutput, KVOutputAggregator +from atom.kv_transfer.progress_doorbell import KV_PROGRESS_DOORBELL from atom.model_engine.block_table_codec import ( FORWARD_RPC, BlockTableDeltaDecoder, @@ -209,6 +211,10 @@ def __init__( ) t.start() self.io_threads.append(t) + # KV progress doorbell sender: whoever in this worker rings it + # (`progress_doorbell.ring`) is heard on this channel at once. + kv_queue = self.kv_queue + progress_doorbell.install(lambda: kv_queue.put_nowait(KV_PROGRESS_DOORBELL)) # Dedicated collective-RPC reply thread if self.rpc_output_addr is not None: @@ -704,7 +710,13 @@ def process_kv_output_sockets(self, output_address: str, worker_id: int): continue obj = output_socket.recv(copy=False) obj = pickle.loads(obj) - self.kv_outputs_queues[worker_id].put_nowait(obj) + if isinstance(obj, str) and obj == KV_PROGRESS_DOORBELL: + # Not an answer: it never joins an aggregation. Rings this + # process's doorbell, which sets `kv_progress_event` where + # one is installed (`progress_doorbell`). + progress_doorbell.ring() + else: + self.kv_outputs_queues[worker_id].put_nowait(obj) if self.kv_progress_event is not None: self.kv_progress_event.set() finally: diff --git a/atom/model_engine/early_load.py b/atom/model_engine/early_load.py index f600c005143..0a021b8f076 100644 --- a/atom/model_engine/early_load.py +++ b/atom/model_engine/early_load.py @@ -49,6 +49,24 @@ def __init__(self) -> None: self.wait_n = 0 self.tick = 0 self._last_log = time.monotonic() + # This tick's pass (lookup prefetch + early tier load) already ran ahead + # of `schedule()` (the offload load wait, `load_wait.prestart_tier_loads`). + self._tick_pass_ran = False + + # -- once per tick ---------------------------------------------------------- + + def mark_tick_pass_ran(self) -> None: + """This tick's early-load pass runs ahead of `schedule()`: the + `schedule()` that follows skips its own (`take_tick_pass`).""" + self._tick_pass_ran = True + + def take_tick_pass(self) -> bool: + """Whether `schedule()` still runs this tick's early-load pass: False + once after `mark_tick_pass_ran`, True otherwise.""" + if self._tick_pass_ran: + self._tick_pass_ran = False + return False + return True # -- counters ------------------------------------------------------------- diff --git a/atom/model_engine/engine_core.py b/atom/model_engine/engine_core.py index 73536e33a23..cd66025c16a 100644 --- a/atom/model_engine/engine_core.py +++ b/atom/model_engine/engine_core.py @@ -16,6 +16,7 @@ from atom.kv_transfer.disaggregation import KVOutputAggregator from atom.kv_transfer.disaggregation.pd_producer import disaggregated_kv_role from atom.kv_transfer.disaggregation.types import connector_metadata_has_work +from atom.kv_transfer.engine_step_hooks import kv_transfer_step_hooks from atom.metrics.scheduler import SchedulerMetrics from atom.model_engine.async_proc import AsyncIOProcManager from atom.model_engine.dp_sync_gate import MAX_DP_SYNC_INTERVAL, DPSyncGate @@ -135,6 +136,10 @@ class EngineCore: # Whether the engine reports its prefill backlog to the CoreManager # (`share_cache` routing); the data-parallel engine turns it on. _report_backlog = False + # Objects called around every step: `before_schedule()` ahead of + # `schedule()`, `on_forward_done(seconds)` after a real forward or a DP + # dummy forward (`atom.kv_transfer.engine_step_hooks`). None by default. + step_hooks: tuple = () def __init__(self, config: Config, input_address: str, output_address: str): self.label = "Engine Core" @@ -310,6 +315,7 @@ def __init__(self, config: Config, input_address: str, output_address: str): self.kv_transfer_enabled = bool(config.kv_transfer_config) self._next_idle_kv_drain = 0.0 if self.kv_transfer_enabled: + self.step_hooks = kv_transfer_step_hooks(self, config) # Physical: one output per launched worker, else this waits forever. self.kv_aggregator = KVOutputAggregator(world_size=config.tp_world_size) @@ -672,6 +678,8 @@ def _process_engine_step_inner(self): # waiting. Arrivals during this step remain latched until the next step. if self.kv_transfer_enabled: self._wake_event.clear() + for hook in self.step_hooks: + hook.before_schedule() result = self.scheduler.schedule() # Surface admit-rejected seqs (those `_unschedulable_reason` flags in @@ -707,9 +715,12 @@ def _process_engine_step_inner(self): self.scheduler.compute_detailed_aggregates(scheduled_batch, seqs) tracing.record_forward(scheduled_batch, seqs) self.scheduler.metrics.record_forward(scheduled_batch, seqs) + fwd_start = time.monotonic() fwd_out = self.runner_mgr.call_func( "forward", scheduled_batch, wait_out=True ) + for hook in self.step_hooks: + hook.on_forward_done(time.monotonic() - fwd_start) if ( self.scheduler.prefill_delayer is not None and scheduled_batch.total_seqs_num_prefill > 0 @@ -856,6 +867,12 @@ def _drain_kv_work_at_exit(self) -> None: def _poll_kv_transfer_progress(self) -> bool: if not self.kv_transfer_enabled: return False + kvoutput = self._collect_kv_transfer_progress() + return kvoutput is not None and not kvoutput.is_empty() + + def _collect_kv_transfer_progress(self): + """Apply the workers' completion answer if every rank has given it + (and request the next); None while it is still out.""" kvoutput = self.runner_mgr.call_func_with_aggregation("async_proc_aggregation") self.scheduler._update_from_kv_xfer_finished(kvoutput) # Reclaim any offload save whose completion report never came (LMCache @@ -864,7 +881,7 @@ def _poll_kv_transfer_progress(self) -> bool: reconcile = getattr(self.scheduler, "_reconcile_stalled_deferred_saves", None) if callable(reconcile): reconcile() - return kvoutput is not None and not kvoutput.is_empty() + return kvoutput def _poll_dynamic_chunking_calibration(self) -> None: """Install a freshly calibrated chunk latency model, if one is ready. @@ -1159,6 +1176,8 @@ def __init__(self, config: Config, input_address: str, output_address: str): self._idle_when_blocked = self._resolve_idle_when_blocked(config) # Reduced by `_sync_dp_state`: some rank's vote hid unfinished work. self._dp_group_hidden_work = False + # Reduced by `_sync_dp_state`: some rank of the group has a running decode. + self.dp_group_decoding = False def _resolve_idle_when_blocked(self, config: Config) -> bool: """`ATOM_DP_IDLE_WHEN_BLOCKED`: whether this rank reports work to its DP @@ -1385,7 +1404,12 @@ def _validate_dp_sync_interval(self, interval: int | None) -> int: return value def _execute_dummy_batch(self): + fwd_start = time.monotonic() fwd_out = self.runner_mgr.call_func("dummy_execution", wait_out=True) + # The dummy is paired with the peers' forwards: its wall time is the + # group's step, which is what a step hook measures against. + for hook in self.step_hooks: + hook.on_forward_done(time.monotonic() - fwd_start) if self.scheduler.running: # The tokens this rank's last real step sampled come back with this # forward (deferred output), and land like any step's. @@ -1401,8 +1425,14 @@ def _sync_dp_state( """MAX-reduce this rank's flags over the DP group. `local_hidden` (ATOM_DP_IDLE_WHEN_BLOCKED: unfinished work the vote left out) is reduced too, into `_dp_group_hidden_work`; every rank sends it, so the - collective is the same whatever each rank's setting.""" + collective is the same whatever each rank's setting. So is whether + this rank has a running decode (`Scheduler.has_running_decode`), into + `dp_group_decoding`: some rank of the group decodes, so anything that + delays this rank's next forward delays those decodes at the collective + too (a step hook reads it). Kept until the next sync.""" + local_decoding = self.scheduler.has_running_decode() self._dp_group_hidden_work = local_hidden + self.dp_group_decoding = local_decoding if self._shutting_down: return local_has_unfinished, True, local_held @@ -1413,6 +1443,7 @@ def _sync_dp_state( int(local_shutdown), int(local_held), int(local_hidden), + int(local_decoding), ], dtype=torch.int64, device="cpu", @@ -1420,9 +1451,10 @@ def _sync_dp_state( torch.distributed.all_reduce( state_tensor, op=torch.distributed.ReduceOp.MAX, group=self.dp_group ) - # One decode for the four flags. - unfinished, shutdown, held, hidden = state_tensor.tolist() + # One decode for the five flags. + unfinished, shutdown, held, hidden, decoding = state_tensor.tolist() self._dp_group_hidden_work = hidden == 1 + self.dp_group_decoding = decoding == 1 return unfinished == 1, shutdown == 1, held == 1 except RuntimeError as e: logger.warning(f"{self.label}: _sync_dp_state failed: {e}") diff --git a/atom/model_engine/scheduler.py b/atom/model_engine/scheduler.py index fa8bfefd429..49ef3777f90 100644 --- a/atom/model_engine/scheduler.py +++ b/atom/model_engine/scheduler.py @@ -2083,6 +2083,10 @@ def is_finished(self): and not self.deferred_free_blocks ) + def has_running_decode(self) -> bool: + """Whether `running` holds anything besides partial prefills.""" + return len(self.running) > self._partial_prefill_count + def has_forward_work(self) -> bool: """Whether a scheduling pass on this rank may produce a batch now. @@ -2696,21 +2700,17 @@ def _schedule(self) -> tuple[ScheduledBatch, dict[int, Sequence]] | None: ) if self.enable_dynamic_chunking: self._record_prefill_supply() - if self.kv_connector is not None and self.waiting: - prefetch = getattr(self.kv_connector, "prefetch_lookups", None) - if prefetch is not None: - # Includes requests whose lookup will be detached: the lookup - # still refreshes the tier's LRU (`_can_detach_tier_lookup`). - prefetch( - itertools.islice(self.waiting, 0, envs.OFFLOAD_ASYNC_LOOKUP_DEPTH) - ) - # Start tier loads for waiting requests whose lookup answered, on this # tick whatever the delayer decides. Before the delayer so a request # whose load is in flight is not counted as prefillable work (and so a # FIRE is not spent on nothing). Local to this rank: no collective, and - # nothing is scheduled for prefill here. - self._early_load_tier_prefixes() + # nothing is scheduled for prefill here. Skipped, with the lookup + # prefetch before it, when this tick's pass already ran ahead of + # `schedule()` (`EarlyLoadState.take_tick_pass`), so the per-tick bounds + # stay per step. + if self._early_load.take_tick_pass(): + self._prefetch_waiting_lookups() + self._early_load_tier_prefixes() # should_allow_prefill() runs a cross-DP all_reduce and MUST be called # every tick on every rank for lockstep — hence before the early-return. @@ -5040,6 +5040,18 @@ def _early_load_tier_prefixes(self) -> int: logger.debug("[EARLY-LOAD] parked %d tier load(s)", parked) return parked + def _prefetch_waiting_lookups(self) -> None: + """Submit the async tier lookups of the head of `waiting`, once per + tick, with that tick's early tier load (`_schedule`, unless the pass + already ran ahead of it: `EarlyLoadState.take_tick_pass`).""" + if self.kv_connector is None or not self.waiting: + return + prefetch = getattr(self.kv_connector, "prefetch_lookups", None) + if prefetch is not None: + # Includes requests whose lookup will be detached: the lookup + # still refreshes the tier's LRU (`_can_detach_tier_lookup`). + prefetch(itertools.islice(self.waiting, 0, envs.OFFLOAD_ASYNC_LOOKUP_DEPTH)) + def _early_load_admit( self, seq: Sequence, diff --git a/atom/utils/envs.py b/atom/utils/envs.py index c721403be5a..9d4e0cc1a7e 100644 --- a/atom/utils/envs.py +++ b/atom/utils/envs.py @@ -1581,6 +1581,27 @@ def _dp_sync_interval_env() -> int | None: "ATOM_OFFLOAD_EARLY_LOAD_MAX_FRAC": lambda: _finite_float_env( "ATOM_OFFLOAD_EARLY_LOAD_MAX_FRAC", 0.15, allow_zero=True ), + # Default on (0 turns it off). Offload load wait, the doorbell part + # (`atom/kv_transfer/offload/load_wait.py`): each step of the + # single-engine and DP loops runs the early tier load ahead of schedule() + # and ships its loads, workers ring a doorbell when a load job ends, and + # after a ring the engine fetches one completion answer before schedule() + # so a landed load is admitted one forward earlier. Installed only when + # the KV connector's offload tier loads early (`supports_early_load`: + # Mooncake Store); any other connector (dense or DSV4 offload, P/D only) + # gets no hook, so the flag changes nothing there. + "ATOM_OFFLOAD_LOAD_EVENT_WAIT": lambda: _flag_env( + "ATOM_OFFLOAD_LOAD_EVENT_WAIT", "1" + ), + # Default on (0 turns it off). With ATOM_OFFLOAD_LOAD_EVENT_WAIT, also + # hold the step for the loads it started while the trade pays + # (`LoadWaitState.budget_s`: tick * gain / (cost * dp_size), at most one + # forward, 0 while any rank of the DP group has a running decode). The DP + # peers the hold delays are charged through cost * dp_size, and their + # decodes through the group flag carried on the per-step DP state sync. + "ATOM_OFFLOAD_LOAD_WAIT_HOLD": lambda: _flag_env( + "ATOM_OFFLOAD_LOAD_WAIT_HOLD", "1" + ), # Minimum external-tier hit worth loading, in tokens. None when unset: each # tier then uses its own default (`KVConnectorFactory.resolve_min_load_tokens`). "OFFLOAD_MIN_LOAD_TOKENS": lambda: _non_negative_or_none( diff --git a/docs/distributed_guide.md b/docs/distributed_guide.md index 204e92bd4bf..873bc9aee16 100644 --- a/docs/distributed_guide.md +++ b/docs/distributed_guide.md @@ -109,15 +109,17 @@ The `stateless_init_dp_group()` method (in `ParallelConfig`) calls `stateless_in ### Synchronized busy loop -The DP busy loop overrides the base `EngineCore.busy_loop()` to synchronize state across DP ranks: every round by default, every N paired rounds after a busy sync with `ATOM_DP_SYNC_INTERVAL` (see [DP state sync interval](#dp-state-sync-interval)). The `_sync_dp_state()` method packs three signals into an int64 tensor and performs a single `AllReduce(MAX)`: +The DP busy loop overrides the base `EngineCore.busy_loop()` to synchronize state across DP ranks: every round by default, every N paired rounds after a busy sync with `ATOM_DP_SYNC_INTERVAL` (see [DP state sync interval](#dp-state-sync-interval)). The `_sync_dp_state()` method packs five signals into an int64 tensor and performs a single `AllReduce(MAX)`: ```python -# State synced: [has_unfinished, shutdown, held] +# State synced: [has_unfinished, shutdown, held, hidden, decoding] state_tensor = torch.tensor( [ - 1 if local_has_unfinished else 0, - 1 if local_shutdown else 0, - 1 if local_held else 0, + int(local_has_unfinished), + int(local_shutdown), + int(local_held), + int(local_hidden), # ATOM_DP_IDLE_WHEN_BLOCKED: work the vote left out + int(local_decoding), # Scheduler.has_running_decode() ], dtype=torch.int64, device="cpu", ) @@ -130,6 +132,7 @@ This ensures: - **All ranks run a step together**: when any rank has unfinished work, every rank steps, an idle one with a dummy batch. The step's phase and padded shape are agreed per step by `ForwardMode.decide`. - **Graceful shutdown**: all ranks must agree before exiting. - **One hold holds the group**: a rank paused, offloaded or fenced for a weight sync holds every rank, so their forwards stay paired. +- **The group's decodes are visible to every rank**: `dp_group_decoding` is set when any rank has a running decode, so a rank that would delay its next forward (the offload load-wait hold, `ATOM_OFFLOAD_LOAD_WAIT_HOLD`) does not add to a peer's ITL. ### Dummy batch execution diff --git a/docs/environment_variables.md b/docs/environment_variables.md index 8e637d3c4e4..9795cf03a9a 100644 --- a/docs/environment_variables.md +++ b/docs/environment_variables.md @@ -534,6 +534,8 @@ derive a bound. | **OFFLOAD_SINGLE_STREAM** | bool | 0 | Experimental: run the staging pack and copy legs on one stream. | | **ATOM_OFFLOAD_EARLY_LOAD_KV_WATERMARK** | float | 0.7 | Early tier load, Mooncake Store only (a waiting request whose async lookup answered gets its blocks and its load on any scheduler tick, not only in the admission pass). No early allocation once the KV pool would be fuller than this fraction; the request is left to the admission pass. | | **ATOM_OFFLOAD_EARLY_LOAD_MAX_FRAC** | float | 0.15 | Cap on the KV blocks held by early-loaded requests, as a fraction of the pool. | +| **ATOM_OFFLOAD_LOAD_EVENT_WAIT** | bool | 1 | Offload load wait: the doorbell part (on by default, `0` turns it off). Installed only when the KV connector's offload tier loads early (`supports_early_load`: Mooncake Store); with any other connector (dense or DSV4 offload, P/D only) there is no hook and nothing changes. An engine step hook (`atom/kv_transfer/offload/load_wait.py`) of the single-engine and DP engine loops (`EngineCore`, `DPEngineCoreProc`; not `PPEngineCoreProc` nor the RapidServe cores). Before each `schedule()` it runs the early tier load (not while a decode is running: that decode's page reservation is installed inside `schedule()`) and ships the loads it started. Workers ring a doorbell on their KV output channel when a load job ends, and a Store lease renewal (`ATOM_STORE_ASYNC_RENEW`) that finishes or reaches its timeout rings it in the engine; after a ring the engine fetches one completion answer requested after it before `schedule()` (a query round trip, bounded by one forward; none before the first forward), so a load that already landed prefills one forward earlier. Loads still in flight are waited for only by the hold (`ATOM_OFFLOAD_LOAD_WAIT_HOLD`, on by default). Rank-local, no collective. Counters are logged once a minute per rank (`[LOAD-WAIT]`). | +| **ATOM_OFFLOAD_LOAD_WAIT_HOLD** | bool | 1 | On by default (`0` turns it off); needs `ATOM_OFFLOAD_LOAD_EVENT_WAIT`. Also holds the step for the loads the pre-schedule pass started while holding pays: at most `tick * gain / (cost * dp_size)` and never more than one tick, where `tick` is the wall time of the engine's last forward, `gain` the started loads this step could still admit (slot and token budget) and `cost` the requests the step carries anyway (`running` plus the admittable waiters ahead). The hold blocks on the doorbell, not a sleep, and ends as soon as every started load landed; a load that misses the bound rides the forward, a failed one falls back to prefill. **DP peers:** the hold delays every DP peer at the next forward collective; the bound charges that through `cost * dp_size`, never exceeds one tick, and is 0 while any rank of the DP group has a running decode (one more flag on the existing per-step `_sync_dp_state` reduction, no new collective; kept between syncs under `ATOM_DP_SYNC_INTERVAL`). `tick` includes the DP dummy forward, so an idle rank measures the group's step, not its own last prefill. With no decode anywhere (a P/D prefill instance) the bound is unchanged. **Measured:** 1P1D (P DEP4 with Mooncake Store, D DEP4) DeepSeek-V4.1-Flash on MI355X, AgentX c256: TTFT mean -20.2% (P90 -24.9%), ITL mean -1.0%, throughput +0.55% against `ATOM_OFFLOAD_LOAD_EVENT_WAIT=0`. **When to turn off:** if a deployment shows an ITL or throughput loss (not measured yet: 4P8D, a DP aggregated Store server, where the group-decode flag keeps the hold at 0 while any rank decodes), set `0`; the doorbell and the fresh answer before `schedule()` stay on. | | **OFFLOAD_GPU_STAGING_CHUNKS** | int | derived from KV geometry | GPU staging buffer size in LMCache chunks (≥ 1). | | **OFFLOAD_GPU_STAGING_MAX_BYTES** | int | unset | Upper bound on the GPU staging buffer in bytes; must hold at least one chunk. Unset, `mooncake_store` bounds it at 48 MiB, which it holds back from the KV budget per save and load thread. | | **OFFLOAD_RELEASE_GPU_STAGING_AFTER_TRANSFER** | bool | 0 | Free the GPU staging buffer after each transfer instead of keeping it. | diff --git a/recipes/DeepSeek-V4.1-Flash-PD.md b/recipes/DeepSeek-V4.1-Flash-PD.md index de67b567715..9e51f0d3102 100644 --- a/recipes/DeepSeek-V4.1-Flash-PD.md +++ b/recipes/DeepSeek-V4.1-Flash-PD.md @@ -118,7 +118,7 @@ ingress in front of the router). PR states are as of 2026-11-27. | PR | What it does | State | Side | As measured (tree `de7d8ec1c`) | How to configure now | Points that used it | Notes | |---|---|---|---|---|---|---|---| -| [#3772](https://github.com/ROCm/ATOM/pull/3772) | Store load wait: the first forward waits for a Mooncake Store load that is already in flight, instead of recomputing the prefix | open | P | Old fixed-wait version: `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS=20`. Its default was 0 (off), so the variable was set explicitly. | Not on main yet. On the current PR head: `ATOM_OFFLOAD_LOAD_EVENT_WAIT`, on by default (`0` turns it off), so set nothing. The PR head removes `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS`, so drop that variable. | all (c1-c768) | The wait is now event-driven: the load-completion doorbell wakes it, and the measured forward time bounds it. There is no fixed timeout. It does nothing without a Store tier. Measured at 1P1D c256: TTFT mean -20.2%, throughput +0.55%. | +| [#3772](https://github.com/ROCm/ATOM/pull/3772) | Store load wait: the first forward waits for a Mooncake Store load that is already in flight, instead of recomputing the prefix | open | P | Old fixed-wait version: `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS=20`. Its default was 0 (off), so the variable was set explicitly. | Not on main yet. On the current PR head: `ATOM_OFFLOAD_LOAD_EVENT_WAIT`, on by default (`0` turns it off), reads a landed load before `schedule()`; the wait for one in flight is `ATOM_OFFLOAD_LOAD_WAIT_HOLD`, also on by default (`0` turns it off). The PR head removes `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS`, so drop that variable. | all (c1-c768) | The wait is now event-driven: the load-completion doorbell wakes it, and the measured forward time bounds it. There is no fixed timeout. It does nothing without a Store tier. Measured at 1P1D c256: TTFT mean -20.2%, throughput +0.55%. | | [#3773](https://github.com/ROCm/ATOM/pull/3773) | Early handoff: P answers the router at DP dispatch, so D allocates pages and pulls KV while P is still computing | open | P | `ATOM_PD_EARLY_HANDOFF=1`. Its default was 0, so the variable was set explicitly. | Not on main yet. On the current PR head it is on by default (`1`). Set `ATOM_PD_EARLY_HANDOFF=0` explicitly wherever it should be off. | all (c1-c768) | **Known issue:** if a P step stalls for more than 60 s, early requests can leak a state slot. Once a rank has leaked `--max-num-seqs` slots, it admits no more requests, permanently. Use `0` at c1024 and above until the fix lands; the fix is in progress. Load visibility is correct only with one P instance. With several P instances behind one router, the router's view of P load is wrong. | | [#3777](https://github.com/ROCm/ATOM/pull/3777) | Idle when blocked: a DP rank whose only work is blocked (Store lookup or load, KV send) idles instead of forcing dummy forwards | merged 2026-11-27 | P | `ATOM_DP_IDLE_WHEN_BLOCKED=1`. The pre-merge default was 0, so the variable was set explicitly. | Set nothing. On main, leaving it unset turns it on for a P/D prefill (`kv_producer`) and off elsewhere. An explicit `0` or `1` applies to any role. | all (c1-c768) | Needs `ATOM_ENABLE_PREFILL_DELAYER=0`, because the prefill delayer turns this setting off. | | [#3854](https://github.com/ROCm/ATOM/pull/3854) | Base64 prompt ids: the prompt token ids are sent as base64-packed uint32, which cuts D's ingest cost | merged 2026-11-26 | P, D, ingress | `ATOM_PROMPT_IDS_B64=1` on P and D (pre-merge default 0; merged into the tree by hand with two conflicts). Ingress: `ATOM_FRONT_IDS_B64=1 ATOM_FRONT_SPLICE_BODY=1`. | P and D: set nothing, since `ATOM_PROMPT_IDS_B64` is on (`1`) by default on main. Ingress: keep `ATOM_FRONT_IDS_B64=1 ATOM_FRONT_SPLICE_BODY=1`. | all (c1-c768) | The two `ATOM_FRONT_*` variables belong to the external ingress, not to ATOM. Without them the ingress sends JSON ids, which still work. | @@ -2536,7 +2536,8 @@ for their current defaults): 3. **ATOM [#3772](https://github.com/ROCm/ATOM/pull/3772)** (open): `ATOM_OFFLOAD_PRESTART_LOAD_WAIT_MS` as measured. The current PR head - replaces it with `ATOM_OFFLOAD_LOAD_EVENT_WAIT` (on by default). + replaces it with `ATOM_OFFLOAD_LOAD_EVENT_WAIT` (on by default) plus the + wait itself, `ATOM_OFFLOAD_LOAD_WAIT_HOLD` (on by default). 4. **ATOM [#3773](https://github.com/ROCm/ATOM/pull/3773)** (open): `ATOM_PD_EARLY_HANDOFF`. It applies only when P uses single-node DP and the router uses the legacy relay. The current PR head turns it on by diff --git a/tests/test_dp_idle_when_blocked.py b/tests/test_dp_idle_when_blocked.py index 5e58a8e50fe..3635dfb3241 100644 --- a/tests/test_dp_idle_when_blocked.py +++ b/tests/test_dp_idle_when_blocked.py @@ -643,12 +643,13 @@ def resume(): def test_sync_reduces_hidden_work_with_the_vote(monkeypatch): - # Every rank sends the same four flags, set or not, so the all_reduce + # Every rank sends the same five flags, set or not, so the all_reduce # matches across ranks whatever each one's setting. p = DPEngineCoreProc.__new__(DPEngineCoreProc) p.label = "dp0" p._shutting_down = False p.dp_group = object() # a real group: the flags go through all_reduce + p.scheduler = SimpleNamespace(has_running_decode=lambda: False) sent = [] def all_reduce(tensor, op=None, group=None): @@ -657,14 +658,14 @@ def all_reduce(tensor, op=None, group=None): monkeypatch.setattr(torch.distributed, "all_reduce", all_reduce) assert p._sync_dp_state(False, True, False) == (False, True, False) - assert sent == [[0, 1, 0, 0]] + assert sent == [[0, 1, 0, 0, 0]] assert p._dp_group_hidden_work is True assert p._sync_dp_state(True, False, False, local_hidden=True) == ( True, False, False, ) - assert sent[-1] == [1, 0, 0, 1] + assert sent[-1] == [1, 0, 0, 1, 0] # ------------------------------- switch ------------------------------------ # diff --git a/tests/test_dp_sync_interval.py b/tests/test_dp_sync_interval.py index 15660b99573..b95b689d289 100644 --- a/tests/test_dp_sync_interval.py +++ b/tests/test_dp_sync_interval.py @@ -166,6 +166,7 @@ def process_step(e=engine, do_step=step): engine.scheduler = SimpleNamespace( heartbeat_throughput=lambda now, e=engine: setattr(e, "tick", e.tick + 1), is_finished=lambda e=engine: not work(e.rank, e.tick), + has_running_decode=lambda: False, engine_stats=SimpleNamespace( note_busy=lambda now: None, note_idle=lambda now: None, diff --git a/tests/test_engine_core_kv_wait.py b/tests/test_engine_core_kv_wait.py index 2a42222509e..19c7b28459b 100644 --- a/tests/test_engine_core_kv_wait.py +++ b/tests/test_engine_core_kv_wait.py @@ -41,6 +41,7 @@ def engine_step(monkeypatch): utility_queue=queue.Queue(), _postprocess=Mock(), label="test", + step_hooks=(), ) engine._wait_for_kv_progress = lambda: engine_core.EngineCore._wait_for_kv_progress( engine diff --git a/tests/test_envs.py b/tests/test_envs.py index 496bc578854..89dfa6316fd 100644 --- a/tests/test_envs.py +++ b/tests/test_envs.py @@ -374,6 +374,24 @@ def test_use_flydsl_gather_kv_b_proj_disabled(self, monkeypatch): monkeypatch.setenv("ATOM_USE_FLYDSL_GATHER_KV_B_PROJ", "0") assert _get_envs().ATOM_USE_FLYDSL_GATHER_KV_B_PROJ is False + def test_offload_load_event_wait_default_enabled(self, monkeypatch): + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_EVENT_WAIT", raising=False) + assert _get_envs().ATOM_OFFLOAD_LOAD_EVENT_WAIT is True + + @pytest.mark.parametrize("value", ["0", "off", ""]) + def test_offload_load_event_wait_opt_out(self, monkeypatch, value): + monkeypatch.setenv("ATOM_OFFLOAD_LOAD_EVENT_WAIT", value) + assert _get_envs().ATOM_OFFLOAD_LOAD_EVENT_WAIT is False + + def test_offload_load_wait_hold_default_enabled(self, monkeypatch): + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_WAIT_HOLD", raising=False) + assert _get_envs().ATOM_OFFLOAD_LOAD_WAIT_HOLD is True + + @pytest.mark.parametrize("value", ["0", "off", ""]) + def test_offload_load_wait_hold_opt_out(self, monkeypatch, value): + monkeypatch.setenv("ATOM_OFFLOAD_LOAD_WAIT_HOLD", value) + assert _get_envs().ATOM_OFFLOAD_LOAD_WAIT_HOLD is False + def test_use_flydsl_gather_kv_b_proj_only_one_enables(self, monkeypatch): monkeypatch.setenv("ATOM_USE_FLYDSL_GATHER_KV_B_PROJ", "true") assert _get_envs().ATOM_USE_FLYDSL_GATHER_KV_B_PROJ is False @@ -428,7 +446,7 @@ def test_offload_env_vars_are_documented(): offload = [ name for name in envs.environment_variables - if name.startswith(("OFFLOAD_", "LMCACHE_")) + if name.startswith(("OFFLOAD_", "LMCACHE_", "ATOM_OFFLOAD_", "ATOM_STORE_")) ] assert offload assert [name for name in offload if f"**{name}**" not in doc] == [] diff --git a/tests/test_offload_load_event_wait.py b/tests/test_offload_load_event_wait.py new file mode 100644 index 00000000000..db89d4d0a77 --- /dev/null +++ b/tests/test_offload_load_event_wait.py @@ -0,0 +1,1157 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors + +"""Offload load wait (`atom/kv_transfer/offload/load_wait.py`). + +The early tier load runs ahead of `schedule()` and its loads are shipped at +once; after a KV progress doorbell (a worker's load job ended) one completion +answer requested after the ring is fetched before `schedule()` +(`ATOM_OFFLOAD_LOAD_EVENT_WAIT`, on). With `ATOM_OFFLOAD_LOAD_WAIT_HOLD` (on by +default) the step is also held for the loads it started while holding pays: +the hold blocks on the doorbell, not on a sleep, and ends as soon as every +started load landed; its bound comes from the measured forward time and the +requests the hold would delay, not from a constant. All of it is an engine +step hook: the engine and the scheduler carry none of its state. +""" + +import pickle +import queue +import socket +import sys +import threading +import time +from collections import deque +from pathlib import Path +from types import ModuleType, SimpleNamespace +from unittest.mock import Mock + +import pytest +from test_mooncake_store_offload import ( # noqa: F401 (fixtures) + aiter_arch, + cluster, + scheduler_clock, +) +from test_scheduler_early_load import _free, _make + +from atom.kv_transfer import progress_doorbell +from atom.kv_transfer.offload import load_wait +from atom.model_engine.sequence import SequenceStatus + +WAITING_LOAD = SequenceStatus.WAITING_FOR_REMOTE_KVS + + +@pytest.fixture(autouse=True) +def _no_doorbell(): + progress_doorbell.install(None) + yield + progress_doorbell.install(None) + + +@pytest.fixture +def engine_core(monkeypatch): + # Scheduling only, not the aiter-backed worker RPC. + async_proc = ModuleType("atom.model_engine.async_proc") + async_proc.AsyncIOProcManager = object + monkeypatch.setitem(sys.modules, "atom.model_engine.async_proc", async_proc) + from atom.model_engine import engine_core as module + + monkeypatch.setattr(module.tracing, "record_forward", Mock()) + return module + + +def _fire(monkeypatch, seq_factory, n=1): + """A scheduler that admits every tick (no prefill delayer).""" + sched, delayer, seqs = _make(monkeypatch, seq_factory, n=n) + sched.set_prefill_delayer(None) + # Metadata the engine treats as carrying work, so it is shipped. + sched.kv_connector.build_connector_meta = lambda: SimpleNamespace( + reqs_to_recv={"load": object()} + ) + return sched, delayer, seqs + + +class _Mgr: + """Runner-manager double. + + A shipped load lands on a timer thread after its delay (None: only with a + forward) and rings the doorbell, as `LoadExecutor` does (the marker's + arrival rings the engine's doorbell, which sets its KV progress event). A + completion answer is a snapshot taken when it is requested, as a worker + answers the query when it reaches it, and arrives at once (setting the + engine's KV progress event); `collect` closes the outstanding one and + requests the next (`AsyncIOProcManager.call_func_with_aggregation`'s + pipelining). A forward lands whatever is still in flight by its end. + """ + + def __init__(self, sched, progress_event, delay=0.0, fail=False, forward_s=0.0): + self.sched = sched + self.progress_event = progress_event + self.delay = delay # seconds, None, or {seq id: seconds | None} + self.fail = fail + self.forward_s = forward_s + self.lock = threading.Lock() + self.shipped, self.inflight, self.landed = set(), set(), set() + self.pending = None # (requested at, snapshot) + self.calls, self.forwards, self.timers = [], [], [] + + def _delay(self, seq_id): + return self.delay.get(seq_id) if isinstance(self.delay, dict) else self.delay + + def land(self, seq_id): + with self.lock: + if seq_id not in self.inflight: + return + self.inflight.discard(seq_id) + self.landed.add(seq_id) + progress_doorbell.ring() + + def call_func(self, name, *args, **kwargs): + self.calls.append(name) + if name == "process_kvconnector_output": + for seq in list(self.sched.waiting): + if seq.status != WAITING_LOAD or seq.id in self.shipped: + continue + self.shipped.add(seq.id) + with self.lock: + self.inflight.add(seq.id) + delay = self._delay(seq.id) + if delay == 0: + self.land(seq.id) + elif delay is not None: + timer = threading.Timer(delay, self.land, (seq.id,)) + timer.start() + self.timers.append(timer) + return None + if name == "forward": + if self.forward_s: + time.sleep(self.forward_s) + self.forwards.append(list(args[0].req_ids)) + for seq_id in list(self.inflight): + self.land(seq_id) + return "fwd" + raise AssertionError(name) + + def _request(self): + with self.lock: + snapshot = set(self.landed) + self.landed -= snapshot + self.pending = (time.monotonic(), snapshot) + self.progress_event.set() # the answer arrives + + def collect(self): + self.calls.append("poll") + if self.pending is None: + self._request() + return None + _, snapshot = self.pending + for seq_id in snapshot: + # As `_update_from_kv_xfer_finished`: an aborted load only cleans up. + if self.sched._finish_aborted_load_cleanup(seq_id): + continue + target = ( + self.sched.failed_recving_kv_req_ids + if self.fail + else self.sched.finished_recving_kv_req_ids + ) + target.append(seq_id) + self._request() + return snapshot + + def stop(self): + for timer in self.timers: + timer.cancel() + + +def _engine(module, sched, *, on=True, hold=True, tick_s=1.0, dp=1, **mgr_kwargs): + """An engine double running the real step (`_process_engine_step_inner`) + with the real hook (`OffloadLoadWait`) as its only step hook; `on=False`: + no hook, as with `ATOM_OFFLOAD_LOAD_EVENT_WAIT=0`.""" + event = threading.Event() + mgr = _Mgr(sched, event, **mgr_kwargs) + engine = SimpleNamespace( + scheduler=sched, + kv_transfer_enabled=True, + runner_mgr=mgr, + _collect_kv_transfer_progress=mgr.collect, + _poll_kv_transfer_progress=lambda: bool(mgr.collect()), + _wake_event=event, + input_queue=queue.Queue(), + utility_queue=queue.Queue(), + output_queue=queue.Queue(), + _postprocess=Mock(), + _release_request_resources=Mock(), + _wait_for_kv_progress=lambda: None, + _advance_idle_kv_transfer=mgr.collect, + label="test", + step_hooks=(), + ) + if on: + hook = load_wait.OffloadLoadWait(engine, dp, hold=hold) + hook.state.tick_s = tick_s + engine.step_hooks = (hook,) + return engine, mgr + + +def _stats(engine): + (hook,) = engine.step_hooks + return hook.state + + +def _step(module, engine): + return module.EngineCore._process_engine_step_inner(engine) + + +def _steps_until_prefill(module, engine, mgr, seq, limit=6): + for step in range(1, limit + 1): + _step(module, engine) + if mgr.forwards and seq.id in mgr.forwards[-1]: + return step + return None + + +# -- load lands before / while / after the hold ------------------------------ + + +def test_load_that_already_landed_prefills_in_this_step_without_waiting( + engine_core, monkeypatch, seq_factory +): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, delay=0) # lands as it ships + + t0 = time.monotonic() + assert _steps_until_prefill(engine_core, engine, mgr, seq) == 1 + assert time.monotonic() - t0 < 0.5 + stats = _stats(engine) + assert (stats.steps, stats.loads, stats.waits, stats.landed) == (1, 1, 1, 1) + assert stats.timed_out == 0 and stats.wakes == 1 + assert sched.kv_connector.allocs == [seq.id] # one admission only + assert sched._num_parked_remote_kv == 0 + + +def test_hold_ends_on_the_doorbell_not_at_its_bound( + engine_core, monkeypatch, seq_factory +): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + # Bound 2 s (one tick, nothing else to delay); the load lands at 50 ms. + engine, mgr = _engine(engine_core, sched, tick_s=2.0, delay=0.05) + + t0 = time.monotonic() + _step(engine_core, engine) + elapsed = time.monotonic() - t0 + + assert mgr.forwards == [[seq.id]] # this step's forward + assert 0.05 <= elapsed < 1.0 + # Shipped first; no poll before the doorbell rang (no sleep-polling). + assert mgr.calls[0] == "process_kvconnector_output" + held = mgr.calls[: mgr.calls.index("forward")] + assert held.count("poll") <= 3 + assert _stats(engine).wakes == 1 + + +class _LateReplyMgr(_Mgr): + """A worker that reaches each completion query late: an answer's snapshot + is taken when it is collected (so a query requested before a ring can + carry the completion that rang), and each new query is answered only + after `reply_s`.""" + + def __init__(self, *args, reply_s, **kwargs): + super().__init__(*args, **kwargs) + self.reply_s = reply_s + self.ready_at = 0.0 + + def _request(self): + self.pending = (time.monotonic(), set()) + self.ready_at = time.monotonic() + self.reply_s + timer = threading.Timer(self.reply_s, self.progress_event.set) + timer.start() + self.timers.append(timer) + + def collect(self): + if self.pending is not None: + if time.monotonic() < self.ready_at: + self.calls.append("poll") + return None + with self.lock: + snapshot = set(self.landed) + self.landed -= snapshot + self.pending = (self.pending[0], snapshot) + return super().collect() + + +def test_an_older_answer_that_lands_every_load_ends_the_hold_at_once( + engine_core, monkeypatch, seq_factory +): + """A query requested before the ring can already finish every started + load. The hold re-checks the loads after applying it instead of waiting + one more query round trip (here 0.5 s) for an answer requested after the + ring.""" + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, _ = _engine(engine_core, sched, tick_s=2.0, delay=0) + mgr = _LateReplyMgr(sched, engine._wake_event, delay=0, reply_s=0.5) + engine.runner_mgr = mgr + engine._collect_kv_transfer_progress = mgr.collect + try: + # The query left with the last forward and its answer is in, but the + # worker reached it only after the load below landed. + mgr.pending = (time.monotonic(), set()) + mgr.ready_at = 0.0 + + t0 = time.monotonic() + _step(engine_core, engine) + elapsed = time.monotonic() - t0 + + assert mgr.forwards == [[seq.id]] # this step's forward + assert elapsed < 0.25 # not the next answer's 0.5 s round trip + stats = _stats(engine) + assert (stats.waits, stats.landed, stats.timed_out) == (1, 1, 0) + held = mgr.calls[: mgr.calls.index("forward")] + assert held.count("poll") == 1 # no poll for the next answer + finally: + mgr.stop() + + +def test_late_load_rides_the_forward_after_the_bound( + engine_core, monkeypatch, seq_factory +): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, tick_s=0.05, delay=None) + + t0 = time.monotonic() + _step(engine_core, engine) + elapsed = time.monotonic() - t0 + + assert 0.05 <= elapsed < 1.0 # held for the bound, one tick + assert seq.status == WAITING_LOAD + stats = _stats(engine) + assert (stats.waits, stats.landed, stats.timed_out, stats.wakes) == (1, 0, 1, 0) + # It lands later and is admitted when its completion is read, as without + # the hold; it is not held for again (not a new load). + mgr.land(seq.id) + assert _steps_until_prefill(engine_core, engine, mgr, seq) is not None + assert _stats(engine).waits == 1 + + +def test_failed_load_wakes_the_hold_and_falls_back_to_prefill( + engine_core, monkeypatch, seq_factory +): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, tick_s=2.0, delay=0.02, fail=True) + + t0 = time.monotonic() + assert _steps_until_prefill(engine_core, engine, mgr, seq) == 1 # recomputed + assert time.monotonic() - t0 < 1.0 + assert _stats(engine).landed == 1 + assert sched._num_parked_remote_kv == 0 + assert seq.id not in sched._early_load.entries + + +def test_without_the_hook_the_same_load_prefills_later( + engine_core, monkeypatch, seq_factory +): + # Off: the load lands during step 1's forward and is read only after it. + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, on=False, delay=0) + assert _steps_until_prefill(engine_core, engine, mgr, seq) >= 2 + assert engine.step_hooks == () + + +# -- hold off: doorbell + a fresh answer before schedule() only ----------------- + + +def test_hold_off_does_not_hold_for_a_load_in_flight( + engine_core, monkeypatch, seq_factory +): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, hold=False, tick_s=2.0, delay=0.3) + try: + t0 = time.monotonic() + _step(engine_core, engine) + assert time.monotonic() - t0 < 0.2 # no hold for the 300 ms load + assert seq.status == WAITING_LOAD + stats = _stats(engine) + assert (stats.steps, stats.loads, stats.waits, stats.skipped) == (1, 1, 0, 0) + assert mgr.calls[0] == "process_kvconnector_output" # still shipped early + finally: + mgr.stop() + + +def _steps_to_prefill_with_pauses(module, engine, mgr, seq, pause_s=0.1): + """Steps until `seq` prefills, idling `pause_s` between steps (the load + lands in a pause, not during a forward).""" + for step in range(1, 7): + _step(module, engine) + if mgr.forwards and seq.id in mgr.forwards[-1]: + return step + time.sleep(pause_s) + return None + + +def test_hold_off_fresh_answer_admits_a_landed_load_before_schedule( + engine_core, monkeypatch, seq_factory +): + """The load lands between steps. The doorbell makes the next step fetch an + answer requested after the ring before it schedules, so it prefills on + that step; without the hook it waits for the pipelined answers.""" + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, hold=False, tick_s=2.0, delay=0.03) + assert _steps_to_prefill_with_pauses(engine_core, engine, mgr, seq) == 2 + stats = _stats(engine) + assert stats.fresh == 1 and stats.waits == 0 + + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, on=False, delay=0.03) + assert _steps_to_prefill_with_pauses(engine_core, engine, mgr, seq) >= 3 + + +def test_hold_off_fresh_answer_runs_while_a_decode_is_running( + engine_core, monkeypatch, seq_factory +): + # No pre-phase load while a decode runs (page reservation), but a load that + # landed is still read before schedule(). + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, hold=False, tick_s=2.0, delay=None) + _step(engine_core, engine) # parks and ships the load + assert seq.status == WAITING_LOAD + allocs = list(sched.kv_connector.allocs) + sched.running = deque([_decode()]) + mgr.land(seq.id) # rings + + (hook,) = engine.step_hooks + hook.before_schedule() + + assert seq.id in sched.finished_recving_kv_req_ids + assert hook.state.fresh == 1 + assert sched.kv_connector.allocs == allocs # nothing allocated ahead + + +def _bare_hook(tick_s, collect): + engine = SimpleNamespace( + scheduler=SimpleNamespace( + waiting=[], kv_connector=SimpleNamespace(build_connector_meta=lambda: None) + ), + runner_mgr=SimpleNamespace(call_func=Mock()), + _collect_kv_transfer_progress=collect, + _wake_event=threading.Event(), + label="test", + ) + hook = load_wait.OffloadLoadWait(engine, 1, hold=False) + hook.state.tick_s = tick_s + return hook + + +def test_fresh_answer_is_bounded_by_one_tick(): + # A query that is never answered: the step goes on after one tick. + collect = Mock(return_value=None) + hook = _bare_hook(0.05, collect) + progress_doorbell.ring() + t0 = time.monotonic() + hook.before_schedule() + assert 0.05 <= time.monotonic() - t0 < 0.5 + assert hook.state.fresh == 1 and collect.called + + +def test_no_fresh_answer_without_a_ring_or_before_the_first_forward(): + collect = Mock(return_value=None) + hook = _bare_hook(0.05, collect) + hook.before_schedule() # nothing rang + assert not collect.called + cold = _bare_hook(0.0, collect) + progress_doorbell.ring() + cold.before_schedule() # no forward yet: left for the next step + assert not collect.called and cold.state.fresh == 0 + + +def test_load_wait_hook_follows_its_envs(monkeypatch): + engine = SimpleNamespace( + _wake_event=threading.Event(), + scheduler=SimpleNamespace( + kv_connector=SimpleNamespace(supports_early_load=True) + ), + ) + config = SimpleNamespace(parallel_config=SimpleNamespace(data_parallel_size=4)) + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_EVENT_WAIT", raising=False) + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_WAIT_HOLD", raising=False) + hook = load_wait.load_wait_hook(engine, config) + assert hook is not None and hook.hold is True # default: hold on + assert hook.state.dp_size == 4 + monkeypatch.setenv("ATOM_OFFLOAD_LOAD_WAIT_HOLD", "0") + hook = load_wait.load_wait_hook(engine, config) + assert hook is not None and hook.hold is False # off: doorbell only + monkeypatch.setenv("ATOM_OFFLOAD_LOAD_EVENT_WAIT", "0") + assert load_wait.load_wait_hook(engine, config) is None + + +@pytest.mark.parametrize( + "connector", + [ + SimpleNamespace(supports_early_load=False), # dense / DSV4 offload, P/D only + None, # no connector (or a disaggregated decode engine before its scheduler) + ], + ids=["dense", "none"], +) +def test_no_hook_without_an_offload_tier_that_loads_early(monkeypatch, connector): + # `LoadExecutor` rings the doorbell on every offload tier: without the gate + # a dense tier's ring would make each step wait for a fresh answer. + from atom.kv_transfer.engine_step_hooks import kv_transfer_step_hooks + + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_EVENT_WAIT", raising=False) + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_WAIT_HOLD", raising=False) + engine = SimpleNamespace( + _wake_event=threading.Event(), + scheduler=SimpleNamespace(kv_connector=connector), + ) + config = SimpleNamespace(parallel_config=SimpleNamespace(data_parallel_size=4)) + assert load_wait.load_wait_hook(engine, config) is None + assert kv_transfer_step_hooks(engine, config) == () + # The doorbell stays uninstalled: a ring sets no engine event. + progress_doorbell.ring() + assert not engine._wake_event.is_set() + + +def test_dense_offload_connector_gets_no_hook(monkeypatch, seq_factory): + # A real scheduler whose connector cannot load early: the factory leaves + # the engine without a step hook, so its steps are main's. + sched, _, _ = _make(monkeypatch, seq_factory) + sched.kv_connector.supports_early_load = False + monkeypatch.delenv("ATOM_OFFLOAD_LOAD_EVENT_WAIT", raising=False) + engine = SimpleNamespace(_wake_event=threading.Event(), scheduler=sched) + config = SimpleNamespace(parallel_config=SimpleNamespace(data_parallel_size=1)) + assert load_wait.load_wait_hook(engine, config) is None + sched.kv_connector.supports_early_load = True + assert load_wait.load_wait_hook(engine, config) is not None + + +def test_cold_engine_never_holds(engine_core, monkeypatch, seq_factory): + sched, _, _ = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, tick_s=0.0, delay=None) + + t0 = time.monotonic() + _step(engine_core, engine) + + assert time.monotonic() - t0 < 0.5 + stats = _stats(engine) + assert (stats.steps, stats.skipped, stats.waits) == (1, 1, 0) + assert mgr.calls[0] == "process_kvconnector_output" # still shipped early + + +def test_abort_while_held_releases_blocks(engine_core, monkeypatch, seq_factory): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + free = _free(sched) + engine, mgr = _engine(engine_core, sched, tick_s=0.02, delay=None) + _step(engine_core, engine) + assert seq.status == WAITING_LOAD + + assert sched.abort_request(seq.id) + assert _free(sched) < free # the aborted-load protocol: freed on its report + mgr.land(seq.id) + _step(engine_core, engine) + _step(engine_core, engine) + assert _free(sched) == free + assert sched._num_parked_remote_kv == 0 + + +# -- several requests ---------------------------------------------------------- + + +def test_hold_waits_for_every_started_load(engine_core, monkeypatch, seq_factory): + sched, _, (a, b) = _fire(monkeypatch, seq_factory, n=2) + engine, mgr = _engine(engine_core, sched, tick_s=2.0, delay=None) + mgr.delay = {a.id: 0.03, b.id: 0.08} + + t0 = time.monotonic() + _step(engine_core, engine) + elapsed = time.monotonic() - t0 + + assert mgr.forwards == [[a.id, b.id]] # both, in arrival order + assert 0.08 <= elapsed < 1.0 + assert _stats(engine).landed == 2 + assert _stats(engine).wakes >= 1 + + +def test_a_load_that_misses_the_bound_does_not_hold_back_one_that_landed( + engine_core, monkeypatch, seq_factory +): + sched, _, (a, b) = _fire(monkeypatch, seq_factory, n=2) + # Both admittable, nothing else to delay: bound = one tick. + engine, mgr = _engine(engine_core, sched, tick_s=0.1, delay=None) + mgr.delay = {a.id: None, b.id: 0.02} + + _step(engine_core, engine) + + assert mgr.forwards == [[b.id]] + assert a.status == WAITING_LOAD + stats = _stats(engine) + assert (stats.landed, stats.timed_out) == (1, 1) + + +# -- the bound: gain against cost, no constant ---------------------------------- + + +def _partial_prefill(remaining=8): + return SimpleNamespace( + is_partial_prefill=True, num_tokens=remaining, num_cached_tokens=0 + ) + + +def _decode(): + return SimpleNamespace(is_partial_prefill=False) + + +def test_budget_formula(engine_core): + state = load_wait.LoadWaitState(dp_size=1) + assert state.budget_s(1, 0) == 0.0 # no forward measured yet + state.tick_s = 0.2 + assert state.budget_s(0, 0) == 0.0 # nothing to gain + assert state.budget_s(1, 0) == pytest.approx(0.2) # nothing to delay: 1 tick + assert state.budget_s(3, 1) == pytest.approx(0.2) # never past one tick + assert state.budget_s(1, 4) == pytest.approx(0.05) + dp = load_wait.LoadWaitState(dp_size=4) + dp.tick_s = 0.2 + assert dp.budget_s(1, 4) == pytest.approx(0.0125) # peers pay too + assert dp.budget_s(1, 0) == pytest.approx(0.05) + + +def test_tradeoff_on_a_prefill_only_step(monkeypatch, seq_factory): + sched, _, (a, b, c) = _fire(monkeypatch, seq_factory, n=3) + sched.kv_connector.not_ready_ids = {a.id} # a stays an ordinary waiter + started = load_wait.prestart_tier_loads(sched) + assert started == [b, c] + # a (16 tokens) ahead of b and c: both still fit the 64-token budget, and + # the step carries a anyway. + assert load_wait.load_wait_tradeoff(sched, started) == (2, 1) + sched.running = deque([_partial_prefill()]) + sched._partial_prefill_count = 1 + assert load_wait.load_wait_tradeoff(sched, started) == (2, 2) + # A load that landed or was aborted is not a gain. + c.status = SequenceStatus.ABORTED + assert load_wait.load_wait_tradeoff(sched, started) == (1, 2) + assert load_wait.load_wait_tradeoff(sched, []) == (0, 1) + + +def test_tradeoff_stops_at_the_token_budget_and_slots(monkeypatch, seq_factory): + sched, _, seqs = _fire(monkeypatch, seq_factory, n=6) + *ahead, last = seqs + sched.kv_connector.not_ready_ids = {s.id for s in ahead} + started = load_wait.prestart_tier_loads(sched) + assert started == [last] + # 5 x 16 tokens ahead fill the 64-token budget: nothing to gain. + assert load_wait.load_wait_tradeoff(sched, started)[0] == 0 + sched2, _, _ = _fire(monkeypatch, seq_factory) + started = load_wait.prestart_tier_loads(sched2) + sched2.running = deque(_partial_prefill(1) for _ in range(sched2.max_num_seqs)) + sched2._partial_prefill_count = sched2.max_num_seqs + assert load_wait.load_wait_tradeoff(sched2, started)[0] == 0 # no free slot + + +def test_running_decodes_shrink_the_bound_to_almost_nothing( + engine_core, monkeypatch, seq_factory +): + # The same rule, no special case: every running decode is delayed by a + # hold, so the bound falls with the decode batch. + sched, _, _ = _fire(monkeypatch, seq_factory) + started = load_wait.prestart_tier_loads(sched) + sched.running = deque(_decode() for _ in range(6)) + gain, cost = load_wait.load_wait_tradeoff(sched, started) + assert (gain, cost) == (1, 6) + state = load_wait.LoadWaitState(dp_size=4) + state.tick_s = 0.012 # a decode step + assert state.budget_s(gain, cost) == pytest.approx(0.0005) + + +def test_no_pre_phase_load_while_a_decode_is_running(monkeypatch, seq_factory): + # Ordering, not tuning: the pre-phase allocates, and a running decode's + # page reservation is installed only inside `_schedule()`. + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + sched.running = deque([_decode()]) + free = _free(sched) + assert load_wait.prestart_tier_loads(sched) == [] + assert sched.kv_connector.allocs == [] and _free(sched) == free + assert seq.status == SequenceStatus.WAITING + assert sched._early_load.take_tick_pass() # `_schedule()` runs its own pass + sched.running = deque([_partial_prefill(), _decode()]) + sched._partial_prefill_count = 1 + assert load_wait.prestart_tier_loads(sched) == [] + # Partial prefills only (the P/D prefill case): the pre-phase runs. + sched.running = deque([_partial_prefill()]) + assert load_wait.prestart_tier_loads(sched) == [seq] + + +def test_no_decode_prefill_only_step_holds(engine_core, monkeypatch, seq_factory): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, tick_s=2.0, delay=0.03) + assert not sched.has_running_decode() + _step(engine_core, engine) + assert mgr.forwards == [[seq.id]] + assert _stats(engine).waits == 1 + + +def test_forward_time_is_the_tick(engine_core, monkeypatch, seq_factory): + sched, _, _ = _fire(monkeypatch, seq_factory) + engine, _ = _engine(engine_core, sched, tick_s=2.0, delay=0, forward_s=0.03) + _step(engine_core, engine) + assert 0.03 <= _stats(engine).tick_s < 0.5 + + +def test_dp_dummy_forward_updates_the_tick(engine_core, monkeypatch, seq_factory): + # An idle DP rank runs dummy forwards paired with its peers' real ones: + # their wall time is the group's step, so the tick follows it instead of + # keeping this rank's last real (long prefill) forward. + sched, _, _ = _fire(monkeypatch, seq_factory) + engine, _ = _engine(engine_core, sched, tick_s=0.5, dp=8) # a 500 ms prefill + + def dummy_execution(name, wait_out=False): + assert name == "dummy_execution" and wait_out + time.sleep(0.03) + return "fwd" + + engine.runner_mgr = SimpleNamespace(call_func=dummy_execution) + engine.scheduler = SimpleNamespace(running=()) + engine_core.DPEngineCoreProc._execute_dummy_batch(engine) + state = _stats(engine) + assert 0.03 <= state.tick_s < 0.3 + assert state.budget_s(1, 0) == pytest.approx(state.tick_s / 8) + + +def test_a_peer_decode_makes_the_hold_budget_zero(engine_core): + state = load_wait.LoadWaitState(dp_size=8) + state.tick_s = 0.03 + # No decode on this rank (cost 0) and a fresh Store hit: tick / dp_size ... + assert state.budget_s(1, 0) == pytest.approx(0.03 / 8) + # ... unless a peer decodes: the hold would add to its ITL. + assert state.budget_s(1, 0, group_decoding=True) == 0.0 + assert state.budget_s(3, 1, group_decoding=True) == 0.0 + + +def test_a_peer_decode_keeps_the_step_from_holding( + engine_core, monkeypatch, seq_factory +): + # This rank has no decode, so its pre-phase still starts and ships the + # load, but a peer's running decode (reduced on `_sync_dp_state`) leaves + # nothing to hold for: the step goes on and the load rides the forward. + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, tick_s=2.0, dp=4, delay=None) + engine.dp_group_decoding = True + + t0 = time.monotonic() + _step(engine_core, engine) + + assert time.monotonic() - t0 < 0.5 + stats = _stats(engine) + assert (stats.steps, stats.loads, stats.skipped, stats.waits) == (1, 1, 1, 0) + assert mgr.calls[0] == "process_kvconnector_output" # still shipped early + assert seq.status == WAITING_LOAD + + +def test_prefill_only_group_keeps_the_hold_and_its_bound( + engine_core, monkeypatch, seq_factory +): + # The measured case (a P/D prefill instance: no decode on any rank): the + # group flag is clear, the bound is the same formula as before, and the + # step holds for the load and prefills it in this step. + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + engine, mgr = _engine(engine_core, sched, tick_s=2.0, dp=4, delay=0.03) + engine.dp_group_decoding = False + + _step(engine_core, engine) + + state = _stats(engine) + assert mgr.forwards == [[seq.id]] + assert (state.waits, state.landed, state.timed_out) == (1, 1, 0) + # tick * gain / (max(1, cost) * dp_size) = 2.0 * 1 / (1 * 4): unchanged. + assert state.budget_total_s == pytest.approx(2.0 / 4) + + +def test_sync_dp_state_carries_any_rank_decoding(engine_core, monkeypatch): + # One more flag on the same all_reduce (no new collective): a peer's + # running decode reaches every rank as `dp_group_decoding`. + import torch + + p = engine_core.DPEngineCoreProc.__new__(engine_core.DPEngineCoreProc) + p.label = "dp0" + p._shutting_down = False + p.dp_group = object() + p.scheduler = SimpleNamespace(has_running_decode=lambda: False) + calls = [] + peer = {"decoding": 1} + + def all_reduce(tensor, op=None, group=None): + calls.append(tensor.tolist()) + tensor[4] = max(int(tensor[4]), peer["decoding"]) + + monkeypatch.setattr(torch.distributed, "all_reduce", all_reduce) + assert p._sync_dp_state(True, False, False) == (True, False, False) + assert p.dp_group_decoding is True + peer["decoding"] = 0 + p._sync_dp_state(True, False, False) + assert p.dp_group_decoding is False + p.scheduler = SimpleNamespace(has_running_decode=lambda: True) + p._sync_dp_state(True, False, False) + assert calls[-1] == [1, 0, 0, 0, 1] # this rank's own decode is sent + assert p.dp_group_decoding is True + assert len(calls) == 3 # one collective per sync + + +# -- off is main, one early-load pass per step ------------------------------------ + + +def test_off_step_is_unchanged(engine_core, monkeypatch): + monkeypatch.setattr( + load_wait, + "prestart_tier_loads", + Mock(side_effect=AssertionError("pre-phase ran")), + ) + batch = SimpleNamespace( + req_ids=["r"], connector_meta_output=None, total_seqs_num_prefill=1 + ) + order = Mock() + scheduler = SimpleNamespace( + schedule=Mock(return_value=(batch, {})), + take_rejected=Mock(return_value=[]), + compute_detailed_aggregates=Mock(), + metrics=SimpleNamespace(record_forward=Mock()), + prefill_delayer=None, + ) + order.attach_mock(scheduler.schedule, "schedule") + runner = SimpleNamespace(call_func=Mock(return_value="fwd")) + order.attach_mock(runner.call_func, "call_func") + poll = Mock(return_value=False) + order.attach_mock(poll, "poll") + engine = SimpleNamespace( + step_hooks=(), + scheduler=scheduler, + kv_transfer_enabled=True, + runner_mgr=runner, + _poll_kv_transfer_progress=poll, + _wake_event=threading.Event(), + _postprocess=Mock(), + ) + assert engine_core.EngineCore._process_engine_step_inner(engine) is True + assert [c[0] for c in order.mock_calls] == ["schedule", "call_func", "poll"] + + +@pytest.mark.parametrize("on", [False, True], ids=["off", "on"]) +def test_one_lookup_prefetch_and_one_early_load_pass_per_step( + engine_core, monkeypatch, seq_factory, on +): + sched, _, seqs = _fire(monkeypatch, seq_factory, n=2) + sched.kv_connector.not_ready_ids = {s.id for s in seqs} # stay waiting + events = [] + conn = sched.kv_connector + prefetch = conn.prefetch_lookups + early_load = sched._early_load_tier_prefixes + + def counting_prefetch(waiting): + events.append("prefetch") + return prefetch(waiting) + + def tracing_early_load(): + events.append("early_load") + return early_load() + + conn.prefetch_lookups = counting_prefetch + monkeypatch.setattr(sched, "_early_load_tier_prefixes", tracing_early_load) + engine, _ = _engine(engine_core, sched, on=on, delay=None) + for _ in range(3): + events.clear() + _step(engine_core, engine) + assert events == ["prefetch", "early_load"] + assert sched._early_load.tick == 3 + + +def test_state_load_queued_by_the_pre_phase_ships_with_its_first_build( + engine_core, monkeypatch, seq_factory +): + sched, _, (seq,) = _fire(monkeypatch, seq_factory) + conn = sched.kv_connector + queued, enqueued, shipped = [], [], [] + record_alloc = conn.update_state_after_alloc + + def update_state_after_alloc(s): + record_alloc(s) + queued.append((s.id, "state-hash", 0)) + + def take_state_loads(): + out = list(queued) + queued.clear() + return out + + def enqueue_state_loads(loads): + enqueued.extend(loads) + return True + + def build_connector_meta(): + meta = SimpleNamespace(reqs_to_recv={"load": object()}, state=list(enqueued)) + enqueued.clear() + return meta + + conn.update_state_after_alloc = update_state_after_alloc + conn.enqueue_state_loads = enqueue_state_loads + conn.build_connector_meta = build_connector_meta + monkeypatch.setattr( + sched.block_manager, "take_state_loads", take_state_loads, raising=False + ) + engine, mgr = _engine(engine_core, sched, tick_s=0.01, delay=None) + inner = mgr.call_func + + def call_func(name, *args, **kwargs): + if name == "process_kvconnector_output": + shipped.append(args[0]) + return inner(name, *args, **kwargs) + + mgr.call_func = call_func + _step(engine_core, engine) + assert shipped and shipped[0].state == [(seq.id, "state-hash", 0)] + + +# -- the doorbell ------------------------------------------------------------------- + + +def test_doorbell_coalesces_until_rearmed(): + sent = [] + progress_doorbell.ring() # not installed: a no-op + progress_doorbell.install(lambda: sent.append(1)) + progress_doorbell.ring() + progress_doorbell.ring() + assert sent == [1] + progress_doorbell.rearm() + progress_doorbell.ring() + assert sent == [1, 1] + progress_doorbell.install(lambda: sent.append(2), coalesce=False) + progress_doorbell.ring() + progress_doorbell.ring() + assert sent == [1, 1, 2, 2] + + +def test_a_failed_send_does_not_silence_the_doorbell(): + calls = [] + + def send(): + calls.append(1) + if len(calls) == 1: + raise OSError("queue closed") + + progress_doorbell.install(send) + progress_doorbell.ring() + progress_doorbell.ring() + assert len(calls) == 2 + + +def test_load_executor_rings_after_the_job_recorded_its_result(): + from atom.kv_transfer.offload._offload_common import LoadExecutor + + record, seen = [], [] + progress_doorbell.install(lambda: seen.append(list(record))) + pool = LoadExecutor(max_workers=1) + pool.submit(record.append, "done") + pool.shutdown(wait=True) + assert seen == [["done"]] + + +def test_manager_rings_the_engine_doorbell_and_keeps_the_marker_out_of_answers(): + import zmq + from aiter_stub import stubbed_aiter + + with stubbed_aiter(): + from atom.kv_transfer.disaggregation import KVConnectorOutput + from atom.kv_transfer.progress_doorbell import KV_PROGRESS_DOORBELL + from atom.model_engine.async_proc import AsyncIOProcManager + + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + addr = f"tcp://127.0.0.1:{port}" + mgr = AsyncIOProcManager.__new__(AsyncIOProcManager) + mgr.label = "test" + mgr.zmq_ctx = zmq.Context() + mgr.still_running = True + mgr.kv_outputs_queues = [queue.Queue()] + mgr.kv_progress_event = threading.Event() + # The engine's doorbell, as `OffloadLoadWait` installs it. + rung = threading.Event() + progress_doorbell.install(rung.set, coalesce=False) + rings = progress_doorbell.rings() + thread = threading.Thread( + target=mgr.process_kv_output_sockets, args=(addr, 0), daemon=True + ) + thread.start() + push = mgr.zmq_ctx.socket(zmq.PUSH) + push.connect(addr) + try: + push.send(pickle.dumps(KV_PROGRESS_DOORBELL)) + assert rung.wait(5) + assert progress_doorbell.rings() == rings + 1 + assert mgr.kv_progress_event.wait(5) + assert mgr.kv_outputs_queues[0].empty() # never joins an aggregation + push.send(pickle.dumps(KVConnectorOutput())) + assert isinstance(mgr.kv_outputs_queues[0].get(timeout=5), KVConnectorOutput) + assert progress_doorbell.rings() == rings + 1 # an answer is not a ring + finally: + mgr.still_running = False + push.close(linger=0) + thread.join(timeout=3) + mgr.zmq_ctx.term() + + +def test_offload_worker_rearms_the_doorbell_in_get_finished(): + from atom.kv_transfer.offload._offload_common import OffloadWorkerMixin + + sent = [] + progress_doorbell.install(lambda: sent.append(1)) + worker = OffloadWorkerMixin.__new__(OffloadWorkerMixin) + worker._lock = threading.Lock() + worker._done_load, worker._failed_load, worker._done_save = {"a"}, set(), set() + worker._connector_completions = set() + progress_doorbell.ring() + progress_doorbell.ring() # coalesced + assert worker.get_finished().finished_loading == {"a"} + progress_doorbell.ring() # rearmed by the answer + assert sent == [1, 1] + + +def test_shared_engine_classes_carry_no_load_wait_state(): + """The load wait lives in its offload module, reached through the + engine's generic step hooks: the shared engine classes name none of it.""" + root = Path(__file__).resolve().parents[1] / "atom" / "model_engine" + feature_names = ( + "load_wait", + "LoadWait", + "prestart", + "_load_event_wait", + "kv_doorbell_event", + "kv_aggregation_started_at", + "ATOM_OFFLOAD_LOAD_EVENT_WAIT", + "ATOM_OFFLOAD_LOAD_WAIT_HOLD", + "rearm", + ) + for name in ("engine_core.py", "scheduler.py", "async_proc.py", "model_runner.py"): + source = (root / name).read_text(encoding="utf-8") + assert [n for n in feature_names if n in source] == [], name + + +# -- a load parked on its Store lease renewal ----------------------------------------- + + +def _hold_for_a_renewal(engine_core, clock, monkeypatch, *, stall): + """Hold a step for one load parked on its async Store lease renewal + (`ATOM_STORE_ASYNC_RENEW`), bound 2 s. The renewal finishes at 30 ms, or + with `stall` never (its timeout is 0.1 s). Each shipped GET lands 20 ms + later. Returns (seconds held, GETs shipped, loads reported, wait stats).""" + from concurrent.futures import Future + + from test_mooncake_store_offload import ( + _arm_load, + _config, + _install_future, + _seq, + ) + + from atom.kv_transfer.offload.mooncake_store import async_lookup + from atom.kv_transfer.offload.mooncake_store.scheduler import ( + MooncakeStoreOffloadScheduler, + ) + + monkeypatch.setenv("ATOM_STORE_ASYNC_RENEW", "1") + connector = MooncakeStoreOffloadScheduler(_config("kv_consumer")) + seq = _seq(59, 50) + _arm_load(connector, seq, hbm=16, lmc=40) + clock.now += 2.0 # old enough to need a renewal + future = Future() + if stall: + # Real clock: the renewal's timeout passes while the step is held. + monkeypatch.setattr(async_lookup, "RENEW_TIMEOUT_S", 0.1) + client = connector._lookup_client + client.renew_executor.shutdown() + client.renew_executor = SimpleNamespace( + submit=lambda fn, keys: future, shutdown=lambda: None + ) + else: + _install_future(connector, clock, monkeypatch, future, []) + + event = threading.Event() + shipped, worker_landed, reported = [], set(), set() + pending = [] + + def land(): + worker_landed.add(seq.id) + progress_doorbell.ring() # the worker's marker, rung in the engine + + def call_func(name, meta): + assert name == "process_kvconnector_output" + shipped.extend(r.load_operation for r in meta.requests) + threading.Timer(0.02, land).start() # the GET lands 20 ms later + + def collect(): + answer = None + if pending: + answer = pending.pop() + reported.update(answer) + pending.append(set(worker_landed)) + event.set() + return answer + + monkeypatch.setattr(load_wait, "prestart_tier_loads", lambda sched: [seq]) + monkeypatch.setattr(load_wait, "load_wait_tradeoff", lambda sched, s: (1, 0)) + scheduler = SimpleNamespace( + kv_connector=connector, + _still_loading=lambda s: s.id not in reported, + ) + engine = SimpleNamespace( + scheduler=scheduler, + runner_mgr=SimpleNamespace(call_func=call_func), + _collect_kv_transfer_progress=collect, + _wake_event=event, + label="test", + ) + hook = load_wait.OffloadLoadWait(engine, 1, hold=True) + hook.state.tick_s = 2.0 + if not stall: + threading.Timer(0.03, future.set_result, (5,)).start() # renewal finishes + try: + t0 = time.monotonic() + hook.before_schedule() + elapsed = time.monotonic() - t0 + assert not connector._reqs_need_recv + return elapsed, shipped, reported, seq, hook.state + finally: + connector.close() + + +def test_renewal_finishing_mid_hold_wakes_it_and_ships_the_load( + engine_core, + aiter_arch, # noqa: F811 (fixture) + cluster, # noqa: F811 (fixture) + scheduler_clock, # noqa: F811 (fixture) + monkeypatch, +): + """`ATOM_STORE_ASYNC_RENEW`: the renewal's completion rings the engine's + doorbell, the hold ships the GET it released, and the GET's own landing + ends the hold -- long before its bound.""" + elapsed, shipped, reported, seq, stats = _hold_for_a_renewal( + engine_core, scheduler_clock, monkeypatch, stall=False + ) + assert len(shipped) == 1 # the GET went out once, after the renewal + assert reported == {seq.id} + assert elapsed < 1.0 # ended by events, not the 2 s bound + assert (stats.waits, stats.landed, stats.timed_out) == (1, 1, 0) + assert stats.wakes >= 2 # the renewal, then the GET + + +def test_renewal_stalled_past_its_timeout_wakes_the_hold_and_ships_the_load( + engine_core, + aiter_arch, # noqa: F811 (fixture) + cluster, # noqa: F811 (fixture) + scheduler_clock, # noqa: F811 (fixture) + monkeypatch, +): + """A renewal that never finishes rings nothing itself, but at its timeout + the load may go out ("timeout"): the expiry rings the doorbell, the hold + ships the GET and ends on its landing, not at the 2 s bound.""" + elapsed, shipped, reported, seq, stats = _hold_for_a_renewal( + engine_core, scheduler_clock, monkeypatch, stall=True + ) + assert len(shipped) == 1 # the GET went out at the renewal's timeout + assert reported == {seq.id} + assert 0.1 <= elapsed < 1.0 + assert (stats.waits, stats.landed, stats.timed_out) == (1, 1, 0) + assert stats.wakes >= 2 # the renewal's expiry, then the GET