Skip to content

[serve][llm] Reduce KV router event loop CPU overhead - #67981

Merged
jeffreywang88 merged 1 commit into
masterfrom
serve-llm-kv-router-event-loop-cpu
Nov 19, 2026
Merged

jeffreywang88 merged 1 commit into
masterfrom
serve-llm-kv-router-event-loop-cpu

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

Reduce per-request CPU overhead in LLMRouter:

  • Parse JSON with msgspec instead of json.loads. msgspec is faster because it parses UTF-8 bytes directly. json.loads(body) first decodes the entire byte buffer into a python string, adding an allocation and processing pass. msgspec reads the buffer directly, while CPython performs that conversion first.
  • Encode token IDs with array.array("I") instead of constructing a numpy array. array.array("I", ids) allocates a flat buffer and converts the integers in one C loop. np.asarray(ids, dtype="<u4") first discovers the input’s shape, then allocates and fills the array through its general conversion machinery.
  • Return vLLM’s token list directly, avoiding concatenation and copying for single-prompt requests (multi-prompt requests aren't supported anyways).

These changes optimize existing behavior, so they reuse existing correctness coverage:

  • test_tokenizer_exactness.py compares chat/completion tokens against transformers and exercises Anthropic token staging and reuse.
  • test_token_channel.py verifies token IDs survive encoding, ZMQ delivery, decoding, and forwarding to the selected replica.
  • Existing router tests cover request-body parsing and routing.

Benchmark

1. Mocker engine

Setup follows #67917. This PR's optimization results in 7-10 ms TTFT reduction.

Client TTFT p50 / p90 (ms) Client → engine arrival p50 / p90 (ms)
N=1 (this PR) 67.0 / 289 13.8 / 34.0
N=1 (pre-PR) 74.3 / 294 19.3 / 52
N=16 (this PR) 76.7 / 441.3 15.1 / 38.4
N=16 (pre-PR) 86.3 / 448.2 20.9 / 59.2

Client TTFT: from the AgentX client sending the request to receiving the first token.

2. Realistic LLM deployments: AgentX + 8 replicas across 2 nodes with DSV4.1-Flash on B200s

Concurrency per replica Configuration Throughput p90 TTFT p90 TPOT
64 Master 1318.1 708 8.22
+ Replica mesh #67917 1319.7 691 8.23
+ Tokenization cache #67940 1329.2 608 8.15
+ KV-router CPU #67981 1334.8 570 8.11
128 Master 2009.9 3296 15.70
+ Replica mesh #67917 2008.1 3106 15.69
+ Tokenization cache #67940 2055.0 2313 15.56
+ KV-router CPU #67981 2069.3 2109 15.50

KV-router CPU overhead reduction alone results in 9% p90 TTFT reduction on top of tokenization cache.

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 November 9, 2026 18:57

@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 optimizes performance and dependencies by replacing json with msgspec for request parsing, and replacing numpy with the standard library's array module for encoding prompt token IDs. It also simplifies the tokenizer to support only a single prompt. Feedback on these changes suggests handling potential ValueError exceptions when unpacking rendered_inputs to avoid unexpected 500 errors, and refactoring decode_prompt_token_ids to use array.array as well, which would allow for the complete removal of the numpy import in that module.

Comment on lines +175 to +177
# Only single prompt is supported.
(rendered_input,) = rendered_inputs
return extract_prompt_components(self._model_config, rendered_input).token_ids

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.

high

Unpacking rendered_inputs directly with (rendered_input,) = rendered_inputs is risky because it will raise a ValueError if rendered_inputs is empty or contains multiple elements. Since this ValueError is not caught by the TokenizeError try-except block in LLMRouter.route, it will propagate and cause a 500 Internal Server Error. Consider handling empty or multiple inputs gracefully by checking if rendered_inputs is empty and returning None (which falls back to token-less routing) or taking the first element.

Suggested change
# Only single prompt is supported.
(rendered_input,) = rendered_inputs
return extract_prompt_components(self._model_config, rendered_input).token_ids
if not rendered_inputs:
return None
return extract_prompt_components(self._model_config, rendered_inputs[0]).token_ids

Comment on lines 31 to +36
try:
arr = np.asarray(token_ids, dtype="<u4")
except OverflowError as e:
raise ValueError("prompt token ids must fit in uint32") from e
if arr.ndim != 1:
raise ValueError("prompt token ids must be a one-dimensional sequence")
return arr.tobytes()
return array.array("I", token_ids).tobytes()
except (OverflowError, TypeError) as e:
raise ValueError(
"prompt token ids must be a one-dimensional sequence of uint32 integers"
) from e

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.

medium

Since encode_prompt_token_ids has been refactored to use array.array instead of numpy, we can also refactor decode_prompt_token_ids to use array.array (e.g., using arr = array.array('I'); arr.frombytes(payload); return arr.tolist()). This would allow us to completely remove the numpy import from this module, reducing CPU/memory overhead and startup time.

@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Nov 9, 2026
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-router-event-loop-cpu branch from 7c4442d to b78c81b Compare November 10, 2026 01:14
@jeffreywang88
jeffreywang88 removed this pull request from stack #67970 November 13, 2026 19:54
@jeffreywang88
jeffreywang88 changed the base branch from serve-llm-kv-session-token-cache to master November 13, 2026 19:54
@jeffreywang88
jeffreywang88 requested review from a team as code owners November 13, 2026 19:54
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-router-event-loop-cpu branch from b78c81b to ba490d3 Compare November 13, 2026 19:55
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

Rebasing onto master to merge independently of #67917

@jeffreywang88
jeffreywang88 merged commit 85a0aff into master Nov 19, 2026
7 checks passed
@jeffreywang88
jeffreywang88 deleted the serve-llm-kv-router-event-loop-cpu branch November 19, 2026 18:37
jeffreywang88 added a commit that referenced this pull request Nov 19, 2026
…izer caching (#67940)

## Description
Multi-turn requests can reach different LLMRouter replicas and
repeatedly tokenize shared conversation prefixes. This PR routes a
session to a stable ingress router and configures fastokens’ native
segment cache to reuse tokenized segments across turns and branches.
- Use HAProxy’s native hash-type **consistent** (algorithm) **sdbm**
(hash function) **avalanche** (post-processing). Deterministic server
IDs derived from replica names keep mappings consistent across HAProxy
processes, regardless of server ordering or local IP rewriting.
- Route consultations with session IDs through a private Unix-socket
listener (see diagram below) so the existing Lua request flow can use
HAProxy’s native backend selection.
- Requests without a session use local round robin. Cross-process
affinity requires matching router membership, weights, and health views.

```mermaid
sequenceDiagram
    participant C as Client
    box One HAProxy process
        participant P as Public listener / Lua
        participant B as Private Unix listener + hash backend
    end
    participant R as LLMRouter
    participant S as LLMServer / vLLM

    C->>P: Inference request + session ID
    Note over P: Original request waits

    P->>B: Consultation over local Unix socket
    B->>R: Hash session ID, POST /internal/route
    Note over R: Reuse tokenized segments<br/>Choose an LLMServer
    R-->>B: Selected replica ID + routing headers
    B-->>P: Consultation result

    P->>S: Forward original inference request
    S-->>P: Generated tokens
    P-->>C: Stream response
```

### Configurations
- Default `FASTOKENS_SEGMENT_CACHE` to 1024 MiB per native cache.
Configuration in `LLMConfig.runtime_env.env_vars` takes precedence over
the inherited environment. Fastokens enablement remains controlled by
`VLLM_USE_FASTOKENS`, keeping the router and engine on the same
tokenizer backend.


## Benchmark
### 1. AgentX + mocker engines
Setup follows #67917. This PR
optimizes work at the ingress router, so the benefits shouldn't compound
as the deployment scales. I'm sweeping across deployment sizes to
confirm this.

<img width="1144" height="339" alt="Screenshot 2026-11-07 at 12 20
31 AM"
src="https://github.com/user-attachments/assets/39e1ace6-93e1-45ca-b67f-cfafd2382abb"
/>

Note: We use mocker engines to filter optimization candidates and
realistic LLM deployments below to validate the benefits brought by the
optimization.

### 2. AgentX + 8 replicas across 2 nodes with DSV4.1-Flash on B200s

#### Setup

- **Stack:** Ray Serve LLM, with HAProxy ingress (direct streaming) and
`KVAwareRouter` session affinity. Real vLLM 0.33.0 engines with
`VLLM_USE_FASTOKENS=1`.
- **Model:** DSV4.1-Flash FP4 + MTP (DSpark, 5 speculative tokens,
synthetic acceptance length 3.51), with engine flags matching
[InferenceX](https://github.com/SemiAnalysisAI/InferenceX/actions/runs/40269923234/attempts/1)
DEP2 + DRAM KV.
- **Compute:** 2 B200 nodes, plus a CPU-only head node. 8 replicas of
DEP2 (TP1 × DP2 + EP).
- **Engine config:**
- `max_num_seqs` 48, `max_num_batched_tokens` 4096,
`gpu_memory_utilization` 0.955.
  - Native CPU KV offload, 32 GiB per rank.
  - DeepGEMM MegaMoE.
- **Variants:** baseline (master, session pinning) → + replica mesh
(#67917) → + tokenization cache (#67940) → + KV-router CPU (#67981).
- **Traffic:**
  - AgentX: 3600 s profiling window, seed 42, 393 traces.
  - 64 or 128 concurrent sessions per replica, so 512 or 1024 in total.
- Requests carry `X-Session-ID` for sticky-session routing through
`KVAwareRouter`.

#### Results

| Concurrency per replica | Configuration | Throughput | p90 TTFT | p90
TPOT |
| --- | --- | --- | --- | --- |
| 64 | Master | 1318.1 | 708 | 8.22 |
| | + Replica mesh #67917 | 1319.7 | 691 | 8.23 |
| | + Tokenization cache #67940 | **1329.2** | **608** | **8.15** |
| | + KV-router CPU #67981 | 1334.8 | 570 | 8.11 |
| 128 | Master | 2009.9 | 3296 | 15.70 |
| | + Replica mesh #67917 | 2008.1 | 3106 | 15.69 |
| | + Tokenization cache #67940 | **2055.0** | **2313** | **15.56** |
| | + KV-router CPU #67981 | 2069.3 | 2109 | 15.50 |

Tokenization cache alone, with replica mesh as the baseline, results in
up to **25% p90 TTFT reduction** (c128).

## Related issues
Follow-up to #67917, adding ingress affinity and tokenization reuse on
top of the replica mesh and lifecycle work.

## Additional information
### Validation
- Determinism: 100,000 session IDs across three HAProxy processes and
1,000 configured routers; zero mismatches over 400,000 requests,
including restart. Varied addresses, ordering, and thread counts.
- Failover and recovery: Both proxies excluded a stopped router and
restored its original session assignments after recovery.

---------

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

2 participants