Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-16 20:33:18 +09:00
117 changed files with 6209 additions and 995 deletions
+3
View File
@@ -215,6 +215,9 @@ def test_cache_config_hash_ignores_kv_cache_sizing_knobs():
base_hash = CacheConfig().compute_hash()
assert CacheConfig(kv_cache_memory_bytes=1 << 30).compute_hash() == base_hash
assert CacheConfig(gpu_memory_utilization=0.5).compute_hash() == base_hash
config = CacheConfig()
config.effective_attention_block_size = 64
assert config.compute_hash() == base_hash
def test_scheduler_config_hash_includes_max_num_seqs():
+32 -3
View File
@@ -694,14 +694,43 @@ def test_check_shm_free_space_raises_when_insufficient(tmp_path):
def test_check_shm_free_space_passes_when_sufficient(tmp_path):
with mock.patch.object(
shm_broadcast.shutil, "disk_usage", return_value=_fake_disk_usage(512 << 20)
with (
mock.patch.object(
shm_broadcast.shutil,
"disk_usage",
return_value=_fake_disk_usage(512 << 20),
),
mock.patch.object(shm_broadcast, "check_cgroup_memory_available"),
):
check_shm_free_space(240 << 20, shm_path=str(tmp_path))
def test_check_shm_free_space_skipped_when_path_missing(tmp_path):
check_shm_free_space(1 << 60, shm_path=str(tmp_path / "does-not-exist"))
with mock.patch.object(shm_broadcast, "check_cgroup_memory_available"):
check_shm_free_space(1 << 60, shm_path=str(tmp_path / "does-not-exist"))
def test_check_shm_free_space_checks_cgroup(tmp_path):
with (
mock.patch.object(
shm_broadcast.shutil,
"disk_usage",
return_value=_fake_disk_usage(512 << 20),
),
mock.patch.object(
shm_broadcast, "check_cgroup_memory_available"
) as check_cgroup,
):
check_shm_free_space(
240 << 20,
shm_path=str(tmp_path),
allocation_name="SHM mmap",
)
check_cgroup.assert_called_once_with(
240 << 20,
"SHM mmap",
)
def test_shm_ring_buffer_creation_checks_free_space():
@@ -948,7 +948,7 @@ def test_structured_output_batched_with_non_structured_outputs_requests(
prompts = [structured_outputs_prompt, non_structured_outputs_prompt]
sampling_params = [
SamplingParams(
temperature=1.0,
temperature=0,
max_tokens=400,
structured_outputs=StructuredOutputsParams(json=sample_json_schema),
),
@@ -45,7 +45,8 @@ async def test_include_reasoning_true_non_streaming(client: openai.AsyncOpenAI):
response = await client.chat.completions.create(
model=MODEL_NAME,
messages=MESSAGES,
max_tokens=200,
max_tokens=512,
temperature=0,
extra_body={"include_reasoning": True},
)
@@ -63,7 +64,8 @@ async def test_include_reasoning_false_non_streaming(client: openai.AsyncOpenAI)
response = await client.chat.completions.create(
model=MODEL_NAME,
messages=MESSAGES,
max_tokens=200,
max_tokens=512,
temperature=0,
extra_body={"include_reasoning": False},
)
@@ -99,7 +101,8 @@ async def test_include_reasoning_true_streaming(client: openai.AsyncOpenAI):
stream = await client.chat.completions.create(
model=MODEL_NAME,
messages=MESSAGES,
max_tokens=200,
max_tokens=512,
temperature=0,
stream=True,
extra_body={"include_reasoning": True},
)
@@ -130,7 +133,8 @@ async def test_include_reasoning_false_streaming(client: openai.AsyncOpenAI):
stream = await client.chat.completions.create(
model=MODEL_NAME,
messages=MESSAGES,
max_tokens=200,
max_tokens=512,
temperature=0,
stream=True,
extra_body={"include_reasoning": False},
)
@@ -353,7 +353,7 @@ async def test_parallel_no_streaming(client: openai.AsyncOpenAI, model_name: str
prompt = "What is an LLM?"
n = 3
max_tokens = 50 # we want some to finish earlier than others
max_tokens = 50
# High temperature to maximize chance of unique completions.
completion = await client.completions.create(
@@ -371,16 +371,12 @@ async def test_parallel_no_streaming(client: openai.AsyncOpenAI, model_name: str
num_completions = len(completion.choices)
assert num_completions == n, f"Num completions {num_completions} but expected {n}."
completion_repeats: dict[str, int] = {}
output_token_lengths = set()
for idx, choice in enumerate(completion.choices):
# Assert correct completion index & some finish reason.
assert choice.index == idx, f"Index {choice.index} but expected {idx}."
assert choice.finish_reason is not None, "None finish_reason is invalid."
text = choice.text
completion_repeats[text] = completion_repeats.get(text, 0) + 1
output_token_lengths.add(len(choice.logprobs.tokens))
# Assert subrequests finished at different times
assert len(output_token_lengths) > 1
# Assert `n` unique completions
num_unique = len(completion_repeats)
if num_unique != n:
@@ -403,7 +399,7 @@ async def test_parallel_streaming(client: openai.AsyncOpenAI, model_name: str):
prompt = "What is an LLM?"
n = 3
max_tokens = 50 # we want some to finish earlier than others
max_tokens = 50
stream = await client.completions.create(
model=model_name,
@@ -427,19 +423,15 @@ async def test_parallel_streaming(client: openai.AsyncOpenAI, model_name: str):
f"Expected {n} completions with valid indices and finish_reason."
)
completion_repeats: dict[str, int] = {}
chunk_lengths = set()
for chunk in chunks:
chunk_len = len(chunk)
# Assert correct number of completion tokens
chunk_lengths.add(chunk_len)
assert chunk_len <= max_tokens, (
f"max_tokens={max_tokens} but chunk len is {chunk_len}."
)
text = "".join(chunk)
completion_repeats[text] = completion_repeats.get(text, 0) + 1
print(text)
# Assert subrequests finished at different times
assert len(chunk_lengths) > 1
# Assert `n` unique completions
num_unique = len(completion_repeats)
if num_unique != n:
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from contextlib import AsyncExitStack
from contextlib import AsyncExitStack, asynccontextmanager
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -41,6 +41,7 @@ from vllm.entrypoints.mcp.tool_server import ToolServer
from vllm.entrypoints.openai.responses.context import (
ConversationContext,
HarmonyContext,
ParsableContext,
SimpleContext,
)
from vllm.entrypoints.openai.responses.protocol import (
@@ -551,6 +552,87 @@ def test_responses_render_result_rejects_non_single_prompt(engine_inputs):
class TestInitializeToolSessions:
"""Test class for _initialize_tool_sessions method"""
@pytest.fixture(params=[ParsableContext, HarmonyContext])
def tool_context(self, request):
context = request.param.__new__(request.param)
context.available_tools = ["browser", "python"]
context._tool_sessions = {}
context.called_tools = set()
return context
@pytest.mark.asyncio
@pytest.mark.parametrize(
("available_tools", "called_tools"),
[
([], []),
(["browser"], ["browser"]),
(["browser", "python"], []),
(["browser", "python"], ["browser"]),
(["browser", "python"], ["python"]),
(["browser", "python"], ["browser", "python"]),
],
ids=["empty", "single", "unused", "first", "last", "both"],
)
async def test_mcp_sessions_cleaned_once_before_close(
self, tool_context, available_tools, called_tools
):
events = []
sessions = {}
@asynccontextmanager
async def new_session(name, *_args):
session = MagicMock()
session.call_tool = AsyncMock(
side_effect=lambda *_: events.append(("cleanup", name))
)
sessions[name] = session
try:
yield session
finally:
events.append(("close", name))
tool_server = MagicMock(spec=ToolServer)
tool_server.new_session.side_effect = new_session
tool_context.available_tools = available_tools
async with AsyncExitStack() as stack:
await tool_context.init_tool_sessions(tool_server, stack, "req", {})
# Reinitializing existing sessions must not duplicate cleanup either.
await tool_context.init_tool_sessions(tool_server, stack, "req", {})
tool_context.called_tools.update(called_tools)
for name, session in sessions.items():
if name in called_tools:
session.call_tool.assert_awaited_once_with("cleanup_session", {})
assert events.index(("cleanup", name)) < events.index(("close", name))
else:
session.call_tool.assert_not_awaited()
assert [name for event, name in events if event == "close"] == list(
reversed(available_tools)
)
@pytest.mark.asyncio
async def test_mcp_partial_initialization_closes_opened_session(self, tool_context):
closed = []
session = MagicMock(call_tool=AsyncMock())
@asynccontextmanager
async def new_session(name, *_args):
if name == "python":
raise RuntimeError("session initialization failed")
try:
yield session
finally:
closed.append(name)
tool_server = MagicMock(spec=ToolServer)
tool_server.new_session.side_effect = new_session
with pytest.raises(RuntimeError, match="session initialization failed"):
async with AsyncExitStack() as stack:
await tool_context.init_tool_sessions(tool_server, stack, "req", {})
assert closed == ["browser"]
session.call_tool.assert_not_awaited()
@pytest_asyncio.fixture
async def serving_responses_instance(self):
"""Create a real OpenAIServingResponses instance for testing"""
@@ -17,6 +17,88 @@ from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
def assert_rope_close_rocm(
actual: torch.Tensor,
ref: torch.Tensor,
rope_input: torch.Tensor,
cos_sin_cache: torch.Tensor,
positions: torch.Tensor,
is_neox: bool,
*,
max_fail_fraction: float | None = None,
atol: float | None = None,
rtol: float | None = None,
) -> None:
"""assert_close for RoPE fused-vs-reference on ROCm, with a per-element
product-ULP allowance for catastrophic-cancellation elements.
The fused and reference kernels may contract the RoPE multiply-add into an
FMA with either product pre-rounded to the working dtype. The two valid
orderings differ by at most 2 ULPs of the product at that element, which
cancellation (x*cos ~= -y*sin) can amplify past the default tolerance.
Tier 1: |actual - ref| <= atol + rtol * |ref| (default tolerance).
Tier 2: elements failing tier 1 must each satisfy
|actual_e - ref_e| <= 2 * eps * |product_e|, where product_e is the larger
of the two products combined at that element, and their fraction must be
<= max_fail_fraction (1e-4 for fp16; 1e-2 for bf16, whose coarser eps
puts 1-ULP divergences past the default tolerance far more often).
"""
if atol is None:
atol = get_default_atol(ref)
if rtol is None:
rtol = get_default_rtol(ref)
if max_fail_fraction is None:
max_fail_fraction = 1e-2 if ref.dtype == torch.bfloat16 else 1e-4
eps = torch.finfo(ref.dtype).eps
# per-element product magnitude, in the (seq, heads, rot_dim) layout
seq_len, rot_dim = rope_input.shape[0], rope_input.shape[-1]
half = rot_dim // 2
inp = rope_input.reshape(seq_len, -1, rot_dim).to(torch.float32)
cs = cos_sin_cache[positions].to(torch.float32) # (seq_len, 2*half)
cos = cs[:, :half].unsqueeze(1) # broadcast over heads
sin = cs[:, half:].unsqueeze(1)
x, y = inp[..., :half], inp[..., half:]
if is_neox:
# out = [x*cos - y*sin, y*cos + x*sin]
prod = torch.cat(
[
torch.maximum((x * cos).abs(), (y * sin).abs()),
torch.maximum((y * cos).abs(), (x * sin).abs()),
],
dim=-1,
)
else:
# out[2i] = x[2i]*cos[i] - x[2i+1]*sin[i], interleaved
xe, xo = inp[..., 0::2], inp[..., 1::2]
prod = torch.stack(
[
torch.maximum((xe * cos).abs(), (xo * sin).abs()),
torch.maximum((xo * cos).abs(), (xe * sin).abs()),
],
dim=-1,
).flatten(-2)
prod = prod.reshape(rope_input.shape)
diff = (actual.to(torch.float32) - ref.to(torch.float32)).abs()
tol = atol + rtol * ref.to(torch.float32).abs()
fail = diff > tol
n_fail = int(fail.sum())
if n_fail == 0:
return
assert n_fail <= max_fail_fraction * diff.numel(), (
f"{n_fail} elements beyond default tolerance "
f"({n_fail / diff.numel():.2%} > {max_fail_fraction:.2%}); "
f"max diff {diff.max().item()}"
)
excess = diff[fail] - 2 * eps * prod[fail]
assert (excess <= 0).all(), (
f"{int((excess > 0).sum())} cancellation elements exceed 2 product-ULPs; "
f"worst excess {excess.max().item()}"
)
@pytest.fixture
def default_vllm_config(monkeypatch):
"""Enable the AITER triton rope on ROCm for fp16-consistent numerics.
@@ -99,6 +181,8 @@ def test_concat_and_cache_mla_rope_fused(
k_pe = torch.flatten(key[..., :qk_rope_head_dim], start_dim=1).to(device=device)
kv_c = torch.flatten(key[..., qk_rope_head_dim:], start_dim=1).to(device=device)
k_pe_orig = k_pe.clone()
query_orig = query.clone()
if current_platform.is_rocm():
# We use forward_hip for the same numerics as the fused custom kernel on ROCm
@@ -181,12 +265,9 @@ def test_concat_and_cache_mla_rope_fused(
kv_cache_scale,
)
# On ROCm the AITER Triton rope diverges by ~1 ULP from the fused kernel,
# which the tight CUDA tolerances don't cover for the low-precision paths:
# - bf16: up to ~1 bf16 ULP (0.0156-0.03125 at values ~2-3), so relax the
# kv-cache atol (bounded ~0.02) and the query atol (~0.04).
# - neox-style fp8: one e4m3 ULP (~12.5%), so relax rtol.
# Other paths use the CUDA defaults.
# On ROCm the AITER Triton rope diverges by up to 2 product-ULPs from the
# fused kernel, which the default tolerance misses at the rare
# catastrophic-cancellation elements. fp8 keeps its calibrated tolerance.
rocm_neox = current_platform.is_rocm() and is_neox_style
rocm_bf16 = current_platform.is_rocm() and dtype == torch.bfloat16
if kv_cache_dtype == "fp8":
@@ -207,16 +288,40 @@ def test_concat_and_cache_mla_rope_fused(
atol=0.004 if rocm_bf16 else 0.001,
rtol=0.15 if rocm_neox or rocm_bf16 else 0.1,
)
elif rocm_bf16:
torch.testing.assert_close(kv_cache, ref_kv_cache, atol=0.02, rtol=1e-3)
elif rocm_neox:
torch.testing.assert_close(kv_cache, ref_kv_cache, atol=1e-3, rtol=1e-3)
elif current_platform.is_rocm() and dtype in (torch.half, torch.bfloat16):
# gather the rope region of the cache back to token order
block_idx = slot_mapping // block_size
block_offset = slot_mapping % block_size
fused_k_rope = kv_cache[block_idx, block_offset, kv_lora_rank:]
ref_k_rope_gathered = ref_kv_cache[block_idx, block_offset, kv_lora_rank:]
assert_rope_close_rocm(
fused_k_rope,
ref_k_rope_gathered,
k_pe_orig,
rope.cos_sin_cache,
positions,
is_neox_style,
)
# the nope region is a byte-exact copy
torch.testing.assert_close(
kv_cache[..., :kv_lora_rank], ref_kv_cache[..., :kv_lora_rank]
)
else:
torch.testing.assert_close(kv_cache, ref_kv_cache)
torch.testing.assert_close(
query,
ref_q_pe,
atol=0.04 if rocm_bf16 else get_default_atol(query),
rtol=get_default_rtol(query),
)
if current_platform.is_rocm() and dtype in (torch.half, torch.bfloat16):
assert_rope_close_rocm(
query,
ref_q_pe,
query_orig,
rope.cos_sin_cache,
positions,
is_neox_style,
)
else:
torch.testing.assert_close(
query,
ref_q_pe,
atol=get_default_atol(query),
rtol=get_default_rtol(query),
)
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for the AITER norm support predicates.
The AITER norm wrappers flatten >2-D activations with ``Tensor.reshape``, which
silently copies when the flattened shape is not expressible with the input's
strides. The support predicates must reject those inputs so dispatch falls
through to a provider that handles arbitrary strides.
"""
import pytest
import torch
from vllm._aiter_ops import is_aiter_found_and_supported
from vllm.kernels.aiter_ops import flatten_to_2d_is_free
pytestmark = pytest.mark.skipif(
not is_aiter_found_and_supported(),
reason="Only test on ROCm with AITER installed and supported",
)
def _qkv_slice_by_head(num_tokens, num_q_heads, num_kv_heads, head_dim):
"""q viewed per-head from a fused QKV projection, as Qwen3-style QK-norm does."""
q_size, kv_size = num_q_heads * head_dim, num_kv_heads * head_dim
qkv = torch.empty(num_tokens, q_size + 2 * kv_size)
q = qkv.split([q_size, kv_size, kv_size], dim=-1)[0]
return q.view(*q.shape[:-1], num_q_heads, head_dim)
@pytest.mark.parametrize(
"x",
[
torch.empty(8, 16),
torch.empty(16),
torch.empty(2, 4, 16),
torch.empty(2, 1, 16),
# A contiguous tensor stays flattenable after a leading-dim slice.
torch.empty(8, 4, 16)[2:6],
],
)
def test_flattenable(x):
assert flatten_to_2d_is_free(x)
assert x.reshape(-1, x.shape[-1]).data_ptr() == x.data_ptr()
@pytest.mark.parametrize(
"x",
[
_qkv_slice_by_head(8, 32, 8, 128),
# Non-unit last-dim stride.
torch.empty(4, 8, 32).transpose(-1, -2),
# Leading dims cannot be merged: a slice along the middle dim.
torch.empty(4, 8, 32)[:, :4],
],
)
def test_not_flattenable(x):
assert not flatten_to_2d_is_free(x)
# reshape has to copy, which is exactly what the predicate guards against.
assert x.reshape(-1, x.shape[-1]).data_ptr() != x.data_ptr()
@@ -9,6 +9,15 @@ import pytest
import torch
from vllm import _custom_ops as ops
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8PerTensorScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.ScaledMMLinearKernel import (
FP8ScaledMMLinearLayerConfig,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8StaticTensorSym,
)
from vllm.platforms import current_platform
if not current_platform.is_cpu():
@@ -17,6 +26,9 @@ if not current_platform.is_cpu():
if not ops._supports_cpu_fp8_w8a16:
pytest.skip("fp8_scaled_mm_cpu op not available", allow_module_level=True)
if not torch.cpu._is_amx_tile_supported():
pytest.skip("requires AMX tile support", allow_module_level=True)
BLOCK_SIZE = [128, 128]
@@ -160,3 +172,104 @@ def test_cpu_fp8_scaled_mm(M: int, N: int, K: int, use_bias: bool):
assert kernel_out.dtype == out_dtype
torch.testing.assert_close(kernel_out, ref_out, rtol=0.02, atol=0.01)
def quantize_weight_per_tensor_fp8(
weight: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Quantize weight [N, K] to FP8 with a single per-tensor scale."""
fp8_max = torch.finfo(torch.float8_e4m3fn).max
scale = weight.abs().amax() / fp8_max
scale = torch.where(scale == 0, torch.ones_like(scale), scale)
q = (weight / scale).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
return q, scale
def ref_fp8_per_tensor_scaled_mm(
x: torch.Tensor,
fp8_weight: torch.Tensor,
scale: torch.Tensor,
bias: torch.Tensor | None,
out_dtype: torch.dtype,
) -> torch.Tensor:
w_dq = fp8_weight.float() * scale
out = torch.mm(x.float(), w_dq.t())
if bias is not None:
out = out + bias.float()
return out.to(out_dtype)
NK_SIZES_PER_TENSOR = [
(32, 64),
(5120, 5120),
]
@pytest.mark.parametrize("M", [1, 64])
@pytest.mark.parametrize("N,K", NK_SIZES_PER_TENSOR)
@pytest.mark.parametrize("use_bias", [False, True])
def test_cpu_fp8_per_tensor_scaled_mm_kernel(
M: int, N: int, K: int, use_bias: bool, default_vllm_config
):
"""CPUFp8PerTensorScaledMMLinearKernel correctness against float reference.
Exercises the full kernel class (not just the raw op), including the
weight-orientation fixup: Fp8LinearMethod stores `layer.weight` as
[K, N] (torch._scaled_mm convention) before calling
process_weights_after_loading, so the kernel must transpose back to
[N, K] before VNNI-packing.
"""
torch.manual_seed(0)
out_dtype = torch.bfloat16
x = torch.randn(M, K, dtype=out_dtype) / (K**0.5)
w_f32 = torch.randn(N, K, dtype=torch.float32) / (K**0.5)
fp8_weight, scale = quantize_weight_per_tensor_fp8(w_f32)
bias = torch.randn(N, dtype=torch.float32) * 0.1 if use_bias else None
ref_out = ref_fp8_per_tensor_scaled_mm(x, fp8_weight, scale, bias, out_dtype)
config = FP8ScaledMMLinearLayerConfig(
weight_quant_key=kFp8StaticTensorSym,
activation_quant_key=kFp8StaticTensorSym,
weight_shape=(N, K),
input_dtype=out_dtype,
out_dtype=out_dtype,
)
kernel = CPUFp8PerTensorScaledMMLinearKernel(
config,
layer_param_names=["weight", "weight_scale", "input_scale", "input_scale_ub"],
)
layer = torch.nn.Module()
# Fp8LinearMethod stores the weight transposed to [K, N] before calling
# process_weights_after_loading.
layer.register_parameter(
"weight", torch.nn.Parameter(fp8_weight.t().contiguous(), requires_grad=False)
)
layer.register_parameter(
"weight_scale", torch.nn.Parameter(scale.clone(), requires_grad=False)
)
kernel.process_weights_after_loading(layer)
kernel_out = kernel.apply_weights(layer, x, bias)
assert kernel_out.dtype == out_dtype
torch.testing.assert_close(kernel_out, ref_out, rtol=0.02, atol=0.01)
@pytest.mark.parametrize("n", [16, 48])
def test_cpu_fp8_per_tensor_kernel_rejects_non_multiple_of_32_n(n: int):
"""The AMX tinygemm kernel tiles N in chunks of 32 and cannot handle a
remainder tile smaller than that, so can_implement must reject any N
that isn't a multiple of 32 rather than let it crash the process.
"""
config = FP8ScaledMMLinearLayerConfig(
weight_quant_key=kFp8StaticTensorSym,
activation_quant_key=kFp8StaticTensorSym,
weight_shape=(n, 64),
input_dtype=torch.bfloat16,
out_dtype=torch.bfloat16,
)
supported, _ = CPUFp8PerTensorScaledMMLinearKernel.can_implement(config)
assert not supported
+133 -6
View File
@@ -331,6 +331,19 @@ def test_v41_fused_save_compress_and_insert(
torch.testing.assert_close(cache_backing, expected_cache, rtol=0, atol=0)
def _rotate_rope_tail(
latent_row: torch.Tensor, cos_sin_row: torch.Tensor
) -> torch.Tensor:
"""GPT-J RoPE of one latent row's last 64 dims, in fp32."""
row = latent_row.float()
c, s = cos_sin_row.chunk(2)
rotated = row.clone()
even, odd = row[448::2], row[449::2]
rotated[448::2] = even * c - odd * s
rotated[449::2] = odd * c + even * s
return rotated
def _mxfp8_record_reference(
latent_row: torch.Tensor, cos_sin_row: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
@@ -339,12 +352,7 @@ def _mxfp8_record_reference(
Mirrors FlashMLA's ``KVCacheLayout.V41_FP8Sparse`` quantizer: rotate the
RoPE tail first, then scale every 32-dim tile, RoPE tiles included.
"""
row = latent_row.float()
c, s = cos_sin_row.chunk(2)
rotated = row.clone()
even, odd = row[448::2], row[449::2]
rotated[448::2] = even * c - odd * s
rotated[449::2] = odd * c + even * s
rotated = _rotate_rope_tail(latent_row, cos_sin_row)
quantized, scales = _ue8m0_reference(rotated, 32, 448.0)
return quantized.view(torch.uint8), (scales.log2() + 127).to(torch.uint8)
@@ -461,6 +469,125 @@ def test_v41_mxfp8_cache_round_trip():
assert (error <= tolerance.repeat_interleave(32, dim=-1)).all()
# e2m1 magnitudes indexed by the low 3 bits of a code; bit 3 is the sign.
_E2M1_MAGNITUDES = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
def _decode_nvfp4_row(packed: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
"""Unpack one 256-byte e2m1 row and apply its 32 e4m3 tile scales."""
mags = torch.tensor(_E2M1_MAGNITUDES, device=packed.device)
codes = torch.empty(512, dtype=torch.uint8, device=packed.device)
codes[0::2] = packed & 0xF # even element in the low nibble
codes[1::2] = packed >> 4
vals = mags[(codes & 7).long()] * torch.where(codes >= 8, -1.0, 1.0)
return (
vals.view(32, 16) * scales.view(torch.float8_e4m3fn).float().view(32, 1)
).flatten()
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
@pytest.mark.parametrize("compress_ratio", [1, 2])
def test_v41_rope_insert_nvfp4_record(compress_ratio: int):
"""The 288-byte V4.1 NVFP4 record: 256 B of e2m1 pairs then 32 e4m3 scales.
Scales are byte-exact against the reference (``amax / 6`` clamped to the
e4m3 range); values are checked as round-to-nearest on the e2m1 grid, whose
coarsest step is 2 between 4 and 6, so half a step is ``1.0 * scale``.
"""
from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
rope_quant_insert,
)
torch.manual_seed(13)
device = "cuda"
cache_block = 64
cache_stride = math.ceil(cache_block * 288 / 512) * 512
num_tokens = 12
positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
latent = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
angles = torch.randn(64, 32, device=device)
cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
cache_backing = torch.full((2, cache_stride), 165, dtype=torch.uint8, device=device)
cache = cache_backing.as_strided((2, cache_block, 288), (cache_stride, 288, 1))
slots = torch.arange(num_tokens, dtype=torch.int64, device=device)
slots[3] = -1 # covers the negative-slot skip
rope_quant_insert(latent, positions, cos_sin, cache, slots, compress_ratio)
untouched = torch.full_like(cache_backing, 165)
for t in range(num_tokens):
slot = slots[t].item()
pos = positions[t].item()
if slot < 0 or (pos + 1) % compress_ratio:
continue
page, row = divmod(slot, cache_block)
cs = cos_sin[pos // compress_ratio * compress_ratio]
rotated = _rotate_rope_tail(latent[t], cs)
amax = rotated.view(32, 16).abs().amax(-1)
scale = (amax / 6.0).clamp(2.0**-9, 448.0).to(torch.float8_e4m3fn)
got_scales = cache_backing[page, cache_block * 256 + row * 32 :][:32]
torch.testing.assert_close(got_scales, scale.view(torch.uint8), rtol=0, atol=0)
decoded = _decode_nvfp4_row(
cache_backing[page, row * 256 : (row + 1) * 256], got_scales
)
step = scale.float().repeat_interleave(16)
assert ((decoded - rotated).abs() <= step).all()
untouched[page, row * 256 : (row + 1) * 256] = cache_backing[
page, row * 256 : (row + 1) * 256
]
untouched[page, cache_block * 256 + row * 32 :][:32] = got_scales
# Rows the kernel must not have touched, page padding included.
torch.testing.assert_close(cache_backing, untouched, rtol=0, atol=0)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
def test_v41_nvfp4_gather_matches_insert():
"""The NVFP4 gather dequantizes exactly what the insert kernel wrote."""
from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
rope_quant_insert,
)
torch.manual_seed(17)
device = "cuda"
block_size = 64
num_tokens = 70
num_blocks = 4
page_bytes = math.ceil(block_size * 288 / 512) * 512
positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
latent = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
angles = torch.randn(128, 32, device=device)
cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
backing = torch.zeros(num_blocks, page_bytes, dtype=torch.uint8, device=device)
cache = backing.as_strided((num_blocks, block_size, 288), (page_bytes, 288, 1))
slots = torch.arange(num_tokens, dtype=torch.int64, device=device)
rope_quant_insert(latent, positions, cos_sin, cache, slots, 1)
out = torch.zeros(1, num_tokens, 512, dtype=torch.bfloat16, device=device)
dequantize_and_gather_k_cache(
out,
cache,
seq_lens=torch.tensor([num_tokens], dtype=torch.int32, device=device),
gather_lens=None,
block_table=torch.arange(num_blocks, dtype=torch.int32, device=device).view(
1, -1
),
block_size=block_size,
offset=0,
)
for t in (0, 1, block_size, num_tokens - 1):
page, row = divmod(t, block_size)
expected = _decode_nvfp4_row(
backing[page, row * 256 : (row + 1) * 256],
backing[page, block_size * 256 + row * 32 :][:32],
)
torch.testing.assert_close(out[0, t].float(), expected, rtol=0, atol=0)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
@pytest.mark.parametrize("compress_ratio", [1, 2])
@pytest.mark.parametrize("store_fp8", [False, True])
@@ -0,0 +1,71 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Layout plumbing for DeepSeek V4.1 mega attention.
The kernel's Q and O layouts are produced by permuting ``wq_b`` rows and
``wo_a`` columns once at load, so what has to hold is that the permuted GEMMs
agree with a reference that permutes the activation instead.
"""
import torch
from vllm.models.deepseek_v41.common.ops.fused_layout import (
WV_GROUP_SIZE,
o_fused_chunk_permutation,
o_fused_permutation,
permute_q_to_fused,
permute_wo_a_,
permute_wq_b_,
q_fused_permutation,
)
HEAD_DIM = 512
def test_permuted_wq_b_gemm_matches_permuted_activation():
"""Permuting wq_b's rows makes the Q GEMM emit the fused layout directly."""
torch.manual_seed(0)
num_heads, q_lora_rank, num_tokens = 16, 64, 5
weight = torch.randn(num_heads * HEAD_DIM, q_lora_rank)
# One scale row per weight row, as an MXFP8 wq_b shard carries.
scale = torch.randint(
0, 256, (num_heads * HEAD_DIM, q_lora_rank // 32), dtype=torch.uint8
)
qr = torch.randn(num_tokens, q_lora_rank)
orig_weight, orig_scale = weight.clone(), scale.clone()
standard = (qr @ weight.T).view(num_tokens, num_heads, HEAD_DIM)
expected = permute_q_to_fused(standard)
permute_wq_b_(weight, scale, num_heads)
fused = (qr @ weight.T).view(num_tokens, num_heads, HEAD_DIM)
torch.testing.assert_close(fused, expected)
# The scale has to follow its row, or dequant reads another row's scale.
perm = q_fused_permutation(num_heads, HEAD_DIM)
torch.testing.assert_close(weight, orig_weight[perm])
torch.testing.assert_close(scale, orig_scale[perm])
def test_permuted_wo_a_consumes_fused_output():
"""Permuting wo_a's input columns lets it read the kernel's O layout."""
torch.manual_seed(1)
out_features, num_tokens = 32, 4
in_features = WV_GROUP_SIZE * HEAD_DIM
weight = torch.randn(out_features, in_features)
scale = torch.randint(0, 256, (out_features, in_features // 32), dtype=torch.uint8)
standard_o = torch.randn(num_tokens, in_features)
orig_weight, orig_scale = weight.clone(), scale.clone()
expected = standard_o @ weight.T
# The kernel emits the same values in the fused chunk order.
perm = o_fused_permutation(WV_GROUP_SIZE, HEAD_DIM)
fused_o = standard_o[:, perm]
permute_wo_a_(weight, scale, WV_GROUP_SIZE)
torch.testing.assert_close(weight, orig_weight[:, perm])
torch.testing.assert_close(
scale, orig_scale[:, o_fused_chunk_permutation(WV_GROUP_SIZE, HEAD_DIM)]
)
# Unlike wq_b, this permutation sits inside the 4096-term reduction, so the
# summation order changes and the result differs in the last few ulps.
torch.testing.assert_close(fused_o @ weight.T, expected, rtol=1e-3, atol=1e-3)
@@ -522,6 +522,189 @@ def test_kv_path_mxfp8_record_matches_reference(num_tokens: int, block_size: int
)
# ── Test 2d: mega-attention Q layout (is_q_interleaved) ──────────────────────
Q_CHUNK = 16
NUM_Q_CHUNKS = HEAD_DIM // Q_CHUNK # 32
@pytest.mark.parametrize("num_tokens", [1, 17, 2048])
@pytest.mark.parametrize("n_heads,q_head_padded", [(16, 64), (64, 128), (64, 0)])
def test_q_interleaved_pads_without_rope(
num_tokens: int, n_heads: int, q_head_padded: int
):
"""``is_q_interleaved`` with no norm or RoPE only zero-pads Q.
The mega-attention kernel norms and rotates Q itself, so every live
element must survive bit-exact while the padding heads -- which interleave
with the live ones inside each of the 32 head-dim chunks -- come back
zero. ``q_head_padded=0`` drops the Q pass entirely and returns nothing,
for a shard already at the kernel's head count.
"""
torch.manual_seed(5)
device = "cuda"
dtype = torch.bfloat16
block_size = 64
q = torch.randn(num_tokens, n_heads, HEAD_DIM, dtype=dtype, device=device)
kv = torch.randn(num_tokens, HEAD_DIM, dtype=dtype, device=device)
positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
cos_sin_cache = make_cos_sin_cache(4096, ROPE_DIM, torch.float32, device)
num_blocks = (num_tokens + block_size - 1) // block_size + 1
slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
k_cache = torch.zeros(
num_blocks, block_size * V41_HEAD_BYTES, dtype=torch.uint8, device=device
)
q_out = torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
q,
kv,
k_cache,
slot_mapping,
positions,
cos_sin_cache,
q_head_padded,
1e-6,
block_size,
False, # apply_q_norm
True, # kv_mxfp8
False, # apply_q_rope
True, # is_q_interleaved
)
# The KV half is unaffected by the Q mode: it must still be inserted.
assert k_cache.any()
if q_head_padded == 0:
assert q_out.numel() == 0
return
assert q_out.shape == (num_tokens, q_head_padded, HEAD_DIM)
got = q_out.view(num_tokens, NUM_Q_CHUNKS, q_head_padded, Q_CHUNK)
want = q.view(num_tokens, NUM_Q_CHUNKS, n_heads, Q_CHUNK)
torch.testing.assert_close(got[:, :, :n_heads], want, rtol=0, atol=0)
assert (got[:, :, n_heads:] == 0).all()
@pytest.mark.parametrize("n_heads", [8, 16, 32])
def test_q_interleaved_survives_graph_replay(n_heads: int):
"""A captured fused insert refills its padded Q buffer on every replay.
The op allocates ``q_out`` itself, so the tensor a capture hands back has
to keep receiving the new padding when the graph is replayed over changed
input -- that is what lets the layer prepare Q inside the captured region
rather than in ``forward_mqa``.
"""
torch.manual_seed(6)
device = "cuda"
dtype = torch.bfloat16
block_size, num_tokens, q_head_padded = 64, 7, 64
q = torch.randn(num_tokens, n_heads, HEAD_DIM, dtype=dtype, device=device)
kv = torch.randn(num_tokens, HEAD_DIM, dtype=dtype, device=device)
positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
cos_sin_cache = make_cos_sin_cache(4096, ROPE_DIM, torch.float32, device)
num_blocks = (num_tokens + block_size - 1) // block_size + 1
slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
k_cache = torch.zeros(
num_blocks, block_size * V41_HEAD_BYTES, dtype=torch.uint8, device=device
)
def prepare():
return torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
q,
kv,
k_cache,
slot_mapping,
positions,
cos_sin_cache,
q_head_padded,
1e-6,
block_size,
False, # apply_q_norm
True, # kv_mxfp8
False, # apply_q_rope
True, # is_q_interleaved
)
# Capture takes its warmup on a side stream.
side = torch.cuda.Stream()
side.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(side):
for _ in range(3):
prepare()
torch.cuda.current_stream().wait_stream(side)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
q_out = prepare()
for factor in (0.25, -0.75):
q.copy_(torch.randn_like(q) * factor)
graph.replay()
torch.accelerator.synchronize()
got = q_out.view(num_tokens, NUM_Q_CHUNKS, q_head_padded, Q_CHUNK)
want = q.view(num_tokens, NUM_Q_CHUNKS, n_heads, Q_CHUNK)
torch.testing.assert_close(got[:, :, :n_heads], want, rtol=0, atol=0)
assert (got[:, :, n_heads:] == 0).all()
@pytest.mark.parametrize("n_heads", [16, 64])
@pytest.mark.parametrize("apply_q_norm", [False, True])
@pytest.mark.parametrize("apply_q_rope", [False, True])
def test_q_interleaved_is_orthogonal_to_norm_and_rope(
n_heads: int, apply_q_norm: bool, apply_q_rope: bool
):
"""The Q layout composes with whatever norm and RoPE it is given.
A lane owns the same 512-dim slice of its head in either layout -- only
the address differs -- so the head-major result permuted into the
interleaved layout must equal running the interleaved path on a permuted
input, bit for bit, for every norm/RoPE combination.
"""
from vllm.models.deepseek_v41.common.ops.fused_layout import permute_q_to_fused
torch.manual_seed(7)
device = "cuda"
dtype = torch.bfloat16
block_size, num_tokens, q_head_padded = 64, 5, 64
q = torch.randn(num_tokens, n_heads, HEAD_DIM, dtype=dtype, device=device)
kv = torch.randn(num_tokens, HEAD_DIM, dtype=dtype, device=device)
positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
cos_sin_cache = make_cos_sin_cache(4096, ROPE_DIM, torch.float32, device)
num_blocks = (num_tokens + block_size - 1) // block_size + 1
slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
def run(q_in, is_q_interleaved):
cache = torch.zeros(
num_blocks, block_size * V41_HEAD_BYTES, dtype=torch.uint8, device=device
)
out = torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
q_in,
kv,
cache,
slot_mapping,
positions,
cos_sin_cache,
q_head_padded,
1e-6,
block_size,
apply_q_norm,
True, # kv_mxfp8
apply_q_rope,
is_q_interleaved,
)
return out, cache
head_major, cache_major = run(q, False)
interleaved, cache_inter = run(permute_q_to_fused(q), True)
torch.testing.assert_close(
interleaved, permute_q_to_fused(head_major), rtol=0, atol=0
)
# The Q layout must not leak into the KV half.
torch.testing.assert_close(cache_inter, cache_major, rtol=0, atol=0)
# ── Test 2b: DP padding (slot_mapping shorter than q/kv) ─────────────────────
+80 -18
View File
@@ -367,17 +367,21 @@ def test_deepseek_v4_mega_moe_padding_preserves_weights(monkeypatch, intermediat
[
pytest.param(128, 512, 128, True, False, id="aligned-block128"),
pytest.param(128, 512, 128, True, True, id="aligned-block128-mxfp8"),
pytest.param(5120, 2304, 32, False, False, id="deepseek-v41-flash"),
pytest.param(5120, 2304, 32, True, False, id="deepseek-v41-flash"),
pytest.param(128, 2304, 128, True, False, id="padded-block128"),
pytest.param(5120, 2304, 32, True, True, id="deepseek-v41-flash-mxfp8"),
pytest.param(128, 2304, 128, False, False, id="padded-packed-scale-fallback"),
],
)
def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
monkeypatch, hidden_size, intermediate_size, block_size, fused, mxfp8
):
"""V4.1-Flash's routed padding must preserve the serial shared-expert fallback."""
"""Shared fusion preserves checkpoint channels and zeros padded channels."""
class FakeDeepGemm:
transformed_dims: list[tuple[int, int]] = []
scale_inputs: list[tuple[int, ...]] = []
scale_values: list[torch.Tensor] = []
@staticmethod
def get_symm_buffer_for_mega_moe(*args, num_shared_experts=0, **kwargs):
@@ -402,6 +406,7 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
@classmethod
def transform_sf_into_required_layout(cls, sf, mn, k, *args, **kwargs):
cls.scale_inputs.append(tuple(sf.shape))
cls.scale_values.append(sf)
return torch.empty((sf.shape[0], mn, k // 128), dtype=torch.int32)
@classmethod
@@ -429,7 +434,10 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
def fp8_parameter(*shape):
return torch.nn.Parameter(
torch.empty(*shape, dtype=torch.float8_e4m3fn), requires_grad=False
torch.empty(*shape, dtype=torch.uint8)
.random_(1, 119)
.view(torch.float8_e4m3fn),
requires_grad=False,
)
def scale_parameter(*shape, dtype=torch.int32):
@@ -460,21 +468,34 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
linear.weight_block_size = (1, 32)
linear.weight_scale = torch.nn.Parameter(
linear.weight_scale_inv.view(torch.uint8)
.repeat_interleave(128, dim=0)
.repeat_interleave(4, dim=1),
.repeat_interleave(block_size, dim=0)
.repeat_interleave(block_size // 32, dim=1),
requires_grad=False,
)
del linear.weight_scale_inv
originals = []
for linear in (shared_experts.gate_up_proj, shared_experts.down_proj):
scale = linear.weight_scale if mxfp8 else linear.weight_scale_inv
if not fused:
# Already packed scales cannot be padded as checkpoint UE8M0 bytes.
linear.weight_scale_inv = scale_parameter(
linear.weight.shape[0], linear.weight.shape[1] // 128
)
continue
scale.data.view(torch.uint8).random_(124, 130)
block_m, block_k = linear.weight_block_size
scale_1x32 = (
experts._ue8m0_uint8_to_float(scale.view(torch.uint8))
.repeat_interleave(block_m, dim=0)
.repeat_interleave(block_k // 32, dim=1)
)
originals.append((linear.weight.view(torch.uint8).clone(), scale_1x32))
monkeypatch.setattr("vllm.utils.deep_gemm._import_deep_gemm", lambda: FakeDeepGemm)
original_gate_up_ptr = shared_experts.gate_up_proj.weight.data_ptr()
original_down_ptr = shared_experts.down_proj.weight.data_ptr()
experts.finalize_weights(shared_experts)
assert FakeDeepGemm.scale_inputs[-2:] == [
(1, 2 * intermediate_size, hidden_size // 32),
(1, hidden_size, intermediate_size // 32),
]
assert experts.has_fused_shared_experts is fused
if not fused:
assert experts.intermediate_size == 2560
@@ -490,15 +511,56 @@ def test_deepseek_v4_mega_moe_finalizes_native_shared_expert_weights(
return
assert FakeDeepGemm.transformed_dims == [(3, 3), (2, 2)]
assert shared_experts.gate_up_proj.weight.data_ptr() != original_gate_up_ptr
assert (
experts._transformed_shared_l1_weights[0].data_ptr()
== shared_experts.gate_up_proj.weight.data_ptr()
)
assert (
experts._transformed_shared_l2_weights[0].data_ptr()
== shared_experts.down_proj.weight.data_ptr()
)
padded_size = experts.intermediate_size
assert FakeDeepGemm.scale_inputs[-2:] == [
(1, 2 * padded_size, hidden_size // 32),
(1, hidden_size, padded_size // 32),
]
for actual, original, fill in (
(
experts._transformed_shared_l1_weights[0].view(torch.uint8),
originals[0][0],
0,
),
(FakeDeepGemm.scale_values[-2][0], originals[0][1], 1),
):
actual = actual.unflatten(0, (2, padded_size))
assert torch.equal(
actual[:, :intermediate_size], original.unflatten(0, (2, intermediate_size))
)
assert torch.all(actual[:, intermediate_size:] == fill)
for actual, original, fill in (
(
experts._transformed_shared_l2_weights[0].view(torch.uint8),
originals[1][0],
0,
),
(FakeDeepGemm.scale_values[-1][0], originals[1][1], 1),
):
assert torch.equal(actual[:, : original.shape[1]], original)
assert torch.all(actual[:, original.shape[1] :] == fill)
if padded_size != intermediate_size:
# Generic linear post-load hooks still receive checkpoint-shaped weights.
for linear, (weight, _) in zip(
(shared_experts.gate_up_proj, shared_experts.down_proj), originals
):
assert torch.equal(linear.weight.view(torch.uint8), weight)
assert shared_experts.gate_up_proj.weight.data_ptr() == original_gate_up_ptr
assert shared_experts.down_proj.weight.data_ptr() == original_down_ptr
else:
assert shared_experts.gate_up_proj.weight.data_ptr() != original_gate_up_ptr
assert (
experts._transformed_shared_l1_weights[0].data_ptr()
== shared_experts.gate_up_proj.weight.data_ptr()
)
assert (
experts._transformed_shared_l2_weights[0].data_ptr()
== shared_experts.down_proj.weight.data_ptr()
)
transformed_l1 = experts._transformed_shared_l1_weights
experts.finalize_weights(shared_experts)
assert experts._transformed_shared_l1_weights is transformed_l1
@pytest.mark.parametrize("fused", [False, True])
+30 -1
View File
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
import hashlib
import struct
import uuid
from io import BytesIO
from pathlib import Path
@@ -8,7 +10,7 @@ from pathlib import Path
import numpy as np
import pytest
import torch
from PIL import Image, ImageDraw
from PIL import Image, ImageDraw, ImageOps
from vllm.config.multimodal import MMHasherAlgorithm
from vllm.multimodal.hasher import MultiModalHasher
@@ -199,6 +201,33 @@ def test_hash_image_exif_id():
)
def test_hash_image_malformed_exif():
# Test that images with malformed EXIF headers (e.g. invalid TIFF header)
# do not raise an unhandled exception during hashing and fall back to image data.
buf = BytesIO()
Image.new("RGB", (64, 48)).save(buf, "JPEG")
jpg = buf.getvalue()
rest = jpg[2:]
rest = rest[2 + struct.unpack(">H", rest[2:4])[0] :]
payload = b"Exif\x00\x00XXXX\x00\x00\x00\x08" + bytes(32)
data = b"\xff\xd8\xff\xe1" + struct.pack(">H", len(payload) + 2) + payload + rest
image = Image.open(BytesIO(data))
with contextlib.suppress(Exception):
image = ImageOps.exif_transpose(image)
image.load()
hasher = MultiModalHasher
# Should hash without raising SyntaxError or any other exception
hash_val = hasher.hash_kwargs("blake3", image=image)
assert isinstance(hash_val, str) and len(hash_val) > 0
# Also verify MediaWithBytes wrapping the image with malformed EXIF
media_item = MediaWithBytes(image, data)
hash_media = hasher.hash_kwargs("blake3", image=media_item)
assert isinstance(hash_media, str) and len(hash_media) > 0
def _rgba_png_bytes() -> bytes:
image = Image.new("RGBA", (8, 8), (255, 0, 0, 128))
buf = BytesIO()
+108
View File
@@ -0,0 +1,108 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Reasoning-boundary tests for the GLM-4.7 parser.
GLM can transition straight from reasoning into a tool call without ever
emitting ``</think>``, so ``<tool_call>`` is an implicit reasoning
terminator. These cover that path plus the multi-turn prompts where an
earlier turn's markers must not be read as the current turn's state.
"""
import pytest
from tests.parser.engine.conftest import make_mock_tokenizer
from vllm.parser.glm47_moe import (
THINK_END,
THINK_START,
TOOL_CALL_END,
TOOL_CALL_START,
Glm47MoeParser,
)
THINK_S, THINK_E = 1000, 1001
TOOL_S, TOOL_E = 1002, 1003
ASSISTANT, OBSERVATION, USER = 1004, 1005, 1006
TEXT = 42 # stand-in for an ordinary reasoning/content token
VOCAB = {
THINK_START: THINK_S,
THINK_END: THINK_E,
TOOL_CALL_START: TOOL_S,
TOOL_CALL_END: TOOL_E,
"<|assistant|>": ASSISTANT,
"<|observation|>": OBSERVATION,
"<|user|>": USER,
}
@pytest.fixture
def parser():
return Glm47MoeParser(make_mock_tokenizer(VOCAB))
@pytest.fixture
def no_thinking_parser():
return Glm47MoeParser(
make_mock_tokenizer(VOCAB),
chat_template_kwargs={"thinking": False},
)
class TestIsReasoningEnd:
def test_open_reasoning(self, parser):
assert not parser.is_reasoning_end([THINK_S, TEXT])
def test_think_end(self, parser):
assert parser.is_reasoning_end([THINK_S, TEXT, THINK_E, TEXT])
def test_tool_call_without_think_end(self, parser):
"""Reasoning -> tool call with no ``</think>`` still ends reasoning."""
assert parser.is_reasoning_end([THINK_S, TEXT, TOOL_S, TEXT])
def test_previous_turn_tool_call_ignored(self, parser):
"""A finished tool call from an earlier turn says nothing about the
turn currently being generated."""
prompt = [THINK_S, TEXT, TOOL_S, TEXT, TOOL_E, OBSERVATION, TEXT, ASSISTANT]
assert not parser.is_reasoning_end(prompt)
def test_previous_turn_think_end_ignored(self, parser):
prompt = [THINK_S, TEXT, THINK_E, TEXT, USER, TEXT, ASSISTANT]
assert not parser.is_reasoning_end(prompt)
def test_empty_input(self, parser):
assert not parser.is_reasoning_end([])
def test_thinking_disabled(self, no_thinking_parser):
assert no_thinking_parser.is_reasoning_end([THINK_S, TEXT])
class TestExtractContentIds:
def test_think_end_wins_over_later_tool_call(self, parser):
"""Content between ``</think>`` and a tool call must survive."""
ids = [THINK_S, TEXT, THINK_E, 20, 21, TOOL_S, 30, TOOL_E]
assert parser.extract_content_ids(ids) == [20, 21, TOOL_S, 30, TOOL_E]
def test_every_tool_call_after_think_end_kept(self, parser):
ids = [THINK_E, 20, TOOL_S, 30, TOOL_E, 21, TOOL_S, 31, TOOL_E]
assert parser.extract_content_ids(ids) == ids[1:]
def test_falls_back_to_tool_call(self, parser):
"""Without ``</think>``, content starts at the opener itself so the
tool parser still receives a well-formed call."""
ids = [THINK_S, TEXT, TOOL_S, 30, TOOL_E]
assert parser.extract_content_ids(ids) == [TOOL_S, 30, TOOL_E]
def test_falls_back_to_first_tool_call_of_turn(self, parser):
ids = [THINK_S, TEXT, TOOL_S, 30, TOOL_E, TOOL_S, 31, TOOL_E]
assert parser.extract_content_ids(ids) == ids[2:]
def test_previous_turn_tool_call_ignored(self, parser):
ids = [TOOL_S, 30, TOOL_E, OBSERVATION, TEXT, ASSISTANT, THINK_S, TEXT]
assert parser.extract_content_ids(ids) == ids
def test_no_markers_returns_input_ids(self, parser):
assert parser.extract_content_ids([20, 21]) == [20, 21]
def test_thinking_disabled(self, no_thinking_parser):
ids = [THINK_S, TEXT, TOOL_S]
assert no_thinking_parser.extract_content_ids(ids) == ids
@@ -0,0 +1,163 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""`prompt_embeds` payloads that are not tensor files must be client errors.
`prompt_embeds` is a base64 blob the caller writes, and every other way of
getting it wrong -- wrong rank, wrong hidden_size, wrong dtype, not a tensor at
all -- already answers 400. A payload that `torch.load` cannot read at all was
the exception: torch has no single error type for that (the zip reader raises
`RuntimeError`, the legacy pickle path raises an unpickling error, `KeyError` or
`IndexError`, an empty payload raises `EOFError`), none of them is a
`ValueError`, and the entrypoints' fallback therefore mapped them to 500.
The assertions go through `create_error_response`, which is what actually turns
an exception into a status code, so they pin the HTTP answer rather than the
exception class alone.
"""
import io
import zipfile
from unittest.mock import patch
import pybase64 as base64
import pytest
import torch
from vllm.entrypoints.serve.exception_handling.error_response import (
create_error_response,
)
from vllm.exceptions import VLLMValidationError
from vllm.renderers.embed_utils import (
_MAX_EMBED_ERROR_REASON_CHARS,
safe_load_prompt_embeds,
)
@pytest.fixture
def model_config():
from vllm.config import ModelConfig
return ModelConfig(
model="facebook/opt-125m",
tokenizer="facebook/opt-125m",
tokenizer_mode="auto",
trust_remote_code=False,
dtype="float32",
seed=0,
enable_prompt_embeds=True,
)
def _encode(raw: bytes) -> bytes:
return base64.b64encode(raw)
def _zip_without_a_tensor() -> bytes:
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("junk.txt", "hello")
return buffer.getvalue()
def _saved_tensor(tensor: torch.Tensor) -> bytes:
buffer = io.BytesIO()
torch.save(tensor, buffer)
return buffer.getvalue()
UNPARSABLE_PAYLOADS = [
pytest.param(b"", id="empty"),
pytest.param(b"\x80", id="single-byte"),
pytest.param(b"\x00\x01\x02\x03not-a-tensor", id="random-bytes"),
pytest.param(b"hello world this is not a torch file", id="ascii-text"),
pytest.param(b"PK\x03\x04" + b"\x00" * 20, id="truncated-zip"),
pytest.param(_zip_without_a_tensor(), id="zip-without-a-tensor"),
# pickle.dumps(42): a valid pickle stream that is not a torch checkpoint.
# Spelled out rather than built, so this file does not import pickle.
pytest.param(b"\x80\x04K*.", id="legacy-pickle-of-an-int"),
]
@pytest.mark.parametrize("payload", UNPARSABLE_PAYLOADS)
def test_unreadable_prompt_embeds_payload_is_a_client_error(model_config, payload):
with pytest.raises(VLLMValidationError) as excinfo:
safe_load_prompt_embeds(model_config, _encode(payload))
assert excinfo.value.parameter == "prompt_embeds"
assert int(create_error_response(excinfo.value).error.code) == 400
@pytest.mark.parametrize("payload", UNPARSABLE_PAYLOADS)
def test_the_error_body_stays_bounded(model_config, payload):
"""torch's reason is built from the caller's bytes, so it must be truncated.
An unpickler that reports the offending global, for instance, quotes a name
the caller chose; without a bound a large one would be reflected whole.
"""
padding = b"A" * 100_000
with pytest.raises(VLLMValidationError) as excinfo:
safe_load_prompt_embeds(model_config, _encode(payload + padding))
assert len(str(excinfo.value)) < 500
def test_a_long_reason_is_truncated_and_says_how_much_was_left_out(model_config):
"""The cap is pinned against a reason of known length, not a real payload.
Which of torch's messages happen to exceed the cap is torch's business and
changes between releases, so the reason is injected here: that keeps the
assertion about *this* code's truncation rule rather than about whichever
error text the installed torch produces.
"""
reason = "E" * (_MAX_EMBED_ERROR_REASON_CHARS + 37)
with (
patch(
"vllm.renderers.embed_utils.torch.load", side_effect=RuntimeError(reason)
),
pytest.raises(VLLMValidationError) as excinfo,
):
safe_load_prompt_embeds(model_config, _encode(b"ignored"))
message = str(excinfo.value)
assert "E" * _MAX_EMBED_ERROR_REASON_CHARS in message
assert "E" * (_MAX_EMBED_ERROR_REASON_CHARS + 1) not in message
assert "... (37 more characters truncated)" in message
def test_a_short_reason_is_passed_through_whole(model_config):
"""A reason that fits is not annotated -- the count only appears when it is
telling the reader something."""
reason = "invalid magic number; corrupt file?"
assert len(reason) <= _MAX_EMBED_ERROR_REASON_CHARS
with (
patch(
"vllm.renderers.embed_utils.torch.load", side_effect=RuntimeError(reason)
),
pytest.raises(VLLMValidationError) as excinfo,
):
safe_load_prompt_embeds(model_config, _encode(b"ignored"))
message = str(excinfo.value)
assert reason in message
assert "truncated" not in message
def test_a_well_formed_payload_still_loads(model_config):
"""Positive control: the healthy path is untouched."""
hidden_size = model_config.get_hidden_size()
tensor = torch.zeros(3, hidden_size, dtype=torch.float32)
loaded = safe_load_prompt_embeds(model_config, _encode(_saved_tensor(tensor)))
assert loaded.shape == (3, hidden_size)
assert loaded.dtype == model_config.dtype
def test_a_payload_that_is_not_base64_is_still_a_client_error(model_config):
"""Positive control: the base64 stage already answered 400 and still does."""
with pytest.raises(ValueError) as excinfo:
safe_load_prompt_embeds(model_config, b"!!!!not base64!!!!")
assert int(create_error_response(excinfo.value).error.code) == 400
@@ -11,6 +11,7 @@ import pytest
import torch
from vllm.config import ModelConfig
from vllm.exceptions import VLLMValidationError
from vllm.multimodal.media import AudioEmbeddingMediaIO, ImageEmbeddingMediaIO
from vllm.renderers.embed_utils import safe_load_prompt_embeds
from vllm.utils.sparse_utils import check_sparse_tensor_invariants_threadsafe
@@ -54,7 +55,7 @@ class TestNegativeControlWithoutRace:
def test_malicious_sparse_rejected_by_prompt_loader(self, model_config):
encoded = _encode_tensor(_create_malicious_sparse_tensor())
with pytest.raises((RuntimeError, ValueError)):
with pytest.raises((RuntimeError, ValueError, VLLMValidationError)):
safe_load_prompt_embeds(model_config, encoded)
def test_malicious_sparse_rejected_by_image_loader(self):
@@ -147,7 +148,7 @@ class TestConcurrentRaceProtection:
try:
safe_load_prompt_embeds(model_config, malicious_encoded)
bypassed.append(True)
except (RuntimeError, ValueError):
except (RuntimeError, ValueError, VLLMValidationError):
rejected.append(True)
with ThreadPoolExecutor(max_workers=num_workers) as pool:
@@ -192,7 +193,7 @@ class TestGlobalFlagRestoration:
initial = torch.sparse.check_sparse_tensor_invariants.is_enabled()
malicious_encoded = _encode_tensor(_create_malicious_sparse_tensor())
with pytest.raises((RuntimeError, ValueError)):
with pytest.raises((RuntimeError, ValueError, VLLMValidationError)):
safe_load_prompt_embeds(model_config, malicious_encoded)
assert torch.sparse.check_sparse_tensor_invariants.is_enabled() == initial
@@ -203,7 +204,7 @@ class TestGlobalFlagRestoration:
malicious_encoded = _encode_tensor(_create_malicious_sparse_tensor())
def attempt_load(_):
with contextlib.suppress(RuntimeError, ValueError):
with contextlib.suppress(RuntimeError, ValueError, VLLMValidationError):
safe_load_prompt_embeds(model_config, malicious_encoded)
with ThreadPoolExecutor(max_workers=4) as pool:
@@ -244,7 +245,7 @@ class TestCrossLoaderLockSharing:
# serialization — one finishes before the other starts), AND invalid
# tensors are still rejected.
malicious = _encode_tensor(_create_malicious_sparse_tensor())
with pytest.raises((RuntimeError, ValueError)):
with pytest.raises((RuntimeError, ValueError, VLLMValidationError)):
safe_load_prompt_embeds(model_config, malicious)
with pytest.raises((RuntimeError, ValueError)):
io_handler.load_base64("", malicious.decode("utf-8"))
@@ -117,8 +117,10 @@ class TestPromptEmbedsValidation:
malicious_tensor = _create_malicious_sparse_tensor()
encoded = _encode_tensor(malicious_tensor)
# Should raise RuntimeError due to invalid sparse tensor
with pytest.raises((RuntimeError, ValueError)) as exc_info:
# The invariant check raises RuntimeError from inside torch.load;
# safe_load_prompt_embeds now reports that as a client error so the
# caller gets a 400 rather than the 500 a bare RuntimeError produced.
with pytest.raises(VLLMValidationError) as exc_info:
safe_load_prompt_embeds(model_config, encoded)
# Error should indicate sparse tensor validation failure
@@ -137,7 +139,7 @@ class TestPromptEmbedsValidation:
)
encoded = _encode_tensor(malicious_tensor)
with pytest.raises((RuntimeError, ValueError)):
with pytest.raises(VLLMValidationError):
safe_load_prompt_embeds(model_config, encoded)
def test_negative_indices_rejected(self, model_config):
@@ -152,7 +154,7 @@ class TestPromptEmbedsValidation:
)
encoded = _encode_tensor(malicious_tensor)
with pytest.raises((RuntimeError, ValueError)):
with pytest.raises(VLLMValidationError):
safe_load_prompt_embeds(model_config, encoded)
def test_hidden_size_mismatch_rejected(self, model_config):
@@ -379,8 +381,8 @@ class TestSparseTensorValidationIntegration:
# Step 1-2: Attacker creates malicious payload
attack_payload = _encode_tensor(_create_malicious_sparse_tensor())
# Step 3-4: Server processes and should reject
with pytest.raises((RuntimeError, ValueError)):
# Step 3-4: Server processes and should reject, as a client error
with pytest.raises(VLLMValidationError):
safe_load_prompt_embeds(model_config, attack_payload)
def test_attack_scenario_chat_api_image(self):
+50 -2
View File
@@ -65,7 +65,7 @@ def test_cpu_target_selects_cpu_platform_from_non_cpu_wheel(
rocm_plugin.assert_not_called()
def test_platform_detection_logs_zentorch_import_failure(caplog):
def test_broken_zentorch_falls_back_to_cpu_platform(caplog):
original_import = builtins.__import__
def import_with_broken_zentorch(name, *args, **kwargs):
@@ -88,6 +88,54 @@ def test_platform_detection_logs_zentorch_import_failure(caplog):
):
platform = resolve_current_platform_cls_qualname()
assert platform == "vllm.platforms.cpu.CpuPlatform"
assert "zentorch failed to import" in caplog.text
assert "OSError: incompatible shared library" in caplog.text
def test_zentorch_failure_other_than_oserror_is_not_recovered(caplog):
original_import = builtins.__import__
def import_with_broken_zentorch(name, *args, **kwargs):
if name == "zentorch":
raise RuntimeError("unknown zentorch failure")
return original_import(name, *args, **kwargs)
with (
patch("vllm.platforms.envs.VLLM_TARGET_DEVICE", "cuda"),
patch.dict(
"vllm.platforms.builtin_platform_plugins",
{"cpu": cpu_platform_plugin},
clear=True,
),
patch("vllm.platforms.load_plugins_by_group", return_value={}),
patch("vllm.platforms.vllm_version_matches_substr", return_value=True),
patch("vllm.platforms._is_amd_zen_cpu", return_value=True),
patch.object(builtins, "__import__", side_effect=import_with_broken_zentorch),
caplog.at_level(logging.DEBUG, logger="vllm.platforms"),
):
platform = resolve_current_platform_cls_qualname()
assert platform == "vllm.platforms.interface.UnspecifiedPlatform"
assert "RuntimeError: unknown zentorch failure" in caplog.text
def test_platform_plugin_failure_is_logged(caplog):
def failing_plugin():
raise RuntimeError("plugin exploded")
with (
patch("vllm.platforms.envs.VLLM_TARGET_DEVICE", "cuda"),
patch.dict(
"vllm.platforms.builtin_platform_plugins",
{"cpu": failing_plugin},
clear=True,
),
patch("vllm.platforms.load_plugins_by_group", return_value={}),
caplog.at_level(logging.DEBUG, logger="vllm.platforms"),
):
platform = resolve_current_platform_cls_qualname()
assert platform == "vllm.platforms.interface.UnspecifiedPlatform"
assert "Platform plugin cpu failed during detection" in caplog.text
assert "OSError: incompatible shared library" in caplog.text
assert "RuntimeError: plugin exploded" in caplog.text
+189
View File
@@ -0,0 +1,189 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Cgroup memory readers and SHM allocation preflight checks."""
import sys
from io import StringIO
from unittest import mock
import pytest
from vllm.utils import cpu_resource_utils as cru
from vllm.utils.mem_constants import GiB_bytes
_V2_LIMIT_PATH = "/sys/fs/cgroup/memory.max"
_V2_USAGE_PATH = "/sys/fs/cgroup/memory.current"
_V1_LIMIT_PATH = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
_V1_USAGE_PATH = "/sys/fs/cgroup/memory/memory.usage_in_bytes"
@pytest.fixture(autouse=True)
def _clear_cgroup_cache():
cru.get_cgroup_memory_limit.cache_clear()
yield
cru.get_cgroup_memory_limit.cache_clear()
def _stub_files(monkeypatch, files: dict):
"""Stub ``open()`` for a fixed set of paths; ``None`` -> OSError."""
real_open = open
def fake_open(path, *args, **kwargs):
if path in files:
content = files[path]
if content is None:
raise OSError(f"no such file: {path}")
return StringIO(content)
return real_open(path, *args, **kwargs)
monkeypatch.setattr("builtins.open", fake_open)
def test_cgroup_v2_limit_and_usage(monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
_stub_files(
monkeypatch,
{
_V2_LIMIT_PATH: f"{20 * GiB_bytes}\n",
_V2_USAGE_PATH: f"{5 * GiB_bytes}\n",
},
)
assert cru.get_cgroup_memory_limit() == 20 * GiB_bytes
assert cru.get_cgroup_memory_usage() == 5 * GiB_bytes
def test_cgroup_v2_unlimited_falls_back_to_v1(monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
_stub_files(
monkeypatch,
{
_V2_LIMIT_PATH: "max\n",
_V1_LIMIT_PATH: f"{8 * GiB_bytes}\n",
_V1_USAGE_PATH: f"{1 * GiB_bytes}\n",
},
)
assert cru.get_cgroup_memory_limit() == 8 * GiB_bytes
assert cru.get_cgroup_memory_usage() == 1 * GiB_bytes
def test_cgroup_v1_limit_and_usage(monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
_stub_files(
monkeypatch,
{
_V2_LIMIT_PATH: None,
_V1_LIMIT_PATH: f"{8 * GiB_bytes}\n",
_V1_USAGE_PATH: f"{2 * GiB_bytes}\n",
},
)
assert cru.get_cgroup_memory_limit() == 8 * GiB_bytes
assert cru.get_cgroup_memory_usage() == 2 * GiB_bytes
def test_cgroup_v1_unlimited_sentinel_is_ignored(monkeypatch):
"""An unlimited cgroup v1 sentinel must not be treated as a real limit."""
monkeypatch.setattr(sys, "platform", "linux")
_stub_files(
monkeypatch,
{_V2_LIMIT_PATH: None, _V1_LIMIT_PATH: f"{(1 << 63) - 1}\n"},
)
assert cru.get_cgroup_memory_limit() is None
assert cru.get_cgroup_memory_usage() is None
def test_cgroup_no_limit_files_present(monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
_stub_files(monkeypatch, {_V2_LIMIT_PATH: None, _V1_LIMIT_PATH: None})
assert cru.get_cgroup_memory_limit() is None
assert cru.get_cgroup_memory_usage() is None
def test_cgroup_skipped_on_non_linux(monkeypatch):
monkeypatch.setattr(sys, "platform", "darwin")
_stub_files(monkeypatch, {_V2_LIMIT_PATH: f"{1 * GiB_bytes}\n"})
assert cru.get_cgroup_memory_limit() is None
assert cru.get_cgroup_memory_usage() is None
def test_cgroup_limit_is_cached_until_explicitly_cleared(monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
files = {
_V2_LIMIT_PATH: f"{1 * GiB_bytes}\n",
_V2_USAGE_PATH: f"{512 << 20}\n",
}
_stub_files(monkeypatch, files)
assert cru.get_cgroup_memory_limit() == 1 * GiB_bytes
files[_V2_LIMIT_PATH] = f"{2 * GiB_bytes}\n"
assert cru.get_cgroup_memory_limit() == 1 * GiB_bytes
cru.get_cgroup_memory_limit.cache_clear()
assert cru.get_cgroup_memory_limit() == 2 * GiB_bytes
def test_cgroup_usage_is_read_without_cache(monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
files = {
_V2_LIMIT_PATH: f"{1 * GiB_bytes}\n",
_V2_USAGE_PATH: f"{512 << 20}\n",
}
_stub_files(monkeypatch, files)
assert cru.get_cgroup_memory_usage() == 512 << 20
files[_V2_USAGE_PATH] = f"{768 << 20}\n"
assert cru.get_cgroup_memory_usage() == 768 << 20
def test_check_cgroup_memory_available_warns_on_low_headroom(monkeypatch):
monkeypatch.setattr(cru, "get_cgroup_memory_limit", lambda: 1 << 30)
monkeypatch.setattr(cru, "get_cgroup_memory_usage", lambda: 512 << 20)
with (
mock.patch.object(cru.logger, "debug") as log_debug,
mock.patch.object(cru.logger, "warning") as log_warning,
):
cru.check_cgroup_memory_available(600 << 20, "mmap")
log_debug.assert_not_called()
log_warning.assert_called_once()
assert "current headroom is below" in log_warning.call_args.args[-1]
def test_check_cgroup_memory_available_logs_success_at_debug(monkeypatch):
monkeypatch.setattr(cru, "get_cgroup_memory_limit", lambda: 1 << 30)
monkeypatch.setattr(cru, "get_cgroup_memory_usage", lambda: 512 << 20)
with (
mock.patch.object(cru.logger, "debug") as log_debug,
mock.patch.object(cru.logger, "warning") as log_warning,
):
cru.check_cgroup_memory_available(256 << 20, "mmap")
log_debug.assert_called_once()
log_warning.assert_not_called()
@pytest.mark.parametrize(
("limit", "usage"),
[(None, 512 << 20), (1 << 30, None)],
)
def test_check_cgroup_memory_available_skips_without_snapshot(
monkeypatch, limit, usage
):
monkeypatch.setattr(cru, "get_cgroup_memory_limit", lambda: limit)
monkeypatch.setattr(cru, "get_cgroup_memory_usage", lambda: usage)
with (
mock.patch.object(cru.logger, "debug") as log_debug,
mock.patch.object(cru.logger, "warning") as log_warning,
):
cru.check_cgroup_memory_available(1 << 60, "mmap")
log_debug.assert_not_called()
log_warning.assert_not_called()
@@ -20,10 +20,10 @@ kernel is documented to replicate.
import torch
# Bootstrap the glm5next package before entering the indexer module: its
# kpool_compress import runs glm5next/__init__, which pulls model ->
# attention -> back into sparse_attn_indexer_kpool (attention.py imports the
# class at module scope). Production always enters via attention.py first.
# Bootstrap the glm5next package before importing kpool_compress directly: its
# import runs glm5next/__init__, which pulls model -> attention -> the indexer
# dispatcher (sparse_indexer) -> back into the nvidia/amd sparse_indexer
# modules. Production always enters via attention.py first.
# isort: off
import vllm.models.glm5next # noqa: F401
from vllm.models.glm5next.nvidia.ops.kpool_compress import ( # noqa: E402
@@ -32,13 +32,17 @@ from vllm.models.glm5next.nvidia.ops.kpool_compress import ( # noqa: E402
)
# isort: on
import vllm.model_executor.layers.sparse_attn_indexer_kpool as indexer_mod
from vllm.model_executor.layers.sparse_attn_indexer_kpool import (
from vllm.models.glm5next.common.sparse_indexer import (
_decode_topk_seq_lens,
_fill_short_decode_causal_indices,
)
from vllm.platforms import current_platform
if current_platform.is_rocm():
from vllm.models.glm5next.amd import sparse_indexer as indexer_mod
else:
from vllm.models.glm5next.nvidia import sparse_indexer as indexer_mod
KPOOL = 4
TOPK_TOKENS = 16
SELECT_K = TOPK_TOKENS // KPOOL
+38
View File
@@ -279,6 +279,44 @@ def make_request(
)
@pytest.mark.parametrize("dcp", [1, 4])
def test_effective_attention_block_size_matches_events(dcp):
from vllm.distributed.kv_events import BlockStored
from vllm.v1.engine.core import EngineCore
config = KVCacheConfig(
num_blocks=32,
kv_cache_tensors=[],
kv_cache_groups=[
KVCacheGroupSpec(["attention"], new_kv_cache_spec()),
],
)
manager = KVCacheManager(
generate_scheduler_kv_cache_config([config]),
max_model_len=256,
scheduler_block_size=16 * dcp,
hash_block_size=16 * dcp,
dcp_world_size=dcp,
enable_kv_cache_events=True,
)
core = EngineCore.__new__(EngineCore)
core.vllm_config = SimpleNamespace(cache_config=CacheConfig(block_size=16))
core.scheduler = SimpleNamespace(kv_cache_manager=manager)
core._initialize_effective_attention_block_size()
block_size = core.vllm_config.cache_config.effective_attention_block_size
assert block_size == 16 * dcp
request = make_request(
"block-size", list(range(64)), block_size=16 * dcp, hash_fn=sha256
)
assert manager.allocate_slots(request, 64) is not None
assert [
event.block_size
for event in manager.take_events()
if isinstance(event, BlockStored)
] == [block_size]
def new_kv_cache_spec(
block_size=16,
num_kv_heads=2,
@@ -179,6 +179,63 @@ def test_mamba_retirement_bounds_prefill_states(block_size, in_flight_chunks):
assert pool.get_num_free_blocks() == initial_free
@pytest.mark.parametrize("block_size", [896, 1536])
@pytest.mark.parametrize("num_speculative_blocks", [0, 1, 4])
@pytest.mark.parametrize("prompt_tokens", [25121, 704547])
def test_mamba_checkpoint_admission_matches_allocation(
block_size, num_speculative_blocks, prompt_tokens
):
"""Checkpoint admission must match the subsequent physical allocation."""
spec = MambaSpec(
block_size=block_size,
shapes=((1, 1),),
dtypes=(torch.float32,),
mamba_cache_mode="align",
num_speculative_blocks=num_speculative_blocks,
num_prefill_checkpoint_blocks=1,
prefill_checkpoint_alignment=64,
)
pool = BlockPool(
num_gpu_blocks=2048,
enable_caching=True,
hash_block_size=128,
)
manager = MambaManager(
spec,
block_pool=pool,
enable_caching=True,
kv_cache_group_id=0,
scheduler_block_size=block_size,
)
request_id = "prefill"
computed_tokens = 23040
def estimate(num_tokens, total_computed_tokens, apply_admission_cap):
return manager.get_num_blocks_to_allocate(
request_id=request_id,
num_tokens=num_tokens,
new_computed_blocks=[],
total_computed_tokens=total_computed_tokens,
num_local_computed_tokens=total_computed_tokens,
num_tokens_main_model=num_tokens,
apply_admission_cap=apply_admission_cap,
)
estimate(computed_tokens, 0, False)
manager.allocate_new_blocks(request_id, computed_tokens, computed_tokens)
assert request_id in manager._allocated_block_reqs
admission_estimate = estimate(prompt_tokens, computed_tokens, True)
allocation_estimate = estimate(prompt_tokens, computed_tokens, False)
assert request_id in manager._checkpoints
free_before = pool.get_num_free_blocks()
manager.allocate_new_blocks(request_id, prompt_tokens, prompt_tokens)
allocated = free_before - pool.get_num_free_blocks()
assert admission_estimate == allocation_estimate == allocated
def get_sliding_window_manager(
sliding_window_spec,
block_pool,
+1 -1
View File
@@ -131,7 +131,7 @@ SMOKE_CONFIGS = [
id="dflash",
),
pytest.param(
"Qwen/Qwen3.5-0.8B-Base",
"Qwen/Qwen3.5-0.8B",
{
"method": "mtp",
"num_speculative_tokens": 3,
+28 -3
View File
@@ -158,7 +158,10 @@ def test_mp_client_uses_env_timeout(monkeypatch: pytest.MonkeyPatch):
local_engines_only=False,
enable_elastic_ep=False,
)
vllm_config = SimpleNamespace(parallel_config=parallel_config)
vllm_config = SimpleNamespace(
parallel_config=parallel_config,
cache_config=SimpleNamespace(effective_attention_block_size=None),
)
client = core_client_mod.MPClient(
asyncio_mode=False,
@@ -368,10 +371,15 @@ def test_dplb_finished_requests_release_inflight():
assert req.request_id not in client.reqs_in_flight
def test_apply_ready_response_syncs_block_size():
@pytest.mark.parametrize(
("effective_size", "other_size"),
[(None, None), (4224, 4224), (4224, 1056), (4224, None)],
)
def test_apply_ready_response_syncs_block_size(effective_size, other_size):
import msgspec
client = object.__new__(MPClient)
client._effective_attention_block_sizes = set()
client.vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(block_size=16, num_gpu_blocks=0),
model_config=SimpleNamespace(max_model_len=8192),
@@ -399,14 +407,31 @@ def test_apply_ready_response_syncs_block_size():
max_loras=0,
)
)
client._apply_ready_response(payload)
fields = msgspec.msgpack.decode(payload)
if effective_size is None:
del fields["effective_attention_block_size"]
else:
fields["effective_attention_block_size"] = effective_size
client._apply_ready_response(msgspec.msgpack.encode(fields))
assert client.vllm_config.cache_config.block_size == 1056
cache_config = client.vllm_config.cache_config
assert cache_config.effective_attention_block_size == effective_size
fields["effective_attention_block_size"] = other_size
client._apply_ready_response(msgspec.msgpack.encode(fields))
assert cache_config.effective_attention_block_size == (
effective_size if effective_size == other_size else None
)
client._apply_ready_response(b"")
assert cache_config.effective_attention_block_size is None
def test_apply_ready_response_syncs_mamba_block_size():
import msgspec
client = object.__new__(MPClient)
client._effective_attention_block_sizes = set()
client.vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(block_size=16, num_gpu_blocks=0),
model_config=SimpleNamespace(max_model_len=8192),
@@ -79,20 +79,31 @@ from vllm.v1.outputs import KVConnectorOutput, ModelRunnerOutput
from vllm.v1.request import RequestStatus
@pytest.mark.parametrize("boundary", [3840, 3904])
@pytest.mark.parametrize(
"window,extra_retained", [(128, 0), (128, 3), (256, 1), (256, 3)]
)
@pytest.mark.parametrize("boundary", [3840, 3904, 3968])
@pytest.mark.parametrize("eagle", [False, True])
@pytest.mark.parametrize("left_state", ["present", "missing", "pending", "loading"])
def test_swa_offload_window_covers_unaligned_hit(boundary, eagle, left_state):
def test_swa_offload_window_covers_unaligned_hit(
boundary, eagle, left_state, window, extra_retained
):
"""A smaller SWA group can move the hit inside another group's CPU chunk."""
groups = []
for i, (block_size, window) in enumerate([(256, None), (64, 128), (8, 128)]):
for i, (block_size, group_window) in enumerate(
[(256, None), (64, window), (8, 128)]
):
kwargs = dict(
block_size=block_size, num_kv_heads=1, head_size=1, dtype=torch.float32
)
kv_spec = (
FullAttentionSpec(**kwargs)
if window is None
else SlidingWindowSpec(**kwargs, sliding_window=window)
if group_window is None
else SlidingWindowSpec(
**kwargs,
sliding_window=group_window,
extra_retained_tokens=extra_retained if i == 1 else 0,
)
)
groups.append(
KVCacheGroupSpec([f"layer{i}"], kv_spec, is_eagle_group=eagle and i == 1)
@@ -153,7 +164,9 @@ def test_swa_offload_window_covers_unaligned_hit(boundary, eagle, left_state):
sched._chunks_being_loaded.add(left_key)
external, load_async = sched.get_num_new_matched_tokens(request, 0)
if boundary == 3904 and left_state != "present":
first_retained_block = (boundary - window + 1 - extra_retained) // 64
needs_left = first_retained_block // 4 < end - 1
if needs_left and left_state != "present":
assert external == (0 if left_state == "missing" else None)
assert not load_async
return
@@ -177,8 +190,8 @@ def test_swa_offload_window_covers_unaligned_hit(boundary, eagle, left_state):
sched.update_state_after_alloc(request, blocks, external)
assert len(sched._jobs) == 1
job = next(iter(sched._jobs.values()))
if boundary == 3904:
assert {swa[14], swa[15]} <= job.keys
if needs_left:
assert {left_key, swa[end - 1]} <= job.keys
manager.complete_load(job.keys, state.req_context)
@@ -245,6 +258,9 @@ def test_partial_tail_store_uses_attention_and_recurrent_cow_sources():
jobs = scheduler._build_partial_tail_store_jobs(output)
assert len(jobs) == 1
offered_keys = scheduler.manager.prepare_store.call_args.args[0]
req_context = scheduler._req_status["req"].req_context
assert all(req_context.get_offload_key_position(key) == 28 for key in offered_keys)
[job_id] = jobs
src_spec = jobs[job_id].src_spec
assert isinstance(src_spec, GPULoadStoreSpec)
@@ -367,6 +383,13 @@ def test_normal_store_excludes_align_mode_mamba_sources():
req_status.group_states[0].block_ids[:] = [11]
req_status.group_states[1].block_ids[:] = [99]
req_status.update_offload_keys()
for group_config, group_state in zip(
scheduler.config.kv_group_configs, req_status.group_states
):
assert (
req_status.req_context.get_offload_key_position(group_state.offload_keys[0])
== group_config.tokens_per_chunk
)
scheduler.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
)
@@ -908,7 +931,6 @@ def test_offloading_connector(request_runner, async_scheduling: bool):
runner.run(decoded_tokens=[0] * (tokens_per_chunk + 1))
# 1 more block (+ token for kicking off offloading)
# now check touch was called with all 6 blocks
runner.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
)
@@ -916,9 +938,6 @@ def test_offloading_connector(request_runner, async_scheduling: bool):
decoded_tokens=[0] * (tokens_per_chunk + 1),
expected_stored=(15, 16, 17),
)
runner.manager.touch.assert_called()
block_hashes1 = list(runner.manager.touch.call_args.args[0])
assert len(block_hashes1) == 6
# terminate request
runner.run(decoded_tokens=[EOS_TOKEN_ID])
@@ -926,13 +945,7 @@ def test_offloading_connector(request_runner, async_scheduling: bool):
# create a new request differing only on the last token
runner.new_request(token_ids=[0] * (tokens_per_chunk * 6 - 1) + [1])
runner.run(decoded_tokens=[0])
runner.manager.touch.assert_called()
block_hashes2 = list(runner.manager.touch.call_args.args[0])
assert len(block_hashes2) == 6
# verify hashes are the same, except for the last block
assert block_hashes1[:5] == block_hashes2[:5]
assert block_hashes1[5] != block_hashes2[5]
runner.manager.touch.assert_not_called()
# terminate request
runner.run(
@@ -1340,14 +1353,7 @@ def test_two_groups_full_and_sliding_window(request_runner, async_scheduling: bo
generate_store_output(keys)
)
runner.run(decoded_tokens=[0])
# _touch called from get_num_new_matched_tokens (2 groups) and
# _get_reqs_to_store (2 groups) → 4 touch calls total.
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 4
assert len(touch_calls[0].args[0]) == 3
assert len(touch_calls[1].args[0]) == 3
assert len(touch_calls[2].args[0]) == 3
assert len(touch_calls[3].args[0]) == 3
runner.manager.touch.assert_not_called()
# store 3 more block
runner.manager.prepare_store.side_effect = lambda keys, req_context: (
@@ -1358,9 +1364,7 @@ def test_two_groups_full_and_sliding_window(request_runner, async_scheduling: bo
expected_stored=(0, 1, 2, 3, 4, 5),
)
# touch called from _get_reqs_to_store * 3 blocks, once for each group
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 6
runner.manager.touch.assert_not_called()
# EOS lands in the last slot of the 7th block (offset 6). No forward pass
# writes that slot, so the finishing step declines the block.
@@ -1379,13 +1383,7 @@ def test_two_groups_full_and_sliding_window(request_runner, async_scheduling: bo
expected_loaded=((0, 0), (0, 1), (0, 2), (1, 1), (1, 2)),
)
# 2 touch calls from get_num_new_matched_tokens (2 groups)
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 2
# full attention group touched all 3 blocks
assert len(touch_calls[0].args[0]) == 3
# sliding window group touched just the last 2 blocks
assert len(touch_calls[1].args[0]) == 2
runner.manager.touch.assert_not_called()
# 3 blocks are hit on GPU [0, 1, 2]
# 1 block loaded [3,]
@@ -1451,15 +1449,7 @@ def test_two_groups_different_block_sizes(request_runner, async_scheduling: bool
generate_store_output(keys)
)
runner.run(decoded_tokens=[0])
# _touch called from get_num_new_matched_tokens (2 groups) and
# _get_reqs_to_store (2 groups) → 4 touch calls total.
# Group 0 has 2 offload keys, group 1 has 1.
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 4
assert len(touch_calls[0].args[0]) == 2
assert len(touch_calls[1].args[0]) == 1
assert len(touch_calls[2].args[0]) == 2
assert len(touch_calls[3].args[0]) == 1
runner.manager.touch.assert_not_called()
# Get to 31 tokens
# No further blocks offloaded
@@ -1469,11 +1459,7 @@ def test_two_groups_different_block_sizes(request_runner, async_scheduling: bool
# Group 0 blocks: [0, 1], ending_token_offset = 24
# Group 1 blocks: [0, 1], ending_token_offset = 32
runner.run(decoded_tokens=[0])
# _get_reqs_to_store touch: only group 1 has a new block to store
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 2
assert len(touch_calls[0].args[0]) == 2
assert len(touch_calls[1].args[0]) == 2
runner.manager.touch.assert_not_called()
# Get to 35 tokens
# No further blocks offloaded
@@ -1483,11 +1469,7 @@ def test_two_groups_different_block_sizes(request_runner, async_scheduling: bool
# Group 0 blocks: [0, 1, 2], ending_token_offset = 36
# Group 1 blocks: [0, 1], ending_token_offset = 32
runner.run(decoded_tokens=[0])
# _get_reqs_to_store touch: only group 0 has a new block to store
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 2
assert len(touch_calls[0].args[0]) == 3
assert len(touch_calls[1].args[0]) == 2
runner.manager.touch.assert_not_called()
# Get to 47 tokens
# No further blocks offloaded
@@ -1497,11 +1479,7 @@ def test_two_groups_different_block_sizes(request_runner, async_scheduling: bool
# Group 0 blocks: [0, 1, 2, 3], ending_token_offset = 4
# Group 1 blocks: [0, 1, 2], ending_token_offset = 48
runner.run(decoded_tokens=[0])
# _get_reqs_to_store touch: both groups have a new block, each with 1 key
touch_calls = runner.manager.touch.call_args_list
assert len(touch_calls) == 2
assert len(touch_calls[0].args[0]) == 4
assert len(touch_calls[1].args[0]) == 3
runner.manager.touch.assert_not_called()
runner.run(decoded_tokens=[0], expected_stored=((0, 3), (1, 2)))
@@ -2629,27 +2607,14 @@ def test_async_preempt_readmit_before_transfer_output_is_deferred(request_runner
assert req_status.transfer_jobs == pending_store_jobs
@pytest.mark.parametrize("extra_retained", [0, 1, 3])
@pytest.mark.parametrize("async_scheduling", [True, False])
def test_swa_alignment_skip(request_runner, async_scheduling: bool):
"""SWA blocks unreachable by the load path are skipped during store.
def test_swa_alignment_skip(request_runner, async_scheduling: bool, extra_retained):
"""Store the window a cold consumer must restore at each FA boundary.
Simulates a DeepSeek V4-like hybrid architecture where SWA groups have
much smaller block sizes than the full-attention (MLA) group, causing
most SWA blocks to be unreachable by the alignment-based load path.
Setup:
- Group 0: full attention (MLA-like), block_size=16
- Group 1: SWA, block_size=4, sliding_window=8
alignment_tokens = 16, so 16 / 4 = 4 SWA blocks per alignment segment.
sliding_window_size_in_chunks = ceil(8 / 4) = 2.
Within each segment of 4 SWA blocks, only the trailing 2 are stored.
With 32 tokens (2 full-attn blocks, 8 SWA blocks):
- Group 0 stores: blocks 0, 1 (all full-attn blocks)
- Group 1 stores: blocks 2, 3, 6, 7 (skip 0,1,4,5)
For real DeepSeek V4 (100K tokens), this reduces SWA stores by ~78%.
With FA blocks of 16 tokens and SWA blocks of 4 tokens, a window of 8
needs the last two blocks per segment. Retaining three extra tokens for
MTP requires one more block; retaining just one token does not.
"""
full_attn_block_size = 16
swa_block_size = 4
@@ -2674,6 +2639,7 @@ def test_swa_alignment_skip(request_runner, async_scheduling: bool):
head_size=1,
dtype=torch.float32,
sliding_window=sliding_window,
extra_retained_tokens=extra_retained,
),
),
]
@@ -2691,16 +2657,17 @@ def test_swa_alignment_skip(request_runner, async_scheduling: bool):
# Group 0: full attention
assert kv_group_configs[0].sliding_window_size_in_chunks is None
assert kv_group_configs[0].tokens_per_chunk == full_attn_block_size
# Group 1: SWA with sliding_window_size of 2 chunks
assert kv_group_configs[1].sliding_window_size_in_chunks == 2
# Group 1: SWA, including any additional retained blocks
assert kv_group_configs[1].sliding_window_size_in_chunks == (
3 if extra_retained > 1 else 2
)
assert kv_group_configs[1].tokens_per_chunk == swa_block_size
# alignment_tokens = full_attn_block_size = 16
assert runner.connector_scheduler.config.alignment_tokens == full_attn_block_size
# Send 32 tokens = 2 full-attn blocks (block_size=16) = 8 SWA blocks
# (block_size=4). Decode 1 token to kick off processing (stores are
# deferred to next step).
num_tokens = 32
# Keep a partial last block so decoding does not reuse the producer's
# freed blocks before the harness records its deferred stores.
num_tokens = 33
runner.new_request(token_ids=[0] * num_tokens)
runner.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
@@ -2713,12 +2680,7 @@ def test_swa_alignment_skip(request_runner, async_scheduling: bool):
)
runner.run(
decoded_tokens=[EOS_TOKEN_ID],
# Group 0 (full attn, block_size=16): 2 offloaded chunks
# -> GPU blocks (0, 0) and (0, 1)
# Group 1 (SWA, block_size=4): 8 offloaded chunks, skip first 2
# per segment of 4:
# Segment 0 (blocks 0-3): skip 0,1 -> store (1, 2), (1, 3)
# Segment 1 (blocks 4-7): skip 4,5 -> store (1, 6), (1, 7)
# Retain each segment's tail, including MTP history when needed.
expected_stored=(
(0, 0),
(0, 1),
@@ -2726,27 +2688,26 @@ def test_swa_alignment_skip(request_runner, async_scheduling: bool):
(1, 3),
(1, 6),
(1, 7),
),
)
+ (((1, 1), (1, 5)) if extra_retained > 1 else ()),
)
# Verify that loads still work correctly for the stored SWA blocks.
runner.scheduler.reset_prefix_cache()
runner.new_request(token_ids=[0] * num_tokens + [1])
runner.manager.lookup.return_value = LookupResult.HIT
runner.connector_scheduler._maximal_prefix_lookup = lambda keys, ctx, *_: 2
runner.manager.lookup.side_effect = lambda key, ctx: (
LookupResult.HIT if (key, 0) in runner.offloaded else LookupResult.MISS
)
runner.run(
decoded_tokens=[EOS_TOKEN_ID],
# Group 0: full prefix lookup hits 2 offloaded chunks
# -> loads GPU blocks (0, 0), (0, 1)
# Group 1: sliding window lookup finds trailing 2 from last segment
# (blocks 6, 7 which were stored)
# -> loads GPU blocks (1, 6), (1, 7)
# The consumer restores the full FA prefix and the final SWA tail.
expected_loaded=(
(0, 0),
(0, 1),
(1, 6),
(1, 7),
),
)
+ (((1, 5),) if extra_retained > 1 else ()),
)
+428 -8
View File
@@ -23,6 +23,7 @@ from vllm.v1.kv_offload.cpu.common import (
)
from vllm.v1.kv_offload.cpu.manager import CPUOffloadingManager
from vllm.v1.kv_offload.cpu.policies.arc import ARCCachePolicy
from vllm.v1.kv_offload.cpu.policies.lru import LRUCachePolicy
def make_req_context(
@@ -430,31 +431,34 @@ def test_cpu_manager():
assert cpu_manager.lookup(to_key(0), _EMPTY_REQ_CTX) is LookupResult.MISS
# prepare load [2, 3]
prepare_load_output = cpu_manager.prepare_load(to_keys([2, 3]), _EMPTY_REQ_CTX)
load_ctx = make_req_context("load-2-3")
prepare_load_output = cpu_manager.prepare_load(to_keys([2, 3]), load_ctx)
verify_load_output(prepare_load_output, [1, 2])
# prepare store with no space ([2, 3] is being loaded)
assert cpu_manager.prepare_store(to_keys([6, 7, 8]), _EMPTY_REQ_CTX) is None
# complete load [2, 3]. Load changes the eviction list, making 2, 3 recent.
cpu_manager.complete_load(to_keys([2, 3]), _EMPTY_REQ_CTX)
cpu_manager.complete_load(to_keys([2, 3]), load_ctx)
cpu_manager.on_request_finished(load_ctx)
# prepare store [6, 7, 8] -> evicts [4, 5, 2] (oldest)
# prepare store [6, 7, 8] -> evicts [4, 5, 3] (oldest). Within
# the accessed prefix [2, 3], the tail is less valuable than the head.
prepare_store_output = cpu_manager.prepare_store(to_keys([6, 7, 8]), _EMPTY_REQ_CTX)
verify_store_output(
prepare_store_output,
ExpectedPrepareStoreOutput(
keys_to_store=[6, 7, 8],
store_chunk_ids=[1, 0, 3],
evicted_keys=[4, 5, 2],
store_chunk_ids=[2, 0, 3],
evicted_keys=[4, 5, 3],
),
)
# complete store [6, 7, 8]
cpu_manager.complete_store(to_keys([6, 7, 8]), _EMPTY_REQ_CTX)
# touch [3, 6, 7] (move to end of LRU order)
cpu_manager.touch(to_keys([3, 6, 7]), _EMPTY_REQ_CTX)
# touch [2, 6, 7] (move to end of LRU order)
cpu_manager.touch(to_keys([2, 6, 7]), _EMPTY_REQ_CTX)
# prepare store [7, 9] -> evicts [8] (oldest following previous touch)
prepare_store_output = cpu_manager.prepare_store(to_keys([9]), _EMPTY_REQ_CTX)
@@ -477,7 +481,7 @@ def test_cpu_manager():
verify_events(
cpu_manager.take_events(),
expected_stores=({3, 4, 5}, {6, 7, 8}),
expected_evictions=({4, 5, 2}, {8}),
expected_evictions=({4, 5, 3}, {8}),
)
@@ -518,6 +522,65 @@ def test_prepare_load_preserves_key_order():
manager.complete_load([key_a, key_b, key_c], _EMPTY_REQ_CTX) # order irrelevant
def test_lru_batch_eviction_failure_is_atomic():
manager = make_cpu_manager(num_chunks=4, cache_policy="lru")
policy = manager._policy
assert isinstance(policy, LRUCachePolicy)
keys = to_keys([1, 2, 3, 4])
assert manager.prepare_store(keys, _EMPTY_REQ_CTX) is not None
manager.complete_store(keys, _EMPTY_REQ_CTX)
protected = set(keys[1:])
assert policy.evict(2, protected) is None
assert all(manager.lookup(key, _EMPTY_REQ_CTX) is LookupResult.HIT for key in keys)
evicted = policy.evict(1, protected)
assert evicted is not None
assert [key for key, _ in evicted] == [keys[0]]
def test_lru_repeated_pin_cycles_compact_lazy_heap_entries():
manager = make_cpu_manager(num_chunks=1, cache_policy="lru")
policy = manager._policy
assert isinstance(policy, LRUCachePolicy)
key = to_key(1)
assert manager.prepare_store([key], _EMPTY_REQ_CTX) is not None
manager.complete_store([key], _EMPTY_REQ_CTX)
for _ in range(128):
manager.prepare_load([key], _EMPTY_REQ_CTX)
manager.complete_load([key], _EMPTY_REQ_CTX)
assert len(policy._heap) < 64
evicted = policy.evict(1, set())
assert evicted is not None
assert [evicted_key for evicted_key, _ in evicted] == [key]
def test_reset_discards_stale_request_access_classification():
manager = make_cpu_manager(num_chunks=1, cache_policy="arc")
policy = manager._policy
assert isinstance(policy, ARCCachePolicy)
key = to_key(1)
resumed_ctx = make_req_context("resumed")
assert manager.prepare_store([key], resumed_ctx) is not None
manager.complete_store([key], resumed_ctx)
manager.reset_cache()
replacement_ctx = make_req_context("replacement")
assert manager.prepare_store([key], replacement_ctx) is not None
manager.complete_store([key], replacement_ctx)
manager.on_request_finished(replacement_ctx)
assert key in policy.t1
manager.prepare_load([key], resumed_ctx)
manager.complete_load([key], resumed_ctx)
manager.on_request_finished(resumed_ctx)
assert key in policy.t2
class TestARCPolicy:
"""Unit tests for CPUOffloadingManager with ARC eviction policy."""
@@ -1042,6 +1105,48 @@ def test_filter_reused_manager_oversized_offer_makes_progress():
assert stored_keys == set(keys)
def test_store_threshold_does_not_hide_ready_reuse():
manager = make_cpu_manager(
num_chunks=2,
cache_policy="lru",
store_threshold=2,
max_tracker_size=2,
)
head, tail, noise_1, noise_2, replacement = to_keys(list(range(5)))
seed_ctx = make_req_context("seed")
output = manager.prepare_store([head, tail], seed_ctx)
assert output is not None
assert not output.keys_to_store
output = manager.prepare_store([head, tail], seed_ctx)
assert output is not None
assert output.keys_to_store == [head, tail]
manager.complete_store([head, tail], seed_ctx)
manager.on_request_finished(seed_ctx)
# Age both resident keys out of the admission tracker without storing the
# noise keys. Reusing the tail recreates its counter at one, below the
# threshold, but must still refresh its cache recency.
output = manager.prepare_store([noise_1, noise_2], make_req_context("noise"))
assert output is not None
assert not output.keys_to_store
reuse_ctx = make_req_context("reuse")
skipped_before_reuse = manager.stores_skipped_in_current_batch
output = manager.prepare_store([tail], reuse_ctx)
assert output is not None
assert not output.keys_to_store
assert manager.stores_skipped_in_current_batch == skipped_before_reuse
manager.on_request_finished(reuse_ctx)
replacement_ctx = make_req_context("replacement")
output = manager.prepare_store([replacement], replacement_ctx)
assert output is not None
assert not output.keys_to_store
output = manager.prepare_store([replacement], replacement_ctx)
assert output is not None
assert output.evicted_keys == [head]
def test_evictable_cache_chunk_count():
"""
Verifies _num_evictable_cache_chunks is maintained correctly through the
@@ -1156,3 +1261,318 @@ def test_touch_forwards_req_context_to_policy(monkeypatch):
assert len(received) == 1
assert received[0][0] == keys
assert received[0][1] is ctx
@pytest.mark.parametrize("finish_before_completion", [False, True])
def test_request_finish_orders_lru_prefix_independent_of_store_completion(
finish_before_completion: bool,
):
"""A transfer's completion order must not make the prefix head LRU."""
manager = make_cpu_manager(num_chunks=4, cache_policy="lru")
prefix = to_keys([1, 2, 3, 4])
ctx = make_req_context("prefix")
output = manager.prepare_store(prefix, ctx)
assert output is not None
if finish_before_completion:
manager.on_request_finished(ctx)
manager.complete_store(set(prefix), ctx)
if not finish_before_completion:
manager.on_request_finished(ctx)
output = manager.prepare_store(to_keys([5]), make_req_context("evict"))
assert output is not None
assert output.evicted_keys == to_keys([4])
@pytest.mark.parametrize("finish_before_completion", [False, True])
def test_request_finish_orders_lru_prefix_independent_of_load_completion(
finish_before_completion: bool,
):
manager = make_cpu_manager(num_chunks=4, cache_policy="lru")
prefix = to_keys([1, 2, 3, 4])
seed_ctx = make_req_context("seed")
output = manager.prepare_store(prefix, seed_ctx)
assert output is not None
manager.complete_store(prefix, seed_ctx)
reuse_ctx = make_req_context("reuse")
manager.prepare_load(prefix, reuse_ctx)
if finish_before_completion:
manager.on_request_finished(reuse_ctx)
manager.complete_load(set(prefix), reuse_ctx)
if not finish_before_completion:
manager.on_request_finished(reuse_ctx)
output = manager.prepare_store(to_keys([5]), make_req_context("evict"))
assert output is not None
assert output.evicted_keys == to_keys([4])
def test_late_old_completion_does_not_override_newer_request_recency():
manager = make_cpu_manager(num_chunks=4, cache_policy="lru")
old_keys = to_keys([1, 2])
new_keys = to_keys([3, 4])
old_ctx = make_req_context("old")
assert manager.prepare_store(old_keys, old_ctx) is not None
manager.on_request_finished(old_ctx)
new_ctx = make_req_context("new")
assert manager.prepare_store(new_keys, new_ctx) is not None
manager.complete_store(new_keys, new_ctx)
manager.on_request_finished(new_ctx)
# Physical completion is late, but the logical access is still older.
manager.complete_store(old_keys, old_ctx)
output = manager.prepare_store(to_keys([5]), make_req_context("evict"))
assert output is not None
assert output.evicted_keys == [old_keys[-1]]
def test_arc_counts_reuse_once_and_keeps_insertions_in_t1():
manager = make_cpu_manager(num_chunks=4, cache_policy="arc")
policy = manager._policy
assert isinstance(policy, ARCCachePolicy)
prefix = to_keys([1, 2, 3, 4])
seed_ctx = make_req_context("seed")
assert manager.prepare_store(prefix, seed_ctx) is not None
manager.complete_store(prefix, seed_ctx)
# Repeated store offers from the same request must not become ARC hits.
assert manager.prepare_store(prefix, seed_ctx) is not None
# Nor should an internal read used to cascade the new chunks to a tier.
manager.prepare_load(prefix, seed_ctx)
manager.complete_load(prefix, seed_ctx)
manager.on_request_finished(seed_ctx)
assert list(policy.t1) == list(reversed(prefix))
assert not policy.t2
reuse_ctx = make_req_context("reuse")
manager.prepare_load(prefix, reuse_ctx)
manager.complete_load(prefix, reuse_ctx)
# A duplicate internal pin, as used by tiering cascades, is deduplicated.
manager.prepare_load(prefix, reuse_ctx)
manager.complete_load(prefix, reuse_ctx)
manager.on_request_finished(reuse_ctx)
assert not policy.t1
assert list(policy.t2) == list(reversed(prefix))
def test_arc_reuse_wins_if_same_request_later_reinserts_key():
manager = make_cpu_manager(num_chunks=1, cache_policy="arc")
policy = manager._policy
assert isinstance(policy, ARCCachePolicy)
key_1, key_2 = to_keys([1, 2])
seed_ctx = make_req_context("seed")
assert manager.prepare_store([key_1], seed_ctx) is not None
manager.complete_store([key_1], seed_ctx)
manager.on_request_finished(seed_ctx)
reuse_ctx = make_req_context("reuse-and-reinsert")
manager.prepare_load([key_1], reuse_ctx)
manager.complete_load([key_1], reuse_ctx)
other_ctx = make_req_context("evict-reused-key")
assert manager.prepare_store([key_2], other_ctx) is not None
manager.complete_store([key_2], other_ctx)
manager.on_request_finished(other_ctx)
assert manager.prepare_store([key_1], reuse_ctx) is not None
manager.complete_store([key_1], reuse_ctx)
manager.on_request_finished(reuse_ctx)
assert key_1 not in policy.t1
assert list(policy.t2) == [key_1]
def test_request_finish_forwards_grouped_deduplicated_accesses(monkeypatch):
manager = make_cpu_manager(num_chunks=5)
existing = make_offload_key(b"existing", 0)
group_0_new = make_offload_key(b"group-0-new", 0)
group_1_head = make_offload_key(b"group-1-head", 1)
group_1_tail = make_offload_key(b"group-1-tail", 1)
seed_ctx = make_req_context("seed")
assert manager.prepare_store([existing], seed_ctx) is not None
manager.complete_store([existing], seed_ctx)
ctx = make_req_context("grouped")
# Group 1 is observed first, but policy finalization follows group index.
offered = [group_1_head, existing, group_0_new]
assert manager.prepare_store(offered, ctx) is not None
# Later offers extend a group's prefix and may repeat earlier keys.
assert (
manager.prepare_store([group_0_new, group_1_head, group_1_tail], ctx)
is not None
)
received = []
def on_request_finished(key_groups, insertion_only_keys, reused_keys, req_context):
received.append((key_groups, insertion_only_keys, reused_keys, req_context))
monkeypatch.setattr(manager._policy, "on_request_finished", on_request_finished)
manager.on_request_finished(ctx)
manager.on_request_finished(ctx)
assert received == [
(
((existing, group_0_new), (group_1_head, group_1_tail)),
{group_0_new, group_1_head, group_1_tail},
{existing},
ctx,
)
]
def test_failed_store_records_access_once_and_uses_store_miss_hook(monkeypatch):
manager = make_cpu_manager(num_chunks=1)
resident, candidate = to_keys([1, 2])
seed_ctx = make_req_context("seed")
assert manager.prepare_store([resident], seed_ctx) is not None
manager.complete_store([resident], seed_ctx)
pin_ctx = make_req_context("pin")
manager.prepare_load([resident], pin_ctx)
record_calls = 0
original_record = manager._record_request_cache_access
def record_access(*args, **kwargs):
nonlocal record_calls
record_calls += 1
return original_record(*args, **kwargs)
store_miss_calls = []
def on_store_miss(keys, req_context):
store_miss_calls.append((list(keys), req_context))
finalized = []
def on_request_finished(key_groups, insertion_only_keys, reused_keys, req_context):
finalized.append((key_groups, insertion_only_keys, reused_keys, req_context))
monkeypatch.setattr(manager, "_record_request_cache_access", record_access)
monkeypatch.setattr(manager._policy, "on_store_miss", on_store_miss)
monkeypatch.setattr(manager._policy, "on_request_finished", on_request_finished)
ctx = make_req_context("failed-store")
assert manager.prepare_store([candidate, resident], ctx) is None
assert record_calls == 1
assert store_miss_calls == [([candidate], ctx)]
manager.on_request_finished(ctx)
assert finalized == [
(((candidate, resident),), set(), {resident}, ctx),
]
manager.complete_load([resident], pin_ctx)
def test_arc_ghost_hit_adapts_once_per_request_before_insertion():
manager = make_cpu_manager(num_chunks=2, cache_policy="arc")
policy = manager._policy
assert isinstance(policy, ARCCachePolicy)
keys = to_keys([1, 2, 3])
seed_ctx = make_req_context("seed")
assert manager.prepare_store(keys[:2], seed_ctx) is not None
manager.complete_store(keys[:2], seed_ctx)
manager.on_request_finished(seed_ctx)
evict_ctx = make_req_context("create-ghost")
output = manager.prepare_store([keys[2]], evict_ctx)
assert output is not None
[ghost_key] = output.evicted_keys
manager.complete_store([keys[2]], evict_ctx)
manager.on_request_finished(evict_ctx)
assert ghost_key in policy.b1
resident_keys = [key for key in keys if key != ghost_key]
pin_ctx = make_req_context("pin-residents")
manager.prepare_load(resident_keys, pin_ctx)
ghost_ctx = make_req_context("ghost-hit")
target_before = policy.target_t1_size
assert manager.prepare_store([ghost_key], ghost_ctx) is None
target_after_first_offer = policy.target_t1_size
assert target_after_first_offer > target_before
assert manager.prepare_store([ghost_key], ghost_ctx) is None
assert policy.target_t1_size == target_after_first_offer
manager.complete_load(resident_keys, pin_ctx)
output = manager.prepare_store([ghost_key], ghost_ctx)
assert output is not None
assert policy.target_t1_size == target_after_first_offer
manager.complete_store([ghost_key], ghost_ctx)
manager.on_request_finished(ghost_ctx)
assert ghost_key in policy.t1
assert ghost_key not in policy.t2
def test_arc_pending_chunk_is_not_a_frequency_hit():
manager = make_cpu_manager(num_chunks=2, cache_policy="arc")
policy = manager._policy
assert isinstance(policy, ARCCachePolicy)
key = to_key(1)
writer_ctx = make_req_context("writer")
assert manager.prepare_store([key], writer_ctx) is not None
observer_ctx = make_req_context("pending-observer")
output = manager.prepare_store([key], observer_ctx)
assert output is not None and not output.keys_to_store
manager.on_request_finished(observer_ctx)
chunk = policy.get(key)
assert chunk is not None and not chunk.is_ready
assert key in policy.t1
assert key not in policy.t2
def test_request_key_positions_override_store_observation_order():
manager = make_cpu_manager(num_chunks=2, cache_policy="lru")
head, tail = to_keys([1, 2])
ctx = make_req_context("out-of-order-store")
ctx.set_offload_key_position(head, 16)
ctx.set_offload_key_position(tail, 32)
# A backfill or partial-tail path may offer a later key first.
assert manager.prepare_store([tail], ctx) is not None
assert manager.prepare_store([head], ctx) is not None
manager.on_request_finished(ctx)
manager.complete_store({head, tail}, ctx)
output = manager.prepare_store([to_key(3)], make_req_context("evict-tail"))
assert output is not None
assert output.evicted_keys == [tail]
def test_request_key_positions_order_tails_across_kv_groups():
manager = make_cpu_manager(num_chunks=4, cache_policy="lru")
group_0_head = make_offload_key(b"group-0-head", 0)
group_0_tail = make_offload_key(b"group-0-tail", 0)
group_1_head = make_offload_key(b"group-1-head", 1)
group_1_tail = make_offload_key(b"group-1-tail", 1)
keys = [group_0_head, group_0_tail, group_1_head, group_1_tail]
ctx = make_req_context("hybrid-groups")
for key in (group_0_head, group_1_head):
ctx.set_offload_key_position(key, 16)
for key in (group_0_tail, group_1_tail):
ctx.set_offload_key_position(key, 32)
assert manager.prepare_store(keys, ctx) is not None
manager.complete_store(keys, ctx)
manager.on_request_finished(ctx)
output = manager.prepare_store(to_keys([10, 11]), make_req_context("evict"))
assert output is not None
assert set(output.evicted_keys) == {group_0_tail, group_1_tail}
@@ -906,12 +906,13 @@ def test_insufficient_space_raises_clear_error(monkeypatch):
monkeypatch.setattr(region.os, "open", mock_open)
monkeypatch.setattr(region.os, "unlink", mock_unlink)
monkeypatch.setattr(region.os, "close", mock_close)
mock_check = MagicMock(
side_effect=RuntimeError("Insufficient space in /dev/shm: 30 GB required.")
)
monkeypatch.setattr(
region,
"check_shm_free_space",
lambda *a, **kw: (_ for _ in ()).throw(
RuntimeError("Insufficient space in /dev/shm: 30 GB required.")
),
mock_check,
)
with pytest.raises(RuntimeError, match="Insufficient space"):
@@ -925,6 +926,10 @@ def test_insufficient_space_raises_clear_error(monkeypatch):
mock_unlink.assert_called_once_with(mmap_path)
mock_close.assert_called_once_with(9999)
mock_check.assert_called_once_with(
4 * PAGE_SIZE,
allocation_name="CPU KV offload shared region in /dev/shm",
)
def test_ftruncate_failure_cleans_up_creator(monkeypatch):
@@ -40,6 +40,7 @@ from vllm.v1.kv_offload.base import (
TierMatcher,
make_offload_key,
)
from vllm.v1.kv_offload.cpu.policies.lru import LRUCachePolicy
from vllm.v1.kv_offload.tiering.base import (
JobResult,
SecondaryTierManager,
@@ -753,14 +754,64 @@ class TestTieringOffloadingManager:
# Touch chunks
self.manager.touch(chunks, _CTX)
# Verify touch was called on primary tier (check LRU order)
primary_keys = list(self.primary_tier._policy.evictable_chunks.keys())
assert primary_keys[-3:] == list(reversed(chunks))
# Verify touch was called on the primary tier (head is most recent).
policy = self.primary_tier._policy
assert isinstance(policy, LRUCachePolicy)
ranks = policy._ranks
assert ranks[chunks[2]] < ranks[chunks[1]] < ranks[chunks[0]]
# Verify touch was propagated to all secondary tiers
self.secondary_tier1.touch.assert_called_once_with(chunks, _CTX)
self.secondary_tier2.touch.assert_called_once_with(chunks, _CTX)
def test_request_order_survives_late_cascade_completion(self, manager_setup):
"""Cascade completion must not replace request order with I/O order."""
chunks = to_keys(range(5))
self._start_request()
output = self.manager.prepare_store(chunks, _CTX)
assert output is not None
self.manager.complete_store(chunks, _CTX, success=True)
# Finalize while both secondary-tier cascades still pin primary chunks.
self.manager.on_request_finished(_CTX)
self._simulate_on_schedule_end()
self._simulate_on_schedule_end()
evict_ctx = ReqContext(req_id="evict")
self._start_request(evict_ctx)
output = self.manager.prepare_store(to_keys([5]), evict_ctx)
assert output is not None
assert output.evicted_keys == [chunks[-1]]
def test_late_old_store_submission_does_not_override_newer_request_order(
self, manager_setup
):
"""Cascade submission after finish is not a new primary access."""
old_blocks = to_keys(range(2))
old_ctx = ReqContext(req_id="old")
self._start_request(old_ctx)
assert self.manager.prepare_store(old_blocks, old_ctx) is not None
self.manager.on_request_finished(old_ctx)
new_blocks = to_keys(range(2, 5))
new_ctx = ReqContext(req_id="new")
self._start_request(new_ctx)
assert self.manager.prepare_store(new_blocks, new_ctx) is not None
self.manager.complete_store(new_blocks, new_ctx, success=True)
self.manager.on_request_finished(new_ctx)
# The old GPU->primary write lands after the newer request finished.
# Its cascade pins must not turn it into the more recent request.
self.manager.complete_store(old_blocks, old_ctx, success=True)
self._simulate_on_schedule_end()
self._simulate_on_schedule_end()
evict_ctx = ReqContext(req_id="evict")
self._start_request(evict_ctx)
output = self.manager.prepare_store(to_keys([5]), evict_ctx)
assert output is not None
assert output.evicted_keys == [old_blocks[-1]]
def test_failed_store_no_cascade(self, manager_setup):
"""Test that failed GPU→primary store doesn't cascade."""
chunks = to_keys(range(3))
@@ -873,10 +924,10 @@ class TestTieringOffloadingManager:
job_metadata = self.secondary_tier1.submit_store.call_args.args[0]
assert job_metadata.req_context is ctx
def test_on_request_finished_delays_secondary_until_store_submitted(
def test_on_request_finished_delays_only_secondary_until_store_submitted(
self, manager_setup
):
"""Manager hook is eager; secondary hooks wait for cascade submission."""
"""Primary order commits immediately; secondary cleanup waits."""
chunks = to_keys(range(2))
ctx = ReqContext(req_id="req_delayed_secondary")
calls: list[tuple[str, str]] = []
+105 -3
View File
@@ -21,7 +21,12 @@ pytest.importorskip("triton")
if not torch.cuda.is_available():
pytest.skip("CUDA required for Gumbel sampler tests", allow_module_level=True)
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
from vllm.triton_utils import tl, triton
from vllm.v1.worker.gpu.sample.gumbel import (
_uniform64_from_random53,
gumbel_sample,
murmur3_hash32,
)
DEVICE = "cuda"
VOCAB_SIZE = 200_000
@@ -33,6 +38,103 @@ HEAD_LOG_GAP = 18.0
Z_TOLERANCE = 10.0
@triton.jit
def _murmur3_known_answer_kernel(
seeds_ptr,
positions_ptr,
offsets_ptr,
hashes_ptr,
domain_hashes_ptr,
numel: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
idx = tl.arange(0, BLOCK_SIZE)
mask = idx < numel
seed = tl.load(seeds_ptr + idx, mask=mask)
pos = tl.load(positions_ptr + idx, mask=mask)
offset = tl.load(offsets_ptr + idx, mask=mask)
hash32 = murmur3_hash32(seed, pos, offset).to(tl.int64)
domain_hash32 = murmur3_hash32(seed, pos, offset, domain=0x9E3779B9).to(tl.int64)
tl.store(hashes_ptr + idx, hash32, mask=mask)
tl.store(domain_hashes_ptr + idx, domain_hash32, mask=mask)
@triton.jit
def _uniform64_endpoint_kernel(
random53_ptr,
uniform_ptr,
numel: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
idx = tl.arange(0, BLOCK_SIZE)
mask = idx < numel
random53 = tl.load(random53_ptr + idx, mask=mask).to(tl.uint64)
tl.store(uniform_ptr + idx, _uniform64_from_random53(random53), mask=mask)
def test_murmur3_known_answers():
seeds = torch.tensor(
[0, 1, -1, 0x123456789ABCDEF, -(1 << 63), (1 << 63) - 1],
dtype=torch.int64,
device=DEVICE,
)
positions = torch.tensor(
[0, 2, 17, 123456789, 1 << 30, (1 << 30) + 7],
dtype=torch.int64,
device=DEVICE,
)
offsets = torch.tensor(
[0, 3, 1023, 199999, 4096, 0xFFFFFFFF],
dtype=torch.int64,
device=DEVICE,
)
hashes = torch.empty_like(seeds)
domain_hashes = torch.empty_like(seeds)
_murmur3_known_answer_kernel[(1,)](
seeds,
positions,
offsets,
hashes,
domain_hashes,
numel=seeds.numel(),
BLOCK_SIZE=8,
)
assert hashes.tolist() == [
0x8134CDF8,
0x23B53F91,
0xC8C13C14,
0x5DDE974F,
0xF1A9355B,
0xD952F9AA,
]
assert domain_hashes.tolist() == [
0xD28AD962,
0xE3AAF818,
0xD223C51C,
0x0547D2FE,
0x3AED160F,
0x49E8EA7F,
]
def test_uniform64_excludes_endpoints():
random53 = torch.tensor([0, (1 << 53) - 1], dtype=torch.int64, device=DEVICE)
uniform = torch.empty(2, dtype=torch.float64, device=DEVICE)
_uniform64_endpoint_kernel[(1,)](
random53,
uniform,
numel=random53.numel(),
BLOCK_SIZE=2,
)
assert torch.isfinite(uniform).all()
assert ((uniform > 0.0) & (uniform < 1.0)).all()
assert uniform.tolist() == [2.0**-54, 1.0 - 2.0**-53]
def _make_heavy_tailed_counts(seed: int = 1234) -> torch.Tensor:
"""Non-negative int64 counts of shape [VOCAB_SIZE]; target prob = counts/N."""
gen = torch.Generator(device=DEVICE).manual_seed(seed)
@@ -180,7 +282,7 @@ def test_full_vocab_distribution_fidelity():
def test_drafting_uses_a_separate_noise_stream():
"""is_drafting salts the Philox offset: same inputs, different draws.
"""is_drafting salts the RNG position: same inputs, different draws.
The draft proposal and the residual resample after a rejection must be
independent. They key noise by the same (seed, pos), so only the salt keeps
@@ -189,7 +291,7 @@ def test_drafting_uses_a_separate_noise_stream():
tests/v1/spec_decode/test_rejection_sampler_utils.py for the distributional
consequence.
Relocating the offset must not distort the draw either, so both streams are
Salting the position must not distort the draw either, so both streams are
checked against the target's far-tail mass, which sits HEAD_LOG_GAP logits
below the head -- the regime where fp32 Gumbel precision matters.
"""