[Model] Add Inkling model support [1/N] (#48799)
Signed-off-by: Woosuk Kwon <woosuk@inferact.ai> Signed-off-by: Bugen Zhao <i@bugenzhao.com> Co-authored-by: Bugen Zhao <i@bugenzhao.com> Co-authored-by: Giancarlo Delfin <32987265+TheEpicDolphin@users.noreply.github.com> Co-authored-by: Isotr0py <Isotr0py@outlook.com> Co-authored-by: Isotr0py <mozf@inferact.ai> Co-authored-by: Jee Jee Li <jeejeelee@inferact.ai> Co-authored-by: Roger Wang <hey@rogerw.io> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
Bugen Zhao
Giancarlo Delfin
Isotr0py
Isotr0py
Jee Jee Li
Roger Wang
Yifan Qiao
Claude Fable 5
OpenAI Codex
parent
8bfd683901
commit
6570c9800c
@@ -0,0 +1,50 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm.config.compilation import CompilationConfig, CUDAGraphMode
|
||||
from vllm.models.inkling.common.mm_preprocess import InklingMultiModalDataParser
|
||||
from vllm.models.inkling.configs import (
|
||||
InklingAudioConfig,
|
||||
InklingVisionConfig,
|
||||
)
|
||||
from vllm.models.inkling.nvidia.sconv_swa_attn import (
|
||||
InklingSconvMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backend import AttentionCGSupport
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config_cls", "kwargs", "missing"),
|
||||
[
|
||||
(InklingAudioConfig, {"decoder_dmodel": 16}, "n_mel_bins"),
|
||||
(InklingVisionConfig, {"decoder_dmodel": 16}, "vision_encoder_type"),
|
||||
],
|
||||
)
|
||||
def test_enabled_tower_requires_architecture_fields(config_cls, kwargs, missing):
|
||||
with pytest.raises(ValueError, match=missing):
|
||||
config_cls(**kwargs)
|
||||
|
||||
|
||||
def test_inkling_raw_2d_audio_is_rejected_as_ambiguous():
|
||||
parser = InklingMultiModalDataParser(target_sr=16_000, target_channels=1)
|
||||
with pytest.raises(ValueError, match="ambiguous channel layout"):
|
||||
parser._parse_audio_data(np.zeros((2, 100), dtype=np.float32))
|
||||
|
||||
|
||||
def test_inkling_supports_full_decode_only_cudagraphs():
|
||||
support = InklingSconvMetadataBuilder.get_cudagraph_support
|
||||
assert support(None, None) == AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
|
||||
|
||||
compilation_config = CompilationConfig(
|
||||
cudagraph_mode=CUDAGraphMode.FULL,
|
||||
splitting_ops=[],
|
||||
)
|
||||
resolved_mode = compilation_config.resolve_cudagraph_mode_and_sizes(
|
||||
AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE,
|
||||
"InklingSconvBackend",
|
||||
)
|
||||
|
||||
assert resolved_mode == CUDAGraphMode.FULL_DECODE_ONLY
|
||||
@@ -0,0 +1,381 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Correctness test for the Inkling FA4 relative-attention score-mod kernel.
|
||||
|
||||
Checks ``inkling_fa4_rel_attention`` against a pure-PyTorch reference that
|
||||
implements the relative bias exactly as documented in the Inkling architecture
|
||||
guide::
|
||||
|
||||
logit(i, j, h) = (1 / head_dim) * dot(q[i, h], k[j, h]) + rel_bias(i, j, h)
|
||||
rel_bias(i, j, h) = rel_logits[i, h, i - j] if 0 <= i - j < rel_extent
|
||||
= 0 otherwise
|
||||
|
||||
with causal (and optionally sliding-window) masking handled by the backend.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.inkling.nvidia.attention import (
|
||||
InklingAttention,
|
||||
compute_log_scaling_tau,
|
||||
)
|
||||
from vllm.models.inkling.nvidia.ops.fa4_rel_attention import (
|
||||
inkling_fa4_num_splits,
|
||||
inkling_fa4_rel_attention,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
_cap = current_platform.get_device_capability() if current_platform.is_cuda() else None
|
||||
|
||||
NUM_HEADS = [(4, 4), (8, 2)] # (num_heads, num_kv_heads)
|
||||
GLOBAL_REL_EXTENTS = [128, 1024]
|
||||
LOCAL_REL_EXTENTS = [128, 256]
|
||||
HEAD_DIM = 128
|
||||
BLOCK_SIZE = 16
|
||||
DTYPE = torch.bfloat16
|
||||
|
||||
|
||||
def test_log_scaling_tau_matches_reference():
|
||||
positions = torch.tensor([0, 127999, 128000, 999999], dtype=torch.int64)
|
||||
actual = compute_log_scaling_tau(positions, 128000, 0.1)
|
||||
expected = 1.0 + 0.1 * torch.log(
|
||||
torch.clamp((positions + 1).float() / 128000.0, min=1.0)
|
||||
)
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
|
||||
|
||||
|
||||
def test_split_packed_kv_cache():
|
||||
attention = InklingAttention.__new__(InklingAttention)
|
||||
torch.nn.Module.__init__(attention)
|
||||
attention.head_dim = 8
|
||||
attention.kv_cache = torch.arange(2 * 3 * 4 * 16).reshape(2, 3, 4, 16)
|
||||
|
||||
key_cache, value_cache = attention._split_kv_cache()
|
||||
|
||||
assert key_cache.shape == value_cache.shape == (2, 4, 3, 8)
|
||||
torch.testing.assert_close(key_cache, attention.kv_cache[..., :8].transpose(1, 2))
|
||||
torch.testing.assert_close(value_cache, attention.kv_cache[..., 8:].transpose(1, 2))
|
||||
|
||||
|
||||
def test_num_splits_hopper_is_unsplit(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"get_device_capability",
|
||||
lambda: DeviceCapability(major=9, minor=0),
|
||||
)
|
||||
assert (
|
||||
inkling_fa4_num_splits(
|
||||
is_local=False,
|
||||
batch_size=1,
|
||||
max_query_len=1,
|
||||
num_heads=16,
|
||||
num_kv_heads=2,
|
||||
max_kv_len=1_048_576,
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def blackwell_platform(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"get_device_capability",
|
||||
lambda: DeviceCapability(major=10, minor=0),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("batch_size", "max_query_len", "expected"),
|
||||
[
|
||||
(1, 1, (16, 32, 128, 128)),
|
||||
(8, 1, (2, 4, 8, 16)),
|
||||
(32, 1, (1, 1, 2, 4)),
|
||||
(1, 128, (2, 4, 8, 16)),
|
||||
(1, 2048, (1, 1, 1, 1)),
|
||||
],
|
||||
)
|
||||
def test_num_splits_all_tp(blackwell_platform, batch_size, max_query_len, expected):
|
||||
actual = tuple(
|
||||
inkling_fa4_num_splits(
|
||||
is_local=False,
|
||||
batch_size=batch_size,
|
||||
max_query_len=max_query_len,
|
||||
num_heads=64 // tp,
|
||||
num_kv_heads=8 // tp,
|
||||
max_kv_len=131072,
|
||||
)
|
||||
for tp in (1, 2, 4, 8)
|
||||
)
|
||||
assert actual == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tp", [1, 2, 4, 8])
|
||||
def test_num_splits_local_is_unsplit(tp):
|
||||
assert (
|
||||
inkling_fa4_num_splits(
|
||||
is_local=True,
|
||||
batch_size=1,
|
||||
max_query_len=1,
|
||||
num_heads=64 // tp,
|
||||
num_kv_heads=16 // tp,
|
||||
max_kv_len=512,
|
||||
)
|
||||
== 1
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("max_kv_len", "expected"),
|
||||
[(8192, 32), (65536, 64), (1048576, 128)],
|
||||
)
|
||||
@pytest.mark.parametrize("tp", [4, 8])
|
||||
def test_num_splits_long_context_bound(blackwell_platform, tp, max_kv_len, expected):
|
||||
assert (
|
||||
inkling_fa4_num_splits(
|
||||
is_local=False,
|
||||
batch_size=1,
|
||||
max_query_len=1,
|
||||
num_heads=64 // tp,
|
||||
num_kv_heads=8 // tp,
|
||||
max_kv_len=max_kv_len,
|
||||
)
|
||||
== expected
|
||||
)
|
||||
|
||||
|
||||
def _ref_rel_attn(
|
||||
q: torch.Tensor, # [total_q, H, D]
|
||||
key_cache: torch.Tensor, # [num_blocks, block, Hkv, D]
|
||||
value_cache: torch.Tensor,
|
||||
rel_logits: torch.Tensor, # [total_q, H, rel_extent]
|
||||
*,
|
||||
q_lens: list[int],
|
||||
kv_lens: list[int],
|
||||
block_table: torch.Tensor,
|
||||
scale: float,
|
||||
rel_extent: int,
|
||||
window_left: int | None,
|
||||
) -> torch.Tensor:
|
||||
num_kv_heads = key_cache.shape[2]
|
||||
num_heads = q.shape[1]
|
||||
g = num_heads // num_kv_heads
|
||||
bt = block_table.cpu().numpy()
|
||||
out = torch.empty_like(q)
|
||||
|
||||
start = 0
|
||||
for i, (ql, kl) in enumerate(zip(q_lens, kv_lens)):
|
||||
qi = q[start : start + ql].float() # [ql, H, D]
|
||||
rl = rel_logits[start : start + ql].float() # [ql, H, rel_extent]
|
||||
|
||||
nblk = (kl + BLOCK_SIZE - 1) // BLOCK_SIZE
|
||||
blk = bt[i, :nblk]
|
||||
k = key_cache[blk].reshape(-1, num_kv_heads, HEAD_DIM)[:kl].float()
|
||||
v = value_cache[blk].reshape(-1, num_kv_heads, HEAD_DIM)[:kl].float()
|
||||
k = k.repeat_interleave(g, dim=1) # [kl, H, D]
|
||||
v = v.repeat_interleave(g, dim=1)
|
||||
|
||||
# [H, ql, kl]
|
||||
scores = torch.einsum("qhd,khd->hqk", qi, k) * scale
|
||||
|
||||
dev = q.device
|
||||
qpos = torch.arange(ql, device=dev).view(ql, 1) + (kl - ql) # query pos
|
||||
kpos = torch.arange(kl, device=dev).view(1, kl)
|
||||
dist = qpos - kpos # [ql, kl] = i - j
|
||||
|
||||
# Relative bias: rel_logits[i, h, dist] when 0 <= dist < rel_extent.
|
||||
in_rng = (dist >= 0) & (dist < rel_extent) # [ql, kl]
|
||||
idx = dist.clamp(0, rel_extent - 1)
|
||||
# gather per head: bias[h, i, j] = rl[i, h, idx[i, j]]
|
||||
bias = rl.permute(1, 0, 2).gather( # [H, ql, rel_extent]
|
||||
2, idx.unsqueeze(0).expand(num_heads, -1, -1)
|
||||
) # [H, ql, kl]
|
||||
bias = torch.where(in_rng.unsqueeze(0), bias, torch.zeros_like(bias))
|
||||
scores = scores + bias
|
||||
|
||||
mask = dist < 0 # causal
|
||||
if window_left is not None:
|
||||
mask = mask | (dist > window_left)
|
||||
scores.masked_fill_(mask.unsqueeze(0), float("-inf"))
|
||||
|
||||
probs = torch.softmax(scores, dim=-1)
|
||||
out[start : start + ql] = torch.einsum("hqk,khd->qhd", probs, v).to(q.dtype)
|
||||
start += ql
|
||||
return out
|
||||
|
||||
|
||||
def _run_case(seq_lens, num_heads, num_kv_heads, rel_extent, window_left, seed=0):
|
||||
torch.manual_seed(seed)
|
||||
device = "cuda"
|
||||
q_lens = [s[0] for s in seq_lens]
|
||||
kv_lens = [s[1] for s in seq_lens]
|
||||
total_q = sum(q_lens)
|
||||
num_seqs = len(seq_lens)
|
||||
|
||||
scale = 1.0 / HEAD_DIM
|
||||
|
||||
# q/k are RMS-normed in the model (unit-ish norm); normalize here so the
|
||||
# logit magnitudes are realistic and the bias is not numerically dwarfed.
|
||||
q = torch.randn(total_q, num_heads, HEAD_DIM, device=device, dtype=DTYPE)
|
||||
q = torch.nn.functional.normalize(q.float(), dim=-1).to(DTYPE)
|
||||
|
||||
# Paged KV cache.
|
||||
max_blocks = (max(kv_lens) + BLOCK_SIZE - 1) // BLOCK_SIZE
|
||||
num_blocks = num_seqs * max_blocks + 1
|
||||
key_cache = torch.randn(
|
||||
num_blocks, BLOCK_SIZE, num_kv_heads, HEAD_DIM, device=device, dtype=DTYPE
|
||||
)
|
||||
key_cache = torch.nn.functional.normalize(key_cache.float(), dim=-1).to(DTYPE)
|
||||
value_cache = torch.randn(
|
||||
num_blocks, BLOCK_SIZE, num_kv_heads, HEAD_DIM, device=device, dtype=DTYPE
|
||||
)
|
||||
|
||||
# Distinct blocks per sequence (block 0 left as a never-referenced pad).
|
||||
block_table = torch.zeros(num_seqs, max_blocks, dtype=torch.int32, device=device)
|
||||
for i in range(num_seqs):
|
||||
block_table[i] = torch.arange(
|
||||
1 + i * max_blocks, 1 + (i + 1) * max_blocks, dtype=torch.int32
|
||||
)
|
||||
|
||||
cu_seqlens_q = torch.tensor(
|
||||
[0, *torch.cumsum(torch.tensor(q_lens), 0).tolist()],
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
)
|
||||
cache_seqlens = torch.tensor(kv_lens, dtype=torch.int32, device=device)
|
||||
|
||||
rel_logits = torch.randn(total_q, num_heads, rel_extent, device=device, dtype=DTYPE)
|
||||
|
||||
window_size = (-1, -1) if window_left is None else (window_left, 0)
|
||||
|
||||
preallocated_out = torch.empty_like(q)
|
||||
out = inkling_fa4_rel_attention(
|
||||
q,
|
||||
key_cache,
|
||||
value_cache,
|
||||
block_table=block_table,
|
||||
cache_seqlens=cache_seqlens,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
max_seqlen_q=max(q_lens),
|
||||
softmax_scale=scale,
|
||||
causal=True,
|
||||
window_size=window_size,
|
||||
rel_extent=rel_extent,
|
||||
rel_logits=rel_logits,
|
||||
out=preallocated_out,
|
||||
)
|
||||
assert out.data_ptr() == preallocated_out.data_ptr()
|
||||
out = out.view(total_q, num_heads, HEAD_DIM)
|
||||
|
||||
ref = _ref_rel_attn(
|
||||
q,
|
||||
key_cache,
|
||||
value_cache,
|
||||
rel_logits,
|
||||
q_lens=q_lens,
|
||||
kv_lens=kv_lens,
|
||||
block_table=block_table,
|
||||
scale=scale,
|
||||
rel_extent=rel_extent,
|
||||
window_left=window_left,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(out.float(), ref.float(), atol=2e-2, rtol=2e-2)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
|
||||
@pytest.mark.skipif(
|
||||
_cap is None or _cap.major < 9,
|
||||
reason="FA4 score-mod requires Hopper+ (SM90+)",
|
||||
)
|
||||
@pytest.mark.parametrize("num_heads", NUM_HEADS)
|
||||
@pytest.mark.parametrize(
|
||||
"seq_lens",
|
||||
[
|
||||
[(64, 64)], # single full prefill
|
||||
[(64, 64), (33, 33), (17, 17)], # ragged prefill batch
|
||||
[(512, 512)], # seq_len >> rel_extent (most keys get zero bias)
|
||||
[(300, 300), (512, 512), (129, 129)], # large ragged batch
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("rel_extent", GLOBAL_REL_EXTENTS)
|
||||
@torch.inference_mode()
|
||||
def test_full_attention(seq_lens, num_heads, rel_extent):
|
||||
# rel_extent=128 exercises the out-of-range (zero bias) path; 1024 covers all.
|
||||
# With the 512-token cases and rel_extent=128, query/seq lengths are far
|
||||
# larger than rel_extent so the vast majority of (i, j) pairs are out of
|
||||
# range and must contribute zero bias.
|
||||
_run_case(seq_lens, num_heads[0], num_heads[1], rel_extent, window_left=None)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
|
||||
@pytest.mark.skipif(
|
||||
_cap is None or _cap.major < 9,
|
||||
reason="FA4 score-mod requires Hopper+ (SM90+)",
|
||||
)
|
||||
@pytest.mark.parametrize("num_heads", NUM_HEADS)
|
||||
@pytest.mark.parametrize(
|
||||
"seq_lens",
|
||||
[
|
||||
[(200, 512)], # chunked prefill: q_len=200 (> rel_extent), 312 cached
|
||||
[(200, 512), (50, 300), (1, 400)], # mixed chunked + decode
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("rel_extent", GLOBAL_REL_EXTENTS)
|
||||
@torch.inference_mode()
|
||||
def test_chunked_prefill(seq_lens, num_heads, rel_extent):
|
||||
# q_len < kv_len with q_len itself larger than rel_extent (for the 128 case):
|
||||
# exercises the seqlen_k - seqlen_q offset together with the out-of-range path.
|
||||
_run_case(seq_lens, num_heads[0], num_heads[1], rel_extent, window_left=None)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
|
||||
@pytest.mark.skipif(
|
||||
_cap is None or _cap.major < 9,
|
||||
reason="FA4 score-mod requires Hopper+ (SM90+)",
|
||||
)
|
||||
@pytest.mark.parametrize("num_heads", NUM_HEADS)
|
||||
@pytest.mark.parametrize(
|
||||
"seq_lens",
|
||||
[
|
||||
[(64, 64), (40, 40)], # seq_len > window
|
||||
[(512, 512), (300, 300)], # seq_len/query_len >> window
|
||||
[(1, 512)], # decode with kv_len >> window
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("local_extent", LOCAL_REL_EXTENTS)
|
||||
@torch.inference_mode()
|
||||
def test_sliding_window(seq_lens, num_heads, local_extent):
|
||||
# Local layers use window_size=(local_extent-1, 0) and rel_extent==local_extent.
|
||||
# With the 512-token cases, query/seq lengths far exceed the window so most
|
||||
# keys are masked out by the sliding window.
|
||||
_run_case(
|
||||
seq_lens,
|
||||
num_heads[0],
|
||||
num_heads[1],
|
||||
rel_extent=local_extent,
|
||||
window_left=local_extent - 1,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
|
||||
@pytest.mark.skipif(
|
||||
_cap is None or _cap.major < 9,
|
||||
reason="FA4 score-mod requires Hopper+ (SM90+)",
|
||||
)
|
||||
@pytest.mark.parametrize("num_heads", NUM_HEADS)
|
||||
@pytest.mark.parametrize(
|
||||
"seq_lens",
|
||||
[
|
||||
[(1, 50)],
|
||||
[(1, 50), (1, 7), (1, 200)],
|
||||
[(1, 512), (1, 333)], # kv_len >> rel_extent
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("rel_extent", GLOBAL_REL_EXTENTS)
|
||||
@torch.inference_mode()
|
||||
def test_decode(seq_lens, num_heads, rel_extent):
|
||||
# q_len=1 with kv_len>q_len: the score-mod's seqlen_k - seqlen_q offset path.
|
||||
_run_case(seq_lens, num_heads[0], num_heads[1], rel_extent, window_left=None)
|
||||
@@ -0,0 +1,69 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.models.inkling.nvidia.ops.fa4_rel_attention import (
|
||||
bucket_max_seqlen_q,
|
||||
inkling_fa4_num_splits,
|
||||
)
|
||||
from vllm.models.inkling.nvidia.ops.fa4_warmup import (
|
||||
InklingFA4WarmupConfig,
|
||||
_iter_compile_units,
|
||||
_num_warps_bucket,
|
||||
)
|
||||
|
||||
|
||||
def test_bucket_max_seqlen_q():
|
||||
assert [bucket_max_seqlen_q(n) for n in range(1, 10)] == [
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
4,
|
||||
8,
|
||||
8,
|
||||
8,
|
||||
8,
|
||||
16,
|
||||
]
|
||||
|
||||
|
||||
def test_warmup_enumerates_every_runtime_compile_class():
|
||||
config = InklingFA4WarmupConfig(
|
||||
num_heads=16,
|
||||
num_kv_heads=2,
|
||||
head_dim=128,
|
||||
rel_extent=1024,
|
||||
window_size=(-1, -1),
|
||||
is_local=False,
|
||||
max_kv_len=65536,
|
||||
dtype=torch.bfloat16,
|
||||
kv_dtype=torch.bfloat16,
|
||||
block_size=16,
|
||||
max_num_reqs=64,
|
||||
max_num_batched_tokens=192,
|
||||
)
|
||||
warmed_keys = {unit.key[-1] for unit in _iter_compile_units(config)}
|
||||
|
||||
for query_len in range(1, config.max_num_batched_tokens + 1):
|
||||
max_seqlen_q = bucket_max_seqlen_q(query_len)
|
||||
max_num_reqs = min(
|
||||
config.max_num_reqs,
|
||||
config.max_num_batched_tokens - query_len + 1,
|
||||
)
|
||||
for num_reqs in range(1, max_num_reqs + 1):
|
||||
num_splits = inkling_fa4_num_splits(
|
||||
is_local=config.is_local,
|
||||
batch_size=num_reqs,
|
||||
max_query_len=max_seqlen_q,
|
||||
num_heads=config.num_heads,
|
||||
num_kv_heads=config.num_kv_heads,
|
||||
max_kv_len=config.max_kv_len,
|
||||
)
|
||||
runtime_key = (
|
||||
max_seqlen_q,
|
||||
num_splits,
|
||||
_num_warps_bucket(num_reqs) if num_splits > 1 else None,
|
||||
num_reqs > 1024,
|
||||
)
|
||||
assert runtime_key in warmed_keys
|
||||
@@ -0,0 +1,138 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Correctness tests for the fused Inkling vision/audio tower kernels.
|
||||
|
||||
Each kernel is checked against a pure-PyTorch reference implementing the
|
||||
towers' original op sequence (native ``rms_norm`` semantics: fp32 variance,
|
||||
bf16-rounded weight multiply; exact-erf GELU; fp32-accumulated embedding sum).
|
||||
The fused kernels keep the same accumulation dtype and rounding points, so
|
||||
outputs differ from the reference only by reduction order — a few bf16 ulps.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip("requires CUDA", allow_module_level=True)
|
||||
|
||||
from vllm.models.inkling.common.towers import fold_timespace_to_depth
|
||||
from vllm.models.inkling.nvidia.ops.mm_towers import dmel_embed_sum_norm, rmsnorm_gelu
|
||||
|
||||
DTYPE = torch.bfloat16
|
||||
|
||||
|
||||
def _bf16_spacing(x: torch.Tensor) -> torch.Tensor:
|
||||
return torch.exp2(torch.floor(torch.log2(x.float().abs().clamp(min=1e-30)))) * (
|
||||
2**-7
|
||||
)
|
||||
|
||||
|
||||
def _assert_close_ulps(
|
||||
got: torch.Tensor,
|
||||
ref: torch.Tensor,
|
||||
max_ulps: float = 4.0,
|
||||
atol: float = 1e-3,
|
||||
pre_act: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
"""Fused vs reference differ only by fp32 reduction order, which shows up
|
||||
as a few bf16 ulps at any magnitude — a fixed rtol misrepresents that, so
|
||||
compare against the reference's local ulp spacing. ``pre_act`` (the
|
||||
reference pre-activation) adds derivative-propagated slack: near
|
||||
``gelu(x) ~ 0`` an ulp-level input flip legitimately moves the output by
|
||||
many of ITS (tiny) ulps, bounded by |gelu'| <= 1.13 times the input ulps."""
|
||||
g, r = got.float(), ref.float()
|
||||
tol = torch.clamp(max_ulps * _bf16_spacing(ref), min=atol)
|
||||
if pre_act is not None:
|
||||
tol = tol + 2.5 * _bf16_spacing(pre_act)
|
||||
bad = (g - r).abs() > tol
|
||||
assert not bad.any(), (
|
||||
f"{int(bad.sum())}/{ref.numel()} elements beyond tolerance; "
|
||||
f"max abs diff {(g - r).abs().max().item():.3e}"
|
||||
)
|
||||
|
||||
|
||||
def _ref_rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:
|
||||
# Matches ir.ops.rms_norm: fp32 normalize, bf16 weight multiply.
|
||||
x32 = x.float()
|
||||
var = x32.pow(2).mean(dim=-1, keepdim=True)
|
||||
xn = x32 * torch.rsqrt(var + eps)
|
||||
return (xn.to(weight.dtype) * weight).to(x.dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rows", [1, 7, 1200, 38400])
|
||||
@pytest.mark.parametrize("dim", [128, 320, 4800, 6144])
|
||||
@pytest.mark.parametrize("gelu", [True, False])
|
||||
def test_rmsnorm_gelu(rows: int, dim: int, gelu: bool) -> None:
|
||||
torch.manual_seed(rows * dim)
|
||||
x = torch.randn(rows, dim, device="cuda", dtype=DTYPE)
|
||||
w = torch.randn(dim, device="cuda", dtype=DTYPE)
|
||||
|
||||
h = _ref_rms_norm(x, w, 1e-5)
|
||||
ref = F.gelu(h) if gelu else h
|
||||
got = rmsnorm_gelu(x, w, 1e-5, gelu=gelu)
|
||||
|
||||
_assert_close_ulps(got, ref, pre_act=h if gelu else None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n", [1, 5, 64])
|
||||
@pytest.mark.parametrize(
|
||||
"shape,fold",
|
||||
[
|
||||
((2, 8, 8, 128), (1, 2)), # the real L0 -> L1 vision transition
|
||||
((2, 4, 4, 320), (1, 2)),
|
||||
((2, 8, 8, 128), (2, 2)), # temporal + spatial fold
|
||||
],
|
||||
)
|
||||
def test_rmsnorm_gelu_folded_store(
|
||||
n: int, shape: tuple[int, ...], fold: tuple[int, int]
|
||||
) -> None:
|
||||
torch.manual_seed(n)
|
||||
x = torch.randn(n, *shape, device="cuda", dtype=DTYPE)
|
||||
w = torch.randn(shape[-1], device="cuda", dtype=DTYPE)
|
||||
|
||||
plain = rmsnorm_gelu(x, w, 1e-5, gelu=True)
|
||||
ref = fold_timespace_to_depth(plain, *fold)
|
||||
got = rmsnorm_gelu(x, w, 1e-5, gelu=True, fold=fold)
|
||||
|
||||
# The folded store is a pure permutation of the unfolded output.
|
||||
assert got.shape == ref.shape
|
||||
torch.testing.assert_close(got, ref, rtol=0, atol=0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_frames", [1, 3, 100, 4097])
|
||||
@pytest.mark.parametrize("with_norm", [True, False])
|
||||
def test_dmel_embed_sum_norm(num_frames: int, with_norm: bool) -> None:
|
||||
torch.manual_seed(num_frames)
|
||||
n_bins, vocab, dim = 80, 16, 6144
|
||||
idx = torch.randint(
|
||||
0, vocab, (num_frames, n_bins), device="cuda", dtype=torch.int32
|
||||
)
|
||||
table = torch.randn(n_bins * vocab, dim, device="cuda", dtype=DTYPE)
|
||||
norm_w = torch.randn(dim, device="cuda", dtype=DTYPE)
|
||||
|
||||
flat = (torch.arange(n_bins, device="cuda", dtype=torch.int32) * vocab).unsqueeze(
|
||||
0
|
||||
) + idx
|
||||
ref = (
|
||||
F.embedding(flat.reshape(-1).long(), table)
|
||||
.reshape(num_frames, n_bins, dim)
|
||||
.sum(dim=1)
|
||||
)
|
||||
if with_norm:
|
||||
ref = _ref_rms_norm(ref, norm_w, 1e-6)
|
||||
|
||||
got = dmel_embed_sum_norm(idx, table, norm_w if with_norm else None, 1e-6)
|
||||
_assert_close_ulps(got, ref)
|
||||
|
||||
|
||||
def test_empty_inputs() -> None:
|
||||
x = torch.empty(0, 320, device="cuda", dtype=DTYPE)
|
||||
w = torch.randn(320, device="cuda", dtype=DTYPE)
|
||||
assert rmsnorm_gelu(x, w, 1e-5).shape == (0, 320)
|
||||
|
||||
idx = torch.empty(0, 80, device="cuda", dtype=torch.int32)
|
||||
table = torch.randn(1280, 6144, device="cuda", dtype=DTYPE)
|
||||
assert dmel_embed_sum_norm(idx, table, None, 0.0).shape == (0, 6144)
|
||||
@@ -0,0 +1,118 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.inkling.nvidia import moe
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
|
||||
def test_gate_loads_directly_into_padded_runtime_weight() -> None:
|
||||
gate = moe.InklingGate(
|
||||
d_model=4,
|
||||
n_routed_experts=5,
|
||||
n_shared_experts=2,
|
||||
experts_per_token=2,
|
||||
route_scale=1.0,
|
||||
)
|
||||
loaded = torch.arange(28, dtype=gate.weight.dtype).reshape(7, 4)
|
||||
|
||||
gate.weight.weight_loader(gate.weight, loaded)
|
||||
|
||||
assert gate.weight.shape == (8, 4)
|
||||
torch.testing.assert_close(gate.weight[:7], loaded)
|
||||
torch.testing.assert_close(gate.weight[7], torch.zeros(4))
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize(("num_tokens", "expected_calls"), [(1, 1), (64, 1), (65, 0)])
|
||||
def test_gate_uses_ll_bf16_gemm_through_token_limit(
|
||||
monkeypatch, num_tokens, expected_calls
|
||||
) -> None:
|
||||
gate = moe.InklingGate(
|
||||
d_model=8,
|
||||
n_routed_experts=5,
|
||||
n_shared_experts=2,
|
||||
experts_per_token=2,
|
||||
route_scale=1.0,
|
||||
).to(device="cuda", dtype=torch.bfloat16)
|
||||
hidden_states = torch.randn(num_tokens, 8, device="cuda", dtype=torch.bfloat16)
|
||||
calls = []
|
||||
|
||||
def fake_ll_bf16_gemm(x, weight):
|
||||
calls.append((x, weight))
|
||||
return torch.ones(num_tokens, 8, device="cuda", dtype=torch.float32)
|
||||
|
||||
monkeypatch.setattr(
|
||||
moe.current_platform, "has_device_capability", lambda capability: True
|
||||
)
|
||||
monkeypatch.setattr(moe.ll_bf16, "is_available", lambda: True)
|
||||
monkeypatch.setattr(moe.ll_bf16, "ll_bf16_gemm", fake_ll_bf16_gemm)
|
||||
|
||||
logits = gate.compute_logits(hidden_states)
|
||||
|
||||
assert len(calls) == expected_calls
|
||||
if calls:
|
||||
assert calls[0][0] is hidden_states
|
||||
assert calls[0][1] is gate.weight
|
||||
assert logits.shape == (num_tokens, 8)
|
||||
assert logits.dtype == torch.float32
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("projection", "amax"), [("w13", 4.375), ("w2", 2960.0)])
|
||||
def test_moe_loads_calibrated_input_scale(projection: str, amax: float) -> None:
|
||||
experts = SimpleNamespace(
|
||||
w13_input_scale=torch.nn.Parameter(torch.empty(3, 2)),
|
||||
w2_input_scale=torch.nn.Parameter(torch.empty(3)),
|
||||
)
|
||||
layer = SimpleNamespace(experts=SimpleNamespace(routed_experts=experts))
|
||||
|
||||
loaded = moe.InklingMoE.load_expert_weight(
|
||||
layer,
|
||||
f"experts.{projection}_weight.input_amax",
|
||||
torch.tensor([amax]),
|
||||
)
|
||||
|
||||
scale = getattr(experts, f"{projection}_input_scale")
|
||||
expected = torch.full_like(scale, amax / (448.0 * 6.0))
|
||||
torch.testing.assert_close(scale, expected)
|
||||
assert loaded == [f"experts.routed_experts.{projection}_input_scale"]
|
||||
|
||||
|
||||
def test_sink_down_projection_is_packed_during_load(monkeypatch) -> None:
|
||||
monkeypatch.setattr(moe, "get_tensor_model_parallel_world_size", lambda: 2)
|
||||
monkeypatch.setattr(moe, "get_tensor_model_parallel_rank", lambda: 1)
|
||||
sink = moe.InklingSinkExperts(n_experts=2, d_model=3, d_mlp=8)
|
||||
loaded = torch.arange(48, dtype=sink.w2_weight.dtype).reshape(2, 3, 8)
|
||||
|
||||
sink.load_weight("w2_weight", loaded)
|
||||
|
||||
expected = loaded[:, :, 4:].permute(1, 0, 2).reshape(3, 8)
|
||||
torch.testing.assert_close(sink.w2_weight, expected)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="requires CUDA")
|
||||
def test_sink_packed_weight_forward_matches_expert_sum(monkeypatch) -> None:
|
||||
monkeypatch.setattr(moe, "get_tensor_model_parallel_world_size", lambda: 2)
|
||||
monkeypatch.setattr(moe, "get_tensor_model_parallel_rank", lambda: 1)
|
||||
sink = moe.InklingSinkExperts(n_experts=2, d_model=3, d_mlp=8).to(
|
||||
device="cuda", dtype=torch.bfloat16
|
||||
)
|
||||
torch.manual_seed(1)
|
||||
w13 = torch.randn(2, 16, 3, dtype=torch.bfloat16)
|
||||
w2 = torch.randn(2, 3, 8, dtype=torch.bfloat16)
|
||||
sink.load_weight("w13_weight", w13)
|
||||
sink.load_weight("w2_weight", w2)
|
||||
x = torch.randn(5, 3, device="cuda", dtype=torch.bfloat16)
|
||||
gammas = torch.randn(5, 2, device="cuda")
|
||||
|
||||
output = sink(x, gammas)
|
||||
|
||||
raw = torch.einsum("td,efd->tef", x, w13[:, 8:].to("cuda"))
|
||||
hidden = torch.nn.functional.silu(raw[:, :, 0::2].float())
|
||||
hidden = (hidden * raw[:, :, 1::2] * gammas[:, :, None]).to(torch.bfloat16)
|
||||
expected = torch.einsum("tef,edf->td", hidden, w2[:, :, 4:].to("cuda"))
|
||||
torch.testing.assert_close(output, expected, rtol=0, atol=0)
|
||||
@@ -0,0 +1,258 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.models.inkling.nvidia.ops.sconv as sconv
|
||||
from vllm.models.inkling.nvidia.ops import qkvr_prep
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
_cap = current_platform.get_device_capability() if current_platform.is_cuda() else None
|
||||
|
||||
|
||||
def _make_inputs(*, is_local: bool, tokens: int = 33, tp_size: int = 4):
|
||||
torch.manual_seed(0)
|
||||
heads = 64 // tp_size
|
||||
kv_heads = (16 if is_local else 8) // tp_size
|
||||
head_dim = 128
|
||||
d_rel = 16
|
||||
rel_extent = 512 if is_local else 1024
|
||||
page_size = 16
|
||||
num_blocks = (tokens + page_size - 1) // page_size
|
||||
q_width = heads * head_dim
|
||||
kv_width = kv_heads * head_dim
|
||||
r_width = heads * d_rel
|
||||
device = "cuda"
|
||||
|
||||
qkvr = torch.randn(
|
||||
tokens,
|
||||
q_width + 2 * kv_width + r_width,
|
||||
device=device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
k_weight = torch.randn(kv_width, 4, device=device, dtype=torch.bfloat16)
|
||||
v_weight = torch.randn_like(k_weight)
|
||||
q_norm_weight = torch.randn(head_dim, device=device, dtype=torch.bfloat16)
|
||||
k_norm_weight = torch.randn_like(q_norm_weight)
|
||||
rel_proj = torch.randn(d_rel, rel_extent, device=device, dtype=torch.bfloat16)
|
||||
conv_cache = torch.zeros(
|
||||
num_blocks,
|
||||
kv_heads,
|
||||
page_size,
|
||||
2 * head_dim,
|
||||
device=device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
key_cache = torch.empty(
|
||||
num_blocks,
|
||||
page_size,
|
||||
kv_heads,
|
||||
head_dim,
|
||||
device=device,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
value_cache = torch.empty_like(key_cache)
|
||||
positions = torch.arange(tokens, device=device, dtype=torch.int64)
|
||||
block_table = torch.arange(num_blocks, device=device, dtype=torch.int32)[None]
|
||||
seq_idx = torch.zeros(tokens, device=device, dtype=torch.int32)
|
||||
slots = torch.arange(tokens, device=device, dtype=torch.int64)
|
||||
query_start = torch.zeros(tokens, device=device, dtype=torch.int32)
|
||||
log_scaling_n_floor = None if is_local else 128000
|
||||
log_scaling = None
|
||||
if log_scaling_n_floor is not None:
|
||||
log_scaling = torch.linspace(
|
||||
1.0,
|
||||
1.1,
|
||||
tokens,
|
||||
device=device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
return (
|
||||
qkvr,
|
||||
k_weight,
|
||||
v_weight,
|
||||
q_norm_weight,
|
||||
k_norm_weight,
|
||||
rel_proj,
|
||||
1e-6,
|
||||
heads,
|
||||
kv_heads,
|
||||
head_dim,
|
||||
d_rel,
|
||||
conv_cache,
|
||||
key_cache,
|
||||
value_cache,
|
||||
positions,
|
||||
block_table,
|
||||
seq_idx,
|
||||
slots,
|
||||
query_start,
|
||||
slots,
|
||||
0,
|
||||
head_dim,
|
||||
page_size,
|
||||
log_scaling,
|
||||
)
|
||||
|
||||
|
||||
def _reference(args):
|
||||
qkvr = args[0]
|
||||
heads, kv_heads, head_dim, d_rel = args[7:11]
|
||||
q_width = heads * head_dim
|
||||
kv_width = kv_heads * head_dim
|
||||
q, k, v, r = qkvr.split((q_width, kv_width, kv_width, heads * d_rel), dim=1)
|
||||
conv_cache = args[11].clone()
|
||||
k = sconv.fused_sconv(
|
||||
k.contiguous(),
|
||||
args[1],
|
||||
conv_cache,
|
||||
args[14],
|
||||
args[15],
|
||||
args[16],
|
||||
args[17],
|
||||
args[18],
|
||||
args[20],
|
||||
head_dim,
|
||||
args[22],
|
||||
)
|
||||
v = sconv.fused_sconv(
|
||||
v.contiguous(),
|
||||
args[2],
|
||||
conv_cache,
|
||||
args[14],
|
||||
args[15],
|
||||
args[16],
|
||||
args[17],
|
||||
args[18],
|
||||
args[21],
|
||||
head_dim,
|
||||
args[22],
|
||||
)
|
||||
|
||||
def rms_norm(x, weight):
|
||||
x = x.reshape(-1, head_dim).float()
|
||||
rstd = torch.rsqrt(x.square().mean(1, keepdim=True) + args[6])
|
||||
return (x * rstd * weight.float()).to(qkvr.dtype)
|
||||
|
||||
q = rms_norm(q, args[3]).view(qkvr.shape[0], heads, head_dim)
|
||||
k = rms_norm(k, args[4]).view(qkvr.shape[0], kv_heads, head_dim)
|
||||
v = v.view(qkvr.shape[0], kv_heads, head_dim)
|
||||
rel = torch.mm(r.reshape(-1, d_rel), args[5]).view(qkvr.shape[0], heads, -1)
|
||||
if args[23] is not None:
|
||||
q = (q.float() * args[23][:, None, None]).to(q.dtype)
|
||||
rel = (rel.float() * args[23][:, None, None]).to(rel.dtype)
|
||||
|
||||
key_cache = args[12].clone()
|
||||
value_cache = args[13].clone()
|
||||
slots = args[19]
|
||||
valid = slots >= 0
|
||||
key_cache.view(-1, kv_heads, head_dim)[slots[valid]] = k[valid]
|
||||
value_cache.view(-1, kv_heads, head_dim)[slots[valid]] = v[valid]
|
||||
return q.flatten(1), rel, key_cache, value_cache
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
_cap is None,
|
||||
reason="Inkling QKVR prep kernels require CUDA",
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("is_local", "tokens", "tp_size"),
|
||||
[
|
||||
(True, 9, 4),
|
||||
(False, 33, 4),
|
||||
(True, 33, 8),
|
||||
(True, 128, 4),
|
||||
(False, 128, 8),
|
||||
(True, 512, 4),
|
||||
(False, 640, 8),
|
||||
],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_qkvr_prep_matches_reference(is_local, tokens, tp_size):
|
||||
args = _make_inputs(is_local=is_local, tokens=tokens, tp_size=tp_size)
|
||||
ref_q, ref_rel, ref_key, ref_value = _reference(args)
|
||||
|
||||
q, rel = qkvr_prep.fused_qkvr_prep(*args)
|
||||
|
||||
torch.testing.assert_close(q, ref_q, rtol=0.01, atol=0.02)
|
||||
torch.testing.assert_close(rel, ref_rel, rtol=0.02, atol=0.125)
|
||||
torch.testing.assert_close(args[12], ref_key, rtol=0.01, atol=0.01)
|
||||
torch.testing.assert_close(args[13], ref_value, rtol=0, atol=0)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
_cap is None,
|
||||
reason="Inkling QKVR prep kernels require CUDA",
|
||||
)
|
||||
@pytest.mark.parametrize("tokens", [9, 128])
|
||||
@torch.inference_mode()
|
||||
def test_qkvr_log_scaling_preserves_bf16_norm_output(tokens):
|
||||
args = list(_make_inputs(is_local=False, tokens=tokens, tp_size=8))
|
||||
tau = args[23]
|
||||
assert tau is not None
|
||||
|
||||
scaled_q, scaled_rel = qkvr_prep.fused_qkvr_prep(*args)
|
||||
args[23] = None
|
||||
unscaled_q, unscaled_rel = qkvr_prep.fused_qkvr_prep(*args)
|
||||
|
||||
expected_q = (unscaled_q.float() * tau[:, None]).to(unscaled_q.dtype)
|
||||
expected_rel = (unscaled_rel.float() * tau[:, None, None]).to(unscaled_rel.dtype)
|
||||
torch.testing.assert_close(scaled_q, expected_q, rtol=0, atol=0)
|
||||
torch.testing.assert_close(scaled_rel, expected_rel, rtol=0, atol=0)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
_cap is None,
|
||||
reason="Inkling QKVR prep kernels require CUDA",
|
||||
)
|
||||
@pytest.mark.parametrize("tokens", [9, 128])
|
||||
@torch.inference_mode()
|
||||
def test_qkvr_prep_negative_slots_skip_cache_writes(tokens):
|
||||
args = list(_make_inputs(is_local=True, tokens=tokens))
|
||||
args[17].fill_(-1)
|
||||
args[19].fill_(-1)
|
||||
conv_cache = args[11].clone()
|
||||
key_cache = args[12].clone()
|
||||
value_cache = args[13].clone()
|
||||
|
||||
qkvr_prep.fused_qkvr_prep(*args)
|
||||
|
||||
torch.testing.assert_close(args[11], conv_cache, rtol=0, atol=0)
|
||||
torch.testing.assert_close(args[12], key_cache, rtol=0, atol=0)
|
||||
torch.testing.assert_close(args[13], value_cache, rtol=0, atol=0)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@torch.inference_mode()
|
||||
def test_fused_sconv_negative_slots_skip_cache_writes():
|
||||
args = list(_make_inputs(is_local=True, tokens=9))
|
||||
args[17].fill_(-1)
|
||||
cache = args[11].clone()
|
||||
|
||||
sconv.fused_sconv(
|
||||
args[0][:, 16 * 128 : 16 * 128 + 4 * 128].contiguous(),
|
||||
args[1],
|
||||
args[11],
|
||||
args[14],
|
||||
args[15],
|
||||
args[16],
|
||||
args[17],
|
||||
args[18],
|
||||
0,
|
||||
128,
|
||||
args[22],
|
||||
)
|
||||
|
||||
torch.testing.assert_close(args[11], cache, rtol=0, atol=0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("rel_extent", "last_latency_rows", "first_throughput_rows"),
|
||||
[(512, 8191, 8192), (1024, 2047, 2048)],
|
||||
)
|
||||
def test_rel_projection_schedule_crossover(
|
||||
rel_extent, last_latency_rows, first_throughput_rows
|
||||
):
|
||||
assert not qkvr_prep.use_rel_proj_throughput(last_latency_rows, rel_extent)
|
||||
assert qkvr_prep.use_rel_proj_throughput(first_throughput_rows, rel_extent)
|
||||
@@ -0,0 +1,119 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Parity test for the fused sconv seq-metadata kernel.
|
||||
|
||||
``sconv_seq_metadata`` fills the per-token ``seq_idx`` (owning request) and
|
||||
``query_start`` (first x-row of that request) buffers in a single launch. Actual
|
||||
tokens must match the searchsorted-based reference, while CUDA graph padding
|
||||
must be initialized to safe zero values.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.models.inkling.nvidia.ops.sconv import sconv_seq_metadata
|
||||
from vllm.models.inkling.nvidia.sconv_swa_attn import InklingSconvMetadataBuilder
|
||||
|
||||
CASES = [
|
||||
# (query_lens, extra_pad_tokens)
|
||||
([1], 0), # bsz1 decode
|
||||
([1] * 8, 0), # uniform decode
|
||||
([1] * 8, 3), # uniform decode, padded tokens past the last request
|
||||
([2] * 4, 0), # uniform spec-decode
|
||||
([2048], 0), # single prefill
|
||||
([517, 1, 1, 33, 1, 128], 0), # mixed prefill/decode
|
||||
([517, 1, 1, 33, 1, 128], 5), # mixed, padded
|
||||
([1] * 500, 0), # many requests (deep binary search)
|
||||
]
|
||||
|
||||
|
||||
def _ref(query_start_loc: torch.Tensor, num_reqs: int, num_tokens: int):
|
||||
cu_seqlens = query_start_loc[: num_reqs + 1].to(torch.int64)
|
||||
token_idx = torch.arange(num_tokens, device=cu_seqlens.device, dtype=torch.int64)
|
||||
seq_idx = (torch.searchsorted(cu_seqlens, token_idx, right=True) - 1).clamp(
|
||||
max=num_reqs - 1
|
||||
)
|
||||
return seq_idx.to(torch.int32), cu_seqlens[seq_idx].to(torch.int32)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("query_lens,extra_pad", CASES)
|
||||
def test_sconv_seq_metadata_matches_searchsorted(query_lens, extra_pad):
|
||||
device = "cuda"
|
||||
num_reqs = len(query_lens)
|
||||
query_start_loc = torch.tensor(
|
||||
[0] + list(torch.tensor(query_lens).cumsum(0)), dtype=torch.int32
|
||||
).to(device)
|
||||
num_actual_tokens = int(query_start_loc[-1])
|
||||
num_padded_tokens = num_actual_tokens + extra_pad
|
||||
|
||||
ref_seq, ref_qs = _ref(query_start_loc, num_reqs, num_actual_tokens)
|
||||
|
||||
seq_idx = torch.full((num_padded_tokens,), -1, dtype=torch.int32, device=device)
|
||||
query_start = torch.full_like(seq_idx, -1)
|
||||
sconv_seq_metadata(
|
||||
query_start_loc,
|
||||
num_reqs,
|
||||
num_actual_tokens,
|
||||
seq_idx,
|
||||
query_start,
|
||||
num_padded_tokens,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(seq_idx[:num_actual_tokens], ref_seq, rtol=0, atol=0)
|
||||
torch.testing.assert_close(query_start[:num_actual_tokens], ref_qs, rtol=0, atol=0)
|
||||
assert torch.count_nonzero(seq_idx[num_actual_tokens:]) == 0
|
||||
assert torch.count_nonzero(query_start[num_actual_tokens:]) == 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_sconv_metadata_reuses_padded_static_buffers():
|
||||
device = torch.device("cuda")
|
||||
builder = object.__new__(InklingSconvMetadataBuilder)
|
||||
builder.seq_idx_buffer = torch.empty(8, dtype=torch.int32, device=device)
|
||||
builder.query_start_buffer = torch.empty(8, dtype=torch.int32, device=device)
|
||||
|
||||
class CommonMetadata:
|
||||
num_reqs = 1
|
||||
num_actual_tokens = 8
|
||||
query_start_loc = torch.tensor([0, 3], dtype=torch.int32, device=device)
|
||||
query_start_loc_cpu = torch.tensor([0, 3], dtype=torch.int32)
|
||||
block_table_tensor = torch.zeros((1, 1), dtype=torch.int32, device=device)
|
||||
slot_mapping = torch.tensor(
|
||||
[0, 1, 2, -1, -1, -1, -1, -1],
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
|
||||
common = CommonMetadata()
|
||||
first = builder.build(0, common)
|
||||
pointers = tuple(
|
||||
tensor.data_ptr()
|
||||
for tensor in (
|
||||
first.block_table,
|
||||
first.slot_mapping,
|
||||
first.seq_idx,
|
||||
first.query_start,
|
||||
)
|
||||
)
|
||||
|
||||
common.query_start_loc[1] = 5
|
||||
common.query_start_loc_cpu[1] = 5
|
||||
common.slot_mapping[:5] = torch.arange(5, dtype=torch.int64, device=device)
|
||||
second = builder.build(0, common)
|
||||
|
||||
assert second.slot_mapping.shape == (8,)
|
||||
assert second.seq_idx.shape == (8,)
|
||||
assert second.query_start.shape == (8,)
|
||||
assert pointers == tuple(
|
||||
tensor.data_ptr()
|
||||
for tensor in (
|
||||
second.block_table,
|
||||
second.slot_mapping,
|
||||
second.seq_idx,
|
||||
second.query_start,
|
||||
)
|
||||
)
|
||||
assert torch.count_nonzero(second.seq_idx[5:]) == 0
|
||||
assert torch.count_nonzero(second.query_start[5:]) == 0
|
||||
assert torch.all(second.slot_mapping[5:] == -1)
|
||||
@@ -330,6 +330,12 @@ _TEXT_GENERATION_EXAMPLE_MODELS = {
|
||||
"naver-hyperclovax/HyperCLOVAX-SEED-Think-14B",
|
||||
min_transformers_version="5.9.0",
|
||||
),
|
||||
"InklingForCausalLM": _HfExamplesInfo(
|
||||
"thinkingmachines/Inkling-NVFP4",
|
||||
tokenizer_mode="inkling",
|
||||
trust_remote_code=True,
|
||||
max_model_len=4096,
|
||||
),
|
||||
"InternLM2ForCausalLM": _HfExamplesInfo(
|
||||
"internlm/internlm2-chat-7b", trust_remote_code=True
|
||||
),
|
||||
@@ -956,6 +962,12 @@ _MULTIMODAL_EXAMPLE_MODELS = {
|
||||
"HuggingFaceM4/Idefics3-8B-Llama3",
|
||||
extras={"tiny": "HuggingFaceTB/SmolVLM-256M-Instruct"},
|
||||
),
|
||||
"InklingForConditionalGeneration": _HfExamplesInfo(
|
||||
"thinkingmachines/Inkling-NVFP4",
|
||||
tokenizer_mode="inkling",
|
||||
trust_remote_code=True,
|
||||
max_model_len=4096,
|
||||
),
|
||||
"IsaacForConditionalGeneration": _HfExamplesInfo(
|
||||
"PerceptronAI/Isaac-0.1",
|
||||
trust_remote_code=True,
|
||||
|
||||
Reference in New Issue
Block a user