[Profiler] Add per-session profiling controls to Python and Rust frontends (#57875)
Signed-off-by: czhu <conway.zhu@cohere.com> Signed-off-by: Conway Zhu <conway.zhu@cohere.com> Co-authored-by: aoshen02 <aoshen@inferact.ai>
This commit is contained in:
@@ -122,8 +122,6 @@ def _validate_api_url(
|
||||
if isinstance(expected_suffixes, str):
|
||||
expected_suffixes = {expected_suffixes}
|
||||
|
||||
expected_suffixes = {*expected_suffixes, "profile"}
|
||||
|
||||
if not api_url.endswith(tuple(expected_suffixes)):
|
||||
raise ValueError(f"{api_name} URL must end with one of: {expected_suffixes}.")
|
||||
|
||||
@@ -158,6 +156,34 @@ def _get_headers(content_type: str | None = None) -> dict[str, str]:
|
||||
return headers
|
||||
|
||||
|
||||
async def async_request_profile(
|
||||
api_url: str,
|
||||
session: aiohttp.ClientSession,
|
||||
extra_headers: dict | None = None,
|
||||
) -> RequestFuncOutput:
|
||||
_validate_api_url(
|
||||
api_url,
|
||||
"Profiling API",
|
||||
{"start_profile", "stop_profile"},
|
||||
)
|
||||
|
||||
headers = _get_headers()
|
||||
if extra_headers:
|
||||
headers |= extra_headers
|
||||
|
||||
output = RequestFuncOutput()
|
||||
try:
|
||||
async with session.post(url=api_url, headers=headers) as response:
|
||||
output.success = response.status == 200
|
||||
if not output.success:
|
||||
output.error = response.reason or ""
|
||||
except Exception:
|
||||
exc_info = sys.exc_info()
|
||||
output.error = "".join(traceback.format_exception(*exc_info))
|
||||
|
||||
return output
|
||||
|
||||
|
||||
async def async_request_openai_completions(
|
||||
request_func_input: RequestFuncInput,
|
||||
session: aiohttp.ClientSession,
|
||||
|
||||
@@ -49,6 +49,7 @@ from vllm.benchmarks.lib.endpoint_request_func import (
|
||||
POOLING_BACKENDS,
|
||||
RequestFuncInput,
|
||||
RequestFuncOutput,
|
||||
async_request_profile,
|
||||
)
|
||||
from vllm.benchmarks.lib.ready_checker import wait_for_endpoint
|
||||
from vllm.benchmarks.lib.utils import (
|
||||
@@ -936,22 +937,10 @@ async def benchmark(
|
||||
|
||||
if profile:
|
||||
print("Starting profiler...")
|
||||
profile_input = RequestFuncInput(
|
||||
model=model_id,
|
||||
model_name=model_name,
|
||||
prompt=test_prompt,
|
||||
api_url=base_url + "/start_profile",
|
||||
prompt_len=test_prompt_len,
|
||||
output_len=test_output_len,
|
||||
logprobs=logprobs,
|
||||
multi_modal_content=test_mm_content,
|
||||
ignore_eos=ignore_eos,
|
||||
profile_output = await async_request_profile(
|
||||
base_url + "/start_profile",
|
||||
session,
|
||||
extra_headers=extra_headers,
|
||||
extra_body=test_extra_body,
|
||||
chat_messages=test_chat_messages,
|
||||
)
|
||||
profile_output = await request_func(
|
||||
request_func_input=profile_input, session=session
|
||||
)
|
||||
if profile_output.success:
|
||||
print("Profiler started")
|
||||
@@ -1469,16 +1458,10 @@ async def benchmark(
|
||||
|
||||
if profile:
|
||||
print("Stopping profiler...")
|
||||
profile_input = RequestFuncInput(
|
||||
model=model_id,
|
||||
prompt=test_prompt,
|
||||
api_url=base_url + "/stop_profile",
|
||||
prompt_len=test_prompt_len,
|
||||
output_len=test_output_len,
|
||||
logprobs=logprobs,
|
||||
)
|
||||
profile_output = await request_func(
|
||||
request_func_input=profile_input, session=session
|
||||
profile_output = await async_request_profile(
|
||||
base_url + "/stop_profile",
|
||||
session,
|
||||
extra_headers=extra_headers,
|
||||
)
|
||||
if profile_output.success:
|
||||
print("Profiler stopped")
|
||||
|
||||
+39
-7
@@ -22,6 +22,34 @@ ProtonHook = Literal["triton"]
|
||||
ProtonOutputFormat = Literal["hatchet", "hatchet_msgpack", "chrome_trace"]
|
||||
|
||||
|
||||
def validate_profile_prefix(prefix: str | None) -> str | None:
|
||||
"""Validate a trace filename prefix supplied for one profiling session."""
|
||||
if prefix is None:
|
||||
return None
|
||||
if (
|
||||
not 1 <= len(prefix) <= 128
|
||||
or not prefix.isascii()
|
||||
or not prefix[0].isalnum()
|
||||
or any(not (char.isalnum() or char in "._-") for char in prefix[1:])
|
||||
):
|
||||
raise ValueError(
|
||||
"profile_prefix must be 1-128 ASCII characters, start with a letter "
|
||||
"or number, and contain only letters, numbers, '.', '_', or '-'"
|
||||
)
|
||||
return prefix
|
||||
|
||||
|
||||
def validate_profile_iteration_bounds(
|
||||
delay_iterations: int | None,
|
||||
max_iterations: int | None,
|
||||
) -> None:
|
||||
"""Validate iteration bounds supplied for one profiling session."""
|
||||
if delay_iterations is not None and delay_iterations < 0:
|
||||
raise ValueError("delay_iterations must be greater than or equal to 0")
|
||||
if max_iterations is not None and max_iterations < 0:
|
||||
raise ValueError("max_iterations must be greater than or equal to 0")
|
||||
|
||||
|
||||
def _is_uri_path(path: str) -> bool:
|
||||
"""Check if path is a URI (scheme://...), excluding Windows drive letters.
|
||||
|
||||
@@ -136,6 +164,16 @@ class ProfilerConfig:
|
||||
Defaults to 0, meaning no limit.
|
||||
"""
|
||||
|
||||
@property
|
||||
def should_profile_frontend(self) -> bool:
|
||||
"""Whether the frontend CPU profiler should be enabled."""
|
||||
activities = self.torch_profiler_activities
|
||||
return (
|
||||
self.profiler == "torch"
|
||||
and not self.ignore_frontend
|
||||
and (activities is None or "CPU" in activities)
|
||||
)
|
||||
|
||||
warmup_iterations: int = Field(default=0, ge=0)
|
||||
"""Number of warmup iterations for PyTorch profiler schedule.
|
||||
During warmup, the profiler runs but data is discarded. This helps reduce
|
||||
@@ -188,13 +226,7 @@ class ProfilerConfig:
|
||||
raise ValueError(
|
||||
"torch_profiler_activities must not contain duplicates"
|
||||
)
|
||||
records_cpu_activity = activities is None or "CPU" in activities
|
||||
if (
|
||||
self.profiler == "torch"
|
||||
and has_delay_or_limit
|
||||
and not self.ignore_frontend
|
||||
and records_cpu_activity
|
||||
):
|
||||
if has_delay_or_limit and self.should_profile_frontend:
|
||||
logger.warning_once(
|
||||
"Using 'torch' profiler with delay_iterations or max_iterations "
|
||||
"while ignore_frontend is False may result in high overhead."
|
||||
|
||||
@@ -162,8 +162,14 @@ class EngineClient(ABC):
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
async def start_profile(self) -> None:
|
||||
"""Start profiling the engine."""
|
||||
async def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
"""Start profiling with optional per-session overrides."""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
|
||||
+17
-3
@@ -785,16 +785,30 @@ class LLM(BeamSearchOfflineMixin, PoolingOfflineMixin, OfflineInferenceMixin):
|
||||
mm_processor_kwargs=mm_processor_kwargs,
|
||||
)
|
||||
|
||||
def start_profile(self, profile_prefix: str | None = None) -> None:
|
||||
"""Start profiling with optional custom trace prefix.
|
||||
def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
"""Start profiling with optional per-session overrides.
|
||||
|
||||
Args:
|
||||
profile_prefix: Optional prefix for the trace file names. If provided,
|
||||
trace files will be named as "<prefix>_dp<X>_pp<Y>_tp<Z>".
|
||||
If not provided, default naming will be used.
|
||||
delay_iterations: Optional number of worker iterations to skip before
|
||||
profiling starts.
|
||||
max_iterations: Optional maximum number of worker iterations to profile.
|
||||
Zero means no limit.
|
||||
|
||||
"""
|
||||
self.llm_engine.start_profile(profile_prefix)
|
||||
self.llm_engine.start_profile(
|
||||
profile_prefix,
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
|
||||
def stop_profile(self) -> None:
|
||||
self.llm_engine.stop_profile()
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
from fastapi import APIRouter, FastAPI, Request
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from vllm.config import ProfilerConfig
|
||||
from vllm.engine.protocol import EngineClient
|
||||
@@ -14,14 +15,32 @@ logger = init_logger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class StartProfileRequest(BaseModel):
|
||||
"""Optional overrides for one profiling session.
|
||||
|
||||
Values are validated by the engine client.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore", strict=True)
|
||||
|
||||
profile_prefix: str | None = None
|
||||
delay_iterations: int | None = None
|
||||
max_iterations: int | None = None
|
||||
|
||||
|
||||
def engine_client(request: Request) -> EngineClient:
|
||||
return request.app.state.engine_client
|
||||
|
||||
|
||||
@router.post("/start_profile")
|
||||
async def start_profile(raw_request: Request):
|
||||
async def start_profile(
|
||||
raw_request: Request, profile_request: StartProfileRequest | None = None
|
||||
):
|
||||
logger.info("Starting profiler...")
|
||||
await engine_client(raw_request).start_profile()
|
||||
# Only pass supplied overrides so clients without them keep the
|
||||
# zero-argument call.
|
||||
overrides = profile_request.model_dump(exclude_none=True) if profile_request else {}
|
||||
await engine_client(raw_request).start_profile(**overrides)
|
||||
logger.info("Profiler started.")
|
||||
return Response(status_code=200)
|
||||
|
||||
|
||||
@@ -181,3 +181,14 @@ class MaxQueuedTokensError(GracefulHTTPError):
|
||||
"Please try again later or on a different instance.",
|
||||
HTTPStatus.SERVICE_UNAVAILABLE,
|
||||
)
|
||||
|
||||
|
||||
class ProfilerAlreadyActiveError(GracefulHTTPError):
|
||||
"""Raised when a profiling session is already active."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
"A profiling session is already active. Call /stop_profile before "
|
||||
"starting another session.",
|
||||
HTTPStatus.CONFLICT,
|
||||
)
|
||||
|
||||
+104
-26
@@ -5,6 +5,7 @@ import importlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from contextlib import AbstractContextManager, contextmanager, nullcontext, suppress
|
||||
@@ -17,7 +18,13 @@ from typing_extensions import override
|
||||
|
||||
import vllm.version
|
||||
from vllm.config import ProfilerConfig
|
||||
from vllm.config.profiler import ProfilerKind, TorchProfilerActivity, _is_uri_path
|
||||
from vllm.config.profiler import (
|
||||
ProfilerKind,
|
||||
TorchProfilerActivity,
|
||||
_is_uri_path,
|
||||
validate_profile_iteration_bounds,
|
||||
)
|
||||
from vllm.config.utils import replace
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
@@ -28,14 +35,16 @@ _TRITON_PROTON_3_7_VERSION = Version("3.7.0")
|
||||
|
||||
class WorkerProfiler(ABC):
|
||||
def __init__(self, profiler_config: ProfilerConfig) -> None:
|
||||
self._delay_iters = profiler_config.delay_iterations
|
||||
self._default_delay_iters = profiler_config.delay_iterations
|
||||
self._delay_iters = self._default_delay_iters
|
||||
if self._delay_iters > 0:
|
||||
logger.info_once(
|
||||
"GPU profiling will start "
|
||||
f"{self._delay_iters} steps after start_profile."
|
||||
)
|
||||
|
||||
self._max_iters = profiler_config.max_iterations
|
||||
self._default_max_iters = profiler_config.max_iterations
|
||||
self._max_iters = self._default_max_iters
|
||||
if self._max_iters > 0:
|
||||
logger.info_once(
|
||||
"GPU profiling will stop "
|
||||
@@ -43,6 +52,9 @@ class WorkerProfiler(ABC):
|
||||
"or when stop_profile is received."
|
||||
)
|
||||
|
||||
# Serializes start()/stop(), which AsyncLLM may call from different threads.
|
||||
self._lifecycle_lock = threading.Lock()
|
||||
|
||||
# Track when the profiler gets triggered by start_profile
|
||||
self._active_iteration_count = 0
|
||||
self._active = False
|
||||
@@ -88,17 +100,32 @@ class WorkerProfiler(ABC):
|
||||
logger.warning("Failed to stop profiler: %s", e)
|
||||
self._running = False # Always mark as not running, assume stop worked
|
||||
|
||||
def start(self) -> None:
|
||||
def start(
|
||||
self,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
"""Attempt to start the profiler, accounting for delayed starts."""
|
||||
if self._active:
|
||||
logger.debug(
|
||||
"start_profile received when profiler is already active. "
|
||||
"Ignoring request."
|
||||
with self._lifecycle_lock:
|
||||
if self._active:
|
||||
logger.debug(
|
||||
"start_profile received when profiler is already active. "
|
||||
"Ignoring request."
|
||||
)
|
||||
return
|
||||
validate_profile_iteration_bounds(delay_iterations, max_iterations)
|
||||
self._delay_iters = (
|
||||
self._default_delay_iters
|
||||
if delay_iterations is None
|
||||
else delay_iterations
|
||||
)
|
||||
return
|
||||
self._active = True
|
||||
if self._delay_iters == 0:
|
||||
self._call_start()
|
||||
self._max_iters = (
|
||||
self._default_max_iters if max_iterations is None else max_iterations
|
||||
)
|
||||
self._active = True
|
||||
if self._delay_iters == 0:
|
||||
self._call_start()
|
||||
|
||||
def step(self) -> None:
|
||||
"""Update the profiler state at each worker step,
|
||||
@@ -148,17 +175,19 @@ class WorkerProfiler(ABC):
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Attempt to stop the profiler, accounting for overlapped calls."""
|
||||
if not self._active:
|
||||
logger.debug(
|
||||
"stop_profile received when profiler is not active. Ignoring request."
|
||||
)
|
||||
return
|
||||
self._active = False
|
||||
self._active_iteration_count = 0
|
||||
self._profiling_for_iters = 0
|
||||
with self._lifecycle_lock:
|
||||
if not self._active:
|
||||
logger.debug(
|
||||
"stop_profile received when profiler is not active. "
|
||||
"Ignoring request."
|
||||
)
|
||||
return
|
||||
self._active = False
|
||||
self._active_iteration_count = 0
|
||||
self._profiling_for_iters = 0
|
||||
|
||||
if self._running:
|
||||
self._call_stop()
|
||||
if self._running:
|
||||
self._call_stop()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Ensure profiler is stopped when shutting down."""
|
||||
@@ -175,6 +204,10 @@ class WorkerProfiler(ABC):
|
||||
"""Observe graph creation for backends that attribute replay activity."""
|
||||
return nullcontext()
|
||||
|
||||
def set_output_name(self, worker_name: str) -> None:
|
||||
"""Set the output name for the next profiling session."""
|
||||
return None
|
||||
|
||||
def annotate_context_manager(self, name: str):
|
||||
"""Return a context manager to annotate profiler traces."""
|
||||
return nullcontext()
|
||||
@@ -202,6 +235,10 @@ class TorchProfilerWrapper(WorkerProfiler):
|
||||
self.local_rank = local_rank
|
||||
self.profiler_config = profiler_config
|
||||
torch_profiler_trace_dir = profiler_config.torch_profiler_dir
|
||||
self._torch_profiler_trace_dir = torch_profiler_trace_dir
|
||||
self._torch_profiler_use_gzip = profiler_config.torch_profiler_use_gzip
|
||||
self._worker_name = worker_name
|
||||
self._custom_trace_handler = on_trace_ready is not None
|
||||
if local_rank in (None, 0):
|
||||
logger.info_once(
|
||||
"Torch profiling enabled. Traces will be saved to: %s",
|
||||
@@ -276,6 +313,21 @@ class TorchProfilerWrapper(WorkerProfiler):
|
||||
self._warmup_steps_remaining = self._initial_warmup_steps_remaining
|
||||
self._version_metadata_added = False
|
||||
|
||||
@override
|
||||
def set_output_name(self, worker_name: str) -> None:
|
||||
if self._active:
|
||||
return
|
||||
self._worker_name = worker_name
|
||||
if self._custom_trace_handler:
|
||||
return
|
||||
self._profiler_kwargs["on_trace_ready"] = (
|
||||
torch.profiler.tensorboard_trace_handler(
|
||||
self._torch_profiler_trace_dir,
|
||||
worker_name=worker_name,
|
||||
use_gzip=self._torch_profiler_use_gzip,
|
||||
)
|
||||
)
|
||||
|
||||
def _build_profiler_table(
|
||||
self,
|
||||
sort_key: str,
|
||||
@@ -293,13 +345,15 @@ class TorchProfilerWrapper(WorkerProfiler):
|
||||
row_limit=row_limit,
|
||||
)
|
||||
|
||||
def _write_profiler_table(self, rank: int, table: str) -> None:
|
||||
def _write_profiler_table(self, table: str) -> None:
|
||||
profiler_dir = self.profiler_config.torch_profiler_dir
|
||||
|
||||
# Skip file write for URI paths (gs://, s3://, etc.)
|
||||
# as standard file I/O doesn't work with URI schemes
|
||||
if not _is_uri_path(profiler_dir):
|
||||
profiler_out_file = f"{profiler_dir}/profiler_out_{rank}.txt"
|
||||
profiler_out_file = os.path.join(
|
||||
profiler_dir, f"{self._worker_name}.profiler_out.txt"
|
||||
)
|
||||
with open(profiler_out_file, "w") as f:
|
||||
print(table, file=f)
|
||||
|
||||
@@ -344,7 +398,7 @@ class TorchProfilerWrapper(WorkerProfiler):
|
||||
rank = self.local_rank
|
||||
if self.dump_device_time_total:
|
||||
table = self._build_profiler_table(sort_key="self_device_time_total")
|
||||
self._write_profiler_table(rank, table)
|
||||
self._write_profiler_table(table)
|
||||
|
||||
# only print profiler results on rank 0
|
||||
if rank == 0:
|
||||
@@ -354,7 +408,7 @@ class TorchProfilerWrapper(WorkerProfiler):
|
||||
table = self._build_profiler_table(
|
||||
sort_key="self_cpu_time_total", row_limit=50
|
||||
)
|
||||
self._write_profiler_table(rank, table)
|
||||
self._write_profiler_table(table)
|
||||
|
||||
# only print profiler results on rank 0
|
||||
if rank == 0:
|
||||
@@ -494,6 +548,7 @@ class ProtonProfilerWrapper(WorkerProfiler):
|
||||
def has_cuda_graph_session(self) -> bool:
|
||||
return self._graph_session
|
||||
|
||||
@override
|
||||
def set_output_name(self, worker_name: str) -> None:
|
||||
"""Set the next run's output name after startup graph capture."""
|
||||
if self._active:
|
||||
@@ -701,6 +756,29 @@ def create_worker_profiler(
|
||||
return ProtonProfilerWrapper(profiler_config, worker_name=worker_name)
|
||||
|
||||
|
||||
def create_frontend_profiler(
|
||||
profiler_config: ProfilerConfig, *, worker_name: str
|
||||
) -> TorchProfilerWrapper:
|
||||
"""Create the CPU-only frontend profiler, which runs for the whole session
|
||||
rather than following engine iterations."""
|
||||
logger.info(
|
||||
"Torch profiler enabled. AsyncLLM CPU traces will be collected under %s",
|
||||
profiler_config.torch_profiler_dir,
|
||||
)
|
||||
return TorchProfilerWrapper(
|
||||
replace(
|
||||
profiler_config,
|
||||
delay_iterations=0,
|
||||
max_iterations=0,
|
||||
wait_iterations=0,
|
||||
warmup_iterations=0,
|
||||
),
|
||||
worker_name=worker_name,
|
||||
local_rank=0,
|
||||
activities=["CPU"],
|
||||
)
|
||||
|
||||
|
||||
def create_graph_capture_profiler(
|
||||
profiler_config: ProfilerConfig, global_rank: int
|
||||
) -> WorkerProfiler | None:
|
||||
|
||||
+65
-26
@@ -13,6 +13,10 @@ import vllm.envs as envs
|
||||
from vllm import TokensPrompt
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.kv_events import KVEventsConfig
|
||||
from vllm.config.profiler import (
|
||||
validate_profile_iteration_bounds,
|
||||
validate_profile_prefix,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
WeightTransferInitRequest,
|
||||
WeightTransferUpdateRequest,
|
||||
@@ -23,6 +27,7 @@ from vllm.entrypoints.serve.elastic_ep.middleware import set_scaling_elastic_ep
|
||||
from vllm.exceptions import (
|
||||
GracefulHTTPError,
|
||||
MaxQueuedTokensError,
|
||||
ProfilerAlreadyActiveError,
|
||||
QueueOverflowError,
|
||||
VLLMClientError,
|
||||
VLLMValidationError,
|
||||
@@ -33,7 +38,7 @@ from vllm.lora.request import LoRARequest
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
|
||||
from vllm.outputs import STREAM_FINISHED, PoolingRequestOutput, RequestOutput
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.profiler.wrapper import TorchProfilerWrapper
|
||||
from vllm.profiler.wrapper import TorchProfilerWrapper, create_frontend_profiler
|
||||
from vllm.renderers import renderer_from_config
|
||||
from vllm.renderers.inputs.preprocess import extract_prompt_components
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
@@ -211,24 +216,27 @@ class AsyncLLM(EngineClient):
|
||||
pass
|
||||
|
||||
self.profiler = profiler
|
||||
configured_activities = vllm_config.profiler_config.torch_profiler_activities
|
||||
self._frontend_profiler_injected = profiler is not None
|
||||
self._profile_lock = asyncio.Lock()
|
||||
self._profile_session_guard_enabled = client_count == 1
|
||||
self._profile_session_active = False
|
||||
if (
|
||||
vllm_config.profiler_config.profiler == "torch"
|
||||
and not vllm_config.profiler_config.ignore_frontend
|
||||
and (configured_activities is None or "CPU" in configured_activities)
|
||||
not self._frontend_profiler_injected
|
||||
and vllm_config.profiler_config.should_profile_frontend
|
||||
):
|
||||
profiler_dir = vllm_config.profiler_config.torch_profiler_dir
|
||||
logger.info(
|
||||
"Torch profiler enabled. AsyncLLM CPU traces will be collected under %s", # noqa: E501
|
||||
profiler_dir,
|
||||
)
|
||||
worker_name = f"{socket.gethostname()}_{os.getpid()}.async_llm"
|
||||
self.profiler = TorchProfilerWrapper(
|
||||
vllm_config.profiler_config,
|
||||
worker_name=worker_name,
|
||||
local_rank=0,
|
||||
activities=["CPU"],
|
||||
)
|
||||
if self._profile_session_guard_enabled:
|
||||
self._frontend_profiler_worker_name = (
|
||||
f"{socket.gethostname()}_{os.getpid()}.async_llm"
|
||||
)
|
||||
self.profiler = create_frontend_profiler(
|
||||
vllm_config.profiler_config,
|
||||
worker_name=self._frontend_profiler_worker_name,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"Frontend CPU profiling is disabled when multiple API server "
|
||||
"processes share an engine."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(
|
||||
@@ -1081,17 +1089,48 @@ class AsyncLLM(EngineClient):
|
||||
if self.errored:
|
||||
raise self.dead_error
|
||||
|
||||
async def start_profile(self, profile_prefix: str | None = None) -> None:
|
||||
coros = [self.engine_core.profile_async(True, profile_prefix)]
|
||||
if self.profiler is not None:
|
||||
coros.append(asyncio.to_thread(self.profiler.start))
|
||||
await asyncio.gather(*coros)
|
||||
async def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
async with self._profile_lock:
|
||||
if self._profile_session_guard_enabled and self._profile_session_active:
|
||||
raise ProfilerAlreadyActiveError()
|
||||
validate_profile_prefix(profile_prefix)
|
||||
validate_profile_iteration_bounds(delay_iterations, max_iterations)
|
||||
|
||||
if self._profile_session_guard_enabled:
|
||||
self._profile_session_active = True
|
||||
# A cancelled start may still take effect, so only a reported
|
||||
# engine failure clears the session; otherwise /stop_profile is needed.
|
||||
try:
|
||||
await self.engine_core.profile_async(
|
||||
True,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
except Exception:
|
||||
self._profile_session_active = False
|
||||
raise
|
||||
if self.profiler is not None:
|
||||
if not self._frontend_profiler_injected:
|
||||
worker_name = self._frontend_profiler_worker_name
|
||||
if profile_prefix is not None:
|
||||
worker_name = f"{profile_prefix}_{worker_name}"
|
||||
self.profiler.set_output_name(worker_name)
|
||||
await asyncio.to_thread(self.profiler.start)
|
||||
|
||||
async def stop_profile(self) -> None:
|
||||
coros = [self.engine_core.profile_async(False)]
|
||||
if self.profiler is not None:
|
||||
coros.append(asyncio.to_thread(self.profiler.stop))
|
||||
await asyncio.gather(*coros)
|
||||
async with self._profile_lock:
|
||||
coros = [self.engine_core.profile_async(False)]
|
||||
if self.profiler is not None:
|
||||
coros.append(asyncio.to_thread(self.profiler.stop))
|
||||
await asyncio.gather(*coros)
|
||||
self._profile_session_active = False
|
||||
|
||||
async def reset_mm_cache(self) -> None:
|
||||
# Join the background MM warmup first: the mm_processor_cache is not
|
||||
|
||||
+13
-2
@@ -810,8 +810,19 @@ class EngineCore:
|
||||
cleanup_dist_env_and_memory()
|
||||
logger.debug_once("[shutdown] EngineCore: local resource teardown complete")
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
|
||||
self.model_executor.profile(is_start, profile_prefix)
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
self.model_executor.profile(
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
|
||||
def reset_mm_cache(self):
|
||||
# NOTE: Since this is mainly for debugging, we don't attempt to
|
||||
|
||||
@@ -181,7 +181,13 @@ class EngineCoreClient(ABC):
|
||||
def add_request(self, request: EngineCoreRequest) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def reset_mm_cache(self) -> None:
|
||||
@@ -275,7 +281,11 @@ class EngineCoreClient(ABC):
|
||||
raise NotImplementedError
|
||||
|
||||
async def profile_async(
|
||||
self, is_start: bool = True, profile_prefix: str | None = None
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -392,8 +402,19 @@ class InprocClient(EngineCoreClient):
|
||||
if self._finalizer.detach() is not None:
|
||||
self.engine_core.shutdown()
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
self.engine_core.profile(is_start, profile_prefix)
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
self.engine_core.profile(
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
|
||||
def reset_mm_cache(self) -> None:
|
||||
self.engine_core.reset_mm_cache()
|
||||
@@ -1019,8 +1040,20 @@ class SyncMPClient(MPClient):
|
||||
if request_ids and not self.resources.engine_dead:
|
||||
self._send_input(EngineCoreRequestType.ABORT, request_ids)
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
self.call_utility("profile", is_start, profile_prefix)
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
self.call_utility(
|
||||
"profile",
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
|
||||
def reset_mm_cache(self) -> None:
|
||||
self.call_utility("reset_mm_cache")
|
||||
@@ -1294,9 +1327,19 @@ class AsyncMPClient(MPClient):
|
||||
return await self.call_utility_consensus_async("is_scheduler_paused")
|
||||
|
||||
async def profile_async(
|
||||
self, is_start: bool = True, profile_prefix: str | None = None
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
await self.call_utility_async("profile", is_start, profile_prefix)
|
||||
await self.call_utility_async(
|
||||
"profile",
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
|
||||
async def reset_mm_cache_async(self) -> None:
|
||||
await self.call_utility_async("reset_mm_cache")
|
||||
|
||||
@@ -12,9 +12,14 @@ from typing_extensions import TypeVar
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import ParallelConfig, VllmConfig
|
||||
from vllm.config.profiler import (
|
||||
validate_profile_iteration_bounds,
|
||||
validate_profile_prefix,
|
||||
)
|
||||
from vllm.distributed import stateless_destroy_torch_distributed_process_group
|
||||
from vllm.distributed.parallel_state import get_dp_group
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.exceptions import ProfilerAlreadyActiveError
|
||||
from vllm.inputs import EngineInput, PromptType
|
||||
from vllm.logger import configure_logging_if_needed, init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
@@ -116,6 +121,7 @@ class LLMEngine:
|
||||
log_stats=self.log_stats,
|
||||
renderer=renderer,
|
||||
)
|
||||
self._profile_session_active = False
|
||||
|
||||
self.logger_manager: StatLoggerManager | None = None
|
||||
if self.log_stats:
|
||||
@@ -358,11 +364,33 @@ class LLMEngine:
|
||||
|
||||
return processed_outputs.request_outputs
|
||||
|
||||
def start_profile(self, profile_prefix: str | None = None):
|
||||
self.engine_core.profile(True, profile_prefix)
|
||||
def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
if self._profile_session_active:
|
||||
raise ProfilerAlreadyActiveError()
|
||||
validate_profile_prefix(profile_prefix)
|
||||
validate_profile_iteration_bounds(delay_iterations, max_iterations)
|
||||
|
||||
self._profile_session_active = True
|
||||
try:
|
||||
self.engine_core.profile(
|
||||
True,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
except BaseException:
|
||||
self._profile_session_active = False
|
||||
raise
|
||||
|
||||
def stop_profile(self):
|
||||
self.engine_core.profile(False)
|
||||
self._profile_session_active = False
|
||||
|
||||
def reset_mm_cache(self):
|
||||
# Join the background MM warmup first: the mm_processor_cache is not
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import inspect
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
@@ -38,6 +39,18 @@ SLEEP_TAGS = frozenset(("weights", "kv_cache"))
|
||||
FailureCallback = Callable[[], None]
|
||||
|
||||
|
||||
def _check_worker_profile_kwargs(worker_cls: str, kwargs: dict[str, int]) -> None:
|
||||
"""Raise if the worker's ``profile`` cannot accept the given overrides."""
|
||||
params = inspect.signature(resolve_obj_by_qualname(worker_cls).profile).parameters
|
||||
if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()):
|
||||
return
|
||||
if unsupported := [name for name in kwargs if name not in params]:
|
||||
raise ValueError(
|
||||
f"Worker class {worker_cls} does not support per-session profiling "
|
||||
f"overrides: {', '.join(unsupported)}"
|
||||
)
|
||||
|
||||
|
||||
class Executor(ABC):
|
||||
"""Abstract base class for vLLM executors.
|
||||
|
||||
@@ -269,8 +282,30 @@ class Executor(ABC):
|
||||
output: list[DraftTokenIds] = self.collective_rpc("take_draft_token_ids")
|
||||
return output[0]
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
|
||||
self.collective_rpc("profile", args=(is_start, profile_prefix))
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
kwargs: dict[str, int] = {}
|
||||
if delay_iterations is not None:
|
||||
kwargs["delay_iterations"] = delay_iterations
|
||||
if max_iterations is not None:
|
||||
kwargs["max_iterations"] = max_iterations
|
||||
if kwargs:
|
||||
# Reject before dispatch: a failing collective_rpc may leave
|
||||
# unread worker replies queued.
|
||||
_check_worker_profile_kwargs(
|
||||
self.vllm_config.parallel_config.worker_cls, kwargs
|
||||
)
|
||||
self.collective_rpc(
|
||||
"profile",
|
||||
args=(is_start, profile_prefix),
|
||||
kwargs=kwargs or None,
|
||||
)
|
||||
|
||||
def save_sharded_state(
|
||||
self,
|
||||
|
||||
@@ -19,6 +19,7 @@ import torch.nn as nn
|
||||
import vllm.envs as envs
|
||||
from vllm.config import CUDAGraphMode, VllmConfig, set_current_vllm_config
|
||||
from vllm.config.compilation import CompilationMode
|
||||
from vllm.config.profiler import validate_profile_prefix
|
||||
from vllm.device_allocator import get_mem_allocator_instance
|
||||
from vllm.distributed import (
|
||||
ensure_model_parallel_initialized,
|
||||
@@ -1359,7 +1360,14 @@ class Worker(WorkerBase):
|
||||
def take_draft_token_ids(self) -> DraftTokenIds | None:
|
||||
return self.model_runner.take_draft_token_ids()
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
# Check if profiling is enabled
|
||||
if self.profiler_config is None or self.profiler_config.profiler is None:
|
||||
raise RuntimeError(
|
||||
@@ -1370,6 +1378,8 @@ class Worker(WorkerBase):
|
||||
)
|
||||
|
||||
if is_start:
|
||||
validate_profile_prefix(profile_prefix)
|
||||
|
||||
# Generate the trace name by combining prefix with comprehensive rank suffix
|
||||
from vllm.distributed.utils import get_worker_rank_suffix
|
||||
|
||||
@@ -1381,9 +1391,6 @@ class Worker(WorkerBase):
|
||||
else:
|
||||
trace_name = rank_suffix
|
||||
|
||||
if self.profiler_config.profiler == "proton" and self.profiler is not None:
|
||||
self.profiler.set_output_name(trace_name)
|
||||
|
||||
# Create the profiler wrapper only on the first start call
|
||||
if self.profiler is None:
|
||||
self.profiler = create_worker_profiler(
|
||||
@@ -1392,7 +1399,11 @@ class Worker(WorkerBase):
|
||||
local_rank=self.local_rank,
|
||||
)
|
||||
|
||||
self.profiler.start()
|
||||
self.profiler.set_output_name(trace_name)
|
||||
self.profiler.start(
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
else:
|
||||
if self.profiler is None:
|
||||
logger.warning("Profiler was not started, nothing to stop.")
|
||||
|
||||
Reference in New Issue
Block a user