Repository navigation
[Serve][LLM][2/3] Token based autoscaling: report custom autoscaling metrics from fixed deployments - #67938
[Serve][LLM][2/3] Token based autoscaling: report custom autoscaling metrics from fixed deployments#67938celinaky wants to merge 8 commits into
Conversation
cf06413 to
a05201c
Compare
367bb60 to
b4d4142
Compare
There was a problem hiding this comment.
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.
d77a3de to
d0c6290
Compare
d0c6290 to
6771443
Compare
jeffreywang88
left a comment
There was a problem hiding this comment.
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:
- each
LLMRouterreplica callsrecord_autoscaling_stats()periodically and pushes the results to the controller. - each router's raw samples over the look-back window land in
LLMRouter'sAutoscalingContext.raw_metrics, one series per router replica. - 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 forLLMServeronly.
Signed-off-by: Celina Yang <[email protected]>
28d5a4b to
0bd6925
Compare
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
…ontexts Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
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]>
…-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]>
Token-based autoscaling stack
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.AutoscalingMetricsConfig. Existing autoscaling deployments continue to use the reporting settings from their autoscaling config by default.contexts[source_id].raw_metricsor.aggregated_metricsand can return a replica-count decision for an autoscaling-enabled target.AutoscalingMetricsContextwith identity, observed replicas, timestamp, and per-replica metrics. Autoscaling targets getAutoscalingContext, a subclass adding request counts, target count, bounds, configuration, and policy state. The application policy receives both in a single dictionary keyed byDeploymentID.Example
Inside a Serve builder, configure a fixed reporter before binding it:
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) andpytest -q python/ray/serve/tests/unit/test_autoscaling_policy.py— 49 passed in total.pytest -q python/ray/serve/tests/unit/test_llm_token_autoscaling_policy.py— 4 passed.Developed with AI assistance.