Repository navigation
[serve] Enable model multiplexing for RoundRobinRouter - #65679
Conversation
RoundRobinRouter
There was a problem hiding this comment.
Code Review
This pull request integrates model multiplexing support into the experimental RoundRobinRouter by mixing in MultiplexMixin and updating its routing logic to prefer replicas with the requested model loaded. It also updates the documentation and unit tests to reflect this new behavior. The feedback suggests restoring a removed architectural detail in the documentation regarding arbitrary replica startup to prevent synchronization, and adding a unit test to verify the fallback behavior when a requested multiplexed model is not loaded on any replica.
| ## Experimental: Use the round-robin request router | ||
|
|
||
| `RoundRobinRouter` cycles through replicas in round-robin fashion, starting at an arbitrary replica so routers spun up together don't synchronize on the same first replica. If the chosen replica is at capacity, the router falls back to the next replica in order and wraps around the candidate list. Each router instance keeps its own cursor, so with multiple routers (for example, one per Ray Serve proxy) the fan-out is round-robin per router and approximately uniform across replicas in aggregate. The router mixes in [`FIFOMixin`](../api/doc/ray.serve.request_router.FIFOMixin.rst) so queued requests are routed in arrival order. | ||
| `RoundRobinRouter` cycles through replicas in round-robin fashion. If the chosen replica is at capacity, the router falls back to the next replica in order and wraps around the candidate list. Each router instance keeps its own cursor, so with multiple routers (for example, one per Ray Serve proxy) the fan-out is round-robin per router and approximately uniform across replicas in aggregate. |
There was a problem hiding this comment.
The phrase explaining that the router starts at an arbitrary replica to prevent synchronization across multiple routers was removed in this revision. Since this is an important architectural detail for users to understand the behavior of RoundRobinRouter under load, it should be restored.
| `RoundRobinRouter` cycles through replicas in round-robin fashion. If the chosen replica is at capacity, the router falls back to the next replica in order and wraps around the candidate list. Each router instance keeps its own cursor, so with multiple routers (for example, one per Ray Serve proxy) the fan-out is round-robin per router and approximately uniform across replicas in aggregate. | |
| `RoundRobinRouter` cycles through replicas in round-robin fashion, starting at an arbitrary replica so routers spun up together don't synchronize on the same first replica. If the chosen replica is at capacity, the router falls back to the next replica in order and wraps around the candidate list. Each router instance keeps its own cursor, so with multiple routers (for example, one per Ray Serve proxy) the fan-out is round-robin per router and approximately uniform across replicas in aggregate. |
| assert _ranked_replica_unique_ids( | ||
| await router.choose_replicas(replicas, _make_request(model_id="model-a")) | ||
| ) == [["r2"], ["r0"], ["r1"]] | ||
| ) == [["r0"], ["r2"]] |
There was a problem hiding this comment.
It would be beneficial to add a test case verifying the fallback behavior when a requested multiplexed model is not loaded on any replica. This ensures that the fallback logic (routing to the replica with the fewest loaded models) is correctly integrated and behaves as expected.
| ) == [["r0"], ["r2"]] | |
| ) == [["r0"], ["r2"]] | |
| @pytest.mark.asyncio | |
| async def test_multiplex_fallback_to_fewest_models(router): | |
| replicas = [ | |
| FakeRunningReplica("r0", model_ids={"model-a"}), | |
| FakeRunningReplica("r1"), | |
| FakeRunningReplica("r2", model_ids={"model-a"}), | |
| ] | |
| for replica in replicas: | |
| replica.set_queue_len_response(0) | |
| router.update_replicas(replicas) | |
| router._round_robin_counter = 0 | |
| await asyncio.sleep(0) | |
| # "model-b" is not loaded on any replica, so it should fall back to the replica with the fewest loaded models ("r1"). | |
| assert _ranked_replica_unique_ids( | |
| await router.choose_replicas(replicas, _make_request(model_id="model-b")) | |
| ) == [["r1"]] |
|
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. |
Signed-off-by: Jeffrey Wang <[email protected]>
f2fe971 to
c35e1e5
Compare
| if not candidate_replicas: | ||
| return [] | ||
|
|
||
| index = self._round_robin_counter % len(candidate_replicas) |
There was a problem hiding this comment.
Hmm suppose there are four replicas, r0..r3. r0 and r1 have model A, r2 and r3 have model B.
Then, there are 6 requests against the models in the following order:
A
B
A
B
A
B
If the counter starts at 0 (for example), it seems like the index into A's candidates will always be 0 (choosing r0), and the index into B's candidates will always be 1 (choosing r3).
There was a problem hiding this comment.
Great find, thank you!
What changed in 1798e6c
- Per-model cursors prevent interleaved requests from pinning to one warm replica, i.e. round-robin among each multiplexed model separately.
- Fallback tiers use the shared cursor. Reason: Only matched multiplexed model needs per-model round-robin. Once multiplexed affinity is relaxed (no matching multiplexed model), fallback resumes normal router-wide balancing with the shared cursor.
- Replica updates prune stale model cursors.
Signed-off-by: Jeffrey Wang <[email protected]>
1798e6c to
0d49465
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 0d49465. Configure here.
| self._multiplexed_round_robin_counters[multiplexed_model_id] = counter + 1 | ||
| else: | ||
| index = self._round_robin_counter % len(candidate_replicas) | ||
| self._round_robin_counter += 1 |
There was a problem hiding this comment.
Shared cursor skews mixed-tier routing
Medium Severity
The shared fallback cursor is advanced with modulo of the current candidate list length, but fallback tiers and non-multiplexed requests see different-sized lists. Interleaving those paths can pin fallback traffic to one replica and skip others, so load no longer spreads once warm-model affinity is relaxed.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 0d49465. Configure here.
There was a problem hiding this comment.
This is intentional. We only need model-scoped round robin while preserving warm-model affinity. Once we fall back, using the existing shared cursor avoids adding state for every fallback subset to keep routing simple.
Fallback order
For a request for model M, fallback occurs when:
- No viable replica is known to host
M, or the known warm replicas were already tried. - Then it tries viable replicas with the fewest loaded models, i.e.
shared_counter % len(fewest_model_replicas). - After the multiplexing match timeout, if that tier was also tried, it tries all viable replicas, i.e.
shared_counter % len(all_replicas).
Tier 2 and 3 can't select outside the active tier, but different tier sizes can produce imperfect per-tier rotation under interleaved traffic.
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
0269119 to
be4658b
Compare
) ## Description - Enable model multiplexing for direct-ingress deployments over both HTTP and gRPC. - Remove the deployment-time and runtime rejections that prevented a multiplexed direct-ingress app from running. - At the direct ASGI entry point, recognize both `serve_multiplexed_model_id` and proxy-normalized `serve-multiplexed-model-id`, then store the value in `RequestMetadata.multiplexed_model_id`. - At the direct gRPC entry point, read `multiplexed_model_id` from gRPC invocation metadata and store it in `RequestMetadata.multiplexed_model_id`. ### Client usage ```python # HTTP response = httpx.get( direct_ingress_url, headers={"serve_multiplexed_model_id": "multiplex-model-id"}, ) ``` ```python # gRPC response = stub.Method2( request, metadata=( ("application", "default"), ("multiplexed_model_id", "multiplex-model-id"), ), ) ``` ## Related issues Stack: This PR -> #65679 -> #66170 -> #65680 -> `KVAwareRouter` LoRA support. ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Jeffrey Wang <[email protected]>
## Problem `choose_replica(_reserve=False)` previously called the routing policy once and failed if it returned no candidates. Multiplexed routing can temporarily return no candidates while model-location metadata propagates, even when eligible replicas exist. Through an ingress request router, this becomes a client-visible HTTP 503. ## Solution Reuse the existing selection retry loop with the same pending request so the policy can fall back to an eligible replica. Selection still skips capacity reservations and queue-length probes. Explicitly close the generator to clean up its backoff accounting on success and cancellation. Add a Serve-only HAProxy integration test emulating Serve LLM's separate ingress router: select a backend replica with a multiplexed handle and `_reserve=False`, then return its endpoint for HAProxy to forward the original request. Hold the model-location index empty and require two requests to succeed without client retries. ## Implication for LLM applications When a LoRA adapter first loads, there’s a delay before its location propagates through the controller to the router. An immediate subsequent request can fail because the router [remembers](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/serve/_private/request_router/request_router.py#L331) that an earlier request was sent to a replica to load the adapter, but it has not yet received metadata identifying a replica hosting it. In this state, the multiplexed policy returns no candidates on the new request’s first selection attempt. The old `_reserve=False` [path](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319) fails immediately instead of retrying, producing HTTP 503. With the retry mechanism, selection runs again using the same pending request, preserving its fallback state. The policy can then select an eligible replica even before the metadata arrives, so this propagation delay alone no longer causes a client-visible failure. ## Stack #65678 → #65679 → this PR → #65680 --------- Signed-off-by: Jeffrey Wang <[email protected]>
…ject#66170) ## Problem `choose_replica(_reserve=False)` previously called the routing policy once and failed if it returned no candidates. Multiplexed routing can temporarily return no candidates while model-location metadata propagates, even when eligible replicas exist. Through an ingress request router, this becomes a client-visible HTTP 503. ## Solution Reuse the existing selection retry loop with the same pending request so the policy can fall back to an eligible replica. Selection still skips capacity reservations and queue-length probes. Explicitly close the generator to clean up its backoff accounting on success and cancellation. Add a Serve-only HAProxy integration test emulating Serve LLM's separate ingress router: select a backend replica with a multiplexed handle and `_reserve=False`, then return its endpoint for HAProxy to forward the original request. Hold the model-location index empty and require two requests to succeed without client retries. ## Implication for LLM applications When a LoRA adapter first loads, there’s a delay before its location propagates through the controller to the router. An immediate subsequent request can fail because the router [remembers](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/serve/_private/request_router/request_router.py#L331) that an earlier request was sent to a replica to load the adapter, but it has not yet received metadata identifying a replica hosting it. In this state, the multiplexed policy returns no candidates on the new request’s first selection attempt. The old `_reserve=False` [path](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319) fails immediately instead of retrying, producing HTTP 503. With the retry mechanism, selection runs again using the same pending request, preserving its fallback state. The policy can then select an eligible replica even before the metadata arrives, so this propagation delay alone no longer causes a client-visible failure. ## Stack ray-project#65678 → ray-project#65679 → this PR → ray-project#65680 --------- Signed-off-by: Jeffrey Wang <[email protected]>
…gregated deployments (#65680) ## Description Enable LoRA multiplexing for direct streaming, including PD deployments. ### How LoRA used to work with non-direct-streaming? For normal, non-direct-streaming requests, `OpenAIIngress` calls `LLMServer.chat()` or `completions()`, which reach `_run_request()` and resolve the requested LoRA before submitting work to vLLM. ### How LoRA now works with direct streaming? Direct streaming instead has the ingress router select a replica, HAProxy proxy the request to that replica’s native vLLM ASGI application, and stream the response back to the client. That path bypasses `LLMServer.chat()`, `completions()`, and `_run_request()`, so LoRA was never resolved. In this PR, - [Fix] Initialize vLLM’s OpenAI serving state once and share it with the native ASGI app. When the LoRA resolver registers an adapter, the `/v1/completions`, `/v1/chat/completions`, and `/v1/models` handlers now see that same adapter registry. - [Test] Add a direct-streaming LoRA test that sends a cold adapter request through HAProxy, verifies the adapter appears in `/v1/models`, and exercises base-model and adapter requests through completions and chat-completions, with and without streaming. - [Config and docs] Require request-body forwarding for direct-streaming multi-LoRA, enable it in the direct-streaming release test job, and document the required settings. - [Existing] For a LoRA-enabled direct-streaming application, `LLMRouter` reads the requested `model` from the forwarded request body. If it belongs to the configured base model, it selects through a multiplexed Serve handle and HAProxy injects the resulting trusted adapter header for the selected replica. - [Existing] `LLMServer` adds a LoRA-resolving ASGI middleware before vLLM handles the request. - [Existing] Serve’s multiplexed loader downloads and caches the adapter lazily on the selected replica. For PD deployments, propagate the multiplexed model ID to the prefill handle and reject incompatible prefill/decode LoRA configuration. ## Related issues Stack: #65678 -> #65679 -> #66170 -> this PR -> `KVAwareRouter` LoRA support ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Jeffrey Wang <[email protected]>
…-project#65678) ## Description - Enable model multiplexing for direct-ingress deployments over both HTTP and gRPC. - Remove the deployment-time and runtime rejections that prevented a multiplexed direct-ingress app from running. - At the direct ASGI entry point, recognize both `serve_multiplexed_model_id` and proxy-normalized `serve-multiplexed-model-id`, then store the value in `RequestMetadata.multiplexed_model_id`. - At the direct gRPC entry point, read `multiplexed_model_id` from gRPC invocation metadata and store it in `RequestMetadata.multiplexed_model_id`. ### Client usage ```python # HTTP response = httpx.get( direct_ingress_url, headers={"serve_multiplexed_model_id": "multiplex-model-id"}, ) ``` ```python # gRPC response = stub.Method2( request, metadata=( ("application", "default"), ("multiplexed_model_id", "multiplex-model-id"), ), ) ``` ## Related issues Stack: This PR -> ray-project#65679 -> ray-project#66170 -> ray-project#65680 -> `KVAwareRouter` LoRA support. ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Jeffrey Wang <[email protected]>
…#65679) ## Description Enable `RoundRobinRouter` to use `MultiplexMixin` for requests with a multiplexed model ID. Replica selection proceeds as follows: 1. Serve provides the currently viable candidate replicas. 2. `apply_multiplex_routing()` first selects replicas already hosting the requested model. This warm tier uses a per-model round-robin cursor. 3. If no host is known, or those hosts were already attempted, it selects replicas with the fewest loaded models. This fallback uses the shared cursor. 4. After the matching timeout, it tries fewest-model replicas once more, then all replicas, using the shared cursor. 5. The router intersects the selected tier with viable candidates and applies round-robin ordering. Non-multiplexed requests retain existing shared-cursor round-robin behavior. ### Why `ConsistentHashRouter` is skipped? Model multiplexing and consistent hashing can place conflicting constraints on replica selection. Model multiplexing limits the candidates to replicas that have the requested model loaded, while consistent hashing maps a request to a specific replica. The problem is that the hashed replica may not be one of the replicas with that model loaded. Since it is unclear which constraint should take priority, we deliberately do not support model multiplexing with `ConsistentHashRouter`. ## Related issues Stack: ray-project#65678 -> this PR -> ray-project#66170 -> ray-project#65680 -> `KVAwareRouter` LoRA support. --------- Signed-off-by: Jeffrey Wang <[email protected]>
…ject#66170) ## Problem `choose_replica(_reserve=False)` previously called the routing policy once and failed if it returned no candidates. Multiplexed routing can temporarily return no candidates while model-location metadata propagates, even when eligible replicas exist. Through an ingress request router, this becomes a client-visible HTTP 503. ## Solution Reuse the existing selection retry loop with the same pending request so the policy can fall back to an eligible replica. Selection still skips capacity reservations and queue-length probes. Explicitly close the generator to clean up its backoff accounting on success and cancellation. Add a Serve-only HAProxy integration test emulating Serve LLM's separate ingress router: select a backend replica with a multiplexed handle and `_reserve=False`, then return its endpoint for HAProxy to forward the original request. Hold the model-location index empty and require two requests to succeed without client retries. ## Implication for LLM applications When a LoRA adapter first loads, there’s a delay before its location propagates through the controller to the router. An immediate subsequent request can fail because the router [remembers](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/serve/_private/request_router/request_router.py#L331) that an earlier request was sent to a replica to load the adapter, but it has not yet received metadata identifying a replica hosting it. In this state, the multiplexed policy returns no candidates on the new request’s first selection attempt. The old `_reserve=False` [path](https://github.com/ray-project/ray/blob/9634fa77aab2ece9759b380d20d315d4e27c912b/python/ray/llm/_internal/serve/core/ingress/router.py#L314-L319) fails immediately instead of retrying, producing HTTP 503. With the retry mechanism, selection runs again using the same pending request, preserving its fallback state. The policy can then select an eligible replica even before the metadata arrives, so this propagation delay alone no longer causes a client-visible failure. ## Stack ray-project#65678 → ray-project#65679 → this PR → ray-project#65680 --------- Signed-off-by: Jeffrey Wang <[email protected]>
…gregated deployments (ray-project#65680) ## Description Enable LoRA multiplexing for direct streaming, including PD deployments. ### How LoRA used to work with non-direct-streaming? For normal, non-direct-streaming requests, `OpenAIIngress` calls `LLMServer.chat()` or `completions()`, which reach `_run_request()` and resolve the requested LoRA before submitting work to vLLM. ### How LoRA now works with direct streaming? Direct streaming instead has the ingress router select a replica, HAProxy proxy the request to that replica’s native vLLM ASGI application, and stream the response back to the client. That path bypasses `LLMServer.chat()`, `completions()`, and `_run_request()`, so LoRA was never resolved. In this PR, - [Fix] Initialize vLLM’s OpenAI serving state once and share it with the native ASGI app. When the LoRA resolver registers an adapter, the `/v1/completions`, `/v1/chat/completions`, and `/v1/models` handlers now see that same adapter registry. - [Test] Add a direct-streaming LoRA test that sends a cold adapter request through HAProxy, verifies the adapter appears in `/v1/models`, and exercises base-model and adapter requests through completions and chat-completions, with and without streaming. - [Config and docs] Require request-body forwarding for direct-streaming multi-LoRA, enable it in the direct-streaming release test job, and document the required settings. - [Existing] For a LoRA-enabled direct-streaming application, `LLMRouter` reads the requested `model` from the forwarded request body. If it belongs to the configured base model, it selects through a multiplexed Serve handle and HAProxy injects the resulting trusted adapter header for the selected replica. - [Existing] `LLMServer` adds a LoRA-resolving ASGI middleware before vLLM handles the request. - [Existing] Serve’s multiplexed loader downloads and caches the adapter lazily on the selected replica. For PD deployments, propagate the multiplexed model ID to the prefill handle and reject incompatible prefill/decode LoRA configuration. ## Related issues Stack: ray-project#65678 -> ray-project#65679 -> ray-project#66170 -> this PR -> `KVAwareRouter` LoRA support ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. --------- Signed-off-by: Jeffrey Wang <[email protected]>
) ## Summary Wire a specialized `MultiplexedIngressRequestRouter` into HAProxy applications whose ingress uses `@serve.multiplexed`. The router passes the model ID and session metadata through the ingress deployment handle, selects a replica with the requested model loaded, and returns that replica to HAProxy. User-defined ingress routing remains explicit. Users attach their own ingress request router deployment that implements `/internal/route`. A custom `request_router_config` on an HAProxy ingress is rejected when no explicit ingress request router is attached because HAProxy would otherwise bypass it. An explicitly attached router always takes priority over automatic multiplexing wiring. The multiplexing router uses `max_ongoing_requests=1000` so its default deployment limit does not throttle ingress replica selection. ## Tests - 11 focused build and application-state tests passed - Pre-commit passed, including Ruff, Black, mypy, Pyrefly, and import-order checks ## Duplicate search No open duplicate found. #65678 and #65679 add request-router primitives but do not wire multiplexed ingress routing into HAProxy. ## AI assistance AI assistance was used. The changes require submitter review before merge. --------- Signed-off-by: Seiji Eicher <[email protected]>


Description
Enable
RoundRobinRouterto useMultiplexMixinfor requests with a multiplexed model ID. Replica selection proceeds as follows:apply_multiplex_routing()first selects replicas already hosting the requested model. This warm tier uses a per-model round-robin cursor.Non-multiplexed requests retain existing shared-cursor round-robin behavior.
Why
ConsistentHashRouteris skipped?Model multiplexing and consistent hashing can place conflicting constraints on replica selection. Model multiplexing limits the candidates to replicas that have the requested model loaded, while consistent hashing maps a request to a specific replica. The problem is that the hashed replica may not be one of the replicas with that model loaded.
Since it is unclear which constraint should take priority, we deliberately do not support model multiplexing with
ConsistentHashRouter.Related issues
Stack: #65678 -> this PR -> #66170 -> #65680 ->
KVAwareRouterLoRA support.