Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 48 additions & 9 deletions tests/v1/kv_connector/unit/test_nixl_desc_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,20 +168,30 @@ def _make_packed_mla_view_worker(
backend_names=("FLASHMLA",),
indexer_layer=None,
worker_cls=NixlPushConnectorWorker,
use_mla=True,
):
"""Register real strided views; only NIXL and distributed runtime are fake."""
block_size = 16
raw = torch.zeros(num_blocks * block_stride, dtype=torch.int8)
tensors, groups, caches = [], [], {}
for name, (offset, page_size) in layouts.items():
spec = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=page_size // block_size,
dtype=torch.uint8,
cache_role=SparseCacheRole.INDEXER
if name == indexer_layer
else SparseCacheRole.SPARSE,
spec = (
MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=page_size // block_size,
dtype=torch.uint8,
cache_role=SparseCacheRole.INDEXER
if name == indexer_layer
else SparseCacheRole.SPARSE,
)
if use_mla
else AttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=page_size // (2 * block_size),
dtype=torch.uint8,
)
)
tensor = KVCacheTensor(
size=raw.nbytes,
Expand Down Expand Up @@ -229,7 +239,7 @@ def _make_packed_mla_view_worker(
"producer" if pp_size > 1 else "consumer",
KVCacheConfig(num_blocks, tensors, groups),
)
worker.use_mla = True
worker.use_mla = use_mla
worker.register_kv_caches(caches)
return worker, raw

Expand Down Expand Up @@ -257,6 +267,35 @@ def test_packed_mla_pp1_transfers_whole_rows(num_layers, worker_cls):
assert metadata.packed_member_layouts == layouts


@pytest.mark.cpu_test
@pytest.mark.parametrize(
"worker_cls", [NixlPullConnectorWorker, NixlPushConnectorWorker]
)
def test_packed_head_sharded_pp1_transfers_whole_rows(worker_cls):
# Non-MLA BLHNC: a row holds this rank's heads of every layer, so at equal
# P/D TP a block is still one descriptor, not one per layer.
layouts = {"L0": (0, 128), "L1": (128, 128)}
worker, raw = _make_packed_mla_view_worker(
layouts, 256, worker_cls=worker_cls, use_mla=False
)
assert worker.num_regions == 1
assert worker.num_descs == 4
assert worker.src_blocks_data.tolist() == [[raw.data_ptr(), 256, 0, 256, 4]]
assert worker.region_members == [list(layouts)]


@pytest.mark.cpu_test
def test_packed_head_sharded_rows_reject_tp_mismatch():
producer, _ = _make_packed_mla_view_worker({"L0": (0, 128)}, 128, use_mla=False)
consumer, _ = _make_packed_mla_view_worker({"L0": (0, 128)}, 128, use_mla=False)
metadata = msgspec.msgpack.decode(
producer.xfer_handshake_metadata.agent_metadata_bytes, type=NixlAgentMetadata
)
metadata.engine_id = "remote"
with pytest.raises(RuntimeError, match="need the same TP"):
consumer.add_remote_agent(metadata, remote_tp_size=2)


@pytest.mark.cpu_test
def test_per_layer_peer_addresses_pages_inside_packed_rows():
# E.g. a HiSparse decoder reading a BLHNC prefiller's whole-row region.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1764,6 +1764,14 @@ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
and self.use_mla
and not self._has_mamba
)
# A non-MLA packed row holds this rank's heads of every layer, so it
# may transfer whole when P and D shard heads alike (equal TP, checked
# at handshake).
packed_head_sharded_storage = (
_share_storage_and_block_stride(list(xfer_buffers.values()))
and not self.use_mla
and not self._has_mamba
)
if split_packed_rows and any(
not isinstance(spec, MLAAttentionSpec)
for spec in self._layer_specs.values()
Expand Down Expand Up @@ -1884,13 +1892,16 @@ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
and cache[0].is_contiguous()
and cache[0].nbytes == physical_page_size
)
# Block-outermost MLA: one block row holds every layer's page.
# Block-outermost: one block row holds every layer's page (in an
# MLA model, only its MLA layers' pages travel as rows).
packed_mla = (
self._has_packed_cache
and not self._has_mamba
and replicated_shared_storage
and (
(replicated_shared_storage and is_mla_region)
or packed_head_sharded_storage
)
and storage_is_block_major
and is_mla_region
)
if not self._has_packed_cache and _splits_kernel_rows(
layer_name, cache, num_blocks, physical_page_size
Expand Down Expand Up @@ -3167,6 +3178,13 @@ def _validate_remote_agent_handshake(
f"(local TP {self.transfer_topo.tp_size}, remote TP "
f"{remote_tp_size}). Use matching TP sizes on prefill and decode."
)
# A whole row holds this rank's heads of every layer: no re-sharding.
if self._packed_member_layouts and not self.use_mla and tp_ratio != 1:
raise RuntimeError(
"Packed KV rows of a non-MLA model need the same TP on prefill "
f"and decode (local TP {self.transfer_topo.tp_size}, remote TP "
f"{remote_tp_size}). Use LBHNC for heterogeneous TP."
)

# Per-region block_len validation enforcing the P/D invariant.
# REPLICATE regions (MLA, or a whole-model MLA / replicated-KV transfer)
Expand Down
11 changes: 11 additions & 0 deletions vllm/models/minimax_m3/amd/glue/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,17 @@ def _refusals(model, vllm_config) -> list[str]:
layer.block_sparse_moe.shared_experts is None for layer in layers
):
reasons.append("no MoE layers or fused shared experts")
from vllm.models.minimax_m3.amd.nvfp4_experts import MiniMaxM3NvFp4HipMoEMethod

experts = [layer.block_sparse_moe.experts for layer in layers]
if any(
isinstance(
getattr(getattr(e, "routed_experts", e), "quant_method", None),
MiniMaxM3NvFp4HipMoEMethod,
)
for e in experts
):
reasons.append("NVFP4 routed experts (AITER moe_nvfp4, not A16W4)")
return reasons

def __init__(self, model, vllm_config) -> None:
Expand Down
91 changes: 54 additions & 37 deletions vllm/models/minimax_m3/amd/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""

from collections.abc import Iterable
from contextlib import nullcontext
from functools import partial
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -76,6 +77,9 @@
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.quantization.modelopt import ModelOptMxFp8Config
from vllm.model_executor.layers.quantization.online.requantization import (
skip_checkpoint_backend_selection,
)
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
MXFP8_BLOCK_SIZE,
MXFP8_SCALE_DTYPE,
Expand Down Expand Up @@ -120,6 +124,10 @@
MiniMaxM3IndexerRocmNvfp4Impl,
init_rocm_nvfp4_indexer_decode_cp,
)
from vllm.models.minimax_m3.amd.nvfp4_experts import (
keep_nvfp4_experts,
nvfp4_moe_supported,
)
from vllm.models.minimax_m3.amd.ops import (
gemma_fused_add_rmsnorm,
gemma_fused_add_rmsnorm_mxfp8,
Expand Down Expand Up @@ -465,10 +473,11 @@ def __init__(
)

# MiniMax-M3.1 like checkpoints (`quant_method: mxfp8`, `moe_quant_algo:
# NVFP4`) have no native NVFP4 MoE backend on ROCm: the routed experts must be
# NVFP4`): without an online MoE config the routed experts run natively on
# the AITER NVFP4 MoE kernels (gfx950 only); otherwise they must be
# re-quantized online.
experts_prefix = f"{prefix}.experts"
if (
keep_nvfp4 = (
isinstance(quant_config, ModelOptMxFp8Config)
and quant_config.moe_quant_algo == "NVFP4"
and not quant_config.is_layer_excluded(experts_prefix)
Expand All @@ -479,13 +488,14 @@ def __init__(
)
is None
)
):
)
if keep_nvfp4 and not nvfp4_moe_supported():
raise NotImplementedError(
"This MiniMax model with NVFP4 MoE experts "
"(`moe_quant_algo: NVFP4`, `moe_quant_format: nvfp4-pack-quantized`) "
"is not supported on ROCm. Please use `--quantization-config.moe "
"mxfp8` (or `--quantization-config.moe mxfp4`) to re-quantize the "
"MoE to MXFP8 (or MXFP4) when loading to serve on ROCm."
"needs gfx950 and AITER `moe_nvfp4` on ROCm. Otherwise use "
"`--quantization-config.moe mxfp8` (or `--quantization-config.moe "
"mxfp4`) to re-quantize the MoE to MXFP8 (or MXFP4) when loading."
)

self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0)
Expand Down Expand Up @@ -545,37 +555,44 @@ def __init__(
# always-on shared expert; aiter applies the routed scaling internally.
# Every other path (vLLM top-k bias router, or no fusion) applies the
# routed scaling to the MoE output here.
self.experts = FusedMoEFactory(
num_experts=config.num_local_experts,
top_k=config.num_experts_per_tok,
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
intermediate_pad=0,
scoring_func="sigmoid",
e_score_correction_bias=self.e_score_correction_bias,
renormalize=True,
use_grouped_topk=self.use_aiter_moe_fse,
num_expert_group=1 if self.use_aiter_moe_fse else None,
topk_group=1 if self.use_aiter_moe_fse else None,
activation="swigluoai_uninterleave",
swiglu_limit=config.swiglu_limit,
swiglu_alpha=config.swiglu_alpha,
swiglu_beta=1.0,
routed_scaling_factor=self.routed_scaling_factor,
routed_scale_mode=RoutedScaleMode.ROUTER
if self.use_aiter_moe_fse
else RoutedScaleMode.OUTPUT,
router_logits_dtype=self.gate.out_dtype,
shared_experts=self.shared_experts,
n_shared_experts=(
self.n_shared_experts if self.is_fused_shared_expert_enabled else None
),
fuse_shared_experts=self.is_fused_shared_expert_enabled,
shared_expert_prefix=f"{prefix}.shared_experts",
quant_config=quant_config,
ckpt_names=("w1", "w2", "w3"),
prefix=f"{prefix}.experts",
)
# The NVFP4 HIP path only reads the checkpoint weights of the NVFP4 method,
# so its MoE backend selection is skipped.
with skip_checkpoint_backend_selection() if keep_nvfp4 else nullcontext():
self.experts = FusedMoEFactory(
num_experts=config.num_local_experts,
top_k=config.num_experts_per_tok,
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
intermediate_pad=0,
scoring_func="sigmoid",
e_score_correction_bias=self.e_score_correction_bias,
renormalize=True,
use_grouped_topk=self.use_aiter_moe_fse,
num_expert_group=1 if self.use_aiter_moe_fse else None,
topk_group=1 if self.use_aiter_moe_fse else None,
activation="swigluoai_uninterleave",
swiglu_limit=config.swiglu_limit,
swiglu_alpha=config.swiglu_alpha,
swiglu_beta=1.0,
routed_scaling_factor=self.routed_scaling_factor,
routed_scale_mode=RoutedScaleMode.ROUTER
if self.use_aiter_moe_fse
else RoutedScaleMode.OUTPUT,
router_logits_dtype=self.gate.out_dtype,
shared_experts=self.shared_experts,
n_shared_experts=(
self.n_shared_experts
if self.is_fused_shared_expert_enabled
else None
),
fuse_shared_experts=self.is_fused_shared_expert_enabled,
shared_expert_prefix=f"{prefix}.shared_experts",
quant_config=quant_config,
ckpt_names=("w1", "w2", "w3"),
prefix=f"{prefix}.experts",
)
if keep_nvfp4:
keep_nvfp4_experts(self.experts)

@staticmethod
def ebias_weight_loader(param: nn.Parameter, loaded_weight: torch.Tensor) -> None:
Expand Down
Loading
Loading