Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
138 changes: 138 additions & 0 deletions tests/models/kimi_k3/test_amd_latent_moe_runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""The ROCm latent-MoE tail: sharded output must equal the replicated one.

``ROCmLatentMoERunner`` has each rank project only its slice of the hidden dim
into its partial shared-expert output and leaves the final all-reduce to stitch
the shards. If the slicing or the accumulation is wrong the model still runs and
still produces plausible text, so these pin the arithmetic instead.
"""

from types import SimpleNamespace

import pytest
import torch

from vllm.model_executor.layers.fused_moe.runner import moe_runner
from vllm.models.kimi_k3.amd import latent_moe_runner
from vllm.models.kimi_k3.amd.latent_moe_runner import ROCmLatentMoERunner

TP_SIZE = 4
HIDDEN = 32
LATENT = 16
NUM_TOKENS = 5


class _Norm(torch.nn.Module):
"""Stands in for the transform's RMSNorm.

The tail is exact for any normalisation, because the norm runs on the
all-reduced latent before the shard; keeping it device-independent lets
this test run without a GPU.
"""

def __init__(self, size: int) -> None:
super().__init__()
self.weight = torch.nn.Parameter(1 + 0.1 * torch.randn(size))

def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + 1e-6) * self.weight


def _runner(**attrs) -> ROCmLatentMoERunner:
"""A runner carrying only what the tail reads, so no engine is needed."""
runner = object.__new__(ROCmLatentMoERunner)
for name, value in attrs.items():
object.__setattr__(runner, name, value)
return runner


@pytest.fixture
def tail_inputs():
torch.manual_seed(0)
transform = SimpleNamespace(
norm=_Norm(LATENT),
up_proj=SimpleNamespace(weight=torch.randn(HIDDEN, LATENT) / LATENT**0.5),
)
return SimpleNamespace(
transform=transform,
# What each rank holds before any collective: partial routed output in
# latent space, partial shared-expert output at full hidden dim.
fused=[torch.randn(NUM_TOKENS, LATENT) for _ in range(TP_SIZE)],
shared=[torch.randn(NUM_TOKENS, HIDDEN) for _ in range(TP_SIZE)],
)


def _run_all_ranks(tail_inputs, monkeypatch: pytest.MonkeyPatch) -> torch.Tensor:
"""Run the tail on every simulated rank and sum, as the final AR would."""
latent_total = sum(tail_inputs.fused)
monkeypatch.setattr(
latent_moe_runner, "tensor_model_parallel_all_reduce", lambda _: latent_total
)

outputs = []
for rank in range(TP_SIZE):
monkeypatch.setattr(
latent_moe_runner, "get_tensor_model_parallel_rank", lambda r=rank: r
)
runner = _runner(
routed_output_transform=tail_inputs.transform,
_up_proj_shard_size=HIDDEN // TP_SIZE,
_logged_sharded_tail=True,
)
# Stand in for the final all-reduce, which the caller performs below.
monkeypatch.setattr(
runner, "_maybe_reduce_final_output", lambda states, *_, **__: states
)
outputs.append(
runner._shard_up_proj_tail(
tail_inputs.fused[rank], tail_inputs.shared[rank], None
)
)
return sum(outputs)


def test_sharded_tail_sums_to_the_replicated_projection(
tail_inputs, monkeypatch: pytest.MonkeyPatch
):
transform = tail_inputs.transform
latent = transform.norm(sum(tail_inputs.fused))
expected = sum(tail_inputs.shared) + latent @ transform.up_proj.weight.t()

actual = _run_all_ranks(tail_inputs, monkeypatch)

torch.testing.assert_close(actual, expected)


def test_every_rank_writes_only_its_own_shard(
tail_inputs, monkeypatch: pytest.MonkeyPatch
):
"""Overlapping or gapped shards would still sum to something plausible."""
untouched = [s.clone() for s in tail_inputs.shared]
shard = HIDDEN // TP_SIZE

_run_all_ranks(tail_inputs, monkeypatch)

for rank, (before, after) in enumerate(zip(untouched, tail_inputs.shared)):
start, end = rank * shard, (rank + 1) * shard
assert not torch.equal(after[:, start:end], before[:, start:end])
torch.testing.assert_close(after[:, :start], before[:, :start])
torch.testing.assert_close(after[:, end:], before[:, end:])


@pytest.mark.parametrize(
"shardable,pre_reduced",
[(False, False), (True, True), (False, True)],
)
def test_falls_back_to_the_base_runner(
shardable: bool, pre_reduced: bool, monkeypatch: pytest.MonkeyPatch
):
"""The shard needs an un-reduced shared partial to accumulate into."""
sentinel = torch.zeros(1)
monkeypatch.setattr(moe_runner.MoERunner, "forward", lambda *a, **k: sentinel)
monkeypatch.setattr(
ROCmLatentMoERunner, "_fused_output_is_reduced", property(lambda _: pre_reduced)
)
runner = _runner(_tail_shardable=shardable)

assert runner.forward(torch.zeros(1), torch.zeros(1)) is sentinel
5 changes: 5 additions & 0 deletions vllm/envs.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
VLLM_ROCM_FP8_PADDING: bool = True
VLLM_ROCM_MOE_PADDING: bool = True
VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT: bool = False
VLLM_ROCM_USE_LATENT_MOE_RUNNER: bool = True
VLLM_ENABLE_V1_MULTIPROCESSING: bool = True
VLLM_LOG_BATCHSIZE_INTERVAL: float = -1
VLLM_DISABLE_COMPILE_CACHE: bool = False
Expand Down Expand Up @@ -1328,6 +1329,10 @@ def _resolve_rust_cli_path() -> str | None:
"VLLM_ROCM_QUICK_REDUCE_QUANTIZATION_MIN_SIZE_KB": lambda: maybe_convert_int(
os.environ.get("VLLM_ROCM_QUICK_REDUCE_QUANTIZATION_MIN_SIZE_KB", None)
),
# For Kimi-K3 on ROCm, use the latent-MoE runner if set.
"VLLM_ROCM_USE_LATENT_MOE_RUNNER": lambda: bool(
int(os.getenv("VLLM_ROCM_USE_LATENT_MOE_RUNNER", "1"))
),
# If set, enable multiprocessing in LLM for the V1 code path.
"VLLM_ENABLE_V1_MULTIPROCESSING": lambda: bool(
int(os.getenv("VLLM_ENABLE_V1_MULTIPROCESSING", "1"))
Expand Down
152 changes: 152 additions & 0 deletions vllm/models/kimi_k3/amd/latent_moe_runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch

from vllm.distributed import (
get_tensor_model_parallel_rank,
tensor_model_parallel_all_reduce,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe.runner.moe_runner import MoERunner, _unpack

logger = init_logger(__name__)


class ROCmLatentMoERunner(MoERunner):
"""MoE runner for latent MoE with a replicated routed up-projection.

Mirrors CUDA's LatentMoERunner, but currently only the up projection
-sharded path is implemented. (Tier 2)

Native path: the replicated up-proj produces the full hidden dim on every
rank, so the base runner combines routed + shared correctly at any TP size.
"""

def __init__(
self,
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)

transform = self.routed_output_transform
up_proj = getattr(transform, "up_proj", None)
tp_size = self.moe_config.tp_size

self._up_proj_shard_size = 0
self._tail_shardable = (
up_proj is not None
and tp_size > 1
and up_proj.weight.shape[0] % tp_size == 0
and self._shared_experts is not None
and not self.moe_config.is_sequence_parallel
and self.routed_scaling_factor == 1.0
)
if self._tail_shardable:
assert up_proj is not None
self._up_proj_shard_size = up_proj.weight.shape[0] // tp_size
else:
logger.warning_once(
"K3 latent-MoE tail is not shardable under this config, "
"falling back to the replicated up-projection.",
scope="global",
)
self._logged_sharded_tail = False

def _shard_up_proj_tail(
self,
fused_output: torch.Tensor,
shared_output: torch.Tensor,
trunc_size: int | None,
) -> torch.Tensor:
"""
Tier 2: column-parallel up-projection folded into the final reduce.
"""
if not self._logged_sharded_tail:
self._logged_sharded_tail = True
logger.info_once(
"Kimi-K3 latent-MoE tail: up-projecting only this rank's "
"hidden shard into the shared output.",
scope="global",
)

transform = self.routed_output_transform
assert transform is not None

latent = tensor_model_parallel_all_reduce(fused_output)
if transform.norm is not None:
latent = transform.norm(latent)

shard_size = self._up_proj_shard_size
shard_start = get_tensor_model_parallel_rank() * shard_size
up_proj_shard = transform.up_proj.weight.narrow(0, shard_start, shard_size)
hidden_shard = shared_output.narrow(-1, shard_start, shard_size)

# hidden_shard += latent @ up_proj_shard.T, accumulated in the GEMM's
# beta-add epilogue so folding in the shared partial costs no kernel.
hidden_shard.addmm_(latent, up_proj_shard.t())

return self._maybe_reduce_final_output(
shared_output, trunc_size, output_is_reduced=False
)

def forward(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
input_ids: torch.Tensor | None = None,
shared_experts_input: torch.Tensor | None = None,
) -> torch.Tensor:
if self._tail_shardable and not self._fused_output_is_reduced:
return self._fused_forward(
hidden_states, router_logits, input_ids, shared_experts_input
)
return super().forward(
hidden_states, router_logits, input_ids, shared_experts_input
)

def _fused_forward(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
input_ids: torch.Tensor | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
# When the caller pre-applies the routed input transform outside the
# runner (e.g. to overlap it on a separate stream), it passes the
# already-transformed routed input as ``hidden_states`` and the original
# hidden states as ``shared_experts_input``; skip the transform then.
if shared_experts_input is None:
hidden_states, shared_experts_input = self.apply_routed_input_transform(
hidden_states
)

hidden_states, og_hidden_dim_pre_xform, og_hidden_dim_post_xform = (
self._maybe_pad_hidden_states(
shared_experts_input,
hidden_states,
)
)

result = self._forward_entry(
hidden_states,
router_logits,
shared_experts_input,
input_ids,
self._encode_layer_name(),
self.moe_config.hidden_dim_unpadded
if self._quant_method.has_unpadded_output
else 0,
)

shared_output, fused_output = _unpack(result)
assert shared_output is not None

if og_hidden_dim_pre_xform is not None:
fused_output = fused_output[..., :og_hidden_dim_pre_xform]

result = self._shard_up_proj_tail(
fused_output, shared_output, og_hidden_dim_post_xform
)

return self._maybe_add_zero_expert_output(result)
5 changes: 5 additions & 0 deletions vllm/models/kimi_k3/amd/linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import torch
from torch import nn

import vllm.envs as envs
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import (
get_pp_group,
Expand Down Expand Up @@ -62,6 +63,7 @@
maybe_prefix,
)
from vllm.models.kimi_k3.amd.kda import KimiK3DeltaAttention
from vllm.models.kimi_k3.amd.latent_moe_runner import ROCmLatentMoERunner
from vllm.models.kimi_k3.amd.ops.attn_res import attn_res
from vllm.sequence import IntermediateTensors
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
Expand Down Expand Up @@ -289,6 +291,9 @@ def __init__(
routed_scaling_factor=self.routed_scaling_factor,
routed_input_transform=self.routed_expert_down_proj,
routed_output_transform=self.routed_output_transform,
runner_cls=ROCmLatentMoERunner
if self.use_latent_moe and envs.VLLM_ROCM_USE_LATENT_MOE_RUNNER
else None,
)
if self.padded_moe_intermediate_size != moe_intermediate_size:
w13_weight = getattr(self.experts, "w13_weight", None)
Expand Down
Loading