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-27 18:25:21 +09:00
1165 changed files with 51759 additions and 14579 deletions
@@ -15,7 +15,7 @@ from vllm.model_executor.offloader import (
)
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
from ..utils import compare_two_settings
from ...utils import compare_two_settings
@pytest.mark.parametrize("disable_pin_memory", [False, True])
@@ -0,0 +1,302 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
import vllm.device_allocator.cumem as cumem
from vllm import LLM, SamplingParams
from vllm.device_allocator import get_mem_allocator_instance
from vllm.platforms import current_platform
from ....utils import create_new_process_for_each_test
DEVICE_TYPE = current_platform.device_type
def mapped_usage(allocator) -> int:
"""Bytes the allocator still has mapped on the device.
`torch.accelerator.get_memory_info()` is a device-wide `cudaMemGetInfo` /
`hipMemGetInfo` query, so its delta also carries whatever else on the GPU
allocates or frees while we measure. The allocator's own bookkeeping is
process-local and exact.
"""
return sum(
data.handle[1]
for data in allocator.pointer_to_data.values()
if not data.is_asleep
)
def _wake_up_with_poisoned_mappings(allocator, byte_value: int = 0xA5) -> None:
"""Wake discarded allocations with deterministic nonzero contents."""
original_create_and_map = cumem.create_and_map
def create_and_map_with_poison(handle) -> None:
original_create_and_map(handle)
_, size, ptr, _ = handle
cumem.libcudart.cudaMemset(ptr, byte_value, size)
cumem.create_and_map = create_and_map_with_poison
try:
allocator.wake_up()
finally:
cumem.create_and_map = original_create_and_map
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_python_error():
"""Test if Python error occurs when there's low-level
error happening from the C++ side.
"""
allocator = get_mem_allocator_instance()
total_bytes = torch.accelerator.get_memory_info()[1]
alloc_bytes = int(total_bytes * 0.7)
tensors = []
with allocator.use_memory_pool():
# allocate 70% of the total memory
x = torch.empty(alloc_bytes, dtype=torch.uint8, device=DEVICE_TYPE)
tensors.append(x)
# release the memory
allocator.sleep(offload_tags=())
# allocate more memory than the total memory
y = torch.empty(alloc_bytes, dtype=torch.uint8, device=DEVICE_TYPE)
tensors.append(y)
with pytest.raises(RuntimeError):
# when the allocator is woken up, it should raise an error
# because we don't have enough memory
allocator.wake_up()
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_basic_cumem():
# some tensors from default memory pool
shape = (1024, 1024)
x = torch.empty(shape, device=DEVICE_TYPE)
x.zero_()
# some tensors from custom memory pool
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool():
# custom memory pool
y = torch.empty(shape, device=DEVICE_TYPE)
y.zero_()
y += 1
z = torch.empty(shape, device=DEVICE_TYPE)
z.zero_()
z += 2
# they can be used together
output = x + y + z
assert torch.allclose(output, torch.ones_like(output) * 3)
# Track the allocator's own mapped bytes, not device-wide free memory.
mapped_bytes = mapped_usage(allocator)
assert mapped_bytes >= y.nbytes + z.nbytes
allocator.sleep()
assert mapped_usage(allocator) == 0
allocator.wake_up()
assert mapped_usage(allocator) == mapped_bytes
# they can be used together
output = x + y + z
assert torch.allclose(output, torch.ones_like(output) * 3)
@pytest.mark.parametrize("full_sleep", [0, 1, 2], ids=["kv-only", "sleep-1", "sleep-2"])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_release_kv_cache_memory_preserves_generation(full_sleep, monkeypatch):
"""Rejected release and KV-only/full sleep cycles preserve greedy tokens."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
kv_cache_memory_bytes = 256 * 1024 * 1024
llm = LLM(
"Qwen/Qwen3-0.6B",
enable_sleep_mode=True,
enforce_eager=True,
kv_cache_memory_bytes=kv_cache_memory_bytes,
max_model_len=1024,
max_num_seqs=4,
gpu_memory_utilization=0.05,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
def get_mapped_bytes_by_tag(worker):
allocator = get_mem_allocator_instance()
mapped_bytes = mapped_usage(allocator)
kv_cache_bytes = sum(
data.handle[1]
for data in allocator.pointer_to_data.values()
if data.tag == "kv_cache" and not data.is_asleep
)
return mapped_bytes, kv_cache_bytes
mapped_before, kv_cache_before = llm.collective_rpc(get_mapped_bytes_by_tag)[0]
# Utility RPC transports the engine error as a plain Exception.
with pytest.raises(Exception, match="requires a completed pause"):
llm.release_kv_cache_memory()
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == mapped_before
assert not llm.llm_engine.is_sleeping()
assert llm.generate(prompt, sampling_params)[0].outputs[0].token_ids == expected
llm.sleep(level=0)
llm.release_kv_cache_memory()
mapped_after, kv_cache_after = llm.collective_rpc(get_mapped_bytes_by_tag)[0]
assert kv_cache_before > 0
assert kv_cache_after == 0
assert mapped_before - mapped_after >= kv_cache_before
assert mapped_after > 0
assert llm.llm_engine.is_sleeping()
if full_sleep:
llm.sleep(level=full_sleep)
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == 0
llm.wake_up(tags=None if full_sleep else ["kv_cache"])
if full_sleep == 2:
llm.collective_rpc("reload_weights")
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == mapped_before
assert not llm.llm_engine.is_sleeping()
actual = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
assert actual == expected
@pytest.mark.parametrize("first_level", [1, 2])
@pytest.mark.parametrize("second_level", [1, 2])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_sleep_with_only_weights_asleep(first_level, second_level, monkeypatch):
"""Repeated sleep after KV-only wake preserves mappings and recoverability."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
llm = LLM(
"Qwen/Qwen3-0.6B",
enable_sleep_mode=True,
enforce_eager=True,
kv_cache_memory_bytes=256 * 1024 * 1024,
max_model_len=1024,
max_num_seqs=4,
gpu_memory_utilization=0.05,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
def get_mapped_bytes(worker):
return mapped_usage(get_mem_allocator_instance())
llm.sleep(level=first_level)
llm.wake_up(tags=["kv_cache"])
mapped_before = llm.collective_rpc(get_mapped_bytes)[0]
assert mapped_before > 0
llm.sleep(level=second_level)
assert llm.collective_rpc(get_mapped_bytes)[0] == mapped_before
llm.wake_up(tags=["weights"])
if first_level == 2:
llm.collective_rpc("reload_weights")
assert not llm.llm_engine.is_sleeping()
actual = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
assert actual == expected
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_discard_tags():
"""Test that discard(tags) selectively frees GPU memory for specific
tags while keeping other tags mapped and usable."""
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool("weights"):
weights = torch.ones(1024, 1024, device=DEVICE_TYPE)
with allocator.use_memory_pool("kv_cache"):
kv = torch.ones(512, 512, device=DEVICE_TYPE)
mapped_bytes = mapped_usage(allocator)
# Discard kv_cache only — weights should remain valid
allocator.discard("kv_cache")
mapped_bytes_after_discard = mapped_usage(allocator)
assert mapped_bytes - mapped_bytes_after_discard >= kv.nbytes
assert mapped_bytes_after_discard >= weights.nbytes
# Weights are still usable
assert torch.allclose(weights, torch.ones_like(weights))
# Wake up and verify kv_cache is remapped; discarded contents are undefined.
allocator.wake_up()
assert kv.shape == (512, 512)
# Full sleep/wake cycle still works after discard
allocator.sleep(offload_tags="weights")
allocator.wake_up()
assert torch.allclose(weights, torch.ones_like(weights))
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.skipif(current_platform.is_xpu(), reason="Uses the CuMem allocator")
def test_level2_discards_ordinary_tensor_with_weights_tag():
"""Reproduce the level-2 variant for an ordinary tensor in weights."""
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool("weights"):
fake_weight = torch.full((4096,), 0x44, dtype=torch.uint8, device=DEVICE_TYPE)
ordinary_tensor = torch.full(
(4096,), 0x55, dtype=torch.uint8, device=DEVICE_TYPE
)
pointers = (fake_weight.data_ptr(), ordinary_tensor.data_ptr())
allocator.sleep(offload_tags=())
_wake_up_with_poisoned_mappings(allocator)
torch.accelerator.synchronize()
assert (fake_weight.data_ptr(), ordinary_tensor.data_ptr()) == pointers
assert torch.all(fake_weight == 0xA5)
assert torch.all(ordinary_tensor == 0xA5)
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.skipif(current_platform.is_xpu(), reason="CUDA graph not supported on XPU")
def test_cumem_with_cudagraph():
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool():
weight = torch.eye(1024, device=DEVICE_TYPE)
with allocator.use_memory_pool(tag="discard"):
cache = torch.empty(1024, 1024, device=DEVICE_TYPE)
def model(x):
out = x @ weight
cache[: out.size(0)].copy_(out)
return out + 1
x = torch.empty(128, 1024, device=DEVICE_TYPE)
# warmup
model(x)
# capture cudagraph
model_graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(model_graph):
y = model(x)
mapped_bytes = mapped_usage(allocator)
assert mapped_bytes >= weight.nbytes + cache.nbytes
allocator.sleep()
assert mapped_usage(allocator) == 0
allocator.wake_up()
assert mapped_usage(allocator) == mapped_bytes
# after waking up, the content in the weight tensor
# should be restored, but the content in the cache tensor
# should be discarded
# this operation is also compatible with cudagraph
x.random_()
model_graph.replay()
# cache content is as expected
assert torch.allclose(x, cache[: x.size(0)])
# output content is as expected
assert torch.allclose(y, x + 1)
@@ -0,0 +1,312 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
import pytest
import torch
import vllm.device_allocator.cumem as cumem
import vllm.envs as envs
from vllm import LLM, AsyncEngineArgs, AsyncLLMEngine, SamplingParams
from vllm.platforms import current_platform
from vllm.utils.mem_constants import GiB_bytes
from ....utils import create_new_process_for_each_test, multi_gpu_test, requires_fp8
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.parametrize(
"model",
[
# sleep mode with safetensors
"hmellor/tiny-random-LlamaForCausalLM",
# sleep mode with pytorch checkpoint
"facebook/opt-125m",
],
)
def test_end_to_end(model: str):
free, total = torch.accelerator.get_memory_info()
used_bytes_baseline = total - free # in case other process is running
llm = LLM(model, enable_sleep_mode=True)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# the benefit of `llm.sleep(level=2)` is mainly CPU memory usage,
# which is difficult to measure in the test. therefore, we only
# test sleep level 1 here.
llm.sleep(level=1)
free_gpu_bytes_after_sleep, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_after_sleep - used_bytes_baseline
# now the memory usage is mostly cudagraph memory pool,
# and it should be less than the model weights (1B model, 2GiB weights)
# NOTE: In V1, the memory buffer for logits (max_num_reqs x vocab_size)
# is captured but cannot be releasesd from PyTorch due to a known bug,
# therefore high memory usage after `llm.sleep` is called is expected.
# FIXME(youkaichao & ywang96): Fix memory buffer issue with sleep mode
# in V1.
assert used_bytes < 7 * GiB_bytes
llm.wake_up()
output2 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output2[0].outputs[0].text
llm.sleep(level=1)
llm.wake_up(tags=["weights"])
free_gpu_bytes_wake_up_w, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_wake_up_w - used_bytes_baseline
# should just reallocate memory for weights (1B model, ~2GiB weights)
assert used_bytes < 10 * GiB_bytes
# now allocate kv cache memory
llm.wake_up(tags=["kv_cache"])
output3 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output3[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep(gpu_memory_cleared):
model = "hmellor/tiny-random-LlamaForCausalLM"
free, total = torch.accelerator.get_memory_info()
used_bytes_baseline = total - free # in case other process is running
llm = LLM(model, enable_sleep_mode=True)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# Put the engine to deep sleep
llm.sleep(level=2)
free_gpu_bytes_after_sleep, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_after_sleep - used_bytes_baseline
assert used_bytes < 3 * GiB_bytes
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
free_gpu_bytes_wake_up_w, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_wake_up_w - used_bytes_baseline
assert used_bytes < 4 * GiB_bytes
# now allocate kv cache and cuda graph memory
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output2[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep_lora(gpu_memory_cleared):
"""Level-2 sleep/wake/reload with enable_lora=True.
LoRA wrapping moves parameters under base_layer and adds LoRA
stacked tensors that are plain attributes, not restored by the
reload machinery — reload must forward checkpoint weights through
the wrappers and reset the LoRA state afterwards.
"""
model = "hmellor/tiny-random-LlamaForCausalLM"
llm = LLM(
model,
enable_sleep_mode=True,
enable_lora=True,
max_lora_rank=8,
enforce_eager=True,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# Level-2 sleep discards all GPU memory
llm.sleep(level=2)
# Reload weights from checkpoint
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
assert output[0].outputs[0].text == output2[0].outputs[0].text
# Multiple cycles should not accumulate corruption
for _ in range(3):
llm.sleep(level=2)
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
output3 = llm.generate(prompt, sampling_params)
assert output[0].outputs[0].text == output3[0].outputs[0].text
def _lora_logits_mapping_present(model) -> bool:
from vllm.lora.layers.logits_processor import LogitsProcessorWithLoRA
return any(
isinstance(m, LogitsProcessorWithLoRA)
and m.sharded_to_full_mapping_gpu is not None
for m in model.modules()
)
@multi_gpu_test(num_gpus=2)
def test_deep_sleep_lora_tp2(monkeypatch):
"""Level-2 sleep/wake/reload with enable_lora=True and TP=2.
With TP > 1 the LoRA logits processor carries
``sharded_to_full_mapping_gpu``, a permanent index mapping used to
reorder gathered logits. Like the LoRA stacked tensors it is a plain
attribute allocated in the sleep-mode pool, so level-2 sleep destroys
its contents — it must be restored after reload.
"""
# Needed for apply_model to reach the multiproc TP workers below.
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
model = "hmellor/tiny-random-LlamaForCausalLM"
llm = LLM(
model,
enable_sleep_mode=True,
enable_lora=True,
max_lora_rank=8,
tensor_parallel_size=2,
enforce_eager=True,
)
# Guard against this test silently not exercising the TP>1 reindex
# path (e.g. if lm_head wrapping conditions change).
assert all(llm.apply_model(_lora_logits_mapping_present))
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
llm.sleep(level=2)
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
assert output[0].outputs[0].text == output2[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep_async(gpu_memory_cleared):
async def test():
model = "hmellor/tiny-random-LlamaForCausalLM"
free, total = torch.accelerator.get_memory_info()
used_bytes_baseline = total - free # in case other process is running
engine_args = AsyncEngineArgs(
model=model,
enable_sleep_mode=True,
)
llm = AsyncLLMEngine.from_engine_args(engine_args)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
outputs = llm.generate(prompt, sampling_params, request_id="test_request_id1")
async for output in outputs:
pass
# Put the engine to deep sleep
await llm.sleep(level=2)
await llm.wake_up(tags=["weights"])
await llm.collective_rpc("reload_weights")
free_gpu_bytes_wake_up_w, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_wake_up_w - used_bytes_baseline
assert used_bytes < 4 * GiB_bytes
# now allocate kv cache and cuda graph memory
await llm.wake_up(tags=["kv_cache"])
outputs2 = llm.generate(prompt, sampling_params, request_id="test_request_id2")
async for output2 in outputs2:
pass
# cmp output
assert output.outputs[0].text == output2.outputs[0].text
asyncio.run(test())
@requires_fp8
def test_deep_sleep_fp8_kvcache_mrv1(
monkeypatch: pytest.MonkeyPatch, gpu_memory_cleared
):
# Regression test for https://github.com/vllm-project/vllm/pull/28783.
# In particular, verify that MRV1 does not rely on post_kv_cache_wake_up()
# to restore correct output after level-2 sleep.
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "0")
envs.disable_envs_cache()
model = "Qwen/Qwen2-0.5B"
used_bytes_baseline = current_platform.get_current_memory_usage()
llm = LLM(model, enable_sleep_mode=True, kv_cache_dtype="fp8")
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# Put the engine to deep sleep
llm.sleep(level=2)
used_bytes = current_platform.get_current_memory_usage() - used_bytes_baseline
# Rocm uses more memory for CudaGraphs, so we add 2 GiB more for the threshold
rocm_extra_mem_bytes = 2 * GiB_bytes if current_platform.is_rocm() else 0
mem_threshold_after_sleep = 3 * GiB_bytes + rocm_extra_mem_bytes
assert used_bytes < mem_threshold_after_sleep
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
used_bytes = current_platform.get_current_memory_usage() - used_bytes_baseline
mem_threshold_after_wake_up = 4 * GiB_bytes + rocm_extra_mem_bytes
assert used_bytes < mem_threshold_after_wake_up
# now allocate kv cache and cuda graph memory
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output2[0].outputs[0].text
@requires_fp8
def test_deep_sleep_fp8_kvcache_mrv1_with_undefined_remap(
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "0")
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
envs.disable_envs_cache()
llm = LLM(
"Qwen/Qwen2-0.5B",
enable_sleep_mode=True,
kv_cache_dtype="fp8",
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)
llm.sleep(level=2)
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
original_create_and_map = cumem.create_and_map
def create_and_map_with_poison(handle) -> None:
original_create_and_map(handle)
_, size, ptr, _ = handle
cumem.libcudart.cudaMemset(ptr, 0xA5, size)
monkeypatch.setattr(cumem, "create_and_map", create_and_map_with_poison)
# New requests must overwrite undefined remapped KV bytes before reading them.
llm.wake_up(tags=["kv_cache"])
actual = llm.generate(prompt, sampling_params)
assert expected[0].outputs[0].text == actual[0].outputs[0].text
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Compare the short outputs of HF and vLLM when using greedy sampling.
Run `pytest tests/basic_correctness/test_basic_correctness.py`.
Run `pytest tests/basic_correctness/models/test_basic_correctness.py`.
"""
import os
@@ -17,9 +17,9 @@ from vllm import LLM
from vllm.platforms import current_platform
from vllm.v1.engine.llm_engine import LLMEngine
from ..conftest import HfRunner, VllmRunner
from ..models.utils import check_outputs_equal
from ..utils import multi_gpu_test
from ...conftest import HfRunner, VllmRunner
from ...models.utils import check_outputs_equal
from ...utils import multi_gpu_test
ATTN_BACKEND = ["ROCM_ATTN"] if current_platform.is_rocm() else ["FLASH_ATTN"]
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Test prefetch offloading correctness with Llama model."""
from ..utils import compare_two_settings
from ...utils import compare_two_settings
def test_prefetch_offload_llama():
-604
View File
@@ -1,604 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
import pytest
import torch
import vllm.device_allocator.cumem as cumem
import vllm.envs as envs
from vllm import LLM, AsyncEngineArgs, AsyncLLMEngine, SamplingParams
from vllm.device_allocator import get_mem_allocator_instance
from vllm.platforms import current_platform
from vllm.utils.mem_constants import GiB_bytes
from ..utils import create_new_process_for_each_test, requires_fp8
DEVICE_TYPE = current_platform.device_type
def mapped_usage(allocator) -> int:
"""Bytes the allocator still has mapped on the device.
`torch.accelerator.get_memory_info()` is a device-wide `cudaMemGetInfo` /
`hipMemGetInfo` query, so its delta also carries whatever else on the GPU
allocates or frees while we measure. The allocator's own bookkeeping is
process-local and exact.
"""
return sum(
data.handle[1]
for data in allocator.pointer_to_data.values()
if not data.is_asleep
)
def _wake_up_with_poisoned_mappings(allocator, byte_value: int = 0xA5) -> None:
"""Wake discarded allocations with deterministic nonzero contents."""
original_create_and_map = cumem.create_and_map
def create_and_map_with_poison(handle) -> None:
original_create_and_map(handle)
_, size, ptr, _ = handle
cumem.libcudart.cudaMemset(ptr, byte_value, size)
cumem.create_and_map = create_and_map_with_poison
try:
allocator.wake_up()
finally:
cumem.create_and_map = original_create_and_map
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_python_error():
"""Test if Python error occurs when there's low-level
error happening from the C++ side.
"""
allocator = get_mem_allocator_instance()
total_bytes = torch.accelerator.get_memory_info()[1]
alloc_bytes = int(total_bytes * 0.7)
tensors = []
with allocator.use_memory_pool():
# allocate 70% of the total memory
x = torch.empty(alloc_bytes, dtype=torch.uint8, device=DEVICE_TYPE)
tensors.append(x)
# release the memory
allocator.sleep(offload_tags=())
# allocate more memory than the total memory
y = torch.empty(alloc_bytes, dtype=torch.uint8, device=DEVICE_TYPE)
tensors.append(y)
with pytest.raises(RuntimeError):
# when the allocator is woken up, it should raise an error
# because we don't have enough memory
allocator.wake_up()
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_basic_cumem():
# some tensors from default memory pool
shape = (1024, 1024)
x = torch.empty(shape, device=DEVICE_TYPE)
x.zero_()
# some tensors from custom memory pool
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool():
# custom memory pool
y = torch.empty(shape, device=DEVICE_TYPE)
y.zero_()
y += 1
z = torch.empty(shape, device=DEVICE_TYPE)
z.zero_()
z += 2
# they can be used together
output = x + y + z
assert torch.allclose(output, torch.ones_like(output) * 3)
# Track the allocator's own mapped bytes, not device-wide free memory.
mapped_bytes = mapped_usage(allocator)
assert mapped_bytes >= y.nbytes + z.nbytes
allocator.sleep()
assert mapped_usage(allocator) == 0
allocator.wake_up()
assert mapped_usage(allocator) == mapped_bytes
# they can be used together
output = x + y + z
assert torch.allclose(output, torch.ones_like(output) * 3)
@pytest.mark.parametrize("full_sleep", [0, 1, 2], ids=["kv-only", "sleep-1", "sleep-2"])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_release_kv_cache_memory_preserves_generation(full_sleep, monkeypatch):
"""Rejected release and KV-only/full sleep cycles preserve greedy tokens."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
kv_cache_memory_bytes = 256 * 1024 * 1024
llm = LLM(
"Qwen/Qwen3-0.6B",
enable_sleep_mode=True,
enforce_eager=True,
kv_cache_memory_bytes=kv_cache_memory_bytes,
max_model_len=1024,
max_num_seqs=4,
gpu_memory_utilization=0.05,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
def get_mapped_bytes_by_tag(worker):
allocator = get_mem_allocator_instance()
mapped_bytes = mapped_usage(allocator)
kv_cache_bytes = sum(
data.handle[1]
for data in allocator.pointer_to_data.values()
if data.tag == "kv_cache" and not data.is_asleep
)
return mapped_bytes, kv_cache_bytes
mapped_before, kv_cache_before = llm.collective_rpc(get_mapped_bytes_by_tag)[0]
# Utility RPC transports the engine error as a plain Exception.
with pytest.raises(Exception, match="requires a completed pause"):
llm.release_kv_cache_memory()
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == mapped_before
assert not llm.llm_engine.is_sleeping()
assert llm.generate(prompt, sampling_params)[0].outputs[0].token_ids == expected
llm.sleep(level=0)
llm.release_kv_cache_memory()
mapped_after, kv_cache_after = llm.collective_rpc(get_mapped_bytes_by_tag)[0]
assert kv_cache_before > 0
assert kv_cache_after == 0
assert mapped_before - mapped_after >= kv_cache_before
assert mapped_after > 0
assert llm.llm_engine.is_sleeping()
if full_sleep:
llm.sleep(level=full_sleep)
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == 0
llm.wake_up(tags=None if full_sleep else ["kv_cache"])
if full_sleep == 2:
llm.collective_rpc("reload_weights")
assert llm.collective_rpc(get_mapped_bytes_by_tag)[0][0] == mapped_before
assert not llm.llm_engine.is_sleeping()
actual = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
assert actual == expected
@pytest.mark.parametrize("first_level", [1, 2])
@pytest.mark.parametrize("second_level", [1, 2])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_sleep_with_only_weights_asleep(first_level, second_level, monkeypatch):
"""Repeated sleep after KV-only wake preserves mappings and recoverability."""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
llm = LLM(
"Qwen/Qwen3-0.6B",
enable_sleep_mode=True,
enforce_eager=True,
kv_cache_memory_bytes=256 * 1024 * 1024,
max_model_len=1024,
max_num_seqs=4,
gpu_memory_utilization=0.05,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
def get_mapped_bytes(worker):
return mapped_usage(get_mem_allocator_instance())
llm.sleep(level=first_level)
llm.wake_up(tags=["kv_cache"])
mapped_before = llm.collective_rpc(get_mapped_bytes)[0]
assert mapped_before > 0
llm.sleep(level=second_level)
assert llm.collective_rpc(get_mapped_bytes)[0] == mapped_before
llm.wake_up(tags=["weights"])
if first_level == 2:
llm.collective_rpc("reload_weights")
assert not llm.llm_engine.is_sleeping()
actual = llm.generate(prompt, sampling_params)[0].outputs[0].token_ids
assert actual == expected
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
def test_discard_tags():
"""Test that discard(tags) selectively frees GPU memory for specific
tags while keeping other tags mapped and usable."""
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool("weights"):
weights = torch.ones(1024, 1024, device=DEVICE_TYPE)
with allocator.use_memory_pool("kv_cache"):
kv = torch.ones(512, 512, device=DEVICE_TYPE)
mapped_bytes = mapped_usage(allocator)
# Discard kv_cache only — weights should remain valid
allocator.discard("kv_cache")
mapped_bytes_after_discard = mapped_usage(allocator)
assert mapped_bytes - mapped_bytes_after_discard >= kv.nbytes
assert mapped_bytes_after_discard >= weights.nbytes
# Weights are still usable
assert torch.allclose(weights, torch.ones_like(weights))
# Wake up and verify kv_cache is remapped; discarded contents are undefined.
allocator.wake_up()
assert kv.shape == (512, 512)
# Full sleep/wake cycle still works after discard
allocator.sleep(offload_tags="weights")
allocator.wake_up()
assert torch.allclose(weights, torch.ones_like(weights))
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.skipif(current_platform.is_xpu(), reason="Uses the CuMem allocator")
def test_level2_discards_ordinary_tensor_with_weights_tag():
"""Reproduce the level-2 variant for an ordinary tensor in weights."""
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool("weights"):
fake_weight = torch.full((4096,), 0x44, dtype=torch.uint8, device=DEVICE_TYPE)
ordinary_tensor = torch.full(
(4096,), 0x55, dtype=torch.uint8, device=DEVICE_TYPE
)
pointers = (fake_weight.data_ptr(), ordinary_tensor.data_ptr())
allocator.sleep(offload_tags=())
_wake_up_with_poisoned_mappings(allocator)
torch.accelerator.synchronize()
assert (fake_weight.data_ptr(), ordinary_tensor.data_ptr()) == pointers
assert torch.all(fake_weight == 0xA5)
assert torch.all(ordinary_tensor == 0xA5)
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.skipif(current_platform.is_xpu(), reason="CUDA graph not supported on XPU")
def test_cumem_with_cudagraph():
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool():
weight = torch.eye(1024, device=DEVICE_TYPE)
with allocator.use_memory_pool(tag="discard"):
cache = torch.empty(1024, 1024, device=DEVICE_TYPE)
def model(x):
out = x @ weight
cache[: out.size(0)].copy_(out)
return out + 1
x = torch.empty(128, 1024, device=DEVICE_TYPE)
# warmup
model(x)
# capture cudagraph
model_graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(model_graph):
y = model(x)
mapped_bytes = mapped_usage(allocator)
assert mapped_bytes >= weight.nbytes + cache.nbytes
allocator.sleep()
assert mapped_usage(allocator) == 0
allocator.wake_up()
assert mapped_usage(allocator) == mapped_bytes
# after waking up, the content in the weight tensor
# should be restored, but the content in the cache tensor
# should be discarded
# this operation is also compatible with cudagraph
x.random_()
model_graph.replay()
# cache content is as expected
assert torch.allclose(x, cache[: x.size(0)])
# output content is as expected
assert torch.allclose(y, x + 1)
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.parametrize(
"model",
[
# sleep mode with safetensors
"hmellor/tiny-random-LlamaForCausalLM",
# sleep mode with pytorch checkpoint
"facebook/opt-125m",
],
)
def test_end_to_end(model: str):
free, total = torch.accelerator.get_memory_info()
used_bytes_baseline = total - free # in case other process is running
llm = LLM(model, enable_sleep_mode=True)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# the benefit of `llm.sleep(level=2)` is mainly CPU memory usage,
# which is difficult to measure in the test. therefore, we only
# test sleep level 1 here.
llm.sleep(level=1)
free_gpu_bytes_after_sleep, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_after_sleep - used_bytes_baseline
# now the memory usage is mostly cudagraph memory pool,
# and it should be less than the model weights (1B model, 2GiB weights)
# NOTE: In V1, the memory buffer for logits (max_num_reqs x vocab_size)
# is captured but cannot be releasesd from PyTorch due to a known bug,
# therefore high memory usage after `llm.sleep` is called is expected.
# FIXME(youkaichao & ywang96): Fix memory buffer issue with sleep mode
# in V1.
assert used_bytes < 7 * GiB_bytes
llm.wake_up()
output2 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output2[0].outputs[0].text
llm.sleep(level=1)
llm.wake_up(tags=["weights"])
free_gpu_bytes_wake_up_w, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_wake_up_w - used_bytes_baseline
# should just reallocate memory for weights (1B model, ~2GiB weights)
assert used_bytes < 10 * GiB_bytes
# now allocate kv cache memory
llm.wake_up(tags=["kv_cache"])
output3 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output3[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep():
model = "hmellor/tiny-random-LlamaForCausalLM"
free, total = torch.accelerator.get_memory_info()
used_bytes_baseline = total - free # in case other process is running
llm = LLM(model, enable_sleep_mode=True)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# Put the engine to deep sleep
llm.sleep(level=2)
free_gpu_bytes_after_sleep, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_after_sleep - used_bytes_baseline
assert used_bytes < 3 * GiB_bytes
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
free_gpu_bytes_wake_up_w, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_wake_up_w - used_bytes_baseline
assert used_bytes < 4 * GiB_bytes
# now allocate kv cache and cuda graph memory
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output2[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep_lora():
"""Level-2 sleep/wake/reload with enable_lora=True.
LoRA wrapping moves parameters under base_layer and adds LoRA
stacked tensors that are plain attributes, not restored by the
reload machinery — reload must forward checkpoint weights through
the wrappers and reset the LoRA state afterwards.
"""
model = "hmellor/tiny-random-LlamaForCausalLM"
llm = LLM(
model,
enable_sleep_mode=True,
enable_lora=True,
max_lora_rank=8,
enforce_eager=True,
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# Level-2 sleep discards all GPU memory
llm.sleep(level=2)
# Reload weights from checkpoint
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
assert output[0].outputs[0].text == output2[0].outputs[0].text
# Multiple cycles should not accumulate corruption
for _ in range(3):
llm.sleep(level=2)
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
output3 = llm.generate(prompt, sampling_params)
assert output[0].outputs[0].text == output3[0].outputs[0].text
def _lora_logits_mapping_present(model) -> bool:
from vllm.lora.layers.logits_processor import LogitsProcessorWithLoRA
return any(
isinstance(m, LogitsProcessorWithLoRA)
and m.sharded_to_full_mapping_gpu is not None
for m in model.modules()
)
@create_new_process_for_each_test()
def test_deep_sleep_lora_tp2(num_gpus_available, monkeypatch):
"""Level-2 sleep/wake/reload with enable_lora=True and TP=2.
With TP > 1 the LoRA logits processor carries
``sharded_to_full_mapping_gpu``, a permanent index mapping used to
reorder gathered logits. Like the LoRA stacked tensors it is a plain
attribute allocated in the sleep-mode pool, so level-2 sleep destroys
its contents — it must be restored after reload.
"""
if num_gpus_available < 2:
pytest.skip("Requires at least 2 GPUs")
# Needed for apply_model to reach the multiproc TP workers below.
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
model = "hmellor/tiny-random-LlamaForCausalLM"
llm = LLM(
model,
enable_sleep_mode=True,
enable_lora=True,
max_lora_rank=8,
tensor_parallel_size=2,
enforce_eager=True,
)
# Guard against this test silently not exercising the TP>1 reindex
# path (e.g. if lm_head wrapping conditions change).
assert all(llm.apply_model(_lora_logits_mapping_present))
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
llm.sleep(level=2)
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
assert output[0].outputs[0].text == output2[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep_async():
async def test():
model = "hmellor/tiny-random-LlamaForCausalLM"
free, total = torch.accelerator.get_memory_info()
used_bytes_baseline = total - free # in case other process is running
engine_args = AsyncEngineArgs(
model=model,
enable_sleep_mode=True,
)
llm = AsyncLLMEngine.from_engine_args(engine_args)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
outputs = llm.generate(prompt, sampling_params, request_id="test_request_id1")
async for output in outputs:
pass
# Put the engine to deep sleep
await llm.sleep(level=2)
await llm.wake_up(tags=["weights"])
await llm.collective_rpc("reload_weights")
free_gpu_bytes_wake_up_w, total = torch.accelerator.get_memory_info()
used_bytes = total - free_gpu_bytes_wake_up_w - used_bytes_baseline
assert used_bytes < 4 * GiB_bytes
# now allocate kv cache and cuda graph memory
await llm.wake_up(tags=["kv_cache"])
outputs2 = llm.generate(prompt, sampling_params, request_id="test_request_id2")
async for output2 in outputs2:
pass
# cmp output
assert output.outputs[0].text == output2.outputs[0].text
asyncio.run(test())
@requires_fp8
def test_deep_sleep_fp8_kvcache_mrv1(monkeypatch: pytest.MonkeyPatch):
# Regression test for https://github.com/vllm-project/vllm/pull/28783.
# In particular, verify that MRV1 does not rely on post_kv_cache_wake_up()
# to restore correct output after level-2 sleep.
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "0")
envs.disable_envs_cache()
model = "Qwen/Qwen2-0.5B"
used_bytes_baseline = current_platform.get_current_memory_usage()
llm = LLM(model, enable_sleep_mode=True, kv_cache_dtype="fp8")
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
output = llm.generate(prompt, sampling_params)
# Put the engine to deep sleep
llm.sleep(level=2)
used_bytes = current_platform.get_current_memory_usage() - used_bytes_baseline
# Rocm uses more memory for CudaGraphs, so we add 2 GiB more for the threshold
rocm_extra_mem_bytes = 2 * GiB_bytes if current_platform.is_rocm() else 0
mem_threshold_after_sleep = 3 * GiB_bytes + rocm_extra_mem_bytes
assert used_bytes < mem_threshold_after_sleep
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
used_bytes = current_platform.get_current_memory_usage() - used_bytes_baseline
mem_threshold_after_wake_up = 4 * GiB_bytes + rocm_extra_mem_bytes
assert used_bytes < mem_threshold_after_wake_up
# now allocate kv cache and cuda graph memory
llm.wake_up(tags=["kv_cache"])
output2 = llm.generate(prompt, sampling_params)
# cmp output
assert output[0].outputs[0].text == output2[0].outputs[0].text
@requires_fp8
def test_deep_sleep_fp8_kvcache_mrv1_with_undefined_remap(
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "0")
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
envs.disable_envs_cache()
llm = LLM(
"Qwen/Qwen2-0.5B",
enable_sleep_mode=True,
kv_cache_dtype="fp8",
)
prompt = "How are you?"
sampling_params = SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, sampling_params)
llm.sleep(level=2)
llm.wake_up(tags=["weights"])
llm.collective_rpc("reload_weights")
original_create_and_map = cumem.create_and_map
def create_and_map_with_poison(handle) -> None:
original_create_and_map(handle)
_, size, ptr, _ = handle
cumem.libcudart.cudaMemset(ptr, 0xA5, size)
monkeypatch.setattr(cumem, "create_and_map", create_and_map_with_poison)
# New requests must overwrite undefined remapped KV bytes before reading them.
llm.wake_up(tags=["kv_cache"])
actual = llm.generate(prompt, sampling_params)
assert expected[0].outputs[0].text == actual[0].outputs[0].text
@@ -2,18 +2,22 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import logging
import pytest
from tests.compile.fusions_e2e.common import FUSION_LOG_PATTERNS
from tests.models.registry import HF_EXAMPLE_MODELS
from tests.utils import (
compare_two_settings,
create_new_process_for_each_test,
multi_gpu_test,
)
from vllm.config import (
CompilationMode,
)
from vllm.platforms import current_platform
from vllm.transformers_utils.repo_utils import hf_api
from vllm.utils.flashinfer import has_flashinfer
NVFP4_MODEL_ID = "nvidia/Llama-3.1-8B-Instruct-NVFP4"
@@ -26,6 +30,78 @@ NVFP4_HF_OVERRIDES = {
}
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm AsyncTP contract")
def test_rocm_async_tp_bf16_output_correctness(caplog_mp_spawn):
"""Trained-model outputs must agree with unfused TP, including padded decode."""
# A snapshot path pins both servers and the comparison helper's tokenizer.
model = hf_api().snapshot_download(
"Qwen/Qwen3-0.6B", revision="c1899de289a04d12100db370d81485cdf75e47ca"
)
common_args = [
"--dtype",
"bfloat16",
"--load-format",
"auto",
"--tensor-parallel-size",
"2",
"--distributed-executor-backend",
"mp",
"--max-model-len",
"512",
"--max-num-batched-tokens",
"512",
"--max-num-seqs",
"8",
"--kv-cache-memory-bytes",
str(64 * 1024**2),
"--gpu-memory-utilization",
"0.01",
"--attention-backend",
"TRITON_ATTN",
"--disable-custom-all-reduce",
]
def settings(enabled):
return [
*common_args,
"--compilation-config",
json.dumps(
{
"mode": CompilationMode.VLLM_COMPILE,
"cudagraph_mode": "NONE",
"splitting_ops": [],
"inductor_compile_config": {"force_disable_caches": True},
"pass_config": {
"enable_sp": enabled,
"fuse_gemm_comms": enabled,
"fuse_allreduce_rms": False,
"sp_min_token_num": 1,
},
}
),
]
env = {"VLLM_ROCM_USE_AITER": "0", "VLLM_DISABLE_COMPILE_CACHE": "1"}
with caplog_mp_spawn(logging.DEBUG) as logs:
compare_two_settings(
model,
settings(False),
settings(True),
env1=env,
env2=env,
method="generate",
force_v1_runner=True,
)
matches = [
int(count) for count in FUSION_LOG_PATTERNS["async_tp"].findall(logs.text)
]
print(f"AsyncTP rewrite counts: {matches}")
assert len(matches) >= 2 and all(count > 0 for count in matches), (
f"Expected positive AsyncTP rewrites on both TP workers, found {matches}"
)
@create_new_process_for_each_test()
@pytest.mark.parametrize(
"model_id",
@@ -0,0 +1,88 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import logging
import pytest
import regex as re
from tests.utils import compare_two_settings
from vllm._aiter_ops import is_aiter_found_and_supported
from vllm.config import CompilationMode
from vllm.platforms import current_platform
from vllm.transformers_utils.repo_utils import hf_api
@pytest.mark.skipif(
not current_platform.is_rocm() or not is_aiter_found_and_supported(),
reason="Requires ROCm AITER attention and quantization",
)
def test_rocm_aiter_static_attention_output_correctness(caplog_mp_spawn):
"""Trained FP8 outputs agree when actual AITER output quantization is fused."""
model = hf_api().snapshot_download(
"RedHatAI/Meta-Llama-3.1-8B-Instruct-FP8",
revision="870a1177ed082c0ba5dbefd62573ab8f91803f6a",
allow_patterns=["*.json", "*.safetensors", "*.model", "*.txt", "*.jinja"],
)
common_args = [
"--dtype",
"bfloat16",
"--load-format",
"auto",
"--max-model-len",
"512",
"--max-num-batched-tokens",
"512",
"--max-num-seqs",
"8",
"--kv-cache-memory-bytes",
str(256 * 1024**2),
"--gpu-memory-utilization",
"0.01",
"--attention-backend",
"ROCM_AITER_UNIFIED_ATTN",
]
def settings(enabled):
return [
*common_args,
"--compilation-config",
json.dumps(
{
"mode": CompilationMode.VLLM_COMPILE,
"cudagraph_mode": "NONE",
"splitting_ops": [],
"inductor_compile_config": {"force_disable_caches": True},
"custom_ops": ["+quant_fp8", "-rms_norm"],
"pass_config": {
"fuse_attn_quant": enabled,
"fuse_norm_quant": False,
"fuse_act_quant": False,
"fuse_allreduce_rms": False,
},
}
),
]
env = {
"VLLM_ROCM_USE_AITER": "1",
"VLLM_ROCM_USE_AITER_LINEAR": "1",
"VLLM_DISABLE_COMPILE_CACHE": "1",
}
with caplog_mp_spawn(logging.DEBUG) as logs:
compare_two_settings(
model,
settings(False),
settings(True),
env1=env,
env2=env,
method="generate",
force_v1_runner=True,
)
matches = [
int(count) for count in re.findall(r"'attn_quant_fusion': (\d+)", logs.text)
]
print(f"Attention output quantization rewrite counts: {matches}")
assert matches and all(count == 32 for count in matches), (
f"Expected output quantization fused in all 32 Llama layers, found {matches}"
)
+38 -17
View File
@@ -10,6 +10,7 @@ from tests.utils import wait_for_gpu_memory_to_clear
from tests.v1.attention.utils import full_cg_backend_configs as backend_configs
from vllm import LLM, SamplingParams
from vllm.config import CompilationConfig, CUDAGraphMode
from vllm.outputs import RequestOutput
from vllm.platforms import current_platform
from vllm.utils.torch_utils import is_torch_equal_or_newer
from vllm.v1.attention.backends.registry import AttentionBackendEnum
@@ -36,7 +37,7 @@ def temporary_environ(env_vars):
model_backends_full_cudagraph = []
# deepseek-ai/DeepSeek-V2-Lite with MLA
MLA_backends = ["FlashMLA", "FlashAttentionMLA", "CutlassMLA"]
MLA_backends = ["FlashMLA", "FlashAttentionMLA", "CutlassMLA", "FlashInferMLA"]
for mla_backend in MLA_backends:
model_backends_full_cudagraph.append(
("deepseek-ai/DeepSeek-V2-Lite", backend_configs[mla_backend])
@@ -53,27 +54,28 @@ for backend_config in other_backend_configs:
@pytest.fixture(scope="class")
def llm_pair(request):
model, backend_config, use_inductor_graph_partition = request.param
backend_config.comp_config["use_inductor_graph_partition"] = (
use_inductor_graph_partition
)
if use_inductor_graph_partition and not is_torch_equal_or_newer("2.9.0.dev"):
pytest.skip("Inductor graph partition only supported in torch>=2.9")
backend = AttentionBackendEnum[backend_config.attention_config["backend"]]
if current_platform.is_rocm() and backend not in (
AttentionBackendEnum.TRITON_ATTN,
AttentionBackendEnum.ROCM_ATTN,
):
pytest.skip(f"{backend_config.name} is a CUDA-only attention backend")
if backend == AttentionBackendEnum.ROCM_ATTN and not current_platform.is_rocm():
pytest.skip("ROCM_ATTN requires ROCm")
# Dynamically skip test if GPU capability is not met
if (
backend_config.specific_gpu_arch
and backend_config.specific_gpu_arch != current_platform.get_device_capability()
if backend_config.specific_gpu_arch and (
not current_platform.is_cuda()
or backend_config.specific_gpu_arch != current_platform.get_device_capability()
):
if backend_config.specific_gpu_arch == (9, 0):
pytest.skip("Only Hopper GPUs support FA3 and FlashMLA")
elif backend_config.specific_gpu_arch == (10, 0):
pytest.skip("Only Blackwell GPUs support Cutlass MLA")
# FlashInfer is not supported on ROCm
if backend_config == AttentionBackendEnum.FLASHINFER and current_platform.is_rocm():
pytest.skip("FlashInfer is not supported on ROCm")
env_vars = {
# Force native sampler to avoid potential nondeterminism in FlashInfer
# when per-request generators are not used in V1.
@@ -86,7 +88,11 @@ def llm_pair(request):
trust_remote_code=True,
max_model_len=1024,
max_num_seqs=128,
compilation_config=CompilationConfig(**backend_config.comp_config),
attention_config=backend_config.attention_config,
compilation_config=CompilationConfig(
**backend_config.comp_config,
use_inductor_graph_partition=use_inductor_graph_partition,
),
generation_config="vllm",
seed=42,
)
@@ -96,8 +102,10 @@ def llm_pair(request):
trust_remote_code=True,
max_model_len=1024,
max_num_seqs=128,
attention_config=backend_config.attention_config,
compilation_config=CompilationConfig(
cudagraph_mode=CUDAGraphMode.PIECEWISE
cudagraph_mode=CUDAGraphMode.PIECEWISE,
use_inductor_graph_partition=use_inductor_graph_partition,
),
generation_config="vllm",
seed=42,
@@ -117,7 +125,10 @@ def llm_pair(request):
@pytest.mark.parametrize(
"llm_pair",
[
pytest.param((model, backend_config, use_inductor_graph_partition))
pytest.param(
(model, backend_config, use_inductor_graph_partition),
id=f"{backend_config.name}-partition={use_inductor_graph_partition}",
)
for model, backend_config in model_backends_full_cudagraph
for use_inductor_graph_partition in [True, False]
],
@@ -159,10 +170,20 @@ class TestFullCUDAGraph:
temperature=0.0, max_tokens=max_tokens, top_p=1.0
)
piecewise_responses = piecewise_llm.generate(prompts, sampling_params)
full_responses = full_cudagraph_llm.generate(prompts, sampling_params)
responses = []
for llm in (piecewise_llm, full_cudagraph_llm):
# Queue the whole batch before scheduling so both engines exercise
# the requested batch size instead of timing-dependent sub-batches.
llm.sleep(level=0, mode="keep")
try:
llm.enqueue(prompts, sampling_params)
finally:
llm.wake_up(tags=["scheduling"])
responses.append(llm.wait_for_completion(output_type=RequestOutput))
piecewise_responses, full_responses = responses
# Check that all responses are the same
assert len(piecewise_responses) == len(full_responses) == batch_size
for piecewise_res, full_res in zip(piecewise_responses, full_responses):
assert (
piecewise_res.outputs[0].text.lower()
+4 -1
View File
@@ -128,8 +128,11 @@ FUSION_LOG_PATTERNS: dict[str, re.Pattern] = {
),
"rms_quant_fusion": re.compile(r"rms_quant_fusion.py:\d+] Replaced (\d+) patterns"),
"act_quant_fusion": re.compile(r"act_quant_fusion.py:\d+] Replaced (\d+) patterns"),
# The combined pass can consume these sites before the standalone pass.
"norm_rope_fusion": re.compile(
r"qk_norm_rope_fusion.py:\d+] Fused QK Norm\+RoPE on (\d+) sites"
r"(?:qk_norm_rope_fusion.py:\d+] Fused QK Norm\+RoPE on|"
r"qk_norm_rope_kvcache_fusion.py:\d+] "
r"QK-Norm\+RoPE(?:/MRoPE)?\+KVCache fusion: replaced) (\d+)"
),
"attn_quant_fusion": re.compile(
r"attn_quant_fusion.py:\d+] Fused quant onto (\d+) attention nodes"
+15 -2
View File
@@ -182,7 +182,11 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn):
# TODO: Remove log counting in unit tests
# once all matchers implement VllmFusionPatternMatcherPass
n_expected = tp_size * num_ranges_activated
if match_name not in ("attn_quant_fusion", "act_quant_fusion"):
if match_name not in (
"attn_quant_fusion",
"act_quant_fusion",
"norm_rope_fusion",
):
assert len(log_matches) == n_expected, (
f"Could not find {n_expected} {match_name} "
f"(found {len(log_matches)}) in:\n {log_holder.text}"
@@ -190,7 +194,16 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn):
expected_matches = getattr(matches, match_name)
if match_name == "rms_quant_fusion" and "ar_rms_fusion" in matches_check:
if match_name == "norm_rope_fusion":
# Opaque LayerName lets the combined pass consume short-range
# sites before the standalone pass; count either owner.
assert len(log_matches) >= n_expected
assert all(m in (0, expected_matches) for m in log_matches)
assert sum(log_matches) == expected_matches * n_expected, (
f"{match_name} expected {expected_matches * n_expected} "
f"sites across both passes, found: {log_matches}"
)
elif match_name == "rms_quant_fusion" and "ar_rms_fusion" in matches_check:
# AR+rms+quant takes precedence over rms+quant if activated.
# That means we get full matching where ar+rms+quant was not
# activated, and less where it was (only the smallest range).
+9
View File
@@ -44,6 +44,15 @@ ROCM_AITER_UNIFIED_ATTN = pytest.param(
),
)
ROCM_AITER_MLA_ATTN = pytest.param(
AttentionBackendCase(backend=AttentionBackendEnum.ROCM_AITER_MLA),
id="ROCM_AITER_MLA",
marks=pytest.mark.skipif(
not is_aiter_found_and_supported(),
reason="ROCM_AITER_MLA only for AMD when AITER is installed",
),
)
FLASHINFER_MLA_ATTN = pytest.param(
AttentionBackendCase(backend=AttentionBackendEnum.FLASHINFER_MLA),
id="FLASHINFER_MLA",
+57 -8
View File
@@ -19,6 +19,7 @@ from .common import (
from .models import (
FLASHINFER_ATTN,
FLASHINFER_MLA_ATTN,
ROCM_AITER_MLA_ATTN,
ROCM_AITER_UNIFIED_ATTN,
ROCM_ATTN,
TRITON_ATTN,
@@ -40,25 +41,35 @@ pytestmark = pytest.mark.skipif(
)
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"model_name, matches_fn, model_kwargs, hf_overrides",
# qwen3 & dsv3 should still fuse AR+rms even though group quant is not yet supported
# qwen3 & dsv3 should still fuse AR+rms even though group quant is not yet
# supported. ROCm carries only the payloads its two backends support.
TP2_FP8_MODELS = (
[
llama3_8b_fp8,
llama4_scout_fp8,
qwen3_a3b_fp8,
deepseek_coder_v2_lite_fp8,
deepseek_v3_fp8,
],
]
if current_platform.is_cuda()
else [llama3_8b_fp8, qwen3_a3b_fp8, deepseek_coder_v2_lite_fp8]
)
TP2_FP8_ATTN_BACKENDS = (
[TRITON_ATTN, FLASHINFER_ATTN, FLASHINFER_MLA_ATTN]
if current_platform.is_cuda()
else [ROCM_AITER_UNIFIED_ATTN, ROCM_AITER_MLA_ATTN]
)
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"attn_backend", [TRITON_ATTN, FLASHINFER_ATTN, FLASHINFER_MLA_ATTN]
"model_name, matches_fn, model_kwargs, hf_overrides", TP2_FP8_MODELS
)
@pytest.mark.parametrize("attn_backend", TP2_FP8_ATTN_BACKENDS)
@pytest.mark.parametrize("n_layers", [4])
@pytest.mark.parametrize("custom_ops", custom_ops_combos("quant_fp8", "rms_norm"))
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Only test CUDA")
def test_tp2_ar_rms_fp8_fusions(
model_name: str,
matches_fn: Callable[[int], Matches],
@@ -69,10 +80,27 @@ def test_tp2_ar_rms_fp8_fusions(
custom_ops: str,
inductor_graph_partition: bool,
run_e2e_fusion_test,
monkeypatch,
):
matches = matches_fn(n_layers)
block_fp8 = "qwen" in model_name.lower() or "deepseek" in model_name.lower()
model_name_lower = model_name.lower()
# DeepSeek-Coder on AITER MLA is the one static-FP8 payload here, validated
# against the native QuantFP8 pattern; every other DeepSeek stays group
# quantized as on CUDA.
rocm_static_fp8_mla = (
current_platform.is_rocm()
and "deepseek-coder" in model_name_lower
and attn_backend.backend.name == "ROCM_AITER_MLA"
)
block_fp8 = "qwen" in model_name_lower or "deepseek" in model_name_lower
if rocm_static_fp8_mla:
block_fp8 = False
if custom_ops != "-quant_fp8,-rms_norm":
pytest.skip("ROCm static-FP8 MLA parity uses native quant and RMSNorm")
# AITER's MoE GEMM rejects this reduced dummy model shape; keep AITER
# for MLA and the all-reduce, and let the MoE run on Triton.
monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "0")
if block_fp8 and "-quant_fp8" in custom_ops:
# This is why config forces +quant_fp8 by default
pytest.skip("native QuantFP8 matching not supported for group quant")
@@ -83,6 +111,13 @@ def test_tp2_ar_rms_fp8_fusions(
model_kwargs["max_model_len"] = 1024
model_kwargs["kernel_config"] = {"enable_flashinfer_autotune": False}
model_kwargs["disable_custom_all_reduce"] = False
if current_platform.is_rocm() and "llama-3" in model_name_lower:
model_kwargs.update(
gpu_memory_utilization=0.01,
kv_cache_memory_bytes=64 * 1024**2,
max_num_batched_tokens=1024,
max_num_seqs=32,
)
compilation_config = dict(
use_inductor_graph_partition=inductor_graph_partition,
@@ -103,6 +138,19 @@ def test_tp2_ar_rms_fp8_fusions(
"ar_rms_fusion",
]
use_aiter = current_platform.is_rocm()
if use_aiter:
matches = matches._replace(aiter_ar_rms_fusion=matches.ar_rms_fusion)
# The AITER all-reduce pass registers the AR+RMS(+group-quant) patterns
# before its AR+RMS-only ones, so the standalone AITER RMS-quant pass
# does not own the post-AR sites here. ROCm's contract is native
# QK-norm+RoPE and attention-output quant fusion plus AITER AR+RMS.
matches_check = [
"norm_rope_fusion",
"attn_quant_fusion",
"aiter_ar_rms_fusion",
]
run_e2e_fusion_test(
model_name,
matches,
@@ -111,6 +159,7 @@ def test_tp2_ar_rms_fp8_fusions(
compilation_config,
matches_check,
tp_size=2,
use_aiter=use_aiter,
)
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Bounded ROCm model coverage for actual sequence-parallel AsyncTP rewrites."""
import pytest
from tests.utils import multi_gpu_test
from vllm.config import PassConfig
from vllm.platforms import current_platform
from .common import INDUCTOR_GRAPH_PARTITION, custom_ops_combos
from .models import TRITON_ATTN, llama3_8b
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm AsyncTP contract")
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
@pytest.mark.parametrize("custom_ops", tuple(custom_ops_combos("rms_norm")))
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN])
def test_tp2_rocm_async_tp_bf16_fusions(
inductor_graph_partition, custom_ops, attn_backend, run_e2e_fusion_test
):
n_layers = 4
model_kwargs = dict(
hf_overrides=dict(
num_hidden_layers=n_layers,
hidden_size=512,
intermediate_size=1024,
num_attention_heads=8,
num_key_value_heads=2,
head_dim=64,
),
load_format="dummy",
max_model_len=1024,
kv_cache_memory_bytes=64 * 1024**2,
gpu_memory_utilization=0.01,
max_num_batched_tokens=1024,
max_num_seqs=32,
)
run_e2e_fusion_test(
llama3_8b.model_name,
llama3_8b.matches(n_layers),
model_kwargs,
attn_backend,
dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=False,
sp_min_token_num=512,
),
),
["norm_rope_fusion", "sequence_parallel", "async_tp"],
tp_size=2,
)
@@ -303,6 +303,7 @@ def async_tp_pass_on_test_model(
dtype: torch.dtype,
dynamic: bool,
distributed_init_method: str,
check_numerics: bool = False,
):
set_random_seed(0)
@@ -363,12 +364,24 @@ def async_tp_pass_on_test_model(
hidden_states = torch.randn(
(batch_size * seq_len, hidden_size), dtype=dtype, requires_grad=False
)
if check_numerics:
hidden_states += local_rank * 0.125
if dynamic:
torch._dynamo.mark_dynamic(hidden_states, 0)
compiled_model = torch.compile(model, backend=backend)
compiled_model(hidden_states)
actual = compiled_model(hidden_states)
if check_numerics:
# These are new checks, so no existing tolerance is relaxed.
# Allow BF16 rounding vs. eager, but keep the lifetime check exact.
expected = model(hidden_states)
torch.testing.assert_close(actual, expected, rtol=1e-2, atol=1e-2)
snapshot = actual.clone()
changed = compiled_model(-hidden_states)
torch.testing.assert_close(changed, -expected, rtol=1e-2, atol=1e-2)
torch.testing.assert_close(actual, snapshot, rtol=0, atol=0)
assert async_tp_pass.matched_count == 1
+61 -5
View File
@@ -12,6 +12,7 @@ from tests.v1.attention.utils import (
create_common_attn_metadata,
dense_kv_cache_views,
)
from vllm._aiter_ops import is_aiter_found_and_supported, rocm_aiter_ops
from vllm._custom_ops import cutlass_scaled_fp4_mm, scaled_fp4_quant
from vllm.compilation.passes.fusion.attn_quant_fusion import (
ATTN_OP,
@@ -189,6 +190,17 @@ class TestAttentionFp8StaticQuantPatternModel(AttentionQuantPatternModel):
return self.fp8_linear(attn_output)
class TestAttentionAiterFp8StaticQuantPatternModel(
TestAttentionFp8StaticQuantPatternModel
):
aiter_quant = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fp8_linear.kernel.quant_fp8.use_aiter = True
self.fp8_linear.input_scale.fill_(0.125)
class TestAttentionNvfp4QuantPatternModel(AttentionQuantPatternModel):
"""Test model for AttentionNvfp4QuantPattern fusion."""
@@ -455,11 +467,12 @@ def test_attention_quant_pattern(
)
# Check quantization ops in the graph before and after fusion
quant_op = (
torch.ops.aten.reciprocal
if "-quant_fp8" in custom_ops_list
else QUANT_OPS[quant_key]
)
if "-quant_fp8" in custom_ops_list:
quant_op = torch.ops.aten.reciprocal
elif getattr(model_class, "aiter_quant", False):
quant_op = torch.ops.vllm.rocm_aiter_per_tensor_quant.default
else:
quant_op = QUANT_OPS[quant_key]
if expect_fusion:
# Note: for fp8, fully_replaced=False because query quant ops remain in
@@ -523,3 +536,46 @@ def test_attention_quant_pattern(
# Check that results are close
torch.testing.assert_close(result_unfused, result_fused, atol=1e-2, rtol=1e-2)
if getattr(model_class, "aiter_quant", False):
# Query quantization remains; exactly the output quant op is removed.
assert test_backend.op_count(quant_op, before=True) == (
test_backend.op_count(quant_op) + 1
)
for model in (model_unfused, model_fused):
torch.testing.assert_close(
model.fp8_linear.input_scale,
torch.full_like(model.fp8_linear.input_scale, 0.125),
atol=0,
rtol=0,
)
@pytest.mark.skipif(
not current_platform.is_rocm() or not is_aiter_found_and_supported(),
reason="Requires ROCm AITER attention and quantization",
)
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
def test_rocm_aiter_static_quant_attention(
dtype, dist_init, disable_vllm_compile_cache, monkeypatch
):
"""Fuse the actual AITER op without changing its static scale or outputs."""
try:
with monkeypatch.context() as patch:
patch.setenv("VLLM_ROCM_USE_AITER", "1")
rocm_aiter_ops.refresh_env_variables()
test_attention_quant_pattern(
num_qo_heads=32,
num_kv_heads=8,
head_size=128,
batch_size=8,
dtype=dtype,
kv_cache_dtype="fp8",
custom_ops="+quant_fp8",
model_name="amd/Llama-3.1-8B-Instruct-FP8-KV",
model_class=TestAttentionAiterFp8StaticQuantPatternModel,
backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
dist_init=dist_init,
disable_vllm_compile_cache=disable_vllm_compile_cache,
)
finally:
rocm_aiter_ops.refresh_env_variables()
@@ -271,7 +271,6 @@ class TestMLAAttentionFp8GroupQuantPatternModel(MLAAttentionQuantPatternModel):
quant_key = kFp8Dynamic128Sym
quant_config = Fp8Config(
is_checkpoint_fp8_serialized=True,
weight_block_size=[128, 128],
)
@@ -362,13 +361,27 @@ if current_platform.is_cuda():
]
BACKENDS_MLA_FP8 = [AttentionBackendEnum.TRITON_MLA]
BACKENDS_MLA_FP4 = [AttentionBackendEnum.TRITON_MLA]
elif current_platform.is_rocm():
# ROCm supports the static-FP8 output-quant fusion through AITER MLA.
# Per-group FP8 still relies on the CUDA-only CUTLASS block-scaled
# kernel, and NVFP4 is NVIDIA-specific.
MLA_DIMS = [(16, 128, 64, 128, 512)]
PATTERN_TEST_MODELS_MLA_FP8 = [
(
"deepseek-ai/DeepSeek-V2-Lite",
TestMLAAttentionFp8StaticQuantPatternModel,
)
]
BACKENDS_MLA_FP8 = [AttentionBackendEnum.ROCM_AITER_MLA]
@pytest.mark.parametrize(
"num_heads, qk_nope_head_dim, qk_rope_head_dim, v_head_dim, kv_lora_rank",
MLA_DIMS,
)
@pytest.mark.parametrize("batch_size", [7, 256] if current_platform.is_cuda() else [8])
@pytest.mark.parametrize(
"batch_size", [7, 256] if current_platform.is_cuda_alike() else [8]
)
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@pytest.mark.parametrize(
"backend, model_name, model_class, custom_ops",
@@ -406,6 +419,7 @@ def test_mla_attention_quant_pattern(
backend: AttentionBackendEnum,
dist_init,
disable_vllm_compile_cache,
workspace_init,
):
"""Test MLA AttentionQuantPattern fusion pass."""
if (
@@ -8,6 +8,7 @@ import pytest
import torch
from packaging.version import Version
import vllm.compilation.passes.fusion.qk_norm_rope_kvcache_fusion as fusion_module
import vllm.config
from tests.compile.backend import TestBackend
from tests.v1.attention.utils import (
@@ -15,8 +16,12 @@ from tests.v1.attention.utils import (
create_common_attn_metadata,
dense_kv_cache_views,
)
from vllm._aiter_ops import is_aiter_found_and_supported, rocm_aiter_ops
from vllm.compilation.passes.fusion.matcher_utils import ROTARY_OP
from vllm._aiter_ops import (
IS_AITER_FOUND,
is_aiter_found_and_supported,
rocm_aiter_ops,
)
from vllm.compilation.passes.fusion.matcher_utils import MROPE_OP, ROTARY_OP
from vllm.compilation.passes.fusion.qk_norm_rope_kvcache_fusion import (
QkNormRopeKvCacheFusionPass,
)
@@ -37,8 +42,12 @@ from vllm.config import (
from vllm.forward_context import get_forward_context, set_forward_context
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
from vllm.model_executor.layers.rotary_embedding import RotaryEmbedding
from vllm.model_executor.layers.rotary_embedding.mrope import MRotaryEmbedding
from vllm.platforms import current_platform
from vllm.utils.torch_utils import _USE_LAYERNAME, _encode_layer_name
from vllm.v1.attention.backend import (
AttentionBackend,
CommonAttentionMetadata,
@@ -94,6 +103,7 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
device: torch.device,
rotary_dim: int | None = None,
prefix: str = "model.layers.0.self_attn.attn",
expected_query_quant_group_shape: GroupShape | None = None,
):
super().__init__()
self.num_heads = num_heads
@@ -133,6 +143,9 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
attn_backend=attn_backend.get_class(),
)
self.attn_backend: type[AttentionBackend] = self.attn.get_attn_backend()
if expected_query_quant_group_shape is not None:
assert self.attn.query_quant is not None
assert self.attn.query_quant.group_shape == expected_query_quant_group_shape
assert not self.attn_backend.forward_includes_kv_cache_update, (
f"Attention backend {self.attn_backend} does not support "
"fuse_qk_norm_rope_kvcache."
@@ -227,18 +240,15 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
self.kv_cache_dtype != self.dtype
and self.attn.impl.supports_quant_query_input
):
q_fp8 = torch.empty_like(q, dtype=FP8_DTYPE)
torch.ops.vllm.rocm_aiter_per_tensor_quant(
q_fp8, q, self.attn._q_scale, False
)
q = q_fp8
assert self.attn.query_quant is not None
q, _ = self.attn.query_quant(q, self.attn._q_scale)
# Final views + KV cache update
q = q.view(-1, self.num_heads, self.head_size)
k = k.view(-1, self.num_kv_heads, self.head_size)
v = v.view(-1, self.num_kv_heads, self.head_size)
kv_cache_dummy_dep = torch.ops.vllm.unified_kv_cache_update(
k, v, self.layer_name
k, v, _encode_layer_name(self.layer_name)
)
return q, k, v, kv_cache_dummy_dep
@@ -260,6 +270,64 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
return [torch.ops.vllm.fused_qk_norm_rope_and_unified_kv_cache_update.default]
class QKNormMRoPEKVCacheTestModel(QKNormRoPEKVCacheTestModel):
def __init__(
self,
*,
mrope_section: tuple[int, int, int],
mrope_interleaved: bool,
**kwargs,
):
super().__init__(**kwargs)
self.rotary_emb = MRotaryEmbedding(
self.head_size,
rotary_dim=self.rotary_dim,
max_position_embeddings=4096,
base=10000,
is_neox_style=self.is_neox,
dtype=self.dtype,
mrope_section=list(mrope_section),
mrope_interleaved=mrope_interleaved,
)
self.enable_rope_custom_op = self.rotary_emb.enabled()
def forward(
self, qkv: torch.Tensor, positions: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
q, k, v, kv_cache_dummy_dep = super().forward(qkv, positions)
output = torch.empty(
q.shape[0],
self.num_heads * self.head_size,
device=q.device,
dtype=self.dtype,
)
torch.ops.vllm.unified_attention_with_output(
q,
k,
v,
output,
_encode_layer_name(self.layer_name),
kv_cache_dummy_dep=kv_cache_dummy_dep,
)
# Production decoder attention consumes K from the cache rather than
# its direct K argument. Returning `output` keeps that production user
# in the graph without exposing K to an unsupported consumer.
return q, output, v, kv_cache_dummy_dep
def ops_in_model_before(self) -> list[torch._ops.OpOverload]:
return [MROPE_OP, torch.ops.vllm.unified_kv_cache_update.default]
def ops_in_model_after(self) -> list[torch._ops.OpOverload]:
return [torch.ops.vllm.fused_qk_norm_mrope_and_unified_kv_cache_update.default]
class QKNormMRoPEObservableKTestModel(QKNormMRoPEKVCacheTestModel):
def forward(
self, qkv: torch.Tensor, positions: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
return QKNormRoPEKVCacheTestModel.forward(self, qkv, positions)
def _run_qk_norm_rope_kvcache_fusion_test(
*,
attn_backend: AttentionBackendEnum,
@@ -278,18 +346,33 @@ def _run_qk_norm_rope_kvcache_fusion_test(
rms_norm_eps: float,
custom_op: str,
monkeypatch: pytest.MonkeyPatch,
mrope_section: tuple[int, int, int] | None = None,
mrope_interleaved: bool = False,
observe_mrope_k: bool = False,
expect_fusion: bool = True,
use_quark_scalar_query_scale: bool = False,
) -> None:
device = os.environ.get("VLLM_TEST_CUDA_DEVICE", "cuda")
torch.set_default_device(device)
torch.set_default_dtype(dtype)
torch.manual_seed(0)
# Set AITER toggles before VllmConfig initialization enables env caching.
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
monkeypatch.setenv("VLLM_ROCM_USE_AITER_LINEAR", "1")
rocm_aiter_ops.refresh_env_variables()
vllm_config = VllmConfig(
model_config=ModelConfig(dtype=dtype),
cache_config=CacheConfig(
block_size=block_size,
cache_dtype=kv_cache_dtype,
),
quant_config=(
QuarkConfig(quant_config={"exclude": []})
if use_quark_scalar_query_scale
else None
),
compilation_config=CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
custom_ops=[custom_op],
@@ -302,6 +385,7 @@ def _run_qk_norm_rope_kvcache_fusion_test(
with vllm.config.set_current_vllm_config(vllm_config), monkeypatch.context() as m:
m.setenv("VLLM_ROCM_USE_AITER", "1")
m.setenv("VLLM_ROCM_USE_AITER_LINEAR", "1")
m.setenv(
"VLLM_ROCM_USE_AITER_TRITON_ROPE",
"1" if enable_aiter_triton_rope else "0",
@@ -309,18 +393,49 @@ def _run_qk_norm_rope_kvcache_fusion_test(
m.setenv("VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT", use_shuffle_kv_layout)
rocm_aiter_ops.refresh_env_variables()
model = QKNormRoPEKVCacheTestModel(
vllm_config=vllm_config,
attn_backend=attn_backend,
num_heads=num_heads,
num_kv_heads=num_kv_heads,
head_size=head_size,
rotary_dim=rotary_dim,
is_neox=is_neox,
rms_norm_eps=rms_norm_eps,
dtype=dtype,
device=torch.get_default_device(),
)
expected_query_quant_group_shape = None
if use_quark_scalar_query_scale:
expected_query_quant_group_shape = (
GroupShape(-1, num_heads * head_size)
if num_kv_heads == 1
else GroupShape.PER_TENSOR
)
model_kwargs = {
"vllm_config": vllm_config,
"attn_backend": attn_backend,
"num_heads": num_heads,
"num_kv_heads": num_kv_heads,
"head_size": head_size,
"rotary_dim": rotary_dim,
"is_neox": is_neox,
"rms_norm_eps": rms_norm_eps,
"dtype": dtype,
"device": torch.get_default_device(),
"expected_query_quant_group_shape": expected_query_quant_group_shape,
}
if mrope_section is None:
model = QKNormRoPEKVCacheTestModel(**model_kwargs)
else:
alternate_section = (8, 8, 8)
m.setattr(
fusion_module,
"_discover_mrope_configs",
lambda _: (
(mrope_section, mrope_interleaved),
(alternate_section, not mrope_interleaved),
),
)
model_cls = (
QKNormMRoPEObservableKTestModel
if observe_mrope_k
else QKNormMRoPEKVCacheTestModel
)
model = model_cls(
**model_kwargs,
mrope_section=mrope_section,
mrope_interleaved=mrope_interleaved,
)
fusion_pass = QkNormRopeKvCacheFusionPass(vllm_config)
passes = [
@@ -337,7 +452,12 @@ def _run_qk_norm_rope_kvcache_fusion_test(
num_heads * head_size + 2 * num_kv_heads * head_size,
dtype=dtype,
)
pos = torch.arange(num_tokens, dtype=torch.long)
if mrope_section is None:
pos = torch.arange(num_tokens, dtype=torch.long)
else:
# Real Qwen-VL position IDs can be a strided [3, N] view.
pos = torch.randint(0, 4096, (3, 2 * num_tokens), dtype=torch.long)[:, ::2]
assert not pos.is_contiguous()
qkv_unfused = qkv.clone()
pos_unfused = pos.clone()
@@ -356,7 +476,7 @@ def _run_qk_norm_rope_kvcache_fusion_test(
# Run fused (compiled) forward
torch._dynamo.mark_dynamic(qkv, 0)
torch._dynamo.mark_dynamic(pos, 0)
torch._dynamo.mark_dynamic(pos, 0 if mrope_section is None else 1)
with set_forward_context(None, vllm_config):
model_fused = torch.compile(model, backend=backend)
forward_context = get_forward_context()
@@ -369,14 +489,33 @@ def _run_qk_norm_rope_kvcache_fusion_test(
kv_cache_fused = attn_layer.kv_cache
del dummy
assert fusion_pass.matched_count == 1
assert fusion_pass.matched_count == int(expect_fusion)
backend.check_before_ops(model.ops_in_model_before())
backend.check_after_ops(model.ops_in_model_after())
if expect_fusion:
backend.check_before_ops(model.ops_in_model_before())
backend.check_after_ops(model.ops_in_model_after())
else:
for op in model.ops_in_model_before():
assert backend.op_count(op, before=True) > 0
assert backend.op_count(op) > 0
if use_quark_scalar_query_scale:
expected_quant_op = (
torch.ops.vllm.rocm_aiter_per_tensor_quant.default
if num_kv_heads != 1
else torch.ops._C.static_scaled_fp8_quant.default
)
assert backend.op_count(expected_quant_op, before=True) > 0
# Query quantization remains separate after the prologue fusion.
assert backend.op_count(expected_quant_op) > 0
# Sweep-backed (18.2k pts, PR #42749): native-rope ref worst 7.7e-3 -> 1e-2;
# AITER-triton-rope ref is itself approximate (plateau 1.28e-2) -> 2e-2.
ATOL, RTOL = (2e-2, 2e-2) if enable_aiter_triton_rope else (1e-2, 1e-2)
ATOL, RTOL = (
(2e-2, 2e-2)
if enable_aiter_triton_rope or mrope_section is not None
else (1e-2, 1e-2)
)
is_fp8_cache = model.kv_cache_dtype != dtype
if q_fused.dtype == FP8_DTYPE:
@@ -387,7 +526,7 @@ def _run_qk_norm_rope_kvcache_fusion_test(
else:
torch.testing.assert_close(q_unfused, q_fused, atol=ATOL, rtol=RTOL)
if not is_fp8_cache:
if not expect_fusion or (not is_fp8_cache and mrope_section is None):
# The AITER PTS kernel populates k_out only for non-FP8 caches.
# With FP8, the kernel writes quantized K directly to the cache
# and may leave k_out uninitialised. In production this is fine
@@ -397,15 +536,16 @@ def _run_qk_norm_rope_kvcache_fusion_test(
# Should be bit exact since no processing had been done on v for both paths
torch.testing.assert_close(v_unfused, v_fused, atol=0.0, rtol=0.0)
# fp8 vs triton-rope ref requires loosening tolerance to 1.25e-1.
if is_fp8_cache and enable_aiter_triton_rope:
# Fused and unfused arithmetic can straddle an FP8 rounding boundary.
# Allow one E4M3 quantization step while still comparing every block.
if is_fp8_cache:
cache_atol = cache_rtol = 1.25e-1
else:
cache_atol, cache_rtol = ATOL, RTOL
torch.testing.assert_close(
kv_cache_unfused[0].float(),
kv_cache_fused[0].float(),
kv_cache_unfused.float(),
kv_cache_fused.float(),
atol=cache_atol,
rtol=cache_rtol,
)
@@ -494,3 +634,225 @@ def test_qk_norm_rope_kvcache_fusion(
custom_op=custom_op,
monkeypatch=monkeypatch,
)
@pytest.mark.parametrize(
"mrope_section",
[
pytest.param((16, 24, 24), id="full_rotary"),
pytest.param((4, 6, 6), id="partial_rotary"),
],
)
@pytest.mark.parametrize("mrope_interleaved", [False, True])
@pytest.mark.parametrize("is_neox", [False, True])
@pytest.mark.parametrize(
"kv_layout",
[
pytest.param(KVCacheLayout.LBHNC, id="head_major"),
pytest.param(KVCacheLayout.LBNHC, id="token_major"),
pytest.param(KVCacheLayout.LHBNC, id="block_major"),
],
)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
@pytest.mark.skipif(
not IS_AITER_FOUND,
reason="Requires AITER",
)
def test_qk_norm_mrope_kvcache_fusion(
mrope_section: tuple[int, int, int],
mrope_interleaved: bool,
is_neox: bool,
kv_layout: KVCacheLayout,
kv_cache_dtype: str,
monkeypatch: pytest.MonkeyPatch,
):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=8,
num_kv_heads=2,
head_size=128,
rotary_dim=2 * sum(mrope_section),
block_size=16,
is_neox=is_neox,
use_shuffle_kv_layout="0",
kv_layout=kv_layout,
dtype=torch.bfloat16,
kv_cache_dtype=kv_cache_dtype,
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=mrope_section,
mrope_interleaved=mrope_interleaved,
)
@pytest.mark.parametrize(
("num_heads", "num_kv_heads"),
[(32, 2), (16, 1), (8, 1)],
ids=["tp2", "tp4", "tp8"],
)
def test_qk_norm_mrope_kvcache_fusion_quark_scalar_query_scale(
num_heads: int,
num_kv_heads: int,
monkeypatch: pytest.MonkeyPatch,
):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=num_heads,
num_kv_heads=num_kv_heads,
head_size=128,
rotary_dim=128,
block_size=16,
is_neox=True,
use_shuffle_kv_layout="0",
kv_layout=KVCacheLayout.LBHNC,
dtype=torch.bfloat16,
kv_cache_dtype="fp8",
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=(24, 20, 20),
mrope_interleaved=True,
use_quark_scalar_query_scale=True,
)
def test_mrope_fusion_rejects_observable_k(monkeypatch: pytest.MonkeyPatch):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=8,
num_kv_heads=2,
head_size=128,
rotary_dim=128,
block_size=16,
is_neox=True,
use_shuffle_kv_layout="0",
kv_layout=KVCacheLayout.LBHNC,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=(16, 24, 24),
observe_mrope_k=True,
expect_fusion=False,
)
def test_mrope_fusion_rejects_unaligned_rotary_dim(
monkeypatch: pytest.MonkeyPatch,
):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=8,
num_kv_heads=2,
head_size=128,
rotary_dim=6,
block_size=16,
is_neox=True,
use_shuffle_kv_layout="0",
kv_layout=KVCacheLayout.LBHNC,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=(1, 1, 1),
expect_fusion=False,
)
@pytest.mark.skipif(not _USE_LAYERNAME, reason="requires opaque LayerName")
def test_opaque_layer_name_patterns_register_once(monkeypatch: pytest.MonkeyPatch):
device = os.environ.get("VLLM_TEST_CUDA_DEVICE", "cuda")
vllm_config = VllmConfig(
model_config=ModelConfig(dtype=torch.bfloat16),
cache_config=CacheConfig(block_size=16, cache_dtype="fp8_e4m3"),
compilation_config=CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
custom_ops=["+rotary_embedding"],
pass_config=PassConfig(fuse_qk_norm_rope_kvcache=True),
),
)
with vllm.config.set_current_vllm_config(vllm_config), monkeypatch.context() as m:
m.setenv("VLLM_ROCM_USE_AITER", "1")
rocm_aiter_ops.refresh_env_variables()
model_kwargs = {
"vllm_config": vllm_config,
"attn_backend": AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
"num_heads": 8,
"num_kv_heads": 2,
"head_size": 128,
"is_neox": True,
"rms_norm_eps": 1e-6,
"dtype": torch.bfloat16,
"device": torch.device(device),
}
models = [
QKNormRoPEKVCacheTestModel(
**model_kwargs,
prefix=f"model.layers.{index}.self_attn.attn",
)
for index in range(2)
]
# Opaque layer names are wildcards in the pattern graph. Registering
# once per physical layer raises "Duplicate pattern" on torch >= 2.11.
fusion_pass = QkNormRopeKvCacheFusionPass(vllm_config)
assert models
assert fusion_pass.patterns
def _call_fused_mrope_impl(q_out: torch.Tensor) -> None:
device = q_out.device
fusion_module.fused_qk_norm_mrope_and_unified_kv_cache_update_impl(
q_out=q_out,
qkv=torch.zeros(2, 16, device=device),
positions=torch.arange(2, device=device),
q_weight=torch.ones(4, device=device),
k_weight=torch.ones(4, device=device),
rms_norm_eps=1e-6,
cos_sin_cache=torch.zeros(16, 4, device=device),
is_neox=True,
mrope_section_t=1,
mrope_section_h=1,
mrope_section_w=0,
is_interleaved=False,
rotary_dim=4,
layer_name="model.layers.0.self_attn.attn",
)
def test_mrope_profiling_pass_initializes_query(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
fusion_module,
"get_attention_context",
lambda _: (None, None, None, None),
)
q_out = torch.full((2, 8), torch.nan, device="cpu")
_call_fused_mrope_impl(q_out)
torch.testing.assert_close(q_out, torch.zeros_like(q_out))
def test_mrope_attention_context_failure_propagates(
monkeypatch: pytest.MonkeyPatch,
):
def fail_context(_):
raise RuntimeError("missing attention context")
monkeypatch.setattr(fusion_module, "get_attention_context", fail_context)
with pytest.raises(RuntimeError, match="missing attention context"):
_call_fused_mrope_impl(torch.empty(2, 8, device="cpu"))
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
+75
View File
@@ -0,0 +1,75 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ROCm AsyncTP numerical coverage kept outside the shared distributed suite."""
import pytest
import torch
from tests.compile.passes.distributed.test_async_tp import (
TestAGMMModel,
TestMMRSModel,
async_tp_pass_on_test_model,
)
from tests.utils import multi_gpu_test
from vllm.distributed import (
tensor_model_parallel_all_gather,
tensor_model_parallel_reduce_scatter,
)
from vllm.platforms import current_platform
from vllm.utils.network_utils import get_file_store_init_method
class TestRocmMMRSModel(TestMMRSModel):
def forward(self, hidden_states):
view = hidden_states.reshape(-1, self.hidden_size)
mm = torch.ops.vllm.rocm_unquantized_gemm(view, self.gate_proj, None)
return tensor_model_parallel_reduce_scatter(mm, dim=0)
def ops_in_model_before(self):
return super().ops_in_model_before() + [
torch.ops.vllm.rocm_unquantized_gemm.default
]
class TestRocmAGMMModel(TestAGMMModel):
def __init__(self, hidden_size=16, dtype=torch.bfloat16):
super().__init__(hidden_size, dtype)
self.weight = torch.nn.Parameter(
torch.empty((hidden_size * 2, hidden_size)), requires_grad=False
)
torch.nn.init.normal_(self.weight, std=0.02)
def forward(self, hidden_states):
view = hidden_states.reshape(-1, self.hidden_size)
gathered = tensor_model_parallel_all_gather(view, dim=0)
return torch.ops.vllm.rocm_unquantized_gemm(gathered, self.weight, None)
def ops_in_model_before(self):
return super().ops_in_model_before() + [
torch.ops.vllm.rocm_unquantized_gemm.default
]
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm backend contract")
@pytest.mark.parametrize(
"test_model", [TestMMRSModel, TestAGMMModel, TestRocmMMRSModel, TestRocmAGMMModel]
)
@pytest.mark.parametrize("dynamic", [False, True])
def test_rocm_async_tp_bf16_rewrite_and_correctness(test_model, dynamic):
"""Real symmetric-memory AG/GEMM and GEMM/RS must replace the collectives."""
torch.multiprocessing.spawn(
async_tp_pass_on_test_model,
args=(
2,
test_model,
8,
16,
128,
torch.bfloat16,
dynamic,
get_file_store_init_method(),
True,
),
nprocs=2,
)
+46
View File
@@ -70,6 +70,37 @@ def test_get_raw_stream_patch():
assert get_raw_stream is _cuda_getCurrentRawStream
# Inductor can initialize CUDA even for CPU inputs.
@pytest.mark.forked
@pytest.mark.parametrize("use_v2", [False, True])
def test_e8m0_custom_op_fullgraph(use_v2, use_fresh_inductor_cache):
"""E8M0 inputs must not prevent mutable custom-op decomposition."""
with torch.library._scoped_library("test_e8m0", "FRAGMENT") as lib:
lib.define("scale_(Tensor(a!) out, Tensor scale) -> ()")
@torch.library.impl(lib, "scale_", "CPU")
def scale_impl(out, scale):
out.mul_(scale.float())
@torch.library.register_fake("test_e8m0::scale_", lib=lib)
def scale_fake(out, scale):
return None
def forward(x, scale):
out = x.clone()
torch.ops.test_e8m0.scale_(out, scale)
return out
x = torch.randn(4, 4)
scale = torch.full((4,), 128, dtype=torch.uint8).view(torch.float8_e8m0fnu)
compiled = torch.compile(
forward,
fullgraph=True,
options={"enable_auto_functionalized_v2": use_v2},
)
torch.testing.assert_close(compiled(x, scale), x * 2)
def test_copy_pass():
vllm_config = VllmConfig()
inductor_pass = FixFunctionalizationPass(vllm_config)
@@ -233,6 +264,21 @@ def test_enforce_eager(vllm_runner, monkeypatch):
pass
@pytest.mark.parametrize("enable_fault_tolerance", [False, True])
def test_enforce_eager_jit_warmup(enable_fault_tolerance):
"""Enforce-eager disables JIT warmup unless fault tolerance is on.
FT fault detection runs against deadlines that in-inference Triton
compilation latency spikes can blow past, so warmup stays enabled.
"""
config = VllmConfig(
model_config=ModelConfig(model="facebook/opt-125m", enforce_eager=True),
parallel_config=ParallelConfig(enable_fault_tolerance=enable_fault_tolerance),
)
assert config.compilation_config.mode == CompilationMode.NONE
assert config.kernel_config.enable_jit_warmup == enable_fault_tolerance
@pytest.mark.forked
def test_torch_compile_disable(vllm_runner, monkeypatch):
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
+3 -3
View File
@@ -3,7 +3,7 @@
from typing import get_args
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config.speculative import MTPModelTypes, SpeculativeConfig
from vllm.transformers_utils.model_arch_config_convertor import (
@@ -11,8 +11,8 @@ from vllm.transformers_utils.model_arch_config_convertor import (
)
def _bailing_config() -> PretrainedConfig:
config = PretrainedConfig(
def _bailing_config() -> PreTrainedConfig:
config = PreTrainedConfig(
architectures=["BailingMoeV2_5ForCausalLM"],
hidden_size=4096,
kv_lora_rank=512,
+57
View File
@@ -109,3 +109,60 @@ def test_unrecognized_env(monkeypatch):
fail_on_environ_validation=True,
)
engine_args.create_engine_config()
def test_get_diff_sampling_param_includes_penalties():
"""``--override-generation-config`` must apply presence_penalty and
frequency_penalty as server-side defaults, like the other sampling
params. Regression test for the whitelist silently dropping them.
Called unbound with a lightweight stand-in so no model is loaded:
generation_config="vllm" makes the method skip try_get_generation_config
and read only override_generation_config.
"""
from types import SimpleNamespace
from vllm.config.model import ModelConfig
fake = SimpleNamespace(
generation_config="vllm",
override_generation_config={
"presence_penalty": 1.5,
"frequency_penalty": 0.5,
"temperature": 0.6,
},
)
diff = ModelConfig.get_diff_sampling_param(fake) # type: ignore[arg-type]
assert diff["presence_penalty"] == 1.5
assert diff["frequency_penalty"] == 0.5
assert diff["temperature"] == 0.6
def test_generation_config_penalties_survive_diff_sampling_filter():
"""``generation_config.json`` penalties must survive the diff-sampling
whitelist (regression for #50767, auto path).
Covers the ``generation_config="auto"`` branch, where the override
dict is empty and the values come from ``try_get_generation_config``.
"""
from types import SimpleNamespace
from vllm.config.model import ModelConfig
fake = SimpleNamespace(
generation_config="auto",
override_generation_config={},
try_get_generation_config=lambda: {
"presence_penalty": 1.1,
"frequency_penalty": 0.7,
"temperature": 0.9,
},
)
diff = ModelConfig.get_diff_sampling_param(fake) # type: ignore[arg-type]
assert diff["presence_penalty"] == 1.1
assert diff["frequency_penalty"] == 0.7
assert diff["temperature"] == 0.9
+33 -8
View File
@@ -10,13 +10,15 @@ from typing import cast
from unittest.mock import Mock
import pytest
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from transformers.models.gemma4.configuration_gemma4 import Gemma4TextConfig
from vllm.config import ModelConfig, ParallelConfig, SpeculativeConfig
from vllm.config.model_arch import ModelArchitectureConfig
from vllm.transformers_utils.configs.diffusion_gemma import DiffusionGemmaConfig
from vllm.transformers_utils.configs.gemma4 import gemma4_layer_config
from vllm.transformers_utils.model_arch_config_convertor import (
MODEL_ARCH_CONFIG_CONVERTORS,
Gemma4ModelArchConfigConvertor,
ModelArchConfigConvertorBase,
)
@@ -123,7 +125,7 @@ def _assert_model_config_methods(
def test_head_size_falls_back_when_head_dim_is_zero():
"""Regression test for configs that materialize missing head_dim as 0."""
hf_config = PretrainedConfig(
hf_config = PreTrainedConfig(
model_type="deepseek_vl_v2",
hidden_size=1280,
num_attention_heads=10,
@@ -138,7 +140,7 @@ def test_head_size_falls_back_when_head_dim_is_zero():
def test_qk_rope_head_dim_recovery_uses_model_revision(monkeypatch: pytest.MonkeyPatch):
hf_config = PretrainedConfig(
hf_config = PreTrainedConfig(
model_type="deepseek_v2",
qk_rope_head_dim=128,
qk_nope_head_dim=128,
@@ -174,7 +176,7 @@ def test_qk_rope_head_dim_recovery_uses_model_revision(monkeypatch: pytest.Monke
],
)
def test_num_experts_per_tok_aliases(attribute: str):
hf_config = PretrainedConfig(**{attribute: 4})
hf_config = PreTrainedConfig(**{attribute: 4})
convertor = ModelArchConfigConvertorBase(hf_config, hf_config)
model_config = cast(
ModelConfig,
@@ -189,7 +191,7 @@ def test_num_experts_per_tok_aliases(attribute: str):
def test_num_experts_per_tok_none_is_normalized():
hf_config = PretrainedConfig(top_k_experts=None)
hf_config = PreTrainedConfig(top_k_experts=None)
convertor = ModelArchConfigConvertorBase(hf_config, hf_config)
assert convertor.get_num_experts_per_token() == 0
@@ -205,7 +207,7 @@ def test_legacy_modelopt_config_without_producer_is_normalized():
"modelopt_quant_config": {"quant_cfg": {}},
}
}
hf_config = PretrainedConfig(quantization_config=quantization_config)
hf_config = PreTrainedConfig(quantization_config=quantization_config)
convertor = ModelArchConfigConvertorBase(hf_config, hf_config)
@@ -368,7 +370,7 @@ def test_gemma4_uniform_head_dims_are_homogeneous():
assert arch[3] is arch
class _HeterogeneousConfig(PretrainedConfig):
class _HeterogeneousConfig(PreTrainedConfig):
"""A heterogeneous config with no convertor of its own.
Mirrors the parts vLLM uses: per-layer configs are shallow copies with the
@@ -382,7 +384,7 @@ class _HeterogeneousConfig(PretrainedConfig):
super().__init__(**kwargs)
@property
def per_layer_config(self) -> list[PretrainedConfig]:
def per_layer_config(self) -> list[PreTrainedConfig]:
layers = []
for i in range(self.num_hidden_layers):
layer = copy(self)
@@ -496,3 +498,26 @@ def test_deepseek_v4_convertor_splits_vision_architecture():
conv = DeepseekV4ModelArchConfigConvertor(draft_cfg, draft_cfg)
assert conv.get_architectures() == [draft_arch]
assert draft_cfg.architectures == [draft_arch]
def test_diffusion_gemma_head_dims_vary_by_layer_type():
"""Checkpoints carry model_type `diffusion_gemma` at the top level. Under
the base convertor every layer reports the sliding head dim, Gemma4Config
skips its head-dim handling, and the full-attention KV-cache group falls to
FlashInfer, which cannot take a per-request causal tensor."""
text_config = dict(
num_hidden_layers=6,
hidden_size=64,
num_attention_heads=8,
num_key_value_heads=4,
head_dim=16,
global_head_dim=32,
layer_types=["sliding_attention"] * 5 + ["full_attention"],
)
hf_config = DiffusionGemmaConfig(text_config=text_config)
convertor_cls = MODEL_ARCH_CONFIG_CONVERTORS[hf_config.model_type]
assert convertor_cls is Gemma4ModelArchConfigConvertor
arch = convertor_cls(hf_config, hf_config.text_config).convert()
assert [arch[i].head_size for i in range(6)] == [16] * 5 + [32]
+2 -2
View File
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch
import pytest
import torch
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from tests.models.utils import build_model_context
from vllm.config.ec_transfer import ECRole, ECTransferConfig
@@ -136,7 +136,7 @@ def test_language_model_only_disables_via_supports_multimodal_inputs():
def test_convertor_clears_mm_prefix_when_multimodal_disabled():
hf_config = PretrainedConfig(
hf_config = PreTrainedConfig(
model_type="gemma3",
architectures=["Gemma3ForConditionalGeneration"],
)
@@ -15,20 +15,20 @@ import functools
from unittest.mock import MagicMock, patch
import pytest
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config.parallel import ParallelConfig
from vllm.config.speculative import SpeculativeConfig
def _make_hf_config(**kwargs) -> PretrainedConfig:
def _make_hf_config(**kwargs) -> PreTrainedConfig:
defaults = dict(
architectures=["LlamaForCausalLM"],
model_type="llama",
num_hidden_layers=64,
)
defaults.update(kwargs)
return PretrainedConfig(**defaults)
return PreTrainedConfig(**defaults)
@pytest.mark.cpu_test
@@ -47,12 +47,97 @@ def test_none_overrides_fall_back_to_arch_mapping():
assert composed is SpeculativeConfig.hf_config_override
def _make_speculative_config(
hf_kwargs: dict, architecture: str, **speculative_kwargs
) -> SpeculativeConfig:
hf_config = SpeculativeConfig.hf_config_override(_make_hf_config(**hf_kwargs))
draft = MagicMock(
hf_config=hf_config, architectures=hf_config.architectures, max_model_len=128
)
draft.registry.inspect_model_cls.return_value = (None, architecture)
target = MagicMock(max_model_len=128, quantization=None, hf_overrides={})
target.hf_config.model_type = hf_kwargs["model_type"]
with patch("vllm.config.speculative.ModelConfig", return_value=draft):
return SpeculativeConfig(
model="draft",
**speculative_kwargs,
target_model_config=target,
target_parallel_config=ParallelConfig(),
)
@pytest.mark.cpu_test
@pytest.mark.parametrize(
("hf_kwargs", "n_predict", "architecture"),
[
(
dict(
model_type="deepseek_v4",
num_nextn_predict_layers=3,
dspark_block_size=5,
),
3,
"DSparkDraftModel",
),
(
dict(
model_type="deepseek_v41",
num_nextn_predict_layers=3,
dspark_block_size=5,
),
3,
"DSparkV41DraftModel",
),
(
dict(
model_type="gemma4_text",
architectures=["Gemma4DSparkModel"],
block_size=5,
),
None,
"Gemma4DSparkModel",
),
],
)
@pytest.mark.parametrize("speculative_kwargs", [{"num_speculative_tokens": 5}, {}])
def test_dspark_width_is_independent_of_mtp_stages(
hf_kwargs, n_predict, architecture, speculative_kwargs
):
config = _make_speculative_config(
hf_kwargs, architecture, method="dspark", **speculative_kwargs
)
assert config.num_speculative_tokens == 5
assert getattr(config.draft_model_config.hf_config, "n_predict", None) == n_predict
assert config.draft_model_config.hf_config.architectures == [architecture]
@pytest.mark.cpu_test
def test_mtp_stages_are_independent_of_dspark_width():
hf_kwargs = dict(
model_type="deepseek_v4", num_nextn_predict_layers=3, dspark_block_size=5
)
config = _make_speculative_config(
hf_kwargs, "DeepSeekV4MTPModel", method="mtp", num_speculative_tokens=6
)
assert config.num_speculative_tokens == 6
assert config.draft_model_config.hf_config.n_predict == 3
assert config.draft_model_config.hf_config.architectures == ["DeepSeekV4MTPModel"]
with pytest.raises(ValueError, match="must be divisible by n_predict=3"):
_make_speculative_config(
hf_kwargs, "DeepSeekV4MTPModel", method="mtp", num_speculative_tokens=5
)
@pytest.mark.cpu_test
def test_callable_overrides_reach_the_draft_config():
"""A callable override (config-to-config transform) composes with the
architecture-mapping override and is applied to the draft config."""
def shrink(hf_config: PretrainedConfig) -> PretrainedConfig:
def shrink(hf_config: PreTrainedConfig) -> PreTrainedConfig:
hf_config.num_hidden_layers = 1
return hf_config
@@ -70,7 +155,7 @@ def test_arch_mapping_applies_before_callable_override():
observes (and may adjust) the post-mapping config."""
seen_architectures: list[str] = []
def record(hf_config: PretrainedConfig) -> PretrainedConfig:
def record(hf_config: PreTrainedConfig) -> PreTrainedConfig:
seen_architectures.append(hf_config.architectures[0])
return hf_config
@@ -117,7 +202,7 @@ def test_inkling_override_exposes_all_mtp_depths():
assert out.local_layer_ids == [0, 2, 4]
def _module_level_shrink(hf_config: PretrainedConfig) -> PretrainedConfig:
def _module_level_shrink(hf_config: PreTrainedConfig) -> PreTrainedConfig:
hf_config.num_hidden_layers = 1
return hf_config
@@ -17,7 +17,7 @@ import logging
from typing import Literal
import pytest
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config.model import ModelConfig
from vllm.config.parallel import ParallelConfig
@@ -46,7 +46,7 @@ def _override_logged(caplog: pytest.LogCaptureFixture) -> bool:
@pytest.mark.cpu_test
def test_override_raises_smaller_value(vllm_caplog: pytest.LogCaptureFixture):
hf_config = PretrainedConfig(max_position_embeddings=2048)
hf_config = PreTrainedConfig(max_position_embeddings=2048)
SpeculativeConfig._maybe_override_draft_max_position_embeddings(
hf_config, target_max_model_len=8192
)
@@ -56,7 +56,7 @@ def test_override_raises_smaller_value(vllm_caplog: pytest.LogCaptureFixture):
@pytest.mark.cpu_test
def test_override_keeps_sufficient_value(vllm_caplog: pytest.LogCaptureFixture):
hf_config = PretrainedConfig(max_position_embeddings=8192)
hf_config = PreTrainedConfig(max_position_embeddings=8192)
SpeculativeConfig._maybe_override_draft_max_position_embeddings(
hf_config, target_max_model_len=8192
)
@@ -66,7 +66,7 @@ def test_override_keeps_sufficient_value(vllm_caplog: pytest.LogCaptureFixture):
@pytest.mark.cpu_test
def test_override_ignores_missing_attribute(vllm_caplog: pytest.LogCaptureFixture):
hf_config = PretrainedConfig()
hf_config = PreTrainedConfig()
hf_config.__dict__.pop("max_position_embeddings", None)
SpeculativeConfig._maybe_override_draft_max_position_embeddings(
hf_config, target_max_model_len=8192
+31 -13
View File
@@ -317,14 +317,6 @@ def example_system_message() -> str:
return f.read()
class DecoderPromptType(Enum):
"""For encoder/decoder models only."""
CUSTOM = 1
NONE = 2
EMPTY_STR = 3
@pytest.fixture
def example_long_prompts() -> list[str]:
return [prompt for filename in _LONG_PROMPTS for prompt in _read_prompts(filename)]
@@ -928,7 +920,7 @@ class HfRunner:
# shutdown. This is helpful in cases where the HfRunner is
# initialized after significant GPU memory is already occupied,
# e.g. in
# tests/basic_correctness/test_basic_correctness.py::test_models_distributed
# tests/basic_correctness/models/test_basic_correctness.py::test_models_distributed
# where vllm worker processes are still alive and holding GPU
# memory when hf_runner.__exit__ is called.
from tests.utils import record_gpu_memory_usage_stats
@@ -982,6 +974,8 @@ class VllmRunner:
- `enable_chunked_prefill`: Set to `False` instead of `None` for
test reproducibility.
- `enforce_eager`: Set to `False` to test CUDA graph.
- `kernel_config.enable_jit_warmup`: Set to `False` to reduce test startup
time.
"""
def __init__(
@@ -1010,6 +1004,8 @@ class VllmRunner:
else set_default_torch_num_threads(default_torch_num_threads)
)
kwargs.setdefault("kernel_config", {"enable_jit_warmup": False})
if not kwargs.get("compilation_config", None):
# Note(@tdoublep): This is set to 4 because some tests (e.g., hybrid
# model tests) may set max_num_seqs=4. If min cudagraph_capture_size is
@@ -1426,16 +1422,20 @@ def temporary_enable_log_propagate():
import logging
logger = logging.getLogger("vllm")
previous_propagate = logger.propagate
logger.propagate = True
yield
logger.propagate = False
logger.propagate = previous_propagate
@pytest.fixture()
def caplog_vllm(temporary_enable_log_propagate, caplog):
# To capture vllm log, we should enable propagate=True temporarily
# because caplog depends on logs propagated to the root logger.
yield caplog
# caplog depends on logs propagated to the root logger. The vLLM logger
# inherits this INFO level until runtime initialization configures it.
import logging
with caplog.at_level(logging.INFO):
yield caplog
@pytest.fixture()
@@ -1786,6 +1786,24 @@ def disable_deepgemm_ue8m0(monkeypatch):
is_deep_gemm_e8m0_used.cache_clear()
@pytest.fixture
def gpu_memory_cleared():
"""Wait for prior tests to release GPU memory on gfx950."""
if not current_platform.is_rocm():
return
from tests.utils import wait_for_gpu_memory_to_clear
from vllm.platforms.rocm import on_gfx950
if on_gfx950():
wait_for_gpu_memory_to_clear(
devices=[0],
threshold_ratio=0.08,
timeout_s=30,
stable_duration_s=1,
)
def _should_clean_gpu_memory_between_tests() -> bool:
# This must stay opt-in: a function-scoped fixture cannot distinguish
# stale VRAM from allocations owned by longer-lived module/session fixtures.
+130
View File
@@ -0,0 +1,130 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from vllm.device_allocator import alloc_conf
pytestmark = pytest.mark.cpu_test
ES = alloc_conf.EXPANDABLE_SEGMENTS
@pytest.mark.parametrize(
"environ,expected",
[
({}, False),
({"PYTORCH_ALLOC_CONF": "expandable_segments:True"}, True),
({"PYTORCH_ALLOC_CONF": "expandable_segments:true"}, True),
({"PYTORCH_ALLOC_CONF": "expandable_segments:1"}, True),
({"PYTORCH_ALLOC_CONF": "expandable_segments:False"}, False),
({"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, True),
# ROCm users set this one; it was previously not looked at.
({"PYTORCH_HIP_ALLOC_CONF": "expandable_segments:True"}, True),
(
{"PYTORCH_ALLOC_CONF": "max_split_size_mb:512,expandable_segments:True"},
True,
),
({"PYTORCH_ALLOC_CONF": "max_split_size_mb:512"}, False),
({"PYTORCH_ALLOC_CONF": "not_expandable_segments_really:True"}, False),
({"PYTORCH_ALLOC_CONF": ""}, False),
# torch's precedence: the accelerator-agnostic variable wins.
(
{
"PYTORCH_ALLOC_CONF": "expandable_segments:False",
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
},
False,
),
],
)
def test_expandable_segments_from_env(environ, expected):
assert alloc_conf.expandable_segments_enabled_from_env(environ) is expected
@pytest.mark.parametrize(
"conf,key,expected",
[
("", ES, False),
("expandable_segments:True", ES, True),
("expandable_segments:TRUE", ES, True),
("expandable_segments:1", ES, True),
("expandable_segments:0", ES, False),
(" expandable_segments : True ", ES, True),
("max_split_size_mb:512", ES, False),
("max_split_size_mb:512", "max_split_size_mb", False),
("garbage_collection_threshold:0.9", ES, False),
],
)
def test_conf_flag_enabled(conf, key, expected):
assert alloc_conf.conf_flag_enabled(conf, key) is expected
@pytest.mark.parametrize(
"conf,enabled,expected",
[
("", False, "expandable_segments:False"),
("expandable_segments:True", False, "expandable_segments:False"),
("expandable_segments:False", True, "expandable_segments:True"),
(
"max_split_size_mb:512,expandable_segments:True",
False,
"max_split_size_mb:512,expandable_segments:False",
),
(
"garbage_collection_threshold:0.9,max_split_size_mb:512",
False,
"garbage_collection_threshold:0.9,max_split_size_mb:512,"
"expandable_segments:False",
),
],
)
def test_with_conf_flag_preserves_other_fields(conf, enabled, expected):
assert alloc_conf.with_conf_flag(conf, ES, enabled) == expected
def test_with_conf_flag_round_trips():
"""The regression this guards: torch resets every option absent from the
string it is handed, so a one-field write drops the rest permanently."""
conf = (
"max_split_size_mb:512,expandable_segments:True,"
"garbage_collection_threshold:0.9"
)
off = alloc_conf.with_conf_flag(conf, ES, False)
assert "max_split_size_mb:512" in off
assert "garbage_collection_threshold:0.9" in off
assert alloc_conf.with_conf_flag(off, ES, True) == conf
def test_alloc_conf_from_env_precedence():
assert (
alloc_conf.alloc_conf_from_env(
{
"PYTORCH_CUDA_ALLOC_CONF": "max_split_size_mb:256",
"PYTORCH_HIP_ALLOC_CONF": "max_split_size_mb:128",
}
)
== "max_split_size_mb:256"
)
assert alloc_conf.alloc_conf_from_env({}) == ""
def test_current_alloc_conf_prefers_live_state(monkeypatch):
monkeypatch.setattr(alloc_conf, "live_alloc_conf", lambda: "max_split_size_mb:64")
monkeypatch.setattr(alloc_conf, "alloc_conf_from_env", lambda: "stale:True")
assert alloc_conf.current_alloc_conf() == "max_split_size_mb:64"
monkeypatch.setattr(alloc_conf, "live_alloc_conf", lambda: None)
assert alloc_conf.current_alloc_conf() == "stale:True"
def test_expandable_segments_enabled_returns_none_when_unreadable(monkeypatch):
"""'cannot read' must stay distinct from 'disabled'."""
class _NoSnapshot:
@staticmethod
def _snapshot():
raise RuntimeError("no allocator here")
monkeypatch.setattr(alloc_conf.torch.cuda, "memory", _NoSnapshot)
assert alloc_conf.expandable_segments_enabled() is None
@@ -23,6 +23,7 @@ import torch
import torch.distributed as dist
from vllm.distributed.parallel_state import get_tp_group
from vllm.models.common.ops.sequence_parallel import sp_reduce_scatter
from vllm.platforms import current_platform
from ..utils import (
@@ -53,6 +54,11 @@ def _supports_multimem():
)
def _supports_sm100_or_sm103():
capability = current_platform.get_device_capability()
return current_platform.is_cuda() and capability in ((10, 0), (10, 3))
def _payload(value, device):
return torch.full((_ROWS, _HIDDEN), value, dtype=torch.bfloat16, device=device)
@@ -324,3 +330,65 @@ def test_mnnvl_lamport_stage_cleanup(monkeypatch: pytest.MonkeyPatch):
if torch.accelerator.device_count() < 2:
pytest.skip("Need at least two GPUs to run the test.")
multi_process_parallel(monkeypatch, 2, 1, _run_stage_cleanup_test)
@ray.remote(num_gpus=1, max_calls=1)
def _run_multimem_reduce_scatter_test(
monkeypatch: pytest.MonkeyPatch,
tp_size,
pp_size,
rank,
distributed_init_port,
):
with monkeypatch.context() as m:
m.delenv("CUDA_VISIBLE_DEVICES", raising=False)
m.delenv("HIP_VISIBLE_DEVICES", raising=False)
device = torch.device(f"cuda:{rank}")
torch.accelerator.set_device_index(device)
init_test_distributed_environment(tp_size, pp_size, rank, distributed_init_port)
ensure_model_parallel_initialized(tp_size, pp_size)
fa = get_tp_group().device_communicator.ca_comm
assert fa is not None and not fa.disabled
assert fa.mnnvl_multimem_rs_supported
assert not fa.mnnvl_multimem_rs_initialized
assert not fa.mnnvl_multimem_rs_multicast_ptr
message_bytes = {
"mnnvl_lamport": 1 * 1024 * 1024,
"mnnvl_multimem": 20 * 1024 * 1024,
"nccl": 64 * 1024 * 1024 + 128,
}
for _ in range(2):
for backend, size_bytes in message_bytes.items():
shard_elements = size_bytes // torch.bfloat16.itemsize // tp_size
inp = torch.full(
(tp_size, shard_elements),
rank + 1,
dtype=torch.bfloat16,
device=device,
)
selected = fa._select_reduce_scatter_backend(inp)
if backend == "nccl":
assert selected is None
out = sp_reduce_scatter(inp)
else:
assert selected == backend
out = fa.custom_reduce_scatter(inp)
assert out is not None
if backend == "mnnvl_multimem":
assert fa.mnnvl_multimem_rs_initialized
assert fa.mnnvl_multimem_rs_multicast_ptr
expected = tp_size * (tp_size + 1) // 2
torch.testing.assert_close(out, torch.full_like(out, expected))
@pytest.mark.skipif(
not _supports_sm100_or_sm103(),
reason="The low-SM MNNVL reduce-scatter path requires SM100 or SM103.",
)
@pytest.mark.parametrize("tp_size", [2, 4, 8])
def test_mnnvl_multimem_reduce_scatter(monkeypatch: pytest.MonkeyPatch, tp_size: int):
if torch.accelerator.device_count() < tp_size:
pytest.skip(f"Need at least {tp_size} GPUs to run the test.")
multi_process_parallel(monkeypatch, tp_size, 1, _run_multimem_reduce_scatter_test)
+380 -71
View File
@@ -25,12 +25,43 @@ for i, v in enumerate(test_sizes):
test_sizes[i] -= v % 8
def _bf16_ulps(a: torch.Tensor, b: torch.Tensor) -> int:
"""Largest distance between two BF16 tensors in units in the last place."""
def ordered(t: torch.Tensor) -> torch.Tensor:
bits = t.view(torch.int16).int() & 0xFFFF
return torch.where(bits >= 0x8000, 0x8000 - bits, bits)
return int((ordered(a) - ordered(b)).abs().max())
def _unfused_all_reduce_mhc(peers, residual, post, comb, pre, weight, eps):
"""All-reduce, mHC post, collapse and RMSNorm in the fused kernel's FP32
order, rounding to BF16 where the unfused path returns BF16."""
reduced = peers[0].float()
for peer in peers[1:]:
reduced = reduced + peer.float()
reduced = reduced.bfloat16().float()
output = torch.empty_like(residual)
collapse = torch.zeros_like(reduced)
for target in range(4):
mixed = reduced * post[:, target : target + 1]
for source in range(4):
mixed = torch.addcmul(
mixed, residual[:, source].float(), comb[:, source, target, None]
)
output[:, target] = mixed.bfloat16()
collapse = torch.addcmul(
collapse, output[:, target].float(), pre[:, target : target + 1]
)
prenorm = collapse.bfloat16().float()
inv_rms = torch.rsqrt(prenorm.square().mean(-1, keepdim=True) + eps)
return output, (prenorm * inv_rms * weight.float()).bfloat16()
@ray.remote(num_gpus=1, max_calls=1)
def _all_reduce_mhc(monkeypatch, tp_size, pp_size, rank, distributed_init_port):
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_post_tilelang,
mhc_pre_delayed_tilelang,
)
from vllm.models.deepseek_v41.nvidia.ops.cute_dsl import AllReduceMHC
with monkeypatch.context() as m:
m.delenv("CUDA_VISIBLE_DEVICES", raising=False)
@@ -38,98 +69,114 @@ def _all_reduce_mhc(monkeypatch, tp_size, pp_size, rank, distributed_init_port):
torch.accelerator.set_device_index(device)
init_test_distributed_environment(tp_size, pp_size, rank, distributed_init_port)
ensure_model_parallel_initialized(tp_size, pp_size)
comm = get_tp_group().device_communicator.ca_comm
assert comm is not None and comm.mnnvl_lamport_ag_multicast_ptr
fn = torch.zeros(24, 20480, device=device)
scale = torch.ones(3, device=device)
base = torch.zeros(24, device=device)
op = AllReduceMHC(
hidden_size=5120, hc_mult=4, max_num_tokens=16, top_k=6, device=device
)
# Changing shapes and interleaving all-gather exercise the shared
# Lamport stages, including cleanup of a larger previous payload.
def run(n):
torch.manual_seed(42 + rank)
x = torch.randn(n, 5120, device=device, dtype=torch.bfloat16)
# Packed +0/-0 pairs collide with the Lamport sentinel.
x[:, :16] = 0
x[:, 9:16:2] = -0.0
def check_eager_and_replayed(fused, check, halved, doubled):
check(fused())
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
for _ in range(5):
fused()
captured = fused()
for _ in range(20):
graph.replay()
check(captured)
# Replays must pick up in-place input changes.
halved.mul_(0.5)
doubled.mul_(2)
graph.replay()
check(captured)
def mhc_inputs(n):
torch.manual_seed(123)
residual = torch.randn(n, 4, 5120, device=device, dtype=torch.bfloat16)
post = torch.rand(n, 4, device=device)
comb = torch.randn(n, 4, 4, device=device) * 0.1
pre = torch.rand(n, 4, device=device)
weight = torch.randn(5120, device=device, dtype=torch.bfloat16)
output = torch.empty_like(residual)
normalized = torch.empty_like(x)
return residual, post, comb, pre, weight
def run(n):
torch.manual_seed(42 + rank)
x = torch.randn(n, 5120, device=device, dtype=torch.bfloat16)
# Packed +0/-0 pairs collide with the Lamport sentinel.
x[:, :16] = 0
x[:, 9:16:2] = -0.0
residual, post, comb, pre, weight = mhc_inputs(n)
def fused():
torch.ops._C_custom_ar.all_reduce_mhc(
x,
return op(x, residual, post, comb, pre, weight, 1e-6)
def check(outputs):
peers = get_tp_group().all_gather(x, dim=0).view(tp_size, n, 5120)
output, normalized = _unfused_all_reduce_mhc(
peers, residual, post, comb, pre, weight, 1e-6
)
# The mixed hc streams match bit for bit. The RMSNorm sums the
# squares in another order and uses an approximate rsqrt.
assert torch.equal(outputs[0], output)
assert _bf16_ulps(outputs[1], normalized) <= 1
check_eager_and_replayed(fused, check, x, residual)
def run_finalize(n):
torch.manual_seed(7 + rank)
# A padded permuted GEMM2 buffer, like the MoE's.
rows = n * 6 + 5
gemm2 = torch.randn(rows, 5120, device=device, dtype=torch.bfloat16)
permuted = torch.randperm(rows, device=device)[: n * 6].view(n, 6).int()
# A route to an expert this rank does not hold.
permuted[0, -1] = -1
weights = torch.rand(n, 6, device=device)
shared = torch.randn(n, 5120, device=device, dtype=torch.bfloat16)
residual, post, comb, pre, weight = mhc_inputs(n)
def fused():
return op.finalize(
gemm2,
weights,
permuted,
shared,
residual,
post,
comb,
pre,
weight,
output,
normalized,
comm.mnnvl_lamport_ag_local_ptr,
comm.mnnvl_lamport_ag_multicast_ptr,
comm.mnnvl_lamport_epochs[0],
rank,
comm.mnnvl_buffer_size,
1e-6,
)
def check():
gathered = comm.custom_all_gather(x)
assert gathered is not None
peers = gathered.view(tp_size, n, 5120).float()
reduced = peers[0].clone()
for peer in peers[1:]:
reduced.add_(peer)
expected = mhc_post_tilelang(
reduced.bfloat16(), residual, post.unsqueeze(-1), comb
)
expected_norm = mhc_pre_delayed_tilelang(
expected,
fn,
scale,
base,
1e-6,
1e-6,
1e-6,
2.0,
20,
pre_mix=pre,
norm_weight=weight,
)[2]
torch.testing.assert_close(output, expected, rtol=0.008, atol=1e-6)
torch.testing.assert_close(
normalized, expected_norm, rtol=0.008, atol=0.008
)
def check(outputs):
# One FP32 FMA per route in route order, the shared add, one
# rounding, then the plain path: only the finalize differs.
acc = torch.zeros(n, 5120, device=device)
for k in range(6):
valid = (permuted[:, k] >= 0).unsqueeze(-1)
rows_k = gemm2[permuted[:, k].clamp_min(0).long()].float()
torch.addcmul(
acc,
torch.where(valid, rows_k, 0.0),
torch.where(valid, weights[:, k : k + 1], 0.0),
out=acc,
)
x = (acc + shared.float()).bfloat16()
expected = op(x, residual, post, comb, pre, weight, 1e-6)
assert torch.equal(outputs[0], expected[0])
assert torch.equal(outputs[1], expected[1])
fused()
check()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
for _ in range(6):
fused()
for _ in range(20):
graph.replay()
check()
x.mul_(0.5)
residual.mul_(2)
graph.replay()
check()
check_eager_and_replayed(fused, check, gemm2, shared)
# Cover fixed Q6 and shrinking/growing adaptive verification batches.
# Changing shapes cover shrinking and growing batches in one mailbox.
for n in (1, 6, 12, 8, 16, 3, 5, 2, 4, 1):
run(n)
run_finalize(n)
@pytest.mark.skipif(
not current_platform.is_device_capability_family(100), reason="Requires SM100"
)
def test_all_reduce_mhc_preserves_bf16_boundaries_and_graph_replay(monkeypatch):
def test_all_reduce_mhc_matches_unfused_path(monkeypatch):
if torch.accelerator.device_count() < 4:
pytest.skip("Requires four GPUs with NVLink multicast")
multi_process_parallel(monkeypatch, 4, 1, _all_reduce_mhc)
@@ -151,9 +198,9 @@ def test_custom_allreduce_filters_dtype(
) -> None:
communicator = car.CustomAllreduce.__new__(car.CustomAllreduce)
communicator.disabled = False
communicator._ptr = 0
communicator.world_size = 2
communicator.max_size = 1024
communicator._ptr = 0
assert communicator.should_custom_ar(torch.empty(16, dtype=dtype)) is expected
@@ -219,6 +266,268 @@ def test_local_multicast_support_rejects_non_cuda(monkeypatch):
assert not car._has_local_multicast_support(torch.device("cuda:0"))
@pytest.mark.parametrize(
("world_size", "device_capability", "local_multicast", "expected"),
[
(2, (10, 0), True, True),
(4, (10, 3), True, True),
(8, (10, 0), True, True),
(8, (10, 3), True, True),
(6, (10, 3), True, False),
(8, (10, 1), True, False),
(8, (9, 0), True, False),
(8, (10, 3), False, False),
],
)
def test_mnnvl_multimem_reduce_scatter_platform_gate(
monkeypatch,
world_size,
device_capability,
local_multicast,
expected,
):
def is_device_capability(capability, device_id):
assert capability in ((10, 0), (10, 3))
assert device_id == 3
return device_capability == capability
monkeypatch.setattr(
car.current_platform,
"is_device_capability",
is_device_capability,
)
monkeypatch.setattr(
car,
"_has_local_multicast_support",
lambda _device: local_multicast,
)
supported = car._supports_mnnvl_multimem_reduce_scatter(
torch.device("cuda:3"), world_size
)
assert supported is expected
@pytest.mark.parametrize(
(
"message_bytes",
"multimem_ptr",
"multimem_initialized",
"batch_invariant",
"expected",
),
[
(16 * 1024 * 1024, 1, True, False, "mnnvl_lamport"),
(16 * 1024 * 1024 + 128, 1, True, False, "mnnvl_multimem"),
(64 * 1024 * 1024, 1, True, False, "mnnvl_multimem"),
(64 * 1024 * 1024 + 128, 1, True, False, None),
(32 * 1024 * 1024, 0, True, False, None),
(32 * 1024 * 1024, 0, False, False, "mnnvl_multimem"),
(8 * 1024 * 1024, 1, True, True, "mnnvl_lamport"),
(32 * 1024 * 1024, 1, True, True, None),
],
)
@pytest.mark.parametrize("world_size", [2, 4, 8])
def test_mnnvl_reduce_scatter_backend_gate(
monkeypatch,
world_size,
message_bytes,
multimem_ptr,
multimem_initialized,
batch_invariant,
expected,
):
monkeypatch.setattr(car.current_platform, "is_cuda", lambda: True)
monkeypatch.setattr(car.envs, "VLLM_BATCH_INVARIANT", batch_invariant)
communicator = car.CustomAllreduce.__new__(car.CustomAllreduce)
communicator.disabled = False
communicator._ptr = 0
communicator.world_size = world_size
communicator.mnnvl_only = False
communicator.fully_connected = True
communicator.mnnvl_multicast_ptr = 1
communicator.mnnvl_multimem_rs_supported = True
communicator.mnnvl_multimem_rs_initialized = multimem_initialized
communicator.mnnvl_multimem_rs_multicast_ptr = multimem_ptr
communicator.max_mnnvl_reduce_scatter_size = 16 * 1024 * 1024
communicator.max_mnnvl_multimem_reduce_scatter_size = 64 * 1024 * 1024
communicator.max_reduce_scatter_size = 16 * 1024 * 1024
inp = torch.empty(
(world_size, message_bytes // torch.bfloat16.itemsize // world_size),
dtype=torch.bfloat16,
)
assert inp.nbytes == message_bytes
assert communicator._select_reduce_scatter_backend(inp) == expected
assert communicator.should_custom_reduce_scatter(inp) is (expected is not None)
assert communicator.should_mnnvl_multimem_reduce_scatter(inp) is (
expected == "mnnvl_multimem"
)
def test_mnnvl_multimem_reduce_scatter_skips_rendezvous_after_peer_alloc_failure(
monkeypatch,
):
events = []
class FakeSymmMem:
@staticmethod
def empty(*_args, **_kwargs):
events.append("empty")
return torch.empty(1, dtype=torch.uint8)
@staticmethod
def rendezvous(*_args, **_kwargs):
events.append("rendezvous")
return None
def report_peer_allocation_failure(group_value, **_kwargs):
events.append("all_reduce")
assert group_value.item() == 1
group_value.zero_()
monkeypatch.setattr(car, "torch_symm_mem", FakeSymmMem)
monkeypatch.setattr(car.ops, "meta_size", lambda: 128)
monkeypatch.setattr(car.dist, "all_reduce", report_peer_allocation_failure)
warnings = []
monkeypatch.setattr(
car.logger,
"warning_once",
lambda message, *_args, **_kwargs: warnings.append(message),
)
communicator = car.CustomAllreduce.__new__(car.CustomAllreduce)
communicator.disabled = True
communicator._ptr = 0
communicator.group = object()
communicator.device = torch.device("cuda:0")
communicator.max_mnnvl_multimem_reduce_scatter_size = 64 * 1024 * 1024
communicator.mnnvl_multimem_rs_supported = True
communicator.mnnvl_multimem_rs_initialized = False
communicator.mnnvl_multimem_rs_buffer = None
communicator.mnnvl_multimem_rs_multicast_ptr = 0
communicator._init_mnnvl_multimem_reduce_scatter_buffer()
assert events == ["empty", "all_reduce"]
assert communicator.mnnvl_multimem_rs_initialized
assert communicator.mnnvl_multimem_rs_buffer is None
assert communicator.mnnvl_multimem_rs_multicast_ptr == 0
assert warnings == [
"MNNVL multimem reduce-scatter symmetric-memory allocation "
"failed on at least one rank; falling back to NCCL."
]
def test_mnnvl_multimem_reduce_scatter_warns_on_rendezvous_failure(monkeypatch):
events = []
class FakeSymmMem:
@staticmethod
def empty(*_args, **_kwargs):
events.append("empty")
return torch.empty(1, dtype=torch.uint8)
@staticmethod
def rendezvous(*_args, **_kwargs):
events.append("rendezvous")
raise RuntimeError("rendezvous failed")
def preserve_local_result(_group_value, **_kwargs):
events.append("all_reduce")
warnings = []
monkeypatch.setattr(car, "torch_symm_mem", FakeSymmMem)
monkeypatch.setattr(car.ops, "meta_size", lambda: 128)
monkeypatch.setattr(car.dist, "all_reduce", preserve_local_result)
monkeypatch.setattr(
car.logger,
"warning_once",
lambda message, *_args, **_kwargs: warnings.append(message),
)
communicator = car.CustomAllreduce.__new__(car.CustomAllreduce)
communicator.disabled = True
communicator._ptr = 0
communicator.group = type("Group", (), {"group_name": "test"})()
communicator.device = torch.device("cuda:0")
communicator.max_mnnvl_multimem_reduce_scatter_size = 64 * 1024 * 1024
communicator.mnnvl_multimem_rs_supported = True
communicator.mnnvl_multimem_rs_initialized = False
communicator.mnnvl_multimem_rs_buffer = None
communicator.mnnvl_multimem_rs_multicast_ptr = 0
communicator._init_mnnvl_multimem_reduce_scatter_buffer()
assert events == ["empty", "all_reduce", "rendezvous", "all_reduce"]
assert communicator.mnnvl_multimem_rs_initialized
assert communicator.mnnvl_multimem_rs_buffer is None
assert communicator.mnnvl_multimem_rs_multicast_ptr == 0
assert warnings == [
"MNNVL multimem reduce-scatter symmetric-memory rendezvous "
"failed on at least one rank; falling back to NCCL."
]
def test_mnnvl_multimem_reduce_scatter_initializes_signals(monkeypatch):
events = []
buffers = []
class FakeHandle:
multicast_ptr = 0x3000
class FakeSymmMem:
@staticmethod
def empty(size, **_kwargs):
events.append(("empty", size))
buffer = torch.ones(size, dtype=torch.uint8)
buffers.append(buffer)
return buffer
@staticmethod
def rendezvous(*_args, **_kwargs):
events.append(("rendezvous", None))
return FakeHandle()
def preserve_local_result(*_args, **_kwargs):
events.append(("all_reduce", None))
monkeypatch.setattr(car, "torch_symm_mem", FakeSymmMem)
monkeypatch.setattr(car.ops, "meta_size", lambda: 128)
monkeypatch.setattr(
car.torch.accelerator,
"synchronize",
lambda: events.append(("synchronize", None)),
)
monkeypatch.setattr(car.dist, "all_reduce", preserve_local_result)
communicator = car.CustomAllreduce.__new__(car.CustomAllreduce)
communicator.disabled = True
communicator._ptr = 0
communicator.group = type("Group", (), {"group_name": "test"})()
communicator.device = torch.device("cpu")
communicator.max_mnnvl_multimem_reduce_scatter_size = 129
communicator.mnnvl_multimem_rs_supported = True
communicator.mnnvl_multimem_rs_initialized = False
communicator.mnnvl_multimem_rs_buffer = None
communicator.mnnvl_multimem_rs_multicast_ptr = 0
communicator._init_mnnvl_multimem_reduce_scatter_buffer()
assert events == [
("empty", 257),
("all_reduce", None),
("rendezvous", None),
("synchronize", None),
("all_reduce", None),
]
assert torch.all(buffers[0][:128] == 0)
assert torch.all(buffers[0][128:] == 1)
assert communicator.mnnvl_multimem_rs_buffer_size == 129
assert communicator.mnnvl_multimem_rs_local_ptr == buffers[0].data_ptr() + 128
assert communicator.mnnvl_multimem_rs_multicast_ptr == 0x3080
@ray.remote(num_gpus=1, max_calls=1)
def graph_allreduce(
monkeypatch: pytest.MonkeyPatch,
@@ -455,13 +455,29 @@ def test_mla_dcp_manager_selects_fallback_backends(monkeypatch):
)
def test_dcp_workspace_covers_parallel_drafting():
@pytest.mark.parametrize(
("parallel_drafting", "use_v2_model_runner", "expected"),
[
# Model runner V1's parallel drafter widens requests to 1 + 2 * 3.
(True, False, 28),
(True, True, 16),
# A diffusion canvas of 3 without a speculative config.
(None, True, 16),
],
)
def test_dcp_workspace_covers_decode_width(
parallel_drafting, use_v2_model_runner, expected
):
config = _manager_config()
config.scheduler_config.max_num_batched_tokens = 128
config.num_speculative_tokens = 3
config.speculative_config = MagicMock(parallel_drafting=True)
config.use_v2_model_runner = use_v2_model_runner
if parallel_drafting is not None:
config.speculative_config = MagicMock(
num_speculative_tokens=3, parallel_drafting=parallel_drafting
)
assert dcp.get_dcp_workspace_max_num_tokens(config) == 28
assert dcp.get_dcp_workspace_max_num_tokens(config) == expected
def test_mla_dcp_manager_selects_pcp_combine(monkeypatch):
@@ -0,0 +1,868 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for the NCCL M2N weight transfer backend.
These cover how a transfer is *described* — layout encoding and the wire-type
validation that keeps a bad plan from reaching a collective, since a mismatch
there is a hang rather than an error. The transfer itself needs the m2n runtime
and multiple GPUs, so it is exercised separately.
"""
import logging
from functools import wraps
from types import MethodType
from unittest.mock import Mock
import pybase64 as base64
import pytest
import ray
import torch
from vllm.distributed.weight_transfer import (
WeightTransferEngineFactory,
WeightTransferTrainerFactory,
)
from vllm.distributed.weight_transfer.m2n_common import (
REPLICATE,
REPLICATED,
M2NMesh,
M2NParamMeta,
check_placements,
check_transferable,
publish_destination_placements,
resolve_layout,
validate_layout,
)
from vllm.distributed.weight_transfer.m2n_engine import (
M2NWeightTransferEngine,
M2NWeightTransferInitInfo,
M2NWeightTransferUpdateInfo,
)
from vllm.distributed.weight_transfer.m2n_layout import (
M2NDestination,
resolve_parameter_destinations,
)
from vllm.distributed.weight_transfer.m2n_source import (
mesh_from_tensor,
placements_from_tensor,
)
from vllm.distributed.weight_transfer.m2n_trainer import M2NTrainerInitInfo
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
RowParallelLinear,
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.platforms import current_platform
VALID_UID_B64 = base64.b64encode(b"\x00" * 128).decode()
class TestLayout:
def test_replicated_splits_nothing(self):
"""A replicated tensor imposes no divisibility constraint. The shape
dims are deliberately coprime with the mesh size: a layout that actually
split the tensor would reject them."""
mesh = M2NMesh((2, 2), start_rank=1)
indivisible_shape = (7, 13) # neither dim divisible by any mesh axis
resolved_mesh, placements = resolve_layout(mesh, REPLICATED)
validate_layout(resolved_mesh, placements, indivisible_shape, "destination")
def test_replicated_keeps_the_same_ranks(self):
"""Replication re-factors the mesh to get a size-1 axis for its no-op
shard. That is only sound if it still covers exactly the same GPUs."""
mesh = M2NMesh((2, 3), start_rank=4)
resolved_mesh, _ = resolve_layout(mesh, REPLICATED)
assert resolved_mesh.size == mesh.size
assert resolved_mesh.start_rank == mesh.start_rank
def test_sharded_keeps_its_own_factorization(self):
"""Rank order decides who owns which shard, so a sharded tensor must
not be re-factored the way a replicated one is."""
mesh = M2NMesh((2, 3), start_rank=4)
resolved_mesh, placements = resolve_layout(mesh, (REPLICATE, 0))
assert resolved_mesh == mesh
assert placements == (REPLICATE, 0)
def test_two_shard_axes_rejected(self):
"""One axis has to replicate; a 2-D mesh that shards both is not
something a single reshard can express."""
with pytest.raises(ValueError, match="shards both"):
check_placements((0, 1))
def test_placement_below_replicate_rejected(self):
with pytest.raises(ValueError, match=r"parameter 'w'.*-2"):
check_placements((-2, REPLICATE), "parameter 'w' source placements")
def test_shard_dim_must_exist(self):
with pytest.raises(ValueError, match="rank 2"):
validate_layout(M2NMesh((1, 2), 0), (REPLICATE, 2), (8, 16), "source")
def test_shard_must_divide_evenly(self):
with pytest.raises(ValueError, match="does not divide evenly"):
validate_layout(M2NMesh((1, 3), 0), (REPLICATE, 0), (8, 16), "source")
class TestSourceLayout:
def test_plain_tensor_is_replicated_across_trainer_ranks(self):
"""A tensor with no DTensor metadata is the same on every trainer rank,
so the source describes it as replicated over all of them."""
assert placements_from_tensor(torch.zeros(4)) is REPLICATED
assert mesh_from_tensor(torch.zeros(4), 4) == M2NMesh((4, 1), 0)
class TestTransferable:
def test_unsupported_dtype_names_the_parameter(self):
with pytest.raises(ValueError, match="'w'"):
check_transferable("w", torch.complex64, (4,))
def test_rank_four_rejected(self):
with pytest.raises(ValueError, match="rank 4"):
check_transferable("w", torch.bfloat16, (2, 2, 2, 2))
class TestWireTypes:
def _init_info(self, **overrides):
fields = dict(
master_address="127.0.0.1",
master_port=1234,
rank_offset=1,
world_size=3,
src_mesh_dims=[1, 1],
dst_mesh_dims=[2, 1],
names=["w"],
dtype_names=["bfloat16"],
shapes=[[16, 16]],
src_placements=[None],
)
fields.update(overrides)
return M2NWeightTransferInitInfo(**fields)
def test_accepts_a_consistent_plan(self):
assert self._init_info().names == ["w"]
def test_accepts_pre_shared_nccl_unique_id(self):
info = self._init_info(
master_address=None,
master_port=None,
nccl_unique_id_b64=VALID_UID_B64,
)
assert info.nccl_unique_id_bytes == b"\x00" * 128
assert VALID_UID_B64 not in repr(info)
def test_destination_plan_uses_uid_communicator_without_group(self):
comm = Mock(rank=0, device=torch.device("cpu"), group=None)
def receive_plan(tensor, src):
assert src == 1
tensor.copy_(torch.tensor([[-1, 0], [-2, -2]], dtype=torch.int8))
comm.broadcast.side_effect = receive_plan
placements = publish_destination_placements(comm, 1, None, 2)
assert placements == [(REPLICATE, 0), REPLICATED]
def test_rejects_both_rendezvous_modes(self):
with pytest.raises(ValueError, match="not both"):
self._init_info(nccl_unique_id_b64=VALID_UID_B64)
def test_trainer_accepts_pre_shared_nccl_unique_id(self):
info = M2NTrainerInitInfo(
nccl_unique_id_b64=VALID_UID_B64,
world_size=3,
num_trainer_ranks=1,
rank=0,
)
assert info.nccl_unique_id_bytes == b"\x00" * 128
assert VALID_UID_B64 not in repr(info)
def test_ragged_plan_rejected(self):
with pytest.raises(ValueError, match="`shapes`"):
self._init_info(shapes=[])
def test_destination_mesh_must_cover_the_workers(self):
"""The trainer declares the inference mesh, so one that does not cover
the workers is a config error — and it has to fail the init RPC, since
a mismatched mesh would otherwise surface as a hung collective."""
with pytest.raises(ValueError, match="dst_mesh_dims"):
self._init_info(dst_mesh_dims=[3, 1]) # 3 != the 2 workers
def test_world_must_hold_a_trainer_and_a_worker(self):
with pytest.raises(ValueError, match="rank_offset"):
self._init_info(rank_offset=3, world_size=3)
@pytest.mark.parametrize("dtype_name", ["not_a_dtype", "Tensor"])
def test_invalid_dtype_name_names_parameter(self, monkeypatch, dtype_name):
monkeypatch.setattr(
"vllm.distributed.weight_transfer.m2n_engine.import_m2n",
lambda: object(),
)
engine = object.__new__(M2NWeightTransferEngine)
with pytest.raises(ValueError, match=r"parameter 'w'.*dtype"):
engine.init_transfer_engine(self._init_info(dtype_names=[dtype_name]))
def _init_32_to_4_plan(self, monkeypatch, destination):
m2n = Mock()
m2n.Handle.create.return_value = object()
monkeypatch.setattr(
"vllm.distributed.weight_transfer.m2n_engine.import_m2n", lambda: m2n
)
monkeypatch.setattr(
"vllm.distributed.weight_transfer.m2n_engine."
"resolve_parameter_destinations",
lambda *args, **kwargs: [destination],
)
monkeypatch.setattr(
"vllm.distributed.weight_transfer.m2n_engine.worker_init_process_group",
lambda *args, **kwargs: object(),
)
monkeypatch.setattr(
"vllm.distributed.weight_transfer.m2n_engine."
"publish_destination_placements",
lambda *args: args[2],
)
engine = object.__new__(M2NWeightTransferEngine)
engine.parallel_config = Mock(pipeline_parallel_size=1)
engine.model_config = Mock(quantization=None)
engine.model = torch.nn.Module()
engine.init_transfer_engine(
self._init_info(
rank_offset=32,
world_size=36,
src_mesh_dims=[1, 32],
dst_mesh_dims=[1, 4],
shapes=[[32, 8]],
src_placements=[[REPLICATE, 0]],
)
)
def test_limits_use_resolved_sharded_destination(self, monkeypatch):
destination = M2NDestination("w", (REPLICATE, 0), torch.empty(8, 8))
self._init_32_to_4_plan(monkeypatch, destination)
def test_limits_still_reject_replicated_destination(self, monkeypatch):
destination = M2NDestination("w", REPLICATED, None)
with pytest.raises(ValueError, match=r"32 source shards.*MAX_SOURCES=16"):
self._init_32_to_4_plan(monkeypatch, destination)
def test_update_preflights_all_names_before_reshard(self):
engine = object.__new__(M2NWeightTransferEngine)
engine._handle = object()
engine.model_update_group = object()
engine._index = {"valid": 0}
engine._metas = [M2NParamMeta("valid", torch.float32, (4,), REPLICATED)]
engine._reshard = Mock()
with pytest.raises(ValueError, match=r"parameter 'unknown'"):
engine.receive_weights(
M2NWeightTransferUpdateInfo(names=["valid", "unknown"])
)
engine._reshard.assert_not_called()
def test_fallback_tensors_share_one_load_weights_invocation(self, monkeypatch):
class CoupledModel:
def __init__(self):
self.calls = 0
self.loaded = []
def load_weights(self, weights):
self.calls += 1
received = list(weights)
if [name for name, _ in received] == ["pair.weight", "pair.scale"]:
self.loaded = [(name, tensor.clone()) for name, tensor in received]
model = CoupledModel()
direct = torch.zeros(1)
engine = object.__new__(M2NWeightTransferEngine)
engine._handle = object()
engine.model_update_group = object()
engine.device = torch.device("cpu")
engine.model = model
engine._index = {"pair.weight": 0, "direct": 1, "pair.scale": 2}
engine._metas = [
M2NParamMeta(name, torch.float32, (1,), REPLICATED)
for name in engine._index
]
engine._parameter_destinations = [
M2NDestination("pair.weight", REPLICATED, None),
M2NDestination("direct", REPLICATED, direct),
M2NDestination("pair.scale", REPLICATED, None),
]
reshard_order = []
def reshard(comm, stream, meta, placements, buffer):
reshard_order.append(meta.name)
buffer.fill_(len(reshard_order))
engine._reshard = reshard
stream = Mock()
monkeypatch.setattr(
"vllm.distributed.weight_transfer.m2n_engine.comm_ptr", lambda group: 0
)
monkeypatch.setattr(torch.cuda, "current_stream", lambda: stream)
engine.receive_weights(
M2NWeightTransferUpdateInfo(names=["pair.weight", "direct", "pair.scale"])
)
assert model.calls == 1
assert [name for name, _ in model.loaded] == ["pair.weight", "pair.scale"]
assert [tensor.item() for _, tensor in model.loaded] == [1, 3]
assert direct.item() == 2
assert reshard_order == ["pair.weight", "direct", "pair.scale"]
assert stream.synchronize.call_count == 2
def test_trainer_rank_must_be_a_trainer_rank(self):
"""A trainer rank must fall within the trainer portion of the group."""
with pytest.raises(ValueError, match="num_trainer_ranks"):
M2NTrainerInitInfo(
master_address="127.0.0.1",
master_port=1234,
world_size=4,
num_trainer_ranks=2,
rank=2,
)
def test_trainer_destination_mesh_must_cover_the_workers(self):
"""The destination mesh must include every inference worker."""
with pytest.raises(ValueError, match="dst_mesh_dims"):
M2NTrainerInitInfo(
master_address="127.0.0.1",
master_port=1234,
world_size=6,
num_trainer_ranks=2,
dst_mesh_dims=(3, 1), # 3 != the 4 inference workers
rank=0,
)
def test_destination_mesh_defaults_to_flat(self):
"""A replicated destination does not care how the mesh is factored, so
callers that do not shard it need not supply one."""
info = M2NTrainerInitInfo(
master_address="127.0.0.1",
master_port=1234,
world_size=6,
num_trainer_ranks=2,
rank=0,
)
assert info.destination_mesh_dims == (4, 1)
def test_sender_is_trainer_rank_zero(self):
"""Trainer rank 0 drives the inference control plane."""
info = M2NTrainerInitInfo(
master_address="127.0.0.1", master_port=1234, world_size=4, rank=0
)
assert info.is_sender
class TestRegistration:
def test_both_registries_expose_the_backend(self):
"""Both worker and trainer factories register nccl_m2n."""
assert "nccl_m2n" in WeightTransferEngineFactory._registry
assert "nccl_m2n" in WeightTransferTrainerFactory._registry
def test_init_info_dispatches_to_the_backend(self):
"""Trainer init info selects the nccl_m2n factory entry."""
assert M2NTrainerInitInfo.backend == "nccl_m2n"
# ---------------------------------------------------------------------------
# End-to-end transfer
#
# Transport-only, in the style of the NCCL/sparse tests in
# test_weight_transfer.py: two Ray tasks with one GPU each drive the two engines
# directly, so no HTTP server or LLM instance is involved. The worker is not an
# RPC endpoint here, so the trainer engine gets a no-op control-plane client --
# the NCCL rendezvous and the reshard itself are the real thing.
# ---------------------------------------------------------------------------
SHAPE = [64, 32]
DTYPE = "float32"
def _init_ray() -> None:
if ray.is_initialized():
return
ray.init(
ignore_reinit_error=True,
runtime_env={
"env_vars": {
"RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES": "1",
"RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES": "1",
"RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES": "1",
}
},
)
def _assigned_device() -> "torch.device":
gpu_ids = ray.get_gpu_ids()
device = torch.device(f"cuda:{int(gpu_ids[0])}" if gpu_ids else "cuda:0")
current_platform.set_device(device)
return device
@ray.remote(num_gpus=1)
def _m2n_trainer_send(nccl_unique_id_b64: str, world_size: int) -> bool:
"""Send one parameter through the real trainer engine."""
device = _assigned_device()
from vllm.distributed.weight_transfer import WeightTransferTrainerFactory
from vllm.distributed.weight_transfer.m2n_source import DTensorModuleSource
from vllm.distributed.weight_transfer.m2n_trainer import M2NTrainerInitInfo
class NoopClient:
def init_weight_transfer_engine(self, init_info):
pass
def start_weight_update(self):
pass
def update_weights(self, update_info):
pass
def finish_weight_update(self, weight_version=None):
pass
class Tiny(torch.nn.Module):
def __init__(self):
super().__init__()
self.weight = torch.nn.Parameter(
torch.arange(
SHAPE[0] * SHAPE[1], dtype=torch.float32, device=device
).reshape(SHAPE)
)
engine = WeightTransferTrainerFactory.trainer_init(
init_info=M2NTrainerInitInfo(
nccl_unique_id_b64=nccl_unique_id_b64,
world_size=world_size,
num_trainer_ranks=1,
dst_mesh_dims=(1, world_size - 1),
rank=0,
),
client=NoopClient(),
source=DTensorModuleSource(Tiny(), num_trainer_ranks=1),
)
engine.send_weights()
torch.accelerator.synchronize()
engine.shutdown()
return True
@ray.remote(num_gpus=1)
def _m2n_worker_receive(
nccl_unique_id_b64: str,
world_size: int,
worker_rank: int = 0,
) -> dict:
"""Receive that parameter through the real worker engine."""
import contextlib
from unittest.mock import MagicMock
device = _assigned_device()
from vllm.config.parallel import ParallelConfig
from vllm.config.weight_transfer import WeightTransferConfig
from vllm.distributed.weight_transfer.m2n_engine import (
M2NWeightTransferEngine,
M2NWeightTransferInitInfo,
M2NWeightTransferUpdateInfo,
)
class Recorder(torch.nn.Module):
def __init__(self):
super().__init__()
self.received = []
if world_size > 2:
self.weight = torch.nn.Parameter(
torch.zeros(
SHAPE[0] // (world_size - 1),
SHAPE[1],
dtype=torch.float32,
device=device,
)
)
self.weight.output_dim = 0
self.weight.weight_loader = MethodType(
ColumnParallelLinear.weight_loader,
Mock(tp_size=world_size - 1),
)
def load_weights(self, weights):
for name, tensor in weights:
self.received.append((name, tensor.clone()))
parallel_config = MagicMock(spec=ParallelConfig)
parallel_config.rank = worker_rank
parallel_config.world_size = world_size - 1
parallel_config.data_parallel_rank = 0
parallel_config.data_parallel_index = 0
parallel_config.tensor_parallel_size = world_size - 1
parallel_config.pipeline_parallel_size = 1
vllm_config = MagicMock()
vllm_config.parallel_config = parallel_config
vllm_config.model_config = MagicMock()
vllm_config.model_config.quantization = None
recorder = Recorder()
engine = M2NWeightTransferEngine(
WeightTransferConfig(backend="nccl_m2n"), vllm_config, device, recorder
)
# Transport-only: receive_weights enters set_current_vllm_config, and
# vllm_config here is a mock.
import vllm.config as _vllm_config_mod
_vllm_config_mod.set_current_vllm_config = lambda cfg: contextlib.nullcontext()
engine.init_transfer_engine(
M2NWeightTransferInitInfo(
nccl_unique_id_b64=nccl_unique_id_b64,
rank_offset=1, # trainer occupies rank 0
world_size=world_size,
src_mesh_dims=[1, 1],
dst_mesh_dims=[1, world_size - 1],
names=["weight"],
dtype_names=[DTYPE],
shapes=[SHAPE],
src_placements=[None], # replicated on the single trainer rank
)
)
engine.receive_weights(M2NWeightTransferUpdateInfo(names=["weight"]))
torch.accelerator.synchronize()
full = torch.arange(
SHAPE[0] * SHAPE[1], dtype=torch.float32, device=device
).reshape(SHAPE)
direct = world_size > 2
name: str | None
got: torch.Tensor | None
if direct:
name, got = "weight", recorder.weight
expected = full.chunk(world_size - 1, dim=0)[worker_rank]
else:
name, got = recorder.received[0] if recorder.received else (None, None)
expected = full
result = {
"count": len(recorder.received),
"name": name,
"shape": list(got.shape) if got is not None else None,
"exact": bool(torch.equal(got, expected)) if got is not None else False,
"direct": direct,
}
engine.shutdown()
return result
@pytest.mark.skipif(
torch.accelerator.device_count() < 2,
reason="Need at least 2 GPUs: one trainer rank and one inference worker.",
)
def test_m2n_weight_transfer_between_processes():
"""A parameter survives a real reshard from a trainer process to a worker.
This is the only test here that moves bytes: it builds both engines, joins
one NCCL communicator across two processes, and reshards. Everything else
in this file checks how a transfer is *described*.
"""
pytest.importorskip("nccl.m2n", reason="nccl_m2n backend needs the m2n runtime")
_init_ray()
from vllm.distributed.device_communicators.pynccl_wrapper import NCCLLibrary
nccl = NCCLLibrary()
nccl_unique_id_b64 = base64.b64encode(
bytes(nccl.ncclGetUniqueId().internal)
).decode()
world_size = 2 # 1 trainer + 1 inference worker
worker = _m2n_worker_receive.remote(nccl_unique_id_b64, world_size)
trainer = _m2n_trainer_send.remote(nccl_unique_id_b64, world_size)
trainer_ok, result = ray.get([trainer, worker])
assert trainer_ok, "trainer engine did not complete"
assert result["count"] == 1, f"expected one parameter, got {result['count']}"
assert result["name"] == "weight"
assert result["shape"] == SHAPE
assert result["exact"], "resharded tensor does not match what the trainer sent"
@pytest.mark.skipif(
torch.accelerator.device_count() < 3,
reason="Need at least 3 GPUs: one trainer rank and two inference workers.",
)
def test_m2n_weight_transfer_to_tp2_shards():
"""Two inference workers receive their own TP shard in live model storage."""
pytest.importorskip("nccl.m2n", reason="nccl_m2n backend needs the m2n runtime")
_init_ray()
from vllm.distributed.device_communicators.pynccl_wrapper import NCCLLibrary
nccl = NCCLLibrary()
nccl_unique_id_b64 = base64.b64encode(
bytes(nccl.ncclGetUniqueId().internal)
).decode()
world_size = 3
workers = [
_m2n_worker_receive.remote(nccl_unique_id_b64, world_size, rank)
for rank in range(2)
]
trainer = _m2n_trainer_send.remote(nccl_unique_id_b64, world_size)
trainer_ok, *results = ray.get([trainer, *workers])
assert trainer_ok, "trainer engine did not complete"
for rank, result in enumerate(results):
assert result["count"] == 0, f"worker {rank} unexpectedly called load_weights"
assert result["name"] == "weight"
assert result["shape"] == [SHAPE[0] // 2, SHAPE[1]]
assert result["direct"]
assert result["exact"], f"worker {rank} received the wrong shard"
class _Model(torch.nn.Module):
"""Stand-in for a TP=2 shard of a tiny model.
`column` is sharded on dim 0 and `row` on dim 1 (the two shapes a TP linear
layer produces), `norm` is replicated, and `fused` has no checkpoint-name
counterpart — the shape a fused parameter presents to the resolver.
"""
def __init__(self) -> None:
super().__init__()
self.column = torch.nn.Parameter(torch.zeros(8, 16))
self.column.output_dim = 0
self.column.weight_loader = MethodType(
ColumnParallelLinear.weight_loader, Mock(tp_size=2)
)
self.row = torch.nn.Parameter(torch.zeros(16, 8))
self.row.input_dim = 1
self.row.weight_loader = MethodType(
RowParallelLinear.weight_loader, Mock(tp_size=2)
)
self.norm = torch.nn.Parameter(torch.zeros(16))
self.norm.weight_loader = default_weight_loader
self.fused = torch.nn.Parameter(torch.zeros(24, 16))
class _MixedModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.proj = torch.nn.Module()
self.proj.weight = torch.nn.Parameter(torch.zeros(16, 8))
self.proj.weight.input_dim = 1
self.proj.weight.weight_loader = MethodType(
RowParallelLinear.weight_loader, Mock(tp_size=2)
)
self.proj.bias = torch.nn.Parameter(torch.zeros(16))
def _resolve(names, dtypes, shapes, **kwargs):
defaults = dict(num_workers=2, shard_axis_size=2, allow_direct=True)
defaults.update(kwargs)
return resolve_parameter_destinations(_Model(), names, dtypes, shapes, **defaults)
class TestDestinationResolution:
@pytest.mark.parametrize(
"name,expected_dim",
[("column", 0), ("row", 1)],
)
def test_sharded_parameter_resolves_to_its_tp_dim(self, name, expected_dim):
[destination] = _resolve([name], [torch.float32], [(16, 16)])
assert destination.direct
assert destination.placements == (REPLICATE, expected_dim)
def test_replicated_parameter_needs_no_placement(self):
"""A parameter every rank holds in full is REPLICATED, so it works
whatever way the inference mesh happens to be factored."""
[destination] = _resolve(["norm"], [torch.float32], [(16,)])
assert destination.direct
assert destination.placements is REPLICATED
def test_direct_destination_is_the_live_parameter(self):
model = _Model()
[destination] = resolve_parameter_destinations(
model,
["column"],
[torch.float32],
[(16, 16)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert destination.tensor.data_ptr() == model.column.data_ptr()
def test_known_transforming_model_submodule_falls_back(self):
class GPT2Model(_Model):
pass
GPT2Model.__module__ = "vllm.model_executor.models.gpt2"
model = torch.nn.Module()
model.transforming = GPT2Model()
[destination] = resolve_parameter_destinations(
model,
["transforming.row"],
[torch.float32],
[(16, 16)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
assert destination.placements is REPLICATED
def test_unknown_name_falls_back(self):
"""Fused parameters reach the worker under checkpoint names that do not
exist in the model; those must take the full-tensor path."""
[destination] = _resolve(["mlp.gate_proj.weight"], [torch.float32], [(16, 16)])
assert not destination.direct
assert destination.placements is REPLICATED
def test_fallback_parameter_demotes_direct_sibling_in_same_module(self):
"""Layerwise finalization must not overwrite a directly loaded weight
when a sibling bias takes the fallback path."""
destinations = resolve_parameter_destinations(
_MixedModel(),
["proj.weight", "proj.bias"],
[torch.float32, torch.float32],
[(16, 16), (16,)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not any(destination.direct for destination in destinations)
def test_unknown_loader_falls_back_despite_matching_name_and_shape(self):
model = _Model()
model.norm.weight_loader = lambda param, weight: param.data.copy_(weight)
[destination] = resolve_parameter_destinations(
model,
["norm"],
[torch.float32],
[(16,)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
def test_missing_loader_is_not_assumed_to_be_a_plain_copy(self):
model = _Model()
del model.norm.weight_loader
[destination] = resolve_parameter_destinations(
model,
["norm"],
[torch.float32],
[(16,)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
def test_wrapped_known_loader_falls_back(self):
model = _Model()
@wraps(default_weight_loader)
def wrapped_loader(param, weight):
default_weight_loader(param, weight)
model.norm.weight_loader = wrapped_loader
[destination] = resolve_parameter_destinations(
model,
["norm"],
[torch.float32],
[(16,)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
def test_replicated_loader_with_transform_metadata_falls_back(self):
model = _Model()
model.norm.is_transposed = True
[destination] = resolve_parameter_destinations(
model,
["norm"],
[torch.float32],
[(16,)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
def test_packed_dim_zero_falls_back(self):
model = _Model()
model.column.packed_dim = 0
[destination] = resolve_parameter_destinations(
model,
["column"],
[torch.float32],
[(16, 16)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
def test_loader_declared_dim_wins_over_shape_guessing(self):
model = _Model()
model.column.output_dim = 1
[destination] = resolve_parameter_destinations(
model,
["column"],
[torch.float32],
[(16, 16)],
num_workers=2,
shard_axis_size=2,
allow_direct=True,
)
assert not destination.direct
def test_shape_the_tp_factor_cannot_explain_falls_back(self):
[destination] = _resolve(["fused"], [torch.float32], [(16, 16)])
assert not destination.direct
def test_dtype_mismatch_falls_back(self):
"""A parameter stored in a different dtype than the wire dtype means a
quantized or otherwise transformed layout — never write into it."""
[destination] = _resolve(["column"], [torch.bfloat16], [(16, 16)])
assert not destination.direct
def test_allow_direct_false_forces_every_parameter_to_fall_back(self):
destinations = _resolve(
["column", "norm"],
[torch.float32] * 2,
[(16, 16), (16,)],
allow_direct=False,
)
assert not any(d.direct for d in destinations)
def test_plan_reports_byte_coverage(self, caplog_vllm):
"""A small direct parameter must not hide a large fallback tensor."""
with caplog_vllm.at_level(
logging.INFO,
logger="vllm.distributed.weight_transfer.m2n_layout",
):
_resolve(
["norm", "missing_fused_weight"],
[torch.float32, torch.bfloat16],
[(16,), (1024, 1024)],
)
assert (
"1/2 parameters resharded directly into the model, 1 via "
"full-tensor fallback; direct byte coverage: 64/2097216 bytes "
"(0.0%)" in caplog_vllm.text
)
+12
View File
@@ -480,6 +480,18 @@ def test_compilation_config():
)
def test_trust_request_mm_kwargs_cli():
from vllm.entrypoints.launchers.cli_args import FrontendArgs
parser = FrontendArgs.add_cli_args(FlexibleArgumentParser())
args = parser.parse_args([])
assert not args.trust_request_mm_kwargs
args = parser.parse_args(["--trust-request-mm-kwargs"])
assert args.trust_request_mm_kwargs
def test_attention_config():
from vllm.v1.attention.backends.registry import AttentionBackendEnum
@@ -15,8 +15,9 @@ Also covers cache usage computation in ``_build_anthropic_usage``.
import json
from argparse import Namespace
from http import HTTPStatus
from types import SimpleNamespace
from typing import Annotated
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi import FastAPI
@@ -1382,6 +1383,11 @@ Q35_TEMPLATE = (
"{%- endfor %}"
)
PERMISSIVE_TEMPLATE = (
"{%- for message in messages %}{{- message.role }}: {{ message.content }}\n"
"{%- endfor %}"
)
class TestDetectMergeInlineSystem:
"""Verify _detect_merge_inline_system auto-detection.
@@ -1401,11 +1407,7 @@ class TestDetectMergeInlineSystem:
def test_no_restriction_no_merge(self):
"""Template without restriction accepts mid-conversation system."""
assert (
AnthropicServingMessages._detect_merge_inline_system(
"{%- for message in messages %}"
"{{- message.role }}: {{ message.content }}\n"
"{%- endfor %}"
)
AnthropicServingMessages._detect_merge_inline_system(PERMISSIVE_TEMPLATE)
is False
)
@@ -1413,6 +1415,38 @@ class TestDetectMergeInlineSystem:
"""No chat_template → conservative default: merge."""
assert AnthropicServingMessages._detect_merge_inline_system(None) is True
@pytest.mark.parametrize(
("resolved", "expected"),
[(PERMISSIVE_TEMPLATE, False), (Q35_TEMPLATE, True)],
)
def test_probes_resolved_template_without_cli_override(
self, monkeypatch, resolved, expected
):
"""Without --chat-template, probe the tokenizer's template (#58727).
Merging defeats prefix caching, so it is warned about at startup.
"""
import vllm.entrypoints.anthropic.serving as serving_mod
from vllm.renderers.hf import HfRenderer
monkeypatch.setattr(
serving_mod, "resolve_chat_template", lambda *a, **kw: resolved
)
mock_logger = MagicMock()
monkeypatch.setattr(serving_mod, "logger", mock_logger)
renderer = MagicMock(spec=HfRenderer)
renderer.tokenizer = MagicMock()
online_renderer = SimpleNamespace(
renderer=renderer,
chat_template=None,
model_config=None,
)
assert (
AnthropicServingMessages._should_merge_inline_system(online_renderer)
is expected
)
assert mock_logger.warning.called is expected
# ======================================================================
# Full (non-streaming) response conversion: messages_full_converter
@@ -1727,3 +1761,197 @@ class TestClientErrorResponses:
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json()["error"]["type"] == "BadRequestError"
# ======================================================================
# thinking configuration pass-through
# ======================================================================
class TestThinkingConfig:
def test_absent_thinking_leaves_reasoning_untouched(self):
"""Requests without `thinking` must convert exactly as before."""
request = _make_request([{"role": "user", "content": "Hello"}])
result = _convert(request)
assert result.reasoning_effort is None
assert result.thinking_token_budget is None
assert result.include_reasoning is True
def test_disabled_clears_reasoning_effort(self):
"""`disabled` maps to reasoning_effort="none", which is what clears
enable_thinking for templates that honor it."""
request = _make_request(
[{"role": "user", "content": "Hello"}],
thinking={"type": "disabled"},
)
result = _convert(request)
assert result.reasoning_effort == "none"
def test_disabled_overrides_output_config_effort(self):
"""`thinking` is applied after output_config so an explicit opt-out wins
over an inherited effort ceiling."""
request = _make_request(
[{"role": "user", "content": "Hello"}],
output_config={"effort": "high"},
thinking={"type": "disabled"},
)
result = _convert(request)
assert result.reasoning_effort == "none"
def test_enabled_sets_thinking_token_budget(self):
request = AnthropicMessagesRequest(
model="test-model",
max_tokens=4096,
messages=[{"role": "user", "content": "Hello"}],
thinking={"type": "enabled", "budget_tokens": 2048},
)
result = _convert(request)
assert result.thinking_token_budget == 2048
assert result.reasoning_effort is None
@pytest.mark.parametrize(
"thinking",
[
pytest.param({"budget_tokens": 2048}, id="missing-type"),
pytest.param({"type": "enabled"}, id="enabled-missing-budget"),
pytest.param(
{"type": "enabled", "budget_tokens": 1023}, id="budget-below-1024"
),
pytest.param(
{"type": "enabled", "budget_tokens": 4096}, id="budget-not-below-max"
),
pytest.param({"type": "adaptive", "display": "full"}, id="bad-display"),
],
)
def test_rejects_invalid_thinking(self, thinking):
"""Mirror the Anthropic API's BetaThinkingConfigParam constraints."""
with pytest.raises(ValidationError):
AnthropicMessagesRequest(
model="test-model",
max_tokens=4096,
messages=[{"role": "user", "content": "Hello"}],
thinking=thinking,
)
def test_pd_prefill_leg_skips_budget_check(self):
"""P/D sidecars resend the request to the prefill node with
max_tokens=1; the budget is enforced on the decode leg instead."""
thinking = {"type": "enabled", "budget_tokens": 1024}
request = AnthropicMessagesRequest(
model="test-model",
max_tokens=1,
messages=[{"role": "user", "content": "Hello"}],
thinking=thinking,
kv_transfer_params={"do_remote_decode": True},
)
assert _convert(request).thinking_token_budget == 1024
with pytest.raises(ValidationError):
AnthropicMessagesRequest(
model="test-model",
max_tokens=1,
messages=[{"role": "user", "content": "Hello"}],
thinking=thinking,
kv_transfer_params={"do_remote_decode": False},
)
def test_adaptive_pins_nothing_and_keeps_effort_ceiling(self):
"""`adaptive` lets the model choose depth, so only the ceiling from
output_config.effort should survive."""
request = _make_request(
[{"role": "user", "content": "Hello"}],
output_config={"effort": "low"},
thinking={"type": "adaptive"},
)
result = _convert(request)
assert result.reasoning_effort == "low"
assert result.thinking_token_budget is None
def test_disabled_uses_configured_effort(self):
"""Models that always think (GLM-5.3) or reject "none" (Harmony) are
served with a low effort instead."""
request = _make_request(
[{"role": "user", "content": "Hello"}],
thinking={"type": "disabled"},
)
result = _convert(request, disabled_thinking_effort="low")
assert result.reasoning_effort == "low"
@pytest.mark.parametrize("display", ["omitted", "summarized", "updates"])
def test_display_keeps_reasoning_included(self, display):
"""Suppressing reasoning would mark it ended for structured outputs and
drop it from multi-turn history, so `display` is ignored."""
request = _make_request(
[{"role": "user", "content": "Hello"}],
thinking={"type": "adaptive", "display": display},
)
result = _convert(request)
assert result.include_reasoning is True
def test_claude_code_payload(self):
"""The combination Claude Code sends on every request: an effort ceiling
plus adaptive thinking with reasoning display omitted."""
request = _make_request(
[{"role": "user", "content": "Hello"}],
output_config={"effort": "high"},
thinking={"type": "adaptive", "display": "omitted"},
)
result = _convert(request)
assert result.reasoning_effort == "high"
assert result.include_reasoning is True
assert result.thinking_token_budget is None
class TestProbeDisabledThinkingEffort:
"""``auto`` falls back to ``low`` when ``none`` cannot turn thinking off."""
@staticmethod
async def _probe(render):
obj = MagicMock(spec=AnthropicServingMessages)
obj.online_renderer = MagicMock()
obj.online_renderer.render_chat = AsyncMock(
side_effect=lambda req: ([], [render(req.reasoning_effort)])
)
obj._extract_prompt_components = lambda engine_input: SimpleNamespace(
token_ids=engine_input, text=None
)
obj._render_probe_prompt = (
AnthropicServingMessages._render_probe_prompt.__get__(obj)
)
return await AnthropicServingMessages._probe_disabled_thinking_effort(obj)
@staticmethod
def _reject_none(effort):
"""Harmony (gpt-oss) raises on ``none``."""
if effort == "none":
raise ValueError(f"unsupported {effort=}")
return [1]
@staticmethod
def _none_as_max(effort):
"""GLM-5.3 treats efforts other than low/high as max."""
return [1, {"low": 0, "high": 1}.get(effort, 2)]
@pytest.mark.asyncio
async def test_template_honors_none(self):
assert await self._probe(lambda effort: [1, int(effort == "none")]) == "none"
@pytest.mark.asyncio
async def test_template_ignores_effort(self):
assert await self._probe(lambda effort: [1]) == "low"
@pytest.mark.asyncio
async def test_template_renders_none_as_thinking_effort(self):
assert await self._probe(self._none_as_max) == "low"
@pytest.mark.asyncio
async def test_renderer_rejects_none(self):
assert await self._probe(self._reject_none) == "low"
@@ -19,6 +19,7 @@ from vllm.entrypoints.anthropic.protocol import (
AnthropicMessagesResponse,
AnthropicOutputConfig,
AnthropicStreamEvent,
AnthropicThinkingConfig,
AnthropicUsage,
)
@@ -35,6 +36,7 @@ SERVING_PROTOCOL_EXPORTS = (
AnthropicMessagesResponse,
AnthropicOutputConfig,
AnthropicStreamEvent,
AnthropicThinkingConfig,
AnthropicUsage,
)
@@ -8,6 +8,7 @@ import pytest
import vllm.entrypoints.launchers.cli_args as cli_args_module
from tests.utils import VLLM_PATH
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.entrypoints.launchers.cli_args import (
make_arg_parser,
validate_parsed_serve_args,
@@ -69,6 +70,24 @@ def test_config_arg_parsing(serve_parser, cli_config_file):
assert args.port == 9000
def test_logging_config_cli_args(serve_parser):
with pytest.warns(UserWarning, match="--log-config-file is deprecated"):
args = serve_parser.parse_args(
[
"--logging-config",
'{"log_level":"WARNING","pylogging_config_file":"/tmp/json.json"}',
"--log-level",
"DEBUG",
"--log-config-file",
"/tmp/flat.json",
]
)
config = AsyncEngineArgs.from_cli_args(args).create_logging_config()
assert config.log_level == "DEBUG"
assert config.pylogging_config_file == "/tmp/flat.json"
### Tests for LoRA module parsing
def test_valid_key_value_format(serve_parser):
# Test old format: name=path
@@ -455,7 +455,7 @@ def test_structured_output(
structured_outputs=StructuredOutputsParams(grammar="not a grammar"),
)
with pytest.raises(
VLLMValidationError, match="Failed to convert the grammar "
VLLMValidationError, match="Invalid grammar specification"
):
runner.llm.generate(
(
@@ -26,13 +26,11 @@ def server():
"--enforce-eager",
"--limit-mm-per-prompt",
json.dumps({"audio": 3, "video": 3}),
"--trust-request-mm-kwargs",
*ROCM_EXTRA_ARGS,
]
with RemoteOpenAIServer(
MODEL_NAME,
args,
) as remote_server:
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
yield remote_server
@@ -37,6 +37,7 @@ def server():
json.dumps({"video": MAXIMUM_VIDEOS}),
"--media-io-kwargs",
json.dumps({"video": {"num_frames": 32}}),
"--trust-request-mm-kwargs",
]
# ROCm: Increase timeouts to handle potential network delays and slower
@@ -45,6 +45,8 @@ class MockModelConfig:
trust_remote_code = False
tokenizer_mode = "auto"
max_model_len = 100
revision = None
code_revision = None
tokenizer_revision = None
multimodal_config = MultiModalConfig()
hf_config = MockHFConfig()
@@ -475,6 +477,81 @@ def test_json_schema_response_format_missing_schema():
)
@pytest.mark.asyncio
async def test_online_renderer_rejects_mm_processor_kwargs_by_default():
model_config = MockModelConfig()
model_config.multimodal_config = MultiModalConfig()
online_renderer = OnlineRenderer(
model_config=model_config,
renderer=MagicMock(),
request_logger=None,
chat_template=None,
chat_template_content_format="auto",
)
request = ChatCompletionRequest(
model=MODEL_NAME,
messages=[{"role": "user", "content": "hello"}],
mm_processor_kwargs={
"patch_size": 1,
"vision_min_num_patches": 3_000_000_000,
},
)
with pytest.raises(
VLLMValidationError,
match="Per-request mm_processor_kwargs are disabled",
):
await online_renderer.preprocess_chat(
request,
request.messages,
default_template=None,
default_template_content_format="auto",
default_template_kwargs=None,
)
@pytest.mark.asyncio
async def test_online_renderer_rejects_media_io_kwargs_by_default():
model_config = MockModelConfig()
model_config.multimodal_config = MultiModalConfig()
online_renderer = OnlineRenderer(
model_config=model_config,
renderer=MagicMock(),
request_logger=None,
chat_template=None,
chat_template_content_format="auto",
)
request = ChatCompletionRequest(
model=MODEL_NAME,
messages=[{"role": "user", "content": "hello"}],
media_io_kwargs={"video": {"num_frames": 1_000_000}},
)
with pytest.raises(
VLLMValidationError,
match="Per-request media_io_kwargs are disabled",
):
await online_renderer.preprocess_chat(
request,
request.messages,
default_template=None,
default_template_content_format="auto",
default_template_kwargs=None,
)
def test_trust_request_mm_kwargs_opt_in_allows_overrides():
from vllm.entrypoints.generate.base.protocol import validate_request_mm_kwargs
validate_request_mm_kwargs(
mm_processor_kwargs={"use_audio_in_video": True},
media_io_kwargs={"video": {"num_frames": 4}},
trust_request_mm_kwargs=True,
)
@pytest.mark.parametrize("format_value", [None, {}])
def test_structural_tag_response_format_invalid(format_value):
"""Malformed structural tags should be rejected during request validation."""
@@ -44,6 +44,7 @@ from vllm.entrypoints.openai.parser.harmony_utils import get_encoding
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.exceptions import QueueOverflowError, VLLMValidationError
from vllm.inputs import TokensPrompt
from vllm.logprobs import Logprob
from vllm.multimodal.inputs import PlaceholderRange
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.parser import HarmonyParser
@@ -797,38 +798,401 @@ async def test_chat_streaming_metrics_ride_on_usage_chunk():
@pytest.mark.asyncio
async def test_streaming_reasoning_usage_counts_across_deltas():
serving = _build_minimal_metrics_serving_chat(enable_per_request_metrics=False)
serving._include_reasoning_tokens_details = True
@pytest.mark.parametrize("n", [1, 2])
@pytest.mark.parametrize("include_reasoning", [True, False])
@pytest.mark.parametrize("include_details", [True, False])
@pytest.mark.parametrize("separate_finish", [True, False])
@pytest.mark.parametrize(
"stream_options, force_usage, include_usage, continuous_usage",
[
(None, False, False, False),
({"include_usage": True}, False, True, False),
({"include_usage": True, "continuous_usage_stats": True}, False, True, True),
({"include_usage": False, "continuous_usage_stats": True}, False, False, False),
(None, True, True, True),
],
)
async def test_streaming_reasoning_usage_counts_across_deltas(
n,
include_reasoning,
include_details,
separate_finish,
stream_options,
force_usage,
include_usage,
continuous_usage,
):
"""Final usage needs one recount per choice, not per streamed delta."""
serving = _build_minimal_metrics_serving_chat(
enable_per_request_metrics=False, enable_force_include_usage=force_usage
)
serving._include_reasoning_tokens_details = include_details
serving.model_config = None
parser = MagicMock()
parser.parse_delta.side_effect = [
DeltaMessage(reasoning="reasoning"),
DeltaMessage(content="answer"),
]
parser.count_reasoning_tokens.side_effect = lambda token_ids: sum(
token_id == 20 for token_id in token_ids
)
serving.parser_cls = MagicMock(return_value=parser)
first = _make_metrics_request_output(metrics=None, token_ids=(10, 20))
first.outputs[0].text = "<think>reasoning"
first.outputs[0].finish_reason = None
second = _make_metrics_request_output(metrics=None, token_ids=(11, 30))
second.outputs[0].text = "</think>answer"
parsers = [MagicMock() for _ in range(n)]
request_outputs = []
num_steps = 3 if separate_finish else 2
for parser in parsers:
parser.parse_delta.side_effect = [
DeltaMessage(reasoning="reasoning") if include_reasoning else None,
DeltaMessage(content="answer"),
DeltaMessage(),
]
parser.count_reasoning_tokens.side_effect = lambda token_ids: sum(
token_id == 20 for token_id in token_ids
)
serving.parser_cls = MagicMock(side_effect=parsers)
for step in range(num_steps):
for i in reversed(range(n)):
tokens = ((10,) + (20,) * (i + 1), (11, 20, 30), ())[step]
result = _make_metrics_request_output(metrics=None, token_ids=tokens)
result.outputs[0].index = i
result.outputs[0].text = ("<think>reasoning", "</think>answer", "")[step]
finished = step == num_steps - 1
result.outputs[0].finish_reason = "stop" if finished else None
result.finished = finished and i == 0
request_outputs.append(result)
request = ChatCompletionRequest(
model="test-model",
messages=[{"role": "user", "content": "Test prompt"}],
max_tokens=10,
stream=True,
stream_options={"include_usage": True},
n=n,
include_reasoning=include_reasoning,
return_token_ids=True,
stream_options=stream_options,
)
metadata = RequestResponseMetadata(request_id="chatcmpl-test-id")
chunks: list[dict[str, Any]] = []
async for line in serving.chat_completion_stream_generator(
request,
_stream_request_outputs(*request_outputs),
"chatcmpl-test-id",
"test-model",
conversation=[{"role": "user", "content": "Test"}],
tokenizer=MagicMock(),
request_metadata=metadata,
):
payload = line.removeprefix("data: ").strip()
if payload != "[DONE]":
chunks.append(json.loads(payload))
assert all("error" not in chunk for chunk in chunks)
expected_count = sum(i + 2 for i in range(n))
expected_details = {"reasoning_tokens": expected_count} if include_details else None
assert metadata.final_usage_info is not None
assert metadata.final_usage_info.model_dump()["completion_tokens_details"] == (
expected_details
)
final_chunks = [chunk for chunk in chunks if not chunk["choices"]]
assert len(final_chunks) == int(include_usage)
if include_usage:
assert final_chunks[0]["usage"].get("completion_tokens_details") == (
expected_details
)
for i, parser in enumerate(parsers):
expected_calls = (
(num_steps if continuous_usage else 1) if include_details else 0
)
assert parser.count_reasoning_tokens.call_count == expected_calls
if include_details:
assert parser.count_reasoning_tokens.call_args.args == (
(10,) + (20,) * (i + 1) + (11, 20, 30),
)
choices = [
chunk
for chunk in chunks
if chunk["choices"] and chunk["choices"][0]["index"] == i
]
assert (
"".join(c["choices"][0]["delta"].get("content") or "" for c in choices)
== "answer"
)
if not include_reasoning:
assert all(c["choices"][0].get("token_ids") is None for c in choices)
if continuous_usage and include_details:
counts = [
c["usage"]["completion_tokens_details"]["reasoning_tokens"]
for c in choices
]
expected_counts = [0, i + 1] if include_reasoning else [0]
assert counts == expected_counts + [i + 2] * (num_steps - 1)
def _reasoning_lifecycle_output(
index: int = 0,
tokens: tuple[int, ...] = (20, 30),
text: str = "answer",
finish: str | None = None,
) -> RequestOutput:
result = _make_metrics_request_output(None, tokens)
result.outputs[0].index = index
result.outputs[0].text = text
result.outputs[0].finish_reason = finish
result.finished = finish is not None
return result
_EMPTY_OUTPUTS = _reasoning_lifecycle_output(tokens=(), text="")
_EMPTY_OUTPUTS.outputs = []
_REASONING_LIFECYCLE_CASES = [
("empty-generator", 1, [], 0, 0),
("empty-outputs", 1, [_EMPTY_OUTPUTS], 0, 0),
(
"empty-finish",
1,
[_reasoning_lifecycle_output(tokens=(), text="", finish="stop")],
0,
0,
),
(
"empty-prefill",
1,
[
_reasoning_lifecycle_output(tokens=(), text=""),
_reasoning_lifecycle_output(finish="stop"),
],
2,
1,
),
(
"one-empty-choice",
2,
[_reasoning_lifecycle_output(index=1, finish="stop")],
2,
1,
),
(
"uneven-finish",
2,
[
_reasoning_lifecycle_output(index=1, finish="stop"),
_reasoning_lifecycle_output(),
_reasoning_lifecycle_output(tokens=(20,), finish="stop"),
],
5,
3,
),
(
"empty-final-delta",
1,
[
_reasoning_lifecycle_output(),
_reasoning_lifecycle_output(tokens=(), text="", finish="stop"),
],
2,
1,
),
(
"ignore-finished-choice",
2,
[
_reasoning_lifecycle_output(index=1, finish="stop"),
_reasoning_lifecycle_output(index=1, tokens=(20, 20, 20)),
_reasoning_lifecycle_output(finish="stop"),
],
4,
2,
),
("exception-before", 1, [RuntimeError("fixture engine error")], None, None),
(
"exception-after",
1,
[_reasoning_lifecycle_output(), RuntimeError("fixture engine error")],
None,
None,
),
(
"generation-error",
1,
[
_reasoning_lifecycle_output(),
_reasoning_lifecycle_output(finish="error"),
],
None,
None,
),
(
"cancel-after",
1,
[_reasoning_lifecycle_output(), asyncio.CancelledError()],
None,
None,
),
(
"close-after",
1,
[
_reasoning_lifecycle_output(),
_reasoning_lifecycle_output(finish="stop"),
],
None,
None,
),
]
@pytest.mark.asyncio
@pytest.mark.parametrize("usage_mode", ["none", "final", "continuous"])
@pytest.mark.parametrize(
"name, n, outputs, expected_tokens, expected_reasoning",
_REASONING_LIFECYCLE_CASES,
ids=[case[0] for case in _REASONING_LIFECYCLE_CASES],
)
async def test_streaming_reasoning_usage_lifecycle_edges(
usage_mode,
name,
n,
outputs,
expected_tokens,
expected_reasoning,
):
"""Cancel, errors, and empty choices still match baseline stream usage."""
serving = _build_minimal_metrics_serving_chat(enable_per_request_metrics=False)
serving.model_config = None
serving._include_reasoning_tokens_details = True
parsers = [MagicMock() for _ in range(n)]
for parser in parsers:
parser.parse_delta.side_effect = lambda **kwargs: DeltaMessage(
content=kwargs["delta_text"]
)
parser.count_reasoning_tokens.side_effect = lambda ids: ids.count(20)
serving.parser_cls = MagicMock(side_effect=parsers)
stream_options = (
None
if usage_mode == "none"
else {
"include_usage": True,
"continuous_usage_stats": usage_mode == "continuous",
}
)
request = ChatCompletionRequest(
model="test-model",
messages=[{"role": "user", "content": "Test prompt"}],
stream=True,
n=n,
return_token_ids=True,
stream_options=stream_options,
)
metadata = RequestResponseMetadata(request_id="chatcmpl-lifecycle")
async def source():
for result in outputs:
if isinstance(result, BaseException):
raise result
yield result
iterator = source()
stream = serving.chat_completion_stream_generator(
request,
iterator,
"chatcmpl-lifecycle",
"test-model",
conversation=[{"role": "user", "content": "Test"}],
tokenizer=MagicMock(),
request_metadata=metadata,
)
chunks: list[object] = []
outcome = "exhausted"
try:
async for line in stream:
raw = line.removeprefix("data: ").strip()
if raw == "[DONE]":
chunks.append(raw)
continue
item = json.loads(raw)
chunks.append(item)
if name == "close-after" and any(
choice["delta"].get("content") for choice in item.get("choices", [])
):
await stream.aclose()
outcome = "closed"
break
except asyncio.CancelledError:
outcome = "cancelled"
finally:
await stream.aclose()
await iterator.aclose()
error_chunks = [c for c in chunks if isinstance(c, dict) and "error" in c]
call_count = sum(parser.count_reasoning_tokens.call_count for parser in parsers)
if expected_tokens is not None:
assert outcome == "exhausted" and chunks[-1] == "[DONE]" and not error_chunks
assert metadata.final_usage_info is not None
assert metadata.final_usage_info.completion_tokens == expected_tokens
assert (
metadata.final_usage_info.completion_tokens_details.reasoning_tokens
== expected_reasoning
)
nonempty_choices = sum(
bool(parser.count_reasoning_tokens.call_args) for parser in parsers
)
if usage_mode == "continuous":
assert call_count >= nonempty_choices
else:
assert call_count == nonempty_choices
return
assert metadata.final_usage_info is None
if name in {"cancel-after", "close-after"}:
assert outcome == ("cancelled" if name == "cancel-after" else "closed")
assert "[DONE]" not in chunks and not error_chunks
else:
assert outcome == "exhausted" and chunks[-1] == "[DONE]"
assert len(error_chunks) == 1
if usage_mode != "continuous" or name == "exception-before":
assert call_count == 0
else:
assert call_count >= 1
@pytest.mark.asyncio
@pytest.mark.parametrize(
("include_reasoning", "expected_tokens"),
[(True, ["<tool_call>", "answer"]), (False, [])],
)
async def test_streaming_logprobs_kept_when_parser_suppresses_delta(
include_reasoning: bool, expected_tokens: list[str]
):
"""Logprobs of tokens the parser swallows (e.g. <tool_call>) must still
be streamed, unless per-token metadata is hidden with the reasoning."""
serving = _build_minimal_metrics_serving_chat(enable_per_request_metrics=False)
serving.model_config = None
serving.return_tokens_as_token_ids = False
parser = MagicMock()
parser.parse_delta.side_effect = [None, DeltaMessage(content="answer")]
parser.count_reasoning_tokens.return_value = 0
serving.parser_cls = MagicMock(return_value=parser)
def make_output(token_id: int, text: str, finish_reason: str | None):
request_output = _make_metrics_request_output(
metrics=None, token_ids=(token_id,)
)
completion = request_output.outputs[0]
completion.text = text
completion.finish_reason = finish_reason
completion.logprobs = [
{token_id: Logprob(logprob=-0.5, rank=1, decoded_token=text)}
]
return request_output
request = ChatCompletionRequest(
model="test-model",
messages=[{"role": "user", "content": "Test prompt"}],
max_tokens=10,
stream=True,
logprobs=True,
include_reasoning=include_reasoning,
)
chunks: list[dict[str, Any]] = []
async for line in serving.chat_completion_stream_generator(
request,
_stream_request_outputs(first, second),
_stream_request_outputs(
make_output(10, "<tool_call>", None), make_output(11, "answer", "stop")
),
"chatcmpl-test-id",
"test-model",
conversation=[{"role": "user", "content": "Test"}],
@@ -839,10 +1203,14 @@ async def test_streaming_reasoning_usage_counts_across_deltas():
if payload != "[DONE]":
chunks.append(json.loads(payload))
usage_chunks = [chunk for chunk in chunks if chunk.get("usage")]
assert usage_chunks[-1]["usage"]["completion_tokens_details"] == {
"reasoning_tokens": 1
}
streamed_tokens = [
entry["token"]
for chunk in chunks
for choice in chunk["choices"]
if choice.get("logprobs")
for entry in choice["logprobs"]["content"]
]
assert streamed_tokens == expected_tokens
@dataclass
@@ -2239,7 +2607,13 @@ async def test_tool_choice_validation_without_parser():
@pytest.mark.asyncio
async def test_streaming_n_gt1_independent_tool_parsers():
@pytest.mark.parametrize(
("engine_finish_reason", "expected_finish_reason"),
[("stop", "tool_calls"), ("length", "length")],
)
async def test_streaming_n_gt1_independent_tool_parsers(
engine_finish_reason: str, expected_finish_reason: str
):
"""n>1 streaming must use independent parser instances
and token-id histories per choice.
"""
@@ -2344,7 +2718,7 @@ async def test_streaming_n_gt1_independent_tool_parsers():
token_ids=[],
cumulative_logprob=0.0,
logprobs=None,
finish_reason="stop",
finish_reason=engine_finish_reason,
)
for choice_idx in range(num_choices)
],
@@ -2408,8 +2782,8 @@ async def test_streaming_n_gt1_independent_tool_parsers():
assert len(reasons) == 1, (
f"Choice {choice_idx}: expected exactly 1 finish_reason, got {reasons}"
)
assert reasons[0] == "tool_calls", (
f"Choice {choice_idx}: expected finish_reason='tool_calls', "
assert reasons[0] == expected_finish_reason, (
f"Choice {choice_idx}: expected finish_reason={expected_finish_reason!r}, "
f"got '{reasons[0]}'"
)
@@ -14,8 +14,10 @@ from vllm.entrypoints.openai.completion.serving import OpenAIServingCompletion
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.scale_out.render.serving import ServingRender
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.exceptions import GenerationError, VLLMValidationError
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.renderers.deepseek_v4 import DeepseekV4Renderer
from vllm.renderers.hf import HfRenderer
from vllm.renderers.online_renderer import OnlineRenderer
from vllm.tokenizers.registry import cached_tokenizer_from_config
@@ -24,6 +26,9 @@ from vllm.v1.metrics.stats import RequestSpecDecodeMetrics, RequestStateStats
MODEL_NAME = "openai-community/gpt2"
MODEL_NAME_SHORT = "gpt2"
DEEPSEEK_V4_FIM_BEGIN = "<|fim▁begin|>"
DEEPSEEK_V4_FIM_HOLE = "<|fim▁hole|>"
DEEPSEEK_V4_FIM_END = "<|fim▁end|>"
_PER_REQUEST_STATS = RequestStateStats(
queued_ts=1.0,
scheduled_ts=1.5,
@@ -51,6 +56,8 @@ class MockModelConfig:
trust_remote_code = False
tokenizer_mode = "auto"
max_model_len = 100
revision = None
code_revision = None
tokenizer_revision = None
multimodal_config = MultiModalConfig()
hf_config = MockHFConfig()
@@ -302,6 +309,179 @@ def test_completion_metrics_carries_both_timing_and_spec_decode():
assert response.metrics.speculative_decoding.num_spec_steps == 2
def _build_online_renderer_for_completion(
model_config: MockModelConfig,
renderer: Any | None = None,
) -> OnlineRenderer:
if renderer is None:
renderer = MagicMock()
renderer.render_completion_suffix.return_value = None
return OnlineRenderer(
model_config=model_config,
renderer=renderer,
request_logger=None,
chat_template=None,
chat_template_content_format="auto",
)
def _deepseek_v4_suffix_renderer(
model_config: MockModelConfig,
) -> DeepseekV4Renderer:
return DeepseekV4Renderer(
MockVllmConfig(model_config, parallel_config=MockParallelConfig()),
None,
)
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_uses_renderer_capability():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock(return_value=[{"ok": True}])
request = CompletionRequest(
model=MODEL_NAME,
prompt="def fib(n):\n return ",
suffix="\n\nprint(fib(10))",
max_tokens=64,
)
result = await online_renderer.render_completion(request)
assert result == [{"ok": True}]
online_renderer.preprocess_completion.assert_awaited_once()
assert online_renderer.preprocess_completion.call_args.kwargs["prompt_input"] == (
f"{DEEPSEEK_V4_FIM_BEGIN}def fib(n):\n return "
f"{DEEPSEEK_V4_FIM_HOLE}\n\nprint(fib(10))"
f"{DEEPSEEK_V4_FIM_END}"
)
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_supports_text_prompt_list():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock(return_value=[{"ok": True}])
request = CompletionRequest(
model=MODEL_NAME,
prompt=["prefix A", "prefix B"],
suffix=" suffix",
)
result = await online_renderer.render_completion(request)
assert result == [{"ok": True}]
assert online_renderer.preprocess_completion.call_args.kwargs["prompt_input"] == [
f"{DEEPSEEK_V4_FIM_BEGIN}prefix A"
f"{DEEPSEEK_V4_FIM_HOLE} suffix{DEEPSEEK_V4_FIM_END}",
f"{DEEPSEEK_V4_FIM_BEGIN}prefix B"
f"{DEEPSEEK_V4_FIM_HOLE} suffix{DEEPSEEK_V4_FIM_END}",
]
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_rejects_renderer_without_fim_support():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(model_config)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt="prefix",
suffix="suffix",
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "FIM completion rendering" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_rejects_echo():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt="prefix",
suffix="suffix",
echo=True,
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "Echo is unsupported with suffix" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_rejects_prompt_embeds():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt="prefix",
suffix="suffix",
prompt_embeds=b"embeds",
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "suffix is not supported with prompt_embeds" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
@pytest.mark.parametrize("prompt", ([1, 2, 3], [[1, 2, 3]]))
async def test_completion_suffix_rejects_token_prompt(prompt):
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt=prompt,
suffix="suffix",
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "requires text prompt input" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
async def test_completion_error_non_stream():
"""Test finish_reason='error' returns 500 InternalServerError (non-streaming)."""
@@ -748,6 +748,7 @@ class TestInitializeToolSessions:
class ToolCallingHarmonyContext(HarmonyContext):
def __init__(self):
self._messages = []
self.request = None
self._needs_tool_call = True
def append_output(self, output) -> None:
@@ -804,6 +805,53 @@ class TestInitializeToolSessions:
assert followup_engine_input.get("cache_salt") == "request-salt"
assert followup_engine_input["prompt_token_ids"] == [3, 4]
@pytest.mark.asyncio
async def test_harmony_tool_followup_respects_max_output_tokens(
self, serving_responses_instance
):
class ToolCallingHarmonyContext(HarmonyContext):
def __init__(self, request):
self._messages = []
self.request = request
self._needs_tool_call = True
def append_output(self, output) -> None:
pass
def need_builtin_tool_call(self) -> bool:
return self._needs_tool_call
async def call_tool(self):
self._needs_tool_call = False
return []
def append_tool_output(self, output) -> None:
pass
max_tokens_per_turn = []
async def generate_output(engine_input, sampling_params, *args, **kwargs):
max_tokens_per_turn.append(sampling_params.max_tokens)
yield MagicMock()
serving_responses_instance.engine_client.generate.side_effect = generate_output
serving_responses_instance.online_renderer.render_responses_harmony_messages = (
MagicMock(return_value=tokens_input([1, 2, 3]))
)
context = ToolCallingHarmonyContext(
ResponsesRequest(input="test", max_output_tokens=10)
)
async for _ in serving_responses_instance._generate_with_builtin_tools(
request_id="req",
engine_input=tokens_input([1]),
sampling_params=SamplingParams(max_tokens=10),
context=context,
):
pass
assert max_tokens_per_turn == [10, 10]
@pytest.mark.asyncio
async def test_initialize_tool_sessions(
self, serving_responses_instance, mock_context, mock_exit_stack
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for presence_penalty / frequency_penalty resolution from
default_sampling_params in ChatCompletionRequest and CompletionRequest.
Regression test for https://github.com/vllm-project/vllm/issues/50767:
these two penalties defaulted to 0.0 (not None) and to_sampling_params()
forwarded them straight through, so server-side defaults coming from
--override-generation-config / generation_config.json were silently
discarded on the /v1/chat/completions and /v1/completions endpoints.
"""
from vllm.entrypoints.openai.chat_completion.protocol import (
ChatCompletionRequest,
)
from vllm.entrypoints.openai.completion.protocol import (
CompletionRequest,
)
_DEFAULTS = {"presence_penalty": 1.5, "frequency_penalty": 0.5}
def _chat(**kwargs):
return ChatCompletionRequest(
model="test-model",
messages=[{"role": "user", "content": "hi"}],
**kwargs,
)
class TestChatCompletionPenaltyDefaults:
def test_defaults_applied_when_client_omits(self):
"""Server-default penalties are applied when the client sends none."""
sp = _chat().to_sampling_params(100, _DEFAULTS)
assert sp.presence_penalty == 1.5
assert sp.frequency_penalty == 0.5
def test_client_value_overrides_default(self):
"""An explicit client penalty wins over the server default."""
sp = _chat(presence_penalty=0.2).to_sampling_params(100, _DEFAULTS)
assert sp.presence_penalty == 0.2
assert sp.frequency_penalty == 0.5
def test_falls_back_to_zero_without_default(self):
"""Without a server default the neutral 0.0 is used (no regression)."""
sp = _chat().to_sampling_params(100, {})
assert sp.presence_penalty == 0.0
assert sp.frequency_penalty == 0.0
class TestCompletionPenaltyDefaults:
def test_defaults_applied_when_client_omits(self):
sp = CompletionRequest(model="test-model", prompt="hi").to_sampling_params(
16, _DEFAULTS
)
assert sp.presence_penalty == 1.5
assert sp.frequency_penalty == 0.5
def test_client_value_overrides_default(self):
sp = CompletionRequest(
model="test-model", prompt="hi", frequency_penalty=0.9
).to_sampling_params(16, _DEFAULTS)
assert sp.presence_penalty == 1.5
assert sp.frequency_penalty == 0.9
@@ -233,6 +233,7 @@ def online_renderer(model_config: MockModelConfig, request) -> OnlineRenderer:
enable_auto_tools=True,
tool_parser="openai",
exclude_tools_when_tool_choice_none=exclude_tools_when_tool_choice_none,
trust_request_mm_kwargs=True,
)
@@ -46,6 +46,7 @@ def server():
json.dumps({"image": MAXIMUM_IMAGES}),
"--chat-template",
str(vlm2vec_jinja_path),
"--trust-request-mm-kwargs",
]
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
@@ -126,35 +126,6 @@ async def test_score_api_queries_str_n_documents_str_n(
assert hf_outputs[i] == pytest.approx(vllm_outputs[i], rel=0.01)
@pytest.mark.asyncio
async def test_score_api_queries_vs_documents(hf_model, server: RemoteOpenAIServer):
text_pairs = [
[TEXTS_1[0], TEXTS_2[0]],
[TEXTS_1[1], TEXTS_2[1]],
]
score_response = requests.post(
server.url_for("score"),
json={
"model": MODEL_NAME,
"queries": TEXTS_1,
"documents": TEXTS_2,
},
)
score_response.raise_for_status()
score = ScoreResponse.model_validate(score_response.json())
assert score.id is not None
assert score.data is not None
assert len(score.data) == 2
vllm_outputs = [d.score for d in score.data]
hf_outputs = hf_model.predict(text_pairs).tolist()
for i in range(len(vllm_outputs)):
assert hf_outputs[i] == pytest.approx(vllm_outputs[i], rel=0.01)
@pytest.mark.asyncio
async def test_score_api_queries_vs_items(hf_model, server: RemoteOpenAIServer):
text_pairs = [
@@ -143,35 +143,6 @@ async def test_score_api_queries_str_n_documents_str_n(
assert hf_outputs[i] == pytest.approx(vllm_outputs[i], rel=0.01)
@pytest.mark.asyncio
async def test_score_api_queries_vs_documents(hf_model, server: RemoteOpenAIServer):
text_pairs = [
[TEXTS_1[0], TEXTS_2[0]],
[TEXTS_1[1], TEXTS_2[1]],
]
score_response = requests.post(
server.url_for("score"),
json={
"model": MODEL_NAME,
"queries": TEXTS_1,
"documents": TEXTS_2,
},
)
score_response.raise_for_status()
score = ScoreResponse.model_validate(score_response.json())
assert score.id is not None
assert score.data is not None
assert len(score.data) == 2
vllm_outputs = [d.score for d in score.data]
hf_outputs = hf_model.predict(text_pairs).tolist()
for i in range(len(vllm_outputs)):
assert hf_outputs[i] == pytest.approx(vllm_outputs[i], rel=0.01)
@pytest.mark.asyncio
async def test_score_api_queries_vs_items(hf_model, server: RemoteOpenAIServer):
text_pairs = [
@@ -3,11 +3,15 @@
"""Unit tests for ScoringIOProcessor post-tokenization helpers."""
from dataclasses import dataclass
from types import SimpleNamespace
import pytest
from tokenizers import Tokenizer, models, pre_tokenizers, processors
from transformers import TokenizersBackend
from vllm import TokensPrompt
from vllm.entrypoints.pooling.scoring.io_processor import (
CrossEncoderIOProcessor,
_apply_post_tokenization_to_token_type_ids,
)
from vllm.entrypoints.pooling.scoring.utils import compress_token_type_ids
@@ -24,6 +28,53 @@ class _DummyTokenizer:
pad_token_id: int = 99999
@pytest.fixture
def llm_reranker_processor() -> CrossEncoderIOProcessor:
vocab = {
"[UNK]": 0,
"[CLS]": 1,
"[SEP]": 2,
"a": 3,
"bc": 4,
"##b": 5,
"##c": 6,
}
backend = Tokenizer(models.WordPiece(vocab, unk_token="[UNK]"))
backend.pre_tokenizer = pre_tokenizers.WhitespaceSplit()
backend.post_processor = processors.TemplateProcessing(
single="[CLS] $A [SEP]",
special_tokens=[("[CLS]", 1), ("[SEP]", 2)],
)
processor = CrossEncoderIOProcessor.__new__(CrossEncoderIOProcessor)
processor.model_config = SimpleNamespace(enable_prompt_embeds=False)
processor.tokenizer = TokenizersBackend(
tokenizer_object=backend,
unk_token="[UNK]",
cls_token="[CLS]",
sep_token="[SEP]",
)
processor.supports_score_template = False
processor.use_sep_token = False
processor.model = None
return processor
def test_llm_reranker_tokenization_is_independent_of_nonbinding_doc_limit(
llm_reranker_processor: CrossEncoderIOProcessor,
):
encode_kwargs = {"add_special_tokens": True}
_, uncapped = llm_reranker_processor.get_score_prompt("a", "bc", encode_kwargs)
_, nonbinding = llm_reranker_processor.get_score_prompt(
"a", "bc", encode_kwargs, max_tokens_per_doc=10
)
expected = [1, 3, 5, 6, 2]
assert uncapped["prompt_token_ids"] == expected
assert nonbinding["prompt_token_ids"] == expected
def test_token_type_ids_stay_aligned_with_a_truncated_padded_prompt():
"""The cross-encoder segment boundary must survive truncate + pad.
@@ -7,7 +7,7 @@ from unittest.mock import MagicMock
import pytest
from tokenizers import Tokenizer, models, pre_tokenizers
from transformers import PreTrainedTokenizerFast
from transformers import TokenizersBackend
from vllm import PoolingParams
from vllm.entrypoints.pooling.base.io_processor import PoolingIOProcessor
@@ -70,7 +70,7 @@ def offline_processor_and_context():
backend = Tokenizer(models.WordLevel({"[UNK]": 0}, unk_token="[UNK]"))
backend.pre_tokenizer = pre_tokenizers.WhitespaceSplit()
proc = JinaRankingIOProcessor.__new__(JinaRankingIOProcessor)
proc.tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend)
proc.tokenizer = TokenizersBackend(tokenizer_object=backend)
proc.model_config = SimpleNamespace(max_model_len=1024, is_encoder_decoder=False)
proc.renderer = SimpleNamespace(
default_cmpl_tok_params=TokenizeParams(max_total_tokens=1024)
@@ -26,6 +26,36 @@ TEXTS_2 = [
]
@pytest.mark.asyncio
async def test_flash_late_interaction_rejects_mm_processor_kwargs_by_default():
from unittest.mock import MagicMock
from vllm.config.multimodal import MultiModalConfig
from vllm.entrypoints.pooling.base.serving import PoolingBaseServing
from vllm.entrypoints.pooling.scoring.protocol import ScoreQueriesDocumentsRequest
from vllm.entrypoints.pooling.scoring.serving import ServingScores
from vllm.exceptions import VLLMValidationError
serving = MagicMock()
serving.model_config = MagicMock(multimodal_config=MultiModalConfig())
serving.trust_request_mm_kwargs = False
serving.io_processor = MagicMock()
serving._init_ctx = PoolingBaseServing._init_ctx.__get__(serving)
request = ScoreQueriesDocumentsRequest(
model=MODEL_NAME,
queries=TEXTS_1[0],
documents=TEXTS_2[0],
mm_processor_kwargs={"vision_min_num_patches": 3_000_000_000},
)
with pytest.raises(
VLLMValidationError,
match="Per-request mm_processor_kwargs are disabled",
):
await ServingScores.flash_late_interaction(serving, request)
serving._preprocessing.assert_not_called()
@pytest.fixture(scope="module", params=[True, False])
def server(request):
args = [
@@ -2,9 +2,14 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tokenizers import Tokenizer, models, pre_tokenizers
from transformers import TokenizersBackend
from vllm.entrypoints.pooling.scoring.typing import ScoreInput
from vllm.entrypoints.pooling.scoring.utils import validate_score_input
from vllm.entrypoints.pooling.scoring.utils import (
truncate_text_to_tokens,
validate_score_input,
)
from vllm.exceptions import VLLMValidationError
@@ -63,3 +68,17 @@ def test_validate_score_input_rejects_invalid_inputs(
assert str(exc_info.value) == message
assert exc_info.value.parameter is None
assert exc_info.value.value is None
def test_truncate_text_to_tokens_handles_shared_character_offsets():
vocab = {
token: i for i, token in enumerate(sorted(pre_tokenizers.ByteLevel.alphabet()))
}
backend = Tokenizer(models.BPE(vocab=vocab, merges=[]))
backend.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tokenizer = TokenizersBackend(tokenizer_object=backend)
truncated = truncate_text_to_tokens("aéx", tokenizer, max_tokens=2)
assert truncated == "a"
assert len(tokenizer(truncated, add_special_tokens=False)["input_ids"]) == 1
@@ -18,6 +18,8 @@ Tests are split into two layers:
"""
import json
import threading
from concurrent.futures import ThreadPoolExecutor
import pytest
import pytest_asyncio
@@ -214,7 +216,7 @@ def tokenizer():
@pytest.fixture(scope="module")
def derenderer(tokenizer):
def derenderer(tokenizer, request):
"""Construct a minimal OnlineDerenderer backed by a stub renderer."""
from unittest.mock import MagicMock
@@ -223,6 +225,10 @@ def derenderer(tokenizer):
renderer = MagicMock()
renderer.get_tokenizer.return_value = tokenizer
executor = ThreadPoolExecutor(max_workers=1)
request.addfinalizer(executor.shutdown)
renderer._executor = executor
model_config = MagicMock()
model_config.hf_config.model_type = "llama"
model_config.model = MODEL_NAME
@@ -244,13 +250,11 @@ def derenderer(tokenizer):
def parsed_derenderer(tokenizer):
"""OnlineDerenderer with `_FakeParser` wired in as `self.parser`.
The parser configured path runs `_derender_chat_stream_parsed` via
`make_async(..., executor=renderer._executor)`, so unlike
`derenderer` above (whose streaming paths never touch the executor),
`renderer._executor` must be a real `ThreadPoolExecutor` here.
The parser-configured path runs `_derender_chat_stream_parsed` via
`make_async(..., executor=renderer._executor)`, so
`renderer._executor` must be a real `ThreadPoolExecutor`.
`loop.run_in_executor` cannot submit work to a `MagicMock`.
"""
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import MagicMock
from vllm.renderers.online_derenderer import OnlineDerenderer
@@ -390,6 +394,46 @@ class TestDetokenizeDelta:
assert results[0] == self._one_shot(tokenizer, token_ids)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"stream_method",
["derender_chat_stream", "derender_completion_stream"],
)
async def test_streaming_detokenization_runs_off_event_loop(
derenderer, monkeypatch, stream_method
):
"""Streaming detokenization runs on the renderer executor."""
import vllm.renderers.online_derenderer as online_derenderer_module
event_loop_thread_id = threading.get_ident()
executor_thread_id = derenderer.renderer._executor.submit(
threading.get_ident
).result()
detokenize_thread_id = None
original_detokenize = online_derenderer_module.detokenize_incrementally
def record_detokenize_thread(*args, **kwargs):
nonlocal detokenize_thread_id
detokenize_thread_id = threading.get_ident()
return original_detokenize(*args, **kwargs)
monkeypatch.setattr(
online_derenderer_module,
"detokenize_incrementally",
record_detokenize_thread,
)
await getattr(derenderer, stream_method)(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk([10]),
)
assert detokenize_thread_id is not None
assert detokenize_thread_id == executor_thread_id
assert detokenize_thread_id != event_loop_thread_id
class TestDerenderCompletionStream:
"""derender_completion_stream: streaming output parity with one shot."""
@@ -875,7 +919,6 @@ def harmony_derenderer(harmony_tokenizer):
with a real tokenizer and parser, so the replay path is exercised
against Harmony's actual channel grammar rather than a stub.
"""
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import MagicMock
from vllm.parser.harmony import HarmonyParser
@@ -651,9 +651,9 @@ async def test_messages_render_system_and_multi_turn(client):
async def test_messages_render_merges_inline_system(client):
"""Inline system messages merge into the leading system block.
Without a --chat-template arg the /v1/messages server path detects
merge_inline_system=True, so render must produce the same tokens as
the manually pre-merged request.
The model's chat template rejects non-leading system messages, so the
/v1/messages server path detects merge_inline_system=True and render must
produce the same tokens as the manually pre-merged request.
"""
inline = await client.post(
"/v1/messages/render",
@@ -26,3 +26,13 @@ def test_logprobs_zero_emits_sampled_token():
num_output_top_logprobs=0,
)
assert len(result.content[0].top_logprobs) == 1
def test_logprobs_minus_one_emits_all_tokens():
result = ServingTokens._create_tokens_logprobs(
None,
token_ids=[7],
top_logprobs=[{7: Logprob(-0.9), 8: Logprob(-1.1)}],
num_output_top_logprobs=-1,
)
assert len(result.content[0].top_logprobs) == 2
@@ -15,7 +15,6 @@ import subprocess
import sys
import threading
import time
from collections.abc import Callable
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any
@@ -138,36 +137,6 @@ def server(
proc.kill()
# ---------------------------------------------------------------------------
# Polling helper (200-lie workaround)
# ---------------------------------------------------------------------------
def poll_until(
predicate: Callable[[], bool],
timeout: float = 10.0,
interval: float = 0.5,
) -> bool:
"""Poll predicate() until it returns True or timeout expires.
Workaround for the vLLM sleep/wake "200-lie" — the HTTP endpoints may
return 200 before the underlying operation is complete, so callers that
need to verify state *after* an operation can use this helper instead of
assuming the 200 means completion.
Returns True if predicate became true within timeout, False otherwise.
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
if predicate():
return True
except Exception:
pass
time.sleep(interval)
return False
# ---------------------------------------------------------------------------
# HTTP helpers — generation
# ---------------------------------------------------------------------------
@@ -191,27 +160,6 @@ def gen(url, prompt="The capital of France is", max_tokens=8, timeout=30):
return None
def gen_with_logprobs(
url, prompt="The capital of France is", max_tokens=8, logprobs=5, timeout=30
):
"""Fire a /v1/completions request with logprobs; return JSON or None."""
try:
r = requests.post(
f"{url}/v1/completions",
json={
"model": "m",
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": 0,
"logprobs": logprobs,
},
timeout=timeout,
)
return r.json()
except Exception:
return None
def ok(resp) -> bool:
"""True iff resp is a successful completion (has choices, no error key)."""
return (
@@ -399,37 +347,3 @@ def get_world_size(url, include_dp=True):
params={"include_dp": include_dp},
timeout=5,
)
# ---------------------------------------------------------------------------
# GPU / metrics helpers
# ---------------------------------------------------------------------------
def gpu_free_bytes(device: int = 0) -> int:
"""Read GPU free bytes via subprocess to avoid import-time torch init."""
out = subprocess.check_output(
[
sys.executable,
"-c",
f"import torch; f,_=torch.accelerator.get_memory_info({device}); print(f)",
],
timeout=10,
)
return int(out.strip())
def sleep_metrics(url):
"""Return (awake, weights_offloaded, discard_all) from /metrics."""
try:
from prometheus_client.parser import text_string_to_metric_families
except ImportError:
return None, None, None
r = requests.get(f"{url}/metrics", timeout=5)
vals: dict = {}
for family in text_string_to_metric_families(r.text):
if family.name == "vllm:engine_sleep_state":
for s in family.samples:
vals[s.labels.get("sleep_state", "")] = s.value
return vals.get("awake"), vals.get("weights_offloaded"), vals.get("discard_all")
@@ -18,6 +18,10 @@ def test_sanitize_message():
sanitize_message("<_io.BytesIO object at 0x7a95e299e750>")
== "<_io.BytesIO object>"
)
assert (
sanitize_message("<PIL.Image.Image image mode=RGB size=2x2 at 0x7D52EAF07BF0>")
== "<PIL.Image.Image image mode=RGB size=2x2>"
)
class TestSanitizeMessageFilePaths:
@@ -0,0 +1,28 @@
model_name: "deepseek-ai/DeepSeek-V4-Flash-DSpark"
accuracy_threshold: 0.92
tolerance: 0.08
min_acceptance_length: 1.2
num_questions: 1319
num_fewshot: 5
startup_max_wait_seconds: 1800
env:
VLLM_ROCM_USE_AITER: "1"
server_args: >-
--tokenizer-mode deepseek_v4
--trust-remote-code
--max-model-len 8192
--tensor-parallel-size 4
--enable-expert-parallel
--all2all-backend allgather_reducescatter
--block-size 256
--gpu-memory-utilization 0.5
--kv-cache-dtype fp8
--attention_config.indexer_kv_dtype=fp8
--max-num-batched-tokens 16384
--max-num-seqs 128
--enforce-eager
--speculative-config '{"method":"dspark",
"model":"deepseek-ai/DeepSeek-V4-Flash-DSpark",
"num_speculative_tokens":7,
"draft_sample_method":"probabilistic",
"enable_adaptive_verification":false}'
@@ -0,0 +1,6 @@
model_name: "Qwen/Qwen3-4B"
accuracy_threshold: 0.78
num_questions: 1319
num_fewshot: 5
# Triton serves the unquantized boundary layers with TurboQuant-compatible layout.
server_args: "--kv-cache-dtype turboquant_k3v4_nc --max-model-len 4096 --attention-backend TRITON_ATTN"
@@ -0,0 +1,6 @@
model_name: "Qwen/Qwen3-4B"
accuracy_threshold: 0.80
num_questions: 1319
num_fewshot: 5
# Triton serves the unquantized boundary layers with TurboQuant-compatible layout.
server_args: "--kv-cache-dtype turboquant_k8v4 --max-model-len 4096 --attention-backend TRITON_ATTN"
@@ -0,0 +1,6 @@
model_name: "Qwen/Qwen3-4B"
accuracy_threshold: 0.75
num_questions: 1319
num_fewshot: 5
# Triton serves the unquantized boundary layers with TurboQuant-compatible layout.
server_args: "--kv-cache-dtype turboquant_3bit_nc --max-model-len 4096 --attention-backend TRITON_ATTN"
@@ -0,0 +1,6 @@
model_name: "Qwen/Qwen3-4B"
accuracy_threshold: 0.80
num_questions: 1319
num_fewshot: 5
# Triton serves the unquantized boundary layers with TurboQuant-compatible layout.
server_args: "--kv-cache-dtype turboquant_4bit_nc --max-model-len 4096 --attention-backend TRITON_ATTN"
@@ -3,6 +3,5 @@ accuracy_threshold: 0.39
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--linear-backend humming
@@ -3,7 +3,6 @@ accuracy_threshold: 0.86
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--moe-backend humming
--linear-backend humming
@@ -1,5 +1,5 @@
model_name: "nm-testing/Qwen3-4B-mixed-quant-RTN-wNaM"
accuracy_threshold: 0.78
model_name: "nm-testing/Qwen3-4B-mixed-quant-RTN-wNaM-a4"
accuracy_threshold: 0.70
num_questions: 1319
num_fewshot: 5
server_args: >-
@@ -0,0 +1,8 @@
model_name: "nm-testing/Qwen3-4B-mixed-quant-RTN-wNaM-asym"
accuracy_threshold: 0.85
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 4096
--linear-backend humming
@@ -1,3 +1,4 @@
gpt-oss-20b-humming.yaml
Qwen3.5-35B-A3B-experts-int8-humming-act-int8.yaml
Qwen3.5-35B-A3B-int6wc-hadamard-humming-act-int8.yaml
Qwen3-4B-mixed-quant-RTN-no-w4a4-humming.yaml
@@ -4,4 +4,4 @@ Qwen3-30B-A3B-GPTQ-Int4-humming-act-int8.yaml
Qwen3-30B-A3B-AWQ-humming.yaml
Qwen3.5-35B-A3B-experts-int8-humming-act-int8.yaml
Qwen3.5-35B-A3B-int6wc-hadamard-humming-act-int8.yaml
Qwen3-4B-mixed-quant-RTN-humming.yaml
Qwen3-4B-mixed-quant-RTN-no-w4a4-humming.yaml
@@ -0,0 +1,2 @@
Qwen3-0.6B-FP8.yaml
Qwen3-1.7B-MXFP4.yaml
@@ -1,2 +1,3 @@
Kimi-K3-pruned75-DSpark-AITER-TP4.yaml
DeepSeek-V4-Flash-DSpark-AITER-TEP4.yaml
DeepSeek-V4-Flash-DSpark-FP8-TP4-ROCm.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-k3v4nc-ROCm.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-k3v4nc.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-k8v4-ROCm.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-k8v4.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-t3nc-ROCm.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-t3nc.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-t4nc-ROCm.yaml
@@ -0,0 +1 @@
Qwen3-4B-TQ-t4nc.yaml
@@ -1,4 +0,0 @@
Qwen3-4B-TQ-k8v4.yaml
Qwen3-4B-TQ-t4nc.yaml
Qwen3-4B-TQ-k3v4nc.yaml
Qwen3-4B-TQ-t3nc.yaml
@@ -0,0 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Keep the MRV2 sampler warmup registry populated on ROCm."""
import pytest
from vllm import LLM
from vllm.platforms import current_platform
from ..models.utils import dummy_hf_overrides
from ..utils import create_new_process_for_each_test
from .test_no_runtime_jit import _run_shape_battery
pytestmark = pytest.mark.skipif(not current_platform.is_rocm(), reason="Requires ROCm")
def _worker_monitor_state(worker):
from vllm.utils import jit_monitor
return (
jit_monitor.is_active(),
worker.observability_config.jit_monitor_mode,
)
@create_new_process_for_each_test("spawn")
def _run_rocm_shape_battery() -> None:
llm = LLM(
"Qwen/Qwen3-0.6B",
max_model_len=2048,
max_num_seqs=8,
gpu_memory_utilization=0.03,
kv_cache_memory_bytes=256 * 1024 * 1024,
load_format="dummy",
hf_overrides=dummy_hf_overrides,
enforce_eager=False,
jit_monitor_mode="error",
)
try:
states = llm.collective_rpc(_worker_monitor_state, timeout=30)
assert states and all(state == (True, "error") for state in states)
_run_shape_battery(llm)
finally:
llm.llm_engine.engine_core.shutdown(timeout=30)
def test_v2_sampler_warmup_rocm(monkeypatch, tmp_path):
"""Warmup must cover the existing prefill, decode, and sampler battery.
A fresh cache and child process prevent previous model executions from
hiding a missing warmup specialization.
"""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "0")
monkeypatch.setenv("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
monkeypatch.setenv("TRITON_CACHE_DIR", str(tmp_path / "triton"))
monkeypatch.setenv("VLLM_CACHE_ROOT", str(tmp_path / "vllm"))
monkeypatch.setenv("TORCHINDUCTOR_CACHE_DIR", str(tmp_path / "inductor"))
_run_rocm_shape_battery()
-40
View File
@@ -309,46 +309,6 @@ def test_paged_attention(
torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol)
def ref_multi_query_kv_attention(
cu_seq_lens: list[int],
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
scale: float,
alibi_bias: list[torch.Tensor] | None,
dtype: torch.dtype,
) -> torch.Tensor:
num_seqs = len(cu_seq_lens) - 1
ref_outputs: list[torch.Tensor] = []
if alibi_bias:
assert len(alibi_bias) == num_seqs
for i in range(num_seqs):
start_idx = cu_seq_lens[i]
end_idx = cu_seq_lens[i + 1]
seq_len = end_idx - start_idx
# Create attention mask. ALiBi already includes a tril causal mask.
if alibi_bias:
attn_mask = alibi_bias[i]
else:
attn_mask = torch.triu(
torch.ones(seq_len, seq_len, dtype=dtype), diagonal=1
)
attn_mask = attn_mask * torch.finfo(dtype).min
attn_mask = attn_mask.to(dtype=dtype)
ref_output = ref_masked_attention(
query[start_idx:end_idx],
key[start_idx:end_idx],
value[start_idx:end_idx],
scale,
attn_mask=attn_mask,
)
ref_outputs.append(ref_output)
return torch.cat(ref_outputs, dim=0)
@pytest.mark.parametrize("attention_cls", [Attention, MMEncoderAttention])
def test_num_heads_not_divisible_by_num_kv_heads(attention_cls: type) -> None:
head_size = 64
@@ -341,61 +341,6 @@ def test_fp32_fallback(device: str):
get_attn_backend(16, torch.float32, None)
def test_flash_attn(monkeypatch: pytest.MonkeyPatch):
"""Test FlashAttn validation."""
pytest.skip(
"Skipping as current backend selector does not "
"handle fallbacks when a backend is explicitly set."
)
attention_config = AttentionConfig(backend=AttentionBackendEnum.FLASH_ATTN)
cache_config = CacheConfig(block_size=16)
vllm_config = VllmConfig(
attention_config=attention_config, cache_config=cache_config
)
with set_current_vllm_config(vllm_config):
# Unsupported CUDA arch
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _=None: (7, 5))
backend = get_attn_backend(16, torch.float16, None)
assert backend.get_name() != "FLASH_ATTN"
# Reset the monkeypatch for subsequent tests
monkeypatch.undo()
# Unsupported data type
backend = get_attn_backend(16, torch.float8_e4m3fn, None)
assert backend.get_name() != "FLASH_ATTN"
# Unsupported kv cache data type
backend = get_attn_backend(16, torch.float16, "fp8")
assert backend.get_name() != "FLASH_ATTN"
# Unsupported block size
vllm_config.cache_config.block_size = 8
backend = get_attn_backend(16, torch.float16, None)
assert backend.get_name() != "FLASH_ATTN"
# flash-attn is not installed
import sys
vllm_config.cache_config.block_size = 16
original_module = sys.modules.get("vllm_flash_attn")
monkeypatch.setitem(sys.modules, "vllm_flash_attn", None)
backend = get_attn_backend(16, torch.float16, None)
assert backend.get_name() != "FLASH_ATTN"
# Restore the original module if it existed
if original_module is not None:
monkeypatch.setitem(sys.modules, "vllm_flash_attn", original_module)
else:
monkeypatch.delitem(sys.modules, "vllm_flash_attn", raising=False)
# Unsupported head size
backend = get_attn_backend(17, torch.float16, None)
assert backend.get_name() != "FLASH_ATTN"
def test_invalid_backend():
"""Test that invalid attention backend names raise ValueError."""
with (
@@ -848,7 +793,7 @@ def hopper_selection():
def test_hopper_mm_prefix_selects_triton_flash_attn(
use_mm_prefix, flash_attn_version, hopper_selection
):
"""Hopper selects the composite only when its causal route resolves FA4."""
"""Hopper selects the composite when its causal route resolves FA3 or FA4."""
from vllm.engine.arg_utils import EngineArgs
config = EngineArgs(
@@ -860,11 +805,7 @@ def test_hopper_mm_prefix_selects_triton_flash_attn(
backend = get_attn_backend(
256, torch.bfloat16, None, use_mm_prefix=use_mm_prefix
)
fa4_resolved = config.attention_config.flash_attn_version == 4
if use_mm_prefix:
expected = "TRITON_FLASH_ATTN" if fa4_resolved else "TRITON_ATTN"
else:
expected = "FLASH_ATTN"
expected = "TRITON_FLASH_ATTN" if use_mm_prefix else "FLASH_ATTN"
assert backend.get_name() == expected
+44
View File
@@ -1012,6 +1012,50 @@ def test_concat_and_cache_ds_mla(
torch.testing.assert_close(kv_rope, ref_rope, atol=0.001, rtol=0.1)
@pytest.mark.parametrize("device", CUDA_DEVICES)
@pytest.mark.parametrize("block_size", [64, 256])
@torch.inference_mode()
def test_concat_and_cache_ds_mla_nope(device: str, block_size: int) -> None:
"""NoPE matches zero RoPE, clears valid tails, and preserves unused slots."""
dtype = torch.bfloat16
if current_platform.is_rocm():
pytest.skip("concat_and_cache_mla doesn't support fp8_ds_mla on ROCm")
num_tokens, num_blocks = 3, 2
set_random_seed(0)
torch.set_default_device(device)
torch.accelerator.set_device_index(device)
slot_mapping = torch.tensor(
[block_size - 1, block_size, -1], dtype=torch.long, device=device
)
kv_c = torch.randn(num_tokens, 512, dtype=dtype, device=device)
k_pe = torch.empty(num_tokens, 0, dtype=dtype, device=device)
zero_k_pe = torch.zeros(num_tokens, 64, dtype=dtype, device=device)
scale = torch.tensor(1.0, dtype=torch.float32, device=device)
kv_cache = torch.full(
(num_blocks, block_size, 656), 0xFF, dtype=torch.uint8, device=device
)
ref_cache = kv_cache.clone()
opcheck(
torch.ops._C_cache_ops.concat_and_cache_mla,
(kv_c, k_pe, kv_cache, slot_mapping, "fp8_ds_mla", scale),
test_utils=DEFAULT_OPCHECK_TEST_UTILS,
)
kv_cache.fill_(0xFF)
ops.concat_and_cache_mla(kv_c, k_pe, kv_cache, slot_mapping, "fp8_ds_mla", scale)
ops.concat_and_cache_mla(
kv_c, zero_k_pe, ref_cache, slot_mapping, "fp8_ds_mla", scale
)
torch.testing.assert_close(kv_cache, ref_cache, atol=0, rtol=0)
rows = kv_cache.view(num_blocks * block_size, 656)
assert (rows[slot_mapping[:2], 528:] == 0).all()
untouched = torch.ones(num_blocks * block_size, dtype=torch.bool, device=device)
untouched[slot_mapping[:2]] = False
assert (rows[untouched] == 0xFF).all()
# Bytes per token for the nvfp4_ds_mla cache layout (see flashmla_sparse.py).
NVFP4_DS_MLA_ENTRY_SIZE = 352
+182 -3
View File
@@ -3,13 +3,20 @@
import functools
import math
from types import SimpleNamespace
import pytest
import torch
from vllm.model_executor.kernels.linear.zentorch_utils import has_zentorch_op
from vllm.platforms import CpuArchEnum, current_platform
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.attention.backend import AttentionType
from vllm.v1.attention.backends.cpu_attn import _get_attn_isa
from vllm.v1.attention.backends.zentorch_sdpa import (
should_use_zentorch_sdpa,
zentorch_sdpa_attn,
)
if not current_platform.is_cpu():
pytest.skip("skipping CPU-only tests", allow_module_level=True)
@@ -47,6 +54,24 @@ _FP8_RTOL = 0.1
ENCODER_SEQ_LENS = [
[1, 678, 2367, 145, 4162, 36, 7812],
]
# Uniform (dense zentorch_sdpa call) and ragged (per-sequence loop).
ZEN_ENCODER_SEQ_LENS = [
[128, 128, 128],
[1, 67, 233, 5],
]
_skip_no_zentorch_sdpa = pytest.mark.skipif(
not current_platform.is_zen_cpu() or not has_zentorch_op(["zentorch_sdpa_attn"]),
reason="zentorch_sdpa requires a Zen CPU with the op registered",
)
# should_use_zentorch_sdpa additionally gates each dtype on its ISA.
_skip_no_avx512_bf16 = pytest.mark.skipif(
not torch.cpu._is_avx512_bf16_supported(),
reason="zentorch_sdpa bfloat16 requires AVX512-BF16",
)
_skip_no_avx512 = pytest.mark.skipif(
not torch.cpu._is_avx512_supported(),
reason="zentorch_sdpa float32 requires AVX512",
)
def get_attn_isa(
@@ -205,6 +230,7 @@ def ref_varlen_encoder_attn(
seq_lens: list[int],
scale: float,
sliding_window: int | None = None,
alibi_slopes: torch.Tensor | None = None,
) -> torch.Tensor:
num_seqs = len(seq_lens)
dtype = query.dtype
@@ -232,6 +258,11 @@ def ref_varlen_encoder_attn(
else:
mask = empty_mask.logical_not()
if alibi_slopes is not None:
q_pos = torch.arange(0, seq_len)[None, :, None]
kv_pos = torch.arange(0, seq_len)[None, None, :]
attn += -alibi_slopes[:, None, None].float() * (q_pos - kv_pos)
attn.masked_fill_(mask, float("-inf"))
attn = torch.softmax(attn, dim=-1)
out = torch.einsum("hqk,khd->qhd", attn, v).to(dtype=dtype)
@@ -428,6 +459,7 @@ def varlen_with_paged_kv(
k_scale: float = 1.0,
v_scale: float = 1.0,
dynamic_causal: list[bool] | None = None,
s_aux_dtype: torch.dtype = torch.bfloat16,
) -> None:
set_random_seed(0)
num_seqs = len(seq_lens)
@@ -449,9 +481,7 @@ def varlen_with_paged_kv(
# 2^(-8/n)
alibi_slopes = _get_alibi_slopes(num_query_heads) if use_alibi else None
s_aux = (
15 * torch.rand((num_query_heads,), dtype=torch.bfloat16) if use_sink else None
)
s_aux = 15 * torch.rand((num_query_heads,), dtype=s_aux_dtype) if use_sink else None
is_fp8 = kv_cache_dtype != "auto"
if is_fp8 and current_platform.get_cpu_architecture() != CpuArchEnum.X86:
@@ -538,6 +568,8 @@ def varlen_with_paged_kv(
)
out_without_split = torch.empty_like(query)
if s_aux is not None and s_aux.dtype != torch.bfloat16:
s_aux = s_aux.to(torch.float32)
cpu_attention_with_kv_cache(
query=query,
key_cache=packed_key_cache,
@@ -771,6 +803,108 @@ def test_varlen_encoder_attention_amx(
)
@torch.inference_mode()
def varlen_encoder_zentorch_sdpa(
seq_lens: list[int],
num_heads: tuple[int, int],
head_size: int,
sliding_window: int | None,
dtype: torch.dtype,
use_alibi: bool,
) -> None:
set_random_seed(0)
num_query_heads, num_kv_heads = num_heads
assert num_query_heads % num_kv_heads == 0
scale = head_size**-0.5
token_num = sum(seq_lens)
query = tensor_cache(
token_num * num_query_heads * head_size, dtype, tag="query"
).view(token_num, num_query_heads, head_size)
key_value = tensor_cache(
2 * token_num * num_kv_heads * head_size, dtype, tag="kv"
).view(2, token_num, num_kv_heads, head_size)
key, value = key_value.unbind(0)
query_start_loc = torch.zeros(len(seq_lens) + 1, dtype=torch.int32)
torch.cumsum(torch.tensor(seq_lens, dtype=torch.int32), 0, out=query_start_loc[1:])
alibi_slopes = _get_alibi_slopes(num_query_heads) if use_alibi else None
output = torch.empty_like(query)
zentorch_sdpa_attn(
query,
key,
value,
output,
SimpleNamespace(query_start_loc=query_start_loc, causal=False),
scale,
sliding_window if sliding_window is not None else -1,
alibi_slopes,
)
ref_output = ref_varlen_encoder_attn(
query=query,
key=key,
value=value,
seq_lens=seq_lens,
scale=scale,
sliding_window=sliding_window,
alibi_slopes=alibi_slopes,
)
torch.testing.assert_close(output, ref_output, atol=1.5e-2, rtol=1e-2)
_ZENTORCH_SDPA_DTYPES = [
pytest.param(torch.bfloat16, marks=_skip_no_avx512_bf16),
pytest.param(torch.float32, marks=_skip_no_avx512),
]
@_skip_no_zentorch_sdpa
@pytest.mark.parametrize("seq_lens", ZEN_ENCODER_SEQ_LENS)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@pytest.mark.parametrize("head_size", [128])
@pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS)
@pytest.mark.parametrize("dtype", _ZENTORCH_SDPA_DTYPES)
@pytest.mark.parametrize("use_alibi", [False, True])
def test_zentorch_sdpa_attn(
seq_lens: list[int],
num_heads: tuple[int, int],
head_size: int,
sliding_window: int | None,
dtype: torch.dtype,
use_alibi: bool,
) -> None:
varlen_encoder_zentorch_sdpa(
seq_lens=seq_lens,
num_heads=num_heads,
head_size=head_size,
sliding_window=sliding_window,
dtype=dtype,
use_alibi=use_alibi,
)
@_skip_no_zentorch_sdpa
@pytest.mark.parametrize(
"attn_type", [AttentionType.ENCODER_ONLY, AttentionType.ENCODER]
)
@pytest.mark.parametrize("dtype", _ZENTORCH_SDPA_DTYPES)
def test_should_use_zentorch_sdpa(attn_type: str, dtype: torch.dtype) -> None:
assert should_use_zentorch_sdpa(attn_type, dtype)
@_skip_no_zentorch_sdpa
@pytest.mark.parametrize(
"attn_type,dtype",
[
(AttentionType.DECODER, torch.bfloat16),
(AttentionType.ENCODER_ONLY, torch.float16),
],
)
def test_should_not_use_zentorch_sdpa(attn_type: str, dtype: torch.dtype) -> None:
assert not should_use_zentorch_sdpa(attn_type, dtype)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8_e4m3", "fp8_e5m2"])
@pytest.mark.parametrize("seq_lens", SEQ_LENS)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@@ -1128,6 +1262,51 @@ def test_varlen_with_paged_kv_sink(
)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8_e4m3"])
@pytest.mark.parametrize("seq_lens", SEQ_LENS)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@pytest.mark.parametrize("head_size", [96])
@pytest.mark.parametrize("block_size", [128])
@pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS)
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@pytest.mark.parametrize("soft_cap", [None])
@pytest.mark.parametrize("num_blocks", NUM_BLOCKS)
@pytest.mark.parametrize("use_alibi", [False])
@pytest.mark.parametrize("use_sink", [True])
@pytest.mark.parametrize("isa", [get_attn_isa()])
@pytest.mark.parametrize("s_aux_dtype", [torch.float16])
def test_varlen_with_paged_kv_sink_fp16(
seq_lens: list[tuple[int, int]],
num_heads: tuple[int, int],
head_size: int,
sliding_window: int | None,
dtype: torch.dtype,
block_size: int,
soft_cap: float | None,
num_blocks: int,
use_alibi: bool,
use_sink: bool,
isa: str,
kv_cache_dtype: str,
s_aux_dtype: torch.dtype,
) -> None:
varlen_with_paged_kv(
seq_lens=seq_lens,
num_heads=num_heads,
head_size=head_size,
sliding_window=sliding_window,
dtype=dtype,
block_size=block_size,
soft_cap=soft_cap,
num_blocks=num_blocks,
use_alibi=use_alibi,
use_sink=use_sink,
isa=isa,
kv_cache_dtype=kv_cache_dtype,
s_aux_dtype=s_aux_dtype,
)
@pytest.mark.parametrize(
"kv_cache_dtype",
[
@@ -509,3 +509,334 @@ def test_flashinfer_mixed_sparse_indices_separates_window_and_padded_width():
assert sparse_indices.shape == (1, padded_width)
assert sparse_indices[0].cpu().tolist() == [0, 1, 2, 3, -1, -1, -1, -1]
assert sparse_lens.cpu().tolist() == [padded_width]
def test_flashinfer_mixed_sparse_indices_noncausal_rows_have_no_active_gaps():
"""A DSpark non-causal row keeps -1 out of the kernel's active ranges.
Each draft token's causal window holds its first visible entries, the rest
of the block starts at column `window`, and the compressed entries follow
directly; `sparse_topk_lens` ends right after them.
"""
from vllm.models.deepseek_v4.common.ops.cache_utils import (
build_flashinfer_mixed_sparse_indices,
)
device = torch.device("cuda")
window, width = 4, 8
# One request: 1 context token, a 2-token draft block, slots 0..2 visible.
decode_swa = torch.full((2, width), -1, dtype=torch.int32, device=device)
decode_swa[:, :3] = torch.arange(3, dtype=torch.int32, device=device)
compressed = torch.tensor(
[[100, 101, -1, -1]] * 2, dtype=torch.int32, device=device
)
sparse_indices, sparse_lens = build_flashinfer_mixed_sparse_indices(
decode_swa_indices=decode_swa,
decode_compressed_indices=compressed,
decode_compressed_topk_lens=torch.tensor(
[2, 2], dtype=torch.int32, device=device
),
prefill_topk_indices=torch.empty((0, 4), dtype=torch.int32, device=device),
query_start_loc=torch.tensor([0, 2], dtype=torch.int32, device=device),
seq_lens=torch.tensor([3], dtype=torch.int32, device=device),
token_to_req_indices=torch.tensor([0, 0], dtype=torch.int32, device=device),
swa_block_table=torch.tensor([[0]], dtype=torch.int32, device=device),
swa_block_size=64,
compressed_block_table=torch.tensor([[0]], dtype=torch.int32, device=device),
compressed_block_size=64,
window_size=window,
compress_ratio=128,
topk=0,
)
assert sparse_indices.cpu().tolist() == [
# pos 1: window [0, 1]; slot 2 spills to column 4; compressed after it.
[0, 1, -1, -1, 2, 100, 101, -1, -1, -1, -1, -1],
# pos 2: window [0, 1, 2]; nothing spills; compressed at column 4.
[0, 1, 2, -1, 100, 101, -1, -1, -1, -1, -1, -1],
]
assert sparse_lens.cpu().tolist() == [7, 6]
def test_flashinfer_mixed_sparse_indices_noncausal_pad_rows_keep_min_length():
"""A CUDA-graph pad token of the DSpark graph (a zero-length request) gets
a causal pad row's shape instead of negative spill arithmetic."""
from vllm.models.deepseek_v4.common.ops.cache_utils import (
build_flashinfer_mixed_sparse_indices,
)
device = torch.device("cuda")
window, width = 128, 192
decode_swa = torch.full((3, width), -1, dtype=torch.int32, device=device)
decode_swa[:2, :3] = torch.arange(3, dtype=torch.int32, device=device)
sparse_indices, sparse_lens = build_flashinfer_mixed_sparse_indices(
decode_swa_indices=decode_swa,
decode_compressed_indices=None,
decode_compressed_topk_lens=None,
prefill_topk_indices=torch.empty((0, 0), dtype=torch.int32, device=device),
# Request 1 is the padding: no query tokens, seq_len 0.
query_start_loc=torch.tensor([0, 2, 2], dtype=torch.int32, device=device),
seq_lens=torch.tensor([3, 0], dtype=torch.int32, device=device),
token_to_req_indices=torch.tensor([0, 0, 1], dtype=torch.int32, device=device),
swa_block_table=torch.zeros((2, 1), dtype=torch.int32, device=device),
swa_block_size=64,
compressed_block_table=None,
compressed_block_size=64,
window_size=window,
compress_ratio=1,
topk=0,
)
assert sparse_lens.cpu().tolist() == [129, 128, 128]
assert (sparse_indices[2] == -1).all()
@pytest.mark.parametrize("model", ["deepseek_v4", "deepseek_v41"])
@pytest.mark.parametrize("page_padding", [0, 64])
def test_flashinfer_sparse_forward_reads_packed_kv_rows(model, page_padding):
"""Decode and prefill must read storage rows after vLLM remaps packed pages."""
import importlib
from vllm.platforms import current_platform
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
if not current_platform.is_device_capability_family(100):
pytest.skip("Requires FlashInfer TRTLLM sparse MLA on SM100/SM103")
mod = importlib.import_module(f"vllm.models.{model}.nvidia.flashinfer_sparse")
device = "cuda"
block_size = 64
storage = torch.full(
(3, block_size + page_padding, 512), 99, dtype=torch.bfloat16, device=device
)
cache = storage[:, :block_size]
cache[1].fill_(2)
cache[2].fill_(3)
attn = object.__new__(mod.DeepseekV4FlashInferMLAAttention)
attn.compress_ratio = 1
attn.window_size = 128
attn.scale = 512**-0.5
attn.kv_cache_torch_dtype = torch.bfloat16
attn.attn_sink = torch.full((64,), -float("inf"), device=device)
attn.topk_indices_buffer = torch.empty((3, 0), dtype=torch.int32, device=device)
decode_indices = torch.full((1, 128), -1, dtype=torch.int32, device=device)
decode_indices[0, :4] = torch.arange(64, 68, dtype=torch.int32, device=device)
query_start = torch.tensor([0, 1, 3], dtype=torch.int32)
metadata = DeepseekSparseSWAMetadata(
block_table=torch.tensor([[1], [2]], dtype=torch.int32, device=device),
slot_mapping=torch.tensor([67, 130, 131], device=device),
block_size=block_size,
seq_lens=torch.tensor([4, 4], dtype=torch.int32, device=device),
query_start_loc=query_start.to(device),
query_start_loc_cpu=query_start,
token_to_req_indices=torch.tensor([0, 1, 1], dtype=torch.int32, device=device),
decode_swa_indices=decode_indices,
decode_swa_lens=torch.tensor([4], dtype=torch.int32, device=device),
decode_swa_width=128,
is_valid_token=torch.ones(3, dtype=torch.bool, device=device),
replay_start=torch.zeros(2, dtype=torch.int32, device=device),
num_decodes=1,
num_prefills=1,
num_decode_tokens=1,
num_prefill_tokens=2,
max_decode_query_len=1,
)
query = torch.zeros((3, 64, 512), dtype=torch.bfloat16, device=device)
output = torch.empty_like(query)
attn._forward(query, None, cache, metadata, None, True, output)
expected = torch.tensor([2, 3, 3], dtype=output.dtype, device=device)
torch.testing.assert_close(output, expected[:, None, None].expand_as(output))
def _make_rope_quant_attn(mod, num_rows: int, device: str):
"""A bare DSv4 FlashInfer layer set up for RopeQuant: 128 heads, fp8 KV."""
from types import SimpleNamespace
heads, groups, rank = 128, 16, 256
angles = torch.arange(2048, device=device, dtype=torch.float32)[:, None] * 0.05
angles = angles + torch.arange(32, device=device)[None] * 0.1
attn = object.__new__(mod.DeepseekV4FlashInferMLAAttention)
attn.compress_ratio = 1
attn.window_size = 128
attn.scale = 512**-0.5
attn.kv_cache_torch_dtype = torch.float8_e4m3fn
attn._flashinfer_fp8_bmm1_scale = attn.scale
attn._flashinfer_fp8_bmm2_scale = 1.0
attn.attn_sink = torch.linspace(-1, 1, heads, device=device)
attn.padded_heads = heads
attn.topk_indices_buffer = torch.empty(
(num_rows, 0), dtype=torch.int32, device=device
)
attn.rotary_emb = SimpleNamespace(
cos_sin_cache=torch.cat((angles.cos(), angles.sin()), -1).contiguous()
)
attn.n_local_heads, attn.n_local_groups, attn.o_lora_rank = heads, groups, rank
attn.nope_head_dim, attn.rope_head_dim = 448, 64
attn._einsum_recipe, attn._tma_aligned_scales = (1, 1, 128), True
attn.wo_a = SimpleNamespace(
weight=(torch.randn((groups, rank, 4096), device=device) * 0.05).to(
torch.float8_e4m3fn
),
weight_scale=torch.ones((groups, rank, 32), device=device),
)
attn.wo_b = lambda z: z
return attn
def _rope_quant_vs_unfused(attn, q, cache, metadata, positions, num_tokens):
"""Run `_forward` unfused and fused; return (bf16 attention, z_unfused, z_fused)."""
from vllm.models.deepseek_v4.nvidia.ops.o_proj import rope_quant_attn_out
heads, groups = attn.n_local_heads, attn.n_local_groups
unfused = torch.empty(q.shape, dtype=torch.bfloat16, device=q.device)
attn._forward(q, None, cache, metadata, None, True, unfused)
fused = rope_quant_attn_out(q.shape[0], q.device)
metadata.flashinfer_sparse_index_cache.clear()
attn._forward(q, None, cache, metadata, None, True, fused)
z_unfused = attn._o_proj(unfused[:num_tokens, :heads], positions)
z_fused = attn._o_proj(fused, positions)[:num_tokens]
return unfused[:num_tokens], z_unfused, z_fused.view(num_tokens, groups, -1)
def _assert_projects_alike(z_unfused, z_fused):
z_unfused = z_unfused.float().view_as(z_fused)
rel = (z_fused.float() - z_unfused).norm() / z_unfused.norm()
assert rel < 2e-2, rel
def _skip_unless_rope_quant():
from vllm.platforms import current_platform
if not current_platform.is_device_capability_family(100):
pytest.skip("Requires FlashInfer TRTLLM sparse MLA on SM100/SM103")
def test_flashinfer_rope_quant_matches_unfused_o_proj():
"""RopeQuant's fused output must project like the bf16 + inv-RoPE/quant path.
One mixed step (two decodes, a three-token prefill) plus CUDA-graph pad rows,
so both calls run over the full buffer with un-rebased cum_seq_lens_q.
"""
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse as mod
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
_skip_unless_rope_quant()
torch.manual_seed(0)
device = "cuda"
block_size = 64
q_lens, seq_lens = [1, 1, 3], [5, 9, 70]
num_tokens, num_rows = sum(q_lens), sum(q_lens) + 3
cache = torch.randn((3, block_size, 512), device=device).to(torch.float8_e4m3fn)
attn = _make_rope_quant_attn(mod, num_rows, device)
decode_indices = torch.full((2, 128), -1, dtype=torch.int32, device=device)
for i, seq_len in enumerate(seq_lens[:2]):
decode_indices[i, :seq_len] = torch.arange(
i * block_size, i * block_size + seq_len, device=device
)
query_start = torch.tensor([0, 1, 2, 5], dtype=torch.int32)
metadata = DeepseekSparseSWAMetadata(
block_table=torch.tensor([[0], [1], [2]], dtype=torch.int32, device=device),
slot_mapping=torch.zeros(num_tokens, dtype=torch.int64, device=device),
block_size=block_size,
seq_lens=torch.tensor(seq_lens, dtype=torch.int32, device=device),
query_start_loc=query_start.to(device),
query_start_loc_cpu=query_start,
token_to_req_indices=torch.tensor(
[0, 1, 2, 2, 2], dtype=torch.int32, device=device
),
decode_swa_indices=decode_indices,
decode_swa_lens=torch.tensor(seq_lens[:2], dtype=torch.int32, device=device),
decode_swa_width=128,
is_valid_token=torch.ones(num_tokens, dtype=torch.bool, device=device),
num_decodes=2,
num_prefills=1,
num_decode_tokens=2,
num_prefill_tokens=3,
max_decode_query_len=1,
)
positions = torch.tensor([4, 8, 67, 68, 69], device=device)
q = torch.randn((num_rows, 128, 512), device=device).to(torch.float8_e4m3fn)
_, z_unfused, z_fused = _rope_quant_vs_unfused(
attn, q, cache, metadata, positions, num_tokens
)
_assert_projects_alike(z_unfused, z_fused)
@pytest.mark.parametrize("context_len", [0, 20, 127, 900])
def test_flashinfer_dspark_noncausal_block_sees_future_tokens(context_len):
"""Every DSpark draft token attends to the whole block, fused or not.
The kernel counts every entry of its active index ranges as a key, so the
builder must place the block around each query's causal window without -1
gaps, down to an empty context.
"""
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse as mod
from vllm.v1.attention.backends.mla.compressor_utils import (
get_dspark_swa_index_width,
)
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
_skip_unless_rope_quant()
torch.manual_seed(0)
device = "cuda"
block_size, window, draft = 64, 128, 4
width = get_dspark_swa_index_width(window, draft)
contexts = [context_len, context_len + 37]
num_reqs, num_tokens = len(contexts), len(contexts) * draft
num_rows = num_tokens + 2
pages = -(-(max(contexts) + draft) // block_size)
cache = torch.randn((num_reqs * pages, block_size, 512), device=device)
cache = cache.clamp_(-1, 1).to(torch.float8_e4m3fn)
attn = _make_rope_quant_attn(mod, num_rows, device)
attn.attn_sink = torch.full((128,), -float("inf"), device=device)
# As the DSpark SWA builder lays them out: the trailing window of context
# and the whole block, contiguous from column 0.
decode_indices = torch.full((num_tokens, width), -1, dtype=torch.int32)
visible, positions = [], []
for r, ctx in enumerate(contexts):
slots = torch.arange(max(ctx - window, 0), ctx + draft) + r * pages * block_size
for k in range(draft):
decode_indices[r * draft + k, : slots.numel()] = slots.to(torch.int32)
visible.append(slots)
positions.append(ctx + k)
query_start = torch.arange(0, num_tokens + 1, draft, dtype=torch.int32)
seq_lens = torch.tensor([c + draft for c in contexts], dtype=torch.int32)
metadata = DeepseekSparseSWAMetadata(
block_table=torch.arange(
num_reqs * pages, dtype=torch.int32, device=device
).view(num_reqs, pages),
slot_mapping=torch.zeros(num_tokens, dtype=torch.int64, device=device),
block_size=block_size,
seq_lens=seq_lens.to(device),
query_start_loc=query_start.to(device),
query_start_loc_cpu=query_start,
token_to_req_indices=torch.arange(
num_reqs, dtype=torch.int32, device=device
).repeat_interleave(draft),
decode_swa_indices=decode_indices.to(device),
decode_swa_lens=torch.tensor(
[v.numel() for v in visible], dtype=torch.int32, device=device
),
decode_swa_width=width,
is_valid_token=torch.ones(num_tokens, dtype=torch.bool, device=device),
num_decodes=num_reqs,
num_prefills=0,
num_decode_tokens=num_tokens,
num_prefill_tokens=0,
max_decode_query_len=draft,
)
q = torch.randn((num_rows, 128, 512), device=device).clamp_(-1, 1)
q = q.to(torch.float8_e4m3fn)
attention, z_unfused, z_fused = _rope_quant_vs_unfused(
attn, q, cache, metadata, torch.tensor(positions, device=device), num_tokens
)
keys_all = cache.flatten(0, 1).float()
for token, slots in enumerate(visible):
keys = keys_all[slots.to(device)]
weights = torch.softmax(q[token].float() @ keys.T * attn.scale, -1)
torch.testing.assert_close(
attention[token].float(), weights @ keys, atol=0.05, rtol=0.05
)
_assert_projects_alike(z_unfused, z_fused)
@@ -1,73 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.config import AttentionConfig, VllmConfig, set_current_vllm_config
from vllm.platforms.rocm import RocmPlatform
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.attention.selector import _cached_get_attn_backend, get_attn_backend
@pytest.fixture(autouse=True)
def clear_cache():
"""Clear lru cache to ensure each test case runs without caching."""
_cached_get_attn_backend.cache_clear()
@pytest.mark.skip(reason="Skipped for now. Should be revisited.")
def test_selector(monkeypatch: pytest.MonkeyPatch):
# Set the current platform to ROCm using monkeypatch
monkeypatch.setattr("vllm.v1.attention.selector.current_platform", RocmPlatform())
# Test standard ROCm attention
attention_config = AttentionConfig(backend=AttentionBackendEnum.ROCM_ATTN)
vllm_config = VllmConfig(attention_config=attention_config)
with set_current_vllm_config(vllm_config):
backend = get_attn_backend(16, torch.float16, torch.float16, 16, False)
assert backend.get_name() == "ROCM_FLASH" or backend.get_name() == "TRITON_ATTN"
# MLA test for deepseek related
# Change the attention backend to triton MLA
attention_config = AttentionConfig(backend=AttentionBackendEnum.TRITON_MLA)
vllm_config = VllmConfig(attention_config=attention_config)
with set_current_vllm_config(vllm_config):
backend = get_attn_backend(576, torch.bfloat16, "auto", 16, False, use_mla=True)
assert backend.get_name() == "TRITON_MLA"
# If attention backend is None
# If use_mla is true
# The selected backend is triton MLA
attention_config = AttentionConfig(backend=None)
vllm_config = VllmConfig(attention_config=attention_config)
with set_current_vllm_config(vllm_config):
backend = get_attn_backend(576, torch.bfloat16, "auto", 16, False, use_mla=True)
assert backend.get_name() == "TRITON_MLA"
# Change the attention backend to AITER MLA
attention_config = AttentionConfig(backend=AttentionBackendEnum.ROCM_AITER_MLA)
vllm_config = VllmConfig(attention_config=attention_config)
with set_current_vllm_config(vllm_config):
backend = get_attn_backend(576, torch.bfloat16, "auto", 1, False, use_mla=True)
assert backend.get_name() == "ROCM_AITER_MLA"
# If attention backend is None
# If use_mla is true
# If VLLM_ROCM_USE_AITER is enabled
# The selected backend is ROCM_AITER_MLA
with monkeypatch.context() as m:
m.setenv("VLLM_ROCM_USE_AITER", "1")
attention_config = AttentionConfig(backend=None)
vllm_config = VllmConfig(attention_config=attention_config)
with set_current_vllm_config(vllm_config):
backend = get_attn_backend(
576, torch.bfloat16, "auto", 1, False, use_mla=True
)
assert backend.get_name() == "ROCM_AITER_MLA"
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
from types import SimpleNamespace
import pytest
@@ -51,6 +52,65 @@ ROPE_HEAD_DIM = 64
HEAD_DIM = NOPE_HEAD_DIM + ROPE_HEAD_DIM
@pytest.fixture
def enable_aiter_mqa(monkeypatch):
from vllm._aiter_ops import rocm_aiter_ops
with monkeypatch.context() as context:
context.setenv("VLLM_ROCM_USE_AITER", "1")
rocm_aiter_ops.refresh_env_variables()
yield
rocm_aiter_ops.refresh_env_variables()
@requires_gfx950
@pytest.mark.parametrize("column_scales", [False, True], ids=["vector", "column"])
@torch.inference_mode()
def test_unpaged_mqa_logits_preserves_intervals_and_scale_layout(
column_scales, monkeypatch, enable_aiter_mqa
) -> None:
"""The vLLM AITER dispatch preserves ragged masking and per-token scales."""
from vllm._aiter_ops import rocm_aiter_ops
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod
assert rocm_aiter_ops.is_enabled(), "AITER is required on gfx950"
assert mod.mqa_logits_module() is not None, "AITER MQA logits are required"
torch.manual_seed(42)
device = torch.device("cuda")
dtype = current_platform.fp8_dtype()
q = torch.randn(7, 32, 128, device=device).to(dtype)
k = torch.randn(259, 128, device=device).to(dtype)
scales = torch.linspace(0.25, 1.25, k.shape[0], device=device)
if column_scales:
scales = scales[:, None]
weights = torch.rand(q.shape[:2], device=device) / q.shape[1]
starts = torch.tensor([0, 3, 128, 5, 0, 257, 259], device=device, dtype=torch.int32)
ends = torch.tensor(
[1, 129, 259, 5, 259, 259, 259], device=device, dtype=torch.int32
)
module = mod.mqa_logits_module()
implementation = module.fp8_mqa_logits
calls = 0
def traced_implementation(*args, **kwargs):
nonlocal calls
calls += 1
return implementation(*args, **kwargs)
monkeypatch.setattr(module, "fp8_mqa_logits", traced_implementation)
actual = mod.rocm_fp8_mqa_logits(q, (k, scales), weights, starts, ends)
assert calls == 1
score = torch.einsum("mhd,nd->mhn", q.float(), k.float()) * scales.reshape(-1)
expected = (score.relu() * weights[..., None]).sum(dim=1)
positions = torch.arange(k.shape[0], device=device)
valid = (positions >= starts[:, None]) & (positions < ends[:, None])
assert actual.shape == expected.shape
assert actual.dtype == torch.float32
assert torch.equal(torch.isneginf(actual), ~valid)
torch.testing.assert_close(actual[valid], expected[valid], rtol=1e-3, atol=1e-3)
def _ref_global_topk_ragged(
topk_indices: torch.Tensor,
token_to_req_indices: torch.Tensor,
@@ -259,13 +319,21 @@ def _launch_sparse_decode_reduce(
part_l: torch.Tensor,
part_acc: torch.Tensor,
adaptive_splits: bool,
positions: torch.Tensor | None = None,
cos_sin_cache: torch.Tensor | None = None,
out_dtype: torch.dtype = torch.bfloat16,
out_scale: torch.Tensor | None = None,
) -> torch.Tensor:
"""Run the reduce kernel, with the inverse-RoPE epilogue if given positions.
Passing ``out_scale`` selects the MXFP8 epilogue (``out_dtype`` e4m3).
"""
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod
num_queries, num_splits, num_heads = part_m.shape
out = torch.empty(
(num_queries, num_heads, HEAD_DIM),
dtype=torch.bfloat16,
dtype=out_dtype,
device=part_m.device,
)
attn_sink = torch.empty(1, dtype=torch.float32, device=part_m.device)
@@ -275,13 +343,19 @@ def _launch_sparse_decode_reduce(
part_acc,
attn_sink,
out,
positions,
cos_sin_cache,
out_scale,
out.stride(0),
out.stride(1),
out_scale.stride(0) if out_scale is not None else 0,
HEAD_DIM // 32,
part_m.stride(0),
part_m.stride(1),
part_acc.stride(0),
part_acc.stride(1),
part_acc.stride(2),
cos_sin_cache.stride(0) if cos_sin_cache is not None else 0,
num_heads,
HAS_ATTN_SINK=False,
ADAPTIVE_SPLITS=adaptive_splits,
@@ -289,6 +363,10 @@ def _launch_sparse_decode_reduce(
BLOCK_H=1,
NUM_SPLITS=num_splits,
SPLITS_PAD=1 << (num_splits - 1).bit_length(),
FUSE_INV_ROPE=positions is not None,
NOPE=NOPE_HEAD_DIM,
HALF=ROPE_HEAD_DIM // 2,
QUANT_OUT=out_scale is not None,
num_warps=4,
)
return out
@@ -1008,6 +1086,224 @@ def test_sparse_attn_decode_gfx950_adaptive_reduce_ignores_stale_scratch() -> No
assert torch.equal(actual, torch.full_like(actual, 2))
@requires_gfx950
@pytest.mark.parametrize("adaptive_splits", [False, True])
@torch.inference_mode()
def test_sparse_attn_decode_reduce_inverse_rope_epilogue(adaptive_splits: bool) -> None:
"""FUSE_INV_ROPE must land where the standalone rotation would.
The epilogue rotates a whole [H, nope + rope] row with one expression by
feeding cos=1/sin=0 to the NoPE lanes, which only holds if the pair split
lands on ``nope_head_dim // 2``; the NoPE lanes therefore have to come
back untouched, not merely close.
"""
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _fused_inverse_rope_gptj
device = torch.device("cuda")
torch.manual_seed(7)
num_queries, num_splits, num_heads, max_pos = 5, 4, 8, 64
shape = (num_queries, num_splits, num_heads)
part_m = torch.randn(shape, dtype=torch.float32, device=device)
part_l = torch.rand(shape, dtype=torch.float32, device=device) + 0.5
part_acc = torch.randn((*shape, HEAD_DIM), dtype=torch.float32, device=device)
positions = torch.randint(
0, max_pos, (num_queries,), dtype=torch.int64, device=device
)
angle = torch.randn(max_pos, ROPE_HEAD_DIM // 2, device=device)
cos_sin_cache = torch.cat((angle.cos(), angle.sin()), dim=-1).contiguous()
unfused = _launch_sparse_decode_reduce(part_m, part_l, part_acc, adaptive_splits)
expected = _fused_inverse_rope_gptj(
unfused, positions, cos_sin_cache, ROPE_HEAD_DIM
)
actual = _launch_sparse_decode_reduce(
part_m, part_l, part_acc, adaptive_splits, positions, cos_sin_cache
)
torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2)
assert torch.equal(actual[..., :NOPE_HEAD_DIM], unfused[..., :NOPE_HEAD_DIM])
# An epilogue that quietly did nothing would satisfy everything above.
assert not torch.equal(actual[..., NOPE_HEAD_DIM:], unfused[..., NOPE_HEAD_DIM:])
def _mxfp8_dequant(data: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
blocks = data.float().view(*data.shape[:-1], -1, 32)
return (blocks * torch.exp2(scale.float() - 127.0)[..., None]).view(data.shape)
def _random_cos_sin_cache(max_pos: int, device: torch.device) -> torch.Tensor:
angle = torch.randn(max_pos, ROPE_HEAD_DIM // 2, device=device)
return torch.cat((angle.cos(), angle.sin()), dim=-1).contiguous()
@requires_gfx950
@torch.inference_mode()
def test_sparse_attn_decode_reduce_mxfp8_epilogue() -> None:
"""QUANT_OUT must equal MXFP8-quantizing the reduce's fp32 output."""
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
_mxfp8_e4m3_quantize_torch,
)
device = torch.device("cuda")
torch.manual_seed(7)
num_queries, num_splits, num_heads = 5, 4, 8
shape = (num_queries, num_splits, num_heads)
part_m = torch.randn(shape, device=device)
part_l = torch.rand(shape, device=device) + 0.5
part_acc = torch.randn((*shape, HEAD_DIM), device=device)
positions = torch.randint(0, 64, (num_queries,), device=device)
cos_sin_cache = _random_cos_sin_cache(64, device)
args = (part_m, part_l, part_acc, False, positions, cos_sin_cache)
rotated = _launch_sparse_decode_reduce(*args, out_dtype=torch.float32)
expected_data, expected_scale = _mxfp8_e4m3_quantize_torch(
rotated.view(num_queries, -1)
)
scale = torch.empty_like(expected_scale)
data = _launch_sparse_decode_reduce(
*args, out_dtype=torch.float8_e4m3fn, out_scale=scale
)
assert torch.equal(scale, expected_scale)
assert torch.equal(
data.view(num_queries, -1).view(torch.uint8), expected_data.view(torch.uint8)
)
@requires_gfx950
@torch.inference_mode()
def test_inverse_rope_mxfp8_rows() -> None:
"""Prefill rows get the same inverse RoPE + MXFP8 as the decode epilogue."""
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
_mxfp8_e4m3_quantize_torch,
)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_inverse_rope_mxfp8_rows,
)
device = torch.device("cuda")
torch.manual_seed(5)
num_tokens, num_heads = 7, 4
o = torch.randn(num_tokens, num_heads, HEAD_DIM, device=device).bfloat16()
positions = torch.randint(0, 64, (num_tokens,), device=device)
cos_sin_cache = _random_cos_sin_cache(64, device)
ref = o.float()
cos, sin = cos_sin_cache[positions, None].chunk(2, dim=-1)
even, odd = ref[..., NOPE_HEAD_DIM::2].clone(), ref[..., NOPE_HEAD_DIM + 1 :: 2]
ref[..., NOPE_HEAD_DIM::2] = even * cos + odd * sin
ref[..., NOPE_HEAD_DIM + 1 :: 2] = odd * cos - even * sin
ref = ref.view(num_tokens, -1)
_, expected_scale = _mxfp8_e4m3_quantize_torch(ref)
data = torch.empty_like(ref, dtype=torch.float8_e4m3fn)
scale = torch.empty_like(expected_scale)
rocm_inverse_rope_mxfp8_rows(
o, positions, cos_sin_cache, ROPE_HEAD_DIM, data, scale
)
assert torch.equal(scale, expected_scale)
# Within half an e4m3 step at the top of each block's range.
half_step = 16.0 * torch.exp2(scale.float() - 127.0).repeat_interleave(32, -1)
assert bool(((_mxfp8_dequant(data, scale) - ref).abs() <= half_step).all())
@requires_gfx950
@torch.inference_mode()
def test_sparse_attn_decode_mxfp8_output() -> None:
"""``out_mxfp8`` routes the real decode through the MXFP8 epilogue."""
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_rocm_sparse_attn_decode_ragged_triton,
)
device = torch.device("cuda")
torch.manual_seed(1)
num_heads = 16
q = torch.randn(2, num_heads, HEAD_DIM, device=device).bfloat16() * 0.125
kv = torch.randn(6, HEAD_DIM, device=device).bfloat16() * 0.125
decode = functools.partial(
_rocm_sparse_attn_decode_ragged_triton,
q=q,
main_cache=_pack_fp8_ds_mla_cache(kv, 4, current_platform.is_fp8_fnuz()),
main_indices=torch.tensor([0, 2, 4, 1], dtype=torch.int32, device=device),
main_indptr=torch.tensor([0, 2, 4], dtype=torch.int32, device=device),
scale=HEAD_DIM**-0.5,
attn_sink=None,
nope_head_dim=NOPE_HEAD_DIM,
rope_head_dim=ROPE_HEAD_DIM,
inv_rope_positions=torch.tensor([3, 9], device=device),
inv_rope_cos_sin_cache=_random_cos_sin_cache(16, device),
)
expected = decode().float().view(2, -1)
data = torch.empty(
2, num_heads * HEAD_DIM, dtype=torch.float8_e4m3fn, device=device
)
scale = torch.empty(2, num_heads * HEAD_DIM // 32, dtype=torch.uint8, device=device)
decode(out_mxfp8=(data, scale))
torch.testing.assert_close(
_mxfp8_dequant(data, scale), expected, atol=1e-3, rtol=2**-4
)
@requires_gfx950
@pytest.mark.parametrize(
"num_tokens, n_groups",
# One case per tile tier of _mxfp8_wo_a_bmm_config, with partial M tiles.
[
(1, 4),
(20, 4),
(48, 4),
(77, 4),
(130, 4),
(300, 4),
(700, 4),
(1000, 4),
(1100, 8),
],
)
@pytest.mark.parametrize("block_scales", [False, True])
@torch.inference_mode()
def test_rocm_mxfp8_wo_a_bmm(
num_tokens: int, n_groups: int, block_scales: bool
) -> None:
from vllm.model_executor.kernels.linear.mxfp8.rocm_native import (
_as_block32_scale,
)
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
_mxfp8_e4m3_quantize_torch,
)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import rocm_mxfp8_wo_a_bmm
device = torch.device("cuda")
torch.manual_seed(3)
o_lora_rank, group_dim = 128, 2048
a, a_scale = _mxfp8_e4m3_quantize_torch(
torch.randn(num_tokens, n_groups * group_dim, device=device)
)
w, w_scale = _mxfp8_e4m3_quantize_torch(
torch.randn(n_groups * o_lora_rank, group_dim, device=device)
)
if block_scales:
# A 32x32 checkpoint loads as per-row scales that repeat every 32 rows;
# RocmDotScaledMxfp8LinearKernel compacts them before wo_a sees them.
w_scale = _as_block32_scale(w_scale[::32].repeat_interleave(32, dim=0))
assert w_scale is not None
wo_a = SimpleNamespace(weight=w, weight_scale=w_scale)
out = rocm_mxfp8_wo_a_bmm(a, a_scale, wo_a, n_groups, o_lora_rank)
expected = torch.einsum(
"tgd,grd->tgr",
_mxfp8_dequant(a, a_scale).view(num_tokens, n_groups, group_dim),
_mxfp8_dequant(
w, w_scale.repeat_interleave(w.shape[0] // w_scale.shape[0], 0)
).view(n_groups, o_lora_rank, group_dim),
)
torch.testing.assert_close(out.float(), expected.flatten(1), atol=5e-2, rtol=1e-2)
@requires_gfx950
@pytest.mark.parametrize("extra_len", [0, 1, 31, 32, 33, 63, 64, 65])
@torch.inference_mode()
@@ -5,6 +5,7 @@ import pytest
import torch
import torch.nn.functional as F
import vllm.v1.attention.ops.triton_prefill_attention as prefill_ops
from vllm.platforms import current_platform
from vllm.v1.attention.ops.triton_prefill_attention import context_attention_fwd
@@ -230,3 +231,87 @@ def test_context_attention_sliding_window(
# Compare outputs
torch.testing.assert_close(o, o_ref, rtol=2e-2, atol=2e-2)
class _LaunchCapture:
"""Records the launch configuration in place of ``_fwd_kernel``."""
grid: tuple
kwargs: dict
def __getitem__(self, grid):
self.grid = grid
return self._record
def _record(self, *args, **kwargs) -> None:
self.kwargs = kwargs
def _capture_tile_config(
monkeypatch, *, is_rocm: bool, on_gfx1x: bool, dtype=torch.bfloat16
) -> _LaunchCapture:
"""Capture the tile configuration with the platform predicates mocked.
Both tile widths are numerically correct, so the tests above pass whichever
one is selected. This needs no RDNA part and allocates no device memory, so
it covers the RDNA branch on the CDNA and NVIDIA agents CI actually runs.
"""
platform = prefill_ops.current_platform
monkeypatch.setattr(platform, "is_rocm", lambda: is_rocm)
# Every device this kernel targets is cuda-alike at capability 80 or better,
# so the stock tile is 128 for 16-bit dtypes.
monkeypatch.setattr(platform, "is_cuda_alike", lambda: True)
monkeypatch.setattr(platform, "has_device_capability", lambda *a, **k: True)
if is_rocm:
import vllm.platforms.rocm as rocm_platform
monkeypatch.setattr(rocm_platform, "on_gfx1x", lambda: on_gfx1x)
capture = _LaunchCapture()
monkeypatch.setattr(prefill_ops, "_fwd_kernel", capture)
def meta(*shape):
return torch.empty(shape, dtype=dtype, device="meta")
seq_lens = torch.empty(2, dtype=torch.int32, device="meta")
context_attention_fwd(
meta(256, 8, 128),
meta(256, 2, 128),
meta(256, 2, 128),
meta(256, 8, 128),
seq_lens,
seq_lens,
128,
)
return capture
@pytest.mark.parametrize(
("is_rocm", "on_gfx1x", "dtype", "expected_block_n"),
[
pytest.param(True, True, torch.bfloat16, 32, id="rdna"),
# on_gfx1x() is what excludes gfx10xx, CDNA and gfx1250.
pytest.param(True, False, torch.bfloat16, 128, id="rocm-not-rdna"),
pytest.param(False, False, torch.bfloat16, 128, id="not-rocm"),
# get_block_size already returns 32 here, so min() must not widen it.
pytest.param(True, True, torch.float32, 32, id="rdna-float32"),
],
)
def test_kv_tile_width_is_gated_by_platform(
monkeypatch, is_rocm: bool, on_gfx1x: bool, dtype, expected_block_n: int
) -> None:
capture = _capture_tile_config(
monkeypatch, is_rocm=is_rocm, on_gfx1x=on_gfx1x, dtype=dtype
)
assert capture.kwargs["BLOCK_N"] == expected_block_n
def test_rdna_narrows_the_kv_tile_and_nothing_else(monkeypatch) -> None:
with monkeypatch.context() as m:
tuned = _capture_tile_config(m, is_rocm=True, on_gfx1x=True)
with monkeypatch.context() as m:
stock = _capture_tile_config(m, is_rocm=True, on_gfx1x=False)
assert tuned.kwargs.pop("BLOCK_N") != stock.kwargs.pop("BLOCK_N")
assert tuned.kwargs == stock.kwargs
assert tuned.grid == stock.grid
@@ -10,6 +10,7 @@ from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import next_power_of_2
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.attention.ops.triton_attention_helpers import (
apply_softcap,
compute_tile_loop_bounds,
)
from vllm.v1.attention.ops.triton_unified_attention import unified_attention
@@ -899,3 +900,40 @@ def test_triton_unified_attn_use_td_tile_clamp(
soft_cap=None,
seq_threshold_3D=0,
)
@triton.jit
def _softcap_probe_kernel(
scores_ptr,
out_ptr,
numel,
soft_cap,
BLOCK: tl.constexpr,
):
offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
mask = offs < numel
scores = tl.load(scores_ptr + offs, mask=mask, other=0.0)
tl.store(out_ptr + offs, apply_softcap(scores, soft_cap), mask=mask)
@torch.inference_mode()
def test_softcap_does_not_overflow_on_large_scores() -> None:
"""Scores above ~88 * soft_cap must not overflow to inf/NaN.
The exp-based softcap computes ``(exp(y) - exp(-y)) / (exp(y) + exp(-y))``
with ``y = S / soft_cap``. For ``|y| > ~88`` the exponentials overflow to
``inf`` and the ratio becomes ``inf / inf = NaN``, poisoning the whole
attention row. Gemma-2 style models use ``attn_logit_softcapping = 50``,
so scores above 4400 are in range for their large attention logits.
"""
soft_cap = 50.0
scores = torch.tensor(
[1.0, 100.0, 1000.0, 3000.0, 5000.0, 10000.0, -1.0, -10000.0, 4400.0],
device=DEVICE_TYPE,
dtype=torch.float32,
)
out = torch.empty_like(scores)
_softcap_probe_kernel[(1,)](scores, out, scores.numel(), soft_cap, BLOCK=16)
ref = soft_cap * torch.tanh(scores / soft_cap)
assert torch.isfinite(out).all(), out
torch.testing.assert_close(out, ref, atol=1e-3, rtol=1e-3)
+48 -7
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import random
from unittest.mock import patch
import pytest
import torch
@@ -236,6 +237,10 @@ def test_swiglu_limit_func_without_routing_uses_output_buffer() -> None:
torch.testing.assert_close(output, expected, atol=2e-2, rtol=2e-2)
@pytest.mark.parametrize(
("alpha", "beta"),
[(1.0, 0.0), (1.702, 0.0), (1.0, 1.0)],
)
@pytest.mark.parametrize("swiglu_limit", SWIGLU_LIMITS)
@pytest.mark.parametrize("num_tokens", NUM_TOKENS)
@pytest.mark.parametrize("d", D)
@@ -245,6 +250,8 @@ def test_swiglu_limit_func_without_routing_uses_output_buffer() -> None:
@torch.inference_mode()
def test_silu_and_mul_with_clamp(
default_vllm_config,
alpha: float,
beta: float,
swiglu_limit: float,
num_tokens: int,
d: int,
@@ -258,8 +265,38 @@ def test_silu_and_mul_with_clamp(
# Use large values to ensure clamping is exercised.
x = torch.randn(num_tokens, 2 * d, dtype=dtype) * swiglu_limit * 2
layer = SiluAndMulWithClamp(swiglu_limit, compile_native=False)
out = layer(x)
default_vllm_config.compilation_config.custom_ops = [
"none",
"+silu_and_mul_with_clamp",
]
layer = SiluAndMulWithClamp(
swiglu_limit,
alpha=alpha,
beta=beta,
compile_native=False,
)
if current_platform.is_rocm():
# forward_hip is always dispatched; the alpha/beta gate is checked
# inside it at call time rather than picked at construction time, so
# verify the actual routing by spying on the two candidate methods.
assert layer._forward_method == layer.forward_hip
with (
patch.object(layer, "forward_cuda", wraps=layer.forward_cuda) as cuda_spy,
patch.object(
layer, "forward_native", wraps=layer.forward_native
) as native_spy,
):
out = layer(x)
if alpha == 1.0 and beta == 0.0:
cuda_spy.assert_called_once()
native_spy.assert_not_called()
else:
native_spy.assert_called_once()
cuda_spy.assert_not_called()
else:
assert layer._forward_method == layer.forward_cuda
out = layer(x)
ref_out = layer.forward_native(x)
rtol = {
@@ -273,10 +310,11 @@ def test_silu_and_mul_with_clamp(
# Verify clamping is actually being applied: the clamped output should
# differ from the unclamped SiluAndMul output when inputs are large.
unclamped_out = SiluAndMul.forward_native(x)
assert not torch.equal(ref_out.float(), unclamped_out.float()), (
"Input was not large enough to exercise the clamp; increase scale"
)
if alpha == 1.0 and beta == 0.0:
unclamped_out = SiluAndMul.forward_native(x)
assert not torch.equal(ref_out.float(), unclamped_out.float()), (
"Input was not large enough to exercise the clamp; increase scale"
)
# Verify gate clamping semantics with a controlled scalar case.
# gate=large_val is clamped to limit first, then silu(limit) * 1.0.
@@ -309,7 +347,10 @@ def test_silu_and_mul_with_clamp(
# opcheck
out_buf = torch.empty(x.shape[:-1] + (d,), dtype=dtype, device=device)
opcheck(torch.ops._C.silu_and_mul_with_clamp, (out_buf, x, swiglu_limit))
opcheck(
torch.ops._C.silu_and_mul_with_clamp,
(out_buf, x, swiglu_limit, layer.alpha, layer.beta),
)
@pytest.mark.parametrize("linear_beta", [-1.0, 2.0])
@@ -184,3 +184,44 @@ def test_rotary_embedding_dispatch(
- forward_cuda/forward methods should call ApplyRotaryEmb.forward()
"""
run_dispatch_test(test_case, device)
@pytest.mark.skipif(not current_platform.is_xpu(), reason="XPU only test.")
@pytest.mark.parametrize(
"num_tokens,num_heads,head_size,rot_dim,is_neox_style",
[
(128, 32, 128, 128, True), # typical text shape
(4096, 16, 80, 80, False), # GPT-J style (interleaved)
(4096, 32, 128, 64, True), # partial rotary (rot_dim < head_size)
],
ids=["text", "gptj_interleaved", "partial_rotary"],
)
def test_apply_rotary_emb_xpu_matches_native(
num_tokens: int,
num_heads: int,
head_size: int,
rot_dim: int,
is_neox_style: bool,
):
"""ApplyRotaryEmb.forward_xpu (vllm_xpu_kernels SYCL op) must match
forward_native (the CustomOp default fallback) exactly."""
from vllm.model_executor.layers.rotary_embedding.common import ApplyRotaryEmb
vllm_config = VllmConfig(
compilation_config=CompilationConfig(custom_ops=["all", "+apply_rotary_emb"])
)
get_cached_compilation_config.cache_clear()
with set_current_vllm_config(vllm_config):
op = ApplyRotaryEmb(enforce_enable=True, is_neox_style=is_neox_style)
x = torch.randn(
num_tokens, num_heads, head_size, device="xpu", dtype=torch.bfloat16
)
x = x[..., :rot_dim].contiguous()
cos = torch.randn(num_tokens, rot_dim // 2, device="xpu", dtype=torch.bfloat16)
sin = torch.randn(num_tokens, rot_dim // 2, device="xpu", dtype=torch.bfloat16)
expected = op.forward_native(x, cos, sin)
actual = op.forward_xpu(x, cos, sin)
torch.testing.assert_close(actual, expected, atol=0, rtol=0)
@@ -223,7 +223,6 @@ def test_shared_query_quant_preserves_projection(
with set_current_vllm_config(
VllmConfig(compilation_config=CompilationConfig(mode=CompilationMode.NONE))
):
kernel = cls(Mxfp8LinearLayerConfig())
# Match the checkpoint's TP4 attention and replicated indexer widths.
if projection == "attention":
linear = ColumnParallelLinear.__new__(ColumnParallelLinear)
@@ -247,6 +246,7 @@ def test_shared_query_quant_preserves_projection(
)
linear.weight = torch.nn.Parameter(w, requires_grad=False)
linear.weight_scale = torch.nn.Parameter(ws, requires_grad=False)
kernel = cls(Mxfp8LinearLayerConfig(weight_shape=w.shape))
quant_config = DeepseekV4FP8Config.from_config(
{
"quant_method": "fp8",
@@ -318,10 +318,13 @@ def test_rms_norm(
# Per-block bf16 scales: allow a small relative tolerance for a few groups
# whose abs-max flips by one ULP between the fused and reference paths. The
# per-token and fp32 paths stay strict.
relax_block_rocm = (
# The same one-ULP group-scale flip also occurs on CUDA (H200), so extend
# the block relaxation there too — the fused groupwise reduction rounds
# differently than the reference for isolated groups.
relax_block = (
group_size is not None
and dtype == torch.bfloat16
and current_platform.is_rocm()
and (current_platform.is_rocm() or current_platform.is_cuda())
)
use_gfx950_fp8_allclose = (
current_platform.is_rocm()
@@ -340,7 +343,7 @@ def test_rms_norm(
def scales_close(rtol: float, atol: float) -> bool:
if torch.allclose(ref_scales, ops_scales, rtol=rtol, atol=atol):
return True
return relax_block_rocm and torch.allclose(
return relax_block and torch.allclose(
ref_scales, ops_scales, rtol=1e-2, atol=atol
)
@@ -354,7 +357,7 @@ def test_rms_norm(
b = ops_out.to(dtype=torch.float32)
ok = torch.allclose(a, b, atol=1e-6)
if not ok:
if relax_block_rocm:
if relax_block:
# ULP-flipped group scale can cross an E4M3 tie; tolerate a
# bounded count of isolated fp8 outliers.
ulp = fp8_ulp_distance(ref_out, ops_out)

Some files were not shown because too many files have changed in this diff Show More