Skip to content

[llm][kv][4+5/N] Pre-routing tokenization & KV cache aware routing - #64224

Merged
kouroshHakha merged 22 commits into
masterfrom
pre-routing-tokenization
Jun 30, 2026
Merged

kouroshHakha merged 22 commits into
masterfrom
pre-routing-tokenization

Conversation

@jeffreywang88

Copy link
Copy Markdown
Contributor

Description

KV-aware routing scores replicas by prompt-token KV-cache overlap, so the router needs the request's token IDs before it picks a replica.

This PR adds pre-routing tokenization: the ingress LLMRouter tokenizes each request via a replica's /tokenize endpoint and forwards the token IDs into choose_replica, so a KV-aware request router (introduced in a follow-up) can score on them.

  • Tokenizer: tokenizes the body via the LLMServer /tokenize endpoint (add_generation_prompt/add_special_tokens mirror the generation path so the IDs match the engine's prefill tokens). Returns None for bodies not routed on (truncated/empty, multi-prompt, no messages/prompt); raises TokenizeError on rejection.
  • Router wiring (core/ingress/router.py): pre_routing_tokenization flag builds a Tokenizer; route tokenizes before _pick_replica, forwards request_token_ids via choose_replica (into PendingRequest.kwargs), and maps TokenizeError → HTTPException.
  • Not yet consumed: KVAwareRouter.choose_replicas is still a stub; reading the token IDs and forwarding to KVRouterActor.select_worker lands in a follow-up.
  • Tests: test_tokenizer.py (Tokenizer unit + router wiring + builder gate) and a real-Tokenizer assertion in test_router.py.
image

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@jeffreywang88
jeffreywang88 requested a review from a team as a code owner June 18, 2026 23:37

@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 pre-routing tokenization for KV-aware routing in Ray LLM. It adds a Tokenizer class to tokenize incoming chat or completion requests via the replica's /tokenize endpoint, passing the resulting token IDs to the replica selection mechanism. This pre-routing tokenization is conditionally enabled only when a KVAwareRouter is configured. The review feedback focuses on improving robustness: handling non-integer error codes and missing attributes in tokenization responses, catching unexpected exceptions during tokenization to gracefully fall back to token-less routing, and defensively verifying that the retrieved request router is a class before calling issubclass.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue llm labels Jun 19, 2026
@jeffreywang88
jeffreywang88 force-pushed the kv-aware-routing-event-plane branch from 108973f to e2e4cfa Compare June 22, 2026 19:00
@jeffreywang88
jeffreywang88 force-pushed the kv-aware-routing-event-plane branch from e2e4cfa to b021b1c Compare June 22, 2026 19:43
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 force-pushed the pre-routing-tokenization branch 2 times, most recently from 7b7452c to 0672485 Compare June 22, 2026 22:56
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Jun 22, 2026
if not isinstance(payload, dict):
return None

if "messages" in payload:

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.

this is a bit brittle. For example, how do we support new api formats e.g. anthropic sdk, etc. Is there a better way. (worth pondering about)?

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.

Fair enough, but I'd rather cross that bridge when we get there. Probably need to introduce some schema that the payload is validated against and dispatch off that request type.

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.

Noted this gap in #64389.

# /tokenize yields a single response; drain the stream fully so the
# handle response is cleaned up.
resp = None
async for chunk in self._handle.options(stream=True).tokenize.remote(

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 use streaming? is that how servers api are written ? (they return generators? )

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.

yeah our LLMServer(LLMServerProtocol) implements tokenize to return generators:

async def tokenize(
self,
request: "TokenizeRequest",
raw_request_info: Optional[RawRequestInfo] = None,
) -> AsyncGenerator[Union["TokenizeResponse", "ErrorResponse"], None]:

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.

Adjusting the return type would cause breaking changes and is out-of-scope of this PR.

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.

Noted this gap in #64389.

@jeffreywang88
jeffreywang88 force-pushed the pre-routing-tokenization branch from 0672485 to e671dbc Compare June 26, 2026 08:18
Base automatically changed from kv-aware-routing-event-plane to master June 27, 2026 19:48
…ation

# Conflicts:
#	release/llm_tests/kv_router_test/test_kv_event_ingestion.py
#	release/llm_tests/kv_router_test/test_kv_events.py
if not isinstance(payload["prompt"], str):
# TODO (jeffreywang): Multi-prompt (list) tokenization is unsupported;
# fall back to token-less routing.
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Empty messages skips prompt tokenize

Medium Severity

_build_tokenize_request chooses the chat tokenize path whenever the messages key exists, but _parse_routing_payload treats empty or null messages as no routing signal and still routes on a truthy prompt. Those bodies reach the tokenizer with a valid routing payload yet return None or chat tokens that do not match the completion prefill.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6b5f0d6. Configure here.

)
return deployment.bind(
server=server,
pre_routing_tokenization=is_kv_aware_routing(

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.

I would make this is_kv_aware_routing signature use the server directly instead of builder using private serve apis.

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.

Sounds good, refactored here: e766f0e.

@jeffreywang88

jeffreywang88 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor Author

#64108 was merged into this PR, so now this PR includes both [4/N] pre-routing tokenization and [5/N] request routing with KV awareness.

Kicking off release tests: https://buildkite.com/ray-project/release/builds/98697/canvas?sid=019f14d0-cf5d-45a9-a8e0-cece5eb95c61&open=false.

Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

@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 using default effort and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ 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 e13720c. Configure here.

@jeffreywang88 jeffreywang88 changed the title [llm][kv][4/N] Pre-routing tokenization [llm][kv][4+5/N] Pre-routing tokenization & KV cache aware routing Jun 30, 2026
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

e13720c: returns a random candidate replica to route to for .tokenize.remote(). This is fine even though the selected replica is unresponsive because serve's probe-deadline + backoff + re-randomization self-heals.

@kouroshHakha
kouroshHakha merged commit 41801cb into master Jun 30, 2026
3 checks passed
@kouroshHakha
kouroshHakha deleted the pre-routing-tokenization branch June 30, 2026 04:59
jeffreywang88 added a commit that referenced this pull request Jun 30, 2026
Brings the request-lifecycle-tracking branch up to date with master, which
landed the pre-routing tokenization & KV cache aware routing work (#64224)
that this branch had developed in separate commits.

Conflict resolutions (adopt master's finalized shared infra; keep the
branch's unique request-lifecycle / token-tracking additions on top):

- core/ingress/builder.py, vllm_engine.py, test_request_lifecycle_tracking.py:
  converge on master's canonical is_kv_aware(llm_config) API, dropping the
  branch's equivalent is_kv_aware_routing(request_router_config) helper.
- kv_aware/kv_aware_router.py: take master's choose_replicas behavior
  (route token-less requests to a random replica) over the branch's earlier
  strict ValueError design, and its is_kv_aware() definition.
- tests/.../kv/test_kv_aware_router.py: take master's random-routing tests
  to match the adopted behavior.
- kv_aware/kv_aware_actor.py: keep the branch's on_lifecycle_events dispatch
  and the lifecycle hook signatures the token-tracking forwarder calls.
- release/.../test_kv_event_ingestion.py: take master's no-arg
  LocalKVRouterActor.remote() (block_size now flows via kv_event_metadata).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
eicherseiji added a commit that referenced this pull request Sep 22, 2026
## Why

The current 256 KiB cap truncates the router copy of large LLM requests,
causing body-aware routing to lose information. Several recent routing
changes depend on this body:

- [#64224](#64224),
[#64328](#64328), and
[#65095](#65095) use it for
KV-aware routing.
- [#65680](#65680) uses it for
LoRA model selection.
- [#66258](#66258) and
[#66315](#66315) use it for
deployment-aware, multi-model direct streaming.
- [#63183](#63183) introduced the
body-forwarding gate shared by these paths.

This PR raises the default buffer to 8 MiB and lowers the default
`maxconn` to 4,096. The sizing and behavior were verified with a real
HAProxy 2.8.25 test and against the bundled HAProxy source code. Both
settings retain their existing environment-variable overrides.

| Consideration | Result |
|---|---|
| Request size | A one-million-token English request is commonly
estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves
2.28 MiB (~40%) headroom. |
| Latency | Requests below 256 KiB do not wait longer. Requests from 256
KiB to 8 MiB now wait for the complete body before routing. |
| Memory | Buffers are allocated dynamically. A live stream can use
roughly 16 MiB across request and response buffers. Lowering `maxconn`
from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB
to 64 GiB. |

## Changes

- Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB
to 8 MiB.
- Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096.
- Test a 6,000,014-byte, million-token-sized request end to end.
- Derive rendered-config assertions from their constants so environment
overrides remain testable.
- Update the KV-aware routing guide.

## Tests

- Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly
passed.
- HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using
bundled HAProxy 2.8.25.

This does not duplicate the related PRs: they introduce or consume
body-aware routing, while this PR increases the shared buffer default
and tests a million-token-sized body.

AI assistance was used to implement and validate this change; the
submitter reviewed every changed line.

---------

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
…t#66360)

## Why

The current 256 KiB cap truncates the router copy of large LLM requests,
causing body-aware routing to lose information. Several recent routing
changes depend on this body:

- [ray-project#64224](ray-project#64224),
[ray-project#64328](ray-project#64328), and
[ray-project#65095](ray-project#65095) use it for
KV-aware routing.
- [ray-project#65680](ray-project#65680) uses it for
LoRA model selection.
- [ray-project#66258](ray-project#66258) and
[ray-project#66315](ray-project#66315) use it for
deployment-aware, multi-model direct streaming.
- [ray-project#63183](ray-project#63183) introduced the
body-forwarding gate shared by these paths.

This PR raises the default buffer to 8 MiB and lowers the default
`maxconn` to 4,096. The sizing and behavior were verified with a real
HAProxy 2.8.25 test and against the bundled HAProxy source code. Both
settings retain their existing environment-variable overrides.

| Consideration | Result |
|---|---|
| Request size | A one-million-token English request is commonly
estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves
2.28 MiB (~40%) headroom. |
| Latency | Requests below 256 KiB do not wait longer. Requests from 256
KiB to 8 MiB now wait for the complete body before routing. |
| Memory | Buffers are allocated dynamically. A live stream can use
roughly 16 MiB across request and response buffers. Lowering `maxconn`
from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB
to 64 GiB. |

## Changes

- Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB
to 8 MiB.
- Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096.
- Test a 6,000,014-byte, million-token-sized request end to end.
- Derive rendered-config assertions from their constants so environment
overrides remain testable.
- Update the KV-aware routing guide.

## Tests

- Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly
passed.
- HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using
bundled HAProxy 2.8.25.

This does not duplicate the related PRs: they introduce or consume
body-aware routing, while this PR increases the shared buffer default
and tests a million-token-sized body.

AI assistance was used to implement and validate this change; the
submitter reviewed every changed line.

---------

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…t#66360)

## Why

The current 256 KiB cap truncates the router copy of large LLM requests,
causing body-aware routing to lose information. Several recent routing
changes depend on this body:

- [ray-project#64224](ray-project#64224),
[ray-project#64328](ray-project#64328), and
[ray-project#65095](ray-project#65095) use it for
KV-aware routing.
- [ray-project#65680](ray-project#65680) uses it for
LoRA model selection.
- [ray-project#66258](ray-project#66258) and
[ray-project#66315](ray-project#66315) use it for
deployment-aware, multi-model direct streaming.
- [ray-project#63183](ray-project#63183) introduced the
body-forwarding gate shared by these paths.

This PR raises the default buffer to 8 MiB and lowers the default
`maxconn` to 4,096. The sizing and behavior were verified with a real
HAProxy 2.8.25 test and against the bundled HAProxy source code. Both
settings retain their existing environment-variable overrides.

| Consideration | Result |
|---|---|
| Request size | A one-million-token English request is commonly
estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves
2.28 MiB (~40%) headroom. |
| Latency | Requests below 256 KiB do not wait longer. Requests from 256
KiB to 8 MiB now wait for the complete body before routing. |
| Memory | Buffers are allocated dynamically. A live stream can use
roughly 16 MiB across request and response buffers. Lowering `maxconn`
from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB
to 64 GiB. |

## Changes

- Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB
to 8 MiB.
- Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096.
- Test a 6,000,014-byte, million-token-sized request end to end.
- Derive rendered-config assertions from their constants so environment
overrides remain testable.
- Update the KV-aware routing guide.

## Tests

- Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly
passed.
- HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using
bundled HAProxy 2.8.25.

This does not duplicate the related PRs: they introduce or consume
body-aware routing, while this PR increases the shared buffer default
and tests a million-token-sized body.

AI assistance was used to implement and validate this change; the
submitter reviewed every changed line.

---------

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

Labels

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.

Ray fails to serialize self-reference objects

2 participants