Skip to content

[Serve][LLM][2/3] Token based autoscaling: report custom autoscaling metrics from fixed deployments - #67938

Open
celinaky wants to merge 8 commits into
masterfrom
celina/prefill-token-autoscaling-2-metrics-path
Open

celinaky wants to merge 8 commits into
masterfrom
celina/prefill-token-autoscaling-2-metrics-path

Conversation

@celinaky

@celinaky celinaky commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Token-based autoscaling stack

  1. [Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router #67937 tracks outstanding effective prefill tokens in the KV router.
  2. [Serve][LLM][2/3] Token based autoscaling: report custom autoscaling metrics from fixed deployments #67938 (this PR) lets a deployment report metrics to an application autoscaling policy while its replica count is managed independently.
  3. [Serve][LLM][3/3] Token based autoscaling: scale the bound server from router token metrics #67941 uses the router’s token metrics to scale its bound LLM server.

Changes in this PR

An application policy may need a signal produced by a different deployment from the one it scales. This revision uses Serve’s existing record_autoscaling_stats() hook and replica report transport.

  • A Serve builder can opt a deployment into reporting with an experimental internal AutoscalingMetricsConfig. Existing autoscaling deployments continue to use the reporting settings from their autoscaling config by default.
  • The controller stores each replica’s report under its source deployment. An application policy reads contexts[source_id].raw_metrics or .aggregated_metrics and can return a replica-count decision for an autoscaling-enabled target.
  • A metrics-only reporter gets an experimental AutoscalingMetricsContext with identity, observed replicas, timestamp, and per-replica metrics. Autoscaling targets get AutoscalingContext, a subclass adding request counts, target count, bounds, configuration, and policy state. The application policy receives both in a single dictionary keyed by DeploymentID.

Example

Inside a Serve builder, configure a fixed reporter before binding it:

from ray import serve
from ray.serve._private.config import AutoscalingMetricsConfig

@serve.deployment(num_replicas=2)
class Reporter:
    def record_autoscaling_stats(self):
        return {"backlog": 12}

Reporter._deployment_config.autoscaling_metrics_config = AutoscalingMetricsConfig(
    metrics_interval_s=1,
    look_back_period_s=30,
    aggregation_function="mean",
)
reporter = Reporter.bind()

Each replica’s metrics manager polls the hook and pushes the buffered samples to the controller. In the application policy, contexts[reporter_id].aggregated_metrics["backlog"] maps each reporting replica ID to its own window aggregate. The policy chooses which eligible deployment receives the scaling decision.

Verification

The mixed-context regression exercises the application-policy wrapper with a readable router and a scalable server, including rejection of a router scaling decision. Across the two PRs, the focused custom-metrics, policy, config, and deployment-state tests yielded 518 passed and 12 skipped.

  • pytest -q python/ray/serve/tests/test_custom_autoscaling_metrics.py -k metric_source (both metric-source tests) and pytest -q python/ray/serve/tests/unit/test_autoscaling_policy.py — 49 passed in total.
  • Stacked policy suite pytest -q python/ray/serve/tests/unit/test_llm_token_autoscaling_policy.py — 4 passed.
  • Repository pre-commit checks passed. Focused tests used a local import overlay with the installed native Ray binary.

Developed with AI assistance.

@celinaky
celinaky added this pull request to stack #67950 November 8, 2026 00:45
@celinaky
celinaky force-pushed the celina/prefill-token-autoscaling-2-metrics-path branch 3 times, most recently from cf06413 to a05201c Compare November 8, 2026 21:04
@celinaky celinaky added the go add ONLY when ready to merge, run all tests label Nov 9, 2026
@celinaky
celinaky force-pushed the celina/prefill-token-autoscaling-2-metrics-path branch 2 times, most recently from 367bb60 to b4d4142 Compare November 9, 2026 19:29
@celinaky celinaky added go add ONLY when ready to merge, run all tests and removed go add ONLY when ready to merge, run all tests labels Nov 9, 2026
@celinaky
celinaky requested a review from eicherseiji November 11, 2026 19:16
@celinaky
celinaky marked this pull request as ready for review November 11, 2026 19:16
@celinaky
celinaky requested review from a team as code owners November 11, 2026 19:16

@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 support for tracking and reporting router-owned custom autoscaling metrics in Ray Serve, enabling integrations like LLM routers to expose workload signals directly to the controller. The changes span the metrics codec, router, autoscaling state, and handle APIs, along with corresponding unit tests. The review feedback highlights two important improvements: optimizing the conversion of NumPy arrays to Python lists in autoscaling_state.py using .tolist() for better performance, and updating the type validation in router.py to use numbers.Real to correctly support NumPy numeric types.

Comment thread python/ray/serve/_private/router.py Resolved
@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Nov 12, 2026
@celinaky
celinaky force-pushed the celina/prefill-token-autoscaling-2-metrics-path branch 3 times, most recently from d77a3de to d0c6290 Compare November 13, 2026 08:57
Base automatically changed from celina/prefill-token-autoscaling-1-kv-router to master November 13, 2026 19:39
@jeffreywang88
jeffreywang88 force-pushed the celina/prefill-token-autoscaling-2-metrics-path branch from d0c6290 to 6771443 Compare November 13, 2026 19:39
@celinaky celinaky changed the title [Serve][LLM][2/3] Token based autoscaling: transport router metrics to controller [Serve][LLM][2/3] Token based autoscaling: transport and aggregate router metrics Nov 13, 2026

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

i'm a bit hesitant about coupling per-handle router metrics in serve's core mechanics (handle → router → RouterMetricsManager → wire format → controller), and about exposing aggregated_router_metrics on AutoscalingContext in config.py.

have you evaluated the existing custom autoscaling hooks? serve already supports this: a deployment can report custom metrics from each replica through record_autoscaling_stats(), and an application-level autoscaling policy gets the AutoscalingContext of every autoscaling deployment in the app, so it can scale one deployment (LLMServer) from another deployment's (LLMRouter) metrics. the logic can live in ray.llm entirely:

# LLMRouter: Serve calls this on every router replica periodically.
async def record_autoscaling_stats(self) -> Dict[str, float]:
    if self._kv_token_tracker is None:
        return {}
    return await self._kv_token_tracker.get_autoscaling_snapshot()


def _max_across_routers(series_by_router: Dict[ReplicaID, TimeSeries]) -> TimeSeries:
    """Merge router gauges into one step series: at each sample, the max of
    every router's latest value."""
    points = sorted(
        ((p.timestamp, rid, p.value) for rid, series in series_by_router.items() for p in series),
        key=lambda point: point[0],
    )
    latest, merged = {}, []
    for ts, rid, value in points:
        latest[rid] = value
        merged.append(TimeStampedValue(ts, max(latest.values())))
    return merged


# App-level policy: gets one AutoscalingContext per deployment in the app.
def llm_token_autoscaling_policy(ctxs: Dict[DeploymentID, AutoscalingContext]):
    router_id = next(d for d in ctxs if d.name == LLM_ROUTER_DEPLOYMENT_NAME)
    server_id = next(d for d in ctxs if d != router_id)
    router_ctx = ctxs[router_id]
    # Max across routers first, then time-weighted average over the look-back window.
    merged = _max_across_routers(
        (router_ctx.raw_metrics or {}).get(OUTSTANDING_EFFECTIVE_PREFILL_TOKENS, {})
    )
    tokens = time_weighted_average(
        merged,
        window_start=router_ctx.current_time - router_ctx.config.look_back_period_s,
    ) or 0.0
    # Only LLMServer gets a decision. LLMRouter keeps its replica count.
    return {server_id: math.ceil(tokens / TARGET_PREFILL_TOKENS_PER_REPLICA)}, {}

the autoscaling flow would be:

  1. each LLMRouter replica calls record_autoscaling_stats() periodically and pushes the results to the controller.
  2. each router's raw samples over the look-back window land in LLMRouter's AutoscalingContext.raw_metrics, one series per router replica.
  3. the app-level policy merges them into one series by taking the max across routers at each point. it averages that series over look_back_period_s (time-weighted) and returns a target for LLMServer only.

@celinaky
celinaky force-pushed the celina/prefill-token-autoscaling-2-metrics-path branch from 28d5a4b to 0bd6925 Compare November 20, 2026 16:43
@celinaky celinaky changed the title [Serve][LLM][2/3] Token based autoscaling: transport and aggregate router metrics [Serve] Report custom autoscaling metrics from fixed deployments Nov 20, 2026
@celinaky celinaky changed the title [Serve] Report custom autoscaling metrics from fixed deployments [Serve][LLM][2/3] Token based autoscaling: report custom autoscaling metrics from fixed deployments Nov 20, 2026
@celinaky
celinaky requested review from a team as code owners November 20, 2026 20:32
Metrics-only contexts called aggregate_timeseries directly, which holds the
last sample for a fixed second. Share the helper autoscaled deployments use
so the last sample holds until now.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
celinaky added a commit to celinaky/serve-llm-autoscaling-experiment that referenced this pull request Nov 20, 2026
…-off

The repository had grown into a record of many experiments. This keeps what
a new owner needs to evaluate autoscaling policy changes and removes the
rest; everything removed is still in history before this commit.

Kept and reworked:
- Config: only options still in use. Removed the SLA policy, Mooncake shared
  KV cache, other routers, synthetic/request-rate/fixed-concurrency
  workloads and switches tied to retired Ray branches. Unknown keys are now
  errors; old runs' resolved.yaml still loads for re-analysis.
- Workload: AgentX replay following a concurrency_series (ramp up, hold,
  ramp down) is the only mode.
- The vLLM tracing scheduler moved from the vendored serve-llm-profiler into
  the package (scheduler_trace.py, vllm_compat.py) and is always injected.
- Compile-cache warm-up is a command (`autoscale-harness warm`, `run --warm`)
  instead of a script outside the repo.
- Outputs after a run: the scorecard, the policy-vs-engine plot and the
  arrival-statistics plot. `compare` also draws a multi-run plot. The
  timeline, replica-percentile and session-lane plots are removed.
- Six experiment configs (token at 32/64/100 sessions, default at target
  12/32, smoke) replace about 110.

Ray pin: celina/prefill-token-autoscaling-post-downscale-cooldown at
4db7cf9007 (ray-project/ray#67938, #67941, #68148, #68414). The token policy
is now application-level, so the harness deploys from an application config
instead of serve.run(), and reads the policy signal from
serve_autoscaling_replica_metric. Regenerated Serve protos are in setup/.

Fixes found on the way:
- Pre-deploy check that the policy accepts the configured kwargs; a
  mismatch used to leave the deployment without a policy and hang.
- Metrics scrape: 20s timeout and filtering while streaming. On a
  long-lived cluster the 43 MB metrics page made nearly every 2s scrape time
  out, leaving the policy line empty; the run summary now warns on failures.
- Teardown waits for the Serve controller to exit; a deploy sent to a
  controller that was still shutting down was silently dropped.
- Readiness fails fast on DEPLOY_FAILED or a dropped deploy.
- An interrupt during the workload is recorded as such.

Removed from the tree: tracked run directories, findings-*, tools/,
workspace/, patches/, serve-llm-profiler/. runs/ is local output and is no
longer tracked.

Verified with the test suite (no cluster needed) and a live smoke run on
8x B200 against the pinned Ray commit. No full-length run has been made on
this pin yet, and the README's example plots are from 2026-11-17 runs on the
previous pin.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

No deployments
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.

2 participants