[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,79 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.backends.utils import get_dcp_local_seq_lens
|
||||
from vllm.v1.worker.cp_utils import should_skip_dcp_context_attention
|
||||
|
||||
|
||||
def test_cp_checks_allow_a_replicated_draft_backend_without_dcp(monkeypatch):
|
||||
from vllm.v1.worker import cp_utils
|
||||
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=1,
|
||||
decode_context_parallel_size=4,
|
||||
cp_kv_cache_interleave_size=16,
|
||||
),
|
||||
speculative_config=object(),
|
||||
)
|
||||
target = SimpleNamespace(
|
||||
impl=SimpleNamespace(
|
||||
dcp_world_size=4,
|
||||
supports_mtp_with_cp_non_trivial_interleave_size=True,
|
||||
need_to_return_lse_for_decode=True,
|
||||
)
|
||||
)
|
||||
draft = SimpleNamespace(
|
||||
impl=SimpleNamespace(
|
||||
dcp_world_size=1,
|
||||
supports_mtp_with_cp_non_trivial_interleave_size=False,
|
||||
need_to_return_lse_for_decode=False,
|
||||
)
|
||||
)
|
||||
layers = {"target": target, "draft": draft}
|
||||
monkeypatch.setattr(cp_utils, "get_layers_from_vllm_config", lambda *args: layers)
|
||||
cp_utils.check_attention_cp_compatibility(config, target_layer_names={"target"})
|
||||
with pytest.raises(AssertionError, match="MTP with cp_kv_cache_interleave_size"):
|
||||
cp_utils.check_attention_cp_compatibility(config)
|
||||
|
||||
|
||||
def test_skip_gate_only_for_zero_context():
|
||||
assert should_skip_dcp_context_attention(torch.zeros(3, dtype=torch.int32))
|
||||
assert not should_skip_dcp_context_attention(
|
||||
torch.tensor([0, 5, 0], dtype=torch.int32)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dcp_world_size,interleave_size,context_len",
|
||||
[(2, 16, 10), (4, 16, 10), (8, 16, 10), (4, 1, 2)],
|
||||
)
|
||||
def test_skip_gate_rank_invariant_with_divergent_local_context(
|
||||
dcp_world_size: int, interleave_size: int, context_len: int
|
||||
):
|
||||
"""Contexts shorter than a full interleave round land entirely on a
|
||||
subset of DCP ranks, so the per-rank local context lengths diverge:
|
||||
some ranks hold zero local context while others hold all of it. Ranks
|
||||
with zero local context must still take the collective (non-skip) path,
|
||||
otherwise the query all-gather in _forward_with_dcp deadlocks across
|
||||
ranks. The skip gate must therefore depend only on the rank-invariant
|
||||
global context lengths, never on get_dcp_local_seq_lens output.
|
||||
"""
|
||||
context_kv_lens = torch.tensor([context_len], dtype=torch.int32)
|
||||
local_maxes = [
|
||||
int(
|
||||
get_dcp_local_seq_lens(
|
||||
context_kv_lens, dcp_world_size, rank, interleave_size
|
||||
).max()
|
||||
)
|
||||
for rank in range(dcp_world_size)
|
||||
]
|
||||
# Precondition: the local view diverges across ranks.
|
||||
assert 0 in local_maxes
|
||||
assert max(local_maxes) > 0
|
||||
# The batch still has context globally, so no rank may skip.
|
||||
assert not should_skip_dcp_context_attention(context_kv_lens)
|
||||
@@ -1,70 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The CPU worker's automatic KV cache sizing must report the right cause.
|
||||
|
||||
A worker whose own footprint exceeds its reservation and a node that is short
|
||||
of free memory need opposite remedies, so they get separate errors.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.cpu_resource_utils import MemoryNodeInfo
|
||||
|
||||
# Importing the CPU worker patches torch and the GPU buffer utilities for the
|
||||
# whole process (vllm/v1/worker/cpu/shm.py), so the import is deferred into
|
||||
# the tests and they run only on the CPU platform.
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cpu(), reason="CPU worker test; needs the CPU platform"
|
||||
)
|
||||
|
||||
GiB = 1 << 30
|
||||
|
||||
|
||||
def _worker(monkeypatch, *, reserved, rss, total=8 * GiB, available=4 * GiB):
|
||||
import vllm.v1.worker.cpu_worker as cpu_worker_mod
|
||||
from vllm.v1.worker.cpu_worker import CPUWorker
|
||||
|
||||
worker = CPUWorker.__new__(CPUWorker)
|
||||
worker.requested_cpu_memory = reserved
|
||||
worker.cache_config = SimpleNamespace(kv_cache_memory_bytes=None)
|
||||
monkeypatch.setattr(CPUWorker, "_should_warm_up_model", lambda self: False)
|
||||
monkeypatch.setattr(
|
||||
cpu_worker_mod,
|
||||
"get_allowed_cpu_list",
|
||||
lambda: [SimpleNamespace(numa_node=0)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
cpu_worker_mod,
|
||||
"get_memory_node_info",
|
||||
lambda node: MemoryNodeInfo(total_memory=total, available_memory=available),
|
||||
)
|
||||
process = SimpleNamespace(memory_info=lambda: SimpleNamespace(rss=rss))
|
||||
monkeypatch.setattr(cpu_worker_mod.psutil, "Process", lambda pid: process)
|
||||
return worker
|
||||
|
||||
|
||||
def test_footprint_above_reservation_asks_for_a_larger_reservation(monkeypatch):
|
||||
# 0.76 GiB already in use against a 0.16 GiB reservation (2% of 8 GiB).
|
||||
worker = _worker(monkeypatch, reserved=int(0.16 * GiB), rss=int(0.76 * GiB))
|
||||
with pytest.raises(ValueError) as exc:
|
||||
worker.determine_available_memory()
|
||||
msg = str(exc.value)
|
||||
assert "increase `--gpu-memory-utilization` to more than 0.10" in msg
|
||||
assert "--kv-cache-memory-bytes" in msg
|
||||
# Neither the misleading remedy nor a negative KV size.
|
||||
assert "other processes" not in msg
|
||||
assert "-0." not in msg
|
||||
|
||||
|
||||
def test_short_node_memory_still_asks_to_free_memory(monkeypatch):
|
||||
worker = _worker(monkeypatch, reserved=6 * GiB, rss=1 * GiB, available=2 * GiB)
|
||||
with pytest.raises(ValueError, match="Reduce CPU memory used by other processes"):
|
||||
worker.determine_available_memory()
|
||||
|
||||
|
||||
def test_budget_that_fits_sizes_the_kv_cache(monkeypatch):
|
||||
worker = _worker(monkeypatch, reserved=3 * GiB, rss=1 * GiB)
|
||||
assert worker.determine_available_memory() == 2 * GiB
|
||||
@@ -1,172 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
from vllm.v1.worker.gpu import model_runner
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.dspark.utils import _get_dspark_parallel_config
|
||||
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FakeHFConfig:
|
||||
model_type: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FakeModelConfig:
|
||||
hf_config: _FakeHFConfig
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FakeEPLBConfig:
|
||||
num_redundant_experts: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FakeParallelConfig:
|
||||
pipeline_parallel_size: int = 2
|
||||
tensor_parallel_size: int = 8
|
||||
enable_eplb: bool = True
|
||||
eplb_config: _FakeEPLBConfig = field(
|
||||
default_factory=lambda: _FakeEPLBConfig(num_redundant_experts=32)
|
||||
)
|
||||
enable_elastic_ep: bool = True
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.enable_eplb and self.eplb_config.num_redundant_experts:
|
||||
raise ValueError("redundant experts require EPLB")
|
||||
if self.enable_elastic_ep and not self.enable_eplb:
|
||||
raise ValueError("elastic EP requires EPLB")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model_type", "enable_eplb", "num_redundant_experts", "shares_eplb_config"),
|
||||
[
|
||||
("deepseek_v4", True, 32, True),
|
||||
("deepseek_v41", False, 0, False),
|
||||
],
|
||||
)
|
||||
def test_dspark_parallel_config_eplb_by_model_type(
|
||||
model_type: str,
|
||||
enable_eplb: bool,
|
||||
num_redundant_experts: int,
|
||||
shares_eplb_config: bool,
|
||||
):
|
||||
target_config = _FakeParallelConfig()
|
||||
draft_model_config = _FakeModelConfig(
|
||||
hf_config=_FakeHFConfig(model_type=model_type)
|
||||
)
|
||||
|
||||
draft_config = _get_dspark_parallel_config(
|
||||
target_config,
|
||||
tensor_parallel_size=4,
|
||||
draft_model_config=draft_model_config,
|
||||
)
|
||||
|
||||
assert target_config.pipeline_parallel_size == 2
|
||||
assert target_config.tensor_parallel_size == 8
|
||||
assert target_config.enable_eplb
|
||||
assert target_config.eplb_config.num_redundant_experts == 32
|
||||
assert target_config.enable_elastic_ep
|
||||
|
||||
assert draft_config is not target_config
|
||||
assert draft_config.pipeline_parallel_size == 1
|
||||
assert draft_config.tensor_parallel_size == 4
|
||||
assert draft_config.enable_eplb is enable_eplb
|
||||
assert draft_config.eplb_config.num_redundant_experts == num_redundant_experts
|
||||
assert not draft_config.enable_elastic_ep
|
||||
if shares_eplb_config:
|
||||
assert draft_config.eplb_config is target_config.eplb_config
|
||||
else:
|
||||
assert draft_config.eplb_config is not target_config.eplb_config
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pcp_size", [1, 4])
|
||||
@pytest.mark.parametrize("dcp_size", [1, 4])
|
||||
@pytest.mark.parametrize("use_mla", [False, True])
|
||||
def test_draft_context_parallelism_without_changing_target(
|
||||
monkeypatch, pcp_size, dcp_size, use_mla
|
||||
):
|
||||
target_parallel = ParallelConfig(
|
||||
tensor_parallel_size=4,
|
||||
prefill_context_parallel_size=pcp_size,
|
||||
decode_context_parallel_size=dcp_size,
|
||||
cp_kv_cache_interleave_size=16,
|
||||
distributed_executor_backend="mp",
|
||||
)
|
||||
target_config = SimpleNamespace(
|
||||
parallel_config=target_parallel,
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(use_mla=use_mla)
|
||||
),
|
||||
)
|
||||
|
||||
class CapturedConfig(Exception):
|
||||
pass
|
||||
|
||||
def capture_init(self, config, device):
|
||||
raise CapturedConfig(config)
|
||||
|
||||
monkeypatch.setattr(DraftModelSpeculator, "__init__", capture_init)
|
||||
with pytest.raises(CapturedConfig) as captured:
|
||||
DFlashSpeculator(target_config, device=None)
|
||||
draft_parallel = captured.value.args[0].parallel_config
|
||||
assert draft_parallel.tensor_parallel_size == 4
|
||||
assert draft_parallel.prefill_context_parallel_size == 1
|
||||
assert draft_parallel.decode_context_parallel_size == (dcp_size if use_mla else 1)
|
||||
assert draft_parallel.cp_kv_cache_interleave_size == 16
|
||||
assert target_parallel.prefill_context_parallel_size == pcp_size
|
||||
assert target_parallel.decode_context_parallel_size == dcp_size
|
||||
assert target_parallel.cp_kv_cache_interleave_size == 16
|
||||
|
||||
|
||||
@pytest.mark.parametrize("configured_dcp", [1, 4])
|
||||
def test_attention_uses_draft_dcp_setting_inside_target_process_group(
|
||||
monkeypatch, configured_dcp
|
||||
):
|
||||
import vllm.config as config_module
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.v1.attention.backend import AttentionImplBase
|
||||
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(decode_context_parallel_size=configured_dcp)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
config_module, "get_current_vllm_config_or_none", lambda: config
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
parallel_state, "_DCP", SimpleNamespace(world_size=4, rank_in_group=2)
|
||||
)
|
||||
impl = AttentionImplBase()
|
||||
assert impl.dcp_world_size == configured_dcp
|
||||
assert impl.dcp_rank == (0 if configured_dcp == 1 else 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft_dcp_size", [1, 4])
|
||||
def test_runner_marks_only_replicated_draft_caches(monkeypatch, draft_dcp_size):
|
||||
spec = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=64, dtype=torch.bfloat16
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
model_runner, "get_kv_cache_spec", lambda _: {"target": spec, "draft": spec}
|
||||
)
|
||||
runner = object.__new__(model_runner.GPUModelRunner)
|
||||
runner.vllm_config = None
|
||||
runner.dcp_size = 4
|
||||
runner.speculator = object.__new__(DFlashSpeculator)
|
||||
runner.speculator.dcp_size = draft_dcp_size
|
||||
runner.speculator.draft_attn_layer_names = {"draft"}
|
||||
|
||||
specs = runner.get_kv_cache_spec()
|
||||
|
||||
assert specs["target"].dcp_sharded
|
||||
assert specs["draft"].dcp_sharded == (draft_dcp_size == 4)
|
||||
@@ -1,217 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import gc
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.quantization.online.lm_head import (
|
||||
quantized_lm_head_copy,
|
||||
refresh_quantized_lm_heads,
|
||||
)
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
|
||||
from vllm.model_executor.model_loader.reload import (
|
||||
finalize_layerwise_reload,
|
||||
initialize_layerwise_reload,
|
||||
record_metadata_for_reloading,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
# Not a multiple of the vocab padding, so the head has padded rows.
|
||||
VOCAB, HIDDEN = 4000, 512
|
||||
requires_cuda = pytest.mark.skipif(
|
||||
not torch.cuda.is_available(), reason="Marlin needs CUDA"
|
||||
)
|
||||
# NVFP4 needs a CUDA W4A16 kernel; ROCm only runs the fp8 cases.
|
||||
requires_nvfp4 = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="nvfp4 needs a CUDA W4A16 kernel"
|
||||
)
|
||||
NVFP4 = pytest.param("nvfp4", marks=requires_nvfp4)
|
||||
|
||||
|
||||
def _target_head(monkeypatch, seed: int = 0) -> ParallelLMHead:
|
||||
# Online methods read the model dtype from the current config.
|
||||
model_config = SimpleNamespace(dtype=torch.bfloat16)
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.quantization.online.fp8.get_current_vllm_config",
|
||||
lambda: SimpleNamespace(model_config=model_config),
|
||||
)
|
||||
head = ParallelLMHead(VOCAB, HIDDEN, disable_tp=True)
|
||||
gen = torch.Generator().manual_seed(seed)
|
||||
head.weight.data.copy_(torch.randn(head.weight.shape, generator=gen) * 0.02)
|
||||
return head.to("cuda", torch.bfloat16)
|
||||
|
||||
|
||||
def _tensors(module: torch.nn.Module) -> dict[str, torch.Tensor]:
|
||||
return dict(module.named_parameters()) | dict(module.named_buffers())
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@pytest.mark.parametrize(
|
||||
("quantization", "max_rel_err", "min_top1"),
|
||||
[("fp8", 0.05, 0.9), pytest.param("nvfp4", 0.15, 0.75, marks=requires_nvfp4)],
|
||||
)
|
||||
def test_tracks_bf16_head_through_logits_processor(
|
||||
default_vllm_config, dist_init, monkeypatch, quantization, max_rel_err, min_top1
|
||||
):
|
||||
head = _target_head(monkeypatch)
|
||||
target_weight = head.weight.detach().clone()
|
||||
draft_head = quantized_lm_head_copy(head, quantization)
|
||||
|
||||
assert isinstance(draft_head, ParallelLMHead)
|
||||
# The source head keeps its bf16 weight, and no bf16 copy is kept around.
|
||||
assert torch.equal(head.weight, target_weight)
|
||||
assert draft_head.weight.dtype != torch.bfloat16
|
||||
|
||||
logits_processor = LogitsProcessor(VOCAB)
|
||||
hidden = torch.randn(2048, HIDDEN, device="cuda", dtype=torch.bfloat16)
|
||||
ref = logits_processor(head, hidden).float()
|
||||
out = logits_processor(draft_head, hidden).float()
|
||||
assert out.shape == ref.shape == (2048, VOCAB)
|
||||
rel_err = ((out - ref).norm() / ref.norm()).item()
|
||||
top1 = (out.argmax(-1) == ref.argmax(-1)).float().mean().item()
|
||||
assert rel_err < max_rel_err
|
||||
assert top1 > min_top1
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@pytest.mark.parametrize("quantization", ["fp8", NVFP4])
|
||||
def test_refresh_follows_target_update(
|
||||
default_vllm_config, dist_init, monkeypatch, quantization
|
||||
):
|
||||
"""After the target's weights change, the copy is re-derived in place: it
|
||||
equals a fresh quantization of the new target, keeps its storage, and
|
||||
frees the temporary copy without waiting for the cycle collector."""
|
||||
head = _target_head(monkeypatch)
|
||||
drafter = torch.nn.Module()
|
||||
drafter.lm_head = quantized_lm_head_copy(head, quantization)
|
||||
ptrs = {k: t.data_ptr() for k, t in _tensors(drafter.lm_head).items()}
|
||||
|
||||
new_weight = _target_head(monkeypatch, seed=1).weight.detach()
|
||||
head.weight.data.copy_(new_weight)
|
||||
gc.disable()
|
||||
try:
|
||||
allocated = torch.accelerator.memory_allocated()
|
||||
refresh_quantized_lm_heads(drafter)
|
||||
assert torch.accelerator.memory_allocated() == allocated
|
||||
finally:
|
||||
gc.enable()
|
||||
|
||||
expected = _tensors(quantized_lm_head_copy(head, quantization))
|
||||
for name, tensor in _tensors(drafter.lm_head).items():
|
||||
assert tensor.data_ptr() == ptrs[name]
|
||||
if name != "workspace":
|
||||
assert torch.equal(tensor, expected[name]), name
|
||||
assert torch.equal(head.weight, new_weight)
|
||||
|
||||
|
||||
def _draft_update_worker(vllm_config, drafter: torch.nn.Module, **engine) -> Worker:
|
||||
worker = object.__new__(Worker)
|
||||
worker.vllm_config = vllm_config
|
||||
worker.weight_transfer_engine = SimpleNamespace(
|
||||
supports_draft_weight_update=True,
|
||||
reset_weight_update_target=lambda: None,
|
||||
**engine,
|
||||
)
|
||||
worker.model_runner = SimpleNamespace(get_draft_model=lambda: drafter)
|
||||
worker._weight_update_active = False
|
||||
worker._set_draft_weight_update_target = lambda: None
|
||||
return worker
|
||||
|
||||
|
||||
@requires_cuda
|
||||
def test_draft_weight_update_refreshes_copy(
|
||||
default_vllm_config, dist_init, monkeypatch
|
||||
):
|
||||
"""A draft weight update can write a target weight the drafter shares, such
|
||||
as an embedding tied to the lm_head; the copy must follow it."""
|
||||
head = _target_head(monkeypatch)
|
||||
drafter = torch.nn.Module()
|
||||
drafter.lm_head = quantized_lm_head_copy(head, "fp8")
|
||||
worker = _draft_update_worker(
|
||||
default_vllm_config,
|
||||
drafter,
|
||||
start_weight_update=lambda: None,
|
||||
finish_weight_update=lambda: None,
|
||||
)
|
||||
|
||||
worker.start_draft_weight_update()
|
||||
head.weight.data.copy_(_target_head(monkeypatch, seed=1).weight)
|
||||
worker.finish_weight_update()
|
||||
|
||||
expected = _tensors(quantized_lm_head_copy(head, "fp8"))
|
||||
for name, tensor in _tensors(drafter.lm_head).items():
|
||||
assert torch.equal(tensor, expected[name]), name
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@pytest.mark.parametrize("quantization", ["fp8", NVFP4])
|
||||
def test_draft_weight_update_loads_lm_head(
|
||||
default_vllm_config, dist_init, monkeypatch, quantization
|
||||
):
|
||||
"""A draft update carrying lm_head.weight loads the shared target head, as
|
||||
without quantization, and the copy is re-derived from it in place."""
|
||||
head = _target_head(monkeypatch)
|
||||
record_metadata_for_reloading(head)
|
||||
drafter = torch.nn.Module()
|
||||
draft_head = quantized_lm_head_copy(head, quantization)
|
||||
drafter.lm_head = draft_head
|
||||
ptrs = {k: t.data_ptr() for k, t in _tensors(draft_head).items()}
|
||||
new_weight = torch.randn(VOCAB, HIDDEN, device="cuda", dtype=torch.bfloat16)
|
||||
|
||||
def load(update_info):
|
||||
param = drafter.get_parameter("lm_head.weight")
|
||||
getattr(param, "weight_loader", default_weight_loader)(param, new_weight)
|
||||
|
||||
worker = _draft_update_worker(
|
||||
default_vllm_config,
|
||||
drafter,
|
||||
start_weight_update=lambda: initialize_layerwise_reload(drafter),
|
||||
update_weights=load,
|
||||
finish_weight_update=lambda: finalize_layerwise_reload(drafter, None),
|
||||
)
|
||||
worker.start_draft_weight_update()
|
||||
worker.update_weights({})
|
||||
worker.finish_weight_update()
|
||||
|
||||
assert drafter.lm_head is draft_head
|
||||
assert torch.equal(head.weight[:VOCAB], new_weight)
|
||||
expected = _tensors(quantized_lm_head_copy(head, quantization))
|
||||
for name, tensor in _tensors(draft_head).items():
|
||||
assert tensor.data_ptr() == ptrs[name]
|
||||
if name != "workspace":
|
||||
assert torch.equal(tensor, expected[name]), name
|
||||
hidden = torch.randn(64, HIDDEN, device="cuda", dtype=torch.bfloat16)
|
||||
assert LogitsProcessor(VOCAB)(draft_head, hidden).isfinite().all()
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@requires_nvfp4
|
||||
def test_layerwise_reload_of_drafter_keeps_copy(
|
||||
default_vllm_config, dist_init, monkeypatch
|
||||
):
|
||||
"""A drafter weight update reloads the drafter layerwise; the derived copy
|
||||
must come back unchanged, not be re-quantized."""
|
||||
head = _target_head(monkeypatch)
|
||||
drafter = torch.nn.Module()
|
||||
record_metadata_for_reloading(drafter)
|
||||
drafter.lm_head = quantized_lm_head_copy(head, "nvfp4")
|
||||
before = {k: t.clone() for k, t in _tensors(drafter.lm_head).items()}
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise AssertionError("the copy was re-quantized")
|
||||
|
||||
monkeypatch.setattr(
|
||||
drafter.lm_head.quant_method, "process_weights_after_loading", fail
|
||||
)
|
||||
initialize_layerwise_reload(drafter)
|
||||
finalize_layerwise_reload(drafter, None)
|
||||
|
||||
after = _tensors(drafter.lm_head)
|
||||
assert after.keys() == before.keys()
|
||||
for name, tensor in before.items():
|
||||
assert torch.equal(after[name], tensor), name
|
||||
@@ -1,704 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import inspect
|
||||
from collections.abc import Sequence
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.utils.torch_utils import make_tensor_with_pad
|
||||
from vllm.v1.pool.metadata import PoolingMetadata
|
||||
from vllm.v1.sample.logits_processor import LogitsProcessors
|
||||
from vllm.v1.sample.metadata import SamplingMetadata
|
||||
from vllm.v1.utils import CpuGpuBuffer
|
||||
from vllm.v1.worker.block_table import BlockTable, MultiGroupBlockTable
|
||||
from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
|
||||
|
||||
VOCAB_SIZE = 1024
|
||||
NUM_OUTPUT_TOKENS = 20
|
||||
MAX_PROMPT_SIZE = 100
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
DEVICES = [f"{DEVICE_TYPE}:{i}" for i in range(min(current_platform.device_count(), 2))]
|
||||
MAX_NUM_PROMPT_TOKENS = 64
|
||||
|
||||
|
||||
def _compare_objs(obj1, obj2, skip: Sequence = ("logitsprocs", "batch_update_builder")):
|
||||
attrs = inspect.getmembers(obj1, lambda a: not (inspect.isroutine(a)))
|
||||
attr_names = set(
|
||||
[a[0] for a in attrs if not (a[0].startswith("__") and a[0].endswith("__"))]
|
||||
)
|
||||
for attr_name in attr_names:
|
||||
if attr_name in skip:
|
||||
continue
|
||||
|
||||
a = getattr(obj1, attr_name)
|
||||
b = getattr(obj2, attr_name)
|
||||
|
||||
is_same = False
|
||||
if isinstance(a, torch.Tensor):
|
||||
if a.numel() == 0 or b.numel() == 0:
|
||||
is_same = a.numel() == 0 and b.numel() == 0
|
||||
elif torch.allclose(a, b):
|
||||
is_same = True
|
||||
elif isinstance(a, np.ndarray):
|
||||
if np.allclose(a, b):
|
||||
is_same = True
|
||||
elif isinstance(a, MultiGroupBlockTable):
|
||||
for a_i, b_i in zip(a.block_tables, b.block_tables):
|
||||
_compare_objs(a_i, b_i)
|
||||
is_same = True
|
||||
elif isinstance(a, (BlockTable, SamplingMetadata, PoolingMetadata)):
|
||||
_compare_objs(a, b)
|
||||
is_same = True # if we make it here must be same
|
||||
elif a == b:
|
||||
is_same = True
|
||||
elif isinstance(a, CpuGpuBuffer):
|
||||
is_same = np.allclose(a.np, b.np) and torch.allclose(a.gpu, b.gpu)
|
||||
assert is_same, (
|
||||
f"Attribute {attr_name} is different in {obj1} and {obj2}: {a} != {b}"
|
||||
)
|
||||
|
||||
|
||||
def _remove_requests(
|
||||
input_batch: InputBatch, batch_size: int, reqs: list[CachedRequestState]
|
||||
) -> set[str]:
|
||||
"""Remove some requests randomly from the batch and returns
|
||||
set of request removed
|
||||
"""
|
||||
num_reqs_to_remove = np.random.randint(0, batch_size)
|
||||
req_indices_to_remove: set[int] = set()
|
||||
for _ in range(num_reqs_to_remove):
|
||||
req_index_to_remove = np.random.randint(0, batch_size)
|
||||
req_indices_to_remove.add(req_index_to_remove)
|
||||
|
||||
req_ids_to_remove: set[str] = set()
|
||||
for index in req_indices_to_remove:
|
||||
input_batch.remove_request(reqs[index].req_id)
|
||||
req_ids_to_remove.add(reqs[index].req_id)
|
||||
return req_ids_to_remove
|
||||
|
||||
|
||||
def _construct_expected_sampling_metadata(
|
||||
reqs: list[CachedRequestState],
|
||||
req_ids_retained: set[int],
|
||||
req_id_index_in_input_batch: dict[str, int],
|
||||
device: torch.device,
|
||||
) -> SamplingMetadata:
|
||||
"""Constructs and returns the expected SamplingMetadata for this
|
||||
batch.
|
||||
"""
|
||||
num_reqs = len(req_ids_retained)
|
||||
output_token_ids: list[list[int]] = [list() for _ in range(num_reqs)]
|
||||
prompt_token_ids: list[list[int]] = [list() for _ in range(num_reqs)]
|
||||
presence_penalties = [0.0 for _ in range(num_reqs)]
|
||||
frequency_penalties = [0.0 for _ in range(num_reqs)]
|
||||
repetition_penalties = [1.0 for _ in range(num_reqs)]
|
||||
top_k = [0 for _ in range(num_reqs)]
|
||||
top_p = [0.0 for _ in range(num_reqs)]
|
||||
temperature = [0.0 for _ in range(num_reqs)]
|
||||
min_tokens = {}
|
||||
logit_bias = [None] * num_reqs
|
||||
allowed_token_ids_mask = torch.zeros(
|
||||
num_reqs, VOCAB_SIZE, dtype=torch.bool, device=device
|
||||
)
|
||||
bad_words_token_ids = {}
|
||||
for req in reqs:
|
||||
if req.req_id not in req_ids_retained:
|
||||
continue
|
||||
index_in_input_batch = req_id_index_in_input_batch[req.req_id]
|
||||
output_token_ids[index_in_input_batch] = req.output_token_ids
|
||||
prompt_token_ids[index_in_input_batch] = req.prompt_token_ids
|
||||
presence_penalties[index_in_input_batch] = req.sampling_params.presence_penalty
|
||||
frequency_penalties[index_in_input_batch] = (
|
||||
req.sampling_params.frequency_penalty
|
||||
)
|
||||
repetition_penalties[index_in_input_batch] = (
|
||||
req.sampling_params.repetition_penalty
|
||||
)
|
||||
top_k[index_in_input_batch] = req.sampling_params.top_k
|
||||
top_p[index_in_input_batch] = req.sampling_params.top_p
|
||||
temperature[index_in_input_batch] = req.sampling_params.temperature
|
||||
min_tokens[index_in_input_batch] = (
|
||||
req.sampling_params.min_tokens,
|
||||
req.sampling_params.all_stop_token_ids,
|
||||
)
|
||||
logit_bias[index_in_input_batch] = req.sampling_params.logit_bias
|
||||
if req.sampling_params.allowed_token_ids:
|
||||
allowed_token_ids_mask[index_in_input_batch][
|
||||
req.sampling_params.allowed_token_ids
|
||||
] = True
|
||||
if req.sampling_params.bad_words_token_ids:
|
||||
bad_words_token_ids[index_in_input_batch] = (
|
||||
req.sampling_params.bad_words_token_ids
|
||||
)
|
||||
|
||||
return SamplingMetadata(
|
||||
temperature=torch.tensor(temperature, dtype=torch.float, device=device),
|
||||
all_greedy=False,
|
||||
all_random=True,
|
||||
top_p=None
|
||||
if all(x == 1.0 for x in top_p)
|
||||
else torch.tensor(top_p, dtype=torch.float, device=device),
|
||||
top_k=None
|
||||
if all(x == 0 for x in top_k)
|
||||
else torch.tensor(top_k, dtype=torch.int, device=device),
|
||||
generators={},
|
||||
max_num_logprobs=0,
|
||||
prompt_token_ids=make_tensor_with_pad(
|
||||
prompt_token_ids,
|
||||
pad=VOCAB_SIZE,
|
||||
device=torch.device(device),
|
||||
dtype=torch.int64,
|
||||
),
|
||||
frequency_penalties=torch.tensor(
|
||||
frequency_penalties, dtype=torch.float, device=device
|
||||
),
|
||||
presence_penalties=torch.tensor(
|
||||
presence_penalties, dtype=torch.float, device=device
|
||||
),
|
||||
repetition_penalties=torch.tensor(
|
||||
repetition_penalties, dtype=torch.float, device=device
|
||||
),
|
||||
output_token_ids=output_token_ids,
|
||||
spec_token_ids=[[] for _ in range(len(output_token_ids))],
|
||||
no_penalties=(
|
||||
all(x == 0 for x in presence_penalties)
|
||||
and all(x == 0 for x in frequency_penalties)
|
||||
and all(x == 1 for x in repetition_penalties)
|
||||
),
|
||||
allowed_token_ids_mask=allowed_token_ids_mask,
|
||||
bad_words_token_ids=bad_words_token_ids,
|
||||
logitsprocs=LogitsProcessors(),
|
||||
)
|
||||
|
||||
|
||||
def _create_sampling_params():
|
||||
return SamplingParams(
|
||||
top_k=np.random.randint(1, 10),
|
||||
top_p=np.random.uniform(0.0, 1.0),
|
||||
presence_penalty=np.random.uniform(-2.0, 2.0),
|
||||
repetition_penalty=np.random.uniform(0.0, 2.0),
|
||||
frequency_penalty=np.random.uniform(-2.0, 2.0),
|
||||
min_tokens=np.random.randint(1, 10),
|
||||
stop_token_ids=[
|
||||
np.random.randint(0, VOCAB_SIZE) for _ in range(np.random.randint(10))
|
||||
],
|
||||
logit_bias={0: np.random.uniform(-3.0, 3.0)},
|
||||
)
|
||||
|
||||
|
||||
def _construct_cached_request_state(req_id_suffix: int):
|
||||
prompt_token_ids = [
|
||||
np.random.randint(0, VOCAB_SIZE)
|
||||
for _ in range(np.random.randint(0, MAX_PROMPT_SIZE))
|
||||
]
|
||||
output_token_ids = [
|
||||
np.random.randint(0, VOCAB_SIZE)
|
||||
for _ in range(np.random.randint(0, NUM_OUTPUT_TOKENS))
|
||||
]
|
||||
return CachedRequestState(
|
||||
req_id=f"req_id_{req_id_suffix}",
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
sampling_params=_create_sampling_params(),
|
||||
pooling_params=None,
|
||||
mm_features=[],
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=len(output_token_ids),
|
||||
output_token_ids=output_token_ids,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
@pytest.mark.parametrize("batch_size", [1, 2, 32, 64])
|
||||
def test_sampling_metadata_in_input_batch(device: str, batch_size: int):
|
||||
"""Tests the logic for managing sampling metadata in the InputBatch.
|
||||
|
||||
This test involves adding a set of requests to the InputBatch,
|
||||
followed by removing a subset of them. Afterward, the batch is compacted,
|
||||
and the `make_sampling_metadata` method is invoked on the batch. The
|
||||
output of `make_sampling_metadata` is then compared against the expected
|
||||
results to ensure correctness.
|
||||
|
||||
Note: Ignore logits processor logic, which is tested separately
|
||||
"""
|
||||
input_batch: InputBatch = InputBatch(
|
||||
max_num_reqs=batch_size,
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=1024,
|
||||
device=torch.device(device),
|
||||
vocab_size=1024,
|
||||
block_sizes=[1],
|
||||
max_num_blocks_per_req=[1024],
|
||||
)
|
||||
reqs: list[CachedRequestState] = []
|
||||
req_id_reqs = {}
|
||||
req_id_output_token_ids = {}
|
||||
|
||||
# Add requests
|
||||
for req_index in range(batch_size):
|
||||
req: CachedRequestState = _construct_cached_request_state(req_index)
|
||||
assigned_req_index = input_batch.add_request(req)
|
||||
assert req_index == assigned_req_index
|
||||
reqs.append(req)
|
||||
req_id_reqs[req.req_id] = req
|
||||
req_id_output_token_ids[req.req_id] = req.output_token_ids
|
||||
|
||||
# Remove some requests
|
||||
req_ids_to_remove = _remove_requests(input_batch, batch_size, reqs)
|
||||
req_ids_retained = set(req_id_reqs.keys()) - req_ids_to_remove
|
||||
|
||||
# Compact the input batch
|
||||
input_batch.condense()
|
||||
|
||||
# Generate the sampling metadata
|
||||
sampling_metadata = input_batch._make_sampling_metadata()
|
||||
|
||||
# Create expected output.
|
||||
expected_sampling_metadata = _construct_expected_sampling_metadata(
|
||||
reqs, req_ids_retained, input_batch.req_id_to_index, device=torch.device(device)
|
||||
)
|
||||
|
||||
def same(t1: torch.Tensor | None, t2: torch.Tensor | None) -> bool:
|
||||
return (t1 is None and t2 is None) or (
|
||||
t1 is not None and t2 is not None and torch.allclose(t1, t2)
|
||||
)
|
||||
|
||||
# Assert the actual and expected output.
|
||||
assert torch.allclose(
|
||||
expected_sampling_metadata.temperature, sampling_metadata.temperature
|
||||
)
|
||||
assert same(expected_sampling_metadata.top_p, sampling_metadata.top_p)
|
||||
assert same(expected_sampling_metadata.top_k, sampling_metadata.top_k)
|
||||
assert torch.allclose(
|
||||
expected_sampling_metadata.frequency_penalties,
|
||||
sampling_metadata.frequency_penalties,
|
||||
)
|
||||
assert torch.allclose(
|
||||
expected_sampling_metadata.presence_penalties,
|
||||
sampling_metadata.presence_penalties,
|
||||
)
|
||||
assert torch.allclose(
|
||||
expected_sampling_metadata.repetition_penalties,
|
||||
sampling_metadata.repetition_penalties,
|
||||
)
|
||||
assert torch.allclose(
|
||||
expected_sampling_metadata.prompt_token_ids, sampling_metadata.prompt_token_ids
|
||||
)
|
||||
assert (
|
||||
expected_sampling_metadata.output_token_ids
|
||||
== sampling_metadata.output_token_ids
|
||||
)
|
||||
assert expected_sampling_metadata.no_penalties == sampling_metadata.no_penalties
|
||||
if sampling_metadata.allowed_token_ids_mask:
|
||||
assert torch.allclose(
|
||||
expected_sampling_metadata.allowed_token_ids_mask,
|
||||
sampling_metadata.allowed_token_ids_mask,
|
||||
)
|
||||
assert (
|
||||
expected_sampling_metadata.bad_words_token_ids
|
||||
== sampling_metadata.bad_words_token_ids
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
@pytest.mark.parametrize("batch_size", [32])
|
||||
@pytest.mark.parametrize("swap_list", [((0, 1),)])
|
||||
def test_swap_states_in_input_batch(device: str, batch_size: int, swap_list: list):
|
||||
"""Tests the logic for managing sampling metadata in the InputBatch.
|
||||
|
||||
This test involves adding a set of requests to the InputBatch,
|
||||
followed by removing a subset of them. Afterward, the batch is compacted,
|
||||
and the `make_sampling_metadata` method is invoked on the batch. The
|
||||
output of `make_sampling_metadata` is then compared against the expected
|
||||
results to ensure correctness.
|
||||
|
||||
Note: Ignore logits processor logic, which is tested separately
|
||||
"""
|
||||
input_batch: InputBatch = InputBatch(
|
||||
max_num_reqs=batch_size,
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=1024,
|
||||
device=torch.device(device),
|
||||
vocab_size=1024,
|
||||
block_sizes=[1],
|
||||
max_num_blocks_per_req=[1024],
|
||||
)
|
||||
ref_input_batch: InputBatch = InputBatch(
|
||||
max_num_reqs=batch_size,
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=1024,
|
||||
device=torch.device(device),
|
||||
vocab_size=1024,
|
||||
block_sizes=[1],
|
||||
max_num_blocks_per_req=[1024],
|
||||
)
|
||||
|
||||
reqs: list[CachedRequestState] = []
|
||||
req_id_reqs = {}
|
||||
req_id_output_token_ids = {}
|
||||
# Add requests
|
||||
for req_index in range(batch_size):
|
||||
req: CachedRequestState = _construct_cached_request_state(req_index)
|
||||
assigned_req_index = input_batch.add_request(req)
|
||||
assert assigned_req_index == req_index
|
||||
reqs.append(req)
|
||||
req_id_reqs[req.req_id] = req
|
||||
req_id_output_token_ids[req.req_id] = req.output_token_ids
|
||||
|
||||
reordered_reqs = reqs.copy()
|
||||
for swap_pair in swap_list:
|
||||
reordered_reqs[swap_pair[0]], reordered_reqs[swap_pair[1]] = (
|
||||
reordered_reqs[swap_pair[1]],
|
||||
reordered_reqs[swap_pair[0]],
|
||||
)
|
||||
input_batch.swap_states(swap_pair[0], swap_pair[1])
|
||||
|
||||
for req_index in range(batch_size):
|
||||
req = reordered_reqs[req_index]
|
||||
assigned_req_index = ref_input_batch.add_request(req)
|
||||
assert assigned_req_index == req_index
|
||||
|
||||
input_batch.refresh_metadata()
|
||||
ref_input_batch.refresh_metadata()
|
||||
|
||||
_compare_objs(input_batch, ref_input_batch)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
def test_condense_clears_stale_allowed_token_ids_mask(device: str):
|
||||
"""condense() must clear the mask row a constrained request is moved out
|
||||
of. Otherwise a later request that reuses that row without
|
||||
allowed_token_ids inherits the stale whitelist.
|
||||
See https://github.com/vllm-project/vllm/issues/43894.
|
||||
"""
|
||||
batch_size = 4
|
||||
allowed_token_id = 13
|
||||
input_batch = InputBatch(
|
||||
max_num_reqs=batch_size,
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=1024,
|
||||
device=torch.device(device),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[1],
|
||||
max_num_blocks_per_req=[1024],
|
||||
)
|
||||
|
||||
def _make_req(suffix: int, allowed_token_ids=None) -> CachedRequestState:
|
||||
return CachedRequestState(
|
||||
req_id=f"req_id_{suffix}",
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(allowed_token_ids=allowed_token_ids),
|
||||
pooling_params=None,
|
||||
mm_features=[],
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=0,
|
||||
output_token_ids=[],
|
||||
)
|
||||
|
||||
# Only req_id_2 is constrained, and it lands on the highest row.
|
||||
assert input_batch.add_request(_make_req(0)) == 0
|
||||
assert input_batch.add_request(_make_req(1)) == 1
|
||||
assert input_batch.add_request(_make_req(2, [allowed_token_id])) == 2
|
||||
|
||||
mask = input_batch.allowed_token_ids_mask_cpu_tensor
|
||||
assert mask is not None
|
||||
# The constrained row masks every token except the single allowed id.
|
||||
assert not mask[2][allowed_token_id].item()
|
||||
assert int(mask[2].sum().item()) == VOCAB_SIZE - 1
|
||||
|
||||
# Free row 0, then condense: req_id_2 slides from row 2 down into row 0.
|
||||
input_batch.remove_request("req_id_0")
|
||||
input_batch.condense()
|
||||
assert input_batch.req_id_to_index["req_id_2"] == 0
|
||||
assert int(mask[2].sum().item()) == 0
|
||||
|
||||
# A new unrestricted request reuses row 2 and must stay unconstrained.
|
||||
assert input_batch.add_request(_make_req(3)) == 2
|
||||
assert "req_id_3" not in input_batch.has_allowed_token_ids
|
||||
assert int(mask[2].sum().item()) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
def test_swap_states_preserves_allowed_token_ids_mask(device: str):
|
||||
"""swap_states() must exchange the two allowed_token_ids_mask rows.
|
||||
|
||||
Swapping row views via a tuple assignment
|
||||
(t[i1], t[i2] = t[i2], t[i1]) aliases them, so both rows collapse to the
|
||||
second row's contents and one request silently loses its token
|
||||
restriction. This is the sibling of the condense() leak fixed for
|
||||
https://github.com/vllm-project/vllm/issues/43894.
|
||||
"""
|
||||
allowed_token_id = 13
|
||||
input_batch = InputBatch(
|
||||
max_num_reqs=2,
|
||||
max_model_len=1024,
|
||||
max_num_batched_tokens=1024,
|
||||
device=torch.device(device),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[1],
|
||||
max_num_blocks_per_req=[1024],
|
||||
)
|
||||
|
||||
def _make_req(suffix: int, allowed_token_ids=None) -> CachedRequestState:
|
||||
return CachedRequestState(
|
||||
req_id=f"req_id_{suffix}",
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(allowed_token_ids=allowed_token_ids),
|
||||
pooling_params=None,
|
||||
mm_features=[],
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=0,
|
||||
output_token_ids=[],
|
||||
)
|
||||
|
||||
# Row 0 is constrained to a single token; row 1 is unconstrained.
|
||||
assert input_batch.add_request(_make_req(0, [allowed_token_id])) == 0
|
||||
assert input_batch.add_request(_make_req(1)) == 1
|
||||
|
||||
mask = input_batch.allowed_token_ids_mask_cpu_tensor
|
||||
assert mask is not None
|
||||
assert int(mask[0].sum().item()) == VOCAB_SIZE - 1
|
||||
assert not mask[0][allowed_token_id].item()
|
||||
assert int(mask[1].sum().item()) == 0
|
||||
|
||||
input_batch.swap_states(0, 1)
|
||||
|
||||
# The constrained request now sits at row 1 and must keep its mask; the
|
||||
# unconstrained request now sits at row 0 and must stay open.
|
||||
assert int(mask[1].sum().item()) == VOCAB_SIZE - 1
|
||||
assert not mask[1][allowed_token_id].item()
|
||||
assert int(mask[0].sum().item()) == 0
|
||||
|
||||
|
||||
def _construct_pooling_request(req_id_suffix: int, pooling_params=None):
|
||||
from vllm.pooling_params import PoolingParams
|
||||
|
||||
prompt_token_ids = [
|
||||
np.random.randint(0, VOCAB_SIZE)
|
||||
for _ in range(np.random.randint(10, MAX_PROMPT_SIZE))
|
||||
]
|
||||
return CachedRequestState(
|
||||
req_id=f"pool_req_{req_id_suffix}",
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
sampling_params=None,
|
||||
pooling_params=pooling_params or PoolingParams(task="classify"),
|
||||
mm_features=[],
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=0,
|
||||
output_token_ids=[],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("device", DEVICES)
|
||||
def test_pooling_prompt_lens_not_aliased(device: str):
|
||||
"""Verify that prompt_lens in PoolingMetadata does not share memory
|
||||
with the internal num_prompt_tokens pinned buffer. Guards against possible
|
||||
non-determinism in pooling metadata due to mutations to the internal buffer.
|
||||
"""
|
||||
batch_size = 4
|
||||
input_batch = InputBatch(
|
||||
max_num_reqs=batch_size * 2,
|
||||
max_model_len=MAX_PROMPT_SIZE + NUM_OUTPUT_TOKENS,
|
||||
max_num_batched_tokens=batch_size * (MAX_PROMPT_SIZE + NUM_OUTPUT_TOKENS),
|
||||
device=torch.device(device),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[16],
|
||||
max_num_blocks_per_req=[64],
|
||||
is_pooling_model=True,
|
||||
)
|
||||
|
||||
reqs = []
|
||||
# Add requests
|
||||
for i in range(batch_size):
|
||||
req = _construct_pooling_request(i)
|
||||
input_batch.add_request(req)
|
||||
reqs.append(req)
|
||||
input_batch.refresh_metadata()
|
||||
|
||||
# prompt_lens must be a snapshot
|
||||
metadata = input_batch.get_pooling_metadata()
|
||||
prompt_lens_snapshot = metadata.prompt_lens.clone()
|
||||
|
||||
# Mutate the internal buffer (simulates next batch adding new requests)
|
||||
input_batch.num_prompt_tokens_cpu_tensor.fill_(999)
|
||||
|
||||
# prompt_lens must be unaffected by the mutation
|
||||
assert torch.equal(metadata.prompt_lens, prompt_lens_snapshot), (
|
||||
"prompt_lens shares memory with internal pinned buffer; "
|
||||
"mutations to num_prompt_tokens_cpu_tensor corrupted prompt_lens. "
|
||||
f"Expected {prompt_lens_snapshot}, got {metadata.prompt_lens}"
|
||||
)
|
||||
|
||||
|
||||
def test_placeholder_spec_token_ids_written_verbatim():
|
||||
input_batch = InputBatch(
|
||||
max_num_reqs=1,
|
||||
max_model_len=8,
|
||||
max_num_batched_tokens=8,
|
||||
device=torch.device("cpu"),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[16],
|
||||
max_num_blocks_per_req=[1],
|
||||
)
|
||||
req = CachedRequestState(
|
||||
req_id="req",
|
||||
prompt_token_ids=[10, 11],
|
||||
mm_features=[],
|
||||
sampling_params=SamplingParams(),
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=3,
|
||||
output_token_ids=[12],
|
||||
)
|
||||
input_batch.add_request(req)
|
||||
|
||||
input_batch.update_req_spec_token_ids(
|
||||
req,
|
||||
{"req": [13, -1, -1]},
|
||||
)
|
||||
|
||||
# Placeholders (-1) are kept verbatim in both the spec_token_ids list and
|
||||
# the token buffer; they are clamped to 0 only at the embedding boundary
|
||||
# (GPUModelRunner._preprocess).
|
||||
assert input_batch.spec_token_ids[0] == [13, -1, -1]
|
||||
assert input_batch.token_ids_cpu[0, 3:6].tolist() == [13, -1, -1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pooling_params", "expect_cpu_prompt_token_ids"),
|
||||
[
|
||||
({"task": "classify"}, False),
|
||||
({"task": "classify", "requires_token_ids": True}, True),
|
||||
],
|
||||
)
|
||||
def test_pooling_metadata_token_id_buffers(
|
||||
pooling_params: dict[str, object],
|
||||
expect_cpu_prompt_token_ids: bool,
|
||||
):
|
||||
from vllm.pooling_params import PoolingParams
|
||||
|
||||
input_batch = InputBatch(
|
||||
max_num_reqs=1,
|
||||
max_model_len=MAX_PROMPT_SIZE + NUM_OUTPUT_TOKENS,
|
||||
max_num_batched_tokens=MAX_PROMPT_SIZE + NUM_OUTPUT_TOKENS,
|
||||
device=torch.device("cpu"),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[16],
|
||||
max_num_blocks_per_req=[64],
|
||||
is_pooling_model=True,
|
||||
)
|
||||
req = _construct_pooling_request(0, PoolingParams(**pooling_params))
|
||||
input_batch.add_request(req)
|
||||
input_batch.refresh_metadata()
|
||||
|
||||
metadata = input_batch.get_pooling_metadata()
|
||||
assert input_batch.sampling_metadata.prompt_token_ids is None
|
||||
assert metadata.prompt_token_ids is None
|
||||
|
||||
if expect_cpu_prompt_token_ids:
|
||||
assert metadata.prompt_token_ids_cpu is not None
|
||||
assert metadata.get_prompt_token_ids_cpu()[0].tolist() == req.prompt_token_ids
|
||||
else:
|
||||
assert metadata.prompt_token_ids_cpu is None
|
||||
|
||||
|
||||
PROMPT_EMBEDS_HIDDEN = 8
|
||||
PROMPT_EMBEDS_LEN = 4
|
||||
|
||||
|
||||
def _make_input_batch(is_pooling_model: bool = False) -> InputBatch:
|
||||
return InputBatch(
|
||||
max_num_reqs=2,
|
||||
max_model_len=MAX_PROMPT_SIZE + NUM_OUTPUT_TOKENS,
|
||||
max_num_batched_tokens=MAX_PROMPT_SIZE + NUM_OUTPUT_TOKENS,
|
||||
device=torch.device("cpu"),
|
||||
vocab_size=VOCAB_SIZE,
|
||||
block_sizes=[16],
|
||||
max_num_blocks_per_req=[64],
|
||||
is_pooling_model=is_pooling_model,
|
||||
)
|
||||
|
||||
|
||||
def _make_embeds_request(req_id: str, pooling: bool = False) -> CachedRequestState:
|
||||
from vllm.pooling_params import PoolingParams
|
||||
|
||||
return CachedRequestState(
|
||||
req_id=req_id,
|
||||
prompt_token_ids=None,
|
||||
prompt_embeds=torch.randn(PROMPT_EMBEDS_LEN, PROMPT_EMBEDS_HIDDEN),
|
||||
mm_features=[],
|
||||
sampling_params=None if pooling else SamplingParams(),
|
||||
pooling_params=PoolingParams(task="classify") if pooling else None,
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=0,
|
||||
output_token_ids=[],
|
||||
)
|
||||
|
||||
|
||||
def _make_token_request(req_id: str) -> CachedRequestState:
|
||||
return CachedRequestState(
|
||||
req_id=req_id,
|
||||
prompt_token_ids=[10, 11, 12, 13],
|
||||
mm_features=[],
|
||||
sampling_params=SamplingParams(),
|
||||
block_ids=([],),
|
||||
generator=None,
|
||||
num_computed_tokens=0,
|
||||
output_token_ids=[],
|
||||
)
|
||||
|
||||
|
||||
def test_remove_request_releases_prompt_embeds():
|
||||
"""A finished prompt-embeds request must not keep its tensor referenced by
|
||||
the persistent batch; an empty batch owns no prompt embeds."""
|
||||
input_batch = _make_input_batch()
|
||||
req = _make_embeds_request("embeds-req")
|
||||
input_batch.add_request(req)
|
||||
req_index = input_batch.req_id_to_index[req.req_id]
|
||||
assert req_index in input_batch.req_prompt_embeds
|
||||
|
||||
input_batch.remove_request(req.req_id)
|
||||
input_batch.condense()
|
||||
|
||||
assert req_index not in input_batch.req_prompt_embeds
|
||||
assert not input_batch.req_prompt_embeds
|
||||
|
||||
|
||||
def test_reused_slot_does_not_retain_prompt_embeds():
|
||||
"""Reusing a vacated slot with a token-id request must not keep the previous
|
||||
occupant's prompt-embeds tensor alive."""
|
||||
input_batch = _make_input_batch()
|
||||
embeds_req = _make_embeds_request("embeds-req")
|
||||
input_batch.add_request(embeds_req)
|
||||
slot = input_batch.req_id_to_index[embeds_req.req_id]
|
||||
|
||||
input_batch.remove_request(embeds_req.req_id)
|
||||
input_batch.condense()
|
||||
|
||||
token_req = _make_token_request("token-req")
|
||||
input_batch.add_request(token_req)
|
||||
assert input_batch.req_id_to_index[token_req.req_id] == slot
|
||||
assert slot not in input_batch.req_prompt_embeds
|
||||
|
||||
|
||||
def test_pooling_model_releases_prompt_embeds():
|
||||
"""The cleanup must run before remove_request's pooling-model early return."""
|
||||
input_batch = _make_input_batch(is_pooling_model=True)
|
||||
req = _make_embeds_request("pool-embeds-req", pooling=True)
|
||||
input_batch.add_request(req)
|
||||
req_index = input_batch.req_id_to_index[req.req_id]
|
||||
assert req_index in input_batch.req_prompt_embeds
|
||||
|
||||
input_batch.remove_request(req.req_id)
|
||||
input_batch.condense()
|
||||
|
||||
assert req_index not in input_batch.req_prompt_embeds
|
||||
@@ -1,161 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for the V2 model runner's InputBatch (vllm.v1.worker.gpu.input_batch)."""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.forward_context import set_forward_context
|
||||
from vllm.model_executor.layers.fused_moe.router.fused_topk_router import fused_topk
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.utils import get_dcp_local_seq_lens
|
||||
from vllm.v1.worker.gpu import cp_utils
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
|
||||
|
||||
DEVICE = current_platform.device_type
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"num_reqs,num_tokens",
|
||||
[
|
||||
(256, 496), # remainder 240: previously gave the last request 241 tokens
|
||||
(128, 512), # no remainder
|
||||
(3, 8),
|
||||
(1, 7),
|
||||
],
|
||||
)
|
||||
def test_make_dummy_distributes_remainder(num_reqs: int, num_tokens: int):
|
||||
"""No dummy request may exceed ceil(num_tokens / num_reqs) tokens.
|
||||
|
||||
Dumping the remainder on a single request can produce a dummy request with
|
||||
seq_len > max_model_len, which the block tables cannot back; attention
|
||||
kernels running on the dummy batch during cudagraph capture then read
|
||||
block-table entries out of bounds (https://github.com/vllm-project/vllm/pull/49364
|
||||
CI failure).
|
||||
"""
|
||||
buffers = InputBuffers(
|
||||
max_num_reqs=num_reqs, max_num_tokens=num_tokens, device=torch.device(DEVICE)
|
||||
)
|
||||
batch = InputBatch.make_dummy(num_reqs, num_tokens, buffers)
|
||||
|
||||
max_per_req = -(-num_tokens // num_reqs)
|
||||
assert batch.num_scheduled_tokens.sum() == num_tokens
|
||||
assert batch.num_scheduled_tokens.max() == max_per_req
|
||||
assert batch.num_scheduled_tokens.min() >= num_tokens // num_reqs
|
||||
# Requests with an extra token are placed at the end of the batch.
|
||||
assert (batch.num_scheduled_tokens[:-1] <= batch.num_scheduled_tokens[1:]).all()
|
||||
|
||||
# seq_len == query_len for the dummy prefill-shaped batch, on GPU and CPU.
|
||||
query_lens = batch.query_start_loc_np[1:] - batch.query_start_loc_np[:-1]
|
||||
assert (query_lens == batch.num_scheduled_tokens).all()
|
||||
assert torch.equal(
|
||||
batch.seq_lens, torch.from_numpy(batch.num_scheduled_tokens).to(DEVICE)
|
||||
)
|
||||
assert batch.query_start_loc_np[-1] == num_tokens
|
||||
assert torch.equal(
|
||||
batch.query_start_loc.cpu(), torch.from_numpy(batch.query_start_loc_np)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA top-k.")
|
||||
@pytest.mark.parametrize("is_padding", [True, False])
|
||||
def test_make_dummy_padding_controls_moe_routing(monkeypatch, is_padding: bool):
|
||||
"""Dummy tokens marked as padding are dropped by the MoE router (top-k id
|
||||
-1), which is wanted for idle DP ranks. Profile runs must not mark them, or
|
||||
no token reaches the experts and MoE memory is never profiled."""
|
||||
monkeypatch.setenv("VLLM_MOE_SKIP_PADDING", "1")
|
||||
num_tokens = 16
|
||||
buffers = InputBuffers(
|
||||
max_num_reqs=4, max_num_tokens=num_tokens, device=torch.device(DEVICE)
|
||||
)
|
||||
batch = InputBatch.make_dummy(4, num_tokens, buffers, is_padding=is_padding)
|
||||
hidden_states = torch.randn(num_tokens, 4, device=DEVICE)
|
||||
router_logits = torch.randn(num_tokens, 8, device=DEVICE)
|
||||
|
||||
with set_forward_context(None, VllmConfig(), is_padding=batch.is_padding):
|
||||
_, topk_ids, _ = fused_topk(hidden_states, router_logits, 2, False)
|
||||
|
||||
assert bool((topk_ids == -1).all()) is is_padding
|
||||
assert bool((topk_ids >= 0).all()) is not is_padding
|
||||
|
||||
|
||||
def test_prepare_dcp_local_seq_lens_uses_shared_buffer(monkeypatch):
|
||||
"""The batch must view the caller-owned buffer, sliced to padded length.
|
||||
|
||||
Runtime (and capture) paths all funnel through this helper; attention
|
||||
metadata indexes padded rows, so the view must reach
|
||||
num_reqs_after_padding, and it must alias the persistent buffer so CUDA
|
||||
graph replay sees the recomputed values.
|
||||
"""
|
||||
buffers = InputBuffers(max_num_reqs=4, max_num_tokens=4, device=torch.device("cpu"))
|
||||
batch = InputBatch.make_dummy(2, 4, buffers)
|
||||
batch.num_reqs_after_padding = 4
|
||||
|
||||
def fake_kernel(
|
||||
output,
|
||||
seq_lens,
|
||||
dcp_size,
|
||||
dcp_rank,
|
||||
cp_interleave,
|
||||
num_reqs,
|
||||
max_num_reqs,
|
||||
block_size,
|
||||
):
|
||||
assert output is buffers.dcp_local_seq_lens
|
||||
assert seq_lens is batch.seq_lens
|
||||
assert (num_reqs, dcp_size, dcp_rank, cp_interleave) == (2, 4, 1, 16)
|
||||
assert (max_num_reqs, block_size) == (4, 128)
|
||||
output[:] = torch.tensor([1, 2, 0, 0], dtype=output.dtype)
|
||||
|
||||
class FakeKernel:
|
||||
def __getitem__(self, grid):
|
||||
assert grid == (1,)
|
||||
return fake_kernel
|
||||
|
||||
monkeypatch.setattr(cp_utils, "_dcp_local_seq_lens_kernel", FakeKernel())
|
||||
batch.dcp_local_seq_lens = cp_utils.prepare_dcp_local_seq_lens(
|
||||
buffers.dcp_local_seq_lens,
|
||||
batch.seq_lens,
|
||||
batch.num_reqs,
|
||||
4,
|
||||
1,
|
||||
16,
|
||||
num_reqs_padded=batch.num_reqs_after_padding,
|
||||
)
|
||||
|
||||
assert batch.dcp_local_seq_lens is not None
|
||||
assert batch.dcp_local_seq_lens.data_ptr() == buffers.dcp_local_seq_lens.data_ptr()
|
||||
assert batch.dcp_local_seq_lens.tolist() == [1, 2, 0, 0]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="triton kernel needs CUDA")
|
||||
@pytest.mark.parametrize("dcp_size", [2, 4])
|
||||
@pytest.mark.parametrize("cp_interleave", [1, 16])
|
||||
def test_prepare_dcp_local_seq_lens_matches_reference(
|
||||
dcp_size: int, cp_interleave: int
|
||||
):
|
||||
"""Every rank's local lengths must equal the reference torch formula."""
|
||||
device = torch.device("cuda:0")
|
||||
seq_lens_np = np.array([7, 16, 33, 64, 512, 1023], dtype=np.int32)
|
||||
buffers = InputBuffers(max_num_reqs=8, max_num_tokens=32, device=device)
|
||||
batch = InputBatch.make_dummy(6, 12, buffers)
|
||||
buffers.seq_lens[: len(seq_lens_np)] = torch.from_numpy(seq_lens_np).to(device)
|
||||
|
||||
for dcp_rank in range(dcp_size):
|
||||
buffers.dcp_local_seq_lens.fill_(-1)
|
||||
batch.dcp_local_seq_lens = cp_utils.prepare_dcp_local_seq_lens(
|
||||
buffers.dcp_local_seq_lens,
|
||||
batch.seq_lens,
|
||||
batch.num_reqs,
|
||||
dcp_size,
|
||||
dcp_rank,
|
||||
cp_interleave,
|
||||
num_reqs_padded=batch.num_reqs_after_padding,
|
||||
)
|
||||
expected = get_dcp_local_seq_lens(
|
||||
torch.from_numpy(seq_lens_np), dcp_size, dcp_rank, cp_interleave
|
||||
)
|
||||
assert batch.dcp_local_seq_lens is not None
|
||||
assert torch.equal(batch.dcp_local_seq_lens.cpu(), expected.to(torch.int32))
|
||||
@@ -1,96 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""GPU regression test for the kpool tail group's slot mapping.
|
||||
|
||||
The kpool tail cache holds one circular block per request, so its block table
|
||||
row is orders of magnitude shorter than the sequence it serves.
|
||||
`_compute_slot_mappings_kernel` indexes block tables by
|
||||
`position // block_size` with an effectively unmasked load, so
|
||||
this leads to a read of neighboring requests' rows (and for the later requests, outside
|
||||
the buffer entirely).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.kv_cache_interface import CircularBufferSpec
|
||||
from vllm.v1.worker.block_table import get_block_table_width
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(),
|
||||
reason="requires CUDA or ROCm",
|
||||
)
|
||||
|
||||
KPOOL = 4
|
||||
MAX_MODEL_LEN = 1 << 20
|
||||
MLA_BLOCK_SIZE = 640
|
||||
MAX_NUM_REQS = 4
|
||||
POISON_BLOCK_ID = 1 << 20
|
||||
|
||||
|
||||
def make_tail_spec():
|
||||
return CircularBufferSpec(
|
||||
block_size=KPOOL,
|
||||
num_kv_heads=2,
|
||||
head_size=128,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
|
||||
def test_kpool_tail_group_never_position_indexes_its_block_table():
|
||||
device = torch.device("cuda")
|
||||
spec = make_tail_spec()
|
||||
tail_width = get_block_table_width(
|
||||
spec.max_num_blocks_per_req(None, MAX_MODEL_LEN),
|
||||
spec.block_size,
|
||||
token_alignment=spec.block_table_token_alignment,
|
||||
)
|
||||
mla_width = get_block_table_width(MAX_MODEL_LEN // MLA_BLOCK_SIZE, MLA_BLOCK_SIZE)
|
||||
|
||||
# Positions chosen against the tail row: `in_row` still lands inside
|
||||
# request 0's own row, `next_row` lands on request 1's poisoned row, and
|
||||
# `past_table` is past the whole [MAX_NUM_REQS, tail_width] allocation.
|
||||
in_row = KPOOL - 1
|
||||
next_row = tail_width * KPOOL
|
||||
past_table = MAX_NUM_REQS * tail_width * KPOOL + KPOOL
|
||||
assert past_table < MAX_MODEL_LEN
|
||||
positions = [0, in_row, next_row, past_table]
|
||||
|
||||
block_tables = BlockTables(
|
||||
block_sizes=[MLA_BLOCK_SIZE, spec.block_size],
|
||||
max_num_reqs=MAX_NUM_REQS,
|
||||
max_num_batched_tokens=len(positions),
|
||||
max_num_blocks_per_group=[mla_width, tail_width],
|
||||
device=device,
|
||||
slot_mapping_enabled=[True, spec.uses_slot_mapping],
|
||||
)
|
||||
mla_blocks = list(range(1, mla_width + 1))
|
||||
block_tables.append_block_ids(0, (mla_blocks, [7]), overwrite=True)
|
||||
block_tables.append_block_ids(1, ([2], [POISON_BLOCK_ID]), overwrite=True)
|
||||
block_tables.apply_staged_writes()
|
||||
|
||||
idx_mapping = torch.zeros(1, dtype=torch.int32, device=device)
|
||||
query_start_loc = torch.tensor(
|
||||
[0, len(positions)], dtype=torch.int32, device=device
|
||||
)
|
||||
slot_mappings = block_tables.compute_slot_mappings(
|
||||
idx_mapping,
|
||||
query_start_loc,
|
||||
torch.tensor(positions, dtype=torch.int64, device=device),
|
||||
num_tokens_padded=len(positions),
|
||||
)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
tail_slots = slot_mappings[1].tolist()
|
||||
assert tail_slots == [PAD_SLOT_ID] * len(positions)
|
||||
assert POISON_BLOCK_ID * KPOOL not in tail_slots
|
||||
|
||||
mla_slots = slot_mappings[0].tolist()
|
||||
assert mla_slots == [
|
||||
mla_blocks[p // MLA_BLOCK_SIZE] * MLA_BLOCK_SIZE + p % MLA_BLOCK_SIZE
|
||||
for p in positions
|
||||
]
|
||||
@@ -1,257 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""`GPUModelRunner._prepare_inputs` must tell a chunked-prefill continuation
|
||||
row apart from a genuine zero-draft decode row.
|
||||
|
||||
Both kinds of row are absent from `scheduled_spec_decode_tokens` and both
|
||||
schedule exactly one token, so `num_decode_draft_tokens` starts at the
|
||||
placeholder `-1` for either. The `zero_draft_decode_mask` in
|
||||
`gpu_model_runner.py` is what tells them apart afterwards, using
|
||||
`num_computed_tokens >= num_prompt_tokens`: a prefill continuation must keep
|
||||
`-1` (it carries no drafts and no accepted-token offset to apply), while a
|
||||
zero-draft decode row must become `0` (it still has to run the speculative
|
||||
path so the recurrent backends apply that offset). Getting this wrong in
|
||||
either direction was the root cause behind issue #40875: Kimi-Linear crashed
|
||||
with an illegal memory access when prefill tails were misclassified as
|
||||
zero-draft decodes.
|
||||
|
||||
Each batch below also includes one row with a real draft token, so
|
||||
`scheduled_spec_decode_tokens` is non-empty even under the pre-fix
|
||||
`use_spec_decode = len(scheduled_spec_decode_tokens) > 0` predicate. That
|
||||
keeps the assertions targeted at the mask fix alone, not the unrelated
|
||||
`use_spec_decode` predicate fix (`self.speculative_config is not None`) that
|
||||
landed in the same patch.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
ModelConfig,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
SpeculativeConfig,
|
||||
VllmConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.model_executor.layers.attention import Attention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.v1.core.sched.output import CachedRequestData, NewRequestData, SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
)
|
||||
from vllm.v1.worker.gpu_input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
|
||||
|
||||
BLOCK_SIZE = 16
|
||||
NUM_BLOCKS = 10
|
||||
|
||||
|
||||
def _get_vllm_config() -> VllmConfig:
|
||||
model_config = ModelConfig(model="facebook/opt-125m", dtype="float16", seed=42)
|
||||
scheduler_config = SchedulerConfig(
|
||||
max_num_seqs=10,
|
||||
max_num_batched_tokens=512,
|
||||
max_model_len=512,
|
||||
is_encoder_decoder=model_config.is_encoder_decoder,
|
||||
)
|
||||
cache_config = CacheConfig(
|
||||
block_size=BLOCK_SIZE, gpu_memory_utilization=0.9, cache_dtype="auto"
|
||||
)
|
||||
cache_config.kv_cache_layout = "LBNHC"
|
||||
return VllmConfig(
|
||||
model_config=model_config,
|
||||
cache_config=cache_config,
|
||||
scheduler_config=scheduler_config,
|
||||
parallel_config=ParallelConfig(),
|
||||
# ngram needs no draft model weights, so the fixture stays as cheap as
|
||||
# the speculative-decoding-free one in test_gpu_model_runner.py.
|
||||
speculative_config=SpeculativeConfig(method="ngram", num_speculative_tokens=3),
|
||||
)
|
||||
|
||||
|
||||
def _make_model_runner(vllm_config: VllmConfig) -> GPUModelRunner:
|
||||
"""Build the V1 runner the platform's worker would, without starting it."""
|
||||
worker_cls = resolve_obj_by_qualname(vllm_config.parallel_config.worker_cls)
|
||||
worker = SimpleNamespace(
|
||||
vllm_config=vllm_config,
|
||||
device=current_platform.device_type,
|
||||
use_v2_model_runner=False,
|
||||
)
|
||||
return worker_cls._make_model_runner(worker)
|
||||
|
||||
|
||||
def _initialize_kv_cache(runner: GPUModelRunner) -> None:
|
||||
attn_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=runner.model_config.get_num_kv_heads(runner.parallel_config),
|
||||
head_size=runner.model_config.get_head_size(),
|
||||
dtype=runner.kv_cache_dtype,
|
||||
)
|
||||
tensor_size = attn_spec.page_size_bytes * NUM_BLOCKS
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=NUM_BLOCKS,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=tensor_size,
|
||||
layers=["layer.0"],
|
||||
layer_stride=tensor_size,
|
||||
block_stride=attn_spec.page_size_bytes,
|
||||
),
|
||||
],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(layer_names=["layer.0"], kv_cache_spec=attn_spec)
|
||||
],
|
||||
)
|
||||
runner.kv_cache_config = kv_cache_config
|
||||
runner.input_batch = InputBatch(
|
||||
max_num_reqs=runner.max_num_reqs,
|
||||
max_model_len=runner.max_model_len,
|
||||
max_num_batched_tokens=runner.max_num_tokens,
|
||||
device=runner.device,
|
||||
vocab_size=runner.model_config.get_vocab_size(),
|
||||
block_sizes=[kv_cache_config.kv_cache_groups[0].kv_cache_spec.block_size],
|
||||
max_num_blocks_per_req=[NUM_BLOCKS],
|
||||
)
|
||||
runner.initialize_attn_backend(kv_cache_config)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def spec_decode_model_runner(dist_init):
|
||||
vllm_config = _get_vllm_config()
|
||||
with set_current_vllm_config(vllm_config):
|
||||
model_config = vllm_config.model_config
|
||||
num_heads = model_config.get_num_kv_heads(vllm_config.parallel_config)
|
||||
head_size = model_config.get_head_size()
|
||||
vllm_config.compilation_config.static_forward_context["layer.0"] = Attention(
|
||||
num_heads, head_size, 0.1
|
||||
)
|
||||
runner = _make_model_runner(vllm_config)
|
||||
_initialize_kv_cache(runner)
|
||||
yield runner
|
||||
|
||||
|
||||
def _new_request(
|
||||
req_id: str, prompt_len: int, num_computed_tokens: int
|
||||
) -> tuple[NewRequestData, int]:
|
||||
"""A request with `prompt_len` prompt tokens, `num_computed_tokens` of
|
||||
which are already computed (e.g. a prefix-cache hit), scheduled for the
|
||||
single remaining/next token this step."""
|
||||
return (
|
||||
NewRequestData(
|
||||
req_id=req_id,
|
||||
prompt_token_ids=list(range(prompt_len)),
|
||||
mm_features=[],
|
||||
sampling_params=SamplingParams(),
|
||||
pooling_params=None,
|
||||
block_ids=([0],),
|
||||
num_computed_tokens=num_computed_tokens,
|
||||
lora_request=None,
|
||||
),
|
||||
1,
|
||||
)
|
||||
|
||||
|
||||
def test_prefill_continuation_keeps_placeholder_decode_zero_draft_becomes_zero(
|
||||
spec_decode_model_runner,
|
||||
):
|
||||
"""One request has one token left to prefill (`num_computed_tokens ==
|
||||
num_prompt_tokens - 1`); another has already finished its prompt and is
|
||||
now decoding with no draft tokens proposed this step; a third is decoding
|
||||
with a real draft. `decode_with_draft` gives the batch a non-empty
|
||||
`scheduled_spec_decode_tokens`, so this also exercises the `-1`-vs-`0`
|
||||
distinction on the pre-fix definition of `use_spec_decode` (`len(sched
|
||||
uled_spec_decode_tokens) > 0`), isolating the mask fix from the unrelated
|
||||
`use_spec_decode` predicate fix that landed in the same patch."""
|
||||
runner = spec_decode_model_runner
|
||||
|
||||
prefill_req, prefill_sched = _new_request(
|
||||
"prefill_tail", prompt_len=11, num_computed_tokens=10
|
||||
)
|
||||
decode_req, decode_sched = _new_request(
|
||||
"decode_zero_draft", prompt_len=3, num_computed_tokens=3
|
||||
)
|
||||
drafted_req, _ = _new_request(
|
||||
"decode_with_draft", prompt_len=3, num_computed_tokens=3
|
||||
)
|
||||
num_scheduled_tokens = {
|
||||
"prefill_tail": prefill_sched,
|
||||
"decode_zero_draft": decode_sched,
|
||||
"decode_with_draft": 2, # 1 draft token + 1 bonus token
|
||||
}
|
||||
scheduler_output = SchedulerOutput(
|
||||
scheduled_new_reqs=[prefill_req, decode_req, drafted_req],
|
||||
scheduled_cached_reqs=CachedRequestData.make_empty(),
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
total_num_scheduled_tokens=sum(num_scheduled_tokens.values()),
|
||||
scheduled_spec_decode_tokens={"decode_with_draft": [99]},
|
||||
scheduled_encoder_inputs={},
|
||||
finished_req_ids=set(),
|
||||
free_encoder_mm_hashes=[],
|
||||
)
|
||||
|
||||
runner._update_states(scheduler_output)
|
||||
runner._prepare_inputs(
|
||||
scheduler_output,
|
||||
np.array(
|
||||
[num_scheduled_tokens[r] for r in runner.input_batch.req_ids],
|
||||
dtype=np.int32,
|
||||
),
|
||||
)
|
||||
|
||||
prefill_idx = runner.input_batch.req_id_to_index["prefill_tail"]
|
||||
decode_idx = runner.input_batch.req_id_to_index["decode_zero_draft"]
|
||||
drafted_idx = runner.input_batch.req_id_to_index["decode_with_draft"]
|
||||
assert runner.num_decode_draft_tokens.np[prefill_idx] == -1
|
||||
assert runner.num_decode_draft_tokens.np[decode_idx] == 0
|
||||
assert runner.num_decode_draft_tokens.np[drafted_idx] == 1
|
||||
|
||||
|
||||
def test_prefill_tail_of_two_or_three_tokens_also_keeps_the_placeholder(
|
||||
spec_decode_model_runner,
|
||||
):
|
||||
"""A chunked-prefill tail can be 1, 2, or 3 tokens (`long_prefill_token_
|
||||
threshold` rounding); the mask only fires for `num_scheduled_tokens == 1`,
|
||||
so wider tails must keep `-1` regardless of how much prompt is left. A
|
||||
third, drafted decode row keeps `scheduled_spec_decode_tokens` non-empty
|
||||
so the assertions hold on the pre-fix `use_spec_decode` predicate too."""
|
||||
runner = spec_decode_model_runner
|
||||
|
||||
tail_2_req, _ = _new_request("tail_2", prompt_len=12, num_computed_tokens=10)
|
||||
tail_3_req, _ = _new_request("tail_3", prompt_len=13, num_computed_tokens=10)
|
||||
drafted_req, _ = _new_request(
|
||||
"decode_with_draft", prompt_len=3, num_computed_tokens=3
|
||||
)
|
||||
num_scheduled_tokens = {"tail_2": 2, "tail_3": 3, "decode_with_draft": 2}
|
||||
scheduler_output = SchedulerOutput(
|
||||
scheduled_new_reqs=[tail_2_req, tail_3_req, drafted_req],
|
||||
scheduled_cached_reqs=CachedRequestData.make_empty(),
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
total_num_scheduled_tokens=sum(num_scheduled_tokens.values()),
|
||||
scheduled_spec_decode_tokens={"decode_with_draft": [99]},
|
||||
scheduled_encoder_inputs={},
|
||||
finished_req_ids=set(),
|
||||
free_encoder_mm_hashes=[],
|
||||
)
|
||||
|
||||
runner._update_states(scheduler_output)
|
||||
runner._prepare_inputs(
|
||||
scheduler_output,
|
||||
np.array(
|
||||
[num_scheduled_tokens[r] for r in runner.input_batch.req_ids],
|
||||
dtype=np.int32,
|
||||
),
|
||||
)
|
||||
|
||||
tail_2_idx = runner.input_batch.req_id_to_index["tail_2"]
|
||||
tail_3_idx = runner.input_batch.req_id_to_index["tail_3"]
|
||||
assert runner.num_decode_draft_tokens.np[tail_2_idx] == -1
|
||||
assert runner.num_decode_draft_tokens.np[tail_3_idx] == -1
|
||||
@@ -1,810 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import CUDAGraphMode, ParallelConfig, VllmConfig
|
||||
from vllm.forward_context import set_forward_context
|
||||
from vllm.model_executor.layers.fused_moe.router.fused_topk_router import fused_topk
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID, get_dcp_local_seq_lens
|
||||
from vllm.v1.attention.ops import pcp as attention_pcp
|
||||
from vllm.v1.worker.gpu import cp_utils as gpu_cp_utils
|
||||
from vllm.v1.worker.gpu import pcp_manager as pcp_manager_module
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers, set_dummy_context
|
||||
from vllm.v1.worker.gpu.pcp_manager import PCPManager
|
||||
|
||||
|
||||
def _copy_to_cpu(value, device=None, dtype=None, out=None):
|
||||
tensor = torch.from_numpy(value) if isinstance(value, np.ndarray) else value
|
||||
if out is not None:
|
||||
return out.copy_(tensor)
|
||||
return tensor
|
||||
|
||||
|
||||
def _make_config(cudagraph_mode: CUDAGraphMode):
|
||||
return SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=2,
|
||||
decode_context_parallel_size=1,
|
||||
pipeline_parallel_size=1,
|
||||
dcp_comm_backend="ag_rs",
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
use_mla=True,
|
||||
is_encoder_decoder=False,
|
||||
hf_text_config=SimpleNamespace(),
|
||||
),
|
||||
lora_config=None,
|
||||
speculative_config=None,
|
||||
compilation_config=SimpleNamespace(cudagraph_mode=cudagraph_mode),
|
||||
)
|
||||
|
||||
|
||||
def _make_capture_manager(block_table: torch.Tensor):
|
||||
block_tables = SimpleNamespace(
|
||||
input_block_tables=(block_table,),
|
||||
num_kv_cache_groups=1,
|
||||
block_sizes=(2,),
|
||||
cp_interleave=1,
|
||||
)
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=False,
|
||||
max_num_reqs=4,
|
||||
max_num_tokens=8,
|
||||
block_tables=block_tables,
|
||||
)
|
||||
return manager, block_tables
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cudagraph_mode",
|
||||
[CUDAGraphMode.FULL_DECODE_ONLY, CUDAGraphMode.FULL_AND_PIECEWISE],
|
||||
)
|
||||
def test_validate_config_accepts_decode_only_full_graphs(cudagraph_mode):
|
||||
PCPManager.validate_config(_make_config(cudagraph_mode), supports_mm_inputs=False)
|
||||
|
||||
|
||||
def test_validate_config_rejects_full_graph_for_prefills():
|
||||
with pytest.raises(NotImplementedError, match="decode-only routines"):
|
||||
PCPManager.validate_config(
|
||||
_make_config(CUDAGraphMode.FULL), supports_mm_inputs=False
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft_uses_mla", [False, True])
|
||||
@pytest.mark.parametrize("dcp_size", [1, 2, 4])
|
||||
def test_validate_config_dcp_for_dspark(draft_uses_mla, dcp_size):
|
||||
config = _make_config(CUDAGraphMode.NONE)
|
||||
config.parallel_config.prefill_context_parallel_size = 4
|
||||
config.parallel_config.decode_context_parallel_size = dcp_size
|
||||
config.model_config.hf_text_config.index_topk = 1
|
||||
config.speculative_config = SimpleNamespace(
|
||||
use_dspark=lambda: True,
|
||||
draft_model_config=SimpleNamespace(use_mla=draft_uses_mla),
|
||||
)
|
||||
if draft_uses_mla and dcp_size == 2:
|
||||
with pytest.raises(NotImplementedError, match="requires DCP=1 or DCP=PCP"):
|
||||
PCPManager.validate_config(config, supports_mm_inputs=False)
|
||||
return
|
||||
PCPManager.validate_config(config, supports_mm_inputs=False)
|
||||
|
||||
|
||||
def test_sharded_decode_piecewise_graph_padding(monkeypatch):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
dcp_world_size=1,
|
||||
)
|
||||
monkeypatch.setattr(pcp_manager_module, "async_tensor_h2d", _copy_to_cpu)
|
||||
|
||||
segments_by_rank, per_rank_num_tokens = manager._build_batch_layout(
|
||||
num_scheduled_tokens=np.ones(3, dtype=np.int32),
|
||||
num_computed_tokens=np.full(3, 16, dtype=np.int32),
|
||||
is_prefilling=np.zeros(3, dtype=np.bool_),
|
||||
query_start_loc_np=np.arange(4, dtype=np.int32),
|
||||
padded_num_tokens=4,
|
||||
)
|
||||
|
||||
assert per_rank_num_tokens == [2, 1]
|
||||
request_indices = [
|
||||
[segment.global_batch_req_idx for segment in rank] for rank in segments_by_rank
|
||||
]
|
||||
assert request_indices == [[0, 2], [1]]
|
||||
assert torch.equal(manager._hidden_restore_idx, torch.tensor([0, 4, 1]))
|
||||
assert torch.equal(
|
||||
manager._padded_gather_idx,
|
||||
torch.tensor([0, 2, 0, 0, 1, 0, 0, 0]),
|
||||
)
|
||||
assert torch.equal(
|
||||
manager._gathered_kv_write_mask,
|
||||
torch.tensor([True, True, False, False, True, False, False, False]),
|
||||
)
|
||||
|
||||
|
||||
def test_input_buffers_are_exposed_for_cudagraph_capture():
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=False,
|
||||
max_num_reqs=4,
|
||||
max_num_tokens=8,
|
||||
)
|
||||
|
||||
assert manager.input_buffers is manager._input_buffers
|
||||
assert manager.input_buffers.input_ids.shape == (8,)
|
||||
assert manager.input_buffers.positions.shape == (8,)
|
||||
assert manager.input_buffers.is_padding.shape == (8,)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pcp_world_size", "num_scheduled_tokens", "is_prefilling", "expected"),
|
||||
[
|
||||
(2, [8], [True], 4),
|
||||
(2, [7], [True], 4),
|
||||
(2, [3], [False], 3),
|
||||
(2, [3, 8], [False, True], 7),
|
||||
(4, [2, 9], [False, True], 4),
|
||||
],
|
||||
)
|
||||
def test_num_tokens_for_dispatch_uses_largest_pcp_rank(
|
||||
pcp_world_size, num_scheduled_tokens, is_prefilling, expected
|
||||
):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=pcp_world_size,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
)
|
||||
|
||||
actual = manager.get_num_tokens_for_dispatch(
|
||||
np.asarray(num_scheduled_tokens, dtype=np.int32),
|
||||
np.asarray(is_prefilling, dtype=np.bool_),
|
||||
)
|
||||
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def test_graph_padding_cannot_be_smaller_than_largest_pcp_rank(monkeypatch):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
dcp_world_size=1,
|
||||
)
|
||||
monkeypatch.setattr(pcp_manager_module, "async_tensor_h2d", _copy_to_cpu)
|
||||
|
||||
with pytest.raises(ValueError, match="smaller than the largest rank-local batch"):
|
||||
manager._build_batch_layout(
|
||||
num_scheduled_tokens=np.ones(3, dtype=np.int32),
|
||||
num_computed_tokens=np.full(3, 16, dtype=np.int32),
|
||||
is_prefilling=np.zeros(3, dtype=np.bool_),
|
||||
query_start_loc_np=np.arange(4, dtype=np.int32),
|
||||
padded_num_tokens=1,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs GPU kernels")
|
||||
@pytest.mark.parametrize(
|
||||
("cg_mode", "num_reqs", "expected_tokens", "expected_reqs"),
|
||||
[
|
||||
(CUDAGraphMode.NONE, 4, 2, 2),
|
||||
(CUDAGraphMode.PIECEWISE, None, 8, 2),
|
||||
(CUDAGraphMode.FULL, 4, 8, 4),
|
||||
],
|
||||
)
|
||||
def test_partition_padding_is_derived_from_batch_descriptor(
|
||||
cg_mode, num_reqs, expected_tokens, expected_reqs
|
||||
):
|
||||
"""partition_batch derives graph padding from the batch descriptor: no
|
||||
padding without graphs, token padding only for PIECEWISE, and request
|
||||
padding on top for FULL."""
|
||||
device = torch.device("cuda:0")
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=device,
|
||||
shard_decode_requests=False,
|
||||
max_num_reqs=4,
|
||||
max_num_tokens=8,
|
||||
)
|
||||
global_batch = _make_global_decode_batch(
|
||||
[16, 24], InputBuffers(4, 8, device), device
|
||||
)
|
||||
|
||||
local_batch = manager.partition_batch(
|
||||
global_batch,
|
||||
BatchExecutionDescriptor(
|
||||
cg_mode=cg_mode,
|
||||
num_tokens=8,
|
||||
num_reqs=num_reqs,
|
||||
),
|
||||
)
|
||||
|
||||
assert local_batch.num_tokens_after_padding == expected_tokens
|
||||
assert local_batch.num_reqs_after_padding == expected_reqs
|
||||
|
||||
|
||||
def test_dummy_draft_does_not_reuse_previous_graph_batch():
|
||||
manager, _ = _make_capture_manager(torch.ones((4, 2), dtype=torch.int32))
|
||||
dummy_batch = InputBatch.make_dummy(1, 4, manager.input_buffers)
|
||||
manager.draft_prefill_batch = replace(dummy_batch)
|
||||
|
||||
manager.prepare_draft_prefill(dummy_batch, dummy_batch.input_ids)
|
||||
|
||||
draft_inputs, _ = manager.get_draft_input_buffers(
|
||||
manager.input_buffers, dummy_batch.num_tokens_after_padding
|
||||
)
|
||||
assert draft_inputs is manager.input_buffers
|
||||
|
||||
|
||||
def test_capture_uses_pcp_persistent_inputs():
|
||||
manager, _ = _make_capture_manager(torch.ones((4, 2), dtype=torch.int32))
|
||||
|
||||
dummy_batch = InputBatch.make_dummy(
|
||||
num_reqs=4,
|
||||
num_tokens=4,
|
||||
input_buffers=InputBuffers(4, 8, torch.device("cpu")),
|
||||
max_query_len=1,
|
||||
)
|
||||
dummy_batch.input_ids.copy_(torch.arange(4))
|
||||
dummy_batch.positions.fill_(7)
|
||||
input_batch = manager.prepare_inputs_for_capture_or_profile(dummy_batch)
|
||||
|
||||
assert input_batch is not dummy_batch
|
||||
assert input_batch.req_ids == dummy_batch.req_ids
|
||||
for name in ("input_ids", "positions", "is_padding", "query_start_loc", "seq_lens"):
|
||||
actual = getattr(input_batch, name)
|
||||
torch.testing.assert_close(actual, getattr(dummy_batch, name))
|
||||
assert actual.data_ptr() == getattr(manager.input_buffers, name).data_ptr()
|
||||
|
||||
|
||||
def test_block_table_rebind_updates_interleave():
|
||||
manager, block_tables = _make_capture_manager(torch.ones((4, 2), dtype=torch.int32))
|
||||
final_block_tables = SimpleNamespace(**vars(block_tables))
|
||||
final_block_tables.cp_interleave = 64
|
||||
|
||||
manager.set_block_tables(final_block_tables)
|
||||
|
||||
assert manager._block_tables is final_block_tables
|
||||
assert manager.cp_interleave == 64
|
||||
|
||||
|
||||
def test_dummy_context_updates_pcp_local_block_tables():
|
||||
global_block_table = torch.full((4, 4), -1, dtype=torch.int32)
|
||||
manager, block_tables = _make_capture_manager(global_block_table)
|
||||
input_batch = InputBatch.make_dummy(
|
||||
num_reqs=2,
|
||||
num_tokens=2,
|
||||
input_buffers=manager.input_buffers,
|
||||
max_query_len=1,
|
||||
)
|
||||
input_batch = manager.prepare_inputs_for_capture_or_profile(input_batch)
|
||||
local_block_tables = manager.get_dummy_block_tables(input_batch.num_reqs)
|
||||
|
||||
set_dummy_context(
|
||||
input_batch,
|
||||
block_tables,
|
||||
context_len=3,
|
||||
num_kv_blocks=16,
|
||||
max_model_len=16,
|
||||
input_block_tables=local_block_tables,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(
|
||||
local_block_tables[0][:2, :2],
|
||||
torch.tensor([[0, 1], [2, 3]], dtype=torch.int32),
|
||||
)
|
||||
assert torch.all(global_block_table == -1)
|
||||
|
||||
|
||||
def _rank_request_ids(
|
||||
manager: PCPManager,
|
||||
rank: int,
|
||||
req_ids: list[str],
|
||||
*,
|
||||
is_prefilling: np.ndarray | None = None,
|
||||
) -> list[str]:
|
||||
num_reqs = len(req_ids)
|
||||
if is_prefilling is None:
|
||||
is_prefilling = np.zeros(num_reqs, dtype=np.bool_)
|
||||
segments = manager._get_rank_segments(
|
||||
rank=rank,
|
||||
num_scheduled_tokens=np.ones(num_reqs, dtype=np.int32),
|
||||
is_prefilling=is_prefilling,
|
||||
query_start_loc_np=np.arange(num_reqs + 1, dtype=np.int32),
|
||||
)
|
||||
return [req_ids[segment.global_batch_req_idx] for segment in segments]
|
||||
|
||||
|
||||
def test_pcp_only_decode_requests_are_round_robin_balanced_each_step():
|
||||
manager = PCPManager(
|
||||
pcp_world_size=4,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
dcp_world_size=1,
|
||||
)
|
||||
req_ids = [f"request-{idx}" for idx in range(18)]
|
||||
|
||||
owners: dict[str, int] = {}
|
||||
for rank in range(manager.pcp_world_size):
|
||||
for req_id in _rank_request_ids(manager, rank, req_ids):
|
||||
assert req_id not in owners
|
||||
owners[req_id] = rank
|
||||
|
||||
assert owners == {
|
||||
req_id: index % manager.pcp_world_size for index, req_id in enumerate(req_ids)
|
||||
}
|
||||
counts = [list(owners.values()).count(rank) for rank in range(4)]
|
||||
assert max(counts) - min(counts) == 1
|
||||
|
||||
reordered_req_ids = req_ids[::2] + req_ids[1::2]
|
||||
reordered_owners = {
|
||||
req_id: rank
|
||||
for rank in range(manager.pcp_world_size)
|
||||
for req_id in _rank_request_ids(manager, rank, reordered_req_ids)
|
||||
}
|
||||
assert reordered_owners == {
|
||||
req_id: index % manager.pcp_world_size
|
||||
for index, req_id in enumerate(reordered_req_ids)
|
||||
}
|
||||
assert reordered_owners != owners
|
||||
|
||||
|
||||
def test_decode_requests_remain_replicated_when_dcp_is_enabled():
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=False,
|
||||
dcp_world_size=2,
|
||||
)
|
||||
req_ids = ["request-a", "request-b", "request-c"]
|
||||
|
||||
assert _rank_request_ids(manager, 0, req_ids) == req_ids
|
||||
assert _rank_request_ids(manager, 1, req_ids) == req_ids
|
||||
|
||||
|
||||
def test_decode_sharding_allows_ranks_with_no_owned_request():
|
||||
manager = PCPManager(
|
||||
pcp_world_size=4,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
dcp_world_size=1,
|
||||
)
|
||||
req_ids = ["request-a"]
|
||||
|
||||
assert _rank_request_ids(manager, 0, req_ids) == req_ids
|
||||
assert _rank_request_ids(manager, 1, req_ids) == []
|
||||
assert _rank_request_ids(manager, 2, req_ids) == []
|
||||
assert _rank_request_ids(manager, 3, req_ids) == []
|
||||
|
||||
|
||||
def test_prefill_partitioning_is_preserved_with_sharded_decode():
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
dcp_world_size=1,
|
||||
)
|
||||
segments_by_rank = [
|
||||
manager._get_rank_segments(
|
||||
rank=rank,
|
||||
num_scheduled_tokens=np.array([8, 1, 0, 1], dtype=np.int32),
|
||||
is_prefilling=np.array([True, False, False, False]),
|
||||
query_start_loc_np=np.array([0, 8, 9, 9, 10], dtype=np.int32),
|
||||
)
|
||||
for rank in range(manager.pcp_world_size)
|
||||
]
|
||||
|
||||
prefill_tokens = sorted(
|
||||
token_idx
|
||||
for segments in segments_by_rank
|
||||
for segment in segments
|
||||
if segment.global_batch_req_idx == 0
|
||||
for token_idx in range(
|
||||
segment.global_batch_slice.start, segment.global_batch_slice.stop
|
||||
)
|
||||
)
|
||||
decode_owners = {
|
||||
segment.global_batch_req_idx: rank
|
||||
for rank, segments in enumerate(segments_by_rank)
|
||||
for segment in segments
|
||||
if segment.global_batch_req_idx in (1, 3)
|
||||
}
|
||||
|
||||
assert prefill_tokens == list(range(8))
|
||||
assert decode_owners == {1: 0, 3: 1}
|
||||
|
||||
|
||||
def test_sharded_decode_layout_selects_owner_kv_for_replication(monkeypatch):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=True,
|
||||
dcp_world_size=1,
|
||||
)
|
||||
monkeypatch.setattr(pcp_manager_module, "async_tensor_h2d", _copy_to_cpu)
|
||||
manager._build_batch_layout(
|
||||
num_scheduled_tokens=np.array([1, 1, 1], dtype=np.int32),
|
||||
num_computed_tokens=np.array([16, 16, 16], dtype=np.int32),
|
||||
is_prefilling=np.array([False, False, False]),
|
||||
query_start_loc_np=np.array([0, 1, 2, 3], dtype=np.int32),
|
||||
)
|
||||
|
||||
gathered_slot_mapping = manager._convert_to_gathered_slot_mappings(
|
||||
torch.tensor([[123, 456, 789]], dtype=torch.int64)
|
||||
)
|
||||
assert torch.equal(
|
||||
gathered_slot_mapping,
|
||||
torch.tensor([[123, 789, 456, PAD_SLOT_ID]], dtype=torch.int64),
|
||||
)
|
||||
assert torch.equal(manager._hidden_restore_idx, torch.tensor([0, 2, 1]))
|
||||
|
||||
class FakePCPGroup:
|
||||
world_size = 2
|
||||
|
||||
def all_gather(self, tensor: torch.Tensor, dim: int = 0) -> torch.Tensor:
|
||||
assert dim == 0
|
||||
assert tensor.shape == (2, 1)
|
||||
return torch.tensor([[11.0], [33.0], [22.0], [0.0]])
|
||||
|
||||
monkeypatch.setattr(attention_pcp, "get_pcp_group", FakePCPGroup)
|
||||
(gathered_kv,), cache_slot_mapping = attention_pcp._gather_prefill_cache_inputs(
|
||||
(torch.tensor([[11.0], [33.0]]),),
|
||||
gathered_slot_mapping[0],
|
||||
num_decode_tokens=0,
|
||||
shard_decode_requests=True,
|
||||
)
|
||||
|
||||
assert torch.equal(gathered_kv, torch.tensor([[11.0], [33.0], [22.0], [0.0]]))
|
||||
assert torch.equal(cache_slot_mapping, torch.tensor([123, 789, 456, PAD_SLOT_ID]))
|
||||
|
||||
|
||||
def test_replicated_draft_cache_inputs_keep_unexpanded_slot_mapping(monkeypatch):
|
||||
def unexpected_gather():
|
||||
pytest.fail("replicated draft decode must not gather PCP cache inputs")
|
||||
|
||||
monkeypatch.setattr(attention_pcp, "get_pcp_group", unexpected_gather)
|
||||
kv = torch.tensor([[11.0], [22.0], [0.0]])
|
||||
slot_mapping = torch.tensor([123, 456])
|
||||
|
||||
(cache_kv,), cache_slot_mapping = attention_pcp._gather_prefill_cache_inputs(
|
||||
(kv,), slot_mapping, num_decode_tokens=2, shard_decode_requests=True
|
||||
)
|
||||
|
||||
assert torch.equal(cache_kv, kv[:2])
|
||||
assert torch.equal(cache_slot_mapping, slot_mapping)
|
||||
|
||||
|
||||
def _rank_rows(
|
||||
pcp_rank: int,
|
||||
pcp_world_size: int,
|
||||
num_scheduled_tokens: np.ndarray,
|
||||
num_computed_tokens: np.ndarray,
|
||||
is_prefilling: np.ndarray,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""One PCP+DCP rank's rows as (global request, extent)."""
|
||||
manager = PCPManager(
|
||||
pcp_world_size=pcp_world_size,
|
||||
pcp_rank=pcp_rank,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=False,
|
||||
dcp_world_size=2,
|
||||
)
|
||||
query_start_loc_np = np.concatenate([[0], np.cumsum(num_scheduled_tokens)]).astype(
|
||||
np.int32
|
||||
)
|
||||
segments = manager._get_rank_segments(
|
||||
pcp_rank, num_scheduled_tokens, is_prefilling, query_start_loc_np
|
||||
)
|
||||
rows = np.array([segment.global_batch_req_idx for segment in segments])
|
||||
extents = (num_computed_tokens + num_scheduled_tokens)[rows]
|
||||
return rows, extents
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("num_scheduled_tokens", "num_computed_tokens"),
|
||||
[
|
||||
([32, 32], [0, 0]),
|
||||
([32, 32, 32, 32], [0, 0, 0, 0]),
|
||||
([32, 32], [100, 0]), # one continued, one fresh
|
||||
([64, 32, 48], [0, 512, 0]), # ragged lengths and mixed contexts
|
||||
# A replicated prefill BEHIND a split one. Sorting replicated rows first
|
||||
# put request 1 ahead of request 0.
|
||||
([64, 3], [0, 0]),
|
||||
([64, 3, 64], [0, 0, 0]),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("pcp_world_size", [2, 4])
|
||||
def test_published_row_order_is_identical_on_every_pcp_rank(
|
||||
num_scheduled_tokens, num_computed_tokens, pcp_world_size
|
||||
):
|
||||
"""Every rank must map its rows to the same global requests, in the same order."""
|
||||
num_scheduled_tokens = np.array(num_scheduled_tokens, dtype=np.int32)
|
||||
num_computed_tokens = np.array(num_computed_tokens, dtype=np.int32)
|
||||
is_prefilling = np.ones(len(num_scheduled_tokens), dtype=np.bool_)
|
||||
|
||||
orders = [
|
||||
_rank_rows(
|
||||
rank,
|
||||
pcp_world_size,
|
||||
num_scheduled_tokens,
|
||||
num_computed_tokens,
|
||||
is_prefilling,
|
||||
)[0]
|
||||
for rank in range(pcp_world_size)
|
||||
]
|
||||
for rank, order in enumerate(orders[1:], start=1):
|
||||
assert np.array_equal(orders[0], order), (
|
||||
f"rank {rank} rows map to {order.tolist()}, rank 0 to {orders[0].tolist()}"
|
||||
)
|
||||
# Grouped by request and ascending: what the indexer plan indexes by.
|
||||
assert np.all(np.diff(orders[0]) >= 0)
|
||||
|
||||
|
||||
def test_published_row_order_puts_every_decode_before_every_prefill():
|
||||
"""split_decodes_and_prefills takes the FIRST prefilling row as the boundary."""
|
||||
# req 0 is a continued prefill, req 1 is a decode.
|
||||
req_idx, _ = _rank_rows(
|
||||
pcp_rank=0,
|
||||
pcp_world_size=2,
|
||||
num_scheduled_tokens=np.array([32, 1], dtype=np.int32),
|
||||
num_computed_tokens=np.array([100, 20], dtype=np.int32),
|
||||
is_prefilling=np.array([True, False], dtype=np.bool_),
|
||||
)
|
||||
# The decode (request 1) must be row 0.
|
||||
assert req_idx[0] == 1
|
||||
|
||||
|
||||
def test_split_prefill_rows_repeat_the_request_and_its_full_extent():
|
||||
"""Equal adjacent request indices are what let a backend share a KV region."""
|
||||
req_idx, extents = _rank_rows(
|
||||
pcp_rank=1,
|
||||
pcp_world_size=2,
|
||||
num_scheduled_tokens=np.array([64, 3], dtype=np.int32),
|
||||
num_computed_tokens=np.array([100, 0], dtype=np.int32),
|
||||
is_prefilling=np.ones(2, dtype=np.bool_),
|
||||
)
|
||||
assert req_idx.tolist() == [0, 0, 1]
|
||||
assert extents.tolist() == [164, 164, 3]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query_len", [1, 2, 3, 5, 6, 9])
|
||||
def test_dcp_replicates_prefills_too_short_to_split(query_len):
|
||||
"""A prefill that cannot fill 2*pcp chunks is replicated, not split."""
|
||||
pcp_world_size = 2
|
||||
num_scheduled_tokens = np.array([query_len], dtype=np.int32)
|
||||
is_prefilling = np.ones(1, dtype=np.bool_)
|
||||
|
||||
rows_per_rank = []
|
||||
for rank in range(pcp_world_size):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=pcp_world_size,
|
||||
pcp_rank=rank,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=False,
|
||||
dcp_world_size=2,
|
||||
)
|
||||
assert manager.replicated_requests(num_scheduled_tokens, is_prefilling)[0]
|
||||
rows = list(
|
||||
manager._iter_rank_chunks(rank, num_scheduled_tokens, is_prefilling)
|
||||
)
|
||||
assert rows == [(0, 0, query_len)]
|
||||
rows_per_rank.append(rows)
|
||||
assert rows_per_rank[0] == rows_per_rank[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pcp_world_size", [2, 4, 8])
|
||||
@pytest.mark.parametrize(
|
||||
"query_len", [16, 17, 31, 32, 33, 63, 64, 65, 127, 128, 129, 1000, 4097]
|
||||
)
|
||||
def test_pcp_first_chunk_row_is_never_short(pcp_world_size, query_len):
|
||||
num_scheduled_tokens = np.array([query_len], dtype=np.int32)
|
||||
is_prefilling = np.ones(1, dtype=np.bool_)
|
||||
|
||||
charged_per_rank = []
|
||||
for rank in range(pcp_world_size):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=pcp_world_size,
|
||||
pcp_rank=rank,
|
||||
device=torch.device("cpu"),
|
||||
shard_decode_requests=False,
|
||||
dcp_world_size=pcp_world_size,
|
||||
)
|
||||
chunk_lens = [
|
||||
chunk_len
|
||||
for _, _, chunk_len in manager._iter_rank_chunks(
|
||||
rank, num_scheduled_tokens, is_prefilling
|
||||
)
|
||||
]
|
||||
assert chunk_lens, f"rank {rank} got no rows for {query_len=}"
|
||||
assert chunk_lens[0] == max(chunk_lens), (
|
||||
f"rank {rank} emitted a short first chunk for {query_len=}: {chunk_lens}"
|
||||
)
|
||||
charged_per_rank.append(len(chunk_lens) * chunk_lens[0])
|
||||
|
||||
assert len(set(charged_per_rank)) == 1, (
|
||||
f"ranks would chunk differently for {query_len=}: {charged_per_rank}"
|
||||
)
|
||||
|
||||
|
||||
def _make_global_decode_batch(
|
||||
num_computed_tokens: list[int], buffers: InputBuffers, device: torch.device
|
||||
) -> InputBatch:
|
||||
"""A replicate-decode global batch as `prepare_inputs` would build it."""
|
||||
num_reqs = len(num_computed_tokens)
|
||||
num_tokens = num_reqs
|
||||
seq_lens_np = np.asarray(num_computed_tokens, dtype=np.int32) + 1
|
||||
|
||||
base = InputBatch.make_dummy(num_reqs, num_tokens, buffers)
|
||||
buffers.seq_lens[:num_reqs] = torch.from_numpy(seq_lens_np).to(device)
|
||||
buffers.positions[:num_reqs] = torch.tensor(num_computed_tokens, device=device)
|
||||
query_start_loc_np = np.arange(num_reqs + 1, dtype=np.int32)
|
||||
buffers.query_start_loc[: num_reqs + 1] = torch.from_numpy(query_start_loc_np).to(
|
||||
device
|
||||
)
|
||||
|
||||
return replace(
|
||||
base,
|
||||
req_ids=[f"req_{i}" for i in range(num_reqs)],
|
||||
num_reqs=num_reqs,
|
||||
num_reqs_after_padding=num_reqs,
|
||||
idx_mapping=torch.arange(num_reqs, dtype=torch.int32, device=device),
|
||||
idx_mapping_np=np.arange(num_reqs, dtype=np.int32),
|
||||
num_scheduled_tokens=np.ones(num_reqs, dtype=np.int32),
|
||||
num_tokens=num_tokens,
|
||||
num_tokens_after_padding=num_tokens,
|
||||
num_draft_tokens=0,
|
||||
num_draft_tokens_per_req=np.zeros(num_reqs, dtype=np.int32),
|
||||
query_start_loc=buffers.query_start_loc[: num_reqs + 1],
|
||||
query_start_loc_np=query_start_loc_np,
|
||||
seq_lens=buffers.seq_lens[:num_reqs],
|
||||
seq_lens_cpu_upper_bound=torch.from_numpy(seq_lens_np),
|
||||
dcp_local_seq_lens=None,
|
||||
num_computed_tokens_np=np.asarray(num_computed_tokens, dtype=np.int32),
|
||||
prefill_len_np=np.zeros(num_reqs, dtype=np.int32),
|
||||
num_computed_prefill_tokens_np=np.zeros(num_reqs, dtype=np.int32),
|
||||
is_prefilling_np=np.zeros(num_reqs, dtype=np.bool_),
|
||||
input_ids=buffers.input_ids[:num_tokens],
|
||||
positions=buffers.positions[:num_tokens],
|
||||
is_padding=buffers.is_padding[:num_tokens],
|
||||
prompt_lens=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs GPU kernels")
|
||||
def test_partition_defers_dcp_metadata_to_post_partition_batch():
|
||||
"""DCP-local lengths must derive from the partitioned batch, not the
|
||||
global one: the partition replaces seq_lens, so a pre-partition value is
|
||||
stale. partition_batch therefore returns None, and the runtime populates
|
||||
the field afterwards from the PCP-owned buffers.
|
||||
"""
|
||||
device = torch.device("cuda:0")
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=0,
|
||||
device=device,
|
||||
shard_decode_requests=False,
|
||||
max_num_reqs=4,
|
||||
max_num_tokens=8,
|
||||
dcp_world_size=2,
|
||||
dcp_rank=0,
|
||||
)
|
||||
|
||||
global_buffers = InputBuffers(4, 8, device)
|
||||
global_batch = _make_global_decode_batch([16, 24], global_buffers, device)
|
||||
# A leftover from an earlier DCP batch must not survive the partition.
|
||||
global_batch.dcp_local_seq_lens = global_buffers.dcp_local_seq_lens[:2]
|
||||
global_batch.dcp_local_seq_lens.fill_(-1)
|
||||
|
||||
local_batch = manager.partition_batch(
|
||||
global_batch,
|
||||
BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.FULL,
|
||||
num_tokens=4,
|
||||
num_reqs=4,
|
||||
),
|
||||
)
|
||||
|
||||
assert local_batch.dcp_local_seq_lens is None
|
||||
assert local_batch.seq_lens.tolist() == [17, 25, 0, 0]
|
||||
assert local_batch.dcp_local_seq_lens_cpu_upper_bound is not None
|
||||
expected_dcp_upper_bound = get_dcp_local_seq_lens(
|
||||
torch.tensor([17, 25], dtype=torch.int32), 2, 0, 1
|
||||
)
|
||||
assert torch.equal(
|
||||
local_batch.dcp_local_seq_lens_cpu_upper_bound,
|
||||
torch.cat([expected_dcp_upper_bound, torch.zeros(2, dtype=torch.int32)]),
|
||||
)
|
||||
|
||||
# What execute_model does next: derive DCP metadata from the final batch
|
||||
# on the PCP-owned buffers.
|
||||
local_batch.dcp_local_seq_lens = gpu_cp_utils.prepare_dcp_local_seq_lens(
|
||||
manager.input_buffers.dcp_local_seq_lens,
|
||||
local_batch.seq_lens,
|
||||
local_batch.num_reqs,
|
||||
dcp_size=2,
|
||||
dcp_rank=0,
|
||||
cp_interleave=1,
|
||||
num_reqs_padded=local_batch.num_reqs_after_padding,
|
||||
)
|
||||
expected = get_dcp_local_seq_lens(
|
||||
torch.tensor([17, 25, 0, 0], dtype=torch.int32), 2, 0, 1
|
||||
)
|
||||
assert local_batch.dcp_local_seq_lens is not None
|
||||
assert torch.equal(local_batch.dcp_local_seq_lens.cpu(), expected)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs GPU kernels")
|
||||
def test_moe_padding_matches_pcp_all_gather(monkeypatch):
|
||||
"""The PCP batch carries the all-gather of every rank's local padding mask,
|
||||
the rows the MoE routes, even when ranks own different numbers of tokens."""
|
||||
monkeypatch.setenv("VLLM_MOE_SKIP_PADDING", "1")
|
||||
device = torch.device("cuda:0")
|
||||
local_masks, batch_masks = [], []
|
||||
for pcp_rank in range(2):
|
||||
manager = PCPManager(
|
||||
pcp_world_size=2,
|
||||
pcp_rank=pcp_rank,
|
||||
device=device,
|
||||
shard_decode_requests=True,
|
||||
max_num_reqs=4,
|
||||
max_num_tokens=8,
|
||||
moe_gathers_tokens=True,
|
||||
)
|
||||
global_batch = _make_global_decode_batch(
|
||||
[16, 24, 32], InputBuffers(4, 8, device), device
|
||||
)
|
||||
local_batch = manager.partition_batch(
|
||||
global_batch,
|
||||
BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.PIECEWISE, num_tokens=4, num_reqs=None
|
||||
),
|
||||
)
|
||||
num_tokens = local_batch.num_tokens_after_padding
|
||||
local_masks.append(manager.input_buffers.is_padding[:num_tokens].cpu())
|
||||
batch_masks.append(local_batch.is_padding.clone())
|
||||
|
||||
# Sharded decode puts two requests on rank 0 and one on rank 1.
|
||||
assert [mask.logical_not().sum().item() for mask in local_masks] == [2, 1]
|
||||
for batch_mask in batch_masks:
|
||||
assert torch.equal(batch_mask.cpu(), torch.cat(local_masks))
|
||||
num_tokens = batch_mask.numel()
|
||||
hidden_states = torch.randn(num_tokens, 4, device=device)
|
||||
router_logits = torch.randn(num_tokens, 8, device=device)
|
||||
with set_forward_context(None, VllmConfig(), is_padding=batch_mask):
|
||||
_, topk_ids, _ = fused_topk(hidden_states, router_logits, 2, False)
|
||||
assert (topk_ids[~batch_mask] >= 0).all()
|
||||
assert (topk_ids[batch_mask] == -1).all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pcp_world_size", "dcp_world_size", "expected"),
|
||||
[(1, 1, False), (2, 1, True), (2, 2, False)],
|
||||
)
|
||||
def test_parallel_config_manages_decode_sharding(
|
||||
pcp_world_size: int, dcp_world_size: int, expected: bool
|
||||
):
|
||||
parallel_config = ParallelConfig(
|
||||
prefill_context_parallel_size=pcp_world_size,
|
||||
decode_context_parallel_size=dcp_world_size,
|
||||
distributed_executor_backend="ray",
|
||||
)
|
||||
|
||||
assert parallel_config.pcp_shard_decode_requests is expected
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,291 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import MethodType, SimpleNamespace
|
||||
from typing import get_args
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config.model import PROCESSED_LOGPROBS_MODES, LogprobsMode
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.sample.output import SamplingMaskTensors
|
||||
from vllm.v1.worker.gpu.spec_decode.rejection_sampler import (
|
||||
RejectionSampler,
|
||||
_iter_request_chunks,
|
||||
)
|
||||
|
||||
|
||||
def _make_input_batch(
|
||||
cu_num_logits_np: np.ndarray,
|
||||
idx_mapping_np: np.ndarray,
|
||||
device: torch.device,
|
||||
) -> SimpleNamespace:
|
||||
"""Minimal InputBatch fields read by RejectionSampler._verify_in_chunks."""
|
||||
num_reqs = len(idx_mapping_np)
|
||||
num_logits_per_req = np.diff(cu_num_logits_np)
|
||||
return SimpleNamespace(
|
||||
num_reqs=num_reqs,
|
||||
cu_num_logits_np=cu_num_logits_np,
|
||||
cu_num_logits=torch.from_numpy(cu_num_logits_np).to(device),
|
||||
idx_mapping_np=idx_mapping_np,
|
||||
idx_mapping=torch.from_numpy(idx_mapping_np).to(device),
|
||||
expanded_idx_mapping=torch.from_numpy(
|
||||
np.repeat(idx_mapping_np, num_logits_per_req)
|
||||
).to(device),
|
||||
expanded_local_pos=torch.from_numpy(
|
||||
np.concatenate(
|
||||
[np.arange(count, dtype=np.int32) for count in num_logits_per_req]
|
||||
)
|
||||
).to(device),
|
||||
seq_lens_cpu_upper_bound=torch.full((num_reqs,), 64, dtype=torch.int32),
|
||||
)
|
||||
|
||||
|
||||
def _make_rejection_sampler(
|
||||
sampler: SimpleNamespace, num_speculative_steps: int
|
||||
) -> RejectionSampler:
|
||||
"""RejectionSampler for standard, fixed-boundary, unwatermarked verification."""
|
||||
rejection_sampler = object.__new__(RejectionSampler)
|
||||
rejection_sampler.sampler = sampler
|
||||
rejection_sampler.num_speculative_steps = num_speculative_steps
|
||||
rejection_sampler.enable_adaptive_verification = False
|
||||
rejection_sampler.synthetic_conditional_rates = None
|
||||
rejection_sampler.use_block_verification = False
|
||||
rejection_sampler.watermark_key = None
|
||||
return rejection_sampler
|
||||
|
||||
|
||||
def test_iter_request_chunks_preserves_request_boundaries():
|
||||
cu_num_logits = np.array([0, 3, 4, 11, 13], dtype=np.int32)
|
||||
|
||||
assert list(_iter_request_chunks(cu_num_logits, max_chunk_logits=5)) == [
|
||||
(0, 2),
|
||||
(2, 3),
|
||||
(3, 4),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
|
||||
@pytest.mark.parametrize("logprobs_mode", get_args(LogprobsMode))
|
||||
def test_chunked_scores_match_full_batch(logprobs_mode: str):
|
||||
device = torch.device("cuda")
|
||||
cu_num_logits_np = np.array([0, 3, 4, 8, 10], dtype=np.int32)
|
||||
num_logits_per_req = np.diff(cu_num_logits_np)
|
||||
idx_mapping_np = np.array([7, 2, 9, 1], dtype=np.int32)
|
||||
input_batch = _make_input_batch(cu_num_logits_np, idx_mapping_np, device)
|
||||
rejection_sampler = _make_rejection_sampler(
|
||||
SimpleNamespace(logprobs_mode=logprobs_mode, return_sampling_mask=False),
|
||||
num_speculative_steps=3,
|
||||
)
|
||||
|
||||
def fake_verify(
|
||||
self,
|
||||
logits,
|
||||
_draft_logits,
|
||||
_draft_sampled,
|
||||
_pos,
|
||||
cu_num_logits,
|
||||
idx_mapping,
|
||||
*_mappings,
|
||||
):
|
||||
num_sampled = torch.diff(cu_num_logits).to(torch.int32)
|
||||
sampled = (
|
||||
idx_mapping.to(torch.int64).unsqueeze(1) + torch.arange(4, device=device)
|
||||
) % logits.shape[1]
|
||||
return logits.float() + 1, sampled, num_sampled
|
||||
|
||||
rejection_sampler._verify = MethodType(fake_verify, rejection_sampler)
|
||||
logits = torch.arange(170, dtype=torch.float32, device=device).view(10, 17)
|
||||
|
||||
sampled, num_sampled, chunked_logprobs, sampling_mask_tensors = (
|
||||
rejection_sampler._verify_in_chunks(
|
||||
logits,
|
||||
input_batch,
|
||||
draft_logits=None,
|
||||
draft_sampled=torch.arange(10, device=device),
|
||||
pos=torch.arange(10, device=device),
|
||||
max_chunk_logits=5,
|
||||
max_num_logprobs=2,
|
||||
)
|
||||
)
|
||||
score_logits = logits + 1 if logprobs_mode in PROCESSED_LOGPROBS_MODES else logits
|
||||
full_logprobs = rejection_sampler._get_logprobs_tensors(
|
||||
sampled,
|
||||
num_sampled,
|
||||
score_logits,
|
||||
input_batch.cu_num_logits,
|
||||
input_batch.cu_num_logits_np,
|
||||
max_num_logprobs=2,
|
||||
)
|
||||
|
||||
assert sampled[:, 0].tolist() == idx_mapping_np.tolist()
|
||||
assert num_sampled.tolist() == num_logits_per_req.tolist()
|
||||
assert chunked_logprobs is not None
|
||||
assert full_logprobs is not None
|
||||
assert torch.equal(
|
||||
chunked_logprobs.logprob_token_ids,
|
||||
full_logprobs.logprob_token_ids,
|
||||
)
|
||||
assert torch.equal(chunked_logprobs.logprobs, full_logprobs.logprobs)
|
||||
assert torch.equal(
|
||||
chunked_logprobs.selected_token_ranks,
|
||||
full_logprobs.selected_token_ranks,
|
||||
)
|
||||
assert (
|
||||
chunked_logprobs.cu_num_generated_tokens
|
||||
== full_logprobs.cu_num_generated_tokens
|
||||
)
|
||||
assert sampling_mask_tensors is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
|
||||
def test_replay_on_off_preserves_rejection_sampling_and_rng(monkeypatch):
|
||||
device = torch.device("cuda")
|
||||
num_reqs = 3
|
||||
num_speculative_steps = 3
|
||||
rows_per_request = num_speculative_steps + 1
|
||||
vocab_size = 8
|
||||
cu_num_logits_np = np.arange(0, 13, rows_per_request, dtype=np.int32)
|
||||
idx_mapping_np = np.arange(num_reqs, dtype=np.int32)
|
||||
input_batch = _make_input_batch(cu_num_logits_np, idx_mapping_np, device)
|
||||
processed_logits = torch.zeros((12, vocab_size), device=device)
|
||||
processed_logits[0, 0] = -float("inf")
|
||||
processed_logits[rows_per_request + 1, 1] = -float("inf")
|
||||
draft_logits = torch.zeros(
|
||||
(num_reqs, num_speculative_steps, vocab_size), device=device
|
||||
)
|
||||
draft_sampled = torch.zeros(
|
||||
(num_reqs, rows_per_request), dtype=torch.int64, device=device
|
||||
)
|
||||
draft_sampled[:, 1:] = torch.tensor([0, 1, 2], device=device)
|
||||
draft_sampled = draft_sampled.flatten()
|
||||
sampler = SimpleNamespace(
|
||||
logprobs_mode="processed_logprobs",
|
||||
return_sampling_mask=False,
|
||||
sampling_states=SimpleNamespace(
|
||||
top_k=SimpleNamespace(np=np.full(num_reqs, vocab_size)),
|
||||
temperature=SimpleNamespace(gpu=torch.ones(num_reqs, device=device)),
|
||||
seeds=SimpleNamespace(
|
||||
gpu=torch.arange(num_reqs, dtype=torch.int64, device=device)
|
||||
),
|
||||
),
|
||||
use_fp64_gumbel=False,
|
||||
apply_sampling_params=lambda logits, *_: logits,
|
||||
)
|
||||
rejection_sampler = _make_rejection_sampler(sampler, num_speculative_steps)
|
||||
pos = torch.arange(12, dtype=torch.int32, device=device)
|
||||
|
||||
pack_calls: list[tuple[list[int], int, int]] = []
|
||||
pack = SamplingMaskTensors.from_logits.__func__
|
||||
|
||||
def track_pack(
|
||||
cls,
|
||||
logits,
|
||||
cu_num_logits,
|
||||
num_sampled_tokens,
|
||||
max_num_kept,
|
||||
rows_per_request=1,
|
||||
):
|
||||
pack_calls.append(
|
||||
(cu_num_logits.cpu().tolist(), max_num_kept, rows_per_request)
|
||||
)
|
||||
return pack(
|
||||
cls,
|
||||
logits,
|
||||
cu_num_logits,
|
||||
num_sampled_tokens,
|
||||
max_num_kept,
|
||||
rows_per_request,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
SamplingMaskTensors,
|
||||
"from_logits",
|
||||
classmethod(track_pack),
|
||||
)
|
||||
|
||||
rng_before = torch.cuda.get_rng_state()
|
||||
off_sampled, off_counts, off_logprobs, off_masks = (
|
||||
rejection_sampler._verify_in_chunks(
|
||||
processed_logits,
|
||||
input_batch,
|
||||
draft_logits,
|
||||
draft_sampled,
|
||||
pos,
|
||||
max_chunk_logits=8,
|
||||
max_num_logprobs=0,
|
||||
)
|
||||
)
|
||||
rng_after_off = torch.cuda.get_rng_state()
|
||||
assert pack_calls == []
|
||||
|
||||
sampler.return_sampling_mask = True
|
||||
on_sampled, on_counts, on_logprobs, on_masks = rejection_sampler._verify_in_chunks(
|
||||
processed_logits,
|
||||
input_batch,
|
||||
draft_logits,
|
||||
draft_sampled,
|
||||
pos,
|
||||
max_chunk_logits=8,
|
||||
max_num_logprobs=0,
|
||||
)
|
||||
rng_after_on = torch.cuda.get_rng_state()
|
||||
|
||||
assert pack_calls == [
|
||||
([0, 4, 8], vocab_size, rows_per_request),
|
||||
([0, 4], vocab_size, rows_per_request),
|
||||
]
|
||||
assert off_masks is None and on_masks is not None
|
||||
assert on_masks.rows_per_request == rows_per_request
|
||||
assert on_masks.token_ids.shape == (num_reqs * rows_per_request, vocab_size)
|
||||
assert on_masks.packed_mask.shape[0] == num_reqs * rows_per_request
|
||||
assert off_counts.tolist() == [1, 2, 4]
|
||||
assert torch.equal(off_counts, on_counts)
|
||||
counts = off_counts.cpu().tolist()
|
||||
for req_idx, count in enumerate(counts):
|
||||
assert torch.equal(off_sampled[req_idx, :count], on_sampled[req_idx, :count])
|
||||
|
||||
mapped_rows = [
|
||||
int(input_batch.cu_num_logits_np[req_idx]) + slot_idx
|
||||
for req_idx, count in enumerate(counts)
|
||||
for slot_idx in range(count)
|
||||
]
|
||||
assert off_logprobs is not None and on_logprobs is not None
|
||||
assert torch.equal(
|
||||
off_logprobs.logprob_token_ids[mapped_rows],
|
||||
on_logprobs.logprob_token_ids[mapped_rows],
|
||||
)
|
||||
assert torch.equal(
|
||||
off_logprobs.logprobs[mapped_rows], on_logprobs.logprobs[mapped_rows]
|
||||
)
|
||||
assert torch.equal(
|
||||
off_logprobs.selected_token_ranks[mapped_rows],
|
||||
on_logprobs.selected_token_ranks[mapped_rows],
|
||||
)
|
||||
assert torch.equal(rng_before, rng_after_off)
|
||||
assert torch.equal(rng_after_off, rng_after_on)
|
||||
|
||||
masks = (
|
||||
on_masks.to_cpu_nonblocking().tolists(on_counts.cpu().numpy()).to_nested_list()
|
||||
)
|
||||
expected_masks = [
|
||||
torch.isfinite(processed_logits[row]).nonzero().flatten().tolist()
|
||||
for row in mapped_rows
|
||||
]
|
||||
emitted = [
|
||||
int(on_sampled[req_idx, slot_idx])
|
||||
for req_idx, count in enumerate(on_counts.cpu().tolist())
|
||||
for slot_idx in range(count)
|
||||
]
|
||||
expected_logprobs = torch.stack(
|
||||
[
|
||||
torch.log_softmax(processed_logits[row], dim=-1)[token_id]
|
||||
for row, token_id in zip(mapped_rows, emitted)
|
||||
]
|
||||
)
|
||||
|
||||
assert masks == expected_masks
|
||||
assert all(token_id in mask for token_id, mask in zip(emitted, masks))
|
||||
assert torch.equal(on_logprobs.logprobs[mapped_rows, 0], expected_logprobs)
|
||||
@@ -1,144 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""int64 indexing in the block-verification rejection sampler kernels.
|
||||
|
||||
With a GLM-scale vocab (~155k), logit_idx * vocab_stride exceeds int32 once
|
||||
logit_idx >= ~13.8k (and req_state_idx * draft_stride_0 similarly), so the
|
||||
block-verification kernels must promote indices to int64 before the stride
|
||||
multiply. These tests place one request at a high logit/request-state index
|
||||
and check its outputs match the same request run alone at index 0.
|
||||
|
||||
Each case allocates ~5 GiB of GPU memory.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.spec_decode.rejection_sampler_utils import rejection_sample
|
||||
|
||||
VOCAB_SIZE = 155264
|
||||
NUM_SPECULATIVE_STEPS = 2
|
||||
LOGITS_PER_REQ = NUM_SPECULATIVE_STEPS + 1
|
||||
|
||||
|
||||
def _run(
|
||||
target_logits: torch.Tensor, # [LOGITS_PER_REQ, V], the request under test
|
||||
draft_logits: torch.Tensor, # [NUM_SPECULATIVE_STEPS, V]
|
||||
draft_tokens: list[int],
|
||||
num_reqs: int,
|
||||
max_num_reqs: int,
|
||||
roi_req: int,
|
||||
req_state_idx: int,
|
||||
device: torch.device,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Run rejection_sample on a batch of uniform k=2 requests, with the
|
||||
request under test at request index `roi_req` and draft-logits row
|
||||
`req_state_idx`. Returns that request's (sampled, num_sampled)."""
|
||||
num_logits = num_reqs * LOGITS_PER_REQ
|
||||
roi_row = roi_req * LOGITS_PER_REQ
|
||||
|
||||
full_target = torch.randn(
|
||||
num_logits, VOCAB_SIZE, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
full_target[roi_row : roi_row + LOGITS_PER_REQ] = target_logits
|
||||
full_draft = torch.randn(
|
||||
max_num_reqs,
|
||||
NUM_SPECULATIVE_STEPS,
|
||||
VOCAB_SIZE,
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
full_draft[req_state_idx] = draft_logits
|
||||
|
||||
# Draft token for step i of request r lives at row r*LOGITS_PER_REQ + i + 1.
|
||||
draft_sampled = torch.zeros(num_logits, dtype=torch.int64, device=device)
|
||||
for i, tok in enumerate(draft_tokens):
|
||||
draft_sampled[roi_row + i + 1] = tok
|
||||
|
||||
cu_num_logits = torch.arange(
|
||||
0, num_logits + 1, LOGITS_PER_REQ, dtype=torch.int32, device=device
|
||||
)
|
||||
# Filler requests all map to draft-logits row 0.
|
||||
idx_mapping = torch.zeros(num_reqs, dtype=torch.int32, device=device)
|
||||
idx_mapping[roi_req] = req_state_idx
|
||||
expanded_idx_mapping = idx_mapping.repeat_interleave(LOGITS_PER_REQ)
|
||||
expanded_local_pos = (
|
||||
torch.arange(LOGITS_PER_REQ, dtype=torch.int32, device=device)
|
||||
.repeat(num_reqs)
|
||||
.contiguous()
|
||||
)
|
||||
|
||||
# Positions only need to match between the reference and big-batch runs
|
||||
# for the request under test (they key the Gumbel noise and uniforms).
|
||||
pos = torch.arange(num_logits, dtype=torch.int64, device=device)
|
||||
pos[roi_row : roi_row + LOGITS_PER_REQ] = torch.arange(
|
||||
1000, 1000 + LOGITS_PER_REQ, dtype=torch.int64, device=device
|
||||
)
|
||||
temperature = torch.ones(max_num_reqs, dtype=torch.float32, device=device)
|
||||
seeds = torch.full((max_num_reqs,), 42, dtype=torch.int64, device=device)
|
||||
|
||||
sampled, num_sampled = rejection_sample(
|
||||
target_logits=full_target,
|
||||
draft_logits=full_draft,
|
||||
draft_sampled=draft_sampled,
|
||||
cu_num_logits=cu_num_logits,
|
||||
pos=pos,
|
||||
idx_mapping=idx_mapping,
|
||||
expanded_idx_mapping=expanded_idx_mapping,
|
||||
expanded_local_pos=expanded_local_pos,
|
||||
temperature=temperature,
|
||||
seed=seeds,
|
||||
num_speculative_steps=NUM_SPECULATIVE_STEPS,
|
||||
use_block_verification=True,
|
||||
)
|
||||
return sampled[roi_req].clone(), num_sampled[roi_req].clone()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
|
||||
@pytest.mark.parametrize(
|
||||
# Overflow triggers when roi_req * LOGITS_PER_REQ * VOCAB_SIZE (target
|
||||
# logits) or req_state_idx * NUM_SPECULATIVE_STEPS * VOCAB_SIZE (draft
|
||||
# logits) exceeds 2**31.
|
||||
("num_reqs", "max_num_reqs", "roi_req", "req_state_idx"),
|
||||
[
|
||||
(5500, 4, 5000, 2), # target-side: logit_idx 15000 * V > 2**31
|
||||
(22, 8192, 11, 8000), # draft-side: req_state_idx 8000 * 2V > 2**31
|
||||
],
|
||||
)
|
||||
def test_block_verification_i64_indexing(
|
||||
num_reqs: int, max_num_reqs: int, roi_req: int, req_state_idx: int
|
||||
):
|
||||
device = torch.device("cuda:0")
|
||||
torch.manual_seed(0)
|
||||
target_logits = torch.randn(
|
||||
LOGITS_PER_REQ, VOCAB_SIZE, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
draft_logits = torch.randn(
|
||||
NUM_SPECULATIVE_STEPS, VOCAB_SIZE, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
draft_tokens = [123, 45678]
|
||||
|
||||
sampled_ref, num_sampled_ref = _run(
|
||||
target_logits,
|
||||
draft_logits,
|
||||
draft_tokens,
|
||||
num_reqs=1,
|
||||
max_num_reqs=1,
|
||||
roi_req=0,
|
||||
req_state_idx=0,
|
||||
device=device,
|
||||
)
|
||||
sampled, num_sampled = _run(
|
||||
target_logits,
|
||||
draft_logits,
|
||||
draft_tokens,
|
||||
num_reqs=num_reqs,
|
||||
max_num_reqs=max_num_reqs,
|
||||
roi_req=roi_req,
|
||||
req_state_idx=req_state_idx,
|
||||
device=device,
|
||||
)
|
||||
assert num_sampled.item() == num_sampled_ref.item()
|
||||
n = num_sampled_ref.item()
|
||||
assert torch.equal(sampled[:n], sampled_ref[:n])
|
||||
@@ -1,203 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""int64 row offsets in the MRV2 staged-write and idx-mapping kernels.
|
||||
|
||||
With int32 request-slot indices, `slot * stride` wraps once the product
|
||||
crosses 2**31 (issue #57030): at max_model_len=1M from row 2148, and from
|
||||
row 716 for the 3-dim mrope positions. Each test runs a control row below
|
||||
and an overflow row above the threshold in the same kernel launch.
|
||||
Requires CUDA/ROCm and ~11 GiB free device memory: the tensors must exceed
|
||||
2**31 elements by construction.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.worker.gpu.buffer_utils import StagedWriteTensor
|
||||
from vllm.v1.worker.gpu.input_batch import post_update
|
||||
from vllm.v1.worker.gpu.mm.rope import RopeState
|
||||
from vllm.v1.worker.gpu.sample.penalties import bincount
|
||||
|
||||
STRIDE = 1_000_000 # max_model_len
|
||||
ROW = 2559 # ROW * STRIDE > 2**31 (first overflowing row at 1M: 2148)
|
||||
NUM_ROWS = ROW + 1 # (2560, 1M) int32 = 10.24 GB
|
||||
NEEDED_BYTES = NUM_ROWS * STRIDE * 4
|
||||
VOCAB_SIZE = 8192
|
||||
PROMPT_LEN = 1024
|
||||
PREFILL_LEN = 2048
|
||||
|
||||
# mrope: flat row = NUM_DIMS * req + j and stride0 = NUM_DIMS * STRIDE, so
|
||||
# the overflow threshold drops to row 716 of a 1M-row buffer.
|
||||
NUM_DIMS = 3
|
||||
ROPE_ROW = 716 # NUM_DIMS * ROPE_ROW * STRIDE > 2**31
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(), reason="requires CUDA or ROCm"
|
||||
),
|
||||
pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike()
|
||||
or torch.accelerator.get_memory_info(0)[0]
|
||||
< NEEDED_BYTES + 2**30, # slack for the outputs
|
||||
reason=f"requires >= {NEEDED_BYTES / 2**30:.0f} GiB free memory",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def test_staged_write_high_row():
|
||||
"""Apply-write past the int32 offset limit must land on the target row."""
|
||||
device = torch.device("cuda:0")
|
||||
content = list(range(9000, 9016))
|
||||
staged = StagedWriteTensor((NUM_ROWS, STRIDE), torch.int32, device)
|
||||
staged.stage_write(ROW, 0, content)
|
||||
staged.apply_write()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert staged.gpu[ROW, : len(content)].tolist() == content
|
||||
# A wrapped offset must not clobber row 0 (silent-corruption variant).
|
||||
assert staged.gpu[0, : len(content)].tolist() == [0] * len(content)
|
||||
|
||||
|
||||
def test_bincount_high_row():
|
||||
"""penalties.bincount past the int32 offset limit must hit the right row."""
|
||||
device = torch.device("cuda:0")
|
||||
tokens = torch.arange(PREFILL_LEN, dtype=torch.int32, device=device)
|
||||
|
||||
all_token_ids = torch.zeros(NUM_ROWS, STRIDE, dtype=torch.int32, device=device)
|
||||
all_token_ids[0, :PREFILL_LEN] = tokens
|
||||
all_token_ids[ROW, :PREFILL_LEN] = tokens
|
||||
|
||||
prompt_len = torch.zeros(NUM_ROWS, dtype=torch.int32, device=device)
|
||||
prefill_len = torch.zeros(NUM_ROWS, dtype=torch.int32, device=device)
|
||||
prompt_len[[0, ROW]] = PROMPT_LEN
|
||||
prefill_len[[0, ROW]] = PREFILL_LEN
|
||||
|
||||
idx_mapping = torch.tensor([0, ROW], dtype=torch.int64, device=device)
|
||||
prompt_bin_mask = torch.zeros(
|
||||
NUM_ROWS, cdiv(VOCAB_SIZE, 32), dtype=torch.int32, device=device
|
||||
)
|
||||
output_bin_counts = torch.zeros(
|
||||
NUM_ROWS, VOCAB_SIZE, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
bincount(
|
||||
idx_mapping,
|
||||
all_token_ids,
|
||||
prompt_len,
|
||||
prefill_len,
|
||||
prompt_bin_mask,
|
||||
output_bin_counts,
|
||||
max_prefill_len=PREFILL_LEN,
|
||||
)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert torch.equal(prompt_bin_mask[ROW], prompt_bin_mask[0])
|
||||
assert torch.equal(output_bin_counts[ROW], output_bin_counts[0])
|
||||
# Sanity: the control row got prompt bits and output counts.
|
||||
assert prompt_bin_mask[0, : cdiv(PROMPT_LEN, 32)].any().item()
|
||||
assert (
|
||||
output_bin_counts[0, PROMPT_LEN:PREFILL_LEN].sum().item()
|
||||
== PREFILL_LEN - PROMPT_LEN
|
||||
)
|
||||
|
||||
|
||||
def test_post_update_high_row():
|
||||
"""post_update (runs every sampled token) must store on the mapped row."""
|
||||
device = torch.device("cuda:0")
|
||||
# Big buffer first so a wrapped (negative) offset cannot land in-bounds.
|
||||
all_token_ids = torch.zeros(NUM_ROWS, STRIDE, dtype=torch.int32, device=device)
|
||||
num_computed = torch.zeros(NUM_ROWS, dtype=torch.int32, device=device)
|
||||
last_sampled = torch.full((NUM_ROWS, 1), -1, dtype=torch.int64, device=device)
|
||||
total_len = torch.zeros(NUM_ROWS, dtype=torch.int32, device=device)
|
||||
total_len[[0, ROW]] = torch.tensor([50, 100], dtype=torch.int32, device=device)
|
||||
|
||||
idx_mapping = torch.tensor([0, ROW], dtype=torch.int64, device=device)
|
||||
sampled_tokens = torch.tensor([[111], [222]], dtype=torch.int64, device=device)
|
||||
num_sampled = torch.tensor([1, 1], dtype=torch.int32, device=device)
|
||||
num_rejected = torch.tensor([0, 0], dtype=torch.int32, device=device)
|
||||
query_start_loc = torch.tensor([0, 1, 2], dtype=torch.int32, device=device)
|
||||
|
||||
post_update(
|
||||
idx_mapping,
|
||||
num_computed,
|
||||
last_sampled,
|
||||
None, # output_bin_counts: a second product of the same idx load
|
||||
sampled_tokens,
|
||||
num_sampled,
|
||||
num_rejected,
|
||||
query_start_loc,
|
||||
all_token_ids,
|
||||
total_len,
|
||||
)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert int(all_token_ids[0, 50]) == 111
|
||||
assert int(all_token_ids[ROW, 100]) == 222
|
||||
# Each mapped row holds exactly its own token; unmapped rows stay zero.
|
||||
assert int(all_token_ids[0].sum()) == 111
|
||||
assert int(all_token_ids[ROW].sum()) == 222
|
||||
assert int(all_token_ids[1].sum()) == 0
|
||||
assert int(last_sampled[0, 0]) == 111
|
||||
assert int(last_sampled[ROW, 0]) == 222
|
||||
assert int(total_len[0]) == 51
|
||||
assert int(total_len[ROW]) == 101
|
||||
assert int(num_computed[0]) == 1
|
||||
assert int(num_computed[ROW]) == 1
|
||||
|
||||
|
||||
def test_rope_positions_high_row():
|
||||
"""M-RoPE prepare_positions must read staged rows past the int32 limit.
|
||||
|
||||
Threshold is 3x lower than the other tests (stride0 = num_dims * 1M), so
|
||||
this is the variant that trips at default max_num_seqs on 1M context.
|
||||
"""
|
||||
device = torch.device("cuda:0")
|
||||
max_num_reqs = NUM_ROWS // NUM_DIMS
|
||||
base = torch.arange(PREFILL_LEN, dtype=torch.int32, device=device)
|
||||
# (num_dims * max_num_reqs, max_model_len), logically [req][dim][pos].
|
||||
prefill_positions = torch.zeros(NUM_ROWS, STRIDE, dtype=torch.int32, device=device)
|
||||
# Distinct per-(dim, request) patterns so mixed-up rows are detectable.
|
||||
for j in range(NUM_DIMS):
|
||||
prefill_positions[j, :PREFILL_LEN] = 1_000 * (j + 1) + base
|
||||
target_row = NUM_DIMS * ROPE_ROW + j
|
||||
prefill_positions[target_row, :PREFILL_LEN] = 7_000 * (j + 1) + base
|
||||
|
||||
# Skeletal RopeState: the real __init__ pins num_dims * max_num_reqs host
|
||||
# memory, which the stride arithmetic does not depend on.
|
||||
rope = object.__new__(RopeState)
|
||||
rope.num_dims = NUM_DIMS
|
||||
rope.max_num_reqs = max_num_reqs
|
||||
rope.max_model_len = STRIDE
|
||||
rope.prefill_positions = SimpleNamespace(gpu=prefill_positions)
|
||||
rope.positions = torch.zeros(
|
||||
(NUM_DIMS, 2 * PREFILL_LEN + 1), dtype=torch.int64, device=device
|
||||
)
|
||||
rope.prefill_delta = SimpleNamespace(
|
||||
gpu=torch.zeros(max_num_reqs, dtype=torch.int32, device=device)
|
||||
)
|
||||
|
||||
idx_mapping = torch.tensor([0, ROPE_ROW], dtype=torch.int64, device=device)
|
||||
query_start_loc = torch.tensor(
|
||||
[0, PREFILL_LEN, 2 * PREFILL_LEN], dtype=torch.int32, device=device
|
||||
)
|
||||
prefill_len = torch.zeros(max_num_reqs, dtype=torch.int32, device=device)
|
||||
prefill_len[[0, ROPE_ROW]] = PREFILL_LEN
|
||||
num_computed = torch.zeros(max_num_reqs, dtype=torch.int32, device=device)
|
||||
|
||||
rope.prepare_positions(idx_mapping, query_start_loc, prefill_len, num_computed)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expect_control = torch.stack([1_000 * (j + 1) + base for j in range(NUM_DIMS)]).to(
|
||||
torch.int64
|
||||
)
|
||||
expect_target = torch.stack([7_000 * (j + 1) + base for j in range(NUM_DIMS)]).to(
|
||||
torch.int64
|
||||
)
|
||||
assert torch.equal(rope.positions[:, :PREFILL_LEN], expect_control)
|
||||
assert torch.equal(rope.positions[:, PREFILL_LEN : 2 * PREFILL_LEN], expect_target)
|
||||
# Padding column stays zero.
|
||||
assert bool((rope.positions[:, 2 * PREFILL_LEN :] == 0).all())
|
||||
@@ -1,963 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Dual batch overlap (DBO) in the V2 model runner.
|
||||
|
||||
The V2 runner slices the batch *before* building attention metadata, where V1
|
||||
builds metadata for the whole batch and slices it afterwards. Both must describe
|
||||
the same microbatches, so the main test here pins V2's slicing against V1's
|
||||
`split_attn_metadata`. The rest covers the decision to microbatch and the
|
||||
threaded execution of the microbatches.
|
||||
"""
|
||||
|
||||
import threading
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
|
||||
from vllm.config import (
|
||||
CompilationConfig,
|
||||
CUDAGraphMode,
|
||||
ModelConfig,
|
||||
ParallelConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.forward_context import create_forward_context
|
||||
from vllm.v1.attention.backends.utils import get_dcp_local_seq_lens
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.worker import gpu_ubatch_wrapper as legacy_gpu_ubatch_wrapper
|
||||
from vllm.v1.worker.gpu import cp_utils as gpu_cp_utils
|
||||
from vllm.v1.worker.gpu import cudagraph_utils, dp_utils
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import (
|
||||
BatchExecutionDescriptor,
|
||||
CudaGraphManager,
|
||||
)
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
|
||||
from vllm.v1.worker.gpu.model_states.interface import ModelState
|
||||
from vllm.v1.worker.gpu.ubatch_utils import (
|
||||
UBatchRunner,
|
||||
UBatchState,
|
||||
_slice_input_batch,
|
||||
create_ubatch_slices,
|
||||
slice_model_inputs,
|
||||
)
|
||||
from vllm.v1.worker.ubatch_utils import (
|
||||
UBatchSlice,
|
||||
maybe_create_ubatch_slices,
|
||||
split_attn_metadata,
|
||||
)
|
||||
from vllm.v1.worker.ubatching import dbo_current_ubatch_id, dbo_yield
|
||||
|
||||
MAX_NUM_REQS = 32
|
||||
MAX_NUM_TOKENS = 128
|
||||
|
||||
|
||||
def _make_buffers() -> InputBuffers:
|
||||
return InputBuffers(
|
||||
max_num_reqs=MAX_NUM_REQS,
|
||||
max_num_tokens=MAX_NUM_TOKENS,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
|
||||
|
||||
def _make_ubatch_buffers(num_ubatches: int = 2) -> list[tuple[torch.Tensor, ...]]:
|
||||
"""The per-microbatch (query_start_loc, seq_lens) buffers UBatchRunner owns."""
|
||||
return [
|
||||
(
|
||||
torch.zeros(MAX_NUM_REQS + 1, dtype=torch.int32),
|
||||
torch.zeros(MAX_NUM_REQS, dtype=torch.int32),
|
||||
)
|
||||
for _ in range(num_ubatches)
|
||||
]
|
||||
|
||||
|
||||
def _make_input_batch(
|
||||
query_lens: list[int],
|
||||
seq_lens: list[int],
|
||||
buffers: InputBuffers,
|
||||
num_reqs_padded: int | None = None,
|
||||
num_tokens_padded: int | None = None,
|
||||
) -> InputBatch:
|
||||
"""Build an InputBatch shaped like the one `prepare_inputs` produces."""
|
||||
num_reqs = len(query_lens)
|
||||
num_tokens = int(sum(query_lens))
|
||||
num_reqs_padded = num_reqs_padded or num_reqs
|
||||
num_tokens_padded = num_tokens_padded or num_tokens
|
||||
|
||||
# make_dummy writes the shared buffers, so fill them afterwards.
|
||||
base = InputBatch.make_dummy(num_reqs, num_tokens, buffers)
|
||||
|
||||
query_start_loc_np = np.zeros(num_reqs_padded + 1, dtype=np.int32)
|
||||
np.cumsum(query_lens, out=query_start_loc_np[1 : num_reqs + 1])
|
||||
# Padded entries repeat the token count, as `prepare_inputs` does.
|
||||
query_start_loc_np[num_reqs + 1 :] = num_tokens
|
||||
buffers.query_start_loc[: num_reqs_padded + 1] = torch.from_numpy(
|
||||
query_start_loc_np
|
||||
)
|
||||
|
||||
buffers.seq_lens[:num_reqs] = torch.tensor(seq_lens, dtype=torch.int32)
|
||||
buffers.seq_lens[num_reqs:num_reqs_padded] = 0
|
||||
|
||||
seq_lens_upper_bound = np.zeros(num_reqs_padded, dtype=np.int32)
|
||||
seq_lens_upper_bound[:num_reqs] = seq_lens
|
||||
|
||||
return replace(
|
||||
base,
|
||||
req_ids=[f"req_{i}" for i in range(num_reqs)],
|
||||
num_reqs=num_reqs,
|
||||
num_reqs_after_padding=num_reqs_padded,
|
||||
idx_mapping=torch.arange(num_reqs, dtype=torch.int32),
|
||||
idx_mapping_np=np.arange(num_reqs, dtype=np.int32),
|
||||
num_scheduled_tokens=np.array(query_lens, dtype=np.int32),
|
||||
num_tokens=num_tokens,
|
||||
num_tokens_after_padding=num_tokens_padded,
|
||||
query_start_loc=buffers.query_start_loc[: num_reqs_padded + 1],
|
||||
query_start_loc_np=query_start_loc_np,
|
||||
seq_lens=buffers.seq_lens[:num_reqs_padded],
|
||||
seq_lens_cpu_upper_bound=torch.from_numpy(seq_lens_upper_bound),
|
||||
num_computed_tokens_np=np.array(seq_lens, dtype=np.int32)
|
||||
- np.array(query_lens, dtype=np.int32),
|
||||
prefill_len_np=np.zeros(num_reqs, dtype=np.int32),
|
||||
num_computed_prefill_tokens_np=np.zeros(num_reqs, dtype=np.int32),
|
||||
is_prefilling_np=np.zeros(num_reqs, dtype=np.bool_),
|
||||
input_ids=buffers.input_ids[:num_tokens_padded],
|
||||
positions=buffers.positions[:num_tokens_padded],
|
||||
is_padding=buffers.is_padding[:num_tokens_padded],
|
||||
)
|
||||
|
||||
|
||||
# (query_lens, seq_lens): uniform decode, a boundary that lands inside a
|
||||
# request, and a boundary that lands exactly on a request start.
|
||||
BATCHES = {
|
||||
"uniform_decode": ([1] * 8, [128 + 4 * i for i in range(8)]),
|
||||
"split_request": ([1, 1, 10, 1, 1], [64, 96, 512, 32, 48]),
|
||||
"aligned_prefills": ([6, 2, 4, 4], [6, 130, 260, 4]),
|
||||
"split_first_and_last": ([3, 9, 3], [70, 300, 41]),
|
||||
# A long prefill trailing a decode: it straddles the boundary and is also
|
||||
# the last request, so the second microbatch holds nothing else.
|
||||
"trailing_prefill_spans_boundary": ([2, 20], [64, 300]),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch_name", list(BATCHES))
|
||||
def test_slicing_matches_v1_split_attn_metadata(batch_name: str):
|
||||
"""V2's pre-sliced inputs describe the same microbatches as V1's."""
|
||||
query_lens, seq_lens = BATCHES[batch_name]
|
||||
num_scheduled_tokens = np.array(query_lens, dtype=np.int32)
|
||||
num_tokens = int(num_scheduled_tokens.sum())
|
||||
|
||||
ubatch_slices, _ = maybe_create_ubatch_slices(
|
||||
True, num_scheduled_tokens, num_tokens, len(query_lens), num_ubatches=2
|
||||
)
|
||||
assert ubatch_slices is not None
|
||||
|
||||
v1_metadata = create_common_attn_metadata(
|
||||
BatchSpec(seq_lens=seq_lens, query_lens=query_lens),
|
||||
block_size=16,
|
||||
device=torch.device("cpu"),
|
||||
)
|
||||
v1_ubatches = split_attn_metadata(ubatch_slices, v1_metadata)
|
||||
|
||||
buffers = _make_buffers()
|
||||
ubatch_buffers = _make_ubatch_buffers()
|
||||
input_batch = _make_input_batch(query_lens, seq_lens, buffers)
|
||||
|
||||
for i, (ubatch_slice, v1_ubatch) in enumerate(zip(ubatch_slices, v1_ubatches)):
|
||||
v2_ubatch = _slice_input_batch(input_batch, ubatch_slice, *ubatch_buffers[i])
|
||||
|
||||
assert v2_ubatch.num_reqs == v1_ubatch.num_reqs
|
||||
assert v2_ubatch.num_tokens == v1_ubatch.num_actual_tokens
|
||||
assert int(v2_ubatch.num_scheduled_tokens.max()) == v1_ubatch.max_query_len
|
||||
torch.testing.assert_close(v2_ubatch.query_start_loc, v1_ubatch.query_start_loc)
|
||||
torch.testing.assert_close(v2_ubatch.seq_lens, v1_ubatch.seq_lens)
|
||||
torch.testing.assert_close(
|
||||
torch.from_numpy(v2_ubatch.query_start_loc_np),
|
||||
v1_ubatch.query_start_loc_cpu,
|
||||
)
|
||||
# `prepare_attn` derives max_seq_len from the upper bound. Compare the
|
||||
# bound itself rather than V1's max_seq_len: V1 floors it with the full
|
||||
# batch's max_seq_len to keep the value CUDA-graph capture installed,
|
||||
# which V2 gets from `prepare_attn(for_capture=True)` instead.
|
||||
torch.testing.assert_close(
|
||||
v2_ubatch.seq_lens_cpu_upper_bound, v1_ubatch.seq_lens_cpu_upper_bound
|
||||
)
|
||||
|
||||
|
||||
def test_microbatches_do_not_share_buffers():
|
||||
"""Both microbatches are live at once, so their buffers must be distinct."""
|
||||
query_lens, seq_lens = BATCHES["split_request"]
|
||||
num_scheduled_tokens = np.array(query_lens, dtype=np.int32)
|
||||
num_tokens = int(num_scheduled_tokens.sum())
|
||||
|
||||
ubatch_slices, _ = maybe_create_ubatch_slices(
|
||||
True, num_scheduled_tokens, num_tokens, len(query_lens), num_ubatches=2
|
||||
)
|
||||
assert ubatch_slices is not None
|
||||
|
||||
buffers = _make_buffers()
|
||||
ubatch_buffers = _make_ubatch_buffers()
|
||||
input_batch = _make_input_batch(query_lens, seq_lens, buffers)
|
||||
|
||||
first = _slice_input_batch(input_batch, ubatch_slices[0], *ubatch_buffers[0])
|
||||
first_query_start_loc = first.query_start_loc.clone()
|
||||
first_seq_lens = first.seq_lens.clone()
|
||||
|
||||
# Slicing the second microbatch must not disturb the first.
|
||||
_slice_input_batch(input_batch, ubatch_slices[1], *ubatch_buffers[1])
|
||||
|
||||
torch.testing.assert_close(first.query_start_loc, first_query_start_loc)
|
||||
torch.testing.assert_close(first.seq_lens, first_seq_lens)
|
||||
|
||||
|
||||
def test_trailing_microbatch_absorbs_cudagraph_padding():
|
||||
"""The padded microbatch keeps padded rows empty and query_start_loc flat."""
|
||||
query_lens, seq_lens = [1] * 6, [64] * 6
|
||||
num_tokens_padded = 8
|
||||
|
||||
buffers = _make_buffers()
|
||||
input_batch = _make_input_batch(
|
||||
query_lens,
|
||||
seq_lens,
|
||||
buffers,
|
||||
num_reqs_padded=num_tokens_padded,
|
||||
num_tokens_padded=num_tokens_padded,
|
||||
)
|
||||
ubatch_slices_padded = create_ubatch_slices(input_batch, num_ubatches=2)
|
||||
|
||||
last = _slice_input_batch(
|
||||
input_batch, ubatch_slices_padded[-1], *_make_ubatch_buffers()[1]
|
||||
)
|
||||
|
||||
# Two real decodes plus two padded rows.
|
||||
assert last.num_reqs == 2
|
||||
assert last.num_tokens == 2
|
||||
assert last.num_reqs_after_padding == 4
|
||||
assert last.num_tokens_after_padding == 4
|
||||
torch.testing.assert_close(
|
||||
last.query_start_loc, torch.tensor([0, 1, 2, 2, 2], dtype=torch.int32)
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
last.seq_lens, torch.tensor([64, 64, 0, 0], dtype=torch.int32)
|
||||
)
|
||||
|
||||
|
||||
DECODE_THRESHOLD = 32
|
||||
PREFILL_THRESHOLD = 128
|
||||
DECODE_QUERY_LEN = 1
|
||||
|
||||
|
||||
def test_dummy_batch_can_be_microbatched():
|
||||
"""A DP rank with no work still has to split, so its dummy batch must slice.
|
||||
|
||||
Microbatching is all-or-nothing across the group, so a rank whose step is a
|
||||
dummy batch runs it microbatched like everyone else.
|
||||
"""
|
||||
num_reqs, num_tokens = 1, 32
|
||||
buffers = _make_buffers()
|
||||
input_batch = InputBatch.make_dummy(num_reqs, num_tokens, buffers)
|
||||
|
||||
ubatch_slices_padded = create_ubatch_slices(input_batch, num_ubatches=2)
|
||||
|
||||
ubatch_buffers = _make_ubatch_buffers()
|
||||
ubatches = [
|
||||
_slice_input_batch(input_batch, ubatch_slice, *ubatch_buffers[i])
|
||||
for i, ubatch_slice in enumerate(ubatch_slices_padded)
|
||||
]
|
||||
|
||||
assert [u.num_tokens for u in ubatches] == [16, 16]
|
||||
# The one dummy request spans both microbatches, 16 of its tokens in each.
|
||||
assert all(u.num_reqs == 1 for u in ubatches)
|
||||
for ubatch in ubatches:
|
||||
torch.testing.assert_close(
|
||||
ubatch.query_start_loc, torch.tensor([0, 16], dtype=torch.int32)
|
||||
)
|
||||
|
||||
|
||||
def _sync_dp(
|
||||
num_tokens_per_rank: list[int],
|
||||
uniform_token_count_per_rank: list[int] | None = None,
|
||||
allow_ubatching: bool = True,
|
||||
cudagraph_manager: Any = None,
|
||||
) -> tuple[BatchExecutionDescriptor, dp_utils.DPSyncState | None]:
|
||||
"""Run the DP handshake with the all-reduce stubbed out.
|
||||
|
||||
The microbatching decision lives inside `sync_cudagraph_and_dp_padding`, so
|
||||
the cases below stand in for the collective rather than for the decision,
|
||||
and need no process group. Every rank asks for eager, which keeps the
|
||||
non-microbatched path off the cudagraph manager. This rank is rank 0.
|
||||
"""
|
||||
dp_size = len(num_tokens_per_rank)
|
||||
uniform_token_counts = uniform_token_count_per_rank or [0] * dp_size
|
||||
reduced = torch.zeros(6, dp_size, dtype=torch.int32)
|
||||
reduced[0] = torch.tensor(num_tokens_per_rank, dtype=torch.int32)
|
||||
reduced[1] = CUDAGraphMode.NONE.value
|
||||
reduced[2] = torch.tensor(uniform_token_counts, dtype=torch.int32)
|
||||
reduced[3] = -1 # max_query_len, -1 means None
|
||||
reduced[4] = int(allow_ubatching)
|
||||
reduced[5] = 8 # num_reqs
|
||||
|
||||
dp_group = SimpleNamespace(cpu_all_reduce_=lambda t: t.copy_(reduced))
|
||||
with patch.object(dp_utils, "get_dp_group", lambda: dp_group):
|
||||
return dp_utils.sync_cudagraph_and_dp_padding(
|
||||
cudagraph_manager=cudagraph_manager,
|
||||
desired_batch_desc=BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.NONE,
|
||||
num_tokens=num_tokens_per_rank[0],
|
||||
num_reqs=8,
|
||||
),
|
||||
num_tokens=num_tokens_per_rank[0],
|
||||
num_reqs=8,
|
||||
uniform_token_count=uniform_token_counts[0] or None,
|
||||
dp_size=dp_size,
|
||||
dp_rank=0,
|
||||
parallel_config=ParallelConfig(
|
||||
enable_dbo=True,
|
||||
dbo_decode_token_threshold=DECODE_THRESHOLD,
|
||||
dbo_prefill_token_threshold=PREFILL_THRESHOLD,
|
||||
),
|
||||
allow_ubatching=allow_ubatching,
|
||||
uniform_decode=uniform_token_counts[0] == DECODE_QUERY_LEN,
|
||||
)
|
||||
|
||||
|
||||
def test_every_dp_rank_must_agree_to_microbatch():
|
||||
"""One rank below the threshold is enough to keep the group on one batch.
|
||||
|
||||
The thresholds are not communicated -- they are checked against the token
|
||||
counts the all-reduce already carries -- so this also pins that the whole
|
||||
vector is consulted, not just this rank's own entry.
|
||||
"""
|
||||
assert _sync_dp([256, 256])[0].num_ubatches == 2
|
||||
assert _sync_dp([256, 100])[0].num_ubatches == 1
|
||||
assert _sync_dp([100, 256])[0].num_ubatches == 1
|
||||
|
||||
|
||||
def test_decode_threshold_only_applies_when_every_rank_is_a_uniform_decode():
|
||||
"""Otherwise the group is held to the prefill threshold."""
|
||||
# 64 tokens clears the decode threshold but not the prefill one, so it only
|
||||
# microbatches when both ranks are uniform decodes.
|
||||
assert _sync_dp([64, 64], uniform_token_count_per_rank=[1, 1])[0].num_ubatches == 2
|
||||
assert _sync_dp([64, 64], uniform_token_count_per_rank=[1, 0])[0].num_ubatches == 1
|
||||
|
||||
|
||||
def test_microbatching_pads_all_ranks_to_the_largest():
|
||||
"""Ranks must run the same token count so microbatch sizes line up."""
|
||||
desc, dp_sync_state = _sync_dp([200, 256])
|
||||
assert desc.num_tokens == 256
|
||||
assert dp_sync_state is not None
|
||||
assert dp_sync_state.num_tokens_across_dp.tolist() == [256, 256]
|
||||
|
||||
|
||||
def test_microbatching_survives_a_rank_that_cannot_fill_it():
|
||||
"""A rank whose real tokens all land in the first microbatch still splits.
|
||||
|
||||
Rank 0 has 128 real tokens but the split point is at 512 // 2 = 256, so its
|
||||
second microbatch is pure padding. That microbatch does no work, which is
|
||||
fine -- it still has to run so the expert all-to-all stays collective.
|
||||
"""
|
||||
desc, _ = _sync_dp([128, 512])
|
||||
assert desc.num_tokens == 512
|
||||
assert desc.num_ubatches == 2
|
||||
|
||||
|
||||
def test_all_padding_microbatch_has_no_work_to_do():
|
||||
"""The microbatch past the last real token is well-formed and empty.
|
||||
|
||||
It carries the last request with none of its query tokens, so attention and
|
||||
sampling see nothing to do while the microbatch still runs.
|
||||
"""
|
||||
query_lens, seq_lens = [1] * 6, [64] * 6
|
||||
num_tokens_padded = 16 # split at 8, past all 6 real tokens
|
||||
|
||||
buffers = _make_buffers()
|
||||
input_batch = _make_input_batch(
|
||||
query_lens, seq_lens, buffers, num_tokens_padded=num_tokens_padded
|
||||
)
|
||||
ubatch_slices_padded = create_ubatch_slices(input_batch, num_ubatches=2)
|
||||
ubatch_buffers = _make_ubatch_buffers()
|
||||
|
||||
first = _slice_input_batch(input_batch, ubatch_slices_padded[0], *ubatch_buffers[0])
|
||||
last = _slice_input_batch(input_batch, ubatch_slices_padded[1], *ubatch_buffers[1])
|
||||
|
||||
# The first microbatch keeps every real request; the second gets none.
|
||||
assert first.num_reqs == 6
|
||||
assert first.num_tokens == 6
|
||||
assert last.num_tokens == 0
|
||||
assert last.num_reqs == 1
|
||||
assert last.num_reqs_after_padding == 1
|
||||
assert last.num_tokens_after_padding == 8
|
||||
|
||||
# Zero query tokens for the one request it holds, so no attention work.
|
||||
torch.testing.assert_close(
|
||||
last.query_start_loc, torch.tensor([0, 0], dtype=torch.int32)
|
||||
)
|
||||
assert last.num_scheduled_tokens.tolist() == [0]
|
||||
# ...and its sequence still ends where its tokens do: they all live in the
|
||||
# first microbatch, which computes them before this one runs.
|
||||
torch.testing.assert_close(last.seq_lens, torch.tensor([64], dtype=torch.int32))
|
||||
torch.testing.assert_close(
|
||||
last.seq_lens_cpu_upper_bound, torch.tensor([64], dtype=torch.int32)
|
||||
)
|
||||
|
||||
|
||||
def test_microbatching_off_when_a_rank_does_not_allow_it():
|
||||
assert _sync_dp([256, 256], allow_ubatching=False)[0].num_ubatches == 1
|
||||
|
||||
|
||||
def test_slice_model_inputs_handles_mrope_positions():
|
||||
model_inputs = {
|
||||
"input_ids": torch.arange(8),
|
||||
# M-RoPE positions carry a leading section dim.
|
||||
"positions": torch.arange(24).view(3, 8),
|
||||
"inputs_embeds": None,
|
||||
"intermediate_tensors": None,
|
||||
}
|
||||
sliced = slice_model_inputs(model_inputs, slice(4, 8))
|
||||
|
||||
torch.testing.assert_close(sliced["input_ids"], torch.arange(4, 8))
|
||||
torch.testing.assert_close(sliced["positions"], torch.arange(24).view(3, 8)[:, 4:8])
|
||||
assert sliced["inputs_embeds"] is None
|
||||
assert sliced["intermediate_tensors"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("cudagraph_runtime_mode", "execution_method"),
|
||||
[
|
||||
(CUDAGraphMode.FULL, "_capture_ubatches"),
|
||||
(CUDAGraphMode.NONE, "_run_ubatches"),
|
||||
],
|
||||
)
|
||||
def test_legacy_ubatch_contexts_slice_padding_mask(
|
||||
cudagraph_runtime_mode: CUDAGraphMode, execution_method: str
|
||||
):
|
||||
"""Replacement contexts preserve each microbatch's padding rows."""
|
||||
ubatch_slices = [
|
||||
UBatchSlice(slice(0, 2), slice(0, 3)),
|
||||
UBatchSlice(slice(2, 4), slice(3, 6)),
|
||||
]
|
||||
is_padding = torch.tensor([False, True, False, True, False, True])
|
||||
forward_context = SimpleNamespace(
|
||||
batch_descriptor=object(),
|
||||
ubatch_slices=ubatch_slices,
|
||||
cudagraph_runtime_mode=cudagraph_runtime_mode,
|
||||
attn_metadata=[{}, {}],
|
||||
slot_mapping={},
|
||||
dp_metadata=object(),
|
||||
is_padding=is_padding,
|
||||
)
|
||||
|
||||
wrapper = object.__new__(legacy_gpu_ubatch_wrapper.UBatchWrapper)
|
||||
wrapper.vllm_config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(data_parallel_size=2)
|
||||
)
|
||||
wrapper.comm_stream = object()
|
||||
wrapper.ready_barrier = object()
|
||||
wrapper.cudagraphs = {}
|
||||
wrapper.sm_control = nullcontext()
|
||||
wrapper.runnable = object()
|
||||
|
||||
def make_contexts(*, forward_contexts, **kwargs):
|
||||
return [
|
||||
SimpleNamespace(id=i, forward_context=context)
|
||||
for i, context in enumerate(forward_contexts)
|
||||
]
|
||||
|
||||
def create_context(attn_metadata, vllm_config, **kwargs):
|
||||
return SimpleNamespace(attn_metadata=attn_metadata, **kwargs)
|
||||
|
||||
model_inputs = {
|
||||
"input_ids": torch.arange(6),
|
||||
"positions": torch.arange(6),
|
||||
"inputs_embeds": None,
|
||||
"intermediate_tensors": None,
|
||||
}
|
||||
expected = object()
|
||||
with (
|
||||
patch.object(
|
||||
legacy_gpu_ubatch_wrapper,
|
||||
"get_forward_context",
|
||||
return_value=forward_context,
|
||||
),
|
||||
patch.object(
|
||||
legacy_gpu_ubatch_wrapper.torch.cuda,
|
||||
"current_stream",
|
||||
return_value=object(),
|
||||
),
|
||||
patch.object(
|
||||
legacy_gpu_ubatch_wrapper.DPMetadata, "make", return_value=object()
|
||||
),
|
||||
patch.object(
|
||||
legacy_gpu_ubatch_wrapper,
|
||||
"create_forward_context",
|
||||
side_effect=create_context,
|
||||
),
|
||||
patch.object(
|
||||
legacy_gpu_ubatch_wrapper,
|
||||
"make_ubatch_contexts",
|
||||
side_effect=make_contexts,
|
||||
),
|
||||
patch.object(wrapper, execution_method, return_value=expected) as execute,
|
||||
):
|
||||
result = wrapper(**model_inputs)
|
||||
|
||||
assert result is expected
|
||||
contexts = [
|
||||
metadata.context.forward_context for metadata in execute.call_args.args[0]
|
||||
]
|
||||
torch.testing.assert_close(contexts[0].is_padding, is_padding[:3])
|
||||
torch.testing.assert_close(contexts[1].is_padding, is_padding[3:])
|
||||
|
||||
|
||||
def _make_dbo_config() -> VllmConfig:
|
||||
return VllmConfig(
|
||||
model_config=ModelConfig(model="facebook/opt-125m", dtype="float16", seed=0),
|
||||
parallel_config=ParallelConfig(
|
||||
enable_dbo=True, all2all_backend="deepep_low_latency"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _make_model_inputs(num_tokens: int, device: torch.device) -> dict[str, Any]:
|
||||
return {
|
||||
"input_ids": torch.arange(num_tokens, device=device),
|
||||
"positions": torch.arange(num_tokens, device=device),
|
||||
"inputs_embeds": None,
|
||||
"intermediate_tensors": None,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_comm_sm_reservation(monkeypatch):
|
||||
"""CI runs on MIG slices with fewer SMs than the default comm reservation."""
|
||||
monkeypatch.setenv("VLLM_DBO_COMM_SMS", "0")
|
||||
|
||||
|
||||
def _make_execution_runner(vllm_config: VllmConfig) -> UBatchRunner:
|
||||
"""A runner for the execution tests below, which never call `prepare()`.
|
||||
|
||||
The attention-side dependencies are only read while building per-microbatch
|
||||
metadata, so they are left out here.
|
||||
"""
|
||||
return UBatchRunner(
|
||||
vllm_config,
|
||||
torch.device("cuda:0"),
|
||||
model_state=cast(ModelState, None),
|
||||
attn_groups=[],
|
||||
kv_cache_config=cast(KVCacheConfig, None),
|
||||
max_num_reqs=MAX_NUM_REQS,
|
||||
)
|
||||
|
||||
|
||||
def _make_ubatch_state(
|
||||
vllm_config: VllmConfig, ubatch_slices: list[UBatchSlice]
|
||||
) -> UBatchState:
|
||||
return UBatchState(
|
||||
slices=ubatch_slices,
|
||||
forward_contexts=[
|
||||
create_forward_context(None, vllm_config) for _ in ubatch_slices
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_thresholds_below_the_microbatch_count_are_rejected():
|
||||
"""A batch with fewer tokens than microbatches cannot be split at all.
|
||||
|
||||
Nothing downstream copes with an unsplittable batch, so the thresholds are
|
||||
what keep one out: a one-token decode split two ways leaves an empty
|
||||
microbatch.
|
||||
"""
|
||||
with pytest.raises(ValueError, match="number of microbatches"):
|
||||
ParallelConfig(enable_dbo=True, dbo_decode_token_threshold=1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="DBO needs a GPU")
|
||||
def test_runner_allocates_one_buffer_pair_per_microbatch():
|
||||
"""All microbatches are live at once, so none may share rebase buffers."""
|
||||
vllm_config = _make_dbo_config()
|
||||
runner = _make_execution_runner(vllm_config)
|
||||
|
||||
for buffers in (runner.ubatch_query_start_loc, runner.ubatch_seq_lens):
|
||||
assert len(buffers) == runner.num_ubatches
|
||||
storages = {b.untyped_storage().data_ptr() for b in buffers}
|
||||
assert len(storages) == runner.num_ubatches
|
||||
|
||||
|
||||
class _YieldingModel(torch.nn.Module):
|
||||
"""Toy model that hands off to the other microbatch mid-forward."""
|
||||
|
||||
def __init__(self, trace: list[tuple[str, int]]):
|
||||
super().__init__()
|
||||
self.trace = trace
|
||||
|
||||
def forward(self, input_ids, positions, intermediate_tensors=None, **kwargs):
|
||||
self.trace.append(("enter", dbo_current_ubatch_id()))
|
||||
out = input_ids.float().unsqueeze(-1) * 2 + positions.float().unsqueeze(-1)
|
||||
# Stands in for the expert all-to-all handoff point.
|
||||
dbo_yield()
|
||||
self.trace.append(("exit", dbo_current_ubatch_id()))
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="DBO needs a GPU")
|
||||
def test_ubatch_runner_overlaps_and_matches_single_batch():
|
||||
"""Microbatches interleave at the yield point and produce the same output."""
|
||||
vllm_config = _make_dbo_config()
|
||||
device = torch.device("cuda:0")
|
||||
runner = _make_execution_runner(vllm_config)
|
||||
|
||||
model_inputs = _make_model_inputs(16, device)
|
||||
ubatch_state = _make_ubatch_state(
|
||||
vllm_config,
|
||||
[
|
||||
UBatchSlice(slice(0, 4), slice(0, 8)),
|
||||
UBatchSlice(slice(4, 8), slice(8, 16)),
|
||||
],
|
||||
)
|
||||
|
||||
trace: list[tuple[str, int]] = []
|
||||
model = _YieldingModel(trace)
|
||||
output = runner.run(model, model_inputs, ubatch_state)
|
||||
|
||||
expected = model_inputs["input_ids"].float().unsqueeze(-1) * 2 + model_inputs[
|
||||
"positions"
|
||||
].float().unsqueeze(-1)
|
||||
torch.testing.assert_close(output, expected)
|
||||
|
||||
# Both microbatches reach the handoff before either finishes.
|
||||
assert trace == [("enter", 0), ("enter", 1), ("exit", 0), ("exit", 1)]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="DBO needs a GPU")
|
||||
def test_ubatch_runner_names_the_microbatch_that_failed():
|
||||
"""A failing microbatch surfaces as a named error, not a downstream KeyError.
|
||||
|
||||
The model here never yields, so the microbatches run back to back and no
|
||||
handoff is left outstanding when one of them dies. A microbatch that fails
|
||||
*while its sibling is parked at a yield* hangs the step instead -- the
|
||||
shared handoff protocol in `ubatching.py` has no way to unwind a parked
|
||||
microbatch, and the V1 runner has the same gap. Fixing that means changing
|
||||
`ubatching.py`, which is out of scope for the V2 runner.
|
||||
"""
|
||||
vllm_config = _make_dbo_config()
|
||||
device = torch.device("cuda:0")
|
||||
runner = _make_execution_runner(vllm_config)
|
||||
|
||||
class _FailingModel(torch.nn.Module):
|
||||
def forward(self, input_ids, positions, **kwargs):
|
||||
if dbo_current_ubatch_id() == 0:
|
||||
raise ValueError("boom")
|
||||
return input_ids.float().unsqueeze(-1)
|
||||
|
||||
model_inputs = _make_model_inputs(8, device)
|
||||
ubatch_state = _make_ubatch_state(
|
||||
vllm_config,
|
||||
[
|
||||
UBatchSlice(slice(0, 2), slice(0, 4)),
|
||||
UBatchSlice(slice(2, 4), slice(4, 8)),
|
||||
],
|
||||
)
|
||||
|
||||
result: dict[str, BaseException] = {}
|
||||
|
||||
def _call():
|
||||
try:
|
||||
runner.run(_FailingModel(), model_inputs, ubatch_state)
|
||||
except BaseException as e: # noqa: BLE001
|
||||
result["error"] = e
|
||||
|
||||
# Run behind a watchdog: `UBatchRunner.run` joins without a timeout, so a
|
||||
# regression here would wedge the suite rather than fail it.
|
||||
caller = threading.Thread(target=_call, daemon=True)
|
||||
caller.start()
|
||||
caller.join(timeout=60.0)
|
||||
assert not caller.is_alive(), "UBatchRunner.run hung on a failing microbatch"
|
||||
|
||||
assert isinstance(result["error"], RuntimeError)
|
||||
assert "Microbatch 0" in str(result["error"])
|
||||
assert isinstance(result["error"].__cause__, ValueError)
|
||||
|
||||
|
||||
# DCP x DBO: each microbatch recomputes DCP-local seq_lens from its own
|
||||
# truncated seq_lens into its own persistent buffer (the parent's values for
|
||||
# a straddling request are wrong for the leading microbatch).
|
||||
|
||||
DCP_SIZE = 2
|
||||
CP_INTERLEAVE = 1
|
||||
|
||||
|
||||
def _make_cuda_input_batch(
|
||||
query_lens: list[int], seq_lens: list[int]
|
||||
) -> tuple[InputBatch, InputBuffers]:
|
||||
buffers = InputBuffers(
|
||||
max_num_reqs=MAX_NUM_REQS,
|
||||
max_num_tokens=MAX_NUM_TOKENS,
|
||||
device=torch.device("cuda:0"),
|
||||
)
|
||||
return _make_input_batch(query_lens, seq_lens, buffers), buffers
|
||||
|
||||
|
||||
def _make_dcp_ubatch_buffers(
|
||||
num_ubatches: int = 2,
|
||||
) -> list[tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
|
||||
"""Per-microbatch (query_start_loc, seq_lens, dcp_local_seq_lens)."""
|
||||
return [
|
||||
(
|
||||
torch.zeros(MAX_NUM_REQS + 1, dtype=torch.int32, device="cuda:0"),
|
||||
torch.zeros(MAX_NUM_REQS, dtype=torch.int32, device="cuda:0"),
|
||||
torch.zeros(MAX_NUM_REQS, dtype=torch.int32, device="cuda:0"),
|
||||
)
|
||||
for _ in range(num_ubatches)
|
||||
]
|
||||
|
||||
|
||||
def _slice_with_dcp(
|
||||
input_batch: InputBatch, dcp_rank: int, num_ubatches: int = 2
|
||||
) -> tuple[list[InputBatch], list[torch.Tensor]]:
|
||||
dcp_buffers = [
|
||||
torch.zeros(MAX_NUM_REQS, dtype=torch.int32, device="cuda:0")
|
||||
for _ in range(num_ubatches)
|
||||
]
|
||||
ubatch_buffers = _make_dcp_ubatch_buffers(num_ubatches)
|
||||
ubatches = [
|
||||
_slice_input_batch(
|
||||
input_batch,
|
||||
ubatch_slice,
|
||||
ubatch_buffers[i][0],
|
||||
ubatch_buffers[i][1],
|
||||
dcp_buffers[i],
|
||||
dcp_size=DCP_SIZE,
|
||||
dcp_rank=dcp_rank,
|
||||
cp_interleave=CP_INTERLEAVE,
|
||||
)
|
||||
for i, ubatch_slice in enumerate(
|
||||
create_ubatch_slices(input_batch, num_ubatches)
|
||||
)
|
||||
]
|
||||
return ubatches, dcp_buffers
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="triton kernel needs CUDA")
|
||||
@pytest.mark.parametrize("dcp_rank", [0, 1])
|
||||
def test_microbatches_recompute_dcp_lens_from_truncated_seq_lens(dcp_rank: int):
|
||||
"""A boundary-split request keeps a truncated seq_len on the leading
|
||||
microbatch, whose DCP-local length may differ (in parity) from the full
|
||||
batch's. Microbatches must therefore derive DCP lengths from their own
|
||||
seq_lens, not reuse the parent's row.
|
||||
"""
|
||||
input_batch, buffers = _make_cuda_input_batch(
|
||||
[1, 1, 10, 1, 1], [64, 96, 512, 32, 48]
|
||||
)
|
||||
# execute_model has populated the merged batch's DCP metadata already.
|
||||
input_batch.dcp_local_seq_lens = gpu_cp_utils.prepare_dcp_local_seq_lens(
|
||||
buffers.dcp_local_seq_lens,
|
||||
input_batch.seq_lens,
|
||||
input_batch.num_reqs,
|
||||
DCP_SIZE,
|
||||
dcp_rank,
|
||||
CP_INTERLEAVE,
|
||||
num_reqs_padded=input_batch.num_reqs_after_padding,
|
||||
)
|
||||
parent_lens = input_batch.dcp_local_seq_lens.clone()
|
||||
|
||||
ubatches, _ = _slice_with_dcp(input_batch, dcp_rank)
|
||||
|
||||
for ubatch in ubatches:
|
||||
assert ubatch.dcp_local_seq_lens is not None
|
||||
expected = get_dcp_local_seq_lens(
|
||||
ubatch.seq_lens.cpu(), DCP_SIZE, dcp_rank, CP_INTERLEAVE
|
||||
)
|
||||
assert torch.equal(
|
||||
ubatch.dcp_local_seq_lens[: ubatch.num_reqs].cpu(),
|
||||
expected.to(torch.int32),
|
||||
)
|
||||
|
||||
# The straddling request (512 tokens, 5 of its 10 query tokens truncated)
|
||||
# lands on this rank with a different local length than the full batch
|
||||
# reports (507 vs 512 -> 254 vs 256 for dcp_size=2, interleave=1); copying
|
||||
# the parent's row would ship the stale value.
|
||||
assert ubatches[0].num_reqs == 3
|
||||
assert ubatches[0].seq_lens[2].item() == 507
|
||||
assert ubatches[0].dcp_local_seq_lens[2].item() != parent_lens[2].item()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="triton kernel needs CUDA")
|
||||
def test_each_microbatch_owns_its_dcp_buffer():
|
||||
"""Microbatch DCP lengths live in per-microbatch persistent buffers so
|
||||
CPU-visible shapes stay valid under CUDA graph capture and replay."""
|
||||
input_batch, _ = _make_cuda_input_batch([4, 4, 4, 4], [8, 9, 10, 11])
|
||||
|
||||
ubatches, dcp_buffers = _slice_with_dcp(input_batch, dcp_rank=0)
|
||||
|
||||
for ubatch, dcp_buffer in zip(ubatches, dcp_buffers):
|
||||
assert ubatch.dcp_local_seq_lens is not None
|
||||
assert ubatch.dcp_local_seq_lens.data_ptr() == dcp_buffer.data_ptr()
|
||||
assert dcp_buffers[0].data_ptr() != dcp_buffers[1].data_ptr()
|
||||
|
||||
|
||||
def test_slicing_drops_stale_dcp_metadata_when_dcp_is_off():
|
||||
"""dcp_size == 1 yields None even when the parent carries a value, so a
|
||||
microbatch can never consume DCP metadata this deployment did not
|
||||
enable.
|
||||
"""
|
||||
buffers = _make_buffers()
|
||||
input_batch = _make_input_batch([4, 4, 4, 4], [8, 9, 10, 11], buffers)
|
||||
input_batch.dcp_local_seq_lens = buffers.dcp_local_seq_lens[:4]
|
||||
|
||||
ubatch_buffers = _make_ubatch_buffers()
|
||||
ubatches = [
|
||||
_slice_input_batch(input_batch, ubatch_slice, *ubatch_buffers[i])
|
||||
for i, ubatch_slice in enumerate(create_ubatch_slices(input_batch, 2))
|
||||
]
|
||||
|
||||
assert all(ubatch.dcp_local_seq_lens is None for ubatch in ubatches)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="DBO needs a GPU")
|
||||
def test_capturable_run_replays_as_a_cudagraph():
|
||||
"""Microbatched graph replay reads updated persistent input buffers."""
|
||||
vllm_config = VllmConfig(
|
||||
model_config=ModelConfig(model="facebook/opt-125m", dtype="float16", seed=0),
|
||||
parallel_config=ParallelConfig(
|
||||
enable_dbo=True, all2all_backend="deepep_low_latency"
|
||||
),
|
||||
)
|
||||
device = torch.device("cuda:0")
|
||||
runner = _make_execution_runner(vllm_config)
|
||||
|
||||
num_tokens = 16
|
||||
input_ids = torch.arange(num_tokens, device=device)
|
||||
positions = torch.arange(num_tokens, device=device)
|
||||
model_inputs = {
|
||||
"input_ids": input_ids,
|
||||
"positions": positions,
|
||||
"inputs_embeds": None,
|
||||
"intermediate_tensors": None,
|
||||
}
|
||||
ubatch_state = _make_ubatch_state(
|
||||
vllm_config,
|
||||
[
|
||||
UBatchSlice(slice(0, 4), slice(0, 8)),
|
||||
UBatchSlice(slice(4, 8), slice(8, 16)),
|
||||
],
|
||||
)
|
||||
|
||||
model = _YieldingModel([])
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
finish = runner.begin_capturable_run(
|
||||
model, model_inputs, ubatch_state, for_capture=True
|
||||
)
|
||||
with torch.cuda.graph(graph, stream=runner.capture_stream):
|
||||
captured = finish()
|
||||
|
||||
input_ids.fill_(3)
|
||||
positions.fill_(5)
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expected = torch.full(
|
||||
(num_tokens, 1), 3 * 2 + 5, dtype=torch.float32, device=device
|
||||
)
|
||||
torch.testing.assert_close(captured, expected)
|
||||
|
||||
|
||||
def _request_slices(input_batch: InputBatch) -> list[slice]:
|
||||
return [s.request_slice for s in create_ubatch_slices(input_batch, 2)]
|
||||
|
||||
|
||||
def test_captured_split_survives_a_replay_with_enough_requests():
|
||||
"""Replay preserves the captured split only if real requests reach it."""
|
||||
buffers = _make_buffers()
|
||||
captured = _request_slices(InputBatch.make_dummy(16, 16, buffers))
|
||||
|
||||
def replay(num_reqs: int) -> list[slice]:
|
||||
return _request_slices(
|
||||
_make_input_batch(
|
||||
[1] * num_reqs,
|
||||
[128] * num_reqs,
|
||||
buffers,
|
||||
num_reqs_padded=16,
|
||||
num_tokens_padded=16,
|
||||
)
|
||||
)
|
||||
|
||||
assert replay(16) == captured
|
||||
assert replay(9) == captured
|
||||
assert replay(4) != captured
|
||||
|
||||
|
||||
def _make_cudagraph_manager(capture_sizes: list[int]) -> CudaGraphManager:
|
||||
vllm_config = VllmConfig(
|
||||
model_config=ModelConfig(model="facebook/opt-125m", dtype="float16", seed=0),
|
||||
parallel_config=ParallelConfig(
|
||||
enable_dbo=True,
|
||||
all2all_backend="deepep_low_latency",
|
||||
dbo_decode_token_threshold=DECODE_THRESHOLD,
|
||||
dbo_prefill_token_threshold=PREFILL_THRESHOLD,
|
||||
),
|
||||
compilation_config=CompilationConfig(
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
cudagraph_capture_sizes=capture_sizes,
|
||||
),
|
||||
)
|
||||
with patch.object(
|
||||
cudagraph_utils,
|
||||
"get_pp_group",
|
||||
lambda: SimpleNamespace(is_first_rank=True, is_last_rank=True),
|
||||
):
|
||||
manager = CudaGraphManager(
|
||||
vllm_config,
|
||||
torch.device("cuda:0"),
|
||||
CUDAGraphMode.FULL,
|
||||
decode_query_len=1,
|
||||
ubatch_runner=cast(UBatchRunner, object()),
|
||||
)
|
||||
manager._graphs_captured = True
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a graph pool")
|
||||
def test_microbatched_graphs_are_only_offered_to_uniform_batches():
|
||||
"""Mixed batches cannot reuse graphs captured with uniform query lengths."""
|
||||
manager = _make_cudagraph_manager([64, 128])
|
||||
|
||||
desc = manager.dispatch(
|
||||
num_reqs=64,
|
||||
num_tokens=64,
|
||||
uniform_token_count=1,
|
||||
num_active_loras=0,
|
||||
num_ubatches=2,
|
||||
)
|
||||
assert desc.cg_mode == CUDAGraphMode.FULL
|
||||
assert desc.num_ubatches == 2
|
||||
|
||||
desc = manager.dispatch(
|
||||
num_reqs=8,
|
||||
num_tokens=64,
|
||||
uniform_token_count=None,
|
||||
num_active_loras=0,
|
||||
num_ubatches=2,
|
||||
)
|
||||
assert desc.cg_mode == CUDAGraphMode.NONE
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a graph pool")
|
||||
def test_microbatched_graph_needs_every_rank_to_reach_the_split():
|
||||
"""Fall back to eager on all ranks if any rank cannot reach the captured split."""
|
||||
manager = _make_cudagraph_manager([64, 128])
|
||||
uniform = [1, 1]
|
||||
|
||||
desc, _ = _sync_dp([64, 64], uniform, cudagraph_manager=manager)
|
||||
assert desc.cg_mode == CUDAGraphMode.FULL
|
||||
assert desc.num_ubatches == 2
|
||||
|
||||
# Rank 1 pads the group up to a 128-token graph, but rank 0 only reaches 33.
|
||||
desc, dp_sync_state = _sync_dp([33, 128], uniform, cudagraph_manager=manager)
|
||||
assert desc.cg_mode == CUDAGraphMode.NONE
|
||||
assert desc.num_ubatches == 2
|
||||
assert dp_sync_state is not None and dp_sync_state.eager
|
||||
@@ -1,385 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""The V2 warmup must reserve the KV blocks the scheduler would reserve.
|
||||
|
||||
`KVCacheManager.allocate_slots` sizes every allocation for
|
||||
`num_computed + num_scheduled + num_lookahead_tokens`, because the speculator
|
||||
writes KV past the token range the target model was scheduled for. The warmup
|
||||
hand-builds its `SchedulerOutput`s, so it has to reserve the same blocks.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.core.test_prefix_caching import make_kv_cache_manager
|
||||
from tests.v1.core.utils import create_requests
|
||||
from vllm.config.speculative import SpeculativeConfig
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
MambaSpec,
|
||||
)
|
||||
from vllm.v1.worker.gpu.warmup import (
|
||||
_reserved_block_count,
|
||||
run_mixed_prefill_decode_warmup,
|
||||
warmup_kernels,
|
||||
)
|
||||
|
||||
BLOCK_SIZE = 16
|
||||
MAX_MODEL_LEN = 1024
|
||||
NUM_SPEC_STEPS = 3
|
||||
|
||||
# `warmup_kernels` ends on `torch.accelerator.synchronize()`.
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="warmup synchronizes on the accelerator"
|
||||
)
|
||||
|
||||
|
||||
def _attention_group() -> KVCacheGroupSpec:
|
||||
return KVCacheGroupSpec(
|
||||
["layer"],
|
||||
FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.float32,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _circular_group() -> KVCacheGroupSpec:
|
||||
return KVCacheGroupSpec(
|
||||
["circular"],
|
||||
CircularBufferSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.float32,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _mamba_group(mamba_cache_mode: str) -> KVCacheGroupSpec:
|
||||
# Name carries the mode so several groups can coexist in one config.
|
||||
return KVCacheGroupSpec(
|
||||
[f"mamba_{mamba_cache_mode}"],
|
||||
MambaSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
shapes=((1,),),
|
||||
dtypes=(torch.float32,),
|
||||
mamba_cache_mode=mamba_cache_mode,
|
||||
num_speculative_blocks=NUM_SPEC_STEPS,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _make_runner(
|
||||
kv_cache_groups: list[KVCacheGroupSpec],
|
||||
num_lookahead_tokens: int,
|
||||
num_spec_steps: int = NUM_SPEC_STEPS,
|
||||
) -> SimpleNamespace:
|
||||
"""Stub model runner exposing only what the warmup entry points read."""
|
||||
return SimpleNamespace(
|
||||
num_speculative_steps=num_spec_steps,
|
||||
speculative_config=SimpleNamespace() if num_spec_steps else None,
|
||||
adaptive_verification=None,
|
||||
rejection_sampler=None,
|
||||
decode_query_len=num_spec_steps + 1,
|
||||
is_pooling_model=False,
|
||||
is_encoder_decoder=False,
|
||||
is_last_pp_rank=True,
|
||||
max_num_reqs=4,
|
||||
max_model_len=MAX_MODEL_LEN,
|
||||
model_config=SimpleNamespace(get_vocab_size=lambda: 64),
|
||||
model_state=SimpleNamespace(max_encoder_len=0),
|
||||
scheduler_config=SimpleNamespace(max_num_seqs=4, max_num_batched_tokens=2048),
|
||||
kv_cache_config=SimpleNamespace(
|
||||
kv_cache_groups=kv_cache_groups, num_blocks=1024
|
||||
),
|
||||
vllm_config=SimpleNamespace(
|
||||
num_lookahead_tokens=num_lookahead_tokens, is_mm_encoder_only=False
|
||||
),
|
||||
kv_block_zeroer=None,
|
||||
kv_connector=SimpleNamespace(set_disabled=lambda disabled: None),
|
||||
)
|
||||
|
||||
|
||||
class _StepRecorder:
|
||||
"""Rebuilds each request's per-group block holdings from the warmup steps."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
# (blocks held per group, num_computed_tokens, num_scheduled_tokens)
|
||||
self.steps: list[tuple[list[int], int, int]] = []
|
||||
self.num_spec_tokens_to_schedule: list[int] = []
|
||||
self._held: dict[str, list[int]] = {}
|
||||
|
||||
def execute_model(self, scheduler_output) -> None:
|
||||
if scheduler_output.total_num_scheduled_tokens:
|
||||
self.num_spec_tokens_to_schedule.append(
|
||||
scheduler_output.num_spec_tokens_to_schedule
|
||||
)
|
||||
for new_req in scheduler_output.scheduled_new_reqs:
|
||||
self._held[new_req.req_id] = [len(ids) for ids in new_req.block_ids]
|
||||
self._record(new_req.req_id, new_req.num_computed_tokens, scheduler_output)
|
||||
cached = scheduler_output.scheduled_cached_reqs
|
||||
for i, req_id in enumerate(cached.req_ids):
|
||||
new_block_ids = cached.new_block_ids[i]
|
||||
if new_block_ids is not None:
|
||||
self._held[req_id] = [
|
||||
held + len(ids)
|
||||
for held, ids in zip(self._held[req_id], new_block_ids)
|
||||
]
|
||||
self._record(req_id, cached.num_computed_tokens[i], scheduler_output)
|
||||
|
||||
def _record(self, req_id: str, num_computed: int, scheduler_output) -> None:
|
||||
self.steps.append(
|
||||
(
|
||||
list(self._held[req_id]),
|
||||
num_computed,
|
||||
scheduler_output.num_scheduled_tokens[req_id],
|
||||
)
|
||||
)
|
||||
|
||||
def sample_tokens(self, grammar_output=None) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _assert_covers_lookahead(
|
||||
steps: list[tuple[list[int], int, int]], num_lookahead_tokens: int
|
||||
) -> None:
|
||||
assert steps, "warmup ran no steps"
|
||||
for num_blocks, num_computed, num_scheduled in steps:
|
||||
num_tokens = min(
|
||||
num_computed + num_scheduled + num_lookahead_tokens, MAX_MODEL_LEN
|
||||
)
|
||||
assert num_blocks[0] >= cdiv(num_tokens, BLOCK_SIZE), (
|
||||
f"{num_blocks[0]} blocks for {num_computed}+{num_scheduled} tokens "
|
||||
f"and {num_lookahead_tokens} lookahead tokens"
|
||||
)
|
||||
|
||||
|
||||
# 0 covers eagle / MTP / draft models, 1 covers DFlash's extra in-fill query.
|
||||
@pytest.mark.parametrize("extra_lookahead", [0, 1])
|
||||
@pytest.mark.parametrize("num_spec_steps", [1, 2, 3, 5, 7])
|
||||
def test_warmup_kernels_reserves_lookahead_blocks(num_spec_steps, extra_lookahead):
|
||||
num_lookahead_tokens = num_spec_steps + extra_lookahead
|
||||
recorder = _StepRecorder()
|
||||
|
||||
warmup_kernels(
|
||||
_make_runner([_attention_group()], num_lookahead_tokens, num_spec_steps),
|
||||
recorder.execute_model,
|
||||
recorder.sample_tokens,
|
||||
)
|
||||
|
||||
_assert_covers_lookahead(recorder.steps, num_lookahead_tokens)
|
||||
assert set(recorder.num_spec_tokens_to_schedule) == {num_spec_steps}
|
||||
|
||||
|
||||
def test_mixed_warmup_reserves_lookahead_blocks():
|
||||
num_lookahead_tokens = NUM_SPEC_STEPS + 1
|
||||
recorder = _StepRecorder()
|
||||
|
||||
assert run_mixed_prefill_decode_warmup(
|
||||
_make_runner([_attention_group()], num_lookahead_tokens),
|
||||
worker_execute_model=recorder.execute_model,
|
||||
worker_sample_tokens=recorder.sample_tokens,
|
||||
num_tokens=128,
|
||||
)
|
||||
|
||||
_assert_covers_lookahead(recorder.steps, num_lookahead_tokens)
|
||||
assert set(recorder.num_spec_tokens_to_schedule) == {NUM_SPEC_STEPS}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mamba_cache_mode", ["none", "align"])
|
||||
def test_warmup_reserves_mamba_speculative_blocks(mamba_cache_mode):
|
||||
"""Mamba groups hold the running-state block plus the speculative tail.
|
||||
|
||||
`MambaManager` reserves `num_speculative_blocks` blocks past the token
|
||||
range in every cache mode, and the mamba kernels read all
|
||||
`1 + num_speculative_blocks` of those block-table columns (see
|
||||
`mamba_get_block_table_tensor`).
|
||||
"""
|
||||
recorder = _StepRecorder()
|
||||
|
||||
warmup_kernels(
|
||||
_make_runner(
|
||||
[_attention_group(), _mamba_group(mamba_cache_mode)], NUM_SPEC_STEPS
|
||||
),
|
||||
recorder.execute_model,
|
||||
recorder.sample_tokens,
|
||||
)
|
||||
|
||||
assert recorder.steps, "warmup ran no steps"
|
||||
for num_blocks, num_computed, num_scheduled in recorder.steps:
|
||||
# `MambaManager` drops the lookahead tokens in align mode to keep the
|
||||
# allocation block-aligned, and keeps them otherwise. Pin the token
|
||||
# range and the speculative tail separately, so an implementation that
|
||||
# returned a flat `1 + num_speculative_blocks` would fail.
|
||||
if mamba_cache_mode == "align":
|
||||
# Align mode sizes from the uncapped main-model range.
|
||||
lookahead, num_tokens = 0, num_computed + num_scheduled
|
||||
else:
|
||||
lookahead = NUM_SPEC_STEPS
|
||||
num_tokens = min(num_computed + num_scheduled + lookahead, MAX_MODEL_LEN)
|
||||
assert num_blocks[1] == cdiv(num_tokens, BLOCK_SIZE) + NUM_SPEC_STEPS, (
|
||||
f"{mamba_cache_mode}: {num_blocks[1]} mamba blocks for "
|
||||
f"{num_computed}+{num_scheduled} tokens and {lookahead} lookahead"
|
||||
)
|
||||
|
||||
|
||||
def _hybrid_kv_cache_config(num_blocks: int) -> KVCacheConfig:
|
||||
"""Attention, circular, and Mamba groups exercise every reservation branch."""
|
||||
return KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
_attention_group(),
|
||||
_circular_group(),
|
||||
_mamba_group("none"),
|
||||
_mamba_group("align"),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_reserved_block_count_matches_real_kv_cache_manager():
|
||||
"""`_reserved_block_count` must predict exactly what the real
|
||||
`KVCacheManager.allocate_slots` consumes, for every group, at every step
|
||||
of a warmup-realistic trajectory: a prefill followed by decode steps that
|
||||
mix spec and non-spec shapes, all at the fixed `num_lookahead_tokens`
|
||||
`_warmup_block_counter` binds once per model runner.
|
||||
|
||||
The existing tests above pin this arithmetic against a hand-built
|
||||
`_StepRecorder` fake, which only proves the fake and the production
|
||||
function agree with each other. Driving `allocate_slots` itself is the
|
||||
only way to catch a real divergence from the allocator warmup has to
|
||||
match.
|
||||
|
||||
Since `num_computed_tokens` only grows and `num_lookahead_tokens` is held
|
||||
fixed across the trajectory, the real manager's held-block count is
|
||||
non-decreasing in lockstep with the prediction, so equality (not just
|
||||
the reservation lower bound) holds at every step -- exactly the shape of
|
||||
trajectory `warmup_kernels` itself drives the allocator through.
|
||||
"""
|
||||
num_lookahead_tokens = NUM_SPEC_STEPS + 1
|
||||
decode_query_len = NUM_SPEC_STEPS + 1
|
||||
|
||||
kv_cache_config = _hybrid_kv_cache_config(num_blocks=256)
|
||||
specs = [g.kv_cache_spec for g in kv_cache_config.kv_cache_groups]
|
||||
manager = make_kv_cache_manager(
|
||||
kv_cache_config,
|
||||
max_model_len=MAX_MODEL_LEN,
|
||||
hash_block_size=BLOCK_SIZE,
|
||||
enable_caching=False,
|
||||
)
|
||||
(request,) = create_requests(
|
||||
num_requests=1, num_tokens=decode_query_len + 1, block_size=BLOCK_SIZE
|
||||
)
|
||||
|
||||
def _step(num_new_tokens: int) -> None:
|
||||
computed_blocks, num_new_computed, _ = manager.get_computed_blocks(request)
|
||||
blocks = manager.allocate_slots(
|
||||
request,
|
||||
num_new_tokens,
|
||||
num_new_computed,
|
||||
computed_blocks,
|
||||
num_lookahead_tokens=num_lookahead_tokens,
|
||||
)
|
||||
assert blocks is not None, "block pool exhausted"
|
||||
held = manager.get_block_ids(request.request_id)
|
||||
num_tokens = request.num_computed_tokens + num_new_tokens
|
||||
for spec, group_held in zip(specs, held):
|
||||
expected = _reserved_block_count(
|
||||
num_tokens,
|
||||
spec,
|
||||
num_lookahead_tokens=num_lookahead_tokens,
|
||||
max_model_len=MAX_MODEL_LEN,
|
||||
max_encoder_len=0,
|
||||
)
|
||||
assert len(group_held) == expected, (
|
||||
f"{type(spec).__name__} "
|
||||
f"mode={getattr(spec, 'mamba_cache_mode', None)}: real manager "
|
||||
f"holds {len(group_held)} blocks for {num_tokens} tokens, "
|
||||
f"_reserved_block_count predicts {expected}"
|
||||
)
|
||||
request.num_computed_tokens = num_tokens
|
||||
|
||||
# Prefill, a spec decode step, a no-draft decode step, and another spec
|
||||
# decode step: the same shapes `warmup_kernels` drives its decode steps
|
||||
# through (see `decode_steps` in `warmup.py`).
|
||||
_step(decode_query_len + 1)
|
||||
_step(decode_query_len)
|
||||
_step(1)
|
||||
_step(decode_query_len)
|
||||
|
||||
manager.free(request)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "draft_hf_config", "expected"),
|
||||
[
|
||||
("eagle", None, NUM_SPEC_STEPS),
|
||||
("eagle3", None, NUM_SPEC_STEPS),
|
||||
("mtp", None, NUM_SPEC_STEPS),
|
||||
("dspark", None, NUM_SPEC_STEPS),
|
||||
("dspark", {"sample_from_anchor": True}, NUM_SPEC_STEPS),
|
||||
("dspark", {"sample_from_anchor": False}, NUM_SPEC_STEPS + 1),
|
||||
("draft_model", None, NUM_SPEC_STEPS),
|
||||
# DFlash's in-fill decoding adds a query for the last sampled token.
|
||||
("dflash", None, NUM_SPEC_STEPS + 1),
|
||||
("ngram", None, 0),
|
||||
("ngram_gpu", None, 0),
|
||||
("suffix", None, 0),
|
||||
("extract_hidden_states", None, 0),
|
||||
],
|
||||
)
|
||||
def test_num_lookahead_tokens_per_method(
|
||||
method: str, draft_hf_config: dict | None, expected: int
|
||||
):
|
||||
"""`VllmConfig.num_lookahead_tokens` is the single source of the reservation.
|
||||
|
||||
Both the scheduler and the warmup read it, so a wrong answer here silently
|
||||
changes how many blocks every request holds. Exercises the real property
|
||||
and the real `SpeculativeConfig` predicates; the config is built without
|
||||
`__post_init__` because the speculative methods otherwise require a draft
|
||||
model to be resolvable.
|
||||
"""
|
||||
|
||||
class _Config:
|
||||
speculative_config: SpeculativeConfig | None = None
|
||||
diffusion_config = None
|
||||
num_speculative_tokens = VllmConfig.num_speculative_tokens
|
||||
num_lookahead_tokens = VllmConfig.num_lookahead_tokens
|
||||
|
||||
speculative_config = object.__new__(SpeculativeConfig)
|
||||
object.__setattr__(speculative_config, "method", method)
|
||||
object.__setattr__(speculative_config, "num_speculative_tokens", NUM_SPEC_STEPS)
|
||||
hf_config = SimpleNamespace(**(draft_hf_config or {}))
|
||||
object.__setattr__(
|
||||
speculative_config,
|
||||
"draft_model_config",
|
||||
SimpleNamespace(hf_config=hf_config),
|
||||
)
|
||||
|
||||
config = _Config()
|
||||
config.speculative_config = speculative_config
|
||||
|
||||
assert config.num_lookahead_tokens == expected
|
||||
|
||||
|
||||
def test_num_lookahead_tokens_without_speculation():
|
||||
class _Config:
|
||||
speculative_config: SpeculativeConfig | None = None
|
||||
diffusion_config = None
|
||||
num_speculative_tokens = VllmConfig.num_speculative_tokens
|
||||
num_lookahead_tokens = VllmConfig.num_lookahead_tokens
|
||||
|
||||
config = _Config()
|
||||
|
||||
assert config.num_lookahead_tokens == 0
|
||||
@@ -1,36 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Validate the registry reference kernel against runtime dispatch."""
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("NVIDIA dispatch tests require CUDA", allow_module_level=True)
|
||||
|
||||
from vllm.v1.worker.block_table import ComputeSlotMappingKernel
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kv_cache_block_size", [256, 64, 8, 4])
|
||||
def test_compute_slot_mapping_warmup_matches_runtime_specializations(
|
||||
kv_cache_block_size: int,
|
||||
) -> None:
|
||||
kernel = ComputeSlotMappingKernel()
|
||||
kwargs = dict(
|
||||
kv_cache_block_size=kv_cache_block_size,
|
||||
total_cp_world_size=1,
|
||||
total_cp_rank=0,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
block_table_stride=32768,
|
||||
)
|
||||
expected = kernel.CompileKey(
|
||||
kv_cache_block_size=kv_cache_block_size,
|
||||
total_cp_world_size=1,
|
||||
total_cp_rank=0,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
block_table_stride=16,
|
||||
)
|
||||
|
||||
assert kernel.dispatch(**kwargs) == expected
|
||||
assert kernel.get_warmup_keys(**kwargs) == [expected]
|
||||
@@ -1,397 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.utils import dense_kv_cache_views
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
ChunkedLocalAttentionSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheLayout,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
from vllm.v1.worker import utils as worker_utils
|
||||
from vllm.v1.worker.utils import (
|
||||
AttentionGroup,
|
||||
KVBlockZeroer,
|
||||
_zero_kv_blocks_kernel,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
@pytest.mark.parametrize(
|
||||
"spec",
|
||||
[
|
||||
SlidingWindowSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.uint8,
|
||||
sliding_window=4,
|
||||
),
|
||||
ChunkedLocalAttentionSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.uint8,
|
||||
attention_chunk_size=4,
|
||||
),
|
||||
],
|
||||
ids=["sliding-window", "chunked-local"],
|
||||
)
|
||||
def test_attention_blocks_are_zeroed(spec):
|
||||
device = torch.device("cuda")
|
||||
storage = torch.ones((4, 1, 2, 2), dtype=torch.uint8, device=device)
|
||||
layer_name = "draft.self_attn"
|
||||
zeroer = KVBlockZeroer(
|
||||
device,
|
||||
attn_groups_iter=[AttentionGroup(None, [layer_name], spec, 0)],
|
||||
kernel_block_sizes=[2],
|
||||
static_forward_context={
|
||||
layer_name: SimpleNamespace(kv_cache=storage),
|
||||
},
|
||||
num_blocks=4,
|
||||
)
|
||||
|
||||
zeroer.zero_block_ids([1])
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expected = torch.ones_like(storage)
|
||||
expected[1] = 0
|
||||
assert torch.equal(storage, expected)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_layers_in_one_group_may_use_different_kernel_pages_per_block():
|
||||
"""Derive kernel pages per block from each layer's allocation."""
|
||||
device = torch.device("cuda")
|
||||
num_blocks = 4
|
||||
spec = SlidingWindowSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.int32,
|
||||
sliding_window=2,
|
||||
)
|
||||
# Two kernel pages per logical block.
|
||||
wide = torch.ones((num_blocks * 2, 3), dtype=torch.int32, device=device)
|
||||
# One kernel page per logical block, carved out of a larger allocation so
|
||||
# an over-strided write lands in the guard region instead of faulting or
|
||||
# silently hitting another tensor.
|
||||
narrow_backing = torch.ones((num_blocks * 3, 5), dtype=torch.int32, device=device)
|
||||
narrow = narrow_backing[:num_blocks]
|
||||
|
||||
zeroer = KVBlockZeroer(
|
||||
device,
|
||||
attn_groups_iter=[
|
||||
AttentionGroup(
|
||||
None,
|
||||
["wide", "narrow"],
|
||||
spec,
|
||||
0,
|
||||
)
|
||||
],
|
||||
kernel_block_sizes=[1],
|
||||
static_forward_context={
|
||||
"wide": SimpleNamespace(kv_cache=wide),
|
||||
"narrow": SimpleNamespace(kv_cache=narrow),
|
||||
},
|
||||
num_blocks=num_blocks,
|
||||
)
|
||||
|
||||
zeroer.zero_block_ids([num_blocks - 1])
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expected_wide = torch.ones_like(wide)
|
||||
expected_wide[2 * (num_blocks - 1) :] = 0
|
||||
assert torch.equal(wide, expected_wide)
|
||||
|
||||
expected_narrow = torch.ones_like(narrow_backing)
|
||||
expected_narrow[num_blocks - 1] = 0
|
||||
assert torch.equal(narrow_backing, expected_narrow)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_block_ids_are_not_overwritten_while_copy_is_in_flight():
|
||||
device = torch.device("cuda")
|
||||
num_blocks = 4
|
||||
page_size_el = 4
|
||||
storage = torch.ones((num_blocks, page_size_el), dtype=torch.int32, device=device)
|
||||
|
||||
# Build the minimal zeroer state directly so the test can focus on the
|
||||
# in-flight copy behavior without constructing model attention groups.
|
||||
zeroer = KVBlockZeroer.__new__(KVBlockZeroer)
|
||||
zeroer.device = device
|
||||
zeroer._meta = (
|
||||
torch.tensor([storage.data_ptr()], dtype=torch.uint64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
page_size_el // page_size_el, # max_chunks = 1
|
||||
page_size_el, # blk_size
|
||||
1, # n_segs
|
||||
)
|
||||
|
||||
stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(stream):
|
||||
# Keep the first nonblocking H2D copy pending while the host submits the
|
||||
# second call. Each call must stage from its own pinned source so the
|
||||
# first copy is not corrupted before it runs.
|
||||
torch.cuda._sleep(10_000_000)
|
||||
zeroer.zero_block_ids([1])
|
||||
zeroer.zero_block_ids([2])
|
||||
stream.synchronize()
|
||||
|
||||
assert torch.all(storage[0] == 1)
|
||||
assert torch.all(storage[1] == 0)
|
||||
assert torch.all(storage[2] == 0)
|
||||
assert torch.all(storage[3] == 1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_non_uniform_page_sizes():
|
||||
"""Two segments with different page sizes (e.g. MLA + DSA indexer)."""
|
||||
device = torch.device("cuda")
|
||||
num_blocks = 4
|
||||
page_size_a = 10496 # int32 elements
|
||||
page_size_b = 2112
|
||||
|
||||
storage_a = torch.ones((num_blocks, page_size_a), dtype=torch.int32, device=device)
|
||||
storage_b = torch.ones((num_blocks, page_size_b), dtype=torch.int32, device=device)
|
||||
|
||||
zeroer = KVBlockZeroer.__new__(KVBlockZeroer)
|
||||
zeroer.device = device
|
||||
|
||||
seg_page_sizes = [page_size_a, page_size_b]
|
||||
max_ps = max(seg_page_sizes)
|
||||
|
||||
blk_size = min(1 << (max_ps - 1).bit_length(), 1024)
|
||||
|
||||
zeroer._meta = (
|
||||
torch.tensor(
|
||||
[storage_a.data_ptr(), storage_b.data_ptr()],
|
||||
dtype=torch.uint64,
|
||||
device=device,
|
||||
),
|
||||
torch.tensor(seg_page_sizes, dtype=torch.int64, device=device),
|
||||
torch.tensor(seg_page_sizes, dtype=torch.int64, device=device),
|
||||
(max_ps + blk_size - 1) // blk_size,
|
||||
blk_size,
|
||||
2,
|
||||
)
|
||||
|
||||
stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(stream):
|
||||
zeroer.zero_block_ids([1, 2])
|
||||
stream.synchronize()
|
||||
|
||||
for storage in (storage_a, storage_b):
|
||||
assert torch.all(storage[0] == 1)
|
||||
assert torch.all(storage[1] == 0)
|
||||
assert torch.all(storage[2] == 0)
|
||||
assert torch.all(storage[3] == 1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_packed_segment_zeros_only_its_last_block_page():
|
||||
"""A packed KV segment steps by block stride but clears only its page."""
|
||||
device = torch.device("cuda")
|
||||
num_blocks = 4
|
||||
block_stride_el = 12
|
||||
page_size_el = 4
|
||||
page_offset_el = 3
|
||||
backing = torch.ones(
|
||||
(num_blocks, block_stride_el), dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
zeroer = KVBlockZeroer.__new__(KVBlockZeroer)
|
||||
zeroer.device = device
|
||||
zeroer._meta = (
|
||||
torch.tensor(
|
||||
[backing.data_ptr() + page_offset_el * backing.element_size()],
|
||||
dtype=torch.uint64,
|
||||
device=device,
|
||||
),
|
||||
torch.tensor([block_stride_el], dtype=torch.int64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
1,
|
||||
page_size_el,
|
||||
1,
|
||||
)
|
||||
|
||||
zeroer.zero_block_ids([num_blocks - 1])
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
expected = torch.ones_like(backing)
|
||||
expected[-1, page_offset_el : page_offset_el + page_size_el] = 0
|
||||
assert torch.equal(backing, expected)
|
||||
|
||||
|
||||
def test_large_dsv4_launch_geometry(monkeypatch):
|
||||
"""Keep the failing DSV4 shape efficient and within launch limits."""
|
||||
device = torch.device("cpu")
|
||||
n_blocks, n_segs = 6870, 181
|
||||
layer_names = [f"layer.{i}" for i in range(n_segs)]
|
||||
page_sizes = [9344 if i % 2 == 0 else 292 for i in range(n_segs)]
|
||||
spec = SlidingWindowSpec(
|
||||
block_size=1,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.int32,
|
||||
sliding_window=1,
|
||||
)
|
||||
storages = {
|
||||
name: torch.ones((1, page_size), dtype=torch.int32)
|
||||
for name, page_size in zip(layer_names, page_sizes)
|
||||
}
|
||||
zeroer = KVBlockZeroer(
|
||||
device,
|
||||
attn_groups_iter=[
|
||||
AttentionGroup(None, [name], spec, group_id)
|
||||
for group_id, name in enumerate(layer_names)
|
||||
],
|
||||
kernel_block_sizes=[1] * n_segs,
|
||||
static_forward_context={
|
||||
name: SimpleNamespace(kv_cache=storage)
|
||||
for name, storage in storages.items()
|
||||
},
|
||||
num_blocks=1,
|
||||
)
|
||||
|
||||
assert zeroer._meta is not None
|
||||
_, _, seg_page_sizes, max_chunks, blk_size, n_segs = zeroer._meta
|
||||
assert seg_page_sizes.tolist() == page_sizes
|
||||
assert (max_chunks, blk_size, n_segs) == (10, 1024, 181)
|
||||
|
||||
captured_grids = []
|
||||
|
||||
class FakeKernel:
|
||||
def __getitem__(self, grid):
|
||||
captured_grids.append(grid)
|
||||
return lambda *args, **kwargs: None
|
||||
|
||||
monkeypatch.setattr(worker_utils, "_zero_kv_blocks_kernel", FakeKernel())
|
||||
monkeypatch.setattr(
|
||||
worker_utils,
|
||||
"async_tensor_h2d",
|
||||
lambda values, **kwargs: torch.tensor(values, dtype=torch.int64),
|
||||
)
|
||||
|
||||
zeroer.zero_block_ids(list(range(n_blocks)))
|
||||
|
||||
old_max_chunks = max(page_sizes) // 4
|
||||
assert math.prod((n_blocks, n_segs, old_max_chunks)) > 2**31 - 1
|
||||
assert captured_grids == [(n_blocks, n_segs, max_chunks)]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_warmup_compiles_for_all_block_counts():
|
||||
"""After warmup, no launch should trigger a first-request JIT compile.
|
||||
|
||||
The block count is carried by the launch grid, so changing it must reuse
|
||||
the warmup's compiled kernel.
|
||||
"""
|
||||
device = torch.device("cuda")
|
||||
num_blocks = 64
|
||||
page_size_el = 4
|
||||
storage = torch.ones((num_blocks, page_size_el), dtype=torch.int32, device=device)
|
||||
|
||||
zeroer = KVBlockZeroer.__new__(KVBlockZeroer)
|
||||
zeroer.device = device
|
||||
zeroer._meta = (
|
||||
torch.tensor([storage.data_ptr()], dtype=torch.uint64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
1, # max_chunks
|
||||
page_size_el, # blk_size
|
||||
1, # n_segs
|
||||
)
|
||||
|
||||
def compiled_variants() -> set:
|
||||
return {
|
||||
key
|
||||
for caches in _zero_kv_blocks_kernel.device_caches.values()
|
||||
for key in caches[0]
|
||||
}
|
||||
|
||||
zeroer.warmup(num_blocks)
|
||||
torch.accelerator.synchronize()
|
||||
warmed = compiled_variants()
|
||||
assert warmed
|
||||
|
||||
for n_blocks in (1, 2, 3, 16, 32):
|
||||
zeroer.zero_block_ids(list(range(n_blocks)))
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert compiled_variants() == warmed
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_warmup_respects_available_block_count():
|
||||
"""An empty KV cache must not be warmed with out-of-range block IDs."""
|
||||
device = torch.device("cuda")
|
||||
page_size_el = 4
|
||||
storage = torch.ones((1, page_size_el), dtype=torch.int32, device=device)
|
||||
|
||||
zeroer = KVBlockZeroer.__new__(KVBlockZeroer)
|
||||
zeroer.device = device
|
||||
zeroer._meta = (
|
||||
torch.tensor([storage.data_ptr()], dtype=torch.uint64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
torch.tensor([page_size_el], dtype=torch.int64, device=device),
|
||||
1,
|
||||
page_size_el,
|
||||
1,
|
||||
)
|
||||
|
||||
zeroer.warmup(0)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
assert torch.all(storage == 1)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
@pytest.mark.parametrize("layout", list(KVCacheLayout))
|
||||
def test_zeroes_exactly_one_block_per_layer(layout: KVCacheLayout):
|
||||
"""The zeroer must zero every byte of the target block in every layer and nothing
|
||||
outside it — per head-group region under LHBNC, and never past the target block's
|
||||
tile under block-major layouts (no out-of-bounds writes, no clobbering)."""
|
||||
device = torch.device("cuda")
|
||||
num_blocks, num_layers = 4, 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=4, num_kv_heads=2, head_size=8, dtype=torch.float32
|
||||
)
|
||||
raw = torch.empty(
|
||||
num_blocks * num_layers * spec.page_size_bytes,
|
||||
dtype=torch.int8,
|
||||
device=device,
|
||||
).fill_(1)
|
||||
views = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
|
||||
groups = [
|
||||
AttentionGroup(
|
||||
backend=None,
|
||||
layer_names=[f"layer.{i}" for i in range(num_layers)],
|
||||
kv_cache_spec=spec,
|
||||
kv_cache_group_id=0,
|
||||
)
|
||||
]
|
||||
ctx = {f"layer.{i}": SimpleNamespace(kv_cache=views[i]) for i in range(num_layers)}
|
||||
zeroer = KVBlockZeroer(
|
||||
device,
|
||||
attn_groups_iter=iter(groups),
|
||||
kernel_block_sizes=[spec.block_size],
|
||||
static_forward_context=ctx,
|
||||
num_blocks=num_blocks,
|
||||
)
|
||||
zeroer.zero_block_ids([2])
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
for view in views:
|
||||
assert (view[2] == 0).all(), layout
|
||||
for b in (0, 1, 3):
|
||||
assert (view[b].view(torch.int8) == 1).all(), layout
|
||||
zero_bytes = int((raw == 0).sum().item())
|
||||
assert zero_bytes == num_layers * spec.page_size_bytes, layout
|
||||
@@ -1,426 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.v1.attention.test_gdn_metadata_builder import (
|
||||
BLOCK_SIZE,
|
||||
DEVICE,
|
||||
_create_gdn_builder,
|
||||
)
|
||||
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.recoverssm_metadata import (
|
||||
RecoverSSMMetadata,
|
||||
RecoverSSMPostprocessMetadata,
|
||||
)
|
||||
from vllm.v1.worker.gpu.model_states import mamba_hybrid
|
||||
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
|
||||
from vllm.v1.worker.gpu.model_states.recoverssm import RecoverSSMState
|
||||
|
||||
|
||||
def test_prepare_attn_forwards_positions(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
state = object.__new__(MambaHybridModelState)
|
||||
state.vllm_config = SimpleNamespace(num_speculative_tokens=0)
|
||||
state.model_config = SimpleNamespace(max_model_len=8192)
|
||||
state._align_mode = False
|
||||
state.recoverssm = None
|
||||
|
||||
positions = torch.tensor([1536], dtype=torch.int64)
|
||||
input_batch = SimpleNamespace(
|
||||
num_reqs=1,
|
||||
num_tokens=1,
|
||||
num_reqs_after_padding=1,
|
||||
num_tokens_after_padding=1,
|
||||
query_start_loc_np=torch.tensor([0, 1], dtype=torch.int32).numpy(),
|
||||
query_start_loc=torch.tensor([0, 1], dtype=torch.int32),
|
||||
num_scheduled_tokens=torch.tensor([1], dtype=torch.int32),
|
||||
max_query_len=None,
|
||||
seq_lens_cpu_upper_bound=torch.tensor([1537], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([1537], dtype=torch.int32),
|
||||
is_prefilling_np=torch.tensor([False]).numpy(),
|
||||
prefill_runs_as_decode_np=None,
|
||||
dcp_local_seq_lens=None,
|
||||
positions=positions,
|
||||
prompt_lens=torch.tensor([1024], dtype=torch.int32),
|
||||
)
|
||||
expected_metadata = {"layer": object()}
|
||||
build_attn_metadata = Mock(return_value=expected_metadata)
|
||||
monkeypatch.setattr(mamba_hybrid, "build_attn_metadata", build_attn_metadata)
|
||||
|
||||
metadata = state.prepare_attn(
|
||||
input_batch=input_batch,
|
||||
cudagraph_mode=CUDAGraphMode.NONE,
|
||||
block_tables=(),
|
||||
slot_mappings=torch.empty(0, dtype=torch.int64),
|
||||
attn_groups=[],
|
||||
kv_cache_config=Mock(),
|
||||
)
|
||||
|
||||
assert metadata is expected_metadata
|
||||
assert build_attn_metadata.call_args.kwargs["positions"] is positions
|
||||
|
||||
|
||||
def test_add_request_seeds_state_idx_in_mamba_blocks() -> None:
|
||||
"""A drafter group can lower cache_config.block_size below the mamba
|
||||
block size; the seeded column must still be in mamba blocks."""
|
||||
state = object.__new__(MambaHybridModelState)
|
||||
state.cache_config = SimpleNamespace(block_size=16, mamba_block_size=880)
|
||||
state._align_mode = True
|
||||
state.rope_state = None
|
||||
state.prompt_embeds_state = None
|
||||
state.num_accepted_tokens_gpu = torch.ones(2, dtype=torch.int32)
|
||||
state._mamba_state_idx_gpu = torch.zeros(2, dtype=torch.int32)
|
||||
|
||||
state.add_request(1, SimpleNamespace(num_computed_tokens=107_360))
|
||||
|
||||
assert state._mamba_state_idx_gpu[1] == 121
|
||||
|
||||
|
||||
def test_padded_prompt_tail_builds_as_spec_decode(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A one-token prompt tail over prior state, padded with K placeholder
|
||||
drafts (e.g. a P/D decode-node arrival), must reach the GDN builder as a
|
||||
spec-decode row. Built as a prefill, the placeholder tokens are folded into
|
||||
the recurrent state and can't be rolled back.
|
||||
"""
|
||||
k = 3
|
||||
state = object.__new__(MambaHybridModelState)
|
||||
state.vllm_config = SimpleNamespace(num_speculative_tokens=k)
|
||||
state.model_config = SimpleNamespace(max_model_len=8192)
|
||||
state._align_mode = False
|
||||
state.recoverssm = None
|
||||
state.num_accepted_tokens_gpu = torch.ones(4, dtype=torch.int32)
|
||||
|
||||
# A verify decode, a padded prompt tail (128 of 129 prompt tokens already
|
||||
# computed), and a fresh prompt chunk of the same length.
|
||||
query_lens = [k + 1] * 3
|
||||
seq_lens = [50, 128 + k + 1, k + 1]
|
||||
is_prefilling = [False, True, True]
|
||||
query_start_loc = np.array([0, 4, 8, 12], dtype=np.int32)
|
||||
input_batch = SimpleNamespace(
|
||||
num_reqs=3,
|
||||
num_tokens=12,
|
||||
num_reqs_after_padding=3,
|
||||
num_tokens_after_padding=12,
|
||||
idx_mapping=torch.arange(3),
|
||||
query_start_loc_np=query_start_loc,
|
||||
query_start_loc=torch.from_numpy(query_start_loc),
|
||||
num_scheduled_tokens=np.array(query_lens, dtype=np.int32),
|
||||
num_draft_tokens_per_req=np.array([k, k, 0], dtype=np.int32),
|
||||
max_query_len=None,
|
||||
seq_lens_cpu_upper_bound=torch.tensor(seq_lens, dtype=torch.int32),
|
||||
seq_lens=torch.tensor(seq_lens, dtype=torch.int32),
|
||||
is_prefilling_np=np.array(is_prefilling),
|
||||
prefill_runs_as_decode_np=np.array([False, True, False]),
|
||||
dcp_local_seq_lens=None,
|
||||
positions=torch.zeros(12, dtype=torch.int64),
|
||||
prompt_lens=None,
|
||||
)
|
||||
build_attn_metadata = Mock(return_value={})
|
||||
monkeypatch.setattr(mamba_hybrid, "build_attn_metadata", build_attn_metadata)
|
||||
state.prepare_attn(
|
||||
input_batch=input_batch,
|
||||
cudagraph_mode=CUDAGraphMode.NONE,
|
||||
block_tables=(),
|
||||
slot_mappings=torch.empty(0, dtype=torch.int64),
|
||||
attn_groups=[],
|
||||
kv_cache_config=Mock(),
|
||||
)
|
||||
mamba_metadata = build_attn_metadata.call_args.kwargs[
|
||||
"model_specific_attn_metadata"
|
||||
]
|
||||
assert mamba_metadata.is_prefilling.tolist() == [False, False, True]
|
||||
|
||||
builder = _create_gdn_builder(num_speculative_tokens=k)
|
||||
common = create_common_attn_metadata(
|
||||
BatchSpec(seq_lens=seq_lens, query_lens=query_lens), BLOCK_SIZE, DEVICE
|
||||
).replace(**mamba_metadata.get_extra_common_attn_kwargs(0, 3))
|
||||
meta = builder.build(
|
||||
common_prefix_len=0,
|
||||
common_attn_metadata=common,
|
||||
num_accepted_tokens=mamba_metadata.num_accepted_tokens,
|
||||
num_decode_draft_tokens_cpu=mamba_metadata.num_decode_draft_tokens_cpu,
|
||||
)
|
||||
|
||||
# Only the fresh prompt chunk needs the prefill kernels.
|
||||
assert meta.num_spec_decodes == 2
|
||||
assert meta.num_prefills == 1
|
||||
assert meta.num_prefill_tokens == k + 1
|
||||
|
||||
|
||||
def _mamba_hybrid_state(num_speculative_tokens: int) -> MambaHybridModelState:
|
||||
state = object.__new__(MambaHybridModelState)
|
||||
state.vllm_config = SimpleNamespace(num_speculative_tokens=num_speculative_tokens)
|
||||
state.model_config = SimpleNamespace(max_model_len=8192)
|
||||
state._align_mode = False
|
||||
state.recoverssm = None
|
||||
# A request that accepted 3 drafts (plus the bonus token) on the previous
|
||||
# step; the others have never had a draft accepted.
|
||||
state.num_accepted_tokens_gpu = torch.tensor([4, 1, 1], dtype=torch.int32)
|
||||
return state
|
||||
|
||||
|
||||
def _input_batch(
|
||||
num_scheduled_tokens: list[int],
|
||||
num_draft_tokens_per_req: list[int] | None,
|
||||
is_prefilling: list[bool],
|
||||
num_reqs_after_padding: int | None = None,
|
||||
) -> SimpleNamespace:
|
||||
"""`num_draft_tokens_per_req=None` is a batch where nobody proposed a
|
||||
draft this step, e.g. because ngram found no match for anyone."""
|
||||
num_reqs = len(num_scheduled_tokens)
|
||||
query_start_loc = np.zeros(num_reqs + 1, dtype=np.int32)
|
||||
query_start_loc[1:] = np.cumsum(num_scheduled_tokens)
|
||||
num_tokens = int(query_start_loc[-1])
|
||||
seq_lens = torch.full((num_reqs,), 10, dtype=torch.int32)
|
||||
return SimpleNamespace(
|
||||
num_reqs=num_reqs,
|
||||
num_reqs_after_padding=num_reqs_after_padding or num_reqs,
|
||||
num_tokens=num_tokens,
|
||||
num_tokens_after_padding=num_tokens,
|
||||
query_start_loc_np=query_start_loc,
|
||||
num_scheduled_tokens=np.array(num_scheduled_tokens, dtype=np.int32),
|
||||
max_query_len=None,
|
||||
seq_lens_cpu_upper_bound=seq_lens,
|
||||
is_prefilling_np=np.array(is_prefilling),
|
||||
prefill_runs_as_decode_np=None,
|
||||
num_draft_tokens_per_req=None
|
||||
if num_draft_tokens_per_req is None
|
||||
else np.array(num_draft_tokens_per_req, dtype=np.int32),
|
||||
idx_mapping=torch.arange(num_reqs),
|
||||
query_start_loc=torch.from_numpy(query_start_loc),
|
||||
seq_lens=seq_lens,
|
||||
dcp_local_seq_lens=None,
|
||||
positions=torch.zeros(num_tokens, dtype=torch.int64),
|
||||
prompt_lens=None,
|
||||
)
|
||||
|
||||
|
||||
def _prepare_attn_metadata(
|
||||
state: MambaHybridModelState,
|
||||
monkeypatch,
|
||||
input_batch: SimpleNamespace | None = None,
|
||||
cudagraph_mode: CUDAGraphMode = CUDAGraphMode.NONE,
|
||||
) -> SimpleNamespace:
|
||||
captured = {}
|
||||
|
||||
def fake_build_attn_metadata(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return Mock()
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.worker.gpu.model_states.mamba_hybrid.build_attn_metadata",
|
||||
fake_build_attn_metadata,
|
||||
)
|
||||
|
||||
if input_batch is None:
|
||||
input_batch = _input_batch([1, 1], None, [False, False])
|
||||
state.prepare_attn(
|
||||
input_batch=input_batch,
|
||||
cudagraph_mode=cudagraph_mode,
|
||||
block_tables=(),
|
||||
slot_mappings={},
|
||||
attn_groups=[],
|
||||
kv_cache_config=Mock(),
|
||||
)
|
||||
return captured["model_specific_attn_metadata"]
|
||||
|
||||
|
||||
def test_prepare_attn_keeps_the_accepted_offset_when_the_batch_drafted_nothing(
|
||||
monkeypatch,
|
||||
):
|
||||
"""`num_accepted_tokens` must reach the attention builders whenever the
|
||||
speculative config is on, even when *this* batch scheduled no draft
|
||||
tokens at all. Before the fix, `use_spec_decode` was gated on this step's
|
||||
scheduled drafts (`len(scheduled_spec_decode_tokens) > 0` in the V1
|
||||
runner) rather than on the speculative config, so a request that accepted
|
||||
drafts on a previous step would silently lose that offset the moment
|
||||
ngram found no match for anyone in the batch.
|
||||
"""
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=3)
|
||||
|
||||
metadata = _prepare_attn_metadata(state, monkeypatch)
|
||||
|
||||
assert metadata.num_accepted_tokens is not None
|
||||
assert metadata.num_accepted_tokens.tolist() == [4, 1]
|
||||
assert metadata.num_decode_draft_tokens_cpu is not None
|
||||
|
||||
|
||||
def test_prepare_attn_omits_the_offset_without_a_speculative_config(monkeypatch):
|
||||
"""Mirrors the check above: with speculative decoding off entirely, there
|
||||
is no accepted-token offset to carry, and the metadata must say so
|
||||
explicitly (`None`) rather than a stale or default value."""
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=0)
|
||||
|
||||
metadata = _prepare_attn_metadata(state, monkeypatch)
|
||||
|
||||
assert metadata.num_accepted_tokens is None
|
||||
assert metadata.num_decode_draft_tokens_cpu is None
|
||||
|
||||
|
||||
def test_zero_draft_decode_row_is_marked_as_a_speculative_row(monkeypatch):
|
||||
"""A decode row that got no drafts still has to reach the speculative path.
|
||||
|
||||
The recurrent backends only apply a row's accepted-token offset on that
|
||||
path, and a row that accepted drafts on the previous step keeps that offset
|
||||
even when the current step proposes nothing (the scheduler drops drafts
|
||||
whenever the token budget truncates the step). Marking such a row with the
|
||||
-1 sentinel sends it to the plain decode path, which reads the state at
|
||||
column 0 and ignores the offset.
|
||||
"""
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=3)
|
||||
input_batch = _input_batch([3, 1, 1], [2, 0, 0], [False, False, True])
|
||||
|
||||
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
|
||||
|
||||
assert metadata.num_decode_draft_tokens_cpu.tolist() == [
|
||||
2, # decode row with drafts
|
||||
0, # decode row with no drafts: speculative path, offset applied
|
||||
-1, # one-token prefill tail: no offset to apply, stays a plain row
|
||||
]
|
||||
|
||||
|
||||
def test_batch_without_any_drafts_still_marks_its_decode_rows(monkeypatch):
|
||||
"""`num_draft_tokens_per_req` is None whenever no row in the batch drafted
|
||||
anything. Those rows are ordinary decode rows carrying an offset from the
|
||||
previous step, so the absence of drafts in this step must not be read as
|
||||
speculative decoding being off."""
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=3)
|
||||
input_batch = _input_batch([1, 1], None, [False, True])
|
||||
|
||||
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
|
||||
|
||||
assert metadata.num_decode_draft_tokens_cpu.tolist() == [0, -1]
|
||||
|
||||
|
||||
def test_padded_rows_keep_the_sentinel(monkeypatch):
|
||||
"""Full CUDA-graph capture pads the batch; padded rows describe no request
|
||||
and must not be picked up as speculative rows."""
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=3)
|
||||
input_batch = _input_batch([1, 1], [0, 0], [False, False], num_reqs_after_padding=4)
|
||||
|
||||
metadata = _prepare_attn_metadata(
|
||||
state, monkeypatch, input_batch, cudagraph_mode=CUDAGraphMode.FULL
|
||||
)
|
||||
|
||||
assert metadata.num_decode_draft_tokens_cpu.tolist() == [0, 0, -1, -1]
|
||||
|
||||
|
||||
def test_rows_wider_than_the_speculative_state_window_keep_the_sentinel(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=7)
|
||||
input_batch = _input_batch([12, 8, 1], None, [False, False, False])
|
||||
|
||||
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
|
||||
|
||||
assert metadata.num_decode_draft_tokens_cpu.tolist() == [-1, 0, 0]
|
||||
|
||||
|
||||
def test_chunked_prefill_tail_of_two_or_three_tokens_keeps_the_sentinel(
|
||||
monkeypatch,
|
||||
):
|
||||
"""A prefill continuation is excluded by `is_prefilling`, not by its token
|
||||
count, so tails wider than one token are covered by the same rule."""
|
||||
state = _mamba_hybrid_state(num_speculative_tokens=3)
|
||||
input_batch = _input_batch([2, 3], [0, 0], [True, True])
|
||||
|
||||
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
|
||||
|
||||
assert metadata.num_decode_draft_tokens_cpu.tolist() == [-1, -1]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
|
||||
@pytest.mark.parametrize(("num_sampled", "expected_value"), [(0, 1), (3, 3)])
|
||||
def test_postprocess_state_scalar_with_int32_mapping(
|
||||
num_sampled: int, expected_value: int
|
||||
) -> None:
|
||||
state = object.__new__(MambaHybridModelState)
|
||||
state.num_accepted_tokens_gpu = torch.full(
|
||||
(4,), 9, dtype=torch.int32, device="cuda"
|
||||
)
|
||||
state._align_mode = False
|
||||
state.recoverssm = None
|
||||
state._mamba_ctx = None
|
||||
idx_mapping = torch.tensor([2, -1, 0], dtype=torch.int32, device="cuda")
|
||||
|
||||
state.postprocess_state(idx_mapping, num_sampled)
|
||||
|
||||
expected = torch.tensor(
|
||||
[expected_value, 9, expected_value, 9], dtype=torch.int32, device="cuda"
|
||||
)
|
||||
torch.testing.assert_close(state.num_accepted_tokens_gpu, expected)
|
||||
|
||||
|
||||
def test_recoverssm_commits_accepted_window_after_v2_sampling() -> None:
|
||||
state = RecoverSSMState()
|
||||
metadata = Mock(spec=RecoverSSMMetadata)
|
||||
metadata.commit_recoverssm_state.return_value = None
|
||||
num_sampled = torch.tensor([3, 1], dtype=torch.int32)
|
||||
idx_mapping = torch.tensor([0, 1], dtype=torch.int32)
|
||||
num_accepted_tokens = torch.ones(2, dtype=torch.int32)
|
||||
group = SimpleNamespace(layer_names=["layer"])
|
||||
|
||||
state.record_step({"layer": metadata}, [[group]], for_capture=False)
|
||||
state.commit_step(
|
||||
num_sampled,
|
||||
idx_mapping,
|
||||
state_indices=None,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
)
|
||||
state.commit_step(
|
||||
num_sampled,
|
||||
idx_mapping,
|
||||
state_indices=None,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
)
|
||||
|
||||
metadata.commit_recoverssm_state.assert_called_once_with(num_sampled)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
|
||||
@pytest.mark.parametrize(
|
||||
("computed", "sampled", "expected_column"),
|
||||
[(4, 3, 0), (4, 4, 0), (4, 5, 1), (8, 8, 1), (8, 9, 2)],
|
||||
)
|
||||
def test_recoverssm_align_tracks_mixed_batch_state_and_neutralizes_copy_bias(
|
||||
computed: int, sampled: int, expected_column: int
|
||||
) -> None:
|
||||
state = object.__new__(MambaHybridModelState)
|
||||
state._align_mode = True
|
||||
state._mamba_ctx = None
|
||||
state._mamba_state_idx_gpu = torch.full((5,), -1, dtype=torch.int32, device="cuda")
|
||||
state.recoverssm = RecoverSSMState()
|
||||
state.num_accepted_tokens_gpu = torch.full(
|
||||
(5,), 9, dtype=torch.int32, device="cuda"
|
||||
)
|
||||
metadata = Mock(spec=RecoverSSMMetadata)
|
||||
metadata.commit_recoverssm_state.return_value = RecoverSSMPostprocessMetadata(
|
||||
num_spec_decodes=1,
|
||||
request_indices=torch.tensor([1], dtype=torch.int32, device="cuda"),
|
||||
num_computed_tokens=torch.tensor(
|
||||
[6, computed], dtype=torch.int32, device="cuda"
|
||||
),
|
||||
block_size=8,
|
||||
block_table=torch.zeros((2, 4), dtype=torch.int32, device="cuda"),
|
||||
)
|
||||
num_sampled = torch.tensor([2, sampled], dtype=torch.int32, device="cuda")
|
||||
idx_mapping = torch.tensor([3, 1], dtype=torch.int32, device="cuda")
|
||||
group = SimpleNamespace(layer_names=["layer"])
|
||||
|
||||
state.recoverssm.record_step({"layer": metadata}, [[group]], for_capture=False)
|
||||
|
||||
state.postprocess_state(idx_mapping, num_sampled)
|
||||
|
||||
expected_state_indices = [-1, expected_column, -1, -1, -1]
|
||||
assert state._mamba_state_idx_gpu.tolist() == expected_state_indices
|
||||
expected_accepted = [9, 1, 9, 2, 9]
|
||||
assert state.num_accepted_tokens_gpu.tolist() == expected_accepted
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,153 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for the Model Runner V2 prompt-embeds overlay (PromptEmbedsState).
|
||||
|
||||
The overlay kernel reads each request's GPU-resident prompt embeddings through
|
||||
a per-request pointer table and writes the rows scheduled this step into
|
||||
`inputs_embeds`, honoring chunked prefill (`num_computed_tokens` offset), the
|
||||
prompt/decode boundary (rows past the embeds length untouched), and the
|
||||
mixed-mode `prompt_is_token_ids` mask (token-id rows keep the base embedding).
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
pytest.importorskip("triton")
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not (current_platform.is_cuda_alike() or current_platform.is_xpu()):
|
||||
pytest.skip(
|
||||
"An accelerator is required for prompt-embeds overlay tests",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm.v1.worker.gpu.model_states.prompt_embeds import PromptEmbedsState
|
||||
|
||||
HIDDEN = 24
|
||||
MAX_NUM_REQS = 8
|
||||
DEVICE = torch.device(current_platform.device_type)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _NewReqData:
|
||||
req_id: str
|
||||
prompt_embeds: torch.Tensor | None
|
||||
prompt_is_token_ids: list[bool] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Batch:
|
||||
num_reqs: int
|
||||
num_scheduled_tokens: torch.Tensor # np-like, only .max() is used
|
||||
idx_mapping: torch.Tensor
|
||||
query_start_loc: torch.Tensor
|
||||
|
||||
|
||||
def _make_state() -> PromptEmbedsState:
|
||||
return PromptEmbedsState(MAX_NUM_REQS, HIDDEN, torch.float32, DEVICE)
|
||||
|
||||
|
||||
def _batch(num_scheduled: list[int], idx_mapping: list[int]) -> _Batch:
|
||||
query_start_loc = [0]
|
||||
for n in num_scheduled:
|
||||
query_start_loc.append(query_start_loc[-1] + n)
|
||||
return _Batch(
|
||||
num_reqs=len(num_scheduled),
|
||||
num_scheduled_tokens=torch.tensor(num_scheduled, dtype=torch.int32),
|
||||
idx_mapping=torch.tensor(idx_mapping, dtype=torch.int64, device=DEVICE),
|
||||
query_start_loc=torch.tensor(query_start_loc, dtype=torch.int32, device=DEVICE),
|
||||
)
|
||||
|
||||
|
||||
def _apply(
|
||||
state: PromptEmbedsState,
|
||||
batch: _Batch,
|
||||
num_computed: list[int],
|
||||
num_tokens: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Run the overlay on a fresh base buffer; return (result, base)."""
|
||||
num_computed_tokens = torch.zeros(MAX_NUM_REQS, dtype=torch.int32, device=DEVICE)
|
||||
for batch_idx, req_index in enumerate(batch.idx_mapping.tolist()):
|
||||
num_computed_tokens[req_index] = num_computed[batch_idx]
|
||||
base = torch.randn(num_tokens, HIDDEN, dtype=torch.float32, device=DEVICE)
|
||||
inputs_embeds = base.clone()
|
||||
state.apply(batch, num_computed_tokens, inputs_embeds)
|
||||
torch.accelerator.synchronize()
|
||||
return inputs_embeds, base
|
||||
|
||||
|
||||
def test_overlay_chunked_prefill_and_decode():
|
||||
"""Rows within the embeds range come from prompt_embeds at the
|
||||
num_computed offset; requests without embeds and requests past their
|
||||
embeds length (decode) keep the base embedding."""
|
||||
state = _make_state()
|
||||
embeds_a = torch.randn(6, HIDDEN, dtype=torch.float32)
|
||||
embeds_b = torch.randn(5, HIDDEN, dtype=torch.float32)
|
||||
state.add_request(0, _NewReqData("a", embeds_a))
|
||||
state.add_request(1, _NewReqData("b", embeds_b))
|
||||
state.add_request(2, _NewReqData("c", None))
|
||||
state.apply_staged_writes()
|
||||
|
||||
# a: chunk [2, 6) of its embeds; b: fully decoded; c: no embeds.
|
||||
batch = _batch(num_scheduled=[4, 1, 3], idx_mapping=[0, 1, 2])
|
||||
out, base = _apply(state, batch, num_computed=[2, 7, 1], num_tokens=8)
|
||||
|
||||
torch.testing.assert_close(out[0:4], embeds_a[2:6].to(DEVICE))
|
||||
torch.testing.assert_close(out[4:8], base[4:8])
|
||||
|
||||
|
||||
def test_overlay_clamps_to_embeds_length():
|
||||
"""A window straddling the end of the prompt embeds writes only the
|
||||
in-range rows (e.g. final prefill chunk + sampled token)."""
|
||||
state = _make_state()
|
||||
embeds = torch.randn(4, HIDDEN, dtype=torch.float32)
|
||||
state.add_request(3, _NewReqData("a", embeds))
|
||||
state.apply_staged_writes()
|
||||
|
||||
batch = _batch(num_scheduled=[3], idx_mapping=[3])
|
||||
out, base = _apply(state, batch, num_computed=[2], num_tokens=3)
|
||||
|
||||
torch.testing.assert_close(out[0:2], embeds[2:4].to(DEVICE))
|
||||
torch.testing.assert_close(out[2:3], base[2:3])
|
||||
|
||||
|
||||
def test_overlay_respects_is_token_ids_mask():
|
||||
"""Mixed mode: positions marked as real token ids keep the base
|
||||
embedding; only embed positions are overwritten."""
|
||||
state = _make_state()
|
||||
embeds = torch.randn(5, HIDDEN, dtype=torch.float32)
|
||||
is_token_ids = [True, False, False, True, False]
|
||||
state.add_request(0, _NewReqData("a", embeds, is_token_ids))
|
||||
state.apply_staged_writes()
|
||||
|
||||
batch = _batch(num_scheduled=[5], idx_mapping=[0])
|
||||
out, base = _apply(state, batch, num_computed=[0], num_tokens=5)
|
||||
|
||||
embeds_gpu = embeds.to(DEVICE)
|
||||
for pos, is_token in enumerate(is_token_ids):
|
||||
expected = base[pos] if is_token else embeds_gpu[pos]
|
||||
torch.testing.assert_close(out[pos], expected)
|
||||
|
||||
|
||||
def test_index_reuse_clears_stale_entry():
|
||||
"""A request added at a previously-used index without embeds must not
|
||||
inherit the prior occupant's pointer-table entry."""
|
||||
state = _make_state()
|
||||
state.add_request(0, _NewReqData("a", torch.randn(4, HIDDEN, dtype=torch.float32)))
|
||||
# A second live embeds request so the kernel actually launches (the
|
||||
# overlay is skipped entirely when no request holds embeds).
|
||||
other = torch.randn(2, HIDDEN, dtype=torch.float32)
|
||||
state.add_request(1, _NewReqData("other", other))
|
||||
state.apply_staged_writes()
|
||||
state.remove_request("a")
|
||||
state.add_request(0, _NewReqData("b", None))
|
||||
state.apply_staged_writes()
|
||||
|
||||
batch = _batch(num_scheduled=[2, 2], idx_mapping=[0, 1])
|
||||
out, base = _apply(state, batch, num_computed=[0, 0], num_tokens=4)
|
||||
|
||||
torch.testing.assert_close(out[0:2], base[0:2])
|
||||
torch.testing.assert_close(out[2:4], other.to(DEVICE))
|
||||
@@ -1,298 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import importlib
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.model_executor.model_loader.mtp_validation import (
|
||||
disable_mtp_completeness_check,
|
||||
)
|
||||
from vllm.model_executor.models.utils import (
|
||||
PPMissingLayer,
|
||||
spec_decode_needs_target_embed,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle import utils as eagle_utils
|
||||
|
||||
VOCAB, HIDDEN = 32, 8
|
||||
|
||||
|
||||
def _fake_pp(world_size: int, is_last_rank: bool = True):
|
||||
return lambda: SimpleNamespace(
|
||||
world_size=world_size,
|
||||
is_last_rank=is_last_rank,
|
||||
is_first_rank=world_size == 1,
|
||||
)
|
||||
|
||||
|
||||
def _inner(embed: nn.Module | None) -> nn.Module:
|
||||
inner = nn.Module()
|
||||
if embed is not None:
|
||||
inner.embed_tokens = embed
|
||||
return inner
|
||||
|
||||
|
||||
def _embed(fill: float | None = None) -> nn.Embedding:
|
||||
embed = nn.Embedding(VOCAB, HIDDEN)
|
||||
if fill is not None:
|
||||
with torch.no_grad():
|
||||
embed.weight.fill_(fill)
|
||||
return embed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("draft_embed", ["loaded", "unset"])
|
||||
def test_drafter_without_own_embedding_gets_the_targets(monkeypatch, draft_embed):
|
||||
monkeypatch.setattr(eagle_utils, "get_pp_group", _fake_pp(2))
|
||||
target_embed = _embed()
|
||||
draft_inner = _inner(_embed() if draft_embed == "loaded" else None)
|
||||
if draft_embed == "unset":
|
||||
draft_inner.embed_tokens = None
|
||||
draft = SimpleNamespace(has_own_embed_tokens=False)
|
||||
|
||||
eagle_utils.maybe_share_target_embed(draft, draft_inner, _inner(target_embed))
|
||||
|
||||
assert draft_inner.embed_tokens is target_embed
|
||||
|
||||
|
||||
def test_missing_target_embedding_raises_instead_of_running_on_garbage(monkeypatch):
|
||||
monkeypatch.setattr(eagle_utils, "get_pp_group", _fake_pp(2))
|
||||
draft_inner = _inner(_embed())
|
||||
draft = SimpleNamespace(has_own_embed_tokens=False)
|
||||
|
||||
with pytest.raises(RuntimeError, match="needs the target input embedding"):
|
||||
eagle_utils.maybe_share_target_embed(
|
||||
draft, draft_inner, _inner(PPMissingLayer())
|
||||
)
|
||||
|
||||
|
||||
def test_drafter_with_distinct_weights_keeps_them(monkeypatch):
|
||||
monkeypatch.setattr(eagle_utils, "get_pp_group", _fake_pp(2))
|
||||
draft_embed = _embed(fill=1.0)
|
||||
draft_inner = _inner(draft_embed)
|
||||
draft = SimpleNamespace(has_own_embed_tokens=True)
|
||||
|
||||
eagle_utils.maybe_share_target_embed(draft, draft_inner, _inner(_embed(fill=2.0)))
|
||||
|
||||
assert draft_inner.embed_tokens is draft_embed
|
||||
|
||||
|
||||
def test_mtp_style_drafter_is_left_alone_under_pp(monkeypatch):
|
||||
monkeypatch.setattr(eagle_utils, "get_pp_group", _fake_pp(2))
|
||||
draft_embed = _embed()
|
||||
draft_inner = _inner(draft_embed)
|
||||
|
||||
eagle_utils.maybe_share_target_embed(nn.Module(), draft_inner, _inner(_embed()))
|
||||
|
||||
assert draft_inner.embed_tokens is draft_embed
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method,pp_size,is_last_rank,expected",
|
||||
[
|
||||
("eagle", 2, True, True),
|
||||
("eagle3", 2, True, True),
|
||||
("dflash", 2, True, True),
|
||||
("dspark", 2, True, True),
|
||||
("eagle3", 1, True, False),
|
||||
("eagle3", 2, False, False),
|
||||
("mtp", 2, True, False),
|
||||
(None, 2, True, False),
|
||||
],
|
||||
)
|
||||
def test_target_embedding_provisioning(
|
||||
monkeypatch, method, pp_size, is_last_rank, expected
|
||||
):
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.parallel_state.get_pp_group",
|
||||
_fake_pp(pp_size, is_last_rank),
|
||||
raising=True,
|
||||
)
|
||||
speculative_config = None if method is None else SimpleNamespace(method=method)
|
||||
config = SimpleNamespace(speculative_config=speculative_config)
|
||||
assert spec_decode_needs_target_embed(config) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pp_size,is_last_rank,expected",
|
||||
[(2, True, True), (2, False, False), (1, True, False)],
|
||||
)
|
||||
def test_mtp_target_embedding_requires_model_opt_in(
|
||||
monkeypatch, pp_size, is_last_rank, expected
|
||||
):
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.parallel_state.get_pp_group",
|
||||
_fake_pp(pp_size, is_last_rank),
|
||||
)
|
||||
config = SimpleNamespace(speculative_config=SimpleNamespace(method="mtp"))
|
||||
assert spec_decode_needs_target_embed(config, include_mtp=True) is expected
|
||||
assert not spec_decode_needs_target_embed(config)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def m3_modules():
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("M3 model imports require CUDA or ROCm dependencies")
|
||||
backend = "amd" if current_platform.is_rocm() else "nvidia"
|
||||
root = f"vllm.models.minimax_m3.{backend}"
|
||||
return importlib.import_module(f"{root}.mtp"), importlib.import_module(
|
||||
f"{root}.model"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def m3_config():
|
||||
hf_config = SimpleNamespace(
|
||||
vocab_size=VOCAB,
|
||||
hidden_size=HIDDEN,
|
||||
num_local_experts=0,
|
||||
num_hidden_layers=0,
|
||||
rms_norm_eps=1e-5,
|
||||
)
|
||||
return SimpleNamespace(
|
||||
use_v2_model_runner=True,
|
||||
load_config=SimpleNamespace(load_format="auto"),
|
||||
model_config=SimpleNamespace(hf_text_config=hf_config),
|
||||
speculative_config=SimpleNamespace(
|
||||
method="mtp", draft_model_config=SimpleNamespace(hf_config=hf_config)
|
||||
),
|
||||
quant_config=None,
|
||||
cache_config=None,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_m3_draft(monkeypatch, m3_modules, m3_config):
|
||||
mtp, _ = m3_modules
|
||||
inner = _inner(_embed())
|
||||
inner.layers = nn.ModuleDict({"0": nn.Linear(1, 1, bias=False)})
|
||||
inner.num_mtp_layers = 1
|
||||
monkeypatch.setattr(mtp, "MiniMaxM3MultiTokenPredictor", lambda **_: inner)
|
||||
monkeypatch.setattr(mtp, "ParallelLMHead", lambda *_, **kw: _embed())
|
||||
monkeypatch.setattr(mtp, "LogitsProcessor", lambda *_: None)
|
||||
monkeypatch.setattr(
|
||||
mtp, "fused_moe_make_expert_params_mapping", lambda *_, **kw: []
|
||||
)
|
||||
monkeypatch.setattr(mtp, "get_pp_group", _fake_pp(2))
|
||||
monkeypatch.setattr(eagle_utils, "get_pp_group", _fake_pp(2))
|
||||
return lambda: mtp.MiniMaxM3MTP(vllm_config=m3_config)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"key",
|
||||
[None, "model.embed_tokens.weight", "language_model.model.embed_tokens.weight"],
|
||||
)
|
||||
def test_m3_checkpoint_embedding_ownership(make_m3_draft, key):
|
||||
"""Actual M3 loading determines sharing and survives an unrelated reload."""
|
||||
draft = make_m3_draft()
|
||||
assert draft.has_own_embed_tokens
|
||||
weights = [("model.mtp.layers.0.weight", torch.ones(1, 1))]
|
||||
if key is not None:
|
||||
weights.append((key, torch.ones(VOCAB, HIDDEN)))
|
||||
loaded = draft.load_weights(weights)
|
||||
assert ("model.embed_tokens.weight" in loaded) is (key is not None)
|
||||
with disable_mtp_completeness_check():
|
||||
draft.load_weights([("lm_head.weight", torch.zeros(VOCAB, HIDDEN))])
|
||||
assert draft.has_own_embed_tokens is (key is not None)
|
||||
target = _inner(_embed(fill=2.0))
|
||||
original = draft.model.embed_tokens
|
||||
eagle_utils.maybe_share_target_embed(draft, draft.model, target)
|
||||
if key is None:
|
||||
assert draft.model.embed_tokens is target.embed_tokens
|
||||
else:
|
||||
assert draft.model.embed_tokens is original
|
||||
torch.testing.assert_close(original.weight, torch.ones(VOCAB, HIDDEN))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"load_format", ["dummy", "sharded_state", "runai_streamer_sharded", "tensorizer"]
|
||||
)
|
||||
def test_m3_direct_loader_embedding_ownership(make_m3_draft, m3_config, load_format):
|
||||
"""Directly loaded embeddings survive transfers and share only when equal."""
|
||||
m3_config.load_config.load_format = load_format
|
||||
draft = make_m3_draft()
|
||||
draft.load_state_dict(
|
||||
{key: torch.ones_like(value) for key, value in draft.state_dict().items()}
|
||||
)
|
||||
with disable_mtp_completeness_check():
|
||||
draft.load_weights([("model.mtp.layers.0.weight", torch.zeros(1, 1))])
|
||||
target = _inner(_embed(fill=2.0))
|
||||
original = draft.model.embed_tokens
|
||||
eagle_utils.maybe_share_target_embed(draft, draft.model, target)
|
||||
assert draft.model.embed_tokens is (
|
||||
target.embed_tokens if load_format == "dummy" else original
|
||||
)
|
||||
if load_format != "dummy":
|
||||
equal_target = _inner(_embed(fill=1.0))
|
||||
eagle_utils.maybe_share_target_embed(draft, draft.model, equal_target)
|
||||
assert draft.model.embed_tokens is equal_target.embed_tokens
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_v2,pp_size", [(True, 1), (False, 1), (False, 2)])
|
||||
def test_m3_preserves_legacy_embedding_sharing(
|
||||
monkeypatch, m3_modules, m3_config, make_m3_draft, use_v2, pp_size
|
||||
):
|
||||
mtp, _ = m3_modules
|
||||
m3_config.use_v2_model_runner = use_v2
|
||||
monkeypatch.setattr(mtp, "get_pp_group", _fake_pp(pp_size))
|
||||
draft = make_m3_draft()
|
||||
draft.load_weights(
|
||||
[
|
||||
("model.mtp.layers.0.weight", torch.ones(1, 1)),
|
||||
("model.embed_tokens.weight", torch.ones(VOCAB, HIDDEN)),
|
||||
]
|
||||
)
|
||||
assert not hasattr(draft, "has_own_embed_tokens")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rank,use_v2,method,expected",
|
||||
[
|
||||
(0, True, "mtp", True),
|
||||
(1, True, "mtp", False),
|
||||
(2, True, "mtp", True),
|
||||
(2, False, "mtp", False),
|
||||
(2, True, None, False),
|
||||
],
|
||||
)
|
||||
def test_m3_target_allocates_embedding_on_required_stage(
|
||||
monkeypatch, m3_modules, m3_config, rank, use_v2, method, expected
|
||||
):
|
||||
_, model = m3_modules
|
||||
pp = lambda: SimpleNamespace(
|
||||
world_size=3, is_first_rank=rank == 0, is_last_rank=rank == 2
|
||||
)
|
||||
monkeypatch.setattr(model, "get_pp_group", pp)
|
||||
monkeypatch.setattr("vllm.distributed.parallel_state.get_pp_group", pp)
|
||||
monkeypatch.setattr(model, "VocabParallelEmbedding", lambda *_, **kw: _embed())
|
||||
monkeypatch.setattr(model, "make_layers", lambda *_, **kw: (0, 0, nn.ModuleList()))
|
||||
monkeypatch.setattr(model, "MiniMAXGemmaRMSNorm", lambda *_, **kw: nn.Identity())
|
||||
m3_config.use_v2_model_runner = use_v2
|
||||
if method is None:
|
||||
m3_config.speculative_config = None
|
||||
target = model.MiniMaxM3Model(vllm_config=m3_config)
|
||||
assert isinstance(target.embed_tokens, nn.Embedding) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("initial_embed", [False, True])
|
||||
def test_m3_weight_transfer_updates_embedding_ownership(make_m3_draft, initial_embed):
|
||||
"""Layer transfers retain ownership; newly loaded embeddings become owned."""
|
||||
draft = make_m3_draft()
|
||||
weights = [("model.mtp.layers.0.weight", torch.ones(1, 1))]
|
||||
if initial_embed:
|
||||
weights.append(("model.embed_tokens.weight", torch.ones(VOCAB, HIDDEN)))
|
||||
draft.load_weights(weights)
|
||||
with disable_mtp_completeness_check():
|
||||
draft.load_weights([("model.mtp.layers.0.weight", torch.zeros(1, 1))])
|
||||
assert draft.has_own_embed_tokens is initial_embed
|
||||
draft.load_weights(
|
||||
[("model.embed_tokens.weight", torch.full((VOCAB, HIDDEN), 3.0))]
|
||||
)
|
||||
assert draft.has_own_embed_tokens
|
||||
target = _inner(_embed(fill=2.0))
|
||||
original = draft.model.embed_tokens
|
||||
eagle_utils.maybe_share_target_embed(draft, draft.model, target)
|
||||
assert draft.model.embed_tokens is original
|
||||
torch.testing.assert_close(original.weight, torch.full((VOCAB, HIDDEN), 3.0))
|
||||
@@ -1,80 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import threading
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm.v1.worker import ubatching
|
||||
from vllm.v1.worker.ubatch_utils import maybe_create_ubatch_slices
|
||||
from vllm.v1.worker.ubatching import (
|
||||
dbo_current_ubatch_token_offset,
|
||||
make_ubatch_contexts,
|
||||
)
|
||||
|
||||
|
||||
def test_token_offset_without_dbo_context():
|
||||
assert dbo_current_ubatch_token_offset() == 0
|
||||
|
||||
|
||||
def test_token_offset_defaults_to_zero():
|
||||
ready_barrier = threading.Barrier(3)
|
||||
ctxs = make_ubatch_contexts(
|
||||
num_micro_batches=2,
|
||||
compute_stream=object(),
|
||||
comm_stream=object(),
|
||||
forward_contexts=[object(), object()],
|
||||
ready_barrier=ready_barrier,
|
||||
)
|
||||
assert [ctx.token_offset for ctx in ctxs] == [0, 0]
|
||||
|
||||
|
||||
def test_token_offset_per_ubatch_thread():
|
||||
compute_stream = object()
|
||||
ready_barrier = threading.Barrier(3)
|
||||
ctxs = make_ubatch_contexts(
|
||||
num_micro_batches=2,
|
||||
compute_stream=compute_stream,
|
||||
comm_stream=object(),
|
||||
forward_contexts=[object(), object()],
|
||||
ready_barrier=ready_barrier,
|
||||
token_offsets=[0, 7],
|
||||
)
|
||||
assert [ctx.token_offset for ctx in ctxs] == [0, 7]
|
||||
|
||||
offsets_seen: dict[int, int] = {}
|
||||
|
||||
def run(ctx: ubatching.UBatchContext) -> None:
|
||||
with ctx:
|
||||
offsets_seen[ctx.id] = dbo_current_ubatch_token_offset()
|
||||
|
||||
# Keep torch.cuda.set_stream out of the way. Patch once here rather than
|
||||
# per thread: a per-thread patch exit would restore the real function
|
||||
# while the other thread is still inside its context.
|
||||
with patch.object(ubatching, "current_stream", return_value=compute_stream):
|
||||
threads = [threading.Thread(target=run, args=(ctx,)) for ctx in ctxs]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
ready_barrier.wait()
|
||||
ctxs[0].cpu_wait_event.set()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
assert offsets_seen == {0: 0, 1: 7}
|
||||
|
||||
|
||||
def test_ubatch_slice_bounds_are_python_ints():
|
||||
# The last bound comes from np.cumsum; numpy scalars leaking into the
|
||||
# per-ubatch metadata break Triton argument specialization.
|
||||
ubatch_slices, ubatch_slices_padded = maybe_create_ubatch_slices(
|
||||
should_ubatch=True,
|
||||
num_scheduled_tokens=np.array([5, 9, 6], dtype=np.int32),
|
||||
num_tokens_padded=20,
|
||||
num_reqs_padded=3,
|
||||
num_ubatches=2,
|
||||
)
|
||||
for slices in (ubatch_slices, ubatch_slices_padded):
|
||||
assert slices is not None
|
||||
for s in slices:
|
||||
for bound in (s.token_slice.start, s.token_slice.stop):
|
||||
assert type(bound) is int
|
||||
@@ -1,85 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.v1.worker import worker_base
|
||||
from vllm.v1.worker.worker_base import WorkerBase, WorkerWrapperBase
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
|
||||
class ExtensionA:
|
||||
events: list[str]
|
||||
|
||||
def init_worker_extension(self):
|
||||
self.events.append("init-a")
|
||||
|
||||
def destroy_worker_extension(self):
|
||||
self.events.append("destroy-a")
|
||||
|
||||
|
||||
class ExtensionB: ...
|
||||
|
||||
|
||||
class FailingExtension:
|
||||
def destroy_worker_extension(self):
|
||||
raise RuntimeError("destroy failed")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_wrapper(monkeypatch):
|
||||
# Fresh worker class per test, since extension injection mutates its bases.
|
||||
class Worker(WorkerBase):
|
||||
def __init__(self, **_kwargs):
|
||||
self.events: list[str] = []
|
||||
|
||||
def init_device(self):
|
||||
self.events.append("device")
|
||||
|
||||
def shutdown(self):
|
||||
self.events.append("shutdown")
|
||||
|
||||
classes = {
|
||||
cls.__name__: cls for cls in (Worker, ExtensionA, ExtensionB, FailingExtension)
|
||||
}
|
||||
monkeypatch.setattr(worker_base, "resolve_obj_by_qualname", classes.__getitem__)
|
||||
monkeypatch.setattr(
|
||||
worker_base,
|
||||
"worker_receiver_cache_from_config",
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
|
||||
def make(extension: str) -> WorkerWrapperBase:
|
||||
config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(
|
||||
worker_cls="Worker", worker_extension_cls=extension
|
||||
),
|
||||
enable_trace_function_call_for_thread=lambda: None,
|
||||
)
|
||||
wrapper = WorkerWrapperBase()
|
||||
wrapper.init_worker([{"vllm_config": config}])
|
||||
wrapper.init_device()
|
||||
return wrapper
|
||||
|
||||
return make
|
||||
|
||||
|
||||
def test_worker_extension_hooks_follow_configured_class(make_wrapper):
|
||||
for extension, expected in (
|
||||
("ExtensionA", ["device", "init-a", "destroy-a", "shutdown"]),
|
||||
("ExtensionB", ["device", "shutdown"]),
|
||||
("ExtensionA", ["device", "init-a", "destroy-a", "shutdown"]),
|
||||
):
|
||||
wrapper = make_wrapper(extension)
|
||||
wrapper.shutdown()
|
||||
assert wrapper.worker.events == expected
|
||||
|
||||
|
||||
def test_failing_destroy_hook_is_logged_not_raised(make_wrapper, caplog_vllm):
|
||||
wrapper = make_wrapper("FailingExtension")
|
||||
wrapper.shutdown()
|
||||
assert wrapper.worker.events == ["device", "shutdown"]
|
||||
assert "Worker extension destroy hook failed" in caplog_vllm.text
|
||||
@@ -1,212 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import tempfile
|
||||
from multiprocessing.queues import Queue
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.mem_utils import MemorySnapshot
|
||||
from vllm.v1.worker.gpu_worker import Worker, init_worker_distributed_environment
|
||||
|
||||
# Global queue to track operation order across processes
|
||||
_QUEUE: Queue | None = None
|
||||
|
||||
|
||||
def track_operation(operation: str, rank: int):
|
||||
"""Track when an operation happens and its rank."""
|
||||
if _QUEUE is not None:
|
||||
_QUEUE.put((operation, rank))
|
||||
|
||||
|
||||
def make_operation_tracker(operation_name: str, original_func):
|
||||
"""Create a mock function that tracks when an operation is called.
|
||||
|
||||
Args:
|
||||
operation_name: Name to use when tracking this operation
|
||||
original_func: The original function to wrap
|
||||
|
||||
Returns:
|
||||
A wrapper function that tracks the operation and calls the original
|
||||
|
||||
"""
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
rank = int(os.environ.get("RANK", "-1"))
|
||||
track_operation(operation_name, rank)
|
||||
return original_func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def worker_process(
|
||||
rank: int,
|
||||
world_size: int,
|
||||
distributed_init_method: str,
|
||||
queue: Queue,
|
||||
error_queue: Queue,
|
||||
):
|
||||
"""Worker process that initializes a GPU worker with proper tracking."""
|
||||
global _QUEUE
|
||||
_QUEUE = queue
|
||||
|
||||
try:
|
||||
# Set environment variables
|
||||
os.environ["RANK"] = str(rank)
|
||||
os.environ["LOCAL_RANK"] = str(rank)
|
||||
os.environ["WORLD_SIZE"] = str(world_size)
|
||||
|
||||
# Create vLLM config with small model
|
||||
vllm_config = EngineArgs(
|
||||
model="facebook/opt-125m", tensor_parallel_size=2, load_format="dummy"
|
||||
).create_engine_config()
|
||||
|
||||
# Select worker class and patch target based on platform
|
||||
if current_platform.is_xpu():
|
||||
from vllm.v1.worker.xpu_worker import XPUWorker
|
||||
|
||||
worker_cls = XPUWorker
|
||||
init_patch_target = (
|
||||
"vllm.v1.worker.xpu_worker.init_worker_distributed_environment"
|
||||
)
|
||||
else:
|
||||
worker_cls = Worker
|
||||
init_patch_target = (
|
||||
"vllm.v1.worker.gpu_worker.init_worker_distributed_environment"
|
||||
)
|
||||
|
||||
# Create worker
|
||||
worker = worker_cls(
|
||||
vllm_config=vllm_config,
|
||||
local_rank=rank,
|
||||
rank=rank,
|
||||
distributed_init_method=distributed_init_method,
|
||||
)
|
||||
|
||||
# Get original functions before patching
|
||||
original_init_worker = init_worker_distributed_environment
|
||||
original_memory_snapshot_init = MemorySnapshot.__init__
|
||||
original_all_reduce = torch.distributed.all_reduce
|
||||
|
||||
# Apply minimal patches to track operation order
|
||||
init_patch = patch(
|
||||
init_patch_target,
|
||||
side_effect=make_operation_tracker(
|
||||
"init_distributed", original_init_worker
|
||||
),
|
||||
)
|
||||
memory_patch = patch.object(
|
||||
MemorySnapshot,
|
||||
"__init__",
|
||||
make_operation_tracker("memory_snapshot", original_memory_snapshot_init),
|
||||
)
|
||||
all_reduce_patch = patch(
|
||||
"torch.distributed.all_reduce",
|
||||
side_effect=make_operation_tracker("dist_all_reduce", original_all_reduce),
|
||||
)
|
||||
|
||||
with (
|
||||
init_patch,
|
||||
memory_patch,
|
||||
all_reduce_patch,
|
||||
set_current_vllm_config(vllm_config),
|
||||
):
|
||||
# Initialize device (this is where we test the order)
|
||||
worker.init_device()
|
||||
|
||||
# Load model to ensure everything works
|
||||
worker.load_model()
|
||||
|
||||
# Signal success
|
||||
queue.put(("success", rank))
|
||||
|
||||
except Exception as e:
|
||||
error_queue.put((rank, str(e), type(e).__name__))
|
||||
raise
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
torch.accelerator.device_count() < 2,
|
||||
reason="Need at least 2 GPUs for tensor parallelism",
|
||||
)
|
||||
def test_init_distributed_is_called_before_memory_snapshot():
|
||||
"""Test that distributed env is setup before memory snapshot.
|
||||
|
||||
This test makes sure during worker initialization, the initial memory
|
||||
snapshot is taken after distributed env is setup to include all the buffers
|
||||
allocated by distributed env.
|
||||
"""
|
||||
world_size = 2
|
||||
|
||||
# Create a temporary file for distributed init
|
||||
with tempfile.NamedTemporaryFile(delete=False) as f:
|
||||
distributed_init_method = f"file://{f.name}"
|
||||
|
||||
# Create queues for inter-process communication
|
||||
ctx = mp.get_context("spawn")
|
||||
operation_queue = ctx.Queue()
|
||||
error_queue = ctx.Queue()
|
||||
|
||||
# Start worker processes
|
||||
processes = []
|
||||
for rank in range(world_size):
|
||||
p = ctx.Process(
|
||||
target=worker_process,
|
||||
args=(
|
||||
rank,
|
||||
world_size,
|
||||
distributed_init_method,
|
||||
operation_queue,
|
||||
error_queue,
|
||||
),
|
||||
)
|
||||
p.start()
|
||||
processes.append(p)
|
||||
|
||||
# Wait for all processes to complete
|
||||
for p in processes:
|
||||
p.join(timeout=60) # 60 second timeout
|
||||
|
||||
# Check for errors
|
||||
errors = []
|
||||
while not error_queue.empty():
|
||||
rank, error_msg, error_type = error_queue.get()
|
||||
errors.append(f"Rank {rank}: {error_type}: {error_msg}")
|
||||
|
||||
if errors:
|
||||
pytest.fail("Worker processes failed:\n" + "\n".join(errors))
|
||||
|
||||
# Collect all operations from the queue
|
||||
operations = []
|
||||
while not operation_queue.empty():
|
||||
operations.append(operation_queue.get())
|
||||
|
||||
# Verify we got operations from both ranks
|
||||
print(f"Collected operations: {operations}")
|
||||
|
||||
# Check operations for each rank
|
||||
for rank in range(world_size):
|
||||
rank_ops = [op for op, r in operations if r == rank]
|
||||
print(f"\nRank {rank} operations: {rank_ops}")
|
||||
|
||||
# Raises ValueError if the operation is not found
|
||||
init_distributed = rank_ops.index("init_distributed")
|
||||
dist_all_reduce = rank_ops.index("dist_all_reduce")
|
||||
memory_snapshot = rank_ops.index("memory_snapshot")
|
||||
|
||||
# Verify order: init_distributed should happen before memory_snapshot
|
||||
assert init_distributed < dist_all_reduce < memory_snapshot, (
|
||||
f"Rank {rank}: init_distributed (index {init_distributed}) "
|
||||
f"must happen before dist_all_reduce (index {dist_all_reduce}) "
|
||||
f"and memory_snapshot (index {memory_snapshot})"
|
||||
)
|
||||
|
||||
# Clean up
|
||||
os.unlink(distributed_init_method.replace("file://", ""))
|
||||
@@ -1,46 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Unit tests for ``vllm.v1.worker.xpu_model_runner`` (XPU worker / CUDA shims)."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch._dynamo.variables.torch import TorchInGraphFunctionVariable
|
||||
|
||||
from vllm.v1.worker.xpu_model_runner import _torch_cuda_wrapper
|
||||
|
||||
# XPU-only: needs distinct torch.cuda vs torch.xpu current_stream symbols.
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not hasattr(torch, "xpu") or not hasattr(torch.xpu, "current_stream"),
|
||||
reason="torch.xpu.current_stream is required",
|
||||
)
|
||||
|
||||
|
||||
# Child process: patched torch.cuda must not leak to other tests in the session.
|
||||
@pytest.mark.forked
|
||||
def test_torch_cuda_wrapper_allows_dynamo_handler_registration() -> None:
|
||||
"""Guard against XPU CUDA shim breaking Torch Dynamo during AOT compile.
|
||||
|
||||
Before the fix, ``_torch_cuda_wrapper`` assigned
|
||||
``torch.cuda.current_stream = torch.xpu.current_stream`` (same function object).
|
||||
On the first AOT/profile run, Dynamo builds its in-graph handler table and
|
||||
registers ``torch.cuda.current_stream`` and ``torch.xpu.current_stream``
|
||||
separately; duplicate identity triggers::
|
||||
|
||||
AssertionError: Handler already registered for <function current_stream ...>
|
||||
|
||||
That surfaced as EngineCore failing in ``profile_run`` / ``_get_handlers()``.
|
||||
The fix uses distinct shim callables so both can be registered.
|
||||
|
||||
This test replays the post-init state (wrapper applied, patches left on
|
||||
``torch.cuda``) and checks that Dynamo's real ``_get_handlers()`` succeeds.
|
||||
"""
|
||||
# Same entry point as XPUModelRunner.__init__ (patches persist after exit).
|
||||
with _torch_cuda_wrapper():
|
||||
pass
|
||||
|
||||
# Fresh handler table build, as on first torch.compile / AOT in the worker.
|
||||
# Registers torch.cuda.current_stream and torch.xpu.current_stream separately;
|
||||
# if they are the same object (pre-fix alias), raises Handler already registered.
|
||||
TorchInGraphFunctionVariable._get_handlers.cache_clear()
|
||||
TorchInGraphFunctionVariable._get_handlers()
|
||||
Reference in New Issue
Block a user