Repository navigation
[Serve] Support ordered list of candidate multiplexed model IDs - #67095
Asthenia0412 wants to merge 9 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for an ordered list of candidate multiplexed model IDs (candidate_multiplexed_model_ids) in Ray Serve's request routing, allowing the router to pick the first warm replica matching any of the candidates to reduce cold-start latency while maintaining backwards compatibility. The review feedback identifies a critical issue where pending-request coalescing is broken for candidate-only requests because they are not properly indexed in _add_pending_request_to_indices. Additionally, the feedback points out a discrepancy between the docstring and implementation of rank_replicas_via_multiplex, and a bug in the timeout fallback unit test where a new request is incorrectly instantiated instead of reusing the original request.
7fd7879 to
fa5b7ca
Compare
|
Fixed two critical bugs: (1) pending request coalescing index was missing candidate IDs so fallback never worked, (2) resolved multiplexed_model_id was never written back to metadata so replicas saw empty strings. Could someone please re-trigger Buildkite microcheck to verify? |
fa5b7ca to
0b17d7d
Compare
c9b936c to
40f943c
Compare
|
All reviewer comments have been resolved: gemini-code-assist comments:
cursor bugbot comments:
Pushed an empty commit to re-trigger Buildkite microcheck. |
Signed-off-by: Asthenia0412 <[email protected]>
Signed-off-by: Asthenia0412 <[email protected]>
9ef9bd4 to
fa55609
Compare
| pending_request.metadata.candidate_multiplexed_model_ids | ||
| and multiplexed_model_id | ||
| ): | ||
| pending_request.metadata.candidate_multiplexed_model_ids = None |
There was a problem hiding this comment.
Early model lock breaks candidate fallback
High Severity
apply_multiplex_routing writes a single resolved ID onto RequestMetadata and clears candidate_multiplexed_model_ids before any replica is assigned. The request stays indexed under every original candidate, so coalescing can hand it a replica selected for a different model while the replica still sees the locked ID and may cold-load it. Other already-warm candidates are also ignored once the first one is busy.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit fa55609. Configure here.
ee5d1fb to
fc1a853
Compare
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
1. Index pending requests under every effective multiplexed model ID, not just the legacy single-value field. Requests that only set candidate_multiplexed_model_ids (without multiplexed_model_id) were never added to _pending_requests_by_model_id, so same-model coalescing could never find them. 2. After resolving the effective model ID in apply_multiplex_routing, write it back to pending_request.metadata.multiplexed_model_id so that replica-side @serve.multiplexed loaders see whichever ID the router actually routed to. Without this write-back the replica saw an empty model ID on candidate-only requests and either cold-loaded the wrong model or failed to multiplex at all. Both bugs surfaced in the upstream microcheck CI. Signed-off-by: Asthenia0412 <[email protected]>
…tiplexMixin RequestRouter._add_pending_request_to_indices calls self._get_effective_multiplexed_model_ids unconditionally, but that helper lives only on MultiplexMixin. Routers that do not compose the mixin (e.g. ConsistentHashRouter or custom RequestRouter subclasses) raise AttributeError on every request. Wrap the call in hasattr() with a fallback that reconstructs the legacy single-ID behaviour. This matches the defensive pattern used in on_replica_actor_died and update_replicas. Signed-off-by: Asthenia0412 <[email protected]>
Three targeted fixes for bot-flagged issues on the ordered candidate model ID PR: 1. Write-back no longer inverts caller priority. After apply_multiplex_routing resolves an ordered candidate list to a warm model ID and writes it back to metadata.multiplexed_model_id, we now also clear candidate_multiplexed_model_ids. Otherwise _get_effective_multiplexed_model_ids re-prepends the resolved ID as highest priority on the next call, permanently reordering the caller's original list so retries and pending-request coalescing could no longer fall back to later candidates once an earlier one warms up. 2. Fix timeout-fallback unit test to actually exercise the timeout. test_candidate_model_ids_fallback_when_no_warm advanced the clock then created a brand-new request with a fresh multiplexed_start_matching_time, so the timeout never elapsed. It also reset routing_context on an unused object. Now we reuse the same request across successive calls: one call after timeout to try the fewest-model fallback (the single allowed retry there), and a second call to verify it falls back to all replicas. 3. Correct rank_replicas_via_multiplex docstring. The old docstring implied the method handled ordered candidate lists directly, but it accepts only a single resolved model ID. Clarify that apply_multiplex_routing (or _get_first_available_multiplexed_model_id) is the right place to do candidate-list resolution before passing a single ID here. All three fixes are local to the changes already in this PR and do not touch unrelated code paths. Signed-off-by: Asthenia0412 <[email protected]>
Signed-off-by: Asthenia0412 <[email protected]>
All inline reviewer comments have been addressed in prior commits: - _add_pending_request_to_indices now indexes under all effective model IDs with hasattr() guard for routers without MultiplexMixin - apply_multiplex_routing writes the resolved model ID back to metadata and clears the candidate list to preserve caller ordering - rank_replicas_via_multiplex docstring updated to match implementation - test_candidate_model_ids_fallback_when_no_warm reuses the same request so the timeout is properly exercised Signed-off-by: Asthenia0412 <[email protected]>
Signed-off-by: Asthenia0412 <[email protected]>
Signed-off-by: Asthenia0412 <[email protected]>
Signed-off-by: Asthenia0412 <[email protected]>
These functions were removed but are still imported by plan_generated_id_ops.py, causing ImportError at runtime. Signed-off-by: Asthenia0412 <[email protected]>
9246b3d to
50e36fd
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
There are 3 total unresolved issues (including 1 from previous review).
Reviewed by Cursor Bugbot for commit 50e36fd. Configure here.
|
|
||
| For ``generated_id_column`` configs it also loads the checkpoint when | ||
| execution starts; the planned ``ListFiles`` / ``ReadFiles`` operators | ||
| read it through :meth:`load_checkpoint`. |
There was a problem hiding this comment.
Generated-ID checkpoint load removed
High Severity
LoadCheckpointCallback no longer loads a generated-ID checkpoint at execution start and no longer exposes load_checkpoint, but Planner.plan still passes checkpoint_callback.load_checkpoint into generated-ID restore planning. Resuming a job that uses generated_id_column fails.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 50e36fd. Configure here.
| # Both root-path listing and the prelisted route must honor them. | ||
| excluded_ids = ctx.kwargs.get(EXCLUDED_READ_UNIT_IDS_KWARG_NAME) | ||
| if isinstance(excluded_ids, (pa.Array, pa.ChunkedArray)): | ||
| # A set built straight from an Arrow array holds Arrow scalars, which |
There was a problem hiding this comment.
Excluded IDs skip Arrow conversion
Medium Severity
list_files_for_each_block now builds excluded_read_unit_ids with frozenset(excluded_ids) and no longer converts Arrow arrays to Python strings. plan_list_files_op_with_done_read_units still passes done_unit_ids, a pa.Array, so the frozenset holds Arrow scalars that never match string unit IDs and finished work is listed again.
Reviewed by Cursor Bugbot for commit 50e36fd. Configure here.
…68085) ## Description Ray Serve request routers never free finished multiplexed requests from `_pending_requests_by_model_id`, so each one keeps its `args`/`kwargs` alive. `_remove_pending_request_from_indices` only cleans `_pending_requests_by_id`. The model ID index relies on lazy cleanup that only `FIFOMixin` runs, and only when a later request for the same model ID is fulfilled. Before this fix: - `FIFOMixin` routers, including the default `PowerOfTwoChoicesRequestRouter`, kept the last request of every model ID, so memory grew with the number of distinct model IDs. - Routers without `FIFOMixin` (`ConsistentHashRouter`, `KVAwareRouter`, `PrefixCacheAffinityRouter`, custom routers) kept every multiplexed request, so memory grew with traffic. With Serve LLM's KV-aware or prefix-aware routing, this happens on every LoRA request. - Cancelling a request didn't clean the model ID index in any router. **Fix:** every fulfilled or cancelled request already calls `_remove_pending_request_from_indices` once its future is done. That method now pops done entries from the front of the request's model ID deque, and drops the key when the deque is empty. The cost stays amortized O(1), and routing behavior doesn't change. ## Related issues - Related to #60139, which introduced the lazy cleanup. - Related to #67095, which extends the same index to lists of model IDs and will need the same cleanup per ID. ## Additional information Standalone repro (script below). Run it on master vs. this branch. Entries left in `_pending_requests_by_model_id` after 200 finished requests over 50 model IDs, 1 MiB args each: | Router | Fulfilled (master → PR) | Cancelled (master → PR) | |---|---|---| | `PowerOfTwoChoicesRequestRouter` | 50 → 0 | 200 → 0 | | `ConsistentHashRouter` | 200 → 0 | 200 → 0 | <details> <summary><code>repro_router_leak.py</code></summary> ```python """Count finished multiplexed requests left in `_pending_requests_by_model_id`. Run with the Ray you want to check, e.g. on master vs. this PR's branch: python repro_router_leak.py """ import asyncio from ray.serve._private.common import ( DeploymentHandleSource, DeploymentID, RequestMetadata, ) from ray.serve._private.request_router import PendingRequest from ray.serve._private.request_router.pow_2_router import ( PowerOfTwoChoicesRequestRouter, ) from ray.serve._private.test_utils import FakeRunningReplica from ray.serve._private.utils import generate_request_id from ray.serve.experimental.consistent_hash_router import ConsistentHashRouter NUM_REQUESTS = 200 NUM_MODEL_IDS = 50 PAYLOAD_BYTES = 1024 * 1024 async def run(router_cls, cancel: bool): model_ids = [f"model-{i}" for i in range(NUM_MODEL_IDS)] router = router_cls( deployment_id=DeploymentID(name="repro"), handle_source=DeploymentHandleSource.REPLICA, self_actor_id="repro-actor", self_actor_handle=None, use_replica_queue_len_cache=False, ) replica = FakeRunningReplica("r1", model_ids=set(model_ids)) replica.set_queue_len_response(0) router.update_replicas([replica]) for i in range(NUM_REQUESTS): request = PendingRequest( args=[b"x" * PAYLOAD_BYTES], kwargs={}, metadata=RequestMetadata( request_id=generate_request_id(), internal_request_id=generate_request_id(), multiplexed_model_id=model_ids[i % NUM_MODEL_IDS], ), ) task = asyncio.create_task(router._choose_replica_for_request(request)) if cancel: await asyncio.sleep(0) task.cancel() await asyncio.gather(task, return_exceptions=True) for task in list(router._routing_tasks): task.cancel() await asyncio.gather(*router._routing_tasks, return_exceptions=True) entries = [pr for dq in router._pending_requests_by_model_id.values() for pr in dq] assert all(pr.future.done() for pr in entries) return len(entries), len(entries) * PAYLOAD_BYTES / 2**20 async def main(): print( f"{NUM_REQUESTS} finished requests over {NUM_MODEL_IDS} model IDs, " f"{PAYLOAD_BYTES // 2**20} MiB args each. Entries left in the index:" ) for router_cls in (PowerOfTwoChoicesRequestRouter, ConsistentHashRouter): for cancel in (False, True): entries, mib = await run(router_cls, cancel) ending = "cancelled" if cancel else "fulfilled" print(f" {router_cls.__name__:<32}{ending:<11}{entries:>4} ({mib:.0f} MiB)") if __name__ == "__main__": asyncio.run(main()) ``` </details> --------- Signed-off-by: GNITOAHC <[email protected]>


Background / Problem
Ray Serve's
RequestMetadata.multiplexed_model_id— and the correspondinghandle.options(multiplexed_model_id=...)API — only accepts a single modelID. Users who know several mutually-compatible model IDs (e.g. when doing LLM
routing across a small family of quantised checkpoints, or when the same request
can be satisfied by multiple fine-tuned variants) have no way to say "pick
whichever replica already has one of these models loaded". As a result they
either route to an arbitrarily-chosen replica and pay a cold-load penalty, or
load-balance naively and waste GPU memory.
Issue: #65348 — "[Serve] Support passing an ordered list of model_ids to controllers"
Solution
Add a new optional field
candidate_multiplexed_model_ids: Optional[List[str]]that flows through the whole Serve stack:
RequestMetadata.candidate_multiplexed_model_idsDynamicHandleOptionsBase.candidate_multiplexed_model_idsDeploymentHandle.options(...)/GenericDeploymentHandle.options(...)callable API
The routing changes live in
MultiplexMixin(shared by every defaultrouter, including
Pow2Routerand the experimentalRoundRobinRouter):_get_effective_multiplexed_model_ids()and_get_first_available_multiplexed_model_id(). The first merges the legacysingle
multiplexed_model_id(treated as highest priority, prepended)with the new ordered candidate list and de-duplicates while preserving
order. The second walks that list and returns the first model ID that
currently has a warm replica.
apply_multiplex_routing()and_get_pending_request_matching_multiplexed_model_id()now call thosehelpers, so both dispatch and pending-request coalescing naturally prefer
whichever replica already hosts any of the caller's candidates.
pow_2_routerandround_robin_routerrecognise the new field intheir early "has multiplexed" gates, and resolve the effective ID via
_get_first_available_multiplexed_model_idso per-model round-robincounters are keyed by whichever model actually routed.
Backward compatibility
Callers that still set only
multiplexed_model_idsee exactly the samebehaviour as before. When both fields are set, the single value is
treated as highest priority (prepended to the candidate list), so existing
code that mixes the two still gets deterministic results.
What is not in this PR (follow-up work)
serve_multiplexed_model_idfrom asingle header. Adding support for comma-separated / repeated headers is out
of scope here (can be done once this API lands).
follow-up work; the Python-side handle API is the primary user-facing path.
Testing
New tests added to
python/ray/serve/tests/unit/test_round_robin_router.py:test_candidate_model_ids_picks_first_warmtest_candidate_model_ids_fallback_when_no_warmtest_legacy_single_model_id_still_worksmultiplexed_model_idworks exactly as beforetest_single_id_prepended_to_candidate_listRun locally:
The rest of the existing
test_round_robin_router.py,test_pow_2_request_router.py,and Serve router unit tests should continue to pass without modification — the
change is additive and preserves the legacy single-ID path.