Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
7144935
Add cuda graph capture profiling support for v2 runner
devalshahamd Aug 27, 2026
ca2cf3a
Merge branch 'main' into main
devalshahamd Aug 31, 2026
c8f8829
Merge remote-tracking branch 'upstream/main'
devalshahamd Sep 3, 2026
5268c4f
Merge branch 'main' into main
tjtanaa Sep 7, 2026
ccf4db5
Merge branch 'main' into main
devalshahamd Sep 11, 2026
03b525d
Merge branch 'main' of https://github.com/vllm-project/vllm into main
devalshahamd Sep 14, 2026
809c115
Use TorchProfilerWrapper to create capture profiler
devalshahamd Sep 14, 2026
2e1a22d
Moved profiler to the base capture function
devalshahamd Sep 15, 2026
8fb58bc
Merge branch 'main' into main
devalshahamd Sep 15, 2026
de8403b
Merge branch 'main' into main
devalshahamd Sep 15, 2026
f4a6cbb
Sort stdlib imports in profiler wrapper.
devalshahamd Sep 15, 2026
f0d20a1
Merge branch 'main' into main
devalshahamd Sep 15, 2026
6bcee19
Merge branch 'main' into main
devalshahamd Sep 15, 2026
e47d513
Restore single-line use_aux_hidden_state_outputs in V2 capture.
devalshahamd Sep 15, 2026
ac837b6
Merge branch 'main' into main
devalshahamd Sep 16, 2026
6da05d3
Merge branch 'main' into main
devalshahamd Sep 17, 2026
d9c4f84
Document vllm_config in graph_capture_profiler docstring.
devalshahamd Sep 17, 2026
cfec17a
Merge branch 'main' into main
devalshahamd Sep 21, 2026
1393529
Merge branch 'main' into main
devalshahamd Sep 24, 2026
0f23134
Merge branch 'main' into main
devalshahamd Oct 1, 2026
7e2ebd9
Merge branch 'main' into main
devalshahamd Oct 20, 2026
e66c4ce
Merge branch 'main' of https://github.com/devalshahamd/vllm
devalshahamd Oct 20, 2026
063d504
Merge branch 'main' into main
devalshahamd Oct 28, 2026
a063047
[Bugfix][Profiler] Build an unstarted profiler for graph capture
devalshahamd Oct 29, 2026
d1eb3d4
Merge branch 'main' into main
devalshahamd Oct 29, 2026
83312ea
[Profiler] Skip capture binding when graph-capture profiling is disabled
devalshahamd Oct 29, 2026
9cb7aae
[Profiler] Reuse serving's activity selection for graph-capture profi…
devalshahamd Oct 29, 2026
11bd32f
Merge branch 'main' into main
mergify[bot] Oct 30, 2026
632a3d2
Merge branch 'main' into main
mergify[bot] Nov 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 106 additions & 1 deletion tests/v1/worker/test_gpu_profiler.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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
Expand Down Expand Up @@ -349,6 +352,108 @@
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):

Check failure on line 393 in tests/v1/worker/test_gpu_profiler.py

View workflow job for this annotation

GitHub Actions / pre-commit

Ruff (SIM117)

tests/v1/worker/test_gpu_profiler.py:392:9: SIM117 Use a single `with` statement with multiple contexts instead of nested `with` statements
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),
Expand Down
127 changes: 127 additions & 0 deletions vllm/profiler/graph_capture.py
Original file line number Diff line number Diff line change
@@ -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.<timestamp>.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
2 changes: 2 additions & 0 deletions vllm/v1/worker/encoder_cudagraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_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 (
Expand Down Expand Up @@ -325,6 +326,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()),
):
Expand Down
14 changes: 10 additions & 4 deletions vllm/v1/worker/gpu/cudagraph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,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
Expand Down Expand Up @@ -392,12 +393,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}"
Expand All @@ -413,8 +418,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
Expand Down
48 changes: 31 additions & 17 deletions vllm/v1/worker/gpu/model_runner.py

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can the changes in this file be moved inside the respective capture methods?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @njhill Thanks for the suggestion!
I moved the binding into the capture methods themselves (CudaGraphManager.capture, the encoder/speculator managers, and V1 _capture_cudagraphs), so capture_model() no longer has to wrap anything. Nested speculator/encoder capture inherits the outer binding, and the throwaway memory-estimate run skips tracing.

Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,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.gc_utils import freeze_gc_for_cudagraph_capture
Expand Down Expand Up @@ -983,29 +984,42 @@ def capture_model(self, *, profile_only: bool = False) -> 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:
Expand Down
Loading
Loading