Repository navigation
[llm][kv][4+5/N] Pre-routing tokenization & KV cache aware routing - #64224
Conversation
There was a problem hiding this comment.
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.
108973f to
e2e4cfa
Compare
Signed-off-by: Jeffrey Wang <[email protected]>
…Actor Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
…GPU e2e) Signed-off-by: Jeffrey Wang <[email protected]>
e2e4cfa to
b021b1c
Compare
Signed-off-by: Jeffrey Wang <[email protected]>
7b7452c to
0672485
Compare
| if not isinstance(payload, dict): | ||
| return None | ||
|
|
||
| if "messages" in payload: |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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.
| # /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( |
There was a problem hiding this comment.
why use streaming? is that how servers api are written ? (they return generators? )
There was a problem hiding this comment.
yeah our LLMServer(LLMServerProtocol) implements tokenize to return generators:
ray/python/ray/llm/_internal/serve/core/protocol.py
Lines 174 to 178 in ff2cfc6
There was a problem hiding this comment.
Adjusting the return type would cause breaking changes and is out-of-scope of this PR.
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]>
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]>
0672485 to
e671dbc
Compare
…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 |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 6b5f0d6. Configure here.
| ) | ||
| return deployment.bind( | ||
| server=server, | ||
| pre_routing_tokenization=is_kv_aware_routing( |
There was a problem hiding this comment.
I would make this is_kv_aware_routing signature use the server directly instead of builder using private serve apis.
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
|
#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. |
…g tokenization) 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]>
There was a problem hiding this comment.
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).
❌ 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.
|
e13720c: returns a random candidate replica to route to for |
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]>
…ay-project#64224) Signed-off-by: Jeffrey Wang <[email protected]> Signed-off-by: 400Ping <[email protected]>
## 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]>
…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]>
…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]>


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
LLMRoutertokenizes each request via a replica's/tokenizeendpoint and forwards the token IDs intochoose_replica, so a KV-aware request router (introduced in a follow-up) can score on them.LLMServer/tokenizeendpoint (add_generation_prompt/add_special_tokensmirror the generation path so the IDs match the engine's prefill tokens). ReturnsNonefor bodies not routed on (truncated/empty, multi-prompt, nomessages/prompt); raisesTokenizeErroron rejection.core/ingress/router.py):pre_routing_tokenizationflag builds aTokenizer;routetokenizes before_pick_replica, forwardsrequest_token_idsviachoose_replica(intoPendingRequest.kwargs), and mapsTokenizeError→HTTPException.KVAwareRouter.choose_replicasis still a stub; reading the token IDs and forwarding toKVRouterActor.select_workerlands in a follow-up.test_tokenizer.py(Tokenizer unit + router wiring + builder gate) and a real-Tokenizerassertion intest_router.py.Related issues
Additional information