Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-27 18:25:21 +09:00
1165 changed files with 51759 additions and 14579 deletions
@@ -1150,7 +1150,12 @@ def override_envs_for_invariance():
os.environ["NCCL_MIN_NCHANNELS"] = "1"
os.environ["NCCL_MAX_NCHANNELS"] = "1"
os.environ["NCCL_PROTO"] = "Simple"
os.environ["NCCL_ALGO"] = "allreduce:tree"
# NCCL >= 2.31 zero-fills the algorithm table of every collective when
# NCCL_ALGO is set and re-enables only the named ones; together with the
# NCCL_PROTO above, collectives not named here end up with no algorithm
# and fail with ncclInvalidUsage. Re-enable Ring and Tree for all
# collectives, then pin AllReduce to Tree for determinism.
os.environ["NCCL_ALGO"] = "ring,tree;allreduce:tree"
os.environ["NCCL_NTHREADS"] = "1"
os.environ["NCCL_SOCKET_NTHREADS"] = "1"
@@ -146,19 +146,21 @@ def _sparse_topk_remap_kernel(
out_ptr,
out_stride,
k,
width,
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.
``(si[row, j] - ks // SBK) * SBK + o``; columns outside ``[0, width)``
(including DeepSelect's sentinel for NaN rows) become -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
valid = (c >= 0) & (c < width)
cc = tl.where(valid, c, 0)
blocks = tl.load(si_ptr + row * si_stride + cc // SBK)
pos = (blocks - ks_base) * SBK + cc % SBK
@@ -301,6 +303,7 @@ def sparse_topk_remap(
topk_indices,
topk_indices.stride(0),
topk_tokens,
width,
SBK=sparse_block_kv,
K_POW2=triton.next_power_of_2(topk_tokens),
)
@@ -26,9 +26,6 @@ from vllm.model_executor.kernels.linear.mixed_precision import (
MPLinearKernel,
MPLinearLayerConfig,
)
from vllm.model_executor.kernels.linear.mixed_precision.allspark import (
AllSparkLinearKernel,
)
from vllm.model_executor.kernels.linear.mixed_precision.conch import (
ConchLinearKernel,
)
@@ -504,7 +501,6 @@ _POSSIBLE_KERNELS: dict[PlatformEnum, list[type[MPLinearKernel]]] = {
PlatformEnum.CUDA: [
CutlassW4A8LinearKernel,
MacheteLinearKernel,
AllSparkLinearKernel,
MarlinLinearKernel,
ConchLinearKernel,
ExllamaLinearKernel,
@@ -884,10 +880,15 @@ def choose_mp_linear_kernel(
)
def init_mxfp8_linear_kernel(*, bmm_batch_size: int | None = None) -> Mxfp8LinearKernel:
def init_mxfp8_linear_kernel(
*, weight_shape: tuple[int, int], bmm_batch_size: int | None = None
) -> Mxfp8LinearKernel:
"""Select and instantiate the best MXFP8 linear kernel for the
current platform."""
config = Mxfp8LinearLayerConfig(bmm_batch_size=bmm_batch_size)
current platform and `(N, K)` weight shape."""
config = Mxfp8LinearLayerConfig(
weight_shape=weight_shape,
bmm_batch_size=bmm_batch_size,
)
platform = current_platform._enum
possible: list[type[Mxfp8LinearKernel]]
@@ -1272,7 +1273,6 @@ __all__ = [
"ZentorchWNA16LinearKernel",
"MPLinearKernel",
"MPLinearLayerConfig",
"AllSparkLinearKernel",
"ConchLinearKernel",
"CPUWNA16LinearKernel",
"CutlassW4A8LinearKernel",
@@ -1,9 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.model_executor.kernels.linear.mixed_precision.allspark import (
AllSparkLinearKernel,
)
from vllm.model_executor.kernels.linear.mixed_precision.conch import (
ConchLinearKernel,
)
@@ -52,7 +49,6 @@ from vllm.model_executor.kernels.linear.mixed_precision.zentorch import (
__all__ = [
"MPLinearKernel",
"MPLinearLayerConfig",
"AllSparkLinearKernel",
"ConchLinearKernel",
"CPUWNA16LinearKernel",
"CutlassW4A8LinearKernel",
@@ -1,113 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm import _custom_ops as ops
from vllm.model_executor.layers.quantization.utils import replace_parameter
from vllm.model_executor.layers.quantization.utils.allspark_utils import (
ALLSPARK_AMPERE_M_CUBLAS_THRESHOLD,
check_allspark_supported_dtype_shape,
)
from vllm.model_executor.parameter import BasevLLMParameter, permute_param_layout_
from vllm.utils.platform_utils import num_compute_units
from .MPLinearKernel import MPLinearKernel, MPLinearLayerConfig
class AllSparkLinearKernel(MPLinearKernel):
@classmethod
def get_min_capability(cls) -> int:
return 80
@classmethod
def can_implement(cls, c: MPLinearLayerConfig) -> tuple[bool, str | None]:
if c.zero_points:
return False, "Zero points currently not supported by AllSpark"
return check_allspark_supported_dtype_shape(
c.partition_weight_shape[0], # in_features
c.partition_weight_shape[1], # out_features
c.group_size,
c.weight_type,
c.act_type,
)
# note assumes that
# `weight_packed` is: {input_dim = 0, output_dim = 1, packed_dim = 0}
# `weight_scale` is: {input_dim = 0, output_dim = 1}
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
device = getattr(layer, self.w_q_name).device
c = self.config
# prepare the parameters required for the kernel
properties = torch.cuda.get_device_properties(device.index)
sm_count = num_compute_units(device.index)
sm_version = properties.major * 10 + properties.minor
gemm_args = {}
gemm_args["sm_count"] = sm_count
gemm_args["sm_version"] = sm_version
self.gemm_args = gemm_args
# transform param weight, scale
old_weight_param = getattr(layer, self.w_q_name)
old_scale_param = getattr(layer, self.w_s_name)
assert isinstance(old_weight_param, BasevLLMParameter)
permute_param_layout_(old_weight_param, input_dim=0, output_dim=1, packed_dim=0)
assert isinstance(old_scale_param, BasevLLMParameter)
permute_param_layout_(old_scale_param, input_dim=0, output_dim=1)
# unpack weight from K / 4 x N int32 to K x N uint8
new_weight_param = torch.nn.Parameter(
old_weight_param.data, requires_grad=False
)
new_weight_param.data = (
new_weight_param.data.t().contiguous().view(dtype=torch.uint8)
)
new_weight_param.data = new_weight_param.data.t().contiguous()
new_scale_param = torch.nn.Parameter(old_scale_param.data, requires_grad=False)
# reorder K x N weight as N32K16 format for Ampere W8A16
new_weight_param.data, new_scale_param.data, _ = ops.allspark_repack_weight(
new_weight_param.data, new_scale_param.data, None, c.zero_points
)
replace_parameter(layer, self.w_q_name, new_weight_param.data)
replace_parameter(layer, self.w_s_name, new_scale_param.data)
def apply_weights(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
c = self.config
gemm_args = self.gemm_args
w_q, w_s, _ = self._get_weight_params(layer)
reshaped_x = x.reshape(-1, x.shape[-1])
out_shape = x.shape[:-1] + (c.partition_weight_shape[1],)
output = ops.allspark_w8a16_gemm(
a=reshaped_x,
b_qweight=w_q,
b_scales=w_s,
b_qzeros=None,
n=c.partition_weight_shape[1],
group_size=c.group_size,
sm_count=gemm_args["sm_count"],
sm_version=gemm_args["sm_version"],
CUBLAS_M_THRESHOLD=ALLSPARK_AMPERE_M_CUBLAS_THRESHOLD,
has_zp=c.zero_points,
n32k16_reorder=True,
)
if bias is not None:
output.add_(bias) # In-place add
return output.reshape(out_shape)
@@ -31,11 +31,14 @@ class HummingLinearKernel(MPLinearKernel):
)
name_map = {"weight": self.w_q_name, "weight_scale": self.w_s_name}
if self.w_zp_name is not None and hasattr(layer, self.w_zp_name):
name_map["zero_point"] = self.w_zp_name
group_size = self.config.group_size
quant_config = {
"quant_method": "humming",
"dtype": "int" + str(self.config.weight_type.size_bits),
"group_size": 0 if group_size == -1 else group_size,
"has_zero_point": self.config.zero_points,
}
if self.config.zero_points:
@@ -15,8 +15,13 @@ class Mxfp8LinearLayerConfig:
All MXFP8 layers share the same structure: FP8-E4M3 weights with
uint8 (E8M0) per-block scales at block size 32.
Attributes:
weight_shape: The layer's `(out_features, in_features)`, i.e. `(N, K)`.
"""
weight_shape: tuple[int, int]
bmm_batch_size: int | None = None
@@ -24,6 +24,20 @@ from vllm.utils.flashinfer import has_flashinfer, has_flashinfer_cutedsl
from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig
def _check_mm_mxfp8_shape(weight_shape: tuple[int, int]) -> tuple[bool, str | None]:
N, K = weight_shape
if K < 128:
return False, f"mm_mxfp8 requires K >= 128, got K={K}."
if K % MXFP8_BLOCK_SIZE != 0:
return (
False,
f"mm_mxfp8 requires K to be divisible by {MXFP8_BLOCK_SIZE}, got K={K}.",
)
if N < 128:
return False, f"mm_mxfp8 requires N >= 128, got N={N}."
return True, None
class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel):
"""MXFP8 W8A8 GEMM via FlashInfer CUTLASS (SM100+)."""
@@ -43,6 +57,15 @@ class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel):
@classmethod
def can_implement(cls, c: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]:
can_implement, reason = _check_mm_mxfp8_shape(c.weight_shape)
if not can_implement:
return False, reason
N, _ = c.weight_shape
if current_platform.is_device_capability_family(120) and N % 32 != 0:
return (
False,
f"mm_mxfp8 on SM12x requires N to be divisible by 32, got N={N}.",
)
return True, None
def input_quant_key(self) -> QuantKey:
@@ -72,20 +95,6 @@ class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel):
weight_scale = layer.weight_scale
N, K = weight.shape
min_dim = 128
assert min_dim <= K, (
f"mm_mxfp8 requires K >= {min_dim}, got K={K}. "
f"in_features is too small for mm_mxfp8."
)
assert K % MXFP8_BLOCK_SIZE == 0, (
f"mm_mxfp8 requires K to be divisible by {MXFP8_BLOCK_SIZE}, got K={K}."
)
assert min_dim <= N, (
f"mm_mxfp8 requires N >= {min_dim}, got N={N}. "
f"out_features is too small for mm_mxfp8."
)
qa = as_quantized_activation(x, self.input_quant_key())
if qa is not None:
input_mxfp8, input_scale = qa.data, qa.scale
@@ -136,7 +145,7 @@ class FlashInferCutedslMxfp8LinearKernel(Mxfp8LinearKernel):
@classmethod
def can_implement(cls, c: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]:
return True, None
return _check_mm_mxfp8_shape(c.weight_shape)
def input_quant_key(self) -> QuantKey:
# Activations use FlashInfer's F8_128x4 swizzled scale layout.
@@ -166,20 +175,6 @@ class FlashInferCutedslMxfp8LinearKernel(Mxfp8LinearKernel):
weight_scale = layer.weight_scale
K, N = weight.shape
min_dim = 128
assert min_dim <= K, (
f"mm_mxfp8 requires K >= {min_dim}, got K={K}. "
f"in_features is too small for mm_mxfp8."
)
assert K % MXFP8_BLOCK_SIZE == 0, (
f"mm_mxfp8 requires K to be divisible by {MXFP8_BLOCK_SIZE}, got K={K}."
)
assert min_dim <= N, (
f"mm_mxfp8 requires N >= {min_dim}, got N={N}. "
f"out_features is too small for mm_mxfp8."
)
qa = as_quantized_activation(x, self.input_quant_key())
if qa is not None:
input_mxfp8, input_scale = qa.data, qa.scale
@@ -3,6 +3,10 @@
import torch
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
MXFP8_BLOCK_SIZE,
)
from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig
@@ -23,6 +27,16 @@ class MarlinMxfp8LinearKernel(Mxfp8LinearKernel):
@classmethod
def can_implement(cls, c: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]:
N, K = c.weight_shape
if N <= 0 or K <= 0:
return False, f"Marlin MXFP8 requires positive N and K, got N={N}, K={K}."
if K % MXFP8_BLOCK_SIZE != 0:
return (
False,
f"Marlin MXFP8 requires K to be divisible by {MXFP8_BLOCK_SIZE}, "
f"got K={K}.",
)
# Tile misalignment is fixed by zero-padding at weight prep.
return True, None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
@@ -0,0 +1,737 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Portions adapted from ROCm/aiter (https://github.com/ROCm/aiter/pull/5750):
# SPDX-License-Identifier: MIT
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""MXFP8 GEMM on 32x32 block-scaled weights for gfx950 (``tl.dot_scaled``).
``y = x @ w.T`` with an MXFP8 activation (e4m3 values, one E8M0 scale per
row and 32 K, ``[M, K / 32]``) and an e4m3 weight whose E8M0 scales stay in
the checkpoint's 32x32 blocks, ``[N / 32, K / 32]``, instead of being
expanded to every row. Each weight scale byte is then read once per 32 output
rows, and small-M shapes can use the packed kernel below.
Two kernels, picked per shape from a table tuned on MI355X:
* a tiled kernel for larger M;
* a packed kernel for small M, which fills the MFMA's rows with K panels
instead of tokens and keeps only the matching-panel (block-diagonal)
products, so a handful of tokens still streams the weight at full width.
Either can split K. The partials are normally summed in the same launch by
the last program of each output tile to finish, in split order, so the result
does not depend on scheduling. Otherwise a second launch reduces them.
The packed kernel and the in-launch split-K reduction on one XCD
(``_split_tile``, ``_sum_splits``, ``_split_counters``, ``_k_partition``) are
adapted from the group32 GEMM in ROCm/aiter#5750.
"""
from typing import NamedTuple
import torch
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import direct_register_custom_op
BLOCK_ROWS = 32
# gfx950 hands out workgroups to its XCDs round-robin by program id, and 8 is
# a multiple of the XCD count in every partition mode. _split_tile hardcodes
# the same stride.
_XCD_STRIDE = 8
# One arrival counter per output tile of an in-launch split-K GEMM.
_SPLIT_COUNTERS = 1 << 16
@triton.jit
def _split_tile(N: tl.constexpr, BLOCK_N: tl.constexpr, SPLITS: tl.constexpr):
"""(pid_m, pid_n, tile, split) of a 1D grid that keeps a tile's splits on
one XCD, so they meet in that XCD's L2."""
pid = tl.program_id(0)
tile = pid // (8 * SPLITS) * 8 + pid % 8
grid_n: tl.constexpr = (N + BLOCK_N - 1) // BLOCK_N
return tile // grid_n, tile % grid_n, tile, pid // 8 % SPLITS
@triton.jit
def _sum_splits(
acc, out_ptrs, out_mask, slot_ptr, count_ptr, split, SPLITS: tl.constexpr
):
"""Publish this split's partial; the tile's last arrival sums all of them
in split order and re-arms the counter."""
BM: tl.constexpr = acc.shape[0]
BN: tl.constexpr = acc.shape[1]
local = tl.arange(0, BM)[:, None] * BN + tl.arange(0, BN)[None, :]
tl.store(slot_ptr + split * BM * BN + local, acc)
# The partial must be in L2 before the arrival is counted. The splits
# share an XCD, so no device-scope release (an L2 writeback) is needed.
tl.inline_asm_elementwise(
"s_waitcnt vmcnt(0)", "=v,v", [split], dtype=tl.int32, is_pure=False, pack=1
)
tl.debug_barrier()
if tl.atomic_add(count_ptr, 1, sem="acq_rel", scope="cta") == SPLITS - 1:
total = tl.zeros((BM, BN), dtype=tl.float32)
for s in tl.static_range(SPLITS):
total += tl.load(slot_ptr + s * BM * BN + local, cache_modifier=".cv")
tl.store(out_ptrs, total.to(out_ptrs.dtype.element_ty), mask=out_mask)
tl.store(count_ptr, 0)
@triton.jit(do_not_specialize=["M"])
def _block32_tiled_kernel(
x_ptr,
xs_ptr,
w_ptr,
ws_ptr,
out_ptr,
slot_ptr,
count_ptr,
M,
N: tl.constexpr,
K: tl.constexpr,
stride_om,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
K_PER_SPLIT: tl.constexpr,
N_FIRST: tl.constexpr,
EVEN_K: tl.constexpr,
FUSED_SPLITS: tl.constexpr,
):
if FUSED_SPLITS > 1:
pid_m, pid_n, tile, pid_k = _split_tile(N, BLOCK_N, FUSED_SPLITS)
if pid_m * BLOCK_M >= M:
return
else:
# N_FIRST launches output-column tiles fastest, so consecutive
# programs share an activation tile.
if N_FIRST:
pid_n, pid_m = tl.program_id(0), tl.program_id(1)
else:
pid_m, pid_n = tl.program_id(0), tl.program_id(1)
pid_k = tl.program_id(2)
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
m_mask = offs_m < M
n_mask = offs_n < N
k0 = pid_k * K_PER_SPLIT
offs_k = k0 + tl.arange(0, BLOCK_K)
offs_sk = k0 // 32 + tl.arange(0, BLOCK_K // 32)
x_ptrs = x_ptr + offs_m[:, None] * K + offs_k[None, :]
xs_ptrs = xs_ptr + offs_m[:, None] * (K // 32) + offs_sk[None, :]
w_ptrs = w_ptr + offs_n[:, None] * K + offs_k[None, :]
ws_ptrs = ws_ptr + (offs_n[:, None] // 32) * (K // 32) + offs_sk[None, :]
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
for kk in range(0, K_PER_SPLIT, BLOCK_K):
if EVEN_K:
x = tl.load(x_ptrs, mask=m_mask[:, None], other=0.0)
xs = tl.load(xs_ptrs, mask=m_mask[:, None], other=127)
w = tl.load(w_ptrs, mask=n_mask[:, None], other=0.0)
ws = tl.load(ws_ptrs, mask=n_mask[:, None], other=127)
else:
k_ok = (offs_k + kk) < K
s_ok = (offs_sk + kk // 32) < K // 32
x = tl.load(x_ptrs, mask=m_mask[:, None] & k_ok[None, :], other=0.0)
xs = tl.load(xs_ptrs, mask=m_mask[:, None] & s_ok[None, :], other=127)
w = tl.load(w_ptrs, mask=n_mask[:, None] & k_ok[None, :], other=0.0)
ws = tl.load(ws_ptrs, mask=n_mask[:, None] & s_ok[None, :], other=127)
acc = tl.dot_scaled(x, xs, "e4m3", w.T, ws, "e4m3", acc=acc)
x_ptrs += BLOCK_K
w_ptrs += BLOCK_K
xs_ptrs += BLOCK_K // 32
ws_ptrs += BLOCK_K // 32
out_mask = m_mask[:, None] & n_mask[None, :]
if FUSED_SPLITS > 1:
_sum_splits(
acc,
out_ptr + offs_m[:, None] * stride_om + offs_n[None, :],
out_mask,
slot_ptr + tile * (FUSED_SPLITS * BLOCK_M * BLOCK_N),
count_ptr + tile,
pid_k,
FUSED_SPLITS,
)
else:
out_ptrs = (
out_ptr + pid_k * M * N + offs_m[:, None] * stride_om + offs_n[None, :]
)
tl.store(out_ptrs, acc.to(out_ptr.dtype.element_ty), mask=out_mask)
@triton.jit(do_not_specialize=["M"])
def _block32_packed_kernel(
x_ptr,
xs_ptr,
w_ptr,
ws_ptr,
out_ptr,
slot_ptr,
count_ptr,
M,
N: tl.constexpr,
K: tl.constexpr,
stride_om,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
K_PACK: tl.constexpr,
K_PER_SPLIT: tl.constexpr,
EVEN_K: tl.constexpr,
FUSED_SPLITS: tl.constexpr,
):
if FUSED_SPLITS > 1:
pid_m, pid_n, tile, pid_k = _split_tile(N, BLOCK_N, FUSED_SPLITS)
if pid_m * BLOCK_M >= M:
return
k_start = pid_k * K_PER_SPLIT
k_stop = tl.minimum(k_start + K_PER_SPLIT, K)
else:
pid_m, pid_n, pid_k = tl.program_id(0), tl.program_id(1), tl.program_id(2)
if K_PER_SPLIT >= K:
k_start = 0
k_stop = K
else:
k_start = pid_k * K_PER_SPLIT
k_stop = tl.minimum(k_start + K_PER_SPLIT, K)
# Tile row r is token r // K_PACK reading K panel r % K_PACK (and likewise
# for weight rows), so one dot covers K_PACK consecutive BLOCK_K slices.
rows = pid_m * BLOCK_M + tl.arange(0, BLOCK_M * K_PACK) // K_PACK
x_panel = tl.arange(0, BLOCK_M * K_PACK) % K_PACK
cols = pid_n * BLOCK_N + tl.arange(0, BLOCK_N * K_PACK) // K_PACK
w_panel = tl.arange(0, BLOCK_N * K_PACK) % K_PACK
ks = tl.arange(0, BLOCK_K)
gs = tl.arange(0, BLOCK_K // 32)
row_ok = rows < M
col_ok = cols < N
acc = tl.zeros((BLOCK_M * K_PACK, BLOCK_N * K_PACK), dtype=tl.float32)
for base in range(k_start, k_stop, BLOCK_K * K_PACK):
xk = base + x_panel[:, None] * BLOCK_K + ks[None, :]
wk = base + w_panel[:, None] * BLOCK_K + ks[None, :]
xg = base // 32 + x_panel[:, None] * (BLOCK_K // 32) + gs[None, :]
wg = base // 32 + w_panel[:, None] * (BLOCK_K // 32) + gs[None, :]
x_mask = row_ok[:, None]
w_mask = col_ok[:, None]
xs_mask = row_ok[:, None]
ws_mask = col_ok[:, None]
if not EVEN_K:
x_mask = x_mask & (xk < K)
w_mask = w_mask & (wk < K)
xs_mask = xs_mask & (xg < K // 32)
ws_mask = ws_mask & (wg < K // 32)
x = tl.load(x_ptr + rows[:, None] * K + xk, mask=x_mask, other=0.0)
w = tl.load(w_ptr + cols[:, None] * K + wk, mask=w_mask, other=0.0)
xs = tl.load(xs_ptr + rows[:, None] * (K // 32) + xg, mask=xs_mask, other=127)
ws = tl.load(
ws_ptr + (cols[:, None] // 32) * (K // 32) + wg, mask=ws_mask, other=127
)
acc = tl.dot_scaled(x, xs, "e4m3", w.T, ws, "e4m3", acc=acc)
# Keep only products of matching K panels: the block diagonal.
blocks = acc.reshape(BLOCK_M, K_PACK, BLOCK_N, K_PACK).trans(0, 2, 1, 3)
pair = tl.arange(0, K_PACK)
diagonal = tl.where(
pair[None, None, :, None] == pair[None, None, None, :], blocks, 0.0
)
y = tl.sum(tl.sum(diagonal, 3), 2)
out_rows = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
out_cols = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
out_ptrs = out_ptr + out_rows[:, None] * stride_om + out_cols[None, :]
out_mask = (out_rows[:, None] < M) & (out_cols[None, :] < N)
if FUSED_SPLITS > 1:
_sum_splits(
y,
out_ptrs,
out_mask,
slot_ptr + tile * (FUSED_SPLITS * BLOCK_M * BLOCK_N),
count_ptr + tile,
pid_k,
FUSED_SPLITS,
)
else:
tl.store(
out_ptrs + pid_k * M * N, y.to(out_ptr.dtype.element_ty), mask=out_mask
)
@triton.jit(do_not_specialize=["M"])
def _block32_splitk_reduce_kernel(
partial_ptr,
out_ptr,
M,
N: tl.constexpr,
stride_om,
SPLIT_K: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
offs_m = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = tl.program_id(1) * BLOCK_N + tl.arange(0, BLOCK_N)
mask = (offs_m[:, None] < M) & (offs_n[None, :] < N)
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
for split in tl.static_range(SPLIT_K):
acc += tl.load(
partial_ptr + split * M * N + offs_m[:, None] * N + offs_n[None, :],
mask=mask,
other=0.0,
)
tl.store(
out_ptr + offs_m[:, None] * stride_om + offs_n[None, :],
acc.to(out_ptr.dtype.element_ty),
mask=mask,
)
class _Config(NamedTuple):
packed: bool
block_m: int
block_n: int
block_k: int
# K panels per MFMA tile (packed) or K partitions reduced by a second
# launch (tiled).
k_split: int
n_first: bool
num_warps: int
num_stages: int
matrix_instr_nonkdim: int
waves_per_eu: int
# K partitions summed within the launch.
fused_splits: int = 1
def _tiled(
bm, bn, bk, split_k, n_first, warps, stages, nonkdim, waves, fused=1
) -> _Config:
return _Config(
False, bm, bn, bk, split_k, bool(n_first), warps, stages, nonkdim, waves, fused
)
def _packed(bm, bn, bk, k_pack, warps, stages, nonkdim, waves, fused=1) -> _Config:
return _Config(
True, bm, bn, bk, k_pack, False, warps, stages, nonkdim, waves, fused
)
# (N, K) -> [(max M, config), ...] for the DeepSeek-V4.1-Flash MXFP8 linears at
# TP2/TP4, tuned on MI355X under HIP graphs with weights cold in the LLC. A
# tier serves every M up to its bound; larger M reuse the last tier.
_TUNED: dict[tuple[int, int], list[tuple[int, _Config]]] = {
# shared expert gate_up, TP4
(1152, 5120): [
(1, _packed(8, 16, 1024, 2, 2, 2, 16, 1, 3)),
(2, _packed(4, 32, 256, 4, 2, 2, 16, 1, 5)),
(4, _packed(4, 32, 256, 4, 2, 2, 16, 0, 5)),
(8, _packed(8, 16, 1024, 2, 2, 2, 16, 0, 3)),
(16, _tiled(16, 32, 512, 1, True, 2, 3, 16, 0, 5)),
(24, _tiled(32, 32, 512, 1, True, 4, 3, 16, 1, 5)),
(32, _packed(32, 32, 1024, 1, 4, 2, 16, 0, 5)),
(48, _tiled(64, 32, 512, 1, True, 4, 3, 16, 1, 5)),
(64, _tiled(64, 32, 512, 1, True, 8, 3, 16, 1, 5)),
(96, _tiled(32, 16, 1024, 1, True, 2, 3, 16, 1)),
(128, _tiled(64, 32, 512, 1, True, 8, 2, 16, 0, 3)),
(160, _tiled(64, 32, 512, 1, True, 8, 3, 16, 0, 2)),
(192, _tiled(32, 32, 1024, 1, True, 4, 2, 16, 0)),
(256, _tiled(64, 32, 256, 1, True, 4, 3, 16, 0, 3)),
(320, _tiled(64, 32, 256, 1, True, 8, 3, 16, 0, 2)),
(384, _tiled(32, 32, 512, 1, True, 4, 2, 16, 0)),
(512, _tiled(64, 64, 256, 1, True, 4, 2, 16, 0, 3)),
(768, _tiled(64, 64, 512, 1, True, 4, 2, 32, 0)),
(1024, _tiled(128, 128, 256, 2, False, 4, 2, 16, 1)),
(1536, _tiled(128, 128, 256, 2, False, 4, 2, 16, 0)),
(2048, _tiled(128, 128, 256, 1, False, 4, 2, 32, 0)),
(3072, _tiled(128, 128, 256, 1, False, 4, 2, 32, 1)),
(4096, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(8192, _tiled(128, 128, 256, 1, False, 4, 2, 32, 1)),
],
# fused wq_a|wkv (replicated)
(1792, 5120): [
(1, _packed(8, 16, 1024, 2, 2, 3, 16, 0)),
(8, _packed(8, 16, 1024, 2, 2, 3, 16, 1)),
(16, _tiled(16, 64, 1024, 1, True, 4, 2, 16, 0, 5)),
(32, _packed(16, 16, 1024, 1, 2, 3, 16, 1)),
(48, _tiled(64, 32, 512, 1, True, 8, 2, 16, 0, 4)),
(64, _tiled(64, 32, 512, 1, True, 8, 3, 16, 1, 4)),
(96, _tiled(64, 32, 512, 1, True, 8, 3, 16, 0, 2)),
(128, _tiled(64, 32, 256, 1, True, 4, 3, 16, 0, 4)),
(192, _tiled(64, 32, 256, 1, True, 4, 3, 16, 0, 3)),
(256, _tiled(64, 64, 512, 1, True, 4, 2, 16, 1, 2)),
(384, _tiled(64, 64, 256, 1, True, 4, 2, 16, 0, 3)),
(512, _tiled(64, 64, 512, 1, True, 4, 2, 32, 1)),
(768, _tiled(128, 128, 256, 1, True, 4, 2, 16, 1, 2)),
(1024, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(2048, _tiled(128, 128, 256, 1, False, 4, 2, 32, 1)),
(3072, _tiled(128, 128, 256, 1, False, 8, 2, 32, 1)),
(4096, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(8192, _tiled(128, 128, 128, 1, False, 8, 2, 16, 1)),
],
# shared expert gate_up, TP2
(2304, 5120): [
(1, _packed(8, 16, 1024, 2, 2, 3, 16, 1)),
(8, _packed(8, 16, 1024, 2, 2, 3, 16, 0)),
(16, _tiled(16, 64, 1024, 1, True, 4, 3, 16, 1, 5)),
(24, _packed(32, 32, 512, 1, 4, 2, 16, 0, 5)),
(32, _packed(32, 32, 1024, 1, 4, 2, 16, 1, 3)),
(48, _tiled(64, 32, 512, 1, True, 8, 3, 16, 0, 3)),
(64, _tiled(64, 64, 512, 1, True, 8, 2, 16, 0, 5)),
(128, _tiled(64, 32, 256, 1, True, 4, 3, 16, 0, 3)),
(160, _tiled(64, 64, 512, 1, True, 8, 2, 16, 1, 2)),
(192, _tiled(64, 64, 512, 1, True, 4, 2, 16, 0, 2)),
(256, _tiled(64, 64, 256, 1, True, 4, 2, 16, 0, 3)),
(320, _tiled(64, 64, 512, 1, True, 4, 2, 32, 0)),
(384, _tiled(64, 64, 512, 1, True, 4, 2, 32, 1)),
(512, _tiled(128, 128, 256, 1, True, 8, 2, 16, 0, 3)),
(768, _tiled(128, 128, 256, 1, True, 4, 2, 16, 1, 2)),
(1536, _tiled(128, 128, 256, 1, False, 4, 2, 32, 0)),
(2048, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(3072, _tiled(128, 128, 128, 1, True, 8, 2, 16, 0)),
(4096, _tiled(128, 128, 256, 1, False, 4, 2, 32, 1)),
(8192, _tiled(128, 128, 128, 1, False, 8, 2, 32, 0)),
],
# indexer wq_b
(4096, 1280): [
(1, _packed(4, 16, 256, 4, 4, 2, 16, 1)),
(2, _packed(4, 16, 256, 4, 4, 2, 16, 0)),
(4, _packed(4, 16, 256, 4, 4, 2, 16, 1)),
(8, _packed(8, 16, 256, 4, 4, 3, 16, 1)),
(16, _packed(16, 16, 512, 2, 2, 3, 16, 1)),
(32, _packed(32, 16, 1024, 1, 2, 3, 16, 1)),
(64, _tiled(32, 32, 512, 1, True, 4, 3, 16, 1)),
(128, _tiled(64, 32, 512, 1, True, 8, 3, 16, 0)),
(192, _tiled(64, 32, 256, 1, True, 4, 3, 16, 0)),
(256, _tiled(64, 64, 512, 1, True, 4, 2, 32, 1)),
(384, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(512, _tiled(128, 64, 256, 1, True, 8, 3, 32, 0)),
(1024, _tiled(128, 128, 256, 1, True, 4, 2, 32, 1)),
(2048, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(3072, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(4096, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(8192, _tiled(128, 128, 128, 1, True, 4, 2, 16, 0)),
],
# shared expert down, TP4
(5120, 576): [
(8, _packed(8, 32, 256, 2, 2, 2, 16, 1)),
(16, _packed(16, 32, 512, 1, 2, 2, 16, 0)),
(32, _packed(32, 32, 256, 1, 8, 3, 16, 1)),
(64, _tiled(32, 32, 128, 1, True, 4, 3, 16, 0)),
(96, _tiled(32, 64, 256, 1, True, 4, 3, 16, 0)),
(128, _tiled(32, 32, 256, 1, True, 2, 2, 16, 0)),
(192, _tiled(64, 64, 256, 1, True, 4, 3, 32, 0)),
(256, _tiled(64, 64, 256, 1, True, 2, 3, 32, 1)),
(320, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(384, _tiled(128, 64, 256, 1, True, 8, 3, 32, 1)),
(512, _tiled(64, 64, 128, 1, True, 4, 2, 32, 0)),
(768, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(1024, _tiled(128, 64, 128, 1, True, 4, 2, 32, 0)),
(3072, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(4096, _tiled(128, 128, 128, 1, True, 8, 2, 32, 0)),
(8192, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
],
# shared expert down, TP2
(5120, 1152): [
(1, _packed(4, 32, 128, 4, 2, 3, 16, 1)),
(8, _packed(8, 32, 256, 2, 4, 3, 16, 0)),
(32, _packed(32, 32, 512, 1, 2, 3, 16, 1)),
(128, _tiled(32, 32, 128, 1, True, 4, 3, 16, 0)),
(192, _tiled(64, 64, 512, 1, True, 4, 2, 32, 1)),
(320, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(384, _tiled(128, 64, 256, 1, True, 8, 3, 32, 1)),
(512, _tiled(128, 128, 256, 1, True, 4, 2, 32, 1)),
(768, _tiled(128, 128, 256, 1, True, 4, 2, 32, 0)),
(1024, _tiled(128, 64, 128, 1, True, 8, 2, 32, 0)),
(1536, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(2048, _tiled(128, 128, 128, 1, True, 8, 2, 32, 0)),
(3072, _tiled(128, 256, 128, 1, True, 2, 2, 32, 0)),
(4096, _tiled(128, 128, 128, 1, True, 8, 2, 32, 0)),
(8192, _tiled(128, 64, 128, 1, True, 8, 2, 32, 1)),
],
# wo_b, TP4
(5120, 2048): [
(1, _packed(4, 32, 256, 4, 2, 2, 16, 0)),
(4, _packed(4, 32, 256, 4, 2, 2, 16, 1)),
(8, _packed(8, 32, 256, 4, 2, 3, 16, 0)),
(16, _tiled(16, 32, 1024, 1, True, 2, 3, 16, 0)),
(32, _tiled(32, 32, 512, 1, False, 4, 3, 16, 1)),
(64, _tiled(32, 32, 512, 1, True, 4, 2, 16, 0)),
(96, _tiled(32, 64, 512, 1, True, 8, 2, 16, 0)),
(128, _tiled(64, 64, 512, 1, True, 4, 2, 32, 0)),
(192, _tiled(64, 64, 512, 1, True, 4, 2, 32, 1)),
(320, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(384, _tiled(128, 64, 256, 1, True, 8, 3, 32, 0)),
(768, _tiled(128, 128, 256, 1, True, 4, 2, 32, 0)),
(1024, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(1536, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(2048, _tiled(128, 128, 256, 1, True, 8, 2, 32, 1)),
(4096, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(8192, _tiled(128, 128, 128, 1, True, 2, 2, 32, 1)),
],
# wo_b, TP2
(5120, 4096): [
(4, _packed(4, 32, 512, 4, 2, 2, 16, 0)),
(8, _packed(8, 16, 128, 4, 2, 2, 16, 0, 2)),
(16, _tiled(16, 32, 256, 1, True, 2, 2, 16, 0, 4)),
(24, _tiled(32, 32, 256, 1, True, 4, 3, 16, 0, 4)),
(32, _tiled(32, 64, 512, 1, True, 8, 3, 16, 0, 3)),
(48, _tiled(64, 64, 512, 1, True, 8, 2, 16, 1, 3)),
(64, _tiled(64, 64, 512, 1, True, 8, 2, 16, 0, 3)),
(128, _tiled(64, 64, 256, 1, True, 4, 2, 16, 0, 3)),
(192, _tiled(64, 64, 512, 1, True, 4, 2, 32, 0)),
(256, _tiled(128, 128, 256, 1, True, 4, 2, 16, 1, 2)),
(320, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(384, _tiled(128, 128, 256, 1, True, 4, 2, 16, 0, 2)),
(768, _tiled(128, 128, 256, 1, True, 4, 2, 32, 1)),
(1024, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(1536, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(2048, _tiled(128, 128, 256, 1, True, 8, 2, 32, 1)),
(3072, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(4096, _tiled(128, 128, 128, 1, True, 8, 2, 16, 1)),
(8192, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
],
# wq_b, TP4
(8192, 1280): [
(1, _packed(8, 32, 256, 2, 4, 3, 16, 1)),
(8, _packed(8, 32, 256, 2, 4, 3, 16, 0)),
(16, _packed(16, 32, 1024, 1, 2, 3, 16, 1)),
(32, _packed(32, 32, 512, 1, 2, 3, 16, 0)),
(48, _tiled(64, 32, 512, 1, True, 8, 3, 16, 1)),
(64, _packed(32, 64, 256, 1, 4, 3, 16, 1)),
(128, _tiled(64, 64, 512, 1, True, 4, 2, 32, 1)),
(192, _tiled(64, 64, 256, 1, True, 4, 2, 32, 0)),
(256, _tiled(128, 64, 256, 1, True, 8, 3, 32, 1)),
(384, _tiled(128, 128, 256, 1, True, 4, 2, 32, 1)),
(512, _tiled(128, 128, 256, 1, True, 4, 2, 32, 0)),
(1024, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(1536, _tiled(128, 128, 128, 1, True, 8, 2, 16, 0)),
(4096, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(8192, _tiled(128, 256, 128, 1, True, 2, 2, 32, 0)),
],
# wq_b, TP2
(16384, 1280): [
(2, _packed(4, 32, 128, 4, 2, 3, 16, 1)),
(4, _packed(4, 32, 128, 4, 4, 2, 16, 0)),
(8, _packed(8, 32, 256, 2, 4, 2, 16, 0)),
(32, _packed(32, 64, 256, 1, 4, 3, 16, 1)),
(64, _tiled(64, 64, 256, 1, False, 4, 3, 32, 1)),
(128, _tiled(128, 64, 256, 1, True, 8, 3, 32, 0)),
(256, _tiled(128, 128, 256, 1, True, 4, 2, 32, 1)),
(384, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(512, _tiled(128, 128, 128, 1, True, 8, 2, 32, 0)),
(768, _tiled(128, 128, 128, 1, True, 8, 2, 16, 1)),
(1024, _tiled(128, 128, 128, 1, True, 8, 2, 32, 1)),
(2048, _tiled(128, 128, 128, 1, True, 4, 2, 32, 0)),
(8192, _tiled(128, 256, 128, 1, True, 2, 2, 32, 0)),
],
}
def _default_config(M: int, N: int, K: int) -> _Config:
"""Untuned shapes: the tiers most tuned shapes settle on."""
if M <= 8:
return _packed(8, 16, 256, 2, 2, 3, 16, 0)
if M <= 32:
return _packed(32, 32, 256, 1, 2, 3, 16, 0)
if M <= 256:
return _tiled(64, 64, 256, 1, True, 4, 2, 16, 0)
return _tiled(128, 128, 128, 1, True, 4, 2, 16, 0)
def _config(M: int, N: int, K: int) -> _Config:
tiers = _TUNED.get((N, K))
if tiers is None:
return _default_config(M, N, K)
for max_m, cfg in tiers:
if max_m >= M:
return cfg
return tiers[-1][1]
_split_counters_by_stream: dict[tuple[int, int], torch.Tensor] = {}
def _split_counters(device: torch.device) -> torch.Tensor | None:
"""Zeroed arrival counters, one set per stream so concurrent launches never
share a tile's counter. Each launch leaves the counters it used at zero.
None when a stream first needs them inside a CUDA graph capture: that
allocation would come from the graph's pool, where it can take the address
of an intermediate that every replay overwrites. vLLM warms up on its
capture streams first, so this only affects captures without a warmup.
"""
key = (device.index, torch.accelerator.current_stream(device).stream_id)
counters = _split_counters_by_stream.get(key)
if counters is None:
if torch.cuda.is_current_stream_capturing():
return None
counters = torch.zeros(_SPLIT_COUNTERS, dtype=torch.int32, device=device)
_split_counters_by_stream[key] = counters
return counters
def _k_partition(K: int, splits: int, step: int) -> tuple[int, int]:
"""K per split, rounded up to whole steps, and the number of non-empty
splits."""
size = triton.cdiv(triton.cdiv(K, splits), step) * step
return size, triton.cdiv(K, size)
def _launch(
x: torch.Tensor,
x_scale: torch.Tensor,
weight: torch.Tensor,
weight_scale: torch.Tensor,
out: torch.Tensor,
cfg: _Config,
) -> None:
M, K = x.shape
N = weight.shape[0]
opts = dict(
num_warps=cfg.num_warps,
num_stages=cfg.num_stages,
matrix_instr_nonkdim=cfg.matrix_instr_nonkdim,
waves_per_eu=cfg.waves_per_eu,
)
grid_m, grid_n = triton.cdiv(M, cfg.block_m), triton.cdiv(N, cfg.block_n)
tiles = grid_m * grid_n
step = cfg.block_k * cfg.k_split if cfg.packed else cfg.block_k
splits = cfg.fused_splits if cfg.fused_splits > 1 or cfg.packed else cfg.k_split
k_per_split, splits = _k_partition(K, splits, step)
counters = None
if cfg.fused_splits > 1 and splits > 1 and tiles <= _SPLIT_COUNTERS:
counters = _split_counters(out.device)
if counters is not None:
fused = splits
target = out
slots = torch.empty(
tiles * fused * cfg.block_m * cfg.block_n,
dtype=torch.float32,
device=out.device,
)
grid: tuple[int, ...] = (triton.cdiv(tiles, _XCD_STRIDE) * _XCD_STRIDE * fused,)
else:
# Without counters, split K through a second launch.
fused = 1
target = (
out
if splits == 1
else torch.empty((splits, M, N), dtype=torch.float32, device=x.device)
)
slots = counters = target # Unused by the kernels.
if cfg.packed or not cfg.n_first:
grid = (grid_m, grid_n, splits)
else:
grid = (grid_n, grid_m, splits)
args = (x, x_scale, weight, weight_scale, target, slots, counters, M, N, K)
stride = out.stride(0) if splits == 1 or fused > 1 else N
if cfg.packed:
_block32_packed_kernel[grid](
*args,
stride,
BLOCK_M=cfg.block_m,
BLOCK_N=cfg.block_n,
BLOCK_K=cfg.block_k,
K_PACK=cfg.k_split,
K_PER_SPLIT=k_per_split,
EVEN_K=K % step == 0,
FUSED_SPLITS=fused,
**opts,
)
else:
_block32_tiled_kernel[grid](
*args,
stride,
BLOCK_M=cfg.block_m,
BLOCK_N=cfg.block_n,
BLOCK_K=cfg.block_k,
K_PER_SPLIT=k_per_split,
N_FIRST=cfg.n_first,
EVEN_K=K % k_per_split == 0,
FUSED_SPLITS=fused,
**opts,
)
if fused == 1 and splits > 1:
_block32_splitk_reduce_kernel[(triton.cdiv(M, 32), triton.cdiv(N, 64))](
target,
out,
M,
N,
out.stride(0),
SPLIT_K=splits,
BLOCK_M=32,
BLOCK_N=64,
)
def _rocm_mxfp8_block32_gemm_impl(
x: torch.Tensor,
x_scale: torch.Tensor,
weight: torch.Tensor,
weight_scale: torch.Tensor,
out_dtype: torch.dtype,
) -> torch.Tensor:
M, K = x.shape
out = torch.empty((M, weight.shape[0]), dtype=out_dtype, device=x.device)
if M > 0:
_launch(x, x_scale, weight, weight_scale, out, _config(M, weight.shape[0], K))
return out
def _rocm_mxfp8_block32_gemm_fake(
x: torch.Tensor,
x_scale: torch.Tensor,
weight: torch.Tensor,
weight_scale: torch.Tensor,
out_dtype: torch.dtype,
) -> torch.Tensor:
return x.new_empty((x.shape[0], weight.shape[0]), dtype=out_dtype)
# An opaque op: the kernel and tile choice branch on the token count, which a
# compiled caller must not freeze at its trace-time value.
direct_register_custom_op(
op_name="rocm_mxfp8_block32_gemm",
op_func=_rocm_mxfp8_block32_gemm_impl,
fake_impl=_rocm_mxfp8_block32_gemm_fake,
)
def rocm_mxfp8_block32_gemm(
x: torch.Tensor,
x_scale: torch.Tensor,
weight: torch.Tensor,
weight_scale: torch.Tensor,
out_dtype: torch.dtype,
) -> torch.Tensor:
"""``x @ weight.T`` for MXFP8 ``x`` and a 32x32 block-scaled MXFP8 weight.
Args:
x: [M, K] e4m3 activation, contiguous.
x_scale: [M, K / 32] E8M0 (uint8) activation scales.
weight: [N, K] e4m3 weight, contiguous.
weight_scale: [ceil(N / 32), K / 32] E8M0 (uint8) weight block scales.
out_dtype: Output dtype.
Returns:
The [M, N] product.
"""
return torch.ops.vllm.rocm_mxfp8_block32_gemm(
x, x_scale, weight, weight_scale, out_dtype
)
@@ -22,6 +22,7 @@ from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig
from .rocm_block32_gemm import BLOCK_ROWS, rocm_mxfp8_block32_gemm
@triton.jit
@@ -119,12 +120,10 @@ def _mxfp8_dot_scaled_linear(
return out
# Triton 3.8 enables TRITON_HIP_USE_ASYNC_COPY by default on gfx950; its extra LDS
# buffer leaves no room for num_stages=3 at BLOCK_K=256.
# TODO(rasmith)(Rohan138): Remove the 3.8 check once
# https://github.com/vllm-project/vllm/pull/50605 merges.
# gfx950's async-copy LDS (default in the triton 3.8 this branch pins) leaves no
# room for num_stages=3 at BLOCK_K=256; use 2 there.
_BK256_STAGES = 3
if triton.__version__.startswith("3.8") and current_platform.is_rocm():
if current_platform.is_rocm():
from vllm.platforms.rocm import on_gfx950
if on_gfx950():
@@ -209,6 +208,17 @@ def _select_cfg(M, N, K):
_DOT_SCALED_K_ALIGN = 128
def _as_block32_scale(weight_scale: torch.Tensor) -> torch.Tensor | None:
"""The [N / 32, K / 32] block scales, if every 32 rows share their scales."""
N = weight_scale.shape[0]
if N % BLOCK_ROWS != 0:
return None
blocks = weight_scale.view(N // BLOCK_ROWS, BLOCK_ROWS, -1)
if not torch.equal(blocks, blocks[:, :1].expand_as(blocks)):
return None
return blocks[:, 0].contiguous()
class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
"""Native CDNA4 (gfx950) MXFP8 linear via Triton ``tl.dot_scaled``."""
@@ -236,7 +246,13 @@ 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:
block_scale = _as_block32_scale(weight_scale)
if block_scale is not None:
# Checkpoints with 32x32 scale blocks (DeepSeek V4/V4.1) get them
# back from the loader expanded per row; keep the blocks and use
# the block-scaled GEMM, which also handles any K % 32 == 0.
weight_scale = block_scale
elif 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)
@@ -254,7 +270,13 @@ class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
)
out_shape = (*x.shape[:-1], layer.weight.shape[0])
x2d = x.reshape(-1, x.shape[-1])
if layer.weight.element_size() >= 2:
if layer.weight_scale.shape[0] != layer.weight.shape[0]:
# One scale row per 32 weight rows (see process_weights_after_loading).
x_q, x_scale = mxfp8_e4m3_quantize(x2d)
out = rocm_mxfp8_block32_gemm(
x_q, x_scale, layer.weight, layer.weight_scale, x.dtype
)
elif 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)
+1 -1
View File
@@ -81,7 +81,7 @@ def hc_head_fused_cpu(
hc_eps: float,
) -> torch.Tensor:
"""CPU-ported HC head reduction (see `test_hc_head_cpu` in
tests/kernels/test_mhc_kernels.py for the eager reference this is tested
tests/kernels/mhc/test_mhc_kernels.py for the eager reference this is tested
against).
The ported kernel's C++ signature takes `(hc_eps, norm_eps)` -- the
@@ -23,6 +23,23 @@ from vllm.utils.math_utils import cdiv
ENABLE_PDL = current_platform.is_arch_support_pdl() and current_platform.is_cuda()
# TileLang's HIP AllReduce shuffle phase ignores a nonzero reduction-group
# offset, so the 64-thread RMSNorm reduction must be wave64-aligned and use
# threads 0..63.
_MIX_ON_TRAILING_THREADS = current_platform.is_rocm()
def _is_mix_thread():
if _MIX_ON_TRAILING_THREADS:
return T.get_thread_binding() >= 64
return T.get_thread_binding() < 32
def _is_collapse_thread():
if _MIX_ON_TRAILING_THREADS:
return T.get_thread_binding() < 64
return T.get_thread_binding() >= 32
@cache
def compute_num_split(block_k: int, k: int | None, grid_size: int) -> int:
@@ -353,7 +370,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
mixes[j] *= rms[0]
T.copy(mixes, mixes_shared)
if split_mode != "input" and T.get_thread_binding() < 32:
if split_mode != "input" and _is_mix_thread():
cm = T.alloc_fragment((hc_mult, hc_mult), T.float32)
for j in T.Parallel(hc_mult):
if save_pre_mix:
@@ -399,7 +416,7 @@ def mhc_pre_big_fuse_with_norm_tilelang(
for j, k in T.Parallel(hc_mult, hc_mult):
comb_mix[i, j * hc_mult + k] = cm[j, k]
elif split_mode != "stats" and T.get_thread_binding() >= 32:
elif split_mode != "stats" and _is_collapse_thread():
pre_mix_shared = T.alloc_shared(hc_mult, T.float32)
for j in T.Parallel(hc_mult):
if use_pre_mix_in:
@@ -546,7 +563,7 @@ def mhc_pre_big_fuse_broadcast_with_norm_tilelang(
mixes_shared = T.alloc_shared(hc_mult3, T.float32)
T.copy(mixes, mixes_shared)
if T.get_thread_binding() < 32:
if _is_mix_thread():
cm = T.alloc_fragment((hc_mult, hc_mult), T.float32)
for j in T.Parallel(hc_mult):
post_mix[i, j] = (
+6 -6
View File
@@ -233,12 +233,8 @@ class SiluAndMulWithClamp(CustomOp):
self.swiglu_limit = float(swiglu_limit)
self.alpha = float(alpha)
self.beta = float(beta)
if current_platform.is_rocm() or current_platform.is_xpu():
self._forward_method = self.forward_native
elif current_platform.is_cuda_alike():
if current_platform.is_cuda_alike():
self.op = torch.ops._C.silu_and_mul_with_clamp
elif current_platform.is_cpu():
self._forward_method = self.forward_native
def forward_native(self, x: torch.Tensor) -> torch.Tensor:
d = x.shape[-1] // 2
@@ -253,7 +249,11 @@ class SiluAndMulWithClamp(CustomOp):
self.op(out, x, self.swiglu_limit, self.alpha, self.beta)
return out
def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
def forward_hip(self, x: torch.Tensor) -> torch.Tensor:
# Limit the ROCm _C path to the default case to avoid the
# precision loss MiniMax saw without fp32 intermediates.
if self.alpha == 1.0 and self.beta == 0.0:
return self.forward_cuda(x)
return self.forward_native(x)
def extra_repr(self) -> str:
@@ -8,7 +8,10 @@ import torch.nn as nn
import vllm.envs as envs
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import CacheConfig, get_current_vllm_config
from vllm.config import (
CacheConfig,
get_current_vllm_config,
)
from vllm.config.vllm import VllmConfig
from vllm.forward_context import ForwardContext, get_forward_context
from vllm.logger import init_logger
@@ -100,6 +103,7 @@ def _largest_kernel_block_within(
per_token_bytes: int,
page_budget: int,
fallback: int,
kv_cache_spec: KVCacheSpec | None = None,
) -> int:
"""Largest supported kernel block size whose page fits in ``page_budget``.
@@ -111,7 +115,7 @@ def _largest_kernel_block_within(
"""
from vllm.v1.attention.backend import MultipleOf
sizes = attn_backend.get_supported_kernel_block_sizes()
sizes = attn_backend.get_supported_kernel_block_sizes(kv_cache_spec)
max_block_size = page_budget // per_token_bytes
candidates = [s for s in sizes if isinstance(s, int)]
candidates.extend(
@@ -632,7 +636,7 @@ class Attention(nn.Module, AttentionLayerBase):
# ``unify`` scales it up by an integer ratio.
shared_page = vllm_config.cache_config.skip_page_size_padded
# The backend owns its packing
sw_per_token = self.attn_backend.customize_spec(
kv_cache_spec = self.attn_backend.customize_spec(
SlidingWindowSpec(
block_size=1,
num_kv_heads=self.num_kv_heads,
@@ -642,10 +646,15 @@ class Attention(nn.Module, AttentionLayerBase):
kv_quant_mode=quant_mode,
sliding_window=self.sliding_window,
)
).real_page_size_bytes
)
sw_per_token = kv_cache_spec.real_page_size_bytes
page_budget = shared_page or sw_per_token * block_size
sw_block_size = _largest_kernel_block_within(
self.attn_backend, sw_per_token, page_budget, block_size
self.attn_backend,
sw_per_token,
page_budget,
block_size,
kv_cache_spec,
)
return SlidingWindowSpec(
block_size=sw_block_size,
@@ -404,6 +404,24 @@ def _get_kv_b_proj_input_dtype(
return weight_dtype
def split_kv_b_proj(
kv_b_proj: nn.Module,
out_dtype: torch.dtype,
kv_lora_rank: int,
num_heads: int,
qk_nope_head_dim: int,
v_head_dim: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Dequantize ``kv_b_proj`` and return ``W_UK [L,N,P]``, ``W_UV [L,N,V]``."""
weight = get_and_maybe_dequant_weights(kv_b_proj, out_dtype=out_dtype).T
assert weight.shape == (
kv_lora_rank,
num_heads * (qk_nope_head_dim + v_head_dim),
), f"kv_b_proj weight {tuple(weight.shape)} vs {kv_lora_rank=} {num_heads=}"
weight = weight.view(kv_lora_rank, num_heads, qk_nope_head_dim + v_head_dim)
return weight.split([qk_nope_head_dim, v_head_dim], dim=-1)
class MLAAttention(nn.Module, AttentionLayerBase):
"""Multi-Head Latent Attention layer.
@@ -717,13 +735,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
self.kv_cache = kv_cache.squeeze(1)
if (
self._vllm_config.kernel_config.enable_jit_warmup
and self.attn_backend.get_name()
in (
"FLASHMLA_SPARSE",
"FLASHINFER_MLA_SPARSE",
"FLASHINFER_MLA_SPARSE_SM120",
"DEEPSEEK_V32_INDEXER",
)
and self._uses_flat_kv_cache()
):
from vllm.v1.attention.backends.mla.sparse_utils import (
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL,
@@ -736,6 +748,13 @@ class MLAAttention(nn.Module, AttentionLayerBase):
block_stride_rows=self.kv_cache.stride(0) // row_width,
)
def _uses_flat_kv_cache(self) -> bool:
backend = self.attn_backend.get_name()
return backend == "FLASHINFER_MLA_SPARSE" or (
backend == "FLASHMLA_SPARSE"
and self.kv_cache_dtype not in ("fp8_ds_mla", "nvfp4_ds_mla")
)
@property
def chunked_prefill_workspace_size(self) -> int:
if self._chunked_prefill_workspace_size is None:
@@ -1025,9 +1044,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
mqa_q_pe = mqa_pe_padded
if self.is_aiter_triton_fp4_bmm_enabled:
from aiter.ops.triton.batched_gemm_a16wfp4 import batched_gemm_a16wfp4
mqa_ql_nope = batched_gemm_a16wfp4(
mqa_ql_nope = rocm_aiter_ops.batched_gemm_a16wfp4(
mqa_q_nope,
self.W_K,
self.W_K_scale,
@@ -1223,13 +1240,6 @@ class MLAAttention(nn.Module, AttentionLayerBase):
)
return
# we currently do not have quantized bmm's which are needed for
# `W_UV` and `W_UK_T`, we just store fp16/bf16 copies and perform
# the bmm's in 16-bit, the extra memory overhead of this is fairly low
kv_b_proj_weight = get_and_maybe_dequant_weights(
self.kv_b_proj, out_dtype=act_dtype
).T
if self.dcp_q_replicate:
# qrep wired here: validate unsupported decode backends once.
assert self.q_pad_num_heads in (None, self.num_heads), (
@@ -1245,24 +1255,13 @@ class MLAAttention(nn.Module, AttentionLayerBase):
"FP4/FP8 MLA BMM paths."
)
assert kv_b_proj_weight.shape == (
self.kv_lora_rank,
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
), (
f"{kv_b_proj_weight.shape=}, "
f"{self.kv_lora_rank=}, "
f"{self.num_heads=}, "
f"{self.qk_nope_head_dim=}, "
f"{self.v_head_dim=}"
)
kv_b_proj_weight = kv_b_proj_weight.view(
W_UK, W_UV = split_kv_b_proj(
self.kv_b_proj,
act_dtype,
self.kv_lora_rank,
self.num_heads,
self.qk_nope_head_dim + self.v_head_dim,
)
W_UK, W_UV = kv_b_proj_weight.split(
[self.qk_nope_head_dim, self.v_head_dim], dim=-1
self.qk_nope_head_dim,
self.v_head_dim,
)
# If kv_b_proj_weight is unquantized, quantize it to mxfp4 if supported
@@ -1367,11 +1366,20 @@ class MLAAttention(nn.Module, AttentionLayerBase):
**common_kwargs,
sliding_window=self.sliding_window,
)
return MLAAttentionSpec(
spec = MLAAttentionSpec(
**common_kwargs,
is_index_group_leader=self.indexer is not None,
non_causal_multi_token_decode=self.non_causal_multi_token_decode,
)
# SM100 FlashMLA paged kernels also express TMA coordinates in token rows.
uses_tma_rows = (
self.attn_backend.get_name() == "FLASHMLA_SPARSE"
and self.kv_cache_dtype in ("fp8_ds_mla", "nvfp4_ds_mla")
and current_platform.is_device_capability_family(100)
)
if self._uses_flat_kv_cache() or uses_tma_rows:
spec = replace(spec, block_stride_alignment=spec.state_content_size_bytes)
return spec
def _v_up_proj(self, x: torch.Tensor, out: torch.Tensor):
# Convert from (B, N, L) to (N, B, L)
@@ -2473,6 +2481,7 @@ class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
query_start_loc_cpu: torch.Tensor,
query_start_loc_device: torch.Tensor,
num_decode_tokens: int,
max_query_len: int,
dcp_tot_seq_lens_device: torch.Tensor | None,
) -> MLACommonDecodeMetadata:
return MLACommonDecodeMetadata(
@@ -2637,6 +2646,9 @@ class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]):
query_start_loc_cpu=query_start_loc_cpu[: num_decodes + 1],
query_start_loc_device=query_start_loc[: num_decodes + 1],
num_decode_tokens=num_decode_tokens,
max_query_len=min(
common_attn_metadata.max_query_len, self.reorder_batch_threshold
),
dcp_tot_seq_lens_device=dcp_tot_seq_lens_device,
)
@@ -291,17 +291,7 @@ class SparseMLACommonMetadataBuilder(AttentionMetadataBuilder[T]):
self,
common_attn_metadata: "CommonAttentionMetadata",
) -> torch.Tensor:
num_tokens = common_attn_metadata.num_actual_tokens
starts = np.asarray(common_attn_metadata.query_start_loc_cpu, dtype=np.int32)
seg_lengths = np.diff(starts)
req_id_per_token = np.repeat(
np.arange(seg_lengths.shape[0], dtype=np.int32), seg_lengths
)
self.req_id_per_token_buffer.fill_(0)
self.req_id_per_token_buffer[: req_id_per_token.shape[0]].copy_(
np_to_pinned_tensor(req_id_per_token), non_blocking=True
)
return self.req_id_per_token_buffer[:num_tokens]
return common_attn_metadata.token_to_req_indices(self.req_id_per_token_buffer)
def _build_chunked_context_fields(
self,
@@ -48,9 +48,18 @@ class FlashInferOneSidedDispatchLayout:
def flashinfer_one_sided_dispatch_layout(
hidden_dim: int, quant_config: FusedMoEQuantConfig
hidden_dim: int,
quant_config: FusedMoEQuantConfig,
input_dtype: torch.dtype | None = None,
) -> FlashInferOneSidedDispatchLayout:
"""Return the one-sided activation payload layout."""
if input_dtype is not None:
if input_dtype not in (torch.float16, torch.bfloat16):
raise ValueError(
"flashinfer_nvlink_one_sided unpacked inputs must be float16 "
f"or bfloat16, got {input_dtype}"
)
return FlashInferOneSidedDispatchLayout(hidden_dim * input_dtype.itemsize, 0)
if quant_config.quant_dtype is None:
return FlashInferOneSidedDispatchLayout(hidden_dim * 2, 0)
if quant_config.quant_dtype == "nvfp4":
@@ -174,6 +183,7 @@ def maybe_make_prepare_finalize(
allow_new_interface: bool = False,
use_monolithic: bool = False,
all2all_manager: Any | None = None,
input_dtype: torch.dtype | None = None,
) -> FusedMoEPrepareAndFinalize | None:
if not moe.moe_parallel_config.use_all2all_kernels:
if not allow_new_interface:
@@ -367,7 +377,7 @@ def maybe_make_prepare_finalize(
get_current_vllm_config().scheduler_config.max_num_batched_tokens
)
dispatch_layout = flashinfer_one_sided_dispatch_layout(
moe.hidden_dim, quant_config
moe.hidden_dim, quant_config, input_dtype=input_dtype
)
prepare_finalize = FlashInferNVLinkOneSidedPrepareAndFinalize(
max_num_tokens=max_num_tokens,
+57 -13
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Union
@@ -1290,13 +1290,12 @@ class FusedMoEConfig:
# Only honored on the non-reduced (late-AR) TP path. Default False.
skip_final_all_reduce: bool = False
# When True, experts that can stop after GEMM2 are allowed to hand back an
# UnfinalizedMoEOutput instead of finalized states, leaving the top-k
# reduction to fuse into the consumer. Set by layers that have such a
# consumer; read through `use_deferred_moe_finalize`, which applies the
# guards. Kernels without the capability ignore it. Default False.
defer_moe_finalize: bool = False
# Optional consumer capacity for deferred finalize. Negative means unbounded.
# Requested through `defer_moe_finalize()`, read through
# `should_defer_moe_finalize()`.
_defer_moe_finalize: bool = field(default=False, init=False)
# Most tokens a deferred call covers: the consumer's capacity, lowered by
# experts that would split a larger call across kernel launches. Negative
# means unbounded.
defer_moe_finalize_max_num_tokens: int = -1
# SwiGLU clamp limit. When set, backends that do not implement the clamp
@@ -1422,21 +1421,57 @@ class FusedMoEConfig:
def use_deferred_moe_finalize(self) -> bool:
"""Whether experts may return an unfinalized output on this deployment.
Evaluated on read rather than in ``__post_init__`` because
``defer_moe_finalize`` is set after construction, like
``skip_final_all_reduce``.
Evaluated on read rather than in ``__post_init__`` because deferral is
requested after construction, like ``skip_final_all_reduce``.
"""
# The consumer fuses a TP all-reduce. Other parallel modes require a
# combine or reduce-scatter after the experts and cannot defer it.
# combine or reduce-scatter after the experts and cannot defer it, and
# the consumer has no way to strip hidden-dim padding from GEMM2 rows.
return (
self.defer_moe_finalize
self._defer_moe_finalize
and self.tp_size > 1
and self.dp_size == 1
and self.ep_size == 1
and self.pcp_size == 1
and not self.is_sequence_parallel
and self.hidden_dim == self.hidden_dim_unpadded
)
def defer_moe_finalize(self, max_num_tokens: int = -1) -> None:
"""Ask the experts to leave the top-k reduction to the layer's consumer.
A layer whose consumer can fuse the top-k reduction (e.g. into its TP
all-reduce) calls this once while the model is built, and only when its
experts are TRTLLM-Gen ones that can stop after GEMM2 (the
``do_finalize=False`` path). Other experts ignore the request and
always finalize, which ``should_defer_moe_finalize`` can't see, so the
layer checks the quant method's ``experts_cls`` first, as Kimi-K3 does.
From then on:
- The experts return an ``UnfinalizedMoEOutput`` instead of finalized
states for every call ``should_defer_moe_finalize`` accepts.
- ``should_defer_moe_finalize(num_tokens)`` is the answer for a call:
it requires a TP-only deployment without hidden-dim padding
(``use_deferred_moe_finalize``), a non-empty call and at most
``defer_moe_finalize_max_num_tokens`` tokens. The cap starts at
``max_num_tokens`` and only ever goes down: experts that would split a
larger call across kernel launches lower it to their single-launch
size when they are built, since each launch permutes into its own
buffer.
- The model asks ``should_defer_moe_finalize`` before each call and takes
the matching path. A deferred call runs the runner's ``_forward_impl``
directly, since the MoE custom op returns tensors only, and the
consumer then owns the top-k reduction, the shared-expert add and the
all-reduce.
Args:
max_num_tokens: Most tokens per call the consumer can take in
deferred form. Negative means no limit of its own.
"""
self._defer_moe_finalize = True
self.limit_deferred_moe_finalize(max_num_tokens)
def should_defer_moe_finalize(self, num_tokens: int) -> bool:
"""Return whether this invocation may defer the top-k reduction."""
max_num_tokens = self.defer_moe_finalize_max_num_tokens
@@ -1446,6 +1481,15 @@ class FusedMoEConfig:
and (max_num_tokens < 0 or num_tokens <= max_num_tokens)
)
def limit_deferred_moe_finalize(self, max_num_tokens: int) -> None:
"""Finalize calls above ``max_num_tokens`` even when deferring.
Negative means no limit, and leaves the current one in place.
"""
current = self.defer_moe_finalize_max_num_tokens
if max_num_tokens >= 0 and (current < 0 or max_num_tokens < current):
self.defer_moe_finalize_max_num_tokens = max_num_tokens
@property
def use_deepep_ht_kernels(self):
return self.moe_parallel_config.use_deepep_ht_kernels
@@ -1326,7 +1326,9 @@ class CutlassExpertsW4A8Fp8(mk.FusedMoEExpertsModular):
@staticmethod
def _supports_current_device() -> bool:
return cutlass_group_gemm_supported()
return (
current_platform.is_device_capability(90) and cutlass_group_gemm_supported()
)
@staticmethod
def _supports_no_act_and_mul() -> bool:
@@ -1294,9 +1294,6 @@ class UnfusedOAITritonExperts(LoRAExpertsMixin, BaseOAITritonExperts):
if triton_kernels_version == "3.8":
# Activation and topk-reduce kept unfused from the matmuls (3.8 has
# no in-kernel scatter+reduce); combine via external index_add.
assert self._lora_context is None, (
"tk38 unfused MoE path does not support LoRA yet"
)
act_out_dim = self.adjust_N_for_activation(w1.shape[2], activation)
M, K = hidden_states.shape[-2:]
a_ragged = routing_data.ragged
@@ -1313,6 +1310,23 @@ class UnfusedOAITritonExperts(LoRAExpertsMixin, BaseOAITritonExperts):
quant_config.w1_precision,
gammas=gammas if apply_router_weight_on_input else None,
)
lora_context = self._lora_context
if lora_context is not None:
s_ids = e_ids = n_pad = t_map = None
s_ids, e_ids, n_pad, t_map = self.apply_w13_lora(
lora_context,
y=inter,
x=hidden_states,
topk_ids=global_topk_ids,
topk_weights=topk_weights,
expert_map=expert_map,
w1=w1,
w2=w2,
num_tokens=M,
top_k_num=topk,
)
act_out = torch.empty(
(routing_data.n_valid, act_out_dim),
dtype=hidden_states.dtype,
@@ -1330,6 +1344,32 @@ class UnfusedOAITritonExperts(LoRAExpertsMixin, BaseOAITritonExperts):
quant_config.w2_precision,
gammas=None if apply_router_weight_on_input else gammas,
)
if lora_context is not None:
# w2 LoRA works in (num_tokens, topk, K) token-topk order. Scatter
# the ragged rows there via the same expert-sort permutation
# (flat idx = token*topk + slot = argsort(flat_e)), apply, then
# gather the LoRA-updated rows back to ragged order for the combine.
flat_e = topk_ids.reshape(-1).to(torch.int64).clamp(min=0)
order = torch.argsort(flat_e, stable=True)
down_tt = down.new_zeros((M * topk, K))
down_tt[order] = down
self.apply_w2_lora(
lora_context,
y=down_tt.view(M, topk, K),
x=act_out,
topk_weights=topk_weights,
sorted_token_ids_lora=s_ids,
expert_ids_lora=e_ids,
num_tokens_post_padded_lora=n_pad,
token_lora_mapping=t_map,
num_tokens=M,
w1=w1,
w2=w2,
top_k_num=topk,
)
down = down_tt[order]
acc = torch.zeros((M, K), dtype=torch.float32, device=hidden_states.device)
acc.index_add_(0, gather_tok.to(torch.int64), down.to(torch.float32))
output.view(M, K).copy_(acc.to(output.dtype))
@@ -385,10 +385,11 @@ def rocm_aiter_fused_experts(
gate_mode = ""
if activation == MoEActivation.SITU:
# 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
gate_mode = (
GateMode.INTERLEAVE.value
if rocm_aiter_ops.is_fused_moe_situv2_gate_up_interleaved()
else GateMode.SEPARATED.value
)
elif quant_config.use_mxfp4_w4a16:
gate_mode = GateMode.INTERLEAVE.value
elif activation_interleave is not None:
@@ -337,6 +337,25 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular):
)
intermediate_cache3 = _resize_cache(workspace2, (num_tokens, top_k_num, K))
# Under EP, drop the top-k slots routed to remote experts at alignment
# time instead of launching `off_experts == -1` GEMM blocks that only
# write zeros; the pad-aware `moe_sum` below skips the same slots.
# Their rows in the workspace caches are then never written, so every
# consumer of those caches must be row-local: a dynamic per-tensor
# scale for the second GEMM's activation would take its amax over the
# untouched rows, and LoRA aligns the full `topk_ids` itself.
a2_scale_is_global = (
self.quant_dtype is not None
and a2_scale is None
and self.block_shape is None
and (not self.per_act_token_quant or self.quantization_emulation)
)
skip_invalid = (
expert_map is not None
and self._lora_context is None
and not a2_scale_is_global
)
# Include fused shared-expert rows while preserving EP remapping.
num_align_experts = w1.shape[0] if expert_map is None else global_num_experts
sorted_token_ids, expert_ids, num_tokens_post_padded = (
@@ -350,6 +369,7 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular):
use_int8_w8a16=self.quant_config.use_int8_w8a16,
use_int4_w4a16=self.quant_config.use_int4_w4a16,
block_shape=self.block_shape,
ignore_invalid_experts=skip_invalid,
)
)
@@ -585,10 +605,21 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular):
)
# separate function is required for MoE + LoRA
self.moe_sum(intermediate_cache3, output)
self.moe_sum(intermediate_cache3, output, topk_ids, expert_map)
def moe_sum(self, input: torch.Tensor, output: torch.Tensor) -> None:
ops.moe_sum(input, output)
def moe_sum(
self,
input: torch.Tensor,
output: torch.Tensor,
topk_ids: torch.Tensor | None = None,
expert_map: torch.Tensor | None = None,
) -> None:
if expert_map is not None:
# Skip the slots whose expert is not on this rank: the rows the
# alignment dropped, or the zeros the `-1` blocks wrote.
ops.moe_sum(input, output, topk_ids, expert_map)
else:
ops.moe_sum(input, output)
class TritonWNA16Experts(TritonExperts):
@@ -12,6 +12,10 @@ from vllm.model_executor.layers.fused_moe.config import (
FusedMoEQuantConfig,
RoutingMethodType,
)
from vllm.model_executor.layers.fused_moe.moe_output import (
UnfinalizedMoEOutput,
convert_flashinfer_moe_output,
)
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
@@ -273,7 +277,7 @@ class TrtLlmFp8ExpertsModular(TrtLlmFp8ExpertsBase, mk.FusedMoEExpertsModular):
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
):
) -> UnfinalizedMoEOutput | None:
import flashinfer
from flashinfer.fused_moe import Fp8QuantizationType, WeightLayout
@@ -297,7 +301,9 @@ class TrtLlmFp8ExpertsModular(TrtLlmFp8ExpertsBase, mk.FusedMoEExpertsModular):
weight_layout = WeightLayout.BlockMajorK
hidden_states_scale = prepare_deepseek_fp8_x_sf(hidden_states, a1q_scale)
flashinfer.fused_moe.trtllm_fp8_block_scale_routed_moe(
num_tokens = hidden_states.shape[0]
defer = self.moe_config.should_defer_moe_finalize(num_tokens)
flashinfer_output = flashinfer.fused_moe.trtllm_fp8_block_scale_routed_moe(
topk_ids=(topk_ids, topk_weights),
routing_bias=None,
hidden_states=hidden_states,
@@ -321,9 +327,20 @@ class TrtLlmFp8ExpertsModular(TrtLlmFp8ExpertsBase, mk.FusedMoEExpertsModular):
use_shuffled_weight=use_shuffled_weight,
weight_layout=weight_layout,
fp8_quantization_type=fp8_quant_type,
output=output,
do_finalize=not defer,
output=None if defer else output,
tune_max_num_tokens=fi_moe_largest_bucket(self.moe_config),
)
if not defer:
return None
routed_output = convert_flashinfer_moe_output(
flashinfer_output,
do_finalize=False,
num_tokens=num_tokens,
top_k=topk_ids.size(1),
)
assert isinstance(routed_output, UnfinalizedMoEOutput)
return routed_output
class TrtLlmFp8ExpertsMonolithic(TrtLlmFp8ExpertsBase, mk.FusedMoEExpertsMonolithic):
@@ -289,6 +289,18 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
Moved from trtllm_moe.py.
"""
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
**kwargs,
):
super().__init__(moe_config, quant_config, **kwargs)
# Each launch permutes into its own buffer, so a chunked call finalizes.
moe_config.limit_deferred_moe_finalize(
self._max_supported_tokens(self.topk, moe_config.num_experts)
)
@staticmethod
def _supports_parallel_config(
moe_parallel_config: FusedMoEParallelConfig,
@@ -343,7 +355,7 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
def _invoke_kernel(
self,
output: torch.Tensor,
output: torch.Tensor | None,
x_quant: torch.Tensor,
x_scale: torch.Tensor | None,
topk_ids: torch.Tensor,
@@ -355,10 +367,11 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
local_num_experts: int,
local_expert_offset: int,
topk: int,
) -> None:
) -> UnfinalizedMoEOutput | None:
"""Finalize into ``output``, or stop after GEMM2 when it is None."""
from flashinfer import trtllm_fp4_block_scale_routed_moe
trtllm_fp4_block_scale_routed_moe(
flashinfer_output = trtllm_fp4_block_scale_routed_moe(
topk_ids=(topk_ids, topk_weights),
routing_bias=None,
hidden_states=x_quant,
@@ -386,12 +399,22 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
# Modular kernel receives pre-routed tokens, so routing is already
# done. Use Renormalize as a safe default the TRTLLM kernel supports.
routing_method_type=RoutingMethodType.Renormalize,
do_finalize=True,
do_finalize=output is not None,
enable_pdl=True,
activation_type=self._flashinfer_activation_type(activation),
output=output,
tune_max_num_tokens=fi_moe_largest_bucket(self.moe_config),
)
if output is not None:
return None
routed_output = convert_flashinfer_moe_output(
flashinfer_output,
do_finalize=False,
num_tokens=x_quant.shape[0],
top_k=topk,
)
assert isinstance(routed_output, UnfinalizedMoEOutput)
return routed_output
def apply(
self,
@@ -410,7 +433,7 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
):
) -> UnfinalizedMoEOutput | None:
topk_ids = topk_ids.to(dtype=torch.int32)
topk = topk_ids.size(-1)
@@ -428,13 +451,17 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
assert self.w1_scale is not None
assert self.w2_scale is not None
# Chunk tokens so the batched-GEMM grid stays within CUDA limits.
# Chunk tokens so the batched-GEMM grid stays within CUDA limits. Each
# launch permutes into its own buffer, so only a run that fits in one
# launch can leave the top-k reduction to a deferring consumer.
M = x_quant.size(0)
chunk_size = self._max_supported_tokens(topk, global_num_experts)
defer = chunk_size >= M and self.moe_config.should_defer_moe_finalize(M)
unfinalized: UnfinalizedMoEOutput | None = None
for start in range(0, M, chunk_size):
end = min(start + chunk_size, M)
self._invoke_kernel(
output[start:end],
unfinalized = self._invoke_kernel(
None if defer else output[start:end],
x_quant[start:end],
None if x_scale is None else x_scale[start:end],
topk_ids[start:end],
@@ -448,4 +475,4 @@ class TrtLlmMxfp4ExpertsModular(TrtLlmMxfp4ExpertsBase, mk.FusedMoEExpertsModula
topk,
)
return output
return unfinalized
@@ -28,6 +28,7 @@ from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kNvfp4Dynamic,
kNvfp4DynamicToken,
kNvfp4Static,
)
from vllm.model_executor.utils import is_weights_pre_processed
@@ -124,6 +125,10 @@ class TrtLlmNvFp4ExpertsBase:
self.gemm1_beta = _per_expert(situ_linear_beta)
self.gemm1_clamp_limit = None
# Unfolded values: process_weights_after_loading reruns on weight reload.
self._gemm1_clamp_limit_unfolded = self.gemm1_clamp_limit
self._gemm1_beta_unfolded = self.gemm1_beta
logger.debug_once(
"activation=%s, gemm1_alpha=%s, gemm1_beta=%s, gemm1_clamp_limit=%s",
moe_config.activation,
@@ -163,15 +168,15 @@ class TrtLlmNvFp4ExpertsBase:
# Pre-fold the per-expert g1_alphas (= output1_scale_gate_scalar)
# division so the TRTLLM kernel receives the raw-GEMM-space clamp
# directly. g1_alphas is set once here in process_weights_after_loading
# (via the in-place mul above) and never changes again, so this is a
# static, per-expert constant. Register on the layer so EPLB
# rearranges it alongside the other expert tensors.
# directly. Fold from the unfolded value, since g1_alphas changes when
# weights are reloaded. Register on the layer so EPLB rearranges it
# alongside the other expert tensors.
# SITU alpha/beta act on the dequantized gate/up (tanh clamps), not the
# raw GEMM1 accumulator, so they are registered as-is without the
# g1_alphas fold used by the SwiGLU-OAI clamp/beta below.
if self.gemm1_clamp_limit is not None and not self.is_situ:
gemm1_clamp_limit = self.gemm1_clamp_limit / self.quant_config.g1_alphas
clamp_limit = self._gemm1_clamp_limit_unfolded
if clamp_limit is not None and not self.is_situ:
gemm1_clamp_limit = clamp_limit / self.quant_config.g1_alphas
layer.register_parameter(
"gemm1_clamp_limit",
torch.nn.Parameter(gemm1_clamp_limit, requires_grad=False),
@@ -182,12 +187,9 @@ class TrtLlmNvFp4ExpertsBase:
# clamp limit. alpha is applied to the dequantized gate, so it stays
# raw. Register both on the layer so EPLB rearranges them with the
# other per-expert tensors.
if self.gemm1_beta is not None:
gemm1_beta = (
self.gemm1_beta
if self.is_situ
else self.gemm1_beta / self.quant_config.g1_alphas
)
beta = self._gemm1_beta_unfolded
if beta is not None:
gemm1_beta = beta if self.is_situ else beta / self.quant_config.g1_alphas
layer.register_parameter(
"gemm1_beta",
torch.nn.Parameter(gemm1_beta, requires_grad=False),
@@ -222,10 +224,10 @@ class TrtLlmNvFp4ExpertsBase:
activation_key: QuantKey | None,
) -> bool:
"""Supports Nvfp4 quantization."""
SUPPORTED_W_A = [
(kNvfp4Static, kNvfp4Dynamic),
]
return (weight_key, activation_key) in SUPPORTED_W_A
return weight_key == kNvfp4Static and activation_key in (
kNvfp4Dynamic,
kNvfp4DynamicToken,
)
@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
@@ -300,6 +302,16 @@ class TrtLlmNvFp4ExpertsBase:
class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModular):
"""Modular version of the implementation (just the experts)."""
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
per_token_activation: bool = False,
):
super().__init__(moe_config, quant_config, per_token_activation)
# Each launch permutes into its own buffer, so a chunked call finalizes.
moe_config.limit_deferred_moe_finalize(self._get_chunk_size())
@staticmethod
def _supports_parallel_config(moe_parallel_config: FusedMoEParallelConfig) -> bool:
"""The modular implementation supports all parallel configs."""
@@ -316,22 +328,12 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
if self.per_token_activation:
# Deferred input quant leaves K unpacked here, breaking the
# workspace assumptions below. Per-token NVFP4 is only supported on
# the monolithic (non-EP) path for now.
raise NotImplementedError(
"NVFP4 per-token activation is only supported on the monolithic "
"(non-EP) FlashInfer TRTLLM MoE path."
)
# The workspaces for this implementation are managed by flashinfer.
workspace1 = (0,)
workspace2 = (0,)
# Hidden states are Nvfp4, packed into int8 dtype, so we
# need to multiply K by 2 to get the output shape right.
assert self.hidden_dim == K * 2
# Per-token inputs are unpacked; otherwise each byte holds two FP4 values.
assert self.hidden_dim == (K if self.expects_unquantized_inputs else K * 2)
output = (M, self.hidden_dim)
return (workspace1, workspace2, output)
@@ -341,7 +343,7 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
def _invoke_kernel(
self,
output: torch.Tensor,
output: torch.Tensor | None,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
@@ -349,8 +351,9 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
a1q_scale: torch.Tensor,
):
a1q_scale: torch.Tensor | None,
) -> UnfinalizedMoEOutput | None:
"""Finalize into ``output``, or stop after GEMM2 when it is None."""
import flashinfer
assert self.quant_config.w1_scale is not None
@@ -367,7 +370,7 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
output1_scale_gate_scalar = self.quant_config.g1_alphas
# Invoke kernel.
flashinfer.fused_moe.trtllm_fp4_block_scale_routed_moe(
flashinfer_output = flashinfer.fused_moe.trtllm_fp4_block_scale_routed_moe(
topk_ids=(topk_ids, topk_weights),
routing_bias=None,
hidden_states=hidden_states,
@@ -395,7 +398,7 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
local_num_experts=self.local_num_experts,
routed_scaling_factor=None,
routing_method_type=1, # not used
do_finalize=True,
do_finalize=output is not None,
activation_type=activation_to_flashinfer_int(activation),
per_token_scale=per_token_scale,
output=output,
@@ -403,6 +406,16 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
fi_moe_largest_bucket(self.moe_config), self._get_chunk_size()
),
)
if output is not None:
return None
routed_output = convert_flashinfer_moe_output(
flashinfer_output,
do_finalize=False,
num_tokens=hidden_states.shape[0],
top_k=self.topk,
)
assert isinstance(routed_output, UnfinalizedMoEOutput)
return routed_output
def apply(
self,
@@ -421,7 +434,7 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
):
) -> UnfinalizedMoEOutput | None:
assert self._supports_activation(activation)
# Per-token defers input quant to _invoke_kernel, so a1q_scale is None.
assert a1q_scale is not None or self.per_token_activation
@@ -433,8 +446,12 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
chunk_size = self._get_chunk_size()
if chunk_size >= M:
self._invoke_kernel(
output,
# Each launch permutes into its own buffer, so only a run that fits
# in one launch can leave the top-k reduction to a deferring
# consumer.
defer = self.moe_config.should_defer_moe_finalize(M)
return self._invoke_kernel(
None if defer else output,
hidden_states,
w1,
w2,
@@ -458,6 +475,7 @@ class TrtLlmNvFp4ExpertsModular(TrtLlmNvFp4ExpertsBase, mk.FusedMoEExpertsModula
global_num_experts,
None if a1q_scale is None else a1q_scale[start:end],
)
return None
class TrtLlmNvFp4ExpertsMonolithic(
@@ -7,11 +7,6 @@ import json
import os
import torch
from aiter.fused_moe import moe_sorting as aiter_moe_sorting
from aiter.ops.flydsl.kernels.moe_2stage_a16wmix import (
flydsl_a16w4_gemm1,
flydsl_a16w4_gemm2,
)
from vllm.logger import init_logger
from vllm.utils.platform_utils import get_device_name_as_file_name
@@ -81,6 +76,10 @@ def moe_sorting(
model_dim: int,
block_m: int,
):
# Imported lazily so aiter's import-time sort-backend env vars are read
# when this is called, not whenever this module happens to be imported.
from aiter.fused_moe import moe_sorting as aiter_moe_sorting
topk_ids_i32 = topk_ids.to(torch.int32)
topk_w_f32 = topk_weights.to(torch.float32)
sorted_ids, sorted_w, sorted_expert_ids, num_valid_ids, _moe_buf = (
@@ -185,6 +184,12 @@ def fused_flydsl_moe_impl(
tile_n2: int | None = None,
tile_k2: int | None = None,
) -> torch.Tensor:
# Imported lazily -- see the comment in moe_sorting() above.
from aiter.ops.flydsl.kernels.moe_2stage_a16wmix import (
flydsl_a16w4_gemm1,
flydsl_a16w4_gemm2,
)
device = hidden_states.device
tokens = hidden_states.shape[0]
model_dim = hidden_states.shape[1]
@@ -148,7 +148,7 @@ class FusedMoEMethodBase(QuantizeMethodBase):
topk_ids: torch.Tensor,
shared_experts: "SharedExperts | None",
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
"""Apply the MoE operation using modular kernels.
Args:
@@ -160,7 +160,7 @@ class FusedMoEMethodBase(QuantizeMethodBase):
shared_experts: The shared experts module, if any
Returns:
Output tensor from routed experts.
Finalized routed states or a deferred-finalize output.
"""
raise NotImplementedError
@@ -238,6 +238,15 @@ class FusedMoEPrepareAndFinalize(ABC):
"""
return False
def supports_deferred_moe_finalize(self) -> bool:
"""Whether ``finalize`` can be skipped for a deferring consumer.
An implementation opts in only if everything it does in ``finalize``
-- the top-k reduction, and any combine or reduce-scatter -- is work
the consumer takes over.
"""
return False
# TODO: pass FusedMoEParallelConfig in as ctor parameter?
class FusedMoEPrepareAndFinalizeModular(FusedMoEPrepareAndFinalize):
@@ -404,9 +413,6 @@ class FusedMoEPrepareAndFinalizeMonolithic(FusedMoEPrepareAndFinalize):
described above for the monolithic case.
"""
def supports_deferred_moe_finalize(self) -> bool:
return False
@abstractmethod
def prepare(
self,
@@ -895,10 +901,14 @@ class FusedMoEExpertsModular(FusedMoEExperts):
workspace2: torch.Tensor,
expert_tokens_meta: ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
) -> None:
) -> UnfinalizedMoEOutput | None:
"""This function computes the intermediate result of a Mixture of Experts
(MoE) layer using two sets of weights, w1 and w2.
Writes into `output` and returns None, unless the implementation stopped
after GEMM2 and left the top-k reduction to a fused consumer, in which
case `output` is untouched and the unfinalized result is returned.
Args:
output: (torch.Tensor): The unweighted, unreduced output tensor.
hidden_states: (torch.Tensor): The (quantized) input tensor to the MoE
@@ -1270,7 +1280,7 @@ class FusedMoEKernelModularImpl:
apply_router_weight_on_input: bool,
expert_tokens_meta: ExpertTokensMetadata | None,
output_alias: torch.Tensor | None = None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
_, M_full, N, K, top_k = self.fused_experts.moe_problem_size(
a1q, w1, w2, topk_ids
)
@@ -1318,7 +1328,7 @@ class FusedMoEKernelModularImpl:
elif use_output_alias:
fused_out = output_alias
self.fused_experts.apply(
unfinalized = self.fused_experts.apply(
output=fused_out,
hidden_states=a1q,
w1=w1,
@@ -1336,6 +1346,11 @@ class FusedMoEKernelModularImpl:
apply_router_weight_on_input=apply_router_weight_on_input,
)
# Experts that stopped after GEMM2 wrote nothing into `fused_out`; the
# top-k reduction they left open belongs to whoever takes this.
if isinstance(unfinalized, UnfinalizedMoEOutput):
return unfinalized
return fused_out
def _finalize(
@@ -1426,7 +1441,7 @@ class FusedMoEKernelModularImpl:
apply_router_weight_on_input: bool = False,
shared_experts: SharedExperts | None = None,
shared_experts_input: torch.Tensor | None = None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
"""This function computes a Mixture of Experts (MoE) layer using two sets
of weights, w1 and w2, and top-k gating mechanism.
@@ -1453,7 +1468,9 @@ class FusedMoEKernelModularImpl:
hidden_states before latent projection.
Returns:
torch.Tensor: The output tensor after applying the MoE layer.
torch.Tensor: The output tensor after applying the MoE layer, or
the unfinalized output when the experts left the top-k reduction to
a fused consumer.
"""
output = torch.empty_like(hidden_states)
@@ -1498,6 +1515,17 @@ class FusedMoEKernelModularImpl:
if lora_ctx is not None:
lora_ctx.original_hidden_states = None
if isinstance(fused_out, UnfinalizedMoEOutput):
# Nothing below can run on an unfinalized output: finalize is the
# local top-k reduction (and, for DP/EP, the combine) that the
# consumer takes over.
if not self.prepare_finalize.supports_deferred_moe_finalize():
raise RuntimeError(
f"{type(self.prepare_finalize).__name__} cannot pass through "
"a deferred MoE output."
)
return fused_out
return self._finalize(
output,
fused_out,
@@ -1653,10 +1681,7 @@ class FusedMoEKernel:
return self.prepare_finalize.output_is_reduced()
def supports_deferred_moe_finalize(self) -> bool:
return (
isinstance(self.prepare_finalize, FusedMoEPrepareAndFinalizeMonolithic)
and self.prepare_finalize.supports_deferred_moe_finalize()
)
return self.prepare_finalize.supports_deferred_moe_finalize()
def apply_monolithic(
self,
@@ -1703,7 +1728,7 @@ class FusedMoEKernel:
apply_router_weight_on_input: bool,
shared_experts: SharedExperts | None = None,
shared_experts_input: torch.Tensor | None = None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert isinstance(self.impl, FusedMoEKernelModularImpl)
return self.impl.apply(
hidden_states=hidden_states,
@@ -9,7 +9,7 @@ import torch
@dataclass
class UnfinalizedMoEOutput:
"""Unfinalized output of a monolithic MoE kernel.
"""Unfinalized output of a MoE kernel.
Kernels that can stop after GEMM2 (the TRTLLM-Gen ``do_finalize=False`` path)
hand back their permuted, unweighted output plus the routing weights and the
@@ -24,10 +24,11 @@ class UnfinalizedMoEOutput:
# [num_permuted_rows, hidden_dim] permuted, unweighted GEMM2 output.
gemm2_permuted: torch.Tensor
# [num_tokens, top_k] routing weights, in the activation dtype -- consumers
# index them as such, and a buffer typed wider than its contents reads as
# garbage. These already carry routed_scaling_factor for routing methods that
# fold it in.
# [num_tokens, top_k] routing weights, in the activation dtype when the
# kernel routed itself and in the router's dtype for modular experts --
# consumers index them as such, and a buffer typed wider than its contents
# reads as garbage. These already carry routed_scaling_factor for routing
# methods that fold it in.
expert_weights: torch.Tensor
# [num_tokens, top_k] int32 permute map; -1 = expert not local to this rank.
expanded_idx_to_permuted_idx: torch.Tensor
@@ -1596,8 +1596,7 @@ def convert_weight_to_mxfp4_moe_kernel_format(
fp4_dtype = torch.float4_e2m1fn_x2
e8m0_dtype = torch.float8_e8m0fnu
# SiTUv2 flydsl uses separated gate/up layout (a4w4).
guinterleave = False
guinterleave = rocm_aiter_ops.is_fused_moe_situv2_gate_up_interleaved()
w13 = rocm_aiter_ops.shuffle_weight_a16w4(
w13_weight.data.view(fp4_dtype), 16, guinterleave
)
@@ -605,6 +605,7 @@ def make_nvfp4_moe_kernel(
routing_tables=routing_tables,
allow_new_interface=True,
use_monolithic=issubclass(experts_cls, mk.FusedMoEExpertsMonolithic),
input_dtype=moe_config.in_dtype if per_token_activation else None,
)
assert prepare_finalize is not None
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Oracle for W4A8 (INT4, FP8) MoE
from enum import Enum
from typing import TYPE_CHECKING
@@ -22,26 +23,37 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
)
if TYPE_CHECKING:
from vllm.model_executor.layers.fused_moe.experts.cutlass_moe import (
CutlassExpertsW4A8Fp8,
)
from vllm.model_executor.layers.fused_moe import RoutedExperts
logger = init_logger(__name__)
class W4A8MoeBackend(Enum):
CUTLASS = "CUTLASS"
HUMMING = "HUMMING"
def backend_to_kernel_cls(
backend: W4A8MoeBackend,
) -> list[type["CutlassExpertsW4A8Fp8"]]:
) -> list[type[mk.FusedMoEExperts]]:
if backend == W4A8MoeBackend.CUTLASS:
from vllm.model_executor.layers.fused_moe.experts.cutlass_moe import (
CutlassExpertsW4A8Fp8,
)
return [CutlassExpertsW4A8Fp8]
elif backend == W4A8MoeBackend.HUMMING:
from vllm.model_executor.layers.fused_moe.experts.fused_humming_moe import (
BatchedHummingGroupedExperts,
HummingGroupedExperts,
HummingIndexedExperts,
)
return [
BatchedHummingGroupedExperts,
HummingGroupedExperts,
HummingIndexedExperts,
]
else:
raise ValueError(f"Unknown W4A8 MoE backend: {backend.value}")
@@ -50,8 +62,19 @@ def select_w4a8_moe_backend(
config: FusedMoEConfig,
weight_key: QuantKey | None = kInt4Static,
activation_key: QuantKey | None = kFp8DynamicTokenSym,
) -> tuple[W4A8MoeBackend, type["CutlassExpertsW4A8Fp8"]]:
backend = W4A8MoeBackend.CUTLASS
) -> tuple[W4A8MoeBackend, type[mk.FusedMoEExperts]]:
backends = [W4A8MoeBackend.CUTLASS, W4A8MoeBackend.HUMMING]
if config.moe_backend != "auto":
backend_map = {
"cutlass": W4A8MoeBackend.CUTLASS,
"humming": W4A8MoeBackend.HUMMING,
}
if config.moe_backend not in backend_map:
raise ValueError(
f"moe_backend='{config.moe_backend}' is not supported for W4A8 MoE. "
f"Expected one of {list(backend_map)}."
)
backends = [backend_map[config.moe_backend]]
activation_format = (
mk.FusedMoEActivationFormat.BatchedExperts
@@ -59,29 +82,33 @@ def select_w4a8_moe_backend(
else mk.FusedMoEActivationFormat.Standard
)
last_reason: str | None = None
for kernel_cls in backend_to_kernel_cls(backend):
supported, reason = kernel_cls.is_supported_config(
kernel_cls,
config,
weight_key,
activation_key,
activation_format,
)
if supported:
logger.info_once("Using %s W4A8 MoE backend.", backend.value)
return backend, kernel_cls
last_reason = reason
reasons = []
for backend in backends:
for kernel_cls in backend_to_kernel_cls(backend):
supported, reason = kernel_cls.is_supported_config(
kernel_cls,
config,
weight_key,
activation_key,
activation_format,
)
if supported:
logger.info_once("Using %s W4A8 MoE backend.", backend.value)
return backend, kernel_cls
reasons.append(f"{kernel_cls.__name__}: {reason}")
raise NotImplementedError(
f"W4A8 MoE backend {backend.value} does not support the "
f"deployment configuration: {last_reason}."
"No W4A8 MoE backend supports the deployment configuration: "
+ "; ".join(reasons)
)
def convert_to_w4a8_moe_kernel_format(
w13_weight_packed: torch.Tensor,
w2_weight_packed: torch.Tensor,
backend: W4A8MoeBackend,
layer: "RoutedExperts",
group_size: int,
w13_weight: torch.Tensor,
w2_weight: torch.Tensor,
w13_weight_scale: torch.Tensor,
w2_weight_scale: torch.Tensor,
) -> tuple[
@@ -89,11 +116,40 @@ def convert_to_w4a8_moe_kernel_format(
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor,
torch.Tensor | None,
torch.Tensor | None,
torch.Tensor | None,
torch.Tensor | None,
]:
if backend == W4A8MoeBackend.HUMMING:
from vllm.model_executor.layers.quantization.utils.humming import (
convert_to_humming_moe_kernel_format,
)
from vllm.utils.humming import (
HummingInputSchema,
HummingWeightSchema,
dtypes,
)
convert_to_humming_moe_kernel_format(
layer,
weight_schema=HummingWeightSchema(
b_dtype=dtypes.uint4, weight_scale_group_size=group_size
),
input_schema=HummingInputSchema(a_dtype=dtypes.float8e4m3),
allow_input_schema_fallback=False,
)
return (
layer.w13_weight,
layer.w2_weight,
layer.w13_weight_scale,
layer.w2_weight_scale,
None,
None,
None,
None,
)
from vllm import _custom_ops as ops
from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
from vllm.model_executor.layers.quantization.utils.quant_utils import (
@@ -104,18 +160,18 @@ def convert_to_w4a8_moe_kernel_format(
quant_fp8 = QuantFP8(static=False, group_shape=GroupShape.PER_TOKEN)
convert_packed_uint4b8_to_signed_int4_inplace(w13_weight_packed)
convert_packed_uint4b8_to_signed_int4_inplace(w13_weight)
# Mirror the sync in CutlassW4A8LinearKernel; required for TP>1 correctness.
torch.accelerator.synchronize()
w13_weight_shuffled, b_strides1 = ops.cutlass_encode_and_reorder_int4b_grouped(
w13_weight_packed
w13_weight
)
convert_packed_uint4b8_to_signed_int4_inplace(w2_weight_packed)
convert_packed_uint4b8_to_signed_int4_inplace(w2_weight)
# Mirror the sync in CutlassW4A8LinearKernel; required for TP>1 correctness.
torch.accelerator.synchronize()
w2_weight_shuffled, b_strides2 = ops.cutlass_encode_and_reorder_int4b_grouped(
w2_weight_packed
w2_weight
)
w13_weight_scale, w13_weight_chan_scale = convert_bf16_scales_to_fp8(
@@ -147,11 +203,23 @@ def convert_to_w4a8_moe_kernel_format(
def make_w4a8_moe_quant_config(
backend: W4A8MoeBackend,
w1_scale: torch.Tensor,
w2_scale: torch.Tensor,
g1_alphas: torch.Tensor,
g2_alphas: torch.Tensor,
g1_alphas: torch.Tensor | None,
g2_alphas: torch.Tensor | None,
layer: torch.nn.Module | None = None,
) -> FusedMoEQuantConfig:
if backend == W4A8MoeBackend.HUMMING:
from vllm.model_executor.layers.fused_moe import RoutedExperts
from vllm.model_executor.layers.quantization.utils.humming import (
get_humming_moe_quant_config,
)
assert isinstance(layer, RoutedExperts)
return get_humming_moe_quant_config(layer)
assert g1_alphas is not None and g2_alphas is not None
return int4_w4afp8_moe_quant_config(
w1_scale=w1_scale,
w2_scale=w2_scale,
@@ -163,14 +231,30 @@ def make_w4a8_moe_quant_config(
def make_w4a8_moe_kernel(
backend: W4A8MoeBackend,
moe_quant_config: FusedMoEQuantConfig,
moe_config: FusedMoEConfig,
experts_cls: type["CutlassExpertsW4A8Fp8"],
b_strides1: torch.Tensor,
b_strides2: torch.Tensor,
experts_cls: type[mk.FusedMoEExperts],
b_strides1: torch.Tensor | None,
b_strides2: torch.Tensor | None,
group_size: int,
routing_tables: tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None = None,
) -> mk.FusedMoEKernel:
if backend == W4A8MoeBackend.HUMMING:
from vllm.model_executor.layers.quantization.utils.humming import (
make_humming_moe_kernel,
)
return make_humming_moe_kernel(
moe_quant_config, moe_config, experts_cls, routing_tables=routing_tables
)
from vllm.model_executor.layers.fused_moe.experts.cutlass_moe import (
CutlassExpertsW4A8Fp8,
)
assert issubclass(experts_cls, CutlassExpertsW4A8Fp8)
assert b_strides1 is not None and b_strides2 is not None
prepare_finalize = maybe_make_prepare_finalize(
moe=moe_config,
quant_config=moe_quant_config,
@@ -38,6 +38,11 @@ def _quantize_input(
class MoEPrepareAndFinalizeNoDPEPModular(mk.FusedMoEPrepareAndFinalizeModular):
def supports_deferred_moe_finalize(self) -> bool:
# finalize() here is the top-k weight-and-reduce and nothing else,
# which is exactly the work a deferring consumer takes over.
return True
@property
def activation_format(self) -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
@@ -36,6 +36,28 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
def _index_expert_mapping(
mapping: list[tuple[str, str, int, str]],
) -> dict[str, list[tuple[str, str, int, str]]]:
"""Index by logical checkpoint ID, preserving entry order and EPLB replicas.
An empty index keeps the full scan for unsupported mapping names.
"""
mapping_by_expert: dict[str, list[tuple[str, str, int, str]]] = {}
for entry in mapping:
prefix, _, suffix = entry[1].partition(".")
expert_key, sep, _ = suffix.partition(".")
if (
prefix != "experts"
or not expert_key
or (expert_key.isdecimal() and not sep)
):
return {}
if expert_key.isdecimal():
mapping_by_expert.setdefault(expert_key, []).append(entry)
return mapping_by_expert
class FusedMoeWeightScaleSupported(Enum):
TENSOR = "tensor"
CHANNEL = "channel"
@@ -889,14 +911,22 @@ class RoutedExperts(PluggableLayer):
self, weights: Iterable[tuple[str, torch.Tensor]]
) -> Iterable[str]:
expert_mapping = self.get_expert_mapping(include_fused=True)
mapping_by_expert = _index_expert_mapping(expert_mapping)
for expert_name, loaded_weight in weights:
qual_name = f"{self.layer_name}.{expert_name}"
# Fused expert weights can be identified by their 3D tensors
is_fused = loaded_weight.dim() == 3
# Fused tensors and ambiguous names keep the full mapping.
candidates = expert_mapping
if not is_fused and qual_name.count("experts.") == 1:
expert_key = qual_name.partition("experts.")[2].partition(".")[0]
candidates = mapping_by_expert.get(expert_key, expert_mapping)
matched = False
for param_name, weight_name, expert_id, shard_id in expert_mapping:
for param_name, weight_name, expert_id, shard_id in candidates:
if weight_name not in qual_name:
if matched and is_fused:
# Fused tensors use the first contiguous run of matches.
break
continue
matched = True
@@ -1224,7 +1254,7 @@ class RoutedExperts(PluggableLayer):
topk_ids: torch.Tensor,
shared_experts: "SharedExperts | None" = None,
shared_experts_input: torch.Tensor | None = None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
"""Execute routed experts using the quantization method's apply function.
This is called by the runner after router selection (for modular kernels)
@@ -1239,7 +1269,7 @@ class RoutedExperts(PluggableLayer):
shared_experts_input: Input for shared experts (if any)
Returns:
Output tensor from routed experts.
Finalized routed states or a deferred-finalize output.
"""
assert not self.quant_method.is_monolithic
@@ -5,7 +5,11 @@ from torch.nn.parameter import Parameter
import vllm._custom_ops as ops
from vllm.model_executor.custom_op import PluggableLayer
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.linear import (
ReplicatedLinear,
UnquantizedLinearMethod,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.platforms import current_platform
from vllm.utils.torch_utils import direct_register_custom_op
@@ -25,12 +29,18 @@ class GateLinear(ReplicatedLinear):
The ``out_dtype`` attribute is mutable and can be set after init
(e.g. when the required dtype depends on the expert quantization
method which is only known later).
A ``quant_config`` that actually quantizes the gate disables every
specialized tier, leaving plain ``ReplicatedLinear`` behavior.
"""
# (hidden_size, num_experts) pairs with an instantiated fp32 kernel:
# (3072, 256) -> MiniMax-M2/M2.5, (6144, 128) -> MiniMax-M3
FP32_SUPPORTED_SHAPES = {(3072, 256), (6144, 128)}
FP32_MAX_TOKENS = 32
# Largest batch for which tier 1 beats the cuBLAS epilogue. Subclasses
# whose router shape stays ahead further up the range may raise it.
LL_BF16_MAX_TOKENS = 16
def __init__(
self,
@@ -40,7 +50,10 @@ class GateLinear(ReplicatedLinear):
out_dtype: torch.dtype | None = None,
params_dtype: torch.dtype | None = None,
force_fp32_compute: bool = False,
skip_bias_add: bool = False,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
return_bias: bool = True,
):
is_hopper = current_platform.is_device_capability((9, 0))
is_blackwell = current_platform.is_device_capability_family(100)
@@ -72,17 +85,25 @@ class GateLinear(ReplicatedLinear):
input_size,
output_size,
bias=bias,
skip_bias_add=skip_bias_add,
params_dtype=params_dtype,
quant_config=None,
quant_config=quant_config,
prefix=prefix,
return_bias=return_bias,
)
self.out_dtype = out_dtype
# A quantized gate exposes no plain ``weight``, so every specialized
# tier below is disabled and forward falls back to ReplicatedLinear.
self.is_unquantized = isinstance(self.quant_method, UnquantizedLinearMethod)
can_use_specialized_kernels &= self.is_unquantized
self.allow_specialized_router_gemm = can_use_specialized_kernels
# fp32 specialized kernel eligibility (exact dims, fp32 weight)
self.allow_fp32_router_gemm = (
not bias
self.is_unquantized
and not bias
and self.weight.dtype == torch.float32
and (
(
@@ -94,7 +115,8 @@ class GateLinear(ReplicatedLinear):
)
)
self.allow_bf16x3_router_gemm = (
not bias
self.is_unquantized
and not bias
and self.weight.dtype == torch.float32
and current_platform.is_cuda()
and is_blackwell
@@ -108,7 +130,7 @@ class GateLinear(ReplicatedLinear):
# applies on any CUDA-alike device (no bias, since torch.mm has no bias
# term). The specialized-kernel gate above excludes family-120 Blackwell
# (GB10 / DGX Spark), which this tier still covers. See #49921.
self._router_gemm_no_bias = not bias
self._router_gemm_no_bias = self.is_unquantized and not bias
self._router_gemm_cublas_capable = (
current_platform.is_cuda() or current_platform.is_rocm()
) and self._router_gemm_no_bias
@@ -162,17 +184,26 @@ class GateLinear(ReplicatedLinear):
and is_available()
)
def _return(
self, output: torch.Tensor
) -> torch.Tensor | tuple[torch.Tensor, Parameter | None]:
return output if not self.return_bias else (output, None)
def forward(
self, x: torch.Tensor
) -> torch.Tensor | tuple[torch.Tensor, Parameter | None]:
# Tier 1: cuteDSL ll_bf16_gemm (SM90+, any dims)
if self.allow_ll_bf16_gemm and x.shape[0] <= 16 and x.dtype == torch.bfloat16:
if (
self.allow_ll_bf16_gemm
and x.shape[0] <= self.LL_BF16_MAX_TOKENS
and x.dtype == torch.bfloat16
):
from vllm.model_executor.kernels.linear.cute_dsl.ll_bf16 import (
ll_bf16_gemm,
)
output = ll_bf16_gemm(x, self.weight)
return output, None
return self._return(output)
# Tier 2: fp32 specialized kernel (model-specific shapes, M<=32)
# Dispatch is wrapped in a custom op so that torch.compile/CUDA-graph
@@ -184,7 +215,7 @@ class GateLinear(ReplicatedLinear):
output = torch.ops.vllm.fp32_router_gemm_dispatch(
x, self.weight, self.allow_bf16x3_router_gemm
)
return output, None
return self._return(output)
# Tier 3: bf16x3 CuteDSL kernel for fp32 router weights
if self.allow_bf16x3_router_gemm and x.dtype == torch.bfloat16:
@@ -193,20 +224,29 @@ class GateLinear(ReplicatedLinear):
)
output = bf16x3_router_gemm(x, self.weight)
return output, None
return self._return(output)
# Tier 4: cuBLAS bf16→fp32
if self.allow_cublas_router_gemm and x.dtype == torch.bfloat16:
output = torch.mm(x, self.weight.T, out_dtype=torch.float32)
return output, None
return self._return(output)
# Tier 5: F.linear (ReplicatedLinear)
if self.out_dtype is not None and x.dtype != self.weight.dtype:
if (
self.out_dtype is not None
and self.is_unquantized
and x.dtype != self.weight.dtype
):
x = x.to(self.weight.dtype)
output, output_bias = super().forward(x)
base_output = super().forward(x)
output_bias: Parameter | None = None
if isinstance(base_output, tuple):
output, output_bias = base_output
else:
output = base_output
if self.out_dtype is not None and output.dtype != self.out_dtype:
output = output.to(self.out_dtype)
return output, output_bias
return output if not self.return_bias else (output, output_bias)
_FP32_ROUTER_GEMM_MAX_TOKENS = GateLinear.FP32_MAX_TOKENS
@@ -657,7 +657,11 @@ class MoERunner(MoERunnerInterface):
"""
ctx = get_forward_context()
return (
ctx.dp_metadata.sp_local_sizes(self.moe_config.sp_size)
ctx.dp_metadata.sp_local_sizes(
self.moe_config.sp_size,
pcp_size=self.moe_config.pcp_size,
use_ep=self.moe_config.use_ep,
)
if ctx.dp_metadata
else nullcontext()
)
@@ -453,35 +453,6 @@ def normalize_batched_scales_shape(
return scales
@triton.jit
def _pack_topk_ids_weights_kernel(
topk_ids_ptr,
topk_weights_ptr,
output_ptr,
n_elements,
BLOCK_SIZE: tl.constexpr,
USE_GDC: tl.constexpr,
launch_pdl: tl.constexpr, # triton metadata
):
pid = tl.program_id(axis=0)
offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
if USE_GDC:
tl.extra.cuda.gdc_launch_dependents()
tl.extra.cuda.gdc_wait()
expert_id = tl.load(topk_ids_ptr + offsets, mask=mask, other=0).to(tl.int32)
expert_id_shifted = expert_id << 16
weight = tl.load(topk_weights_ptr + offsets, mask=mask, other=0.0)
weight_bf16 = weight.to(tl.bfloat16)
weight_int16 = weight_bf16.to(tl.int16, bitcast=True)
weight_int32 = weight_int16.to(tl.int32) & 0xFFFF
packed = expert_id_shifted | weight_int32
tl.store(output_ptr + offsets, packed, mask=mask)
def fi_moe_largest_bucket(moe_config: "FusedMoEConfig") -> int:
"""Estimate FlashInfer's MoE autotuning maximum token count.
@@ -0,0 +1,361 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused Normalisation on the Device.
Equivalent to::
output = (input * rescale_factor - image_mean) / image_std
This is implemented as a single per-channel affine transform::
output = input * weight[c] + bias[c]
where::
weight = rescale_factor / image_std
bias = -image_mean / image_std
"""
import math
from typing import Any, NamedTuple
import torch
from torch import nn
from vllm.config import ModelConfig
from vllm.model_executor.custom_op import CustomOp
from vllm.transformers_utils.processor import cached_get_processor, get_processor_config
from vllm.triton_utils import tl, triton
@triton.jit
def _fused_mm_input_norm_kernel(
x_ptr,
y_ptr,
w_ptr,
b_ptr,
numel,
L,
C: tl.constexpr,
BLOCK: tl.constexpr,
):
# 1D grid over the flattened (N, C, L) tensor. Each program processes
# BLOCK contiguous elements; the channel index is recovered from the
# flat offset via `(offs // L) % C`. int32 offsets: int64 division is
# ~2x slower here (measured on GB200); the wrapper asserts
# numel < 2**31 so the flat index never overflows.
pid = tl.program_id(0)
offs = pid * BLOCK + tl.arange(0, BLOCK)
mask = offs < numel
c = (offs // L) % C
x = tl.load(
x_ptr + offs,
mask=mask,
other=0,
eviction_policy="evict_first",
).to(tl.float32)
w = tl.load(w_ptr + c, mask=mask, other=0).to(tl.float32)
b = tl.load(b_ptr + c, mask=mask, other=0).to(tl.float32)
tl.store(
y_ptr + offs,
x * w + b,
mask=mask,
eviction_policy="evict_first",
)
def fused_mm_input_norm_triton(
inputs: torch.Tensor,
outputs: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor,
) -> torch.Tensor:
"""Fused per-channel affine transform for normalisation.
Args:
inputs: Input tensor, shape ``(N, C, L)``. A contiguous copy is
materialized internally if needed.
outputs: Output tensor, contiguous and shaped exactly ``(N, C, L)``.
weight: Per-channel scale, shape ``(C,)``.
bias: Per-channel shift, shape ``(C,)``.
Returns:
``outputs``, for chaining.
"""
N, C, L = inputs.shape
assert outputs.shape == (N, C, L), (
f"outputs shape {tuple(outputs.shape)} != inputs shape {(N, C, L)}"
)
assert weight.numel() == C and bias.numel() == C, (
f"weight/bias must have {C} elements, got {weight.numel()} / {bias.numel()}"
)
# The flat 1D kernel writes outputs by raw offset; a non-contiguous
# buffer would be written at the wrong locations and cannot be
# auto-materialized without breaking the caller's aliasing.
assert outputs.is_contiguous(), "outputs must be contiguous"
# Tile size along the flattened element axis. 1024 with 4 warps gives
# 8 elements per lane and benchmarks fastest across realistic image
# sizes; larger tiles starve the SMs on small inputs.
BLOCK_SIZE = 1024
numel = N * C * L
# The kernel indexes with int32 offsets (int64 division costs ~2x
# throughput); guard the flat index range here.
assert numel < 2**31, f"numel={numel} exceeds the int32 index range"
grid = (triton.cdiv(numel, BLOCK_SIZE),)
_fused_mm_input_norm_kernel[grid](
inputs.contiguous(),
outputs,
weight.contiguous(),
bias.contiguous(),
numel,
L,
C=C,
BLOCK=BLOCK_SIZE,
num_warps=4, # 8 elements per lane at BLOCK_SIZE=1024
)
return outputs
class NormParams(NamedTuple):
"""Resolved per-channel affine parameters (flags already folded in)."""
image_mean: list[float]
image_std: list[float]
rescale_factor: float
@property
def is_identity(self) -> bool:
"""Whether ``weight = rescale/std`` and ``bias = -mean/std`` are
numerically the identity transform (mirrors ``torch.allclose``'s
default fp32 tolerances)."""
return all(
math.isclose(self.rescale_factor / s, 1.0, rel_tol=1e-5, abs_tol=1e-8)
and math.isclose(m / s, 0.0, abs_tol=1e-8)
for m, s in zip(self.image_mean, self.image_std)
)
def _load_norm_params(model_config: ModelConfig) -> NormParams:
"""Resolve the per-channel affine parameters ``(image_mean, image_std,
rescale_factor)`` from the processor config, falling back to the image
processor object."""
model = model_config.model
revision = model_config.revision
config = get_processor_config(model, revision=revision)
# NOTE: do not use cached_image_processor_from_config here — it merges
# mm_processor_kwargs, which mm_device_do_normalize poisons with
# do_normalize=False.
image_processor = cached_get_processor(
model, revision=revision, trust_remote_code=model_config.trust_remote_code
).image_processor
def resolve(key: str) -> Any:
"""Processor config value, falling back to the image_processor."""
if (value := config.get(key)) is not None:
return value
return getattr(image_processor, key, None)
do_rescale = bool(resolve("do_rescale"))
do_normalize = bool(resolve("do_normalize"))
# Parameters whose flag is off are unused; default them to no-ops
# without resolving them.
rescale_factor = resolve("rescale_factor") if do_rescale else 1.0
image_mean = resolve("image_mean") if do_normalize else [0.0] * 3
image_std = resolve("image_std") if do_normalize else [1.0] * 3
assert rescale_factor is not None, "rescale_factor is still None after resolution."
assert image_mean is not None, "image_mean is still None after resolution."
assert image_std is not None, "image_std is still None after resolution."
assert len(image_mean) == len(image_std), (
f"image_mean and image_std have different lengths: "
f"{len(image_mean)} vs {len(image_std)}"
)
return NormParams(
image_mean=[float(v) for v in image_mean],
image_std=[float(v) for v in image_std],
rescale_factor=float(rescale_factor),
)
class IdentityInputNorm(nn.Module):
"""Stand-in used when the processor requires no rescale/normalise.
Not a no-op: with ``mm_device_do_normalize`` enabled, raw ``uint8``
pixels travel to the device unprocessed and must be cast to
``visual_dtype`` here.
"""
def forward(
self, pixel_values: torch.Tensor, visual_dtype: torch.dtype
) -> torch.Tensor:
return pixel_values.to(visual_dtype, copy=False)
@CustomOp.register("fused_mm_input_norm")
class FusedMMInputNorm(CustomOp):
"""Module that applies rescaling and normalisation to input images.
Equivalent to: output = (input * rescale_factor - mean) / std
Dtype semantics:
* Input dtype — the dtype of the ``pixel_values`` argument to ``forward_*``.
It is ``uint8`` when ``mm_device_do_normalize`` is enabled (raw bytes
travel to the device unprocessed) and equals ``visual_dtype``
otherwise.
* Output dtype — the ``visual_dtype`` argument of ``forward_*``. The
computation itself is always fp32, independent of the output dtype
(e.g. compute fp32, emit bf16).
Platform dispatch:
* ``forward_native`` — pure PyTorch eager path, used as the semantic
reference and default fallback on all platforms.
* ``forward_cuda`` — Triton kernel path for CUDA devices.
* ``forward_xpu`` — custom XPU kernel path.
* ``forward_oot`` — out-of-tree platform override entry point; falls back
to ``forward_native`` unless a plugin overrides it.
"""
def __init__(
self,
image_mean: list[float],
image_std: list[float],
rescale_factor: float,
channel: int = 3,
):
super().__init__()
assert len(image_mean) == len(image_std) == channel, (
f"image_mean/image_std must have {channel} entries, "
f"got {len(image_mean)} / {len(image_std)}"
)
assert rescale_factor != 0.0, "rescale_factor must be non-zero"
self.channel = channel
# Model construction can set the accelerator as PyTorch's default
# device; build the buffers on CPU first, then move them over.
mean = torch.tensor(image_mean, dtype=torch.float32, device="cpu")
std = torch.tensor(image_std, dtype=torch.float32, device="cpu")
device = torch.get_default_device()
self.register_buffer("weight", (rescale_factor / std).to(device))
self.register_buffer("bias", (-mean / std).to(device))
# ------------------------------------------------------------------
# Internal helpers shared by the platform-specific forward_* methods
# ------------------------------------------------------------------
@staticmethod
def _unpack_2d(pixel_values: torch.Tensor) -> tuple[int, int]:
assert pixel_values.ndim == 2, (
f"pixel_values must be 2D (patches, size), got {pixel_values.dim()}D "
f"with shape {tuple(pixel_values.shape)}"
)
patches, size = pixel_values.shape
return patches, size
def _patch_size(self, size: int) -> int:
assert size % self.channel == 0, (
f"size={size} is not divisible by channel={self.channel}"
)
return size // self.channel
# ------------------------------------------------------------------
# Platform-specific implementations
# ------------------------------------------------------------------
def forward_native(
self, pixel_values: torch.Tensor, visual_dtype: torch.dtype
) -> torch.Tensor:
"""Pure PyTorch eager implementation.
This is the semantic reference implementation and the fallback used
on any platform without a specialised kernel.
"""
patches, size = self._unpack_2d(pixel_values)
patch_size = self._patch_size(size)
# weight/bias are fp32, so type promotion makes the arithmetic fp32
x = pixel_values.reshape(patches, self.channel, patch_size)
x = x * self.weight.view(1, self.channel, 1) + self.bias.view(
1, self.channel, 1
)
return x.view(patches, size).to(visual_dtype)
def forward_cuda(
self, pixel_values: torch.Tensor, visual_dtype: torch.dtype
) -> torch.Tensor:
"""Triton kernel path for CUDA devices."""
patches, size = self._unpack_2d(pixel_values)
patch_size = self._patch_size(size)
x3 = pixel_values.reshape(patches, self.channel, patch_size)
y = torch.empty((patches, size), dtype=visual_dtype, device=pixel_values.device)
y3 = y.view(patches, self.channel, patch_size)
fused_mm_input_norm_triton(x3, y3, self.weight, self.bias)
return y
def forward_xpu(
self, pixel_values: torch.Tensor, visual_dtype: torch.dtype
) -> torch.Tensor:
"""XPU fused custom kernel path.
On XPU, fuse the whole rescale + normalise into a single custom
kernel. The eager path materializes an fp32 intermediate and then
casts back, which adds device-side compute that cancels the
bandwidth saving of transferring uint8 pixel_values. The fused
kernel reads uint8 directly and writes ``visual_dtype`` in one pass.
"""
# The out-of-tree XPU kernel only supports the uint8 input that
# device-side normalisation guarantees; fail loudly otherwise.
assert pixel_values.dtype == torch.uint8, (
f"xpu_fused_input_norm requires uint8 input, got {pixel_values.dtype}"
)
return torch.ops.vllm.xpu_fused_input_norm(
pixel_values, self.weight, self.bias, visual_dtype
)
def forward_oot(
self, pixel_values: torch.Tensor, visual_dtype: torch.dtype
) -> torch.Tensor:
"""Out-of-tree platform override entrypoint."""
return self.forward_native(pixel_values, visual_dtype)
def build_mm_input_norm(model_config: ModelConfig) -> nn.Module:
"""Build the input normalisation module for a model.
Returns an ``IdentityInputNorm`` when device-side normalisation is
disabled or the processor's rescale/normalise is numerically the identity
transform; otherwise a ``FusedMMInputNorm`` built from the processor's
parameters.
"""
mm_config = getattr(model_config, "multimodal_config", None)
if not getattr(mm_config, "mm_device_do_normalize", False):
return IdentityInputNorm()
params = _load_norm_params(model_config)
# Flags off are already defaulted to identity values by
# ``_load_norm_params``; this also catches configs that request
# rescale/normalise but are numerically the identity transform.
if params.is_identity:
return IdentityInputNorm()
return FusedMMInputNorm(
image_mean=params.image_mean,
image_std=params.image_std,
rescale_factor=params.rescale_factor,
channel=len(params.image_mean),
)
+21 -1
View File
@@ -256,6 +256,8 @@ class LogitsProcessor(PluggableLayer):
hidden_states: torch.Tensor,
k: int,
embedding_bias: torch.Tensor | None = None,
*,
return_log_probs: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Vocab-parallel top-k without all-gathering full logits.
@@ -263,7 +265,9 @@ class LogitsProcessor(PluggableLayer):
the values as well as the global ids. Communication is
O(batch * 2k * tp_size) rather than O(batch * vocab_size).
Scale and soft cap are applied to the k selected values rather than
With return_log_probs, values use the full-vocabulary log-partition.
Otherwise scale and soft cap are applied to the k selected values rather than
the whole vocabulary; both are monotonic, so the selection is the same
and only k entries are touched.
"""
@@ -274,12 +278,26 @@ class LogitsProcessor(PluggableLayer):
)
logits = self._apply_head(lm_head, hidden_states, embedding_bias)
if return_log_probs:
if self.soft_cap is not None:
logits = torch.tanh(logits / self.soft_cap) * self.soft_cap
if self.scale != 1.0:
logits = logits * self.scale
# Mask out padding entries beyond org_vocab_size on this shard.
num_pad = lm_head.shard_indices.num_org_vocab_padding
if num_pad > 0:
logits[..., -num_pad:] = -float("inf")
if return_log_probs:
log_partition = torch.logsumexp(logits.float(), dim=-1, keepdim=True)
if lm_head.tp_size > 1:
log_partition = torch.logsumexp(
tensor_model_parallel_all_gather(log_partition, dim=-1),
dim=-1,
keepdim=True,
)
values, ids = _topk(logits, k)
# Convert shard-local indices to global vocab indices.
ids = ids.to(torch.int64) + lm_head.shard_indices.org_vocab_start_index
@@ -291,6 +309,8 @@ class LogitsProcessor(PluggableLayer):
ids = ids.gather(-1, selected)
values = values.float()
if return_log_probs:
return ids, values - log_partition
if self.scale != 1.0:
values = values * self.scale
if self.soft_cap is not None:
+2 -2
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import (
VllmConfig,
@@ -24,7 +24,7 @@ class GatedDeltaNetAttention(PluggableLayer, MambaBase):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
vllm_config: VllmConfig,
prefix: str = "",
) -> None:
@@ -59,7 +59,6 @@ from vllm.third_party.flash_linear_attention.ops import (
from vllm.third_party.flash_linear_attention.ops.chunk import l2norm_fwd
from vllm.third_party.flash_linear_attention.ops.utils import FLA_CHUNK_SIZE
from vllm.transformers_utils.configs.qwen3_next import Qwen3NextConfig
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import (
LayerNameType,
_encode_layer_name,
@@ -228,6 +227,7 @@ def fi_chunk_gated_delta_rule(
initial_state=fi_state,
output_final_state=output_final_state,
cu_seqlens=cu_seqlens,
backend="flashinfer",
)
# FlashInfer returns (output, state) when output_final_state=True,
# or just output when output_final_state=False.
@@ -1961,74 +1961,3 @@ direct_register_custom_op(
op_func=qwen_gdn_attention_core_fused_norm_packed,
mutates_args=["core_attn_out"],
)
@triton.jit
def fused_gdn_gating_kernel(
g,
beta_output,
A_log,
a,
b,
dt_bias,
seq_len,
NUM_HEADS: tl.constexpr,
beta: tl.constexpr,
threshold: tl.constexpr,
BLK_HEADS: tl.constexpr,
):
i_b, i_s, i_d = tl.program_id(0), tl.program_id(1), tl.program_id(2)
head_off = i_d * BLK_HEADS + tl.arange(0, BLK_HEADS)
off = i_b * seq_len * NUM_HEADS + i_s * NUM_HEADS + head_off
mask = head_off < NUM_HEADS
blk_A_log = tl.load(A_log + head_off, mask=mask)
blk_a = tl.load(a + off, mask=mask)
blk_b = tl.load(b + off, mask=mask)
blk_bias = tl.load(dt_bias + head_off, mask=mask)
# If the model is loaded in fp16, without the .float() here, A might be -inf
x = blk_a.to(tl.float32) + blk_bias.to(tl.float32)
softplus_x = tl.where(
beta * x <= threshold, (1 / beta) * tl.log(1 + tl.exp(beta * x)), x
)
blk_g = -tl.exp(blk_A_log.to(tl.float32)) * softplus_x
tl.store(g + off, blk_g.to(g.dtype.element_ty), mask=mask)
# compute beta_output = sigmoid(b)
blk_beta_output = tl.sigmoid(blk_b.to(tl.float32))
tl.store(
beta_output + off, blk_beta_output.to(beta_output.dtype.element_ty), mask=mask
)
def fused_gdn_gating(
A_log: torch.Tensor,
a: torch.Tensor,
b: torch.Tensor,
dt_bias: torch.Tensor,
beta: float = 1.0,
threshold: float = 20.0,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Fused computation of g and beta for Gated Delta Net.
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
beta_output = b.sigmoid()
TODO maybe use torch.compile to replace this triton kernel
"""
batch, num_heads = a.shape
seq_len = 1
grid = (batch, seq_len, triton.cdiv(num_heads, 8))
g = torch.empty(1, batch, num_heads, dtype=torch.float32, device=a.device)
beta_output = torch.empty(1, batch, num_heads, dtype=b.dtype, device=b.device)
fused_gdn_gating_kernel[grid](
g,
beta_output,
A_log,
a,
b,
dt_bias,
seq_len,
num_heads,
beta,
threshold,
8,
num_warps=1,
)
return g, beta_output
@@ -4,7 +4,7 @@ import copy
import torch
import torch.nn.functional as F
from transformers.configuration_utils import PretrainedConfig
from transformers.configuration_utils import PreTrainedConfig
from vllm.config import (
VllmConfig,
@@ -37,7 +37,7 @@ from vllm.triton_utils import tl, triton
from vllm.v1.attention.backends.linear_attn import LinearAttentionMetadata
def _build_rope_parameters(config: PretrainedConfig) -> dict | None:
def _build_rope_parameters(config: PreTrainedConfig) -> dict | None:
rope_parameters = copy.deepcopy(getattr(config, "rope_parameters", None)) or {}
if "rope_theta" not in rope_parameters and hasattr(config, "rope_theta"):
rope_parameters["rope_theta"] = config.rope_theta
@@ -385,7 +385,7 @@ class BailingMoELinearAttention(LinearAttention):
# --8<-- [end:bailing_moe_linear_attention]
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
vllm_config: VllmConfig,
prefix: str = "linear_attn",
):
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import (
VllmConfig,
@@ -24,7 +24,7 @@ class LinearAttention(PluggableLayer, MambaBase):
"""Base class for Linear attention layer."""
def __init__(
self, config: PretrainedConfig, vllm_config: VllmConfig, prefix: str = ""
self, config: PreTrainedConfig, vllm_config: VllmConfig, prefix: str = ""
):
super().__init__()
self.layer_idx = extract_layer_index(prefix)
@@ -56,7 +56,6 @@ from vllm.model_executor.model_loader.weight_utils import (
from vllm.model_executor.parameter import BasevLLMParameter
from vllm.model_executor.utils import set_weight_attrs
from vllm.platforms import current_platform
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.torch_utils import (
LayerNameType,
_encode_layer_name,
@@ -927,67 +926,54 @@ class MambaMixer2(MambaBase, PluggableLayer):
# then chunk_stride = 2
chunk_stride = mamba_block_size // chunk_size
# The per-sequence loop below uses these as Python scalars.
# TODO avoid sync here?
with gpu_sync_allowed():
block_idx_first_cpu = block_idx_first_scheduled_token_p.tolist()
block_idx_last_cpu = block_idx_last_scheduled_token_p.tolist()
num_computed_tokens_p_cpu = num_computed_tokens_p.tolist()
last_chunk_indices_p_cpu = last_chunk_indices_p.tolist()
# Save state for sequences with more than just final state,
# batched over sequences so that the number of kernel launches
# does not scale with the number of prefills.
n_blocks_to_fill = (
block_idx_last_scheduled_token_p - block_idx_first_scheduled_token_p
).clamp(min=0)
total_fill = attn_metadata.num_state_writes_p
if total_fill > 0:
first_chunk = torch.zeros_like(last_chunk_indices_p)
first_chunk[1:] = last_chunk_indices_p[:-1] + 1
# Save state for sequences with more than just final state
for seq_idx in range(num_prefills):
# Block index for the first scheduled token
block_idx_first_scheduled_token = block_idx_first_cpu[seq_idx]
# Block index for the last scheduled token
block_idx_last_scheduled_token = block_idx_last_cpu[seq_idx]
# Number of blocks that need to be written
n_blocks_to_fill = (
block_idx_last_scheduled_token - block_idx_first_scheduled_token
)
# Skip sequences that don't have any blocks to fill
if n_blocks_to_fill == 0:
continue
# Look up the state indices
cache_blocks_to_fill = state_indices_tensor_p[
seq_idx,
block_idx_first_scheduled_token:block_idx_last_scheduled_token,
]
# First chunk index for this sequence
if seq_idx == 0:
first_chunk = 0
else:
first_chunk = 1 + last_chunk_indices_p_cpu[seq_idx - 1]
# First chunk that is aligned on the mamba block boundary
first_aligned_chunk = first_chunk + chunk_stride - 1
# Calculate the number of computed tokens that were not
# already cached
# The chunk that completes this sequence's first mamba block.
# A block spans chunk_stride chunks. When the sequence resumed
# mid-block, the chunks before this step are not in varlen_states,
# so subtract them: the boundary sits earlier by their count.
num_unaligned_computed_tokens = (
num_computed_tokens_p_cpu[seq_idx] % mamba_block_size
num_computed_tokens_p % mamba_block_size
)
unaligned_chunk_shift = num_unaligned_computed_tokens // chunk_size
first_aligned_chunk = (
first_chunk + (chunk_stride - 1) - unaligned_chunk_shift
)
if num_unaligned_computed_tokens > 0:
# If the number of computed tokens is not block aligned,
# then we need to shift the index accordingly
first_aligned_chunk -= (
num_unaligned_computed_tokens // chunk_size
)
# Flatten all writes into one list: fill_counts=[2,1,2]
# -> seq_ids=[0,0,1,2,2], write_offsets=[0,1,0,0,1]
fill_counts = n_blocks_to_fill.long()
# output_size, or repeat_interleave reads the size off the device
seq_ids = torch.repeat_interleave(
torch.arange(num_prefills, device=ssm_state.device),
fill_counts,
output_size=total_fill,
)
write_starts = torch.cumsum(fill_counts, dim=0) - fill_counts
write_offsets = torch.arange(
total_fill, device=ssm_state.device
) - torch.repeat_interleave(
write_starts, fill_counts, output_size=total_fill
)
# Get states to write
from_where = varlen_states[
first_aligned_chunk : first_aligned_chunk
+ n_blocks_to_fill * chunk_stride : chunk_stride
cache_blocks_to_fill = state_indices_tensor_p[
seq_ids,
block_idx_first_scheduled_token_p[seq_ids] + write_offsets,
]
# Write the states. Each row goes to its own cache block,
# so the indexed copy has no duplicate destinations.
ssm_state[cache_blocks_to_fill] = varlen_states[
first_aligned_chunk[seq_ids] + write_offsets * chunk_stride
]
# Write the states
ssm_state[cache_blocks_to_fill] = from_where
# For all seqs, store the last state (note: might be partial):
assert state_indices_tensor_p is not None
@@ -27,6 +27,104 @@ from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata
_CPU_GDN_ATTENTION_OPS_REGISTERED = False
def _stage_ds_conv_states(
conv_states: torch.Tensor, state_indices: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
storage = conv_states.transpose(1, 2).index_select(0, state_indices)
scratch = storage.transpose(1, 2)
identity_indices = torch.arange(
state_indices.numel(), dtype=torch.int32, device=state_indices.device
)
return scratch, identity_indices
def _scatter_ds_conv_states(
conv_states: torch.Tensor,
state_indices: torch.Tensor,
scratch: torch.Tensor,
) -> None:
conv_states.index_copy_(0, state_indices.to(torch.int64), scratch)
def _causal_conv1d_fwd_cpu(
*,
x: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None,
conv_states: torch.Tensor,
query_start_loc: torch.Tensor,
cache_indices: torch.Tensor,
has_initial_state: torch.Tensor,
silu_activation: bool,
is_vnni: bool,
) -> torch.Tensor:
if not is_conv_state_dim_first():
return ops.causal_conv1d_fwd_cpu(
x=x,
weight=weight,
bias=bias,
conv_states=conv_states,
query_start_loc=query_start_loc,
cache_indices=cache_indices,
has_initial_state=has_initial_state,
silu_activation=silu_activation,
is_vnni=is_vnni,
)
scratch, identity_indices = _stage_ds_conv_states(conv_states, cache_indices)
out = ops.causal_conv1d_fwd_cpu(
x=x,
weight=weight,
bias=bias,
conv_states=scratch,
query_start_loc=query_start_loc,
cache_indices=identity_indices,
has_initial_state=has_initial_state,
silu_activation=silu_activation,
is_vnni=is_vnni,
)
_scatter_ds_conv_states(conv_states, cache_indices, scratch)
return out
def _causal_conv1d_update_cpu(
*,
x: torch.Tensor,
conv_states: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None,
silu_activation: bool,
conv_state_indices: torch.Tensor,
is_vnni: bool,
num_accepted_tokens: torch.Tensor | None = None,
) -> torch.Tensor:
if not is_conv_state_dim_first():
return ops.causal_conv1d_update_cpu(
x=x,
conv_states=conv_states,
weight=weight,
bias=bias,
silu_activation=silu_activation,
conv_state_indices=conv_state_indices,
is_vnni=is_vnni,
num_accepted_tokens=num_accepted_tokens,
)
scratch, identity_indices = _stage_ds_conv_states(conv_states, conv_state_indices)
out = ops.causal_conv1d_update_cpu(
x=x,
conv_states=scratch,
weight=weight,
bias=bias,
silu_activation=silu_activation,
conv_state_indices=identity_indices,
is_vnni=is_vnni,
num_accepted_tokens=num_accepted_tokens,
)
_scatter_ds_conv_states(conv_states, conv_state_indices, scratch)
return out
def cpu_gdn_attention_core(
mixed_qkv: torch.Tensor,
b: torch.Tensor,
@@ -109,10 +207,8 @@ def _cpu_gdn_attention_nonspec(
conv_state = layer.kv_cache[0]
if use_cpp_conv:
# C++ conv requires [num_allocated_slots, kernel - 1, conv_dim] (SD).
if is_conv_state_dim_first():
raise RuntimeError("C++ CPU GDN attention requires `SD` conv_state layout.")
conv_state = conv_state.transpose(1, 2)
if not is_conv_state_dim_first():
conv_state = conv_state.transpose(1, 2)
else:
if not is_conv_state_dim_first():
conv_state = conv_state.transpose(-1, -2)
@@ -141,7 +237,7 @@ def _cpu_gdn_attention_nonspec(
decode_a = a[:num_decode_tokens]
decode_state_indices = state_indices_tensor[:num_decodes]
if use_cpp_conv:
decode_mixed_qkv = ops.causal_conv1d_update_cpu(
decode_mixed_qkv = _causal_conv1d_update_cpu(
x=decode_mixed_qkv,
conv_states=conv_state,
weight=layer.conv1d.weight,
@@ -210,7 +306,7 @@ def _cpu_gdn_attention_nonspec(
]
if use_cpp_conv:
prefill_mixed_qkv = ops.causal_conv1d_fwd_cpu(
prefill_mixed_qkv = _causal_conv1d_fwd_cpu(
x=prefill_mixed_qkv.transpose(0, 1),
weight=layer.conv1d.weight,
bias=layer.conv1d.bias,
@@ -416,7 +512,6 @@ def _spec_forward(
can_use_native_conv = (
torch.cpu._is_amx_tile_supported()
and not is_conv_state_dim_first()
and width == 4
and num_spec_decodes > 0
and bool(torch.all(seq_lens == seq_lens[0]).item())
@@ -424,7 +519,7 @@ def _spec_forward(
)
if can_use_native_conv:
q_i = int(seq_lens[0].item())
conv_out = ops.causal_conv1d_update_cpu(
conv_out = _causal_conv1d_update_cpu(
x=mixed_qkv_spec.view(num_spec_decodes, q_i, dim),
conv_states=conv_buf,
weight=layer.conv1d.weight,
@@ -509,8 +604,6 @@ def _spec_aware_nonspec(
state_indices_tensor = state_indices_tensor.contiguous()
is_amx = torch.cpu._is_amx_tile_supported()
if is_amx and is_conv_state_dim_first():
raise RuntimeError("AMX GDN attention requires `SD` conv_state layout.")
if not is_amx:
conv_weights = _unpacked_conv_weight(layer)
@@ -526,7 +619,7 @@ def _spec_aware_nonspec(
decode_a = a[:num_decode_tokens]
decode_state_indices = state_indices_tensor[:num_decodes]
if is_amx:
decode_mixed_qkv = ops.causal_conv1d_update_cpu(
decode_mixed_qkv = _causal_conv1d_update_cpu(
x=decode_mixed_qkv,
conv_states=conv_buf,
weight=layer.conv1d.weight,
@@ -593,7 +686,7 @@ def _spec_aware_nonspec(
num_decodes : num_decodes + num_prefills
]
if is_amx:
prefill_mixed_qkv = ops.causal_conv1d_fwd_cpu(
prefill_mixed_qkv = _causal_conv1d_fwd_cpu(
x=prefill_mixed_qkv.transpose(0, 1),
weight=layer.conv1d.weight,
bias=layer.conv1d.bias,
@@ -664,11 +757,9 @@ def _spec_aware_nonspec_subset(
prefill_state_indices = prefill_state_indices.contiguous()
is_amx = torch.cpu._is_amx_tile_supported()
if is_amx and is_conv_state_dim_first():
raise RuntimeError("AMX GDN attention requires `SD` conv_state layout.")
if is_amx:
conv_out = ops.causal_conv1d_fwd_cpu(
conv_out = _causal_conv1d_fwd_cpu(
x=mixed_qkv.transpose(0, 1),
weight=layer.conv1d.weight,
bias=layer.conv1d.bias,
@@ -7,7 +7,7 @@ from typing import TypeVar
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
from vllm.config import ModelConfig
from vllm.logger import init_logger
@@ -17,7 +17,7 @@ logger = init_logger(__name__)
def get_act_fn(
config: PretrainedConfig,
config: PreTrainedConfig,
static_num_labels: bool = True,
) -> "PoolerActivation":
# get classification act_fn
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, Union
import torch
from safetensors.torch import _TYPES as _SAFETENSORS_TO_TORCH_DTYPE
from torch.nn import Parameter
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
import vllm.model_executor.layers.fused_moe # noqa
from vllm import _custom_ops as ops
@@ -370,7 +370,7 @@ class AutoAWQConfig(QuantizationConfig):
def maybe_update_config(
self,
model_name: str,
hf_config: PretrainedConfig | None = None,
hf_config: PreTrainedConfig | None = None,
revision: str | None = None,
):
if self.modules_to_not_convert:
@@ -6,7 +6,7 @@ from typing import Any
import torch
from safetensors.torch import _TYPES as _SAFETENSORS_TO_TORCH_DTYPE
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
import vllm.model_executor.layers.fused_moe # noqa
from vllm.logger import init_logger
@@ -273,7 +273,7 @@ class AutoGPTQConfig(QuantizationConfig):
def maybe_update_config(
self,
model_name: str,
hf_config: PretrainedConfig | None = None,
hf_config: PreTrainedConfig | None = None,
revision: str | None = None,
):
if self.modules_in_block_to_quantize:
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any
import regex as re
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization import QuantizationMethods
@@ -265,7 +265,7 @@ class QuantizationConfig(ABC):
def maybe_update_config( # noqa: B027
self,
model_name: str,
hf_config: PretrainedConfig | None = None,
hf_config: PreTrainedConfig | None = None,
revision: str | None = None,
):
"""Interface to update values after config initialization.
@@ -511,6 +511,13 @@ class CompressedTensorsConfig(QuantizationConfig):
def _is_dynamic_token_w4a8_int(
weight_quant: QuantizationArgs, input_quant: QuantizationArgs
) -> bool:
if not weight_quant or not input_quant:
return False
if (
weight_quant.type != QuantizationType.INT
or input_quant.type != QuantizationType.INT
):
return False
is_weight_4_bits = weight_quant.num_bits == 4
is_activation_8_bits = input_quant.num_bits == 8
weight_strategy = (
@@ -575,6 +582,11 @@ class CompressedTensorsConfig(QuantizationConfig):
) -> bool:
if not weight_quant or not input_quant:
return False
if (
weight_quant.type != QuantizationType.INT
or input_quant.type != QuantizationType.FLOAT
):
return False
is_weight_4_bits = weight_quant.num_bits == 4
is_activation_8_bits = input_quant.num_bits == 8
weight_strategy = weight_quant.strategy == QuantizationStrategy.GROUP.value
@@ -787,6 +799,7 @@ class CompressedTensorsConfig(QuantizationConfig):
num_bits=weight_quant.num_bits,
strategy=weight_quant.strategy,
group_size=weight_quant.group_size,
symmetric=weight_quant.symmetric,
input_quant=input_quant,
layer_name=layer_name,
quant_format=format,
@@ -799,6 +812,7 @@ class CompressedTensorsConfig(QuantizationConfig):
num_bits=weight_quant.num_bits,
strategy=weight_quant.strategy,
group_size=weight_quant.group_size,
symmetric=weight_quant.symmetric,
input_quant=input_quant,
layer_name=layer_name,
quant_format=format,
@@ -164,7 +164,7 @@ class CompressedTensorsMoEMethod(FusedMoEMethodBase):
return CompressedTensorsW8A8Int8MoEMethod(
weight_quant, input_quant, layer.moe_config
)
elif quant_config._is_fp8_w4a8_sm90(weight_quant, input_quant):
elif quant_config._is_fp8_w4a8(weight_quant, input_quant):
from .compressed_tensors_moe_w4a8_fp8 import (
CompressedTensorsW4A8Fp8MoEMethod,
)
@@ -24,6 +24,7 @@ from vllm.model_executor.layers.fused_moe.experts.marlin_moe import (
from vllm.model_executor.layers.fused_moe.experts.xpu_moe import (
XPUExpertsMxFp4,
)
from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput
from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import (
B12X_BACKENDS,
Mxfp4MoeBackend,
@@ -227,7 +228,7 @@ class CompressedTensorsW4A4Mxfp4MoEMethod(CompressedTensorsMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
x,
@@ -303,7 +303,7 @@ class CompressedTensorsW4A4Nvfp4MoEMethod(CompressedTensorsMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
x,
@@ -143,57 +143,49 @@ class CompressedTensorsW4A8Fp8MoEMethod(CompressedTensorsMoEMethod):
layer.register_parameter("w13_weight_shape", w13_weight_shape)
set_weight_attrs(w13_weight_shape, extra_weight_attrs)
w13_weight_chan_scale = torch.nn.Parameter(
torch.ones(
num_experts,
self.moe.w13_num_shards * intermediate_size_per_partition,
dtype=torch.float32,
),
requires_grad=False,
)
layer.register_parameter("w13_weight_chan_scale", w13_weight_chan_scale)
w2_weight_chan_scale = torch.nn.Parameter(
torch.ones(num_experts, hidden_size, dtype=torch.float32),
requires_grad=False,
)
layer.register_parameter("w2_weight_chan_scale", w2_weight_chan_scale)
# don't use input scales
layer.w13_input_scale = None
layer.w2_input_scale = None
def process_weights_after_loading(self, layer: RoutedExperts) -> None:
for name in ("w13", "w2"):
setattr(layer, f"{name}_weight", getattr(layer, f"{name}_weight_packed"))
delattr(layer, f"{name}_weight_packed")
(
w13_weight_packed,
w2_weight_packed,
w13_weight,
w2_weight,
w13_weight_scale,
w2_weight_scale,
w13_weight_chan_scale,
w2_weight_chan_scale,
b_strides1,
b_strides2,
self.b_strides1,
self.b_strides2,
) = convert_to_w4a8_moe_kernel_format(
w13_weight_packed=layer.w13_weight_packed,
w2_weight_packed=layer.w2_weight_packed,
backend=self.w4a8_backend,
layer=layer,
group_size=self.group_size,
w13_weight=layer.w13_weight,
w2_weight=layer.w2_weight,
w13_weight_scale=layer.w13_weight_scale,
w2_weight_scale=layer.w2_weight_scale,
)
replace_parameter(layer, "w13_weight_packed", w13_weight_packed)
replace_parameter(layer, "w2_weight_packed", w2_weight_packed)
replace_parameter(layer, "w13_weight_scale", w13_weight_scale)
replace_parameter(layer, "w2_weight_scale", w2_weight_scale)
replace_parameter(layer, "w13_weight_chan_scale", w13_weight_chan_scale)
replace_parameter(layer, "w2_weight_chan_scale", w2_weight_chan_scale)
self.b_strides1 = b_strides1
self.b_strides2 = b_strides2
for name, tensor in (
("w13_weight", w13_weight),
("w2_weight", w2_weight),
("w13_weight_scale", w13_weight_scale),
("w2_weight_scale", w2_weight_scale),
("w13_weight_chan_scale", w13_weight_chan_scale),
("w2_weight_chan_scale", w2_weight_chan_scale),
):
replace_parameter(layer, name, tensor)
self.moe_quant_config = self.get_fused_moe_quant_config(layer)
if self.moe_quant_config is not None:
assert self.experts_cls is not None
self.moe_kernel = make_w4a8_moe_kernel(
backend=self.w4a8_backend,
moe_quant_config=self.moe_quant_config,
moe_config=self.moe,
experts_cls=self.experts_cls,
@@ -205,10 +197,12 @@ class CompressedTensorsW4A8Fp8MoEMethod(CompressedTensorsMoEMethod):
def get_fused_moe_quant_config(self, layer: torch.nn.Module) -> FusedMoEQuantConfig:
return make_w4a8_moe_quant_config(
backend=self.w4a8_backend,
w1_scale=layer.w13_weight_scale,
w2_scale=layer.w2_weight_scale,
g1_alphas=layer.w13_weight_chan_scale,
g2_alphas=layer.w2_weight_chan_scale,
layer=layer,
)
def apply(
@@ -224,8 +218,8 @@ class CompressedTensorsW4A8Fp8MoEMethod(CompressedTensorsMoEMethod):
assert self.moe_kernel is not None
return self.moe_kernel.apply(
hidden_states=x,
w1=layer.w13_weight_packed,
w2=layer.w2_weight_packed,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
activation=layer.activation,
@@ -18,6 +18,7 @@ from vllm.model_executor.layers.fused_moe.config import (
FusedMoEConfig,
FusedMoEQuantConfig,
)
from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
make_fp8_moe_kernel,
@@ -375,7 +376,7 @@ class CompressedTensorsW8A8Fp8MoEMethod(CompressedTensorsMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -12,6 +12,7 @@ from vllm.model_executor.layers.fused_moe.config import (
FusedMoEConfig,
FusedMoEQuantConfig,
)
from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
make_fp8_moe_kernel,
@@ -188,7 +189,7 @@ class CompressedTensorsW8A8Mxfp8MoEMethod(CompressedTensorsMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -153,12 +153,10 @@ class CompressedTensorsW8A8Fp8(CompressedTensorsScheme):
layer.logical_widths,
getattr(layer, "input_scale", None),
)
weight = weight.t()
elif self.strategy == QuantizationStrategy.CHANNEL:
weight, weight_scale, input_scale = process_fp8_weight_channel_strategy(
layer.weight, layer.weight_scale, getattr(layer, "input_scale", None)
)
weight = weight.t()
elif self.strategy == QuantizationStrategy.BLOCK:
assert self.is_static_input_scheme is False
@@ -177,8 +175,7 @@ class CompressedTensorsW8A8Fp8(CompressedTensorsScheme):
# required by torch.compile to be torch.nn.Parameter
layer.weight = Parameter(weight.data, requires_grad=False)
# Preserve the dim tags dropped by the transpose so layout-aware
# kernels (humming) see (K, N) instead of assuming (N, K).
# The helpers return (K, N); retag so layout-aware kernels see it.
layer.weight.input_dim = 0
layer.weight.output_dim = 1
layer.weight_scale = Parameter(weight_scale.data, requires_grad=False)
@@ -33,9 +33,6 @@ class CompressedTensorsW8A8Mxfp8(CompressedTensorsScheme):
- Activations dynamically quantized to MXFP8 during inference
"""
def __init__(self):
self.kernel = init_mxfp8_linear_kernel()
@classmethod
def get_min_capability(cls) -> int:
return 75
@@ -79,6 +76,8 @@ class CompressedTensorsW8A8Mxfp8(CompressedTensorsScheme):
)
layer.register_parameter("weight_scale", weight_scale)
self.kernel = init_mxfp8_linear_kernel(weight_shape=layer.weight.shape)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.kernel.process_weights_after_loading(layer)
@@ -42,7 +42,15 @@ WNA16_SUPPORTED_TYPES_MAP = {
7: scalar_types.uint7b64,
8: scalar_types.uint8b128,
}
WNA16_ZP_SUPPORTED_TYPES_MAP = {4: scalar_types.uint4, 8: scalar_types.uint8}
WNA16_ZP_SUPPORTED_TYPES_MAP = {
2: scalar_types.uint2,
3: scalar_types.uint3,
4: scalar_types.uint4,
5: scalar_types.uint5,
6: scalar_types.uint6,
7: scalar_types.uint7,
8: scalar_types.uint8,
}
WNA16_SUPPORTED_BITS = list(WNA16_SUPPORTED_TYPES_MAP.keys())
@@ -111,8 +119,6 @@ class CompressedTensorsWNA16(CompressedTensorsScheme):
layer.output_size_per_partition = output_size_per_partition
layer.output_partition_sizes = output_partition_sizes
layer.params_dtype = params_dtype
if not hasattr(layer, "has_bias"):
layer.has_bias = False
mp_linear_kernel_config = MPLinearLayerConfig(
full_weight_shape=(input_size, output_size),
@@ -1,11 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Weight N-bit INT scheme with symmetric INT4 activation quant via Humming.
"""Weight N-bit INT scheme with INT4 activation quant via Humming.
Handles compressed-tensors pack-quantized INT weight checkpoints (2-8 bit)
with INT4 symmetric dynamic per-token/per-group input activation
quantization. Static, per-tensor, and asymmetric activation quantization
are not supported.
quantization. Supports both symmetric and asymmetric weight quantization.
Static, per-tensor, and asymmetric activation quantization are not supported.
"""
import math
@@ -28,6 +28,7 @@ from vllm.model_executor.layers.quantization.compressed_tensors.schemes import (
)
from vllm.model_executor.layers.quantization.compressed_tensors.schemes.compressed_tensors_wNa16 import ( # noqa: E501
WNA16_SUPPORTED_TYPES_MAP,
WNA16_ZP_SUPPORTED_TYPES_MAP,
)
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
marlin_repeat_scales_on_all_ranks,
@@ -36,6 +37,7 @@ from vllm.model_executor.parameter import (
BasevLLMParameter,
ChannelQuantScaleParameter,
GroupQuantScaleParameter,
PackedColumnParameter,
PackedvLLMParameter,
)
@@ -52,6 +54,7 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
num_bits: int,
strategy: str,
group_size: int | None = None,
symmetric: bool = True,
input_quant: QuantizationArgs | None = None,
layer_name: str | None = None,
quant_format: str = "pack-quantized",
@@ -60,6 +63,7 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
self.pack_factor = Fraction(32, num_bits)
self.strategy = strategy
self.group_size = -1 if group_size is None else group_size
self.symmetric = symmetric
self.input_quant = input_quant
self.layer_name = layer_name
self.quant_format = quant_format
@@ -69,7 +73,19 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
f"Unsupported num_bits = {num_bits} for WNA4Int; "
f"supported = {sorted(WNA16_SUPPORTED_TYPES_MAP)}"
)
self.quant_type = WNA16_SUPPORTED_TYPES_MAP[num_bits]
if not self.symmetric and num_bits not in WNA16_ZP_SUPPORTED_TYPES_MAP:
raise ValueError(
f"Asymmetric quantization not supported for "
f"num_bits = {num_bits}. Supported: "
f"{list(WNA16_ZP_SUPPORTED_TYPES_MAP)}"
)
self.quant_type = (
WNA16_ZP_SUPPORTED_TYPES_MAP[num_bits]
if not self.symmetric
else WNA16_SUPPORTED_TYPES_MAP[num_bits]
)
if input_quant is not None:
if not input_quant.symmetric:
@@ -131,8 +147,6 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
layer.output_size_per_partition = output_size_per_partition
layer.output_partition_sizes = output_partition_sizes
layer.params_dtype = params_dtype
if not hasattr(layer, "has_bias"):
layer.has_bias = False
mp_config = MPLinearLayerConfig(
full_weight_shape=(input_size, output_size),
@@ -143,7 +157,7 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
weight_type=self.quant_type,
act_type=params_dtype,
group_size=self.group_size,
zero_points=False,
zero_points=not self.symmetric,
)
kernel_type = choose_mp_linear_kernel(mp_config)
@@ -151,12 +165,6 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
logger.info("Using %s for CompressedTensorsWNA4Int", kernel_type.__name__)
self._kernel_backends_being_used.add(kernel_type.__name__)
self.kernel = kernel_type(
mp_config,
w_q_param_name="weight_packed",
w_s_param_name="weight_scale",
)
input_quant_config = self._build_input_quant_config()
if input_quant_config is not None:
layer._humming_input_quant_config = input_quant_config
@@ -167,10 +175,10 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
partition_scales = not marlin_repeat_scales_on_all_ranks(
self.group_size, row_parallel
)
scales_size = input_size // group_size
scales_and_zp_size = input_size // group_size
if partition_scales:
assert input_size_per_partition % group_size == 0
scales_size = input_size_per_partition // group_size
scales_and_zp_size = input_size_per_partition // group_size
packed_input_dim = math.ceil(input_size_per_partition * self.num_bits / 32)
layer.register_parameter(
@@ -190,7 +198,7 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
)
scale_data = torch.empty(
output_size_per_partition, scales_size, dtype=params_dtype
output_size_per_partition, scales_and_zp_size, dtype=params_dtype
)
if partition_scales:
weight_scale = GroupQuantScaleParameter(
@@ -207,6 +215,34 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
)
layer.register_parameter("weight_scale", weight_scale)
if not self.symmetric:
packed_output_dim = math.ceil(
output_size_per_partition * self.num_bits / 32
)
zeros_data = torch.zeros(
packed_output_dim,
scales_and_zp_size,
dtype=torch.int32,
)
if not partition_scales:
qzeros = PackedColumnParameter(
output_dim=0,
packed_dim=0,
packed_factor=self.pack_factor,
weight_loader=weight_loader,
data=zeros_data,
)
else:
qzeros = PackedvLLMParameter(
input_dim=1,
output_dim=0,
packed_dim=0,
packed_factor=self.pack_factor,
weight_loader=weight_loader,
data=zeros_data,
)
layer.register_parameter("weight_zero_point", qzeros)
layer.register_parameter(
"weight_shape",
BasevLLMParameter(
@@ -215,6 +251,13 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme):
),
)
self.kernel = kernel_type(
mp_config,
w_q_param_name="weight_packed",
w_s_param_name="weight_scale",
w_zp_param_name="weight_zero_point",
)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.kernel.process_weights_after_loading(layer)
@@ -1,11 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Weight N-bit INT scheme with symmetric INT8 activation quant via Humming.
"""Weight N-bit INT scheme with INT8 activation quant via Humming.
Handles compressed-tensors pack-quantized INT weight checkpoints (2-8 bit)
with INT8 symmetric dynamic per-token/per-group input activation
quantization. Static, per-tensor, and asymmetric activation quantization
are not supported.
quantization. Supports both symmetric and asymmetric weight quantization.
Static, per-tensor, and asymmetric activation quantization are not supported.
"""
import math
@@ -28,6 +28,7 @@ from vllm.model_executor.layers.quantization.compressed_tensors.schemes import (
)
from vllm.model_executor.layers.quantization.compressed_tensors.schemes.compressed_tensors_wNa16 import ( # noqa: E501
WNA16_SUPPORTED_TYPES_MAP,
WNA16_ZP_SUPPORTED_TYPES_MAP,
)
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
marlin_repeat_scales_on_all_ranks,
@@ -36,6 +37,7 @@ from vllm.model_executor.parameter import (
BasevLLMParameter,
ChannelQuantScaleParameter,
GroupQuantScaleParameter,
PackedColumnParameter,
PackedvLLMParameter,
)
@@ -52,6 +54,7 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
num_bits: int,
strategy: str,
group_size: int | None = None,
symmetric: bool = True,
input_quant: QuantizationArgs | None = None,
layer_name: str | None = None,
quant_format: str = "pack-quantized",
@@ -60,6 +63,7 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
self.pack_factor = Fraction(32, num_bits)
self.strategy = strategy
self.group_size = -1 if group_size is None else group_size
self.symmetric = symmetric
self.input_quant = input_quant
self.layer_name = layer_name
self.quant_format = quant_format
@@ -69,7 +73,19 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
f"Unsupported num_bits = {num_bits} for WNA8Int; "
f"supported = {sorted(WNA16_SUPPORTED_TYPES_MAP)}"
)
self.quant_type = WNA16_SUPPORTED_TYPES_MAP[num_bits]
if not self.symmetric and num_bits not in WNA16_ZP_SUPPORTED_TYPES_MAP:
raise ValueError(
f"Asymmetric quantization not supported for "
f"num_bits = {num_bits}. Supported: "
f"{list(WNA16_ZP_SUPPORTED_TYPES_MAP)}"
)
self.quant_type = (
WNA16_ZP_SUPPORTED_TYPES_MAP[num_bits]
if not self.symmetric
else WNA16_SUPPORTED_TYPES_MAP[num_bits]
)
if input_quant is not None:
if not input_quant.symmetric:
@@ -131,8 +147,6 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
layer.output_size_per_partition = output_size_per_partition
layer.output_partition_sizes = output_partition_sizes
layer.params_dtype = params_dtype
if not hasattr(layer, "has_bias"):
layer.has_bias = False
mp_config = MPLinearLayerConfig(
full_weight_shape=(input_size, output_size),
@@ -143,7 +157,7 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
weight_type=self.quant_type,
act_type=params_dtype,
group_size=self.group_size,
zero_points=False,
zero_points=not self.symmetric,
)
kernel_type = choose_mp_linear_kernel(mp_config)
@@ -151,12 +165,6 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
logger.info("Using %s for CompressedTensorsWNA8Int", kernel_type.__name__)
self._kernel_backends_being_used.add(kernel_type.__name__)
self.kernel = kernel_type(
mp_config,
w_q_param_name="weight_packed",
w_s_param_name="weight_scale",
)
input_quant_config = self._build_input_quant_config()
if input_quant_config is not None:
layer._humming_input_quant_config = input_quant_config
@@ -167,10 +175,10 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
partition_scales = not marlin_repeat_scales_on_all_ranks(
self.group_size, row_parallel
)
scales_size = input_size // group_size
scales_and_zp_size = input_size // group_size
if partition_scales:
assert input_size_per_partition % group_size == 0
scales_size = input_size_per_partition // group_size
scales_and_zp_size = input_size_per_partition // group_size
packed_input_dim = math.ceil(input_size_per_partition * self.num_bits / 32)
layer.register_parameter(
@@ -190,7 +198,7 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
)
scale_data = torch.empty(
output_size_per_partition, scales_size, dtype=params_dtype
output_size_per_partition, scales_and_zp_size, dtype=params_dtype
)
if partition_scales:
weight_scale = GroupQuantScaleParameter(
@@ -207,6 +215,34 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
)
layer.register_parameter("weight_scale", weight_scale)
if not self.symmetric:
packed_output_dim = math.ceil(
output_size_per_partition * self.num_bits / 32
)
zeros_data = torch.zeros(
packed_output_dim,
scales_and_zp_size,
dtype=torch.int32,
)
if not partition_scales:
qzeros = PackedColumnParameter(
output_dim=0,
packed_dim=0,
packed_factor=self.pack_factor,
weight_loader=weight_loader,
data=zeros_data,
)
else:
qzeros = PackedvLLMParameter(
input_dim=1,
output_dim=0,
packed_dim=0,
packed_factor=self.pack_factor,
weight_loader=weight_loader,
data=zeros_data,
)
layer.register_parameter("weight_zero_point", qzeros)
layer.register_parameter(
"weight_shape",
BasevLLMParameter(
@@ -215,6 +251,13 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme):
),
)
self.kernel = kernel_type(
mp_config,
w_q_param_name="weight_packed",
w_s_param_name="weight_scale",
w_zp_param_name="weight_zero_point",
)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.kernel.process_weights_after_loading(layer)
@@ -97,12 +97,8 @@ class CompressedTensorsWNA8O8Int(CompressedTensorsScheme):
output_size_per_partition = sum(output_partition_sizes)
layer.input_size_per_partition = input_size_per_partition
layer.output_size_per_partition = output_size_per_partition
# Set for kernels' weight prep; also covers ParallelLMHead, which does
# not set these in __init__.
layer.output_partition_sizes = output_partition_sizes
layer.params_dtype = params_dtype
if not hasattr(layer, "has_bias"):
layer.has_bias = False
mp_config = MPLinearLayerConfig(
full_weight_shape=(input_size, output_size),
@@ -95,13 +95,13 @@ class HadamardTransform(torch.nn.Module):
if self.transforms[part_id].scheme.head_dim is not None:
weight_size = self.transforms[part_id].scheme.head_dim
value = value.unflatten(-1, (-1, weight_size))
value = ops.hadacore_transform(value)
value = ops.hadacore_transform(value, inplace=False)
value = value.flatten(-2, -1)
return value
# sylvester transforms are symmetric, inv => transpose => original
return ops.hadacore_transform(value)
return ops.hadacore_transform(value, inplace=False)
# fall back to dense
else:
+14 -29
View File
@@ -24,6 +24,7 @@ from vllm.model_executor.layers.fused_moe import (
UnquantizedFusedMoEMethod,
)
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
make_fp8_moe_kernel,
@@ -93,7 +94,7 @@ class Fp8Config(QuantizationConfig):
def __init__(
self,
is_checkpoint_fp8_serialized: bool = False,
is_checkpoint_fp8_serialized: bool = True,
activation_scheme: str = "dynamic",
ignored_layers: list[str] | None = None,
weight_block_size: list[int] | None = None,
@@ -102,6 +103,13 @@ class Fp8Config(QuantizationConfig):
super().__init__()
self.is_checkpoint_fp8_serialized = is_checkpoint_fp8_serialized
if not is_checkpoint_fp8_serialized:
raise ValueError(
"The `fp8` quantization method no longer supports online "
"quantization. Please use `--quantization fp8_per_tensor` "
"instead. See "
"https://docs.vllm.ai/en/stable/features/quantization/online/"
)
if activation_scheme not in ACTIVATION_SCHEMES:
raise ValueError(f"Unsupported activation scheme {activation_scheme}")
@@ -112,11 +120,6 @@ class Fp8Config(QuantizationConfig):
)
self.store_dtype = store_dtype
if weight_block_size is not None:
if not is_checkpoint_fp8_serialized:
raise ValueError(
"The block-wise quantization only supports fp8-serialized "
"checkpoint for now."
)
if len(weight_block_size) != 2:
raise ValueError(
"The quantization block size of weight must have 2 "
@@ -182,18 +185,9 @@ class Fp8Config(QuantizationConfig):
match_mode=self.ignored_layers_match_mode,
):
return UnquantizedLinearMethod()
if not self.is_checkpoint_fp8_serialized:
from vllm.model_executor.layers.quantization.online.fp8 import (
Fp8PerTensorOnlineLinearMethod,
)
online_method = Fp8PerTensorOnlineLinearMethod()
online_method.marlin_input_dtype = get_marlin_input_dtype(prefix)
return online_method
else:
offline_method = Fp8LinearMethod(self)
offline_method.marlin_input_dtype = get_marlin_input_dtype(prefix)
return offline_method
offline_method = Fp8LinearMethod(self)
offline_method.marlin_input_dtype = get_marlin_input_dtype(prefix)
return offline_method
elif isinstance(layer, RoutedExperts):
if is_layer_skipped(
prefix=prefix,
@@ -208,14 +202,7 @@ class Fp8Config(QuantizationConfig):
)
return Mxfp4MoEMethod(layer.moe_config)
if self.is_checkpoint_fp8_serialized:
return Fp8MoEMethod(self, layer)
else:
from vllm.model_executor.layers.quantization.online.fp8 import (
Fp8PerTensorOnlineMoEMethod,
)
return Fp8PerTensorOnlineMoEMethod(moe=layer.moe_config)
return Fp8MoEMethod(self, layer)
elif isinstance(layer, Attention):
return Fp8KVCacheMethod(self)
return None
@@ -416,7 +403,6 @@ class Fp8LinearMethod(LinearMethodBase):
if self.act_q_static:
assert input_scale is not None
input_scale = input_scale.max()
weight = weight.t()
# Update layer with new values.
replace_parameter(layer, "weight", weight.data)
@@ -549,7 +535,6 @@ class Fp8MoEMethod(FusedMoEMethodBase):
layer.orig_dtype = params_dtype
layer.weight_block_size = None
assert self.quant_config.is_checkpoint_fp8_serialized
params_dtype = torch.float8_e4m3fn
if self.block_quant:
@@ -843,7 +828,7 @@ class Fp8MoEMethod(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -23,6 +23,7 @@ from vllm.model_executor.layers.fused_moe.experts.marlin_moe import (
from vllm.model_executor.layers.fused_moe.fused_moe_method_base import (
FusedMoEMethodBase,
)
from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput
from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import (
B12X_BACKENDS,
Mxfp4MoeBackend,
@@ -228,7 +229,7 @@ class INCMxfp4MoEMethod(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
x,
@@ -17,9 +17,6 @@ from .inc_scheme import INCLinearScheme
class INCMxfp8LinearScheme(INCLinearScheme):
def __init__(self) -> None:
self.kernel = init_mxfp8_linear_kernel()
@classmethod
def get_min_capability(cls) -> int:
return 75
@@ -72,6 +69,8 @@ class INCMxfp8LinearScheme(INCLinearScheme):
)
layer.register_parameter("weight_scale", weight_scale)
self.kernel = init_mxfp8_linear_kernel(weight_shape=layer.weight.shape)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
self.kernel.process_weights_after_loading(layer)
@@ -12,6 +12,7 @@ from vllm.model_executor.layers.fused_moe import (
from vllm.model_executor.layers.fused_moe.fused_moe_method_base import (
FusedMoEMethodBase,
)
from vllm.model_executor.layers.fused_moe.moe_output import UnfinalizedMoEOutput
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
make_fp8_moe_kernel,
@@ -179,7 +180,7 @@ class INCMxfp8MoEMethod(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
x,
@@ -155,8 +155,11 @@ class QuantFP8(CustomOp):
if use_aiter_per_token_quant:
return rocm_aiter_ops.per_token_quant(x, _FP8_DTYPE, scale)
# Fallback to CUDA implementation
return self.forward_cuda(x, scale, scale_ub)
# Fall back to the CUDA implementation. Dispatch on the class, not
# through self: a subclass may override forward_cuda with a different
# signature (_DecodeConcatQuantFP8 does), and a virtual call would
# re-enter it with mismatched arguments.
return QuantFP8.forward_cuda(self, x, scale, scale_ub)
def forward_xpu(
self,
@@ -175,7 +178,8 @@ class QuantFP8(CustomOp):
dtype=_FP8_DTYPE,
use_ue8m0=self.use_ue8m0,
)
return self.forward_cuda(x, scale, scale_ub, use_triton)
# Dispatch on the class, for the same reason as in forward_hip.
return QuantFP8.forward_cuda(self, x, scale, scale_ub, use_triton)
def forward_native(
self,
@@ -690,7 +690,7 @@ class ModelOptFp8MoEMethod(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -1102,7 +1102,7 @@ class ModelOptNvFp4FusedMoE(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -1471,7 +1471,7 @@ class ModelOptMxFp8FusedMoE(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -2129,7 +2129,7 @@ class KFp8StaticChannel(QuantKeyScheme):
weight, weight_scale, _ = process_fp8_weight_channel_strategy(
layer.weight, layer.weight_scale.data
)
layer.weight = Parameter(weight.t(), requires_grad=False)
layer.weight = Parameter(weight, requires_grad=False)
layer.weight_scale = Parameter(weight_scale, requires_grad=False)
@@ -2320,7 +2320,8 @@ def select_linear_kernel(
return init_nvfp4_linear_kernel(use_a16=spec.activation is None)
if w.scale.dtype == MXFP8_SCALE_DTYPE:
return init_mxfp8_linear_kernel(
bmm_batch_size=getattr(layer, "bmm_batch_size", None)
weight_shape=weight_shape or layer.weight.shape,
bmm_batch_size=getattr(layer, "bmm_batch_size", None),
)
# fp8 family: init_fp8 routes block-vs-plain itself off the activation key,
# and needs a real key -- weight-only fp8 is not a ModelOpt format.
@@ -2508,12 +2509,6 @@ class ModelOptLinearMethod(LinearMethodBase):
layer.logical_widths = output_partition_sizes
layer.input_size_per_partition = input_size_per_partition
layer.output_size_per_partition = sum(output_partition_sizes)
# Humming reads both off the layer in
# prepare_humming_linear_layer_config. LinearBase sets them itself;
# ParallelLMHead does not, so supply them here.
layer.output_partition_sizes = output_partition_sizes
if not hasattr(layer, "has_bias"):
layer.has_bias = getattr(layer, "bias", None) is not None
shapes = Shapes(output_partition_sizes, input_size_per_partition, params_dtype)
self.wkey.create_weights(layer, WEIGHT, self.ctx, shapes, weight_loader)
@@ -2532,7 +2527,10 @@ class ModelOptLinearMethod(LinearMethodBase):
def process_weights_after_loading(self, layer) -> None:
if self.spec.weight == kMxfp8Static and getattr(layer, "is_bmm", False):
self.kernel = init_mxfp8_linear_kernel(bmm_batch_size=layer.bmm_batch_size)
self.kernel = init_mxfp8_linear_kernel(
weight_shape=(layer.weight.shape[-2], layer.weight.shape[-1]),
bmm_batch_size=layer.bmm_batch_size,
)
if is_weights_pre_processed():
if not self.supports_pre_processed_weights:
raise RuntimeError(
@@ -433,7 +433,7 @@ class GptOssMxfp4MoEMethod(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -860,7 +860,7 @@ class Mxfp4MoEMethod(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -166,7 +166,7 @@ class OnlineMoEMethodBase(FusedMoEMethodBase):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert not self.is_monolithic
assert self.moe_kernel is not None
return self.moe_kernel.apply(
@@ -42,10 +42,6 @@ class Mxfp8OnlineLinearMethod(OnlineLinearBase):
FP8 with block-32 scales) during weight loading.
"""
def __init__(self):
super().__init__()
self.kernel = init_mxfp8_linear_kernel()
def create_weights(
self,
layer: torch.nn.Module,
@@ -73,6 +69,8 @@ class Mxfp8OnlineLinearMethod(OnlineLinearBase):
**extra_weight_attrs,
)
self.kernel = init_mxfp8_linear_kernel(weight_shape=layer.weight.shape)
def process_weights_after_loading(self, layer: Module) -> None:
if getattr(layer, "_already_called_process_weights_after_loading", False):
return
@@ -24,7 +24,7 @@ from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
amax_for_moe_weight_quant,
kNvfp4Dynamic,
kNvfp4DynamicToken,
kNvfp4Static,
weight_amax,
)
@@ -100,7 +100,7 @@ class Nvfp4OnlineMoEMethod(OnlineMoEMethodBase):
self.nvfp4_backend, self.experts_cls = select_nvfp4_moe_backend(
config=self.moe,
weight_key=kNvfp4Static,
activation_key=kNvfp4Dynamic,
activation_key=kNvfp4DynamicToken,
)
def process_weights_after_loading(self, layer: Module) -> None:
@@ -178,6 +178,14 @@ class Nvfp4OnlineMoEMethod(OnlineMoEMethodBase):
routing_tables=layer._expert_routing_tables(),
per_token_activation=True,
)
else:
# Reload creates new scale tensors; derived kernel scales must use
# their new values before layerwise reload restores captured storage.
assert self.moe_quant_config is not None
assert self.moe_quant_config.g1_alphas is not None
assert self.moe_quant_config.g2_alphas is not None
self.moe_quant_config.g1_alphas.copy_(w13_scale_2)
self.moe_quant_config.g2_alphas.copy_(w2_scale_2)
self.moe_kernel.fused_experts.process_weights_after_loading(layer)
@@ -5,7 +5,6 @@ import fnmatch
from typing import TYPE_CHECKING, Any, NamedTuple, cast
import torch
from transformers import PretrainedConfig
from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
@@ -46,6 +45,8 @@ from vllm.model_executor.layers.quantization.quark.utils import (
from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import (
_ACTIVATION_QUANT_KEY_MAP,
_WEIGHT_QUANT_KEY_MAP,
OCP_MX_BLOCK_SIZE,
ocp_mx_weight_dtype_and_rows,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
@@ -82,10 +83,6 @@ __all__ = ["QuarkLinearMethod"]
logger = init_logger(__name__)
# model_type values that use dynamic MXFP4 re-quantization for
# OCP MX fp4 Quark checkpoints
_DEEPSEEK_V3_FAMILY_MODEL_TYPES = frozenset({"deepseek_v3", "deepseek_v32"})
class QuantKeyMatch(NamedTuple):
matches: bool
@@ -119,37 +116,6 @@ class QuarkConfig(QuantizationConfig):
self.kv_cache_group = kv_cache_group
self.kv_cache_config = kv_cache_config
self.pack_method = pack_method
# Note : this flag is kept disabled because the overhead of
# dynamic mxfp4 quantization negates the performance gains
# that come from shifting to mxfp4. It is left here in case
# we want to re-enable it in the future.
self.dynamic_mxfp4_quant = False
def maybe_update_config(
self,
model_name: str,
hf_config: PretrainedConfig | None = None,
revision: str | None = None,
):
"""Enable dynamic MXFP4 only for DeepSeek-V3-family fp4 checkpoints."""
if hf_config is None:
return
if (
getattr(hf_config, "model_type", None)
not in _DEEPSEEK_V3_FAMILY_MODEL_TYPES
):
return
quant_config = getattr(hf_config, "quantization_config", None)
if isinstance(quant_config, dict):
quant_dtype = (
quant_config.get("global_quant_config", {})
.get("weight", {})
.get("dtype")
)
if quant_dtype == "fp4":
self.dynamic_mxfp4_quant = True
def get_linear_method(self) -> "QuarkLinearMethod":
return QuarkLinearMethod(self)
@@ -194,6 +160,20 @@ class QuarkConfig(QuantizationConfig):
self.quant_config = quant_config_with_hf_to_vllm_mapper
def _scale_block_rows(self, prefix: str, layer_type: type[torch.nn.Module]) -> int:
"""How many weight rows one checkpoint scale row covers.
1 for the canonical 1-D per-group MX spelling; ``block_size[0]`` for
MXFP8 exports that spell the scale 2-D (DeepSeek-V4.1 uses 32). The
scheme cannot work this out itself: it has no handle on the layer name,
and tensor-parallel sharding narrows the loaded scale so the ratio is
not recoverable from shapes either.
"""
config = self._find_matched_config(prefix, layer_type)
weight = self._unwrap_single_quant_config(config.get("weight"))
normalized = ocp_mx_weight_dtype_and_rows(weight)
return normalized[1] if normalized is not None else 1
def get_quant_method(
self, layer: torch.nn.Module, prefix: str
) -> "QuantizeMethodBase | None":
@@ -201,17 +181,6 @@ class QuarkConfig(QuantizationConfig):
self.get_quant_method_target(prefix, type(layer))
)
exclude_layers = cast(list[str], self.quant_config.get("exclude"))
is_ignored = should_ignore_layer(
prefix,
ignore=exclude_layers,
fused_mapping=self.packed_modules_mapping,
check_children=isinstance(layer, RoutedExperts),
)
dynamic_mxfp4_quant = (
is_ignored and "self_attn" in prefix and self.dynamic_mxfp4_quant
)
if method_cls is UnquantizedFusedMoEMethod:
return UnquantizedFusedMoEMethod(layer.moe_config)
if method_cls is UnquantizedLinearMethod:
@@ -222,7 +191,11 @@ class QuarkConfig(QuantizationConfig):
scheme_cls,
weight_quant_key=weight_quant_key,
activation_quant_key=activation_quant_key,
dynamic_mxfp4_quant=dynamic_mxfp4_quant,
scale_block_rows=(
self._scale_block_rows(prefix, type(layer))
if scheme_cls is QuarkOCP_MX
else 1
),
weight_config=self._find_matched_config(prefix, type(layer)).get(
"weight"
),
@@ -274,11 +247,6 @@ class QuarkConfig(QuantizationConfig):
if is_routed_experts:
return None, None, UnquantizedFusedMoEMethod
if issubclass(layer_type, LinearBase):
if "self_attn" in prefix and self.dynamic_mxfp4_quant:
weight_quant_key, activation_key, _ = self.get_scheme_cls(
layer_type, prefix
)
return weight_quant_key, activation_key, QuarkLinearMethod
return None, None, UnquantizedLinearMethod
return None, None, None
if issubclass(layer_type, LinearBase):
@@ -693,52 +661,18 @@ class QuarkConfig(QuantizationConfig):
The rationale for checking only the weight type is that
the model loading concept and process primarily concerns the weights themselves.
"""
# Confirm weights quantized.
if not isinstance(weight_quant, dict):
# Confirm weights quantized, and normalize the two OCP MX config
# dialects (1-D per_group, and MXFP8's 2-D per_block) to a dtype.
normalized = ocp_mx_weight_dtype_and_rows(weight_quant)
if normalized is None:
logger.debug(
"Quark model's weight quantization is incompatible with OCP_MX format: "
"weight_quant is not a dictionary."
"Quark model's weight quantization is incompatible with OCP MX "
"format: %s",
weight_quant,
)
return QuantKeyMatch(False, None, None)
# Input and weight qscheme needs to be per group.
if weight_quant.get("qscheme") != "per_group":
logger.debug(
"Quark model's weight quantization is incompatible with OCP MX format: "
"weight is not per_group."
)
return QuantKeyMatch(False, None, None)
# Input and weight group size needs to be 32.
if weight_quant.get("group_size") != 32:
logger.debug(
"Quark model's weight quantization is incompatible with OCP MX format: "
"group_size of weight is not 32."
)
return QuantKeyMatch(False, None, None)
# Activations and weight scales need to be in e8m0 format.
if weight_quant.get("scale_format") != "e8m0":
logger.debug(
"Quark model's weight quantization is incompatible with OCP MX format: "
"scale_format of weight is not e8m0."
)
return QuantKeyMatch(False, None, None)
# Input and weight dtypes need to be any of fp4,
# fp6_e3m2 or fp6_e3m2, possibly mixed.
if weight_quant.get("dtype") not in {
"fp4",
"fp6_e3m2",
"fp6_e2m3",
}:
logger.debug(
"Quark model's weight quantization is incompatible with OCP MX format: "
"dtype is not in {fp4, fp6_e3m2, fp6_e2m3}."
)
return QuantKeyMatch(False, None, None)
weight_dtype = weight_quant["dtype"].replace("fp", "mxfp")
weight_dtype, _ = normalized
weight_quant_key = _WEIGHT_QUANT_KEY_MAP[weight_dtype]
if input_quant is None:
activation_quant_key = None
@@ -756,6 +690,14 @@ class QuarkConfig(QuantizationConfig):
"input scales."
)
return QuantKeyMatch(False, None, None)
elif (
input_quant["dtype"] == "fp8_e4m3"
and input_quant.get("qscheme") == "per_group"
and input_quant.get("group_size") == OCP_MX_BLOCK_SIZE
):
# MXFP8 activations. Must be checked before the per-tensor FP8
# branch below, which would otherwise claim them.
activation_quant_key = _ACTIVATION_QUANT_KEY_MAP["mxfp8_e4m3"]
elif input_quant["dtype"] == "fp8_e4m3":
activation_quant_key = kFp8DynamicTensorSym
else:
@@ -956,7 +898,7 @@ class QuarkConfig(QuantizationConfig):
scheme_cls: type["QuarkScheme"],
weight_quant_key: QuantKey | None,
activation_quant_key: QuantKey | None,
dynamic_mxfp4_quant: bool = False,
scale_block_rows: int = 1,
weight_config: dict[str, Any] | None = None,
) -> "QuarkScheme":
"""Construct a Quark scheme selected by get_scheme_cls."""
@@ -997,7 +939,7 @@ class QuarkConfig(QuantizationConfig):
kwargs["weight_quant_key"] = weight_quant_key
if scheme_cls is QuarkOCP_MX:
kwargs["dynamic_mxfp4_quant"] = dynamic_mxfp4_quant
kwargs["scale_block_rows"] = scale_block_rows
scheme = scheme_cls(**kwargs)
@@ -976,7 +976,7 @@ class QuarkW8A8Fp8MoEMethod(QuarkMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
hidden_states=x,
@@ -1587,7 +1587,9 @@ class QuarkOCP_MX_MoEMethod(QuarkMoEMethod):
raise ValueError(
f"Unsupported OCP MX dtype combination for MoE: "
f"input_dtype={self.input_dtype}, weight_dtype={self.weight_dtype}. "
f"Please check that the combination is supported in OCP_MX_Scheme."
f"MXFP8 experts are not supported through the MoE path; only "
f"the linear path handles MXFP8. Supported MoE weight dtypes "
f"are mxfp4, mxfp6_e3m2, and mxfp6_e2m3."
)
# TODO(bowenbao): refactor and introduce backends for other OCP MX schemes,
@@ -1676,10 +1678,16 @@ class QuarkOCP_MX_MoEMethod(QuarkMoEMethod):
if quant_dtype == "mxfp4":
assert dim % 2 == 0
return dim // 2
else:
elif quant_dtype in {"mxfp6_e3m2", "mxfp6_e2m3"}:
# FP6 packs 4 * 6 = 24 bits on 3 bytes.
assert (dim * 3) % 4 == 0
return (dim * 3) // 4
else:
raise NotImplementedError(
f"Unsupported quant_dtype in QuarkOCP_MX_MoEMethod."
f"get_packed_dim: {quant_dtype}. MXFP8 is not supported for "
f"MoE experts."
)
def create_weights(
self,
@@ -1935,7 +1943,7 @@ class QuarkOCP_MX_MoEMethod(QuarkMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
hidden_states=x,
@@ -2182,7 +2190,7 @@ class QuarkNvfp4MoEMethod(QuarkMoEMethod):
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
) -> torch.Tensor | UnfinalizedMoEOutput:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
x,
@@ -10,26 +10,33 @@ from vllm.logger import init_logger
from vllm.model_executor.kernels.linear import (
MxFp4LinearKernel,
MxFp6LinearKernel,
Mxfp8LinearKernel,
init_mxfp4_linear_kernel,
init_mxfp6_linear_kernel,
init_mxfp8_linear_kernel,
)
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
MXFP8_SCALE_DTYPE,
MXFP8_VALUE_DTYPE,
)
from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import (
_ACTIVATION_QUANT_KEY_MAP,
_WEIGHT_QUANT_KEY_MAP,
OCP_MX_BLOCK_SIZE,
OCP_MX_UNPACKED_DTYPES,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kMxfp4Static,
kMxfp6E2M3Static,
kMxfp6E3M2Static,
kMxfp8Static,
)
from vllm.model_executor.parameter import (
GroupQuantScaleParameter,
ModelWeightParameter,
PackedvLLMParameter,
)
from vllm.model_executor.utils import set_weight_attrs
from vllm.platforms import current_platform
from .quark_scheme import QuarkScheme
@@ -38,7 +45,7 @@ logger = init_logger(__name__)
class QuarkOCP_MX(QuarkScheme):
ocp_mx_linear: MxFp6LinearKernel | MxFp4LinearKernel
ocp_mx_linear: MxFp6LinearKernel | MxFp4LinearKernel | Mxfp8LinearKernel
supported_activation_quant_keys = [*_ACTIVATION_QUANT_KEY_MAP.values(), None]
supported_weight_quant_keys = [*_WEIGHT_QUANT_KEY_MAP.values()]
@@ -46,10 +53,10 @@ class QuarkOCP_MX(QuarkScheme):
self,
weight_quant_key: QuantKey,
activation_quant_key: QuantKey | None,
dynamic_mxfp4_quant: bool = False,
scale_block_rows: int = 1,
):
super().__init__(weight_quant_key, activation_quant_key)
self.dynamic_mxfp4_quant = dynamic_mxfp4_quant
self.scale_block_rows = scale_block_rows
self.weight_dtype = next(
dtype
for dtype, quant_key in _WEIGHT_QUANT_KEY_MAP.items()
@@ -65,11 +72,21 @@ class QuarkOCP_MX(QuarkScheme):
else None
)
if self.weight_dtype == "mxfp4":
self.packed_factor: int | Fraction = 2
self.is_unpacked = self.weight_dtype in OCP_MX_UNPACKED_DTYPES
if self.is_unpacked:
self.packed_factor: int | Fraction = 1
elif self.weight_dtype == "mxfp4":
self.packed_factor = 2
else:
self.packed_factor = Fraction(numerator=8, denominator=6)
if self.is_unpacked:
# MXFP8 runs on the shared kernel abstraction, which picks a native
# backend where one exists and emulates otherwise. The MXFP4/MXFP6
# warnings below do not apply.
return
if not current_platform.supports_mx():
logger.warning_once(
"The current platform does not support native MXFP4/MXFP6 "
@@ -91,7 +108,9 @@ class QuarkOCP_MX(QuarkScheme):
)
def get_packed_dim(self, dim: int, quant_dtype: str):
if quant_dtype == "mxfp4":
if quant_dtype in OCP_MX_UNPACKED_DTYPES:
return dim
elif quant_dtype == "mxfp4":
assert dim % 2 == 0
return dim // 2
elif quant_dtype in {"mxfp6_e3m2", "mxfp6_e2m3"}:
@@ -105,25 +124,33 @@ class QuarkOCP_MX(QuarkScheme):
"open an issue."
)
def _expanding_scale_loader(self, weight_loader: Callable) -> Callable:
"""Expand a 2-D block scale to one row per weight row.
A ``block_size=[R, 32]`` export carries one e8m0 value per R weight
rows; the kernels want one per row. At ``R == 1`` the layouts already
coincide, so the loader is passed through untouched.
"""
if self.scale_block_rows == 1:
return weight_loader
rows = self.scale_block_rows
def expanding_loader(param, loaded_weight, *args, **kwargs):
loaded_weight = loaded_weight.view(torch.uint8).repeat_interleave(
rows, dim=0
)
return weight_loader(param, loaded_weight, *args, **kwargs)
return expanding_loader
@classmethod
def get_min_capability(cls) -> int:
return 70
def process_dynamic_mxfp4_weights_after_loading(
self, layer: torch.nn.Module
) -> None:
from aiter.ops.triton.quant import dynamic_mxfp4_quant
w_q, w_s = dynamic_mxfp4_quant(layer.weight)
layer.weight_scale = torch.nn.Parameter(w_s, requires_grad=False)
layer.weight = torch.nn.Parameter(w_q, requires_grad=False)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
layer.weight = torch.nn.Parameter(layer.weight.data, requires_grad=False)
if self.dynamic_mxfp4_quant:
self.process_dynamic_mxfp4_weights_after_loading(layer)
self.ocp_mx_linear.process_weights_after_loading(layer)
def create_weights(
@@ -145,20 +172,37 @@ class QuarkOCP_MX(QuarkScheme):
"tensor-parallel sharding for this layer."
)
if self.dynamic_mxfp4_quant:
if self.is_unpacked:
output_size_per_partition = sum(output_partition_sizes)
layer.logical_widths = output_partition_sizes
layer.input_size_per_partition = input_size_per_partition
layer.output_size_per_partition = output_size_per_partition
layer.params_dtype = params_dtype
weight = ModelWeightParameter(
data=torch.empty(
sum(output_partition_sizes),
output_size_per_partition,
input_size_per_partition,
dtype=params_dtype,
dtype=MXFP8_VALUE_DTYPE,
),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
)
layer.register_parameter("weight", weight)
set_weight_attrs(weight, kwargs)
weight_scale = GroupQuantScaleParameter(
data=torch.empty(
output_size_per_partition,
input_size_per_partition // OCP_MX_BLOCK_SIZE,
dtype=MXFP8_SCALE_DTYPE,
),
input_dim=1,
output_dim=0,
weight_loader=self._expanding_scale_loader(weight_loader),
)
layer.register_parameter("weight_scale", weight_scale)
layer.weight_block_size = [1, OCP_MX_BLOCK_SIZE]
else:
output_size_per_partition = sum(output_partition_sizes)
layer.logical_widths = output_partition_sizes
@@ -200,6 +244,16 @@ class QuarkOCP_MX(QuarkScheme):
weight_quant_key=self.weight_quant_key,
activation_quant_key=self.activation_quant_key,
)
elif self.weight_quant_key == kMxfp8Static:
self.ocp_mx_linear = init_mxfp8_linear_kernel(
weight_shape=layer.weight.shape
)
else:
raise NotImplementedError(
"No OCP MX linear kernel for weight_quant_key="
f"{self.weight_quant_key}. Something is wrong, please open an "
"issue."
)
def apply_weights(
self,
@@ -1,67 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm.platforms import current_platform
from vllm.scalar_type import ScalarType, scalar_types
ALLSPARK_AMPERE_M_CUBLAS_THRESHOLD = 1024
ALLSPARK_SUPPORTED_QUANT_TYPES = [scalar_types.uint8b128]
ALLSPARK_AMPERE_N_ALIGN = 16
ALLSPARK_AMPERE_K_ALIGN = 16
def check_allspark_supported_dtype_shape(
input_size_per_partition: int,
output_size_per_partition: int,
group_size: int,
weight_dtype: ScalarType,
act_dtype: torch.dtype,
):
capability_tuple = current_platform.get_device_capability()
device_capability = -1 if capability_tuple is None else capability_tuple.to_int()
# For Ampere GPU
if device_capability >= 80 and device_capability < 90:
if group_size != -1:
return (
False,
"For Ampere GPU, AllSpark does not support group_size "
f"= {group_size}. Only group_size = -1 are supported.",
)
if weight_dtype not in ALLSPARK_SUPPORTED_QUANT_TYPES:
return (
False,
"For Ampere GPU, AllSpark does not support "
f"quant type ({weight_dtype}). Only quant type "
f"({ALLSPARK_SUPPORTED_QUANT_TYPES}) are supported.",
)
if (
input_size_per_partition % ALLSPARK_AMPERE_K_ALIGN != 0
or output_size_per_partition % ALLSPARK_AMPERE_N_ALIGN != 0
):
return (
False,
"AllSpark needs input_size_per_partition % "
f"{ALLSPARK_AMPERE_K_ALIGN} = 0 and "
f"output_size_per_partition % {ALLSPARK_AMPERE_N_ALIGN} = 0 "
"for Ampere GPU optimized kernels.",
)
if act_dtype != torch.float16 and act_dtype != torch.bfloat16:
return (
False,
"AllSpark only supports act_dtype = float16 or bfloat16,"
f"for Ampere GPU, but got act_dtype = {act_dtype}.",
)
else:
return (
False,
"AllSpark currently does not support "
f"device_capability = {device_capability}.",
)
return True, None
@@ -44,7 +44,12 @@ def get_quark_ocp_mx_group_size(
return None
assert weight_quant is not None
return int(weight_quant["group_size"])
group_size = weight_quant.get("group_size")
if group_size is None:
block_size = weight_quant.get("block_size")
if isinstance(block_size, list | tuple) and len(block_size) >= 2:
group_size = block_size[1]
return int(group_size) if group_size is not None else None
def is_shared_expert_quant_fse_compatible(
@@ -1373,7 +1373,7 @@ def process_fp8_weight_tensor_strategy(
logical_widths: list[int],
input_scale: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
"""Process weights for tensor-wise quantization strategy."""
"""Requantize fused shards to one scale and return ``(K, N)`` weight."""
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
normalize_e4m3fn_to_e4m3fnuz,
requantize_with_max_scale,
@@ -1391,7 +1391,7 @@ def process_fp8_weight_tensor_strategy(
logical_widths=logical_widths,
)
weight = _maybe_pad_fp8_weight(weight)
weight = _maybe_pad_fp8_weight(weight).t()
return weight, weight_scale, input_scale
@@ -1400,7 +1400,7 @@ def process_fp8_weight_channel_strategy(
weight_scale: torch.Tensor,
input_scale: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
"""Process weights for channel-wise quantization strategy."""
"""Normalize FNUZ if needed and return ``(K, N)`` weight."""
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
normalize_e4m3fn_to_e4m3fnuz,
)
@@ -1410,14 +1410,14 @@ def process_fp8_weight_channel_strategy(
weight=weight, weight_scale=weight_scale, input_scale=input_scale
)
return weight, weight_scale, input_scale
return weight.t(), weight_scale, input_scale
def process_fp8_weight_block_strategy(
weight: torch.Tensor,
weight_scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Process weights for block-wise quantization strategy."""
"""Normalize FNUZ if needed and return ``(N, K)`` weight (no transpose)."""
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
normalize_e4m3fn_to_e4m3fnuz,
)
@@ -101,6 +101,19 @@ def prepare_humming_linear_layer_config(
param_dtype=layer.params_dtype,
)
if (
weight_schema.has_zero_point
and input_schema.a_dtype is not None
and weight_schema.b_dtype.num_bits == input_schema.a_dtype.num_bits
):
raise ValueError(
"Humming does not support asymmetric (zero_point) weights "
"when weight and activation bit widths are equal "
f"(W{weight_schema.b_dtype.num_bits}"
f"A{input_schema.a_dtype.num_bits}). "
"Use symmetric weights or a different activation bit width."
)
tensors.update(input_tensors)
layer.weight_schema = weight_schema
input_schema = check_and_fallback_input_schema(
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from enum import Enum
from typing import Any
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.utils.quant_utils import (
@@ -11,6 +12,8 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
kMxfp6E2M3Static,
kMxfp6E3M2Dynamic,
kMxfp6E3M2Static,
kMxfp8Dynamic,
kMxfp8Static,
)
logger = init_logger(__name__)
@@ -21,14 +24,19 @@ _WEIGHT_QUANT_KEY_MAP: dict[str, QuantKey] = {
"mxfp4": kMxfp4Static,
"mxfp6_e3m2": kMxfp6E3M2Static,
"mxfp6_e2m3": kMxfp6E2M3Static,
"mxfp8_e4m3": kMxfp8Static,
}
_ACTIVATION_QUANT_KEY_MAP: dict[str, QuantKey] = {
"mxfp4": kMxfp4Dynamic,
"mxfp6_e3m2": kMxfp6E3M2Dynamic,
"mxfp6_e2m3": kMxfp6E2M3Dynamic,
"mxfp8_e4m3": kMxfp8Dynamic,
}
# Unpacked OCP MX dtypes: one byte per element, no `packed_factor`.
OCP_MX_UNPACKED_DTYPES = {"mxfp8_e4m3"}
OCP_MX_DTYPES = {
"mxfp4",
"mxfp6_e3m2",
@@ -39,6 +47,56 @@ OCP_MX_DTYPES = {
}
def ocp_mx_weight_dtype_and_rows(
weight_quant: dict[str, Any] | None,
) -> tuple[str, int] | None:
"""Normalize a Quark weight quant config to ``(mx_dtype, scale_block_rows)``.
Quark spells OCP MX weights two ways. The canonical one is 1-D per-group:
``qscheme="per_group"``, ``group_size=32``, ``scale_format="e8m0"``. MXFP8
checkpoints may instead use a 2-D per-block spelling
(``qscheme="per_block"``, ``block_size=[R, 32]``,
``scale_type="float8_e8m0fnu"``), which carries one scale per ``R`` weight
rows rather than one per row. ``scale_block_rows`` is that ``R``; it is 1
for the canonical spelling, where the two layouts coincide.
Returns ``None`` when the config is not an OCP MX weight quantization.
"""
if not isinstance(weight_quant, dict):
return None
dtype = weight_quant.get("dtype")
if not isinstance(dtype, str):
return None
mx_dtype = dtype.replace("fp", "mxfp")
if mx_dtype not in _WEIGHT_QUANT_KEY_MAP:
return None
qscheme = weight_quant.get("qscheme")
if qscheme == "per_group":
if weight_quant.get("group_size") != OCP_MX_BLOCK_SIZE:
return None
if weight_quant.get("scale_format") != "e8m0":
return None
return mx_dtype, 1
if qscheme == "per_block":
# Only the unpacked dtypes are accepted here: expanding a 2-D scale
# over a sub-byte packed weight has no checkpoint to validate against.
if mx_dtype not in OCP_MX_UNPACKED_DTYPES:
return None
block_size = list(weight_quant.get("block_size") or [])
if len(block_size) != 2 or block_size[1] != OCP_MX_BLOCK_SIZE:
return None
if weight_quant.get("scale_type") != "float8_e8m0fnu":
return None
if weight_quant.get("symmetric") is not True or weight_quant.get("is_dynamic"):
return None
return mx_dtype, block_size[0]
return None
class OCP_MX_Scheme(str, Enum):
w_mxfp4 = "w_mxfp4"
w_mxfp4_a_mxfp4 = "w_mxfp4_a_mxfp4"
@@ -208,6 +208,9 @@ kNvfp4DynamicGroupScale = ScaleDesc(FP8_DTYPE, False, GroupShape(1, 16))
kNvfp4Dynamic = QuantKey(
FP4_DTYPE, scale=kNvfp4DynamicGroupScale, scale2=kStaticTensorScale
)
kNvfp4DynamicToken = QuantKey(
FP4_DTYPE, scale=kNvfp4DynamicGroupScale, scale2=kDynamicTokenScale
)
kNvfp4StaticGroupScale = ScaleDesc(FP8_DTYPE, True, GroupShape(1, 16))
kNvfp4Static = QuantKey(
@@ -237,6 +237,18 @@ class ApplyRotaryEmb(CustomOp):
output = self._post_process(output, origin_shape, origin_dtype)
return output
def forward_xpu(
self,
x: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
) -> torch.Tensor:
import vllm._xpu_ops # noqa: F401 registers torch.ops.vllm.xpu_apply_rotary_emb
x, cos, sin, origin_shape, origin_dtype = self._pre_process(x, cos, sin)
output = torch.ops.vllm.xpu_apply_rotary_emb(x, cos, sin, self.is_neox_style)
return self._post_process(output, origin_shape, origin_dtype)
def forward_hip(
self,
x: torch.Tensor,
@@ -7,6 +7,7 @@ import torch
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import direct_register_custom_op
from .base import RotaryEmbeddingBase
from .yarn_scaling_rope import YaRNScalingRotaryEmbedding, yarn_get_mscale
@@ -19,6 +20,8 @@ def _triton_mrope_forward(
cos,
sin,
num_tokens,
q_token_stride,
k_token_stride,
n_qh: tl.constexpr,
n_kh: tl.constexpr,
hd: tl.constexpr,
@@ -38,9 +41,10 @@ def _triton_mrope_forward(
# and supports cos and sin cache with shape (3, num_tokens, rotary_dim // 2)
# instead of (3, bsz, seq_len, head_dim), also supports interleaved rotary
pid = tl.program_id(0)
# locate start address
q_ptr = q_ptr + pid * (n_qh * hd)
k_ptr = k_ptr + pid * (n_kh * hd)
# locate start address (int64: num_tokens * row_stride exceeds 2^31 for
# worst-case ViT forwards, e.g. MiniMax M3 packs ~768k patches/item)
q_ptr = q_ptr + pid.to(tl.int64) * q_token_stride
k_ptr = k_ptr + pid.to(tl.int64) * k_token_stride
# ####################################################################
# get the cos(mθ_{i...d/2}) and sin(mθ_{i...d/2}) for token position
@@ -185,6 +189,10 @@ def triton_mrope(
adjacent (GPT-J) layout.
"""
# The kernel indexes each token row through an explicit row stride and
# requires dense rows.
assert q.dim() == 2 and q.stride(-1) == 1
assert k.dim() == 2 and k.stride(-1) == 1
n_row, n_q_head_head_dim = q.shape
n_q_head = n_q_head_head_dim // head_size
n_kv_head = k.shape[1] // head_size
@@ -192,10 +200,6 @@ def triton_mrope(
pad_n_q_head = triton.next_power_of_2(n_q_head)
pad_n_kv_head = triton.next_power_of_2(n_kv_head)
# ensure tensors passed into the kernel are contiguous.
# It will be no-op if they are already contiguous
q = q.contiguous()
k = k.contiguous()
cos = cos.contiguous()
sin = sin.contiguous()
@@ -210,6 +214,8 @@ def triton_mrope(
cos,
sin,
n_row,
q.stride(0),
k.stride(0),
n_q_head,
n_kv_head,
head_size,
@@ -240,6 +246,62 @@ def apply_interleaved_rope(x: torch.Tensor, mrope_section: list[int]) -> torch.T
return torch.where(is_width, x[2], result)
def _mrope_apply(
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
cos_sin_cache: torch.Tensor,
head_size: int,
rotary_dim: int,
mrope_section_t: int,
mrope_section_h: int,
mrope_section_w: int,
mrope_interleaved: bool,
is_neox_style: bool,
) -> None:
cos_sin = cos_sin_cache[positions]
cos, sin = cos_sin.chunk(2, dim=-1)
query_out, key_out = triton_mrope(
query,
key,
cos,
sin,
[mrope_section_t, mrope_section_h, mrope_section_w],
head_size,
rotary_dim,
mrope_interleaved,
is_neox_style,
)
if query_out.data_ptr() != query.data_ptr():
query.copy_(query_out.view_as(query))
if key_out.data_ptr() != key.data_ptr():
key.copy_(key_out.view_as(key))
def _mrope_apply_fake(
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
cos_sin_cache: torch.Tensor,
head_size: int,
rotary_dim: int,
mrope_section_t: int,
mrope_section_h: int,
mrope_section_w: int,
mrope_interleaved: bool,
is_neox_style: bool,
) -> None:
return
direct_register_custom_op(
op_name="mrope",
op_func=_mrope_apply,
mutates_args=["query", "key"],
fake_impl=_mrope_apply_fake,
)
class MRotaryEmbedding(RotaryEmbeddingBase):
"""Rotary Embedding with Multimodal Sections."""
@@ -426,6 +488,35 @@ class MRotaryEmbedding(RotaryEmbeddingBase):
key = torch.cat((key_rot, key_pass), dim=-1).reshape(key_shape)
return query, key
def forward_hip(
self,
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor | None = None,
offsets: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
if positions.ndim == 2:
assert key is not None
assert self.mrope_section
query_shape = query.shape
key_shape = key.shape
cos_sin_cache = self._match_cos_sin_cache_dtype(query)
torch.ops.vllm.mrope(
positions,
query,
key,
cos_sin_cache,
self.head_size,
self.rotary_dim,
self.mrope_section[0],
self.mrope_section[1],
self.mrope_section[2],
self.mrope_interleaved,
self.is_neox_style,
)
return query.reshape(query_shape), key.reshape(key_shape)
return super().forward_hip(positions, query, key)
def forward_cpu(
self,
positions: torch.Tensor,
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import async_tensor_h2d
# num_tokens/num_grids vary per request (incl. the ==1 class) and grids_ptr
# is an offset slice of the packed H2D buffer, so its 16B alignment varies
# with grid count; without these the kernel recompiles mid-serving.
@triton.jit(
do_not_specialize=["num_tokens", "num_grids"],
do_not_specialize_on_alignment=["grids_ptr"],
)
def _vit_mrope_setup_kernel(
inv_freq_t_ptr,
inv_freq_h_ptr,
inv_freq_w_ptr,
cos_out_ptr,
sin_out_ptr,
cu_seqlens_ptr, # (G + 1,) int32 token boundaries per grid
grids_ptr, # (G, 3) int32: t, h, w per grid
num_tokens,
num_grids,
half_t: tl.constexpr,
half_h: tl.constexpr,
half_w: tl.constexpr,
spatial_merge: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Build triton_mrope's (3, N, half_rot) cos/sin t/h/w planes in one
launch: compute each token's (t, h, w) position arithmetically and the
rotation in fp32 from the per-axis inv_freq. Only each axis's mrope
section columns are written; the rest is left uninitialized (the
consumer's per-axis masked loads read only the section columns)."""
pid = tl.program_id(0)
tok = pid * BLOCK_N + tl.arange(0, BLOCK_N)
tok_mask = tok < num_tokens
# Grid (segment) index per token; cu_seqlens is nondecreasing.
seg = tl.zeros([BLOCK_N], dtype=tl.int32)
for g in range(num_grids):
end = tl.load(cu_seqlens_ptr + g + 1)
seg += (tok >= end).to(tl.int32)
seg_start = tl.load(cu_seqlens_ptr + seg, mask=tok_mask, other=0)
grid_h = tl.load(grids_ptr + seg * 3 + 1, mask=tok_mask, other=1)
grid_w = tl.load(grids_ptr + seg * 3 + 2, mask=tok_mask, other=1)
local = tok - seg_start
rem = local % (grid_h * grid_w)
tpos = local // (grid_h * grid_w)
# Within a frame tokens are ordered by spatial-merge block (bh, bw, mh,
# mw), matching the reference ViT position-id permute.
bh = rem // (spatial_merge * grid_w)
r = rem % (spatial_merge * grid_w)
bw = r // (spatial_merge * spatial_merge)
r2 = r % (spatial_merge * spatial_merge)
hpos = bh * spatial_merge + r2 // spatial_merge
wpos = bw * spatial_merge + r2 % spatial_merge
d = tl.arange(0, BLOCK_D)
half_rot = half_t + half_h + half_w
row = (tok * half_rot)[:, None] + d[None, :]
plane = num_tokens * half_rot
# Per-axis compute+store to cap live registers; the fp32 trig sequence
# wants few elements per thread (hence small BLOCK_N, many warps).
in_t = d < half_t
inv_t = tl.load(inv_freq_t_ptr + d, mask=in_t, other=0.0)
freq = tpos.to(tl.float32)[:, None] * inv_t[None, :]
mask = tok_mask[:, None] & in_t[None, :]
tl.store(cos_out_ptr + row, tl.cos(freq), mask=mask)
tl.store(sin_out_ptr + row, tl.sin(freq), mask=mask)
in_h = (d >= half_t) & (d < half_t + half_h)
inv_h = tl.load(inv_freq_h_ptr + d - half_t, mask=in_h, other=0.0)
freq = hpos.to(tl.float32)[:, None] * inv_h[None, :]
mask = tok_mask[:, None] & in_h[None, :]
tl.store(cos_out_ptr + plane + row, tl.cos(freq), mask=mask)
tl.store(sin_out_ptr + plane + row, tl.sin(freq), mask=mask)
in_w = (d >= half_t + half_h) & (d < half_rot)
inv_w = tl.load(inv_freq_w_ptr + d - half_t - half_h, mask=in_w, other=0.0)
freq = wpos.to(tl.float32)[:, None] * inv_w[None, :]
mask = tok_mask[:, None] & in_w[None, :]
tl.store(cos_out_ptr + 2 * plane + row, tl.cos(freq), mask=mask)
tl.store(sin_out_ptr + 2 * plane + row, tl.sin(freq), mask=mask)
def vit_mrope_setup(
inv_freq_t: torch.Tensor,
inv_freq_h: torch.Tensor,
inv_freq_w: torch.Tensor,
grid_thw: list[list[int]],
spatial_merge_size: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""(3, total_N, half_rot_dim) fp32 cos/sin t/h/w planes for triton_mrope.
One fused kernel: positions are computed arithmetically from the grids
and the rotation comes from the per-axis inv_freq, so there is no
cos/sin cache to size or grow.
Args:
inv_freq_t: t-axis inverse frequencies, (t_dim // 2,).
inv_freq_h: h-axis inverse frequencies, (h_dim // 2,).
inv_freq_w: w-axis inverse frequencies, (w_dim // 2,).
grid_thw: per-grid [t, h, w] patch counts (host metadata).
spatial_merge_size: spatial merge factor of the ViT.
"""
device = inv_freq_t.device
cu = [0]
for t, h, w in grid_thw:
cu.append(cu[-1] + t * h * w)
n = cu[-1]
g = len(grid_thw)
# grid_thw is per-request host metadata, so one H2D is unavoidable;
# pack cu_seqlens and grids into a single pinned async copy.
buf = async_tensor_h2d(
cu + [d for grid in grid_thw for d in grid], device=device, dtype=torch.int32
)
cu_seqlens = buf[: g + 1]
grids = buf[g + 1 :].view(g, 3)
half_t = inv_freq_t.numel()
half_h = inv_freq_h.numel()
half_w = inv_freq_w.numel()
half_rot = half_t + half_h + half_w
cos = torch.empty(3, n, half_rot, device=device, dtype=torch.float32)
sin = torch.empty(3, n, half_rot, device=device, dtype=torch.float32)
_vit_mrope_setup_kernel[(triton.cdiv(n, 32),)](
inv_freq_t,
inv_freq_h,
inv_freq_w,
cos,
sin,
cu_seqlens,
grids,
n,
g,
half_t=half_t,
half_h=half_h,
half_w=half_w,
spatial_merge=spatial_merge_size,
BLOCK_N=32,
BLOCK_D=triton.next_power_of_2(half_rot),
num_warps=8,
)
return cos, sin
+16 -5
View File
@@ -346,12 +346,14 @@ def rocm_unquantized_gemm_impl(
if use_skinny:
# The skinny kernels assume contiguous K elements. A shape-preserving
# reshape can retain a transposed activation's non-contiguous strides.
x_view = x.reshape(-1, x.size(-1)).contiguous()
if m > 8 and 0 < n <= 5:
# Note: Only build that view inside the branches that consume it.
if (m == 1 or m > 8) and 0 < n <= 5:
x_view = x.reshape(-1, x.size(-1)).contiguous()
cu_count = num_compute_units()
out = ops.wvSplitK(weight, x_view, cu_count, bias)
return out.reshape(*x.shape[:-1], weight.shape[0])
elif m % 4 == 0 and n == 1 and k <= 8192 and bias is None:
x_view = x.reshape(-1, x.size(-1)).contiguous()
out = ops.LLMM1(weight, x_view, 4)
return out.reshape(*x.shape[:-1], weight.shape[0])
@@ -513,7 +515,10 @@ def dispatch_cpu_unquantized_gemm(
)
)
if remove_weight:
layer.weight = torch.nn.Parameter(torch.empty(0), requires_grad=False)
layer.weight = torch.nn.Parameter(
torch.empty(0, dtype=dtype, device=layer.weight.device),
requires_grad=False,
)
logger.debug_once(
"CPU unquantized GEMM dispatch: using zentorch_linear_unary (prepacked=%s)",
is_prepacked,
@@ -539,7 +544,10 @@ def dispatch_cpu_unquantized_gemm(
bias,
)
if remove_weight:
layer.weight = torch.nn.Parameter(torch.empty(0), requires_grad=False)
layer.weight = torch.nn.Parameter(
torch.empty(0, dtype=dtype, device=layer.weight.device),
requires_grad=False,
)
logger.debug_once(
"CPU unquantized GEMM dispatch: using sgl-kernel weight_packed_linear"
)
@@ -554,7 +562,10 @@ def dispatch_cpu_unquantized_gemm(
handler = ops.create_onednn_mm(origin_weight.t(), 32)
layer.cpu_linear = lambda x, weight, bias: ops.onednn_mm(handler, x, bias)
if remove_weight:
layer.weight = torch.nn.Parameter(torch.empty(0), requires_grad=False)
layer.weight = torch.nn.Parameter(
torch.empty(0, dtype=dtype, device=layer.weight.device),
requires_grad=False,
)
logger.debug_once("CPU unquantized GEMM dispatch: using oneDNN onednn_mm")
return
except RuntimeError as e:
@@ -278,12 +278,12 @@ class VocabParallelEmbedding(PluggableLayer):
self.num_embeddings = num_embeddings
self.padding_size = padding_size
self.org_vocab_size = org_num_embeddings or num_embeddings
num_added_embeddings = num_embeddings - self.org_vocab_size
self.num_added_embeddings = num_embeddings - self.org_vocab_size
self.org_vocab_size_padded = pad_vocab_size(
self.org_vocab_size, self.padding_size
)
self.num_embeddings_padded = pad_vocab_size(
self.org_vocab_size_padded + num_added_embeddings, self.padding_size
self.org_vocab_size_padded + self.num_added_embeddings, self.padding_size
)
assert self.org_vocab_size_padded <= self.num_embeddings_padded
@@ -296,6 +296,18 @@ class VocabParallelEmbedding(PluggableLayer):
self.tp_size,
)
self.embedding_dim = embedding_dim
# Divide the weight matrix along the vocabulary dimension.
self.num_embeddings_per_partition = divide(
self.num_embeddings_padded, self.tp_size
)
# Quantization methods share the same weight factory as linear layers,
# so setup standard linear metadata.
self.input_size = self.input_size_per_partition = embedding_dim
self.output_size = self.num_embeddings_padded
self.output_size_per_partition = self.num_embeddings_per_partition
self.output_partition_sizes = [self.output_size_per_partition]
self.prefix = prefix
# Avoid overriding a preselected model-specific method with generic
# config-based dispatch.
@@ -322,11 +334,6 @@ class VocabParallelEmbedding(PluggableLayer):
if params_dtype is None:
params_dtype = torch.get_default_dtype()
self.params_dtype = params_dtype
# Divide the weight matrix along the vocabulary dimension.
self.num_added_embeddings = self.num_embeddings - self.org_vocab_size
self.num_embeddings_per_partition = divide(
self.num_embeddings_padded, self.tp_size
)
assert (
self.shard_indices.num_elements_padded == self.num_embeddings_per_partition
)
@@ -349,10 +356,10 @@ class VocabParallelEmbedding(PluggableLayer):
self.quant_method.create_weights(
self,
self.embedding_dim,
[self.num_embeddings_per_partition],
self.embedding_dim,
self.num_embeddings_padded,
self.input_size_per_partition,
self.output_partition_sizes,
self.input_size,
self.output_size,
params_dtype=params_dtype,
weight_loader=self.weight_loader,
)
@@ -600,6 +607,7 @@ class ParallelLMHead(VocabParallelEmbedding):
*,
disable_tp: bool = False,
):
self.has_bias = bias
super().__init__(
num_embeddings,
embedding_dim,
@@ -1,11 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import dataclasses
import glob
import os
import time
from collections.abc import Generator, Iterable
from typing import cast
from typing import TYPE_CHECKING, cast
import torch
from torch import nn
@@ -25,6 +27,7 @@ from vllm.model_executor.model_loader.weight_utils import (
fastsafetensors_weights_iterator,
filter_duplicate_safetensors_files,
filter_files_not_needed_for_inference,
filter_mm_encoder_only_safetensors_files,
get_quant_config,
instanttensor_weights_iterator,
maybe_download_from_modelscope,
@@ -32,11 +35,15 @@ from vllm.model_executor.model_loader.weight_utils import (
multi_thread_safetensors_weights_iterator,
np_cache_weights_iterator,
pt_weights_iterator,
resolve_mm_encoder_only_lm_prefixes,
safetensors_weights_iterator,
)
from vllm.tracing import instrument
from vllm.transformers_utils.repo_utils import list_filtered_repo_files
if TYPE_CHECKING:
from vllm.model_executor.models.utils import WeightsMapper
logger = init_logger(__name__)
@@ -74,6 +81,9 @@ class DefaultModelLoader(BaseModelLoader):
def __init__(self, load_config: LoadConfig):
super().__init__(load_config)
self.local_expert_ids: set[int] | None = None
# Set in load_weights when --mm-encoder-only; used to drop LM-only shards.
self._encoder_only_lm_prefixes: tuple[str, ...] | None = None
self._encoder_only_weights_mapper: WeightsMapper | None = None
extra_config = load_config.model_loader_extra_config
if not isinstance(extra_config, dict):
@@ -132,7 +142,7 @@ class DefaultModelLoader(BaseModelLoader):
revision: str | None,
fall_back_to_pt: bool,
allow_patterns_overrides: list[str] | None,
) -> tuple[str, list[str], bool]:
) -> tuple[str, list[str], bool, str]:
"""Prepare weights for the model.
If the model is not local, it will be downloaded."""
@@ -239,20 +249,40 @@ class DefaultModelLoader(BaseModelLoader):
f"Cannot find any model weights with `{model_name_or_path}`"
)
return hf_folder, hf_weights_files, use_safetensors
return hf_folder, hf_weights_files, use_safetensors, index_file
def _get_weights_iterator(
self, source: "Source"
self, source: Source
) -> Generator[tuple[str, torch.Tensor], None, None]:
"""Get an iterator for the model weights based on the load format."""
extra_config = self.load_config.model_loader_extra_config
hf_folder, hf_weights_files, use_safetensors = self._prepare_weights(
source.model_or_path,
source.subfolder,
source.revision,
source.fall_back_to_pt,
source.allow_patterns_overrides,
hf_folder, hf_weights_files, use_safetensors, index_file = (
self._prepare_weights(
source.model_or_path,
source.subfolder,
source.revision,
source.fall_back_to_pt,
source.allow_patterns_overrides,
)
)
if (
self._encoder_only_lm_prefixes is not None
and use_safetensors
and hf_weights_files
):
hf_weights_files = filter_mm_encoder_only_safetensors_files(
hf_weights_files,
hf_folder,
index_file,
self._encoder_only_lm_prefixes,
weights_mapper=self._encoder_only_weights_mapper,
)
if not hf_weights_files:
raise RuntimeError(
"mm-encoder-only shard filter removed all weight files for "
f"`{source.model_or_path}`; check language_model prefixes "
f"{self._encoder_only_lm_prefixes}"
)
if self.load_config.load_format == "npcache":
# Currently np_cache only support *.bin checkpoints
assert use_safetensors is False
@@ -348,6 +378,29 @@ class DefaultModelLoader(BaseModelLoader):
allow_patterns_overrides=None,
)
def _init_mm_encoder_only_weight_filter(
self, model: nn.Module, model_config: ModelConfig
) -> None:
"""Skip pure language-model safetensors shards under --mm-encoder-only."""
mm_config = model_config.multimodal_config
if mm_config is None or not mm_config.mm_encoder_only:
self._encoder_only_lm_prefixes = None
self._encoder_only_weights_mapper = None
return
# Derive from _language_model_names; fail-closed on shared HF roots
# (Molmo/Phi-4-MM/Muse). Qwen nested/flat keys classified via mapper.
weights_mapper = cast(
"WeightsMapper | None", getattr(model, "hf_to_vllm_mapper", None)
)
self._encoder_only_lm_prefixes = resolve_mm_encoder_only_lm_prefixes(
getattr(model, "_language_model_names", None),
weights_mapper=weights_mapper,
)
self._encoder_only_weights_mapper = (
weights_mapper if self._encoder_only_lm_prefixes is not None else None
)
def _init_ep_weight_filter(self, model_config: ModelConfig) -> None:
"""Compute local expert ids for EP weight filtering.
@@ -423,6 +476,7 @@ class DefaultModelLoader(BaseModelLoader):
self.load_config.safetensors_load_strategy = "torchao"
self._init_ep_weight_filter(model_config)
self._init_mm_encoder_only_weight_filter(model, model_config)
loaded_weights = model.load_weights(self.get_all_weights(model_config, model))
@@ -15,6 +15,7 @@ from vllm.model_executor.model_loader.weight_utils import (
download_weights_from_hf,
runai_safetensors_weights_iterator,
)
from vllm.transformers_utils.repo_utils import resolve_revision
from vllm.transformers_utils.runai_utils import is_runai_obj_uri, list_safetensors
@@ -87,6 +88,11 @@ class RunaiModelStreamerLoader(BaseModelLoader):
safetensors_pattern = "*.safetensors"
index_file = SAFE_WEIGHTS_INDEX_NAME
if not is_local and not is_object_storage_path:
# `model_weights` can point to another repo than the one `revision` was
# resolved for, which does not pin this one.
revision = resolve_revision(model_name_or_path, revision)
hf_folder = (
model_name_or_path
if (is_local or is_object_storage_path)
@@ -18,7 +18,7 @@ import regex as re
import torch
from torch import nn
from torch.utils._python_dispatch import TorchDispatchMode
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
import vllm.envs as envs
from vllm.config import ModelConfig, ParallelConfig, VllmConfig, set_current_vllm_config
@@ -173,7 +173,7 @@ class TensorizerConfig(MutableMapping):
deserialization_kwargs: dict[str, Any] | None = None
_extra_serialization_attrs: dict[str, Any] | None = field(init=False, default=None)
model_class: type[torch.nn.Module] | None = field(init=False, default=None)
hf_config: PretrainedConfig | None = field(init=False, default=None)
hf_config: PreTrainedConfig | None = field(init=False, default=None)
dtype: str | torch.dtype | None = field(init=False, default=None)
_is_sharded: bool = field(init=False, default=False)
_fields: ClassVar[tuple[str, ...]]
@@ -9,7 +9,7 @@ reloading from disk.
Launch one daemon per TP rank with a single command:
python -m vllm.model_executor.model_loader.weight_cache.daemon \\
vllm preload \\
--model /path/to/model --tensor-parallel-size 4
Engines then load from the daemons with:
@@ -17,8 +17,8 @@ Engines then load from the daemons with:
vllm serve /path/to/model --tensor-parallel-size 4 \\
--load-format ipc_cache
Only tensor and expert parallelism are supported; pipeline and data parallelism
are rejected at launch.
Tensor, expert and data parallelism are supported; pipeline parallelism is
rejected at launch.
For multi-node tensor parallelism, run one launcher per node with a shared
rendezvous so the global TP group forms across nodes (CUDA IPC handles are
@@ -27,12 +27,12 @@ node-local, so each node serves only its local GPUs' shards). Reuse the same
``--weight-cache-master-port`` distinct from the engine's ``--master-port``:
# node 0 (8 local GPUs)
python -m vllm.model_executor.model_loader.weight_cache.daemon \\
vllm preload \\
--model /path/to/model --tensor-parallel-size 16 \\
--nnodes 2 --node-rank 0 --master-addr 10.0.0.1 \\
--weight-cache-master-port 29600
# node 1 (8 local GPUs)
python -m vllm.model_executor.model_loader.weight_cache.daemon \\
vllm preload \\
--model /path/to/model --tensor-parallel-size 16 \\
--nnodes 2 --node-rank 1 --master-addr 10.0.0.1 \\
--weight-cache-master-port 29600
@@ -42,6 +42,32 @@ The global TP rank of local GPU ``i`` on node ``r`` is
assignment, so each engine worker maps its shard from the daemon on its own
node.
For data parallelism (e.g. a TP1 x DP16 x EP decode fleet) run one launcher per
node with the engine's DP placement flags. Local GPU ``i`` serves DP rank
``start_rank + i // tp_size`` and TP rank ``i % tp_size``, and all
``dp_size * tp_size`` daemons form one world group on
``--data-parallel-address``/``--weight-cache-master-port`` so the expert
shards are laid out exactly as in the engine:
# node r (4 local GPUs)
vllm preload \\
--model /path/to/model --tensor-parallel-size 1 --enable-expert-parallel \\
--data-parallel-size 16 --data-parallel-size-local 4 \\
--data-parallel-start-rank 4r --data-parallel-address 10.0.0.1 \\
--weight-cache-master-port 29600
Data parallelism also combines with multi-node tensor parallelism: pass both
flag sets (``--nnodes``/``--node-rank``/``--master-addr`` and the DP flags with
a reachable ``--data-parallel-address``). Each node then serves a contiguous
block of the ``dp_size * tp_size`` global ranks, e.g. TP8 x DP2 on 4 nodes:
# node r (4 local GPUs)
vllm preload \\
--model /path/to/model --tensor-parallel-size 8 --enable-expert-parallel \\
--nnodes 4 --node-rank r --master-addr 10.0.0.1 \\
--data-parallel-size 2 --data-parallel-address 10.0.0.1 \\
--weight-cache-master-port 29600
With MTP, EAGLE or EAGLE3 speculative decoding the launcher additionally
starts a draft daemon group that caches the draft model. It uses its own cache
key, Unix sockets (``*_draft.sock``) and rendezvous port
@@ -54,25 +80,21 @@ import contextlib
import fcntl
import multiprocessing
import os
import queue
import signal
import socket
import sys
from collections.abc import Callable
from itertools import product
import torch
from vllm.config import (
ParallelConfig,
VllmConfig,
replace,
set_current_vllm_config,
)
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
@@ -80,7 +102,6 @@ from vllm.model_executor.model_loader.weight_cache.protocol import (
TensorEntry,
WeightCacheKey,
WeightCacheUnavailableError,
check_ipc_platform_support,
check_ipc_quant_support,
ensure_private_socket_dir,
get_current_device_uuid,
@@ -95,9 +116,8 @@ from vllm.model_executor.model_loader.weight_cache.utils import (
is_draft_model_cacheable,
)
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
from vllm.v1.worker.workspace import init_workspace_manager
logger = init_logger("vllm.model_executor.model_loader.weight_cache.daemon")
@@ -158,7 +178,25 @@ class WeightCacheDaemon:
distributed_init_method: str,
socket_dir: str | None = None,
is_draft: bool = False,
dp_rank: int = 0,
):
parallel_config = vllm_config.parallel_config
if parallel_config.data_parallel_size > 1:
# The engine sets these on each DP rank's workers; the MoE/EP
# layers read them to place their expert shards.
tp_size = parallel_config.tensor_parallel_size
if parallel_config.nnodes > 1:
world_size = parallel_config.data_parallel_size * tp_size
local_world = world_size // parallel_config.nnodes
start_dp_rank = parallel_config.node_rank * local_world // tp_size
else:
start_dp_rank = parallel_config.data_parallel_rank
parallel_config = replace(
parallel_config,
data_parallel_rank=dp_rank,
data_parallel_rank_local=dp_rank - start_dp_rank,
)
vllm_config = replace(vllm_config, parallel_config=parallel_config)
self.vllm_config = vllm_config
# A draft daemon builds the draft with the target's VllmConfig, like
# the engine does; only the ModelConfig differs.
@@ -169,6 +207,11 @@ class WeightCacheDaemon:
else:
self.model_config = vllm_config.model_config
self.tp_rank = tp_rank
self.dp_rank = dp_rank
self.tp_size = parallel_config.tensor_parallel_size
self.dp_size = parallel_config.data_parallel_size
self.global_rank = dp_rank * self.tp_size + tp_rank
self.world_size = self.dp_size * self.tp_size
self.local_rank = local_rank
self.distributed_init_method = distributed_init_method
self.socket_dir = socket_dir
@@ -179,28 +222,32 @@ class WeightCacheDaemon:
# mutate hf_config.quantization_config.
self.cache_config = WeightCacheKey.from_model_config(
self.model_config,
tp_size=vllm_config.parallel_config.tensor_parallel_size,
tp_size=self.tp_size,
tp_rank=tp_rank,
dp_size=self.dp_size,
dp_rank=dp_rank,
is_draft=is_draft,
)
def load_model(self) -> None:
tp_size = self.cache_config.tp_size
torch.accelerator.set_device_index(self.local_rank)
# Outside the config context so the daemon keeps its own rendezvous
# instead of the engine's; model parallel groups (TP/DP/EP) are then
# carved out of this world group like in the engine.
init_distributed_environment(
world_size=tp_size,
rank=self.tp_rank,
world_size=self.world_size,
rank=self.global_rank,
distributed_init_method=self.distributed_init_method,
local_rank=self.local_rank,
backend=current_platform.dist_backend,
)
with set_current_vllm_config(self.vllm_config):
ensure_model_parallel_initialized(tp_size, 1)
ensure_model_parallel_initialized(self.tp_size, 1)
self.model = self.get_model()
logger.info(
"Weight cache %s daemon rank %d loaded model",
self.role,
self.tp_rank,
self.global_rank,
)
def get_model(self) -> torch.nn.Module:
@@ -219,6 +266,9 @@ class WeightCacheDaemon:
target_device = torch.device(
device_config.device if load_config.device is None else load_config.device
)
# Attention backends may take workspace at construction, like in the
# engine's worker init.
init_workspace_manager(target_device)
with set_default_torch_dtype(model_config.dtype):
with target_device:
model = loader.create_model(vllm_config, model_config)
@@ -255,7 +305,7 @@ class WeightCacheDaemon:
logger.info(
"Weight cache %s daemon rank %d serving on %s",
self.role,
self.tp_rank,
self.global_rank,
socket_path,
)
if ready_callback is not None:
@@ -347,7 +397,7 @@ class WeightCacheDaemon:
logger.info_once(
"Weight cache %s daemon rank %d sent %d tensors (+%d aliases) to engine",
self.role,
self.tp_rank,
self.global_rank,
len(entries),
len(aliases),
)
@@ -358,7 +408,7 @@ class WeightCacheDaemon:
logger.info(
"Weight cache %s daemon rank %d released cached weights",
self.role,
self.tp_rank,
self.global_rank,
)
send_msg(conn, {"status": "ok"})
@@ -371,6 +421,7 @@ def _run_daemon(
socket_dir: str | None,
ready_queue: "multiprocessing.Queue[tuple[str, int]]",
is_draft: bool = False,
dp_rank: int = 0,
) -> None:
daemon = WeightCacheDaemon(
vllm_config,
@@ -379,9 +430,34 @@ def _run_daemon(
distributed_init_method,
socket_dir,
is_draft,
dp_rank,
)
daemon.load_model()
daemon.serve_forever(ready_callback=lambda: ready_queue.put((daemon.role, tp_rank)))
daemon.serve_forever(
ready_callback=lambda: ready_queue.put((daemon.role, daemon.global_rank))
)
def plan_local_ranks(parallel_config: ParallelConfig) -> list[tuple[int, int, int]]:
"""``(local_rank, dp_rank, tp_rank)`` for every GPU this launcher serves.
Global ranks enumerate DP then TP: ``global = dp_rank * tp_size + tp_rank``.
With ``--nnodes`` the engine hands each node a contiguous block of global
ranks, so node ``r`` serves ``node_rank * local + i``; without it a
launcher's block starts at ``--data-parallel-start-rank * tp_size``.
"""
tp_size = parallel_config.tensor_parallel_size
world_size = parallel_config.data_parallel_size * tp_size
if parallel_config.nnodes > 1:
local_world_size = world_size // parallel_config.nnodes
base = parallel_config.node_rank * local_world_size
else:
local_world_size = parallel_config.data_parallel_size_local * tp_size
base = parallel_config.data_parallel_rank * tp_size
return [
(i, (base + i) // tp_size, (base + i) % tp_size)
for i in range(local_world_size)
]
def get_draft_daemon_config(vllm_config: VllmConfig) -> VllmConfig | None:
@@ -393,169 +469,30 @@ def get_draft_daemon_config(vllm_config: VllmConfig) -> VllmConfig | None:
def _reject_unsupported_parallelism(parallel_config: ParallelConfig) -> None:
"""Reject parallelism modes other than tensor/expert parallelism."""
unsupported = {
"pipeline parallelism": parallel_config.pipeline_parallel_size > 1,
"data parallelism": parallel_config.data_parallel_size > 1,
}
for name, enabled in unsupported.items():
if enabled:
raise ValueError(
f"The weight cache daemon only supports tensor and expert "
f"parallelism; {name} is not supported"
)
def main() -> None:
parser = FlexibleArgumentParser(
description="Launch weight cache daemons (one per TP rank)."
)
EngineArgs.add_cli_args(parser)
parser.add_argument(
"--weight-cache-socket-dir",
type=str,
default=None,
help="Directory for the daemon Unix sockets (default: tempdir).",
)
parser.add_argument(
"--weight-cache-master-port",
type=int,
default=None,
help="Rendezvous port for the daemon's own TP group. Must differ from "
"the engine's --master-port (the daemon holds its group open while "
"serving) and match across nodes. Required when --nnodes > 1; defaults "
"to a free port for single-node.",
)
parser.add_argument(
"--weight-cache-draft-master-port",
type=int,
default=None,
help="Rendezvous port for the MTP draft daemon group. Defaults to "
"--weight-cache-master-port + 1 for multi-node, or a free port for "
"single-node.",
)
args = parser.parse_args()
engine_args = EngineArgs.from_cli_args(args)
vllm_config = engine_args.create_engine_config()
if vllm_config.load_config.load_format == "ipc_cache":
"""Reject pipeline parallelism and placements the daemon cannot map."""
if parallel_config.pipeline_parallel_size > 1:
raise ValueError(
"The weight cache daemon itself must load from disk; use the "
"default --load-format"
"The weight cache daemon only supports tensor, expert and data "
"parallelism; pipeline parallelism is not supported"
)
# Config-only so it can fail before any model loading; the quant method
# check needs the created model and runs in get_daemon_model.
check_ipc_platform_support()
parallel_config = vllm_config.parallel_config
_reject_unsupported_parallelism(parallel_config)
dp_size = parallel_config.data_parallel_size
tp_size = parallel_config.tensor_parallel_size
nnodes = parallel_config.nnodes
node_rank = parallel_config.node_rank
local_world_size = tp_size // nnodes
# The daemon forms its own TP group and holds it open while serving, so it
# needs a rendezvous port distinct from the engine's --master-port. All
# nodes must agree on it; single-node can auto-pick a free port. The master
# address is reused from the engine's --master-addr (node_rank 0).
master_addr = parallel_config.master_addr
if nnodes > 1 and args.weight_cache_master_port is None:
raise ValueError("--weight-cache-master-port is required when --nnodes > 1")
master_port = args.weight_cache_master_port or get_open_port()
distributed_init_method = get_distributed_init_method(master_addr, master_port)
# (is_draft, vllm_config, rendezvous) per daemon group.
groups: list[tuple[bool, VllmConfig, str]] = [
(False, vllm_config, distributed_init_method)
]
draft_vllm_config = get_draft_daemon_config(vllm_config)
if draft_vllm_config is not None:
draft_master_port = args.weight_cache_draft_master_port or (
master_port + 1 if nnodes > 1 else get_open_port()
)
if draft_master_port == master_port:
if parallel_config.nnodes > 1:
world_size = dp_size * tp_size
if world_size % parallel_config.nnodes != 0:
raise ValueError(
"--weight-cache-draft-master-port must differ from "
"--weight-cache-master-port"
f"--nnodes ({parallel_config.nnodes}) must evenly divide the "
f"daemon world size ({world_size} = data-parallel-size "
f"{dp_size} x tensor-parallel-size {tp_size})"
)
groups.append(
(
True,
draft_vllm_config,
get_distributed_init_method(master_addr, draft_master_port),
)
)
ctx = multiprocessing.get_context("spawn")
ready_queue: multiprocessing.Queue[tuple[str, int]] = ctx.Queue()
# Global TP rank of local GPU i on this node; local index == device index.
global_ranks = [
node_rank * local_world_size + local_rank
for local_rank in range(local_world_size)
]
expected_ready = {
(format_daemon_role(is_draft), global_rank)
for (is_draft, _, _), global_rank in product(groups, global_ranks)
}
procs = [
ctx.Process(
target=_run_daemon,
args=(
global_rank,
local_rank,
config,
init_method,
args.weight_cache_socket_dir,
ready_queue,
is_draft,
),
name=f"vllm-weight-cache-{format_daemon_role(is_draft)}-{global_rank}",
)
for (is_draft, config, init_method), (local_rank, global_rank) in product(
groups, enumerate(global_ranks)
)
]
for proc in procs:
proc.start()
def _shutdown(signum, frame):
for proc in procs:
proc.terminate()
signal.signal(signal.SIGINT, _shutdown)
signal.signal(signal.SIGTERM, _shutdown)
ready: set[tuple[str, int]] = set()
while len(ready) < len(expected_ready):
try:
ready.add(ready_queue.get(timeout=1.0))
except queue.Empty:
dead = [p for p in procs if p.exitcode is not None]
if dead:
logger.error(
"Weight cache daemon rank(s) exited during startup "
"(exitcodes=%s); shutting down.",
[p.exitcode for p in dead],
)
for proc in procs:
proc.terminate()
for proc in procs:
proc.join()
sys.exit(max((p.exitcode or 0) for p in procs))
socket_dir_msg = args.weight_cache_socket_dir or "the default socket dir"
logger.info_once(
"===== Weight cache daemon READY: node %d/%d serving %d local rank(s) "
"x %d role(s) in %s =====",
node_rank,
nnodes,
local_world_size,
len(groups),
socket_dir_msg,
return
if dp_size == 1:
return
end_rank = (
parallel_config.data_parallel_rank + parallel_config.data_parallel_size_local
)
for proc in procs:
proc.join()
sys.exit(max(proc.exitcode or 0 for proc in procs))
if __name__ == "__main__":
main()
if end_rank > dp_size:
raise ValueError(
"--data-parallel-start-rank + --data-parallel-size-local "
f"({end_rank}) exceeds --data-parallel-size ({dp_size})"
)
@@ -5,6 +5,7 @@ daemon via CUDA IPC instead of loading from disk."""
import dataclasses
import socket
import time
from copy import copy
import torch
@@ -13,6 +14,7 @@ import torch.nn as nn
from vllm.config import ModelConfig, VllmConfig
from vllm.config.load import LoadConfig
from vllm.distributed import (
get_dp_group,
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
@@ -45,6 +47,7 @@ logger = init_logger(__name__)
_CONNECT_TIMEOUT_S = 5.0
_STATE_TIMEOUT_S = 300.0
_STARTUP_RETRY_INTERVAL_S = 0.5
class IpcModelLoader(BaseModelLoader):
@@ -285,14 +288,46 @@ class IpcModelLoader(BaseModelLoader):
_register(alias_name, obj, isinstance(obj, nn.Parameter))
def _fetch_entries(self, model_config: ModelConfig) -> WeightCacheState:
dp_group = get_dp_group()
cache_config = WeightCacheKey.from_model_config(
model_config,
tp_size=get_tensor_model_parallel_world_size(),
tp_rank=get_tensor_model_parallel_rank(),
dp_size=dp_group.world_size,
dp_rank=dp_group.rank_in_group,
is_draft=self.is_draft,
)
if not self.fallback:
return self._request_state_with_startup_wait(cache_config)
return self._request_state(cache_config)
def _request_state_with_startup_wait(
self, cache_config: WeightCacheKey
) -> WeightCacheState:
deadline = time.monotonic() + self.state_timeout_s
waiting_logged = False
while True:
try:
return self._request_state(cache_config)
except WeightCacheUnavailableError as e:
if time.monotonic() >= deadline:
raise WeightCacheUnavailableError(
"Weight cache daemon did not become ready within "
f"{self.state_timeout_s:.1f}s"
) from e
if not waiting_logged:
logger.info(
"Waiting up to %.1fs for the weight cache daemon to start",
self.state_timeout_s,
)
waiting_logged = True
time.sleep(
max(
0.0,
min(_STARTUP_RETRY_INTERVAL_S, deadline - time.monotonic()),
)
)
def _request_state(self, cache_config: WeightCacheKey) -> WeightCacheState:
with self._connect(self.state_timeout_s) as conn:
send_msg(conn, {"cmd": "get_state", "cache_config": cache_config})
@@ -291,6 +291,8 @@ class WeightCacheKey:
vllm_version: str
is_draft: bool = False
"""Daemon group the weights come from; False is the target model."""
dp_size: int = 1
dp_rank: int = 0
@classmethod
def from_model_config(
@@ -300,6 +302,8 @@ class WeightCacheKey:
tp_rank: int,
*,
is_draft: bool = False,
dp_size: int = 1,
dp_rank: int = 0,
) -> "WeightCacheKey":
"""Build the fingerprint for a model configuration.
@@ -327,6 +331,8 @@ class WeightCacheKey:
revision=model_config.revision,
vllm_version=vllm.version.__version__,
is_draft=is_draft,
dp_size=dp_size,
dp_rank=dp_rank,
)
def mismatched_fields(self, other: "WeightCacheKey") -> list[str]:
+218 -78
View File
@@ -12,18 +12,17 @@ import os
import tempfile
import threading
import time
from collections import defaultdict
from collections.abc import Callable, Generator, Iterable
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from pathlib import Path
from typing import IO, Any
from typing import IO, TYPE_CHECKING, Any
import filelock
import huggingface_hub.constants
import numpy as np
import regex as re
import torch
from safetensors.torch import load, load_file, safe_open, save_file
from safetensors.torch import load, load_file, safe_open
from tqdm.auto import tqdm
from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
@@ -62,6 +61,9 @@ except ImportError:
from vllm.model_executor.layers.quantization.torchao import torchao_version_at_least
if TYPE_CHECKING:
from vllm.model_executor.models.utils import WeightsMapper
logger = init_logger(__name__)
# use system-level temp directory for file locks, so that multiple users
@@ -186,56 +188,6 @@ def maybe_download_from_modelscope(
return None
def _shared_pointers(tensors):
ptrs = defaultdict(list)
for k, v in tensors.items():
ptrs[v.data_ptr()].append(k)
failing = []
for _, names in ptrs.items():
if len(names) > 1:
failing.append(names)
return failing
def convert_bin_to_safetensor_file(
pt_filename: str,
sf_filename: str,
) -> None:
loaded = torch.load(pt_filename, map_location="cpu", weights_only=True)
if "state_dict" in loaded:
loaded = loaded["state_dict"]
shared = _shared_pointers(loaded)
for shared_weights in shared:
for name in shared_weights[1:]:
loaded.pop(name)
# For tensors to be contiguous
loaded = {k: v.contiguous() for k, v in loaded.items()}
dirname = os.path.dirname(sf_filename)
os.makedirs(dirname, exist_ok=True)
save_file(loaded, sf_filename, metadata={"format": "pt"})
# check file size
sf_size = os.stat(sf_filename).st_size
pt_size = os.stat(pt_filename).st_size
if (sf_size - pt_size) / pt_size > 0.01:
raise RuntimeError(
f"""The file size different is more than 1%:
- {sf_filename}: {sf_size}
- {pt_filename}: {pt_size}
"""
)
# check if the tensors are the same
reloaded = load_file(sf_filename)
for k in loaded:
pt_tensor = loaded[k]
sf_tensor = reloaded[k]
if not torch.equal(pt_tensor, sf_tensor):
raise RuntimeError(f"The output tensors do not match for key {k}")
# TODO(woosuk): Move this to other place.
def get_quant_config(
model_config: ModelConfig, load_config: LoadConfig
@@ -243,7 +195,11 @@ def get_quant_config(
if model_config.quantization is None:
raise ValueError("Model quantization method is not specified in the config.")
quant_cls = get_quantization_config(model_config.quantization)
from vllm.config.quantization import _ONLINE_SHORTHANDS, QuantizationConfigArgs
from vllm.config.quantization import (
_ONLINE_SHORTHANDS,
QuantizationConfigArgs,
resolve_quantization_config,
)
from vllm.model_executor.layers.quantization.online.base import (
OnlineQuantizationConfig,
)
@@ -383,6 +339,14 @@ def get_quant_config(
# If the quantization config is not found, use the default config.
if not possible_config_filenames:
if model_config.quantization == "fp8":
logger.warning_once(
"--quantization fp8 is deprecated for online quantization; "
"use --quantization fp8_per_tensor instead."
)
fp8_args = resolve_quantization_config("fp8_per_tensor", online_args)
assert fp8_args is not None
return OnlineQuantizationConfig(args=fp8_args)
if model_config.quantization in _ONLINE_SHORTHANDS:
args = online_args or _ONLINE_SHORTHANDS[model_config.quantization]
assert isinstance(args, QuantizationConfigArgs)
@@ -656,6 +620,171 @@ def filter_files_not_needed_for_inference(hf_weights_files: list[str]) -> list[s
return hf_weights_files
def _normalize_module_prefixes(
language_model_names: Iterable[str] | None,
) -> tuple[str, ...]:
names = tuple(language_model_names or ())
return tuple(n if n.endswith(".") else f"{n}." for n in names)
def _mapped_weight_name(weights_mapper: "WeightsMapper | None", key: str) -> str | None:
"""Apply ``WeightsMapper.map_name`` when present; else identity."""
if weights_mapper is None:
return key
return weights_mapper.map_name(key)
def _hf_prefix_maps_to_lm(
new_name: str | None, lm_module_prefixes: tuple[str, ...]
) -> bool:
if not new_name:
return False
new_p = new_name if new_name.endswith(".") else f"{new_name}."
return any(new_p.startswith(p) or p.startswith(new_p) for p in lm_module_prefixes)
def _shared_hf_root_module_prefixes(
lm_module_prefixes: tuple[str, ...],
weights_mapper: "WeightsMapper | None",
) -> tuple[str, ...]:
"""Module prefixes that are also an HF root for non-LM weights.
E.g. Molmo/Phi-4-MM/Muse mark LM as ``model`` while vision HF keys stay
under ``model.vision_*`` / ``model.embed_tokens_extend.*``. Detected via
``WeightsMapper.orig_to_new_prefix`` (no hard-coded name list).
"""
if weights_mapper is None:
return ()
mapping = weights_mapper.orig_to_new_prefix
if not mapping:
return ()
non_lm_origs: list[str] = []
for orig, new in mapping.items():
orig_p = orig if orig.endswith(".") else f"{orig}."
if not _hf_prefix_maps_to_lm(new, lm_module_prefixes):
non_lm_origs.append(orig_p)
if not non_lm_origs:
return ()
shared = [
p
for p in lm_module_prefixes
if any(orig.startswith(p) for orig in non_lm_origs)
]
return tuple(shared)
def resolve_mm_encoder_only_lm_prefixes(
language_model_names: Iterable[str] | None,
*,
weights_mapper: "WeightsMapper | None" = None,
) -> tuple[str, ...] | None:
"""Resolve vLLM LM *module* prefixes for ``--mm-encoder-only`` shard skip.
Prefixes come from ``_language_model_names``. Classification of HF index
keys is done later via optional ``weights_mapper`` (see
``filter_mm_encoder_only_safetensors_files``), so this helper does **not**
hard-code Qwen/HF nest lists.
Returns ``None`` (leave the safetensors file list unchanged) when
``_language_model_names`` is empty/missing, or when a module prefix is a
shared HF checkpoint root for both LM and non-LM weights — fail-closed so
Molmo / Phi-4-MM / Muse cannot under-load the encoder.
"""
prefixes = _normalize_module_prefixes(language_model_names)
if not prefixes:
return None
shared = _shared_hf_root_module_prefixes(prefixes, weights_mapper)
if shared:
logger.warning_once(
"mm-encoder-only whole-shard filter not applied: LM module "
"prefix(es) %s share an HF checkpoint root with non-LM weights "
"(via WeightsMapper). Encoder-only load keeps the full "
"safetensors file list; finer HF prefixes or key-level "
"filtering can enable skip later.",
shared,
)
return None
return prefixes
def filter_mm_encoder_only_safetensors_files(
hf_weights_files: list[str],
hf_folder: str,
index_file: str,
language_model_prefixes: Iterable[str],
*,
weights_mapper: "WeightsMapper | None" = None,
) -> list[str]:
"""Drop safetensors shards that only contain language-model weights.
Used with ``--mm-encoder-only`` so Encoder-only EPD instances avoid reading
pure LM shards from disk/DRAM.
Each HF index key is classified by mapping through ``weights_mapper`` (when
provided) and testing the *vLLM* name against ``language_model_prefixes``.
Without a mapper, HF names are compared directly (identity checkpoint
layout, e.g. Kimi ``language_model.*``).
A shard is kept if it contains any non-LM key. Without an index file,
returns ``hf_weights_files`` unchanged.
"""
prefixes = tuple(language_model_prefixes)
if not prefixes:
return hf_weights_files
index_path = os.path.join(hf_folder, index_file)
if not os.path.isfile(index_path):
logger.warning_once(
"mm-encoder-only shard filter skipped: index file %s not found",
index_path,
)
return hf_weights_files
with open(index_path) as f:
weight_map: dict[str, str] = json.load(f)["weight_map"]
keys_by_file: dict[str, list[str]] = {}
for weight_name, weight_file in weight_map.items():
keys_by_file.setdefault(weight_file, []).append(weight_name)
def _is_lm_key(key: str) -> bool:
mapped = _mapped_weight_name(weights_mapper, key)
if mapped is None:
return False
return any(mapped.startswith(p) for p in prefixes)
def _is_lm_only(weight_file: str) -> bool:
keys = keys_by_file.get(weight_file)
if not keys:
# Not listed in the index (e.g. extra matched glob) — keep.
return False
return all(_is_lm_key(key) for key in keys)
kept: list[str] = []
skipped = 0
for path in hf_weights_files:
rel = os.path.relpath(path, hf_folder)
# Index weight_map values are usually basenames; tolerate either form.
basename = os.path.basename(path)
if _is_lm_only(rel) or _is_lm_only(basename):
skipped += 1
continue
kept.append(path)
if skipped:
logger.info_once(
"mm-encoder-only: skipped %d/%d safetensors shard(s) that only "
"contain language-model weights (prefixes=%s)",
skipped,
skipped + len(kept),
prefixes,
)
return kept
# explicitly use pure text format, with a newline at the end
# this makes it impossible to see the animation in the progress bar
# but will avoid messing up with ray or multiprocessing, which wraps
@@ -715,6 +844,40 @@ def np_cache_weights_iterator(
yield name, torch.from_numpy(param)
def drop_checkpoint_cache(
model_name_or_path: str,
revision: str | None = None,
cache_dir: str | None = None,
) -> None:
checkpoint_dir: Path | None = None
if os.path.isdir(model_name_or_path):
checkpoint_dir = Path(model_name_or_path)
else:
with suppress(OSError, ValueError):
checkpoint_dir = Path(
hf_api().snapshot_download(
model_name_or_path,
revision=revision,
cache_dir=cache_dir,
local_files_only=True,
)
)
if checkpoint_dir is None:
logger.info_once(
"No local checkpoint found for %s; skipping page-cache eviction",
model_name_or_path,
)
return
for path in checkpoint_dir.glob("*.safetensors"):
try:
with path.open("rb") as file:
os.posix_fadvise(file.fileno(), 0, 0, os.POSIX_FADV_DONTNEED)
except OSError as exc:
logger.warning(
"Could not release checkpoint page cache for %s: %s", path, exc
)
def _get_checkpoints_size_bytes(files: list[str]) -> int:
"""Return the total size of the checkpoint files in bytes."""
if not files:
@@ -1313,29 +1476,6 @@ def composed_weight_loader(
return composed_loader
def initialize_dummy_weights(
model: torch.nn.Module,
model_config: ModelConfig,
low: float = -1e-3,
high: float = 1e-3,
seed: int = 1234,
) -> None:
"""Initialize model weights with random values.
The model weights must be randomly initialized for accurate performance
measurements. Additionally, the model weights should not cause NaNs in the
forward pass. We empirically found that initializing the weights with
values between -1e-3 and 1e-3 works well for most models.
We use per-parameter random seed, so that dummy weights are consistent,
even if the model is partitioned across multiple devices. When the seed
is fixed, the random values generated by this function only depends on
the parameter's number of elements and its data type.
"""
for param in model.state_dict().values():
initialize_single_dummy_weight(param, low, high, seed)
@torch.no_grad()
def initialize_single_dummy_weight(
param: torch.Tensor,
+2 -3
View File
@@ -44,6 +44,7 @@ from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.fused_moe.utils import (
@@ -128,11 +129,9 @@ class AXK1MoE(nn.Module):
"Only silu is supported for now."
)
self.gate = ReplicatedLinear(
self.gate = GateLinear(
config.hidden_size,
config.n_routed_experts,
bias=False,
quant_config=None,
prefix=f"{prefix}.gate",
)
if config.topk_method == "noaux_tc":
+3 -3
View File
@@ -284,7 +284,7 @@ def as_embedding_model(cls: type[_T]) -> type[_T]:
def _resolve_num_labels(hf_config: Any, text_config: Any) -> int:
"""Resolve the label count for a sequence classification head.
``PretrainedConfig.num_labels`` is derived from ``id2label``, which always
``PreTrainedConfig.num_labels`` is derived from ``id2label``, which always
carries a default of two entries. Composite configs (such as multimodal
checkpoints) declare their label space on the top-level config, so reading
``num_labels`` from ``get_text_config()`` silently returns that default and
@@ -297,9 +297,9 @@ def _resolve_num_labels(hf_config: Any, text_config: Any) -> int:
if text_config is hf_config:
return hf_config.num_labels
from transformers import PretrainedConfig
from transformers import PreTrainedConfig
if hf_config.num_labels != PretrainedConfig().num_labels:
if hf_config.num_labels != PreTrainedConfig().num_labels:
return hf_config.num_labels
return text_config.num_labels
+6 -4
View File
@@ -19,6 +19,7 @@ from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
MoERunner,
)
from vllm.model_executor.layers.layernorm import RMSNorm
@@ -82,11 +83,12 @@ class AfmoeMoE(nn.Module):
)
# Router gate
self.gate = nn.Linear(
self.gate = GateLinear(
config.hidden_size,
config.num_experts,
bias=False,
dtype=torch.float32,
out_dtype=torch.float32,
params_dtype=torch.float32,
prefix=f"{prefix}.gate",
)
self.expert_bias = nn.Parameter(
torch.empty(config.num_experts, dtype=torch.float32)
@@ -140,7 +142,7 @@ class AfmoeMoE(nn.Module):
num_tokens, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
router_logits = self.gate(hidden_states.to(dtype=torch.float32))
router_logits, _ = self.gate(hidden_states)
final_hidden_states = self.experts(
hidden_states=hidden_states, router_logits=router_logits
+16 -5
View File
@@ -22,7 +22,7 @@ from typing import Annotated, Any, Literal, TypeAlias
import torch
import torch.nn as nn
from transformers import BatchFeature, PretrainedConfig
from transformers import BatchFeature, PreTrainedConfig
from transformers.models.audioflamingo3 import (
AudioFlamingo3Config,
AudioFlamingo3Processor,
@@ -118,7 +118,7 @@ AudioFlamingo3Inputs: TypeAlias = (
class AudioFlamingo3Encoder(Qwen2AudioEncoder):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
):
super().__init__(config)
self.avg_pooler = nn.AvgPool1d(kernel_size=2, stride=2)
@@ -161,7 +161,7 @@ class AudioFlamingo3Encoder(Qwen2AudioEncoder):
class AudioFlamingo3MultiModalProjector(nn.Module):
def __init__(self, config: PretrainedConfig):
def __init__(self, config: PreTrainedConfig):
super().__init__()
self.linear_1 = nn.Linear(
config.audio_config.hidden_size,
@@ -197,6 +197,7 @@ class AudioFlamingo3ProcessingInfo(BaseProcessingInfo):
return AudioFlamingo3MultiModalDataParser(
target_sr=feature_extractor.sampling_rate,
expected_hidden_size=self._get_expected_hidden_size(),
allow_missing_mm_embeddings=self.allow_missing_mm_embeddings,
)
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
@@ -237,6 +238,7 @@ def _audioflamingo3_field_config(hf_inputs: Mapping[str, torch.Tensor]):
if chunk_counts is not None:
return dict(
audio_embeds=MultiModalFieldConfig.batched("audio"),
audio_num_tokens=MultiModalFieldConfig.batched("audio", keep_on_cpu=True),
input_features=MultiModalFieldConfig.flat_from_sizes(
"audio", chunk_counts, dim=0
),
@@ -247,6 +249,7 @@ def _audioflamingo3_field_config(hf_inputs: Mapping[str, torch.Tensor]):
)
return dict(
audio_embeds=MultiModalFieldConfig.batched("audio"),
audio_num_tokens=MultiModalFieldConfig.batched("audio", keep_on_cpu=True),
input_features=MultiModalFieldConfig.batched("audio"),
feature_attention_mask=MultiModalFieldConfig.batched("audio"),
chunk_counts=MultiModalFieldConfig.batched("audio", keep_on_cpu=True),
@@ -354,11 +357,15 @@ def _count_audio_tokens_from_mask(
class AudioFlamingo3MultiModalDataParser(MultiModalDataParser):
embedding_fields = {
"audio": {"audio_embeds": "values", "audio_num_tokens": "metadata"},
}
def _parse_audio_data(
self,
data: dict[str, torch.Tensor] | ModalityData[Any],
) -> ModalityDataItems[Any, Any] | None:
if isinstance(data, dict):
if isinstance(data, dict) and "audio_num_tokens" not in data:
return DictEmbeddingItems(
data,
modality="audio",
@@ -442,7 +449,11 @@ class AudioFlamingo3MultiModalProcessor(
chunk_counts = out_mm_data.get("chunk_counts")
def get_replacement_audioflamingo3(item_idx: int):
if feature_attention_mask is not None:
if "audio_num_tokens" in out_mm_data:
counts = out_mm_data["audio_num_tokens"]
assert isinstance(counts, torch.Tensor)
num_features = int(counts[item_idx])
elif feature_attention_mask is not None:
num_features = _count_audio_tokens_from_mask(
feature_attention_mask,
chunk_counts,
+14 -10
View File
@@ -30,7 +30,7 @@ from itertools import islice
import torch
import torch.nn.functional as F
from torch import nn
from transformers.configuration_utils import PretrainedConfig
from transformers.configuration_utils import PreTrainedConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
@@ -41,7 +41,10 @@ from vllm.distributed import (
)
from vllm.model_executor.layers.activation import SiluAndMul
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import FusedMoEFactory
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
@@ -71,7 +74,7 @@ from .utils import (
class BailingAttention(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
reduce_results: bool = True,
@@ -180,7 +183,7 @@ class BailingMLP(nn.Module):
def __init__(
self,
intermediate_size: int,
config: PretrainedConfig,
config: PreTrainedConfig,
quant_config: QuantizationConfig | None = None,
reduce_results: bool = True,
prefix: str = "",
@@ -214,7 +217,7 @@ class BailingMoE(nn.Module):
def __init__(
self,
intermediate_size: int,
config: PretrainedConfig,
config: PreTrainedConfig,
quant_config: QuantizationConfig | None = None,
reduce_results: bool | None = True,
prefix: str = "",
@@ -243,11 +246,12 @@ class BailingMoE(nn.Module):
else:
self.router_dtype = torch.bfloat16
self.gate = nn.Linear(
self.gate = GateLinear(
self.hidden_size,
self.num_experts,
bias=False,
dtype=self.router_dtype,
out_dtype=self.router_dtype,
params_dtype=self.router_dtype,
prefix=f"{prefix}.gate",
)
if getattr(config, "moe_router_enable_expert_bias", False):
@@ -312,7 +316,7 @@ class BailingMoE(nn.Module):
hidden_states = hidden_states.view(-1, hidden_size)
# router_logits: (num_tokens, n_experts)
router_logits = self.gate(hidden_states.to(self.router_dtype))
router_logits, _ = self.gate(hidden_states)
router_logits = router_logits.to(hidden_states.dtype)
final_hidden_states = self.experts(
@@ -324,7 +328,7 @@ class BailingMoE(nn.Module):
class BailingMoeBlock(nn.Module):
def __init__(
self,
config: PretrainedConfig,
config: PreTrainedConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",

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