Repository navigation
[serve][llm] Reduce KV router event loop CPU overhead - #67981
Conversation
There was a problem hiding this comment.
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.
| # Only single prompt is supported. | ||
| (rendered_input,) = rendered_inputs | ||
| return extract_prompt_components(self._model_config, rendered_input).token_ids |
There was a problem hiding this comment.
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.
| # 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 |
| 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 |
There was a problem hiding this comment.
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.
7c4442d to
b78c81b
Compare
Signed-off-by: Jeffrey Wang <[email protected]>
b78c81b to
ba490d3
Compare
|
Rebasing onto master to merge independently of #67917 |
…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]>
Description
Reduce per-request CPU overhead in
LLMRouter:msgspecinstead ofjson.loads.msgspecis 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.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.These changes optimize existing behavior, so they reuse existing correctness coverage:
test_tokenizer_exactness.pycompares chat/completion tokens against transformers and exercises Anthropic token staging and reuse.test_token_channel.pyverifies token IDs survive encoding, ZMQ delivery, decoding, and forwarding to the selected replica.Benchmark
1. Mocker engine
Setup follows #67917. This PR's optimization results in 7-10 ms TTFT reduction.
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
KV-router CPU overhead reduction alone results in 9% p90 TTFT reduction on top of tokenization cache.
Related issues
Additional information