feat(kimi-k3): route attention-TP slices under attention DP

Kimi-K3's attention-DP MoE path required attention DP == MoE EP == world
size, so routed EP could only be paired with attention TP 1 (DEP). Allow
attention TP > 1 under attention DP with MoE TP 1 and
attention TP x DP == MoE EP == world size, e.g. two attention replicas of
TP8 with KV parallelism 8 and routed EP16 across both replicas.

The attention-DP forward stays one path. After the attention all-reduce
every rank of a replica holds all of the replica's rows; each attention-TP
rank routes a disjoint consecutive slice of them (scatter_count, DP-major
and TP-minor like the expert-parallel ranks), and at attention TP 1 the
slice is the whole replica. The shared experts shard over the replica's
attention-TP group and read all of its rows; a token reduce-scatter adds
their partial sums onto the slices and a token all-gather restores the
replica's rows. The fused input projection and its packed weight apply
only at attention TP 1, where routing and the shared experts read the same
rows. Static expert placement still requires attention TP 1.

The transport is unchanged: the FlashInfer all-to-all, the all-gather
fallback, or MegaMoE, which owns dispatch and combine.

Signed-off-by: Xiangyi Zhang <xiangyiz@nvidia.com>
This commit is contained in:
Xiangyi Zhang
2026-11-30 09:42:50 +00:00
parent 1865648531
commit 82eb424b9c
3 changed files with 314 additions and 72 deletions
+10 -4
View File
@@ -269,10 +269,16 @@ W4A8 variant.
### Kimi-K3 attention DP with MoE EP
With `none`, `agrs`, or `flashinfer` transport and attention DP greater than one,
Kimi-K3 requires
`attention DP == MoE EP == world size`. By default, shared experts and attention
projections are replicated. Only the routed experts require dispatch/combine
communication.
Kimi-K3 requires MoE TP 1 and
`attention TP x attention DP == MoE EP == world size`. Only the routed experts
require dispatch/combine communication. With attention TP 1 (DEP), shared
experts and attention projections are replicated. With attention TP greater
than one, each attention-TP rank routes a slice of its replica's rows and the
shared experts shard over the replica's attention-TP group. For example, two
attention replicas of TP8 with KV parallelism 8 and routed EP16 across both:
`--attn-tp-size 8 --data-parallel-size 2 --kv-parallel-size 8
--decode-context-parallel-size 8 --moe-tp-size 1 --expert-parallel-size 16`.
Static expert placement requires attention TP 1.
On this path (any transport but `deepep`, or MegaMoE), an EP size that does
not divide the 896 routed experts takes redundant slots
([static expert placement](#static-expert-placement-with-redundant-experts)),
+117 -40
View File
@@ -57,7 +57,7 @@ from __future__ import annotations
import logging
import re
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar
@@ -129,6 +129,8 @@ from tokenspeed.runtime.distributed.comm_ops import (
all_reduce,
can_acquire_all_reduce_outputs,
reduce_scatter,
token_all_gather,
token_reduce_scatter,
)
from tokenspeed.runtime.distributed.mapping import DenseLayerMapping, Mapping
from tokenspeed.runtime.distributed.pp_stage import PPStageState, pp_layer_window
@@ -138,6 +140,7 @@ from tokenspeed.runtime.execution.forward_step import (
get_is_capture_mode,
get_is_cuda_graph_phase,
)
from tokenspeed.runtime.execution.query_shard import scatter_count
from tokenspeed.runtime.layers.activation import SituAndMul
from tokenspeed.runtime.layers.dense.fp8 import Fp8LinearMethod
from tokenspeed.runtime.layers.dense.unquant import UnquantizedLinearMethod
@@ -2533,12 +2536,13 @@ def _check_k3_expert_placement(
)
if not (
mapping.attn.dp_size > 1
and mapping.attn.tp_size == 1
and mapping.moe.tp_size == 1
and mapping.moe.ep_size > 1
):
raise ValueError(
"Kimi-K3 expert placement requires attention DP with MoE EP only "
"(moe tp_size 1)"
"Kimi-K3 expert placement requires attention DP with attention TP 1 "
"and MoE EP only (moe tp_size 1)"
)
if peer_weights is not None:
raise ValueError(
@@ -2561,6 +2565,30 @@ def _check_k3_expert_placement(
)
def routes_whole_replica(mapping: Mapping) -> bool:
"""Whether a rank routes every row its shared experts read.
False only for attention TP > 1 under attention DP, where each
attention-TP rank routes a slice of its replica's rows.
"""
return mapping.attn.dp_size == 1 or mapping.attn.tp_size == 1
def attn_tp_route_slices(
counts: Sequence[int], attn_tp_size: int, attn_dp_size: int
) -> list[int]:
"""Rows each expert-parallel rank routes under attention DP.
``counts`` is per rank, DP-major and TP-minor, so a replica's ranks share
its count; each replica splits into ``attn_tp_size`` consecutive slices.
"""
return [
count
for dp_rank in range(attn_dp_size)
for count in scatter_count(counts[dp_rank * attn_tp_size], attn_tp_size)
]
class KimiLinearMoE(nn.Module):
"""Kimi-K3 MoE block: sigmoid / noaux_tc router + Latent MoE + shared experts.
@@ -2599,9 +2627,17 @@ class KimiLinearMoE(nn.Module):
# Decoder layers inspect this even when attention DP skips native setup.
self.native_latent_moe: LatentMoELayer | None = None
if mapping.attn.dp_size > 1 and mapping.moe.tp_ep_size > 1:
if not (mapping.attn.dp_size == mapping.moe.ep_size == mapping.world_size):
# Each attention-TP rank dispatches a disjoint slice of its replica's
# rows, so the expert group spans every attention rank exactly once.
if not (
mapping.moe.tp_size == 1
and mapping.attn.tp_size * mapping.attn.dp_size
== mapping.moe.ep_size
== mapping.world_size
):
raise ValueError(
"Kimi-K3 attention DP requires attention DP == MoE EP == world size."
"Kimi-K3 attention DP requires MoE TP 1 and "
"attention TP x DP == MoE EP == world size."
)
elif mapping.attn.tp_size != mapping.moe.tp_ep_size:
raise ValueError("Kimi-K3 attention TP must match the MoE TP x EP group.")
@@ -2865,28 +2901,38 @@ class KimiLinearMoE(nn.Module):
shared_parallel = shared_expert_mapping(
mapping, envs.TOKENSPEED_KIMI_K3_SHARED_EXPERT_TP_SIZE.get()
)
if shared_parallel is not None:
shared_tp_rank, shared_tp_size, shared_tp_group = (
shared_parallel.tp_rank,
shared_parallel.tp_size,
shared_parallel.tp_group,
)
elif mapping.attn.dp_size > 1:
# Under attention DP the shared experts shard over their replica's
# attention-TP group (TP1 keeps them whole).
attn = mapping.attn
shared_tp_rank, shared_tp_size, shared_tp_group = (
attn.tp_rank,
attn.tp_size,
attn.tp_group if attn.tp_size > 1 else None,
)
else:
shared_tp_rank, shared_tp_size, shared_tp_group = (
mapping.moe.tp_ep_rank,
mapping.moe.tp_ep_size,
mapping.moe.tp_ep_group,
)
self.shared_experts = KimiLinearMLP(
hidden_size=config.hidden_size,
intermediate_size=config.moe_intermediate_size * config.num_shared_experts,
tp_rank=(
shared_parallel.tp_rank
if shared_parallel is not None
else (0 if mapping.attn.dp_size > 1 else mapping.moe.tp_ep_rank)
),
tp_size=(
shared_parallel.tp_size
if shared_parallel is not None
else (1 if mapping.attn.dp_size > 1 else mapping.moe.tp_ep_size)
),
tp_group=(
shared_parallel.tp_group
if shared_parallel is not None
else (None if mapping.attn.dp_size > 1 else mapping.moe.tp_ep_group)
),
tp_rank=shared_tp_rank,
tp_size=shared_tp_size,
tp_group=shared_tp_group,
shared_parallel=shared_parallel,
quant_config=_dense_mlp_quant_config(quant_config),
prefix=add_prefix("shared_experts", prefix),
# TP combines shared partials in the tail; DP keeps complete local outputs.
# The tail combines shared partials: TP in its reduction, attention
# DP in a reduce-scatter over the replica's attention-TP group.
reduce_results=False,
is_shared_expert=True,
activation_situ_beta=situ_beta,
@@ -2994,6 +3040,8 @@ class KimiLinearMoE(nn.Module):
view of that tensor, so the rebinding adds no steady-state memory and
leaves the separate composition working unchanged.
"""
if not routes_whole_replica(self.mapping):
return
modules = (
self.gate,
self.routed_expert_down_proj,
@@ -3664,25 +3712,40 @@ class KimiLinearMoE(nn.Module):
prefix_sum: torch.Tensor,
ctx: ForwardContext,
) -> torch.Tensor:
"""Keep dense work local and dispatch/combine only routed expert activations."""
"""Keep dense work local and dispatch/combine only routed expert activations.
Each attention-TP rank routes a disjoint slice of its replica's rows
(the whole replica at attention TP 1). The shared experts shard over the
attention-TP group and read all of the replica's rows; their partial
sums reduce-scatter onto the slices, and the outputs gather back.
"""
attn = self.mapping.attn
counts = (
ctx.collective_global_num_tokens
if ctx.collective_global_num_tokens is not None
else ctx.global_num_tokens
)
num_tokens = hidden_states.shape[0]
replica_tokens = hidden_states.shape[0]
if (
counts is None
or len(counts) != self.mapping.world_size
or num_tokens != counts[self.mapping.attn.dp_rank]
or replica_tokens != counts[attn.dp_rank * attn.tp_size]
or prefix_sum.shape != hidden_states.shape
):
raise ValueError(
"Kimi-K3 attention DP requires matching collective token counts."
)
max_tokens = max(counts)
slice_counts = attn_tp_route_slices(counts, attn.tp_size, attn.dp_size)
max_tokens = max(slice_counts)
if max_tokens == 0:
return prefix_sum
replica_slices = slice_counts[
attn.dp_rank * attn.tp_size : (attn.dp_rank + 1) * attn.tp_size
]
num_tokens = replica_slices[attn.tp_rank]
start = sum(replica_slices[: attn.tp_rank])
local_hidden = hidden_states.narrow(0, start, num_tokens)
local_prefix = prefix_sum.narrow(0, start, num_tokens)
quant_out = None
routing_out = None
@@ -3704,10 +3767,12 @@ class KimiLinearMoE(nn.Module):
# The fused front runs before the fork scope: the scope's fork event is
# recorded at entry, so an auxiliary branch is only ordered after work
# enqueued on main before this point, and the shared down projection on
# the branch below reads the front's shared_activated.
# the branch below reads the front's shared_activated. It projects one
# row set for both.
fused_inputs = None
if (
num_tokens > 0
and routes_whole_replica(self.mapping)
and shared_communication is None
and hidden_states.is_cuda
and self.shared_experts.gate_up_proj.weight.dtype == hidden_states.dtype
@@ -3739,11 +3804,11 @@ class KimiLinearMoE(nn.Module):
shared_activated = None
if num_tokens > 0:
if fused_inputs is None:
router_logits = self.gate(hidden_states)
router_logits = self.gate(local_hidden)
else:
router_logits, routed_input, shared_activated = fused_inputs
topk = self.topk(
hidden_states,
local_hidden,
router_logits,
output_format=TopKOutputFormat.STANDARD,
num_token_non_padded=None,
@@ -3751,7 +3816,7 @@ class KimiLinearMoE(nn.Module):
out=routing_out,
)
if fused_inputs is None:
routed_input, _ = self.routed_expert_down_proj(hidden_states)
routed_input, _ = self.routed_expert_down_proj(local_hidden)
topk_ids = topk.topk_ids
topk_weights = topk.topk_weights
else:
@@ -3837,7 +3902,7 @@ class KimiLinearMoE(nn.Module):
shared_output, num_tokens
)
if shared_communication is None and num_tokens > 0:
if shared_communication is None and replica_tokens > 0:
with fork.branch():
if shared_activated is None:
shared_output = self.shared_experts(
@@ -3897,17 +3962,29 @@ class KimiLinearMoE(nn.Module):
):
projected, _ = self.routed_expert_up_proj(routed_output)
if num_tokens == 0:
# An idle replica still joined the expert-parallel exchange above; all
# of its attention-TP ranks skip the replica-local collectives together.
if replica_tokens == 0:
return prefix_sum
if projected is not None:
return add3(prefix_sum, projected, shared_output)
return self.routed_expert_up_proj.forward_add3(
routed_output,
prefix_sum,
shared_output,
norm_weight=None,
eps=None,
)
if attn.tp_size > 1:
shared_output = token_reduce_scatter(
shared_output, attn.tp_group, replica_slices
)
if num_tokens == 0:
output = local_prefix
elif projected is not None:
output = add3(local_prefix, projected, shared_output)
else:
output = self.routed_expert_up_proj.forward_add3(
routed_output,
local_prefix,
shared_output,
norm_weight=None,
eps=None,
)
if attn.tp_size > 1:
output = token_all_gather(output, attn.tp_group, replica_slices)
return output
def forward(
self,
+187 -28
View File
@@ -37,20 +37,22 @@ register_cuda_ci(est_time=30, suite="runtime-1gpu")
from tokenspeed.runtime.configs.kimi_k3_config import KimiLinearConfig
from tokenspeed.runtime.distributed.mapping import Mapping
from tokenspeed.runtime.execution.query_shard import scatter_count
from tokenspeed.runtime.layers.moe.latent import Kimi3LatentProjection
from tokenspeed.runtime.layers.moe.topk import StandardTopKOutput, TopKOutputFormat
from tokenspeed.runtime.layers.moe.utils import All2AllBackend, MoeBackend
from tokenspeed.runtime.models import kimi_k3
from tokenspeed.runtime.models.kimi_k3 import KimiLinearMoE
from tokenspeed.runtime.models.kimi_k3 import KimiLinearMoE, attn_tp_route_slices
@pytest.mark.parametrize("dp,ep,world", [(4, 2, 4), (2, 4, 4), (4, 4, 8)])
# (attention DP, MoE EP, world): the expert group must span every attention rank.
@pytest.mark.parametrize("dp,ep,world", [(4, 2, 4), (2, 2, 4), (4, 4, 8), (2, 8, 16)])
def test_attn_dp_rejects_partial_world_layout_before_backend_setup(
monkeypatch, dp: int, ep: int, world: int
) -> None:
backend = mock.Mock(side_effect=AssertionError("backend setup reached"))
monkeypatch.setattr(kimi_k3, "get_moe_backend", backend)
with pytest.raises(ValueError, match="attention DP == MoE EP == world size"):
with pytest.raises(ValueError, match="attention TP x DP == MoE EP == world size"):
KimiLinearMoE(
config=SimpleNamespace(),
mapping=Mapping(
@@ -77,12 +79,14 @@ def test_attn_dp_rejects_partial_world_layout_before_backend_setup(
)
@pytest.mark.parametrize("fabric_available", [False, True])
@pytest.mark.parametrize("weights_dtype", [torch.float32, torch.bfloat16])
@pytest.mark.parametrize("attn_tp", [1, 2])
def test_attn_dp_replicates_dense_weights_and_selects_transport(
monkeypatch,
backend: str,
fabric_available: bool,
moe_backend: str,
weights_dtype: torch.dtype,
attn_tp: int,
) -> None:
mega_moe = moe_backend in {"mega_moe", "gluon_petit"}
expected_a2a = "gluon_petit" if moe_backend == "gluon_petit" else "none"
@@ -134,22 +138,13 @@ def test_attn_dp_replicates_dense_weights_and_selects_transport(
monkeypatch.setitem(
kimi_k3.global_server_args_dict, "speculative_num_draft_tokens", 4
)
mapping = SimpleNamespace(
world_size=2,
# Two attention replicas; the expert group spans every attention rank.
mapping = Mapping(
rank=1,
attn=SimpleNamespace(dp_size=2, dp_rank=1, tp_size=1),
moe=SimpleNamespace(
ep_size=2,
ep_rank=1,
ep_group=(0, 1),
tp_size=1,
tp_rank=0,
tp_group=(1,),
tp_ep_size=2,
tp_ep_rank=1,
tp_ep_group=(0, 1),
dp_size=1,
),
world_size=2 * attn_tp,
attn_tp_size=attn_tp,
moe_tp_size=1,
moe_ep_size=2 * attn_tp,
)
expected_error = (mega_moe and backend != expected_a2a) or (
not mega_moe and backend == "flashinfer" and not fabric_available
@@ -193,10 +188,13 @@ def test_attn_dp_replicates_dense_weights_and_selects_transport(
assert not layer.routed_expert_up_proj.narrowed
assert layer.routed_expert_down_proj.weight.shape == (32, 64)
assert layer.routed_expert_up_proj.weight.shape == (64, 32)
assert layer.shared_experts.gate_up_proj.weight.shape == (64, 64)
assert layer.shared_experts.down_proj.weight.shape == (64, 32)
assert layer.shared_experts.down_proj.tp_size == 1
assert layer.shared_experts.down_proj.tp_group is None
# Shared experts shard over the replica's attention-TP group.
assert layer.shared_experts.gate_up_proj.weight.shape == (64 // attn_tp, 64)
assert layer.shared_experts.down_proj.weight.shape == (64, 32 // attn_tp)
assert layer.shared_experts.down_proj.tp_size == attn_tp
assert layer.shared_experts.down_proj.tp_group == (
mapping.attn.tp_group if attn_tp > 1 else None
)
assert layer.experts.kwargs["routing_mode"] == "precomputed_topk"
assert layer.topk.topk_config.topk_weights_dtype == weights_dtype
assert layer.comm is None
@@ -411,7 +409,7 @@ def test_attn_dp_exchanges_latents_and_returns_reduced_local_rows(
layer = SimpleNamespace(
mapping=SimpleNamespace(
world_size=2,
attn=SimpleNamespace(dp_rank=rank),
attn=SimpleNamespace(dp_rank=rank, dp_size=2, tp_rank=0, tp_size=1),
moe=SimpleNamespace(ep_group=group),
),
execution_plan=SimpleNamespace(use_mega_moe=False, owns_ep_communication=False),
@@ -502,8 +500,10 @@ def test_attn_dp_exchanges_latents_and_returns_reduced_local_rows(
expected_events.append("up")
assert events == expected_events
if rows:
layer.gate.assert_called_once_with(hidden)
layer.routed_expert_down_proj.assert_called_once_with(hidden)
# Attention TP 1 routes the whole replica (a view of its rows).
for projection in (layer.gate, layer.routed_expert_down_proj):
projection.assert_called_once()
torch.testing.assert_close(projection.call_args.args[0], hidden)
layer.shared_experts.assert_called_once_with(hidden, down_out=None)
else:
layer.gate.assert_not_called()
@@ -521,7 +521,10 @@ def test_attn_dp_all_idle_skips_collectives(monkeypatch) -> None:
monkeypatch.setattr(kimi_k3, "reduce_scatter", forbidden)
hidden = torch.empty(0, 4)
layer = SimpleNamespace(
mapping=SimpleNamespace(world_size=2, attn=SimpleNamespace(dp_rank=0))
mapping=SimpleNamespace(
world_size=2,
attn=SimpleNamespace(dp_rank=0, dp_size=2, tp_rank=0, tp_size=1),
)
)
ctx = SimpleNamespace(collective_global_num_tokens=None, global_num_tokens=[0, 0])
result = KimiLinearMoE._forward_attn_dp(layer, hidden, hidden, ctx)
@@ -529,6 +532,156 @@ def test_attn_dp_all_idle_skips_collectives(monkeypatch) -> None:
forbidden.assert_not_called()
@pytest.mark.parametrize(
"counts,tp_size,dp_size,expected",
[
# Uneven split: the first ranks of a replica take the extra rows.
([3, 3, 1, 1], 2, 2, [2, 1, 1, 0]),
# An idle replica beside a busy one.
([0, 0, 5, 5], 2, 2, [0, 0, 3, 2]),
# Fewer rows than attention-TP ranks.
([2] * 8 + [9] * 8, 8, 2, [1, 1] + [0] * 6 + [2] + [1] * 7),
# TP1 routes each replica whole.
([4, 0, 7], 1, 3, [4, 0, 7]),
],
)
def test_attn_tp_route_slices_cover_each_replica_once(
counts: list[int], tp_size: int, dp_size: int, expected: list[int]
) -> None:
assert attn_tp_route_slices(counts, tp_size, dp_size) == expected
# Attention TP2 x DP2 replicas (EP4): uneven slices, fewer rows than TP ranks,
# and an idle replica beside a busy one.
@pytest.mark.parametrize("replica_rows", [(3, 1), (1, 0), (0, 2)])
def test_attn_tp_ranks_route_each_row_once_and_return_replica_outputs(
monkeypatch, replica_rows: tuple[int, int]
) -> None:
tp_size = 2
counts = [rows for rows in replica_rows for _ in range(tp_size)]
capacity = max(max(scatter_count(rows, tp_size)) for rows in replica_rows)
hiddens = [
torch.arange(rows * 4, dtype=torch.float32).reshape(rows, 4) + 1 + 100 * dp
for dp, rows in enumerate(replica_rows)
]
routed_rows: list[list[torch.Tensor]] = [[], []]
# Each attention-TP rank's output slice, as handed to the all-gather.
gathered: list[list[torch.Tensor]] = [[], []]
def reference(hidden: torch.Tensor) -> torch.Tensor:
# prefix + up(experts(down(hidden))) + shared(hidden)
latent = hidden[:, :2] * 2
return hidden + 10 + torch.cat((latent, latent), dim=-1) + hidden * 3
@contextmanager
def scope(*, enable, overlap):
yield fork
fork = SimpleNamespace(scope=scope, branch=nullcontext, join=lambda: None)
monkeypatch.setattr(kimi_k3, "get_is_cuda_graph_phase", lambda: False)
monkeypatch.setattr(kimi_k3, "get_is_capture_mode", lambda: False)
for rank in range(len(counts)):
dp_rank, tp_rank = divmod(rank, tp_size)
hidden = hiddens[dp_rank]
slices = scatter_count(hidden.shape[0], tp_size)
own = slice(sum(slices[:tp_rank]), sum(slices[: tp_rank + 1]))
def gate(value, dp_rank=dp_rank):
routed_rows[dp_rank].append(value.clone())
return torch.empty(value.shape[0], 2)
def dispatch(routed, ids, weights, max_tokens):
assert max_tokens == capacity
return routed, ids, weights
def reduce_scatter_rows(value, group, scattered, own=own):
# The shared partials of the replica's TP ranks are equal here.
return (value * tp_size)[own]
replica_rows_out = torch.empty_like(hidden)
def gather_rows(value, group, scattered, dp_rank=dp_rank, out=replica_rows_out):
gathered[dp_rank].append(value.clone())
return out
monkeypatch.setattr(kimi_k3, "token_reduce_scatter", reduce_scatter_rows)
monkeypatch.setattr(kimi_k3, "token_all_gather", gather_rows)
topk = mock.Mock(
side_effect=lambda value, logits, **_: StandardTopKOutput(
torch.full((value.shape[0], 2), 0.5),
torch.ones(value.shape[0], 2, dtype=torch.int32),
None,
)
)
topk.topk_config = SimpleNamespace(
topk_weights_dtype=torch.float32, topk_indices_dtype=torch.int32
)
layer = SimpleNamespace(
mapping=SimpleNamespace(
world_size=len(counts),
attn=SimpleNamespace(
dp_rank=dp_rank,
dp_size=len(replica_rows),
tp_rank=tp_rank,
tp_size=tp_size,
tp_group=(dp_rank * tp_size, dp_rank * tp_size + 1),
),
moe=SimpleNamespace(ep_group=tuple(range(len(counts)))),
),
execution_plan=SimpleNamespace(
use_mega_moe=False, owns_ep_communication=False
),
moe_alltoall=SimpleNamespace(dispatch=dispatch, combine=lambda v: v),
stream_fork=fork,
routed_hidden=2,
top_k=2,
topk=topk,
expert_dispatch_info=None,
experts=SimpleNamespace(plan={"weight_dtype": "unquant"}),
gate=gate,
routed_expert_down_proj=lambda value: (value[:, :2], None),
shared_experts=_SharedPartials(tp_size),
_routed_experts=lambda routed, routing, **_: routed * 2,
routed_expert_norm=None,
routed_expert_up_proj=SimpleNamespace(
forward_add3=lambda value, residual, shared, **_: residual
+ torch.cat((value, value), dim=-1)
+ shared
),
)
ctx = SimpleNamespace(
collective_global_num_tokens=counts, global_num_tokens=None
)
result = KimiLinearMoE._forward_attn_dp(layer, hidden, hidden + 10, ctx)
# A busy replica returns the gathered rows; an idle one its empty prefix.
if hidden.shape[0]:
assert result is replica_rows_out
else:
assert result.shape == (0, 4)
for dp_rank, hidden in enumerate(hiddens):
seen = routed_rows[dp_rank]
torch.testing.assert_close(torch.cat(seen) if seen else hidden[:0], hidden)
# The replica's TP ranks computed disjoint slices that tile its rows.
slices = gathered[dp_rank]
torch.testing.assert_close(
torch.cat(slices) if slices else hidden[:0], reference(hidden)
)
class _SharedPartials:
"""Shared experts sharded over ``tp_size`` ranks: each returns 1/tp of the sum."""
shared_parallel = None
def __init__(self, tp_size: int) -> None:
self.tp_size = tp_size
def __call__(self, value: torch.Tensor, *, down_out) -> torch.Tensor:
return value * 3 / self.tp_size
def test_attn_dp_forward_bypasses_tp_tail() -> None:
hidden = torch.ones(1, 4)
ctx = SimpleNamespace()
@@ -564,7 +717,10 @@ def test_attn_dp_rejects_invalid_token_metadata_before_collectives(
monkeypatch.setattr(kimi_k3, "all_gather", forbidden)
monkeypatch.setattr(kimi_k3, "reduce_scatter", forbidden)
layer = SimpleNamespace(
mapping=SimpleNamespace(world_size=2, attn=SimpleNamespace(dp_rank=0))
mapping=SimpleNamespace(
world_size=2,
attn=SimpleNamespace(dp_rank=0, dp_size=2, tp_rank=0, tp_size=1),
)
)
ctx = SimpleNamespace(collective_global_num_tokens=counts, global_num_tokens=None)
with pytest.raises(ValueError, match="matching collective token counts"):
@@ -632,7 +788,10 @@ def test_attn_dp_fused_moe_keeps_inputs_local_and_owns_combine(
up.weight.data.normal_(std=0.1)
layer = SimpleNamespace(
execution_plan=SimpleNamespace(use_mega_moe=True, owns_ep_communication=True),
mapping=SimpleNamespace(world_size=2, attn=SimpleNamespace(dp_rank=0)),
mapping=SimpleNamespace(
world_size=2,
attn=SimpleNamespace(dp_rank=0, dp_size=2, tp_rank=0, tp_size=1),
),
stream_fork=SimpleNamespace(scope=scope),
topk=mock.Mock(return_value=StandardTopKOutput(weights, ids, None)),
expert_dispatch_info=None,