diff --git a/tests/v1/worker/test_gpu_profiler.py b/tests/v1/worker/test_gpu_profiler.py index 6e73fe7815ac..4f35f9ca71c6 100644 --- a/tests/v1/worker/test_gpu_profiler.py +++ b/tests/v1/worker/test_gpu_profiler.py @@ -3,7 +3,7 @@ import json import os import threading -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 @@ -20,11 +20,18 @@ ) 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, + skip_graph_capture_tracing, +) from vllm.profiler.wrapper import ( ProtonProfilerWrapper, TorchProfilerWrapper, WorkerProfiler, create_worker_profiler, + graph_capture_profiler_config, validate_worker_profiler_config, ) from vllm.v1.core.sched.output import CachedRequestData @@ -735,17 +742,240 @@ def test_profiler_entered_during_capture(): confirming it is active during the actual graph capture run.""" 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, + ) + + profiler.__enter__.assert_called_once() + 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_graph_capture_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, + 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), 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( + profiler_config=ProfilerConfig( + profiler="torch", + torch_profiler_dir="/traces", + capture_torch_profiler=True, + ), + ) + built = MagicMock() + wrapper = MagicMock(spec=TorchProfilerWrapper) + wrapper.build_profiler.return_value = built + + with ( + patch.object( + graph_capture, "get_world_group", return_value=MagicMock(local_rank=0) + ), + patch.object( + 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 = create.call_args.args[0] + assert capture_config.torch_profiler_dir == "/traces/capture_traces" + 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. 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, + ), + ) + built = MagicMock() + + with ( + 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, + ): + profiler = graph_capture.make_graph_capture_profiler(config) + assert profiler is built + with profiler: + pass + + 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", + 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 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("local_rank,enabled", [(0, False), (1, True)]) + 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), + ), + graph_capture_profiler(config), + ): + assert graph_capture._active_binding.get() is None + with graph_capture_step(32, "FULL"): + pass + + annotation.assert_not_called() + + 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 - mock_profiler.__enter__.assert_called_once() - mock_profiler.__exit__.assert_called_once() + annotation.assert_not_called() + assert graph_capture._active_binding.get() is None def make_proton(session_id: int | None = 7): diff --git a/vllm/config/profiler.py b/vllm/config/profiler.py index 0ad920e21eda..c9f3238bb322 100644 --- a/vllm/config/profiler.py +++ b/vllm/config/profiler.py @@ -136,7 +136,9 @@ 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. + 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 new file mode 100644 index 000000000000..45f37bf7e6cb --- /dev/null +++ b/vllm/profiler/graph_capture.py @@ -0,0 +1,139 @@ +# 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 +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 +from vllm.profiler.wrapper import ( + TorchProfilerWrapper, + create_worker_profiler, + graph_capture_profiler_config, +) + +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) +) +_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( + vllm_config: VllmConfig, + subsystem: str | None = None, +) -> 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 None + + capture_config = graph_capture_profiler_config(profiler_config) + worker_name = f"graph_capture_rank_{local_rank}" + if subsystem: + worker_name += f"_{subsystem}" + 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() + + +@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: + 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. + 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``. + + """ + if _skip_capture_tracing.get() or _active_binding.get() is not None: + yield + return + + 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: + _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 unless a ``graph_capture_profiler`` block is + actively profiling, 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/profiler/wrapper.py b/vllm/profiler/wrapper.py index 57d6bc35530d..cfed6bebab5b 100644 --- a/vllm/profiler/wrapper.py +++ b/vllm/profiler/wrapper.py @@ -225,6 +225,22 @@ def annotate_context_manager(self, name: str): } +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, @@ -401,9 +417,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() diff --git a/vllm/v1/worker/encoder_cudagraph.py b/vllm/v1/worker/encoder_cudagraph.py index 51c832001ca8..0fef6a833f46 100644 --- a/vllm/v1/worker/encoder_cudagraph.py +++ b/vllm/v1/worker/encoder_cudagraph.py @@ -22,6 +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_profiler, graph_capture_step from vllm.utils.gpu_sync_debug import gpu_sync_allowed from vllm.utils.math_utils import round_up_to from vllm.utils.torch_utils import current_stream @@ -245,6 +246,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() @@ -326,6 +333,7 @@ def _capture_budget_graph( 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 995657462bf2..18c97a996ffe 100644 --- a/vllm/v1/worker/gpu/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/cudagraph_utils.py @@ -36,6 +36,11 @@ from vllm.model_executor.models.interfaces import requires_raw_input_tokens from vllm.model_executor.offloader.base import get_offloader from vllm.platforms import current_platform +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 @@ -442,7 +447,11 @@ def capture( stream: Capture on this stream instead of a new one. """ - with graph_capture(self.device, stream) as context, ExitStack() as stack: + with ( + graph_capture_profiler(self.vllm_config), + graph_capture(self.device, stream) as context, + ExitStack() as stack, + ): self.capture_stream = context.stream if self.ubatch_runner is not None: # Join parked threads on failure to avoid blocking later captures. @@ -482,12 +491,14 @@ 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}" @@ -500,6 +511,7 @@ def capture( torch.accelerator.synchronize() free_before = torch.accelerator.get_memory_info()[0] with ( + graph_capture_step(desc.num_tokens, desc.cg_mode.name), capture_pool(self.pool, self.vllm_config) as pool, torch.cuda.graph( graph, pool, stream=self._capture_stream(desc) @@ -1002,7 +1014,7 @@ def profile_cudagraph_memory(runner: "GPUModelRunner") -> int: mem_samples: list[int] = [] manager._capture_mem_samples = mem_samples - with capture_outside_cumem_pool(): + with skip_graph_capture_tracing(), capture_outside_cumem_pool(): measured = int(runner.capture_model(profile_only=True)) # The measured delta covers PIECEWISE, encoder and speculator graphs diff --git a/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py b/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py index 2e189da0c939..c8fe1e898cb2 100644 --- a/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py +++ b/vllm/v1/worker/gpu/spec_decode/dflash/cudagraph.py @@ -6,6 +6,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, @@ -128,4 +129,7 @@ def forward(cg_mode: CUDAGraphMode) -> None: return forward - 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/target_dependent_ar/cudagraph_utils.py b/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/cudagraph_utils.py index a7d3eb52b549..e325d40d8724 100644 --- a/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/cudagraph_utils.py @@ -6,6 +6,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.spec_decode.dynamic.utils import build_dynamic_sd_schedule_lookup from vllm.v1.worker.gpu.block_table import BlockTables @@ -114,4 +115,7 @@ def create_forward_fn( **forward_kwargs, ) - 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 d98498a4f97b..11c024d5a797 100644 --- a/vllm/v1/worker/gpu_model_runner.py +++ b/vllm/v1/worker/gpu_model_runner.py @@ -105,6 +105,11 @@ ) from vllm.platforms import current_platform from vllm.pooling_params import PoolingParams +from vllm.profiler.graph_capture import ( + graph_capture_profiler, + graph_capture_step, + skip_graph_capture_tracing, +) from vllm.sampling_params import SamplingType from vllm.sequence import IntermediateTensors from vllm.tasks import GenerationTask, PoolingTask, SupportedTask @@ -6312,7 +6317,11 @@ def profile_cudagraph_memory(self) -> int: # because encoder graph capture is opt-in. try: set_cudagraph_capturing_enabled(True) - with self._freeze_gc(), graph_capture(device=self.device): + with ( + skip_graph_capture_tracing(), + self._freeze_gc(), + graph_capture(device=self.device), + ): torch.accelerator.synchronize() torch.accelerator.empty_cache() @@ -6424,43 +6433,6 @@ 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 - ) - with self._freeze_gc(), graph_capture(device=self.device): torch.accelerator.synchronize() torch.accelerator.empty_cache() @@ -6473,7 +6445,6 @@ def capture_model(self) -> int: self._capture_cudagraphs( batch_descriptors=batch_descs, cudagraph_runtime_mode=runtime_mode, - profiler=profiler, ) torch.accelerator.synchronize() @@ -6517,10 +6488,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 @@ -6540,12 +6508,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, @@ -6562,7 +6525,6 @@ def _capture_cudagraphs( self, batch_descriptors: list[BatchDescriptor], cudagraph_runtime_mode: CUDAGraphMode, - profiler: AbstractContextManager[Any] | None = None, ): assert ( cudagraph_runtime_mode != CUDAGraphMode.NONE @@ -6572,6 +6534,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 @@ -6605,7 +6575,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)