-
-
Notifications
You must be signed in to change notification settings - Fork 17.5k
[Frontend] Add x-vllm-* response headers for per-request stats #42198
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vrdn-23
wants to merge
16
commits into
vllm-project:main
Choose a base branch
from
vrdn-23:vrdn-23/request-stats-headers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
e725b27
[Frontend] Add x-vllm-* response headers for per-request stats
vrdn-23 09ae3a2
[Frontend] Extract FinishReason to leaf module to remove model_rebuil…
vrdn-23 3b446c3
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 72507ce
[Frontend] Address PR review: reorder stats finalization, add flag va…
vrdn-23 b413ac7
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 961da6c
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 ccf26b4
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 5856977
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 4ad0637
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 42cbfcb
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 aa84093
Merge remote-tracking branch 'origin/main' into vrdn-23/request-stats…
vrdn-23 2e89c87
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 f96c2f5
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 5298a95
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 2976f6f
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 576d27c
Merge branch 'main' into vrdn-23/request-stats-headers
vrdn-23 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # SPDX-FileCopyrightText: Copyright contributors to the vLLM project | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import pytest | ||
| from fastapi import FastAPI, Request | ||
| from fastapi.responses import JSONResponse | ||
| from httpx import ASGITransport, AsyncClient | ||
|
|
||
| from vllm.entrypoints.openai.engine.protocol import RequestResponseMetadata | ||
| from vllm.entrypoints.openai.request_stats_headers import ( | ||
| build_request_stats_headers, | ||
| request_stats_headers_middleware, | ||
| ) | ||
| from vllm.v1.engine import FinishReason | ||
| from vllm.v1.metrics.stats import FinishedRequestStats | ||
|
|
||
|
|
||
| def _stats(**overrides) -> FinishedRequestStats: | ||
| base = dict( | ||
| finish_reason=FinishReason.STOP, | ||
| request_id="req-1", | ||
| e2e_latency=1.0, | ||
| num_prompt_tokens=50, | ||
| num_generation_tokens=10, | ||
| max_tokens_param=None, | ||
| queued_time=0.05, | ||
| prefill_time=0.10, | ||
| inference_time=0.40, | ||
| decode_time=0.30, | ||
| mean_time_per_output_token=0.030, | ||
| is_corrupted=False, | ||
| num_cached_tokens=5, | ||
| ) | ||
| base.update(overrides) | ||
| return FinishedRequestStats(**base) | ||
|
|
||
|
|
||
| def test_build_headers_basic(): | ||
| headers = build_request_stats_headers(_stats()) | ||
|
|
||
| for key in headers: | ||
| assert key.startswith("x-vllm-"), f"{key} missing x-vllm- prefix" | ||
|
|
||
| assert headers["x-vllm-total-time"] == "1000.00" | ||
| assert headers["x-vllm-queue-time"] == "50.00" | ||
| assert headers["x-vllm-prefill-time"] == "100.00" | ||
| assert headers["x-vllm-inference-time"] == "400.00" | ||
| assert headers["x-vllm-decode-time"] == "300.00" | ||
| assert headers["x-vllm-prompt-tokens"] == "50" | ||
| assert headers["x-vllm-completion-tokens"] == "10" | ||
| assert headers["x-vllm-cached-tokens"] == "5" | ||
| assert headers["x-vllm-time-per-output-token"] == "30.00" | ||
|
|
||
|
|
||
| def test_build_headers_zero_decode(): | ||
| """Single-token completion: mean_time_per_output_token is 0.""" | ||
| headers = build_request_stats_headers( | ||
| _stats(num_generation_tokens=1, decode_time=0.0, mean_time_per_output_token=0.0) | ||
| ) | ||
| assert headers["x-vllm-time-per-output-token"] == "0.00" | ||
| assert headers["x-vllm-completion-tokens"] == "1" | ||
|
|
||
|
|
||
| def _create_test_app() -> FastAPI: | ||
| app = FastAPI() | ||
| app.middleware("http")(request_stats_headers_middleware) | ||
|
|
||
| @app.get("/with-stats") | ||
| async def with_stats(request: Request) -> JSONResponse: | ||
| meta = RequestResponseMetadata(request_id="r") | ||
| meta.finished_stats = _stats() | ||
| request.state.request_metadata = meta | ||
| return JSONResponse({"ok": True}) | ||
|
|
||
| @app.get("/no-stats") | ||
| async def no_stats(request: Request) -> JSONResponse: | ||
| meta = RequestResponseMetadata(request_id="r") | ||
| request.state.request_metadata = meta | ||
| return JSONResponse({"ok": True}) | ||
|
|
||
| @app.get("/no-metadata") | ||
| async def no_metadata() -> JSONResponse: | ||
| return JSONResponse({"ok": True}) | ||
|
|
||
| return app | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_middleware_attaches_headers_when_stats_present(): | ||
| app = _create_test_app() | ||
| async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c: | ||
| resp = await c.get("/with-stats") | ||
| assert resp.status_code == 200 | ||
| assert resp.headers["x-vllm-decode-time"] == "300.00" | ||
| assert resp.headers["x-vllm-prompt-tokens"] == "50" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_middleware_passes_through_when_finished_stats_missing(): | ||
| app = _create_test_app() | ||
| async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c: | ||
| resp = await c.get("/no-stats") | ||
| assert resp.status_code == 200 | ||
| assert "x-vllm-decode-time" not in resp.headers | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_middleware_passes_through_when_metadata_missing(): | ||
| app = _create_test_app() | ||
| async with AsyncClient(transport=ASGITransport(app=app), base_url="http://t") as c: | ||
| resp = await c.get("/no-metadata") | ||
| assert resp.status_code == 200 | ||
| assert "x-vllm-decode-time" not in resp.headers |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # SPDX-FileCopyrightText: Copyright contributors to the vLLM project | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| from starlette.requests import Request | ||
| from starlette.responses import Response | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Callable | ||
|
|
||
| from vllm.v1.metrics.stats import FinishedRequestStats | ||
|
|
||
|
|
||
| def build_request_stats_headers(stats: FinishedRequestStats) -> dict[str, str]: | ||
| """Format computed request timings as x-vllm-* response headers. | ||
|
|
||
| Times are in milliseconds, rounded to 2 decimal places. Values come | ||
| directly from FinishedRequestStats; no arithmetic happens here. | ||
| """ | ||
| return { | ||
| "x-vllm-total-time": f"{stats.e2e_latency * 1000:.2f}", | ||
| "x-vllm-queue-time": f"{stats.queued_time * 1000:.2f}", | ||
| "x-vllm-inference-time": f"{stats.inference_time * 1000:.2f}", | ||
| "x-vllm-prefill-time": f"{stats.prefill_time * 1000:.2f}", | ||
| "x-vllm-decode-time": f"{stats.decode_time * 1000:.2f}", | ||
| "x-vllm-prompt-tokens": str(stats.num_prompt_tokens), | ||
| "x-vllm-completion-tokens": str(stats.num_generation_tokens), | ||
| "x-vllm-cached-tokens": str(stats.num_cached_tokens), | ||
| "x-vllm-time-per-output-token": ( | ||
| f"{stats.mean_time_per_output_token * 1000:.2f}" | ||
| ), | ||
| } | ||
|
|
||
|
|
||
| async def request_stats_headers_middleware( | ||
| request: Request, | ||
| call_next: Callable, | ||
| ) -> Response: | ||
| """FastAPI middleware that attaches x-vllm-* timing headers. | ||
|
|
||
| Reads request.state.request_metadata (populated by the serving layer). | ||
| No-op if metadata or finished_stats is missing — covers streaming, | ||
| errors, and non-OpenAI routes. | ||
| """ | ||
| response = await call_next(request) | ||
| metadata = getattr(request.state, "request_metadata", None) | ||
| if metadata is None or metadata.finished_stats is None: | ||
| return response | ||
| for key, value in build_request_stats_headers(metadata.finished_stats).items(): | ||
| response.headers[key] = value | ||
| return response |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.