[Model] Add DiffusionGemma Support (#45163)

Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com>
Signed-off-by: Matthew Bonanni <mbonanni@redhat.com>
Co-authored-by: Martin Kukla <martin.kukla@cantab.net>
Co-authored-by: Matthew Bonanni <mbonanni@redhat.com>
Co-authored-by: Dipika Sikka <dsikka@redhat.com>
Co-authored-by: NickLucche <nlucches@redhat.com>
Co-authored-by: jiahanc <173873397+jiahanc@users.noreply.github.com>
Co-authored-by: Alec Kohlhoff <134344302+aleckohlhoff@users.noreply.github.com>
Co-authored-by: Porras Huang <20535584+porrashuang@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: scoootscooob <167050519+scoootscooob@users.noreply.github.com>
This commit is contained in:
Lucas Wilkinson
2026-06-11 22:17:35 -07:00
committed by GitHub
co-authored by Martin Kukla Matthew Bonanni Dipika Sikka NickLucche jiahanc Alec Kohlhoff Porras Huang Claude scoootscooob
parent 1ce3cdc5c1
commit eb28452b10
52 changed files with 2695 additions and 232 deletions
@@ -0,0 +1,318 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for per-request causal/non-causal attention (mixed batches).
Validates that both triton and flash-attention backends correctly handle
batches where some sequences use causal masking and others use non-causal
(bidirectional) masking — needed by DiffusionGemma.
"""
import pytest
import torch
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
# Mixed causal/non-causal attention is only validated on a subset of GPUs:
# the Triton path on Hopper (SM90) and B200 (SM100); the FA4 path on Hopper
# (SM90) only.
_device_capability = current_platform.get_device_capability()
_major = _device_capability.major if _device_capability is not None else None
NUM_HEADS = [(4, 4), (8, 2)]
HEAD_SIZES = [128]
BLOCK_SIZES = [16]
DTYPES = [torch.bfloat16]
def ref_paged_attn(
query: torch.Tensor,
key_cache: torch.Tensor,
value_cache: torch.Tensor,
query_lens: list[int],
kv_lens: list[int],
block_tables: torch.Tensor,
scale: float,
per_seq_causal: list[bool],
sliding_window: int | None = None,
) -> torch.Tensor:
num_seqs = len(query_lens)
block_tables_np = block_tables.cpu().numpy()
_, block_size, num_kv_heads, head_size = key_cache.shape
outputs: list[torch.Tensor] = []
start_idx = 0
for i in range(num_seqs):
query_len = query_lens[i]
kv_len = kv_lens[i]
q = query[start_idx : start_idx + query_len]
q = q * scale
num_kv_blocks = (kv_len + block_size - 1) // block_size
block_indices = block_tables_np[i, :num_kv_blocks]
k = key_cache[block_indices].view(-1, num_kv_heads, head_size)[:kv_len]
v = value_cache[block_indices].view(-1, num_kv_heads, head_size)[:kv_len]
if q.shape[1] != k.shape[1]:
k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1)
v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1)
attn = torch.einsum("qhd,khd->hqk", q, k).float()
if per_seq_causal[i]:
mask = torch.triu(
torch.ones(query_len, kv_len, device=attn.device),
diagonal=kv_len - query_len + 1,
).bool()
else:
mask = torch.zeros(query_len, kv_len, device=attn.device).bool()
if sliding_window is not None:
sw_mask = (
torch.triu(
torch.ones(query_len, kv_len, device=attn.device),
diagonal=kv_len - (query_len + sliding_window) + 1,
)
.bool()
.logical_not()
)
mask |= sw_mask
attn.masked_fill_(mask, float("-inf"))
attn = torch.softmax(attn, dim=-1).to(v.dtype)
out = torch.einsum("hqk,khd->qhd", attn, v)
outputs.append(out)
start_idx += query_len
return torch.cat(outputs, dim=0)
# ---- Triton backend test ----
@pytest.mark.skipif(
_major not in (9, 10),
reason="Triton mixed causal attention requires Hopper (SM90) or B200 (SM100).",
)
@pytest.mark.parametrize(
"seq_lens",
[[(1, 128), (5, 64), (1, 256)]],
)
@pytest.mark.parametrize(
"per_seq_causal",
[[True, False, True], [False, True, False], [True, True, False]],
)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@pytest.mark.parametrize("head_size", HEAD_SIZES)
@pytest.mark.parametrize("block_size", BLOCK_SIZES)
@pytest.mark.parametrize("dtype", DTYPES)
@torch.inference_mode()
def test_triton_mixed_causal(
seq_lens: list[tuple[int, int]],
per_seq_causal: list[bool],
num_heads: tuple[int, int],
head_size: int,
dtype: torch.dtype,
block_size: int,
):
if not current_platform.is_cuda():
pytest.skip("Triton attention requires CUDA")
from vllm.v1.attention.ops.triton_unified_attention import unified_attention
set_random_seed(42)
device = "cuda"
num_query_heads, num_kv_heads = num_heads
assert len(seq_lens) == len(per_seq_causal)
query_lens = [s[0] for s in seq_lens]
kv_lens = [s[1] for s in seq_lens]
num_seqs = len(seq_lens)
num_query_tokens = sum(query_lens)
max_kv_len = max(kv_lens)
max_num_blocks = (max_kv_len + block_size - 1) // block_size
num_blocks = max_num_blocks * num_seqs + 10
scale = head_size**-0.5
query = torch.randn(
num_query_tokens, num_query_heads, head_size, dtype=dtype, device=device
)
key_cache = torch.randn(
num_blocks, block_size, num_kv_heads, head_size, dtype=dtype, device=device
)
value_cache = torch.randn(
num_blocks, block_size, num_kv_heads, head_size, dtype=dtype, device=device
)
block_tables_list = []
for i in range(num_seqs):
n_blocks = (kv_lens[i] + block_size - 1) // block_size
blocks = list(range(i * max_num_blocks, i * max_num_blocks + n_blocks))
blocks += [0] * (max_num_blocks - n_blocks)
block_tables_list.append(blocks)
block_tables = torch.tensor(block_tables_list, dtype=torch.int32, device=device)
cu_seqlens_q = torch.zeros(num_seqs + 1, dtype=torch.int32, device=device)
for i, ql in enumerate(query_lens):
cu_seqlens_q[i + 1] = cu_seqlens_q[i] + ql
seqused_k = torch.tensor(kv_lens, dtype=torch.int32, device=device)
max_seqlen_q = max(query_lens)
max_seqlen_k = max(kv_lens)
causal_tensor = torch.tensor(per_seq_causal, dtype=torch.bool, device=device)
output = torch.empty_like(query)
unified_attention(
q=query,
k=key_cache,
v=value_cache,
out=output,
cu_seqlens_q=cu_seqlens_q,
max_seqlen_q=max_seqlen_q,
seqused_k=seqused_k,
max_seqlen_k=max_seqlen_k,
softmax_scale=scale,
causal=causal_tensor,
window_size=(-1, -1),
block_table=block_tables,
softcap=0.0,
q_descale=None,
k_descale=1.0,
v_descale=1.0,
)
ref_output = ref_paged_attn(
query,
key_cache,
value_cache,
query_lens,
kv_lens,
block_tables,
scale,
per_seq_causal,
)
torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=1e-2)
# ---- Flash Attention 4 backend test (native per_seq_causal) ----
@pytest.mark.skipif(
_major != 9,
reason="FA4 mixed causal attention requires Hopper (SM90).",
)
@pytest.mark.parametrize(
"seq_lens",
[[(1, 128), (5, 64), (1, 256)]],
)
@pytest.mark.parametrize(
"per_seq_causal",
[[True, False, True], [False, True, False]],
)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@pytest.mark.parametrize("head_size", HEAD_SIZES)
@pytest.mark.parametrize("block_size", BLOCK_SIZES)
@pytest.mark.parametrize("dtype", DTYPES)
@torch.inference_mode()
def test_flash_attn4_mixed_causal(
seq_lens: list[tuple[int, int]],
per_seq_causal: list[bool],
num_heads: tuple[int, int],
head_size: int,
dtype: torch.dtype,
block_size: int,
):
if not current_platform.is_cuda():
pytest.skip("Flash attention requires CUDA")
try:
from vllm.vllm_flash_attn import (
fa_version_unsupported_reason,
flash_attn_varlen_func,
is_fa_version_supported,
)
except ImportError:
pytest.skip("vllm_flash_attn not available")
if not is_fa_version_supported(4):
reason = fa_version_unsupported_reason(4)
pytest.skip(f"FA4 not supported: {reason}")
set_random_seed(42)
device = "cuda"
num_query_heads, num_kv_heads = num_heads
assert len(seq_lens) == len(per_seq_causal)
query_lens = [s[0] for s in seq_lens]
kv_lens = [s[1] for s in seq_lens]
num_seqs = len(seq_lens)
num_query_tokens = sum(query_lens)
max_kv_len = max(kv_lens)
max_num_blocks = (max_kv_len + block_size - 1) // block_size
num_blocks = max_num_blocks * num_seqs + 10
scale = head_size**-0.5
query = torch.randn(
num_query_tokens, num_query_heads, head_size, dtype=dtype, device=device
)
key_cache = torch.randn(
num_blocks, block_size, num_kv_heads, head_size, dtype=dtype, device=device
)
value_cache = torch.randn(
num_blocks, block_size, num_kv_heads, head_size, dtype=dtype, device=device
)
block_tables_list = []
for i in range(num_seqs):
n_blocks = (kv_lens[i] + block_size - 1) // block_size
blocks = list(range(i * max_num_blocks, i * max_num_blocks + n_blocks))
blocks += [0] * (max_num_blocks - n_blocks)
block_tables_list.append(blocks)
block_tables = torch.tensor(block_tables_list, dtype=torch.int32, device=device)
cu_seqlens_q = torch.zeros(num_seqs + 1, dtype=torch.int32, device=device)
for i, ql in enumerate(query_lens):
cu_seqlens_q[i + 1] = cu_seqlens_q[i] + ql
seqused_k = torch.tensor(kv_lens, dtype=torch.int32, device=device)
per_seq_causal_tensor = torch.tensor(
per_seq_causal, dtype=torch.int32, device=device
)
ref_output = ref_paged_attn(
query,
key_cache,
value_cache,
query_lens,
kv_lens,
block_tables,
scale,
per_seq_causal,
)
output = torch.empty_like(query)
flash_attn_varlen_func(
q=query,
k=key_cache,
v=value_cache,
out=output,
cu_seqlens_q=cu_seqlens_q,
max_seqlen_q=max(query_lens),
seqused_k=seqused_k,
max_seqlen_k=max(kv_lens),
softmax_scale=scale,
# The kernel must be compiled causal for `dynamic_causal` to take effect.
causal=True,
block_table=block_tables,
softcap=0.0,
dynamic_causal=per_seq_causal_tensor,
fa_version=4,
)
torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=1e-2)
+4
View File
@@ -898,6 +898,10 @@ _MULTIMODAL_EXAMPLE_MODELS = {
),
"FuyuForCausalLM": _HfExamplesInfo("adept/fuyu-8b"),
"Gemma3ForConditionalGeneration": _HfExamplesInfo("google/gemma-3-4b-it"),
"DiffusionGemmaForBlockDiffusion": _HfExamplesInfo(
"google/diffusiongemma-26B-A4B-it",
trust_remote_code=True,
),
"Gemma4ForConditionalGeneration": _HfExamplesInfo(
"google/gemma-4-E2B-it",
min_transformers_version="5.5.0",
+3 -1
View File
@@ -486,6 +486,7 @@ def dummy_hf_overrides(
"Gemma3nForConditionalGeneration",
"Gemma4ForCausalLM",
"Gemma4ForConditionalGeneration",
"DiffusionGemmaForBlockDiffusion",
)
else 1
)
@@ -558,7 +559,8 @@ def dummy_hf_overrides(
)
# e.g.: Qwen/Qwen2-Audio-7B-Instruct
if hasattr(hf_config, "audio_config"):
# audio_config may exist but be None (e.g. audio-less Gemma4 variants).
if getattr(hf_config, "audio_config", None) is not None:
hf_config.audio_config.update(
{
"num_layers": 1,
@@ -702,6 +702,88 @@ class TestStreamingExtraction:
' <meta name="viewport" content="width=device-width">\n'
)
def _collect_tool_calls_by_index(self, results):
"""Group streamed tool-call fragments by their ``index``.
Returns ``{index: {"name": str | None, "arguments": str}}`` where
``arguments`` is the concatenation of every streamed argument
fragment for that index (which should form valid JSON once complete).
"""
by_index: dict[int, dict[str, Any]] = {}
for delta, _ in results:
if not (delta and delta.tool_calls):
continue
for tc in delta.tool_calls:
entry = by_index.setdefault(tc.index, {"name": None, "arguments": ""})
func = tc.function
if isinstance(func, dict):
name = func.get("name")
arg = func.get("arguments", "")
else:
name = getattr(func, "name", None)
arg = getattr(func, "arguments", "") or ""
if name:
entry["name"] = name
if arg:
entry["arguments"] += arg
return by_index
def test_streaming_single_chunk_complete_tool_call(self, parser, mock_request):
"""A backend may deliver a whole tool call in one streaming delta.
The start token, ``call:name{...}`` payload and the end token all
arrive in a single chunk. The parser must still emit one
``DeltaToolCall`` with the correct name + complete arguments JSON
(rather than swallowing it and finishing with finish_reason="stop").
"""
chunks = [
'<|tool_call>call:name_a_color{color_hex:<|"|>00ff11<|"|>}<tool_call|>',
]
results = self._simulate_streaming(parser, mock_request, chunks)
# Exactly one delta should carry tool_calls, and it must not be
# emitted as plain content (which would yield finish_reason="stop").
tool_call_deltas = [
delta for delta, _ in results if delta is not None and delta.tool_calls
]
assert len(tool_call_deltas) == 1, (
"Expected exactly one delta carrying the batched tool call"
)
assert all(
delta.content is None for delta, _ in results if delta is not None
), "Complete tool call must not leak as content"
by_index = self._collect_tool_calls_by_index(results)
assert set(by_index) == {0}
assert by_index[0]["name"] == "name_a_color"
assert json.loads(by_index[0]["arguments"]) == {"color_hex": "00ff11"}
def test_streaming_multi_chunk_batched_tool_calls(self, parser, mock_request):
"""A single delta may batch MULTIPLE complete tool calls.
``<|tool_call>...<tool_call|><|tool_call>...<tool_call|>`` arriving in
one chunk must emit BOTH calls (one DeltaToolCall each, with distinct
indices), not just the first.
"""
chunks = [
'<|tool_call>call:get_weather{location:<|"|>London<|"|>}<tool_call|>'
'<|tool_call>call:get_time{timezone:<|"|>GMT<|"|>}<tool_call|>',
]
results = self._simulate_streaming(parser, mock_request, chunks)
by_index = self._collect_tool_calls_by_index(results)
assert set(by_index) == {0, 1}, (
f"Expected two tool calls (indices 0 and 1), got {sorted(by_index)}"
)
assert by_index[0]["name"] == "get_weather"
assert json.loads(by_index[0]["arguments"]) == {"location": "London"}
assert by_index[1]["name"] == "get_time"
assert json.loads(by_index[1]["arguments"]) == {"timezone": "GMT"}
def test_streaming_trailing_bare_bool_not_duplicated(self, parser, mock_request):
"""Trailing bare boolean must not be streamed twice."""
chunks = [
@@ -49,6 +49,7 @@ def _create_vllm_config(
)
mock_config.parallel_config = ParallelConfig()
mock_config.speculative_config = None # No speculative decoding
mock_config.num_speculative_tokens = 0
if not lora_config:
mock_config.lora_config = None
else:
@@ -104,7 +104,7 @@ def _run_engine_core_handshake(
speculative_config=None,
ec_transfer_config=None,
max_concurrent_batches=1,
model_config=SimpleNamespace(runner_type="generate"),
model_config=SimpleNamespace(runner_type="generate", is_diffusion=False),
cache_config=SimpleNamespace(
enable_prefix_caching=False,
prefix_caching_hash_algo="builtin",
@@ -70,6 +70,7 @@ def _make_runner(**overrides: Any) -> Any:
runner.use_aux_hidden_state_outputs = False
runner.speculative_config = None
runner.speculator = None
runner.num_speculative_steps = 0
runner.encoder_cache = None
runner.is_pooling_model = False
runner.is_last_pp_rank = True
@@ -102,18 +103,22 @@ def test_v2_load_model_registers_moe_with_eplb(monkeypatch):
lambda load_config: SimpleNamespace(load_model=lambda **_: model),
)
monkeypatch.setattr(mrv2, "prepare_communication_buffer_for_model", prepared.append)
monkeypatch.setattr(mrv2, "init_model_state", lambda *args: "model-state")
monkeypatch.setattr(
mrv2,
"init_model_state",
lambda *args: SimpleNamespace(num_new_sampled_tokens_per_step=1),
)
monkeypatch.setattr(
eplb,
"is_mixture_of_experts",
lambda loaded_model: getattr(loaded_model, "is_moe", False),
)
runner = _make_runner()
runner = _make_runner(is_last_pp_rank=False)
mrv2.GPUModelRunner.load_model(runner)
assert runner.model is model
assert runner.model_state == "model-state"
assert runner.model_state is not None
assert prepared == [model]
assert runner.eplb_state is not None
assert runner.eplb_state.add_model_calls == [(model, runner.model_config)]
@@ -133,10 +138,14 @@ def test_v2_load_model_with_dummy_weights_skips_eplb_registration(monkeypatch):
lambda load_config: SimpleNamespace(load_model=lambda **_: model),
)
monkeypatch.setattr(mrv2, "prepare_communication_buffer_for_model", prepared.append)
monkeypatch.setattr(mrv2, "init_model_state", lambda *args: "model-state")
monkeypatch.setattr(
mrv2,
"init_model_state",
lambda *args: SimpleNamespace(num_new_sampled_tokens_per_step=1),
)
monkeypatch.setattr(eplb, "is_mixture_of_experts", lambda *_: True)
runner = _make_runner()
runner = _make_runner(is_last_pp_rank=False)
mrv2.GPUModelRunner.load_model(runner, load_dummy_weights=True)
assert runner.load_config.load_format == "dummy"