[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests
- Drop dead model modules, keeping files live imports require - Remove anthropic, cohere, codegen entrypoints and batch STT modes - Delete unused attention backends, MoE experts, and NPU/XPU util leaves - Strip dead third_party trees and ROCm leaves with no CUDA path - Remove mooncake EC connectors: dependency missing since branch base - Re-audit verified by full import sweep and Qwen3.5 smoke test Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,679 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Unit tests for the breakable cudagraph primitives."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
HAS_DEVICE_GRAPH = current_platform.is_cuda_alike() or current_platform.is_xpu()
|
||||
|
||||
if current_platform.is_xpu():
|
||||
from vllm.v1.worker.xpu_model_runner import _torch_cuda_wrapper
|
||||
|
||||
# Route torch.cuda graph/stream APIs to torch.xpu, as XPUModelRunner does.
|
||||
with _torch_cuda_wrapper():
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _enable_breakable_cudagraph(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Enable breakable cudagraphs for this module's tests only.
|
||||
|
||||
eager_break_during_capture reads the env at decoration time, which
|
||||
happens inside the test bodies, so a per-test fixture suffices.
|
||||
monkeypatch restores the env so other test files running in the same
|
||||
pytest process are unaffected (a module-level os.environ assignment
|
||||
used to leak into test_cudagraph_dispatch.py and break it).
|
||||
"""
|
||||
import vllm.envs as envs
|
||||
|
||||
monkeypatch.setenv("VLLM_USE_BREAKABLE_CUDAGRAPH", "1")
|
||||
envs.disable_envs_cache()
|
||||
|
||||
|
||||
def test_piecewise_capture_builds_fresh_metadata_for_both_passes():
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import (
|
||||
BatchExecutionDescriptor,
|
||||
CudaGraphManager,
|
||||
)
|
||||
|
||||
manager = CudaGraphManager.__new__(CudaGraphManager)
|
||||
desc = BatchExecutionDescriptor(CUDAGraphMode.PIECEWISE, 8, None)
|
||||
manager.device = torch.device("cpu")
|
||||
manager._capture_descs = {CUDAGraphMode.PIECEWISE: [desc]}
|
||||
manager._graphs_captured = False
|
||||
manager.use_breakable_cg = True
|
||||
manager.ubatch_runner = None
|
||||
|
||||
create_calls = []
|
||||
forward_calls = []
|
||||
|
||||
def create_forward_fn(desc_arg, warmup):
|
||||
assert desc_arg == desc
|
||||
metadata = {"layer": object()}
|
||||
create_calls.append((warmup, metadata))
|
||||
|
||||
def forward_fn(cg_mode):
|
||||
assert metadata
|
||||
forward_calls.append((warmup, cg_mode, metadata))
|
||||
|
||||
return forward_fn
|
||||
|
||||
with (
|
||||
patch(
|
||||
"vllm.v1.worker.gpu.cudagraph_utils.graph_capture",
|
||||
return_value=nullcontext(),
|
||||
),
|
||||
patch(
|
||||
"vllm.v1.worker.gpu.cudagraph_utils.is_global_first_rank",
|
||||
return_value=False,
|
||||
),
|
||||
):
|
||||
manager.capture(create_forward_fn)
|
||||
|
||||
assert [warmup for warmup, _ in create_calls] == [True, False]
|
||||
assert [mode for _, mode, _ in forward_calls] == [
|
||||
CUDAGraphMode.NONE,
|
||||
CUDAGraphMode.PIECEWISE,
|
||||
]
|
||||
assert create_calls[0][1] is not create_calls[1][1]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_breakable_tls():
|
||||
"""Defensively clear thread-local capture state between tests so a
|
||||
failure in one test can't leak "nested capture" errors into the next."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
BreakableCUDAGraphCapture._tls.active = None
|
||||
yield
|
||||
BreakableCUDAGraphCapture._tls.active = None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cuda_capture_stream():
|
||||
"""A non-default CUDA stream suitable for cudagraph capture.
|
||||
|
||||
``CUDAGraph.capture_begin`` refuses to capture from the default
|
||||
stream, so all capture-using tests need to run under
|
||||
``torch.cuda.stream(...)`` for a separate stream.
|
||||
"""
|
||||
if not HAS_DEVICE_GRAPH:
|
||||
pytest.skip("CUDA or XPU graph required")
|
||||
from vllm.utils.torch_utils import _current_stream_tls
|
||||
|
||||
prev_stream = getattr(_current_stream_tls, "value", None)
|
||||
stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(stream):
|
||||
yield stream
|
||||
torch.cuda.current_stream().wait_stream(stream)
|
||||
# Exiting torch.cuda.stream() records the default stream in vllm's
|
||||
# patched set_stream cache. A later CUDAGraphWrapper capture in the same
|
||||
# process would then run on the default stream, which cannot capture
|
||||
# (this broke test_cudagraph_dispatch.py when run in-process after this
|
||||
# file). Restore the pre-fixture value so this module leaves no trace.
|
||||
_current_stream_tls.value = prev_stream
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# eager_break_during_capture: outside capture
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_decorator_passthrough_outside_capture():
|
||||
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
|
||||
|
||||
calls = []
|
||||
|
||||
@eager_break_during_capture
|
||||
def f(x):
|
||||
calls.append(x)
|
||||
return x * 2
|
||||
|
||||
assert f(3) == 6
|
||||
assert calls == [3]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BreakableCUDAGraphCapture: thread-local + nested rejection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_current_is_none_when_inactive():
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
assert BreakableCUDAGraphCapture.is_active() is False
|
||||
|
||||
|
||||
def test_thread_local_active_during_context(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
assert BreakableCUDAGraphCapture.current() is cap
|
||||
assert BreakableCUDAGraphCapture.is_active() is True
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
|
||||
|
||||
def test_nested_capture_raises(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
outer = BreakableCUDAGraphCapture()
|
||||
inner = BreakableCUDAGraphCapture()
|
||||
with outer, pytest.raises(RuntimeError, match="Nested.*not supported"), inner:
|
||||
pass
|
||||
|
||||
|
||||
def test_active_state_isolated_across_threads(cuda_capture_stream):
|
||||
"""Verify the thread-local 'active capture' slot is per-thread.
|
||||
|
||||
We don't run concurrent captures here -- CUDA only supports one
|
||||
in-flight capture per stream and we keep tests cheap. We just check
|
||||
that the worker thread sees its own slot as None while the main
|
||||
thread has a capture active.
|
||||
"""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
worker_view: dict[str, BreakableCUDAGraphCapture | None] = {}
|
||||
|
||||
def worker():
|
||||
worker_view["state"] = BreakableCUDAGraphCapture.current()
|
||||
|
||||
main_cap = BreakableCUDAGraphCapture()
|
||||
with main_cap:
|
||||
# Main thread has a live capture.
|
||||
assert BreakableCUDAGraphCapture.current() is main_cap
|
||||
t = threading.Thread(target=worker)
|
||||
t.start()
|
||||
t.join()
|
||||
|
||||
# Worker thread saw None -- thread-local separation works.
|
||||
assert worker_view["state"] is None
|
||||
# Main thread's slot is cleared on exit.
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Segment list construction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_capture_with_no_eager_break_records_one_graph(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0)
|
||||
assert len(cap.segments) == 1
|
||||
assert cap.num_graphs == 1
|
||||
assert cap.num_eager_breaks == 0
|
||||
|
||||
|
||||
def test_add_eager_creates_alternating_graph_eager_graph(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
counter = {"eager_calls": 0}
|
||||
|
||||
def eager_step():
|
||||
counter["eager_calls"] += 1
|
||||
x.add_(10.0)
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0)
|
||||
cap.add_eager(eager_step)
|
||||
x.add_(1.0)
|
||||
cap.add_eager(eager_step)
|
||||
x.add_(1.0)
|
||||
# 3 graph segments + 2 eager segments, interleaved as G E G E G.
|
||||
assert len(cap.segments) == 5
|
||||
assert cap.num_graphs == 3
|
||||
assert cap.num_eager_breaks == 2
|
||||
# Eager fn is stored as-is in the segment list, so we can confirm
|
||||
# the alternation pattern by identity check.
|
||||
assert cap.segments[1] is eager_step
|
||||
assert cap.segments[3] is eager_step
|
||||
assert counter["eager_calls"] == 2 # only the in-capture invocation
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Capture vs eager numerical equivalence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_capture_replay_matches_eager_simple(cuda_capture_stream):
|
||||
"""Verify that replay reproduces the same end-state as a single eager
|
||||
forward, with an eager break in the middle.
|
||||
|
||||
Note: during capture, the *captured* kernels are recorded but NOT
|
||||
executed (that's CUDA-graph semantics). Only the eager segments
|
||||
actually mutate state at capture time. So we check correctness after
|
||||
``replay()``, not after ``with cap:`` exits.
|
||||
"""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
x = torch.zeros(8, device=DEVICE_TYPE)
|
||||
log: list[str] = []
|
||||
|
||||
def eager_break_op():
|
||||
x.mul_(2.0)
|
||||
log.append("eager")
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0) # recorded into graph[0]
|
||||
cap.add_eager(eager_break_op) # runs eagerly: x *= 2
|
||||
x.add_(5.0) # recorded into graph[1]
|
||||
|
||||
# Capture-time: graph kernels were recorded only; eager segment ran
|
||||
# once on x == 0, leaving x == 0.
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.zeros(8, device=DEVICE_TYPE))
|
||||
assert log == ["eager"]
|
||||
|
||||
# Replay with a fresh input: 10 -> 11 -> 22 -> 27.
|
||||
x.fill_(10.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((8,), 27.0, device=DEVICE_TYPE))
|
||||
assert log == ["eager", "eager"]
|
||||
|
||||
# Replay again with another input: 100 -> 101 -> 202 -> 207.
|
||||
x.fill_(100.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((8,), 207.0, device=DEVICE_TYPE))
|
||||
assert log == ["eager", "eager", "eager"]
|
||||
|
||||
|
||||
def test_decorator_breaks_when_invoked_inside_capture(cuda_capture_stream):
|
||||
"""Verify @eager_break_during_capture correctly routes through
|
||||
add_eager when inside a capture context, and runs straight through
|
||||
when there's no active capture."""
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
|
||||
@eager_break_during_capture
|
||||
def attention_like(t: torch.Tensor) -> None:
|
||||
# In-place double; stands in for "real" attention work.
|
||||
t.mul_(2.0)
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
|
||||
# Outside capture: decorator should just call through.
|
||||
x.fill_(3.0)
|
||||
attention_like(x)
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((4,), 6.0, device=DEVICE_TYPE))
|
||||
|
||||
# Inside capture: decorator should split the graph. Only the eager
|
||||
# segment actually mutates state during capture.
|
||||
x.fill_(0.0)
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(5.0) # recorded
|
||||
attention_like(x) # eager: x *= 2 (on x == 0, no-op)
|
||||
x.add_(1.0) # recorded
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.zeros(4, device=DEVICE_TYPE))
|
||||
# 2 graph segments + 1 eager segment, ordered G E G; the arithmetic
|
||||
# equivalence check below verifies the ordering.
|
||||
assert len(cap.segments) == 3
|
||||
assert cap.num_graphs == 2
|
||||
assert cap.num_eager_breaks == 1
|
||||
|
||||
# Replay: 2 -> 7 -> 14 -> 15.
|
||||
x.fill_(2.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert torch.equal(x, torch.full((4,), 15.0, device=DEVICE_TYPE))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keyword", [False, True])
|
||||
def test_quantized_activation_replay_does_not_retain_tensors(
|
||||
cuda_capture_stream, keyword
|
||||
):
|
||||
"""Release the producer tensors while preserving both buffers on replay."""
|
||||
import gc
|
||||
import weakref
|
||||
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
|
||||
|
||||
@eager_break_during_capture
|
||||
def consume(x, data_out, scale_out):
|
||||
data_out.copy_(x.data)
|
||||
scale_out.copy_(x.scale)
|
||||
|
||||
source = torch.ones((128, 128), device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
data_out = source.to(torch.float8_e4m3fn)
|
||||
scale_out = source[:, ::32].to(torch.uint8)
|
||||
output = torch.empty_like(source)
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
data = source.to(torch.float8_e4m3fn)
|
||||
scale = source[:, ::32].to(torch.uint8)
|
||||
activation = QuantizedActivation(
|
||||
data, scale, source.dtype, source.shape, kMxfp8Dynamic
|
||||
)
|
||||
data_ref, scale_ref = weakref.ref(data), weakref.ref(scale)
|
||||
if keyword:
|
||||
consume(x=activation, data_out=data_out, scale_out=scale_out)
|
||||
else:
|
||||
consume(activation, data_out, scale_out)
|
||||
output.copy_(data_out)
|
||||
|
||||
del data, scale, activation
|
||||
gc.collect()
|
||||
assert data_ref() is None
|
||||
assert scale_ref() is None
|
||||
|
||||
for value in (1, 2, 3):
|
||||
source.fill_(value)
|
||||
cap.replay()
|
||||
cuda_capture_stream.synchronize()
|
||||
torch.testing.assert_close(output, source, rtol=0, atol=0)
|
||||
torch.testing.assert_close(scale_out, source[:, ::32].to(torch.uint8))
|
||||
|
||||
|
||||
def test_eager_attention_inside_multistream_overlap(cuda_capture_stream):
|
||||
"""Handle an eager attention break inside a multi-stream overlap region."""
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
from vllm.utils.multi_stream_utils import maybe_execute_in_parallel
|
||||
|
||||
x = torch.zeros(1024, device=DEVICE_TYPE)
|
||||
output = torch.empty_like(x)
|
||||
aux_stream = torch.cuda.Stream()
|
||||
main_event = torch.cuda.Event()
|
||||
aux_event = torch.cuda.Event()
|
||||
|
||||
@eager_break_during_capture
|
||||
def attention(query: torch.Tensor, out: torch.Tensor) -> None:
|
||||
torch.add(query, 3.0, out=out)
|
||||
|
||||
def attention_frontend() -> torch.Tensor:
|
||||
query = x * 2.0
|
||||
attention_output = torch.empty_like(x)
|
||||
attention(query, attention_output)
|
||||
return attention_output
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
attention_output, gate = maybe_execute_in_parallel(
|
||||
attention_frontend,
|
||||
lambda: x * 5.0,
|
||||
main_event,
|
||||
aux_event,
|
||||
aux_stream,
|
||||
)
|
||||
torch.add(attention_output, gate, out=output)
|
||||
|
||||
assert cap.num_graphs == 2
|
||||
assert cap.num_eager_breaks == 1
|
||||
|
||||
for value in (1.0, 7.0, 19.0):
|
||||
x.fill_(value)
|
||||
cap.replay()
|
||||
cuda_capture_stream.synchronize()
|
||||
torch.testing.assert_close(
|
||||
output,
|
||||
torch.full_like(output, value * 7.0 + 3.0),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Replay ordering
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_replay_invokes_eager_segments_in_order(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
log: list[str] = []
|
||||
x = torch.zeros(1, device=DEVICE_TYPE)
|
||||
|
||||
def make_eager(name):
|
||||
def step():
|
||||
log.append(name)
|
||||
x.add_(1.0)
|
||||
|
||||
return step
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(1.0)
|
||||
cap.add_eager(make_eager("A"))
|
||||
x.add_(1.0)
|
||||
cap.add_eager(make_eager("B"))
|
||||
x.add_(1.0)
|
||||
cap.add_eager(make_eager("C"))
|
||||
x.add_(1.0)
|
||||
|
||||
# Capture-time invocation order
|
||||
assert log == ["A", "B", "C"]
|
||||
|
||||
log.clear()
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
assert log == ["A", "B", "C"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Capture cleanup releases thread-local even if body raises
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_exception_in_body_clears_active(cuda_capture_stream):
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with pytest.raises(RuntimeError, match="boom"), cap:
|
||||
raise RuntimeError("boom")
|
||||
|
||||
# active must be reset even after an exception inside the body
|
||||
assert BreakableCUDAGraphCapture.current() is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Nested decorated ops: inner op must not trigger a recursive eager break
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_nested_decorated_op_runs_inline(cuda_capture_stream):
|
||||
"""A decorated op invoked from inside another decorated op's eager
|
||||
body must execute inline -- starting a second eager break mid-flight
|
||||
corrupts the segment state and explodes ``_begin_segment``'s assert.
|
||||
|
||||
This mirrors the deepseek_v4_attention case where the outer attention
|
||||
op's impl internally dispatches sparse_attn_indexer (also decorated).
|
||||
"""
|
||||
from vllm.compilation.breakable_cudagraph import (
|
||||
BreakableCUDAGraphCapture,
|
||||
eager_break_during_capture,
|
||||
)
|
||||
|
||||
x = torch.zeros(4, device=DEVICE_TYPE)
|
||||
inner_calls = 0
|
||||
|
||||
@eager_break_during_capture
|
||||
def inner_op(t: torch.Tensor) -> None:
|
||||
nonlocal inner_calls
|
||||
inner_calls += 1
|
||||
t.add_(1.0)
|
||||
|
||||
@eager_break_during_capture
|
||||
def outer_op(t: torch.Tensor) -> None:
|
||||
# outer body calls another decorated op -- this is the case that
|
||||
# used to assert in _begin_segment.
|
||||
inner_op(t)
|
||||
t.add_(10.0)
|
||||
|
||||
cap = BreakableCUDAGraphCapture()
|
||||
with cap:
|
||||
x.add_(2.0) # recorded in graph[0]
|
||||
outer_op(x) # one eager break, inner runs inline
|
||||
x.add_(100.0) # recorded in graph[1]
|
||||
|
||||
# Exactly one eager break (the outer); inner must NOT add a second.
|
||||
assert cap.num_graphs == 2
|
||||
assert cap.num_eager_breaks == 1
|
||||
assert inner_calls == 1 # only the capture-time invocation
|
||||
|
||||
x.fill_(0.0)
|
||||
cap.replay()
|
||||
torch.accelerator.synchronize()
|
||||
# 0 -> +2 -> +1 (inner) -> +10 (outer) -> +100 = 113
|
||||
assert torch.equal(x, torch.full((4,), 113.0, device=DEVICE_TYPE))
|
||||
assert inner_calls == 2 # replay invokes the outer's lambda again
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BreakableCUDAGraphWrapper: runtime_mode dispatch gating
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _mock_vllm_config():
|
||||
config = MagicMock()
|
||||
config.parallel_config.data_parallel_size = 1
|
||||
config.parallel_config.use_sequence_parallel_moe = False
|
||||
config.parallel_config.is_moe_model = False
|
||||
return config
|
||||
|
||||
|
||||
def test_wrapper_falls_through_on_runtime_mode_mismatch():
|
||||
"""A PIECEWISE-scoped wrapper runs other modes eagerly, capturing
|
||||
nothing, so an outer CUDAGraphWrapper can own them."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
|
||||
calls = []
|
||||
|
||||
def model(x):
|
||||
calls.append(x)
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
wrapper = BreakableCUDAGraphWrapper(
|
||||
model, config, runtime_mode=CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
desc = BatchDescriptor(num_tokens=4)
|
||||
|
||||
with set_forward_context(
|
||||
None,
|
||||
config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=desc,
|
||||
):
|
||||
assert wrapper(1) == 2
|
||||
|
||||
assert calls == [1]
|
||||
assert not wrapper.entries
|
||||
|
||||
|
||||
def test_wrapper_captures_on_runtime_mode_match():
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
|
||||
calls = []
|
||||
|
||||
def model(x):
|
||||
calls.append(x)
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
wrapper = BreakableCUDAGraphWrapper(
|
||||
model, config, runtime_mode=CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
desc = BatchDescriptor(num_tokens=4)
|
||||
|
||||
sentinel = object()
|
||||
with (
|
||||
patch.object(
|
||||
BreakableCUDAGraphWrapper, "_capture", return_value=sentinel
|
||||
) as mock_capture,
|
||||
set_forward_context(
|
||||
None,
|
||||
config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
|
||||
batch_descriptor=desc,
|
||||
),
|
||||
):
|
||||
assert wrapper(1) is sentinel
|
||||
|
||||
mock_capture.assert_called_once()
|
||||
assert calls == []
|
||||
assert desc in wrapper.entries
|
||||
|
||||
|
||||
def test_wrapper_default_matches_any_non_none_mode():
|
||||
"""runtime_mode=None matches any non-NONE mode (MRV2 relies on this)."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
|
||||
def model(x):
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
wrapper = BreakableCUDAGraphWrapper(model, config)
|
||||
desc = BatchDescriptor(num_tokens=4)
|
||||
|
||||
sentinel = object()
|
||||
with (
|
||||
patch.object(
|
||||
BreakableCUDAGraphWrapper, "_capture", return_value=sentinel
|
||||
) as mock_capture,
|
||||
set_forward_context(
|
||||
None,
|
||||
config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=desc,
|
||||
),
|
||||
):
|
||||
assert wrapper(1) is sentinel
|
||||
|
||||
mock_capture.assert_called_once()
|
||||
assert desc in wrapper.entries
|
||||
|
||||
|
||||
def test_unwrap_recurses_through_nested_wrappers():
|
||||
"""unwrap() reaches the raw model through nested wrappers."""
|
||||
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphWrapper
|
||||
from vllm.compilation.cuda_graph import CUDAGraphWrapper
|
||||
from vllm.config import CUDAGraphMode
|
||||
|
||||
def model(x):
|
||||
return x + 1
|
||||
|
||||
config = _mock_vllm_config()
|
||||
inner = BreakableCUDAGraphWrapper(
|
||||
model, config, runtime_mode=CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
outer = CUDAGraphWrapper(inner, config, runtime_mode=CUDAGraphMode.FULL)
|
||||
|
||||
assert inner.unwrap() is model
|
||||
assert outer.unwrap() is model
|
||||
@@ -1,578 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import replace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from tests.utils import create_new_process_for_each_test
|
||||
from vllm.compilation.cuda_graph import CUDAGraphWrapper
|
||||
from vllm.compilation.monitor import set_cudagraph_capturing_enabled
|
||||
from vllm.config import (
|
||||
CompilationConfig,
|
||||
CompilationMode,
|
||||
CUDAGraphMode,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.config.lora import LoRAConfig
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.cudagraph_dispatcher import CudagraphDispatcher
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
HAS_DEVICE_GRAPH = current_platform.is_cuda() or current_platform.is_xpu()
|
||||
|
||||
if current_platform.is_xpu():
|
||||
from vllm.v1.worker.xpu_model_runner import _torch_cuda_wrapper
|
||||
|
||||
# Route torch.cuda graph/stream APIs to torch.xpu, as XPUModelRunner does.
|
||||
with _torch_cuda_wrapper():
|
||||
pass
|
||||
|
||||
|
||||
# Helper MLP for testing
|
||||
class SimpleMLP(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.fc1 = nn.Linear(10, 10)
|
||||
self.fc2 = nn.Linear(10, 10)
|
||||
|
||||
def forward(self, x):
|
||||
return self.fc2(self.fc1(x))
|
||||
|
||||
|
||||
def _create_vllm_config(
|
||||
compilation_config: CompilationConfig,
|
||||
max_num_seqs: int = 8,
|
||||
lora_config: bool = False,
|
||||
) -> MagicMock:
|
||||
mock_config = MagicMock(spec=VllmConfig)
|
||||
mock_config.compilation_config = compilation_config
|
||||
mock_config.scheduler_config = SchedulerConfig.default_factory(
|
||||
max_num_seqs=max_num_seqs,
|
||||
)
|
||||
mock_config.parallel_config = ParallelConfig()
|
||||
mock_config.speculative_config = None # No speculative decoding
|
||||
mock_config.num_speculative_tokens = 0
|
||||
mock_config.use_cumem_cudagraph_pool = False
|
||||
if not lora_config:
|
||||
mock_config.lora_config = None
|
||||
else:
|
||||
# Create a real LoRAConfig with specialize_active_lora enabled
|
||||
mock_config.lora_config = LoRAConfig(
|
||||
max_loras=4,
|
||||
specialize_active_lora=True,
|
||||
)
|
||||
# Mimic the behavior of VllmConfig.__post_init__()
|
||||
if compilation_config.mode == CompilationMode.VLLM_COMPILE:
|
||||
compilation_config.set_splitting_ops_for_v1(
|
||||
all2all_backend=mock_config.parallel_config.all2all_backend,
|
||||
data_parallel_size=mock_config.parallel_config.data_parallel_size,
|
||||
)
|
||||
|
||||
# mimic VllmConfig.__post_init__
|
||||
if compilation_config.cudagraph_capture_sizes:
|
||||
compilation_config.max_cudagraph_capture_size = (
|
||||
compilation_config.cudagraph_capture_sizes[-1]
|
||||
)
|
||||
|
||||
compilation_config.post_init_cudagraph_sizes()
|
||||
|
||||
return mock_config
|
||||
|
||||
|
||||
class TestCudagraphDispatcher:
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode_str,compilation_mode,lora_config",
|
||||
[
|
||||
# Test case 0: Full CG for mixed batches, no separate routine
|
||||
("FULL", CompilationMode.NONE, False),
|
||||
# Test case 1: Full CG for uniform batches, piecewise for mixed
|
||||
("FULL_AND_PIECEWISE", CompilationMode.NONE, False),
|
||||
# Test case 2: Full CG for uniform batches, no CG for mixed
|
||||
("FULL_DECODE_ONLY", CompilationMode.NONE, False),
|
||||
# Test case 3: PIECEWISE for all
|
||||
("PIECEWISE", CompilationMode.VLLM_COMPILE, False),
|
||||
# Test case 4: PIECEWISE for all, specialize LoRA cases
|
||||
("PIECEWISE", CompilationMode.VLLM_COMPILE, True),
|
||||
],
|
||||
)
|
||||
def test_dispatcher(self, cudagraph_mode_str, compilation_mode, lora_config):
|
||||
# Setup dispatcher
|
||||
comp_config = CompilationConfig(
|
||||
cudagraph_mode=cudagraph_mode_str,
|
||||
mode=compilation_mode,
|
||||
cudagraph_capture_sizes=[1, 8],
|
||||
)
|
||||
|
||||
config = _create_vllm_config(
|
||||
comp_config, max_num_seqs=8, lora_config=lora_config
|
||||
)
|
||||
if (
|
||||
cudagraph_mode_str == "FULL_AND_PIECEWISE"
|
||||
and compilation_mode == CompilationMode.NONE
|
||||
):
|
||||
with pytest.raises(AssertionError):
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
return
|
||||
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
cudagraph_mode=comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
|
||||
# Verify the key is initialized correctly
|
||||
# With LoRA specialization (max_loras=4, specialize_active_lora=True):
|
||||
# - lora_cases = [0, 1, 2, 4, 5] (no-lora + powers of 2 up to 4 + max_loras+1)
|
||||
# - capture_sizes = [1, 8]
|
||||
# - Total keys = 2 sizes × 5 lora_cases = 10
|
||||
if cudagraph_mode_str in ["FULL_AND_PIECEWISE", "PIECEWISE"]:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.PIECEWISE]) == (
|
||||
10 if lora_config else 2
|
||||
)
|
||||
else:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.PIECEWISE]) == 0
|
||||
if cudagraph_mode_str not in ["NONE", "PIECEWISE"]:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.FULL]) == (
|
||||
10 if lora_config else 2
|
||||
)
|
||||
else:
|
||||
assert len(dispatcher.cudagraph_keys[CUDAGraphMode.FULL]) == 0
|
||||
|
||||
# Test dispatch logic
|
||||
# 1. non-uniform batch, size in cudagraph size list
|
||||
# FULL mode uses exact keys with num_reqs set
|
||||
desc_full_with_reqs = BatchDescriptor(num_tokens=8, num_reqs=8, uniform=False)
|
||||
# PIECEWISE mode uses relaxed keys with num_reqs=None
|
||||
desc_piecewise = BatchDescriptor(num_tokens=8, num_reqs=None, uniform=False)
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8, uniform_decode=False, has_lora=False
|
||||
)
|
||||
if cudagraph_mode_str == "FULL":
|
||||
assert rt_mode == CUDAGraphMode.FULL
|
||||
assert key == desc_full_with_reqs
|
||||
elif cudagraph_mode_str in ["FULL_AND_PIECEWISE", "PIECEWISE"]:
|
||||
assert rt_mode == CUDAGraphMode.PIECEWISE
|
||||
assert key == desc_piecewise
|
||||
else:
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
|
||||
# 2. uniform decode batch, size in cudagraph size list
|
||||
desc_uniform_exact = BatchDescriptor(num_tokens=8, num_reqs=8, uniform=True)
|
||||
desc_non_uniform = BatchDescriptor(num_tokens=8, num_reqs=8, uniform=False)
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8, uniform_decode=True, has_lora=False
|
||||
)
|
||||
if cudagraph_mode_str == "FULL":
|
||||
# Pure FULL mode uses non-uniform keys for all batches
|
||||
assert rt_mode == CUDAGraphMode.FULL
|
||||
assert key == desc_non_uniform
|
||||
elif cudagraph_mode_str in ["FULL_DECODE_ONLY", "FULL_AND_PIECEWISE"]:
|
||||
# These modes have separate uniform decode keys
|
||||
assert rt_mode == CUDAGraphMode.FULL
|
||||
assert key == desc_uniform_exact
|
||||
elif cudagraph_mode_str == "PIECEWISE":
|
||||
assert rt_mode == CUDAGraphMode.PIECEWISE
|
||||
assert key == replace(desc_uniform_exact, num_reqs=None, uniform=False)
|
||||
else:
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
|
||||
# 3. No key match
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=15, uniform_decode=False, has_lora=False
|
||||
)
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
assert key == BatchDescriptor(num_tokens=15)
|
||||
|
||||
# 4. invalid_modes={FULL} should have a fall back mode
|
||||
desc_full_exact = BatchDescriptor(num_tokens=8, uniform=False)
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8,
|
||||
uniform_decode=False,
|
||||
has_lora=False,
|
||||
invalid_modes={CUDAGraphMode.FULL},
|
||||
)
|
||||
|
||||
if "PIECEWISE" in cudagraph_mode_str: # string contains check
|
||||
assert rt_mode == CUDAGraphMode.PIECEWISE
|
||||
assert key == replace(desc_full_exact, num_reqs=None, uniform=False)
|
||||
else:
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
|
||||
# 5. valid_modes={NONE} always returns NONE even when keys exist
|
||||
rt_mode, key = dispatcher.dispatch(
|
||||
num_tokens=8,
|
||||
uniform_decode=False,
|
||||
has_lora=False,
|
||||
valid_modes={CUDAGraphMode.NONE},
|
||||
)
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
assert key == BatchDescriptor(num_tokens=8)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode_str,compilation_mode,expected_modes",
|
||||
[
|
||||
# FULL mode: only FULL keys, no PIECEWISE
|
||||
("FULL", CompilationMode.NONE, [CUDAGraphMode.FULL]),
|
||||
# PIECEWISE mode: only PIECEWISE keys
|
||||
("PIECEWISE", CompilationMode.VLLM_COMPILE, [CUDAGraphMode.PIECEWISE]),
|
||||
# FULL_DECODE_ONLY: only FULL keys for uniform decode
|
||||
("FULL_DECODE_ONLY", CompilationMode.NONE, [CUDAGraphMode.FULL]),
|
||||
# NONE mode: no keys
|
||||
("NONE", CompilationMode.NONE, []),
|
||||
],
|
||||
)
|
||||
def test_get_capture_descs(
|
||||
self, cudagraph_mode_str, compilation_mode, expected_modes
|
||||
):
|
||||
"""Test get_capture_descs returns correctly grouped and ordered descs."""
|
||||
comp_config = CompilationConfig(
|
||||
cudagraph_mode=cudagraph_mode_str,
|
||||
mode=compilation_mode,
|
||||
cudagraph_capture_sizes=[1, 4, 8, 16],
|
||||
)
|
||||
|
||||
config = _create_vllm_config(comp_config, max_num_seqs=16)
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
cudagraph_mode=comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
|
||||
capture_descs = dispatcher.get_capture_descs()
|
||||
|
||||
# Verify we get the expected modes
|
||||
actual_modes = [mode for mode, _ in capture_descs]
|
||||
assert actual_modes == expected_modes
|
||||
|
||||
# Verify each group is sorted largest-first
|
||||
for mode, descs in capture_descs:
|
||||
assert len(descs) > 0, "Each group should have at least one descriptor"
|
||||
num_tokens_list = [d.num_tokens for d in descs]
|
||||
assert num_tokens_list == sorted(num_tokens_list, reverse=True), (
|
||||
f"Descriptors for {mode} should be sorted largest-first"
|
||||
)
|
||||
|
||||
# All descriptors in a group should have same uniform value
|
||||
uniform_values = [d.uniform for d in descs]
|
||||
assert len(set(uniform_values)) == 1, (
|
||||
"All descriptors in a group should have the same uniform value"
|
||||
)
|
||||
|
||||
def test_get_capture_descs_empty_when_not_initialized(self):
|
||||
"""Test that get_capture_descs returns empty list when keys not initialized."""
|
||||
comp_config = CompilationConfig(
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
mode=CompilationMode.NONE,
|
||||
cudagraph_capture_sizes=[1, 8],
|
||||
)
|
||||
config = _create_vllm_config(comp_config, max_num_seqs=8)
|
||||
dispatcher = CudagraphDispatcher(config)
|
||||
# Don't initialize keys
|
||||
|
||||
assert dispatcher.get_capture_descs() == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(not HAS_DEVICE_GRAPH, reason="Requires CUDA or XPU graph")
|
||||
class TestCUDAGraphWrapper:
|
||||
def setup_method(self):
|
||||
self.vllm_config = _create_vllm_config(CompilationConfig())
|
||||
self.model = SimpleMLP().to(DEVICE_TYPE)
|
||||
self.persistent_input_buffer = torch.zeros(1, 10, device=DEVICE_TYPE)
|
||||
self.input_tensor = torch.randn(1, 10, device=DEVICE_TYPE)
|
||||
|
||||
def test_capture_and_replay(self):
|
||||
wrapper = CUDAGraphWrapper(
|
||||
self.model, self.vllm_config, runtime_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
batch_descriptor = BatchDescriptor(num_tokens=10)
|
||||
|
||||
# 0. global warmup
|
||||
with set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=None,
|
||||
):
|
||||
wrapper(self.input_tensor)
|
||||
|
||||
# 1. Capture
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_cuda_graph,
|
||||
):
|
||||
output1 = wrapper(self.input_tensor)
|
||||
# capturing phase should generate a zero output
|
||||
assert torch.allclose(output1, torch.zeros_like(output1))
|
||||
mock_cuda_graph.assert_called_once()
|
||||
|
||||
assert batch_descriptor in wrapper.concrete_cudagraph_entries
|
||||
entry = wrapper.concrete_cudagraph_entries[batch_descriptor]
|
||||
assert entry.cudagraph is not None
|
||||
|
||||
# 2. Replay
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.FULL,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch.object(
|
||||
entry.cudagraph, "replay", wraps=entry.cudagraph.replay
|
||||
) as mock_replay,
|
||||
):
|
||||
output2 = wrapper(self.input_tensor)
|
||||
mock_replay.assert_called_once()
|
||||
|
||||
# Compare with eager output
|
||||
eager_output = self.model(self.input_tensor)
|
||||
torch.testing.assert_close(eager_output, output2)
|
||||
|
||||
def test_bypass_on_mode_mismatch(self):
|
||||
wrapper = CUDAGraphWrapper(
|
||||
self.model, self.vllm_config, runtime_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
batch_descriptor = BatchDescriptor(num_tokens=10)
|
||||
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.PIECEWISE,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_cuda_graph,
|
||||
patch.object(
|
||||
self.model, "forward", wraps=self.model.forward
|
||||
) as mock_forward,
|
||||
):
|
||||
wrapper(self.input_tensor)
|
||||
mock_cuda_graph.assert_not_called()
|
||||
mock_forward.assert_called_once()
|
||||
assert not wrapper.concrete_cudagraph_entries
|
||||
|
||||
def test_bypass_on_mode_none(self):
|
||||
wrapper = CUDAGraphWrapper(
|
||||
self.model, self.vllm_config, runtime_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
batch_descriptor = BatchDescriptor(num_tokens=10)
|
||||
|
||||
with (
|
||||
set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=self.vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=batch_descriptor,
|
||||
),
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_cuda_graph,
|
||||
):
|
||||
wrapper(self.input_tensor)
|
||||
mock_cuda_graph.assert_not_called()
|
||||
assert not wrapper.concrete_cudagraph_entries
|
||||
|
||||
|
||||
def _run_and_monitor_call(
|
||||
wrapper, input_tensor, runtime_mode, batch_descriptor, vllm_config
|
||||
):
|
||||
"""Helper to run a single call and monitor the action."""
|
||||
with (
|
||||
patch("torch.cuda.graph", wraps=torch.cuda.graph) as mock_graph_context,
|
||||
patch.object(wrapper, "runnable", wraps=wrapper.runnable) as mock_runnable,
|
||||
):
|
||||
entry = wrapper.concrete_cudagraph_entries.get(batch_descriptor, None)
|
||||
|
||||
context = set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=vllm_config,
|
||||
cudagraph_runtime_mode=runtime_mode,
|
||||
batch_descriptor=batch_descriptor,
|
||||
)
|
||||
mock_replay = MagicMock()
|
||||
if entry and entry.cudagraph:
|
||||
with (
|
||||
context,
|
||||
patch.object(
|
||||
entry.cudagraph, "replay", new_callable=MagicMock
|
||||
) as mock_replay,
|
||||
):
|
||||
wrapper(input_tensor)
|
||||
else:
|
||||
with context:
|
||||
wrapper(input_tensor)
|
||||
|
||||
if mock_graph_context.called:
|
||||
# note that this is globally mocked, so it will be detected
|
||||
# even whether called by the inner or outer wrapper
|
||||
return "capture_global"
|
||||
if mock_replay.called:
|
||||
# only for outer wrapper
|
||||
return "replay"
|
||||
if mock_runnable.call_count > 0:
|
||||
# only for outer wrapper
|
||||
return "bypass"
|
||||
return "unknown"
|
||||
|
||||
|
||||
@create_new_process_for_each_test("spawn")
|
||||
@pytest.mark.skipif(not HAS_DEVICE_GRAPH, reason="Requires CUDA or XPU graph")
|
||||
def test_capture_replay_bypass_logic():
|
||||
comp_config = CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
cudagraph_capture_sizes=[1, 2],
|
||||
)
|
||||
vllm_config = _create_vllm_config(comp_config)
|
||||
dispatcher = CudagraphDispatcher(vllm_config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
model = SimpleMLP().to(DEVICE_TYPE)
|
||||
full_wrapper = CUDAGraphWrapper(model, vllm_config, CUDAGraphMode.FULL)
|
||||
max_bs = 16
|
||||
persistent_input_buffer = torch.zeros(max_bs, 10, device=DEVICE_TYPE)
|
||||
input_1 = persistent_input_buffer[:1]
|
||||
input_2 = persistent_input_buffer[:2]
|
||||
input_3 = persistent_input_buffer[:3]
|
||||
|
||||
desc_1 = BatchDescriptor(num_tokens=1)
|
||||
desc_2 = BatchDescriptor(num_tokens=2)
|
||||
desc_3_unseen = BatchDescriptor(num_tokens=3)
|
||||
|
||||
# 0. global warmup
|
||||
with set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=None,
|
||||
):
|
||||
full_wrapper(input_1)
|
||||
|
||||
rt_mode, key = dispatcher.dispatch(num_tokens=desc_1.num_tokens)
|
||||
# 1. Capture first shape
|
||||
action = _run_and_monitor_call(full_wrapper, input_1, rt_mode, key, vllm_config)
|
||||
assert action == "capture_global"
|
||||
|
||||
# 2. Replay first shape
|
||||
action = _run_and_monitor_call(full_wrapper, input_1, rt_mode, key, vllm_config)
|
||||
assert action == "replay"
|
||||
|
||||
rt_mode, key = dispatcher.dispatch(num_tokens=desc_2.num_tokens)
|
||||
# 3. Capture second shape
|
||||
action = _run_and_monitor_call(full_wrapper, input_2, rt_mode, key, vllm_config)
|
||||
assert action == "capture_global"
|
||||
|
||||
# 4. Replay second shape
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_2, CUDAGraphMode.FULL, key, vllm_config
|
||||
)
|
||||
assert action == "replay"
|
||||
|
||||
# 5. Bypass if no key match
|
||||
rt_mode, key = dispatcher.dispatch(num_tokens=desc_3_unseen.num_tokens)
|
||||
assert rt_mode == CUDAGraphMode.NONE
|
||||
action = _run_and_monitor_call(full_wrapper, input_3, rt_mode, key, vllm_config)
|
||||
assert action == "bypass"
|
||||
|
||||
# capture unseen shape is not allowed after disable
|
||||
set_cudagraph_capturing_enabled(False)
|
||||
with pytest.raises(RuntimeError):
|
||||
_run_and_monitor_call(
|
||||
full_wrapper, input_3, CUDAGraphMode.FULL, desc_3_unseen, vllm_config
|
||||
)
|
||||
set_cudagraph_capturing_enabled(True)
|
||||
|
||||
|
||||
@create_new_process_for_each_test("spawn")
|
||||
@pytest.mark.skipif(not HAS_DEVICE_GRAPH, reason="Requires CUDA or XPU graph")
|
||||
def test_nested_wrappers():
|
||||
"""Tests a scenario with a PIECEWISE wrapper inside a FULL one."""
|
||||
comp_config = CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
cudagraph_capture_sizes=[1],
|
||||
)
|
||||
vllm_config = _create_vllm_config(comp_config)
|
||||
dispatcher = CudagraphDispatcher(vllm_config)
|
||||
dispatcher.initialize_cudagraph_keys(
|
||||
comp_config.cudagraph_mode, uniform_decode_query_len=1
|
||||
)
|
||||
model = SimpleMLP().to(DEVICE_TYPE)
|
||||
full_wrapper = CUDAGraphWrapper(model, vllm_config, CUDAGraphMode.FULL)
|
||||
input_1 = torch.randn(1, 10, device=DEVICE_TYPE)
|
||||
|
||||
# Setup: Inner model is wrapped with PIECEWISE, outer with FULL
|
||||
inner_model = SimpleMLP().to(DEVICE_TYPE)
|
||||
piecewise_wrapper = CUDAGraphWrapper(
|
||||
inner_model, vllm_config, CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
inner_model.forward = MagicMock(wraps=inner_model.forward)
|
||||
outer_model = SimpleMLP().to(DEVICE_TYPE)
|
||||
# When outer model is called, it calls the piecewise_wrapper
|
||||
outer_model.forward = MagicMock(
|
||||
wraps=outer_model.forward, side_effect=piecewise_wrapper
|
||||
)
|
||||
full_wrapper = CUDAGraphWrapper(outer_model, vllm_config, CUDAGraphMode.FULL)
|
||||
|
||||
desc_1 = BatchDescriptor(num_tokens=1)
|
||||
|
||||
# 0. global warmup
|
||||
with set_forward_context(
|
||||
attn_metadata=None,
|
||||
vllm_config=vllm_config,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
batch_descriptor=None,
|
||||
):
|
||||
full_wrapper(input_1)
|
||||
|
||||
# --- Test runtime mode FULL---
|
||||
# Run with FULL mode context. Expect outer wrapper to capture.
|
||||
# The inner mock should be called once inside the graph capture.
|
||||
outer_model.forward.reset_mock()
|
||||
inner_model.forward.reset_mock()
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.FULL, desc_1, vllm_config
|
||||
)
|
||||
assert action == "capture_global"
|
||||
assert outer_model.forward.call_count == 1
|
||||
assert inner_model.forward.call_count == 1
|
||||
|
||||
# Run again. Expect outer wrapper to replay.
|
||||
# The outer model should NOT be called because the whole graph
|
||||
# is replayed.
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.FULL, desc_1, vllm_config
|
||||
)
|
||||
assert action == "replay"
|
||||
assert outer_model.forward.call_count == 1 # No new call
|
||||
assert inner_model.forward.call_count == 1
|
||||
|
||||
# --- Test runtime mode PIECEWISE ---
|
||||
outer_model.forward.reset_mock()
|
||||
inner_model.forward.reset_mock()
|
||||
# Run with PIECEWISE mode context.
|
||||
# Expect outer wrapper to bypass and call inner wrapper.
|
||||
# Inner wrapper should capture.
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.PIECEWISE, desc_1, vllm_config
|
||||
)
|
||||
assert action == "capture_global"
|
||||
assert outer_model.forward.call_count == 1
|
||||
assert inner_model.forward.call_count == 1
|
||||
|
||||
# Run again with PIECEWISE.
|
||||
# Outer bypasses, inner replays.
|
||||
action = _run_and_monitor_call(
|
||||
full_wrapper, input_1, CUDAGraphMode.PIECEWISE, desc_1, vllm_config
|
||||
)
|
||||
assert action == "bypass"
|
||||
assert outer_model.forward.call_count == 2
|
||||
assert inner_model.forward.call_count == 1
|
||||
@@ -1,123 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from contextlib import ExitStack
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.utils import create_new_process_for_each_test
|
||||
from tests.v1.attention.utils import full_cg_backend_configs as backend_configs
|
||||
from vllm import LLM
|
||||
from vllm.config import CompilationConfig, CompilationMode
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# test attention backend and cudagraph_mode combo
|
||||
# (backend_name, cudagraph_mode, supported)
|
||||
if current_platform.is_rocm():
|
||||
combo_cases_1 = [
|
||||
("RocmAttn", "FULL", True),
|
||||
("RocmAttn", "FULL_AND_PIECEWISE", True),
|
||||
("TritonAttn", "FULL", True),
|
||||
("TritonAttn", "FULL_AND_PIECEWISE", True),
|
||||
]
|
||||
elif current_platform.is_xpu():
|
||||
combo_cases_1 = [
|
||||
("FA2", "FULL", True),
|
||||
("FA2", "FULL_AND_PIECEWISE", True),
|
||||
("TritonAttn", "FULL", True),
|
||||
("TritonAttn", "FULL_AND_PIECEWISE", True),
|
||||
]
|
||||
else:
|
||||
combo_cases_1 = [
|
||||
("FA3", "FULL", True),
|
||||
("FA3", "FULL_AND_PIECEWISE", True),
|
||||
("FA2", "FULL", True), # Should fallback to FULL_AND_PIECEWISE
|
||||
("FA2", "FULL_AND_PIECEWISE", True),
|
||||
("FlashInfer", "FULL", True), # Should fallback to FULL_AND_PIECEWISE
|
||||
("FlashInfer", "FULL_AND_PIECEWISE", True),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backend_name, cudagraph_mode, supported", combo_cases_1)
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_backend_and_cudagraph_mode_combo(backend_name, cudagraph_mode, supported):
|
||||
if backend_name == "FlashInfer":
|
||||
try:
|
||||
import flashinfer # noqa: F401
|
||||
except ImportError:
|
||||
pytest.skip("FlashInfer is not installed")
|
||||
backend_config = backend_configs[backend_name]
|
||||
# Dynamically skip test if GPU capability is not met
|
||||
if (
|
||||
backend_config.specific_gpu_arch
|
||||
and backend_config.specific_gpu_arch != current_platform.get_device_capability()
|
||||
):
|
||||
pytest.skip("Only Hopper GPUs support FA3 and FlashMLA")
|
||||
|
||||
attention_config = backend_config.attention_config
|
||||
|
||||
with ExitStack() as stack:
|
||||
if not supported:
|
||||
stack.enter_context(pytest.raises(Exception))
|
||||
|
||||
llm = LLM(
|
||||
model="Qwen/Qwen2-1.5B-Instruct",
|
||||
max_num_seqs=16,
|
||||
max_num_batched_tokens=128,
|
||||
trust_remote_code=True,
|
||||
gpu_memory_utilization=0.45,
|
||||
max_model_len=1024,
|
||||
attention_config=attention_config,
|
||||
compilation_config=CompilationConfig(
|
||||
mode=CompilationMode.VLLM_COMPILE,
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
cudagraph_capture_sizes=[1, 2, 4, 8, 16, 64, 128],
|
||||
),
|
||||
)
|
||||
llm.generate(["Hello, my name is"] * 10)
|
||||
|
||||
|
||||
# test cudagraph_mode with different compilation mode.
|
||||
# (backend_name, cudagraph_mode, compilation_mode, supported)
|
||||
attn_backend = "RocmAttn" if current_platform.is_rocm() else "FA2"
|
||||
|
||||
combo_cases_2 = [
|
||||
(attn_backend, "FULL", CompilationMode.NONE, True),
|
||||
(attn_backend, "PIECEWISE", CompilationMode.NONE, True),
|
||||
(attn_backend, "PIECEWISE", CompilationMode.VLLM_COMPILE, True),
|
||||
(attn_backend, "FULL_AND_PIECEWISE", CompilationMode.NONE, True),
|
||||
(attn_backend, "FULL_DECODE_ONLY", CompilationMode.NONE, True),
|
||||
(attn_backend, "FULL_DECODE_ONLY", CompilationMode.VLLM_COMPILE, True),
|
||||
(attn_backend, "NONE", CompilationMode.NONE, True),
|
||||
(attn_backend, "NONE", CompilationMode.VLLM_COMPILE, True),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend_name,cudagraph_mode,compilation_mode,supported", combo_cases_2
|
||||
)
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_cudagraph_compilation_combo(
|
||||
backend_name, cudagraph_mode, compilation_mode, supported
|
||||
):
|
||||
backend_config = backend_configs[backend_name]
|
||||
attention_config = backend_config.attention_config
|
||||
|
||||
with ExitStack() as stack:
|
||||
if not supported:
|
||||
stack.enter_context(pytest.raises(Exception))
|
||||
|
||||
llm = LLM(
|
||||
model="Qwen/Qwen2-1.5B-Instruct",
|
||||
max_num_seqs=16,
|
||||
max_num_batched_tokens=128,
|
||||
trust_remote_code=True,
|
||||
gpu_memory_utilization=0.45,
|
||||
max_model_len=1024,
|
||||
attention_config=attention_config,
|
||||
compilation_config=CompilationConfig(
|
||||
mode=compilation_mode,
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
cudagraph_capture_sizes=[1, 2, 4, 8, 16, 64, 128],
|
||||
),
|
||||
)
|
||||
llm.generate(["Hello, my name is"] * 10)
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user