[Profiler] Add Proton CUDA graph attribution for MRV2 (#51084)

Signed-off-by: Luossu <zhluosuu@outlook.com>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
鐘天楽
2026-09-14 19:02:07 +00:00
committed by GitHub
co-authored by Nick Hill
parent 5372e72a98
commit 0a5747d410
8 changed files with 657 additions and 45 deletions
+16
View File
@@ -76,6 +76,10 @@ class ProfilerConfig:
"""Optional format passed to Proton when finalizing a profile. ``None``
uses the default format for ``proton_data``."""
proton_graph_attribution: bool = False
"""Observe CUDA graph capture so replayed kernels can be attributed.
Requires Triton >= 3.7 and ``proton_data='tree'``."""
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
@@ -199,6 +203,7 @@ class ProfilerConfig:
("proton_mode", self.proton_mode, None),
("proton_hook", self.proton_hook, None),
("proton_output_format", self.proton_output_format, None),
("proton_graph_attribution", self.proton_graph_attribution, False),
)
if value != default
]
@@ -220,6 +225,17 @@ class ProfilerConfig:
if self.profiler == "proton":
output_format = self.proton_output_format
if self.proton_graph_attribution and self.proton_data != "tree":
raise ValueError("proton_graph_attribution requires proton_data='tree'")
if (
self.proton_graph_attribution
and self.proton_mode
and self.proton_mode.split(":", 1)[0].lower() == "periodic_flushing"
):
raise ValueError(
"proton_graph_attribution is incompatible with periodic_flushing: "
"both manage Proton data phases."
)
if output_format == "chrome_trace" and self.proton_data != "trace":
raise ValueError("chrome_trace output requires proton_data='trace'")
if (
+39 -12
View File
@@ -1551,18 +1551,6 @@ 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. "
@@ -1860,6 +1848,7 @@ class VllmConfig:
else:
self._validate_v1_model_runner()
self._validate_profiler_config()
self._validate_batch_sharded_sampling()
self._validate_adaptive_verification()
@@ -3042,6 +3031,44 @@ class VllmConfig:
return unsupported
def _validate_profiler_config(self) -> None:
if self.profiler_config.profiler != "proton":
return
from vllm.platforms import current_platform
if not current_platform.is_cuda():
raise ValueError("The Proton profiler currently supports NVIDIA CUDA only")
if (
self.profiler_config.proton_graph_attribution
and not self.use_v2_model_runner
):
raise ValueError(
"Proton CUDA graph attribution requires the V2 model runner."
)
has_cuda_graphs = (
self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE
or (
self.compilation_config.cudagraph_mm_encoder
and not (self.model_config and self.model_config.enforce_eager)
)
)
if not has_cuda_graphs:
return
mode = self.profiler_config.proton_mode
if mode and mode.split(":", 1)[0].lower() == "pcsampling":
raise ValueError(
"Proton PC sampling requires CUDA graphs to be disabled. "
"Use --enforce-eager."
)
if not self.profiler_config.proton_graph_attribution:
raise ValueError(
"Proton profiling with CUDA graphs requires "
"proton_graph_attribution=True to capture replayed kernels. "
"Enable attribution or use --enforce-eager."
)
def _validate_v2_model_runner(self) -> None:
"""Check for features not yet supported by the V2 model runner."""
if not HAS_TRITON:
+138 -11
View File
@@ -6,8 +6,9 @@ import inspect
import json
import os
from abc import ABC, abstractmethod
from collections.abc import Callable
from contextlib import nullcontext
from collections.abc import Callable, Iterator
from contextlib import AbstractContextManager, contextmanager, nullcontext, suppress
from glob import glob
from typing import Literal
from uuid import uuid4
@@ -160,6 +161,15 @@ class WorkerProfiler(ABC):
if self._running:
self.stop()
@property
def has_cuda_graph_session(self) -> bool:
"""Whether a capture-time session is retained to attribute replays."""
return False
def capture_cuda_graphs(self) -> AbstractContextManager[None]:
"""Observe graph creation for backends that attribute replay activity."""
return nullcontext()
def annotate_context_manager(self, name: str):
"""Return a context manager to annotate profiler traces."""
return nullcontext()
@@ -387,6 +397,7 @@ class ProtonProfilerWrapper(WorkerProfiler):
self._mode = profiler_config.proton_mode
self._hook = profiler_config.proton_hook
self._output_format = profiler_config.proton_output_format
self._graph_attribution = profiler_config.proton_graph_attribution
self._triton_version_string = getattr(triton, "__version__", "unknown")
try:
self._triton_version = Version(self._triton_version_string)
@@ -398,6 +409,13 @@ class ProtonProfilerWrapper(WorkerProfiler):
# worker cannot overwrite profiles left by an earlier server process.
self._instance_id = f"pid{os.getpid()}_{uuid4().hex}"
self._run_id = 0
self._graph_session = False
self._phase = 0
self._active_output_path: str | None = None
self._session_storage_path = os.path.join(
self._output_dir,
f".proton_cuda_graph_session_{worker_name}_{self._instance_id}",
)
logger.info_once(
"Proton profiling enabled. Output will be saved under: %s",
@@ -412,6 +430,10 @@ class ProtonProfilerWrapper(WorkerProfiler):
)
def _validate_capabilities(self) -> None:
if self._graph_attribution:
self._require_triton_version(
"CUDA graph attribution", _TRITON_PROTON_3_7_VERSION
)
if self._output_format is not None:
parameters = inspect.signature(self._proton.finalize).parameters
supports_output_format = "output_format" in parameters or any(
@@ -428,7 +450,7 @@ class ProtonProfilerWrapper(WorkerProfiler):
self._require_triton_version(
"hatchet_msgpack output", _TRITON_PROTON_3_7_VERSION
)
if self._mode and self._mode.split(":", 1)[0] == "periodic_flushing":
if self._mode and self._mode.split(":", 1)[0].lower() == "periodic_flushing":
self._require_triton_version(
"periodic flushing", _TRITON_PROTON_3_7_VERSION
)
@@ -447,28 +469,112 @@ class ProtonProfilerWrapper(WorkerProfiler):
raise RuntimeError("Proton did not create a profiling session")
return session_id
@property
def has_cuda_graph_session(self) -> bool:
return self._graph_session
def set_output_name(self, worker_name: str) -> None:
"""Set the next run's output name after startup graph capture."""
if self._active:
return
self._output_path = os.path.join(self._output_dir, f"proton_{worker_name}")
@override
@contextmanager
def capture_cuda_graphs(self) -> Iterator[None]:
"""Keep a Proton session active while vLLM captures CUDA graphs."""
if not self._graph_attribution:
yield
return
if self._session_id is None:
self._session_id = self._create_session(self._session_storage_path)
else:
self._proton.activate(session=self._session_id)
self._graph_session = True
try:
yield
finally:
captured_phase = self._phase
try:
self._phase = self._proton.data.advance_phase(self._session_id)
finally:
self._proton.deactivate(session=self._session_id, flushing=True)
self._proton.data.clear(self._session_id, captured_phase)
@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._active_output_path = (
f"{self._output_path}_{self._instance_id}_run{self._run_id}"
)
self._run_id += 1
if self._graph_session:
assert self._session_id is not None
self._proton.activate(session=self._session_id)
else:
self._session_id = self._create_session(self._active_output_path)
def _write_graph_phase(self, phase: int) -> None:
assert self._active_output_path is not None
output_format = self._output_format or "hatchet"
output_path = f"{self._active_output_path}.{output_format}"
if output_format == "hatchet_msgpack":
with open(output_path, "wb") as output_file:
output_file.write(
self._proton.data.get_msgpack(self._session_id, phase)
)
else:
with open(output_path, "w", encoding="utf-8") as output_file:
json.dump(self._proton.data.get(self._session_id, phase), output_file)
def _finalize_session(self, session_id: int) -> None:
if self._output_format is None:
self._proton.finalize(session=session_id)
else:
self._proton.finalize(session=session_id, output_format=self._output_format)
@override
def _stop(self) -> None:
assert self._session_id is not None
session_id = self._session_id
if self._graph_session:
completed_phase = self._phase
try:
self._phase = self._proton.data.advance_phase(session_id)
finally:
self._proton.deactivate(session=session_id, flushing=True)
try:
self._write_graph_phase(completed_phase)
finally:
self._proton.data.clear(session_id, completed_phase)
self._active_output_path = None
return
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
)
self._finalize_session(session_id)
finally:
self._session_id = None
self._active_output_path = None
@override
def shutdown(self) -> None:
super().shutdown()
if self._graph_session and self._session_id is not None:
session_id = self._session_id
self._session_id = None
try:
self._finalize_session(session_id)
except Exception:
logger.exception(
"Failed to finalize Proton CUDA graph session during shutdown."
)
finally:
for output_path in glob(f"{self._session_storage_path}.*"):
with suppress(FileNotFoundError):
os.remove(output_path)
@override
def annotate_context_manager(self, name: str):
@@ -496,3 +602,24 @@ class CudaProfilerWrapper(WorkerProfiler):
@override
def annotate_context_manager(self, name: str):
return torch.cuda.nvtx.range(name)
def create_graph_capture_profiler(
profiler_config: ProfilerConfig, global_rank: int
) -> WorkerProfiler | None:
"""Create a profiler to observe CUDA graph capture, if configured.
Applies only to backends that attribute graph replay activity which
need a session around capture (Proton with ``proton_graph_attribution``).
"""
if (
profiler_config.profiler == "proton"
and profiler_config.proton_graph_attribution
):
from vllm.distributed.utils import get_worker_rank_suffix
return ProtonProfilerWrapper(
profiler_config,
worker_name=get_worker_rank_suffix(global_rank=global_rank),
)
return None
+10
View File
@@ -987,6 +987,16 @@ class GPUModelRunner(LoRAModelRunnerMixin):
"""Estimate the GPU memory required to capture CUDA graphs."""
return _profile_cudagraph_memory(self)
def needs_cudagraph_capture(self) -> bool:
"""Whether capture_model() has any CUDA graphs left to capture."""
return (
self.model_state.supports_mm_inputs
and self.model_state.encoder_runner.has_cudagraph()
) or (
self.cudagraph_manager is not None
and self.cudagraph_manager.needs_capture()
)
@torch.inference_mode()
def capture_model(self, *, profile_only: bool = False) -> int:
assert self.cudagraph_manager is not None
+26 -3
View File
@@ -9,7 +9,7 @@ from collections.abc import Callable
from contextlib import AbstractContextManager, contextmanager, nullcontext
from datetime import timedelta
from types import NoneType
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, cast
import numpy as np
import regex as re
@@ -64,6 +64,7 @@ from vllm.profiler.wrapper import (
CudaProfilerWrapper,
ProtonProfilerWrapper,
TorchProfilerWrapper,
create_graph_capture_profiler,
)
from vllm.sequence import IntermediateTensors
from vllm.tasks import SupportedTask
@@ -142,6 +143,7 @@ def maybe_rocm_profiling_fallback(profile_result: MemoryProfilingResult) -> int
if TYPE_CHECKING:
from vllm.device_allocator.sleep_mode_backend import SleepModeBackend
from vllm.model_executor.model_loader.tensorizer import TensorizerConfig
from vllm.v1.worker.gpu.model_runner import GPUModelRunner as GPUModelRunnerV2
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
@@ -810,7 +812,8 @@ class Worker(WorkerBase):
cuda_graph_memory_bytes = 0
if not self.model_config.enforce_eager:
cuda_graph_memory_bytes = self.model_runner.capture_model()
with self._get_cudagraph_capture_context():
cuda_graph_memory_bytes = self.model_runner.capture_model()
# Compare actual vs estimated CUDA graph memory (if we did profiling)
if (
@@ -949,6 +952,21 @@ class Worker(WorkerBase):
encoder=self.compilation_config.encoder_compilation_time,
)
def _get_cudagraph_capture_context(self) -> AbstractContextManager[None]:
"""Let the configured profiler observe CUDA graph capture."""
if not self.use_v2_model_runner:
return nullcontext()
if self.profiler is None:
model_runner = cast("GPUModelRunnerV2", self.model_runner)
if not model_runner.needs_cudagraph_capture():
return nullcontext()
self.profiler = create_graph_capture_profiler(
self.profiler_config, global_rank=self.rank
)
if self.profiler is None:
return nullcontext()
return self.profiler.capture_cuda_graphs()
def reset_mm_cache(self) -> None:
self.model_runner.reset_mm_cache()
@@ -1248,6 +1266,9 @@ class Worker(WorkerBase):
else:
trace_name = rank_suffix
if profiler_type == "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:
if profiler_type == "torch":
@@ -1284,7 +1305,9 @@ class Worker(WorkerBase):
try:
self.profiler.stop()
finally:
if self.profiler_config.profiler == "proton":
if self.profiler_config.profiler == "proton" and not (
self.profiler.has_cuda_graph_session
):
# Proton output names are fixed when the wrapper is constructed.
# Recreate it so the next profile_prefix is honored.
self.profiler = None
@@ -70,6 +70,9 @@ class MMEncoderModelRunner(GPUModelRunner):
def capture_model(self, *, profile_only: bool = False) -> int:
return 0
def needs_cudagraph_capture(self) -> bool:
return False
def _dummy_run(
self, *args: Any, **kwargs: Any
) -> tuple[torch.Tensor, torch.Tensor]: