Skip to content

[Python][RunInference] vLLM: prefix-aware batching and capacity-based autoscaling - #40908

Draft
AMOOOMA wants to merge 4 commits into
apache:masterfrom
AMOOOMA:pr-vllm-integration
Draft

AMOOOMA wants to merge 4 commits into
apache:masterfrom
AMOOOMA:pr-vllm-integration

Conversation

@AMOOOMA

@AMOOOMA AMOOOMA commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Split out of #40760. This is the vLLM-specific part, built on the generic pieces:

Depends on #40905, #40906 and #40907. Until they merge, this branch includes their commits; only the last commit (vLLM: prefix-aware batching and capacity-based autoscaling) is new here. I'll rebase as the dependencies land.

What

VLLMCompletionsModelHandler / VLLMChatModelHandler:

  • prefix_batching_config: when set, requests that share a prompt prefix are batched together on the same worker, so vLLM's prefix cache is reused. By default the key is the leading characters of the prompt (completions), or the role and leading content of the first message (chat); key_fn overrides it.
  • Capacity-based autoscaling signal: the handlers publish num_loaded_models_<model_identifier> so Dataflow's GPU autoscaling sizes the pool by each worker's capacity.
    • On by default; enable_autoscaling_metric turns it off and autoscaling_config tunes it.
    • Reads vLLM's vllm:request_success_total counter and vllm:num_requests_running gauge via PrometheusCounterGaugeSampler + CompletionRateCapacityEstimator.
    • The tag is the identifier RunInference reports through set_model_identifier.
    • The publisher starts once the vLLM server is reachable and stops with it.

The only vLLM-specific parts are the two metric names, the default prefix extractors and the server lifecycle; everything else lives in the generic modules.

Testing

  • vllm_inference_test.py:
    • Publisher defaults (no double smoothing), and the multiplier and window reaching the estimator.
    • The vLLM metric names reaching the sampler.
    • Tag precedence (identifier used verbatim, sanitized model-name fallback, explicit tag wins).
    • Prefix config reaching BatchElements (8 shards by default).
    • An end-to-end RunInference run with prefix batching and with_preprocess_fn.
  • 4h Dataflow staging run (two 2h sine cycles, 5–40 RPS, OpenOrca, T4, up to 50 workers): GPU scaling applied only to the inference stage. The pool scaled with load and back down at low traffic (50 → 9 and 50 → 2 VMs). An additional single-cycle run with the default 8 shards wrote all 160,166 published requests and scaled down to 4 workers.

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Replace these instructions with a description of your change and why you have made it.
  • Mention the appropriate issue in your description (for example: addresses #123 or fixes #456).
  • Update CHANGES.md with noteworthy changes.

@github-actions github-actions Bot added python core size/xl XL: >=1000 lines changed labels Oct 30, 2026
BatchElements batches per worker, so an LLM server behind RunInference sees
batches that mix unrelated prompt prefixes and its prefix (KV) cache is
thrashed.

Add key_fn and num_shards to BatchElements. With key_fn set, a new WithBatchKey
DoFn keys each element without the per-worker UUID that WithSharedKey and
WithLengthBucketKey add, and GroupIntoBatches routes elements that share a key
to the same worker, so every batch holds a single key. num_shards (an int, a
per-key mapping, or a callable) spreads a hot key over a bounded number of
random sub-keys. Incomplete keyed batches flush after max_batch_duration_secs,
or 1s when it is unset, so low-traffic keys still make progress in streaming.

ModelHandler forwards batch_key_fn / batch_key_num_shards to BatchElements, and
the new apache_beam.ml.inference.prefix_batching module gives LLM handlers a
PrefixBatchingConfig plus default prompt and chat prefix extractors. The config
defaults to 8 shards per prefix: GroupIntoBatches serves each shard on one
worker at a time, so a single shard caps a prefix shared by most traffic at
one worker's throughput.
…er handlers

Dataflow's GPU autoscaling reads num_loaded_models_<tag> in the
BeamML_ModelManager namespace as the number of messages each worker can hold.
A model handler that serves inference through an out-of-process server (vLLM,
Triton, ...) always has exactly one loaded copy per worker, so it needs to
publish a capacity estimate under that metric instead.

Add a generic library for that in apache_beam.ml.inference.autoscaling_metrics:
- NumLoadedModelsPublisher publishes a capacity signal on a background thread,
  resetting the process-wide distribution so the latest value (not a lifetime
  mean) is reported, with optional aggregation policies on top.
- PrometheusCounterGaugeSampler reads a server's completed-requests counter and
  in-flight gauge from its Prometheus /metrics endpoint; the metric names are
  the only server-specific input.
- CompletionRateCapacityEstimator turns those samples into a per-worker
  capacity estimate: per-slot throughput times p90 concurrency over a trailing
  window. It does no I/O.
- AutoscalingMetricConfig holds the user-facing knobs, resolves the metric tag
  (explicit tag, then the RunInference model identifier verbatim, then a
  sanitized model name), and builds the estimator and publisher.
Add ModelHandler.set_model_identifier(), which RunInference calls on each
worker before the first load_model() with the step's model_identifier (the
value passed to RunInference, or the uuid it generates). Handlers that
publish num_loaded_models_<identifier> themselves, such as handlers that
front an out-of-process model server, can then use the exact tag the step is
annotated with. The value is stable across side-input model updates,
matching the metric tag ModelManager uses since apache#40714.

The hook is a no-op by default and is forwarded by the keyed, maybe-keyed,
prebatched, preprocessing and postprocessing wrappers.
…ling

Wire the generic pieces into the vLLM handlers:

- VLLMCompletionsModelHandler / VLLMChatModelHandler accept a
  prefix_batching_config. When set, requests sharing a prompt prefix (the
  leading characters of the prompt, or the role and leading content of the
  first chat message, unless a custom key_fn is given) are batched together on
  the same worker so vLLM's prefix cache is reused.
- The handlers publish num_loaded_models_<model_identifier> (on by default,
  enable_autoscaling_metric / autoscaling_config to tune or disable) so
  Dataflow's GPU autoscaling sizes the pool by each worker's capacity. The
  signal reads vLLM's vllm:request_success_total counter and
  vllm:num_requests_running gauge through PrometheusCounterGaugeSampler and
  CompletionRateCapacityEstimator. The metric tag is the identifier
  RunInference reports through set_model_identifier, and the publisher starts
  once the server is reachable and stops with it.

The only vLLM-specific parts are the two metric names, the default prefix
extractors and the server lifecycle.
@AMOOOMA
AMOOOMA force-pushed the pr-vllm-integration branch from ff5bb1b to 24ee97a Compare October 30, 2026 17:21
@codecov

codecov Bot commented Oct 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.83834% with 44 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.88%. Comparing base (12bbb17) to head (24ee97a).
⚠️ Report is 11 commits behind head on master.

Files with missing lines Patch % Lines
...on/apache_beam/ml/inference/autoscaling_metrics.py 88.67% 29 Missing ⚠️
.../python/apache_beam/ml/inference/vllm_inference.py 69.04% 13 Missing ⚠️
sdks/python/apache_beam/transforms/util.py 96.36% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #40908      +/-   ##
==========================================
+ Coverage   79.83%   79.88%   +0.04%     
==========================================
  Files         494      496       +2     
  Lines       83575    84013     +438     
==========================================
+ Hits        66722    67113     +391     
- Misses      16853    16900      +47     
Flag Coverage Δ
python 79.88% <89.83%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core python size/xl XL: >=1000 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant