[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests
- Drop dead model modules, keeping files live imports require - Remove anthropic, cohere, codegen entrypoints and batch STT modes - Delete unused attention backends, MoE experts, and NPU/XPU util leaves - Strip dead third_party trees and ROCm leaves with no CUDA path - Remove mooncake EC connectors: dependency missing since branch base - Re-audit verified by full import sweep and Qwen3.5 smoke test Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,981 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import contextlib
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import AutoTokenizer
|
||||
from utils import (
|
||||
BACKENDS,
|
||||
TEST_MODEL,
|
||||
_extract_step_logprobs,
|
||||
_random_prompt,
|
||||
skip_if_not_cuda,
|
||||
skip_unsupported,
|
||||
)
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.inputs import TokensPrompt
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.flaky(reruns=3)
|
||||
@pytest.mark.timeout(1000)
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
@pytest.mark.parametrize("rms_norm_impl", ["default", "vllm_c"])
|
||||
def test_v1_generation_is_deterministic_across_batch_sizes_with_needle(
|
||||
backend,
|
||||
rms_norm_impl,
|
||||
):
|
||||
"""Ensures that the same request (the 'needle' prompt) yields identical output
|
||||
whether run alone (bs=1) or mixed into a larger batch (e.g., bs=64),
|
||||
using the high-level v1 LLM() API only (no manual batching).
|
||||
|
||||
Strategy:
|
||||
- Create a single LLM engine configured for the larger batch limit (N).
|
||||
- Compute a baseline output for the needle prompt when it is run alone.
|
||||
- For many trials, generate a mixed batch (size N) where the needle appears
|
||||
at a random position among random filler prompts using the same engine.
|
||||
- Track how many trials match vs mismatch, and report totals at the end.
|
||||
The test fails if any mismatches occur, but we still dump pass/fail
|
||||
counts.
|
||||
|
||||
Notes:
|
||||
- Use seeded stochastic sampling with a fixed seed to test determinism.
|
||||
- Outputs are intentionally longer and sampled at higher temperature/top_p
|
||||
to produce a more random-sounding phrase, yet remain deterministic by
|
||||
seed.
|
||||
- Keep max_tokens and max_model_len bounded for speed and memory use.
|
||||
|
||||
"""
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
|
||||
attention_config = {"backend": backend}
|
||||
# Force the C++ RMSNorm implementation so we actually exercise the
|
||||
# num_tokens-dependent block-size branches.
|
||||
kernel_config = None
|
||||
if rms_norm_impl == "vllm_c":
|
||||
kernel_config = {
|
||||
"ir_op_priority": {
|
||||
"rms_norm": ["vllm_c"],
|
||||
"fused_add_rms_norm": ["vllm_c"],
|
||||
}
|
||||
}
|
||||
# Allow overrides from environment (useful for CI tuning)
|
||||
# "facebook/opt-125m" is too small, doesn't reliably test determinism
|
||||
model = TEST_MODEL
|
||||
num_trials = int(os.getenv("VLLM_NEEDLE_TRIALS", "5"))
|
||||
max_batch_size = int(os.getenv("VLLM_NEEDLE_BATCH_SIZE", "128"))
|
||||
min_random_prompt = int(os.getenv("VLLM_MIN_PROMPT", "1024"))
|
||||
max_random_prompt = int(os.getenv("VLLM_MAX_PROMPT", "2048"))
|
||||
assert max_batch_size >= 2, "Batch size should be >= 2 to mix needle."
|
||||
|
||||
# Keep GPU memory usage low to avoid startup allocation failures.
|
||||
gpu_mem_util = float(os.getenv("VLLM_GPU_MEMORY_UTILIZATION", "0.5"))
|
||||
max_model_len = int(os.getenv("VLLM_MAX_MODEL_LEN", "5120"))
|
||||
|
||||
# Sampling parameters: longer outputs with a more random-sounding
|
||||
# continuation,but still deterministic due to fixed seed.
|
||||
temperature = float(os.getenv("VLLM_NEEDLE_TEMPERATURE", "0.0"))
|
||||
top_p = float(os.getenv("VLLM_NEEDLE_TOP_P", "0.95"))
|
||||
max_tokens = int(os.getenv("VLLM_NEEDLE_MAX_TOKENS", "128"))
|
||||
|
||||
sampling = SamplingParams(
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
max_tokens=max_tokens,
|
||||
seed=20240919,
|
||||
)
|
||||
|
||||
needle_prompt = "There once was a "
|
||||
|
||||
llm = None
|
||||
try:
|
||||
llm = LLM_with_max_seqs(
|
||||
model=model,
|
||||
max_num_seqs=max_batch_size,
|
||||
gpu_memory_utilization=gpu_mem_util,
|
||||
max_model_len=max_model_len,
|
||||
attention_config=attention_config,
|
||||
kernel_config=kernel_config,
|
||||
)
|
||||
|
||||
# Baseline generation for the needle prompt alone.
|
||||
baseline_out = llm.generate([needle_prompt], sampling)
|
||||
assert len(baseline_out) == 1
|
||||
assert len(baseline_out[0].outputs) >= 1
|
||||
baseline_text = baseline_out[0].outputs[0].text
|
||||
|
||||
mismatches = 0
|
||||
|
||||
for trial in range(num_trials):
|
||||
# Create a batch of size `max_batch_size` and insert the needle at
|
||||
# a random index
|
||||
prompts: list[str] = []
|
||||
batch_size = random.randint(max_batch_size // 2, max_batch_size)
|
||||
needle_pos = random.randint(0, batch_size - 1)
|
||||
for i in range(batch_size):
|
||||
if i == needle_pos:
|
||||
prompts.append(needle_prompt)
|
||||
else:
|
||||
prompts.append(_random_prompt(min_random_prompt, max_random_prompt))
|
||||
|
||||
# Generate with the same engine but in a larger batch.
|
||||
outputs = llm.generate(prompts, sampling)
|
||||
# Find the needle output by position
|
||||
needle_output = outputs[needle_pos]
|
||||
assert needle_output.prompt == needle_prompt
|
||||
assert len(needle_output.outputs) >= 1
|
||||
text = needle_output.outputs[0].text
|
||||
|
||||
if text != baseline_text:
|
||||
print(f"{text}\n\n== Not the same as ==\n\n{baseline_text}\n\n")
|
||||
mismatches += 1
|
||||
|
||||
passes = num_trials - mismatches
|
||||
# Dump how many passed vs failed
|
||||
print(
|
||||
f"[determinism] total={num_trials}, passed={passes}, "
|
||||
f"failed={mismatches}, max_batch_size={max_batch_size}"
|
||||
)
|
||||
|
||||
if mismatches > 0:
|
||||
pytest.fail(
|
||||
f"Nondeterministic outputs detected: {mismatches} failed out "
|
||||
f"of {num_trials} trials (max_batch_size={max_batch_size})."
|
||||
)
|
||||
|
||||
finally:
|
||||
# Ensure engines are shutdown to free GPU/VRAM across test sessions
|
||||
if llm is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"block_m,block_n",
|
||||
[(16, 16), (8, 16)],
|
||||
)
|
||||
def test_logprobs_bitwise_batch_invariance_bs1_vs_bsN(
|
||||
backend,
|
||||
block_m,
|
||||
block_n,
|
||||
):
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
|
||||
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
disable_custom_all_reduce=os.getenv("VLLM_TEST_DISABLE_CUSTOM_AR") == "1",
|
||||
max_num_seqs=128,
|
||||
max_model_len=8192,
|
||||
dtype="auto", # not everything is supported
|
||||
gpu_memory_utilization=0.9,
|
||||
attention_config={
|
||||
"backend": backend,
|
||||
"flex_attn_block_m": block_m,
|
||||
"flex_attn_block_n": block_n,
|
||||
},
|
||||
)
|
||||
|
||||
# Use more realistic prompts for better token generation
|
||||
prompts = [_random_prompt(10, 50) for _ in range(32)]
|
||||
|
||||
# Chunked prefill is covered by
|
||||
# test_logprobs_bitwise_batch_invariance_ragged_chunked_prefill below.
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.6,
|
||||
top_p=1.0,
|
||||
max_tokens=16,
|
||||
seed=1234,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
# BS=1: run prompts individually and collect logprobs per step.
|
||||
print("\n" + "=" * 80)
|
||||
print("STARTING BS=1 RUNS (each prompt individually)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
bs1_logprobs_per_prompt = []
|
||||
bs1_tokens_per_prompt = []
|
||||
for idx, p in enumerate(prompts):
|
||||
print(f"\n[BS=1] Running prompt {idx}/{len(prompts)} - Preview: {p[:80]}...")
|
||||
outs = llm.generate([p], sp, use_tqdm=False)
|
||||
assert len(outs) == 1
|
||||
step_logprobs, token_ids = _extract_step_logprobs(outs[0])
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bs1_logprobs_per_prompt.append(step_logprobs)
|
||||
bs1_tokens_per_prompt.append(token_ids)
|
||||
print(f"[BS=1] Prompt {idx} generated tokens: {token_ids}")
|
||||
|
||||
# BS=N: run prompts in a batch and collect logprobs per step for each
|
||||
# prompt.
|
||||
print("\n" + "=" * 80)
|
||||
print(f"STARTING BS={len(prompts)} RUN (all prompts batched)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
outs_batched = llm.generate(prompts, sp, use_tqdm=False)
|
||||
assert len(outs_batched) == len(prompts)
|
||||
bsN_logprobs_per_prompt = []
|
||||
bsN_tokens_per_prompt = []
|
||||
|
||||
print(f"\n[BS={len(prompts)}] Processing batched outputs...")
|
||||
for idx, o in enumerate(outs_batched):
|
||||
tokens = o.outputs[0].token_ids if o.outputs else "N/A"
|
||||
print(f"[BS={len(prompts)}] Prompt {idx} generated tokens: {tokens}")
|
||||
step_logprobs, token_ids = _extract_step_logprobs(o)
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bsN_logprobs_per_prompt.append(step_logprobs)
|
||||
bsN_tokens_per_prompt.append(token_ids)
|
||||
|
||||
# Compare step-by-step logprobs for each prompt between BS=1 and BS=N runs.
|
||||
failed_prompts = []
|
||||
for i, (logprobs_bs1, logprobs_bsN, tokens_bs1, tokens_bsN) in enumerate(
|
||||
zip(
|
||||
bs1_logprobs_per_prompt,
|
||||
bsN_logprobs_per_prompt,
|
||||
bs1_tokens_per_prompt,
|
||||
bsN_tokens_per_prompt,
|
||||
)
|
||||
):
|
||||
if len(logprobs_bs1) != len(logprobs_bsN):
|
||||
reason = (
|
||||
f"Different number of steps: {len(logprobs_bs1)} (BS=1) "
|
||||
f"vs {len(logprobs_bsN)} (BS=N)"
|
||||
)
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "all",
|
||||
"reason": reason,
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# Check if tokens match first
|
||||
if tokens_bs1 != tokens_bsN:
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "sampling",
|
||||
"reason": "Different tokens sampled",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
"bs1_all_logprobs": [
|
||||
logprobs_bs1[s].tolist() for s in range(len(logprobs_bs1))
|
||||
],
|
||||
"bsN_all_logprobs": [
|
||||
logprobs_bsN[s].tolist() for s in range(len(logprobs_bsN))
|
||||
],
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
for t, (a, b) in enumerate(zip(logprobs_bs1, logprobs_bsN)):
|
||||
if a.shape != b.shape:
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Shape mismatch: {a.shape} vs {b.shape}",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
if not torch.equal(a, b):
|
||||
max_diff = torch.abs(a - b).max().item()
|
||||
# Print which token failed
|
||||
print(f"\n[DIVERGENCE] Prompt {i}, Token {t}: max_diff={max_diff:.6e}")
|
||||
bs1_tok = tokens_bs1[t] if t < len(tokens_bs1) else "N/A"
|
||||
bsN_tok = tokens_bsN[t] if t < len(tokens_bsN) else "N/A"
|
||||
print(f" Token IDs: bs1={bs1_tok}, bsN={bsN_tok}")
|
||||
print(f" BS=1 logprob: {a.tolist()}")
|
||||
print(f" BS=N logprob: {b.tolist()}")
|
||||
failed_prompts.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Bitwise mismatch (max_diff={max_diff:.6e})",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
"bs1_all_logprobs": [
|
||||
logprobs_bs1[s].tolist() for s in range(len(logprobs_bs1))
|
||||
],
|
||||
"bsN_all_logprobs": [
|
||||
logprobs_bsN[s].tolist() for s in range(len(logprobs_bsN))
|
||||
],
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
# Print summary of all failures
|
||||
if failed_prompts:
|
||||
print(f"\n{'=' * 80}")
|
||||
fail_msg = (
|
||||
f"BATCH INVARIANCE FAILURES: {len(failed_prompts)}/"
|
||||
f"{len(prompts)} prompts failed"
|
||||
)
|
||||
print(fail_msg)
|
||||
print(f"{'=' * 80}")
|
||||
for fail in failed_prompts:
|
||||
print(f"\nPrompt {fail['prompt_idx']} (step {fail['step']}):")
|
||||
print(f" Reason: {fail['reason']}")
|
||||
print(f" Preview: {fail['prompt_preview']}...")
|
||||
|
||||
# Always show the tokens
|
||||
if "bs1_tokens" in fail:
|
||||
print(f" BS=1 tokens: {fail['bs1_tokens']}")
|
||||
if "bsN_tokens" in fail:
|
||||
print(f" BS=N tokens: {fail['bsN_tokens']}")
|
||||
|
||||
if "bs1_all_logprobs" in fail:
|
||||
print(f" BS=1 logprobs for all {len(fail['bs1_all_logprobs'])} steps:")
|
||||
for step_idx, logprobs in enumerate(fail["bs1_all_logprobs"]):
|
||||
print(f" Step {step_idx}: {logprobs}")
|
||||
print(f" BS=N logprobs for all {len(fail['bsN_all_logprobs'])} steps:")
|
||||
for step_idx, logprobs in enumerate(fail["bsN_all_logprobs"]):
|
||||
print(f" Step {step_idx}: {logprobs}")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
# Fail the test with summary
|
||||
msg = (
|
||||
f"Batch invariance violated in {len(failed_prompts)}/"
|
||||
f"{len(prompts)} prompts. See output above for details."
|
||||
)
|
||||
pytest.fail(msg)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
def test_logprobs_bitwise_batch_invariance_ragged_chunked_prefill(backend):
|
||||
"""Batch invariance must hold when a prefill is split across chunks."""
|
||||
random.seed(int(os.getenv("VLLM_TEST_SEED", "12345")))
|
||||
|
||||
prompts = (
|
||||
[_random_prompt(10, 50) for _ in range(8)]
|
||||
+ [_random_prompt(300, 450) for _ in range(4)]
|
||||
+ [_random_prompt(800, 1200) for _ in range(2)]
|
||||
)
|
||||
random.shuffle(prompts)
|
||||
|
||||
# _random_prompt takes a word target, not a token count, and the ratio
|
||||
# depends on the tokenizer, so derive the budget rather than hardcode it:
|
||||
# half the longest prompt splits that prefill whatever TEST_MODEL is, while
|
||||
# the shorter prompts are still co-scheduled whole. Floor is max_num_seqs.
|
||||
tokenizer = AutoTokenizer.from_pretrained(TEST_MODEL)
|
||||
prompt_lens = [len(tokenizer(p).input_ids) for p in prompts]
|
||||
max_num_batched_tokens = max(len(prompts), max(prompt_lens) // 2)
|
||||
assert max_num_batched_tokens < max(prompt_lens), (
|
||||
f"a {max_num_batched_tokens}-token budget does not split the longest "
|
||||
f"prompt ({max(prompt_lens)} tokens), so nothing would be chunked"
|
||||
)
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.6, top_p=1.0, max_tokens=16, seed=1234, logprobs=5
|
||||
)
|
||||
llm = LLM_with_max_seqs(
|
||||
model=TEST_MODEL,
|
||||
max_num_seqs=len(prompts),
|
||||
gpu_memory_utilization=float(os.getenv("VLLM_GPU_MEMORY_UTILIZATION", "0.5")),
|
||||
max_model_len=4096,
|
||||
attention_config={"backend": backend},
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
)
|
||||
|
||||
try:
|
||||
bs1 = []
|
||||
for p in prompts:
|
||||
out = llm.generate([p], sp, use_tqdm=False)[0]
|
||||
bs1.append(_extract_step_logprobs(out))
|
||||
if any(logprobs is None for logprobs, _ in bs1):
|
||||
pytest.skip("Logprobs are not available on RequestOutput.")
|
||||
|
||||
outs_batched = llm.generate(prompts, sp, use_tqdm=False)
|
||||
assert len(outs_batched) == len(prompts)
|
||||
|
||||
mismatches = []
|
||||
for i, out in enumerate(outs_batched):
|
||||
logprobs, tokens = _extract_step_logprobs(out)
|
||||
bs1_logprobs, bs1_tokens = bs1[i]
|
||||
n = prompt_lens[i]
|
||||
if tokens != bs1_tokens:
|
||||
mismatches.append(f"prompt {i} ({n} tokens): tokens differ")
|
||||
elif not torch.equal(bs1_logprobs, logprobs):
|
||||
delta = torch.max(torch.abs(bs1_logprobs - logprobs)).item()
|
||||
mismatches.append(
|
||||
f"prompt {i} ({n} tokens): logprobs differ, max|delta|={delta:.3e}"
|
||||
)
|
||||
|
||||
assert not mismatches, (
|
||||
"Batch invariance violated under chunked prefill "
|
||||
f"(max_num_batched_tokens={max_num_batched_tokens}): "
|
||||
+ "; ".join(mismatches)
|
||||
)
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
def test_simple_generation(backend):
|
||||
"""Simple test that runs the model with a basic prompt and prints the output.
|
||||
Useful for quick smoke testing and debugging.
|
||||
"""
|
||||
model = TEST_MODEL
|
||||
|
||||
llm = LLM(
|
||||
model=model,
|
||||
max_num_seqs=1,
|
||||
tensor_parallel_size=int(os.getenv("VLLM_TP_SIZE", "1")),
|
||||
gpu_memory_utilization=0.9,
|
||||
max_model_len=2048,
|
||||
dtype="auto",
|
||||
enable_prefix_caching=False,
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
prompt = "the capital of france is"
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=20,
|
||||
)
|
||||
|
||||
print(f"\n{'=' * 80}")
|
||||
print("Running simple generation test")
|
||||
print(f"Prompt: '{prompt}'")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
try:
|
||||
outputs = llm.generate([prompt], sampling_params)
|
||||
|
||||
assert len(outputs) == 1
|
||||
output_text = outputs[0].outputs[0].text
|
||||
|
||||
print(f"Output: '{output_text}'")
|
||||
print(f"\n{'=' * 80}")
|
||||
print(f"Full completion: '{prompt}{output_text}'")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"backend",
|
||||
BACKENDS,
|
||||
)
|
||||
def test_logprobs_without_batch_invariance_should_fail(
|
||||
backend, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""This test is the inverse of test_logprobs_bitwise_batch_invariance_bs1_vs_bsN.
|
||||
It DISABLES batch invariance mode and expects to see non-deterministic behavior
|
||||
between BS=1 and BS=N runs. This demonstrates that batch invariance is actually
|
||||
doing something useful.
|
||||
|
||||
The test will PASS if we detect differences (proving batch invariance matters).
|
||||
The test will FAIL if everything matches (suggesting batch invariance isn't needed).
|
||||
"""
|
||||
# CRITICAL: Disable batch invariance for this test
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0")
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", False)
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
|
||||
|
||||
print(f"\n{'=' * 80}")
|
||||
print("BATCH INVARIANCE DISABLED: Expecting non-deterministic behavior")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
max_num_seqs=32,
|
||||
max_model_len=8192,
|
||||
dtype="auto",
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
# build ragged prompts to change shapes significantly across BS=1 vs BS=N
|
||||
long_min = int(os.getenv("VLLM_MIN_PROMPT", "768"))
|
||||
long_max = int(os.getenv("VLLM_MAX_PROMPT", "2048"))
|
||||
prompts: list[str] = []
|
||||
options = [
|
||||
(max(long_min, 1536), max(long_max, 3072)), # very long
|
||||
(max(1024, long_min), max(2048, long_max)), # long
|
||||
(256, 512), # mid
|
||||
(10, 20), # short
|
||||
]
|
||||
|
||||
for _ in range(32):
|
||||
lo, hi = random.choice(options)
|
||||
prompts.append(_random_prompt(lo, hi))
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.6,
|
||||
top_p=1.0,
|
||||
max_tokens=8,
|
||||
seed=1234,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
# BS=1: run prompts individually and collect logprobs per step.
|
||||
print("\n" + "=" * 80)
|
||||
print("STARTING BS=1 RUNS (each prompt individually)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
bs1_logprobs_per_prompt = []
|
||||
bs1_tokens_per_prompt = []
|
||||
for idx, p in enumerate(prompts):
|
||||
print(f"\n[BS=1] Running prompt {idx}/{len(prompts)} - Preview: {p[:80]}...")
|
||||
outs = llm.generate([p], sp, use_tqdm=False)
|
||||
assert len(outs) == 1
|
||||
step_logprobs, token_ids = _extract_step_logprobs(outs[0])
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bs1_logprobs_per_prompt.append(step_logprobs)
|
||||
bs1_tokens_per_prompt.append(token_ids)
|
||||
print(f"[BS=1] Prompt {idx} generated tokens: {token_ids}")
|
||||
|
||||
# BS=N: run prompts in a batch and collect logprobs per step for each prompt.
|
||||
print("\n" + "=" * 80)
|
||||
print(f"STARTING BS={len(prompts)} RUN (all prompts batched)")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
outs_batched = llm.generate(prompts, sp, use_tqdm=False)
|
||||
assert len(outs_batched) == len(prompts)
|
||||
bsN_logprobs_per_prompt = []
|
||||
bsN_tokens_per_prompt = []
|
||||
|
||||
print(f"\n[BS={len(prompts)}] Processing batched outputs...")
|
||||
for idx, o in enumerate(outs_batched):
|
||||
tokens = o.outputs[0].token_ids if o.outputs else "N/A"
|
||||
print(f"[BS={len(prompts)}] Prompt {idx} generated tokens: {tokens}")
|
||||
step_logprobs, token_ids = _extract_step_logprobs(o)
|
||||
if step_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logits are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
bsN_logprobs_per_prompt.append(step_logprobs)
|
||||
bsN_tokens_per_prompt.append(token_ids)
|
||||
|
||||
# Compare step-by-step logprobs for each prompt between BS=1 and BS=N runs.
|
||||
differences_found = []
|
||||
for i, (logprobs_bs1, logprobs_bsN, tokens_bs1, tokens_bsN) in enumerate(
|
||||
zip(
|
||||
bs1_logprobs_per_prompt,
|
||||
bsN_logprobs_per_prompt,
|
||||
bs1_tokens_per_prompt,
|
||||
bsN_tokens_per_prompt,
|
||||
)
|
||||
):
|
||||
if len(logprobs_bs1) != len(logprobs_bsN):
|
||||
reason = (
|
||||
f"Different number of steps: {len(logprobs_bs1)} (BS=1) "
|
||||
f"vs {len(logprobs_bsN)} (BS=N)"
|
||||
)
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "all",
|
||||
"reason": reason,
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
# Check if tokens match first
|
||||
if tokens_bs1 != tokens_bsN:
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": "sampling",
|
||||
"reason": "Different tokens sampled",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
for t, (a, b) in enumerate(zip(logprobs_bs1, logprobs_bsN)):
|
||||
if a.shape != b.shape:
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Shape mismatch: {a.shape} vs {b.shape}",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
if not torch.equal(a, b):
|
||||
max_diff = torch.abs(a - b).max().item()
|
||||
print(
|
||||
f"\n[EXPECTED DIVERGENCE FOUND] Prompt {i}, "
|
||||
f"Token {t}: max_diff={max_diff:.6e}"
|
||||
)
|
||||
bs1_tok = tokens_bs1[t] if t < len(tokens_bs1) else "N/A"
|
||||
bsN_tok = tokens_bsN[t] if t < len(tokens_bsN) else "N/A"
|
||||
print(f" Token IDs: bs1={bs1_tok}, bsN={bsN_tok}")
|
||||
print(f" BS=1 logprob: {a.tolist()}")
|
||||
print(f" BS=N logprob: {b.tolist()}")
|
||||
differences_found.append(
|
||||
{
|
||||
"prompt_idx": i,
|
||||
"step": t,
|
||||
"reason": f"Bitwise mismatch (max_diff={max_diff:.6e})",
|
||||
"prompt_preview": prompts[i][:100],
|
||||
"bs1_tokens": tokens_bs1,
|
||||
"bsN_tokens": tokens_bsN,
|
||||
}
|
||||
)
|
||||
break
|
||||
|
||||
# Print summary
|
||||
print(f"\n{'=' * 80}")
|
||||
if differences_found:
|
||||
success_msg = (
|
||||
f"✓ SUCCESS: Batch invariance is doing something! "
|
||||
f"Found {len(differences_found)}/{len(prompts)} prompts "
|
||||
f"with differences when batch invariance was DISABLED."
|
||||
)
|
||||
print(success_msg)
|
||||
print(f"{'=' * 80}")
|
||||
for diff in differences_found:
|
||||
print(f"\nPrompt {diff['prompt_idx']} (step {diff['step']}):")
|
||||
print(f" Reason: {diff['reason']}")
|
||||
print(f" Preview: {diff['prompt_preview']}...")
|
||||
if "bs1_tokens" in diff:
|
||||
print(f" BS=1 tokens: {diff['bs1_tokens']}")
|
||||
if "bsN_tokens" in diff:
|
||||
print(f" BS=N tokens: {diff['bsN_tokens']}")
|
||||
print(f"{'=' * 80}\n")
|
||||
# Test PASSES because we found differences (batch invariance matters!)
|
||||
return
|
||||
else:
|
||||
# Test FAILS because everything matched even without batch invariance
|
||||
fail_msg = (
|
||||
f"✗ UNEXPECTED: All {len(prompts)} prompts matched "
|
||||
f"between BS=1 and BS=N even with batch invariance DISABLED. "
|
||||
f"This suggests batch invariance might not be necessary, "
|
||||
f"or the test needs more sensitive prompts."
|
||||
)
|
||||
print(fail_msg)
|
||||
print(f"{'=' * 80}\n")
|
||||
pytest.fail(fail_msg)
|
||||
|
||||
|
||||
@skip_if_not_cuda
|
||||
@pytest.mark.parametrize("backend", ["FLASH_ATTN"])
|
||||
def test_decode_logprobs_match_prefill_logprobs(
|
||||
backend,
|
||||
):
|
||||
"""Test that verifies decode logprobs match prefill logprobs.
|
||||
|
||||
For each decoded token at position i:
|
||||
1. Run decode to generate N tokens and collect their logprobs
|
||||
2. For each position i in [0, N):
|
||||
- Take prefix = prompt + tokens[0:i]
|
||||
- Run prefill(prefix + tokens[i]) to get logprob of tokens[i]
|
||||
- Verify prefill logprob matches decode logprob bitwise
|
||||
|
||||
This ensures that the logprobs from decode are consistent with what
|
||||
we would get if we ran prefill on each prefix.
|
||||
"""
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
|
||||
|
||||
llm = LLM(
|
||||
model=TEST_MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
max_num_seqs=32,
|
||||
max_model_len=8192,
|
||||
dtype="auto",
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
# Use a few test prompts
|
||||
num_test_prompts = int(os.getenv("VLLM_DECODE_PREFILL_NUM_PROMPTS", "4"))
|
||||
prompts = [_random_prompt(10, 50) for _ in range(num_test_prompts)]
|
||||
|
||||
# Generate longer sequences to test multiple decode steps
|
||||
max_tokens = int(os.getenv("VLLM_DECODE_PREFILL_MAX_TOKENS", "16"))
|
||||
|
||||
sp = SamplingParams(
|
||||
temperature=0.0, # Greedy for determinism
|
||||
max_tokens=max_tokens,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
print("\n" + "=" * 80)
|
||||
print("STEP 1: Running decode to generate tokens and collect logprobs")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
# Step 1: Run decode and collect logprobs
|
||||
decode_outputs = llm.generate(prompts, sp, use_tqdm=False)
|
||||
|
||||
failed_comparisons = []
|
||||
|
||||
for prompt_idx, (prompt, decode_output) in enumerate(zip(prompts, decode_outputs)):
|
||||
print(f"\n[Prompt {prompt_idx}] Testing: {prompt[:80]}...")
|
||||
|
||||
# Extract decode logprobs and tokens
|
||||
decode_logprobs, token_ids = _extract_step_logprobs(decode_output)
|
||||
if decode_logprobs is None:
|
||||
pytest.skip(
|
||||
"Logprobs are not available on RequestOutput; "
|
||||
"enable logprobs return to run this test."
|
||||
)
|
||||
|
||||
print(f"[Prompt {prompt_idx}] Generated {len(token_ids)} tokens: {token_ids}")
|
||||
print(f"[Prompt {prompt_idx}] Decode logprobs: {decode_logprobs.tolist()}")
|
||||
|
||||
# Step 2: For each token position, run prefill and compare.
|
||||
prompt_token_ids = list(decode_output.prompt_token_ids or [])
|
||||
|
||||
print(f"\n[Prompt {prompt_idx}] Verifying each token via prefill...")
|
||||
|
||||
for token_idx in range(len(token_ids)):
|
||||
# Construct the prefix up to (but not including) this token using
|
||||
# token ids directly.
|
||||
current_token = token_ids[token_idx]
|
||||
prefix_token_ids = prompt_token_ids + list(token_ids[:token_idx])
|
||||
|
||||
# Now run prefill with max_tokens=1 to get the logprob of the next token
|
||||
prefill_sp = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=1,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
print(
|
||||
f" [Token {token_idx}] Running prefill for prefix "
|
||||
f"(num_tokens={len(prefix_token_ids)})..."
|
||||
)
|
||||
prefill_output = llm.generate(
|
||||
[TokensPrompt(prompt_token_ids=prefix_token_ids)],
|
||||
prefill_sp,
|
||||
use_tqdm=False,
|
||||
)[0]
|
||||
prefill_logprobs, prefill_token_ids_out = _extract_step_logprobs(
|
||||
prefill_output
|
||||
)
|
||||
|
||||
if prefill_logprobs is None:
|
||||
print(f" [Token {token_idx}] Warning: No prefill logprobs available")
|
||||
continue
|
||||
|
||||
# The first token from prefill should match the current token
|
||||
prefill_token = prefill_token_ids_out[0]
|
||||
prefill_logprob = prefill_logprobs[0].item()
|
||||
decode_logprob = decode_logprobs[token_idx].item()
|
||||
|
||||
print(
|
||||
f" [Token {token_idx}] Decode token: {current_token}, "
|
||||
f"logprob: {decode_logprob:.8f}"
|
||||
)
|
||||
print(
|
||||
f" [Token {token_idx}] Prefill token: {prefill_token}, "
|
||||
f"logprob: {prefill_logprob:.8f}"
|
||||
)
|
||||
|
||||
# Check if tokens match
|
||||
if current_token != prefill_token:
|
||||
failed_comparisons.append(
|
||||
{
|
||||
"prompt_idx": prompt_idx,
|
||||
"token_idx": token_idx,
|
||||
"reason": "Token mismatch",
|
||||
"decode_token": current_token,
|
||||
"prefill_token": prefill_token,
|
||||
"decode_logprob": decode_logprob,
|
||||
"prefill_logprob": prefill_logprob,
|
||||
"prompt_text": prompt[:100],
|
||||
"prefix_token_ids": prefix_token_ids[:50],
|
||||
}
|
||||
)
|
||||
print(f" [Token {token_idx}] ✗ TOKEN MISMATCH!")
|
||||
continue
|
||||
|
||||
# Check if logprobs match bitwise
|
||||
if decode_logprob != prefill_logprob:
|
||||
diff = abs(decode_logprob - prefill_logprob)
|
||||
failed_comparisons.append(
|
||||
{
|
||||
"prompt_idx": prompt_idx,
|
||||
"token_idx": token_idx,
|
||||
"reason": "Logprob mismatch",
|
||||
"decode_token": current_token,
|
||||
"prefill_token": prefill_token,
|
||||
"decode_logprob": decode_logprob,
|
||||
"prefill_logprob": prefill_logprob,
|
||||
"diff": diff,
|
||||
"prompt_text": prompt[:100],
|
||||
"prefix_token_ids": prefix_token_ids[:50],
|
||||
"decode_all_tokens": token_ids,
|
||||
"decode_all_logprobs": decode_logprobs.tolist(),
|
||||
}
|
||||
)
|
||||
print(f" [Token {token_idx}] ✗ LOGPROB MISMATCH! diff={diff:.8e}")
|
||||
else:
|
||||
print(f" [Token {token_idx}] ✓ Match (bitwise equal)")
|
||||
|
||||
# Print summary
|
||||
print(f"\n{'=' * 80}")
|
||||
if failed_comparisons:
|
||||
print(f"DECODE-PREFILL MISMATCH: {len(failed_comparisons)} failures detected")
|
||||
print(f"{'=' * 80}")
|
||||
|
||||
# Group failures by prompt for better readability
|
||||
failures_by_prompt: dict[int, list[dict]] = {}
|
||||
for fail in failed_comparisons:
|
||||
pid = fail["prompt_idx"]
|
||||
if pid not in failures_by_prompt:
|
||||
failures_by_prompt[pid] = []
|
||||
failures_by_prompt[pid].append(fail)
|
||||
|
||||
for prompt_idx, failures in failures_by_prompt.items():
|
||||
print(f"\n{'=' * 80}")
|
||||
print(f"PROMPT {prompt_idx}: {failures[0]['prompt_text']}...")
|
||||
print(f"{'=' * 80}")
|
||||
print(f"Total failures for this prompt: {len(failures)}")
|
||||
|
||||
# Show where mismatches occur (which token positions)
|
||||
mismatch_positions = [f["token_idx"] for f in failures]
|
||||
print(f"Mismatch at token positions: {mismatch_positions}")
|
||||
|
||||
# Show first few failures in detail
|
||||
for i, fail in enumerate(failures[:5]): # Show first 5 failures per prompt
|
||||
print(f"\n [Failure {i + 1}] Token position {fail['token_idx']}:")
|
||||
print(f" Reason: {fail['reason']}")
|
||||
print(f" Prefix token ids: {fail['prefix_token_ids']}...")
|
||||
print(
|
||||
f" Decode: token={fail['decode_token']}, "
|
||||
f"logprob={fail['decode_logprob']:.10f}"
|
||||
)
|
||||
print(
|
||||
f" Prefill: token={fail['prefill_token']}, "
|
||||
f"logprob={fail['prefill_logprob']:.10f}"
|
||||
)
|
||||
if "diff" in fail:
|
||||
print(f" Difference: {fail['diff']:.10e}")
|
||||
# Show in hex to see bitwise difference
|
||||
import struct
|
||||
|
||||
decode_hex = struct.pack("f", fail["decode_logprob"]).hex()
|
||||
prefill_hex = struct.pack("f", fail["prefill_logprob"]).hex()
|
||||
print(f" Decode logprob (hex): 0x{decode_hex}")
|
||||
print(f" Prefill logprob (hex): 0x{prefill_hex}")
|
||||
|
||||
# If we have all tokens/logprobs, show the context
|
||||
if "decode_all_tokens" in fail and "decode_all_logprobs" in fail:
|
||||
token_idx = fail["token_idx"]
|
||||
all_tokens = fail["decode_all_tokens"]
|
||||
all_logprobs = fail["decode_all_logprobs"]
|
||||
|
||||
# Show context: 2 tokens before and after
|
||||
start = max(0, token_idx - 2)
|
||||
end = min(len(all_tokens), token_idx + 3)
|
||||
|
||||
print(f" Context (tokens {start} to {end - 1}):")
|
||||
for j in range(start, end):
|
||||
marker = " <-- MISMATCH" if j == token_idx else ""
|
||||
print(
|
||||
f" [{j}] token={all_tokens[j]}, "
|
||||
f"logprob={all_logprobs[j]:.8f}{marker}"
|
||||
)
|
||||
|
||||
if len(failures) > 5:
|
||||
print(f"\n ... and {len(failures) - 5} more failures for this prompt")
|
||||
|
||||
print(f"\n{'=' * 80}\n")
|
||||
|
||||
pytest.fail(
|
||||
f"Decode logprobs do not match prefill logprobs: "
|
||||
f"{len(failed_comparisons)} mismatches found."
|
||||
)
|
||||
else:
|
||||
print("✓ SUCCESS: All decode logprobs match prefill logprobs bitwise!")
|
||||
print(f"{'=' * 80}\n")
|
||||
|
||||
|
||||
def LLM_with_max_seqs(
|
||||
model: str,
|
||||
max_num_seqs: int,
|
||||
gpu_memory_utilization: float,
|
||||
max_model_len: int,
|
||||
attention_config: dict | None = None,
|
||||
kernel_config: dict | None = None,
|
||||
max_num_batched_tokens: int | None = None,
|
||||
) -> LLM:
|
||||
"""Helper to construct an LLM with a specific max_num_seqs (batch-size limit)
|
||||
using the high-level v1 LLM API, while constraining memory usage.
|
||||
"""
|
||||
extra_kwargs: dict = {}
|
||||
if kernel_config is not None:
|
||||
extra_kwargs["kernel_config"] = kernel_config
|
||||
if max_num_batched_tokens is not None:
|
||||
extra_kwargs["max_num_batched_tokens"] = max_num_batched_tokens
|
||||
return LLM(
|
||||
model=model,
|
||||
max_num_seqs=max_num_seqs,
|
||||
gpu_memory_utilization=gpu_memory_utilization,
|
||||
max_model_len=max_model_len,
|
||||
dtype="auto",
|
||||
tensor_parallel_size=int(os.getenv("VLLM_TP_SIZE", "1")),
|
||||
enable_prefix_caching=False,
|
||||
attention_config=attention_config,
|
||||
# Enable for MOE models
|
||||
# enable_expert_parallel=True,
|
||||
**extra_kwargs,
|
||||
)
|
||||
@@ -1,138 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Batch-invariance regression tests for vision-language models (VLMs)."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from PIL import Image
|
||||
from utils import _extract_step_logprobs, skip_if_not_cuda_alike
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.inputs import TextPrompt
|
||||
|
||||
VLM_TEST_MODEL = os.getenv("VLLM_VLM_TEST_MODEL", "Qwen/Qwen3-VL-2B-Instruct")
|
||||
|
||||
IMAGE_PROMPT = (
|
||||
"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>"
|
||||
"Describe this image.<|im_end|><|im_start|>assistant\n"
|
||||
)
|
||||
VIDEO_PROMPT = (
|
||||
"<|im_start|>user\n<|vision_start|><|video_pad|><|vision_end|>"
|
||||
"Describe this video.<|im_end|><|im_start|>assistant\n"
|
||||
)
|
||||
|
||||
|
||||
def _make_image(seed: int, size: int) -> Image.Image:
|
||||
rng = np.random.default_rng(seed)
|
||||
return Image.fromarray(rng.integers(0, 255, (size, size, 3), dtype=np.uint8))
|
||||
|
||||
|
||||
def _make_inputs(input_type: str, num_reqs: int) -> list[TextPrompt]:
|
||||
inputs: list[TextPrompt] = []
|
||||
for i in range(num_reqs):
|
||||
if input_type == "image":
|
||||
prompt = IMAGE_PROMPT
|
||||
mm_data = {"image": _make_image(1000 + i, size=256)}
|
||||
else:
|
||||
frames = [_make_image(1000 + i + f, size=128) for f in range(4)]
|
||||
prompt = VIDEO_PROMPT
|
||||
mm_data = {
|
||||
"video": (
|
||||
frames,
|
||||
{
|
||||
"total_num_frames": len(frames),
|
||||
"fps": 1.0,
|
||||
"frames_indices": list(range(len(frames))),
|
||||
"do_sample_frames": False,
|
||||
},
|
||||
)
|
||||
}
|
||||
inputs.append({"prompt": prompt, "multi_modal_data": mm_data})
|
||||
return inputs
|
||||
|
||||
|
||||
def _assert_batch_invariant(llm: LLM, inputs: list[TextPrompt], sampling) -> None:
|
||||
bs1 = [
|
||||
_extract_step_logprobs(llm.generate([inp], sampling, use_tqdm=False)[0])
|
||||
for inp in inputs
|
||||
]
|
||||
bsN_outputs = llm.generate(inputs, sampling, use_tqdm=False)
|
||||
assert len(bs1) == len(inputs)
|
||||
assert len(bsN_outputs) == len(inputs)
|
||||
bsN = [_extract_step_logprobs(out) for out in bsN_outputs]
|
||||
|
||||
failures = []
|
||||
for i, ((lp1, t1), (lpN, tN)) in enumerate(zip(bs1, bsN)):
|
||||
if lp1 is None or lpN is None:
|
||||
failures.append(f"req {i}: selected-token logprobs are unavailable")
|
||||
continue
|
||||
if len(t1) != sampling.max_tokens or len(tN) != sampling.max_tokens:
|
||||
failures.append(
|
||||
f"req {i}: expected {sampling.max_tokens} tokens, "
|
||||
f"got bs1={len(t1)} bsN={len(tN)}"
|
||||
)
|
||||
continue
|
||||
if t1 != tN:
|
||||
failures.append(f"req {i}: token mismatch bs1={t1} bsN={tN}")
|
||||
elif not torch.equal(lp1, lpN):
|
||||
d = (lp1 - lpN).abs().max().item()
|
||||
failures.append(f"req {i}: logprob mismatch max_diff={d:.3e}")
|
||||
|
||||
if failures:
|
||||
pytest.fail(
|
||||
f"Batch invariance violated for {len(failures)}/{len(inputs)} "
|
||||
f"requests:\n" + "\n".join(failures)
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("input_type", ["image", "video"])
|
||||
@pytest.mark.parametrize("mm_encoder_attn_backend", ["FLASH_ATTN", "TORCH_SDPA"])
|
||||
def test_vlm_batch_invariance_bs1_vs_bsN(
|
||||
input_type: str,
|
||||
mm_encoder_attn_backend: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
||||
_run_vlm_batch_invariance(input_type, mm_encoder_attn_backend, enforce_eager=True)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
def test_vlm_batch_invariance_default_execution(monkeypatch: pytest.MonkeyPatch):
|
||||
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
||||
_run_vlm_batch_invariance("image", "FLASH_ATTN", enforce_eager=False)
|
||||
|
||||
|
||||
def _run_vlm_batch_invariance(
|
||||
input_type: str, mm_encoder_attn_backend: str, enforce_eager: bool
|
||||
) -> None:
|
||||
inputs = _make_inputs(input_type, num_reqs=4)
|
||||
sampling = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=8,
|
||||
seed=1234,
|
||||
ignore_eos=True,
|
||||
logprobs=5,
|
||||
)
|
||||
|
||||
llm = LLM(
|
||||
model=VLM_TEST_MODEL,
|
||||
dtype="bfloat16",
|
||||
enforce_eager=enforce_eager,
|
||||
max_num_seqs=16,
|
||||
max_model_len=4096,
|
||||
max_num_batched_tokens=2048,
|
||||
gpu_memory_utilization=0.85,
|
||||
enable_prefix_caching=False,
|
||||
mm_processor_cache_gb=0,
|
||||
mm_encoder_attn_backend=mm_encoder_attn_backend,
|
||||
)
|
||||
try:
|
||||
_assert_batch_invariant(llm, inputs, sampling)
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
@@ -1,466 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CUTLASS batch-invariance tests.
|
||||
|
||||
The NVFP4 CUTLASS tests in this file must run with ``VLLM_BATCH_INVARIANT=1``
|
||||
before the first relevant native kernel call. Do not run them in the same pytest
|
||||
process after tests that intentionally exercise non-batch-invariant NVFP4
|
||||
scaled-mm kernels.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
|
||||
from tests.kernels.moe.utils import make_dummy_moe_config, make_test_quant_config
|
||||
from tests.kernels.quantization.nvfp4_utils import get_nvfp4_global_scale
|
||||
from tests.utils import TestFP8Layer, requires_fp8
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.model_executor.kernels.linear import fp8_scaled_mm_is_batch_invariant
|
||||
from vllm.model_executor.kernels.linear.scaled_mm import (
|
||||
CutlassFP8ScaledMMLinearKernel,
|
||||
TritonFP8ScaledMMLinearKernel,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe import fused_topk
|
||||
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
|
||||
from vllm.model_executor.layers.fused_moe.all2all_utils import (
|
||||
maybe_make_prepare_finalize,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.experts.cutlass_moe import (
|
||||
CutlassExpertsFp4,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kFp8DynamicTensorSym,
|
||||
kFp8DynamicTokenSym,
|
||||
kFp8StaticChannelSym,
|
||||
kFp8StaticTensorSym,
|
||||
kFp8StaticTokenSym,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import set_random_seed
|
||||
|
||||
pytest.importorskip("torch.cuda")
|
||||
|
||||
_NVFP4_REQUIRES_SM100 = pytest.mark.skipif(
|
||||
not current_platform.has_device_capability(100),
|
||||
reason="Nvfp4 Requires compute capability of 10 or above.",
|
||||
)
|
||||
|
||||
_NVFP4_LINEAR_DTYPES = [torch.float16, torch.bfloat16]
|
||||
_NVFP4_LINEAR_CONSISTENCY_SHAPES = [
|
||||
(256, 128, 4096),
|
||||
(512, 256, 4096),
|
||||
(256, 256, 2048),
|
||||
(241, 160, 2048),
|
||||
(401, 352, 1984),
|
||||
(333, 320, 1008),
|
||||
(287, 96, 4096),
|
||||
]
|
||||
|
||||
_NVFP4_MOE_DTYPES = (torch.bfloat16,)
|
||||
_NVFP4_MOE_NUM_EXPERTS = (40, 64)
|
||||
_NVFP4_MOE_TOPKS = (1, 4)
|
||||
|
||||
_NVFP4_MOE_BATCH_INVARIANT_CASES = (
|
||||
{
|
||||
"m": 12,
|
||||
"n": 1024,
|
||||
"k": 1024,
|
||||
"subset_indices": ((0, 3, 7), (1, 4, 8, 10), (11, 5, 2, 9, 6)),
|
||||
},
|
||||
{
|
||||
"m": 129,
|
||||
"n": 1024,
|
||||
"k": 1024,
|
||||
"subset_indices": (
|
||||
(0, 64, 128),
|
||||
(1, 63, 64, 127),
|
||||
(32, 33, 95, 96, 128),
|
||||
),
|
||||
},
|
||||
{
|
||||
"m": 73,
|
||||
"n": 1472,
|
||||
"k": 1536,
|
||||
"subset_indices": ((0, 17, 35), (8, 36, 72), (1, 9, 33, 48, 64)),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_cuda():
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("Requires CUDA or ROCm.")
|
||||
torch.set_default_device("cuda")
|
||||
|
||||
|
||||
@requires_fp8
|
||||
@pytest.mark.parametrize(
|
||||
"kernel",
|
||||
[
|
||||
pytest.param(
|
||||
CutlassFP8ScaledMMLinearKernel,
|
||||
marks=pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="CUTLASS requires CUDA."
|
||||
),
|
||||
),
|
||||
TritonFP8ScaledMMLinearKernel,
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"act_key,weight_key",
|
||||
[
|
||||
(kFp8DynamicTokenSym, kFp8StaticTensorSym),
|
||||
(kFp8DynamicTokenSym, kFp8StaticChannelSym),
|
||||
(kFp8DynamicTokenSym, kFp8StaticTokenSym),
|
||||
(kFp8StaticTensorSym, kFp8StaticTensorSym),
|
||||
# An amax over the whole batch: the GEMM is invariant, the layer is not.
|
||||
(kFp8DynamicTensorSym, kFp8StaticTensorSym),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("weight_shape", [(1024, 2048), (4608, 4096)])
|
||||
@pytest.mark.parametrize("batch_size", [1, 16, 17, 32, 64, 65, 256, 257])
|
||||
@torch.inference_mode()
|
||||
def test_fp8_scaled_mm_batch_invariant_fixed_config(
|
||||
kernel: type,
|
||||
act_key,
|
||||
weight_key,
|
||||
weight_shape: tuple[int, int],
|
||||
batch_size: int,
|
||||
default_vllm_config,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
|
||||
torch.manual_seed(0)
|
||||
layer = TestFP8Layer(
|
||||
weight_shape=weight_shape,
|
||||
activation_quant_key=act_key,
|
||||
weight_quant_key=weight_key,
|
||||
input_dtype=torch.bfloat16,
|
||||
out_dtype=torch.bfloat16,
|
||||
device=torch.device("cuda"),
|
||||
force_kernel=kernel,
|
||||
)
|
||||
assert isinstance(layer.kernel, kernel)
|
||||
dynamic_per_tensor = act_key == kFp8DynamicTensorSym
|
||||
assert fp8_scaled_mm_is_batch_invariant(layer.kernel) != dynamic_per_tensor
|
||||
|
||||
in_features = weight_shape[1]
|
||||
needle = torch.randn((1, in_features), device="cuda", dtype=torch.bfloat16)
|
||||
baseline = layer(needle)[0]
|
||||
|
||||
filler = torch.randn(
|
||||
(max(batch_size - 1, 0), in_features), device="cuda", dtype=torch.bfloat16
|
||||
)
|
||||
if dynamic_per_tensor:
|
||||
if batch_size == 1:
|
||||
pytest.skip("no other rows to move the scale")
|
||||
front_output = layer(torch.cat([needle, 100 * filler], dim=0))[0]
|
||||
assert not torch.equal(front_output, baseline)
|
||||
return
|
||||
|
||||
front_batch = torch.cat([needle, filler], dim=0)
|
||||
back_batch = torch.cat([filler, needle], dim=0)
|
||||
|
||||
front_output = layer(front_batch)[0]
|
||||
back_output = layer(back_batch)[-1]
|
||||
|
||||
torch.testing.assert_close(front_output, baseline, rtol=0, atol=0)
|
||||
torch.testing.assert_close(back_output, baseline, rtol=0, atol=0)
|
||||
|
||||
|
||||
@requires_fp8
|
||||
@pytest.mark.parametrize("scheme", ["fp8_per_tensor", "fp8_per_channel"])
|
||||
@torch.inference_mode()
|
||||
def test_online_fp8_linear_batch_invariant(
|
||||
scheme, monkeypatch, default_vllm_config, dist_init
|
||||
):
|
||||
from vllm.config.model import ModelConfig
|
||||
from vllm.config.quantization import resolve_quantization_config
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
from vllm.model_executor.layers.quantization.online.base import (
|
||||
OnlineQuantizationConfig,
|
||||
)
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
default_vllm_config.model_config = ModelConfig(dtype="bfloat16")
|
||||
quant_config = OnlineQuantizationConfig(resolve_quantization_config(scheme, None))
|
||||
set_random_seed(0)
|
||||
with set_default_torch_dtype(torch.bfloat16), torch.device("cuda"):
|
||||
layer = ReplicatedLinear(
|
||||
1024, 768, bias=False, quant_config=quant_config, prefix="mlp.down_proj"
|
||||
)
|
||||
layer.weight.weight_loader(layer.weight, torch.randn(768, 1024))
|
||||
|
||||
needle = torch.randn(1, 1024)
|
||||
filler = 100 * torch.randn(63, 1024)
|
||||
baseline = layer(needle)[0]
|
||||
assert torch.equal(layer(torch.cat([needle, filler]))[0][:1], baseline)
|
||||
assert torch.equal(layer(torch.cat([filler, needle]))[0][-1:], baseline)
|
||||
|
||||
|
||||
@requires_fp8
|
||||
@torch.inference_mode()
|
||||
def test_block_fp8_batch_invariant_across_tuned_block_size_k(monkeypatch):
|
||||
"""The block-FP8 kernel applies the block scales once per K tile, so a tuned
|
||||
BLOCK_SIZE_K below the scale group size reorders the sum."""
|
||||
from vllm.model_executor.layers.quantization.utils import fp8_utils
|
||||
|
||||
base = dict(
|
||||
BLOCK_SIZE_M=64, BLOCK_SIZE_N=128, GROUP_SIZE_M=1, num_warps=4, num_stages=2
|
||||
)
|
||||
table = {256: {**base, "BLOCK_SIZE_K": 128}, 512: {**base, "BLOCK_SIZE_K": 64}}
|
||||
monkeypatch.setattr(fp8_utils, "get_w8a8_block_fp8_configs", lambda *_: table)
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
N, K, block = 12288, 2048, [128, 128]
|
||||
|
||||
set_random_seed(0)
|
||||
fp8 = current_platform.fp8_dtype()
|
||||
A = torch.randn(512, K).to(fp8)
|
||||
B = torch.randn(N, K).to(fp8)
|
||||
As = torch.rand(512, K // 128) / 100
|
||||
Bs = torch.rand(N // 128, K // 128) / 100
|
||||
|
||||
def run(m):
|
||||
return fp8_utils.w8a8_triton_block_scaled_mm(
|
||||
A[:m], B, As[:m], Bs, block, torch.bfloat16
|
||||
)[:256]
|
||||
|
||||
assert torch.equal(run(256), run(512))
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", False)
|
||||
assert not torch.equal(run(256), run(512))
|
||||
|
||||
|
||||
@_NVFP4_REQUIRES_SM100
|
||||
@pytest.mark.parametrize("dtype", _NVFP4_LINEAR_DTYPES)
|
||||
@pytest.mark.parametrize("shape", _NVFP4_LINEAR_CONSISTENCY_SHAPES)
|
||||
@torch.inference_mode()
|
||||
def test_cutlass_nvfp4_scaled_mm_batch_invariant(
|
||||
dtype: torch.dtype,
|
||||
shape: tuple[int, int, int],
|
||||
) -> None:
|
||||
"""Each row of a full-M GEMM must match its M=1 counterpart."""
|
||||
set_random_seed(12345)
|
||||
m, n, packed_k = shape
|
||||
k = packed_k * 2 # real K (FP4 elements)
|
||||
|
||||
a_dtype = torch.randn((m, k), dtype=dtype, device="cuda")
|
||||
b_dtype = torch.randn((n, k), dtype=dtype, device="cuda")
|
||||
|
||||
a_global_scale = get_nvfp4_global_scale(a_dtype)
|
||||
b_global_scale = get_nvfp4_global_scale(b_dtype)
|
||||
alpha = 1.0 / (a_global_scale * b_global_scale)
|
||||
|
||||
b_fp4, b_scale_interleaved = ops.scaled_fp4_quant(b_dtype, b_global_scale)
|
||||
|
||||
a_fp4_full, a_sf_full = ops.scaled_fp4_quant(a_dtype, a_global_scale)
|
||||
out_full = ops.cutlass_scaled_fp4_mm(
|
||||
a_fp4_full,
|
||||
b_fp4,
|
||||
a_sf_full,
|
||||
b_scale_interleaved,
|
||||
alpha,
|
||||
dtype,
|
||||
)
|
||||
|
||||
for i in range(m):
|
||||
a_row = a_dtype[i : i + 1]
|
||||
a_fp4_row, a_sf_row = ops.scaled_fp4_quant(a_row, a_global_scale)
|
||||
out_row = ops.cutlass_scaled_fp4_mm(
|
||||
a_fp4_row,
|
||||
b_fp4,
|
||||
a_sf_row,
|
||||
b_scale_interleaved,
|
||||
alpha,
|
||||
dtype,
|
||||
)
|
||||
|
||||
assert torch.equal(out_full[i], out_row[0]), (
|
||||
f"VLLM_BATCH_INVARIANT: row {i} differs between M={m} and M=1: "
|
||||
f"max_abs_diff={(out_full[i] - out_row[0]).abs().max().item()}"
|
||||
)
|
||||
|
||||
|
||||
def _make_cutlass_fp4_moe_batch_invariant_case(
|
||||
case_config: dict[str, Any],
|
||||
activation: MoEActivation,
|
||||
e: int,
|
||||
topk: int,
|
||||
dtype: torch.dtype,
|
||||
) -> dict[str, Any]:
|
||||
set_random_seed(7)
|
||||
assert topk <= e
|
||||
|
||||
hidden_states = (
|
||||
torch.randn((case_config["m"], case_config["k"]), device="cuda", dtype=dtype)
|
||||
/ 10
|
||||
)
|
||||
|
||||
w1_q, w2_q, quant_config = make_test_quant_config(
|
||||
e,
|
||||
case_config["n"],
|
||||
case_config["k"],
|
||||
in_dtype=dtype,
|
||||
quant_dtype="nvfp4",
|
||||
block_shape=None,
|
||||
per_act_token_quant=False,
|
||||
make_gate=activation.is_gated,
|
||||
)
|
||||
|
||||
score = torch.randn((case_config["m"], e), device="cuda", dtype=dtype)
|
||||
|
||||
moe_config = make_dummy_moe_config(
|
||||
num_experts=e,
|
||||
experts_per_token=topk,
|
||||
hidden_dim=case_config["k"],
|
||||
intermediate_size=case_config["n"],
|
||||
in_dtype=dtype,
|
||||
activation=activation,
|
||||
)
|
||||
prepare_finalize = maybe_make_prepare_finalize(
|
||||
moe=moe_config,
|
||||
quant_config=quant_config,
|
||||
allow_new_interface=True,
|
||||
use_monolithic=False,
|
||||
)
|
||||
assert prepare_finalize is not None
|
||||
kernel = mk.FusedMoEKernel(
|
||||
prepare_finalize,
|
||||
CutlassExpertsFp4(
|
||||
moe_config=moe_config,
|
||||
quant_config=quant_config,
|
||||
),
|
||||
)
|
||||
|
||||
return {
|
||||
"config": case_config,
|
||||
"hidden_states": hidden_states,
|
||||
"score": score,
|
||||
"kernel": kernel,
|
||||
"w1_q": w1_q,
|
||||
"w2_q": w2_q,
|
||||
"activation": activation,
|
||||
"e": e,
|
||||
"topk": topk,
|
||||
"dtype": dtype,
|
||||
}
|
||||
|
||||
|
||||
def _run_cutlass_fp4_moe(
|
||||
case: dict[str, Any],
|
||||
hidden_states: torch.Tensor,
|
||||
score: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
topk_weights, topk_ids, _ = fused_topk(
|
||||
hidden_states, score, case["topk"], renormalize=False
|
||||
)
|
||||
return case["kernel"].apply(
|
||||
hidden_states=hidden_states,
|
||||
w1=case["w1_q"],
|
||||
w2=case["w2_q"],
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
global_num_experts=case["e"],
|
||||
activation=case["activation"],
|
||||
apply_router_weight_on_input=False,
|
||||
expert_map=None,
|
||||
)
|
||||
|
||||
|
||||
@_NVFP4_REQUIRES_SM100
|
||||
@pytest.mark.parametrize("case_config", _NVFP4_MOE_BATCH_INVARIANT_CASES)
|
||||
@pytest.mark.parametrize("activation", [MoEActivation.SILU, MoEActivation.SWIGLUSTEP])
|
||||
@pytest.mark.parametrize("e", _NVFP4_MOE_NUM_EXPERTS)
|
||||
@pytest.mark.parametrize("topk", _NVFP4_MOE_TOPKS)
|
||||
@pytest.mark.parametrize("dtype", _NVFP4_MOE_DTYPES)
|
||||
@torch.inference_mode()
|
||||
def test_cutlass_nvfp4_moe_batch_invariant(
|
||||
case_config: dict[str, Any],
|
||||
activation: MoEActivation,
|
||||
e: int,
|
||||
topk: int,
|
||||
dtype: torch.dtype,
|
||||
default_vllm_config,
|
||||
workspace_init,
|
||||
) -> None:
|
||||
case = _make_cutlass_fp4_moe_batch_invariant_case(
|
||||
case_config, activation, e, topk, dtype
|
||||
)
|
||||
case_id = f"{case['config']}, e={case['e']}, topk={case['topk']}"
|
||||
# Establish the baseline output for the full mixed batch once, then
|
||||
# compare every smaller replay against the corresponding slice here.
|
||||
batch_output = _run_cutlass_fp4_moe(case, case["hidden_states"], case["score"])
|
||||
|
||||
assert CutlassExpertsFp4._supports_batch_invariance()
|
||||
|
||||
# Re-run the whole batch with a different batch-row permutation to make
|
||||
# sure the grouped GEMM result is invariant to how tokens are packed into
|
||||
# expert work for scheduling.
|
||||
indices = torch.arange(
|
||||
case["hidden_states"].size(0), device=case["hidden_states"].device
|
||||
)
|
||||
for perm_name, perm in (
|
||||
("reversed", torch.flip(indices, dims=(0,))),
|
||||
("evens_then_odds", torch.cat((indices[::2], indices[1::2]))),
|
||||
):
|
||||
permuted_output = _run_cutlass_fp4_moe(
|
||||
case,
|
||||
case["hidden_states"][perm],
|
||||
case["score"][perm],
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
batch_output[perm],
|
||||
permuted_output,
|
||||
atol=0,
|
||||
rtol=0,
|
||||
msg=(
|
||||
f"{case_id}: permutation '{perm_name}' changed outputs "
|
||||
"relative to the baseline batch order."
|
||||
),
|
||||
)
|
||||
|
||||
# Re-run every batch-row as a batch-size-1 input and compare against the
|
||||
# matching row from the full batch.
|
||||
for idx in range(case["hidden_states"].size(0)):
|
||||
single_idx = torch.tensor([idx], device=case["hidden_states"].device)
|
||||
single_output = _run_cutlass_fp4_moe(
|
||||
case,
|
||||
case["hidden_states"][single_idx],
|
||||
case["score"][single_idx],
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
batch_output[single_idx],
|
||||
single_output,
|
||||
atol=0,
|
||||
rtol=0,
|
||||
msg=(
|
||||
f"{case_id}: batch-row {idx} changed between full-batch "
|
||||
"and batch-size-1 execution."
|
||||
),
|
||||
)
|
||||
|
||||
# Re-run a few nontrivial sub-batches to catch interactions that only
|
||||
# appear when multiple tokens are grouped together.
|
||||
for subset_ids in case["config"]["subset_indices"]:
|
||||
subset = torch.tensor(subset_ids, device=case["hidden_states"].device)
|
||||
subset_output = _run_cutlass_fp4_moe(
|
||||
case,
|
||||
case["hidden_states"][subset],
|
||||
case["score"][subset],
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
batch_output[subset],
|
||||
subset_output,
|
||||
atol=0,
|
||||
rtol=0,
|
||||
msg=(
|
||||
f"{case_id}: sub-batch {list(subset_ids)} changed "
|
||||
"relative to full-batch execution."
|
||||
),
|
||||
)
|
||||
@@ -1,181 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test batch-invariant matmul against torch.matmul for various shape combinations.
|
||||
|
||||
Tests correctness (matches torch.matmul) and batch invariance (result for one
|
||||
item doesn't change based on other items in the batch).
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from utils import skip_unsupported
|
||||
|
||||
import vllm.model_executor.determinism.batch_invariant as bi
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
enable_batch_invariant_mode,
|
||||
matmul_batch_invariant,
|
||||
)
|
||||
from vllm.model_executor.determinism.batch_invariant_configs import (
|
||||
_BATCH_INVARIANT_MATMUL_TUNED_CONFIGS,
|
||||
_get_tuned_matmul_arch_family,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize(
|
||||
"a_shape,b_shape",
|
||||
[
|
||||
# 2D x 2D
|
||||
((32, 64), (64, 16)),
|
||||
# 2D x 3D
|
||||
((64, 16), (4, 16, 32)),
|
||||
# 3D x 2D
|
||||
((4, 32, 64), (64, 16)),
|
||||
# 4D x 2D
|
||||
((1, 4, 32, 64), (64, 16)),
|
||||
# 3D x 3D
|
||||
((4, 32, 64), (4, 64, 16)),
|
||||
# 3D x 4D
|
||||
((2, 32, 64), (1, 2, 64, 16)),
|
||||
# 4D x 3D (Gemma4 pattern)
|
||||
((1, 2, 32, 64), (2, 64, 16)),
|
||||
# 4D x 4D
|
||||
((1, 2, 32, 64), (4, 2, 64, 16)),
|
||||
# 2D x 4D
|
||||
((32, 64), (1, 2, 64, 16)),
|
||||
# 2D x 5D
|
||||
((32, 64), (1, 2, 2, 64, 16)),
|
||||
# 5D x 2D
|
||||
((1, 2, 2, 32, 64), (64, 16)),
|
||||
# 5D x 5D
|
||||
((1, 2, 4, 32, 64), (1, 2, 4, 64, 16)),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
def test_matmul_correctness(a_shape, b_shape, dtype):
|
||||
"""Compare matmul_batch_invariant against torch.matmul for various shapes."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
torch.manual_seed(42)
|
||||
a = torch.rand(a_shape, dtype=dtype, device=device)
|
||||
b = torch.rand(b_shape, dtype=dtype, device=device)
|
||||
|
||||
# Standard implementation (CUDA ops)
|
||||
standard_output = torch.matmul(a, b)
|
||||
|
||||
# Batch-invariant implementation (Triton)
|
||||
triton_output = matmul_batch_invariant(a, b)
|
||||
|
||||
# Compare outputs
|
||||
# Use looser tolerance for bfloat16 due to its lower precision
|
||||
if dtype == torch.bfloat16:
|
||||
rtol, atol = 1e-1, 1e-1 # 10% relative tolerance for bfloat16
|
||||
else:
|
||||
rtol, atol = 1e-2, 1e-2 # 1% for float16/float32
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
standard_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"matmul mismatch for a ndim={a.ndim}, b ndim={b.ndim},",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
def test_matmul_batch_invariance(dtype):
|
||||
"""Verify that the result for one item is bitwise identical regardless
|
||||
of what other items are in the batch.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
torch.manual_seed(42)
|
||||
a_single = torch.rand((1, 64, 32), dtype=dtype, device=device)
|
||||
b = torch.rand((32, 128), dtype=dtype, device=device)
|
||||
|
||||
standard_output = matmul_batch_invariant(a_single, b)
|
||||
|
||||
a_batch = torch.rand((8, 64, 32), dtype=dtype, device=device)
|
||||
a_batch[3] = a_single[0]
|
||||
|
||||
batch_output = matmul_batch_invariant(a_batch, b)
|
||||
batch_output_a = batch_output[3]
|
||||
|
||||
assert torch.equal(standard_output[0], batch_output_a)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize("m", [8, 32, 256, 2048])
|
||||
@pytest.mark.parametrize("transpose_b", [False, True], ids=["contiguous", "transposed"])
|
||||
def test_matmul_batch_invariance_across_tuned_m_buckets(m, transpose_b):
|
||||
# Tuned M buckets must preserve each row's K-reduction order.
|
||||
capability = (
|
||||
current_platform.get_device_capability() if current_platform.is_cuda() else None
|
||||
)
|
||||
arch_family = _get_tuned_matmul_arch_family(capability)
|
||||
if arch_family not in _BATCH_INVARIANT_MATMUL_TUNED_CONFIGS:
|
||||
pytest.skip("No tuned persistent matmul config for this architecture")
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
n = k = 2048
|
||||
torch.manual_seed(42)
|
||||
a = torch.rand((m, k), dtype=torch.bfloat16, device=device)
|
||||
if transpose_b:
|
||||
b = torch.rand((n, k), dtype=torch.bfloat16, device=device).t()
|
||||
else:
|
||||
b = torch.rand((k, n), dtype=torch.bfloat16, device=device)
|
||||
|
||||
single_output = matmul_batch_invariant(a[:1], b)
|
||||
batch_output = matmul_batch_invariant(a, b)
|
||||
|
||||
assert torch.equal(single_output[0], batch_output[0])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def batch_invariant_mode():
|
||||
# The overrides are process-global: remove them so later tests compare
|
||||
# against the stock aten kernels again.
|
||||
enable_batch_invariant_mode()
|
||||
yield
|
||||
assert bi._batch_invariant_LIB is not None
|
||||
bi._batch_invariant_LIB._destroy()
|
||||
bi._batch_invariant_MODE = False
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.usefixtures("batch_invariant_mode")
|
||||
@pytest.mark.parametrize("op", ["mm", "addmm", "bmm"])
|
||||
def test_compiled_matmul_reaches_batch_invariant_out_overloads(op):
|
||||
"""Inductor lowers mm/addmm/bmm to ``extern_kernels.<op>(..., out=buf)``,
|
||||
i.e. the ``.out`` overload, which eager never dispatches."""
|
||||
if (
|
||||
op != "bmm"
|
||||
and current_platform.is_cuda()
|
||||
and not current_platform.is_device_capability_family(80)
|
||||
):
|
||||
pytest.skip("mm/addmm are not overridden on SM90+")
|
||||
torch.manual_seed(0)
|
||||
dtype, k, n, needle = torch.bfloat16, 1024, 768, 37
|
||||
w = torch.randn(4, k, n, device=DEVICE_TYPE, dtype=dtype)
|
||||
bias = torch.randn(n, device=DEVICE_TYPE, dtype=dtype)
|
||||
fn = {
|
||||
"mm": lambda x: torch.mm(x[0], w[0]),
|
||||
# Bare addmm: a following pointwise op would make Inductor unfuse the bias.
|
||||
"addmm": lambda x: torch.addmm(bias, x[0], w[0]),
|
||||
"bmm": lambda x: torch.bmm(x, w),
|
||||
}[op]
|
||||
compiled = torch.compile(fn, fullgraph=True)
|
||||
x = torch.randn(4, 256, k, device=DEVICE_TYPE, dtype=dtype)
|
||||
row = None
|
||||
for m in (64, 256, 128):
|
||||
xs = x[:, :m].clone()
|
||||
# With dynamic=True, a specialization on M would silently recompile.
|
||||
torch._dynamo.mark_dynamic(xs, 1)
|
||||
out = compiled(xs)
|
||||
assert torch.equal(out, fn(xs)), f"compiled {op} bypassed the BI kernel (M={m})"
|
||||
row = out[..., needle, :] if row is None else row
|
||||
assert torch.equal(out[..., needle, :], row)
|
||||
@@ -1,104 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import contextlib
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from utils import (
|
||||
_extract_step_logprobs,
|
||||
_random_prompt,
|
||||
skip_if_not_cuda_alike,
|
||||
)
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# FLASH_ATTN is CUDA-only.
|
||||
E2E_BACKENDS = ["TRITON_ATTN"] if current_platform.is_rocm() else ["FLASH_ATTN"]
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not hasattr(torch, "float8_e4m3fn"),
|
||||
reason="NVFP4 tests require torch.float8_e4m3fn support.",
|
||||
)
|
||||
|
||||
NVFP4_TEST_MODEL = os.getenv(
|
||||
"VLLM_TEST_NVFP4_MODEL", "nm-testing/TinyLlama-1.1B-Chat-v1.0-NVFP4"
|
||||
)
|
||||
|
||||
|
||||
def _make_llm(max_num_seqs: int, backend: str) -> LLM:
|
||||
return LLM(
|
||||
model=NVFP4_TEST_MODEL,
|
||||
max_num_seqs=max_num_seqs,
|
||||
gpu_memory_utilization=float(
|
||||
os.getenv("VLLM_NVFP4_TEST_GPU_MEMORY_UTILIZATION", "0.05")
|
||||
),
|
||||
max_model_len=int(os.getenv("VLLM_NVFP4_TEST_MAX_MODEL_LEN", "2048")),
|
||||
dtype="auto",
|
||||
tensor_parallel_size=int(os.getenv("VLLM_NVFP4_TEST_TP_SIZE", "1")),
|
||||
enable_prefix_caching=False,
|
||||
enforce_eager=True,
|
||||
attention_config={"backend": backend},
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("backend", E2E_BACKENDS)
|
||||
def test_dense_nvfp4_generation_is_deterministic_across_batch_sizes_e2e(backend):
|
||||
seed = int(os.getenv("VLLM_TEST_SEED", "12345"))
|
||||
random.seed(seed)
|
||||
|
||||
num_trials = int(os.getenv("VLLM_NVFP4_NEEDLE_TRIALS", "2"))
|
||||
max_batch_size = int(os.getenv("VLLM_NVFP4_NEEDLE_BATCH_SIZE", "8"))
|
||||
min_random_prompt = int(os.getenv("VLLM_NVFP4_MIN_PROMPT", "32"))
|
||||
max_random_prompt = int(os.getenv("VLLM_NVFP4_MAX_PROMPT", "96"))
|
||||
assert max_batch_size >= 2, "Batch size should be >= 2 to test invariance."
|
||||
|
||||
sampling = SamplingParams(
|
||||
temperature=float(os.getenv("VLLM_NVFP4_NEEDLE_TEMPERATURE", "0.6")),
|
||||
top_p=float(os.getenv("VLLM_NVFP4_NEEDLE_TOP_P", "0.95")),
|
||||
max_tokens=int(os.getenv("VLLM_NVFP4_NEEDLE_MAX_TOKENS", "16")),
|
||||
seed=20240919,
|
||||
logprobs=5,
|
||||
)
|
||||
needle_prompt = "Write one factual sentence about the moon."
|
||||
|
||||
llm = None
|
||||
baseline_completion = None
|
||||
baseline_logprobs = None
|
||||
try:
|
||||
llm = _make_llm(max_num_seqs=max_batch_size, backend=backend)
|
||||
baseline_output = llm.generate([needle_prompt], sampling, use_tqdm=False)[0]
|
||||
baseline_completion = baseline_output.outputs[0]
|
||||
baseline_logprobs, baseline_token_ids = _extract_step_logprobs(baseline_output)
|
||||
assert baseline_logprobs is not None
|
||||
assert baseline_token_ids is not None
|
||||
for _ in range(num_trials):
|
||||
batch_size = random.randint(max_batch_size // 2, max_batch_size)
|
||||
needle_pos = random.randint(0, batch_size - 1)
|
||||
prompts: list[str] = []
|
||||
for idx in range(batch_size):
|
||||
if idx == needle_pos:
|
||||
prompts.append(needle_prompt)
|
||||
else:
|
||||
prompts.append(_random_prompt(min_random_prompt, max_random_prompt))
|
||||
|
||||
outputs = llm.generate(prompts, sampling, use_tqdm=False)
|
||||
needle_output = outputs[needle_pos]
|
||||
needle_completion = needle_output.outputs[0]
|
||||
needle_logprobs, needle_token_ids = _extract_step_logprobs(needle_output)
|
||||
assert needle_logprobs is not None
|
||||
assert needle_token_ids is not None
|
||||
|
||||
assert needle_output.prompt == needle_prompt
|
||||
assert baseline_completion is not None
|
||||
assert baseline_logprobs is not None
|
||||
assert needle_completion.token_ids == baseline_completion.token_ids
|
||||
assert needle_completion.text == baseline_completion.text
|
||||
torch.testing.assert_close(needle_logprobs, baseline_logprobs)
|
||||
finally:
|
||||
if llm is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
llm.llm_engine.engine_core.shutdown()
|
||||
@@ -1,565 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Test batch-invariant RMS normalization against a PyTorch reference."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from utils import skip_if_not_cuda_alike, skip_unsupported
|
||||
|
||||
from vllm.model_executor.determinism.batch_invariant import (
|
||||
rms_norm_batch_invariant,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
def _rms_norm_reference(
|
||||
input_tensor: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
"""Compute RMSNorm independently using PyTorch operations."""
|
||||
input_fp32 = input_tensor.float()
|
||||
output = input_fp32 * torch.rsqrt(
|
||||
input_fp32.square().mean(dim=-1, keepdim=True) + eps
|
||||
)
|
||||
return (output * weight.float()).to(input_tensor.dtype)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("batch_size", [1, 4, 64, 300])
|
||||
@pytest.mark.parametrize("hidden_size", [512, 2048, 4096, 8192])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("eps", [1e-6, 1e-5])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
def test_rms_norm_batch_invariant_vs_reference(
|
||||
default_vllm_config,
|
||||
batch_size: int,
|
||||
hidden_size: int,
|
||||
dtype: torch.dtype,
|
||||
eps: float,
|
||||
seed: int,
|
||||
):
|
||||
"""Compare batch-invariant Triton RMS norm against a PyTorch reference.
|
||||
|
||||
Tests that the Triton-based batch-invariant RMS norm produces numerically
|
||||
equivalent results to an independent implementation across configurations.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
# Create test input and weight
|
||||
torch.manual_seed(seed)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation (Triton)
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Compare outputs
|
||||
# Use looser tolerance for bfloat16 due to its lower precision
|
||||
if dtype == torch.bfloat16:
|
||||
rtol, atol = 1e-1, 1e-1 # 10% relative tolerance for bfloat16
|
||||
else:
|
||||
rtol, atol = 1e-2, 1e-2 # 1% for float16/float32
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"RMS norm mismatch for batch_size={batch_size}, "
|
||||
f"hidden_size={hidden_size}, "
|
||||
f"dtype={dtype}, eps={eps}, seed={seed}",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("eps", [1e-6])
|
||||
@pytest.mark.parametrize("n_extra", [3, 299])
|
||||
@pytest.mark.parametrize("seed", list(range(16)))
|
||||
def test_fused_add_rms_norm_batch_invariant_residual_path(
|
||||
hidden_size: int,
|
||||
dtype: torch.dtype,
|
||||
eps: float,
|
||||
n_extra: int,
|
||||
seed: int,
|
||||
):
|
||||
"""Test the batch-invariant fused residual-add + RMSNorm helper directly."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
|
||||
torch.manual_seed(seed)
|
||||
x_single = torch.randn(1, hidden_size, dtype=dtype, device=device)
|
||||
residual_single = torch.randn(1, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
x_batch = torch.cat(
|
||||
[
|
||||
x_single,
|
||||
torch.randn(n_extra, hidden_size, dtype=dtype, device=device),
|
||||
],
|
||||
dim=0,
|
||||
)
|
||||
residual_batch = torch.cat(
|
||||
[
|
||||
residual_single,
|
||||
torch.randn(n_extra, hidden_size, dtype=dtype, device=device),
|
||||
],
|
||||
dim=0,
|
||||
)
|
||||
|
||||
def fused_add_rms_norm(x, residual, w, e) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
ops.fused_add_rms_norm(x, residual, w, e)
|
||||
return x, residual
|
||||
|
||||
out_single, residual_out_single = fused_add_rms_norm(
|
||||
x_single.clone(),
|
||||
residual_single.clone(),
|
||||
weight,
|
||||
eps,
|
||||
)
|
||||
out_batch, residual_out_batch = fused_add_rms_norm(
|
||||
x_batch.clone(),
|
||||
residual_batch.clone(),
|
||||
weight,
|
||||
eps,
|
||||
)
|
||||
|
||||
merged_single = x_single + residual_single
|
||||
ref_out = _rms_norm_reference(merged_single, weight, eps)
|
||||
|
||||
torch.testing.assert_close(
|
||||
residual_out_single,
|
||||
merged_single,
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="Residual output should equal x + residual exactly",
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
residual_out_batch[:1],
|
||||
merged_single,
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="Residual output should be batch invariant",
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
out_single,
|
||||
out_batch[:1],
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="Fused add RMSNorm output should be batch invariant",
|
||||
)
|
||||
|
||||
if dtype == torch.bfloat16:
|
||||
rtol, atol = 1e-1, 1e-1
|
||||
else:
|
||||
rtol, atol = 1e-2, 1e-2
|
||||
|
||||
torch.testing.assert_close(
|
||||
out_single,
|
||||
ref_out,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg="Fused add RMSNorm output should stay numerically close to the "
|
||||
"PyTorch RMSNorm reference",
|
||||
)
|
||||
|
||||
|
||||
FP8_DTYPE = current_platform.fp8_dtype()
|
||||
|
||||
# The large launch (num_tokens=300 >= 256) drops an un-pinned kernel to block
|
||||
# 256, while the small launch (255 rows) stays under the threshold and keeps the
|
||||
# larger block (1024, or 512 for per-block quant). Under the pin the two launches
|
||||
# use the same block, so the shared first 255 rows must match bit-for-bit; 255 is
|
||||
# the most rows a single small launch can hold (< 256, and <= 256 for per-block).
|
||||
_LARGE_TOKENS = 300
|
||||
_SMALL_TOKENS = 255
|
||||
|
||||
|
||||
def _assert_rows_bit_identical(small, large, msg):
|
||||
if small.dtype == FP8_DTYPE:
|
||||
assert torch.equal(small.view(torch.uint8), large.view(torch.uint8)), msg
|
||||
else:
|
||||
torch.testing.assert_close(small, large, rtol=0.0, atol=0.0, msg=msg)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
def test_rms_norm_batch_invariant_nonresidual_kernel(
|
||||
hidden_size: int, dtype: torch.dtype, seed: int
|
||||
):
|
||||
"""C++ ``rms_norm`` (no residual) must be batch invariant across the block
|
||||
threshold. Reached in compiled mode with ``ir_op_priority.rms_norm=["vllm_c"]``
|
||||
(default priority is ``native``/inductor codegen when compiling).
|
||||
"""
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(seed)
|
||||
rows = torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
def rms_norm(x):
|
||||
out = torch.empty_like(x)
|
||||
ops.rms_norm(out, x, weight, 1e-6)
|
||||
return out
|
||||
|
||||
large = rms_norm(rows.clone())
|
||||
small = rms_norm(rows[:_SMALL_TOKENS].clone())
|
||||
_assert_rows_bit_identical(
|
||||
small,
|
||||
large[:_SMALL_TOKENS],
|
||||
"rms_norm output depends on num_tokens (block size)",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
@pytest.mark.parametrize("add_residual", [False, True])
|
||||
def test_rms_norm_static_fp8_quant_batch_invariant(
|
||||
hidden_size: int, dtype: torch.dtype, seed: int, add_residual: bool
|
||||
):
|
||||
"""C++ static per-tensor fp8-quant RMSNorm must be batch invariant across
|
||||
the block threshold. Covers ``rms_norm_static_fp8_quant`` and, with
|
||||
``add_residual``, ``fused_add_rms_norm_static_fp8_quant`` (the compiled fp8
|
||||
path where ``RMSNormQuantFusionPass`` rewrites norm + quant into them).
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(seed)
|
||||
rows = torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
residual = (
|
||||
torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
if add_residual
|
||||
else None
|
||||
)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
quant_scale = torch.tensor(1.0, dtype=torch.float32, device=device)
|
||||
|
||||
def quant(x, res):
|
||||
out = torch.empty_like(x, dtype=FP8_DTYPE)
|
||||
if add_residual:
|
||||
torch.ops._C.fused_add_rms_norm_static_fp8_quant(
|
||||
out, x, res, weight, quant_scale, 1e-6
|
||||
)
|
||||
else:
|
||||
torch.ops._C.rms_norm_static_fp8_quant(out, x, weight, quant_scale, 1e-6)
|
||||
return out
|
||||
|
||||
large = quant(rows.clone(), residual.clone() if residual is not None else None)
|
||||
small = quant(
|
||||
rows[:_SMALL_TOKENS].clone(),
|
||||
residual[:_SMALL_TOKENS].clone() if residual is not None else None,
|
||||
)
|
||||
_assert_rows_bit_identical(
|
||||
small,
|
||||
large[:_SMALL_TOKENS],
|
||||
"static-fp8-quant RMSNorm output depends on num_tokens (block size)",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [512, 4096])
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
@pytest.mark.parametrize("seed", list(range(4)))
|
||||
def test_rms_norm_per_block_quant_batch_invariant(
|
||||
hidden_size: int, dtype: torch.dtype, seed: int
|
||||
):
|
||||
"""C++ ``rms_norm_per_block_quant`` must be batch invariant across the
|
||||
block threshold (compiled fp8 block-quant path; block pinned to 512)."""
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(seed)
|
||||
rows = torch.randn(_LARGE_TOKENS, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
group_size = [1, 128]
|
||||
|
||||
def per_block_quant(x):
|
||||
return ops.rms_norm_per_block_quant(x, weight, 1e-6, FP8_DTYPE, group_size)
|
||||
|
||||
out_large, scale_large = per_block_quant(rows.clone())
|
||||
out_small, scale_small = per_block_quant(rows[:_SMALL_TOKENS].clone())
|
||||
_assert_rows_bit_identical(
|
||||
out_small,
|
||||
out_large[:_SMALL_TOKENS],
|
||||
"rms_norm_per_block_quant output depends on num_tokens (block size)",
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
scale_small,
|
||||
scale_large[:_SMALL_TOKENS],
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg="rms_norm_per_block_quant scales depend on num_tokens (block size)",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("batch_size", [1, 16, 128])
|
||||
@pytest.mark.parametrize("seq_len", [1, 32, 512])
|
||||
@pytest.mark.parametrize("hidden_size", [2048, 4096])
|
||||
def test_rms_norm_3d_input(
|
||||
default_vllm_config, batch_size: int, seq_len: int, hidden_size: int
|
||||
):
|
||||
"""Test RMS norm with 3D input tensors (batch, seq_len, hidden_size).
|
||||
|
||||
Ensures that the batch-invariant RMS norm correctly handles multi-dimensional
|
||||
inputs that are common in transformer models.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(
|
||||
batch_size, seq_len, hidden_size, dtype=dtype, device=device
|
||||
)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Use looser tolerance for bfloat16
|
||||
rtol, atol = 1e-1, 1e-1 # 10% tolerance for bfloat16
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"RMS norm mismatch for 3D input with batch_size={batch_size}, "
|
||||
f"seq_len={seq_len}, hidden_size={hidden_size}",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
def test_rms_norm_numerical_stability(default_vllm_config):
|
||||
"""Test RMS norm numerical stability with extreme values.
|
||||
|
||||
Ensures that both implementations handle edge cases like very small or large
|
||||
values without producing NaN or Inf.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.float16
|
||||
eps = 1e-6
|
||||
hidden_size = 2048
|
||||
|
||||
# Test cases with extreme values
|
||||
test_cases = [
|
||||
# Very small values
|
||||
torch.ones(4, hidden_size, dtype=dtype, device=device) * 1e-5,
|
||||
# Very large values
|
||||
torch.ones(4, hidden_size, dtype=dtype, device=device) * 1e4,
|
||||
# Mixed small and large
|
||||
torch.randn(4, hidden_size, dtype=dtype, device=device) * 100,
|
||||
# Values near zero
|
||||
torch.randn(4, hidden_size, dtype=dtype, device=device) * 1e-6,
|
||||
]
|
||||
|
||||
weight = torch.ones(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
for idx, input_tensor in enumerate(test_cases):
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Check for NaN or Inf
|
||||
assert not torch.isnan(reference_output).any(), (
|
||||
f"Reference RMS norm produced NaN for test case {idx}"
|
||||
)
|
||||
assert not torch.isinf(reference_output).any(), (
|
||||
f"Reference RMS norm produced Inf for test case {idx}"
|
||||
)
|
||||
assert not torch.isnan(triton_output).any(), (
|
||||
f"Triton RMS norm produced NaN for test case {idx}"
|
||||
)
|
||||
assert not torch.isinf(triton_output).any(), (
|
||||
f"Triton RMS norm produced Inf for test case {idx}"
|
||||
)
|
||||
|
||||
# Compare outputs - very lenient for extreme values with float16
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=2e-1, # 20% tolerance for extreme values
|
||||
atol=2e-1,
|
||||
msg=f"RMS norm mismatch for extreme value test case {idx}",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
def test_rms_norm_formula(default_vllm_config):
|
||||
"""Test that RMS norm follows the correct mathematical formula.
|
||||
|
||||
Verifies: output = input / sqrt(mean(input^2) + eps) * weight
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.float32 # Use float32 for higher precision in formula check
|
||||
eps = 1e-6
|
||||
hidden_size = 1024
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(8, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
# Compute expected output using the formula
|
||||
variance = (input_tensor.pow(2).mean(dim=-1, keepdim=True)).to(dtype)
|
||||
expected_output = input_tensor * torch.rsqrt(variance + eps) * weight
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Compare against formula
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
expected_output,
|
||||
rtol=1e-4,
|
||||
atol=1e-4,
|
||||
msg="Triton RMS norm doesn't match expected formula",
|
||||
)
|
||||
|
||||
|
||||
@skip_if_not_cuda_alike
|
||||
@pytest.mark.parametrize("hidden_size", [128, 1024, 4096, 16384])
|
||||
def test_rms_norm_different_hidden_sizes(default_vllm_config, hidden_size: int):
|
||||
"""Test RMS norm with various hidden sizes to ensure block size handling.
|
||||
|
||||
The Triton kernel uses a fixed BLOCK_SIZE=1024, so this tests that it
|
||||
correctly handles hidden sizes both smaller and larger than the block size.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
batch_size = 16
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
|
||||
# Use looser tolerance for bfloat16
|
||||
rtol, atol = 1e-1, 1e-1 # 10% tolerance for bfloat16
|
||||
|
||||
torch.testing.assert_close(
|
||||
triton_output,
|
||||
reference_output,
|
||||
rtol=rtol,
|
||||
atol=atol,
|
||||
msg=f"RMS norm mismatch for hidden_size={hidden_size}",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
def test_rms_norm_determinism(default_vllm_config):
|
||||
"""Test that batch-invariant RMS norm produces deterministic results.
|
||||
|
||||
Runs the same input through the kernel multiple times and verifies
|
||||
identical outputs.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
hidden_size = 4096
|
||||
batch_size = 32
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
# Run multiple times
|
||||
outputs = []
|
||||
for _ in range(5):
|
||||
output = rms_norm_batch_invariant(input_tensor.clone(), weight, eps=eps)
|
||||
outputs.append(output)
|
||||
|
||||
# All outputs should be identical
|
||||
reference = outputs[0]
|
||||
for idx, output in enumerate(outputs[1:], start=1):
|
||||
torch.testing.assert_close(
|
||||
output,
|
||||
reference,
|
||||
rtol=0.0,
|
||||
atol=0.0,
|
||||
msg=f"RMS norm not deterministic: run {idx} differs from reference",
|
||||
)
|
||||
|
||||
|
||||
@skip_unsupported
|
||||
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
|
||||
def test_rms_norm_batch_invariance(dtype):
|
||||
"""Same row gives identical rms_norm result regardless of batch neighbors.
|
||||
|
||||
This verifies that the output for a given row is independent of what other
|
||||
rows are present in the batch — the core batch-invariance property.
|
||||
"""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
torch.manual_seed(42)
|
||||
hidden_size = 2048
|
||||
eps = 1e-6
|
||||
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
row = torch.randn(1, hidden_size, dtype=dtype, device=device)
|
||||
|
||||
# Compute rms_norm on the single row alone
|
||||
out_single = rms_norm_batch_invariant(row, weight, eps=eps)
|
||||
|
||||
# Embed the same row in a larger batch with random neighbors
|
||||
batch = torch.randn(8, hidden_size, dtype=dtype, device=device)
|
||||
batch[4] = row[0]
|
||||
out_batch = rms_norm_batch_invariant(batch, weight, eps=eps)
|
||||
|
||||
assert isinstance(out_single, torch.Tensor) and isinstance(out_batch, torch.Tensor)
|
||||
assert torch.equal(out_single[0], out_batch[4]), (
|
||||
"rms_norm output for a row differs when batch context changes"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run a quick smoke test
|
||||
print("Running quick smoke test of RMS norm implementations...")
|
||||
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
batch_size = 8
|
||||
hidden_size = 4096
|
||||
dtype = torch.bfloat16
|
||||
eps = 1e-6
|
||||
|
||||
torch.manual_seed(42)
|
||||
input_tensor = torch.randn(batch_size, hidden_size, dtype=dtype, device=device)
|
||||
weight = torch.randn(hidden_size, dtype=dtype, device=device)
|
||||
|
||||
reference_output = _rms_norm_reference(input_tensor, weight, eps)
|
||||
|
||||
# Batch-invariant implementation
|
||||
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
|
||||
assert isinstance(triton_output, torch.Tensor)
|
||||
|
||||
# Compare
|
||||
max_diff = (triton_output - reference_output).abs().max().item()
|
||||
mean_diff = (triton_output - reference_output).abs().mean().item()
|
||||
|
||||
print(f"Max difference: {max_diff:.6e}")
|
||||
print(f"Mean difference: {mean_diff:.6e}")
|
||||
print(f"Reference output sample: {reference_output[0, :5].tolist()}")
|
||||
print(f"Triton output sample: {triton_output[0, :5].tolist()}")
|
||||
|
||||
if max_diff < 1e-3:
|
||||
print("✓ Smoke test passed!")
|
||||
else:
|
||||
print("✗ Smoke test failed - differences too large")
|
||||
@@ -1,228 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""XPU-only batch-invariance tests for norm, collectives, and sampler behavior."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm import envs
|
||||
from vllm.config import CacheConfig, LoadConfig, ModelConfig, VllmConfig
|
||||
from vllm.distributed.device_communicators.xpu_communicator import XpuCommunicator
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_xpu(), reason="XPU batch-invariance tests"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tiny_qwen3_moe_path(tmp_path):
|
||||
"""Create a local Qwen3-MoE config for dummy-loading tests."""
|
||||
from transformers import Qwen3MoeConfig
|
||||
|
||||
config = Qwen3MoeConfig(
|
||||
architectures=["Qwen3MoeForCausalLM"],
|
||||
vocab_size=256,
|
||||
hidden_size=512,
|
||||
intermediate_size=1024,
|
||||
moe_intermediate_size=512,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=128,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
max_position_embeddings=512,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
tie_word_embeddings=False,
|
||||
)
|
||||
config.save_pretrained(tmp_path)
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["argument", "checkpoint"])
|
||||
def test_rejects_weight_quantization(tiny_qwen3_moe_path, source):
|
||||
"""Reject both explicit and checkpoint-inferred quantization before loading."""
|
||||
from transformers import Qwen3MoeConfig
|
||||
|
||||
if source == "checkpoint":
|
||||
config = Qwen3MoeConfig.from_pretrained(tiny_qwen3_moe_path)
|
||||
config.quantization_config = {
|
||||
"quant_method": "fp8",
|
||||
"activation_scheme": "dynamic",
|
||||
}
|
||||
config.save_pretrained(tiny_qwen3_moe_path)
|
||||
|
||||
model_config = ModelConfig(
|
||||
model=str(tiny_qwen3_moe_path),
|
||||
skip_tokenizer_init=True,
|
||||
dtype="bfloat16",
|
||||
quantization="fp8" if source == "argument" else None,
|
||||
)
|
||||
assert model_config.quantization == "fp8"
|
||||
with pytest.raises(ValueError, match="supports only unquantized models"):
|
||||
VllmConfig(
|
||||
model_config=model_config,
|
||||
load_config=LoadConfig(load_format="dummy"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cache_dtype", ["fp8", "int8_per_token_head", "nvfp4"])
|
||||
def test_rejects_quantized_kv_cache(cache_dtype):
|
||||
with pytest.raises(ValueError, match="does not support quantized KV caches"):
|
||||
VllmConfig(cache_config=CacheConfig(cache_dtype=cache_dtype))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cache_dtype", ["auto", "float16", "bfloat16"])
|
||||
def test_accepts_unquantized_kv_cache(cache_dtype):
|
||||
config = VllmConfig(cache_config=CacheConfig(cache_dtype=cache_dtype))
|
||||
assert config.cache_config.cache_dtype == cache_dtype
|
||||
|
||||
|
||||
def test_quantized_kv_cache_allowed_without_batch_invariance(monkeypatch):
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", False)
|
||||
config = VllmConfig(cache_config=CacheConfig(cache_dtype="fp8"))
|
||||
assert config.cache_config.cache_dtype == "fp8"
|
||||
|
||||
|
||||
# These dimensions and seeds locally reproduce non-invariant norm mismatches.
|
||||
# They make the invariant equality assertion exercise a discriminating case.
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"norm_name",
|
||||
"batch_size",
|
||||
"hidden_size",
|
||||
"position",
|
||||
"weight_seed",
|
||||
"input_seed",
|
||||
"input_pattern",
|
||||
),
|
||||
[
|
||||
("rms", 1024, 16384, 512, 7, 42, "normal"),
|
||||
("gemma", 257, 8192, 255, 1, 2, "normal"),
|
||||
("rms", 5, 8192, 3, 7, 46, "scaled"),
|
||||
("gemma", 5, 8192, 3, 1, 46, "scaled"),
|
||||
],
|
||||
)
|
||||
def test_residual_norm_preserves_batch_invariance(
|
||||
norm_name,
|
||||
batch_size,
|
||||
hidden_size,
|
||||
position,
|
||||
weight_seed,
|
||||
input_seed,
|
||||
input_pattern,
|
||||
monkeypatch,
|
||||
default_vllm_config,
|
||||
):
|
||||
"""Residual norm output must not change when its row changes batch position."""
|
||||
from vllm.model_executor.determinism.batch_invariant import init_batch_invariance
|
||||
from vllm.model_executor.layers.layernorm import GemmaRMSNorm, RMSNorm
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_BATCH_INVARIANT", True)
|
||||
init_batch_invariance()
|
||||
norm_cls = RMSNorm if norm_name == "rms" else GemmaRMSNorm
|
||||
norm = norm_cls(hidden_size, eps=1e-6).to(device="xpu", dtype=torch.bfloat16)
|
||||
with torch.no_grad():
|
||||
torch.manual_seed(weight_seed)
|
||||
norm.weight.uniform_(-0.5, 0.5)
|
||||
|
||||
if input_pattern == "scaled":
|
||||
# Heterogeneous columns expose native mean's batch-dependent rounding.
|
||||
generator = torch.Generator(device="cpu").manual_seed(input_seed)
|
||||
scale = torch.randn(hidden_size, generator=generator).exp()
|
||||
x = (torch.randn(batch_size, hidden_size, generator=generator) * scale).to(
|
||||
device="xpu", dtype=torch.bfloat16
|
||||
)
|
||||
residual = (
|
||||
torch.randn(batch_size, hidden_size, generator=generator) * scale
|
||||
).to(device="xpu", dtype=torch.bfloat16)
|
||||
else:
|
||||
torch.manual_seed(input_seed)
|
||||
x = torch.randn(batch_size, hidden_size, device="xpu", dtype=torch.bfloat16)
|
||||
residual = torch.randn_like(x)
|
||||
|
||||
single_output, single_residual = norm(
|
||||
x[position : position + 1].clone(),
|
||||
residual[position : position + 1].clone(),
|
||||
)
|
||||
batch_output, batch_residual = norm(x.clone(), residual.clone())
|
||||
|
||||
assert torch.equal(single_output, batch_output[position : position + 1])
|
||||
assert torch.equal(single_residual, batch_residual[position : position + 1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"operation", ["all_reduce", "reduce_scatter", "reduce_scatterv"]
|
||||
)
|
||||
@pytest.mark.parametrize("rank", range(4))
|
||||
def test_collectives_preserve_rank_order_and_partition(monkeypatch, operation, rank):
|
||||
"""Cancellation exposes reordered sums; mock ranks require no extra XPUs."""
|
||||
from vllm.distributed.device_communicators import xpu_communicator
|
||||
|
||||
inputs = [
|
||||
torch.full((8, 3), value, dtype=torch.float32, device="xpu")
|
||||
for value in (1e20, -1e20, 3.0, 0.0)
|
||||
]
|
||||
inputs[2].add_(torch.arange(24, device="xpu").reshape(8, 3))
|
||||
|
||||
def all_gather_single(output, input_, group):
|
||||
torch.testing.assert_close(input_, inputs[rank].reshape(-1), rtol=0, atol=0)
|
||||
output.copy_(torch.stack(inputs).reshape(-1))
|
||||
|
||||
monkeypatch.setattr(xpu_communicator.dist, "all_gather_single", all_gather_single)
|
||||
communicator = XpuCommunicator.__new__(XpuCommunicator)
|
||||
communicator.world_size = 4
|
||||
communicator.rank_in_group = rank
|
||||
communicator.device_group = object()
|
||||
expected = inputs[0].clone()
|
||||
for value in inputs[1:]:
|
||||
expected.add_(value)
|
||||
assert torch.equal(expected, inputs[2])
|
||||
|
||||
if operation == "all_reduce":
|
||||
actual = communicator.all_reduce(inputs[rank])
|
||||
elif operation == "reduce_scatter":
|
||||
actual = communicator.reduce_scatter(inputs[rank], dim=0)
|
||||
expected = expected.chunk(4)[rank]
|
||||
else:
|
||||
sizes = [1, 3, 2, 2]
|
||||
actual = communicator.reduce_scatterv(inputs[rank], dim=0, sizes=sizes)
|
||||
expected = expected.split(sizes)[rank]
|
||||
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
|
||||
|
||||
|
||||
# This batch size, vocabulary size, and positions locally reproduce an
|
||||
# unseeded non-invariant XPU sampler mismatch.
|
||||
@pytest.mark.parametrize("position", [0, 128, 255])
|
||||
def test_seeded_sampler_preserves_full_distribution_and_rng(position, monkeypatch):
|
||||
"""Moving a request must preserve its distribution and per-request RNG."""
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
from vllm.v1.sample.ops.topk_topp_sampler import TopKTopPSampler
|
||||
|
||||
assert HAS_TRITON, "XPU sampling must exercise the Triton top-k/top-p path"
|
||||
monkeypatch.setattr(envs, "VLLM_XPU_USE_SAMPLER_KERNEL", True)
|
||||
sampler = TopKTopPSampler(logprobs_mode="processed_logprobs")
|
||||
torch.manual_seed(42)
|
||||
logits = torch.randn(256, 8192, device="xpu", dtype=torch.float32)
|
||||
single_rng = torch.Generator(device="xpu").manual_seed(123)
|
||||
batch_rng = torch.Generator(device="xpu").manual_seed(123)
|
||||
k = torch.full((256,), 32, dtype=torch.int32, device="xpu")
|
||||
p = torch.full((256,), 0.9, device="xpu")
|
||||
for _ in range(3):
|
||||
single_token, single_logprobs = sampler(
|
||||
logits[position : position + 1].clone(),
|
||||
{0: single_rng},
|
||||
k[position : position + 1],
|
||||
p[position : position + 1],
|
||||
)
|
||||
batch_tokens, batch_logprobs = sampler(
|
||||
logits.clone(), {position: batch_rng}, k, p
|
||||
)
|
||||
assert single_logprobs is not None and batch_logprobs is not None
|
||||
torch.testing.assert_close(
|
||||
single_logprobs[0], batch_logprobs[position], rtol=0, atol=0
|
||||
)
|
||||
assert single_token.item() == batch_tokens[position].item()
|
||||
assert torch.equal(single_rng.get_state(), batch_rng.get_state())
|
||||
@@ -1,153 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import os
|
||||
import random
|
||||
from typing import NamedTuple
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.transformers_utils.config import get_config
|
||||
from vllm.transformers_utils.model_arch_config_convertor import (
|
||||
ModelArchConfigConvertorBase,
|
||||
)
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
from vllm.v1.attention.backends.fa_utils import flash_attn_supports_mla
|
||||
|
||||
|
||||
class DeviceConfig(NamedTuple):
|
||||
available: bool
|
||||
backends: list[str]
|
||||
|
||||
|
||||
# Maps each device to its availability and supported backends.
|
||||
DEVICE_BACKENDS: dict[str, DeviceConfig] = {
|
||||
"cuda": DeviceConfig(
|
||||
available=current_platform.is_cuda()
|
||||
and current_platform.has_device_capability(80),
|
||||
# FlashInfer backend temporarily disabled due to invariant CTA sizes.
|
||||
# See FlashInfer issue #2424
|
||||
backends=["FLASH_ATTN", "TRITON_ATTN", "FLEX_ATTENTION"],
|
||||
),
|
||||
"xpu": DeviceConfig(
|
||||
available=current_platform.is_xpu() and HAS_TRITON,
|
||||
backends=["TRITON_ATTN"],
|
||||
),
|
||||
"rocm": DeviceConfig(
|
||||
available=current_platform.is_rocm() and HAS_TRITON,
|
||||
backends=["TRITON_ATTN"],
|
||||
),
|
||||
}
|
||||
|
||||
DEFAULT_MODEL = "Qwen/Qwen3-1.7B"
|
||||
TEST_MODEL = os.getenv("VLLM_TEST_MODEL", DEFAULT_MODEL)
|
||||
|
||||
# Override backends for MLA models.
|
||||
if os.getenv("VLLM_TEST_MODEL"):
|
||||
config = get_config(TEST_MODEL, trust_remote_code=False)
|
||||
if ModelArchConfigConvertorBase(config, config.get_text_config()).is_deepseek_mla():
|
||||
DEVICE_BACKENDS["cuda"] = DeviceConfig(
|
||||
available=DEVICE_BACKENDS["cuda"].available,
|
||||
backends=["TRITON_MLA"]
|
||||
+ (["FLASH_ATTN_MLA"] if flash_attn_supports_mla() else []),
|
||||
)
|
||||
DEVICE_BACKENDS["xpu"] = DeviceConfig(
|
||||
available=DEVICE_BACKENDS["xpu"].available,
|
||||
backends=[],
|
||||
)
|
||||
DEVICE_BACKENDS["rocm"] = DeviceConfig(
|
||||
available=DEVICE_BACKENDS["rocm"].available,
|
||||
backends=["TRITON_MLA"],
|
||||
)
|
||||
|
||||
# Only include backends for devices that are actually available.
|
||||
BACKENDS: list[str] = sorted(
|
||||
{b for cfg in DEVICE_BACKENDS.values() if cfg.available for b in cfg.backends}
|
||||
)
|
||||
|
||||
skip_unsupported = pytest.mark.skipif(
|
||||
not any(cfg.available for cfg in DEVICE_BACKENDS.values()),
|
||||
reason="Requires CUDA >= Ampere (SM80), ROCm, or Intel XPU with Triton",
|
||||
)
|
||||
|
||||
skip_if_not_cuda = pytest.mark.skipif(
|
||||
not DEVICE_BACKENDS["cuda"].available,
|
||||
reason="Requires CUDA >= Ampere (SM80)",
|
||||
)
|
||||
|
||||
skip_if_not_cuda_alike = pytest.mark.skipif(
|
||||
not (DEVICE_BACKENDS["cuda"].available or DEVICE_BACKENDS["rocm"].available),
|
||||
reason="Requires CUDA >= Ampere (SM80) or ROCm",
|
||||
)
|
||||
|
||||
requires_mx = pytest.mark.skipif(
|
||||
not (current_platform.is_rocm() and current_platform.supports_mx()),
|
||||
reason="requires a ROCm device with native MX support (gfx95x)",
|
||||
)
|
||||
|
||||
|
||||
def _random_prompt(min_words: int = 1024, max_words: int = 1024 * 2) -> str:
|
||||
# Generate more realistic prompts that will actually produce varied tokens
|
||||
# Use a mix of common English text patterns
|
||||
|
||||
prompt_templates = [
|
||||
# Question-answer style
|
||||
"Question: What is the capital of France?\nAnswer: The capital of France is",
|
||||
"Q: How does photosynthesis work?\nA: Photosynthesis is the process by which",
|
||||
"User: Can you explain quantum mechanics?\nAssistant: Quantum mechanics is",
|
||||
# Story/narrative style
|
||||
"Once upon a time in a distant galaxy, there lived",
|
||||
"The old man walked slowly down the street, remembering",
|
||||
"In the year 2157, humanity finally discovered",
|
||||
# Technical/code style
|
||||
"To implement a binary search tree in Python, first we need to",
|
||||
"The algorithm works by iterating through the array and",
|
||||
"Here's how to optimize database queries using indexing:",
|
||||
# Factual/informative style
|
||||
"The Renaissance was a period in European history that",
|
||||
"Climate change is caused by several factors including",
|
||||
"The human brain contains approximately 86 billion neurons which",
|
||||
# Conversational style
|
||||
"I've been thinking about getting a new laptop because",
|
||||
"Yesterday I went to the store and bought",
|
||||
"My favorite thing about summer is definitely",
|
||||
]
|
||||
|
||||
# Pick a random template
|
||||
base_prompt = random.choice(prompt_templates)
|
||||
|
||||
if max_words < min_words:
|
||||
max_words = min_words
|
||||
target_words = random.randint(min_words, max_words)
|
||||
|
||||
if target_words > 50:
|
||||
# For longer prompts, repeat context
|
||||
padding_text = (
|
||||
" This is an interesting topic that deserves more explanation. "
|
||||
# TODO: Update to * (target_words // 10) to better align with word ratio
|
||||
* (target_words // 50)
|
||||
)
|
||||
base_prompt = padding_text + base_prompt
|
||||
|
||||
return base_prompt
|
||||
|
||||
|
||||
def _extract_step_logprobs(request_output):
|
||||
if getattr(request_output, "outputs", None):
|
||||
inner = request_output.outputs[0]
|
||||
if hasattr(inner, "logprobs") and inner.logprobs is not None:
|
||||
t = torch.tensor(
|
||||
[
|
||||
inner.logprobs[i][tid].logprob
|
||||
for i, tid in enumerate(inner.token_ids)
|
||||
],
|
||||
dtype=torch.float32,
|
||||
)
|
||||
return t, inner.token_ids
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def is_device_capability_below_90() -> bool:
|
||||
return not current_platform.has_device_capability(90)
|
||||
Reference in New Issue
Block a user