perf(kimi-k3): fuse large attention-DP input projections

Use the optional FlashInfer K3 front for qualified GB300 shapes with full shared-expert weights. Keep separate projections for unsupported shapes and packages, and preserve shared-down, routing, and EP ownership.

Validated 2048-16384 rows with checkpoint weights, changed-input graph replay, and GPU block-level checks. At 8192 rows, paired cold-L2 Nsight measurements reduce kernel time from 1131.0 to 985.8 us and complete adapter-call time from 1248.9 to 1186.6 us.

Validation: 28 kernel tests, 619 runtime tests, and pre-commit run --all-files.
Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
This commit is contained in:
Enwei Zhu
2026-10-23 17:37:39 +00:00
parent 1ebce861da
commit d2d01d2221
7 changed files with 615 additions and 21 deletions
+31 -5
View File
@@ -88,6 +88,7 @@ from tokenspeed_kernel.ops.gemm import (
from tokenspeed_kernel.ops.moe import (
latent_moe_decode_pipeline_available,
latent_moe_input_projections,
try_latent_moe_input_projections,
)
from tokenspeed_kernel.ops.moe._cute_dsl.latent_down import KimiK3LatentDownOp
from tokenspeed_kernel.ops.quantization import quantize_fp8_with_gate
@@ -2623,8 +2624,27 @@ class KimiLinearMoE(nn.Module):
fork.record_checkpoint()
shared_output = self.shared_experts(shared_input, down_out=None)
shared_activated = None
if num_tokens > 0:
router_logits = self.gate(hidden_states)
fused_inputs = None
if (
shared_communication is None
and hidden_states.is_cuda
and self.shared_experts.gate_up_proj.weight.dtype
== hidden_states.dtype
):
fused_inputs = try_latent_moe_input_projections(
hidden_states,
self.gate.weight,
self.routed_expert_down_proj.weight,
self.shared_experts.gate_up_proj.weight,
gate_clamp=self.shared_experts.act_fn.beta,
up_clamp=self.shared_experts.act_fn.linear_beta,
)
if fused_inputs is None:
router_logits = self.gate(hidden_states)
else:
router_logits, routed_input, shared_activated = fused_inputs
topk = self.topk(
hidden_states,
router_logits,
@@ -2633,7 +2653,8 @@ class KimiLinearMoE(nn.Module):
expert_location_dispatch_info=None,
out=routing_out,
)
routed_input, _ = self.routed_expert_down_proj(hidden_states)
if fused_inputs is None:
routed_input, _ = self.routed_expert_down_proj(hidden_states)
topk_ids = topk.topk_ids
topk_weights = topk.topk_weights
else:
@@ -2760,9 +2781,14 @@ class KimiLinearMoE(nn.Module):
if shared_communication is None:
with fork.branch():
if num_tokens > 0:
shared_output = self.shared_experts(
hidden_states, down_out=None
)
if shared_activated is None:
shared_output = self.shared_experts(
hidden_states, down_out=None
)
else:
shared_output = kimi3_shared_down_projection(
shared_activated, self.shared_experts.down_proj.weight
)
if num_tokens == 0:
return prefix_sum
+198
View File
@@ -0,0 +1,198 @@
# Copyright (c) 2026 LightSeek Foundation
#
# 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.
"""Front fusion through the attention-DP MoE block with unloaded experts."""
import math
import os
import sys
import pytest
import torch
from tokenspeed_kernel.ops.moe import try_latent_moe_input_projections
from tokenspeed_kernel.platform import ArchVersion, current_platform
from tokenspeed_kernel.thirdparty.cuda.flashinfer_kimi_k3 import latent_front_available
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe import runner
from torch import nn
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ci_system.ci_register import register_cuda_ci
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.context import ForwardContext
from tokenspeed.runtime.execution.forward_batch_info import ForwardMode
from tokenspeed.runtime.execution.output_layout import ForwardOutputLayout
from tokenspeed.runtime.layers.moe.topk import TopKOutputFormat
from tokenspeed.runtime.layers.moe.utils import All2AllBackend, MoeBackend
from tokenspeed.runtime.models import kimi_k3
class UnloadedExperts(nn.Module):
"""Replace missing expert weights/EP ranks while exercising real dense layers."""
def __init__(self, *, top_k, num_experts, hidden_size, **kwargs):
super().__init__()
self.plan = {"weight_dtype": "bf16", "a2a_backend": "none"}
self.supports_precomputed_topk = True
self.num_experts = num_experts
self.activation = torch.empty(8192, hidden_size, dtype=torch.bfloat16)
self.scales = torch.empty(8192, hidden_size // 16, dtype=torch.uint8)
self.ids = torch.empty(8192, top_k, dtype=torch.int64)
self.weights = torch.empty(8192, top_k, dtype=torch.float32)
def input_buffers(self, tokens, capacity):
return (
self.activation[:tokens],
self.scales[:tokens],
self.ids[:tokens],
self.weights[:tokens],
)
def forward(
self,
*,
hidden_states,
topk_output,
num_global_tokens,
max_num_tokens_per_gpu,
do_finalize
):
factor = (
topk_output.topk_weights.float()
* (1.0 + topk_output.topk_ids.float() / self.num_experts)
).sum(-1, keepdim=True)
return (hidden_states.float() * factor).to(hidden_states.dtype)
@pytest.mark.parametrize("rows", [64, 2048, 8192])
def test_attention_dp_front_preserves_routing_and_output(monkeypatch, rows):
platform = current_platform()
if not (
platform.is_nvidia
and platform.arch_version == ArchVersion(10, 3)
and platform.sm_count == 152
and latent_front_available()
):
pytest.skip("requires the GB300 Kimi-K3 source bundle")
monkeypatch.setattr(kimi_k3, "MoELayer", UnloadedExperts)
monkeypatch.setattr(runner, "get_runner", lambda plan, experts: experts)
monkeypatch.setattr(kimi_k3, "get_moe_backend", lambda: MoeBackend.MEGA_MOE)
monkeypatch.setattr(kimi_k3, "get_all2all_backend", lambda: All2AllBackend.NONE)
monkeypatch.setenv("TOKENSPEED_KIMI_K3_SHARED_EXPERT_TP_SIZE", "1")
mapping = Mapping(rank=0, world_size=2, attn_dp_size=2, moe_ep_size=2)
config = KimiLinearConfig(
hidden_size=7168,
routed_expert_hidden_size=3584,
moe_intermediate_size=6144,
num_shared_experts=1,
num_experts=896,
num_experts_per_token=16,
activation_situ_beta=4.0,
activation_situ_linear_beta=25.0,
)
dtype = torch.get_default_dtype()
torch.set_default_dtype(torch.bfloat16)
try:
with torch.device("cuda"):
layer = kimi_k3.KimiLinearMoE(
config=config,
mapping=mapping,
layer_index=1,
model_scope="front_test",
moe_block_count=1,
quant_config=None,
prefix="moe",
alt_stream=None,
)
finally:
torch.set_default_dtype(dtype)
ctx = ForwardContext(
attn_backend=None,
token_to_kv_pool=None,
bs=1,
num_extends=1,
input_num_tokens=rows,
forward_mode=ForwardMode.EXTEND,
output_layout=ForwardOutputLayout(1, 1, 0, 1),
global_num_tokens=[rows, rows],
)
torch.manual_seed(271 + rows)
with torch.no_grad():
for parameter in layer.parameters():
if parameter.ndim == 1:
parameter.fill_(1.0)
else:
parameter.normal_(std=1.0 / math.sqrt(parameter.shape[-1]))
layer.gate.e_score_correction_bias.zero_()
hidden = torch.randn(rows, 7168, device="cuda", dtype=torch.bfloat16) * 0.25
prefix = torch.randn_like(hidden)
def reference():
logits = layer.gate(hidden)
routing = layer.topk(
hidden,
logits,
output_format=TopKOutputFormat.STANDARD,
num_token_non_padded=None,
expert_location_dispatch_info=None,
out=(layer.experts.weights[:rows], layer.experts.ids[:rows]),
)
latent, _ = layer.routed_expert_down_proj(hidden)
routed = layer.experts(
hidden_states=latent,
topk_output=routing,
num_global_tokens=2 * rows,
max_num_tokens_per_gpu=rows,
do_finalize=True,
)
if layer.routed_expert_norm is not None:
routed = layer.routed_expert_norm(routed)
shared = layer.shared_experts(hidden, down_out=None)
return layer.routed_expert_up_proj.forward_add3(
routed,
prefix,
shared,
norm_weight=None,
eps=None,
)
fused = try_latent_moe_input_projections(
hidden,
layer.gate.weight,
layer.routed_expert_down_proj.weight,
layer.shared_experts.gate_up_proj.weight,
gate_clamp=4.0,
up_clamp=25.0,
)
assert (fused is not None) == (rows >= 2048)
expected = reference()
actual = layer(hidden, prefix, 2 * rows, rows, ctx, prefix_is_sharded=False)
torch.testing.assert_close(actual, expected, atol=1e-2, rtol=1e-2)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
captured = layer(
hidden, prefix, 2 * rows, rows, ctx, prefix_is_sharded=False
)
hidden.normal_(std=0.125)
graph.replay()
torch.testing.assert_close(captured, reference(), atol=1e-2, rtol=1e-2)
@@ -387,3 +387,22 @@ hidden width. Some kernels (Triton MXFP4) return no weights; `MoELayer` then
returns the precomputed route weights it passed in. FP16 inputs, ROCm builds
without the fused finalizer, and kernels without deferred finalize keep the
kernel's own finalized output.
## Optional Kimi-K3 front projections
`try_latent_moe_input_projections` runs a registered fused implementation or
returns `None` before any projection. This lets the runtime retain the
separate projections and their stream scheduling for unsupported inputs.
`latent_moe_input_projections` keeps its portable composition when no fused
implementation is available.
The FlashInfer front is enabled on SM103 with 152 SMs for 2048–16384 BF16
rows, Kimi-K3's replicated router/latent weights, full shared-expert weights,
and SiTU clamps 4 and 25. Attention-DP uses it only without shared-expert TP;
EP routing/quantization and the shared down projection keep their existing
owners. Smaller shapes and shared-expert TP retain their existing paths.
This optional backend requires the qualified 152-SM planner and the matching
CUDA source payload in FlashInfer. The unpatched 0.7.2 wheel lacks these and
does not enable the registration. Prepare/warm up before graph capture;
no persistent activation tensors are cached per layer by this adapter.
@@ -29,8 +29,13 @@ from typing import Any, Literal
import torch
from tokenspeed_kernel.platform import current_platform, pdl_enabled
from tokenspeed_kernel.profiling import ShapeCapture, kernel_scope
from tokenspeed_kernel.registry import KernelRegistry
from tokenspeed_kernel.selection import KernelPlan, NoKernelFoundError, select_kernel
from tokenspeed_kernel.registry import KernelRegistry, Priority
from tokenspeed_kernel.selection import (
KernelPlan,
NoKernelFoundError,
resolve_kernel_override,
select_kernel,
)
from tokenspeed_kernel.signature import (
dense_format_signature,
dense_tensor_format,
@@ -46,6 +51,7 @@ __all__ = [
"latent_moe_decode_pipeline_available",
"latent_moe_expert_shared",
"latent_moe_input_projections",
"try_latent_moe_input_projections",
"moe_apply",
"moe_plan",
"moe_process_weights",
@@ -343,6 +349,53 @@ def latent_moe_input_projections(
Returns:
``(router_logits, routed_input, shared_input)``.
"""
result = try_latent_moe_input_projections(
hidden_states,
router_weight,
routed_weight,
shared_gate_up_weight,
gate_clamp=gate_clamp,
up_clamp=up_clamp,
override=override,
solution=solution,
)
if result is not None:
return result
router_logits = torch.nn.functional.linear(
hidden_states.float(), router_weight.float()
)
routed_input = torch.nn.functional.linear(hidden_states, routed_weight)
shared_raw = torch.nn.functional.linear(hidden_states, shared_gate_up_weight)
gate, up = shared_raw.chunk(2, dim=-1)
gate_fp32 = gate.float()
up_fp32 = up.float()
gate_fp32 = gate_clamp * torch.tanh(gate_fp32 / gate_clamp)
gate_fp32 *= torch.sigmoid(gate.float())
if up_clamp is not None:
up_fp32 = up_clamp * torch.tanh(up_fp32 / up_clamp)
shared_input = (gate_fp32 * up_fp32).to(hidden_states.dtype)
return router_logits, routed_input, shared_input
def try_latent_moe_input_projections(
hidden_states: torch.Tensor,
router_weight: torch.Tensor,
routed_weight: torch.Tensor,
shared_gate_up_weight: torch.Tensor,
*,
gate_clamp: float,
up_clamp: float | None,
override: str | None = None,
solution: str | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None:
"""Run a fused input projection, or return None without projecting.
Arguments and outputs match :func:`latent_moe_input_projections`. A caller
that schedules separate projections can retain that scheduling when no
fused implementation supports the inputs. Automatic selection declines
correctness references; explicit backend requests are preserved.
"""
if hidden_states.ndim != 2 or hidden_states.shape[0] < 1:
raise ValueError("hidden_states must have shape [tokens, hidden_size]")
tokens, hidden_size = hidden_states.shape
@@ -379,7 +432,10 @@ def latent_moe_input_projections(
),
"weights_packed": _weights_packed(weights),
"hidden_size_multiple_64": hidden_size % 64 == 0,
"gate_clamp": gate_clamp,
"up_clamp": up_clamp,
}
override = resolve_kernel_override("moe", "latent_input", override)
try:
kernel = select_kernel(
"moe",
@@ -394,6 +450,12 @@ def latent_moe_input_projections(
raise
kernel = None
if kernel is not None and override is None and solution is None:
spec = KernelRegistry.get().get_by_name(kernel.name)
assert spec is not None
if spec.priority == Priority.REFERENCE:
return None
if kernel is not None:
ShapeCapture.get().record(
"moe",
@@ -418,20 +480,7 @@ def latent_moe_input_projections(
up_clamp=up_clamp,
)
router_logits = torch.nn.functional.linear(
hidden_states.float(), router_weight.float()
)
routed_input = torch.nn.functional.linear(hidden_states, routed_weight)
shared_raw = torch.nn.functional.linear(hidden_states, shared_gate_up_weight)
gate, up = shared_raw.chunk(2, dim=-1)
gate_fp32 = gate.float()
up_fp32 = up.float()
gate_fp32 = gate_clamp * torch.tanh(gate_fp32 / gate_clamp)
gate_fp32 *= torch.sigmoid(gate.float())
if up_clamp is not None:
up_fp32 = up_clamp * torch.tanh(up_fp32 / up_clamp)
shared_input = (gate_fp32 * up_fp32).to(hidden_states.dtype)
return router_logits, routed_input, shared_input
return None
# ===-----------------------------------------------------------------------===#
@@ -4258,3 +4258,71 @@ if not platform.is_nvidia:
) -> PreparedNvfp4Routing:
"""Split routing exists only for the NVIDIA flashinfer kernel."""
raise NotImplementedError("split routing needs the NVIDIA flashinfer NVFP4 MoE")
# ===-----------------------------------------------------------------------===#
# Kimi-K3 latent input projections
# ===-----------------------------------------------------------------------===#
if (
platform.is_nvidia
and platform.arch_version == ArchVersion(10, 3)
and platform.sm_count == 152
):
from tokenspeed_kernel.thirdparty.cuda.flashinfer_kimi_k3 import (
latent_front,
latent_front_available,
)
if latent_front_available():
@register_kernel(
"moe",
"latent_input",
name="flashinfer_latent_input",
solution="flashinfer",
capability=CapabilityRequirement(
min_arch_version=ArchVersion(10, 3),
max_arch_version=ArchVersion(10, 3),
vendors=frozenset({"nvidia"}),
),
signatures=format_signatures(
(
"hidden_states",
"router_weight",
"routed_weight",
"shared_gate_up_weight",
),
"dense",
{torch.bfloat16},
),
priority=Priority.SPECIALIZED,
traits={
"tokens_min": frozenset({2048}),
"tokens_max": frozenset({16384}),
"gate_clamp": frozenset({4.0}),
"hidden_size": frozenset({7168}),
"inputs_contiguous": frozenset({True}),
"latent_size": frozenset({3584}),
"num_experts": frozenset({896}),
"shared_size": frozenset({6144}),
"up_clamp": frozenset({25.0}),
},
)
def flashinfer_latent_input(
hidden_states: torch.Tensor,
router_weight: torch.Tensor,
routed_weight: torch.Tensor,
shared_gate_up_weight: torch.Tensor,
*,
gate_clamp: float,
up_clamp: float | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if gate_clamp != 4.0 or up_clamp != 25.0:
raise ValueError(
"FlashInfer Kimi-K3 front requires SiTU clamps 4 and 25"
)
return latent_front(
hidden_states, router_weight, routed_weight, shared_gate_up_weight
)
@@ -0,0 +1,75 @@
# Copyright (c) 2026 LightSeek Foundation
#
# 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.
"""Optional FlashInfer Kimi-K3 front projections with their source payload."""
from __future__ import annotations
import functools
from pathlib import Path
import torch
@functools.cache
def latent_front_available() -> bool:
try:
from flashinfer.experimental.kimi_k3_latent_moe import cake_jit
from flashinfer.experimental.kimi_k3_latent_moe.cake_backend import (
QUALIFIED_SM_COUNTS,
)
except ImportError:
return False
root = Path(cake_jit.__file__).parent / "csrc"
return (
152 in QUALIFIED_SM_COUNTS
and bool(cake_jit.MODULES)
and all(
(root / source).is_file()
for record in cake_jit.MODULES.values()
for source in record["sources"]
)
)
def latent_front(
hidden_states: torch.Tensor,
router_weight: torch.Tensor,
routed_weight: torch.Tensor,
shared_gate_up_weight: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
from flashinfer.kimi_k3_latent_moe import kimi_k3_latent_moe_front
rows = hidden_states.shape[0]
logits = torch.empty(
(rows, router_weight.shape[0]), device=hidden_states.device, dtype=torch.float32
)
routed = hidden_states.new_empty((rows, routed_weight.shape[0]))
shared = hidden_states.new_empty((rows, shared_gate_up_weight.shape[0] // 2))
return kimi_k3_latent_moe_front(
hidden_states,
router_weight,
routed_weight,
shared_gate_up_weight,
logits,
routed,
shared,
backend="cake",
)
@@ -0,0 +1,159 @@
# Copyright (c) 2026 LightSeek Foundation
#
# 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.
"""Kimi-K3 front fusion and its unsupported-input fallback."""
import math
import pytest
import torch
from tokenspeed_kernel.ops.moe import (
latent_moe_input_projections,
try_latent_moe_input_projections,
)
from tokenspeed_kernel.platform import ArchVersion, current_platform
from tokenspeed_kernel.selection import NoKernelFoundError, kernel_override
from tokenspeed_kernel.thirdparty.cuda.flashinfer_kimi_k3 import latent_front_available
@pytest.fixture(scope="module")
def weights():
platform = current_platform()
if (
not platform.is_nvidia
or platform.arch_version != ArchVersion(10, 3)
or platform.sm_count != 152
or not latent_front_available()
):
pytest.skip("requires the GB300 Kimi-K3 source bundle")
torch.manual_seed(621)
return tuple(
(torch.randn(rows, 7168, device="cuda") / math.sqrt(7168)).bfloat16()
for rows in (896, 3584, 12288)
)
def reference(x, weights):
router, latent, shared = weights
raw = torch.nn.functional.linear(x, shared)
gate, up = raw.float().chunk(2, dim=-1)
activated = (4.0 * torch.tanh(gate / 4.0) * torch.sigmoid(gate)) * (
25.0 * torch.tanh(up / 25.0)
)
return (
torch.nn.functional.linear(x.float(), router.float()),
torch.nn.functional.linear(x, latent),
activated.bfloat16(),
)
@pytest.mark.parametrize("rows", [2048, 2049, 4096, 8192])
def test_front_matches_reference_and_replays_changed_inputs(weights, rows):
torch.manual_seed(147 + rows)
x = torch.randn(rows, 7168, device="cuda", dtype=torch.bfloat16)
def run():
return latent_moe_input_projections(
x,
*weights,
gate_clamp=4.0,
up_clamp=25.0,
override="flashinfer_latent_input",
)
actual = run()
assert actual[0].dtype == torch.float32
for i, (value, expected) in enumerate(
zip(actual, reference(x, weights), strict=True)
):
tolerance = 1e-3 if i == 0 else 1e-2
torch.testing.assert_close(value, expected, atol=tolerance, rtol=tolerance)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
captured = run()
x.normal_(std=0.25)
graph.replay()
for i, (value, expected) in enumerate(
zip(captured, reference(x, weights), strict=True)
):
tolerance = 1e-3 if i == 0 else 1e-2
torch.testing.assert_close(value, expected, atol=tolerance, rtol=tolerance)
@pytest.mark.parametrize("rows", [1, 128, 1024, 2047, 16385])
def test_front_declines_unvalidated_rows(weights, rows):
x = torch.zeros(rows, 7168, device="cuda", dtype=torch.bfloat16)
assert (
try_latent_moe_input_projections(x, *weights, gate_clamp=4.0, up_clamp=25.0)
is None
)
assert torch.count_nonzero(x).item() == 0
with pytest.raises(NoKernelFoundError):
try_latent_moe_input_projections(
x,
*weights,
gate_clamp=4.0,
up_clamp=25.0,
solution="flashinfer",
)
@pytest.mark.parametrize("gate_clamp,up_clamp", [(1.0, 25.0), (4.0, None), (4.0, 1.0)])
def test_front_declines_other_activations(weights, gate_clamp, up_clamp):
x = torch.zeros(2048, 7168, device="cuda", dtype=torch.bfloat16)
assert (
try_latent_moe_input_projections(
x, *weights, gate_clamp=gate_clamp, up_clamp=up_clamp
)
is None
)
def test_front_declines_sharded_shared_experts(weights):
x = torch.zeros(2048, 7168, device="cuda", dtype=torch.bfloat16)
router, latent, shared = weights
shard = shared[:3072].clone()
assert (
try_latent_moe_input_projections(
x, router, latent, shard, gate_clamp=4.0, up_clamp=25.0
)
is None
)
def test_front_preserves_explicit_reference_override(weights):
from tokenspeed_kernel.numerics.torch.moe import torch_latent_input
x = torch.randn(1, 7168, device="cuda", dtype=torch.bfloat16) * 0.25
with kernel_override("moe", "latent_input", "torch_latent_input"):
actual = try_latent_moe_input_projections(
x, *weights, gate_clamp=4.0, up_clamp=25.0
)
expected = torch_latent_input(
hidden_states=x,
router_weight=weights[0],
routed_weight=weights[1],
shared_gate_up_weight=weights[2],
gate_clamp=4.0,
up_clamp=25.0,
)
for value, reference in zip(actual, expected, strict=True):
torch.testing.assert_close(value, reference, atol=0, rtol=0)