Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
+196
-44
@@ -583,10 +583,11 @@ def _rocm_aiter_mla_decode_fwd_impl(
|
||||
reduce_indptr: torch.Tensor | None = None,
|
||||
reduce_final_map: torch.Tensor | None = None,
|
||||
reduce_partial_map: torch.Tensor | None = None,
|
||||
causal: bool = True,
|
||||
) -> None:
|
||||
from aiter.mla import mla_decode_fwd
|
||||
|
||||
kwargs: dict[str, float | torch.Tensor | None] = {
|
||||
kwargs: dict[str, float | torch.Tensor | None | bool] = {
|
||||
"sm_scale": sm_scale,
|
||||
"logit_cap": logit_cap,
|
||||
}
|
||||
@@ -596,6 +597,8 @@ def _rocm_aiter_mla_decode_fwd_impl(
|
||||
kwargs["q_scale"] = q_scale
|
||||
kwargs["kv_scale"] = kv_scale
|
||||
|
||||
kwargs["causal"] = causal
|
||||
|
||||
if work_meta_data is not None:
|
||||
assert work_indptr is not None, (
|
||||
"work_indptr must be provided with work_meta_data"
|
||||
@@ -1676,10 +1679,103 @@ def _rocm_aiter_fp8_attn_fake(
|
||||
)
|
||||
|
||||
|
||||
def _mhc_delayed_pre_tail(
|
||||
gemm_out: torch.Tensor,
|
||||
sqrsum: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
hc_scale: torch.Tensor,
|
||||
hc_base: torch.Tensor,
|
||||
pre_mix: torch.Tensor | None,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
hc_sinkhorn_eps: float,
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Finish a delayed mHC pre once AITER has produced the projection.
|
||||
|
||||
Shared by the plain and the post-fused entry points, which differ only in
|
||||
which kernel computes ``gemm_out`` / ``sqrsum`` and the residual they
|
||||
project. ``mhc_pre_big_fuse`` also writes a collapse against its own
|
||||
pre-mix, which the delayed formulation cannot use and so discards.
|
||||
Returns ``(post_mix, comb_mix, layer_input, next_pre_mix)``.
|
||||
"""
|
||||
from aiter.ops.mhc import mhc_pre_big_fuse
|
||||
|
||||
num_tokens, hc_mult, hidden_size = residual.shape
|
||||
device = residual.device
|
||||
with torch.device(device):
|
||||
post_mix = torch.empty(
|
||||
num_tokens, hc_mult, 1, dtype=torch.float32, device=device
|
||||
)
|
||||
comb_mix = torch.empty(
|
||||
num_tokens, hc_mult, hc_mult, dtype=torch.float32, device=device
|
||||
)
|
||||
unused_collapse = torch.empty(
|
||||
num_tokens, hidden_size, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
mhc_pre_big_fuse(
|
||||
post_mix,
|
||||
comb_mix,
|
||||
unused_collapse,
|
||||
gemm_out,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
residual,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
hc_sinkhorn_eps,
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
)
|
||||
|
||||
next_pre_mix = torch.ops.vllm.mhc_pre_mix_triton(
|
||||
gemm_out,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
hc_mult,
|
||||
hc_mult * hidden_size,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
)
|
||||
if pre_mix is None:
|
||||
# Model entry selects residual stream zero.
|
||||
layer_input = residual[:, 0]
|
||||
else:
|
||||
layer_input = torch.ops.vllm.hc_collapse_triton(residual, pre_mix)
|
||||
return post_mix, comb_mix, layer_input, next_pre_mix
|
||||
|
||||
|
||||
# Global flag to ensure ops are registered only once
|
||||
_OPS_REGISTERED = False
|
||||
|
||||
|
||||
def _sync_aiter_situv2_moe_env() -> None:
|
||||
"""Mirror the SiTUv2 MoE toggle into AITER's a4w4 dispatch env.
|
||||
|
||||
AITER selects afp8 vs afp4 activation kernels via AITER_SITUV2_A8W4 /
|
||||
AITER_SITUV2_A4W4 (see ROCm/aiter fused_moe.py, A8W4 checked first).
|
||||
When VLLM_ROCM_USE_AITER_MOE_SITUV2 is enabled we route to a4w4
|
||||
(afp4_wfp4_fp4 kernels) and clear any legacy AITER_SITUV2_A8W4 override.
|
||||
|
||||
Requires AITER with ROCm/aiter#4463 (first tagged in v0.1.20): a4w4
|
||||
dispatch plus kimik3_a4w4_{un,}tuned_fmoe.csv. Older AITER still runs
|
||||
afp4 FlyDSL but falls back to heuristic configs, which is not the
|
||||
tuned a4w4 path this recipe is meant to use.
|
||||
"""
|
||||
import os
|
||||
|
||||
import vllm.envs as envs
|
||||
|
||||
if envs.VLLM_ROCM_USE_AITER_MOE_SITUV2:
|
||||
os.environ["AITER_SITUV2_A4W4"] = "1"
|
||||
os.environ.pop("AITER_SITUV2_A8W4", None)
|
||||
else:
|
||||
os.environ.pop("AITER_SITUV2_A4W4", None)
|
||||
|
||||
|
||||
class rocm_aiter_ops:
|
||||
"""ROCm AITER operations wrapper for AMD GPU acceleration in vLLM.
|
||||
|
||||
@@ -1702,7 +1798,7 @@ class rocm_aiter_ops:
|
||||
VLLM_ROCM_USE_AITER_FP8BMM: Controls FP8 batched matrix multiply.
|
||||
VLLM_ROCM_USE_AITER_TRITON_ROPE: Controls Triton rotary embeddings.
|
||||
VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS: Controls shared expert fusion.
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4: Controls a8w4 SiTU fused MoE variant.
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2: Controls SiTUv2 FlyDSL MoE (a4w4).
|
||||
VLLM_ROCM_USE_AITER_TRITON_GEMM: Controls Triton unquantized GEMM.
|
||||
|
||||
Note:
|
||||
@@ -1769,7 +1865,7 @@ class rocm_aiter_ops:
|
||||
# TODO: Consolidate under VLLM_ROCM_USE_AITER_ROPE
|
||||
_TRITON_ROTARY_EMBED = envs.VLLM_ROCM_USE_AITER_TRITON_ROPE
|
||||
_MOE_SHARED_EXPERTS_ENABLED = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
|
||||
_MOE_SITUV2_A8W4 = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4
|
||||
_MOE_SITUV2 = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2
|
||||
# TODO: Consolidate under _LINEAR_ENABLED
|
||||
_TRITON_UNQUANT_GEMM = envs.VLLM_ROCM_USE_AITER_TRITON_GEMM
|
||||
# Lazily probed: whether aiter.topk_softmax supports the
|
||||
@@ -1798,7 +1894,8 @@ class rocm_aiter_ops:
|
||||
cls._LINEAR_HIPBMM_ENABLED = envs.VLLM_ROCM_USE_AITER_LINEAR_HIPBMM
|
||||
cls._TRITON_ROTARY_EMBED = envs.VLLM_ROCM_USE_AITER_TRITON_ROPE
|
||||
cls._MOE_SHARED_EXPERTS_ENABLED = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
|
||||
cls._MOE_SITUV2_A8W4 = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4
|
||||
cls._MOE_SITUV2 = envs.VLLM_ROCM_USE_AITER_MOE_SITUV2
|
||||
_sync_aiter_situv2_moe_env()
|
||||
cls._TRITON_UNQUANT_GEMM = envs.VLLM_ROCM_USE_AITER_TRITON_GEMM
|
||||
|
||||
@staticmethod
|
||||
@@ -1911,10 +2008,10 @@ class rocm_aiter_ops:
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def is_fused_moe_situv2_a8w4_enabled(cls) -> bool:
|
||||
# _MOE_SITUV2_A8W4 is a variant of aiter fused moe, so aiter
|
||||
def is_fused_moe_situv2_enabled(cls) -> bool:
|
||||
# _MOE_SITUV2 is a variant of aiter fused moe, so aiter
|
||||
# fused moe must be enabled as well.
|
||||
return cls.is_fused_moe_enabled() and cls._MOE_SITUV2_A8W4
|
||||
return cls.is_fused_moe_enabled() and cls._MOE_SITUV2
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
@@ -1967,6 +2064,26 @@ class rocm_aiter_ops:
|
||||
def is_mla_enabled(cls) -> bool:
|
||||
return cls._AITER_ENABLED and cls._MLA_ENABLED
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def mla_decode_supports_non_causal(cls) -> bool:
|
||||
"""Whether installed aiter.mla.mla_decode_fwd accepts `causal`.
|
||||
|
||||
Added in aiter v0.1.20. A missing argument is a hard error rather
|
||||
than a boolean the caller can use to pick another MLA backend.
|
||||
"""
|
||||
import inspect
|
||||
|
||||
from aiter.mla import mla_decode_fwd
|
||||
|
||||
if "causal" not in inspect.signature(mla_decode_fwd).parameters:
|
||||
raise RuntimeError(
|
||||
"ROCM_AITER_MLA requires aiter.mla.mla_decode_fwd(..., causal=). "
|
||||
"The installed aiter is causal-only; upgrade aiter rather than "
|
||||
"falling back to another MLA backend."
|
||||
)
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
@if_aiter_supported
|
||||
def is_mha_enabled(cls) -> bool:
|
||||
@@ -2789,6 +2906,7 @@ class rocm_aiter_ops:
|
||||
reduce_indptr: torch.Tensor | None = None,
|
||||
reduce_final_map: torch.Tensor | None = None,
|
||||
reduce_partial_map: torch.Tensor | None = None,
|
||||
causal: bool = True,
|
||||
):
|
||||
torch.ops.vllm.rocm_aiter_mla_decode_fwd(
|
||||
q,
|
||||
@@ -2809,6 +2927,7 @@ class rocm_aiter_ops:
|
||||
reduce_indptr=reduce_indptr,
|
||||
reduce_final_map=reduce_final_map,
|
||||
reduce_partial_map=reduce_partial_map,
|
||||
causal=causal,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -3611,6 +3730,10 @@ class rocm_aiter_ops:
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
residual_out: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""mHC pre using the pre-mix carried from the previous sublayer.
|
||||
|
||||
@@ -3625,6 +3748,15 @@ class rocm_aiter_ops:
|
||||
that redundant store is the price of not having a native delayed
|
||||
kernel, and is small next to the ~140 launches it replaces.
|
||||
|
||||
Passing ``sublayer_out`` / ``post_layer_mix`` / ``comb_res_mix``
|
||||
also applies the preceding post block. AITER then projects the new
|
||||
residual in the same kernel that computes it
|
||||
(``mhc_fused_post_pre_gemm_sqrsum``), which saves one launch; every
|
||||
later stage is identical either way. That new residual is written to
|
||||
``residual_out``, which the caller must supply in that case; it is an
|
||||
output buffer rather than a return value so the op never has to hand
|
||||
back one of its own inputs on the unfused path.
|
||||
|
||||
Returns:
|
||||
post_mix: shape (..., hc_mult, 1), dtype torch.float32
|
||||
comb_mix: shape (..., hc_mult, hc_mult), dtype torch.float32
|
||||
@@ -3632,8 +3764,9 @@ class rocm_aiter_ops:
|
||||
next_pre_mix: shape (..., hc_mult), dtype torch.float32
|
||||
"""
|
||||
from aiter.ops.mhc import (
|
||||
get_mhc_fused_post_pre_config,
|
||||
get_mhc_pre_splitk,
|
||||
mhc_pre_big_fuse,
|
||||
mhc_fused_post_pre_gemm_sqrsum,
|
||||
mhc_pre_gemm_sqrsum,
|
||||
)
|
||||
|
||||
@@ -3666,9 +3799,16 @@ class rocm_aiter_ops:
|
||||
|
||||
pre_mix_flat = None if pre_mix is None else pre_mix.view(-1, hc_mult)
|
||||
|
||||
fuse_post = sublayer_out is not None
|
||||
# AITER's Python wrappers allocate without explicit device arguments.
|
||||
with torch.device(device):
|
||||
splitk, tile_k = get_mhc_pre_splitk(num_tokens, hc_hidden_size)
|
||||
if fuse_post:
|
||||
# Keyed on the per-stream K, i.e. hidden_size, not hc_mult * it.
|
||||
splitk, tile_m, tile_n, tile_k = get_mhc_fused_post_pre_config(
|
||||
num_tokens, hidden_size
|
||||
)
|
||||
else:
|
||||
splitk, tile_k = get_mhc_pre_splitk(num_tokens, hc_hidden_size)
|
||||
# AITER pads the GEMM output to a multiple of 32 columns.
|
||||
gemm_pad = torch.empty(
|
||||
splitk,
|
||||
@@ -3679,50 +3819,46 @@ class rocm_aiter_ops:
|
||||
)
|
||||
gemm_out = gemm_pad[:, :, :hc_mult3]
|
||||
sqrsum = torch.empty(splitk, num_tokens, dtype=torch.float32, device=device)
|
||||
mhc_pre_gemm_sqrsum(gemm_out, sqrsum, residual_flat, fn, tile_k, 0)
|
||||
if fuse_post:
|
||||
# Restated for the type checker, which cannot narrow the
|
||||
# optional arguments through the fuse_post flag.
|
||||
assert sublayer_out is not None
|
||||
assert post_layer_mix is not None and comb_res_mix is not None
|
||||
assert residual_out is not None
|
||||
projected = residual_out.view(-1, hc_mult, hidden_size)
|
||||
mhc_fused_post_pre_gemm_sqrsum(
|
||||
gemm_out,
|
||||
sqrsum,
|
||||
projected,
|
||||
sublayer_out.view(-1, hidden_size),
|
||||
residual_flat,
|
||||
# The kernel wants the post mix squeezed to (tokens, hc_mult).
|
||||
post_layer_mix.view(-1, hc_mult, 1).squeeze(-1),
|
||||
comb_res_mix.view(-1, hc_mult, hc_mult),
|
||||
fn,
|
||||
tile_m,
|
||||
tile_n,
|
||||
tile_k,
|
||||
0,
|
||||
)
|
||||
else:
|
||||
projected = residual_flat
|
||||
mhc_pre_gemm_sqrsum(gemm_out, sqrsum, projected, fn, tile_k, 0)
|
||||
|
||||
post_mix = torch.empty(
|
||||
num_tokens, hc_mult, 1, dtype=torch.float32, device=device
|
||||
)
|
||||
comb_mix = torch.empty(
|
||||
num_tokens, hc_mult, hc_mult, dtype=torch.float32, device=device
|
||||
)
|
||||
unused_collapse = torch.empty(
|
||||
num_tokens, hidden_size, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
mhc_pre_big_fuse(
|
||||
post_mix,
|
||||
comb_mix,
|
||||
unused_collapse,
|
||||
gemm_out,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
residual_flat,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
hc_sinkhorn_eps,
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
)
|
||||
|
||||
next_pre_mix = torch.ops.vllm.mhc_pre_mix_triton(
|
||||
post_mix, comb_mix, layer_input, next_pre_mix = _mhc_delayed_pre_tail(
|
||||
gemm_out,
|
||||
sqrsum,
|
||||
projected,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
hc_mult,
|
||||
hc_hidden_size,
|
||||
pre_mix_flat,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
hc_sinkhorn_eps,
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
)
|
||||
|
||||
if pre_mix_flat is None:
|
||||
# Model entry selects residual stream zero.
|
||||
layer_input = residual_flat[:, 0]
|
||||
else:
|
||||
layer_input = torch.ops.vllm.hc_collapse_triton(residual_flat, pre_mix_flat)
|
||||
|
||||
return (
|
||||
post_mix.view(*outer_shape, hc_mult, 1),
|
||||
comb_mix.view(*outer_shape, hc_mult, hc_mult),
|
||||
@@ -3730,6 +3866,21 @@ class rocm_aiter_ops:
|
||||
next_pre_mix.view(*outer_shape, hc_mult),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def mhc_fused_post_pre_delayed_prefers_unfused(num_tokens: int) -> bool:
|
||||
"""True when AITER's own heuristic favours separate post and pre.
|
||||
|
||||
Mirrors the ``fused_m_upper_bound`` table in ``aiter.ops.mhc``: the
|
||||
fused GEMM wins for decode-sized batches and loses for large ones.
|
||||
"""
|
||||
from aiter.jit.utils.chip_info import get_gfx_runtime
|
||||
|
||||
return num_tokens >= {
|
||||
"gfx950": 1024,
|
||||
"gfx942": 128,
|
||||
"gfx1250": 1024,
|
||||
}.get(get_gfx_runtime(), 1024)
|
||||
|
||||
@staticmethod
|
||||
def hc_head(
|
||||
hs_flat: torch.Tensor,
|
||||
@@ -3903,3 +4054,4 @@ class rocm_aiter_ops:
|
||||
|
||||
|
||||
rocm_aiter_ops.register_ops_once()
|
||||
_sync_aiter_situv2_moe_env()
|
||||
|
||||
@@ -606,6 +606,7 @@ async def _run_pooling_request(
|
||||
headers: dict[str, Any],
|
||||
pbar: tqdm | None = None,
|
||||
num_input_sequences: int = 1,
|
||||
prompt_len: int = 0,
|
||||
) -> RequestFuncOutput:
|
||||
output = RequestFuncOutput(num_input_sequences=num_input_sequences)
|
||||
st = time.perf_counter()
|
||||
@@ -613,11 +614,19 @@ async def _run_pooling_request(
|
||||
try:
|
||||
async with session.post(url=api_url, headers=headers, json=payload) as response:
|
||||
if response.status == 200:
|
||||
encoding_format = payload.get("encoding_format", "float")
|
||||
if encoding_format in ("bytes", "bytes_only"):
|
||||
async for _ in response.content.iter_any():
|
||||
pass
|
||||
else:
|
||||
await response.read()
|
||||
output.ttft = output.latency = time.perf_counter() - st
|
||||
|
||||
if payload.get("encoding_format", "float") == "bytes":
|
||||
if encoding_format == "bytes":
|
||||
metadata = json.loads(response.headers["metadata"])
|
||||
usage = metadata.get("usage", {})
|
||||
elif encoding_format == "bytes_only":
|
||||
usage = {"prompt_tokens": prompt_len}
|
||||
else:
|
||||
data = await response.json()
|
||||
usage = data.get("usage", {})
|
||||
@@ -672,6 +681,7 @@ async def async_request_openai_embeddings(
|
||||
headers=headers,
|
||||
pbar=pbar,
|
||||
num_input_sequences=_get_num_input_sequences(request_func_input.prompt),
|
||||
prompt_len=request_func_input.prompt_len,
|
||||
)
|
||||
|
||||
|
||||
@@ -709,6 +719,7 @@ async def async_request_vllm_rerank(
|
||||
headers=headers,
|
||||
pbar=pbar,
|
||||
num_input_sequences=len(request_func_input.prompt) - 1,
|
||||
prompt_len=request_func_input.prompt_len,
|
||||
)
|
||||
|
||||
|
||||
@@ -743,6 +754,7 @@ async def async_request_openai_embeddings_chat(
|
||||
payload=payload,
|
||||
headers=headers,
|
||||
pbar=pbar,
|
||||
prompt_len=request_func_input.prompt_len,
|
||||
)
|
||||
|
||||
|
||||
@@ -847,6 +859,7 @@ async def async_request_infinity_embeddings(
|
||||
headers=headers,
|
||||
pbar=pbar,
|
||||
num_input_sequences=_get_num_input_sequences(request_func_input.prompt),
|
||||
prompt_len=request_func_input.prompt_len,
|
||||
)
|
||||
|
||||
|
||||
@@ -896,6 +909,7 @@ async def async_request_vllm_pooling(
|
||||
headers=headers,
|
||||
pbar=pbar,
|
||||
num_input_sequences=_get_num_input_sequences(request_func_input.prompt),
|
||||
prompt_len=request_func_input.prompt_len,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,17 @@ from contextlib import contextmanager
|
||||
from typing import Any
|
||||
|
||||
|
||||
def redact_sensitive_namespace(
|
||||
args: argparse.Namespace, fields: tuple[str, ...]
|
||||
) -> argparse.Namespace:
|
||||
"""Return a copy of CLI arguments with selected values redacted."""
|
||||
redacted_args = argparse.Namespace(**vars(args))
|
||||
for field in fields:
|
||||
if getattr(redacted_args, field, None) is not None:
|
||||
setattr(redacted_args, field, "***")
|
||||
return redacted_args
|
||||
|
||||
|
||||
def extract_field(
|
||||
args: argparse.Namespace, extra_info: dict[str, Any], field_name: str
|
||||
) -> str:
|
||||
|
||||
@@ -51,13 +51,18 @@ from vllm.benchmarks.lib.endpoint_request_func import (
|
||||
RequestFuncOutput,
|
||||
)
|
||||
from vllm.benchmarks.lib.ready_checker import wait_for_endpoint
|
||||
from vllm.benchmarks.lib.utils import convert_to_pytorch_benchmark_format, write_to_json
|
||||
from vllm.benchmarks.lib.utils import (
|
||||
convert_to_pytorch_benchmark_format,
|
||||
redact_sensitive_namespace,
|
||||
write_to_json,
|
||||
)
|
||||
from vllm.tokenizers import TokenizerLike, get_tokenizer
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.gc_utils import freeze_gc_heap
|
||||
from vllm.utils.network_utils import join_host_port
|
||||
|
||||
MILLISECONDS_TO_SECONDS_CONVERSION = 1000
|
||||
_SENSITIVE_ARG_FIELDS = ("header",)
|
||||
|
||||
|
||||
def _merge_overrides(base: dict | None, override: dict | None) -> dict | None:
|
||||
@@ -1536,7 +1541,7 @@ def save_to_pytorch_benchmark_format(
|
||||
# later if needed
|
||||
ignored_metrics = ["ttfts", "itls", "generated_texts", "errors"]
|
||||
pt_records = convert_to_pytorch_benchmark_format(
|
||||
args=args,
|
||||
args=redact_sensitive_namespace(args, _SENSITIVE_ARG_FIELDS),
|
||||
metrics={k: [results[k]] for k in metrics if k in results},
|
||||
extra_info={
|
||||
k: results[k]
|
||||
@@ -2013,7 +2018,7 @@ def main(args: argparse.Namespace) -> dict[str, Any]:
|
||||
|
||||
|
||||
async def main_async(args: argparse.Namespace) -> dict[str, Any]:
|
||||
print(args)
|
||||
print(redact_sensitive_namespace(args, _SENSITIVE_ARG_FIELDS))
|
||||
if args.max_concurrency is not None and args.max_concurrency <= 0:
|
||||
raise ValueError("--max-concurrency must be greater than 0")
|
||||
|
||||
|
||||
@@ -86,9 +86,20 @@ class AttentionConfig:
|
||||
indexer). Quantized formats (fp8, mxfp4, nvfp4) require indexer kernel
|
||||
support in the backend."""
|
||||
|
||||
indexer_sparse_logits: bool = False
|
||||
"""DeepSeek V4.1 two-level indexer: score only the candidate blocks with
|
||||
DeepGEMM's sparse MQA-logits kernels instead of computing dense logits over
|
||||
the whole context and masking them. Requires `indexer_kv_dtype="mxfp4"`,
|
||||
an SM100-class GPU, DeepGEMM >= 2.8 and the DeepSelect top-k extension
|
||||
(the top-k runs on the kernels' bf16 logits). The sparse path costs
|
||||
O(candidate blocks) per query regardless of context length, so it pays off
|
||||
for long contexts (roughly 32K tokens and beyond) and is slower below."""
|
||||
|
||||
hisparse_config: HiSparseConfig | None = None
|
||||
"""HiSparse host-resident KV configuration. Setting this enables experimental
|
||||
Model Runner V2-only HiSparse sparse-MLA decode hot-buffering."""
|
||||
Model Runner V2-only HiSparse sparse-MLA decode hot-buffering. It is inferred
|
||||
with defaults when HiSparseConnector is configured (directly or via
|
||||
MultiConnector); set it explicitly only to tune its fields."""
|
||||
|
||||
use_non_causal: bool = False
|
||||
"""Whether to use non-causal (bidirectional) attention."""
|
||||
|
||||
@@ -34,6 +34,9 @@ class IrOpPriorityConfig:
|
||||
fused_add_rms_norm: list[str] = Field(default_factory=list)
|
||||
"""Priority list for vllm.ir.ops.fused_add_rms_norm"""
|
||||
|
||||
gelu_and_mul_sparse: list[str] = Field(default_factory=list)
|
||||
"""Priority list for vllm.ir.ops.gelu_and_mul_sparse"""
|
||||
|
||||
def compute_hash(self) -> str:
|
||||
"""
|
||||
Produces a hash unique to the pass configuration.
|
||||
@@ -323,6 +326,13 @@ class KernelConfig:
|
||||
- "xpu_woq": Use XPU kernels for weight-only quantization (e.g. W8A16)
|
||||
"""
|
||||
|
||||
linear_backend_per_quant: dict[str, LinearBackend] | None = Field(
|
||||
default=None, min_length=1
|
||||
)
|
||||
"""Backend overrides keyed by linear quantization scheme. Overrides take
|
||||
precedence over ``linear_backend``; for example,
|
||||
``{"nvfp4_w4a16": "humming"}``."""
|
||||
|
||||
@field_validator("moe_backend", mode="before")
|
||||
@classmethod
|
||||
def _normalize_moe_backend(cls, value: Any) -> Any:
|
||||
@@ -356,6 +366,8 @@ class KernelConfig:
|
||||
"enable_flashinfer_autotune",
|
||||
"ir_op_priority", # handled separately below
|
||||
}
|
||||
if self.linear_backend_per_quant is None:
|
||||
ignored_factors.add("linear_backend_per_quant")
|
||||
factors = get_hash_factors(self, ignored_factors)
|
||||
factors["ir_op_priority"] = self.ir_op_priority.compute_hash()
|
||||
return hash_factors(factors)
|
||||
|
||||
@@ -76,6 +76,10 @@ class ProfilerConfig:
|
||||
"""Optional format passed to Proton when finalizing a profile. ``None``
|
||||
uses the default format for ``proton_data``."""
|
||||
|
||||
proton_graph_attribution: bool = False
|
||||
"""Observe CUDA graph capture so replayed kernels can be attributed.
|
||||
Requires Triton >= 3.7 and ``proton_data='tree'``."""
|
||||
|
||||
torch_profiler_with_stack: bool = True
|
||||
"""If `True`, enables stack tracing in the torch profiler. Enabled by default
|
||||
as it is useful for debugging. Can be disabled via
|
||||
@@ -199,6 +203,7 @@ class ProfilerConfig:
|
||||
("proton_mode", self.proton_mode, None),
|
||||
("proton_hook", self.proton_hook, None),
|
||||
("proton_output_format", self.proton_output_format, None),
|
||||
("proton_graph_attribution", self.proton_graph_attribution, False),
|
||||
)
|
||||
if value != default
|
||||
]
|
||||
@@ -220,6 +225,17 @@ class ProfilerConfig:
|
||||
|
||||
if self.profiler == "proton":
|
||||
output_format = self.proton_output_format
|
||||
if self.proton_graph_attribution and self.proton_data != "tree":
|
||||
raise ValueError("proton_graph_attribution requires proton_data='tree'")
|
||||
if (
|
||||
self.proton_graph_attribution
|
||||
and self.proton_mode
|
||||
and self.proton_mode.split(":", 1)[0].lower() == "periodic_flushing"
|
||||
):
|
||||
raise ValueError(
|
||||
"proton_graph_attribution is incompatible with periodic_flushing: "
|
||||
"both manage Proton data phases."
|
||||
)
|
||||
if output_format == "chrome_trace" and self.proton_data != "trace":
|
||||
raise ValueError("chrome_trace output requires proton_data='trace'")
|
||||
if (
|
||||
|
||||
@@ -1561,8 +1561,16 @@ class SpeculativeConfig:
|
||||
self.index_share_for_mtp_iteration
|
||||
)
|
||||
|
||||
if self.method != "dspark" and self.enable_adaptive_verification:
|
||||
raise ValueError("Adaptive verification only supported with DSpark")
|
||||
if (
|
||||
self.method != "dspark"
|
||||
and self.enable_adaptive_verification
|
||||
and self.use_local_argmax_reduction
|
||||
):
|
||||
raise ValueError(
|
||||
"Adaptive verification estimates per-position acceptance from "
|
||||
"the draft logits, which use_local_argmax_reduction never "
|
||||
"materializes. Disable one of them."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
|
||||
+83
-25
@@ -27,7 +27,7 @@ from vllm.triton_utils import HAS_TRITON
|
||||
from vllm.utils import random_uuid
|
||||
from vllm.utils.hashing import safe_hash
|
||||
|
||||
from .attention import AttentionConfig
|
||||
from .attention import AttentionConfig, HiSparseConfig
|
||||
from .cache import CacheConfig
|
||||
from .compilation import CompilationConfig, CompilationMode, CUDAGraphMode
|
||||
from .device import DeviceConfig
|
||||
@@ -650,6 +650,29 @@ class VllmConfig:
|
||||
return self.num_speculative_tokens
|
||||
return 0
|
||||
|
||||
@property
|
||||
def num_prefill_lookahead_tokens(self) -> int:
|
||||
"""Prefill tokens past the computed range that the drafter reads.
|
||||
|
||||
Mid-prefill the drafter consumes tokens the target model has not been
|
||||
scheduled for yet, so every component that has to keep them available
|
||||
must apply this margin: the scheduler, which never ends a chunk within
|
||||
it and shifts encoder scheduling by it, and the KV cache manager, which
|
||||
treats the trailing `this - 1` tokens as re-prefillable rather than
|
||||
finalized. Consumers must read this property rather than re-deriving
|
||||
their own per-method lookahead, so those components cannot drift apart.
|
||||
"""
|
||||
speculative_config = self.speculative_config
|
||||
if speculative_config is None or not speculative_config.use_eagle():
|
||||
return 0
|
||||
if speculative_config.use_multi_module_mtp():
|
||||
# Each MTP module reads one token further ahead than the one before
|
||||
# it, so the chain needs num_speculative_tokens of runway at a
|
||||
# chunked-prefill boundary.
|
||||
return self.num_speculative_tokens
|
||||
# Eagle-family drafters read only the immediate next token.
|
||||
return 1
|
||||
|
||||
@property
|
||||
def uniform_decode_query_len(self) -> int:
|
||||
"""Query length of every request in a uniform decode batch.
|
||||
@@ -1551,18 +1574,6 @@ class VllmConfig:
|
||||
self.compilation_config.mode = CompilationMode.NONE
|
||||
self.compilation_config.cudagraph_mode = CUDAGraphMode.NONE
|
||||
|
||||
if self.profiler_config.profiler == "proton":
|
||||
if not current_platform.is_cuda():
|
||||
raise ValueError(
|
||||
"The Proton profiler currently supports NVIDIA CUDA only"
|
||||
)
|
||||
if self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE:
|
||||
raise ValueError(
|
||||
"The Proton profiler requires CUDA graphs to be disabled. "
|
||||
"Use --enforce-eager or set "
|
||||
"--compilation-config.cudagraph_mode=none."
|
||||
)
|
||||
|
||||
if os.environ.get("TORCH_COMPILE_DISABLE") == "1":
|
||||
logger.warning_once(
|
||||
"TORCH_COMPILE_DISABLE is set, disabling torch.compile. "
|
||||
@@ -1642,6 +1653,13 @@ class VllmConfig:
|
||||
self._maybe_disable_dynamic_sd_for_data_parallel()
|
||||
self._maybe_override_dynamic_sd_cudagraph_mode()
|
||||
|
||||
if (
|
||||
self.attention_config.hisparse_config is None
|
||||
and self.kv_transfer_config is not None
|
||||
and self.kv_transfer_config.has_connector("HiSparseConnector")
|
||||
):
|
||||
self.attention_config.hisparse_config = HiSparseConfig()
|
||||
|
||||
if self.attention_config.hisparse_config is not None:
|
||||
if not current_platform.is_cuda():
|
||||
raise ValueError("HiSparse currently requires NVIDIA CUDA.")
|
||||
@@ -1860,6 +1878,7 @@ class VllmConfig:
|
||||
else:
|
||||
self._validate_v1_model_runner()
|
||||
|
||||
self._validate_profiler_config()
|
||||
self._validate_batch_sharded_sampling()
|
||||
self._validate_adaptive_verification()
|
||||
|
||||
@@ -2840,16 +2859,16 @@ class VllmConfig:
|
||||
unsupported.append("pipeline parallelism with external_launcher")
|
||||
|
||||
if speculative_config is not None:
|
||||
# TODO: ngram / ngram_gpu are not supported by the v2 model runner yet
|
||||
if speculative_config.method in ("ngram", "ngram_gpu"):
|
||||
unsupported.append("ngram/ngram_gpu speculative decoding")
|
||||
elif speculative_config.method not in (
|
||||
"eagle",
|
||||
"eagle3",
|
||||
"mtp",
|
||||
"dflash",
|
||||
"dspark",
|
||||
"extract_hidden_states",
|
||||
if speculative_config.method in (
|
||||
# https://github.com/vllm-project/vllm/pull/40704
|
||||
"ngram",
|
||||
"ngram_gpu",
|
||||
# https://github.com/vllm-project/vllm/pull/43091
|
||||
"draft_model",
|
||||
"suffix",
|
||||
"medusa",
|
||||
"mlp_speculator",
|
||||
"custom_class",
|
||||
):
|
||||
unsupported.append(f"speculative method '{speculative_config.method}'")
|
||||
|
||||
@@ -3034,13 +3053,52 @@ class VllmConfig:
|
||||
unsupported.append("dual batch overlap with multimodal models")
|
||||
if model_config is not None and model_config.is_hybrid:
|
||||
unsupported.append("dual batch overlap with hybrid models")
|
||||
if self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE:
|
||||
unsupported.append("dual batch overlap with CUDA graphs")
|
||||
if self.compilation_config.cudagraph_mode == CUDAGraphMode.PIECEWISE:
|
||||
# DBO captures FULL graphs only.
|
||||
unsupported.append("dual batch overlap with PIECEWISE CUDA graphs")
|
||||
if self.is_mm_encoder_only:
|
||||
unsupported.append("dual batch overlap with encoder only models")
|
||||
|
||||
return unsupported
|
||||
|
||||
def _validate_profiler_config(self) -> None:
|
||||
if self.profiler_config.profiler != "proton":
|
||||
return
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
raise ValueError("The Proton profiler currently supports NVIDIA CUDA only")
|
||||
if (
|
||||
self.profiler_config.proton_graph_attribution
|
||||
and not self.use_v2_model_runner
|
||||
):
|
||||
raise ValueError(
|
||||
"Proton CUDA graph attribution requires the V2 model runner."
|
||||
)
|
||||
|
||||
has_cuda_graphs = (
|
||||
self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE
|
||||
or (
|
||||
self.compilation_config.cudagraph_mm_encoder
|
||||
and not (self.model_config and self.model_config.enforce_eager)
|
||||
)
|
||||
)
|
||||
if not has_cuda_graphs:
|
||||
return
|
||||
mode = self.profiler_config.proton_mode
|
||||
if mode and mode.split(":", 1)[0].lower() == "pcsampling":
|
||||
raise ValueError(
|
||||
"Proton PC sampling requires CUDA graphs to be disabled. "
|
||||
"Use --enforce-eager."
|
||||
)
|
||||
if not self.profiler_config.proton_graph_attribution:
|
||||
raise ValueError(
|
||||
"Proton profiling with CUDA graphs requires "
|
||||
"proton_graph_attribution=True to capture replayed kernels. "
|
||||
"Enable attribution or use --enforce-eager."
|
||||
)
|
||||
|
||||
def _validate_v2_model_runner(self) -> None:
|
||||
"""Check for features not yet supported by the V2 model runner."""
|
||||
if not HAS_TRITON:
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import asyncio
|
||||
import logging
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Collection
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from enum import IntEnum
|
||||
@@ -433,6 +435,9 @@ class PullReqMeta:
|
||||
expire_time: float = float("inf")
|
||||
# Designed for one D pairing to multiple P
|
||||
pull_tasks_count: int = 0
|
||||
# Set once any worker reports a failure, so a success from another worker
|
||||
# for the same request is not counted afterwards.
|
||||
failed: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -582,6 +587,11 @@ class MooncakeConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
assert self.connector_worker is not None
|
||||
return self.connector_worker.get_finished()
|
||||
|
||||
def get_block_ids_with_load_errors(self) -> set[int]:
|
||||
"""Get block IDs whose remote KV load failed."""
|
||||
assert self.connector_worker is not None
|
||||
return self.connector_worker.get_block_ids_with_load_errors()
|
||||
|
||||
def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None:
|
||||
assert self.connector_worker is not None
|
||||
assert isinstance(self._connector_metadata, MooncakeConnectorMetadata)
|
||||
@@ -1034,6 +1044,8 @@ class MooncakeConnectorWorker:
|
||||
|
||||
self.finished_sending_reqs: set[ReqId] = set()
|
||||
self.finished_recving_reqs: set[ReqId] = set()
|
||||
# Written from the receiver loop, drained from the worker thread.
|
||||
self._invalid_block_ids: queue.Queue[set[int]] = queue.Queue()
|
||||
|
||||
self.xfer_stats = MooncakeKVConnectorStats()
|
||||
|
||||
@@ -1907,12 +1919,11 @@ class MooncakeConnectorWorker:
|
||||
ret_msg = await sock.recv()
|
||||
response = self._xfer_resp_decoder.decode(ret_msg)
|
||||
if response.status == MooncakeXferResponseStatus.ERROR:
|
||||
logger.error(
|
||||
"Error happens during transferring kvcache for %s: %s",
|
||||
self._handle_failed_recv(
|
||||
pull_metas,
|
||||
req_ids,
|
||||
response.err_msg,
|
||||
response.err_msg or "transfer error",
|
||||
)
|
||||
self.xfer_stats.record_failed_recv()
|
||||
return
|
||||
self.process_pulling_result(response, pull_metas)
|
||||
if response.status == MooncakeXferResponseStatus.FINISH:
|
||||
@@ -1920,10 +1931,50 @@ class MooncakeConnectorWorker:
|
||||
except zmq.ContextTerminated:
|
||||
logger.debug("ZMQ context terminated, exiting Mooncake receiver thread.")
|
||||
except Exception as e:
|
||||
logger.error("MooncakeXferMetadata transfer failed for %s: %s", req_ids, e)
|
||||
self.xfer_stats.record_failed_recv()
|
||||
self._handle_failed_recv(pull_metas, req_ids, f"transfer failed: {e}")
|
||||
return
|
||||
|
||||
def _handle_failed_recv(
|
||||
self,
|
||||
pull_metas: dict[ReqId, PullReqMeta],
|
||||
req_ids: Collection[ReqId],
|
||||
reason: str,
|
||||
) -> None:
|
||||
"""Report a failed remote KV load so the scheduler can fail or recompute it."""
|
||||
failed: list[ReqId] = []
|
||||
for req_id in req_ids:
|
||||
pull_meta = pull_metas.get(req_id)
|
||||
if pull_meta is None or pull_meta.failed:
|
||||
continue
|
||||
pull_meta.failed = True
|
||||
failed.append(req_id)
|
||||
self.xfer_stats.record_failed_recv()
|
||||
|
||||
invalid = {b for group in pull_meta.local_block_ids for b in group}
|
||||
if not invalid:
|
||||
# A pull with no local blocks only asks P to release its blocks
|
||||
# for a request that never reached the scheduler (see
|
||||
# AsyncLLM.notify_kv_transfer_request_rejected, which submits an
|
||||
# abort_immediately request just to run request_finished). No D
|
||||
# request is waiting on a load, and reporting one here would trip
|
||||
# the scheduler's `assert req_id in self.requests`.
|
||||
continue
|
||||
self._invalid_block_ids.put(invalid)
|
||||
self.finished_recving_reqs.add(pull_meta.d_req_id)
|
||||
|
||||
if failed:
|
||||
logger.error("pulling kv_caches for %s failed: %s", failed, reason)
|
||||
|
||||
def get_block_ids_with_load_errors(self) -> set[int]:
|
||||
"""Drain the blocks whose remote KV load failed since the last call."""
|
||||
result: set[int] = set()
|
||||
while True:
|
||||
try:
|
||||
result.update(self._invalid_block_ids.get_nowait())
|
||||
except queue.Empty:
|
||||
break
|
||||
return result
|
||||
|
||||
def process_pulling_result(
|
||||
self,
|
||||
response: MooncakeXferResponse,
|
||||
@@ -1933,6 +1984,8 @@ class MooncakeConnectorWorker:
|
||||
|
||||
for req_id in ok_reqs:
|
||||
pull_meta = pull_metas[req_id]
|
||||
if pull_meta.failed:
|
||||
continue
|
||||
# No race because we are in async loop.
|
||||
pull_meta.pull_tasks_count -= 1
|
||||
if pull_meta.pull_tasks_count == 0:
|
||||
@@ -1942,10 +1995,8 @@ class MooncakeConnectorWorker:
|
||||
logger.debug("pulling kv_caches for %s finished", ok_reqs)
|
||||
|
||||
if response.err_reqs:
|
||||
logger.error(
|
||||
"pulling kv_caches for %s failed: %s",
|
||||
response.err_reqs,
|
||||
response.err_msg,
|
||||
self._handle_failed_recv(
|
||||
pull_metas, response.err_reqs, response.err_msg or "unknown error"
|
||||
)
|
||||
|
||||
async def _connect_to_prefiller_bootstrap(self, remote_bootstrap_addr: str):
|
||||
@@ -2023,10 +2074,11 @@ class MooncakeConnectorWorker:
|
||||
await self._pending_bootstrap_queries[remote_bootstrap_addr].wait()
|
||||
|
||||
if remote_engine_id not in self._remote_agents:
|
||||
logger.error(
|
||||
"Failed to find remote engine_id %s from bootstrap server %s",
|
||||
remote_engine_id,
|
||||
remote_bootstrap_addr,
|
||||
self._handle_failed_recv(
|
||||
pull_metas,
|
||||
list(pull_metas),
|
||||
f"remote engine_id {remote_engine_id} not found from bootstrap "
|
||||
f"server {remote_bootstrap_addr}",
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import torch
|
||||
import zmq
|
||||
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import BlockIds
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorMetadata,
|
||||
)
|
||||
@@ -444,8 +445,8 @@ class ReqMeta:
|
||||
"""Metadata for a single request."""
|
||||
|
||||
transfer_id: TransferId
|
||||
local_block_ids: list[int]
|
||||
remote_block_ids: list[int]
|
||||
local_block_ids: BlockIds
|
||||
remote_block_ids: BlockIds
|
||||
remote_host: str
|
||||
remote_port: int
|
||||
remote_handshake_port: int
|
||||
@@ -481,7 +482,7 @@ class MoRIIOConnectorMetadata(KVConnectorMetadata):
|
||||
def add_new_req(
|
||||
self,
|
||||
request_id: ReqId,
|
||||
local_block_ids: list[int],
|
||||
local_block_ids: BlockIds,
|
||||
kv_transfer_params: dict[str, Any],
|
||||
write_mode=False,
|
||||
):
|
||||
|
||||
@@ -18,10 +18,12 @@ import torch
|
||||
import zmq
|
||||
|
||||
from vllm.config import CUDAGraphMode, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.utils import BlockIds
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorBase_V1,
|
||||
KVConnectorMetadata,
|
||||
KVConnectorRole,
|
||||
SupportsHMA,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
|
||||
ROLE,
|
||||
@@ -67,19 +69,24 @@ from vllm.distributed.parallel_state import (
|
||||
)
|
||||
from vllm.forward_context import ForwardContext, get_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.network_utils import (
|
||||
make_zmq_path,
|
||||
make_zmq_socket,
|
||||
)
|
||||
from vllm.v1.attention.selector import get_attn_backend
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.attention.backend import AttentionMetadata
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.request import Request
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -189,7 +196,7 @@ def resolve_moriio_transfer_ack(
|
||||
return transfer_id
|
||||
|
||||
|
||||
class MoRIIOConnector(KVConnectorBase_V1):
|
||||
class MoRIIOConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
@@ -225,7 +232,7 @@ class MoRIIOConnector(KVConnectorBase_V1):
|
||||
)
|
||||
if role == KVConnectorRole.SCHEDULER:
|
||||
self.connector_scheduler: MoRIIOConnectorScheduler | None = (
|
||||
MoRIIOConnectorScheduler(vllm_config, self.engine_id)
|
||||
MoRIIOConnectorScheduler(vllm_config, self.engine_id, kv_cache_config)
|
||||
)
|
||||
self.connector_worker: MoRIIOConnectorWorker | None = None
|
||||
elif role == KVConnectorRole.WORKER:
|
||||
@@ -283,6 +290,14 @@ class MoRIIOConnector(KVConnectorBase_V1):
|
||||
self,
|
||||
request: "Request",
|
||||
block_ids: list[int],
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
assert self.connector_scheduler is not None
|
||||
return self.connector_scheduler.request_finished(request, (block_ids,))
|
||||
|
||||
def request_finished_all_groups(
|
||||
self,
|
||||
request: "Request",
|
||||
block_ids: BlockIds,
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
assert self.connector_scheduler is not None
|
||||
return self.connector_scheduler.request_finished(request, block_ids)
|
||||
@@ -368,7 +383,12 @@ class MoRIIOConnector(KVConnectorBase_V1):
|
||||
class MoRIIOConnectorScheduler:
|
||||
"""Implementation of Scheduler side methods"""
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, engine_id: str):
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
engine_id: str,
|
||||
kv_cache_config: "KVCacheConfig",
|
||||
):
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
assert vllm_config.kv_transfer_config is not None, (
|
||||
@@ -378,6 +398,66 @@ class MoRIIOConnectorScheduler:
|
||||
self.block_size = vllm_config.cache_config.block_size
|
||||
self.engine_id: EngineId = engine_id
|
||||
self.mode = get_moriio_mode(self.kv_transfer_config)
|
||||
|
||||
self._is_hma_required = (
|
||||
not vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
|
||||
and any(
|
||||
not isinstance(g.kv_cache_spec, FullAttentionSpec)
|
||||
for g in kv_cache_config.kv_cache_groups
|
||||
)
|
||||
)
|
||||
if self._is_hma_required:
|
||||
# TODO(simondanielsson): support non-sliding window hybrids
|
||||
unsupported = [
|
||||
type(g.kv_cache_spec).__name__
|
||||
for g in kv_cache_config.kv_cache_groups
|
||||
if not isinstance(
|
||||
g.kv_cache_spec, (FullAttentionSpec, SlidingWindowSpec)
|
||||
)
|
||||
]
|
||||
if unsupported:
|
||||
raise NotImplementedError(
|
||||
"MoRIIO only supports sliding-window hybrid models (e.g. "
|
||||
"Gemma) under the hybrid KV cache manager. Unsupported KV "
|
||||
f"cache group spec(s): {sorted(set(unsupported))}. Pass "
|
||||
"--disable-hybrid-kv-cache-manager to run without HMA."
|
||||
)
|
||||
if self.mode == MoRIIOMode.WRITE:
|
||||
# TODO(simondanielsson): support HMA in WRITE mode
|
||||
raise NotImplementedError(
|
||||
"MoRIIO WRITE mode does not support hybrid KV cache groups "
|
||||
"(sliding-window attention). Use READ mode, or pass "
|
||||
"--disable-hybrid-kv-cache-manager."
|
||||
)
|
||||
|
||||
sw_sizes_tokens: list[tuple[int, int]] = [
|
||||
(g.kv_cache_spec.sliding_window, g.kv_cache_spec.block_size)
|
||||
if isinstance(g.kv_cache_spec, SlidingWindowSpec)
|
||||
else (0, self.block_size)
|
||||
for g in kv_cache_config.kv_cache_groups
|
||||
]
|
||||
# add 1 to conservatively account for boundary overlap eg window isn't fully
|
||||
# aligned with blocks.
|
||||
self.blocks_per_sw = [
|
||||
cdiv(n_tokens, block_size) + 1 if n_tokens else 0
|
||||
for n_tokens, block_size in sw_sizes_tokens
|
||||
]
|
||||
# In WRITE mode and chunked prefill, we perform the write after the last chunk.
|
||||
# Hence we need to track once we are in the last chunk. We do this by computing
|
||||
# len(block_ids[g]) * block_size[g] for a full attn group g, as hybrid groups
|
||||
# may be clipped and hence not reflect the full sequence length. Here we store
|
||||
# g and block_size[g] for later.
|
||||
self._full_attn_group_idx = 0
|
||||
self._full_attn_block_size = self.block_size
|
||||
for gi, group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
is_full_attn = self.blocks_per_sw[gi] == 0
|
||||
if is_full_attn:
|
||||
self._full_attn_group_idx = gi
|
||||
self._full_attn_block_size = getattr(
|
||||
group.kv_cache_spec, "block_size", self.block_size
|
||||
)
|
||||
break
|
||||
|
||||
self.host_ip = resolve_host_ip(
|
||||
self.kv_transfer_config.kv_connector_extra_config
|
||||
)
|
||||
@@ -409,14 +489,14 @@ class MoRIIOConnectorScheduler:
|
||||
# Requests that need to start recv/send.
|
||||
# New requests are added by update_state_after_alloc in
|
||||
# the scheduler. Used to make metadata passed to Worker.
|
||||
self._reqs_need_recv: dict[ReqId, tuple[Request, list[int]]] = {}
|
||||
self._reqs_need_save: dict[ReqId, tuple[Request, list[int]]] = {}
|
||||
self._reqs_need_recv: dict[ReqId, tuple[Request, BlockIds]] = {}
|
||||
self._reqs_need_save: dict[ReqId, tuple[Request, BlockIds]] = {}
|
||||
# Snapshot of kv_transfer_params for chunked prefill recovery.
|
||||
self._req_kv_params: dict[ReqId, dict] = {}
|
||||
|
||||
# For chunked prefill, we perform layer-wise access within the final chunk.
|
||||
# TODO: Perform transfer at end chunk.
|
||||
self._reqs_need_pending_save: dict[ReqId, tuple[Request, list[int]]] = {}
|
||||
self._reqs_need_pending_save: dict[ReqId, tuple[Request, BlockIds]] = {}
|
||||
|
||||
if self.is_producer:
|
||||
set_role(ROLE.PRODUCER)
|
||||
@@ -442,6 +522,23 @@ class MoRIIOConnectorScheduler:
|
||||
self.transfer_id_to_request_id: dict[TransferId, ReqId] = {}
|
||||
self.request_id_to_transfer_id: dict[ReqId, TransferId] = {}
|
||||
|
||||
def get_exchange_clipped_blocks(
|
||||
self,
|
||||
block_ids: BlockIds,
|
||||
) -> BlockIds:
|
||||
"""Clip the block list based on the layer type.
|
||||
|
||||
Behavior:
|
||||
- sliding window: keep only the last window size blocks
|
||||
- full attention: keep all blocks
|
||||
"""
|
||||
if len(block_ids) == 0 or not self._is_hma_required:
|
||||
return [list(blocks) for blocks in block_ids]
|
||||
return [
|
||||
blocks[-self.blocks_per_sw[i] :] if self.blocks_per_sw[i] > 0 else blocks
|
||||
for i, blocks in enumerate(block_ids)
|
||||
]
|
||||
|
||||
def map_request_id(self, request_id: ReqId, transfer_id: TransferId):
|
||||
self.transfer_id_to_request_id[transfer_id] = request_id
|
||||
self.request_id_to_transfer_id[request_id] = transfer_id
|
||||
@@ -642,7 +739,7 @@ class MoRIIOConnectorScheduler:
|
||||
request_id = request.request_id
|
||||
self.map_request_id(request_id, transfer_id)
|
||||
if params.get("do_remote_decode"):
|
||||
local_block_ids = blocks.get_block_ids()[0]
|
||||
local_block_ids: BlockIds = blocks.get_block_ids()
|
||||
self._reqs_need_save[request.request_id] = (request, local_block_ids)
|
||||
# Snapshot params now so chunked-prefill build_connector_meta
|
||||
# can recover them on the final chunk even if the live
|
||||
@@ -657,17 +754,22 @@ class MoRIIOConnectorScheduler:
|
||||
if "remote_engine_id" in params:
|
||||
if num_external_tokens > 0:
|
||||
# Get unhashed blocks to pull from remote.
|
||||
local_block_ids = blocks.get_block_ids()[0]
|
||||
assert len(local_block_ids) <= len(remote_block_ids)
|
||||
if len(local_block_ids) != len(remote_block_ids):
|
||||
local_block_ids = remote_block_ids[
|
||||
-len(local_block_ids) :
|
||||
]
|
||||
local_block_ids = self.get_exchange_clipped_blocks(
|
||||
blocks.get_block_ids()
|
||||
)
|
||||
# Partial cache hits can lead to fewer local blocks vs
|
||||
# remote blocks, but never more
|
||||
assert all(
|
||||
len(local) <= len(remote)
|
||||
for local, remote in zip(
|
||||
local_block_ids, remote_block_ids, strict=True
|
||||
)
|
||||
)
|
||||
else:
|
||||
# If remote_blocks and num_external_tokens = 0, we have
|
||||
# a full prefix cache hit on the D worker. We need to call
|
||||
# send_notify in _read_blocks to free the memory on the P.
|
||||
local_block_ids = []
|
||||
local_block_ids = [[] for _ in remote_block_ids]
|
||||
|
||||
self._reqs_need_recv[request.request_id] = (
|
||||
request,
|
||||
@@ -818,8 +920,6 @@ class MoRIIOConnectorScheduler:
|
||||
new_block_ids = scheduler_output.scheduled_cached_reqs.new_block_ids[i]
|
||||
|
||||
if new_block_ids is not None:
|
||||
block_ids = new_block_ids[0]
|
||||
# TODO : hybrid attn, etc
|
||||
# A non-disagg request (no kv_transfer_params, e.g. smoke
|
||||
# test) is never registered in _reqs_need_pending_save;
|
||||
# indexing it unconditionally would KeyError and crash the
|
||||
@@ -827,12 +927,16 @@ class MoRIIOConnectorScheduler:
|
||||
if req_id not in self._reqs_need_pending_save:
|
||||
continue
|
||||
req, existing_blocks = self._reqs_need_pending_save[req_id]
|
||||
updated_blocks = list(existing_blocks) + (block_ids)
|
||||
updated_blocks = [
|
||||
existing_blocks[g] + new_block_ids[g]
|
||||
for g in range(len(new_block_ids))
|
||||
]
|
||||
self._reqs_need_pending_save[req_id] = (req, updated_blocks)
|
||||
if (
|
||||
len(self._reqs_need_pending_save[req_id][1]) * self.block_size
|
||||
>= req.num_prompt_tokens
|
||||
):
|
||||
saved_tokens = (
|
||||
len(updated_blocks[self._full_attn_group_idx])
|
||||
* self._full_attn_block_size
|
||||
)
|
||||
if saved_tokens >= req.num_prompt_tokens:
|
||||
# Final chunk: live kv_transfer_params may be cleared,
|
||||
# so prefer the snapshot from update_state_after_alloc.
|
||||
kv_params = self._req_kv_params.pop(
|
||||
@@ -857,7 +961,10 @@ class MoRIIOConnectorScheduler:
|
||||
|
||||
for req_id, (req, block_ids) in self._reqs_need_save.items():
|
||||
kv_params = self._req_kv_params.get(req_id, req.kv_transfer_params or {})
|
||||
if req.num_prompt_tokens > len(block_ids) * self.block_size:
|
||||
tokens_covered = (
|
||||
len(block_ids[self._full_attn_group_idx]) * self._full_attn_block_size
|
||||
)
|
||||
if req.num_prompt_tokens > tokens_covered:
|
||||
# not last chunk prefill
|
||||
self._reqs_need_pending_save[req_id] = (req, block_ids)
|
||||
continue
|
||||
@@ -898,7 +1005,7 @@ class MoRIIOConnectorScheduler:
|
||||
def request_finished(
|
||||
self,
|
||||
request: "Request",
|
||||
block_ids: list[int],
|
||||
block_ids: BlockIds,
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
"""
|
||||
Once a request is finished, determine whether request blocks
|
||||
@@ -936,7 +1043,8 @@ class MoRIIOConnectorScheduler:
|
||||
if self.mode == MoRIIOMode.WRITE:
|
||||
self._release_write_prefill_blocks(request.request_id, params)
|
||||
else:
|
||||
self._reqs_need_recv[request.request_id] = (request, [])
|
||||
empty_groups: BlockIds = [[] for _ in self.blocks_per_sw]
|
||||
self._reqs_need_recv[request.request_id] = (request, empty_groups)
|
||||
params["do_remote_prefill"] = False
|
||||
return False, None
|
||||
|
||||
@@ -946,10 +1054,9 @@ class MoRIIOConnectorScheduler:
|
||||
):
|
||||
return False, None
|
||||
|
||||
# computed_block_ids = block_ids if all_full else block_ids[:-1]
|
||||
computed_block_ids = block_ids
|
||||
# If prompt < block_size, no xfer so free blocks immediately.
|
||||
delay_free_blocks = len(computed_block_ids) > 0
|
||||
# On producer
|
||||
computed_block_ids = self.get_exchange_clipped_blocks(block_ids)
|
||||
delay_free_blocks = any(len(group) > 0 for group in computed_block_ids)
|
||||
|
||||
if delay_free_blocks:
|
||||
# Prefill request on remote. It will be read from D upon completion
|
||||
@@ -1102,6 +1209,12 @@ class MoRIIOConnectorWorker:
|
||||
self.kv_transfer_config = vllm_config.kv_transfer_config
|
||||
self.is_producer = self.kv_transfer_config.is_kv_producer
|
||||
self.layer_to_spec = build_layer_to_spec(kv_cache_config)
|
||||
# we transfer by layer, but store by kv cache group
|
||||
self.layer_to_group: dict[str, int] = {
|
||||
layer_name: group_idx
|
||||
for group_idx, group in enumerate(kv_cache_config.kv_cache_groups)
|
||||
for layer_name in group.layer_names
|
||||
}
|
||||
|
||||
if self.is_producer:
|
||||
set_role(ROLE.PRODUCER)
|
||||
@@ -1789,8 +1902,6 @@ class MoRIIOConnectorWorker:
|
||||
self.block_size,
|
||||
)
|
||||
self.block_size = first_geometry.block_size
|
||||
# TODO(tms): self.block_len needs to be per-layer for sliding window,
|
||||
# hybrid attn, etc
|
||||
# block size in bytes
|
||||
self.block_len = first_geometry.block_len
|
||||
self.kv_cache_shape = first_kv_cache.shape
|
||||
@@ -1803,14 +1914,30 @@ class MoRIIOConnectorWorker:
|
||||
self.layer_base_addr_index = {}
|
||||
base_addr_idx = 0
|
||||
|
||||
hma_enabled = (
|
||||
not self.vllm_config.scheduler_config.disable_hybrid_kv_cache_manager
|
||||
)
|
||||
for layer_name in kv_caches:
|
||||
self.layer_base_addr_index[layer_name] = base_addr_idx
|
||||
geometry = self._get_layer_transfer_geometry(layer_name)
|
||||
if geometry.block_size != self.block_size:
|
||||
if hma_enabled:
|
||||
if geometry.block_len != self.block_len:
|
||||
raise ValueError(
|
||||
"MoRIIO KV cache block length mismatch for layer "
|
||||
f"{layer_name}: {geometry.block_len} != {self.block_len}"
|
||||
)
|
||||
elif geometry.block_size != self.block_size:
|
||||
raise ValueError(
|
||||
"MoRIIO KV cache block size mismatch for layer "
|
||||
f"{layer_name}: {geometry.block_size} != {self.block_size}"
|
||||
)
|
||||
# num_blocks is advertised as a single scalar to the peer, so must it
|
||||
# be uniform
|
||||
if geometry.num_blocks != self.num_blocks:
|
||||
raise ValueError(
|
||||
"MoRIIO KV cache num_blocks mismatch for layer "
|
||||
f"{layer_name}: {geometry.num_blocks} != {self.num_blocks}"
|
||||
)
|
||||
self.block_lens[layer_name] = geometry.block_len
|
||||
for cache, region_len in self._iter_layer_registration_regions(layer_name):
|
||||
base_addr = cache.data_ptr()
|
||||
@@ -2455,12 +2582,16 @@ class MoRIIOConnectorWorker:
|
||||
self.remote_dp_size_local = int(meta.remote_dp_size_local)
|
||||
else:
|
||||
self.remote_dp_size_local = int(meta.remote_dp_size)
|
||||
# WRITE does not support HMA, so unwrap blocks into flat lists.
|
||||
# remote_block_ids can itself be empty so need to be careful when unwrapping.
|
||||
local_block_ids = meta.local_block_ids[0]
|
||||
remote_block_ids = meta.remote_block_ids[0] if meta.remote_block_ids else []
|
||||
self.schedule_write_blocks(
|
||||
request_id=req_id,
|
||||
transfer_id=meta.transfer_id,
|
||||
dst_engine_id=meta.remote_engine_id,
|
||||
local_block_ids=meta.local_block_ids,
|
||||
remote_block_ids=meta.remote_block_ids,
|
||||
local_block_ids=local_block_ids,
|
||||
remote_block_ids=remote_block_ids,
|
||||
layer_name=layer_name,
|
||||
kv_layer=kv_layer,
|
||||
remote_notify_port=meta.remote_notify_port,
|
||||
@@ -2607,8 +2738,8 @@ class MoRIIOConnectorWorker:
|
||||
|
||||
def _read_blocks(
|
||||
self,
|
||||
local_block_ids: list[int],
|
||||
remote_block_ids: list[int],
|
||||
local_block_ids: BlockIds,
|
||||
remote_block_ids: BlockIds,
|
||||
dst_engine_id: str,
|
||||
request_id: str,
|
||||
transfer_id: str,
|
||||
@@ -2653,10 +2784,11 @@ class MoRIIOConnectorWorker:
|
||||
sess_idx = list(self.layer_name_to_local_kv_cache_metadata.keys()).index(
|
||||
layer_name
|
||||
)
|
||||
group_idx = self.layer_to_group[layer_name]
|
||||
offs = self._compute_block_transfer_offsets(
|
||||
layer_name,
|
||||
local_block_ids,
|
||||
remote_block_ids,
|
||||
local_block_ids[group_idx],
|
||||
remote_block_ids[group_idx],
|
||||
remote_moriio_meta,
|
||||
remote_tp_size=remote_tp_size,
|
||||
remote_engine_id=remote_dp_engine_id,
|
||||
|
||||
@@ -113,7 +113,7 @@ class NixlBaseConnectorScheduler:
|
||||
# New requests are added by update_state_after_alloc in
|
||||
# the scheduler. Used to make metadata passed to Worker.
|
||||
self._reqs_need_recv: dict[
|
||||
ReqId, tuple[Request, BlockIds, tuple[int, ...]]
|
||||
ReqId, tuple[Request, BlockIds, tuple[int, ...], bool]
|
||||
] = {}
|
||||
self._reqs_need_save: dict[ReqId, Request] = {}
|
||||
# Reqs to send and their expiration time
|
||||
@@ -199,8 +199,8 @@ class NixlBaseConnectorScheduler:
|
||||
def on_new_request(self, request: "Request") -> None:
|
||||
"""Track a request that may need heartbeats."""
|
||||
params = request.kv_transfer_params
|
||||
if params is not None and params.get("do_remote_decode") and self._has_mamba:
|
||||
self._truncate_mamba_request_for_prefill(request)
|
||||
if params is not None and params.get("do_remote_decode"):
|
||||
self._truncate_request_for_prefill(request)
|
||||
|
||||
# NOTE (NickLucche) This excludes request meant for P, ie heartbeats are
|
||||
# effectively disabled for Bidirectional KV transfer.
|
||||
@@ -382,36 +382,56 @@ class NixlBaseConnectorScheduler:
|
||||
(identity, b"", encoded_data[(target_pp_rank, target_tp_rank)], ts)
|
||||
)
|
||||
|
||||
def _prefill_backoff(self) -> int:
|
||||
"""Trailing prompt tokens the prefiller must not compute; the decoder
|
||||
recomputes them locally.
|
||||
|
||||
Mamba needs h(N-1) so the decoder can derive h(N) itself. Multi-module
|
||||
MTP needs to keep its whole lookahead window off of the prefiller, which
|
||||
would otherwise embed the unverified drafts in the MTP layer's KV cache. The
|
||||
decoder would never rebuild them, because the update is sized by the rejection
|
||||
count, which is zero for the first decode.
|
||||
"""
|
||||
return max(
|
||||
1 if self._has_mamba else 0,
|
||||
self.vllm_config.num_prefill_lookahead_tokens - 1,
|
||||
)
|
||||
|
||||
def _get_remote_prefill_token_count(self, num_prompt_tokens: int) -> int:
|
||||
"""D-side only. Returns N-1 for Mamba models since the decoder
|
||||
always recomputes the last token and must start from h(N-1)."""
|
||||
if self._has_mamba and num_prompt_tokens > 1:
|
||||
return num_prompt_tokens - 1
|
||||
"""D-side only. The number of prompt tokens to load from the prefiller.
|
||||
Stops short of the trailing ``_prefill_backoff()`` tokens that the decoder
|
||||
will recompute locally."""
|
||||
backoff = self._prefill_backoff()
|
||||
if backoff and num_prompt_tokens > backoff:
|
||||
return num_prompt_tokens - backoff
|
||||
return num_prompt_tokens
|
||||
|
||||
def _truncate_mamba_request_for_prefill(self, request: "Request") -> None:
|
||||
"""P-side only: drop the last prompt token so the prefiller computes
|
||||
h(N-1) instead of h(N). The decoder recomputes the last token to
|
||||
derive h(N) correctly.
|
||||
def _truncate_request_for_prefill(self, request: "Request") -> None:
|
||||
"""P-side only: drop the trailing ``_prefill_backoff()`` prompt tokens
|
||||
so the prefiller stops short of what the decoder recomputes locally.
|
||||
For Mamba that is the single token needed to yield h(N-1); for
|
||||
multi-module MTP it is the drafter's whole lookahead window.
|
||||
|
||||
Guarded by ``_p_side_truncated`` to avoid repeated truncation if the
|
||||
request is preempted and rescheduled."""
|
||||
backoff = self._prefill_backoff()
|
||||
params = request.kv_transfer_params
|
||||
if (
|
||||
params is not None
|
||||
backoff
|
||||
and params is not None
|
||||
# Guard against repeated truncation after preemption/reschedule.
|
||||
and not params.get("_p_side_truncated")
|
||||
and request.num_prompt_tokens > 1
|
||||
and request.num_prompt_tokens > backoff
|
||||
):
|
||||
if request.prompt_token_ids is not None:
|
||||
request.prompt_token_ids.pop()
|
||||
del request.prompt_token_ids[-backoff:]
|
||||
elif request.prompt_embeds is not None:
|
||||
request.prompt_embeds = request.prompt_embeds[:-1]
|
||||
request.prompt_embeds = request.prompt_embeds[:-backoff]
|
||||
else:
|
||||
return
|
||||
|
||||
request._all_token_ids.pop()
|
||||
request.num_prompt_tokens -= 1
|
||||
del request._all_token_ids[-backoff:]
|
||||
request.num_prompt_tokens -= backoff
|
||||
request.max_tokens = 1
|
||||
params["_p_side_truncated"] = True
|
||||
|
||||
@@ -459,13 +479,19 @@ class NixlBaseConnectorScheduler:
|
||||
meta = NixlConnectorMetadata()
|
||||
|
||||
# Loop through scheduled reqs and convert to ReqMeta.
|
||||
for req_id, (req, block_ids, cached) in self._reqs_need_recv.items():
|
||||
for req_id, (
|
||||
req,
|
||||
block_ids,
|
||||
cached,
|
||||
awaiting_kvs,
|
||||
) in self._reqs_need_recv.items():
|
||||
assert req.kv_transfer_params is not None
|
||||
meta.add_new_req_to_recv(
|
||||
request_id=req_id,
|
||||
local_block_ids=block_ids,
|
||||
kv_transfer_params=req.kv_transfer_params,
|
||||
local_num_computed_blocks=cached,
|
||||
awaiting_kvs=awaiting_kvs,
|
||||
)
|
||||
|
||||
if self.use_host_buffer:
|
||||
|
||||
@@ -164,6 +164,10 @@ class NixlBaseConnectorWorker:
|
||||
# Overridden by NixlPushConnectorWorker.
|
||||
_TRANSFER_MODE: str = "pull"
|
||||
|
||||
# Layer-name routing is supported only by NixlPushConnector for HMA KV
|
||||
# caches under PP.
|
||||
_supports_pp_hma = False
|
||||
|
||||
def _compute_desc_ids(
|
||||
self,
|
||||
block_ids: BlockIds,
|
||||
@@ -191,28 +195,42 @@ class NixlBaseConnectorWorker:
|
||||
num_blocks = dst_num_blocks
|
||||
if block_size_ratio is not None:
|
||||
num_blocks = int(num_blocks * block_size_ratio)
|
||||
num_regions = self.num_regions or len(self.block_len_per_layer)
|
||||
use_layer_name_routing = bool(self._transfer_layer_group_ids)
|
||||
num_desc_regions = (
|
||||
len(self._transfer_layer_group_ids)
|
||||
if use_layer_name_routing
|
||||
else self.num_regions or len(self.block_len_per_layer)
|
||||
)
|
||||
if region_num_blocks is None:
|
||||
region_num_blocks = [num_blocks] * num_regions
|
||||
region_num_blocks = [num_blocks] * num_desc_regions
|
||||
elif block_size_ratio is not None:
|
||||
region_num_blocks = [
|
||||
int(count * block_size_ratio) for count in region_num_blocks
|
||||
]
|
||||
if region_num_blocks:
|
||||
num_regions = len(region_num_blocks)
|
||||
assert len(region_num_blocks) == num_regions
|
||||
if region_num_blocks and not use_layer_name_routing:
|
||||
num_desc_regions = len(region_num_blocks)
|
||||
assert len(region_num_blocks) == num_desc_regions
|
||||
region_offsets = np.cumsum([0, *region_num_blocks[:-1]])
|
||||
num_fa_descs = sum(region_num_blocks)
|
||||
|
||||
if use_layer_name_routing:
|
||||
# Descriptors in layer order, using each layer's KV-cache group.
|
||||
return np.concatenate(
|
||||
[
|
||||
np.asarray(block_ids[g], dtype=np.int32) + region_offsets[k]
|
||||
for k, g in enumerate(self._transfer_layer_group_ids)
|
||||
]
|
||||
)
|
||||
|
||||
# All-attention fast path.
|
||||
if num_ssm_regions == 0:
|
||||
if region_group_ids is None:
|
||||
region_group_ids = self.region_group_ids
|
||||
if uses_region_group_mapping is None:
|
||||
uses_region_group_mapping = self._uses_region_group_mapping
|
||||
if not region_group_ids and num_regions == 1:
|
||||
if not region_group_ids and num_desc_regions == 1:
|
||||
region_group_ids = [0]
|
||||
assert len(region_group_ids) == num_regions
|
||||
assert len(region_group_ids) == num_desc_regions
|
||||
if uses_region_group_mapping is None:
|
||||
uses_region_group_mapping = len(set(region_group_ids)) > 1
|
||||
region_group_ids_array = np.asarray(region_group_ids, dtype=np.int32)
|
||||
@@ -392,6 +410,103 @@ class NixlBaseConnectorWorker:
|
||||
"""
|
||||
return region_idx < len(self._region_is_mla) and self._region_is_mla[region_idx]
|
||||
|
||||
def _set_region_layers(self, region_layers: list[list[str]]) -> None:
|
||||
layer_names = [layer_name for region in region_layers for layer_name in region]
|
||||
assert len(layer_names) == len(set(layer_names)), (
|
||||
"A KV cache layer spans multiple NIXL regions"
|
||||
)
|
||||
self.region_members: list[list[str]] = region_layers
|
||||
if not self._requires_layer_name_routing():
|
||||
return
|
||||
group_by_layer = self.kv_cache_config.transfer_group_index_by_layer
|
||||
ungrouped = [name for name in layer_names if name not in group_by_layer]
|
||||
assert not ungrouped, f"KV cache layers outside any local group: {ungrouped}"
|
||||
self._transfer_layer_names = tuple(layer_names)
|
||||
self._transfer_layer_region_indices = tuple(
|
||||
region_idx
|
||||
for region_idx, region in enumerate(region_layers)
|
||||
for _ in region
|
||||
)
|
||||
self._transfer_layer_group_ids = tuple(
|
||||
group_by_layer[name] for name in layer_names
|
||||
)
|
||||
|
||||
def _requires_layer_name_routing(self) -> bool:
|
||||
"""Whether PP push must match HMA layers by name, not region index."""
|
||||
return (
|
||||
self._supports_pp_hma
|
||||
and self.pp_size > 1
|
||||
and self._is_hma_required
|
||||
and not self._has_mamba
|
||||
)
|
||||
|
||||
def _align_remote_regions_by_layer(
|
||||
self, nixl_agent_meta: NixlAgentMetadata
|
||||
) -> None:
|
||||
"""Select remote regions for this PP stage in local layer order."""
|
||||
remote_region_layers = nixl_agent_meta.region_members
|
||||
# Region-index routing here would silently transfer stale KV.
|
||||
assert remote_region_layers, "Remote advertised no region_members"
|
||||
assert (
|
||||
len(nixl_agent_meta.kv_caches_base_addr)
|
||||
== len(nixl_agent_meta.block_lens)
|
||||
== len(nixl_agent_meta.block_strides)
|
||||
== len(remote_region_layers)
|
||||
), "Remote region metadata lengths disagree"
|
||||
assert all(
|
||||
values is None or len(values) == len(remote_region_layers)
|
||||
for values in (
|
||||
nixl_agent_meta.region_num_blocks,
|
||||
nixl_agent_meta.region_group_ids,
|
||||
nixl_agent_meta.region_names,
|
||||
nixl_agent_meta.region_mem_types,
|
||||
)
|
||||
), "Remote region metadata lengths disagree"
|
||||
|
||||
remote_region_by_layer: dict[str, int] = {}
|
||||
for region_idx, layer_names in enumerate(remote_region_layers):
|
||||
for layer_name in layer_names:
|
||||
assert layer_name not in remote_region_by_layer, (
|
||||
f"Remote advertised layer {layer_name!r} in multiple regions"
|
||||
)
|
||||
remote_region_by_layer[layer_name] = region_idx
|
||||
|
||||
missing = [
|
||||
name
|
||||
for name in self._transfer_layer_names
|
||||
if name not in remote_region_by_layer
|
||||
]
|
||||
assert not missing, f"Remote is missing locally owned layers: {missing}"
|
||||
|
||||
remote_regions = [
|
||||
remote_region_by_layer[name] for name in self._transfer_layer_names
|
||||
]
|
||||
nixl_agent_meta.kv_caches_base_addr = [
|
||||
nixl_agent_meta.kv_caches_base_addr[i] for i in remote_regions
|
||||
]
|
||||
nixl_agent_meta.block_lens = [
|
||||
nixl_agent_meta.block_lens[i] for i in remote_regions
|
||||
]
|
||||
nixl_agent_meta.block_strides = [
|
||||
nixl_agent_meta.block_strides[i] for i in remote_regions
|
||||
]
|
||||
if nixl_agent_meta.region_num_blocks is not None:
|
||||
nixl_agent_meta.region_num_blocks = [
|
||||
nixl_agent_meta.region_num_blocks[i] for i in remote_regions
|
||||
]
|
||||
if nixl_agent_meta.region_group_ids is not None:
|
||||
nixl_agent_meta.region_group_ids = [
|
||||
nixl_agent_meta.region_group_ids[i] for i in remote_regions
|
||||
]
|
||||
if nixl_agent_meta.region_mem_types is not None:
|
||||
nixl_agent_meta.region_mem_types = [
|
||||
nixl_agent_meta.region_mem_types[i] for i in remote_regions
|
||||
]
|
||||
if nixl_agent_meta.region_names is not None:
|
||||
nixl_agent_meta.region_names = list(self._transfer_layer_names)
|
||||
# One layer per region keeps a second alignment pass a no-op.
|
||||
nixl_agent_meta.region_members = [[name] for name in self._transfer_layer_names]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: "VllmConfig",
|
||||
@@ -638,18 +753,26 @@ class NixlBaseConnectorWorker:
|
||||
# transfers into the matching sub-range of a PP=1 remote's regions.
|
||||
self.pp_size = vllm_config.parallel_config.pipeline_parallel_size
|
||||
self._remote_region_offset = 0
|
||||
# PP push slices regions per layer (uniform count); HMA breaks that.
|
||||
if self.pp_size > 1 and self._is_hma_required:
|
||||
raise NotImplementedError(
|
||||
"NixlPushConnector does not support pipeline_parallel_size > 1 "
|
||||
"with hybrid KV cache layouts (HMA) yet."
|
||||
)
|
||||
# Decode-side PP is unsupported (completions counted per consumer rank).
|
||||
if vllm_config.kv_transfer_config.kv_role == "kv_consumer" and self.pp_size > 1:
|
||||
raise NotImplementedError(
|
||||
"NixlPushConnector consumer (decode) does not support "
|
||||
"pipeline_parallel_size > 1."
|
||||
)
|
||||
if self.pp_size > 1:
|
||||
if self._is_hma_required and not self._supports_pp_hma:
|
||||
raise NotImplementedError(
|
||||
"NixlConnector (pull) does not support pipeline_parallel_size "
|
||||
"> 1 with hybrid KV cache layouts (HMA); use NixlPushConnector "
|
||||
"for PP + HMA."
|
||||
)
|
||||
# PP push routes HMA (hybrid) attention layouts by layer name;
|
||||
# Mamba/SSM hybrids are not yet supported under PP.
|
||||
if self._has_mamba:
|
||||
raise NotImplementedError(
|
||||
"NixlPushConnector does not support pipeline_parallel_size > 1 "
|
||||
"with Mamba/SSM hybrid KV cache layouts yet."
|
||||
)
|
||||
# Decode-side PP is unsupported (completions counted per consumer rank).
|
||||
if vllm_config.kv_transfer_config.kv_role == "kv_consumer":
|
||||
raise NotImplementedError(
|
||||
"NixlPushConnector consumer (decode) does not support "
|
||||
"pipeline_parallel_size > 1."
|
||||
)
|
||||
# Keep heartbeat handshakes to a PP-sharded producer notif-only.
|
||||
self._hb_handshake_notif_only = False
|
||||
|
||||
@@ -692,7 +815,7 @@ class NixlBaseConnectorWorker:
|
||||
# Uses Queue for thread-safe cross-thread coordination with the
|
||||
# background handshake thread, matching the _ready_requests pattern.
|
||||
self._failed_recv_reqs: queue.Queue[ReqId] = queue.Queue()
|
||||
self._failed_inflight_recvs: set[ReqId] = set()
|
||||
self._recv_failures: set[ReqId] = set()
|
||||
self._pending_recv_notifs: dict[ReqId, list[tuple[str, bytes]]] = {}
|
||||
|
||||
# Handshake metadata of this worker for NIXL transfers.
|
||||
@@ -773,6 +896,13 @@ class NixlBaseConnectorWorker:
|
||||
# within a block (BLHNC/BHLNC), where stride > block_len.
|
||||
self.block_stride_per_layer = list[int]()
|
||||
|
||||
# Region layer membership is populated for HMA layouts.
|
||||
self.region_members = []
|
||||
# Local layer order, set by ``_set_region_layers`` only when
|
||||
# routing by layer name. Empty means region-index routing.
|
||||
self._transfer_layer_names = tuple[str, ...]()
|
||||
self._transfer_layer_region_indices = tuple[int, ...]()
|
||||
self._transfer_layer_group_ids = tuple[int, ...]()
|
||||
# Per-engine TP mappings. Generated during handshake.
|
||||
self.tp_mappings: dict[EngineId, TPMapping] = {}
|
||||
|
||||
@@ -1212,7 +1342,7 @@ class NixlBaseConnectorWorker:
|
||||
error=e,
|
||||
meta=meta,
|
||||
)
|
||||
self._handle_failed_transfer(req_id, None)
|
||||
self._failed_recv_reqs.put(req_id)
|
||||
|
||||
fut.add_done_callback(request_ready)
|
||||
|
||||
@@ -1306,6 +1436,11 @@ class NixlBaseConnectorWorker:
|
||||
):
|
||||
compressed_region_owners.setdefault(cache.data_ptr(), cache)
|
||||
|
||||
track_region_layers = (
|
||||
self._supports_pp_hma and self._is_hma_required and not self._has_mamba
|
||||
)
|
||||
region_layers: list[list[str]] = []
|
||||
|
||||
# K and V are packed into the content dim, so each attention layer is a
|
||||
# single NIXL region whose block transfers as one unit. Mamba layers instead
|
||||
# register separate conv/ssm sub-regions (see `_build_mamba_local`).
|
||||
@@ -1508,6 +1643,12 @@ class NixlBaseConnectorWorker:
|
||||
self._region_is_mla.append(is_mla_region)
|
||||
region_mem_types.append(mem_type)
|
||||
|
||||
if track_region_layers:
|
||||
if region_index == len(region_layers):
|
||||
region_layers.append([layer_name])
|
||||
else:
|
||||
region_layers[region_index].append(layer_name)
|
||||
|
||||
if isinstance(layer_spec, MambaSpec):
|
||||
if layer_spec.tp_replicated:
|
||||
assert self._is_csa_linear
|
||||
@@ -1563,7 +1704,9 @@ class NixlBaseConnectorWorker:
|
||||
if self._has_mamba:
|
||||
self.region_num_blocks = [self.num_blocks] * self.num_regions
|
||||
|
||||
if self.pp_size > 1:
|
||||
self._set_region_layers(region_layers)
|
||||
|
||||
if self.pp_size > 1 and not self._is_hma_required:
|
||||
start_layer, end_layer = self.model_config.get_layers_start_end_indices(
|
||||
self.vllm_config.parallel_config
|
||||
)
|
||||
@@ -1573,7 +1716,12 @@ class NixlBaseConnectorWorker:
|
||||
self._remote_region_offset = regions_per_layer * start_layer
|
||||
|
||||
# Total local FA descriptors (boundary between FA and mamba descs).
|
||||
self.num_descs = sum(self.region_num_blocks)
|
||||
xfer_region_num_blocks = (
|
||||
[self.region_num_blocks[i] for i in self._transfer_layer_region_indices]
|
||||
if self._transfer_layer_region_indices
|
||||
else self.region_num_blocks
|
||||
)
|
||||
self.num_descs = sum(xfer_region_num_blocks)
|
||||
|
||||
self._mixed_mem_types = len(set(region_mem_types)) > 1
|
||||
if self._mixed_mem_types:
|
||||
@@ -1597,7 +1745,7 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
self.device_kv_caches = kv_caches
|
||||
self.dst_num_blocks[self.engine_id] = self.num_blocks
|
||||
self.dst_region_num_blocks[self.engine_id] = self.region_num_blocks
|
||||
self.dst_region_num_blocks[self.engine_id] = xfer_region_num_blocks
|
||||
self.dst_region_group_ids[self.engine_id] = self.region_group_ids
|
||||
self.dst_uses_region_group_mapping[self.engine_id] = (
|
||||
self._uses_region_group_mapping
|
||||
@@ -1647,6 +1795,7 @@ class NixlBaseConnectorWorker:
|
||||
region_mem_types=self.region_mem_types,
|
||||
dcp_size=self.dcp_size,
|
||||
pcp_size=self.pcp_size,
|
||||
region_members=self.region_members,
|
||||
)
|
||||
# Wrap metadata in payload with hash for defensive decoding
|
||||
assert self.compat_hash is not None
|
||||
@@ -1805,12 +1954,16 @@ class NixlBaseConnectorWorker:
|
||||
base_addresses: list[int],
|
||||
block_size_ratio: int,
|
||||
) -> np.ndarray:
|
||||
"""Build local FA descriptors for all layers as an Nx3 uint64 array."""
|
||||
"""Build local FA descriptors as an Nx3 uint64 array."""
|
||||
assert self.transfer_topo is not None
|
||||
assert base_addresses, "Local KV cache base addresses must not be empty."
|
||||
device_id = self.device_id
|
||||
region_indices = self._transfer_layer_region_indices or range(
|
||||
len(base_addresses)
|
||||
)
|
||||
parts: list[np.ndarray] = []
|
||||
for i, base_addr in enumerate(base_addresses):
|
||||
for i in region_indices:
|
||||
base_addr = base_addresses[i]
|
||||
block_len = self.block_len_per_layer[i] // block_size_ratio
|
||||
logical_blocks = np.repeat(
|
||||
np.arange(self.region_num_blocks[i], dtype=np.uint64),
|
||||
@@ -1834,7 +1987,7 @@ class NixlBaseConnectorWorker:
|
||||
nixl_agent_meta: NixlAgentMetadata,
|
||||
block_size_ratio: int,
|
||||
) -> np.ndarray:
|
||||
"""Build remote FA descriptors for all layers as an Nx3 uint64 array."""
|
||||
"""Build remote FA descriptors as an Nx3 uint64 array."""
|
||||
assert self.transfer_topo is not None
|
||||
assert nixl_agent_meta.kv_caches_base_addr, (
|
||||
"Remote KV cache base addresses must not be empty."
|
||||
@@ -1851,10 +2004,14 @@ class NixlBaseConnectorWorker:
|
||||
device_id = nixl_agent_meta.device_id
|
||||
block_strides = nixl_agent_meta.block_strides
|
||||
parts: list[np.ndarray] = []
|
||||
use_layer_name_routing = bool(self._transfer_layer_region_indices)
|
||||
for i, base_addr in enumerate(nixl_agent_meta.kv_caches_base_addr):
|
||||
replicated = self._is_region_replicated(i)
|
||||
local_region = (
|
||||
self._transfer_layer_region_indices[i] if use_layer_name_routing else i
|
||||
)
|
||||
replicated = self._is_region_replicated(local_region)
|
||||
# Read our whole local region size from remote..
|
||||
local_block_len = self.block_len_per_layer[i]
|
||||
local_block_len = self.block_len_per_layer[local_region]
|
||||
remote_kv_block_len = local_block_len // block_size_ratio
|
||||
if block_size_ratio > 1:
|
||||
# ..using remote kv_block_len as transfer unit
|
||||
@@ -2021,9 +2178,22 @@ class NixlBaseConnectorWorker:
|
||||
)
|
||||
return self._remote_agents[engine_id][(0, remote_tp_rank)]
|
||||
|
||||
assert self.transfer_topo is not None
|
||||
transfer_topo = self.transfer_topo
|
||||
# Number of physical regions registered locally (one per layer/tensor).
|
||||
num_local_regions = len(self.block_len_per_layer)
|
||||
if (
|
||||
if self._transfer_layer_region_indices:
|
||||
if self.block_size != nixl_agent_meta.block_size:
|
||||
raise NotImplementedError(
|
||||
"Attention-HMA push requires identical P/D block sizes."
|
||||
)
|
||||
if remote_tp_size > transfer_topo.tp_size and not self.use_mla:
|
||||
raise NotImplementedError(
|
||||
"Attention-HMA push does not support decode TP greater than "
|
||||
"prefill TP yet"
|
||||
)
|
||||
self._align_remote_regions_by_layer(nixl_agent_meta)
|
||||
elif (
|
||||
self.pp_size > 1
|
||||
and len(nixl_agent_meta.kv_caches_base_addr) > num_local_regions
|
||||
):
|
||||
@@ -2038,6 +2208,10 @@ class NixlBaseConnectorWorker:
|
||||
]
|
||||
nixl_agent_meta.block_lens = nixl_agent_meta.block_lens[start:end]
|
||||
nixl_agent_meta.block_strides = nixl_agent_meta.block_strides[start:end]
|
||||
if nixl_agent_meta.region_num_blocks is not None:
|
||||
nixl_agent_meta.region_num_blocks = nixl_agent_meta.region_num_blocks[
|
||||
start:end
|
||||
]
|
||||
if nixl_agent_meta.region_group_ids is not None:
|
||||
nixl_agent_meta.region_group_ids = nixl_agent_meta.region_group_ids[
|
||||
start:end
|
||||
@@ -2048,14 +2222,8 @@ class NixlBaseConnectorWorker:
|
||||
nixl_agent_meta.region_mem_types = nixl_agent_meta.region_mem_types[
|
||||
start:end
|
||||
]
|
||||
if nixl_agent_meta.region_num_blocks is not None:
|
||||
nixl_agent_meta.region_num_blocks = nixl_agent_meta.region_num_blocks[
|
||||
start:end
|
||||
]
|
||||
|
||||
### Register remote engine in TransferTopology (idempotent).
|
||||
assert self.transfer_topo is not None
|
||||
transfer_topo = self.transfer_topo
|
||||
physical_blocks_per_logical = (
|
||||
nixl_agent_meta.physical_blocks_per_logical_kv_block
|
||||
)
|
||||
@@ -2349,6 +2517,9 @@ class NixlBaseConnectorWorker:
|
||||
# the per-rank KV head ratio rather than the raw tp_ratio, because GQA
|
||||
# replication caps per-rank heads at 1 when tp > total_kv_heads
|
||||
# (issue #45330). Mamba uses the ssm_sizes counterpart, so skip here.
|
||||
local_regions = self._transfer_layer_region_indices or range(
|
||||
len(self.block_len_per_layer)
|
||||
)
|
||||
if self._has_mamba and self.use_mla:
|
||||
# Hybrid MLA+SSM (e.g. KimiLinear's KDA+MLA): regions are
|
||||
# kernel-granularity views of the mamba-unified page. The MLA
|
||||
@@ -2365,7 +2536,7 @@ class NixlBaseConnectorWorker:
|
||||
f"remote={nixl_agent_meta.block_lens}."
|
||||
)
|
||||
elif not self._has_mamba:
|
||||
assert len(self.block_len_per_layer) == len(nixl_agent_meta.block_lens), (
|
||||
assert len(local_regions) == len(nixl_agent_meta.block_lens), (
|
||||
"Number of KV layers must match between prefill and decode"
|
||||
)
|
||||
model_replicated = self.use_mla or self.transfer_topo.is_kv_replicated(
|
||||
@@ -2374,8 +2545,9 @@ class NixlBaseConnectorWorker:
|
||||
total_kv_heads = self.transfer_topo.total_num_kv_heads
|
||||
local_heads = self.transfer_topo.local_physical_heads
|
||||
remote_heads = max(1, total_kv_heads // remote_tp_size)
|
||||
for i, local_len in enumerate(self.block_len_per_layer):
|
||||
replicated = model_replicated or self._is_region_replicated(i)
|
||||
for i, region_idx in enumerate(local_regions):
|
||||
local_len = self.block_len_per_layer[region_idx]
|
||||
replicated = model_replicated or self._is_region_replicated(region_idx)
|
||||
remote_len = nixl_agent_meta.block_lens[i]
|
||||
if replicated:
|
||||
assert local_len // block_size_ratio == remote_len, (
|
||||
@@ -2406,8 +2578,7 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
# TP workers that handhshake with same remote have same #blocks.
|
||||
assert self.dst_num_blocks[remote_engine_id] == nixl_agent_meta.num_blocks
|
||||
# Same number of regions/~layers.
|
||||
assert len(nixl_agent_meta.kv_caches_base_addr) == len(self.block_len_per_layer)
|
||||
assert len(nixl_agent_meta.kv_caches_base_addr) == len(local_regions)
|
||||
num_remote_regions = len(nixl_agent_meta.kv_caches_base_addr)
|
||||
if nixl_agent_meta.region_num_blocks is not None:
|
||||
assert len(nixl_agent_meta.region_num_blocks) == num_remote_regions
|
||||
@@ -2423,7 +2594,12 @@ class NixlBaseConnectorWorker:
|
||||
if nixl_agent_meta.region_group_ids is not None:
|
||||
assert len(nixl_agent_meta.region_group_ids) == num_remote_regions
|
||||
if nixl_agent_meta.region_names is not None:
|
||||
assert nixl_agent_meta.region_names == self.region_names, (
|
||||
expected_names = (
|
||||
list(self._transfer_layer_names)
|
||||
if self._transfer_layer_names
|
||||
else self.region_names
|
||||
)
|
||||
assert nixl_agent_meta.region_names == expected_names, (
|
||||
"NIXL transfer regions must name the same model caches in the "
|
||||
"same order"
|
||||
)
|
||||
@@ -2618,22 +2794,32 @@ class NixlBaseConnectorWorker:
|
||||
"""
|
||||
assert self.transfer_topo is not None
|
||||
done_sending = self._get_new_notifs()
|
||||
done_recving = self._pop_done_transfers(self._recving_transfers)
|
||||
done_recving, newly_failed = self._pop_done_transfers(self._recving_transfers)
|
||||
if newly_failed:
|
||||
self._recv_failures.update(newly_failed)
|
||||
|
||||
done_sending.update(self._replicated_pcp_done_sending)
|
||||
self._replicated_pcp_done_sending.clear()
|
||||
|
||||
# Drain queue of requests where handshake or transfer setup failed.
|
||||
failed_recv_reqs = set[ReqId]()
|
||||
# Process receive failures reported by background threads.
|
||||
while not self._failed_recv_reqs.empty():
|
||||
try:
|
||||
failed_recv_reqs.add(self._failed_recv_reqs.get_nowait())
|
||||
req_id = self._failed_recv_reqs.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
self._handle_failed_transfer(req_id, None, self._recv_failures)
|
||||
|
||||
failed_recv_reqs: set[ReqId] = set()
|
||||
if self._recv_failures:
|
||||
# Keep failure bookkeeping independent of healthy request count.
|
||||
for req_id in tuple(self._recv_failures):
|
||||
if req_id not in self._recving_metadata:
|
||||
self._recv_failures.remove(req_id)
|
||||
elif req_id not in self._recving_transfers:
|
||||
self._recv_failures.remove(req_id)
|
||||
failed_recv_reqs.add(req_id)
|
||||
done_recving.update(failed_recv_reqs)
|
||||
|
||||
# Add failed requests to done_recving for scheduler tracking
|
||||
# (blocks are already marked invalid, scheduler will handle recompute)
|
||||
done_recving.update(failed_recv_reqs)
|
||||
if len(done_sending) > 0 or len(done_recving) > 0:
|
||||
logger.debug(
|
||||
"Rank %s, get_finished: %s requests done sending "
|
||||
@@ -2654,12 +2840,17 @@ class NixlBaseConnectorWorker:
|
||||
|
||||
# Skip KV sync and post-processing for failed requests
|
||||
if req_id in failed_recv_reqs:
|
||||
self._pending_recv_notifs.pop(req_id, None)
|
||||
# TODO (NickLucche) handle failed transfer for HMA.
|
||||
if not self._is_hma_required:
|
||||
self._invalid_block_ids.put(set(meta.local_block_ids[0]))
|
||||
logger.warning(
|
||||
"Skipping KV post-processing for failed request %s",
|
||||
req_id,
|
||||
)
|
||||
continue
|
||||
|
||||
self._send_pending_recv_notifs(req_id)
|
||||
assert meta.remote is not None
|
||||
if self.use_host_buffer:
|
||||
self.sync_recved_kv_to_device(req_id, meta)
|
||||
@@ -2783,22 +2974,26 @@ class NixlBaseConnectorWorker:
|
||||
new_expiry,
|
||||
)
|
||||
|
||||
def _pop_done_transfers(self, transfers: dict[str, list[int]]) -> set[str]:
|
||||
"""
|
||||
Pop completed xfers by checking for DONE state.
|
||||
def _pop_done_transfers(
|
||||
self, transfers: dict[str, list[int]]
|
||||
) -> tuple[set[str], set[str]]:
|
||||
"""Poll transfers, retaining handles until they can be released.
|
||||
|
||||
Args:
|
||||
transfers: dict of req_id -> list[running_xfer]
|
||||
transfers: Outstanding handles by request, updated in place.
|
||||
|
||||
Returns:
|
||||
set of req_ids that have all done xfers
|
||||
Requests with no outstanding handles and requests with observed
|
||||
failures. Failed requests may still have outstanding handles.
|
||||
"""
|
||||
done_req_ids: set[str] = set()
|
||||
failed_req_ids: set[str] = set()
|
||||
for req_id, handles in list(transfers.items()):
|
||||
in_progress = []
|
||||
for handle in handles:
|
||||
try:
|
||||
xfer_state = self.nixl_wrapper.check_xfer_state(handle)
|
||||
if xfer_state == "DONE":
|
||||
# Get telemetry from NIXL
|
||||
res = self.nixl_wrapper.get_xfer_telemetry(handle)
|
||||
self.xfer_stats.record_transfer(res)
|
||||
self.nixl_wrapper.release_xfer_handle(handle)
|
||||
@@ -2807,58 +3002,52 @@ class NixlBaseConnectorWorker:
|
||||
else:
|
||||
self._log_failure(
|
||||
failure_type="transfer_failed",
|
||||
msg="Deferring request completion until its last "
|
||||
"xfer is terminal",
|
||||
req_id=req_id,
|
||||
xfer_state=xfer_state,
|
||||
)
|
||||
self._handle_failed_transfer(req_id, handle)
|
||||
if not self._handle_failed_transfer(
|
||||
req_id, handle, failed_req_ids
|
||||
):
|
||||
in_progress.append(handle)
|
||||
except Exception as e:
|
||||
self._log_failure(
|
||||
failure_type="transfer_exception",
|
||||
msg="Handle is unpollable; treating it as terminal",
|
||||
req_id=req_id,
|
||||
error=e,
|
||||
)
|
||||
self._handle_failed_transfer(req_id, handle)
|
||||
if not self._handle_failed_transfer(req_id, handle, failed_req_ids):
|
||||
in_progress.append(handle)
|
||||
|
||||
if not in_progress:
|
||||
del transfers[req_id]
|
||||
done_req_ids.add(req_id)
|
||||
if req_id in self._failed_inflight_recvs:
|
||||
self._failed_inflight_recvs.remove(req_id)
|
||||
self._report_failed_recv(req_id)
|
||||
else:
|
||||
self._send_pending_recv_notifs(req_id)
|
||||
del transfers[req_id]
|
||||
else:
|
||||
transfers[req_id] = in_progress
|
||||
return done_req_ids
|
||||
return done_req_ids, failed_req_ids
|
||||
|
||||
def _handle_failed_transfer(self, req_id: str, handle: int | None):
|
||||
"""
|
||||
Handle a failed transfer by marking all (logical) blocks as invalid and
|
||||
recording the failure.
|
||||
|
||||
Args:
|
||||
req_id: The request ID.
|
||||
handle: The transfer handle.
|
||||
"""
|
||||
# A sibling READ may still be writing these blocks. Retain metadata
|
||||
# and defer invalidation until every handle is terminal.
|
||||
self._pending_recv_notifs.pop(req_id, None)
|
||||
if req_id in self._recving_transfers:
|
||||
self._failed_inflight_recvs.add(req_id)
|
||||
else:
|
||||
self._report_failed_recv(req_id)
|
||||
if handle is not None:
|
||||
def _try_release_xfer_handle(self, req_id: str, handle: int) -> bool:
|
||||
"""Release a handle, returning False if the caller must retain it."""
|
||||
try:
|
||||
self.nixl_wrapper.release_xfer_handle(handle)
|
||||
self.xfer_stats.record_failed_transfer()
|
||||
except Exception as e:
|
||||
# A status error does not guarantee that the backend stopped DMA.
|
||||
self._log_failure(
|
||||
failure_type="transfer_release_failed",
|
||||
msg="Retaining handle and blocks until release succeeds",
|
||||
req_id=req_id,
|
||||
error=e,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
def _report_failed_recv(self, req_id: str) -> None:
|
||||
if (meta := self._recving_metadata.get(req_id)) is not None:
|
||||
if not self._is_hma_required:
|
||||
self._invalid_block_ids.put(set(meta.local_block_ids[0]))
|
||||
self._failed_recv_reqs.put(req_id)
|
||||
def _handle_failed_transfer(
|
||||
self, req_id: str, handle: int | None, failed_req_ids: set[str] | None = None
|
||||
) -> bool:
|
||||
"""Record a failure and release its handle, returning False to retain it."""
|
||||
self.xfer_stats.record_failed_transfer()
|
||||
if failed_req_ids is not None:
|
||||
failed_req_ids.add(req_id)
|
||||
return handle is None or self._try_release_xfer_handle(req_id, handle)
|
||||
|
||||
def _send_pending_recv_notifs(self, req_id: str) -> None:
|
||||
"""Send notifications deferred by split DRAM/VRAM reads."""
|
||||
@@ -3264,7 +3453,10 @@ class NixlBaseConnectorWorker:
|
||||
# Notif-only engines (push-mode D side) have no descriptor state.
|
||||
for handle in self.dst_xfer_side_handles.pop(engine_id, {}).values():
|
||||
self.nixl_wrapper.release_dlist_handle(handle)
|
||||
for agent_name in self._remote_agents.pop(engine_id).values():
|
||||
# Pop under the handshake lock; NIXL teardown stays outside it.
|
||||
with self._handshake_lock:
|
||||
agents = self._remote_agents.pop(engine_id)
|
||||
for agent_name in agents.values():
|
||||
self.nixl_wrapper.remove_remote_agent(agent_name)
|
||||
|
||||
self.kv_caches_base_addr.pop(engine_id, None)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Metadata dataclasses and helpers for the NIXL connector."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
@@ -47,8 +47,9 @@ PUSH_REG_NOTIF_PREFIX = b"PUSH_REG:"
|
||||
# 9: Add block_strides
|
||||
# 10: Add dense virtual transfer pages for compressed MLA caches
|
||||
# 11: Add per-region transfer geometry and memory types to NixlAgentMetadata
|
||||
# 12: Add per-region member names for PP push
|
||||
#
|
||||
NIXL_CONNECTOR_VERSION: int = 11
|
||||
NIXL_CONNECTOR_VERSION: int = 12
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -71,6 +72,8 @@ class NixlAgentMetadata:
|
||||
region_mem_types: list[str] | None = None
|
||||
dcp_size: int = 1
|
||||
pcp_size: int = 1
|
||||
# Layer names sharing each advertised region, in region order.
|
||||
region_members: list[list[str]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -246,6 +249,9 @@ class ReqMeta:
|
||||
remote_block_size: int | None = None
|
||||
# Remote producer pipeline-parallel size (push mode, D side).
|
||||
pp_size: int = 1
|
||||
# True only when the scheduler parked the request in WAITING_FOR_REMOTE_KVS
|
||||
# and expects it in finished_recving; notify-only recvs must not be reported.
|
||||
awaiting_kvs: bool = False
|
||||
|
||||
|
||||
class NixlConnectorMetadata(KVConnectorMetadata):
|
||||
@@ -275,6 +281,7 @@ class NixlConnectorMetadata(KVConnectorMetadata):
|
||||
local_block_ids: BlockIds,
|
||||
kv_transfer_params: dict[str, Any],
|
||||
local_num_computed_blocks: tuple[int, ...] = (),
|
||||
awaiting_kvs: bool = False,
|
||||
) -> ReqMeta:
|
||||
return ReqMeta(
|
||||
local_block_ids=local_block_ids,
|
||||
@@ -285,6 +292,7 @@ class NixlConnectorMetadata(KVConnectorMetadata):
|
||||
remote_block_size=kv_transfer_params.get("remote_block_size"),
|
||||
pp_size=kv_transfer_params.get("pp_size", 1),
|
||||
local_num_computed_blocks=local_num_computed_blocks,
|
||||
awaiting_kvs=awaiting_kvs,
|
||||
)
|
||||
|
||||
def add_new_req_to_save(
|
||||
@@ -303,11 +311,13 @@ class NixlConnectorMetadata(KVConnectorMetadata):
|
||||
local_block_ids: BlockIds,
|
||||
kv_transfer_params: dict[str, Any],
|
||||
local_num_computed_blocks: tuple[int, ...] = (),
|
||||
awaiting_kvs: bool = False,
|
||||
):
|
||||
req = self._add_new_req(
|
||||
local_block_ids,
|
||||
kv_transfer_params,
|
||||
local_num_computed_blocks,
|
||||
awaiting_kvs,
|
||||
)
|
||||
req.remote = RemoteMeta(
|
||||
block_ids=kv_transfer_params["remote_block_ids"],
|
||||
|
||||
@@ -172,6 +172,9 @@ class NixlPullConnectorScheduler(NixlBaseConnectorScheduler):
|
||||
request,
|
||||
local_block_ids,
|
||||
local_num_computed_blocks,
|
||||
# Parked in WAITING_FOR_REMOTE_KVS only when there is
|
||||
# something to pull; a full local hit stays RUNNING.
|
||||
num_external_tokens > 0,
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -224,7 +227,7 @@ class NixlPullConnectorScheduler(NixlBaseConnectorScheduler):
|
||||
# To avoid stranding the prefill blocks in the prefill instance,
|
||||
# we must add empty block_ids to _reqs_need_recv so that our
|
||||
# worker side will notify and free blocks in the prefill instance.
|
||||
self._reqs_need_recv[request.request_id] = (request, [], ())
|
||||
self._reqs_need_recv[request.request_id] = (request, [], (), False)
|
||||
params["do_remote_prefill"] = False
|
||||
return False, None
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
engine_id,
|
||||
)
|
||||
self.xfer_stats.record_kv_expired_req()
|
||||
self._handle_failed_transfer(req_id, None)
|
||||
self._handle_failed_transfer(req_id, None, self._recv_failures)
|
||||
return
|
||||
|
||||
if any(len(group) > 0 for group in meta.local_block_ids):
|
||||
@@ -303,6 +303,7 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
local_dram_handle=local_dram_handle,
|
||||
remote_xfer_side_handle=remote_xfer_side_handle,
|
||||
expected_consumers=plan.local_consumers,
|
||||
awaiting_kvs=meta.awaiting_kvs,
|
||||
):
|
||||
return
|
||||
|
||||
@@ -327,6 +328,7 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
local_dram_handle: int | None,
|
||||
remote_xfer_side_handle: int,
|
||||
expected_consumers: int,
|
||||
awaiting_kvs: bool,
|
||||
) -> bool:
|
||||
"""
|
||||
Post a READ point-to-point xfer request from a single local worker to
|
||||
@@ -387,6 +389,11 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
remote_agent_name=agent_name,
|
||||
)
|
||||
self.xfer_stats.record_failed_notification()
|
||||
# Report even on notification failure: the KV is already local, and
|
||||
# an unreported parked request would hold its blocks forever.
|
||||
# Notify-only recvs must stay unreported (scheduler asserts).
|
||||
if awaiting_kvs:
|
||||
self._recving_transfers.setdefault(request_id, [])
|
||||
return True
|
||||
|
||||
if read_spec.block_ids_by_region:
|
||||
@@ -486,16 +493,19 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
self._recving_transfers[request_id].append(handle)
|
||||
return True
|
||||
except Exception as e:
|
||||
# mark all (logical) blocks for this request as invalid
|
||||
self._log_failure(
|
||||
failure_type="transfer_setup_failed",
|
||||
req_id=request_id,
|
||||
msg="Marking blocks as invalid",
|
||||
msg="Deferring failure reporting until outstanding transfers finish",
|
||||
error=e,
|
||||
dst_engine_id=dst_engine_id,
|
||||
remote_rank=remote_rank,
|
||||
)
|
||||
self._handle_failed_transfer(request_id, handle)
|
||||
if not self._handle_failed_transfer(
|
||||
request_id, handle, self._recv_failures
|
||||
):
|
||||
assert handle is not None
|
||||
self._recving_transfers[request_id].append(handle)
|
||||
return False
|
||||
|
||||
def _read_blocks_mixed(
|
||||
@@ -537,7 +547,8 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
)
|
||||
except Exception:
|
||||
for handle in handles:
|
||||
self.nixl_wrapper.release_xfer_handle(handle)
|
||||
if not self._try_release_xfer_handle(request_id, handle):
|
||||
self._recving_transfers[request_id].append(handle)
|
||||
raise
|
||||
|
||||
self._pending_recv_notifs.setdefault(request_id, []).append(
|
||||
@@ -548,7 +559,8 @@ class NixlPullConnectorWorker(NixlBaseConnectorWorker):
|
||||
self.nixl_wrapper.transfer(handle)
|
||||
except Exception:
|
||||
for unstarted in handles[i:]:
|
||||
self.nixl_wrapper.release_xfer_handle(unstarted)
|
||||
if not self._try_release_xfer_handle(request_id, unstarted):
|
||||
self._recving_transfers[request_id].append(unstarted)
|
||||
raise
|
||||
self._recving_transfers[request_id].append(handle)
|
||||
|
||||
|
||||
@@ -198,7 +198,7 @@ class NixlPushConnectorScheduler(NixlBaseConnectorScheduler):
|
||||
# ReqMeta without a KeyError — the actual remote block IDs are
|
||||
# learned by P over the NIXL handshake at WRITE time.
|
||||
params["remote_block_ids"] = ()
|
||||
self._reqs_need_recv[request.request_id] = (request, local_block_ids, ())
|
||||
self._reqs_need_recv[request.request_id] = (request, local_block_ids, (), False)
|
||||
|
||||
# Mark as processed so a re-entry (e.g. preemption + reschedule)
|
||||
# doesn't re-stage the registration.
|
||||
@@ -240,7 +240,7 @@ class NixlPushConnectorScheduler(NixlBaseConnectorScheduler):
|
||||
# recv so the worker emits a notif that lets P free them.
|
||||
# Seed remote_block_ids so add_new_req_to_recv won't KeyError.
|
||||
params["remote_block_ids"] = ()
|
||||
self._reqs_need_recv[request.request_id] = (request, [], ())
|
||||
self._reqs_need_recv[request.request_id] = (request, [], (), False)
|
||||
params["do_remote_prefill"] = False
|
||||
return False, None
|
||||
|
||||
|
||||
@@ -83,6 +83,8 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
# Distinguishes push from pull in the NIXL compatibility hash.
|
||||
_TRANSFER_MODE: str = "push"
|
||||
|
||||
_supports_pp_hma = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: "VllmConfig",
|
||||
@@ -341,7 +343,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
self._log_failure(
|
||||
failure_type="push_reg_handshake_failed", req_id=rid, error=e
|
||||
)
|
||||
self._handle_failed_transfer(rid, None)
|
||||
self._failed_recv_reqs.put(rid)
|
||||
return
|
||||
# Re-queue for the writer to send now that the handshake is done.
|
||||
self._reg_send_inbox.put((rid, rd))
|
||||
@@ -354,14 +356,16 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
def _do_send_reg_notif(self, req_id: str, reg_data: dict[str, Any]) -> None:
|
||||
engine_id = reg_data["remote_engine_id"]
|
||||
notif_msg = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(reg_data)
|
||||
agents = self._remote_agents.get(engine_id)
|
||||
# _remote_agents is mutated on other threads; snapshot under the lock.
|
||||
with self._handshake_lock:
|
||||
agents = dict(self._remote_agents.get(engine_id) or {})
|
||||
if not agents:
|
||||
logger.error(
|
||||
"No remote agents for engine %s; cannot send registration for %s",
|
||||
engine_id,
|
||||
req_id,
|
||||
)
|
||||
self._handle_failed_transfer(req_id, None)
|
||||
self._failed_recv_reqs.put(req_id)
|
||||
return
|
||||
for rank, agent_name in agents.items():
|
||||
try:
|
||||
@@ -528,7 +532,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
local_region_groups = self.region_group_ids
|
||||
remote_region_groups = self.dst_region_group_ids[engine_id]
|
||||
groups_differ = local_region_groups != remote_region_groups
|
||||
if groups_differ:
|
||||
if groups_differ and not self._transfer_layer_group_ids:
|
||||
raise NotImplementedError(
|
||||
"NixlPushConnector does not support different producer and "
|
||||
"consumer cache-group layouts"
|
||||
@@ -720,9 +724,8 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
# don't have a ``_recving_metadata`` entry to invalidate, so
|
||||
# we just release the handle and let the engine reschedule
|
||||
# via the lease / watchdog.
|
||||
if handle is not None:
|
||||
self.nixl_wrapper.release_xfer_handle(handle)
|
||||
self.xfer_stats.record_failed_transfer()
|
||||
if not self._handle_failed_transfer(request_id, handle):
|
||||
return handle
|
||||
return None
|
||||
|
||||
# --- Notification handling on engine main thread ------------------ #
|
||||
@@ -801,7 +804,16 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
# ``_pop_done_transfers`` mutates ``_sending_transfers``; the
|
||||
# writer thread also appends to it, so guard the pop.
|
||||
with self._sending_transfers_lock:
|
||||
done_pushing = self._pop_done_transfers(self._sending_transfers)
|
||||
done_pushing, failed_pushing = self._pop_done_transfers(
|
||||
self._sending_transfers
|
||||
)
|
||||
# A failed send must never be reported as done: its blocks
|
||||
# are freed via the lease / watchdog instead.
|
||||
done_pushing = {
|
||||
req_id
|
||||
for req_id in done_pushing - failed_pushing
|
||||
if req_id in self._recving_metadata
|
||||
}
|
||||
for req_id in done_pushing:
|
||||
self._reqs_to_send.pop(req_id, None)
|
||||
self._reqs_to_process.discard(req_id)
|
||||
|
||||
@@ -354,6 +354,8 @@ class RequestOffloadState:
|
||||
req_context: ReqContext
|
||||
offloading_context: RequestOffloadingContext
|
||||
group_states: tuple[RequestGroupState, ...] = field(init=False)
|
||||
# upper bound on tokens to load for this request; None means no cap
|
||||
max_load_tokens: int | None = None
|
||||
# upper bound on tokens to offload for this request; None means no cap
|
||||
max_offload_tokens: int | None = None
|
||||
# number of hits in the GPU cache
|
||||
@@ -376,6 +378,20 @@ class RequestOffloadState:
|
||||
)
|
||||
params = self.req.kv_transfer_params
|
||||
|
||||
# NOTE: This field is experimental and subject to change in the future.
|
||||
raw = params.get("max_load_tokens") if params else None
|
||||
if type(raw) is int and raw >= 0:
|
||||
self.max_load_tokens = raw
|
||||
logger.debug(
|
||||
"Request %s: max_load_tokens set to %d",
|
||||
self.req.request_id,
|
||||
raw,
|
||||
)
|
||||
elif raw is not None:
|
||||
logger.warning(
|
||||
"max_load_tokens must be a non-negative int, got %r; ignoring", raw
|
||||
)
|
||||
|
||||
# NOTE: This field is experimental and subject to change in the future.
|
||||
raw = params.get("max_offload_tokens") if params else None
|
||||
if type(raw) is int and raw >= 0:
|
||||
@@ -685,6 +701,7 @@ class OffloadingConnectorScheduler:
|
||||
The first run may need a larger window for a partial rightmost chunk.
|
||||
Returns 0 on miss, None if the backend deferred a lookup."""
|
||||
defer_lookup = False
|
||||
pending_in_window = False
|
||||
consecutive_hits = 0
|
||||
required_window = initial_window_size or sliding_window_size
|
||||
for idx in range(len(keys) - 1, -1, -1):
|
||||
@@ -695,7 +712,7 @@ class OffloadingConnectorScheduler:
|
||||
# Block is in cache, just not readable yet — counts
|
||||
# as hit for the consecutive streak. Don't break:
|
||||
# keep scanning to let manager kick off async lookups.
|
||||
defer_lookup = True
|
||||
pending_in_window = True
|
||||
consecutive_hits += 1
|
||||
case LookupResult.RETRY:
|
||||
# Block location uncertain — does not count as hit.
|
||||
@@ -703,13 +720,18 @@ class OffloadingConnectorScheduler:
|
||||
# async lookups.
|
||||
defer_lookup = True
|
||||
consecutive_hits = 0
|
||||
pending_in_window = False
|
||||
required_window = sliding_window_size
|
||||
case LookupResult.MISS:
|
||||
consecutive_hits = 0
|
||||
# This gap rules out the incomplete window to its right.
|
||||
pending_in_window = False
|
||||
required_window = sliding_window_size
|
||||
if consecutive_hits == required_window:
|
||||
return idx + required_window if not defer_lookup else None
|
||||
return consecutive_hits if not defer_lookup else None
|
||||
return (
|
||||
None if defer_lookup or pending_in_window else idx + required_window
|
||||
)
|
||||
return None if defer_lookup or pending_in_window else consecutive_hits
|
||||
|
||||
def _touch(self, req_status: RequestOffloadState):
|
||||
for group_config, group_state in zip(
|
||||
@@ -761,6 +783,11 @@ class OffloadingConnectorScheduler:
|
||||
max_hit_size_tokens = min(
|
||||
max_hit_size_tokens, num_computed_tokens + max_num_new_tokens
|
||||
)
|
||||
if req_status.max_load_tokens is not None:
|
||||
max_hit_size_tokens = min(
|
||||
max_hit_size_tokens,
|
||||
num_computed_tokens + req_status.max_load_tokens,
|
||||
)
|
||||
if self._sliding_window_groups:
|
||||
# the last prompt token has to be recomputed to get the logprobs
|
||||
# for sliding window attention, we must reduce by 1 to make sure
|
||||
@@ -804,6 +831,10 @@ class OffloadingConnectorScheduler:
|
||||
max_hit_size_tokens = min(
|
||||
max_hit_size_tokens, len(offload_keys) * tokens_per_chunk
|
||||
)
|
||||
if req_status.max_load_tokens is not None:
|
||||
max_hit_size_tokens = round_down(
|
||||
max_hit_size_tokens, tokens_per_chunk
|
||||
)
|
||||
if max_hit_size_tokens - num_computed_tokens < tokens_per_chunk:
|
||||
# We can only load less than a chunk, so skip.
|
||||
return 0
|
||||
@@ -959,6 +990,11 @@ class OffloadingConnectorScheduler:
|
||||
max_boundary = min(req_status.req.num_prompt_tokens - 1, block_end - 1)
|
||||
if max_num_new_tokens is not None:
|
||||
max_boundary = min(max_boundary, local_tokens + max_num_new_tokens)
|
||||
if req_status.max_load_tokens is not None:
|
||||
max_boundary = min(
|
||||
max_boundary,
|
||||
local_tokens + req_status.max_load_tokens,
|
||||
)
|
||||
max_boundary = round_down(max_boundary, tokens_per_hash)
|
||||
if max_boundary <= complete_boundary:
|
||||
return complete_hit
|
||||
|
||||
@@ -91,9 +91,26 @@ def is_nixl_available() -> bool:
|
||||
return pkg in sys.modules or importlib.util.find_spec(pkg) is not None
|
||||
|
||||
|
||||
def alias_nixl_for_ray() -> None:
|
||||
"""Let Ray's ``nixl._api`` import resolve to the ROCm implementation."""
|
||||
if not current_platform.is_rocm() or "nixl._api" in sys.modules:
|
||||
return
|
||||
|
||||
package_name = _get_nixl_package_name()
|
||||
if not is_nixl_available():
|
||||
raise ImportError(f"Ray's NIXL transport on ROCm requires {package_name}")
|
||||
|
||||
_maybe_set_ucx_rcache_limit()
|
||||
package = importlib.import_module(package_name)
|
||||
api = importlib.import_module(f"{package_name}._api")
|
||||
sys.modules.setdefault("nixl", package)
|
||||
sys.modules.setdefault("nixl._api", api)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"NixlWrapper",
|
||||
"nixl_agent_config",
|
||||
"nixlXferTelemetry",
|
||||
"is_nixl_available",
|
||||
"alias_nixl_for_ray",
|
||||
]
|
||||
|
||||
@@ -77,6 +77,16 @@ def check_ray_rdt_version() -> None:
|
||||
)
|
||||
|
||||
|
||||
def register_nixl_memory(tensor: torch.Tensor) -> None:
|
||||
"""Register a tensor with Ray using the platform's NIXL package."""
|
||||
from vllm.distributed.nixl_utils import alias_nixl_for_ray
|
||||
|
||||
alias_nixl_for_ray()
|
||||
from ray.experimental import register_nixl_memory as ray_register_nixl_memory
|
||||
|
||||
ray_register_nixl_memory(tensor)
|
||||
|
||||
|
||||
def assign_producer_indices(
|
||||
num_producers: int, num_consumers: int, consumer_idx: int
|
||||
) -> list[int]:
|
||||
|
||||
@@ -66,6 +66,7 @@ from vllm.distributed.weight_transfer.sharded_rdt_common import (
|
||||
RdtRouter,
|
||||
buffer_alloc_bytes,
|
||||
check_ray_rdt_version,
|
||||
register_nixl_memory,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.sharded_rdt_fake import (
|
||||
BakeSink,
|
||||
@@ -588,8 +589,6 @@ class ShardedRDTWeightTransferEngine(
|
||||
plan = self._cached_plan
|
||||
if plan is None or not plan.chunks:
|
||||
return
|
||||
from ray.experimental import register_nixl_memory
|
||||
|
||||
# (a) consumer receive buffers — one per ring slot, at the largest chunk.
|
||||
max_pack = max(c.pack_bytes for c in plan.chunks)
|
||||
alloc = buffer_alloc_bytes(max_pack, self._buffer_presize)
|
||||
@@ -740,7 +739,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
any time after the metadata push. See the doc's "slot generation
|
||||
handshake".
|
||||
"""
|
||||
from ray.experimental import register_nixl_memory, set_target_for_ref
|
||||
from ray.experimental import set_target_for_ref
|
||||
|
||||
if self._slot_read_done:
|
||||
with self._slot_cv:
|
||||
|
||||
@@ -47,6 +47,7 @@ from vllm.distributed.weight_transfer.sharded_rdt_common import (
|
||||
ALLOWED_OPS,
|
||||
buffer_alloc_bytes,
|
||||
check_ray_rdt_version,
|
||||
register_nixl_memory,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
|
||||
@@ -334,8 +335,6 @@ class _RDTProducerServer:
|
||||
doc). The warmup buffer stays registered so the agent's CUDA-HMEM path
|
||||
stays initialized.
|
||||
"""
|
||||
from ray.experimental import register_nixl_memory
|
||||
|
||||
self._nixl_warmup_buf = torch.zeros(1 << 20, dtype=torch.uint8, device="cuda")
|
||||
with self._reg_lock:
|
||||
register_nixl_memory(self._nixl_warmup_buf)
|
||||
@@ -510,8 +509,6 @@ class _RDTProducerServer:
|
||||
"""Allocate + NIXL-register one serve slot: the single allocation seam,
|
||||
so registration cannot be skipped on either of the two paths that make
|
||||
buffers (the init-time reservation and the serve-path backstop)."""
|
||||
from ray.experimental import register_nixl_memory
|
||||
|
||||
t = torch.empty(nbytes, dtype=torch.uint8, device=self._serve_device)
|
||||
with self._reg_lock:
|
||||
register_nixl_memory(t)
|
||||
|
||||
@@ -18,6 +18,7 @@ from vllm.entrypoints.launchers.cli_args import (
|
||||
from vllm.entrypoints.launchers.dp_supervisor import run_dp_supervisor
|
||||
from vllm.entrypoints.serve.utils.api_utils import VLLM_SUBCMD_PARSER_EPILOG
|
||||
from vllm.logger import init_logger
|
||||
from vllm.reasoning import ReasoningParserManager
|
||||
from vllm.usage.usage_lib import UsageContext
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import get_tcp_uri
|
||||
@@ -179,6 +180,9 @@ def run_headless(args: argparse.Namespace):
|
||||
if args.api_server_count > 1:
|
||||
raise ValueError("api_server_count can't be set in headless mode")
|
||||
|
||||
if args.reasoning_parser_plugin and len(args.reasoning_parser_plugin) > 3:
|
||||
ReasoningParserManager.import_reasoning_parser(args.reasoning_parser_plugin)
|
||||
|
||||
# Create the EngineConfig.
|
||||
engine_args = vllm.AsyncEngineArgs.from_cli_args(args)
|
||||
usage_context = UsageContext.OPENAI_API_SERVER
|
||||
|
||||
@@ -17,9 +17,10 @@ log) and vLLM continues to boot normally.
|
||||
|
||||
Even when the SDK is installed, :func:`attach_router` also requires
|
||||
``VLLM_ENABLE_COHERE_API=1`` in the environment before it will expose
|
||||
the chat route. The render route additionally requires
|
||||
``VLLM_ENABLE_SCALE_OUT_ENDPOINTS=1``. These gates keep unrelated
|
||||
deployments from accidentally exposing the APIs.
|
||||
the chat route. The render route additionally requires scale-out
|
||||
endpoints to be enabled, i.e. ``--enable-scale-out`` or
|
||||
``--tokens-only``. These gates keep unrelated deployments from
|
||||
accidentally exposing the APIs.
|
||||
|
||||
Note: the handlers must live at module scope (not inside
|
||||
``attach_router``) so that FastAPI's ``typing.get_type_hints`` resolves
|
||||
@@ -306,6 +307,7 @@ def attach_router(app: FastAPI) -> None:
|
||||
)
|
||||
return
|
||||
app.include_router(router)
|
||||
if envs.VLLM_ENABLE_SCALE_OUT_ENDPOINTS:
|
||||
args = getattr(app.state, "args", None)
|
||||
if getattr(args, "enable_scale_out", False) or getattr(args, "tokens_only", False):
|
||||
app.include_router(render_router)
|
||||
app.add_middleware(CohereErrorEnvelopeMiddleware)
|
||||
|
||||
@@ -186,7 +186,9 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
|
||||
best_beams = sorted_completed[:beam_width]
|
||||
|
||||
for beam in best_beams:
|
||||
beam.text = tokenizer.decode(beam.tokens)
|
||||
beam.text = tokenizer.decode(
|
||||
beam.tokens, skip_special_tokens=params.skip_special_tokens
|
||||
)
|
||||
|
||||
outputs.append(BeamSearchOutput(sequences=best_beams))
|
||||
|
||||
@@ -291,6 +293,18 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
|
||||
allowed_sets[i] = set(entry[1])
|
||||
|
||||
for (start, end), instance in zip(instance_start_and_end, instances_batch):
|
||||
instance_output = output[start:end]
|
||||
if any(
|
||||
result is not None and result.outputs[0].finish_reason == "abort"
|
||||
for result in instance_output
|
||||
):
|
||||
for beam, result in zip(all_beams[start:end], instance_output):
|
||||
if result is not None:
|
||||
beam.finish_reason = "abort"
|
||||
instance.completed.append(beam)
|
||||
instance.beams = []
|
||||
continue
|
||||
|
||||
instance_new_beams = []
|
||||
for i in range(start, end):
|
||||
current_beam = all_beams[i]
|
||||
@@ -300,8 +314,6 @@ class BeamSearchOfflineMixin(OfflineInferenceMixin):
|
||||
continue
|
||||
|
||||
if result.outputs[0].logprobs is not None:
|
||||
# if logprobs is None, the sequence completed
|
||||
# due to max-model-len or abortion.
|
||||
logprobs = result.outputs[0].logprobs[0]
|
||||
allowed = allowed_sets[i]
|
||||
for token_id, logprob_obj in logprobs.items():
|
||||
|
||||
@@ -99,11 +99,7 @@ class BeamSearchOnlineMixin(ABC):
|
||||
|
||||
output = [x[0] for x in await asyncio.gather(*tasks)]
|
||||
|
||||
candidates = []
|
||||
# Iterate through all beam inference results
|
||||
for i, result in enumerate(output):
|
||||
current_beam = all_beams[i]
|
||||
|
||||
for result in output:
|
||||
# check for error finish reason and abort beam search
|
||||
if result.outputs[0].finish_reason == "error":
|
||||
# yield error output and terminate beam search
|
||||
@@ -126,6 +122,15 @@ class BeamSearchOnlineMixin(ABC):
|
||||
)
|
||||
return
|
||||
|
||||
if any(result.outputs[0].finish_reason == "abort" for result in output):
|
||||
for beam in all_beams:
|
||||
beam.finish_reason = "abort"
|
||||
break
|
||||
|
||||
candidates = []
|
||||
for i, result in enumerate(output):
|
||||
current_beam = all_beams[i]
|
||||
|
||||
if result.outputs[0].logprobs is not None:
|
||||
logprobs = result.outputs[0].logprobs[0]
|
||||
for token_id, logprob_obj in logprobs.items():
|
||||
@@ -197,7 +202,9 @@ class BeamSearchOnlineMixin(ABC):
|
||||
tokens = beam.tokens[tokenized_length:-1]
|
||||
else:
|
||||
tokens = beam.tokens[tokenized_length:]
|
||||
beam.text = tokenizer.decode(tokens)
|
||||
beam.text = tokenizer.decode(
|
||||
tokens, skip_special_tokens=params.skip_special_tokens
|
||||
)
|
||||
|
||||
yield RequestOutput(
|
||||
request_id=request_id,
|
||||
|
||||
@@ -150,7 +150,8 @@ def get_beam_search_score(
|
||||
if tokens[-1] == eos_token_id:
|
||||
seq_len -= 1
|
||||
|
||||
return cumulative_logprob / (seq_len**length_penalty)
|
||||
# An aborted beam may contain only an EOS prompt token.
|
||||
return cumulative_logprob / (max(seq_len, 1) ** length_penalty)
|
||||
|
||||
|
||||
def create_sort_beams_key_function(eos_token_id: int, length_penalty: float):
|
||||
|
||||
@@ -47,7 +47,7 @@ class LoRAParserAction(argparse.Action):
|
||||
if item in [None, ""]: # Skip if item is None or empty string
|
||||
continue
|
||||
if "=" in item and "," not in item: # Old format: name=path
|
||||
name, path = item.split("=")
|
||||
name, path = item.split("=", 1)
|
||||
lora_list.append(LoRAModulePath(name, path))
|
||||
else: # Assume JSON format
|
||||
try:
|
||||
@@ -181,6 +181,13 @@ class BaseFrontendArgs:
|
||||
If set to True, only enable the Tokens In<>Out endpoint.
|
||||
This is intended for use in a Disaggregated Everything setup.
|
||||
"""
|
||||
enable_scale_out: bool = False
|
||||
"""
|
||||
If set to True, register the scale-out endpoints (`/render`, `/derender`,
|
||||
and `/inference/v1/generate`) on `vllm serve`. Has no effect on
|
||||
`vllm launch render` or `vllm serve --tokens-only`, which always register
|
||||
their required endpoints regardless of this flag.
|
||||
"""
|
||||
fingerprint_mode: Literal["full", "hash", "custom", "none"] = "full"
|
||||
"""Controls the ``system_fingerprint`` field on responses.
|
||||
|
||||
|
||||
@@ -659,6 +659,7 @@ class ChatCompletionRequest(OpenAIBaseModel):
|
||||
temperature=temperature,
|
||||
length_penalty=self.length_penalty,
|
||||
include_stop_str_in_output=self.include_stop_str_in_output,
|
||||
skip_special_tokens=self.skip_special_tokens,
|
||||
)
|
||||
|
||||
def extract_structured_outputs(self) -> StructuredOutputsParams | None:
|
||||
|
||||
@@ -303,6 +303,7 @@ class CompletionRequest(OpenAIBaseModel):
|
||||
temperature=temperature,
|
||||
length_penalty=self.length_penalty,
|
||||
include_stop_str_in_output=self.include_stop_str_in_output,
|
||||
skip_special_tokens=self.skip_special_tokens,
|
||||
)
|
||||
|
||||
def extract_structured_outputs(self) -> StructuredOutputsParams | None:
|
||||
|
||||
@@ -171,6 +171,8 @@ class FixedMaxLenTokenizeParamsMixin(PoolingTokenizeParamsMixin):
|
||||
|
||||
|
||||
class EmbeddingTokenizeParamsMixin(PoolingTokenizeParamsMixin):
|
||||
padding: Literal["max_length", "do_not_pad"] | None
|
||||
|
||||
def build_tok_params(self, model_config: ModelConfig) -> TokenizeParams:
|
||||
default_max_total_tokens = model_config.max_model_len
|
||||
max_total_tokens: int | None = default_max_total_tokens
|
||||
@@ -184,7 +186,7 @@ class EmbeddingTokenizeParamsMixin(PoolingTokenizeParamsMixin):
|
||||
max_embed_len = pooler_config.max_embed_len or default_max_total_tokens
|
||||
max_output_tokens = default_max_total_tokens - max_embed_len
|
||||
|
||||
return self._build_pooling_tok_params(
|
||||
tok_params = self._build_pooling_tok_params(
|
||||
model_config,
|
||||
add_special_tokens=self.add_special_tokens,
|
||||
max_total_tokens=max_total_tokens,
|
||||
@@ -192,6 +194,20 @@ class EmbeddingTokenizeParamsMixin(PoolingTokenizeParamsMixin):
|
||||
max_output_tokens_param="max_model_len - max_embed_len",
|
||||
)
|
||||
|
||||
if (
|
||||
self.padding == "max_length"
|
||||
and pooler_config is not None
|
||||
and pooler_config.enable_chunked_processing
|
||||
):
|
||||
max_padding_len = pooler_config.max_embed_len
|
||||
if max_padding_len is None:
|
||||
max_padding_len = default_max_total_tokens
|
||||
return tok_params.with_kwargs(
|
||||
pad_prompt_tokens=min(default_max_total_tokens, max_padding_len)
|
||||
)
|
||||
|
||||
return tok_params
|
||||
|
||||
|
||||
class CompletionRequestMixin(OpenAIBaseModel):
|
||||
# --8<-- [start:completion-params]
|
||||
|
||||
@@ -57,8 +57,6 @@ async def create_score(request: ScoreRequest, raw_request: Request):
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def create_score_v1(request: ScoreRequest, raw_request: Request):
|
||||
logger.warning(
|
||||
"To indicate that Score API is not part of standard OpenAI API, we "
|
||||
@@ -91,7 +89,6 @@ async def do_rerank(request: RerankRequest, raw_request: Request):
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
async def do_rerank_v1(request: RerankRequest, raw_request: Request):
|
||||
logger.warning_once(
|
||||
"To indicate that the rerank API is not part of the standard OpenAI"
|
||||
@@ -110,6 +107,5 @@ async def do_rerank_v1(request: RerankRequest, raw_request: Request):
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
async def do_rerank_v2(request: RerankRequest, raw_request: Request):
|
||||
return await do_rerank(request, raw_request)
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from vllm import envs
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.logger import init_logger
|
||||
from vllm.tasks import SupportedTask
|
||||
@@ -67,22 +66,15 @@ def register_scale_out_api_routers(
|
||||
app: FastAPI,
|
||||
supported_tasks: tuple["SupportedTask", ...],
|
||||
):
|
||||
dedicated_mode = None
|
||||
if "render" in supported_tasks:
|
||||
dedicated_mode = "`vllm launch render`"
|
||||
elif getattr(app.state.args, "tokens_only", False):
|
||||
dedicated_mode = "`--tokens-only`"
|
||||
|
||||
enabled = envs.VLLM_ENABLE_SCALE_OUT_ENDPOINTS
|
||||
if dedicated_mode is not None and enabled is False:
|
||||
raise ValueError(
|
||||
"`VLLM_ENABLE_SCALE_OUT_ENDPOINTS=0` conflicts with "
|
||||
f"{dedicated_mode}; unset it or set it to 1"
|
||||
)
|
||||
if dedicated_mode is None and not enabled:
|
||||
args = getattr(app.state, "args", None)
|
||||
# `vllm launch render` and `vllm serve --tokens-only` are dedicated to
|
||||
# serving these endpoints, so they always register them regardless of
|
||||
# `--enable-scale-out`.
|
||||
dedicated_mode = "render" in supported_tasks or getattr(args, "tokens_only", False)
|
||||
enabled = dedicated_mode or getattr(args, "enable_scale_out", False)
|
||||
if not enabled:
|
||||
logger.info(
|
||||
"Scale-out endpoints are disabled. Set "
|
||||
"VLLM_ENABLE_SCALE_OUT_ENDPOINTS=1 to enable them."
|
||||
"Scale-out endpoints are disabled. Set --enable-scale-out to enable them."
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
+18
-24
@@ -137,7 +137,7 @@ if TYPE_CHECKING:
|
||||
VLLM_ROCM_USE_AITER_LINEAR_HIPBMM: bool = False
|
||||
VLLM_ROCM_USE_AITER_MOE: bool = True
|
||||
VLLM_ROCM_AITER_MOE_DISPATCH_POLICY: int = 0
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4: bool = False
|
||||
VLLM_ROCM_USE_AITER_MOE_SITUV2: bool = False
|
||||
VLLM_ROCM_USE_AITER_RMSNORM: bool = True
|
||||
VLLM_ROCM_USE_AITER_MLA: bool = True
|
||||
VLLM_ROCM_AITER_MLA_ASM_PADDING: Literal["auto", "gluon", "asm"] = "auto"
|
||||
@@ -261,7 +261,6 @@ if TYPE_CHECKING:
|
||||
VLLM_ALLOW_CHUNKED_LOCAL_ATTN_WITH_HYBRID_KV_CACHE: bool = True
|
||||
VLLM_ENABLE_RESPONSES_API_STORE: bool = False
|
||||
VLLM_ENABLE_COHERE_API: bool = False
|
||||
VLLM_ENABLE_SCALE_OUT_ENDPOINTS: bool | None = None
|
||||
VLLM_HAS_FLASHINFER_CUBIN: bool = False
|
||||
VLLM_ROCM_FP8_MFMA_PAGE_ATTN: bool = False
|
||||
VLLM_ALLREDUCE_USE_SYMM_MEM: bool = True
|
||||
@@ -352,15 +351,6 @@ def maybe_convert_bool(value: str | None) -> bool | None:
|
||||
return bool(int(value))
|
||||
|
||||
|
||||
def maybe_convert_scale_out_endpoints(value: str | None) -> bool | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = value.strip()
|
||||
if normalized not in ("0", "1"):
|
||||
raise ValueError("VLLM_ENABLE_SCALE_OUT_ENDPOINTS must be 0 or 1")
|
||||
return maybe_convert_bool(normalized)
|
||||
|
||||
|
||||
def maybe_convert_json_str_or_file(value: str | None) -> dict[str, Any] | None:
|
||||
if value is None:
|
||||
return None
|
||||
@@ -1261,12 +1251,18 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_ROCM_USE_AITER_MOE": lambda: (
|
||||
os.getenv("VLLM_ROCM_USE_AITER_MOE", "True").lower() in ("true", "1")
|
||||
),
|
||||
# Route K3 SiTU MXFP4 MoE through the a8w4 (fp8 activation) gate/up-
|
||||
# interleaved flydsl kernels instead of the default a16w4 separated path.
|
||||
# This is the only flag users need: vLLM picks the kernels by passing
|
||||
# gate_mode to AITER and sets the AITER-side workaround env at init.
|
||||
"VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4": lambda: (
|
||||
os.getenv("VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4", "0").lower() in ("true", "1")
|
||||
# Route K3 SiTU MXFP4 MoE through the FlyDSL SiTUv2 path (a4w4 fp4
|
||||
# activations, separated gate/up layout) instead of default a16w4. vLLM
|
||||
# sets AITER_SITUV2_A4W4 at init when this flag is on and clears any
|
||||
# legacy AITER_SITUV2_A8W4 override (AITER checks A8W4 first).
|
||||
# VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4 is a deprecated alias for existing
|
||||
# recipes; it does not select a8w4 kernels.
|
||||
# Needs AITER >= v0.1.20 (ROCm/aiter#4463) for the a4w4 dispatch flag
|
||||
# and tuned kimik3_a4w4_*_fmoe.csv rows; otherwise FlyDSL uses heuristics.
|
||||
"VLLM_ROCM_USE_AITER_MOE_SITUV2": lambda: (
|
||||
os.getenv("VLLM_ROCM_USE_AITER_MOE_SITUV2", "0").lower() in ("true", "1")
|
||||
or os.getenv("VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4", "0").lower()
|
||||
in ("true", "1")
|
||||
),
|
||||
# MoE sorting dispatch policy for AITER fused MoE kernels.
|
||||
# 0 = auto (default): single-pass for small batches, multi-pass
|
||||
@@ -1858,12 +1854,6 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
"VLLM_ENABLE_COHERE_API": lambda: bool(
|
||||
int(os.getenv("VLLM_ENABLE_COHERE_API", "0"))
|
||||
),
|
||||
# If set to 1, expose the scale-out endpoints on `vllm serve`.
|
||||
# The dedicated `vllm launch render` server exposes render and derender
|
||||
# endpoints when this variable is unset or set to 1.
|
||||
"VLLM_ENABLE_SCALE_OUT_ENDPOINTS": lambda: maybe_convert_scale_out_endpoints(
|
||||
os.getenv("VLLM_ENABLE_SCALE_OUT_ENDPOINTS") or None
|
||||
),
|
||||
# If set, use the fp8 mfma in rocm paged attention.
|
||||
"VLLM_ROCM_FP8_MFMA_PAGE_ATTN": lambda: bool(
|
||||
int(os.getenv("VLLM_ROCM_FP8_MFMA_PAGE_ATTN", "0"))
|
||||
@@ -2186,6 +2176,10 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
# Each op additionally checks its own shape / dtype constraints and falls
|
||||
# back to the eager path when they do not hold.
|
||||
"VLLM_ENABLE_HPC_OPS": lambda: bool(int(os.getenv("VLLM_ENABLE_HPC_OPS", "0"))),
|
||||
# Whether to skip version suffix when building package
|
||||
"VLLM_SKIP_VERSION_SUFFIX": lambda: bool(
|
||||
int(os.getenv("VLLM_SKIP_VERSION_SUFFIX", "0"))
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -2289,7 +2283,6 @@ def compile_factors() -> dict[str, object]:
|
||||
"VLLM_CONFIG_ROOT",
|
||||
"LD_LIBRARY_PATH",
|
||||
"VLLM_SERVER_DEV_MODE",
|
||||
"VLLM_ENABLE_SCALE_OUT_ENDPOINTS",
|
||||
"VLLM_DP_MASTER_IP",
|
||||
"VLLM_DP_MASTER_PORT",
|
||||
"VLLM_NIXL_SIDE_CHANNEL_HOST",
|
||||
@@ -2355,6 +2348,7 @@ def compile_factors() -> dict[str, object]:
|
||||
"LOCAL_RANK",
|
||||
"CUDA_VISIBLE_DEVICES",
|
||||
"NO_COLOR",
|
||||
"VLLM_SKIP_VERSION_SUFFIX",
|
||||
}
|
||||
|
||||
from vllm.config.utils import normalize_value
|
||||
|
||||
@@ -209,6 +209,15 @@ def is_forward_context_available() -> bool:
|
||||
return _forward_context is not None
|
||||
|
||||
|
||||
def in_piecewise_cudagraph() -> bool:
|
||||
"""Whether the current forward runs in piecewise cudagraph mode (graph
|
||||
segments separated by eager breaks), at capture or replay time."""
|
||||
return (
|
||||
is_forward_context_available()
|
||||
and get_forward_context().cudagraph_runtime_mode == CUDAGraphMode.PIECEWISE
|
||||
)
|
||||
|
||||
|
||||
def create_forward_context(
|
||||
attn_metadata: Any,
|
||||
vllm_config: VllmConfig,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from .activation import gelu_and_mul_sparse
|
||||
from .layernorm import fused_add_rms_norm, rms_norm
|
||||
|
||||
__all__ = ["rms_norm", "fused_add_rms_norm"]
|
||||
__all__ = ["rms_norm", "fused_add_rms_norm", "gelu_and_mul_sparse"]
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor
|
||||
|
||||
from ..op import register_op
|
||||
|
||||
|
||||
@register_op
|
||||
def gelu_and_mul_sparse(
|
||||
x: Tensor, std_multiplier: float, approximate: str = "none"
|
||||
) -> Tensor:
|
||||
"""Apply Gaussian sparsification, GELU, and gated multiplication."""
|
||||
d = x.shape[-1] // 2
|
||||
gate = x[..., :d]
|
||||
# Statistics intentionally remain local to each tensor-parallel shard.
|
||||
mean = torch.mean(gate, dim=-1, keepdim=True)
|
||||
std = torch.std(gate, dim=-1, keepdim=True, unbiased=False)
|
||||
sparse_gate = F.relu(gate - (mean + std * std_multiplier))
|
||||
return F.gelu(sparse_gate, approximate=approximate) * x[..., d:]
|
||||
|
||||
|
||||
@gelu_and_mul_sparse.register_input_generator
|
||||
def _gelu_and_mul_sparse_input_generator(
|
||||
num_tokens: int,
|
||||
hidden_size: int,
|
||||
dtype: torch.dtype,
|
||||
std_multiplier: float = 1.6448536269514722,
|
||||
approximate: str = "tanh",
|
||||
) -> tuple:
|
||||
x = torch.randn(num_tokens, hidden_size * 2, dtype=dtype)
|
||||
return x, std_multiplier, approximate
|
||||
@@ -2,6 +2,6 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Kernel implementations for vLLM."""
|
||||
|
||||
from . import aiter_ops, oink_ops, vllm_c
|
||||
from . import aiter_ops, oink_ops, triton, vllm_c
|
||||
|
||||
__all__ = ["vllm_c", "aiter_ops", "oink_ops"]
|
||||
__all__ = ["vllm_c", "aiter_ops", "oink_ops", "triton"]
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Triton kernel implementations."""
|
||||
|
||||
from . import activation
|
||||
|
||||
__all__ = ["activation"]
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
from torch.library import triton_op, wrap_triton
|
||||
|
||||
from vllm import ir
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
|
||||
_MAX_INTERMEDIATE_SIZE = 32768
|
||||
_SUPPORTED_DTYPES = {torch.float16, torch.bfloat16, torch.float32}
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _gelu_and_mul_sparse_kernel(
|
||||
x_ptr,
|
||||
output_ptr,
|
||||
d: tl.constexpr,
|
||||
std_multiplier,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
offsets = tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < d
|
||||
row_start = row * 2 * d
|
||||
|
||||
gate = tl.load(x_ptr + row_start + offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
# TODO: Investigate delaying this load to reduce spills for large reductions
|
||||
# without regressing smaller shapes.
|
||||
up = tl.load(x_ptr + row_start + d + offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
|
||||
input_dtype = x_ptr.dtype.element_ty
|
||||
mean = tl.sum(gate, axis=0) / d
|
||||
centered = tl.where(mask, gate - mean, 0.0)
|
||||
variance = tl.sum(centered * centered, axis=0) / d
|
||||
# Match the input-dtype rounding at each native PyTorch op boundary.
|
||||
mean = mean.to(input_dtype).to(tl.float32)
|
||||
std = tl.sqrt(variance).to(input_dtype).to(tl.float32)
|
||||
scaled_std = (std * std_multiplier).to(input_dtype).to(tl.float32)
|
||||
cutoff = (mean + scaled_std).to(input_dtype).to(tl.float32)
|
||||
sparse_gate = (gate - cutoff).to(input_dtype).to(tl.float32)
|
||||
sparse_gate = tl.where(sparse_gate < 0.0, 0.0, sparse_gate)
|
||||
|
||||
inner = 0.7978845608028654 * (
|
||||
sparse_gate + 0.044715 * sparse_gate * sparse_gate * sparse_gate
|
||||
)
|
||||
tanh = 2.0 * tl.sigmoid(2.0 * inner) - 1.0
|
||||
activated = 0.5 * sparse_gate * (1.0 + tanh)
|
||||
activated = activated.to(input_dtype).to(tl.float32)
|
||||
tl.store(output_ptr + row * d + offsets, activated * up, mask=mask)
|
||||
|
||||
|
||||
def _supports_gelu_and_mul_sparse(
|
||||
x: Tensor, std_multiplier: float, approximate: str = "none"
|
||||
) -> bool:
|
||||
del std_multiplier
|
||||
if (
|
||||
x.device.type != "cuda"
|
||||
or x.dtype not in _SUPPORTED_DTYPES
|
||||
or not x.is_contiguous()
|
||||
or x.ndim == 0
|
||||
or approximate != "tanh"
|
||||
):
|
||||
return False
|
||||
last_dim = x.shape[-1]
|
||||
return (
|
||||
last_dim > 0 and last_dim % 2 == 0 and last_dim // 2 <= _MAX_INTERMEDIATE_SIZE
|
||||
)
|
||||
|
||||
|
||||
@triton_op(
|
||||
"vllm::gelu_and_mul_sparse_triton",
|
||||
mutates_args=(),
|
||||
)
|
||||
def _gelu_and_mul_sparse_triton_op(x: Tensor, std_multiplier: float) -> Tensor:
|
||||
d = x.shape[-1] // 2
|
||||
output = torch.empty((*x.shape[:-1], d), dtype=x.dtype, device=x.device)
|
||||
if output.numel() == 0:
|
||||
return output
|
||||
|
||||
n_rows = x.numel() // x.shape[-1]
|
||||
|
||||
def grid(meta):
|
||||
return (n_rows,)
|
||||
|
||||
block_size = triton.next_power_of_2(d)
|
||||
num_warps = min(max(block_size // 256, 1), 8)
|
||||
wrap_triton(_gelu_and_mul_sparse_kernel)[grid](
|
||||
x,
|
||||
output,
|
||||
d=d,
|
||||
std_multiplier=std_multiplier,
|
||||
BLOCK_SIZE=block_size,
|
||||
num_warps=num_warps,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@ir.ops.gelu_and_mul_sparse.register_impl(
|
||||
"triton",
|
||||
supported=HAS_TRITON and current_platform.is_cuda(),
|
||||
supports_args=_supports_gelu_and_mul_sparse,
|
||||
)
|
||||
def gelu_and_mul_sparse_triton(
|
||||
x: Tensor, std_multiplier: float, approximate: str = "none"
|
||||
) -> Tensor:
|
||||
assert approximate == "tanh"
|
||||
return _gelu_and_mul_sparse_triton_op(x, std_multiplier)
|
||||
@@ -68,6 +68,10 @@ if envs.VLLM_LORA_ENABLE_DUAL_STREAM:
|
||||
|
||||
|
||||
class BaseLinearLayerWithLoRA(BaseLayerWithLoRA):
|
||||
# The adapter branch consumes the original activation, independently of
|
||||
# whether the wrapped base layer can consume a pre-quantized activation.
|
||||
requires_unquantized_input = True
|
||||
|
||||
def __init__(self, base_layer: LinearBase):
|
||||
super().__init__()
|
||||
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DeepGEMM sparse MQA-logits path for the DeepSeek V4.1 two-level indexer.
|
||||
|
||||
The candidate-source indexer publishes the top candidate blocks (in units of
|
||||
``candidate_block_size`` compressed positions). Instead of scoring every KV
|
||||
position and masking the dense logits down to those blocks, this path scores
|
||||
only the candidate tokens with DeepGEMM's sparse MQA logits kernels
|
||||
(``fp8_fp4_(paged_)sparse_mqa_logits``, DeepGEMM >= 2.8, SM100 only), runs
|
||||
DeepSelect's top-k directly on the bf16 logits they produce, and remaps the
|
||||
selected columns back to request-local positions.
|
||||
|
||||
Only the MXFP4 indexer cache is supported: the kernels require UE8M0-packed
|
||||
(granularity-32) Q/KV scales, which is exactly the MXFP4 cache layout. The
|
||||
FP8 indexer cache stores one fp32 scale per quant block instead.
|
||||
|
||||
The functions here take caller-owned output buffers (``sparse_indices``,
|
||||
``end``, ``col_indices``) so the hot path allocates nothing; the indexer
|
||||
metadata builder owns them.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.indexer_topk import (
|
||||
deep_select_topk,
|
||||
get_deep_select_stride_requirement,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.deep_gemm import (
|
||||
fp8_fp4_paged_sparse_mqa_logits,
|
||||
fp8_fp4_sparse_mqa_logits,
|
||||
get_paged_sparse_mqa_logits_metadata,
|
||||
get_sparse_mqa_logits_metadata,
|
||||
)
|
||||
|
||||
# Sparse-block sizes (in tokens) supported by the DeepGEMM kernels.
|
||||
SPARSE_BLOCK_KV_CHOICES = (16, 8)
|
||||
|
||||
|
||||
def has_deep_select() -> bool:
|
||||
"""Whether the DeepSelect top-k extension is built and this GPU runs it."""
|
||||
return (
|
||||
importlib.util.find_spec("vllm._deepselect_C") is not None
|
||||
and current_platform.is_cuda()
|
||||
and current_platform.is_device_capability_family(100)
|
||||
)
|
||||
|
||||
|
||||
def check_deep_select_layout(num_sparse_cols: int, topk_tokens: int) -> None:
|
||||
"""Raise unless DeepSelect accepts the sparse logits layout.
|
||||
|
||||
The sparse kernels return contiguous bf16 ``[rows, num_sparse_cols]``
|
||||
logits and the top-k writes int32 ``[rows, topk_tokens]`` indices;
|
||||
DeepSelect needs both row strides aligned (1024B / 32B on SM100).
|
||||
"""
|
||||
in_align, out_align = get_deep_select_stride_requirement()
|
||||
logits_row_bytes = num_sparse_cols * torch.bfloat16.itemsize
|
||||
if num_sparse_cols >= 2**23 or logits_row_bytes % in_align != 0:
|
||||
raise ValueError(
|
||||
f"DeepSelect needs the sparse logits row ({num_sparse_cols} bf16 "
|
||||
f"columns, {logits_row_bytes} B) to be {in_align}B-aligned."
|
||||
)
|
||||
if topk_tokens > 4096 or (topk_tokens * torch.int32.itemsize) % out_align != 0:
|
||||
raise ValueError(
|
||||
f"DeepSelect needs topk <= 4096 with a {out_align}B-aligned int32 "
|
||||
f"output row, got topk={topk_tokens}."
|
||||
)
|
||||
|
||||
|
||||
_INT32_BIG = tl.constexpr(2**31 - 1)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _expand_candidates_kernel(
|
||||
cand_ptr,
|
||||
cand_stride,
|
||||
ks_ptr,
|
||||
ks_stride,
|
||||
ke_ptr,
|
||||
ke_stride,
|
||||
si_ptr,
|
||||
si_stride,
|
||||
end_ptr,
|
||||
end_stride,
|
||||
K: tl.constexpr,
|
||||
S: tl.constexpr,
|
||||
RATIO: tl.constexpr,
|
||||
SBK: tl.constexpr,
|
||||
):
|
||||
"""One program per row: expand + filter + sort candidate blocks.
|
||||
|
||||
Each row's valid sparse blocks come out sorted ascending (no dedup pass:
|
||||
production candidates are unique, and the kernel tolerates repeats),
|
||||
padded by repeating the last valid block — DeepGEMM's padding convention.
|
||||
``end`` counts valid sparse-token columns; valid columns form a prefix
|
||||
because block ids are sorted.
|
||||
"""
|
||||
row = tl.program_id(0)
|
||||
ks = tl.load(ks_ptr + row * ks_stride)
|
||||
ke = tl.load(ke_ptr + row * ke_stride)
|
||||
cols = tl.arange(0, K)
|
||||
cand = tl.load(cand_ptr + row * cand_stride + cols) # K is pow2, no mask
|
||||
if RATIO == 2:
|
||||
cand = tl.interleave(cand * RATIO, cand * RATIO + 1)
|
||||
|
||||
# Keep only blocks inside the row's KV range [0, ke - ks); the lower
|
||||
# bound is free since candidates are non-negative.
|
||||
kv_len = tl.maximum(ke - ks, 0)
|
||||
max_block = (kv_len + SBK - 1) // SBK
|
||||
valid = (cand >= 0) & (cand < max_block)
|
||||
vals = tl.where(valid, cand, _INT32_BIG)
|
||||
vals = tl.sort(vals)
|
||||
|
||||
# Anchor at the row's ks rounded down to a sparse-block boundary
|
||||
# (identity for the paged path, where ks == 0).
|
||||
base = ks // SBK
|
||||
si = tl.where(vals != _INT32_BIG, vals, 0) + base
|
||||
n_valid = tl.sum(valid.to(tl.int32))
|
||||
last_rel = tl.max(tl.where(valid, cand, -1))
|
||||
pad_val = tl.where(n_valid > 0, last_rel + base, base)
|
||||
tl.store(
|
||||
si_ptr + row * si_stride + tl.arange(0, S),
|
||||
tl.where(tl.arange(0, S) < n_valid, si, pad_val),
|
||||
)
|
||||
|
||||
# Valid sparse-token column count; only the last block can be partial.
|
||||
# Absolute start of the last block: (base + last_rel) * SBK + ks % SBK,
|
||||
# which is exactly last_rel * SBK + ks.
|
||||
last_start = last_rel * SBK + ks
|
||||
fill = tl.minimum(tl.maximum(ke - last_start, 1), SBK)
|
||||
end = tl.where(n_valid > 0, (n_valid - 1) * SBK + fill, 0)
|
||||
tl.store(end_ptr + row * end_stride, end)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _sparse_topk_remap_kernel(
|
||||
col_ptr,
|
||||
col_stride,
|
||||
si_ptr,
|
||||
si_stride,
|
||||
ks_ptr,
|
||||
ks_stride,
|
||||
out_ptr,
|
||||
out_stride,
|
||||
k,
|
||||
SBK: tl.constexpr,
|
||||
K_POW2: tl.constexpr,
|
||||
):
|
||||
"""Remap sparse top-k columns to request-local positions.
|
||||
|
||||
Column ``j * SBK + o`` scores the token at
|
||||
``(si[row, j] - ks // SBK) * SBK + o``; -1 columns stay -1.
|
||||
"""
|
||||
row = tl.program_id(0)
|
||||
ks_base = tl.load(ks_ptr + row * ks_stride) // SBK
|
||||
cols = tl.arange(0, K_POW2)
|
||||
c = tl.load(col_ptr + row * col_stride + cols, mask=cols < k, other=-1)
|
||||
valid = c >= 0
|
||||
cc = tl.where(valid, c, 0)
|
||||
blocks = tl.load(si_ptr + row * si_stride + cc // SBK)
|
||||
pos = (blocks - ks_base) * SBK + cc % SBK
|
||||
tl.store(out_ptr + row * out_stride + cols, tl.where(valid, pos, -1), mask=cols < k)
|
||||
|
||||
|
||||
def pick_sparse_block_kv(candidate_block_size: int) -> int:
|
||||
"""Largest sparse-block size (tokens) dividing the candidate block size."""
|
||||
for sbk in SPARSE_BLOCK_KV_CHOICES:
|
||||
if candidate_block_size % sbk == 0:
|
||||
return sbk
|
||||
raise ValueError(
|
||||
f"candidate_block_size={candidate_block_size} is not a multiple of "
|
||||
f"any supported sparse_block_kv {SPARSE_BLOCK_KV_CHOICES}."
|
||||
)
|
||||
|
||||
|
||||
def candidate_blocks_to_sparse_indices(
|
||||
candidate_blocks: torch.Tensor,
|
||||
row_ks: torch.Tensor,
|
||||
row_ke: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
sparse_block_kv: int,
|
||||
out: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Expand request-local candidate blocks into DeepGEMM sparse block ids.
|
||||
|
||||
Args:
|
||||
candidate_blocks: [rows, K] int32 request-local candidate block ids
|
||||
(-1 padded), in units of ``candidate_block_size`` positions. K
|
||||
must be a power of two (the in-kernel sort); rows may be strided.
|
||||
row_ks/row_ke: [rows] int32 per-row K range; bounds are in the same
|
||||
(packed-workspace) coordinates the sparse kernel iterates over.
|
||||
Pass zeros for the paged path, whose blocks are context-relative.
|
||||
candidate_block_size: Positions per candidate block.
|
||||
sparse_block_kv: Positions per sparse block (8 or 16).
|
||||
out: Optional ``(sparse_indices, end)`` buffers to write into,
|
||||
shaped [rows, K * ratio] and [rows], both int32.
|
||||
|
||||
Returns:
|
||||
sparse_indices: [rows, K * ratio] int32 block ids for DeepGEMM,
|
||||
sorted ascending per row with the valid prefix first (unique in
|
||||
production, where candidates are unique) and the remaining slots
|
||||
repeating the last valid block (the kernel's padding convention).
|
||||
With the unaligned-ks variant, block ``i`` starts at
|
||||
``i * sparse_block_kv + ks % sparse_block_kv``.
|
||||
end: [rows] int32 count of valid sparse-token columns; valid columns
|
||||
always form a prefix because the block ids are sorted.
|
||||
"""
|
||||
rows, num_candidates = candidate_blocks.shape
|
||||
ratio = candidate_block_size // sparse_block_kv
|
||||
assert ratio * sparse_block_kv == candidate_block_size and ratio in (1, 2), (
|
||||
candidate_block_size,
|
||||
sparse_block_kv,
|
||||
)
|
||||
assert num_candidates & (num_candidates - 1) == 0, num_candidates
|
||||
num_sparse = num_candidates * ratio
|
||||
if out is None:
|
||||
device = candidate_blocks.device
|
||||
out = (
|
||||
torch.empty(rows, num_sparse, dtype=torch.int32, device=device),
|
||||
torch.empty(rows, dtype=torch.int32, device=device),
|
||||
)
|
||||
sparse_indices, end = out
|
||||
assert sparse_indices.shape == (rows, num_sparse) and end.shape == (rows,)
|
||||
assert candidate_blocks.stride(1) == 1 and sparse_indices.stride(1) == 1
|
||||
for t in (candidate_blocks, row_ks, row_ke, sparse_indices, end):
|
||||
assert t.dtype == torch.int32, t.dtype
|
||||
|
||||
_expand_candidates_kernel[(rows,)](
|
||||
candidate_blocks,
|
||||
candidate_blocks.stride(0),
|
||||
row_ks,
|
||||
row_ks.stride(0),
|
||||
row_ke,
|
||||
row_ke.stride(0),
|
||||
sparse_indices,
|
||||
sparse_indices.stride(0),
|
||||
end,
|
||||
end.stride(0),
|
||||
K=num_candidates,
|
||||
S=num_sparse,
|
||||
RATIO=ratio,
|
||||
SBK=sparse_block_kv,
|
||||
num_warps=16,
|
||||
)
|
||||
return sparse_indices, end
|
||||
|
||||
|
||||
def sparse_topk_remap(
|
||||
logits: torch.Tensor,
|
||||
sparse_indices: torch.Tensor,
|
||||
end: torch.Tensor,
|
||||
row_ks: torch.Tensor,
|
||||
sparse_block_kv: int,
|
||||
topk_tokens: int,
|
||||
topk_indices: torch.Tensor,
|
||||
*,
|
||||
col_indices: torch.Tensor,
|
||||
) -> None:
|
||||
"""Row top-k over sparse logits, remapped to request-local positions.
|
||||
|
||||
Column ``j * sparse_block_kv + o`` of ``logits`` scores the token at
|
||||
request-local position
|
||||
``(sparse_indices[row, j] - ks // sparse_block_kv) * sparse_block_kv + o``.
|
||||
|
||||
DeepSelect consumes the bf16 logits as they come out of the sparse
|
||||
kernels; the valid columns form a prefix (block ids are sorted), so the
|
||||
per-row ``end`` bounds drive it directly. Slots beyond a row's valid
|
||||
count come back as -1.
|
||||
|
||||
Args:
|
||||
col_indices: [rows, topk_tokens] int32 scratch for the sparse-column
|
||||
top-k result (row stride 32B-aligned for DeepSelect).
|
||||
"""
|
||||
rows, width = logits.shape
|
||||
assert logits.dtype == torch.bfloat16 and width >= topk_tokens
|
||||
assert end.dtype == torch.int32 and end.shape == (rows,)
|
||||
cols = col_indices[:rows]
|
||||
deep_select_topk(logits, topk_tokens, end=end, output_idx=cols)
|
||||
_sparse_topk_remap_kernel[(rows,)](
|
||||
cols,
|
||||
cols.stride(0),
|
||||
sparse_indices,
|
||||
sparse_indices.stride(0),
|
||||
row_ks,
|
||||
row_ks.stride(0),
|
||||
topk_indices,
|
||||
topk_indices.stride(0),
|
||||
topk_tokens,
|
||||
SBK=sparse_block_kv,
|
||||
K_POW2=triton.next_power_of_2(topk_tokens),
|
||||
)
|
||||
|
||||
|
||||
def sparse_mqa_logits_prefill_chunk(
|
||||
q: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
k_quant: torch.Tensor,
|
||||
k_scale: torch.Tensor,
|
||||
weights: torch.Tensor,
|
||||
cu_seqlen_ks: torch.Tensor,
|
||||
cu_seqlen_ke: torch.Tensor,
|
||||
candidate_blocks: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
sparse_block_kv: int,
|
||||
topk_tokens: int,
|
||||
topk_indices: torch.Tensor,
|
||||
*,
|
||||
sparse_indices: torch.Tensor,
|
||||
end: torch.Tensor,
|
||||
col_indices: torch.Tensor,
|
||||
kernel_metadata: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Sparse-MQA logits + top-k for one prefill chunk (packed KV workspace).
|
||||
|
||||
Args:
|
||||
q: [rows, H, D] packed Q values (MXFP4 viewed as int8).
|
||||
q_scale: [rows, H] int32 packed UE8M0 Q scales.
|
||||
k_quant: [total_kv, D] packed K workspace (MXFP4 viewed as int8).
|
||||
k_scale: [total_kv] int32 packed UE8M0 K scales.
|
||||
weights: [rows, H] bf16 per-head weights; the sparse kernels take
|
||||
bf16 and do not fold the Q scale in.
|
||||
cu_seqlen_ks/cu_seqlen_ke: [rows] int32 per-token K bounds in the
|
||||
packed workspace.
|
||||
candidate_blocks: [rows, K] int32 request-local candidate block ids.
|
||||
topk_indices: [rows, topk_tokens] output buffer.
|
||||
sparse_indices/end/col_indices: Caller-owned scratch, see
|
||||
`candidate_blocks_to_sparse_indices` and `sparse_topk_remap`.
|
||||
kernel_metadata: DeepGEMM schedule from a previous call with the same
|
||||
candidates and bounds (i.e. another indexer layer in the same
|
||||
step). When given, the candidate expansion is skipped and
|
||||
``sparse_indices``/``end`` are assumed to be up to date.
|
||||
|
||||
Returns:
|
||||
The DeepGEMM schedule metadata used, for reuse by later layers.
|
||||
"""
|
||||
assert weights.dtype == torch.bfloat16, weights.dtype
|
||||
if kernel_metadata is None:
|
||||
candidate_blocks_to_sparse_indices(
|
||||
candidate_blocks,
|
||||
cu_seqlen_ks,
|
||||
cu_seqlen_ke,
|
||||
candidate_block_size,
|
||||
sparse_block_kv,
|
||||
out=(sparse_indices, end),
|
||||
)
|
||||
kernel_metadata = get_sparse_mqa_logits_metadata(
|
||||
cu_seqlen_ks,
|
||||
cu_seqlen_ke,
|
||||
k_quant.shape[0],
|
||||
sparse_indices,
|
||||
q.dtype,
|
||||
sparse_block_kv,
|
||||
)
|
||||
logits = fp8_fp4_sparse_mqa_logits(
|
||||
(q, q_scale),
|
||||
(k_quant, k_scale),
|
||||
weights,
|
||||
kernel_metadata,
|
||||
sparse_indices.shape[1],
|
||||
sparse_block_kv,
|
||||
)
|
||||
sparse_topk_remap(
|
||||
logits,
|
||||
sparse_indices,
|
||||
end,
|
||||
cu_seqlen_ks,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices,
|
||||
col_indices=col_indices,
|
||||
)
|
||||
return kernel_metadata
|
||||
|
||||
|
||||
def sparse_mqa_logits_paged_decode(
|
||||
q: torch.Tensor,
|
||||
q_scale: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
weights: torch.Tensor,
|
||||
context_lens: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
row_indices: torch.Tensor,
|
||||
candidate_blocks: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
sparse_block_kv: int,
|
||||
topk_tokens: int,
|
||||
topk_indices: torch.Tensor,
|
||||
*,
|
||||
row_ks: torch.Tensor,
|
||||
sparse_indices: torch.Tensor,
|
||||
end: torch.Tensor,
|
||||
col_indices: torch.Tensor,
|
||||
kernel_metadata: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Sparse-MQA logits + top-k for paged decode rows.
|
||||
|
||||
Every query is one row (spec-decode rows are flattened by the metadata
|
||||
builder), so ``block_table`` is already per row.
|
||||
|
||||
Args:
|
||||
q: [rows, 1, H, D] packed Q values (MXFP4 viewed as int8).
|
||||
q_scale: [rows, 1, H] int32 packed UE8M0 Q scales.
|
||||
kv_cache: 4D [num_pages, page_kv, 1, head_bytes] uint8 fused cache
|
||||
view; the page stride must be 512B-aligned.
|
||||
weights: [rows, H] bf16 per-head weights.
|
||||
context_lens: [rows] int32 per-row (compressed) context lengths.
|
||||
block_table: [rows, P] int32 per-row page table, ``stride(-1) == 1``.
|
||||
row_indices: [rows] int32 row -> request map (pairing only affects
|
||||
scheduling).
|
||||
candidate_blocks: [rows, K] int32 candidate block ids.
|
||||
topk_indices: [rows, topk_tokens] output buffer.
|
||||
row_ks: [rows] int32 zeros (paged blocks are context-relative).
|
||||
sparse_indices/end/col_indices: Caller-owned scratch.
|
||||
kernel_metadata: See `sparse_mqa_logits_prefill_chunk`.
|
||||
|
||||
Returns:
|
||||
The DeepGEMM schedule metadata used, for reuse by later layers.
|
||||
"""
|
||||
rows = q.shape[0]
|
||||
page_kv = kv_cache.shape[1]
|
||||
assert weights.dtype == torch.bfloat16, weights.dtype
|
||||
assert kv_cache.stride(0) % 512 == 0, (
|
||||
"paged cache page stride must be 512B-aligned: "
|
||||
f"shape={tuple(kv_cache.shape)} stride={kv_cache.stride()}"
|
||||
)
|
||||
assert page_kv % sparse_block_kv == 0, (page_kv, sparse_block_kv)
|
||||
assert block_table.shape[0] == rows and block_table.stride(-1) == 1
|
||||
assert context_lens.shape == (rows,) and context_lens.is_contiguous()
|
||||
|
||||
if kernel_metadata is None:
|
||||
candidate_blocks_to_sparse_indices(
|
||||
candidate_blocks,
|
||||
row_ks,
|
||||
context_lens,
|
||||
candidate_block_size,
|
||||
sparse_block_kv,
|
||||
out=(sparse_indices, end),
|
||||
)
|
||||
kernel_metadata = get_paged_sparse_mqa_logits_metadata(
|
||||
context_lens,
|
||||
block_table,
|
||||
row_indices,
|
||||
page_kv,
|
||||
sparse_indices,
|
||||
q.dtype,
|
||||
sparse_block_kv,
|
||||
)
|
||||
logits = fp8_fp4_paged_sparse_mqa_logits(
|
||||
(q, q_scale),
|
||||
kv_cache,
|
||||
weights,
|
||||
kernel_metadata,
|
||||
sparse_indices.shape[1],
|
||||
sparse_block_kv,
|
||||
)
|
||||
sparse_topk_remap(
|
||||
logits,
|
||||
sparse_indices,
|
||||
end,
|
||||
row_ks,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices,
|
||||
col_indices=col_indices,
|
||||
)
|
||||
return kernel_metadata
|
||||
@@ -235,14 +235,19 @@ from vllm.platforms import PlatformEnum, current_platform
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _get_linear_backend() -> str:
|
||||
def _get_linear_backend(*, quantization: str) -> str:
|
||||
"""Get the linear_backend setting from the current vllm config."""
|
||||
from vllm.config import get_current_vllm_config_or_none
|
||||
|
||||
config = get_current_vllm_config_or_none()
|
||||
if config is not None:
|
||||
return config.kernel_config.linear_backend
|
||||
return "auto"
|
||||
if (config := get_current_vllm_config_or_none()) is None:
|
||||
return "auto"
|
||||
overrides = config.kernel_config.linear_backend_per_quant
|
||||
if overrides is not None and (override := overrides.get(quantization)):
|
||||
logger.info_once(
|
||||
"Applied linear backend override for %r: %r", quantization, override
|
||||
)
|
||||
return override
|
||||
return config.kernel_config.linear_backend
|
||||
|
||||
|
||||
# Kernel classes covered by each --linear-backend value.
|
||||
@@ -370,6 +375,8 @@ def _filter_kernels_by_backend(
|
||||
def _resolve_backend_kernels(
|
||||
kernels: list[type],
|
||||
layer_desc: str,
|
||||
*,
|
||||
quantization: str,
|
||||
) -> list[type]:
|
||||
"""Apply --linear-backend filtering to one layer type's kernel list.
|
||||
|
||||
@@ -380,7 +387,7 @@ def _resolve_backend_kernels(
|
||||
layer types (e.g. NVFP4 MoE projections next to FP8 attention
|
||||
projections).
|
||||
"""
|
||||
linear_backend = _get_linear_backend()
|
||||
linear_backend = _get_linear_backend(quantization=quantization)
|
||||
if linear_backend == "auto":
|
||||
return kernels
|
||||
filtered = _filter_kernels_by_backend(linear_backend, kernels)
|
||||
@@ -625,6 +632,8 @@ def choose_scaled_mm_linear_kernel(
|
||||
possible_kernels: dict[PlatformEnum, list[type[_KernelT]]],
|
||||
compute_capability: int | None = None,
|
||||
force_kernel: type[_KernelT] | None = None,
|
||||
*,
|
||||
quantization: str,
|
||||
) -> type[_KernelT]:
|
||||
"""
|
||||
Choose a _KernelT that can implement the given config for the
|
||||
@@ -642,6 +651,7 @@ def choose_scaled_mm_linear_kernel(
|
||||
force_kernel (Optional[type[_KernelT]]): An Optional forced kernel to override
|
||||
the possible_kernels if it can be implemented. If None, it will only try the
|
||||
possible kernels.
|
||||
quantization: Quantization scheme used to select a backend override.
|
||||
|
||||
Raises:
|
||||
ValueError: If no kernel can implement the given config.
|
||||
@@ -668,7 +678,11 @@ def choose_scaled_mm_linear_kernel(
|
||||
platform_kernels = possible_kernels.get(current_platform._enum, [])
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
platform_kernels = _resolve_backend_kernels(platform_kernels, "scaled-mm")
|
||||
platform_kernels = _resolve_backend_kernels(
|
||||
platform_kernels,
|
||||
"scaled-mm",
|
||||
quantization=quantization,
|
||||
)
|
||||
|
||||
for kernel in platform_kernels:
|
||||
is_supported_and_can_implement, failure_reason = (
|
||||
@@ -705,6 +719,7 @@ def init_fp8_linear_kernel(
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config=scaled_mm_linear_kernel_config,
|
||||
possible_kernels=_POSSIBLE_FP8_BLOCK_KERNELS, # type: ignore[misc]
|
||||
quantization="fp8_block_w8a8",
|
||||
force_kernel=force_kernel,
|
||||
)
|
||||
if module_name:
|
||||
@@ -736,6 +751,7 @@ def init_fp8_linear_kernel(
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config=scaled_mm_linear_kernel_config,
|
||||
possible_kernels=_POSSIBLE_FP8_KERNELS, # type: ignore[arg-type]
|
||||
quantization="fp8_w8a8",
|
||||
force_kernel=force_kernel,
|
||||
)
|
||||
if module_name:
|
||||
@@ -772,6 +788,7 @@ def init_int8_linear_kernel(
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config,
|
||||
_POSSIBLE_INT8_KERNELS,
|
||||
quantization="int8_w8a8",
|
||||
)
|
||||
|
||||
logger.info_once(
|
||||
@@ -824,7 +841,11 @@ def choose_mp_linear_kernel(
|
||||
platform_kernels = _POSSIBLE_KERNELS.get(current_platform._enum, [])
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
platform_kernels = _resolve_backend_kernels(platform_kernels, "mixed-precision")
|
||||
platform_kernels = _resolve_backend_kernels(
|
||||
platform_kernels,
|
||||
"mixed-precision",
|
||||
quantization="mixed_precision",
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel in platform_kernels:
|
||||
@@ -875,7 +896,11 @@ def init_mxfp8_linear_kernel(*, bmm_batch_size: int | None = None) -> Mxfp8Linea
|
||||
possible = list(_POSSIBLE_MXFP8_KERNELS.get(platform, []))
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
possible = _resolve_backend_kernels(possible, "MXFP8")
|
||||
possible = _resolve_backend_kernels(
|
||||
possible,
|
||||
"MXFP8",
|
||||
quantization="mxfp8",
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel_cls in possible:
|
||||
@@ -917,7 +942,11 @@ def init_mxfp4_linear_kernel(
|
||||
possible = list(_POSSIBLE_MXFP4_KERNELS.get(platform, []))
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
possible = _resolve_backend_kernels(possible, "MXFP4")
|
||||
possible = _resolve_backend_kernels(
|
||||
possible,
|
||||
"MXFP4",
|
||||
quantization="mxfp4",
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel_cls in possible:
|
||||
@@ -957,7 +986,7 @@ def init_mxfp6_linear_kernel(
|
||||
activation_quant_key=activation_quant_key,
|
||||
)
|
||||
|
||||
linear_backend = _get_linear_backend()
|
||||
linear_backend = _get_linear_backend(quantization="mxfp6")
|
||||
|
||||
platform = current_platform._enum
|
||||
possible = list(_POSSIBLE_MXFP6_KERNELS.get(platform, []))
|
||||
@@ -1017,7 +1046,10 @@ def init_wfp8_a16_linear_kernel(
|
||||
)
|
||||
|
||||
kernel_type = choose_scaled_mm_linear_kernel(
|
||||
config, _POSSIBLE_WFP8A16_KERNELS, force_kernel=force_kernel
|
||||
config,
|
||||
_POSSIBLE_WFP8A16_KERNELS,
|
||||
quantization="w8a16_fp8",
|
||||
force_kernel=force_kernel,
|
||||
)
|
||||
|
||||
if module_name:
|
||||
@@ -1048,7 +1080,8 @@ def init_nvfp4_linear_kernel(use_a16: bool = False) -> NvFp4LinearKernel:
|
||||
# batch-invariant CUTLASS implementation when available, otherwise fall
|
||||
# back to emulation. It overrides --linear-backend.
|
||||
force_kernel: type[NvFp4LinearKernel] | None = None
|
||||
linear_backend = _get_linear_backend()
|
||||
quantization = "nvfp4_w4a16" if use_a16 else "nvfp4_w4a4"
|
||||
linear_backend = _get_linear_backend(quantization=quantization)
|
||||
if envs.VLLM_BATCH_INVARIANT:
|
||||
bi_supported, reason = CutlassNvFp4LinearKernel.is_supported()
|
||||
if bi_supported:
|
||||
@@ -1110,7 +1143,11 @@ def init_nvfp4_linear_kernel(use_a16: bool = False) -> NvFp4LinearKernel:
|
||||
possible = [kernel for kernel in possible if kernel in a16_kernels]
|
||||
|
||||
# Apply --linear-backend filtering when set.
|
||||
possible = _resolve_backend_kernels(possible, "NVFP4")
|
||||
possible = _resolve_backend_kernels(
|
||||
possible,
|
||||
"NVFP4",
|
||||
quantization=quantization,
|
||||
)
|
||||
|
||||
failure_reasons = []
|
||||
for kernel_cls in possible:
|
||||
|
||||
@@ -77,7 +77,7 @@ def _triton_w4a16_skinny_fmt_kernel(
|
||||
a_ptr, # [M, K] fp16/bf16 activations
|
||||
b_ptr, # [N, K//8] int32 packed (ExLlama shuffle, K is packed dim)
|
||||
scales_ptr, # [N, K//G] fp16/bf16 scales (skinny layout)
|
||||
zp_ptr, # [N, K//G] fp16/bf16 raw zero-points (when HAS_ZP=True)
|
||||
zp_ptr, # [N//8, K//G] int32 zero-points (when HAS_ZP=True)
|
||||
c_ptr, # [M, N] fp16/bf16 output
|
||||
# Dimensions
|
||||
M,
|
||||
@@ -103,8 +103,9 @@ def _triton_w4a16_skinny_fmt_kernel(
|
||||
| (val[1]<<16) | (val[3]<<20) | (val[5]<<24) | (val[7]<<28)
|
||||
|
||||
Scales are [N, K//G] (skinny layout, NOT transposed).
|
||||
When HAS_ZP=True, raw zero-points zp_raw are loaded from zp_ptr [N, K//G]
|
||||
and subtracted directly: (nibble - zp_raw) * scale.
|
||||
When HAS_ZP=True, zp_ptr holds [N//8, K//G] int32 with row n's raw
|
||||
zero-point at word[n//8] bits 4*(n%8), and dequant is
|
||||
(nibble - zp_raw) * scale.
|
||||
When HAS_ZP=False, only the constant ZP_BIAS is subtracted (symmetric).
|
||||
"""
|
||||
pid_m = tl.program_id(0)
|
||||
@@ -148,9 +149,10 @@ def _triton_w4a16_skinny_fmt_kernel(
|
||||
scales = tl.load(scale_ptrs, mask=scale_mask, other=1.0)
|
||||
|
||||
if HAS_ZP:
|
||||
zp_ptrs = zp_ptr + offs_n * num_groups + group_idx
|
||||
zp_raw = tl.load(zp_ptrs, mask=scale_mask, other=0.0)
|
||||
b_fp = (b.to(scales.dtype) - zp_raw[:, None]) * scales[:, None]
|
||||
zp_ptrs = zp_ptr + (offs_n // 8) * num_groups + group_idx
|
||||
zp_word = tl.load(zp_ptrs, mask=scale_mask, other=0)
|
||||
zp_raw = (zp_word >> (4 * (offs_n % 8))) & 0xF
|
||||
b_fp = (b - zp_raw[:, None]).to(scales.dtype) * scales[:, None]
|
||||
else:
|
||||
b_fp = (b - ZP_BIAS).to(scales.dtype) * scales[:, None]
|
||||
|
||||
@@ -192,7 +194,7 @@ def triton_w4a16_skinny_fmt_gemm(
|
||||
scales: torch.Tensor, # [N, K//G] fp16/bf16
|
||||
group_size: int,
|
||||
zp_bias: int = 8,
|
||||
zp: torch.Tensor | None = None, # [N, K//G] per-group zero-points
|
||||
zp: torch.Tensor | None = None, # [N//8, K//G] int32 zero-points
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Fused W4A16 GEMM reading from skinny weight format [N, K//8].
|
||||
@@ -203,8 +205,8 @@ def triton_w4a16_skinny_fmt_gemm(
|
||||
scales: Per-group scales [N, K//G], same dtype as a.
|
||||
group_size: Quantization group size (resolved from -1 to K by caller).
|
||||
zp_bias: Constant zero bias (default 8 for unsigned int4).
|
||||
zp: Raw per-group zero-points [N, K//G] (asymmetric),
|
||||
stored as zp_raw in activation dtype. When provided,
|
||||
zp: Raw per-group zero-points [N//8, K//G] int32, row n at
|
||||
word[n//8] bits 4*(n%8) (asymmetric). When provided,
|
||||
dequant is (nibble - zp_raw) * scale.
|
||||
|
||||
Returns:
|
||||
@@ -225,8 +227,9 @@ def triton_w4a16_skinny_fmt_gemm(
|
||||
)
|
||||
if zp is not None:
|
||||
assert zp.is_contiguous(), "Zero-points must be contiguous"
|
||||
assert zp.shape == (N, num_groups), (
|
||||
f"zp shape mismatch: {zp.shape} vs ({N}, {num_groups})"
|
||||
assert N % 8 == 0, f"N must be divisible by 8 for packed zp, got {N}"
|
||||
assert zp.shape == (N // 8, num_groups), (
|
||||
f"zp shape mismatch: {zp.shape} vs ({N // 8}, {num_groups})"
|
||||
)
|
||||
has_zp = zp is not None
|
||||
|
||||
@@ -381,7 +384,10 @@ def _rdna_hybrid_w4a16_apply_impl(
|
||||
cu_count: int,
|
||||
group_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Dispatch between skinny GEMM and Triton based on batch size M."""
|
||||
"""Dispatch between skinny GEMM and Triton based on batch size M.
|
||||
|
||||
``w_zp`` is [N//8, K//G] int32 for asymmetric layers, None for symmetric.
|
||||
"""
|
||||
import vllm._custom_ops as ops
|
||||
|
||||
M = x_2d.shape[0]
|
||||
@@ -520,10 +526,7 @@ class RDNAHybridW4A16LinearKernel(MPLinearKernel):
|
||||
assert self.w_zp_name is not None
|
||||
w_zp_raw = getattr(layer, self.w_zp_name)
|
||||
permute_param_layout_(w_zp_raw, input_dim=1, output_dim=0, packed_dim=0)
|
||||
zp_unpacked = unpack_quantized_values_into_int32(
|
||||
w_zp_raw.data, c.weight_type, packed_dim=0
|
||||
)
|
||||
w_zp = zp_unpacked.to(c.act_type).contiguous()
|
||||
w_zp = w_zp_raw.data.contiguous()
|
||||
self._transform_param(layer, self.w_zp_name, lambda x: w_zp)
|
||||
|
||||
self._transform_param(layer, self.w_q_name, lambda x: w_q_skinny)
|
||||
|
||||
@@ -158,7 +158,7 @@ class AiterMxfp4LinearKernel(MxFp4LinearKernel):
|
||||
from vllm._aiter_ops import is_aiter_found_and_supported
|
||||
from vllm.model_executor.kernels.linear import _get_linear_backend
|
||||
|
||||
linear_backend = _get_linear_backend()
|
||||
linear_backend = _get_linear_backend(quantization="mxfp4")
|
||||
|
||||
if (
|
||||
current_platform.is_rocm()
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
Consumes the FP8 E4M3 weights + E8M0 block scales directly (no dequant-to-BF16);
|
||||
activations are MXFP8-quantized per token. Uses the CDNA4 hardware microscaling
|
||||
matrix cores. Falls back (via the kernel selector) to the BF16
|
||||
``EmulationMxfp8LinearKernel`` on archs without native MX or for shapes with
|
||||
``K % 128 != 0``.
|
||||
matrix cores. ``dot_scaled`` tiles K by 128; a weight whose K is not a multiple
|
||||
of that is dequantized to BF16 once at load and served by a plain linear
|
||||
instead, since ``can_implement`` does not filter on K.
|
||||
"""
|
||||
|
||||
import torch
|
||||
@@ -194,6 +194,9 @@ def _select_cfg(M, N, K):
|
||||
return (128, 128, 256, 8, 2) if K % 256 == 0 else (128, 256, 128, 8, 3)
|
||||
|
||||
|
||||
_DOT_SCALED_K_ALIGN = 128
|
||||
|
||||
|
||||
class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
"""Native CDNA4 (gfx950) MXFP8 linear via Triton ``tl.dot_scaled``."""
|
||||
|
||||
@@ -219,6 +222,8 @@ class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
N, K = weight.shape
|
||||
scale_k = K // MXFP8_BLOCK_SIZE
|
||||
weight_scale = layer.weight_scale.data[:N, :scale_k].contiguous()
|
||||
if K % _DOT_SCALED_K_ALIGN != 0:
|
||||
weight = dequant_mxfp8_to_bf16(weight.contiguous(), weight_scale)
|
||||
layer.weight = Parameter(weight.contiguous(), requires_grad=False)
|
||||
layer.weight_scale = Parameter(weight_scale, requires_grad=False)
|
||||
|
||||
@@ -235,10 +240,13 @@ class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
)
|
||||
out_shape = (*x.shape[:-1], layer.weight.shape[0])
|
||||
x2d = x.reshape(-1, x.shape[-1])
|
||||
if x2d.shape[-1] % 128 == 0:
|
||||
if layer.weight.element_size() >= 2:
|
||||
out = torch.nn.functional.linear(x2d, layer.weight.to(x.dtype))
|
||||
elif x2d.shape[-1] % _DOT_SCALED_K_ALIGN == 0:
|
||||
out = _mxfp8_dot_scaled_linear(x2d, layer.weight, layer.weight_scale)
|
||||
else:
|
||||
# dot_scaled tiling needs K % 128 == 0; dequantize fallback otherwise.
|
||||
# process_weights_after_loading dequantizes these weights once, so
|
||||
# this runs only if it did not; dot_scaled would be invalid here.
|
||||
w_bf16 = dequant_mxfp8_to_bf16(layer.weight, layer.weight_scale)
|
||||
out = torch.nn.functional.linear(x2d, w_bf16).to(x.dtype)
|
||||
out = out.reshape(out_shape)
|
||||
|
||||
@@ -261,6 +261,8 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
|
||||
return True, None
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
if getattr(layer, "_cpu_skip_gemm_dispatch", False):
|
||||
return
|
||||
# Skip the base class process (FP8 padding / fnuz normalization)
|
||||
# which is GPU-oriented. Instead, VNNI-prepack weights for AMX.
|
||||
params = self._get_layer_params(layer)
|
||||
|
||||
@@ -115,6 +115,10 @@ def mhc_pre_delayed_aiter(
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
residual_out: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""mHC pre with the pre-mix carried in from the previous sublayer.
|
||||
|
||||
@@ -134,6 +138,13 @@ def mhc_pre_delayed_aiter(
|
||||
sinkhorn_repeat: number of sinkhorn iterations
|
||||
pre_mix: shape (..., hc_mult) from the previous sublayer, or None at
|
||||
model entry to select residual stream zero.
|
||||
sublayer_out: attention or FFN output, shape (..., hidden_size). When
|
||||
given with the two mixes below, the preceding post block is
|
||||
applied here so AITER can fold it into the pre projection.
|
||||
post_layer_mix: shape (..., hc_mult, 1), post gate for that block.
|
||||
comb_res_mix: shape (..., hc_mult, hc_mult), residual comb for it.
|
||||
residual_out: shape (..., hc_mult, hidden_size), written with the post
|
||||
block's new residual. Required exactly when the post is folded in.
|
||||
|
||||
Returns:
|
||||
post_mix: shape (..., hc_mult, 1), dtype torch.float32
|
||||
@@ -156,6 +167,10 @@ def mhc_pre_delayed_aiter(
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
pre_mix,
|
||||
sublayer_out,
|
||||
post_layer_mix,
|
||||
comb_res_mix,
|
||||
residual_out,
|
||||
)
|
||||
|
||||
|
||||
@@ -170,6 +185,10 @@ def _mhc_pre_delayed_aiter_fake(
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
residual_out: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
hc_mult = residual.shape[-2]
|
||||
hidden_size = residual.shape[-1]
|
||||
@@ -313,7 +332,7 @@ direct_register_custom_op(
|
||||
direct_register_custom_op(
|
||||
op_name="mhc_pre_delayed_aiter",
|
||||
op_func=mhc_pre_delayed_aiter,
|
||||
mutates_args=[],
|
||||
mutates_args=["residual_out"],
|
||||
fake_impl=_mhc_pre_delayed_aiter_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
|
||||
@@ -194,6 +194,7 @@ def mhc_pre_delayed_tilelang(
|
||||
norm_weight,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
layer_input,
|
||||
hidden_size=hidden_size,
|
||||
rms_eps=rms_eps,
|
||||
hc_pre_eps=hc_pre_eps,
|
||||
@@ -218,6 +219,7 @@ def mhc_pre_delayed_tilelang(
|
||||
layer_input,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
layer_input,
|
||||
hidden_size,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
@@ -263,6 +265,278 @@ def _mhc_pre_delayed_tilelang_fake(
|
||||
)
|
||||
|
||||
|
||||
def mhc_fused_post_pre_delayed_tilelang(
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
post_layer_mix: torch.Tensor,
|
||||
comb_res_mix: torch.Tensor,
|
||||
fn: torch.Tensor,
|
||||
hc_scale: torch.Tensor,
|
||||
hc_base: torch.Tensor,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
hc_sinkhorn_eps: float,
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
capture_aux: bool = False,
|
||||
) -> tuple[
|
||||
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
"""Run one mHC post block followed by the next delayed mHC pre block.
|
||||
|
||||
Within the fused kernel's token range the post mapping is folded into the
|
||||
pre-norm GEMM, so the updated residual streams feed the projection from
|
||||
registers instead of a second pass over global memory. Above it this runs
|
||||
the same post kernel and split-k GEMM as the unfused pair.
|
||||
|
||||
Args:
|
||||
x: BF16 sublayer output of shape (tokens, hidden_size).
|
||||
residual: BF16 residual streams of shape (tokens, hc_mult, hidden_size).
|
||||
post_layer_mix: FP32 post coefficients of shape (tokens, hc_mult, 1).
|
||||
comb_res_mix: FP32 residual coefficients, (tokens, hc_mult, hc_mult).
|
||||
fn: FP32 projection of shape (hc_mult * (hc_mult + 2), input_size).
|
||||
hc_scale: FP32 scales of shape (3,).
|
||||
hc_base: FP32 bias of shape (hc_mult * (hc_mult + 2),).
|
||||
rms_eps: RMS normalization epsilon.
|
||||
hc_pre_eps: Pre-mix epsilon.
|
||||
hc_sinkhorn_eps: Sinkhorn epsilon.
|
||||
hc_post_mult_value: Post-mix multiplier.
|
||||
sinkhorn_repeat: Number of Sinkhorn iterations.
|
||||
pre_mix: FP32 coefficients from the previous sublayer, or None to
|
||||
select residual stream zero.
|
||||
norm_weight: Optional BF16 RMSNorm weight for the collapsed input.
|
||||
norm_eps: RMSNorm epsilon for the collapsed input.
|
||||
capture_aux: Also return the mean over the post-mapped streams, which
|
||||
draft models consume as the target's hidden state. It is folded
|
||||
into the collapse, which already reads those streams.
|
||||
|
||||
Returns:
|
||||
The post-mapped residual streams, the post and residual coefficients,
|
||||
the optionally normalized BF16 layer input, the next FP32 pre-mix, and
|
||||
the BF16 stream mean (empty unless capture_aux), with shapes
|
||||
(tokens, hc_mult, hidden_size), (tokens, hc_mult, 1),
|
||||
(tokens, hc_mult, hc_mult), (tokens, hidden_size), (tokens, hc_mult),
|
||||
and (tokens, hidden_size).
|
||||
"""
|
||||
from vllm.model_executor.kernels.mhc.tilelang_kernels import (
|
||||
_HC_PRENORM_GEMM_TILELANG_KERNEL,
|
||||
_MHC_FUSED_TILELANG_KERNEL,
|
||||
_MHC_POST_TILELANG_KERNEL,
|
||||
mhc_fused_post_pre_split_config,
|
||||
mhc_pre_big_fuse_tilelang,
|
||||
)
|
||||
from vllm.model_executor.kernels.mhc.warmup import (
|
||||
MHC_PRE_NORM_KERNEL,
|
||||
compute_mhc_pre_num_splits,
|
||||
)
|
||||
from vllm.utils.deep_gemm import (
|
||||
is_deep_gemm_supported,
|
||||
tf32_hc_prenorm_gemm,
|
||||
)
|
||||
|
||||
assert residual.ndim == 3 and residual.dtype == torch.bfloat16
|
||||
assert residual.is_contiguous()
|
||||
num_tokens, hc_mult, hidden_size = residual.shape
|
||||
input_size = hc_mult * hidden_size
|
||||
mix_size = hc_mult * (hc_mult + 2)
|
||||
assert x.shape == (num_tokens, hidden_size) and x.dtype == torch.bfloat16
|
||||
assert x.is_contiguous()
|
||||
assert post_layer_mix.shape[:2] == (num_tokens, hc_mult)
|
||||
assert post_layer_mix.dtype == torch.float32 and post_layer_mix.is_contiguous()
|
||||
assert comb_res_mix.shape == (num_tokens, hc_mult, hc_mult)
|
||||
assert comb_res_mix.dtype == torch.float32 and comb_res_mix.is_contiguous()
|
||||
assert fn.shape == (mix_size, input_size) and fn.dtype == torch.float32
|
||||
assert hc_scale.shape == (3,) and hc_scale.dtype == torch.float32
|
||||
assert hc_base.shape == (mix_size,) and hc_base.dtype == torch.float32
|
||||
if pre_mix is not None:
|
||||
assert pre_mix.shape == (num_tokens, hc_mult)
|
||||
assert pre_mix.dtype == torch.float32 and pre_mix.is_contiguous()
|
||||
|
||||
next_pre_mix = torch.empty(
|
||||
num_tokens, hc_mult, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
post = torch.empty_like(next_pre_mix)
|
||||
comb = torch.empty(
|
||||
num_tokens, hc_mult * hc_mult, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
layer_input = torch.empty(
|
||||
num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device
|
||||
)
|
||||
aux = torch.empty(
|
||||
num_tokens if capture_aux else 0,
|
||||
hidden_size,
|
||||
dtype=torch.bfloat16,
|
||||
device=residual.device,
|
||||
)
|
||||
if num_tokens == 0:
|
||||
return (
|
||||
torch.empty_like(residual),
|
||||
post.unsqueeze(-1),
|
||||
comb.view(num_tokens, hc_mult, hc_mult),
|
||||
layer_input,
|
||||
next_pre_mix,
|
||||
aux,
|
||||
)
|
||||
|
||||
fused_config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
if fused_config is not None:
|
||||
mixes, sqrsum, residual_cur = _MHC_FUSED_TILELANG_KERNEL(
|
||||
comb_res_mix,
|
||||
residual,
|
||||
post_layer_mix.view(num_tokens, hc_mult),
|
||||
x,
|
||||
fn.view(mix_size, hc_mult, hidden_size),
|
||||
hc_mult,
|
||||
hidden_size,
|
||||
mix_size,
|
||||
)
|
||||
else:
|
||||
residual_cur = torch.empty_like(residual)
|
||||
_MHC_POST_TILELANG_KERNEL(
|
||||
comb_res_mix,
|
||||
residual,
|
||||
post_layer_mix.view(num_tokens, hc_mult),
|
||||
x,
|
||||
residual_cur,
|
||||
hc_mult,
|
||||
hidden_size,
|
||||
)
|
||||
# The delayed epilogue is compiled per bucketed split count, so the
|
||||
# projection has to use the same bucket rather than the raw estimate.
|
||||
use_deep_gemm = is_deep_gemm_supported()
|
||||
n_splits = (
|
||||
compute_mhc_pre_num_splits(input_size, num_tokens) if use_deep_gemm else 1
|
||||
)
|
||||
mixes = torch.empty(
|
||||
n_splits, num_tokens, mix_size, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
sqrsum = torch.empty(
|
||||
n_splits, num_tokens, dtype=torch.float32, device=residual.device
|
||||
)
|
||||
residual_cur_2d = residual_cur.view(num_tokens, input_size)
|
||||
if use_deep_gemm:
|
||||
tf32_hc_prenorm_gemm(residual_cur_2d, fn, mixes, sqrsum, n_splits)
|
||||
else:
|
||||
_HC_PRENORM_GEMM_TILELANG_KERNEL(
|
||||
residual_cur_2d,
|
||||
fn,
|
||||
mixes,
|
||||
sqrsum,
|
||||
input_size,
|
||||
1,
|
||||
)
|
||||
|
||||
outputs = (
|
||||
residual_cur,
|
||||
post.unsqueeze(-1),
|
||||
comb.view(num_tokens, hc_mult, hc_mult),
|
||||
layer_input,
|
||||
next_pre_mix,
|
||||
aux,
|
||||
)
|
||||
if norm_weight is not None:
|
||||
assert norm_weight.shape == (hidden_size,)
|
||||
assert norm_weight.dtype == torch.bfloat16 and norm_weight.is_contiguous()
|
||||
MHC_PRE_NORM_KERNEL(
|
||||
mixes,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
residual_cur,
|
||||
post,
|
||||
comb,
|
||||
layer_input,
|
||||
norm_weight,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
aux if capture_aux else layer_input,
|
||||
hidden_size=hidden_size,
|
||||
rms_eps=rms_eps,
|
||||
hc_pre_eps=hc_pre_eps,
|
||||
hc_sinkhorn_eps=hc_sinkhorn_eps,
|
||||
hc_post_mult_value=hc_post_mult_value,
|
||||
sinkhorn_repeat=sinkhorn_repeat,
|
||||
norm_eps=norm_eps,
|
||||
hc_mult=hc_mult,
|
||||
use_pre_mix_in=pre_mix is not None,
|
||||
save_pre_mix=True,
|
||||
rms_numel=input_size,
|
||||
write_aux=capture_aux,
|
||||
)
|
||||
return outputs
|
||||
mhc_pre_big_fuse_tilelang(
|
||||
mixes,
|
||||
sqrsum,
|
||||
hc_scale,
|
||||
hc_base,
|
||||
residual_cur,
|
||||
post,
|
||||
comb,
|
||||
layer_input,
|
||||
pre_mix if pre_mix is not None else post,
|
||||
next_pre_mix,
|
||||
aux if capture_aux else layer_input,
|
||||
hidden_size,
|
||||
rms_eps,
|
||||
hc_pre_eps,
|
||||
hc_sinkhorn_eps,
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
mixes.shape[0],
|
||||
hc_mult,
|
||||
use_pre_mix_in=pre_mix is not None,
|
||||
save_pre_mix=True,
|
||||
rms_numel=input_size,
|
||||
write_aux=capture_aux,
|
||||
)
|
||||
return outputs
|
||||
|
||||
|
||||
def _mhc_fused_post_pre_delayed_tilelang_fake(
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
post_layer_mix: torch.Tensor,
|
||||
comb_res_mix: torch.Tensor,
|
||||
fn: torch.Tensor,
|
||||
hc_scale: torch.Tensor,
|
||||
hc_base: torch.Tensor,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
hc_sinkhorn_eps: float,
|
||||
hc_post_mult_value: float,
|
||||
sinkhorn_repeat: int,
|
||||
pre_mix: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
capture_aux: bool = False,
|
||||
) -> tuple[
|
||||
torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor
|
||||
]:
|
||||
num_tokens, hc_mult, hidden_size = residual.shape
|
||||
return (
|
||||
torch.empty_like(residual),
|
||||
torch.empty(
|
||||
num_tokens, hc_mult, 1, dtype=torch.float32, device=residual.device
|
||||
),
|
||||
torch.empty(
|
||||
num_tokens, hc_mult, hc_mult, dtype=torch.float32, device=residual.device
|
||||
),
|
||||
torch.empty(
|
||||
num_tokens, hidden_size, dtype=torch.bfloat16, device=residual.device
|
||||
),
|
||||
torch.empty(num_tokens, hc_mult, dtype=torch.float32, device=residual.device),
|
||||
torch.empty(
|
||||
num_tokens if capture_aux else 0,
|
||||
hidden_size,
|
||||
dtype=torch.bfloat16,
|
||||
device=residual.device,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def mhc_pre_tilelang(
|
||||
residual: torch.Tensor,
|
||||
fn: torch.Tensor,
|
||||
@@ -574,6 +848,7 @@ def mhc_fused_post_pre_tilelang(
|
||||
_MHC_FUSED_TILELANG_KERNEL,
|
||||
_MHC_POST_TILELANG_KERNEL,
|
||||
_MHC_PRE_BIG_FUSE_TILELANG_KERNEL,
|
||||
mhc_fused_post_pre_split_config,
|
||||
)
|
||||
|
||||
assert residual.dtype == torch.bfloat16
|
||||
@@ -614,7 +889,7 @@ def mhc_fused_post_pre_tilelang(
|
||||
post_layer_mix_flat = post_layer_mix.view(num_tokens, hc_mult)
|
||||
comb_res_mix_flat = comb_res_mix.view(num_tokens, hc_mult, hc_mult)
|
||||
|
||||
use_small_fma = num_tokens <= 16
|
||||
fused_config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
|
||||
post_mix_cur = torch.empty(
|
||||
num_tokens,
|
||||
@@ -635,7 +910,7 @@ def mhc_fused_post_pre_tilelang(
|
||||
device=residual.device,
|
||||
)
|
||||
|
||||
if use_small_fma:
|
||||
if fused_config is not None:
|
||||
gemm_out_mul, gemm_out_sqrsum, residual_cur = _MHC_FUSED_TILELANG_KERNEL(
|
||||
comb_res_mix_flat,
|
||||
residual_flat,
|
||||
@@ -815,6 +1090,12 @@ direct_register_custom_op(
|
||||
mutates_args=[],
|
||||
fake_impl=_mhc_pre_delayed_tilelang_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="mhc_fused_post_pre_delayed_tilelang",
|
||||
op_func=mhc_fused_post_pre_delayed_tilelang,
|
||||
mutates_args=[],
|
||||
fake_impl=_mhc_fused_post_pre_delayed_tilelang_fake,
|
||||
)
|
||||
direct_register_custom_op(
|
||||
op_name="mhc_pre_tilelang",
|
||||
op_func=mhc_pre_tilelang,
|
||||
|
||||
@@ -37,8 +37,67 @@ def compute_num_split(block_k: int, k: int | None, grid_size: int) -> int:
|
||||
return split_k
|
||||
|
||||
|
||||
def _mhc_fused_n_splits(num_tokens: int, hidden_size: int) -> int:
|
||||
return 8 if num_tokens < 8 and hidden_size <= 4096 else 4
|
||||
# ``mhc_fused_tilelang`` splits the hidden size across a fixed thread block, so
|
||||
# every (tile_n, n_thr) pair is one more kernel to compile. Tuned on GB300
|
||||
# (hc_mult 4, hidden_size 5120 and 7168) against the separate post + split-k
|
||||
# GEMM it replaces; the bands are coarse because the loss against a per-shape
|
||||
# optimum is ~1-2%, while one fixed config gives up to 18% at the top of the
|
||||
# range.
|
||||
_FUSED_POST_PRE_N_THR = 128
|
||||
_FUSED_POST_PRE_MAX_TOKENS = 32
|
||||
|
||||
|
||||
def mhc_fused_post_pre_split_config(
|
||||
num_tokens: int, hidden_size: int, hc_mult: int
|
||||
) -> tuple[int, int, int] | None:
|
||||
"""Pick ``(tile_n, n_splits, n_thr)`` for the fused post + pre-norm GEMM.
|
||||
|
||||
Returns None when a separate post kernel followed by a split-k GEMM is the
|
||||
better choice, or when the hidden size does not divide evenly across the
|
||||
fused kernel's block. One source of truth for the dispatch decision, the
|
||||
compile key and the launch, which must agree.
|
||||
"""
|
||||
if num_tokens > _FUSED_POST_PRE_MAX_TOKENS:
|
||||
return None
|
||||
n_thr = _FUSED_POST_PRE_N_THR
|
||||
if hidden_size % n_thr:
|
||||
return None
|
||||
# The projection tiles supply the parallelism a small token count cannot,
|
||||
# so the tile grows with the batch: 1.3x at one token and 1.03x at 32
|
||||
# against a split-k GEMM given the split its own estimator computes.
|
||||
if num_tokens < 16:
|
||||
tile_n, n_splits = 2, 8
|
||||
else:
|
||||
tile_n, n_splits = 6, 8
|
||||
# The kernel drops projection tiles and k-slices it cannot fill evenly.
|
||||
mix_size = hc_mult * (hc_mult + 2)
|
||||
while tile_n > 1 and mix_size % tile_n:
|
||||
tile_n -= 1
|
||||
while n_splits > 1 and hidden_size % (n_splits * n_thr):
|
||||
n_splits //= 2
|
||||
return tile_n, n_splits, n_thr
|
||||
|
||||
|
||||
def require_fused_post_pre_config(
|
||||
num_tokens: int, hidden_size: int, hc_mult: int
|
||||
) -> tuple[int, int, int]:
|
||||
"""The config for a shape the caller has already committed to fusing."""
|
||||
config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
if config is None:
|
||||
raise ValueError(
|
||||
"the fused mHC post + pre-norm GEMM does not cover num_tokens="
|
||||
f"{num_tokens} at hidden_size={hidden_size}"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def mhc_fused_post_pre_splits(hidden_size: int, hc_mult: int) -> tuple[int, ...]:
|
||||
"""Every split-k factor the fused post + pre-norm GEMM path can pick."""
|
||||
configs = (
|
||||
mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
for num_tokens in range(1, _FUSED_POST_PRE_MAX_TOKENS + 1)
|
||||
)
|
||||
return tuple(sorted({config[1] for config in configs if config is not None}))
|
||||
|
||||
|
||||
@tilelang_jit
|
||||
@@ -53,6 +112,7 @@ def mhc_pre_big_fuse_tilelang(
|
||||
layer_input,
|
||||
pre_mix_in,
|
||||
pre_mix_out,
|
||||
aux_out,
|
||||
hidden_size: int,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
@@ -64,6 +124,7 @@ def mhc_pre_big_fuse_tilelang(
|
||||
use_pre_mix_in: bool = False,
|
||||
save_pre_mix: bool = False,
|
||||
rms_numel: int = 0,
|
||||
write_aux: bool = False,
|
||||
):
|
||||
"""Fuse coefficient generation and residual collapse after the projection.
|
||||
|
||||
@@ -88,6 +149,7 @@ def mhc_pre_big_fuse_tilelang(
|
||||
|
||||
pre_mix_in: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
pre_mix_out: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
aux_out: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type]
|
||||
|
||||
with T.Kernel(num_tokens, threads=96) as i:
|
||||
if ENABLE_PDL:
|
||||
@@ -188,11 +250,24 @@ def mhc_pre_big_fuse_tilelang(
|
||||
|
||||
ol = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(ol)
|
||||
if write_aux:
|
||||
# Aux consumers (draft models) take the plain stream mean
|
||||
# of the same residual this collapse reads.
|
||||
aux = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(aux)
|
||||
|
||||
for i_hc in T.serial(hc_mult):
|
||||
pre = pre_mix_shared[i_hc]
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
ol[i1_h] += pre * xl[i_hc, i1_h]
|
||||
if write_aux:
|
||||
aux[i1_h] += xl[i_hc, i1_h]
|
||||
|
||||
if write_aux:
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
aux_out[i, i0_h * hidden_block + i1_h] = T.bfloat16(
|
||||
aux[i1_h] / hc_mult
|
||||
)
|
||||
|
||||
T.copy(ol, layer_input[i, i0_h * hidden_block])
|
||||
|
||||
@@ -216,6 +291,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
norm_weight,
|
||||
pre_mix_in,
|
||||
pre_mix_out,
|
||||
aux_out,
|
||||
hidden_size: int,
|
||||
rms_eps: float,
|
||||
hc_pre_eps: float,
|
||||
@@ -229,6 +305,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
use_pre_mix_in: bool = False,
|
||||
save_pre_mix: bool = False,
|
||||
rms_numel: int = 0,
|
||||
write_aux: bool = False,
|
||||
):
|
||||
num_tokens = T.dynamic("num_tokens")
|
||||
hc_mult3 = hc_mult * (2 + hc_mult)
|
||||
@@ -250,6 +327,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
|
||||
pre_mix_in: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
pre_mix_out: T.Tensor[[num_tokens, hc_mult], T.float32] # type: ignore[no-redef, valid-type]
|
||||
aux_out: T.Tensor[[num_tokens, hidden_size], T.bfloat16] # type: ignore[no-redef, valid-type]
|
||||
|
||||
with T.Kernel(num_tokens, threads=96) as i:
|
||||
rms = T.alloc_fragment(1, T.float32)
|
||||
@@ -345,11 +423,24 @@ def mhc_pre_big_fuse_with_norm_tilelang(
|
||||
|
||||
ol = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(ol)
|
||||
if write_aux:
|
||||
# Aux consumers (draft models) take the plain stream mean
|
||||
# of the same residual this collapse reads.
|
||||
aux = T.alloc_fragment(hidden_block, T.float32)
|
||||
T.clear(aux)
|
||||
|
||||
for i_hc in T.serial(hc_mult):
|
||||
pre = pre_mix_shared[i_hc]
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
ol[i1_h] += pre * xl[i_hc, i1_h]
|
||||
if write_aux:
|
||||
aux[i1_h] += xl[i_hc, i1_h]
|
||||
|
||||
if write_aux:
|
||||
for i1_h in T.Parallel(hidden_block):
|
||||
aux_out[i, i0_h * hidden_block + i1_h] = T.bfloat16(
|
||||
aux[i1_h] / hc_mult
|
||||
)
|
||||
|
||||
if save_pre_mix:
|
||||
# Keep the BF16 boundary before the delayed input RMSNorm.
|
||||
@@ -1211,9 +1302,17 @@ class MhcPreBigFuseTileLangKernel(
|
||||
middle_args = (residual_out, *output_args, norm_weight)
|
||||
elif compile_key.use_norm_weight:
|
||||
assert norm_weight is not None
|
||||
middle_args = (*output_args, norm_weight, post_mix, post_mix)
|
||||
# layer_input stands in for the aux buffer on both epilogues: same
|
||||
# shape and dtype, and write_aux is off here so it is never written.
|
||||
middle_args = (
|
||||
*output_args,
|
||||
norm_weight,
|
||||
post_mix,
|
||||
post_mix,
|
||||
layer_input,
|
||||
)
|
||||
else:
|
||||
middle_args = (*output_args, post_mix, post_mix)
|
||||
middle_args = (*output_args, post_mix, post_mix, layer_input)
|
||||
norm_eps_args = (compile_key.norm_eps,) if compile_key.use_norm_weight else ()
|
||||
return (
|
||||
*common_args,
|
||||
@@ -1247,8 +1346,14 @@ class MhcPreBigFuseTileLangKernel(
|
||||
if use_pre_gemm_splits
|
||||
else n_splits
|
||||
)
|
||||
fused_n_splits = _mhc_fused_n_splits(num_tokens, hidden_size)
|
||||
actual_n_splits = fused_n_splits if use_fused_tilelang else pre_gemm_n_splits
|
||||
# The epilogue reduces over whatever the fused kernel split the GEMM
|
||||
# into, so both have to read the same config.
|
||||
fused_config = mhc_fused_post_pre_split_config(num_tokens, hidden_size, hc_mult)
|
||||
actual_n_splits = (
|
||||
fused_config[1]
|
||||
if use_fused_tilelang and fused_config is not None
|
||||
else pre_gemm_n_splits
|
||||
)
|
||||
actual_norm_eps = broadcast_norm_eps if is_broadcast else norm_eps
|
||||
actual_use_norm_weight = use_norm_weight or is_broadcast
|
||||
return self.CompileKey(
|
||||
@@ -1540,6 +1645,7 @@ class MhcFusedTileLangKernel(
|
||||
hc_mult: int
|
||||
n_splits: int
|
||||
tile_n: int
|
||||
n_thr: int
|
||||
|
||||
@staticmethod
|
||||
def kernel() -> Any:
|
||||
@@ -1552,14 +1658,15 @@ class MhcFusedTileLangKernel(
|
||||
hidden_size: int,
|
||||
hc_mult: int,
|
||||
) -> CompileKey:
|
||||
# TODO(gnovack): investigate autotuning these heuristics
|
||||
tile_n = 2 if num_tokens < 8 else 3
|
||||
n_splits = _mhc_fused_n_splits(num_tokens, hidden_size)
|
||||
# Subscripts rather than an unpack: the warmup tracer parses this body
|
||||
# and allows only plain assignments before the return.
|
||||
config = require_fused_post_pre_config(num_tokens, hidden_size, hc_mult)
|
||||
return self.CompileKey(
|
||||
hidden_size=hidden_size,
|
||||
hc_mult=hc_mult,
|
||||
n_splits=n_splits,
|
||||
tile_n=tile_n,
|
||||
n_splits=config[1],
|
||||
tile_n=config[0],
|
||||
n_thr=config[2],
|
||||
)
|
||||
|
||||
def get_warmup_keys(
|
||||
@@ -1574,11 +1681,11 @@ class MhcFusedTileLangKernel(
|
||||
num_tokens=WarmupIntRange(1, max_tokens + 1),
|
||||
hidden_size=hidden_size,
|
||||
hc_mult=hc_mult,
|
||||
_when=lambda *, num_tokens: num_tokens <= 16,
|
||||
_when=lambda *, num_tokens: num_tokens <= _FUSED_POST_PRE_MAX_TOKENS,
|
||||
)
|
||||
|
||||
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
|
||||
num_tokens = 1 if compile_key.tile_n == 2 else 8
|
||||
num_tokens = 1 if compile_key.tile_n == 2 else 16
|
||||
hidden_size = compile_key.hidden_size
|
||||
hc_mult = compile_key.hc_mult
|
||||
hc_mult3 = hc_mult * (2 + hc_mult)
|
||||
@@ -1617,8 +1724,9 @@ class MhcFusedTileLangKernel(
|
||||
hc_mult3: int,
|
||||
) -> TileLangLaunchSpec:
|
||||
num_tokens = residual_in.shape[0]
|
||||
tile_n = 2 if num_tokens < 8 else 3
|
||||
n_splits = _mhc_fused_n_splits(num_tokens, hidden_size)
|
||||
tile_n, n_splits, n_thr = require_fused_post_pre_config(
|
||||
num_tokens, hidden_size, hc_mult
|
||||
)
|
||||
yp_out = residual_in.new_empty(
|
||||
(n_splits, num_tokens, hc_mult3), dtype=torch.float32
|
||||
)
|
||||
@@ -1639,7 +1747,7 @@ class MhcFusedTileLangKernel(
|
||||
hidden_size,
|
||||
hc_mult3,
|
||||
),
|
||||
dict(tile_n=tile_n, split_k=n_splits),
|
||||
dict(n_thr=n_thr, tile_n=tile_n),
|
||||
(yp_out, rp_out, residual_out),
|
||||
)
|
||||
|
||||
|
||||
@@ -36,23 +36,33 @@ class MHCPreNormKernel(VllmJitKernel["MHCPreNormKernel.CompileKey"]):
|
||||
use_pre_mix_in: bool
|
||||
rms_numel: int
|
||||
save_pre_mix: bool = True
|
||||
write_aux: bool = False
|
||||
|
||||
kernel: Any = staticmethod(mhc_pre_big_fuse_with_norm_tilelang)
|
||||
|
||||
def dispatch(self, *, n_splits, **fields) -> CompileKey: # type: ignore[override]
|
||||
return self.CompileKey(n_splits=n_splits, **fields)
|
||||
|
||||
def get_warmup_keys(self, *, max_tokens: int, **fields) -> list[CompileKey]:
|
||||
# The split heuristic changes only at 64-token boundaries.
|
||||
splits = (
|
||||
sorted(
|
||||
def get_warmup_keys(
|
||||
self,
|
||||
*,
|
||||
max_tokens: int,
|
||||
extra_splits: Iterable[int] = (),
|
||||
**fields,
|
||||
) -> list[CompileKey]:
|
||||
# The split heuristic changes only at 64-token boundaries. Callers that
|
||||
# reach this kernel through another GEMM (the fused post + pre-norm
|
||||
# GEMM) pass the splits that GEMM picks in extra_splits.
|
||||
splits = sorted(
|
||||
set(extra_splits)
|
||||
| (
|
||||
{
|
||||
compute_mhc_pre_num_splits(fields["rms_numel"], num_tokens)
|
||||
for num_tokens in range(1, max_tokens + 1, 64)
|
||||
}
|
||||
if is_deep_gemm_supported()
|
||||
else {1}
|
||||
)
|
||||
if is_deep_gemm_supported()
|
||||
else [1]
|
||||
)
|
||||
return self._trace_dispatch(self.dispatch)(n_splits=splits, **fields)
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm import ir
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.custom_op import CustomOp
|
||||
from vllm.platforms import CpuArchEnum, current_platform
|
||||
@@ -332,24 +333,11 @@ class GeluAndMulSparse(CustomOp):
|
||||
raise ValueError("activation_sparsity is 0.0. Please use GeluAndMul.")
|
||||
target_sparsity_tensor = torch.tensor(activation_sparsity, dtype=torch.float32)
|
||||
normal_dist = torch.distributions.normal.Normal(0, 1)
|
||||
self.std_multiplier = normal_dist.icdf(target_sparsity_tensor)
|
||||
|
||||
def _gaussian_topk(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""Get % sparse percentile of the Gaussian distribution."""
|
||||
# NOTE(rob): for TP>1, we could all-gather to get the means/std.
|
||||
# But we do not do this because in expectation they are the same
|
||||
# and in practice the eval scores are good without gathering.
|
||||
mean = torch.mean(x, dim=-1, keepdim=True)
|
||||
std = torch.std(x, dim=-1, keepdim=True, unbiased=False)
|
||||
cutoff_x = mean + std * self.std_multiplier
|
||||
return nn.functional.relu(x - cutoff_x)
|
||||
self.std_multiplier = normal_dist.icdf(target_sparsity_tensor).item()
|
||||
|
||||
def forward_native(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""PyTorch-native implementation equivalent to forward()."""
|
||||
d = x.shape[-1] // 2
|
||||
out = self._gaussian_topk(x[..., :d])
|
||||
out = F.gelu(out, approximate=self.approximate)
|
||||
return out * x[..., d:]
|
||||
return ir.ops.gelu_and_mul_sparse(x, self.std_multiplier, self.approximate)
|
||||
|
||||
def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
@@ -269,11 +269,11 @@ from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_encode_layer_name,
|
||||
_resolve_layer_name,
|
||||
async_tensor_h2d,
|
||||
direct_register_custom_op,
|
||||
get_dtype_size,
|
||||
is_quantized_kv_cache,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
np_to_pinned_tensor,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
@@ -1980,11 +1980,6 @@ def plan_mla_context_chunks(
|
||||
return plans
|
||||
|
||||
|
||||
def _flat_int32(values: list[int] | np.ndarray) -> torch.Tensor:
|
||||
"""Pinned int32 CPU tensor backing one concatenated per-chunk field."""
|
||||
return np_to_pinned_tensor(np.asarray(values, dtype=np.int32))
|
||||
|
||||
|
||||
def align_mla_chunked_context_workspace_size(
|
||||
vllm_config: VllmConfig,
|
||||
workspace_size: int,
|
||||
@@ -2161,24 +2156,28 @@ def build_mla_chunked_context_metadata(
|
||||
token_offset += num_tokens
|
||||
local_token_offset += num_local_tokens
|
||||
|
||||
seq_lens_cpu = _flat_int32(seq_lens_flat)
|
||||
starts_and_context_lens = _flat_int32(starts_flat + context_lens).to(
|
||||
device, non_blocking=True
|
||||
seq_lens_cpu = torch.tensor(
|
||||
seq_lens_flat, dtype=torch.int32, device="cpu", pin_memory=PIN_MEMORY
|
||||
)
|
||||
starts_and_context_lens = async_tensor_h2d(
|
||||
starts_flat + context_lens, device=device, dtype=torch.int32
|
||||
)
|
||||
starts = starts_and_context_lens[: len(starts_flat)]
|
||||
context_lens_gpu = starts_and_context_lens[len(starts_flat) :]
|
||||
cu_seq_lens = _flat_int32(cu_seq_lens_flat).to(device, non_blocking=True)
|
||||
cu_seqlens_q = _flat_int32(cu_seqlens_q_flat).to(device, non_blocking=True)
|
||||
token_to_seq = _flat_int32(np.concatenate(token_to_seq_parts)).to(
|
||||
device, non_blocking=True
|
||||
cu_seq_lens = async_tensor_h2d(cu_seq_lens_flat, device=device, dtype=torch.int32)
|
||||
cu_seqlens_q = async_tensor_h2d(cu_seqlens_q_flat, device=device, dtype=torch.int32)
|
||||
token_to_seq = async_tensor_h2d(
|
||||
np.concatenate(token_to_seq_parts), device=device, dtype=torch.int32
|
||||
)
|
||||
if use_dcp:
|
||||
padded_local_cu_seq_lens = _flat_int32(padded_local_cu_seq_lens_flat).to(
|
||||
device, non_blocking=True
|
||||
padded_local_cu_seq_lens = async_tensor_h2d(
|
||||
padded_local_cu_seq_lens_flat, device=device, dtype=torch.int32
|
||||
)
|
||||
padded_local_token_to_seq = async_tensor_h2d(
|
||||
np.concatenate(padded_local_token_to_seq_parts),
|
||||
device=device,
|
||||
dtype=torch.int32,
|
||||
)
|
||||
padded_local_token_to_seq = _flat_int32(
|
||||
np.concatenate(padded_local_token_to_seq_parts)
|
||||
).to(device, non_blocking=True)
|
||||
|
||||
chunks: list[MLACommonPrefillMetadata.ContextChunk] = []
|
||||
for index, (plan, layout) in enumerate(zip(plans, layouts)):
|
||||
@@ -2871,6 +2870,10 @@ class MLACommonBaseImpl(MLAAttentionImpl[A], Generic[A]):
|
||||
Returns:
|
||||
Tensor of shape [..., nope_dim + pe_dim]
|
||||
"""
|
||||
if k_pe.shape[-1] == 0:
|
||||
# NoPE MLA: nothing to append, so no copy either.
|
||||
return k_nope
|
||||
|
||||
k = torch.empty(
|
||||
(*k_nope.shape[:-1], k_nope.shape[-1] + k_pe.shape[-1]),
|
||||
dtype=k_nope.dtype,
|
||||
|
||||
@@ -111,6 +111,8 @@ def _is_masked_mha_available(
|
||||
if model_dims not in (
|
||||
(128, 512, 128, 64, 128),
|
||||
(64, 512, 192, 64, 256),
|
||||
# GLM-5.3-Flash: NoPE, qk_head_dim 256 == the (192, 64, 256) kernel.
|
||||
(64, 512, 256, 0, 256),
|
||||
):
|
||||
return False
|
||||
qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
||||
|
||||
@@ -152,8 +152,6 @@ class StaticSinkAttention(Attention, CustomOp):
|
||||
attn_backend=attn_backend,
|
||||
**kwargs,
|
||||
)
|
||||
CustomOp.__init__(self)
|
||||
|
||||
self.sink_len = sink_len
|
||||
self.sink_populated = False
|
||||
self.sink_key = None
|
||||
|
||||
@@ -468,6 +468,7 @@ class CPUExpertsFp8(mk.FusedMoEExpertsModular):
|
||||
RoutingMethodType.Renormalize,
|
||||
RoutingMethodType.RenormalizeNaive,
|
||||
RoutingMethodType.DeepseekV4,
|
||||
RoutingMethodType.DeepSeekV3,
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -385,14 +385,10 @@ def rocm_aiter_fused_experts(
|
||||
|
||||
gate_mode = ""
|
||||
if activation == MoEActivation.SITU:
|
||||
# a8w4 (VLLM_ROCM_USE_AITER_MOE_SITUV2_A8W4=1) uses the gate/up-
|
||||
# interleaved (_gui_) fp8 flydsl kernels; default a16w4 SiTU stays
|
||||
# separated.
|
||||
gate_mode = (
|
||||
GateMode.INTERLEAVE.value
|
||||
if rocm_aiter_ops.is_fused_moe_situv2_a8w4_enabled()
|
||||
else GateMode.SEPARATED.value
|
||||
)
|
||||
# SiTUv2 flydsl (VLLM_ROCM_USE_AITER_MOE_SITUV2=1) uses a4w4
|
||||
# fp4 activations with separated gate/up weights (AITER #4463);
|
||||
# default a16w4 SiTU also stays separated.
|
||||
gate_mode = GateMode.SEPARATED.value
|
||||
elif quant_config.use_mxfp4_w4a16:
|
||||
gate_mode = GateMode.INTERLEAVE.value
|
||||
elif activation_interleave is not None:
|
||||
|
||||
@@ -1572,12 +1572,6 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
if w2_bias is not None:
|
||||
w2_bias = w2_bias.data.to(torch.float32)
|
||||
|
||||
import os
|
||||
|
||||
# TODO: Remove this once AITER is fixed
|
||||
# Necessary for AITER side from crashing
|
||||
os.environ["AITER_BF16_FP8_MOE_BOUND"] = "0"
|
||||
|
||||
if activation == MoEActivation.SITU:
|
||||
from aiter.utility.fp4_utils import e8m0_shuffle
|
||||
|
||||
@@ -1585,9 +1579,8 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
|
||||
fp4_dtype = torch.float4_e2m1fn_x2
|
||||
e8m0_dtype = torch.float8_e8m0fnu
|
||||
# a8w4 uses gate/up-interleaved flydsl kernels;
|
||||
# default a16w4 keeps the separated layout.
|
||||
guinterleave = rocm_aiter_ops.is_fused_moe_situv2_a8w4_enabled()
|
||||
# SiTUv2 flydsl uses separated gate/up layout (a4w4).
|
||||
guinterleave = False
|
||||
w13 = rocm_aiter_ops.shuffle_weight_a16w4(
|
||||
w13_weight.data.view(fp4_dtype), 16, guinterleave
|
||||
)
|
||||
@@ -1606,6 +1599,14 @@ def convert_weight_to_mxfp4_moe_kernel_format(
|
||||
w2.is_shuffled = True
|
||||
return (w13, w2, w13_scale, w2_scale, w13_bias, w2_bias)
|
||||
|
||||
import os
|
||||
|
||||
# Interleaved a16w4 only (DeepSeekV4 etc.). AITER uses this bound to
|
||||
# pick bf16 vs fp8 activations when gate_mode is INTERLEAVE. SiTUv2
|
||||
# a4w4 is separated and selects q_dtype_a independently, so the bound
|
||||
# is unused on that path.
|
||||
os.environ["AITER_BF16_FP8_MOE_BOUND"] = "0"
|
||||
|
||||
from aiter.ops.shuffle import shuffle_scale as _shuf_s
|
||||
from aiter.ops.shuffle import shuffle_weight as _shuf_w
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import round_up
|
||||
from vllm.v1.worker.ubatching import (
|
||||
dbo_current_ubatch_id,
|
||||
dbo_enabled,
|
||||
)
|
||||
|
||||
|
||||
@@ -89,8 +90,10 @@ class DeepEPV2PrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
|
||||
use cudagraphs anyway
|
||||
- Provides expert_tokens_meta for efficient batched expert kernels
|
||||
|
||||
Both modes use async_with_compute_stream=False (synchronous from
|
||||
caller's perspective). The ElasticBuffer handles comm internally.
|
||||
Dispatch always uses async_with_compute_stream=False. finalize_async
|
||||
issues the combine with async_with_compute_stream=True (except under
|
||||
DBO) so the modular kernel can overlap the shared-expert FFN with the
|
||||
combine a2a; the returned receiver joins via a device-side event wait.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -465,15 +468,31 @@ class DeepEPV2PrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
|
||||
f"got {fused_expert_output.dtype}"
|
||||
)
|
||||
|
||||
# DBO drives its own hook/receiver schedule; keep the combine
|
||||
# synchronous there (the receiver then only performs the copy).
|
||||
combine_async = do_async and not dbo_enabled()
|
||||
combined_x, _, event = self.buffer.combine(
|
||||
x=fused_expert_output,
|
||||
handle=handle,
|
||||
topk_weights=None,
|
||||
async_with_compute_stream=False,
|
||||
async_with_compute_stream=combine_async,
|
||||
allocate_on_comm_stream=combine_async,
|
||||
)
|
||||
|
||||
output.copy_(combined_x, non_blocking=True)
|
||||
return None
|
||||
if do_async:
|
||||
# The combine ran on DeepEP's comm stream; the modular kernel
|
||||
# issues the shared-expert FFN before calling the receiver, which
|
||||
# joins via a device-side cudaStreamWaitEvent (no host sync, so
|
||||
# this is safe inside a captured region).
|
||||
def _receiver():
|
||||
if event.event is not None:
|
||||
event.current_stream_wait()
|
||||
output.copy_(combined_x, non_blocking=True)
|
||||
|
||||
return _receiver
|
||||
else:
|
||||
output.copy_(combined_x, non_blocking=True)
|
||||
return None
|
||||
|
||||
def finalize_async(
|
||||
self,
|
||||
@@ -484,16 +503,17 @@ class DeepEPV2PrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
|
||||
apply_router_weight_on_input: bool,
|
||||
weight_and_reduce_impl: mk.TopKWeightAndReduce,
|
||||
) -> Callable:
|
||||
self._finalize(
|
||||
receiver = self._finalize(
|
||||
output,
|
||||
fused_expert_output,
|
||||
topk_weights,
|
||||
topk_ids,
|
||||
apply_router_weight_on_input,
|
||||
weight_and_reduce_impl,
|
||||
False,
|
||||
True,
|
||||
)
|
||||
return lambda: None
|
||||
assert receiver is not None
|
||||
return receiver
|
||||
|
||||
def finalize(
|
||||
self,
|
||||
|
||||
@@ -457,9 +457,18 @@ class MoERunner(MoERunnerInterface):
|
||||
Latent MoE output transforms may contain non-linear ops, e.g. RMSNorm.
|
||||
TP partial routed outputs must be summed in latent space before such
|
||||
transforms are applied.
|
||||
|
||||
A transform that commutes with the TP sum is exempt: if
|
||||
``sum_r T(x_r) == T(sum_r x_r)``, applying the transform to the local
|
||||
partial output and letting the existing late all-reduce sum the
|
||||
combined result is equivalent, and costs one collective instead of two.
|
||||
Such a transform opts out by setting ``reduce_commutative = True``.
|
||||
The default is False, so transforms that do not declare themselves
|
||||
keep being reduced early.
|
||||
"""
|
||||
if (
|
||||
self.routed_output_transform is not None
|
||||
and not getattr(self.routed_output_transform, "reduce_commutative", False)
|
||||
and not self.moe_config.is_sequence_parallel
|
||||
and (self.moe_config.tp_size > 1 or self.moe_config.ep_size > 1)
|
||||
and not fused_output_is_reduced
|
||||
|
||||
@@ -5,21 +5,27 @@ Producer side of the QuantizedActivation contract for activation layers.
|
||||
|
||||
Given an activation module and the downstream linear it feeds, fuse the
|
||||
activation with that linear's input quantization into a single kernel when the
|
||||
linear advertises a consumable input_quant_key (see quant_activation.py).
|
||||
linear advertises a consumable input quantization key (see quant_activation.py).
|
||||
Falls back to the plain activation when nothing matches, so a model forward can
|
||||
always call maybe_fused_act_quant unconditionally.
|
||||
|
||||
This is the manual-fusion counterpart to ActivationQuantFusionPass: when fusion
|
||||
fires here the silu_and_mul pattern is already consumed, so the compiler pass
|
||||
finds nothing to rewrite and the two never double-fuse.
|
||||
fires here, the activation and quantization are already consumed, so a compiler
|
||||
pass cannot fuse the same boundary again.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.activation import SiluAndMul
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.activation import ReLUSquaredActivation, SiluAndMul
|
||||
from vllm.model_executor.layers.fusion.quant_activation import (
|
||||
QuantizedActivation,
|
||||
get_input_quant_key,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.relu2_fp8_quant import (
|
||||
relu_squared_static_fp8_quant,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
QuantKey,
|
||||
@@ -139,12 +145,46 @@ def _silu_and_mul_nvfp4_dynamic(
|
||||
)
|
||||
|
||||
|
||||
# (activation module type, consumer input_quant_key) -> fused producer.
|
||||
# Mirrors ActivationQuantFusionPass.FUSED_OPS; add a row to migrate a scheme.
|
||||
# (activation module type, consumer input quantization key) -> fused producer.
|
||||
# Add a row for each supported manual producer.
|
||||
_FUSED_ACT_QUANT: dict[tuple[type, QuantKey], Callable] = {
|
||||
(SiluAndMul, kFp8StaticTensorSym): _silu_and_mul_fp8_static,
|
||||
}
|
||||
|
||||
|
||||
def _relu_squared_static_fp8_quant_supported(
|
||||
act_fn: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
linear: LinearBase,
|
||||
) -> bool:
|
||||
"""Return whether the ReLU2 static-FP8 producer can consume this input."""
|
||||
scale = getattr(linear, "input_scale", None)
|
||||
return (
|
||||
isinstance(act_fn, ReLUSquaredActivation)
|
||||
and x.is_cuda
|
||||
and x.dtype == torch.bfloat16
|
||||
and x.is_contiguous()
|
||||
and isinstance(scale, torch.Tensor)
|
||||
and scale.dtype == torch.float32
|
||||
and scale.device == x.device
|
||||
and scale.numel() == 1
|
||||
)
|
||||
|
||||
|
||||
# Optional per-entry predicates preserve the unconditional fallback contract
|
||||
# for producers whose supported inputs are narrower than their registry key.
|
||||
_FUSED_ACT_QUANT_SUPPORT: dict[
|
||||
tuple[type, QuantKey], Callable[[torch.nn.Module, torch.Tensor, LinearBase], bool]
|
||||
] = {}
|
||||
|
||||
# This path is validated on SM90 and newer CUDA devices.
|
||||
if current_platform.is_cuda() and current_platform.has_device_capability(90):
|
||||
_RELU2_STATIC_FP8_KEY = (ReLUSquaredActivation, kFp8StaticTensorSym)
|
||||
_FUSED_ACT_QUANT[_RELU2_STATIC_FP8_KEY] = relu_squared_static_fp8_quant
|
||||
_FUSED_ACT_QUANT_SUPPORT[_RELU2_STATIC_FP8_KEY] = (
|
||||
_relu_squared_static_fp8_quant_supported
|
||||
)
|
||||
|
||||
# Add CUDA-specific entries for dynamic block quantization
|
||||
if current_platform.is_cuda_alike():
|
||||
_FUSED_ACT_QUANT[(SiluAndMul, kFp8Dynamic128Sym)] = _silu_and_mul_fp8_dynamic_128
|
||||
@@ -161,12 +201,14 @@ def maybe_fused_act_quant(
|
||||
) -> "torch.Tensor | QuantizedActivation":
|
||||
"""Apply act_fn, fusing the downstream linear's input quant when possible.
|
||||
|
||||
Returns a QuantizedActivation when a fused kernel matches
|
||||
(act_fn, linear.input_quant_key), else the plain activated tensor.
|
||||
Returns a QuantizedActivation when a fused kernel matches the activation and
|
||||
the consumer's effective input quantization key, else the plain activation.
|
||||
"""
|
||||
key = getattr(linear, "input_quant_key", None)
|
||||
key = get_input_quant_key(linear)
|
||||
if key is not None:
|
||||
producer = _FUSED_ACT_QUANT.get((type(act_fn), key))
|
||||
if producer is not None:
|
||||
registry_key = (type(act_fn), key)
|
||||
producer = _FUSED_ACT_QUANT.get(registry_key)
|
||||
support = _FUSED_ACT_QUANT_SUPPORT.get(registry_key)
|
||||
if producer is not None and (support is None or support(act_fn, x, linear)):
|
||||
return producer(x, linear)
|
||||
return act_fn(x)
|
||||
|
||||
@@ -5,7 +5,9 @@ A QuantizedActivation is a pre-quantized activation produced by a fused kernel
|
||||
and consumed directly by a linear layer, letting the layer skip its own input
|
||||
quantization. A linear advertises the key its kernel can consume via
|
||||
expose_input_quant_key; the kernel validates and reads the activation via
|
||||
as_quantized_activation.
|
||||
as_quantized_activation. Producers query the effective capability through
|
||||
get_input_quant_key, which hides the key when another consumer branch needs the
|
||||
original activation.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
@@ -46,12 +48,11 @@ class QuantizedActivation:
|
||||
|
||||
|
||||
def expose_input_quant_key(layer: torch.nn.Module, kernel) -> None:
|
||||
"""Advertise the kernel's pre-quantized input key on the layer, if any.
|
||||
"""Store the kernel's pre-quantized input key on the layer, if any.
|
||||
|
||||
This is the bridge from a kernel's input_quant_key() to the
|
||||
layer.input_quant_key attribute that fusion call sites read. The attribute
|
||||
is left unset when the kernel quantizes its own input, so non-supporting
|
||||
backends never receive a QuantizedActivation.
|
||||
This is the bridge from a kernel's input_quant_key() to the layer capability
|
||||
that fusion call sites read through get_input_quant_key. The raw key is left
|
||||
unset when the kernel quantizes its own input.
|
||||
|
||||
TODO(mgoin): Producers also need the consumer's quantization scales (e.g.
|
||||
static input scale, global scale). Expose those here as well so producers
|
||||
@@ -59,7 +60,14 @@ def expose_input_quant_key(layer: torch.nn.Module, kernel) -> None:
|
||||
"""
|
||||
key = kernel.input_quant_key()
|
||||
if key is not None:
|
||||
layer.input_quant_key = key
|
||||
layer._input_quant_key = key
|
||||
|
||||
|
||||
def get_input_quant_key(layer: torch.nn.Module) -> QuantKey | None:
|
||||
"""Return the pre-quantized input key the complete layer can consume."""
|
||||
if getattr(layer, "requires_unquantized_input", False):
|
||||
return None
|
||||
return getattr(layer, "_input_quant_key", None)
|
||||
|
||||
|
||||
def as_quantized_activation(
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
get_fp8_min_max,
|
||||
kFp8StaticTensorSym,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
_FP8_MIN, _FP8_MAX = get_fp8_min_max()
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _relu_squared_static_fp8_quant_kernel(
|
||||
x_ptr,
|
||||
scale_ptr,
|
||||
output_ptr,
|
||||
num_elements,
|
||||
FP8_MIN: tl.constexpr,
|
||||
FP8_MAX: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
offsets = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < num_elements
|
||||
x = tl.load(x_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
input_is_nan = x != x
|
||||
relu = tl.maximum(x, 0.0)
|
||||
# Preserve the standalone ReLU2 kernel's BF16 output boundary.
|
||||
activated = (relu * relu).to(tl.bfloat16).to(tl.float32)
|
||||
# Match O2's Inductor-compiled QuantFP8 reciprocal-then-multiply.
|
||||
quantized = activated * (1.0 / tl.load(scale_ptr))
|
||||
quantized = tl.maximum(tl.minimum(quantized, FP8_MAX), FP8_MIN)
|
||||
# Match the O2 native chain by preserving NaN through the FP8 conversion.
|
||||
quantized = tl.where(input_is_nan, x, quantized)
|
||||
tl.store(output_ptr + offsets, quantized, mask=mask)
|
||||
|
||||
|
||||
def relu_squared_static_fp8_quant(
|
||||
x: torch.Tensor, linear: LinearBase
|
||||
) -> QuantizedActivation:
|
||||
"""BF16 ReLU2 followed by static per-tensor FP8 quantization."""
|
||||
assert x.dtype == torch.bfloat16
|
||||
assert x.is_contiguous()
|
||||
scale = linear.input_scale
|
||||
assert scale.dtype == torch.float32
|
||||
assert x.device == scale.device
|
||||
assert scale.numel() == 1
|
||||
|
||||
output = torch.empty_like(x, dtype=current_platform.fp8_dtype())
|
||||
if x.numel() != 0:
|
||||
block_size = min(triton.next_power_of_2(x.shape[-1]), 2048)
|
||||
num_warps = min(max(block_size // 256, 1), 4)
|
||||
grid = lambda meta: (triton.cdiv(x.numel(), meta["BLOCK_SIZE"]),)
|
||||
_relu_squared_static_fp8_quant_kernel[grid](
|
||||
x,
|
||||
scale,
|
||||
output,
|
||||
x.numel(),
|
||||
FP8_MIN=_FP8_MIN,
|
||||
FP8_MAX=_FP8_MAX,
|
||||
BLOCK_SIZE=block_size,
|
||||
num_warps=num_warps,
|
||||
)
|
||||
|
||||
return QuantizedActivation(
|
||||
data=output,
|
||||
scale=scale,
|
||||
orig_dtype=x.dtype,
|
||||
orig_shape=x.shape,
|
||||
quant_key=kFp8StaticTensorSym,
|
||||
)
|
||||
@@ -20,9 +20,8 @@ Constraints:
|
||||
- x / residual must be bfloat16; hc_fn weights stay float32 (the checkpoint
|
||||
keeps them out of fp8 quantization via modules_to_not_convert)
|
||||
|
||||
The fused modules own no parameters: they hold references to the weights of the
|
||||
eager layer they replace, bound in ``process_weights_after_loading`` (invoked
|
||||
generically for every ``HpcModule`` by the model loader).
|
||||
The fused modules own no parameters: their forwards read the weights of the
|
||||
eager layer they replace directly via the captured owner reference.
|
||||
|
||||
NOTE: The reference implementation also offers a cross-layer post+pre fusion
|
||||
(``HpcIHCPostPre``) that folds one segment's post into the next segment's pre.
|
||||
@@ -147,41 +146,26 @@ class HpcIHCPre(HpcModule):
|
||||
object.__setattr__(self, "_fallback_op", fallback_op)
|
||||
# Same anti-cycle idiom for the fused RMSNorm owner (a sibling module).
|
||||
object.__setattr__(self, "_norm_owner", norm_owner)
|
||||
self.weight = None
|
||||
self.hc_scale = None
|
||||
self.hc_base = None
|
||||
self.rms_weight = None
|
||||
self.rms_eps = 0.0
|
||||
|
||||
@classmethod
|
||||
def support(cls, hc_mult: int, hidden_size: int) -> bool:
|
||||
return _ihc_supported(hc_mult, hidden_size)
|
||||
|
||||
def process_weights_after_loading(self, model=None):
|
||||
# hc_fn is a ReplicatedLinear whose weight is [2 * hc_mult, hc_mult * d].
|
||||
# It stays float32 -- the HPC kernel consumes fp32 weights directly, so
|
||||
# there is no conversion (and no precision loss) here.
|
||||
owner = self._fallback_op
|
||||
self.weight = owner.hc_fn.weight
|
||||
self.hc_scale = owner.hc_scale
|
||||
self.hc_base = owner.hc_base
|
||||
if self._norm_owner is not None:
|
||||
self.rms_weight = self._norm_owner.weight
|
||||
self.rms_eps = self._norm_owner.variance_epsilon
|
||||
|
||||
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import hpc
|
||||
|
||||
owner = self._fallback_op
|
||||
norm_owner = self._norm_owner
|
||||
return hpc.fuse_ihc_pre(
|
||||
x,
|
||||
self.weight,
|
||||
self.hc_scale,
|
||||
self.hc_base,
|
||||
owner.hc_fn.weight,
|
||||
owner.hc_scale,
|
||||
owner.hc_base,
|
||||
self.norm_eps,
|
||||
self.hc_eps,
|
||||
self.magnitude,
|
||||
self.rms_weight,
|
||||
self.rms_eps,
|
||||
norm_owner.weight if norm_owner is not None else None,
|
||||
norm_owner.variance_epsilon if norm_owner is not None else 0.0,
|
||||
)
|
||||
|
||||
|
||||
@@ -233,29 +217,20 @@ class HpcIHCHead(HpcModule):
|
||||
self.norm_eps = norm_eps
|
||||
# See HpcIHCPre: keep the owner out of the module tree.
|
||||
object.__setattr__(self, "_fallback_op", fallback_op)
|
||||
self.weight = None
|
||||
self.hc_scale = None
|
||||
self.hc_base = None
|
||||
|
||||
@classmethod
|
||||
def support(cls, hc_mult: int, hidden_size: int) -> bool:
|
||||
return _ihc_supported(hc_mult, hidden_size)
|
||||
|
||||
def process_weights_after_loading(self, model=None):
|
||||
# hc_head_fn weight is [hc_mult, hc_mult * d], float32.
|
||||
owner = self._fallback_op
|
||||
self.weight = owner.hc_head_fn.weight
|
||||
self.hc_scale = owner.hc_head_scale
|
||||
self.hc_base = owner.hc_head_base
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
import hpc
|
||||
|
||||
owner = self._fallback_op
|
||||
return hpc.fuse_ihc_head(
|
||||
x,
|
||||
self.weight,
|
||||
self.hc_scale,
|
||||
self.hc_base,
|
||||
owner.hc_head_fn.weight,
|
||||
owner.hc_head_scale,
|
||||
owner.hc_head_base,
|
||||
self.norm_eps,
|
||||
self.hc_eps,
|
||||
)
|
||||
|
||||
@@ -11,8 +11,5 @@ class HpcModule(nn.Module):
|
||||
def support(cls, *args, **kwargs):
|
||||
return True
|
||||
|
||||
def process_weights_after_loading(self, model):
|
||||
pass
|
||||
|
||||
def forward(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
@@ -90,13 +90,13 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
"""HPC fused RoPE + QK-Norm + KV-Cache-Write (+ optional FP8 Q quant).
|
||||
|
||||
Registered as a sub-module in model layers (e.g. HunYuanAttention).
|
||||
Norm weights are extracted from fallback norm modules via
|
||||
process_weights_after_loading() after all weights are loaded.
|
||||
The QK-Norm weights are read directly from the fallback norm modules
|
||||
(built in float32 when HPC is active), eliminating the derived copy.
|
||||
|
||||
forward() is dispatched by CustomOp framework:
|
||||
- In compiled mode: forward_cuda() calls torch.ops.vllm.hpc_rope_norm_forward
|
||||
as a splitting point — internal Python control flow is opaque
|
||||
to torch.compile and not captured by CUDA Graph.
|
||||
to torch.compile (its kernel launches can still be CUDA-graph captured).
|
||||
- In eager/native mode: forward_native() falls back to forward_cuda().
|
||||
"""
|
||||
|
||||
@@ -124,8 +124,6 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
self.num_kv_heads = num_kv_heads
|
||||
self.head_dim = head_dim
|
||||
|
||||
self.use_qk_norm = use_qk_norm
|
||||
|
||||
self.q_size = num_heads * head_dim
|
||||
self.kv_size = num_kv_heads * head_dim
|
||||
|
||||
@@ -139,31 +137,18 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
|
||||
self.head_per_group = num_heads // num_kv_heads
|
||||
|
||||
# Pre-allocate norm weight tensors as Parameters so they are tracked by
|
||||
# CuMemAllocator (for sleep/wake_up) and have stable addresses for CUDA
|
||||
# Graph replay. process_weights_after_loading() updates them inplace via
|
||||
# copy_() so refit does not invalidate captured graph tensor pointers.
|
||||
# Shape is [head_dim] to match the HPC kernel's q/k_norm_weight layout.
|
||||
if use_qk_norm and fallback_qnorm is not None:
|
||||
self.qnorm_weight: torch.nn.Parameter | None = torch.nn.Parameter(
|
||||
torch.empty(head_dim, dtype=torch.float32),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.qnorm_weight = None
|
||||
if use_qk_norm and fallback_knorm is not None:
|
||||
self.knorm_weight: torch.nn.Parameter | None = torch.nn.Parameter(
|
||||
torch.empty(head_dim, dtype=torch.float32),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.knorm_weight = None
|
||||
|
||||
self.use_fp8 = "fp8" in kv_cache_dtype
|
||||
# The RMSNorm/RoPE ordering is model dependent (e.g. HunYuan V3 applies
|
||||
# QK-Norm before RoPE -> NORM_THEN_ROPE), so it is supplied by the
|
||||
# caller. When QK-Norm is disabled the policy is forced to NONE.
|
||||
self.qk_norm_policy = qk_norm_policy if use_qk_norm else QkNormPolicy.NONE
|
||||
if self.qk_norm_policy != QkNormPolicy.NONE and (
|
||||
fallback_qnorm is None or fallback_knorm is None
|
||||
):
|
||||
raise ValueError(
|
||||
"QK-Norm is enabled but fallback_qnorm/fallback_knorm were not "
|
||||
"supplied; the fused kernel reads their weights directly."
|
||||
)
|
||||
|
||||
# Register layer_name + add self to the global instance registry so the
|
||||
# module-level custom op (hpc_rope_norm_forward) can route back here.
|
||||
@@ -215,20 +200,6 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
logger.info_once("enable hpc rope_norm")
|
||||
return True
|
||||
|
||||
def process_weights_after_loading(self, model: torch.nn.Module = None) -> None:
|
||||
"""Copy norm weights (float32) from fallback norm modules inplace.
|
||||
|
||||
Uses copy_() to preserve tensor addresses for CUDA Graph / refit
|
||||
compatibility. Called by the model's load_weights() after all weights
|
||||
are loaded (and generically from the model loader for DummyModelLoader
|
||||
/ sleep-wake_up reload paths).
|
||||
"""
|
||||
if self.use_qk_norm:
|
||||
if self.fallback_qnorm is not None and self.qnorm_weight is not None:
|
||||
self.qnorm_weight.data.copy_(self.fallback_qnorm.weight.data.float())
|
||||
if self.fallback_knorm is not None and self.knorm_weight is not None:
|
||||
self.knorm_weight.data.copy_(self.fallback_knorm.weight.data.float())
|
||||
|
||||
def register_layer_name(self, layer_name: str) -> None:
|
||||
"""Register layer_name and add self to the global registry.
|
||||
|
||||
@@ -430,12 +401,14 @@ class HpcRopeNorm(CustomOp, HpcModule):
|
||||
k_scale = attn_layer._k_scale.reshape(1)
|
||||
v_scale = attn_layer._v_scale.reshape(1)
|
||||
|
||||
q_norm_weight = (
|
||||
self.qnorm_weight if self.qk_norm_policy != QkNormPolicy.NONE else None
|
||||
)
|
||||
k_norm_weight = (
|
||||
self.knorm_weight if self.qk_norm_policy != QkNormPolicy.NONE else None
|
||||
)
|
||||
if self.qk_norm_policy != QkNormPolicy.NONE:
|
||||
assert self.fallback_qnorm is not None
|
||||
assert self.fallback_knorm is not None
|
||||
q_norm_weight = self.fallback_qnorm.weight
|
||||
k_norm_weight = self.fallback_knorm.weight
|
||||
else:
|
||||
q_norm_weight = None
|
||||
k_norm_weight = None
|
||||
|
||||
# --- Prefill ---
|
||||
if num_prefill_reqs > 0:
|
||||
|
||||
@@ -252,6 +252,8 @@ class LinearBase(PluggableLayer):
|
||||
disable_tp: If true, tensor parallelism will be disabled for this layer.
|
||||
"""
|
||||
|
||||
requires_unquantized_input = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_size: int,
|
||||
|
||||
@@ -8,7 +8,6 @@ auto-detected (Blackwell vs not) so call sites need not thread it through.
|
||||
"""
|
||||
|
||||
import functools
|
||||
from contextlib import contextmanager
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import triton
|
||||
@@ -26,20 +25,6 @@ def _is_blackwell() -> bool:
|
||||
_overrides: dict[str, tuple] = {}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def override_replayssm_config(kernel: str, config: tuple):
|
||||
"""Pin ``kernel``'s launch config for the duration of the context."""
|
||||
prev = _overrides.get(kernel)
|
||||
_overrides[kernel] = config
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if prev is None:
|
||||
_overrides.pop(kernel, None)
|
||||
else:
|
||||
_overrides[kernel] = prev
|
||||
|
||||
|
||||
def _dstate_tile(dstate: int, tile: int) -> int:
|
||||
return max(16, min(tile, triton.next_power_of_2(dstate)))
|
||||
|
||||
|
||||
@@ -299,7 +299,13 @@ class MHCPreDelayedOp(CustomOp):
|
||||
|
||||
Same gates as :class:`MHCPreOp`, but the stream collapse applies the
|
||||
caller's ``pre_mix`` and this sublayer's pre-mix is returned for the next
|
||||
sublayer seam. Returns post_mix, comb_mix, layer_input, next_pre_mix.
|
||||
sublayer seam.
|
||||
|
||||
Passing ``sublayer_out`` / ``post_layer_mix`` / ``comb_res_mix`` also
|
||||
applies the preceding post block, which lets AITER fold it into the pre
|
||||
projection and saves a launch. Returns residual, post_mix, comb_mix,
|
||||
layer_input, next_pre_mix; ``residual`` is the caller's own tensor when
|
||||
no post is requested.
|
||||
"""
|
||||
|
||||
# --8<-- [end:mhc_pre_delayed]
|
||||
@@ -307,6 +313,24 @@ class MHCPreDelayedOp(CustomOp):
|
||||
def enabled(cls) -> bool:
|
||||
return True
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
# Built here, not lazily: CustomOp resolves dispatch against the
|
||||
# current vLLM config, which is only set during model construction.
|
||||
self._post = MHCPostOp()
|
||||
|
||||
def _maybe_post(
|
||||
self,
|
||||
residual: torch.Tensor,
|
||||
sublayer_out: torch.Tensor | None,
|
||||
post_layer_mix: torch.Tensor | None,
|
||||
comb_res_mix: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
if sublayer_out is None:
|
||||
return residual
|
||||
assert post_layer_mix is not None and comb_res_mix is not None
|
||||
return self._post(sublayer_out, residual, post_layer_mix, comb_res_mix)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
residual: torch.Tensor,
|
||||
@@ -322,8 +346,14 @@ class MHCPreDelayedOp(CustomOp):
|
||||
x: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
return residual, *torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
residual,
|
||||
fn,
|
||||
hc_scale,
|
||||
@@ -354,7 +384,10 @@ class MHCPreDelayedOp(CustomOp):
|
||||
x: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
# The AITER delayed path drives mhc_pre_gemm_sqrsum against `residual`
|
||||
# and folds no RMSNorm, so it cannot serve the model-entry broadcast
|
||||
# (which projects a narrower `x`) or a fused norm. Both are handled by
|
||||
@@ -364,7 +397,26 @@ class MHCPreDelayedOp(CustomOp):
|
||||
and norm_weight is None
|
||||
and _aiter_mhc_supported(residual, None, supports_norm=False)
|
||||
):
|
||||
return torch.ops.vllm.mhc_pre_delayed_aiter(
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
num_tokens = residual.numel() // (residual.shape[-1] * residual.shape[-2])
|
||||
# Folding the post in only pays while the residual still fits in
|
||||
# cache; past that AITER's heuristic wants the separate kernels,
|
||||
# which can ask for a non-temporal store and a large-m split-k.
|
||||
if sublayer_out is not None and (
|
||||
rocm_aiter_ops.mhc_fused_post_pre_delayed_prefers_unfused(num_tokens)
|
||||
):
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
sublayer_out = None
|
||||
# The op writes the folded post's residual into this buffer rather
|
||||
# than returning it, since on the unfused path it has none of its
|
||||
# own and an op must not hand back one of its inputs.
|
||||
residual_out = (
|
||||
torch.empty_like(residual) if sublayer_out is not None else None
|
||||
)
|
||||
rest = torch.ops.vllm.mhc_pre_delayed_aiter(
|
||||
residual,
|
||||
fn,
|
||||
hc_scale,
|
||||
@@ -375,9 +427,17 @@ class MHCPreDelayedOp(CustomOp):
|
||||
hc_post_mult_value,
|
||||
sinkhorn_repeat,
|
||||
pre_mix,
|
||||
sublayer_out,
|
||||
post_layer_mix,
|
||||
comb_res_mix,
|
||||
residual_out,
|
||||
)
|
||||
return (residual if residual_out is None else residual_out), *rest
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
if HAS_TILELANG_MHC:
|
||||
return torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
return residual, *torch.ops.vllm.mhc_pre_delayed_tilelang(
|
||||
residual,
|
||||
fn,
|
||||
hc_scale,
|
||||
@@ -392,6 +452,7 @@ class MHCPreDelayedOp(CustomOp):
|
||||
norm_weight,
|
||||
norm_eps,
|
||||
)
|
||||
# The post is already applied, so it must not be requested again.
|
||||
return self.forward_native(
|
||||
residual,
|
||||
fn,
|
||||
@@ -423,7 +484,13 @@ class MHCPreDelayedOp(CustomOp):
|
||||
x: torch.Tensor | None = None,
|
||||
norm_weight: torch.Tensor | None = None,
|
||||
norm_eps: float = 1e-6,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
sublayer_out: torch.Tensor | None = None,
|
||||
post_layer_mix: torch.Tensor | None = None,
|
||||
comb_res_mix: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
residual = self._maybe_post(
|
||||
residual, sublayer_out, post_layer_mix, comb_res_mix
|
||||
)
|
||||
post_mix, comb_mix, layer_input, next_pre_mix = (
|
||||
mhc_kernels.mhc_pre_delayed_torch(
|
||||
residual,
|
||||
@@ -440,6 +507,7 @@ class MHCPreDelayedOp(CustomOp):
|
||||
)
|
||||
)
|
||||
return (
|
||||
residual,
|
||||
post_mix,
|
||||
comb_mix,
|
||||
_apply_mhc_norm(layer_input, norm_weight, norm_eps),
|
||||
|
||||
@@ -120,7 +120,7 @@ def get_quantization_config(quantization: str) -> type[QuantizationConfig]:
|
||||
# The v4.1 class is the v4 one extended to accept model_type
|
||||
# "deepseek_v41" and its 32x32 MXFP8 linear layout. V4.1 has
|
||||
# platform-specific implementations for both CUDA and ROCm.
|
||||
from vllm.models.deepseek_v4_1 import (
|
||||
from vllm.models.deepseek_v41 import (
|
||||
DeepseekV4FP8Config as DeepseekV41FP8Config,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Sparse Attention Indexer that scores only the candidate blocks.
|
||||
|
||||
DeepSeek V4.1 two-level selection: the candidate-source indexer publishes
|
||||
the top candidate blocks and later indexers pick their top-k inside them.
|
||||
`SparseAttnIndexer` does that by computing dense logits over the whole
|
||||
context and masking; this layer instead calls DeepGEMM's sparse MQA-logits
|
||||
kernels on the candidate blocks only, so the work is O(candidate blocks)
|
||||
instead of O(context). It requires the `DeepseekV41SparseIndexerBackend`
|
||||
metadata (see ``AttentionConfig.indexer_sparse_logits``).
|
||||
"""
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.model_executor.kernels.attention.dsa.sparse_mqa_logits import (
|
||||
has_deep_select,
|
||||
sparse_mqa_logits_paged_decode,
|
||||
sparse_mqa_logits_prefill_chunk,
|
||||
)
|
||||
from vllm.model_executor.layers.sparse_attn_indexer import (
|
||||
_gather_workspace_shapes,
|
||||
kv_cache_as_quant_view,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import has_deep_gemm_sparse_mqa
|
||||
from vllm.v1.attention.backends.mla.indexer import (
|
||||
DeepseekV32IndexerPrefillChunkMetadata,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_indexer import (
|
||||
DeepseekV41SparseIndexerMetadata,
|
||||
)
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
|
||||
def _prefill_k_workspaces(
|
||||
total_seq_lens: int, head_dim: int
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""The packed MXFP4 K-gather workspace ``(values, scales)``, shared with
|
||||
the dense indexer layers of the same model."""
|
||||
values_spec, scales_spec = _gather_workspace_shapes(
|
||||
total_seq_lens, head_dim, current_platform.fp8_dtype(), use_fp4_cache=True
|
||||
)
|
||||
k_quant, k_scale = current_workspace_manager().get_simultaneous(
|
||||
values_spec, scales_spec
|
||||
)
|
||||
return k_quant, k_scale
|
||||
|
||||
|
||||
def _gather_prefill_chunk_k(
|
||||
kv_cache: torch.Tensor,
|
||||
k_quant_full: torch.Tensor,
|
||||
k_scale_full: torch.Tensor,
|
||||
chunk: DeepseekV32IndexerPrefillChunkMetadata,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Gather one prefill chunk's paged K into the packed workspace."""
|
||||
assert chunk.local_cu_seq_lens is not None
|
||||
k_quant = k_quant_full[: chunk.max_local_total_seq_lens]
|
||||
k_scale = k_scale_full[: chunk.max_local_total_seq_lens]
|
||||
if not chunk.skip_kv_gather and chunk.local_total_seq_lens > 0:
|
||||
ops.cp_gather_indexer_k_quant_cache(
|
||||
kv_cache,
|
||||
k_quant,
|
||||
k_scale,
|
||||
chunk.block_table,
|
||||
chunk.local_cu_seq_lens,
|
||||
)
|
||||
return k_quant, k_scale
|
||||
|
||||
|
||||
class SparseMQAIndexer(nn.Module):
|
||||
"""Candidate-consuming indexer on DeepGEMM's sparse MQA-logits kernels.
|
||||
|
||||
Only valid for indexer layers that read candidate blocks with the MXFP4
|
||||
indexer cache on SM100. The K cache is written by the model before this
|
||||
runs; ``forward`` takes the same arguments as `SparseAttnIndexer` so the
|
||||
attention layer can call either.
|
||||
"""
|
||||
|
||||
weights_dtype = torch.bfloat16
|
||||
"""Per-head weights dtype the sparse kernels take. The fused Q RoPE-quant
|
||||
kernel writes it directly so no cast runs per step."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
k_cache,
|
||||
topk_tokens: int,
|
||||
head_dim: int,
|
||||
max_total_seq_len: int,
|
||||
topk_indices_buffer: torch.Tensor,
|
||||
candidate_blocks: torch.Tensor,
|
||||
candidate_block_size: int,
|
||||
):
|
||||
super().__init__()
|
||||
if not (
|
||||
current_platform.is_cuda()
|
||||
and current_platform.is_device_capability_family(100)
|
||||
and has_deep_gemm_sparse_mqa()
|
||||
):
|
||||
raise ValueError(
|
||||
"SparseMQAIndexer requires an SM100-class GPU and DeepGEMM >= 2.8."
|
||||
)
|
||||
if not has_deep_select():
|
||||
raise ValueError(
|
||||
"SparseMQAIndexer requires the DeepSelect top-k extension "
|
||||
"(vllm._deepselect_C)."
|
||||
)
|
||||
self.k_cache = k_cache
|
||||
self.topk_tokens = topk_tokens
|
||||
self.head_dim = head_dim
|
||||
self.max_total_seq_len = max_total_seq_len
|
||||
self.topk_indices_buffer = topk_indices_buffer
|
||||
self.candidate_blocks = candidate_blocks
|
||||
self.candidate_block_size = candidate_block_size
|
||||
|
||||
def _reserve_workspaces(self, device: torch.device) -> None:
|
||||
"""Profiling run: claim the K-gather workspace and the peak sparse
|
||||
logits allocation so the memory estimate covers them."""
|
||||
_prefill_k_workspaces(self.max_total_seq_len, self.head_dim)
|
||||
max_logits_bytes = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
|
||||
torch.empty(max_logits_bytes, dtype=torch.uint8, device=device)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_quant: tuple[torch.Tensor, torch.Tensor],
|
||||
k: torch.Tensor | None,
|
||||
weights: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
if not isinstance(attn_metadata, dict):
|
||||
self._reserve_workspaces(hidden_states.device)
|
||||
return self.topk_indices_buffer
|
||||
|
||||
metadata = attn_metadata[self.k_cache.prefix]
|
||||
assert isinstance(metadata, DeepseekV41SparseIndexerMetadata), (
|
||||
"SparseMQAIndexer needs DeepseekV41SparseIndexerBackend metadata"
|
||||
)
|
||||
assert k is None, "the model writes the indexer K cache"
|
||||
q_values, q_scale = q_quant
|
||||
kv_cache = self.k_cache.kv_cache
|
||||
topk_tokens = self.topk_tokens
|
||||
topk_indices_buffer = self.topk_indices_buffer
|
||||
topk_indices_buffer[: hidden_states.shape[0]] = -1
|
||||
sparse_block_kv = metadata.sparse_block_kv
|
||||
|
||||
if metadata.num_prefills > 0:
|
||||
prefill = metadata.prefill
|
||||
sparse_chunks = metadata.sparse_prefill
|
||||
assert prefill is not None and sparse_chunks is not None
|
||||
k_quant_full, k_scale_full = _prefill_k_workspaces(
|
||||
self.max_total_seq_len, self.head_dim
|
||||
)
|
||||
for chunk, rows in zip(prefill.chunks, sparse_chunks):
|
||||
k_quant, k_scale = _gather_prefill_chunk_k(
|
||||
kv_cache, k_quant_full, k_scale_full, chunk
|
||||
)
|
||||
if chunk.local_total_seq_lens == 0:
|
||||
continue # buffer already holds -1
|
||||
start, end = chunk.token_start, chunk.token_end
|
||||
rows.kernel_metadata = sparse_mqa_logits_prefill_chunk(
|
||||
q_values[start:end].view(torch.int8),
|
||||
q_scale[start:end],
|
||||
k_quant.view(torch.int8),
|
||||
k_scale.view(torch.int32).squeeze(-1),
|
||||
weights[start:end],
|
||||
chunk.cu_seqlen_ks,
|
||||
chunk.cu_seqlen_ke,
|
||||
self.candidate_blocks[start:end],
|
||||
self.candidate_block_size,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices_buffer[start:end, :topk_tokens],
|
||||
sparse_indices=rows.sparse_indices,
|
||||
end=rows.end,
|
||||
col_indices=rows.col_indices,
|
||||
kernel_metadata=rows.kernel_metadata,
|
||||
)
|
||||
|
||||
if metadata.num_decodes > 0:
|
||||
decode_rows = metadata.sparse_decode
|
||||
assert decode_rows is not None and decode_rows.block_table is not None
|
||||
assert decode_rows.row_indices is not None
|
||||
num_rows = decode_rows.row_ke.shape[0]
|
||||
if num_rows > 0:
|
||||
decode_rows.kernel_metadata = sparse_mqa_logits_paged_decode(
|
||||
q_values[:num_rows].view(torch.int8).unsqueeze(1),
|
||||
q_scale[:num_rows].unsqueeze(1),
|
||||
kv_cache_as_quant_view(kv_cache, self.head_dim, use_fp4_cache=True),
|
||||
weights[:num_rows],
|
||||
decode_rows.row_ke,
|
||||
decode_rows.block_table,
|
||||
decode_rows.row_indices,
|
||||
self.candidate_blocks[:num_rows],
|
||||
self.candidate_block_size,
|
||||
sparse_block_kv,
|
||||
topk_tokens,
|
||||
topk_indices_buffer[:num_rows, :topk_tokens],
|
||||
row_ks=decode_rows.row_ks,
|
||||
sparse_indices=decode_rows.sparse_indices,
|
||||
end=decode_rows.end,
|
||||
col_indices=decode_rows.col_indices,
|
||||
kernel_metadata=decode_rows.kernel_metadata,
|
||||
)
|
||||
return topk_indices_buffer
|
||||
@@ -15,7 +15,6 @@ import vllm.envs as envs
|
||||
from vllm.config import ModelConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.attention import is_deferred_attention_layer
|
||||
from vllm.model_executor.layers.hpc import HpcModule
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizationConfig,
|
||||
QuantizeMethodBase,
|
||||
@@ -154,15 +153,6 @@ def process_weights_after_loading(
|
||||
with device_loading_context(module, target_device):
|
||||
module.process_weights_after_loading(model_config.dtype)
|
||||
|
||||
# Process HPC modules (HpcRopeNorm, etc.) that rely on
|
||||
# process_weights_after_loading being called from the model's
|
||||
# load_weights(). When using DummyModelLoader (e.g. profiling or
|
||||
# sleep/wake_up reload), the model's load_weights() is not called, so we
|
||||
# must handle HPC modules here generically.
|
||||
for _, module in model.named_modules():
|
||||
if isinstance(module, HpcModule):
|
||||
module.process_weights_after_loading(model)
|
||||
|
||||
# Model-level post-load hook, after the per-layer quant finalize.
|
||||
if hasattr(model, "process_weights_after_loading"):
|
||||
model.process_weights_after_loading()
|
||||
|
||||
@@ -60,6 +60,7 @@ from vllm.distributed import (
|
||||
ensure_model_parallel_initialized,
|
||||
init_distributed_environment,
|
||||
)
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader import get_model_loader
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
@@ -70,13 +71,15 @@ from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
check_ipc_platform_support,
|
||||
check_ipc_quant_support,
|
||||
ensure_private_socket_dir,
|
||||
get_physical_device_id,
|
||||
get_current_device_uuid,
|
||||
get_socket_path,
|
||||
recv_msg,
|
||||
send_msg,
|
||||
verify_peer_is_owner,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
logger = init_logger("vllm.model_executor.model_loader.weight_cache.daemon")
|
||||
@@ -90,11 +93,14 @@ def export_entries(
|
||||
``named_parameters``/``named_buffers`` are iterated with
|
||||
``remove_duplicate=False`` so tied weights (e.g. ``lm_head.weight`` sharing
|
||||
storage with ``embed_tokens.weight``) are not silently dropped. Each unique
|
||||
tensor is exported once; every additional name that refers to the same
|
||||
tensor is exported once per call; every additional name that refers to the same
|
||||
tensor object is recorded in the returned alias map so the client can
|
||||
re-establish the shared identity instead of allocating uninitialized
|
||||
memory for it.
|
||||
|
||||
CUDA reduction arguments must be exported separately for each consumer so
|
||||
that PyTorch registers a reference for each IPC mapping's lifetime.
|
||||
|
||||
Returns:
|
||||
A ``(entries, aliases)`` pair where ``entries`` maps a canonical name to
|
||||
its ``TensorEntry`` and ``aliases`` maps each duplicate name to its
|
||||
@@ -164,8 +170,6 @@ class WeightCacheDaemon:
|
||||
self.distributed_init_method = distributed_init_method
|
||||
self.socket_dir = socket_dir
|
||||
self.model: torch.nn.Module | None = None
|
||||
self.entries: dict[str, TensorEntry] = {}
|
||||
self.aliases: dict[str, str] = {}
|
||||
# Fingerprint before loading: process_weights_after_loading may
|
||||
# mutate hf_config.quantization_config.
|
||||
self.cache_config = WeightCacheKey.from_model_config(
|
||||
@@ -187,17 +191,11 @@ class WeightCacheDaemon:
|
||||
with set_current_vllm_config(self.vllm_config):
|
||||
ensure_model_parallel_initialized(tp_size, 1)
|
||||
self.model = get_daemon_model(self.vllm_config)
|
||||
self._export_entries()
|
||||
logger.info(
|
||||
"Weight cache daemon rank %d cached %d tensors",
|
||||
"Weight cache daemon rank %d loaded model",
|
||||
self.tp_rank,
|
||||
len(self.entries),
|
||||
)
|
||||
|
||||
def _export_entries(self) -> None:
|
||||
assert self.model is not None
|
||||
self.entries, self.aliases = export_entries(self.model)
|
||||
|
||||
def serve_forever(self, ready_callback: Callable[[], None] | None = None) -> None:
|
||||
"""Serve requests until terminated.
|
||||
|
||||
@@ -209,7 +207,7 @@ class WeightCacheDaemon:
|
||||
ready_callback: Invoked once the socket is bound and listening,
|
||||
so the launcher can report overall readiness.
|
||||
"""
|
||||
socket_path = self._socket_path()
|
||||
socket_path = self._socket_path
|
||||
ensure_private_socket_dir(
|
||||
os.path.dirname(socket_path), strict_perms=self.socket_dir is None
|
||||
)
|
||||
@@ -268,12 +266,9 @@ class WeightCacheDaemon:
|
||||
) from e
|
||||
return lock_fd
|
||||
|
||||
@property
|
||||
def _socket_path(self) -> str:
|
||||
device_index = torch.accelerator.current_device_index()
|
||||
gpu_id = get_physical_device_id(device_index)
|
||||
if gpu_id is None:
|
||||
gpu_id = device_index
|
||||
return get_socket_path(gpu_id, self.socket_dir)
|
||||
return get_socket_path(get_current_device_uuid(), self.socket_dir)
|
||||
|
||||
def _handle_connection(self, conn: socket.socket) -> None:
|
||||
request = recv_msg(conn)
|
||||
@@ -295,39 +290,33 @@ class WeightCacheDaemon:
|
||||
logger.warning("WeightCacheKey mismatch on fields: %s", mismatched)
|
||||
send_msg(conn, {"status": "mismatch", "fields": mismatched})
|
||||
return
|
||||
if not self.entries:
|
||||
if self.model is None:
|
||||
send_msg(conn, {"status": "error", "message": "Weights were released"})
|
||||
return
|
||||
gpu_uuid = get_current_device_uuid()
|
||||
entries, aliases = export_entries(self.model)
|
||||
send_msg(
|
||||
conn,
|
||||
{
|
||||
"status": "ok",
|
||||
"entries": self.entries,
|
||||
"aliases": self.aliases,
|
||||
"gpu_uuid": self._gpu_uuid(),
|
||||
"entries": entries,
|
||||
"aliases": aliases,
|
||||
"gpu_uuid": gpu_uuid,
|
||||
},
|
||||
)
|
||||
logger.info_once(
|
||||
"Weight cache daemon rank %d sent %d tensors (+%d aliases) to engine",
|
||||
self.tp_rank,
|
||||
len(self.entries),
|
||||
len(self.aliases),
|
||||
len(entries),
|
||||
len(aliases),
|
||||
)
|
||||
|
||||
def _handle_release(self, conn: socket.socket) -> None:
|
||||
self.entries.clear()
|
||||
self.aliases.clear()
|
||||
self.model = None
|
||||
torch.accelerator.empty_cache()
|
||||
logger.info("Weight cache daemon rank %d released cached weights", self.tp_rank)
|
||||
send_msg(conn, {"status": "ok"})
|
||||
|
||||
def _gpu_uuid(self) -> str:
|
||||
props = torch.cuda.get_device_properties(
|
||||
torch.accelerator.current_device_index()
|
||||
)
|
||||
return str(props.uuid)
|
||||
|
||||
|
||||
def _run_daemon(
|
||||
tp_rank: int,
|
||||
@@ -359,10 +348,6 @@ def _reject_unsupported_parallelism(parallel_config: ParallelConfig) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
from vllm.utils.network_utils import get_distributed_init_method, get_open_port
|
||||
|
||||
parser = FlexibleArgumentParser(
|
||||
description="Launch weight cache daemons (one per TP rank)."
|
||||
)
|
||||
|
||||
@@ -12,6 +12,10 @@ import torch.nn as nn
|
||||
|
||||
from vllm.config import ModelConfig, VllmConfig
|
||||
from vllm.config.load import LoadConfig
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.base_loader import BaseModelLoader
|
||||
from vllm.model_executor.model_loader.default_loader import DefaultModelLoader
|
||||
@@ -27,7 +31,7 @@ from vllm.model_executor.model_loader.weight_cache.protocol import (
|
||||
WeightCacheUnavailableError,
|
||||
check_ipc_platform_support,
|
||||
check_ipc_quant_support,
|
||||
get_physical_device_id,
|
||||
get_current_device_uuid,
|
||||
get_socket_path,
|
||||
recv_msg,
|
||||
send_msg,
|
||||
@@ -56,7 +60,7 @@ class IpcModelLoader(BaseModelLoader):
|
||||
Extra config keys (via --model-loader-extra-config):
|
||||
|
||||
- socket_path: explicit daemon socket path. Defaults to a per-GPU path
|
||||
derived from the physical GPU id.
|
||||
derived from the physical GPU uuid.
|
||||
- socket_dir: directory containing the daemon sockets.
|
||||
- mode: "zero_copy" (default) or "copy".
|
||||
- fallback: fall back to disk loading when the daemon is unavailable or
|
||||
@@ -261,11 +265,6 @@ class IpcModelLoader(BaseModelLoader):
|
||||
def _fetch_entries(
|
||||
self, model_config: ModelConfig
|
||||
) -> tuple[dict[str, TensorEntry], dict[str, str]]:
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
|
||||
cache_config = WeightCacheKey.from_model_config(
|
||||
model_config,
|
||||
tp_size=get_tensor_model_parallel_world_size(),
|
||||
@@ -317,22 +316,12 @@ class IpcModelLoader(BaseModelLoader):
|
||||
def _resolve_socket_path(self) -> str:
|
||||
if self.socket_path is not None:
|
||||
return self.socket_path
|
||||
device_index = torch.accelerator.current_device_index()
|
||||
gpu_id = get_physical_device_id(device_index)
|
||||
if gpu_id is None:
|
||||
raise WeightCacheUnavailableError(
|
||||
"Cannot infer the physical GPU id from CUDA_VISIBLE_DEVICES; "
|
||||
"pass socket_path via --model-loader-extra-config"
|
||||
)
|
||||
return get_socket_path(gpu_id, self.socket_dir)
|
||||
return get_socket_path(get_current_device_uuid(), self.socket_dir)
|
||||
|
||||
def _check_gpu_uuid(self, daemon_uuid: str | None) -> None:
|
||||
if daemon_uuid is None:
|
||||
return
|
||||
props = torch.cuda.get_device_properties(
|
||||
torch.accelerator.current_device_index()
|
||||
)
|
||||
local_uuid = str(props.uuid)
|
||||
local_uuid = get_current_device_uuid()
|
||||
if daemon_uuid != local_uuid:
|
||||
raise CacheConfigMismatchError(
|
||||
f"Daemon GPU {daemon_uuid} != engine GPU {local_uuid}; "
|
||||
|
||||
@@ -23,14 +23,19 @@ from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch.multiprocessing.reductions import rebuild_cuda_tensor, reduce_tensor
|
||||
from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
|
||||
|
||||
import vllm.version
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
filter_duplicate_safetensors_files,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.hashing import safe_hash
|
||||
|
||||
SOCKET_NAME_TEMPLATE = "vllm_weight_cache_gpu{gpu_id}.sock"
|
||||
SOCKET_NAME_TEMPLATE = "vllm_weight_cache_{gpu_uuid}.sock"
|
||||
SOCKET_DIR_TEMPLATE = "vllm_weight_cache_{uid}"
|
||||
|
||||
_LEN_STRUCT = struct.Struct("!Q")
|
||||
@@ -102,20 +107,9 @@ def check_ipc_quant_support(model: torch.nn.Module) -> None:
|
||||
)
|
||||
|
||||
|
||||
def get_physical_device_id(device_index: int) -> int | None:
|
||||
"""Map a local CUDA device index to the physical GPU id.
|
||||
|
||||
Returns None if CUDA_VISIBLE_DEVICES contains non-integer entries
|
||||
(e.g. GPU UUIDs), in which case an explicit socket path is required.
|
||||
"""
|
||||
visible = os.environ.get("CUDA_VISIBLE_DEVICES")
|
||||
if not visible:
|
||||
return device_index
|
||||
entries = visible.split(",")
|
||||
try:
|
||||
return int(entries[device_index])
|
||||
except (IndexError, ValueError):
|
||||
return None
|
||||
def get_current_device_uuid() -> str:
|
||||
"""UUID of the physical GPU backing the current accelerator device."""
|
||||
return current_platform.get_device_uuid(torch.accelerator.current_device_index())
|
||||
|
||||
|
||||
def get_socket_dir(socket_dir: str | None = None) -> str:
|
||||
@@ -132,9 +126,9 @@ def get_socket_dir(socket_dir: str | None = None) -> str:
|
||||
)
|
||||
|
||||
|
||||
def get_socket_path(gpu_id: int, socket_dir: str | None = None) -> str:
|
||||
def get_socket_path(gpu_uuid: str, socket_dir: str | None = None) -> str:
|
||||
directory = get_socket_dir(socket_dir)
|
||||
return os.path.join(directory, SOCKET_NAME_TEMPLATE.format(gpu_id=gpu_id))
|
||||
return os.path.join(directory, SOCKET_NAME_TEMPLATE.format(gpu_uuid=gpu_uuid))
|
||||
|
||||
|
||||
def ensure_private_socket_dir(directory: str, strict_perms: bool = True) -> None:
|
||||
@@ -245,12 +239,6 @@ def hash_checkpoint(model: str) -> str | None:
|
||||
"""
|
||||
if not os.path.isdir(model):
|
||||
return None
|
||||
from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
|
||||
|
||||
from vllm.model_executor.model_loader.weight_utils import (
|
||||
filter_duplicate_safetensors_files,
|
||||
)
|
||||
|
||||
files = glob.glob(os.path.join(model, "*.safetensors"))
|
||||
if os.path.isfile(os.path.join(model, SAFE_WEIGHTS_INDEX_NAME)):
|
||||
files = filter_duplicate_safetensors_files(
|
||||
@@ -337,8 +325,6 @@ class TensorEntry:
|
||||
|
||||
@classmethod
|
||||
def from_tensor(cls, tensor: torch.Tensor, kind: str) -> "TensorEntry":
|
||||
from torch.multiprocessing.reductions import reduce_tensor
|
||||
|
||||
tensor = tensor.detach()
|
||||
if tensor.is_cuda:
|
||||
_, ipc_args = reduce_tensor(tensor)
|
||||
@@ -349,8 +335,6 @@ class TensorEntry:
|
||||
if self.ipc_args is None:
|
||||
assert self.cpu_tensor is not None
|
||||
return self.cpu_tensor
|
||||
from torch.multiprocessing.reductions import rebuild_cuda_tensor
|
||||
|
||||
args = list(self.ipc_args)
|
||||
# Index 6 of the args from reduce_tensor is the device index. It must
|
||||
# be retargeted to the local index since the daemon and the engine may
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import MultiModalDataItems
|
||||
@@ -687,28 +688,22 @@ class Blip2ForConditionalGeneration(
|
||||
tower_model="vision_model",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
if num_image_tokens <= 0:
|
||||
return 0
|
||||
assert num_image_tokens % self.config.num_query_tokens == 0, (
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if num_mm_embeds <= 0:
|
||||
return 0, 0
|
||||
assert num_mm_embeds % self.config.num_query_tokens == 0, (
|
||||
"The number of image tokens must be a multiple of "
|
||||
"the number of query tokens."
|
||||
)
|
||||
num_images = num_image_tokens / self.config.num_query_tokens
|
||||
return num_images * self._vision_tokens_per_image
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
if num_vision_tokens <= 0:
|
||||
return 0
|
||||
assert num_vision_tokens % self._vision_tokens_per_image == 0, (
|
||||
"The number of vision tokens must be a multiple of "
|
||||
"the number of tokens per image."
|
||||
num_images = num_mm_embeds // self.config.num_query_tokens
|
||||
return (
|
||||
num_images * self._vision_tokens_per_image,
|
||||
num_images * self.config.num_query_tokens,
|
||||
)
|
||||
num_images = num_vision_tokens / self._vision_tokens_per_image
|
||||
return num_images * self.config.num_query_tokens
|
||||
|
||||
@@ -305,10 +305,14 @@ class Eagle3DeepseekV2ForCausalLM(LocalArgmaxMixin, DeepseekV2ForCausalLM):
|
||||
self.logits_processor = LogitsProcessor(
|
||||
self.config.draft_vocab_size, scale=logit_scale
|
||||
)
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
target_vocab_size = vllm_config.model_config.get_vocab_size()
|
||||
if self.config.draft_vocab_size != target_vocab_size:
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.draft_id_to_target_id = None
|
||||
|
||||
def embed_input_ids(
|
||||
self,
|
||||
|
||||
@@ -53,7 +53,7 @@ from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.outputs import LogprobsTensors
|
||||
from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
|
||||
from vllm.v1.worker.gpu.attn_utils import build_attn_metadata
|
||||
from vllm.v1.worker.gpu.buffer_utils import UvaBackedTensor, async_copy_to_gpu
|
||||
from vllm.v1.worker.gpu.buffer_utils import UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.model_states.interface import ModelState
|
||||
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
|
||||
@@ -1159,7 +1159,7 @@ class DiffusionSampler:
|
||||
return
|
||||
# Move the slot indices across once, up front: indexing a device
|
||||
# tensor with a numpy array copies them over synchronously each time.
|
||||
ps_gpu = async_copy_to_gpu(
|
||||
ps_gpu = async_tensor_h2d(
|
||||
ps.astype(np.int64), device=states.is_encoder_phase.device
|
||||
)
|
||||
states.init_canvas(ps_gpu)
|
||||
@@ -1266,7 +1266,7 @@ class DiffusionSampler:
|
||||
# was truncated near max_model_len, in which case the scheduler gave us
|
||||
# fewer than CL logits for that request.
|
||||
valid_canvas_len_np = per_req_nlogits_np[per_req_nlogits_np > 0]
|
||||
valid_canvas_len = async_copy_to_gpu(
|
||||
valid_canvas_len = async_tensor_h2d(
|
||||
valid_canvas_len_np.astype(np.int64), device=device
|
||||
)
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ from vllm.model_executor.models.utils import (
|
||||
)
|
||||
from vllm.model_executor.models.vision import get_vit_attn_backend
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import MultiModalKwargsItem
|
||||
from vllm.sequence import IntermediateTensors
|
||||
from vllm.transformers_utils.configs.dotsocr import DotsOCRConfig, DotsVisionConfig
|
||||
from vllm.utils.tensor_schema import TensorSchema, TensorShape
|
||||
@@ -718,13 +719,16 @@ class DotsOCRForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsLoRA
|
||||
|
||||
return image_embeds.split(sizes)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
merge_size = self.vision_tower.spatial_merge_size
|
||||
return num_image_tokens * (merge_size**2)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
merge_size = self.vision_tower.spatial_merge_size
|
||||
return num_vision_tokens // (merge_size**2)
|
||||
return num_mm_embeds * (merge_size**2), num_mm_embeds
|
||||
|
||||
def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
|
||||
image_input = self._parse_and_validate_image_input(**kwargs)
|
||||
|
||||
@@ -19,6 +19,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, ImageSize, MultiModalDataItems
|
||||
@@ -686,43 +687,16 @@ class Gemma3ForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
"""
|
||||
Calculate the number of tokens output by the vision encoder.
|
||||
|
||||
The vision encoder processes images into patch embeddings. For Gemma3,
|
||||
the relationship between prompt placeholder tokens and actual vision
|
||||
encoder output tokens depends on the patch grid size.
|
||||
|
||||
Args:
|
||||
num_image_tokens: Number of image placeholder tokens in the prompt
|
||||
(typically mm_tokens_per_image per image)
|
||||
|
||||
Returns:
|
||||
Number of tokens output by the vision encoder
|
||||
"""
|
||||
# For Gemma3, the vision encoder outputs tokens_per_side x tokens_per_side
|
||||
# tokens per image. Since num_image_tokens represents the number of
|
||||
# connector output tokens (mm_tokens_per_image = 256), and tokens_per_side
|
||||
# is sqrt(256) = 16, we need to account for the token expansion.
|
||||
# Based on empirical testing, the multiplier of 16 works correctly.
|
||||
return num_image_tokens * 16
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
"""
|
||||
Calculate the number of tokens output by the multimodal connector.
|
||||
|
||||
The connector applies projection and normalization but maintains the
|
||||
token count for Gemma3.
|
||||
|
||||
Args:
|
||||
num_vision_tokens: Number of tokens from vision encoder
|
||||
|
||||
Returns:
|
||||
Number of tokens after connector processing
|
||||
"""
|
||||
# The Gemma3 connector maintains a 1:1 token mapping
|
||||
return num_vision_tokens
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
tower_tokens = num_mm_embeds * 16
|
||||
return tower_tokens, tower_tokens
|
||||
|
||||
def get_encoder_cudagraph_config(self):
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import (
|
||||
|
||||
@@ -24,6 +24,7 @@ from PIL import Image as PILImage
|
||||
from torch import nn
|
||||
from transformers import AutoModel, BatchFeature
|
||||
from transformers.models.gemma4 import (
|
||||
Gemma4AudioFeatureExtractor,
|
||||
Gemma4Config,
|
||||
Gemma4Processor,
|
||||
Gemma4VisionConfig,
|
||||
@@ -456,6 +457,28 @@ class Gemma4ProcessingInfo(BaseProcessingInfo):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _dummy_audio_num_samples(processor: Any) -> int:
|
||||
"""Length in samples of a worst-case dummy audio item.
|
||||
|
||||
``fft_length`` is set in ``Gemma4AudioFeatureExtractor.__init__`` and is not
|
||||
defined by ``Gemma4UnifiedAudioFeatureExtractor``, which the encoder-free
|
||||
Gemma 4 variant uses. Reading it unconditionally therefore raises
|
||||
``AttributeError`` during memory profiling on that variant, which is reached
|
||||
whenever audio is the modality with the largest per-item token count.
|
||||
|
||||
For any other extractor, fall back to the audio budget the processor itself
|
||||
declares -- the same pair of values used to warn about over-long audio
|
||||
elsewhere in this file.
|
||||
"""
|
||||
feature_extractor = processor.feature_extractor
|
||||
if isinstance(feature_extractor, Gemma4AudioFeatureExtractor):
|
||||
return feature_extractor.fft_length
|
||||
|
||||
sampling_rate = feature_extractor.sampling_rate
|
||||
max_duration_s = processor.audio_seq_length * processor.audio_ms_per_token / 1000.0
|
||||
return int(max_duration_s * sampling_rate)
|
||||
|
||||
|
||||
class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
|
||||
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
num_images = mm_counts.get("image", 0)
|
||||
@@ -508,7 +531,7 @@ class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
|
||||
}
|
||||
|
||||
if num_audios > 0:
|
||||
audio_len = processor.feature_extractor.fft_length
|
||||
audio_len = _dummy_audio_num_samples(processor)
|
||||
data["audio"] = self._get_dummy_audios(
|
||||
length=audio_len,
|
||||
num_audios=num_audios,
|
||||
|
||||
@@ -83,6 +83,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
VideoItem,
|
||||
)
|
||||
@@ -2378,19 +2379,16 @@ class Glm4vForConditionalGeneration(
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_image_tokens * (merge_size**2)
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_vision_tokens // (merge_size**2)
|
||||
return num_mm_embeds * (merge_size**2), num_mm_embeds
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
|
||||
@@ -14,7 +14,7 @@ from transformers import PretrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import BatchedTensorInputs
|
||||
from vllm.multimodal.inputs import BatchedTensorInputs, MultiModalKwargsItem
|
||||
from vllm.multimodal.parse import (
|
||||
ImageEmbeddingItems,
|
||||
ImageProcessorItems,
|
||||
@@ -178,16 +178,17 @@ class H2OVLChatModel(InternVLChatModel):
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
if num_image_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if num_mm_embeds <= 0 or self.num_image_token <= 0:
|
||||
return 0, 0
|
||||
|
||||
num_patches = num_image_tokens // self.num_image_token
|
||||
return num_patches * (self.patch_tokens + 1)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
if num_vision_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
|
||||
num_patches = num_vision_tokens // (self.patch_tokens + 1)
|
||||
return num_patches * self.num_image_token
|
||||
num_patches = num_mm_embeds // self.num_image_token
|
||||
tower_tokens = num_patches * (self.patch_tokens + 1)
|
||||
return tower_tokens, num_patches * self.num_image_token
|
||||
|
||||
@@ -300,8 +300,11 @@ class HYV3Attention(nn.Module):
|
||||
prefix=f"{prefix}.attn",
|
||||
)
|
||||
if self.use_qk_norm:
|
||||
self.q_norm = RMSNorm(self.head_dim, rms_norm_eps)
|
||||
self.k_norm = RMSNorm(self.head_dim, rms_norm_eps)
|
||||
# The HPC fused kernel reads norm weights directly in float32;
|
||||
# the fallback path keeps the model default dtype.
|
||||
norm_dtype = torch.float32 if rope_support else None
|
||||
self.q_norm = RMSNorm(self.head_dim, rms_norm_eps, dtype=norm_dtype)
|
||||
self.k_norm = RMSNorm(self.head_dim, rms_norm_eps, dtype=norm_dtype)
|
||||
|
||||
# HPC fused RoPE + QK-Norm + KV-Cache-Write (+ optional FP8 Q quant).
|
||||
# HunYuan V3 applies QK-Norm *before* RoPE, so NORM_THEN_ROPE.
|
||||
|
||||
@@ -39,6 +39,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, MultiModalDataItems
|
||||
@@ -837,20 +838,14 @@ class Idefics3ForConditionalGeneration(
|
||||
tower_model="model.vision_model",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
hf_config = self.config
|
||||
scale_factor = hf_config.scale_factor
|
||||
|
||||
return num_image_tokens * scale_factor**2
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
hf_config = self.config
|
||||
scale_factor = hf_config.scale_factor
|
||||
|
||||
return num_vision_tokens // scale_factor**2
|
||||
return num_mm_embeds * scale_factor**2, num_mm_embeds
|
||||
|
||||
@@ -31,7 +31,7 @@ import torch
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from transformers.models.whisper.tokenization_whisper import LANGUAGES
|
||||
from typing_extensions import Self, TypeIs
|
||||
from typing_extensions import Self, TypeIs, deprecated
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
@@ -420,23 +420,16 @@ class SupportsMultiModal(SupportsMultiModalEmbeddings, Protocol):
|
||||
|
||||
yield
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
"""
|
||||
Implement this function to enable LoRA support
|
||||
for the tower module of the multi-modal model.
|
||||
Given the number of image tokens, output the number of
|
||||
multi-modal encoder tokens.
|
||||
"""
|
||||
...
|
||||
@deprecated(
|
||||
"get_num_mm_encoder_tokens is deprecated; use get_mm_lora_token_counts instead."
|
||||
)
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int: ...
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
"""
|
||||
Implement this function to enable LoRA support
|
||||
for the connector module of the multi-modal model.
|
||||
Given the number of vision tokens, output the number of
|
||||
multi-modal connector tokens.
|
||||
"""
|
||||
...
|
||||
@deprecated(
|
||||
"get_num_mm_connector_tokens is deprecated; use "
|
||||
"get_mm_lora_token_counts instead."
|
||||
)
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int: ...
|
||||
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
|
||||
@@ -29,6 +29,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
BatchedTensorInputs,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -914,19 +915,20 @@ class InternVLChatModel(
|
||||
tower_model="vision_model",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
if num_image_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
if num_mm_embeds <= 0 or self.num_image_token <= 0:
|
||||
return 0, 0
|
||||
|
||||
num_patches = num_image_tokens // self.num_image_token
|
||||
return num_patches * (self.patch_tokens + 1)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
if num_vision_tokens <= 0 or self.num_image_token <= 0:
|
||||
return 0
|
||||
|
||||
num_patches = num_vision_tokens // (self.patch_tokens + 1)
|
||||
return num_patches * self.num_image_token
|
||||
num_patches = num_mm_embeds // self.num_image_token
|
||||
tower_tokens = num_patches * (self.patch_tokens + 1)
|
||||
return tower_tokens, num_patches * self.num_image_token
|
||||
|
||||
# -- SupportsEncoderCudaGraph protocol methods --
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ from vllm.multimodal.inputs import (
|
||||
ImageItem,
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
VideoItem,
|
||||
)
|
||||
@@ -1495,13 +1496,16 @@ class BaseKeyeModule(nn.Module, SupportsMultiModal):
|
||||
tower_model="visual.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_image_tokens * merge_size**2
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
merge_size = self.config.vision_config.spatial_merge_size
|
||||
return num_vision_tokens // merge_size**2
|
||||
return num_mm_embeds * merge_size**2, num_mm_embeds
|
||||
|
||||
|
||||
@MULTIMODAL_REGISTRY.register_processor(
|
||||
|
||||
@@ -35,6 +35,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, ImageSize, MultiModalDataItems
|
||||
@@ -1284,12 +1285,13 @@ class Lfm2VLForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
downsample_factor = self.config.downsample_factor
|
||||
|
||||
return num_image_tokens * downsample_factor**2
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
downsample_factor = self.config.downsample_factor
|
||||
|
||||
return num_vision_tokens // downsample_factor**2
|
||||
return num_mm_embeds * downsample_factor**2, num_mm_embeds
|
||||
|
||||
@@ -335,10 +335,14 @@ class Eagle3LlamaForCausalLM(_Eagle3LlamaForCausalLMBase):
|
||||
self.logits_processor = LogitsProcessor(
|
||||
self.config.draft_vocab_size, scale=logit_scale
|
||||
)
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
target_vocab_size = vllm_config.model_config.get_vocab_size()
|
||||
if self.config.draft_vocab_size != target_vocab_size:
|
||||
self.draft_id_to_target_id = nn.Parameter(
|
||||
torch.zeros(self.config.draft_vocab_size, dtype=torch.long),
|
||||
requires_grad=False,
|
||||
)
|
||||
else:
|
||||
self.draft_id_to_target_id = None
|
||||
|
||||
self.use_parallel_drafting = speculative_config.parallel_drafting
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.cache import BaseMultiModalProcessorCache
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -739,18 +740,12 @@ class LlavaForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_image_tokens: int,
|
||||
) -> int:
|
||||
# LLaVA's vision encoder outputs one token per patch without
|
||||
# spatial merging or pixel shuffle
|
||||
return num_image_tokens
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
# LLaVA's MLP projector outputs the same number of tokens
|
||||
# as it receives from the vision encoder (1:1 mapping)
|
||||
return num_vision_tokens
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
|
||||
@@ -17,6 +17,7 @@ from vllm.model_executor.models.clip import CLIPVisionModel
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import (
|
||||
@@ -494,31 +495,30 @@ class LlavaNextVideoForConditionalGeneration(
|
||||
tower_model="vision_tower",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
num_video_tokens: int,
|
||||
) -> int:
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
|
||||
# Invert the spatial pooling done by `vision_resampler`: each frame
|
||||
# contributes `pooled_grid_length ** 2` tokens after the language
|
||||
# model's placeholder count, but `patch_grid_length ** 2` tokens
|
||||
# when it leaves the vision encoder.
|
||||
pooled_tokens_per_frame = self.pooled_grid_length**2
|
||||
if num_video_tokens <= 0 or pooled_tokens_per_frame <= 0:
|
||||
return 0
|
||||
|
||||
num_frames = num_video_tokens // pooled_tokens_per_frame
|
||||
return num_frames * (self.patch_grid_length**2)
|
||||
|
||||
def get_num_mm_connector_tokens(
|
||||
self,
|
||||
num_vision_tokens: int,
|
||||
) -> int:
|
||||
# The projector is length-preserving; it runs after
|
||||
# `vision_resampler` has already pooled each frame down to
|
||||
# `pooled_grid_length ** 2` tokens.
|
||||
patch_tokens_per_frame = self.patch_grid_length**2
|
||||
if num_vision_tokens <= 0 or patch_tokens_per_frame <= 0:
|
||||
return 0
|
||||
if (
|
||||
num_mm_embeds <= 0
|
||||
or pooled_tokens_per_frame <= 0
|
||||
or patch_tokens_per_frame <= 0
|
||||
):
|
||||
return 0, 0
|
||||
|
||||
num_frames = num_vision_tokens // patch_tokens_per_frame
|
||||
return num_frames * (self.pooled_grid_length**2)
|
||||
num_frames = num_mm_embeds // pooled_tokens_per_frame
|
||||
return (
|
||||
num_frames * patch_tokens_per_frame,
|
||||
num_frames * pooled_tokens_per_frame,
|
||||
)
|
||||
|
||||
@@ -674,14 +674,6 @@ class MiniCPMV4_6ProcessingInfo(MiniCPMVProcessingInfo):
|
||||
|
||||
|
||||
class MiniCPMV4_6ViTWindowAttentionSelfAttn(nn.Module):
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_stacked={
|
||||
".q_proj": (".qkv_proj", "q"),
|
||||
".k_proj": (".qkv_proj", "k"),
|
||||
".v_proj": (".qkv_proj", "v"),
|
||||
}
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
@@ -729,10 +721,6 @@ class MiniCPMV4_6ViTWindowAttentionSelfAttn(nn.Module):
|
||||
out, _ = self.out_proj(attn_out)
|
||||
return out
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
|
||||
|
||||
|
||||
class MiniCPMV4_6ViTWindowAttentionMerger(nn.Module):
|
||||
def __init__(
|
||||
@@ -971,6 +959,11 @@ class MiniCPMV4_6ForConditionalGeneration(
|
||||
supports_encoder_tp_data = True
|
||||
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_stacked={
|
||||
".q_proj": (".qkv_proj", "q"),
|
||||
".k_proj": (".qkv_proj", "k"),
|
||||
".v_proj": (".qkv_proj", "v"),
|
||||
},
|
||||
orig_to_new_prefix={
|
||||
# transformers v5.7+ uses `vision_tower` and nests `vit_merger`
|
||||
# inside it. Order matters: more specific prefix must come first.
|
||||
@@ -982,7 +975,7 @@ class MiniCPMV4_6ForConditionalGeneration(
|
||||
"model.language_model.": "language_model.model.",
|
||||
"lm_head.": "language_model.lm_head.",
|
||||
"mtp.": None,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
packed_modules_mapping = {
|
||||
|
||||
@@ -60,6 +60,7 @@ from vllm.model_executor.models.module_mapping import MultiModelKeys
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageProcessorItems, ImageSize, MultiModalDataItems
|
||||
@@ -1281,21 +1282,18 @@ class Llama4ForConditionalGeneration(
|
||||
tower_model="vision_model.",
|
||||
)
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
vision_config = self.config.vision_config
|
||||
patches_per_chunk = Mllama4ProcessingInfo.get_patch_per_chunk(vision_config)
|
||||
if num_image_tokens <= 0 or patches_per_chunk <= 0:
|
||||
return 0
|
||||
if num_mm_embeds <= 0 or patches_per_chunk <= 0:
|
||||
return 0, 0
|
||||
raw_patches = (vision_config.image_size // vision_config.patch_size) ** 2
|
||||
num_chunks = num_image_tokens // patches_per_chunk
|
||||
# Encoder processes raw_patches + 1 (CLS) per chunk
|
||||
return num_chunks * (raw_patches + 1)
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
vision_config = self.config.vision_config
|
||||
raw_patches = (vision_config.image_size // vision_config.patch_size) ** 2
|
||||
if num_vision_tokens <= 0:
|
||||
return 0
|
||||
num_chunks = num_vision_tokens // (raw_patches + 1)
|
||||
patches_per_chunk = Mllama4ProcessingInfo.get_patch_per_chunk(vision_config)
|
||||
return num_chunks * patches_per_chunk
|
||||
num_chunks = num_mm_embeds // patches_per_chunk
|
||||
return num_chunks * (raw_patches + 1), num_chunks * patches_per_chunk
|
||||
|
||||
@@ -47,6 +47,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalFieldConfig,
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
)
|
||||
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
|
||||
@@ -1104,11 +1105,15 @@ class Moondream3ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP):
|
||||
def get_language_model(self) -> nn.Module:
|
||||
return self.text
|
||||
|
||||
def get_num_mm_encoder_tokens(self, num_image_tokens: int) -> int:
|
||||
return num_image_tokens
|
||||
|
||||
def get_num_mm_connector_tokens(self, num_vision_tokens: int) -> int:
|
||||
return num_vision_tokens
|
||||
def get_mm_lora_token_counts(
|
||||
self,
|
||||
*,
|
||||
modality: str,
|
||||
mm_kwargs: MultiModalKwargsItem | None,
|
||||
num_mm_embeds: int,
|
||||
) -> tuple[int, int | None]:
|
||||
del modality, mm_kwargs
|
||||
return num_mm_embeds, num_mm_embeds
|
||||
|
||||
def _split_pixel_values(
|
||||
self,
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.config import VllmConfig
|
||||
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
|
||||
from vllm.inputs import MultiModalDataDict, MultiModalInput
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.layers.base import BaseLayerWithLoRA
|
||||
from vllm.model_executor.layers.activation import ReLUSquaredActivation
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
@@ -30,6 +31,7 @@ from vllm.model_executor.models.interfaces import (
|
||||
HasInnerState,
|
||||
IsHybrid,
|
||||
MultiModalEmbeddings,
|
||||
SupportsLoRA,
|
||||
SupportsMultiModal,
|
||||
SupportsMultiModalPruning,
|
||||
)
|
||||
@@ -897,11 +899,22 @@ class NanoNemotronVLDummyInputsBuilder(
|
||||
dummy_inputs=NanoNemotronVLDummyInputsBuilder,
|
||||
)
|
||||
class NemotronH_Nano_VL_V2(
|
||||
nn.Module, HasInnerState, IsHybrid, SupportsMultiModal, SupportsMultiModalPruning
|
||||
nn.Module,
|
||||
HasInnerState,
|
||||
IsHybrid,
|
||||
SupportsMultiModal,
|
||||
SupportsMultiModalPruning,
|
||||
SupportsLoRA,
|
||||
):
|
||||
requires_sequential_video_encoding = True
|
||||
"""Temporarily needed for dynamic res video w/ conv3d, doesn't support bs>1 yet"""
|
||||
|
||||
# LoRA covers the language model only
|
||||
is_non_gated_moe = NemotronHForCausalLM.is_non_gated_moe
|
||||
packed_modules_mapping = NemotronHForCausalLM.packed_modules_mapping
|
||||
embedding_modules = NemotronHForCausalLM.embedding_modules
|
||||
lora_skip_prefixes = NemotronHForCausalLM.lora_skip_prefixes
|
||||
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_prefix={
|
||||
"language_model.backbone": "language_model.model",
|
||||
@@ -1331,7 +1344,19 @@ class NemotronH_Nano_VL_V2(
|
||||
|
||||
# Create final video embeddings, merging text embeddings for indicator
|
||||
# tokens with video embeddings
|
||||
text_embeddings = self.get_language_model().embed_input_ids(repl_token_ids)
|
||||
|
||||
# LoRA support -
|
||||
# These replacement tokens are produced inside the encoder, so they are
|
||||
# absent from the request-token batch that the LoRA adapter index
|
||||
# mapping is built from, and there can be more
|
||||
# of them than max_num_batched_tokens.
|
||||
# Embed them with the base weights -
|
||||
# the LoRA delta is undefined for tokens with no mapping entry.
|
||||
embed_tokens = self.get_language_model().model.embed_tokens
|
||||
if isinstance(embed_tokens, BaseLayerWithLoRA):
|
||||
embed_tokens = embed_tokens.base_layer
|
||||
text_embeddings = embed_tokens(repl_token_ids)
|
||||
|
||||
final_video_embeddings = _merge_multimodal_embeddings(
|
||||
inputs_embeds=text_embeddings,
|
||||
multimodal_embeddings=video_embeddings,
|
||||
|
||||
@@ -25,7 +25,11 @@ import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import CacheConfig, ModelConfig, VllmConfig
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
ModelConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
from vllm.distributed import get_ep_group, get_tensor_model_parallel_world_size
|
||||
from vllm.distributed.communication_op import tensor_model_parallel_all_gather
|
||||
@@ -38,12 +42,14 @@ from vllm.model_executor.layers.fused_moe import (
|
||||
activation_without_mul,
|
||||
fused_moe_make_expert_params_mapping,
|
||||
)
|
||||
from vllm.model_executor.layers.fusion.fused_act_quant import maybe_fused_act_quant
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
ReplicatedLinear,
|
||||
RowParallelLinear,
|
||||
UnquantizedLinearMethod,
|
||||
)
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2
|
||||
@@ -118,7 +124,7 @@ class NemotronHMLP(nn.Module):
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
x, _ = self.up_proj(x)
|
||||
x = self.act_fn(x)
|
||||
x = maybe_fused_act_quant(self.act_fn, x, self.down_proj)
|
||||
x, _ = self.down_proj(x)
|
||||
return x
|
||||
|
||||
@@ -199,6 +205,17 @@ class NemotronHMoE(nn.Module):
|
||||
disable_tp=self.is_sequence_parallel,
|
||||
prefix=f"{prefix}.fc2_latent_proj",
|
||||
)
|
||||
# A bias-free, unquantized linear commutes with the TP sum
|
||||
# (sum_r W x_r == W sum_r x_r), so one reduce after the transform
|
||||
# suffices. Test the layer, not the model-wide `quant_config`: ModelOpt
|
||||
# excludes the latent projections, so quantized checkpoints still get
|
||||
# an UnquantizedLinearMethod here.
|
||||
self.fc2_latent_proj.reduce_commutative = (
|
||||
not config.mlp_bias
|
||||
and isinstance(
|
||||
self.fc2_latent_proj.quant_method, UnquantizedLinearMethod
|
||||
)
|
||||
)
|
||||
else:
|
||||
self.fc1_latent_proj = None
|
||||
self.fc2_latent_proj = None
|
||||
|
||||
@@ -677,14 +677,18 @@ class OpenPanguSinkAttention(nn.Module):
|
||||
},
|
||||
)
|
||||
else:
|
||||
self.param_sink_value = torch.zeros(
|
||||
(
|
||||
self.param_sink_number,
|
||||
self.num_kv_heads,
|
||||
self.v_channels,
|
||||
self.register_buffer(
|
||||
"param_sink_value",
|
||||
torch.zeros(
|
||||
(
|
||||
self.param_sink_number,
|
||||
self.num_kv_heads,
|
||||
self.v_channels,
|
||||
),
|
||||
device=current_platform.current_device(),
|
||||
dtype=config.torch_dtype,
|
||||
),
|
||||
device=current_platform.current_device(),
|
||||
dtype=config.torch_dtype,
|
||||
persistent=False,
|
||||
)
|
||||
# To enable dummy run with out weight
|
||||
self.post_weight_load()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user