Skip to content

[serve][llm] Fix LoRA routing in PrefixCacheAffinityRouter - #66660

Merged
ArturNiederfahrenhorst merged 10 commits into
ray-project:masterfrom
ArturNiederfahrenhorst:serve-llm-prefix-router-one-candidate-set
Oct 24, 2026
Merged

ArturNiederfahrenhorst merged 10 commits into
ray-project:masterfrom
ArturNiederfahrenhorst:serve-llm-prefix-router-one-candidate-set

Conversation

@ArturNiederfahrenhorst

@ArturNiederfahrenhorst ArturNiederfahrenhorst commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Before this PR:

choose_replicas called apply_multiplex_routing or apply_locality_routing twice per attempt: once inside PowerOfTwoChoicesRequestRouter's choose_replicas for the fallback, then again for prefix matching. Both advance per-request state, so the second call returned the next tier's candidates. A multiplexed request, such as one for a LoRA adapter, was prefix-matched among the replicas with the fewest models loaded instead of the replicas that have the adapter.

That spread adapters across replicas by accident and hid two more problems. Serve loads a multiplexed model onto more replicas only when the replicas that have it reject requests, and with Serve LLM's default max_ongoing_requests they never do, so a popular adapter's traffic queues on the replicas that loaded it first. And the prefix tree keyed on prompt text only, so a LoRA request could match text cached under another adapter, which saves nothing because vLLM's prefix cache keys blocks by LoRA ID.

After this PR:

Compute the candidates once, so prefix matching and the power of two choices fallback use the same candidates. The fallback is only drawn when prefix matching finds no replica.
With availability zone locality on, the default for DeploymentHandles, the first attempt now prefix-matches among replicas in the caller's zone instead of all replicas.

When the replicas chosen for a multiplexed request have more than multiplex_spill_threshold (default 64) more ongoing requests than the least busy candidate or replica with the fewest models loaded, the request is routed among those by load, so a busy adapter spreads to more replicas. A multiplexed request's text goes into the prefix tree under its model ID, and only text matched under the model counts toward the match rate. On a low match rate, the fallback picks the smallest tenant among this attempt's candidates instead of among all replicas. Since #66671 moved prefix matching into the tree's single prefix_match_or_smallest_tenants call, that call takes the model ID prefix as key_prefix: it's matched before the text and left out of the match rate.

Also removes the router's unused Sphinx tags: the docs stopped including this file in #57787.

Benchmark

This PR adds a weekly release test, llm_serve_prefix_router_lora_benchmark (release/llm_tests/serve/prefix_router_lora_benchmark.py), that sends LoRA traffic through the router to fake Ray Serve LLM replicas on Serve's real @serve.multiplexed, on a CPU node. 4 replicas, 32 adapters, at most 16 loaded per replica, 2 s to download an adapter (a replica loads one at a time), vLLM-style max_loras=4 and a prefix cache keyed by adapter, replicas never reject. Open-loop Poisson traffic at 40 req/s for 180 s, identical for both routers; cold is the first 60 s, last-60s the final 60 s. Workloads: uniform, zipf (the top adapter gets 28% of traffic) and shared-prompt (all adapters share 2 system prompts). Below is the release test on its setup (Anyscale m5.2xlarge, anyscale/ray-llm:nightly-py312-cu130 at master 0fe2388b9d) with master's router and with this PR's (its prefix_aware_router.py and prefix_tree.py copied over the installed ones), 3 seeds; placement metrics (after the cold start) are means, latencies medians. Master → this PR:

workload adapter ready evictions KV hit busiest replica cold p99 s last-60s p50 s last-60s p99 s
uniform 67% → 100% 1422 → 0 79% → 100% 33% → 30% 57.7 → 60.9 3.9 → 1.9 7.2 → 5.6
zipf 87% → 100% 554 → 0 90% → 100% 51% → 29% 46.9 → 43.1 1.0 → 1.1 4.9 → 5.0
shared-prompt 49% → 100% 1875 → 0 56% → 100% 26% → 30% 66.3 → 60.2 5.0 → 1.9 8.6 → 5.2

The cold start is 6% slower on uniform traffic: the spill downloads adapters onto more replicas while queues build.

multiplex_spill_threshold (the release test's --multiplex-spill-threshold), as uniform / zipf / shared-prompt:

threshold evictions busiest replica replicas per adapter cold p99 s last-60s p99 s
16 66 / 5 / 77 28% / 28% / 28% 2.77 / 2.08 / 2.92 57.4 / 39.2 / 57.1 5.2 / 5.2 / 5.4
32 8 / 0 / 18 30% / 32% / 29% 2.18 / 1.84 / 2.35 58.1 / 39.7 / 57.8 5.6 / 5.2 / 5.5
64 (default) 0 / 0 / 0 30% / 29% / 30% 1.97 / 1.98 / 1.96 60.9 / 43.1 / 60.2 5.6 / 5.0 / 5.2
128 0 / 0 / 0 30% / 29% / 30% 1.98 / 1.86 / 2.00 64.6 / 44.4 / 62.7 5.4 / 4.7 / 5.7
inf (no spill) 0 / 0 / 0 31% / 70% / 31% 1.77 / 1.16 / 1.79 98.6 / 138.1 / 93.5 5.8 / 42.4 / 6.0

64 is the lowest tested threshold that evicts no adapters in any workload. Lower thresholds keep spilling after the cold start, which costs evictions for a 2–4 s faster cold start. Without the spill, the hot zipf adapter stays on one replica: the busiest replica takes 70% of requests and the last-60s p99 is 42.4 s (12.2–67.3 s across seeds).

Both tables were measured before #66671 landed (this PR at 2eadba05dc, image at master 0fe2388b9d) and haven't been rerun on the merged branch.

Tests

python -m pytest --noconftest --import-mode=importlib -q \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py
81 passed

Run locally on macOS (--noconftest because the llm conftest.py imports vLLM). New tests that fail on master: TestPrefixAwareLogic::test_multiplexed_request_matches_replicas_with_model, TestMultiplexedRouting::test_prefix_match_is_per_model, TestMultiplexedRouting::test_spills_from_busy_replica (2 cases) and TestPrefixTreePrefixMatchOrSmallestTenants::test_key_prefix_does_not_count_toward_match_rate. New tests that pass on master too: TestPrefixAwareLogic::test_image_only_request_uses_smallest_tenant and TestMultiplexedRouting::test_low_match_rate_uses_smallest_candidate (#66671 fixed these as well), TestMultiplexedRouting::test_spill_reaches_replica_without_cached_queue_len (with Serve's queue length cache on) and TestMultiplexedRouting::test_prefix_match_within_model, which fails if the router leaves the model ID out of the tree lookup or insert. The prefix-aware routing guide documents multiplex_spill_threshold.

The release test passes on its setup with both routers and every threshold above, in about 10 of its 60 minutes, and ray_release validates the new release_tests.yaml entry.

No existing issue or PR covers this (searched open PRs for PrefixCacheAffinityRouter, prefix_aware_router, multiplex, get_smallest_tenants). #66671, which overlapped, landed first and is merged into this branch (d2dcaaf00c). Written with AI assistance (Claude Code).

🤖 Generated with Claude Code

ArturNiederfahrenhorst and others added 2 commits October 1, 2026 14:24
…AffinityRouter

choose_replicas called apply_multiplex_routing or apply_locality_routing
twice per attempt: once inside PowerOfTwoChoicesRequestRouter's
choose_replicas for the fallback, then again for prefix matching. Both
advance per-request state, so the second call returned the next tier's
candidates. A multiplexed request, such as one for a LoRA adapter, was
prefix-matched among the replicas with the fewest models loaded instead of
the replicas that have the adapter.

Compute the candidates once, so prefix matching and the power of two
choices fallback use the same candidates. The fallback is only drawn when
prefix matching finds no replica.

Behavior change: with availability zone locality on, the default for
DeploymentHandles, the first attempt now prefix-matches among replicas in
the caller's zone instead of all replicas.

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…AffinityRouter

With Serve LLM's default unbounded max_ongoing_requests, replicas never
reject requests, so Serve never loads a multiplexed model, such as a LoRA
adapter, onto more replicas, however busy the replicas that have it get.

- When the replicas chosen for a multiplexed request have more than
  multiplex_spill_threshold (default 64) more requests than the least busy
  candidate or replica with the fewest models loaded, route the request to
  the least busy of those instead, which loads the model there.
- Match a multiplexed request's prefix only against text cached for the
  same model, since vLLM's prefix cache doesn't share KV across adapters.
- On a low match rate, pick the smallest tenant among this attempt's
  candidates instead of among all replicas.

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ArturNiederfahrenhorst ArturNiederfahrenhorst changed the title [serve][llm] Use one candidate set per routing attempt in PrefixCacheAffinityRouter [serve][llm] Fix LoRA routing in PrefixCacheAffinityRouter Oct 2, 2026
@ArturNiederfahrenhorst

ArturNiederfahrenhorst commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor Author

https://gist.github.com/ArturNiederfahrenhorst/44be7bef6710576e4c598973a5654779

It is 100% Claude generated and I'm attaching it only for completeness.
I did not check it myself but am trusting Claude with the benchmark results.

The prefix-aware routing docs stopped including snippets of this file when
they were reorganized in ray-project#57787, so no literalinclude uses these tags.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@ArturNiederfahrenhorst
ArturNiederfahrenhorst marked this pull request as ready for review October 5, 2026 13:56
@ArturNiederfahrenhorst
ArturNiederfahrenhorst requested review from a team as code owners October 5, 2026 13:56

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for multiplexed models (such as LoRA adapters) in the prefix-aware router. It ensures that prefix matching is scoped per model ID to prevent cross-adapter KV cache sharing issues, and adds a multiplex_spill_threshold configuration to route requests to less busy replicas when the chosen replicas are overloaded. The feedback highlights two critical safety issues in the new code: a potential ZeroDivisionError when calculating the prefix match rate for empty inputs, and a potential AttributeError when accessing metadata on an optional pending_request without a None check.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

ArturNiederfahrenhorst and others added 3 commits October 5, 2026 08:35
…refix_aware_router.py

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
When the spill triggered, the router offered the busy replicas along with the
idle ones. Replica selection prefers replicas with a cached queue length, so if
the idle replicas had none, the request stayed on a busy replica. Offer only the
replicas within multiplex_spill_threshold of the least busy one.

The test fixture can now enable the queue length cache, which Serve enables for
handles by default.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Wrap the empty-prompt guard to the line length and say when the text is empty.
Add a test with an image-only request, which divided by zero before the guard.
Also check that the request isn't None before reading its multiplexed model ID.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue docs An issue or change related to documentation llm labels Oct 5, 2026
…outer

Send LoRA traffic through PrefixCacheAffinityRouter to fake LLM replicas on a
CPU node, for uniform, skewed (zipf) and shared-prompt adapter traffic, and
report where the router places adapters and requests: the share of requests
whose adapter is already loaded, prefix cache hits, adapter evictions, the
busiest replica's share, latency and routing time. Runs weekly, and fails if a
request never completes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@ArturNiederfahrenhorst
ArturNiederfahrenhorst requested a review from a team as a code owner October 6, 2026 13:04

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit e611bdf. Configure here.

Requests that failed while traffic was still being sent left the in-flight set
without anyone reading their result, so the test only reported them as
unfinished, without the error. Keep every request and check them all.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
ArturNiederfahrenhorst added a commit to ArturNiederfahrenhorst/ray that referenced this pull request Oct 8, 2026
…mallest_tenants

On a weak match, prefix_match_or_smallest_tenants returned the smallest tenants
in the whole tree, so the router could pick a replica outside the request's
candidates, e.g. one without the requested LoRA adapter. Give get_smallest_tenants
an available_tenants argument and pass it through. The helper and its test are
copied unchanged from ray-project#66660, so the two PRs make the same change there.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
):
input_text = self._extract_text_from_request(pending_request)
if input_text is not None:
# Start Sphinx tag: __begin_load_balance_component__

@ArturNiederfahrenhorst ArturNiederfahrenhorst Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that this tag is not used anywhere anymore so instead of moving it, we can just get rid of it.

multiplexed request goes under its model ID.
"""
model_id = pending_request.metadata.multiplexed_model_id
return f"\0{model_id}\0" if model_id else ""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This means that we route traffic for LoRA adapters to where the model AND the adapter is loaded and spill to where there is little load. A more refined version would be one where we spill to where the model and adapter and low load are but I'm not even sure that would be generally better.

@ArturNiederfahrenhorst ArturNiederfahrenhorst added the go add ONLY when ready to merge, run all tests label Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made this a CPU test even though this is a release test so it is quick and easy to run.
The component under test is the router here so it's ok to fake vLLM.
We fake prefix hits and the prefill lag and evict adapters and I'd argue that that is a good enough target to track since vLLM's behavior will also vary across configurations.

Let me know if you disagree @jeffreywang88

pending_request=pending_request,
)
if pending_request is None or not fallback_replicas:
return fallback_replicas

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this PR, we stop using PowerOfTwoChoicesRequestRouter.choose_replicas in this router entirely.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you call PowerOfTwoChoicesRequestRouter.choose_replicas, it ends up calling apply_multiplex_routing and which sets tried_first_multiplexed_models = True on the pending requests. A few lines below, we then also call apply_multiplex_routing. At that time, the "fried first multiplexed models" flag is already set so apply_multiplex_routing just returns the _get_replica_ids_with_fewest_multiplexed_models(). So that's why, in any case, we just load the adapters on all the replicas and do load balance somehow even though the code does not work as intended I think.

@jeffreywang88 jeffreywang88 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this work with direct streaming?

pending_request=pending_request,
)
if pending_request is None or not fallback_replicas:
return fallback_replicas

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

@ArturNiederfahrenhorst

Copy link
Copy Markdown
Contributor Author
Screenshot 2026-10-15 at 6 35 18 PM

why?

I think this is the same comment that I answer here but it's somehow displayed twice in the github interface. Please let me know if these are two separate comments and there is some question unanswered.

@ArturNiederfahrenhorst
ArturNiederfahrenhorst enabled auto-merge (squash) October 22, 2026 21:25
Resolves the conflicts with ray-project#66671, which moved the router's tree lookup
into one non-blocking prefix_match_or_smallest_tenants call:
- The router passes the request's key prefix to that call. The tree
  counts only text matched after the key prefix toward the match rate,
  which this PR did in the router before.
- The prefix tree insert stays fire-and-forget and keeps the key prefix.
- Drops the Sphinx tags ray-project#66671 moved: no docs include them since ray-project#57787.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Covers the router passing the key prefix to the tree lookup, and the
tree counting only text matched after it toward the match rate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@github-actions
github-actions Bot disabled auto-merge October 24, 2026 14:29
@ArturNiederfahrenhorst
ArturNiederfahrenhorst enabled auto-merge (squash) October 24, 2026 14:32
@ArturNiederfahrenhorst
ArturNiederfahrenhorst merged commit 8d53e59 into ray-project:master Oct 24, 2026
7 checks passed
PCTEJA added a commit to PCTEJA/ray that referenced this pull request Nov 28, 2026
…ree key

Fixes ray-project#68592.

vLLM does not share KV cache blocks across cache salts, but the router
built its prefix-tree key from the prompt/messages text only, so a request
with salt B counted as a prefix hit on the replica that served the same
text under salt A. Include the request's cache salt in the key prefix,
mirroring how multiplexed (LoRA) requests are already keyed by model ID
(ray-project#66660), so requests only match prefixes cached under the same salt
(and model).

Adds regression tests: same-salt prefix match, per-salt isolation, and
model+salt combined isolation.

Signed-off-by: TEJA P C <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs An issue or change related to documentation go add ONLY when ready to merge, run all tests llm serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants