Skip to content

[rollout, vllm] feat: KV-cache-aware request load balancer#7115

Draft
touch869 wants to merge 15 commits into
verl-project:mainfrom
touch869:router
Draft

[rollout, vllm] feat: KV-cache-aware request load balancer#7115
touch869 wants to merge 15 commits into
verl-project:mainfrom
touch869:router

Conversation

@touch869

Copy link
Copy Markdown

What does this PR do?

Add a KV-cache-aware request load balancer as a new routing option for verl's rollout servers, migrated from the standalone uni-agent LLM router. The new balancer routes each request by combining prefix-cache hit rates (GPU/CPU/SSD tiers) with live load metrics (KV-cache usage, running/waiting requests), and preserves sticky sessions for multi-turn conversations with overload-aware fallback.

It is fully opt-in: when no router config is provided (or router.type: default), the existing GlobalRequestLoadBalancer behavior is unchanged.

Depends on #6712.

Related issues/PRs:

Checklist Before Starting

  • Search for similar PRs. Paste at least one query link here:
  • Format the PR title as [{modules}] {type}: {description} (This will be checked by the CI)
    • Suggested title: [rollout, vllm] feat: KV-cache-aware request load balancer

Test

Import, config-parsing, strategy-construction, and LLMServerManager integration smoke tests pass:

pytest tests/workers/rollout/test_kvc_aware_balancer.py::TestKVCAwareBalancerImport -v
# 4 passed

End-to-end validation on a real vLLM rollout (throughput / cache-hit comparison vs. the default balancer):

API and Usage Example

API change (backward compatible): LLMServerClient._acquire_server() gains an optional prompt_ids: list[int] = None parameter, forwarded to the balancer for content-aware routing. Existing callers are unaffected. A new optional router section is added under the rollout config.

actor_rollout_ref:
  rollout:
    name: vllm
    router:
      type: kvc_aware          # omit or "default" -> existing GlobalRequestLoadBalancer
      config:
        strategies:
          - _target_: verl.workers.rollout.llm_router.config.strategy.KVCAwareStrategyConfig
            alpha: 0.7            # S = alpha*S_cache + (1-alpha)*S_load
            load_threshold: 0.9  # sticky session bypassed when load > threshold
            layer_weights: {gpu: 0.7, cpu: 0.2, ssd: 0.1}
            collector_names: [vllm_polling]
            weight: 1.0
        sticky_max_size: 10000
    prometheus:
      enable: true
    disable_log_stats: false     # required for Prometheus metrics
from verl.workers.rollout.llm_router import KVCAwareBalancer  # available as a drop-in balancer

Design & Code Changes

The router is a self-contained package under verl/workers/rollout/llm_router/ that satisfies the same balancer interface as GlobalRequestLoadBalancer (acquire_server / release_server / add_servers / remove_servers / get_all_servers / get_status).

  • New package verl/workers/rollout/llm_router/:
    • balancer.pyKVCAwareBalancer orchestration shell (wrapped with ray.remote at init).
    • strategies/kvc_aware scoring, weighted routing, sticky_session, load_score, registry.
    • collectors/RouteDataProvider + vLLM metrics/KV decoders over HTTP-polling and ZMQ transports.
    • store/ — KV-cache hit and metrics stores.
    • config/ + configs/ — Hydra/OmegaConf config parsing and default YAMLs.
  • verl/workers/rollout/llm_server.py:
    • LLMServerManager._init_global_load_balancer() selects the balancer by router.type (kvc_aware vs default), keeping the default path unchanged.
    • LLMServerClient._acquire_server() / generate() thread prompt_ids through for cache-aware routing.
  • Tests: tests/workers/rollout/test_kvc_aware_balancer.py.
  • Docs: package README.md, config example, and a repo-level quickstart.

Checklist Before Submitting

Important

Please check all the following items before requesting a review, otherwise the reviewer might deprioritize this PR for review.

ZOULQ and others added 11 commits July 22, 2026 17:27
…contract

- Split flat router.py into a router/ package mirroring engine/base.py.
- RequestLoadBalancer Protocol declares the __init__(servers, config) contract.
- LoadBalancerRegistry registers strategies via decorator; get_router_handle dispatches.
- Move GlobalRequestLoadBalancer to global_balancer.py; fix zip subscript typo.
- Add RolloutConfig.router_config field.
- Expose get_rollout_config() on the vLLM server for external routers.
- Register the kvcaware strategy via the decorator.
- Add the KVCAwareBalancer orchestration shell.
- Add the kvcaware subsystem skeleton: config, strategies, collectors, store interfaces, types, logging.
- Package imports cleanly and the strategy registers; no working balancer constructed yet.
- Add KVCacheStore / MetricsStore / StickySessionStore singletons.
- Wire DataStore top-level sub-store imports (C2 left them as a cut).
- Add xxhash chained prefix-hash utils (get_prefix_hashes / compute_hash).
- Add store unit tests (sticky+incr delegation, prefix-chain match).

Store layer is now import-clean and DataStore constructs; no collector/strategy impl yet.
- Add concrete transports: Callback / HTTP (httpx) / ZMQ (pyzmq).
- Add decoders: basic (Inflight, Sticky) + vllm (KV, Metrics, KVCacheEvent).
- Wire transport/__init__ eager re-exports (C2 left them as a cut).
- get_collector factory now resolves all four collector names.

Collectors import-clean and drive DataStore; ut/cpu tests green (22 passed). st/gpu tests (real vLLM) deferred to the NPU/GPU container.
- Add KVCacheAwareStrategy (load + cache + sticky-shortcut scoring).
- Register it in StrategyRegistry via strategies/__init__ side-effect import (C2 left the registry empty).
- route() now ranks real replicas against store metrics.

Strategy layer complete; balancer can now resolve the kvcaware strategy. ut/cpu tests green (81 passed).
- Wire the balancer end-to-end: orchestration tests (unit/sticky/ray-integration),
  kvcaware.yaml Hydra group, test_config compose tests, ci_test.sh, top-level conftest.
- Add e2e tests (router + mooncake) driving run_infer.sh over a real vLLM agent loop.
- Fix get_router_handle struct-mode bug: mutating full_determinism on a Hydra-composed
  router_config node raised ConfigKeyError; materialize the node to a plain dict first
  (production-only — ut used non-struct configs and missed it).
- Add the generic (GPU) example: parallel_infer.py (MooncakeStoreConnector, kv-events,
  oc.select-derived fields), run_infer.sh, agent configs, READMEs.
- Simplify kvcaware/ comments: drop stale FQN/migration-history/external-doc references,
  trim verbose docstrings; license headers consistent across the package.

Verified on the GPU container (vllm 0.21): ci_test ut 233 / st-cpu 5 / st-gpu 11 / e2e 2, all PASS.
…lter + slow_cut config fields

- Add SlowCut enum (prefix-load-aware / least-inflight) to kvcaware.types; export from types.
- Add memory_overload_filter (bool, default True) and slow_cut (SlowCut, default
  prefix-load-aware) to KVCAwareStrategyConfig, with yaml-str→SlowCut coercion + validation
  in __post_init__ (mirrors the Layer pattern).
- plot_metrics.py: refactor into an OOP panel design (LogParser + Panel hierarchy —
  FieldPanel / MFUPanel(SlidingPanel) / EvictPanel(CumulativePanel); the extract/transform/
  derive/draw/summarize hooks absorb the per-metric free functions).
@CLAassistant

CLAassistant commented Jul 22, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 5 committers have signed the CLA.

❌ yyyyrf
❌ ZOULQ
❌ zhaizhiqiangA
❌ hangangqiang
❌ touch869


yyyyrf seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@tardis-key

Copy link
Copy Markdown
Collaborator

There are too many changes in this pr. Can we try breaking it into smaller ones?

…plot walltime subtitle

- per-request observability: turn tracking, prompt-length, route latency,
  load panels + dispatch plots (plot_metrics.py)
- plot_metrics walltime subtitle: run walltime (first→last log timestamp
  across ALL lines, incl. vLLM warmup/teardown that the signal window
  excludes) as a centered figure subtitle; _fmt_walltime helper
- kv-event hardening: surface kv-event decode errors; match vLLM replay
  protocol (zmq transport + kv decoder)
@touch869
touch869 marked this pull request as draft July 24, 2026 07:05
yyyyrf and others added 2 commits July 24, 2026 15:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants