Skip to content

[llm][kv][12/N] Transmit tokens out-of-band and skip tokenization at the engine - #65095

Merged
kouroshHakha merged 35 commits into
masterfrom
kv-skip-tokenization-v1
Aug 2, 2026
Merged

kouroshHakha merged 35 commits into
masterfrom
kv-skip-tokenization-v1

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds skip-tokenization using a per-replica ZMQ token side channel plus a HAProxy token-key header.

API shape

from ray.serve.config import RequestRouterConfig
from ray.serve.llm import LLMConfig, ModelLoadingConfig
from ray.serve.llm.request_router import KVAwareRouter

llm_config = LLMConfig(
    model_loading_config=ModelLoadingConfig(
        model_id="Qwen/Qwen3-0.6B",
        model_source="Qwen/Qwen3-0.6B",
    ),
    deployment_config={
        "request_router_config": RequestRouterConfig(
            request_router_class=KVAwareRouter,
        ),
    },
    runtime_env={
        "env_vars": {
            # Retain unclaimed token payloads for 120 seconds.
            "RAY_SERVE_LLM_KV_TOKEN_STAGING_TTL_S": "120",
            # Store at most 16,384 pending request payloads per replica.
            "RAY_SERVE_LLM_KV_TOKEN_STAGING_MAX_ENTRIES": "16384",
            # Limit staged payloads to 2 GiB per replica.
            "RAY_SERVE_LLM_KV_TOKEN_STAGING_MAX_BYTES": str(2 * 1024**3),
        },
    },
)

Mechanics

  • LLMServer

  • LLMRouter

    • Tokenizes once during KV-aware selection.
    • Encodes token ids as little-endian uint32 bytes.
    • Non-blocking PUSHes [token_key, payload] to the selected LLMServer endpoint.
socket.send_multipart(..., flags=zmq.DONTWAIT, copy=False)
  • HAProxy / Lua
    • Strips user-supplied KV token headers.
    • Injects only x-kv-token-key into the backend request.
    • Avoids carrying large token payloads through proxy headers/body.

Semantics

Best effort, no ACK. If ZMQ is unavailable, queued out, or tokens arrive late, vLLM re-tokenizes normally.

Alternatives

  • HAProxy headers/body mutation: 200k tokens exceed practical header limits. Body splicing forces HAProxy/Lua to buffer, copy, rewrite Content-Length, and burn proxy CPU on every hot-path request.

  • Ray RPC/object paths: Per-request RPC adds scheduling, serialization, and possible large-object transport costs. Slow/restarting replicas can backpressure LLMRouter, while token forwarding only needs best-effort delivery.

image

Ablation study

kv_skip_tokenization_benchmark

FAQ

  • Why NumPy? Dense token vector, exact 4 bytes/token, fast C-level packing.
  • Why not HAProxy payload? 200k tokens would bloat proxy work; side channel keeps HAProxy lean.

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.

…returning calls

_svc.delete_worker's Rust binding returns a future, not a coroutine, so passing
it straight to create_task raised TypeError. _schedule now wraps whatever it is
given in a coroutine, keeping the call sites direct.

Signed-off-by: Jeffrey Wang <[email protected]>
Pure relocation of the tokenizer module (and its unit test) from
core/ingress to routing_policies/kv_aware, updating import paths. No
logic change; the vLLM-specific rewrite follows in the next commit.

Signed-off-by: Jeffrey Wang <[email protected]>
…s vLLM renderer

Replace the per-request /tokenize RPC with an in-process tokenizer that drives
the engine's own vLLM OnlineRenderer: render_chat for chat (the engine's own
entry point, covering the HF chat template, Harmony for gpt_oss, and Mistral)
and preprocess_completion for text prompts. Routing token ids are therefore
byte-identical to the replica's prefill tokens without contending with
inference on the replica processes. The vLLM renderer imports live at module
top (OnlineRenderer needs vLLM >= 0.25); the ingress router imports the
tokenizer lazily so non-KV paths never pull the renderer in.

Signed-off-by: Jeffrey Wang <[email protected]>
…to KVTokenTracker

The KVTokenTracker (formerly KVRouterActor) is built as a plain object by the
LLMRouter ingress replica and shared via a module global, so
KVAwareRouter.choose_replicas selects with a local call rather than an actor
RPC hop. Engine replicas book request lifecycle events through the LLMRouter
handle's on_lifecycle_events method instead of a named deployment actor, so the
DeploymentActorConfig attachment is dropped.

Selection-service tests (KV-event ingestion, scoring, lifecycle tracking) are
kept and adapted to the new hosting.

Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
…gress replicas are supported

Signed-off-by: Jeffrey Wang <[email protected]>
…eplicas to share token load

Signed-off-by: Jeffrey Wang <[email protected]>
# Conflicts:
#	python/ray/llm/_internal/serve/core/ingress/router.py
#	python/ray/llm/_internal/serve/routing_policies/kv_aware/kv_token_tracker.py
#	python/ray/llm/_internal/serve/routing_policies/kv_aware/vllm/token_tracking.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_kv_token_tracker.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_request_lifecycle_tracking.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_tokenizer.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_tokenizer_exactness.py
#	release/llm_tests/kv_router_test/test_request_lifecycle_tracking.py
#	release/llm_tests/kv_router_test/utils.py
#	release/ray_release/byod/byod_llm_kv_router_test.sh
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 marked this pull request as ready for review July 29, 2026 19:18
@jeffreywang88
jeffreywang88 requested review from a team as code owners July 29, 2026 19:18
@jeffreywang88 jeffreywang88 changed the title [DRAFT][llm][kv][12/N] Transmit tokens out-of-band and skip tokenization at the engine [llm][kv][12/N] Transmit tokens out-of-band and skip tokenization at the engine Jul 29, 2026

@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 a best-effort, replica-local ZMQ side channel to forward pre-routing prompt token IDs from the LLMRouter to the selected LLMServer replica, avoiding redundant tokenization. The changes include implementing a TokenSender, TokenStore, and TokenReceiver, integrating them into the router and vLLM engine, and updating HAProxy templates to securely forward the token key header. The review feedback highlights several critical robustness and performance improvements in the new token channel implementation: handling general exceptions in the sender to prevent router crashes, wrapping token decoding in try-except blocks to avoid 500 errors on corrupt payloads, handling ZMQ context termination in the receiver loop to prevent CPU thrashing, and simplifying the TokenStore by removing redundant asyncio locks and async overhead.

@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Jul 29, 2026
@jeffreywang88
jeffreywang88 force-pushed the kv-atomic-reserve-v1 branch from dbaeb54 to 55e4e24 Compare July 29, 2026 21:41
# Conflicts:
#	python/ray/llm/_internal/serve/routing_policies/kv_aware/kv_token_tracker.py
#	python/ray/llm/_internal/serve/routing_policies/kv_aware/vllm/token_tracking.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_kv_token_tracker.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_request_lifecycle_tracking.py
#	release/llm_tests/kv_router_test/test_request_lifecycle_tracking.py
#	release/llm_tests/kv_router_test/test_token_load_state.py
#	release/llm_tests/kv_router_test/utils.py
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner July 30, 2026 17:42

@kouroshHakha kouroshHakha 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.

nit but otherwise good.

@jeffreywang88
jeffreywang88 force-pushed the kv-atomic-reserve-v1 branch from 93e248d to a684bba Compare July 31, 2026 22:03
Base automatically changed from kv-atomic-reserve-v1 to master August 1, 2026 17:25
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Aug 1, 2026
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 force-pushed the kv-skip-tokenization-v1 branch from 1f36120 to af49ebc Compare August 1, 2026 22:37

@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.

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 af49ebc. Configure here.

@kouroshHakha
kouroshHakha merged commit adfc8fb into master Aug 2, 2026
3 checks passed
@kouroshHakha
kouroshHakha deleted the kv-skip-tokenization-v1 branch August 2, 2026 17:19
goutamvenkat-anyscale pushed a commit to goutamvenkat-anyscale/ray that referenced this pull request Aug 3, 2026
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…the engine (ray-project#65095)

Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: kv-benchmark <[email protected]>
Signed-off-by: 400Ping <[email protected]>
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
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]>
jeffreywang88 added a commit that referenced this pull request Nov 19, 2026
## Why are these changes needed?

When `KVAwareRouter` is enabled, `LLMRouter` tokenizes the prompt and
sends the token IDs to the chosen `LLMServer` replica, so the engine can
skip tokenization (#65095). This is best effort: if the tokens don't
arrive in time, the engine tokenizes the prompt itself. Nothing
currently measures how often the bypass works.

This PR adds the counter
`ray_serve_llm_tokenization_bypass_requests_total`. Serve adds the
`application`, `deployment` and `replica` tags, and an `outcome` tag
says what happened:

| `outcome` | Recorded by | Meaning |
|---|---|---|
| `success` | LLMServer | The engine used the forwarded tokens |
| `send_failed` | LLMRouter | The router couldn't send the tokens |
| `miss` | LLMServer | No staged tokens for the request (arrived late,
expired, or evicted) |
| `invalid` | LLMServer | The staged tokens couldn't be decoded, or the
list was empty |

### Implementation details
- Each request that tries the bypass is counted exactly once, by either
the router or the server that receives it. Every outcome except
`success` falls back to engine tokenization. Requests the router never
tries (multimodal requests, bodies it can't parse) aren't counted.
- Each replica exports every outcome at 0 when it starts. Without this,
a series only appears on its first event, and prometheus `rate()` drops
everything recorded before that series' first scrape. That undercounts
rare outcomes and new replicas. `Counter.inc` rejects 0, so this uses
`Counter._record(0, ...)`.

### Example query
Share of skipping tokenization attempts that didn't apply, over 1h:

```promql
sum by (application) (rate(ray_serve_llm_tokenization_bypass_requests_total{outcome!="success"}[1h]))
/
sum by (application) (rate(ray_serve_llm_tokenization_bypass_requests_total[1h]))
```

Filter by `application`, not `deployment`, because `send_failed` comes
from the router deployment and the other outcomes come from the server
deployment.


🤖 Generated with [Claude Code](https://claude.com/claude-code). I
reviewed every line of code.

Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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 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

3 participants