[Profiler] Add minimal Triton Proton profiling backend (#48789)
Signed-off-by: Luossu <zhluosuu@outlook.com>
This commit is contained in:
@@ -147,6 +147,11 @@ def main(args: argparse.Namespace):
|
||||
)
|
||||
elif profiler_config.profiler == "cuda":
|
||||
print("Profiling with cuda profiler ...")
|
||||
elif profiler_config.profiler == "proton":
|
||||
print(
|
||||
"Profiling with Proton (results will be saved under"
|
||||
f" {profiler_config.proton_profiler_dir})..."
|
||||
)
|
||||
run_to_completion(do_profile=True)
|
||||
return
|
||||
|
||||
|
||||
+80
-7
@@ -13,7 +13,12 @@ from vllm.utils.hashing import safe_hash
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
ProfilerKind = Literal["torch", "cuda"]
|
||||
ProfilerKind = Literal["torch", "cuda", "proton"]
|
||||
ProtonBackend = Literal["cupti"]
|
||||
ProtonContext = Literal["shadow", "python"]
|
||||
ProtonData = Literal["tree", "trace"]
|
||||
ProtonHook = Literal["triton"]
|
||||
ProtonOutputFormat = Literal["hatchet", "hatchet_msgpack", "chrome_trace"]
|
||||
|
||||
|
||||
def _is_uri_path(path: str) -> bool:
|
||||
@@ -38,13 +43,39 @@ class ProfilerConfig:
|
||||
"""Which profiler to use. Defaults to None. Options are:
|
||||
|
||||
- 'torch': Use PyTorch profiler.
|
||||
- 'cuda': Use CUDA profiler."""
|
||||
- 'cuda': Use CUDA profiler.
|
||||
- 'proton': Use Triton Proton profiler."""
|
||||
|
||||
torch_profiler_dir: str = ""
|
||||
"""Directory to save torch profiler traces. Both AsyncLLM's CPU traces and
|
||||
worker's traces (CPU & GPU) will be saved under this directory. Note that
|
||||
it must be an absolute path."""
|
||||
|
||||
proton_profiler_dir: str = ""
|
||||
"""Directory to save Triton Proton profiles. Each worker writes a
|
||||
separate rank-qualified file."""
|
||||
|
||||
proton_context: ProtonContext = "shadow"
|
||||
"""Proton context source. ``shadow`` records explicit scopes with low
|
||||
overhead; ``python`` records Python call stacks."""
|
||||
|
||||
proton_data: ProtonData = "tree"
|
||||
"""Proton output type. ``tree`` produces Hatchet data and ``trace``
|
||||
produces a Chrome trace."""
|
||||
|
||||
proton_backend: ProtonBackend | None = None
|
||||
"""Proton GPU backend. ``None`` lets Proton select CUPTI automatically."""
|
||||
|
||||
proton_mode: str | None = None
|
||||
"""Optional backend-specific Proton mode string, such as ``pcsampling``."""
|
||||
|
||||
proton_hook: ProtonHook | None = None
|
||||
"""Optional Proton hook. Use ``triton`` to add Triton launch metadata."""
|
||||
|
||||
proton_output_format: ProtonOutputFormat | None = None
|
||||
"""Optional format passed to Proton when finalizing a profile. ``None``
|
||||
uses the default format for ``proton_data``."""
|
||||
|
||||
torch_profiler_with_stack: bool = True
|
||||
"""If `True`, enables stack tracing in the torch profiler. Enabled by default
|
||||
as it is useful for debugging. Can be disabled via
|
||||
@@ -142,18 +173,60 @@ class ProfilerConfig:
|
||||
"while ignore_frontend is False may result in high overhead."
|
||||
)
|
||||
|
||||
profiler_dir = self.torch_profiler_dir
|
||||
if profiler_dir and self.profiler != "torch":
|
||||
torch_profiler_dir = self.torch_profiler_dir
|
||||
if torch_profiler_dir and self.profiler != "torch":
|
||||
raise ValueError(
|
||||
"torch_profiler_dir is only applicable when profiler is set to 'torch'"
|
||||
)
|
||||
if self.profiler == "torch" and not profiler_dir:
|
||||
if self.profiler == "torch" and not torch_profiler_dir:
|
||||
raise ValueError("torch_profiler_dir must be set when profiler is 'torch'")
|
||||
|
||||
# Support any URI scheme (gs://, s3://, hdfs://, etc.)
|
||||
# These paths should not be converted to absolute paths
|
||||
if profiler_dir and not _is_uri_path(profiler_dir):
|
||||
self.torch_profiler_dir = os.path.abspath(os.path.expanduser(profiler_dir))
|
||||
if torch_profiler_dir and not _is_uri_path(torch_profiler_dir):
|
||||
self.torch_profiler_dir = os.path.abspath(
|
||||
os.path.expanduser(torch_profiler_dir)
|
||||
)
|
||||
|
||||
proton_profiler_dir = self.proton_profiler_dir
|
||||
non_default_proton_options = [
|
||||
name
|
||||
for name, value, default in (
|
||||
("proton_profiler_dir", proton_profiler_dir, ""),
|
||||
("proton_context", self.proton_context, "shadow"),
|
||||
("proton_data", self.proton_data, "tree"),
|
||||
("proton_backend", self.proton_backend, None),
|
||||
("proton_mode", self.proton_mode, None),
|
||||
("proton_hook", self.proton_hook, None),
|
||||
("proton_output_format", self.proton_output_format, None),
|
||||
)
|
||||
if value != default
|
||||
]
|
||||
if self.profiler != "proton" and non_default_proton_options:
|
||||
options = ", ".join(non_default_proton_options)
|
||||
raise ValueError(
|
||||
f"{options} only applicable when profiler is set to 'proton'"
|
||||
)
|
||||
if self.profiler == "proton" and not proton_profiler_dir:
|
||||
raise ValueError(
|
||||
"proton_profiler_dir must be set when profiler is 'proton'"
|
||||
)
|
||||
if proton_profiler_dir:
|
||||
if _is_uri_path(proton_profiler_dir):
|
||||
raise ValueError("proton_profiler_dir must be a local directory")
|
||||
self.proton_profiler_dir = os.path.abspath(
|
||||
os.path.expanduser(proton_profiler_dir)
|
||||
)
|
||||
|
||||
if self.profiler == "proton":
|
||||
output_format = self.proton_output_format
|
||||
if output_format == "chrome_trace" and self.proton_data != "trace":
|
||||
raise ValueError("chrome_trace output requires proton_data='trace'")
|
||||
if (
|
||||
output_format in ("hatchet", "hatchet_msgpack")
|
||||
and self.proton_data != "tree"
|
||||
):
|
||||
raise ValueError(f"{output_format} output requires proton_data='tree'")
|
||||
|
||||
if self.capture_torch_profiler and self.profiler != "torch":
|
||||
raise ValueError(
|
||||
|
||||
@@ -1269,6 +1269,18 @@ class VllmConfig:
|
||||
self.compilation_config.mode = CompilationMode.NONE
|
||||
self.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
|
||||
|
||||
if self.profiler_config.profiler == "proton":
|
||||
if not current_platform.is_cuda():
|
||||
raise ValueError(
|
||||
"The Proton profiler currently supports NVIDIA CUDA only"
|
||||
)
|
||||
if self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE:
|
||||
raise ValueError(
|
||||
"The Proton profiler requires CUDA graphs to be disabled. "
|
||||
"Use --enforce-eager or set "
|
||||
"--compilation-config.cudagraph_mode=none."
|
||||
)
|
||||
|
||||
if os.environ.get("TORCH_COMPILE_DISABLE") == "1":
|
||||
logger.warning_once(
|
||||
"TORCH_COMPILE_DISABLE is set, disabling torch.compile. "
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import importlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from contextlib import nullcontext
|
||||
from typing import Literal
|
||||
from uuid import uuid4
|
||||
|
||||
import torch
|
||||
from packaging.version import InvalidVersion, Version
|
||||
from typing_extensions import override
|
||||
|
||||
import vllm.version
|
||||
@@ -17,6 +22,8 @@ from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_TRITON_PROTON_3_7_VERSION = Version("3.7.0")
|
||||
|
||||
|
||||
class WorkerProfiler(ABC):
|
||||
def __init__(self, profiler_config: ProfilerConfig) -> None:
|
||||
@@ -43,6 +50,11 @@ class WorkerProfiler(ABC):
|
||||
self._profiling_for_iters = 0
|
||||
self._running = False
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
"""Whether the underlying profiler is currently collecting data."""
|
||||
return self._running
|
||||
|
||||
@abstractmethod
|
||||
def _start(self) -> None:
|
||||
"""Start the profiler."""
|
||||
@@ -340,6 +352,123 @@ class TorchProfilerWrapper(WorkerProfiler):
|
||||
return torch.profiler.record_function(name)
|
||||
|
||||
|
||||
class ProtonProfilerWrapper(WorkerProfiler):
|
||||
"""Worker profiler backed by :mod:`triton.profiler` (Proton)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
profiler_config: ProfilerConfig,
|
||||
worker_name: str,
|
||||
) -> None:
|
||||
super().__init__(profiler_config)
|
||||
|
||||
try:
|
||||
self._proton = importlib.import_module("triton.profiler")
|
||||
triton = importlib.import_module("triton")
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"The Proton profiler requires a Triton installation with "
|
||||
"triton.profiler support."
|
||||
) from exc
|
||||
|
||||
self._output_dir = profiler_config.proton_profiler_dir
|
||||
self._output_path = os.path.join(self._output_dir, f"proton_{worker_name}")
|
||||
self._context = profiler_config.proton_context
|
||||
self._data = profiler_config.proton_data
|
||||
self._backend = profiler_config.proton_backend
|
||||
self._mode = profiler_config.proton_mode
|
||||
self._hook = profiler_config.proton_hook
|
||||
self._output_format = profiler_config.proton_output_format
|
||||
self._triton_version_string = getattr(triton, "__version__", "unknown")
|
||||
try:
|
||||
self._triton_version = Version(self._triton_version_string)
|
||||
except InvalidVersion:
|
||||
self._triton_version = None
|
||||
self._validate_capabilities()
|
||||
self._session_id: int | None = None
|
||||
# Qualify output names by process and wrapper instance so a new
|
||||
# worker cannot overwrite profiles left by an earlier server process.
|
||||
self._instance_id = f"pid{os.getpid()}_{uuid4().hex}"
|
||||
self._run_id = 0
|
||||
|
||||
logger.info_once(
|
||||
"Proton profiling enabled. Output will be saved under: %s",
|
||||
self._output_dir,
|
||||
)
|
||||
|
||||
def _require_triton_version(self, feature: str, minimum: Version) -> None:
|
||||
if self._triton_version is None or self._triton_version < minimum:
|
||||
raise RuntimeError(
|
||||
f"Proton {feature} requires Triton >= {minimum}; found "
|
||||
f"{self._triton_version_string}."
|
||||
)
|
||||
|
||||
def _validate_capabilities(self) -> None:
|
||||
if self._output_format is not None:
|
||||
parameters = inspect.signature(self._proton.finalize).parameters
|
||||
supports_output_format = "output_format" in parameters or any(
|
||||
parameter.kind == inspect.Parameter.VAR_KEYWORD
|
||||
for parameter in parameters.values()
|
||||
)
|
||||
if not supports_output_format:
|
||||
raise RuntimeError(
|
||||
"The installed Triton Proton does not support selecting "
|
||||
"an output format during finalize."
|
||||
)
|
||||
|
||||
if self._output_format == "hatchet_msgpack":
|
||||
self._require_triton_version(
|
||||
"hatchet_msgpack output", _TRITON_PROTON_3_7_VERSION
|
||||
)
|
||||
if self._mode and self._mode.split(":", 1)[0] == "periodic_flushing":
|
||||
self._require_triton_version(
|
||||
"periodic flushing", _TRITON_PROTON_3_7_VERSION
|
||||
)
|
||||
|
||||
def _create_session(self, output_path: str) -> int:
|
||||
os.makedirs(self._output_dir, exist_ok=True)
|
||||
session_id = self._proton.start(
|
||||
name=output_path,
|
||||
context=self._context,
|
||||
data=self._data,
|
||||
backend=self._backend,
|
||||
mode=self._mode,
|
||||
hook=self._hook,
|
||||
)
|
||||
if session_id is None:
|
||||
raise RuntimeError("Proton did not create a profiling session")
|
||||
return session_id
|
||||
|
||||
@override
|
||||
def _start(self) -> None:
|
||||
output_path = f"{self._output_path}_{self._instance_id}_run{self._run_id}"
|
||||
self._session_id = self._create_session(output_path)
|
||||
self._run_id += 1
|
||||
|
||||
@override
|
||||
def _stop(self) -> None:
|
||||
assert self._session_id is not None
|
||||
session_id = self._session_id
|
||||
try:
|
||||
self._proton.deactivate(session=session_id)
|
||||
finally:
|
||||
try:
|
||||
if self._output_format is None:
|
||||
self._proton.finalize(session=session_id)
|
||||
else:
|
||||
self._proton.finalize(
|
||||
session=session_id, output_format=self._output_format
|
||||
)
|
||||
finally:
|
||||
self._session_id = None
|
||||
|
||||
@override
|
||||
def annotate_context_manager(self, name: str):
|
||||
if not self._running:
|
||||
return nullcontext()
|
||||
return self._proton.scope(name)
|
||||
|
||||
|
||||
class CudaProfilerWrapper(WorkerProfiler):
|
||||
def __init__(self, profiler_config: ProfilerConfig) -> None:
|
||||
super().__init__(profiler_config)
|
||||
|
||||
@@ -55,7 +55,11 @@ from vllm.lora.request import LoRARequest
|
||||
from vllm.model_executor.warmup.kernel_warmup import kernel_warmup
|
||||
from vllm.multimodal.gpu_ipc_memory import reserve_mm_ipc_gpu_memory
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.profiler.wrapper import CudaProfilerWrapper, TorchProfilerWrapper
|
||||
from vllm.profiler.wrapper import (
|
||||
CudaProfilerWrapper,
|
||||
ProtonProfilerWrapper,
|
||||
TorchProfilerWrapper,
|
||||
)
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.tasks import SupportedTask
|
||||
from vllm.tracing import instrument
|
||||
@@ -162,16 +166,12 @@ class Worker(WorkerBase):
|
||||
self._weight_update_active = False
|
||||
self._weight_update_is_draft = False
|
||||
|
||||
# Torch/CUDA profiler. Enabled and configured through profiler_config.
|
||||
# Worker profiler. Enabled and configured through profiler_config.
|
||||
# Profiler wrapper is created lazily in profile() when start is called,
|
||||
# so we have all the information needed for proper trace naming.
|
||||
self.profiler: Any | None = None
|
||||
self.profiler_config = vllm_config.profiler_config
|
||||
|
||||
# Only validate profiler config is valid, don't instantiate yet
|
||||
if self.profiler_config.profiler not in ("torch", "cuda", None):
|
||||
raise ValueError(f"Unknown profiler type: {self.profiler_config.profiler}")
|
||||
|
||||
self.use_v2_model_runner = vllm_config.use_v2_model_runner
|
||||
# pending non-blocking PP send work from the previous iteration
|
||||
self._pp_send_work: list[Handle] = []
|
||||
@@ -909,6 +909,8 @@ class Worker(WorkerBase):
|
||||
return nullcontext()
|
||||
|
||||
self.profiler.step()
|
||||
if not self.profiler.is_running:
|
||||
return nullcontext()
|
||||
|
||||
iteration_details = compute_iteration_details(scheduler_output)
|
||||
|
||||
@@ -1125,6 +1127,7 @@ class Worker(WorkerBase):
|
||||
)
|
||||
|
||||
if is_start:
|
||||
profiler_type = self.profiler_config.profiler
|
||||
# Generate the trace name by combining prefix with comprehensive rank suffix
|
||||
from vllm.distributed.utils import get_worker_rank_suffix
|
||||
|
||||
@@ -1138,7 +1141,6 @@ class Worker(WorkerBase):
|
||||
|
||||
# Create the profiler wrapper only on the first start call
|
||||
if self.profiler is None:
|
||||
profiler_type = self.profiler_config.profiler
|
||||
if profiler_type == "torch":
|
||||
self.profiler = TorchProfilerWrapper(
|
||||
self.profiler_config,
|
||||
@@ -1152,20 +1154,31 @@ class Worker(WorkerBase):
|
||||
elif profiler_type == "cuda":
|
||||
self.profiler = CudaProfilerWrapper(self.profiler_config)
|
||||
logger.debug("Starting CUDA profiler")
|
||||
elif profiler_type == "proton":
|
||||
self.profiler = ProtonProfilerWrapper(
|
||||
self.profiler_config, worker_name=trace_name
|
||||
)
|
||||
logger.debug(
|
||||
"Starting Proton profiler with trace name: %s", trace_name
|
||||
)
|
||||
else:
|
||||
# Config validation should prevent this code being reached
|
||||
raise ValueError(
|
||||
f"Invalid profiler value of {self.profiler_config.profiler}"
|
||||
)
|
||||
|
||||
# If profiler already initialized, restart profiling but keep
|
||||
# the original trace name from the first initialization.
|
||||
self.profiler.start()
|
||||
else:
|
||||
if self.profiler is None:
|
||||
logger.warning("Profiler was not started, nothing to stop.")
|
||||
return
|
||||
self.profiler.stop()
|
||||
try:
|
||||
self.profiler.stop()
|
||||
finally:
|
||||
if self.profiler_config.profiler == "proton":
|
||||
# Proton output names are fixed when the wrapper is constructed.
|
||||
# Recreate it so the next profile_prefix is honored.
|
||||
self.profiler = None
|
||||
|
||||
def execute_dummy_batch(self) -> None:
|
||||
num_tokens = getattr(self.model_runner, "uniform_decode_query_len", 1)
|
||||
|
||||
Reference in New Issue
Block a user