-
-
Notifications
You must be signed in to change notification settings - Fork 10.6k
[Core] Lite weight profiler implementation #26648
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
namanlalitnyu
wants to merge
8
commits into
vllm-project:main
Choose a base branch
from
namanlalitnyu:vllm_lite_profiler
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.
+350
−25
Open
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
314d2fa
Lite profiler implementation
namanlalitnyu be66fef
Addressed review comments
namanlalitnyu 8dbe58a
address comments and add documentation
namanlalitnyu abee1ae
fix documentation error
namanlalitnyu 910dd31
add line buffer to avoid data leakage
namanlalitnyu e2ced02
Update documentation and add comments
namanlalitnyu 3b8dd27
Address review comments
namanlalitnyu 07dfcc2
use different functools for cache
namanlalitnyu 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
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,144 @@ | ||
# SPDX-License-Identifier: Apache-2.0 | ||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project | ||
"""Minimal helpers for opt-in lightweight timing collection.""" | ||
|
||
from __future__ import annotations | ||
|
||
import atexit | ||
import multiprocessing | ||
import os | ||
import time | ||
from contextlib import suppress | ||
from types import TracebackType | ||
from typing import TextIO | ||
|
||
import vllm.envs as envs | ||
from vllm.logger import init_logger | ||
|
||
logger = init_logger(__name__) | ||
|
||
|
||
def _should_log_results() -> bool: | ||
"""Check if the current process should log results. | ||
Only the data-parallel rank 0 engine core and worker 0 should emit logs in | ||
multi-process deployments so that we avoid duplicating identical timing | ||
data. | ||
""" | ||
process = multiprocessing.current_process() | ||
return process.name in ("EngineCore_DP0", "VllmWorker-0") | ||
|
||
|
||
# Cache for log file handle | ||
_log_file: TextIO | None = None | ||
log_results = _should_log_results() | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
|
||
def _write_log_entry(name: str, elapsed_us: int) -> None: | ||
"""Write a profiler entry using cached file handle for optimal performance. | ||
This function implements an efficient caching approach where the file handle | ||
is opened once and reused for all subsequent writes. This eliminates the | ||
significant overhead of opening/closing files for every profiler entry, | ||
which is crucial for maintaining the lightweight nature of the profiler. | ||
The cached file handle is automatically closed on program exit via atexit. | ||
""" | ||
global _log_file | ||
_LOG_PATH = envs.VLLM_LITE_PROFILER_LOG_PATH | ||
|
||
if not log_results or _LOG_PATH is None: | ||
return | ||
|
||
# Handle case where file handle was opened in parent but we're in the | ||
# child process. The file descriptor may become invalid after fork | ||
if _log_file is not None: | ||
try: | ||
# Verify if the file handle is still valid | ||
_log_file.tell() | ||
except (OSError, ValueError): | ||
# File handle is stale, clear and reopen | ||
_log_file = None | ||
|
||
# Write the log entry | ||
log_line = f"{name}|{elapsed_us}\n" | ||
if _log_file is None: | ||
directory = os.path.dirname(_LOG_PATH) | ||
if directory: | ||
os.makedirs(directory, exist_ok=True) | ||
# ruff: noqa: SIM115 - intentionally keeping file handle cached globally | ||
_log_file = open(_LOG_PATH, "a", buffering=50000) | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
atexit.register(_log_file.close) | ||
|
||
_log_file.write(log_line) | ||
|
||
|
||
class LiteScope: | ||
"""Lightweight context manager for timing code blocks with minimal overhead. | ||
This class provides a simple way to measure and log the execution time of | ||
code blocks using Python's context manager protocol (with statement). It's | ||
designed for high-frequency profiling with minimal performance impact. | ||
""" | ||
|
||
def __init__(self, name: str) -> None: | ||
self._name = name | ||
self._start_time: int | None = None | ||
|
||
def __enter__(self) -> None: | ||
self._start_time = time.perf_counter_ns() | ||
|
||
def __exit__( | ||
self, | ||
exc_type: type[BaseException] | None, | ||
exc_value: BaseException | None, | ||
traceback: TracebackType | None, | ||
) -> bool: | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if self._start_time is not None and exc_type is None: | ||
elapsed_ns = time.perf_counter_ns() - self._start_time | ||
# Use integer microseconds for better performance | ||
elapsed_us = elapsed_ns // 1000 | ||
_write_log_entry(self._name, elapsed_us) | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return False | ||
|
||
|
||
def maybe_emit_lite_profiler_report() -> None: | ||
"""Generate and display a summary report of profiling data if available. | ||
This function serves as the main entry point for analyzing and displaying | ||
profiling results. It checks if profiling was enabled and a log file exists, | ||
then delegates to the lite_profiler_report module to generate statistics | ||
like function call counts, timing distributions, and performance insights. | ||
""" | ||
|
||
log_path = envs.VLLM_LITE_PROFILER_LOG_PATH | ||
if log_path is None: | ||
return | ||
|
||
if not os.path.exists(log_path): | ||
logger.warning( | ||
"Lite profiler log not found. Ensure the profiled process sets " | ||
"the expected path." | ||
) | ||
return | ||
|
||
try: | ||
from vllm.utils import lite_profiler_report | ||
except Exception as exc: # pragma: no cover - import error should not crash | ||
logger.error("Failed to import lite profiler report helper: %s", exc) | ||
return | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
logger.info("") | ||
logger.info("Lite profiler summary (%s):", log_path) | ||
try: | ||
# Generate and display the summary report | ||
lite_profiler_report.summarize_log(log_path) | ||
|
||
# Clear the log file to avoid accumulating data from multiple runs | ||
with suppress(OSError): | ||
directory = os.path.dirname(log_path) | ||
if directory: | ||
os.makedirs(directory, exist_ok=True) | ||
with open(log_path, "w"): | ||
pass | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
except Exception as exc: # pragma: no cover - avoid crashing benchmarks | ||
logger.error("Failed to summarize lite profiler log %s: %s", log_path, exc) |
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,121 @@ | ||
# SPDX-License-Identifier: Apache-2.0 | ||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project | ||
"""Summarize a single vLLM lite-profiler log in tabular form. | ||
The script consumes the pipe-separated records emitted by `vllm.lite_profiler` | ||
It expects log lines in the format: "<scope_name>|<elapsed_microseconds>" | ||
""" | ||
|
||
from __future__ import annotations | ||
|
||
from collections import defaultdict | ||
from collections.abc import Iterable, Sequence | ||
|
||
from vllm.logger import init_logger | ||
|
||
logger = init_logger(__name__) | ||
|
||
|
||
def _extract_event_us(filename: str) -> dict[str, list[int]]: | ||
"""Collect the microsecond timings for every scope in ``filenames``.""" | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
all_event_us: dict[str, list[int]] = defaultdict(list) | ||
try: | ||
with open(filename, encoding="utf-8") as f: | ||
for raw_line in f: | ||
line = raw_line.strip() | ||
if not line: | ||
continue | ||
|
||
# Parse the format: "scope_name|elapsed_microseconds" | ||
if "|" in line: | ||
try: | ||
scope_name, elapsed_us_str = line.split("|", 1) | ||
elapsed_us = int(elapsed_us_str) | ||
all_event_us[scope_name].append(elapsed_us) | ||
except (ValueError, IndexError): | ||
# Skip malformed lines | ||
continue | ||
except FileNotFoundError: | ||
raise FileNotFoundError(f"Lite-profiler log not found: {filename}") from None | ||
return all_event_us | ||
|
||
|
||
def _sum_events(event_us: dict[str, list[int]]) -> dict[str, int]: | ||
return {event: sum(values) for event, values in event_us.items()} | ||
|
||
|
||
def _format_duration_us(value_us: int, total_us: int) -> str: | ||
# Convert microseconds to seconds | ||
seconds = value_us / 1e6 if value_us else 0.0 | ||
percent = (value_us * 100.0 / total_us) if total_us else 0.0 | ||
return f"{seconds:.2f}s ({percent:.2f}%)" | ||
|
||
|
||
def _render_table( | ||
title: str, headers: Sequence[str], rows: Iterable[Sequence[str]] | ||
) -> None: | ||
table = [list(headers)] + [list(row) for row in rows] | ||
widths = [max(len(row[i]) for row in table) for i in range(len(headers))] | ||
|
||
logger.info("") | ||
logger.info(title) | ||
separator = "-" * (sum(widths) + 3 * (len(widths) - 1)) | ||
logger.info(separator) | ||
|
||
def _fmt(row: Sequence[str]) -> str: | ||
return " | ".join(cell.ljust(widths[i]) for i, cell in enumerate(row)) | ||
|
||
logger.info(_fmt(table[0])) | ||
logger.info(" | ".join("-" * w for w in widths)) | ||
for row in table[1:]: | ||
logger.info(_fmt(row)) | ||
|
||
|
||
TOP_EVENTS = [ | ||
"Input:Process", | ||
"Step:Schedule", | ||
"Step:Model", | ||
"Step:Output", | ||
] | ||
|
||
MODEL_EVENTS = [ | ||
"Model:UpdateState", | ||
"Model:PrepareInput", | ||
"Model:Forward", | ||
"Model:Postprocess", | ||
"Model:Sample", | ||
"Model:Bookkeep", | ||
"Model:EPLB", | ||
"Model:Draft", | ||
] | ||
namanlalitnyu marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
def _compute_table_rows( | ||
event_us_sum: dict[str, int], | ||
events: Sequence[str], | ||
) -> list[str]: | ||
total_us = sum(event_us_sum.get(event, 0) for event in events) | ||
cells = [] | ||
for event in events: | ||
cells.append(_format_duration_us(event_us_sum.get(event, 0), total_us)) | ||
# Convert microseconds to seconds | ||
total_seconds = total_us / 1_000_000 if total_us else 0.0 | ||
cells.append(f"{total_seconds:.2f}s") | ||
namanlalitnyu marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return cells | ||
|
||
|
||
def _print_breakdown_tables(event_us_sum: dict[str, int]) -> None: | ||
for title, events in ( | ||
("Top-level pipeline events", TOP_EVENTS), | ||
("Model events breakdown (only includes the main key events)", MODEL_EVENTS), | ||
): | ||
headers = [*events, "TOTAL"] | ||
rows = [_compute_table_rows(event_us_sum, events)] | ||
_render_table(title, headers, rows) | ||
|
||
|
||
def summarize_log(log_path: str) -> None: | ||
event_us = _extract_event_us(log_path) | ||
event_us_sum = _sum_events(event_us) | ||
_print_breakdown_tables(event_us_sum) |
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.
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.