From 7144935ec5cb4b9c50f11541d9c2572c01a5f2d6 Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Thu, 27 Aug 2026 09:06:17 -0500 Subject: [PATCH 1/9] Add cuda graph capture profiling support for v2 runner Signed-off-by: Deval Shah --- tests/v1/worker/test_gpu_profiler.py | 107 +++++++++++++++++++++- vllm/profiler/graph_capture.py | 127 ++++++++++++++++++++++++++ vllm/v1/worker/encoder_cudagraph.py | 2 + vllm/v1/worker/gpu/cudagraph_utils.py | 14 ++- vllm/v1/worker/gpu/model_runner.py | 44 ++++++--- vllm/v1/worker/gpu_model_runner.py | 8 +- 6 files changed, 281 insertions(+), 21 deletions(-) create mode 100644 vllm/profiler/graph_capture.py diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index 347b5b379adf..046af86b7daf 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -1,12 +1,13 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os -from contextlib import nullcontext +from contextlib import contextmanager, nullcontext from types import SimpleNamespace from unittest.mock import MagicMock, Mock, call, patch from uuid import UUID import pytest +import torch from pydantic import ValidationError from vllm.config import ( @@ -17,6 +18,8 @@ ) from vllm.config.profiler import _is_uri_path from vllm.platforms import current_platform +from vllm.profiler import graph_capture +from vllm.profiler.graph_capture import graph_capture_profiler, graph_capture_step from vllm.profiler.wrapper import ProtonProfilerWrapper, WorkerProfiler from vllm.v1.core.sched.output import CachedRequestData from vllm.v1.worker.gpu_model_runner import GPUModelRunner @@ -349,6 +352,108 @@ def test_profiler_entered_during_capture(): mock_profiler.__exit__.assert_called_once() +@contextmanager +def bound_graph_capture(label_prefix=None): + """Enter a graph-capture binding backed by a mock profiler.""" + profiler = MagicMock() + with ( + patch.object(graph_capture, "_make_profiler", return_value=profiler), + graph_capture_profiler(MagicMock(), label_prefix=label_prefix), + ): + yield profiler + + +class TestGraphCaptureProfiler: + """V2 binds one profiler per subsystem; capture loops only call + graph_capture_step and inherit whichever binding is active.""" + + @pytest.fixture + def annotation(self): + with patch.object(torch.profiler, "record_function") as record_function: + yield record_function + + def test_step_is_noop_without_binding(self, annotation): + with graph_capture_step(32, "FULL"): + pass + + annotation.assert_not_called() + + @pytest.mark.parametrize( + "label_prefix,num_tokens,mode,expected", + [ + (None, 512, "PIECEWISE", "capture_512_PIECEWISE"), + ("draft", 32, "FULL", "capture_32_draft_FULL"), + ("encoder", 1024, "default", "capture_1024_encoder_default"), + ], + ) + def test_annotation_label( + self, annotation, label_prefix, num_tokens, mode, expected + ): + with bound_graph_capture(label_prefix) as profiler: + with graph_capture_step(num_tokens, mode): + pass + + annotation.assert_called_once_with(expected) + profiler.__enter__.assert_called_once() + profiler.__exit__.assert_called_once() + + def test_profiler_cycles_once_per_shape(self, annotation): + """Each shape re-enters the profiler, which is what splits capture + into one trace file per shape.""" + with bound_graph_capture() as profiler: + for num_tokens in (32, 64, 128): + with graph_capture_step(num_tokens, "FULL"): + pass + + assert profiler.__enter__.call_count == 3 + assert profiler.__exit__.call_count == 3 + assert annotation.call_count == 3 + + def test_binding_cleared_when_capture_raises(self): + with pytest.raises(RuntimeError): + with bound_graph_capture(): + raise RuntimeError("capture failed") + + assert graph_capture._active_binding.get() is None + + @pytest.mark.parametrize( + "subsystem,expected", + [ + (None, "graph_capture_rank_0"), + ("encoder", "graph_capture_rank_0_encoder"), + ("speculator", "graph_capture_rank_0_speculator"), + ], + ) + def test_trace_file_name_per_subsystem(self, subsystem, expected): + config = MagicMock() + config.profiler_config.capture_torch_profiler = True + config.profiler_config.torch_profiler_dir = "/traces" + + with ( + patch.object( + graph_capture, "get_world_group", return_value=MagicMock(local_rank=0) + ), + patch.object(torch.profiler, "profile"), + patch.object(torch.profiler, "tensorboard_trace_handler") as handler, + ): + graph_capture._make_profiler(config, subsystem) + + assert handler.call_args.args == ("/traces/capture_traces",) + assert handler.call_args.kwargs["worker_name"] == expected + + @pytest.mark.parametrize("local_rank,enabled", [(0, False), (1, True)]) + def test_no_profiler_when_disabled_or_off_rank(self, local_rank, enabled): + config = MagicMock() + config.profiler_config.capture_torch_profiler = enabled + + with patch.object( + graph_capture, + "get_world_group", + return_value=MagicMock(local_rank=local_rank), + ): + assert isinstance(graph_capture._make_profiler(config, None), nullcontext) + + def make_proton(session_id: int | None = 7): return SimpleNamespace( start=Mock(return_value=session_id), diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py new file mode 100644 index 000000000000..e9c6e67176b3 --- /dev/null +++ b/vllm/profiler/graph_capture.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Torch profiler helpers for CUDA/HIP graph capture tracing. + +Graph capture is driven by three subsystems (encoder, decoder and speculator) +that reach the same handful of capture loops by different routes. +``graph_capture_profiler`` binds one profiler around a subsystem's capture, +and ``graph_capture_step`` picks that binding up inside whichever capture loop +ends up running. Capture loops therefore carry no profiler plumbing, and a new +speculator built on an existing capture loop is traced without further changes. +""" + +from __future__ import annotations + +import contextvars +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager, nullcontext +from dataclasses import dataclass +from typing import Any + +import torch + +from vllm.config import VllmConfig +from vllm.distributed.parallel_state import get_world_group +from vllm.logger import init_logger + +logger = init_logger(__name__) + + +@dataclass(frozen=True) +class _CaptureBinding: + profiler: AbstractContextManager[Any] + label_prefix: str | None + + +_active_binding: contextvars.ContextVar[_CaptureBinding | None] = ( + contextvars.ContextVar("vllm_graph_capture_binding", default=None) +) + + +def _make_profiler( + vllm_config: VllmConfig, + subsystem: str | None, +) -> AbstractContextManager[Any]: + profiler_config = vllm_config.profiler_config + local_rank = get_world_group().local_rank + if local_rank != 0 or not profiler_config.capture_torch_profiler: + logger.info_once( + "Rank %d: Torch profiler disabled for CUDA graph capture", local_rank + ) + return nullcontext() + + trace_dir = profiler_config.torch_profiler_dir + "/capture_traces" + worker_name = f"graph_capture_rank_{local_rank}" + if subsystem: + worker_name += f"_{subsystem}" + logger.info_once( + "Rank %d: Torch profiler enabled for %s CUDA graph capture, " + "traces will be saved to: %s", + local_rank, + subsystem or "decoder", + trace_dir, + ) + return torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ], + record_shapes=True, + profile_memory=True, + with_stack=True, + on_trace_ready=torch.profiler.tensorboard_trace_handler( + trace_dir, + worker_name=worker_name, + use_gzip=True, + ), + ) + + +@contextmanager +def graph_capture_profiler( + vllm_config: VllmConfig, + subsystem: str | None = None, + label_prefix: str | None = None, +) -> Iterator[None]: + """Bind a graph-capture profiler for one subsystem's capture. + + Args: + subsystem: Suffix for the trace file name. ``"encoder"`` writes + ``graph_capture_rank_0_encoder..pt.trace.json.gz``; + the main decoder passes ``None`` and keeps the unsuffixed name. + label_prefix: Inserted into every annotation recorded inside the + block, so that e.g. speculator graphs are labelled + ``capture_32_draft_FULL`` rather than reusing the decoder's + ``capture_32_FULL``. + """ + binding = _CaptureBinding( + profiler=_make_profiler(vllm_config, subsystem), + label_prefix=label_prefix, + ) + token = _active_binding.set(binding) + try: + yield + finally: + _active_binding.reset(token) + + +@contextmanager +def graph_capture_step(num_tokens: int, mode: str) -> Iterator[None]: + """Profile the capture of a single graph shape. + + Records a ``capture_{num_tokens}_{mode}`` annotation, or + ``capture_{num_tokens}_{label_prefix}_{mode}`` when the active binding + sets a prefix. Does nothing outside a ``graph_capture_profiler`` block, so + capture loops can call this unconditionally. + """ + binding = _active_binding.get() + if binding is None: + yield + return + + if binding.label_prefix: + label = f"capture_{num_tokens}_{binding.label_prefix}_{mode}" + else: + label = f"capture_{num_tokens}_{mode}" + with binding.profiler, torch.profiler.record_function(label): + yield diff --git a/vllm/v1/worker/encoder_cudagraph.py b/vllm/v1/worker/encoder_cudagraph.py index a1b955a741b2..e07e65a3e294 100644 --- a/vllm/v1/worker/encoder_cudagraph.py +++ b/vllm/v1/worker/encoder_cudagraph.py @@ -19,6 +19,7 @@ ) from vllm.model_executor.models.utils import scatter_output_slices from vllm.model_executor.models.vision import get_load_balance_assignment +from vllm.profiler.graph_capture import graph_capture_step from vllm.utils.gpu_sync_debug import gpu_sync_allowed from vllm.utils.torch_utils import current_stream from vllm.v1.worker.encoder_cudagraph_defs import ( @@ -272,6 +273,7 @@ def _capture_budget_graph(self, token_budget: int, path: str = "default"): graph = torch.cuda.CUDAGraph() with ( + graph_capture_step(token_budget, path), torch.inference_mode(), torch.cuda.graph(graph, pool=self.graph_pool, stream=current_stream()), ): diff --git a/vllm/v1/worker/gpu/cudagraph_utils.py b/vllm/v1/worker/gpu/cudagraph_utils.py index 3c334ca31f4c..ab645fab08b0 100644 --- a/vllm/v1/worker/gpu/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/cudagraph_utils.py @@ -29,6 +29,7 @@ from vllm.logger import init_logger from vllm.model_executor.offloader.base import get_offloader from vllm.platforms import current_platform +from vllm.profiler.graph_capture import graph_capture_step from vllm.sequence import IntermediateTensors from vllm.utils.math_utils import round_up from vllm.utils.torch_utils import current_stream @@ -358,12 +359,16 @@ def capture( desc.cg_mode == CUDAGraphMode.PIECEWISE and not self.use_breakable_cg ): - forward_fn(CUDAGraphMode.PIECEWISE) + with graph_capture_step(desc.num_tokens, desc.cg_mode.name): + forward_fn(CUDAGraphMode.PIECEWISE) else: # Capture with fresh attention state. forward_fn = create_forward_fn(desc, warmup=False) if desc.cg_mode == CUDAGraphMode.PIECEWISE: - forward_fn(CUDAGraphMode.PIECEWISE) + with graph_capture_step( + desc.num_tokens, desc.cg_mode.name + ): + forward_fn(CUDAGraphMode.PIECEWISE) continue assert desc not in self.graphs, ( f"Graph already captured for {desc}" @@ -379,8 +384,9 @@ def capture( if self._capture_mem_samples is not None: torch.accelerator.synchronize() free_before = torch.accelerator.get_memory_info()[0] - with torch.cuda.graph( - graph, self.pool, stream=current_stream() + with ( + graph_capture_step(desc.num_tokens, desc.cg_mode.name), + torch.cuda.graph(graph, self.pool, stream=current_stream()), ): forward_fn(CUDAGraphMode.NONE) # Join offloader's copy stream after forward to avoid diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index f92de74ed9e4..2a8838e58cf6 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -58,6 +58,7 @@ MultiModalBudget, get_dummy_encoder_profile_inputs, ) +from vllm.profiler.graph_capture import graph_capture_profiler from vllm.sequence import IntermediateTensors from vllm.tasks import SupportedTask from vllm.utils.mem_utils import DeviceMemoryProfiler, format_gib @@ -906,27 +907,40 @@ def capture_model(self) -> int: with self.maybe_setup_dummy_loras(self.lora_config): if capture_encoder: - self.model_state.encoder_runner.capture() + with graph_capture_profiler( + self.vllm_config, subsystem="encoder", label_prefix="encoder" + ): + self.model_state.encoder_runner.capture() if capture_decoder: input_buffers = self.input_buffers if self.pcp_manager is not None: input_buffers = self.pcp_manager.input_buffers - self.cudagraph_manager.capture( - self.model, - self.model_state, - input_buffers, - self.intermediate_tensors, - self.block_tables, - self.attn_groups, - self.kv_cache_config, - pcp_manager=self.pcp_manager, - has_lora=self.lora_config is not None, - use_aux_hidden_state_outputs=self.use_aux_hidden_state_outputs, - lora_capture_hook=create_lora_capture_hook(self.lora_config, self), - ) + with graph_capture_profiler(self.vllm_config): + self.cudagraph_manager.capture( + self.model, + self.model_state, + input_buffers, + self.intermediate_tensors, + self.block_tables, + self.attn_groups, + self.kv_cache_config, + pcp_manager=self.pcp_manager, + has_lora=self.lora_config is not None, + use_aux_hidden_state_outputs=self.use_aux_hidden_state_outputs, + lora_capture_hook=create_lora_capture_hook( + self.lora_config, self + ), + ) if self.speculator is not None: - with use_workspace_lane(self._draft_workspace_lane): + with ( + use_workspace_lane(self._draft_workspace_lane), + graph_capture_profiler( + self.vllm_config, + subsystem="speculator", + label_prefix="draft", + ), + ): self.speculator.capture() if self.adaptive_verification is not None: with self.step_timing.collect() as timings: diff --git a/vllm/v1/worker/gpu_model_runner.py b/vllm/v1/worker/gpu_model_runner.py index 0daabc978dab..365d89d69d67 100644 --- a/vllm/v1/worker/gpu_model_runner.py +++ b/vllm/v1/worker/gpu_model_runner.py @@ -118,6 +118,7 @@ ) from vllm.platforms import current_platform from vllm.pooling_params import PoolingParams +from vllm.profiler.graph_capture import graph_capture_profiler from vllm.sampling_params import SamplingType from vllm.sequence import IntermediateTensors from vllm.tasks import GenerationTask, PoolingTask, SupportedTask @@ -7009,7 +7010,12 @@ def capture_model(self) -> int: # Capture encoder CUDA graphs if enabled if self.encoder_cudagraph_manager is not None: encoder_graph_pool = current_platform.graph_pool_handle() - self.encoder_cudagraph_manager.capture(graph_pool=encoder_graph_pool) + with graph_capture_profiler( + self.vllm_config, subsystem="encoder", label_prefix="encoder" + ): + self.encoder_cudagraph_manager.capture( + graph_pool=encoder_graph_pool + ) torch.accelerator.synchronize() end_free_gpu_memory = torch.accelerator.get_memory_info()[0] From 809c11561845d38854894e18c96e17c24982c08a Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Mon, 14 Sep 2026 18:59:54 -0500 Subject: [PATCH 2/9] Use TorchProfilerWrapper to create capture profiler Signed-off-by: Deval Shah --- tests/v1/worker/test_gpu_profiler.py | 97 +++++++++++++++++++++++----- vllm/config/profiler.py | 3 +- vllm/profiler/graph_capture.py | 47 +++++++------- vllm/profiler/wrapper.py | 31 ++++++++- vllm/v1/worker/gpu_model_runner.py | 42 ++---------- 5 files changed, 140 insertions(+), 80 deletions(-) diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index 046af86b7daf..6b84e6330324 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -20,7 +20,12 @@ from vllm.platforms import current_platform from vllm.profiler import graph_capture from vllm.profiler.graph_capture import graph_capture_profiler, graph_capture_step -from vllm.profiler.wrapper import ProtonProfilerWrapper, WorkerProfiler +from vllm.profiler.wrapper import ( + ProtonProfilerWrapper, + WorkerProfiler, + default_torch_profiler_activities, + graph_capture_profiler_config, +) from vllm.v1.core.sched.output import CachedRequestData from vllm.v1.worker.gpu_model_runner import GPUModelRunner from vllm.v1.worker.gpu_worker import Worker @@ -357,7 +362,9 @@ def bound_graph_capture(label_prefix=None): """Enter a graph-capture binding backed by a mock profiler.""" profiler = MagicMock() with ( - patch.object(graph_capture, "_make_profiler", return_value=profiler), + patch.object( + graph_capture, "make_graph_capture_profiler", return_value=profiler + ), graph_capture_profiler(MagicMock(), label_prefix=label_prefix), ): yield profiler @@ -389,9 +396,11 @@ def test_step_is_noop_without_binding(self, annotation): def test_annotation_label( self, annotation, label_prefix, num_tokens, mode, expected ): - with bound_graph_capture(label_prefix) as profiler: - with graph_capture_step(num_tokens, mode): - pass + with ( + bound_graph_capture(label_prefix) as profiler, + graph_capture_step(num_tokens, mode), + ): + pass annotation.assert_called_once_with(expected) profiler.__enter__.assert_called_once() @@ -410,9 +419,8 @@ def test_profiler_cycles_once_per_shape(self, annotation): assert annotation.call_count == 3 def test_binding_cleared_when_capture_raises(self): - with pytest.raises(RuntimeError): - with bound_graph_capture(): - raise RuntimeError("capture failed") + with pytest.raises(RuntimeError), bound_graph_capture(): + raise RuntimeError("capture failed") assert graph_capture._active_binding.get() is None @@ -425,21 +433,74 @@ def test_binding_cleared_when_capture_raises(self): ], ) def test_trace_file_name_per_subsystem(self, subsystem, expected): - config = MagicMock() - config.profiler_config.capture_torch_profiler = True - config.profiler_config.torch_profiler_dir = "/traces" + config = MagicMock( + profiler_config=ProfilerConfig( + profiler="torch", + torch_profiler_dir="/traces", + capture_torch_profiler=True, + ), + device_config=SimpleNamespace(device_type="xpu"), + ) + profiler = MagicMock() + wrapper = MagicMock(profiler=profiler) with ( patch.object( graph_capture, "get_world_group", return_value=MagicMock(local_rank=0) ), - patch.object(torch.profiler, "profile"), - patch.object(torch.profiler, "tensorboard_trace_handler") as handler, + patch.object( + graph_capture, "TorchProfilerWrapper", return_value=wrapper + ) as wrapper_cls, ): - graph_capture._make_profiler(config, subsystem) + result = graph_capture.make_graph_capture_profiler(config, subsystem) + + assert result is profiler + capture_config = wrapper_cls.call_args.args[0] + assert capture_config.torch_profiler_dir == "/traces/capture_traces" + assert wrapper_cls.call_args.kwargs["worker_name"] == expected + # Activities follow the runner device, not a hardcoded CUDA list. + assert wrapper_cls.call_args.kwargs["activities"] == ["CPU", "XPU"] + wrapper.start.assert_not_called() + + def test_capture_config_overrides(self): + config = ProfilerConfig( + profiler="torch", + torch_profiler_dir="/traces", + delay_iterations=2, + max_iterations=3, + warmup_iterations=4, + wait_iterations=5, + torch_profiler_record_shapes=False, + torch_profiler_with_stack=False, + torch_profiler_with_flops=True, + torch_profiler_with_memory=True, + torch_profiler_use_gzip=False, + ignore_frontend=True, + ) + + capture_config = graph_capture_profiler_config(config) - assert handler.call_args.args == ("/traces/capture_traces",) - assert handler.call_args.kwargs["worker_name"] == expected + assert capture_config.delay_iterations == 0 + assert capture_config.max_iterations == 0 + assert capture_config.warmup_iterations == 0 + assert capture_config.wait_iterations == 0 + assert capture_config.torch_profiler_record_shapes + assert capture_config.torch_profiler_with_stack + assert capture_config.torch_profiler_with_flops + assert capture_config.torch_profiler_with_memory + assert not capture_config.torch_profiler_use_gzip + + @pytest.mark.parametrize( + "device_type,expected", + [ + ("cuda", ["CPU", "CUDA"]), + ("xpu", ["CPU", "XPU"]), + ("cpu", ["CPU"]), + ("tpu", ["CPU"]), + ], + ) + def test_activities_follow_runner_device(self, device_type, expected): + assert default_torch_profiler_activities(device_type) == expected @pytest.mark.parametrize("local_rank,enabled", [(0, False), (1, True)]) def test_no_profiler_when_disabled_or_off_rank(self, local_rank, enabled): @@ -451,7 +512,9 @@ def test_no_profiler_when_disabled_or_off_rank(self, local_rank, enabled): "get_world_group", return_value=MagicMock(local_rank=local_rank), ): - assert isinstance(graph_capture._make_profiler(config, None), nullcontext) + profiler = graph_capture.make_graph_capture_profiler(config, None) + + assert isinstance(profiler, nullcontext) def make_proton(session_id: int | None = 7): diff --git a/vllm/config/profiler.py b/vllm/config/profiler.py index b3b232490f01..3d5aae9befcb 100644 --- a/vllm/config/profiler.py +++ b/vllm/config/profiler.py @@ -98,7 +98,8 @@ class ProfilerConfig: Disabled by default.""" capture_torch_profiler: bool = False - """If `True`, enables a torch profiler during CUDA graph capture on rank 0. + """If `True`, enables a torch profiler during GPU graph capture on rank 0. + Activities include CPU and the runner device (CUDA/ROCm or XPU). Traces are saved to a `capture_traces` subdirectory under `torch_profiler_dir`. Requires `profiler` to be set to 'torch'.""" diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py index e9c6e67176b3..925ae044bd4a 100644 --- a/vllm/profiler/graph_capture.py +++ b/vllm/profiler/graph_capture.py @@ -23,6 +23,11 @@ from vllm.config import VllmConfig from vllm.distributed.parallel_state import get_world_group from vllm.logger import init_logger +from vllm.profiler.wrapper import ( + TorchProfilerWrapper, + default_torch_profiler_activities, + graph_capture_profiler_config, +) logger = init_logger(__name__) @@ -38,43 +43,37 @@ class _CaptureBinding: ) -def _make_profiler( +def make_graph_capture_profiler( vllm_config: VllmConfig, - subsystem: str | None, + subsystem: str | None = None, ) -> AbstractContextManager[Any]: + """Build the one-shot capture profiler, or a nullcontext when disabled. + + The single construction site for capture profilers, so callers that still + pass the profiler down their capture loops by hand inherit the same config + overrides and device activities as ``graph_capture_profiler``. + """ profiler_config = vllm_config.profiler_config local_rank = get_world_group().local_rank if local_rank != 0 or not profiler_config.capture_torch_profiler: logger.info_once( - "Rank %d: Torch profiler disabled for CUDA graph capture", local_rank + "Rank %d: Torch profiler disabled for GPU graph capture", local_rank ) return nullcontext() - trace_dir = profiler_config.torch_profiler_dir + "/capture_traces" + capture_config = graph_capture_profiler_config(profiler_config) worker_name = f"graph_capture_rank_{local_rank}" if subsystem: worker_name += f"_{subsystem}" - logger.info_once( - "Rank %d: Torch profiler enabled for %s CUDA graph capture, " - "traces will be saved to: %s", - local_rank, - subsystem or "decoder", - trace_dir, - ) - return torch.profiler.profile( - activities=[ - torch.profiler.ProfilerActivity.CPU, - torch.profiler.ProfilerActivity.CUDA, - ], - record_shapes=True, - profile_memory=True, - with_stack=True, - on_trace_ready=torch.profiler.tensorboard_trace_handler( - trace_dir, - worker_name=worker_name, - use_gzip=True, + wrapper = TorchProfilerWrapper( + capture_config, + worker_name=worker_name, + local_rank=local_rank, + activities=default_torch_profiler_activities( + vllm_config.device_config.device_type ), ) + return wrapper.profiler @contextmanager @@ -95,7 +94,7 @@ def graph_capture_profiler( ``capture_32_FULL``. """ binding = _CaptureBinding( - profiler=_make_profiler(vllm_config, subsystem), + profiler=make_graph_capture_profiler(vllm_config, subsystem), label_prefix=label_prefix, ) token = _active_binding.set(binding) diff --git a/vllm/profiler/wrapper.py b/vllm/profiler/wrapper.py index fb8963198635..6549adda200b 100644 --- a/vllm/profiler/wrapper.py +++ b/vllm/profiler/wrapper.py @@ -8,7 +8,8 @@ from abc import ABC, abstractmethod from collections.abc import Callable from contextlib import nullcontext -from typing import Literal +from dataclasses import replace +from typing import Literal, cast from uuid import uuid4 import torch @@ -174,6 +175,34 @@ def annotate_context_manager(self, name: str): } +def default_torch_profiler_activities(device_type: str) -> list[TorchProfilerActivity]: + """CPU plus the accelerator activity for a runner device. + + ``cuda`` covers CUDA and ROCm; ``xpu`` selects Intel GPU events. Device + types torch cannot profile fall back to CPU-only. + """ + accelerator = device_type.upper() + if accelerator == "CPU" or accelerator not in TorchProfilerActivityMap: + return ["CPU"] + return ["CPU", cast(TorchProfilerActivity, accelerator)] + + +def graph_capture_profiler_config(profiler_config: ProfilerConfig) -> ProfilerConfig: + """Apply one-shot graph-capture overrides to a profiler config.""" + return replace( + profiler_config, + delay_iterations=0, + max_iterations=0, + warmup_iterations=0, + wait_iterations=0, + torch_profiler_record_shapes=True, + torch_profiler_with_stack=True, + torch_profiler_dir=os.path.join( + profiler_config.torch_profiler_dir, "capture_traces" + ), + ) + + class TorchProfilerWrapper(WorkerProfiler): def __init__( self, diff --git a/vllm/v1/worker/gpu_model_runner.py b/vllm/v1/worker/gpu_model_runner.py index 8e633f74642a..2a28486ca998 100644 --- a/vllm/v1/worker/gpu_model_runner.py +++ b/vllm/v1/worker/gpu_model_runner.py @@ -114,7 +114,10 @@ ) from vllm.platforms import current_platform from vllm.pooling_params import PoolingParams -from vllm.profiler.graph_capture import graph_capture_profiler +from vllm.profiler.graph_capture import ( + graph_capture_profiler, + make_graph_capture_profiler, +) from vllm.sampling_params import SamplingType from vllm.sequence import IntermediateTensors from vllm.tasks import GenerationTask, PoolingTask, SupportedTask @@ -6848,42 +6851,7 @@ def capture_model(self) -> int: # can reuse the memory pool allocated for the large shapes. set_cudagraph_capturing_enabled(True) - # Setup torch profiler for graph capture traces (conditional) - from vllm.distributed.parallel_state import get_world_group - - local_rank = get_world_group().local_rank - enable_profiler = ( - local_rank == 0 - ) and self.vllm_config.profiler_config.capture_torch_profiler - if enable_profiler: - trace_dir = ( - self.vllm_config.profiler_config.torch_profiler_dir + "/capture_traces" - ) - profiler = torch.profiler.profile( - activities=[ - torch.profiler.ProfilerActivity.CPU, - torch.profiler.ProfilerActivity.CUDA, - ], - record_shapes=True, - profile_memory=True, - with_stack=True, - on_trace_ready=torch.profiler.tensorboard_trace_handler( - trace_dir, - worker_name=f"graph_capture_rank_{local_rank}", - use_gzip=True, - ), - ) - logger.info_once( - "Rank %d: Torch profiler enabled for CUDA graph capture, " - "traces will be saved to: %s", - local_rank, - trace_dir, - ) - else: - profiler = nullcontext() - logger.info_once( - "Rank %d: Torch profiler disabled for CUDA graph capture", local_rank - ) + profiler = make_graph_capture_profiler(self.vllm_config) with self._freeze_gc(), graph_capture(device=self.device): torch.accelerator.synchronize() From 2e1a22d52ec80d37b2bee7d7a617173a59bdb5fe Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Mon, 14 Sep 2026 19:50:37 -0500 Subject: [PATCH 3/9] Moved profiler to the base capture function Signed-off-by: Deval Shah --- tests/v1/worker/test_gpu_profiler.py | 48 +++++++++++++----- vllm/profiler/graph_capture.py | 17 +++++++ vllm/v1/worker/encoder_cudagraph.py | 8 ++- vllm/v1/worker/gpu/cudagraph_utils.py | 19 ++++--- vllm/v1/worker/gpu/model_runner.py | 50 +++++++------------ .../autoregressive/cudagraph_utils.py | 6 ++- .../gpu/spec_decode/dflash/cudagraph.py | 6 ++- vllm/v1/worker/gpu_model_runner.py | 34 +++++-------- 8 files changed, 115 insertions(+), 73 deletions(-) diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index 6b84e6330324..eec76741e77b 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -19,7 +19,11 @@ from vllm.config.profiler import _is_uri_path from vllm.platforms import current_platform from vllm.profiler import graph_capture -from vllm.profiler.graph_capture import graph_capture_profiler, graph_capture_step +from vllm.profiler.graph_capture import ( + graph_capture_profiler, + graph_capture_step, + skip_graph_capture_tracing, +) from vllm.profiler.wrapper import ( ProtonProfilerWrapper, WorkerProfiler, @@ -340,21 +344,19 @@ def test_skips_annotation_work_after_profiler_stops(self): def test_profiler_entered_during_capture(): - """Profiler is used as a context manager in _warmup_and_capture, - confirming it is active during the actual graph capture run.""" + """graph_capture_step enters the bound profiler during V1 capture.""" runner = MagicMock() runner.compilation_config.cudagraph_num_of_warmups = 0 - mock_profiler = MagicMock() - GPUModelRunner._warmup_and_capture( - runner, - desc=MagicMock(num_tokens=4, uniform=True), - cudagraph_runtime_mode=CUDAGraphMode.FULL, - profiler=mock_profiler, - ) + with bound_graph_capture() as profiler: + GPUModelRunner._warmup_and_capture( + runner, + desc=MagicMock(num_tokens=4, uniform=True), + cudagraph_runtime_mode=CUDAGraphMode.FULL, + ) - mock_profiler.__enter__.assert_called_once() - mock_profiler.__exit__.assert_called_once() + profiler.__enter__.assert_called_once() + profiler.__exit__.assert_called_once() @contextmanager @@ -516,6 +518,28 @@ def test_no_profiler_when_disabled_or_off_rank(self, local_rank, enabled): assert isinstance(profiler, nullcontext) + def test_nested_bind_keeps_outer_prefix(self, annotation): + with ( + bound_graph_capture("draft") as profiler, + graph_capture_profiler(MagicMock(), label_prefix="ignored"), + graph_capture_step(32, "FULL"), + ): + pass + + annotation.assert_called_once_with("capture_32_draft_FULL") + profiler.__enter__.assert_called_once() + + def test_skip_tracing_is_noop_even_if_capture_binds(self, annotation): + with ( + skip_graph_capture_tracing(), + graph_capture_profiler(MagicMock(), label_prefix="encoder"), + graph_capture_step(32, "FULL"), + ): + pass + + annotation.assert_not_called() + assert graph_capture._active_binding.get() is None + def make_proton(session_id: int | None = 7): return SimpleNamespace( diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py index 925ae044bd4a..9c8e3b9d3833 100644 --- a/vllm/profiler/graph_capture.py +++ b/vllm/profiler/graph_capture.py @@ -41,6 +41,19 @@ class _CaptureBinding: _active_binding: contextvars.ContextVar[_CaptureBinding | None] = ( contextvars.ContextVar("vllm_graph_capture_binding", default=None) ) +_skip_capture_tracing: contextvars.ContextVar[bool] = contextvars.ContextVar( + "vllm_skip_graph_capture_tracing", default=False +) + + +@contextmanager +def skip_graph_capture_tracing() -> Iterator[None]: + """Disable capture tracing for the throwaway memory-estimate capture.""" + token = _skip_capture_tracing.set(True) + try: + yield + finally: + _skip_capture_tracing.reset(token) def make_graph_capture_profiler( @@ -93,6 +106,10 @@ def graph_capture_profiler( ``capture_32_draft_FULL`` rather than reusing the decoder's ``capture_32_FULL``. """ + if _skip_capture_tracing.get() or _active_binding.get() is not None: + yield + return + binding = _CaptureBinding( profiler=make_graph_capture_profiler(vllm_config, subsystem), label_prefix=label_prefix, diff --git a/vllm/v1/worker/encoder_cudagraph.py b/vllm/v1/worker/encoder_cudagraph.py index 8cbc1e9f80ef..e5950bfc15ac 100644 --- a/vllm/v1/worker/encoder_cudagraph.py +++ b/vllm/v1/worker/encoder_cudagraph.py @@ -22,7 +22,7 @@ ) from vllm.model_executor.models.utils import scatter_output_slices from vllm.model_executor.models.vision import get_load_balance_assignment -from vllm.profiler.graph_capture import graph_capture_step +from vllm.profiler.graph_capture import graph_capture_profiler, graph_capture_step from vllm.utils.gpu_sync_debug import gpu_sync_allowed from vllm.utils.torch_utils import current_stream from vllm.v1.worker.encoder_cudagraph_defs import ( @@ -245,6 +245,12 @@ def clear(self) -> None: def capture(self, graph_pool: Any): """Capture CUDA graphs for every configured path and token budget.""" + with graph_capture_profiler( + self.vllm_config, subsystem="encoder", label_prefix="encoder" + ): + self._capture_all_budget_graphs(graph_pool) + + def _capture_all_budget_graphs(self, graph_pool: Any) -> None: self.graph_pool = graph_pool num_graphs = self.get_num_graphs_to_capture() diff --git a/vllm/v1/worker/gpu/cudagraph_utils.py b/vllm/v1/worker/gpu/cudagraph_utils.py index fbfff32f4137..dea66e8f237a 100644 --- a/vllm/v1/worker/gpu/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/cudagraph_utils.py @@ -32,7 +32,11 @@ from vllm.logger import init_logger from vllm.model_executor.offloader.base import get_offloader from vllm.platforms import current_platform -from vllm.profiler.graph_capture import graph_capture_step +from vllm.profiler.graph_capture import ( + graph_capture_profiler, + graph_capture_step, + skip_graph_capture_tracing, +) from vllm.sequence import IntermediateTensors from vllm.utils.math_utils import round_up from vllm.utils.torch_utils import current_stream @@ -410,7 +414,11 @@ def capture( because attention backends may mutate or lazily initialize metadata during warmup. """ - with graph_capture(device=self.device), ExitStack() as stack: + with ( + graph_capture_profiler(self.vllm_config), + graph_capture(device=self.device), + ExitStack() as stack, + ): if self.ubatch_runner is not None: # Join parked threads on failure to avoid blocking later captures. stack.callback(self.ubatch_runner.abort_pending_run) @@ -455,9 +463,7 @@ def capture( # Capture with fresh attention state. forward_fn = create_forward_fn(desc, warmup=False) if desc.cg_mode == CUDAGraphMode.PIECEWISE: - with graph_capture_step( - desc.num_tokens, desc.cg_mode.name - ): + with graph_capture_step(desc.num_tokens, desc.cg_mode.name): forward_fn(CUDAGraphMode.PIECEWISE) continue assert desc not in self.graphs, ( @@ -925,7 +931,8 @@ def profile_cudagraph_memory(runner: "GPUModelRunner") -> int: mem_samples: list[int] = [] manager._capture_mem_samples = mem_samples - measured = int(runner.capture_model(profile_only=True)) + with skip_graph_capture_tracing(): + measured = int(runner.capture_model(profile_only=True)) # The measured delta covers PIECEWISE, encoder and speculator graphs # plus the sampled FULL graphs; swap the sampled FULL cost for the diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index 3817d94343c9..a116455f717f 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -60,7 +60,6 @@ MultiModalBudget, get_dummy_encoder_profile_inputs, ) -from vllm.profiler.graph_capture import graph_capture_profiler from vllm.sequence import IntermediateTensors from vllm.tasks import SupportedTask from vllm.utils.gc_utils import freeze_gc_for_cudagraph_capture @@ -1013,42 +1012,31 @@ def capture_model(self, *, profile_only: bool = False) -> int: with self.maybe_setup_dummy_loras(self.lora_config): if capture_encoder: - with graph_capture_profiler( - self.vllm_config, subsystem="encoder", label_prefix="encoder" - ): - self.model_state.encoder_runner.capture() + self.model_state.encoder_runner.capture() if capture_decoder: input_buffers = self.input_buffers if self.pcp_manager is not None: input_buffers = self.pcp_manager.input_buffers - with graph_capture_profiler(self.vllm_config): - self.cudagraph_manager.capture( - self.model, - self.model_state, - input_buffers, - self.intermediate_tensors, - self.block_tables, - self.attn_groups, - self.kv_cache_config, - pcp_manager=self.pcp_manager, - has_lora=self.lora_config is not None, - use_aux_hidden_state_outputs=( - self.use_aux_hidden_state_outputs - ), - lora_capture_hook=create_lora_capture_hook( - self.lora_config, self - ), - ) + self.cudagraph_manager.capture( + self.model, + self.model_state, + input_buffers, + self.intermediate_tensors, + self.block_tables, + self.attn_groups, + self.kv_cache_config, + pcp_manager=self.pcp_manager, + has_lora=self.lora_config is not None, + use_aux_hidden_state_outputs=( + self.use_aux_hidden_state_outputs + ), + lora_capture_hook=create_lora_capture_hook( + self.lora_config, self + ), + ) if self.speculator is not None: - with ( - use_workspace_lane(self._draft_workspace_lane), - graph_capture_profiler( - self.vllm_config, - subsystem="speculator", - label_prefix="draft", - ), - ): + with use_workspace_lane(self._draft_workspace_lane): self.speculator.capture() if self.adaptive_verification is not None: with self.step_timing.collect() as timings: diff --git a/vllm/v1/worker/gpu/spec_decode/autoregressive/cudagraph_utils.py b/vllm/v1/worker/gpu/spec_decode/autoregressive/cudagraph_utils.py index ef3b6e2ed535..5a9ad1802a3c 100644 --- a/vllm/v1/worker/gpu/spec_decode/autoregressive/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/spec_decode/autoregressive/cudagraph_utils.py @@ -5,6 +5,7 @@ import torch from vllm.config.compilation import CUDAGraphMode +from vllm.profiler.graph_capture import graph_capture_profiler from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.block_table import BlockTables from vllm.v1.worker.gpu.cudagraph_utils import ( @@ -68,4 +69,7 @@ def create_forward_fn( cg_mode, ) - super().capture(create_forward_fn, progress_bar_desc) + with graph_capture_profiler( + self.vllm_config, subsystem="speculator", label_prefix="draft" + ): + super().capture(create_forward_fn, progress_bar_desc) diff --git a/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py b/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py index 725714fcdbc0..4a8b10d94d05 100644 --- a/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py +++ b/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py @@ -5,6 +5,7 @@ import torch from vllm.config.compilation import CUDAGraphMode +from vllm.profiler.graph_capture import graph_capture_profiler from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.attn_utils import ( build_attn_metadata, @@ -118,4 +119,7 @@ def create_forward_fn( cg_mode, ) - super().capture(create_forward_fn, progress_bar_desc) + with graph_capture_profiler( + self.vllm_config, subsystem="speculator", label_prefix="draft" + ): + super().capture(create_forward_fn, progress_bar_desc) diff --git a/vllm/v1/worker/gpu_model_runner.py b/vllm/v1/worker/gpu_model_runner.py index 2a28486ca998..421432641163 100644 --- a/vllm/v1/worker/gpu_model_runner.py +++ b/vllm/v1/worker/gpu_model_runner.py @@ -116,7 +116,8 @@ from vllm.pooling_params import PoolingParams from vllm.profiler.graph_capture import ( graph_capture_profiler, - make_graph_capture_profiler, + graph_capture_step, + skip_graph_capture_tracing, ) from vllm.sampling_params import SamplingType from vllm.sequence import IntermediateTensors @@ -6737,6 +6738,7 @@ def profile_cudagraph_memory(self) -> int: try: set_cudagraph_capturing_enabled(True) with ( + skip_graph_capture_tracing(), self._freeze_gc(), graph_capture(device=self.device, graph_capture_context=cap_ctx), ): @@ -6851,8 +6853,6 @@ def capture_model(self) -> int: # can reuse the memory pool allocated for the large shapes. set_cudagraph_capturing_enabled(True) - profiler = make_graph_capture_profiler(self.vllm_config) - with self._freeze_gc(), graph_capture(device=self.device): torch.accelerator.synchronize() torch.accelerator.empty_cache() @@ -6865,19 +6865,13 @@ def capture_model(self) -> int: self._capture_cudagraphs( batch_descriptors=batch_descs, cudagraph_runtime_mode=runtime_mode, - profiler=profiler, ) torch.accelerator.synchronize() # Capture encoder CUDA graphs if enabled if self.encoder_cudagraph_manager is not None: encoder_graph_pool = current_platform.graph_pool_handle() - with graph_capture_profiler( - self.vllm_config, subsystem="encoder", label_prefix="encoder" - ): - self.encoder_cudagraph_manager.capture( - graph_pool=encoder_graph_pool - ) + self.encoder_cudagraph_manager.capture(graph_pool=encoder_graph_pool) torch.accelerator.synchronize() end_free_gpu_memory = torch.accelerator.get_memory_info()[0] @@ -6914,10 +6908,7 @@ def _warmup_and_capture( profile_seq_lens: int | None = None, allow_microbatching: bool = False, num_warmups: int | None = None, - profiler: AbstractContextManager[Any] | None = None, ): - if profiler is None: - profiler = nullcontext() if num_warmups is None: num_warmups = self.compilation_config.cudagraph_num_of_warmups force_attention = cudagraph_runtime_mode == CUDAGraphMode.FULL @@ -6937,12 +6928,7 @@ def _warmup_and_capture( # Warmups may use auxiliary streams. Ensure all of their work has # completed before beginning CUDA graph capture. torch.accelerator.synchronize() - with ( - profiler, - torch.profiler.record_function( - f"capture_{desc.num_tokens}_{cudagraph_runtime_mode.name}" - ), - ): + with graph_capture_step(desc.num_tokens, cudagraph_runtime_mode.name): self._dummy_run( desc.num_tokens, cudagraph_runtime_mode=cudagraph_runtime_mode, @@ -6959,7 +6945,6 @@ def _capture_cudagraphs( self, batch_descriptors: list[BatchDescriptor], cudagraph_runtime_mode: CUDAGraphMode, - profiler: AbstractContextManager[Any] | None = None, ): assert ( cudagraph_runtime_mode != CUDAGraphMode.NONE @@ -6969,6 +6954,14 @@ def _capture_cudagraphs( if not batch_descriptors: return + with graph_capture_profiler(self.vllm_config): + self._capture_cudagraph_shapes(batch_descriptors, cudagraph_runtime_mode) + + def _capture_cudagraph_shapes( + self, + batch_descriptors: list[BatchDescriptor], + cudagraph_runtime_mode: CUDAGraphMode, + ): uniform_decode = batch_descriptors[0].uniform # Only rank 0 should print progress bar during capture @@ -7002,7 +6995,6 @@ def _capture_cudagraphs( batch_desc, cudagraph_runtime_mode=cudagraph_runtime_mode, allow_microbatching=allow_microbatching, - profiler=profiler, ) torch.accelerator.synchronize() self.maybe_remove_all_loras(self.lora_config) From f4a6cbb4b50a25e7fcdfd8b7e5a0d6ce31be72dc Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Mon, 14 Sep 2026 20:22:27 -0500 Subject: [PATCH 4/9] Sort stdlib imports in profiler wrapper. Co-authored-by: Cursor Grok 4.6 Signed-off-by: Deval Shah --- vllm/profiler/wrapper.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vllm/profiler/wrapper.py b/vllm/profiler/wrapper.py index ab3ac3cde7a4..a63caac4736a 100644 --- a/vllm/profiler/wrapper.py +++ b/vllm/profiler/wrapper.py @@ -6,11 +6,11 @@ import json import os from abc import ABC, abstractmethod -from dataclasses import replace -from typing import Literal, cast from collections.abc import Callable, Iterator from contextlib import AbstractContextManager, contextmanager, nullcontext, suppress +from dataclasses import replace from glob import glob +from typing import Literal, cast from uuid import uuid4 import torch From e47d5133de732bc4c5d64ec7fc5124c49fe101f2 Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Tue, 15 Sep 2026 17:56:35 -0500 Subject: [PATCH 5/9] Restore single-line use_aux_hidden_state_outputs in V2 capture. Co-authored-by: Cursor Grok 4.6 Signed-off-by: Deval Shah --- vllm/v1/worker/gpu/model_runner.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index fe3a01647965..25395c3330eb 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -1038,9 +1038,7 @@ def capture_model(self, *, profile_only: bool = False) -> int: self.kv_cache_config, pcp_manager=self.pcp_manager, has_lora=self.lora_config is not None, - use_aux_hidden_state_outputs=( - self.use_aux_hidden_state_outputs - ), + use_aux_hidden_state_outputs=self.use_aux_hidden_state_outputs, lora_capture_hook=create_lora_capture_hook( self.lora_config, self ), From d9c4f84de8e65cce79cdd584142de304ea157c10 Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Thu, 17 Sep 2026 13:40:27 -0500 Subject: [PATCH 6/9] Document vllm_config in graph_capture_profiler docstring. Co-authored-by: Cursor Grok 4.6 Signed-off-by: Deval Shah --- vllm/profiler/graph_capture.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py index 9c8e3b9d3833..10c480dfa1a9 100644 --- a/vllm/profiler/graph_capture.py +++ b/vllm/profiler/graph_capture.py @@ -98,6 +98,7 @@ def graph_capture_profiler( """Bind a graph-capture profiler for one subsystem's capture. Args: + vllm_config: Engine config; used for profiler settings and device type. subsystem: Suffix for the trace file name. ``"encoder"`` writes ``graph_capture_rank_0_encoder..pt.trace.json.gz``; the main decoder passes ``None`` and keeps the unsuffixed name. @@ -105,6 +106,7 @@ def graph_capture_profiler( block, so that e.g. speculator graphs are labelled ``capture_32_draft_FULL`` rather than reusing the decoder's ``capture_32_FULL``. + """ if _skip_capture_tracing.get() or _active_binding.get() is not None: yield From a063047e2a160c4d096f111d04953c70023a763c Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Thu, 29 Oct 2026 15:36:50 -0500 Subject: [PATCH 7/9] [Bugfix][Profiler] Build an unstarted profiler for graph capture TorchProfilerWrapper now creates its profiler in _start(), so capture raised AttributeError by reading wrapper.profiler before any graph was captured. Signed-off-by: Deval Shah --- tests/v1/worker/test_gpu_profiler.py | 50 ++++++++++++++++++++++++++-- vllm/profiler/graph_capture.py | 4 ++- vllm/profiler/wrapper.py | 6 +++- 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index 06b342943e65..fc35182199b2 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -839,8 +839,9 @@ def test_trace_file_name_per_subsystem(self, subsystem, expected): ), device_config=SimpleNamespace(device_type="xpu"), ) - profiler = MagicMock() - wrapper = MagicMock(profiler=profiler) + built = MagicMock() + wrapper = MagicMock() + wrapper.build_profiler.return_value = built with ( patch.object( @@ -852,7 +853,8 @@ def test_trace_file_name_per_subsystem(self, subsystem, expected): ): result = graph_capture.make_graph_capture_profiler(config, subsystem) - assert result is profiler + assert result is built + wrapper.build_profiler.assert_called_once_with() capture_config = wrapper_cls.call_args.args[0] assert capture_config.torch_profiler_dir == "/traces/capture_traces" assert wrapper_cls.call_args.kwargs["worker_name"] == expected @@ -860,6 +862,48 @@ def test_trace_file_name_per_subsystem(self, subsystem, expected): assert wrapper_cls.call_args.kwargs["activities"] == ["CPU", "XPU"] wrapper.start.assert_not_called() + def test_enabled_rank_returns_enterable_profiler(self): + """Rank 0 with capture enabled can enter the profiler it builds. + + The wrapper does not create its profiler until a serving session + starts, so this must build a separate unstarted profiler. + """ + config = MagicMock( + profiler_config=ProfilerConfig( + profiler="torch", + torch_profiler_dir="/traces", + capture_torch_profiler=True, + ), + device_config=SimpleNamespace(device_type="xpu"), + ) + built = MagicMock() + + with ( + patch.object( + graph_capture, "get_world_group", return_value=MagicMock(local_rank=0) + ), + patch( + "vllm.profiler.wrapper.torch.profiler.profile", return_value=built + ) as profile, + ): + profiler = graph_capture.make_graph_capture_profiler(config) + with profiler: + pass + + assert profiler is built + profile.assert_called_once() + kwargs = profile.call_args.kwargs + assert kwargs["schedule"] is None + assert kwargs["record_shapes"] is True + assert kwargs["with_stack"] is True + assert kwargs["activities"] == [ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.XPU, + ] + built.__enter__.assert_called_once() + built.__exit__.assert_called_once() + built.start.assert_not_called() + def test_capture_config_overrides(self): config = ProfilerConfig( profiler="torch", diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py index 10c480dfa1a9..01e1d7017007 100644 --- a/vllm/profiler/graph_capture.py +++ b/vllm/profiler/graph_capture.py @@ -86,7 +86,9 @@ def make_graph_capture_profiler( vllm_config.device_config.device_type ), ) - return wrapper.profiler + # Serving creates wrapper.profiler only when a session starts. Capture + # needs the same settings without starting that session. + return wrapper.build_profiler() @contextmanager diff --git a/vllm/profiler/wrapper.py b/vllm/profiler/wrapper.py index f82dd100735d..a3c10411ad7d 100644 --- a/vllm/profiler/wrapper.py +++ b/vllm/profiler/wrapper.py @@ -430,9 +430,13 @@ def _maybe_add_version_metadata(self) -> None: # Mark done even on failure, to avoid retrying every step. self._version_metadata_added = True + def build_profiler(self) -> torch.profiler.profile: + """Build one unstarted profiler from the current settings.""" + return torch.profiler.profile(**self._profiler_kwargs) + @override def _start(self) -> None: - self.profiler = torch.profiler.profile(**self._profiler_kwargs) + self.profiler = self.build_profiler() self._warmup_steps_remaining = self._initial_warmup_steps_remaining self._version_metadata_added = False self.profiler.start() From 83312ea9f13bf11656fefe498648c4f3a73d2c02 Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Thu, 29 Oct 2026 17:23:58 -0500 Subject: [PATCH 8/9] [Profiler] Skip capture binding when graph-capture profiling is disabled Co-authored-by: Claude Signed-off-by: Deval Shah --- tests/v1/worker/test_gpu_profiler.py | 24 ++++++++++++++++-------- vllm/profiler/graph_capture.py | 28 ++++++++++++---------------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index fc35182199b2..54a6b5240662 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -887,10 +887,10 @@ def test_enabled_rank_returns_enterable_profiler(self): ) as profile, ): profiler = graph_capture.make_graph_capture_profiler(config) + assert profiler is built with profiler: pass - assert profiler is built profile.assert_called_once() kwargs = profile.call_args.kwargs assert kwargs["schedule"] is None @@ -945,18 +945,26 @@ def test_activities_follow_runner_device(self, device_type, expected): assert default_torch_profiler_activities(device_type) == expected @pytest.mark.parametrize("local_rank,enabled", [(0, False), (1, True)]) - def test_no_profiler_when_disabled_or_off_rank(self, local_rank, enabled): + def test_no_binding_when_disabled_or_off_rank( + self, annotation, local_rank, enabled + ): + """Capture without profiling must not pay for per-shape annotations.""" config = MagicMock() config.profiler_config.capture_torch_profiler = enabled - with patch.object( - graph_capture, - "get_world_group", - return_value=MagicMock(local_rank=local_rank), + with ( + patch.object( + graph_capture, + "get_world_group", + return_value=MagicMock(local_rank=local_rank), + ), + graph_capture_profiler(config), ): - profiler = graph_capture.make_graph_capture_profiler(config, None) + assert graph_capture._active_binding.get() is None + with graph_capture_step(32, "FULL"): + pass - assert isinstance(profiler, nullcontext) + annotation.assert_not_called() def test_nested_bind_keeps_outer_prefix(self, annotation): with ( diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py index 01e1d7017007..9250ec1224f4 100644 --- a/vllm/profiler/graph_capture.py +++ b/vllm/profiler/graph_capture.py @@ -14,7 +14,7 @@ import contextvars from collections.abc import Iterator -from contextlib import AbstractContextManager, contextmanager, nullcontext +from contextlib import AbstractContextManager, contextmanager from dataclasses import dataclass from typing import Any @@ -59,20 +59,15 @@ def skip_graph_capture_tracing() -> Iterator[None]: def make_graph_capture_profiler( vllm_config: VllmConfig, subsystem: str | None = None, -) -> AbstractContextManager[Any]: - """Build the one-shot capture profiler, or a nullcontext when disabled. - - The single construction site for capture profilers, so callers that still - pass the profiler down their capture loops by hand inherit the same config - overrides and device activities as ``graph_capture_profiler``. - """ +) -> torch.profiler.profile | None: + """Build the one-shot capture profiler, or ``None`` when disabled.""" profiler_config = vllm_config.profiler_config local_rank = get_world_group().local_rank if local_rank != 0 or not profiler_config.capture_torch_profiler: logger.info_once( "Rank %d: Torch profiler disabled for GPU graph capture", local_rank ) - return nullcontext() + return None capture_config = graph_capture_profiler_config(profiler_config) worker_name = f"graph_capture_rank_{local_rank}" @@ -114,11 +109,12 @@ def graph_capture_profiler( yield return - binding = _CaptureBinding( - profiler=make_graph_capture_profiler(vllm_config, subsystem), - label_prefix=label_prefix, - ) - token = _active_binding.set(binding) + profiler = make_graph_capture_profiler(vllm_config, subsystem) + if profiler is None: + yield + return + + token = _active_binding.set(_CaptureBinding(profiler, label_prefix)) try: yield finally: @@ -131,8 +127,8 @@ def graph_capture_step(num_tokens: int, mode: str) -> Iterator[None]: Records a ``capture_{num_tokens}_{mode}`` annotation, or ``capture_{num_tokens}_{label_prefix}_{mode}`` when the active binding - sets a prefix. Does nothing outside a ``graph_capture_profiler`` block, so - capture loops can call this unconditionally. + sets a prefix. Does nothing unless a ``graph_capture_profiler`` block is + actively profiling, so capture loops can call this unconditionally. """ binding = _active_binding.get() if binding is None: From 9cb7aae8d88cd53542639c89fd3ac85b862b3eae Mon Sep 17 00:00:00 2001 From: Deval Shah Date: Thu, 29 Oct 2026 17:33:57 -0500 Subject: [PATCH 9/9] [Profiler] Reuse serving's activity selection for graph-capture profiling Signed-off-by: Deval Shah --- tests/v1/worker/test_gpu_profiler.py | 35 ++++++++++------------------ vllm/config/profiler.py | 3 ++- vllm/profiler/graph_capture.py | 12 ++++------ vllm/profiler/wrapper.py | 13 ----------- 4 files changed, 18 insertions(+), 45 deletions(-) diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index 54a6b5240662..4f35f9ca71c6 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -31,7 +31,6 @@ TorchProfilerWrapper, WorkerProfiler, create_worker_profiler, - default_torch_profiler_activities, graph_capture_profiler_config, validate_worker_profiler_config, ) @@ -837,10 +836,9 @@ def test_trace_file_name_per_subsystem(self, subsystem, expected): torch_profiler_dir="/traces", capture_torch_profiler=True, ), - device_config=SimpleNamespace(device_type="xpu"), ) built = MagicMock() - wrapper = MagicMock() + wrapper = MagicMock(spec=TorchProfilerWrapper) wrapper.build_profiler.return_value = built with ( @@ -848,33 +846,32 @@ def test_trace_file_name_per_subsystem(self, subsystem, expected): graph_capture, "get_world_group", return_value=MagicMock(local_rank=0) ), patch.object( - graph_capture, "TorchProfilerWrapper", return_value=wrapper - ) as wrapper_cls, + graph_capture, "create_worker_profiler", return_value=wrapper + ) as create, ): result = graph_capture.make_graph_capture_profiler(config, subsystem) assert result is built wrapper.build_profiler.assert_called_once_with() - capture_config = wrapper_cls.call_args.args[0] + capture_config = create.call_args.args[0] assert capture_config.torch_profiler_dir == "/traces/capture_traces" - assert wrapper_cls.call_args.kwargs["worker_name"] == expected - # Activities follow the runner device, not a hardcoded CUDA list. - assert wrapper_cls.call_args.kwargs["activities"] == ["CPU", "XPU"] + assert create.call_args.kwargs["worker_name"] == expected wrapper.start.assert_not_called() def test_enabled_rank_returns_enterable_profiler(self): """Rank 0 with capture enabled can enter the profiler it builds. The wrapper does not create its profiler until a serving session - starts, so this must build a separate unstarted profiler. + starts, so this must build a separate unstarted profiler. Configured + activities are honored, as in serving. """ config = MagicMock( profiler_config=ProfilerConfig( profiler="torch", torch_profiler_dir="/traces", + torch_profiler_activities=["CPU", "XPU"], capture_torch_profiler=True, ), - device_config=SimpleNamespace(device_type="xpu"), ) built = MagicMock() @@ -882,6 +879,10 @@ def test_enabled_rank_returns_enterable_profiler(self): patch.object( graph_capture, "get_world_group", return_value=MagicMock(local_rank=0) ), + patch( + "vllm.profiler.wrapper.current_platform", + SimpleNamespace(device_type="cuda"), + ), patch( "vllm.profiler.wrapper.torch.profiler.profile", return_value=built ) as profile, @@ -932,18 +933,6 @@ def test_capture_config_overrides(self): assert capture_config.torch_profiler_with_memory assert not capture_config.torch_profiler_use_gzip - @pytest.mark.parametrize( - "device_type,expected", - [ - ("cuda", ["CPU", "CUDA"]), - ("xpu", ["CPU", "XPU"]), - ("cpu", ["CPU"]), - ("tpu", ["CPU"]), - ], - ) - def test_activities_follow_runner_device(self, device_type, expected): - assert default_torch_profiler_activities(device_type) == expected - @pytest.mark.parametrize("local_rank,enabled", [(0, False), (1, True)]) def test_no_binding_when_disabled_or_off_rank( self, annotation, local_rank, enabled diff --git a/vllm/config/profiler.py b/vllm/config/profiler.py index e7250a58e85e..c9f3238bb322 100644 --- a/vllm/config/profiler.py +++ b/vllm/config/profiler.py @@ -137,7 +137,8 @@ class ProfilerConfig: capture_torch_profiler: bool = False """If `True`, enables a torch profiler during GPU graph capture on rank 0. - Activities include CPU and the runner device (CUDA/ROCm or XPU). + Uses the same activities as serving (`torch_profiler_activities` or the + platform default). Traces are saved to a `capture_traces` subdirectory under `torch_profiler_dir`. Requires `profiler` to be set to 'torch'.""" diff --git a/vllm/profiler/graph_capture.py b/vllm/profiler/graph_capture.py index 9250ec1224f4..45f37bf7e6cb 100644 --- a/vllm/profiler/graph_capture.py +++ b/vllm/profiler/graph_capture.py @@ -25,7 +25,7 @@ from vllm.logger import init_logger from vllm.profiler.wrapper import ( TorchProfilerWrapper, - default_torch_profiler_activities, + create_worker_profiler, graph_capture_profiler_config, ) @@ -73,14 +73,10 @@ def make_graph_capture_profiler( worker_name = f"graph_capture_rank_{local_rank}" if subsystem: worker_name += f"_{subsystem}" - wrapper = TorchProfilerWrapper( - capture_config, - worker_name=worker_name, - local_rank=local_rank, - activities=default_torch_profiler_activities( - vllm_config.device_config.device_type - ), + wrapper = create_worker_profiler( + capture_config, worker_name=worker_name, local_rank=local_rank ) + assert isinstance(wrapper, TorchProfilerWrapper) # Serving creates wrapper.profiler only when a session starts. Capture # needs the same settings without starting that session. return wrapper.build_profiler() diff --git a/vllm/profiler/wrapper.py b/vllm/profiler/wrapper.py index a3c10411ad7d..cfed6bebab5b 100644 --- a/vllm/profiler/wrapper.py +++ b/vllm/profiler/wrapper.py @@ -10,7 +10,6 @@ from collections.abc import Callable, Iterator, Sequence from contextlib import AbstractContextManager, contextmanager, nullcontext, suppress from glob import glob -from typing import cast from uuid import uuid4 import torch @@ -226,18 +225,6 @@ def annotate_context_manager(self, name: str): } -def default_torch_profiler_activities(device_type: str) -> list[TorchProfilerActivity]: - """CPU plus the accelerator activity for a runner device. - - ``cuda`` covers CUDA and ROCm; ``xpu`` selects Intel GPU events. Device - types torch cannot profile fall back to CPU-only. - """ - accelerator = device_type.upper() - if accelerator == "CPU" or accelerator not in TorchProfilerActivityMap: - return ["CPU"] - return ["CPU", cast(TorchProfilerActivity, accelerator)] - - def graph_capture_profiler_config(profiler_config: ProfilerConfig) -> ProfilerConfig: """Apply one-shot graph-capture overrides to a profiler config.""" return replace(