perf(kimi-k3): fuse large attention-DP input projections with vendored front programs (#3207)

## Summary

Brings the Kimi-K3 fused front projection (originally #2661, commit
d2d01d22) onto `main`, and makes it independent of which FlashInfer
wheel is installed by vendoring the kernel programs it needs.

### Fused front (cherry-pick of d2d01d22)

For qualified attention-DP shapes (SM100 or SM103 parts with 148 or 152
SMs, 2048 BF16 rows or more, full shared-expert weights), one fused
kernel computes the router logits, the latent projection, and the
shared-expert gate/up projection from the same hidden states instead of
three separate GEMMs. Unsupported shapes and packages keep the separate
projections; shared-down, routing, and EP ownership are unchanged.

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.

### Vendored front programs

The original change called `flashinfer.experimental.kimi_k3_latent_moe`.
FlashInfer release wheels from 0.7.3 on are built with
`FLASHINFER_WHEEL_EXCLUDE_EXPERIMENTAL_SOURCES=1`
(flashinfer-ai/flashinfer#8011) and leave the experimental kernel
sources out, so the front is unavailable with the pinned release wheel.

This PR carries the two generated programs the TP1 prefill front can
select (`front:i6144` and its `evict_first` variant) plus the host plan
rules of the same FlashInfer v0.7.3 route (commit 775207de) under
`tokenspeed-kernel/.../thirdparty/cuda/kimi3_latent_front/`, and builds
them through FlashInfer's JIT toolchain the same way the Kimi-K3 router
kernel is built. The kernel files are byte-identical to the FlashInfer
sources; `THIRDPARTYNOTICES` records the Apache-2.0 provenance. The
vendored snapshot does not depend on the installed FlashInfer version;
only a change to the JIT entry point or the tvm-ffi ABI would touch the
adapter.

The registration moves from the `flashinfer` solution to
`cuda_latent_input`. No FlashInfer version bump is required.

### Changes made during review

- **Row ceiling removed.** The front is registered for 2048 rows or more
with no upper bound. The plan rules cover any row count above the floor
(the stream-K split and the `evict_first` selection depend on the
pair-row count, which is at most 8 on 152-SM parts and 2 on 148-SM
parts), and the CUDA tests compare 2048 through 32768 rows.
- **SM gate relaxed from SM103/152 SMs to SM100 and SM103 with 148 or
152 SMs.** These are the SM counts the plan rules are validated for;
`kimi3_latent_front.available()` checks both, so the `b200v2` CI runners
(148 SMs) now exercise the front.
- **Stream ordering.** The fused front is enqueued before the
`StreamFork` scope in `_forward_attn_dp`. The scope records its fork
event at entry, so a branch is only ordered after work enqueued on the
main stream before that point, and the shared down projection on the
auxiliary branch reads the front's shared-expert activation. A runtime
test delays the front and checks the branch waits for it.
- **Small rows on NVIDIA.** `triton_latent_input_packed` is registered
for AMD only. On NVIDIA the separate vendor GEMM projections are faster
than the generic packed kernel, so below the front's row floor no fused
kernel matches and callers keep the separate projections. AMD selection
is unchanged (the kernel benchmark comparison is within budget).
- `__all__` of `ops/moe/cuda.py` only lists `cuda_latent_input` when the
front is registered.

## Changes

- `python/tokenspeed/runtime/models/kimi_k3.py`: select the fused front
through the registry for qualified shapes, ahead of the stream fork
scope.
- `tokenspeed-kernel/.../ops/moe/__init__.py`, `ops/moe/cuda.py`,
`ops/moe/triton.py`: `latent_input` op, the `cuda_latent_input`
registration (SM100/SM103, 148 or 152 SMs, 2048 tokens or more),
AMD-only registration of the packed Triton kernel.
- `tokenspeed-kernel/.../thirdparty/cuda/kimi3_latent_front.py`: plan
rules, JIT module build, control-word slab and workspace lanes,
CUDA-graph-safe runner.
- `tokenspeed-kernel/.../thirdparty/cuda/csrc/kimi3_latent_front/`: the
two vendored Cake programs and shared argument checks, with a README on
provenance and refresh.
- `setup.py`, `THIRDPARTYNOTICES`, `ops/moe/README.md`: package the
sources and document the route.

## Testing

-
`tokenspeed-kernel/test/nvidia/ops/moe/test_kimi3_latent_front_plan.py`
(CPU): plan rules pinned to the values FlashInfer's planner produces for
148 and 152 SMs, including the stream-K split and `evict_first`
selection, and refusal of rows or SM counts outside the vendored
programs.
-
`tokenspeed-kernel/test/nvidia/ops/moe/test_kimi3_latent_front_cuda.py`:
reference comparison against separate projections at 2048 through 32768
rows, CUDA-graph replay with changed inputs, and the small-row decline
for separate and packed weights.
- `test/runtime/test_kimi_k3_latent_front.py`: model-level selection and
fallback at 64 through 32768 rows with CUDA-graph capture and replay,
and the stream-ordering test for the shared down projection.
- GB300 (SM103, 152 SMs, FlashInfer 0.7.3 release wheel): 27 kernel
tests, 5 runtime tests, and the 14 `test/ops/moe/test_latent_input.py`
cases passed.
- GB200 (SM100, 152 SMs, FlashInfer 0.7.1rc2): 41 kernel tests
(including `test_latent_input.py`) and 5 runtime tests passed.
- B200 CI runners (SM100, 148 SMs): kernel and runtime front tests
passed.
- `pre-commit run --all-files`.

---------

Signed-off-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
Signed-off-by: bhsueh <11360707+byshiue@users.noreply.github.com>
Co-authored-by: Enwei Zhu <21126786+syuoni@users.noreply.github.com>
This commit is contained in:
bhsueh_NV
2026-11-13 12:04:09 +08:00
committed by GitHub
co-authored by Enwei Zhu
parent 49bd6a9c6f
commit 04ab2e08b6
16 changed files with 5922 additions and 22 deletions
+36 -5
View File
@@ -92,6 +92,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.moe._cute_dsl.latent_tail import multicast_backend_available
@@ -3148,6 +3149,26 @@ class KimiLinearMoE(nn.Module):
"Shared-expert communication must be prepared before forward"
)
# 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.
fused_inputs = None
if (
num_tokens > 0
and 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,
)
with self.stream_fork.scope(
enable=get_is_cuda_graph_phase(), overlap=get_is_capture_mode()
) as fork:
@@ -3162,8 +3183,12 @@ 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)
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,
@@ -3172,7 +3197,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:
@@ -3299,9 +3325,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
+279
View File
@@ -0,0 +1,279 @@
# 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 current_platform
from tokenspeed_kernel.thirdparty.cuda import kimi3_latent_front
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",
disabled_on_runners=["amd-*"],
disabled_on_runners_reason="the fused front and the CuTe DSL MegaMoE runner are NVIDIA-only",
)
from tokenspeed.runtime.configs.kimi_k3_config import KimiLinearConfig
from tokenspeed.runtime.distributed.mapping import Mapping
from tokenspeed.runtime.execution import forward_step
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
#: Largest row count the test drives through the block.
MAX_ROWS = 32768
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(MAX_ROWS, hidden_size, dtype=torch.bfloat16)
self.scales = torch.empty(MAX_ROWS, hidden_size // 16, dtype=torch.uint8)
self.ids = torch.empty(MAX_ROWS, top_k, dtype=torch.int64)
self.weights = torch.empty(MAX_ROWS, 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)
def build_layer(monkeypatch, *, alt_stream):
"""An attention-DP Kimi-K3 MoE block with packed projection weights."""
if not (current_platform().is_nvidia and kimi3_latent_front.available()):
pytest.skip("requires an SM100/SM103 part with 148 or 152 SMs")
# Imported after the skip: the CuTe DSL runner needs the NVIDIA toolchain.
from tokenspeed_kernel.thirdparty.cute_dsl.mega_moe import runner
monkeypatch.setattr(kimi_k3, "MoELayer", UnloadedExperts)
monkeypatch.setattr(runner, "get_runner", lambda plan, experts, **kwargs: 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=alt_stream,
)
finally:
torch.set_default_dtype(dtype)
# Weight loading packs the three projections into one tensor, which is
# what lets the generic packed kernels match the inputs.
layer.pack_input_projection_weights()
return layer
def forward_context(rows):
return 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],
)
def init_parameters(layer, rows):
torch.manual_seed(271 + rows)
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)
return hidden, prefix
@pytest.mark.parametrize("rows", [64, 2048, 8192, 32768])
def test_attention_dp_front_preserves_routing_and_output(monkeypatch, rows):
layer = build_layer(monkeypatch, alt_stream=None)
ctx = forward_context(rows)
with torch.no_grad():
hidden, prefix = init_parameters(layer, rows)
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,
)
# Below the fused front's row bound no fused kernel matches on NVIDIA
# (the generic packed Triton kernel is AMD-only), so the block keeps
# the separate projections.
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)
def test_attention_dp_shared_down_projection_waits_for_the_front(monkeypatch):
"""The auxiliary stream consumes the front's shared activation after it exists.
During the CUDA graph phase the shared down projection runs on the
auxiliary stream. Delaying the main stream right before the front makes a
missing dependency deterministic: the branch would then read the
activation buffer before the front wrote it.
"""
rows = 2048
layer = build_layer(monkeypatch, alt_stream=torch.cuda.Stream())
ctx = forward_context(rows)
monkeypatch.setattr(forward_step, "_is_cuda_graph_phase", True)
front = kimi_k3.try_latent_moe_input_projections
def delayed_front(*args, **kwargs):
torch.cuda._sleep(2_000_000_000)
return front(*args, **kwargs)
monkeypatch.setattr(kimi_k3, "try_latent_moe_input_projections", delayed_front)
with torch.no_grad():
hidden, prefix = init_parameters(layer, rows)
shared = layer.shared_experts(hidden, down_out=None)
logits, latent, activated = front(
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,
)
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]),
)
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)
expected = layer.routed_expert_up_proj.forward_add3(
routed, prefix, shared, norm_weight=None, eps=None
)
actual = layer(hidden, prefix, 2 * rows, rows, ctx, prefix_is_sharded=False)
torch.cuda.synchronize()
torch.testing.assert_close(actual, expected, atol=1e-2, rtol=1e-2)
@@ -89,6 +89,13 @@ The Kimi-K3 CUDA router derives from FlashInfer v0.7.2
(d84335d8c54e0c8f9f7e22faa15c7e34a58abf94), Copyright (c) 2026 NVIDIA CORPORATION.
It retains the routing computation and omits the expert-aligned plan.
The Kimi-K3 fused front projections (tokenspeed_kernel/thirdparty/cuda/csrc/kimi3_latent_front
and kimi3_latent_front.py) derive from FlashInfer v0.7.3
(775207deb34055667df89ed618fb4b06fc84de74), flashinfer/experimental/kimi_k3_latent_moe,
Copyright (c) 2026 by FlashInfer team. The generated programs are unchanged; the host
plan and launch binding retain the prefill front route of one rank with full shared
experts and omit the decode, sharded-shared-expert and tail routes.
Licensed under the Apache License, Version 2.0, whose full license text is available below.
Notice for fla-org/flash-linear-attention
+3
View File
@@ -1126,6 +1126,9 @@ setup(
"tokenspeed_kernel.thirdparty.cuda": [
"objs/**/*.so",
"csrc/kimi3_router.cu",
# Vendored FlashInfer/Cake Kimi-K3 front programs, JIT-built like the router.
"csrc/kimi3_latent_front/*.cu",
"csrc/kimi3_latent_front/*.h",
# Vendored Lamport protocol and FFI headers for the optional JIT extension.
"csrc/tvm_ffi_utils.h",
"csrc/include/**/*.h",
@@ -576,6 +576,34 @@ normalized FP32 weights (scale 1) and INT32 IDs into caller-owned buffers.
The routing-only kernel has no expert-plan workspace or 8,192-token limit.
Other contracts retain their existing routers.
## 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 generic packed Triton kernel
(`triton_latent_input_packed`) is registered on AMD only: on NVIDIA the
separate vendor GEMM projections are faster, so below the fused front's row
bound no fused kernel matches and the runtime keeps the separate path.
`cuda_latent_input` is the vendored FlashInfer/Cake fused front
(`thirdparty/cuda/kimi3_latent_front.py` and `csrc/kimi3_latent_front/`): one
persistent launch produces the FP32 router logits, the BF16 latent input and
the BF16 SiTU-activated shared-expert input. It is registered on SM100 and
SM103 parts with 148 or 152 SMs (the counts the plan rules are validated for)
for 2048 BF16 rows or more (no upper bound: the plan scales with the row
count), 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.
The programs are JIT-built through FlashInfer's toolchain like the Kimi-K3
router and do not depend on the FlashInfer package shipping its experimental
kernel sources (release wheels omit them). Prepare/warm up before graph capture;
no persistent activation tensors are cached per layer by this adapter.
## NVFP4 MegaMoE for Qwen3.5
The `mega_moe` NVFP4 adapter supports gated SiLU (`silu(gate) * up`) and
@@ -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,
@@ -48,6 +53,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",
@@ -350,6 +356,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
@@ -386,7 +439,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",
@@ -401,6 +457,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",
@@ -425,20 +487,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
# ===-----------------------------------------------------------------------===#
@@ -4,9 +4,15 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
from tokenspeed_kernel.platform import ArchVersion, CapabilityRequirement, pdl_enabled
from tokenspeed_kernel.platform import (
ArchVersion,
CapabilityRequirement,
current_platform,
pdl_enabled,
)
from tokenspeed_kernel.registry import Priority, register_kernel
from tokenspeed_kernel.signature import dense_tensor_format, format_signature
from tokenspeed_kernel.thirdparty.cuda import kimi3_latent_front
from tokenspeed_kernel.thirdparty.cuda.kimi3_router import sigmoid_bias_topk
from tokenspeed_kernel.thirdparty.cuda.moe import moe_finalize_fuse_shared
from tokenspeed_kernel.thirdparty.cuda.routing import (
@@ -157,3 +163,77 @@ __all__ = [
"cuda_kimi3_sigmoid_bias_topk",
"moe_finalize_fuse_shared",
]
# The vendored front serves SM100 and SM103 parts with the SM counts its plan
# rules are validated for (148 and 152); ``available`` checks both.
_FRONT_PLATFORM = current_platform()
if _FRONT_PLATFORM.is_nvidia and kimi3_latent_front.available():
@register_kernel(
"moe",
"latent_input",
name="cuda_latent_input",
solution="cuda",
capability=CapabilityRequirement(
min_arch_version=ArchVersion(10, 0),
max_arch_version=ArchVersion(10, 3),
vendors=frozenset({"nvidia"}),
),
signatures=frozenset(
{
format_signature(
hidden_states=dense_tensor_format(torch.bfloat16),
router_weight=dense_tensor_format(torch.bfloat16),
routed_weight=dense_tensor_format(torch.bfloat16),
shared_gate_up_weight=dense_tensor_format(torch.bfloat16),
)
}
),
priority=Priority.SPECIALIZED,
traits={
# The fused front pays off from 2048 rows; smaller batches keep the separate
# projections (see ops/moe/README.md, "Kimi-K3 front projections"). There is
# no upper bound: the plan scales with the row count.
"tokens_min": frozenset({2048}),
"gate_clamp": frozenset({4.0}),
"hidden_size": frozenset({kimi3_latent_front.HIDDEN}),
"inputs_contiguous": frozenset({True}),
"latent_size": frozenset({kimi3_latent_front.LATENT}),
"num_experts": frozenset({kimi3_latent_front.NUM_EXPERTS}),
"shared_size": frozenset({kimi3_latent_front.SHARED_INTERMEDIATE}),
"up_clamp": frozenset({25.0}),
},
)
def cuda_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]:
"""Fused Kimi-K3 router / latent / shared-input projections; see kimi3_latent_front."""
if gate_clamp != 4.0 or up_clamp != 25.0:
raise ValueError("the Kimi-K3 CUDA front requires SiTU clamps 4 and 25")
rows = hidden_states.shape[0]
logits = torch.empty(
(rows, router_weight.shape[0]),
device=hidden_states.device,
dtype=torch.float32,
)
latent = hidden_states.new_empty((rows, routed_weight.shape[0]))
shared_act = hidden_states.new_empty(
(rows, shared_gate_up_weight.shape[0] // 2)
)
return kimi3_latent_front.front(
hidden_states,
router_weight,
routed_weight,
shared_gate_up_weight,
logits,
latent,
shared_act,
)
__all__.append("cuda_latent_input")
@@ -979,6 +979,10 @@ register_kernel(
"latent_input",
name="triton_latent_input_packed",
solution="triton",
# AMD only: on NVIDIA the separate vendor GEMM projections are faster than
# this generic packed kernel, so no fused kernel is registered there below
# the specialized front's row bound and callers keep the separate path.
capability=CapabilityRequirement(vendors=frozenset({"amd"})),
signatures=frozenset(
{
format_signature(
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2026 by FlashInfer team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Host surface of the generated Cake launchers (``*_binding.cu``) for a package built without
// FlashInfer's csrc: the TVM-FFI / DLPack headers the launchers use, the named tensor-argument
// checks and the CUDA runtime version the library was compiled against.
#pragma once
#include <dlpack/dlpack.h>
#include <tvm/ffi/container/tensor.h>
#include <tvm/ffi/container/shape.h>
#include <tvm/ffi/dtype.h>
#include <tvm/ffi/error.h>
#include <tvm/ffi/extra/c_env_api.h>
#include <tvm/ffi/extra/cuda/base.h>
#include <tvm/ffi/extra/cuda/device_guard.h>
#include <tvm/ffi/function.h>
#include <cuda_runtime_api.h>
inline void check_cuda_tensor(const tvm::ffi::TensorView& t, const char* name) {
TVM_FFI_CHECK(t.device().device_type == kDLCUDA, ValueError)
<< name << " must be a CUDA tensor, got device_type=" << static_cast<int>(t.device().device_type);
}
inline void check_dtype(const tvm::ffi::TensorView& t, DLDataType expected, const char* name) {
DLDataType d = t.dtype();
TVM_FFI_CHECK(d.code == expected.code && d.bits == expected.bits && d.lanes == expected.lanes, TypeError)
<< name << " dtype mismatch: expected DLDataType(code=" << static_cast<int>(expected.code)
<< ", bits=" << static_cast<int>(expected.bits) << ", lanes=" << static_cast<int>(expected.lanes)
<< "), got (code=" << static_cast<int>(d.code) << ", bits=" << static_cast<int>(d.bits)
<< ", lanes=" << static_cast<int>(d.lanes) << ")";
}
inline void check_contiguous(const tvm::ffi::TensorView& t, const char* name) {
TVM_FFI_CHECK(t.IsContiguous(), ValueError) << name << " must be contiguous";
}
inline void check_same_device(const tvm::ffi::TensorView& t, const tvm::ffi::TensorView& reference,
const char* name, const char* reference_name) {
TVM_FFI_CHECK(t.device().device_type == reference.device().device_type &&
t.device().device_id == reference.device().device_id,
ValueError)
<< name << " must be on the same device as " << reference_name << ": got device_type="
<< static_cast<int>(t.device().device_type) << " id=" << t.device().device_id
<< " versus device_type=" << static_cast<int>(reference.device().device_type)
<< " id=" << reference.device().device_id;
}
// Require the dimensions above the last `trailing` dimensions to form one dense
// row-major chain, so they can be folded into a single logical dimension whose
// step is stride(-(trailing + 1)). Shape products are stride-independent, so
// this verifies the physical layout instead of inventing a folded stride.
inline void check_dense_leading_dims(const tvm::ffi::TensorView& t, int trailing, const char* name) {
TVM_FFI_CHECK(trailing > 0 && t.ndim() >= trailing, ValueError)
<< name << " cannot fold leading dimensions above " << trailing << " trailing dims from ndim=" << t.ndim();
int outer_last = t.ndim() - trailing - 1;
if (outer_last <= 0) {
return;
}
int64_t step = t.stride(outer_last);
TVM_FFI_CHECK(step > 0, ValueError) << name << " physical strides must be positive";
int64_t expected = step;
for (int axis = outer_last - 1; axis >= 0; --axis) {
expected *= t.size(axis + 1);
if (t.size(axis) > 1) {
TVM_FFI_CHECK(t.stride(axis) == expected, ValueError)
<< name << " leading dims are not physically foldable above " << trailing
<< " trailing dims: stride(" << axis << ")=" << t.stride(axis) << ", expected " << expected;
}
}
}
// The CUDA runtime this library was compiled against (``CUDART_VERSION``, e.g. 13000 for 13.0); every
// binding exports it as ``build_cuda_version`` so the package loader can compare it with the prebuilt
// sidecar before the first launch.
inline int64_t cake_ffi_build_cuda_version() { return CUDART_VERSION; }
@@ -0,0 +1,339 @@
/*
* Copyright (c) 2026 by FlashInfer team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by Cake: the tvm-ffi host binding of kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9, for the device source that defines it. Do not edit.
#include <cuda_runtime.h>
#include <cuda.h>
#include <cuda_bf16.h>
#include "cake_ffi_checks.h"
#include <cstdint>
extern "C" __global__ void kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9(const __grid_constant__ CUtensorMap A, const __grid_constant__ CUtensorMap WG, const __grid_constant__ CUtensorMap WD, const __grid_constant__ CUtensorMap WS, float* __restrict__ logits, __nv_bfloat16* __restrict__ latent, __nv_bfloat16* __restrict__ shared_act, float* __restrict__ ws, int* __restrict__ counters, int M, int m_tiles, int num_items, int full_items, int sk_ipc, int sk_max_seg, int sk_total);
namespace cake_binding_kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9 {
using tvm::ffi::TensorView;
constexpr const char* KERNEL_NAME = "kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9";
void CheckCuda(cudaError_t status, const char* what) {
TVM_FFI_CHECK(status == cudaSuccess, RuntimeError)
<< KERNEL_NAME << ": " << what << " failed: " << cudaGetErrorString(status);
}
void CheckCu(CUresult result, const char* what) {
if (result != CUDA_SUCCESS) {
const char* name = nullptr;
const char* message = nullptr;
cuGetErrorName(result, &name);
cuGetErrorString(result, &message);
TVM_FFI_THROW(RuntimeError) << KERNEL_NAME << ": " << what << " failed with "
<< (name ? name : "an unknown CUresult") << " (" << static_cast<int>(result)
<< "): " << (message ? message : "");
}
}
void* DataPtr(const TensorView& t) { return static_cast<char*>(t.data_ptr()) + t.byte_offset(); }
void CheckUnitInnerStride(const TensorView& t, const char* name) {
TVM_FFI_CHECK(t.stride(-1) == 1, ValueError)
<< KERNEL_NAME << ": '" << name << "' needs a unit innermost stride, got " << t.stride(-1);
}
// The product of the extents above the trailing `trailing` dims.
int64_t NumelAbove(const TensorView& t, int trailing) {
int64_t product = 1;
for (int axis = 0; axis < t.ndim() - trailing; ++axis) product *= t.size(axis);
return product;
}
[[noreturn]] void NoInt64(int64_t a, const char* op, int64_t b) {
TVM_FFI_THROW(ValueError) << KERNEL_NAME << ": " << a << " " << op << " " << b
<< " has no int64 value in a host check";
}
int64_t CDiv(int64_t a, int64_t b) {
if (b == 0 || (a == INT64_MIN && b == -1)) NoInt64(a, "/", b);
return a / b;
}
int64_t CMod(int64_t a, int64_t b) {
if (b == 0) NoInt64(a, "%", b);
return b == -1 ? 0 : a % b;
}
cuuint64_t Extent(int64_t value, const char* descriptor) {
TVM_FFI_CHECK(value > 0, ValueError)
<< KERNEL_NAME << ": an extent of descriptor '" << descriptor << "' resolves to " << value;
return static_cast<cuuint64_t>(value);
}
cuuint64_t Stride(int64_t value, const char* descriptor) {
TVM_FFI_CHECK(value >= 0, ValueError)
<< KERNEL_NAME << ": a stride of descriptor '" << descriptor << "' resolves to " << value;
return static_cast<cuuint64_t>(value);
}
CUtensorMap EncodeTma_A(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'A' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "A");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "A");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'A' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "A"), Extent(outer1, "A"), Extent(CDiv(d1, 64LL), "A")};
cuuint64_t global_strides[2] = {Stride(s2, "A"), Stride(128LL, "A")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, true, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'A' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'A' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'A' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of A");
return map;
}
CUtensorMap EncodeTma_WG(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'WG' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "WG");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "WG");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'WG' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "WG"), Extent(outer1, "WG"), Extent(CDiv(d1, 64LL), "WG")};
cuuint64_t global_strides[2] = {Stride(s2, "WG"), Stride(128LL, "WG")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, false, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'WG' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'WG' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'WG' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of WG");
return map;
}
CUtensorMap EncodeTma_WD(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'WD' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "WD");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "WD");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'WD' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "WD"), Extent(outer1, "WD"), Extent(CDiv(d1, 64LL), "WD")};
cuuint64_t global_strides[2] = {Stride(s2, "WD"), Stride(128LL, "WD")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, false, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'WD' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'WD' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'WD' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of WD");
return map;
}
CUtensorMap EncodeTma_WS(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'WS' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "WS");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "WS");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'WS' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "WS"), Extent(outer1, "WS"), Extent(CDiv(d1, 64LL), "WS")};
cuuint64_t global_strides[2] = {Stride(s2, "WS"), Stride(128LL, "WS")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, false, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'WS' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'WS' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'WS' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of WS");
return map;
}
void Run(TensorView a_A, TensorView a_WG, TensorView a_WD, TensorView a_WS, TensorView a_logits, TensorView a_latent, TensorView a_shared_act, TensorView a_ws, TensorView a_counters, int64_t a_M, int64_t a_m_tiles, int64_t a_num_items, int64_t a_full_items, int64_t a_sk_ipc, int64_t a_sk_max_seg, int64_t a_sk_total, int64_t grid_x, int64_t grid_y, int64_t grid_z) {
DLDevice dev = a_A.device();
tvm::ffi::CUDADeviceGuard device_guard(dev.device_id);
check_cuda_tensor(a_A, "A");
check_dtype(a_A, DLDataType{kDLBfloat, 16, 1}, "A");
check_cuda_tensor(a_WG, "WG");
check_dtype(a_WG, DLDataType{kDLBfloat, 16, 1}, "WG");
check_cuda_tensor(a_WD, "WD");
check_dtype(a_WD, DLDataType{kDLBfloat, 16, 1}, "WD");
check_cuda_tensor(a_WS, "WS");
check_dtype(a_WS, DLDataType{kDLBfloat, 16, 1}, "WS");
check_cuda_tensor(a_logits, "logits");
check_dtype(a_logits, DLDataType{kDLFloat, 32, 1}, "logits");
check_cuda_tensor(a_latent, "latent");
check_dtype(a_latent, DLDataType{kDLBfloat, 16, 1}, "latent");
check_cuda_tensor(a_shared_act, "shared_act");
check_dtype(a_shared_act, DLDataType{kDLBfloat, 16, 1}, "shared_act");
check_cuda_tensor(a_ws, "ws");
check_dtype(a_ws, DLDataType{kDLFloat, 32, 1}, "ws");
check_cuda_tensor(a_counters, "counters");
check_dtype(a_counters, DLDataType{kDLInt, 32, 1}, "counters");
TVM_FFI_CHECK(a_M >= -2147483648LL && a_M <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'M' = " << a_M
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_m_tiles >= -2147483648LL && a_m_tiles <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'm_tiles' = " << a_m_tiles
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_num_items >= -2147483648LL && a_num_items <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'num_items' = " << a_num_items
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_full_items >= -2147483648LL && a_full_items <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'full_items' = " << a_full_items
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_sk_ipc >= -2147483648LL && a_sk_ipc <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'sk_ipc' = " << a_sk_ipc
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_sk_max_seg >= -2147483648LL && a_sk_max_seg <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'sk_max_seg' = " << a_sk_max_seg
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_sk_total >= -2147483648LL && a_sk_total <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'sk_total' = " << a_sk_total
<< " is outside the i32 range [-2147483648, 2147483647]";
check_same_device(a_WG, a_A, "WG", "A");
check_same_device(a_WD, a_A, "WD", "A");
check_same_device(a_WS, a_A, "WS", "A");
check_contiguous(a_logits, "logits");
check_same_device(a_logits, a_A, "logits", "A");
check_contiguous(a_latent, "latent");
check_same_device(a_latent, a_A, "latent", "A");
check_contiguous(a_shared_act, "shared_act");
check_same_device(a_shared_act, a_A, "shared_act", "A");
check_contiguous(a_ws, "ws");
check_same_device(a_ws, a_A, "ws", "A");
check_contiguous(a_counters, "counters");
check_same_device(a_counters, a_A, "counters", "A");
TVM_FFI_CHECK(grid_x > 0 && grid_y > 0 && grid_z > 0, ValueError)
<< KERNEL_NAME << ": the grid (" << grid_x << ", " << grid_y << ", " << grid_z << ") must be positive";
TVM_FFI_CHECK(grid_x <= 2147483647 && grid_y <= 65535 && grid_z <= 65535, ValueError)
<< KERNEL_NAME << ": the grid (" << grid_x << ", " << grid_y << ", " << grid_z << ") exceeds CUDA's limits";
TVM_FFI_CHECK(grid_x % 2 == 0 && grid_y % 1 == 0 && grid_z % 1 == 0, ValueError)
<< KERNEL_NAME << ": the grid (" << grid_x << ", " << grid_y << ", " << grid_z
<< ") is not a multiple of the cluster shape (2, 1, 1)";
cudaStream_t stream = static_cast<cudaStream_t>(TVMFFIEnvGetStream(dev.device_type, dev.device_id));
{
// Once per thread per device: the kernel's function attributes hold per device; the tensor-map encoders need this thread's context of the device bound.
static thread_local uint64_t prepared_devices = 0;
const uint64_t device_bit = dev.device_id < 64 ? uint64_t{1} << dev.device_id : uint64_t{0};
if (device_bit == 0 || (prepared_devices & device_bit) == 0) {
CheckCuda(cudaSetDevice(dev.device_id), "cudaSetDevice");
CheckCuda(cudaFuncSetAttribute(reinterpret_cast<const void*>(kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9), cudaFuncAttributeMaxDynamicSharedMemorySize, 230528), "cudaFuncSetAttribute");
prepared_devices |= device_bit;
}
}
CUtensorMap v_A = EncodeTma_A(a_A);
CUtensorMap v_WG = EncodeTma_WG(a_WG);
CUtensorMap v_WD = EncodeTma_WD(a_WD);
CUtensorMap v_WS = EncodeTma_WS(a_WS);
void* v_logits = DataPtr(a_logits);
void* v_latent = DataPtr(a_latent);
void* v_shared_act = DataPtr(a_shared_act);
void* v_ws = DataPtr(a_ws);
void* v_counters = DataPtr(a_counters);
int32_t v_M = static_cast<int32_t>(a_M);
int32_t v_m_tiles = static_cast<int32_t>(a_m_tiles);
int32_t v_num_items = static_cast<int32_t>(a_num_items);
int32_t v_full_items = static_cast<int32_t>(a_full_items);
int32_t v_sk_ipc = static_cast<int32_t>(a_sk_ipc);
int32_t v_sk_max_seg = static_cast<int32_t>(a_sk_max_seg);
int32_t v_sk_total = static_cast<int32_t>(a_sk_total);
void* kernel_args[] = {&v_A, &v_WG, &v_WD, &v_WS, &v_logits, &v_latent, &v_shared_act, &v_ws, &v_counters, &v_M, &v_m_tiles, &v_num_items, &v_full_items, &v_sk_ipc, &v_sk_max_seg, &v_sk_total};
cudaLaunchConfig_t config{};
config.gridDim = dim3(static_cast<unsigned>(grid_x), static_cast<unsigned>(grid_y), static_cast<unsigned>(grid_z));
config.blockDim = dim3(320, 1, 1);
config.dynamicSmemBytes = 230528;
config.stream = stream;
cudaLaunchAttribute attrs[2] = {};
attrs[0].id = cudaLaunchAttributeClusterDimension;
attrs[0].val.clusterDim.x = 2;
attrs[0].val.clusterDim.y = 1;
attrs[0].val.clusterDim.z = 1;
attrs[1].id = cudaLaunchAttributeClusterSchedulingPolicyPreference;
attrs[1].val.clusterSchedulingPolicyPreference = cudaClusterSchedulingPolicySpread;
config.attrs = attrs;
config.numAttrs = 2;
CheckCuda(cudaLaunchKernelExC(&config, reinterpret_cast<const void*>(kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9), kernel_args),
"cudaLaunchKernelExC");
}
} // namespace cake_binding_kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9
TVM_FFI_DLL_EXPORT_TYPED_FUNC(run, cake_binding_kernel_cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9::Run);
TVM_FFI_DLL_EXPORT_TYPED_FUNC(build_cuda_version, cake_ffi_build_cuda_version);
@@ -0,0 +1,339 @@
/*
* Copyright (c) 2026 by FlashInfer team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by Cake: the tvm-ffi host binding of kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac, for the device source that defines it. Do not edit.
#include <cuda_runtime.h>
#include <cuda.h>
#include <cuda_bf16.h>
#include "cake_ffi_checks.h"
#include <cstdint>
extern "C" __global__ void kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac(const __grid_constant__ CUtensorMap A, const __grid_constant__ CUtensorMap WG, const __grid_constant__ CUtensorMap WD, const __grid_constant__ CUtensorMap WS, float* __restrict__ logits, __nv_bfloat16* __restrict__ latent, __nv_bfloat16* __restrict__ shared_act, float* __restrict__ ws, int* __restrict__ counters, int M, int m_tiles, int num_items, int full_items, int sk_ipc, int sk_max_seg, int sk_total);
namespace cake_binding_kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac {
using tvm::ffi::TensorView;
constexpr const char* KERNEL_NAME = "kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac";
void CheckCuda(cudaError_t status, const char* what) {
TVM_FFI_CHECK(status == cudaSuccess, RuntimeError)
<< KERNEL_NAME << ": " << what << " failed: " << cudaGetErrorString(status);
}
void CheckCu(CUresult result, const char* what) {
if (result != CUDA_SUCCESS) {
const char* name = nullptr;
const char* message = nullptr;
cuGetErrorName(result, &name);
cuGetErrorString(result, &message);
TVM_FFI_THROW(RuntimeError) << KERNEL_NAME << ": " << what << " failed with "
<< (name ? name : "an unknown CUresult") << " (" << static_cast<int>(result)
<< "): " << (message ? message : "");
}
}
void* DataPtr(const TensorView& t) { return static_cast<char*>(t.data_ptr()) + t.byte_offset(); }
void CheckUnitInnerStride(const TensorView& t, const char* name) {
TVM_FFI_CHECK(t.stride(-1) == 1, ValueError)
<< KERNEL_NAME << ": '" << name << "' needs a unit innermost stride, got " << t.stride(-1);
}
// The product of the extents above the trailing `trailing` dims.
int64_t NumelAbove(const TensorView& t, int trailing) {
int64_t product = 1;
for (int axis = 0; axis < t.ndim() - trailing; ++axis) product *= t.size(axis);
return product;
}
[[noreturn]] void NoInt64(int64_t a, const char* op, int64_t b) {
TVM_FFI_THROW(ValueError) << KERNEL_NAME << ": " << a << " " << op << " " << b
<< " has no int64 value in a host check";
}
int64_t CDiv(int64_t a, int64_t b) {
if (b == 0 || (a == INT64_MIN && b == -1)) NoInt64(a, "/", b);
return a / b;
}
int64_t CMod(int64_t a, int64_t b) {
if (b == 0) NoInt64(a, "%", b);
return b == -1 ? 0 : a % b;
}
cuuint64_t Extent(int64_t value, const char* descriptor) {
TVM_FFI_CHECK(value > 0, ValueError)
<< KERNEL_NAME << ": an extent of descriptor '" << descriptor << "' resolves to " << value;
return static_cast<cuuint64_t>(value);
}
cuuint64_t Stride(int64_t value, const char* descriptor) {
TVM_FFI_CHECK(value >= 0, ValueError)
<< KERNEL_NAME << ": a stride of descriptor '" << descriptor << "' resolves to " << value;
return static_cast<cuuint64_t>(value);
}
CUtensorMap EncodeTma_A(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'A' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "A");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "A");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'A' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "A"), Extent(outer1, "A"), Extent(CDiv(d1, 64LL), "A")};
cuuint64_t global_strides[2] = {Stride(s2, "A"), Stride(128LL, "A")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, true, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'A' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'A' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'A' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of A");
return map;
}
CUtensorMap EncodeTma_WG(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'WG' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "WG");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "WG");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'WG' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "WG"), Extent(outer1, "WG"), Extent(CDiv(d1, 64LL), "WG")};
cuuint64_t global_strides[2] = {Stride(s2, "WG"), Stride(128LL, "WG")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, false, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'WG' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'WG' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'WG' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of WG");
return map;
}
CUtensorMap EncodeTma_WD(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'WD' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "WD");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "WD");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'WD' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "WD"), Extent(outer1, "WD"), Extent(CDiv(d1, 64LL), "WD")};
cuuint64_t global_strides[2] = {Stride(s2, "WD"), Stride(128LL, "WD")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, false, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'WD' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'WD' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'WD' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of WD");
return map;
}
CUtensorMap EncodeTma_WS(const TensorView& t) {
TVM_FFI_CHECK(t.ndim() >= 2, ValueError)
<< KERNEL_NAME << ": descriptor 'WS' takes a source of at least 2 dims, got " << t.ndim();
CheckUnitInnerStride(t, "WS");
int64_t d1 = t.size(-1);
int64_t outer1 = NumelAbove(t, 1);
check_dense_leading_dims(t, 1, "WS");
int64_t s2 = t.stride(-2) * 2;
TVM_FFI_CHECK((CMod(d1, 64LL) == 0LL), ValueError)
<< KERNEL_NAME << ": descriptor 'WS' requires (CMod(d1, 64) == 0)";
cuuint64_t global_dim[3] = {Extent(64LL, "WS"), Extent(outer1, "WS"), Extent(CDiv(d1, 64LL), "WS")};
cuuint64_t global_strides[2] = {Stride(s2, "WS"), Stride(128LL, "WS")};
cuuint32_t box_dim[3] = {64u, 128u, 1u};
cuuint32_t elem_strides[3] = {1u, 1u, 1u};
const bool allow_oob_box[3] = {false, false, false};
for (int axis = 0; axis < 3; ++axis) {
TVM_FFI_CHECK(allow_oob_box[axis] || box_dim[axis] <= global_dim[axis], ValueError)
<< KERNEL_NAME << ": descriptor 'WS' axis " << axis << " (0 is the innermost) has a TMA box of "
<< box_dim[axis] << " elements but the source extent along it is " << global_dim[axis]
<< ". A box may not exceed its extent unless the axis is listed in the descriptor's allow_oob_box (CK.describe_tma(..., allow_oob_box=(axis,))). List it when the box is a tile that may run past the end of the axis, a tail tile: a load fills the part past the extent with zeros (its bytes still count toward the barrier's transaction) and a store or reduce skips it, so that is safe when the kernel ignores or masks those rows and columns. If the box was meant to fit, box_dim or the extent is wrong: check box_dim, global_dim and the tensor's shape";
}
TVM_FFI_CHECK(global_strides[0] % 16 == 0 && global_strides[1] % 16 == 0, ValueError)
<< KERNEL_NAME << ": the strides of descriptor 'WS' must be multiples of 16 bytes";
void* address = DataPtr(t);
TVM_FFI_CHECK(reinterpret_cast<uintptr_t>(address) % 16 == 0, ValueError)
<< KERNEL_NAME << ": the address of descriptor 'WS' must be 16-byte aligned";
CUtensorMap map{};
CheckCu(cuTensorMapEncodeTiled(&map, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 3, address, global_dim, global_strides,
box_dim, elem_strides, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B,
CU_TENSOR_MAP_L2_PROMOTION_NONE, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE),
"cuTensorMapEncodeTiled of WS");
return map;
}
void Run(TensorView a_A, TensorView a_WG, TensorView a_WD, TensorView a_WS, TensorView a_logits, TensorView a_latent, TensorView a_shared_act, TensorView a_ws, TensorView a_counters, int64_t a_M, int64_t a_m_tiles, int64_t a_num_items, int64_t a_full_items, int64_t a_sk_ipc, int64_t a_sk_max_seg, int64_t a_sk_total, int64_t grid_x, int64_t grid_y, int64_t grid_z) {
DLDevice dev = a_A.device();
tvm::ffi::CUDADeviceGuard device_guard(dev.device_id);
check_cuda_tensor(a_A, "A");
check_dtype(a_A, DLDataType{kDLBfloat, 16, 1}, "A");
check_cuda_tensor(a_WG, "WG");
check_dtype(a_WG, DLDataType{kDLBfloat, 16, 1}, "WG");
check_cuda_tensor(a_WD, "WD");
check_dtype(a_WD, DLDataType{kDLBfloat, 16, 1}, "WD");
check_cuda_tensor(a_WS, "WS");
check_dtype(a_WS, DLDataType{kDLBfloat, 16, 1}, "WS");
check_cuda_tensor(a_logits, "logits");
check_dtype(a_logits, DLDataType{kDLFloat, 32, 1}, "logits");
check_cuda_tensor(a_latent, "latent");
check_dtype(a_latent, DLDataType{kDLBfloat, 16, 1}, "latent");
check_cuda_tensor(a_shared_act, "shared_act");
check_dtype(a_shared_act, DLDataType{kDLBfloat, 16, 1}, "shared_act");
check_cuda_tensor(a_ws, "ws");
check_dtype(a_ws, DLDataType{kDLFloat, 32, 1}, "ws");
check_cuda_tensor(a_counters, "counters");
check_dtype(a_counters, DLDataType{kDLInt, 32, 1}, "counters");
TVM_FFI_CHECK(a_M >= -2147483648LL && a_M <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'M' = " << a_M
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_m_tiles >= -2147483648LL && a_m_tiles <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'm_tiles' = " << a_m_tiles
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_num_items >= -2147483648LL && a_num_items <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'num_items' = " << a_num_items
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_full_items >= -2147483648LL && a_full_items <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'full_items' = " << a_full_items
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_sk_ipc >= -2147483648LL && a_sk_ipc <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'sk_ipc' = " << a_sk_ipc
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_sk_max_seg >= -2147483648LL && a_sk_max_seg <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'sk_max_seg' = " << a_sk_max_seg
<< " is outside the i32 range [-2147483648, 2147483647]";
TVM_FFI_CHECK(a_sk_total >= -2147483648LL && a_sk_total <= 2147483647LL, ValueError)
<< KERNEL_NAME << ": 'sk_total' = " << a_sk_total
<< " is outside the i32 range [-2147483648, 2147483647]";
check_same_device(a_WG, a_A, "WG", "A");
check_same_device(a_WD, a_A, "WD", "A");
check_same_device(a_WS, a_A, "WS", "A");
check_contiguous(a_logits, "logits");
check_same_device(a_logits, a_A, "logits", "A");
check_contiguous(a_latent, "latent");
check_same_device(a_latent, a_A, "latent", "A");
check_contiguous(a_shared_act, "shared_act");
check_same_device(a_shared_act, a_A, "shared_act", "A");
check_contiguous(a_ws, "ws");
check_same_device(a_ws, a_A, "ws", "A");
check_contiguous(a_counters, "counters");
check_same_device(a_counters, a_A, "counters", "A");
TVM_FFI_CHECK(grid_x > 0 && grid_y > 0 && grid_z > 0, ValueError)
<< KERNEL_NAME << ": the grid (" << grid_x << ", " << grid_y << ", " << grid_z << ") must be positive";
TVM_FFI_CHECK(grid_x <= 2147483647 && grid_y <= 65535 && grid_z <= 65535, ValueError)
<< KERNEL_NAME << ": the grid (" << grid_x << ", " << grid_y << ", " << grid_z << ") exceeds CUDA's limits";
TVM_FFI_CHECK(grid_x % 2 == 0 && grid_y % 1 == 0 && grid_z % 1 == 0, ValueError)
<< KERNEL_NAME << ": the grid (" << grid_x << ", " << grid_y << ", " << grid_z
<< ") is not a multiple of the cluster shape (2, 1, 1)";
cudaStream_t stream = static_cast<cudaStream_t>(TVMFFIEnvGetStream(dev.device_type, dev.device_id));
{
// Once per thread per device: the kernel's function attributes hold per device; the tensor-map encoders need this thread's context of the device bound.
static thread_local uint64_t prepared_devices = 0;
const uint64_t device_bit = dev.device_id < 64 ? uint64_t{1} << dev.device_id : uint64_t{0};
if (device_bit == 0 || (prepared_devices & device_bit) == 0) {
CheckCuda(cudaSetDevice(dev.device_id), "cudaSetDevice");
CheckCuda(cudaFuncSetAttribute(reinterpret_cast<const void*>(kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac), cudaFuncAttributeMaxDynamicSharedMemorySize, 230528), "cudaFuncSetAttribute");
prepared_devices |= device_bit;
}
}
CUtensorMap v_A = EncodeTma_A(a_A);
CUtensorMap v_WG = EncodeTma_WG(a_WG);
CUtensorMap v_WD = EncodeTma_WD(a_WD);
CUtensorMap v_WS = EncodeTma_WS(a_WS);
void* v_logits = DataPtr(a_logits);
void* v_latent = DataPtr(a_latent);
void* v_shared_act = DataPtr(a_shared_act);
void* v_ws = DataPtr(a_ws);
void* v_counters = DataPtr(a_counters);
int32_t v_M = static_cast<int32_t>(a_M);
int32_t v_m_tiles = static_cast<int32_t>(a_m_tiles);
int32_t v_num_items = static_cast<int32_t>(a_num_items);
int32_t v_full_items = static_cast<int32_t>(a_full_items);
int32_t v_sk_ipc = static_cast<int32_t>(a_sk_ipc);
int32_t v_sk_max_seg = static_cast<int32_t>(a_sk_max_seg);
int32_t v_sk_total = static_cast<int32_t>(a_sk_total);
void* kernel_args[] = {&v_A, &v_WG, &v_WD, &v_WS, &v_logits, &v_latent, &v_shared_act, &v_ws, &v_counters, &v_M, &v_m_tiles, &v_num_items, &v_full_items, &v_sk_ipc, &v_sk_max_seg, &v_sk_total};
cudaLaunchConfig_t config{};
config.gridDim = dim3(static_cast<unsigned>(grid_x), static_cast<unsigned>(grid_y), static_cast<unsigned>(grid_z));
config.blockDim = dim3(320, 1, 1);
config.dynamicSmemBytes = 230528;
config.stream = stream;
cudaLaunchAttribute attrs[2] = {};
attrs[0].id = cudaLaunchAttributeClusterDimension;
attrs[0].val.clusterDim.x = 2;
attrs[0].val.clusterDim.y = 1;
attrs[0].val.clusterDim.z = 1;
attrs[1].id = cudaLaunchAttributeClusterSchedulingPolicyPreference;
attrs[1].val.clusterSchedulingPolicyPreference = cudaClusterSchedulingPolicySpread;
config.attrs = attrs;
config.numAttrs = 2;
CheckCuda(cudaLaunchKernelExC(&config, reinterpret_cast<const void*>(kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac), kernel_args),
"cudaLaunchKernelExC");
}
} // namespace cake_binding_kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac
TVM_FFI_DLL_EXPORT_TYPED_FUNC(run, cake_binding_kernel_cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac::Run);
TVM_FFI_DLL_EXPORT_TYPED_FUNC(build_cuda_version, cake_ffi_build_cuda_version);
@@ -0,0 +1,623 @@
# 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.
"""Vendored FlashInfer/Cake Kimi-K3 fused front projections (prefill, TP1).
One persistent launch computes, for ``M`` BF16 rows of width 7168, the FP32
router logits over 896 experts, the BF16 latent projection (3584 wide) and the
BF16 SiTU-activated shared-expert input (6144 wide, full shared experts). The
generated programs under ``csrc/kimi3_latent_front/`` are unchanged copies from
FlashInfer v0.7.3's ``flashinfer.experimental.kimi_k3_latent_moe`` (provenance in
``THIRDPARTYNOTICES``), and the host plan rules below are those of the same
version. Release wheels of FlashInfer do not ship the experimental kernel
sources, so they live here and are compiled through FlashInfer's JIT toolchain
like ``kimi3_router``.
Scope: the prefill front route of one rank holding the full shared experts
(``shared_gate_up_weight`` of ``2 * 6144`` rows) for 513 rows or more on
148- and 152-SM SM100/SM103 parts. Rows of at most 512 would take programs
that are not vendored (the decode front and the 224-wide tile); the
sharded-shared-expert (TP8) programs are not vendored either. There is no
upper row bound: the row count is a runtime argument, the plan rules scale
with the tile count, and the programs index rows in 64-bit.
"""
from __future__ import annotations
import functools
import threading
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable
import torch
HIDDEN = 7168
LATENT = 3584
NUM_EXPERTS = 896
SHARED_INTERMEDIATE = 6144
#: Compute capabilities the programs are compiled for.
SUPPORTED_COMPUTE_CAPABILITIES = {(10, 0): "sm_100a", (10, 3): "sm_103a"}
#: Physical SM counts the plan rules were validated on: 148 (B200, B300) and 152 (GB200, GB300).
QUALIFIED_SM_COUNTS = (148, 152)
#: Smallest row count the vendored programs serve; see the module docstring.
MIN_TOKENS = 513
# Tile geometry of the front GEMM programs.
BLOCK_M = 128
FRONT_BLOCK_N = 256
CTA_GROUP = 2 # one two-CTA cluster per output tile pair
BLOCK_K = 64
FRONT_NUM_K_ITERS = HIDDEN // BLOCK_K # 112 K iterations per 256 x 256 pair tile
FRONT_SPLIT = 2 # trailing-wave tiles cut into two aligned K halves
FRONT_SK_EPI_ITERS = (
18 # exposed stream-K epilogue of the last contributor, in K iterations
)
FRONT_SK_MIN_GAIN = (
0.04 # split only when the modelled saving is >= 4 % of the whole-tile cost
)
#: Weight boxes re-read by at most this many pair rows stream with the ``evict_first`` L2 policy
#: (a separate program); 152-SM parts take it up to eight pair rows (M <= 2048).
FRONT_EVICT_FIRST_MAX_PAIR_ROWS = 2
FRONT_EVICT_FIRST_MAX_PAIR_ROWS_BY_SM_COUNT = {152: 8}
#: Keyword order of the programs' ``run`` entry; ``grid`` expands to ``grid_x/y/z``.
FRONT_KWARGS = (
"A",
"WG",
"WD",
"WS",
"logits",
"latent",
"shared_act",
"ws",
"counters",
"M",
"m_tiles",
"num_items",
"full_items",
"sk_ipc",
"sk_max_seg",
"sk_total",
"grid",
)
#: Argument position of the partial workspace in ``FRONT_KWARGS``.
WS_POSITION = FRONT_KWARGS.index("ws")
#: Launch shape shared by both programs.
BLOCK_THREADS = 320
DYNAMIC_SMEM_BYTES = 230528
#: Generated program per logical kernel key: ``front:i6144`` streams the weights with the default
#: L2 policy, ``front:i6144e1`` with ``evict_first``. Both take the same arguments.
PROGRAMS = {
"front:i6144": "cake_kimi_k3_latent_moe_b36cca5dfbea2e45cbac",
"front:i6144e1": "cake_kimi_k3_latent_moe_14ba3299b6dbce540fa9",
}
CSRC_DIR = Path(__file__).parent / "csrc" / "kimi3_latent_front"
# Control words are handed out in 128-byte slots of 32 four-byte words.
CTRL_SLOT_WORDS = 32
# Four-byte words of one slab chunk (256 KiB): one zero fill for hundreds of runners.
CTRL_CHUNK_WORDS = 1 << 16
# ---------------------------------------------------------------------------
# Host plan
# ---------------------------------------------------------------------------
def m_tiles_for(M: int) -> int:
"""Row tiles of ``M`` rows, rounded up to whole cluster pairs."""
tiles = (M + BLOCK_M - 1) // BLOCK_M
return tiles + (tiles % CTA_GROUP)
def front_n_tiles() -> int:
"""Column tile pairs per row pair: router, latent, then the shared gate/up halves."""
shared_half = FRONT_BLOCK_N // CTA_GROUP
return (
(NUM_EXPERTS + FRONT_BLOCK_N - 1) // FRONT_BLOCK_N
+ LATENT // FRONT_BLOCK_N
+ SHARED_INTERMEDIATE // shared_half
)
def front_split_plan(cluster_tiles: int, sm_count: int) -> dict[str, int]:
"""Persistent work plan: the full waves run whole pair tiles; the trailing partial wave is cut
into two aligned K halves per tile when the halves fit one wave and the modelled saving
reaches ``FRONT_SK_MIN_GAIN`` of the whole-tile cost."""
resident = max(1, sm_count // CTA_GROUP)
full_waves, rem = divmod(cluster_tiles, resident)
whole = {
"num_items": cluster_tiles,
"full_items": cluster_tiles,
"sk_ipc": FRONT_NUM_K_ITERS,
"sk_max_seg": 1,
"sk_total": 0,
"sk_tiles": 0,
}
if rem == 0 or rem * FRONT_SPLIT > resident:
return whole
whole_cost = (full_waves + 1) * FRONT_NUM_K_ITERS
saving = FRONT_NUM_K_ITERS - FRONT_NUM_K_ITERS // FRONT_SPLIT - FRONT_SK_EPI_ITERS
if saving < FRONT_SK_MIN_GAIN * whole_cost:
return whole
return {
"num_items": cluster_tiles - rem + rem * FRONT_SPLIT,
"full_items": cluster_tiles - rem,
"sk_ipc": FRONT_NUM_K_ITERS // FRONT_SPLIT,
"sk_max_seg": FRONT_SPLIT,
"sk_total": rem * FRONT_NUM_K_ITERS,
"sk_tiles": rem,
}
def front_evict_first(m_tiles: int, sm_count: int) -> bool:
"""Whether the ``evict_first`` weight-policy program serves ``m_tiles`` row tiles."""
limit = FRONT_EVICT_FIRST_MAX_PAIR_ROWS_BY_SM_COUNT.get(
int(sm_count), FRONT_EVICT_FIRST_MAX_PAIR_ROWS
)
return (m_tiles // CTA_GROUP) <= limit
@functools.lru_cache(maxsize=None)
def _front_plan(M: int, sm_count: int) -> dict[str, Any]:
m_tiles = m_tiles_for(M)
cluster_tiles = (m_tiles // CTA_GROUP) * front_n_tiles()
sk = front_split_plan(cluster_tiles, sm_count)
return dict(
M=M,
m_tiles=m_tiles,
cluster_tiles=cluster_tiles,
evict_first=front_evict_first(m_tiles, sm_count),
grid=sk["num_items"] * CTA_GROUP,
**sk,
)
def front_plan(M: int, sm_count: int) -> dict[str, Any]:
"""Host plan of the front launch for ``M`` rows on a device of ``sm_count`` SMs.
Args:
M: Row count, at least ``MIN_TOKENS``.
sm_count: SM count of the device, one of ``QUALIFIED_SM_COUNTS``.
Returns:
A copy of the plan: the kernel arguments (``m_tiles``, ``num_items``, ``full_items``,
``sk_ipc``, ``sk_max_seg``, ``sk_total``, ``grid``), the split-tile count ``sk_tiles``
and the weight policy ``evict_first``.
"""
if int(M) < MIN_TOKENS:
raise ValueError(
f"the vendored Kimi-K3 front programs serve at least {MIN_TOKENS} rows, got {M}"
)
if int(sm_count) not in QUALIFIED_SM_COUNTS:
raise ValueError(
f"the Kimi-K3 front plan rules are validated for {QUALIFIED_SM_COUNTS} SMs, got {sm_count}"
)
return dict(_front_plan(int(M), int(sm_count)))
def front_kernel_key(plan: dict[str, Any]) -> str:
"""The logical kernel key of a plan."""
return "front:i6144e1" if plan["evict_first"] else "front:i6144"
def partial_ws_numel(plan: dict[str, Any]) -> int:
"""FP32 elements of the stream-K partial workspace one launch uses: one ``128 x 256`` slot per
contributor CTA of a split tile (0 for a whole plan, which writes none)."""
sk_tiles = int(plan["sk_tiles"])
return sk_tiles * int(plan["sk_max_seg"]) * CTA_GROUP * BLOCK_M * FRONT_BLOCK_N
def arrival_counter_words(plan: dict[str, Any]) -> int:
"""Int32 stream-K arrival counters of a plan: one per split tile and CTA rank, at least two."""
return max(2, int(plan["sk_tiles"]) * CTA_GROUP)
# ---------------------------------------------------------------------------
# Device facts and program loading
# ---------------------------------------------------------------------------
def _device_index(device: torch.device) -> int:
return device.index if device.index is not None else torch.cuda.current_device()
@functools.cache
def _device_facts(index: int) -> tuple[tuple[int, int], int]:
properties = torch.cuda.get_device_properties(index)
return (int(properties.major), int(properties.minor)), int(
properties.multi_processor_count
)
def available(device: torch.device | None = None) -> bool:
"""Whether the vendored programs run on ``device`` (the current device when omitted)."""
if not torch.cuda.is_available():
return False
index = torch.cuda.current_device() if device is None else _device_index(device)
capability, count = _device_facts(index)
return capability in SUPPORTED_COMPUTE_CAPABILITIES and count in QUALIFIED_SM_COUNTS
@functools.cache
def _module(key: str):
"""The JIT-built program serving ``key``, compiled once per process for SM100a and SM103a."""
from flashinfer.jit.core import gen_jit_spec, sm100a_nvcc_flags, sm103a_nvcc_flags
name = PROGRAMS[key]
sources = [CSRC_DIR / f"{name}_kernel.cu", CSRC_DIR / f"{name}_binding.cu"]
return gen_jit_spec(
f"tokenspeed_kimi3_latent_front_{name[-20:]}",
sources,
extra_cuda_cflags=[*sm100a_nvcc_flags, *sm103a_nvcc_flags, "--use_fast_math"],
# The bindings encode TMA descriptors through the driver API.
extra_ldflags=["-lcuda"],
extra_include_paths=[CSRC_DIR],
use_fast_math=False,
).build_and_load()
# ---------------------------------------------------------------------------
# Device scratch: control words and the stream-K partial workspace
# ---------------------------------------------------------------------------
#
# The programs use two kinds of mutable device scratch:
#
# * Control words: the stream-K arrival counters, which must read zero before a launch and which
# every launch returns to zero. Each prepared runner takes its own slot from the device's slab;
# a slot is never reused, so a CUDA Graph that captured a runner replays into valid private
# words after the runner is dropped. One-shot eager calls share one slot per (device, stream,
# word count): launches on one stream are stream-ordered.
# * Partials: the FP32 workspace of split plans, written before it is read inside one launch. An
# eager launch uses the workspace of its (device, stream), grown to the largest split plan
# launched there; a launch under CUDA Graph capture takes a block of the graph's memory pool.
class _CtrlSlab:
"""Zero-initialised control words of one device, handed out in 128-byte slots, never reused."""
def __init__(self, index: int) -> None:
self.index = index
self._lock = threading.Lock()
self._chunk: torch.Tensor | None = None
self._used = 0
self._pinned: list[torch.Tensor] = []
def take(self, words: int) -> torch.Tensor:
"""``words`` (a multiple of ``CTRL_SLOT_WORDS``) zero int32 words owned by the caller for good."""
with self._lock:
chunk = self._chunk
if chunk is not None and self._used + words <= chunk.numel():
slot = chunk[self._used : self._used + words]
self._used += words
return slot
device = torch.device("cuda", self.index)
if torch.cuda.is_current_stream_capturing():
# No free slot inside a capture: zero fresh words as one node of that graph.
slot = torch.zeros(words, dtype=torch.int32, device=device)
self._pinned.append(slot)
return slot
chunk = torch.zeros(
max(CTRL_CHUNK_WORDS, words), dtype=torch.int32, device=device
)
# Make the zero fill visible to every stream before any launch binds a slot.
torch.cuda.synchronize(self.index)
self._pinned.append(chunk)
self._chunk, self._used = chunk, words
return chunk[:words]
_LOCK = threading.Lock()
_CTRL_SLABS: dict[int, _CtrlSlab] = {}
_CTRL_LANES: dict[tuple[int, int, int], torch.Tensor] = {}
_READ_NEVER: dict[int, torch.Tensor] = {}
_WS_LANES: dict[tuple[int, int], tuple[int, torch.Tensor]] = {}
_FFI_DEVICES: dict[int, Any] = {}
def _raw_stream(index: int) -> int:
return torch.cuda.current_stream(index).cuda_stream
def _ctrl_slab(index: int) -> _CtrlSlab:
slab = _CTRL_SLABS.get(index)
if slab is None:
with _LOCK:
slab = _CTRL_SLABS.setdefault(index, _CtrlSlab(index))
return slab
def _control_words(index: int, words: int, *, lane: bool) -> torch.Tensor:
"""Zero int32 control words on ``cuda:index``: a fresh slot (``lane=False``), or the slot eager
one-shot calls share per (device, current stream, word count) (``lane=True``, outside capture).
"""
slot_words = -(-int(words) // CTRL_SLOT_WORDS) * CTRL_SLOT_WORDS
if lane and not torch.cuda.is_current_stream_capturing():
key = (index, _raw_stream(index), slot_words)
slot = _CTRL_LANES.get(key)
if slot is None:
slab = _ctrl_slab(index)
with _LOCK:
slot = _CTRL_LANES.get(key)
if slot is None:
slot = _CTRL_LANES[key] = slab.take(slot_words)
return slot[:words]
return _ctrl_slab(index).take(slot_words)[:words]
def _read_never(index: int) -> torch.Tensor:
"""The FP32 placeholder bound as ``ws`` by whole plans, which never touch it."""
entry = _READ_NEVER.get(index)
if entry is None:
with _LOCK:
entry = _READ_NEVER.get(index)
if entry is None:
entry = _READ_NEVER[index] = torch.empty(
1024, dtype=torch.float32, device=torch.device("cuda", index)
)
return entry
def _grow_ws_lane(index: int, stream: int, numel: int) -> tuple[int, torch.Tensor]:
with _LOCK:
lane = _WS_LANES.get((index, stream))
if lane is None or lane[0] < numel:
workspace = torch.empty(
numel, dtype=torch.float32, device=torch.device("cuda", index)
)
lane = _WS_LANES[(index, stream)] = (numel, workspace)
return lane
def _ffi_device(index: int) -> Any:
import tvm_ffi
device = _FFI_DEVICES.get(index)
if device is None:
device = _FFI_DEVICES[index] = tvm_ffi.device(f"cuda:{index}")
return device
# ---------------------------------------------------------------------------
# Runner
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class KimiK3LatentFrontRunner:
"""The prepared launch of one front call.
``launch()`` submits the bound program on the current torch stream of the runner's device
with no host synchronisation; the kernel reads every operand on device at launch, so the
runner (or a CUDA Graph capturing it) replays for new values written into the same buffers.
Prepare a new runner when a shape or a tensor binding changes. The runner owns its control
words, which are never freed.
"""
num_tokens: int
sm_count: int
key: str
plan: dict[str, Any] = field(repr=False)
entry: Callable[..., Any] = field(repr=False)
arguments: tuple = field(repr=False)
ws_numel: int = field(repr=False)
outputs: tuple[torch.Tensor, torch.Tensor, torch.Tensor] = field(repr=False)
device_index: int = field(repr=False)
def _partial_ws(self, stream: int) -> torch.Tensor:
"""The partial workspace of a split-plan launch on ``stream``: the stream's lane when eager,
a block of the graph's memory pool under capture."""
if torch.cuda.is_current_stream_capturing():
return torch.empty(
self.ws_numel,
dtype=torch.float32,
device=torch.device("cuda", self.device_index),
)
lane = _WS_LANES.get((self.device_index, stream))
if lane is None or lane[0] < self.ws_numel:
lane = _grow_ws_lane(self.device_index, stream, self.ws_numel)
return lane[1]
def launch(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
import tvm_ffi
index = self.device_index
stream = _raw_stream(index)
with torch.cuda.device(index), tvm_ffi.use_raw_stream(
_ffi_device(index), stream
):
if self.ws_numel:
arguments = (
*self.arguments[:WS_POSITION],
self._partial_ws(stream),
*self.arguments[WS_POSITION + 1 :],
)
else:
arguments = self.arguments
self.entry(*arguments)
return self.outputs
__call__ = launch
def _check(
t: torch.Tensor, shape: tuple[int, ...], name: str, dtype: torch.dtype
) -> None:
if tuple(t.shape) != tuple(shape) or t.dtype != dtype or not t.is_contiguous():
raise ValueError(
f"{name} must be a contiguous {dtype} tensor of shape {tuple(shape)}, "
f"got {tuple(t.shape)} {t.dtype}"
)
def _prepare(
x: torch.Tensor,
router_weight: torch.Tensor,
routed_weight: torch.Tensor,
shared_gate_up_weight: torch.Tensor,
logits: torch.Tensor,
latent: torch.Tensor,
shared_act: torch.Tensor,
*,
lane: bool,
) -> KimiK3LatentFrontRunner:
if x.dim() != 2:
raise ValueError(f"x must be a [rows, {HIDDEN}] tensor, got {tuple(x.shape)}")
M = int(x.shape[0])
bf16 = torch.bfloat16
_check(x, (M, HIDDEN), "x", bf16)
_check(router_weight, (NUM_EXPERTS, HIDDEN), "router_weight", bf16)
_check(routed_weight, (LATENT, HIDDEN), "routed_weight", bf16)
_check(
shared_gate_up_weight,
(2 * SHARED_INTERMEDIATE, HIDDEN),
"shared_gate_up_weight",
bf16,
)
_check(logits, (M, NUM_EXPERTS), "logits", torch.float32)
_check(latent, (M, LATENT), "latent", bf16)
_check(shared_act, (M, SHARED_INTERMEDIATE), "shared_act", bf16)
tensors = (
x,
router_weight,
routed_weight,
shared_gate_up_weight,
logits,
latent,
shared_act,
)
devices = {t.device for t in tensors}
if len(devices) != 1 or x.device.type != "cuda":
raise ValueError(
f"every operand must live on one CUDA device, got {sorted(map(str, devices))}"
)
index = _device_index(x.device)
capability, sm_count = _device_facts(index)
if capability not in SUPPORTED_COMPUTE_CAPABILITIES:
raise ValueError(
f"the Kimi-K3 front programs require compute capability 10.0 or 10.3, got {capability}"
)
plan = front_plan(M, sm_count)
key = front_kernel_key(plan)
with torch.cuda.device(index):
counters = _control_words(index, arrival_counter_words(plan), lane=lane)
kwargs = dict(
A=x,
WG=router_weight,
WD=routed_weight,
WS=shared_gate_up_weight,
logits=logits,
latent=latent,
shared_act=shared_act,
ws=_read_never(
index
), # a split plan's partial workspace replaces it at launch
counters=counters,
M=M,
m_tiles=int(plan["m_tiles"]),
num_items=int(plan["num_items"]),
full_items=int(plan["full_items"]),
sk_ipc=int(plan["sk_ipc"]),
sk_max_seg=int(plan["sk_max_seg"]),
sk_total=int(plan["sk_total"]),
grid=(int(plan["grid"]), 1, 1),
)
assert tuple(kwargs) == FRONT_KWARGS
module = _module(key)
arguments = tuple(kwargs[name] for name in FRONT_KWARGS[:-1]) + kwargs["grid"]
return KimiK3LatentFrontRunner(
num_tokens=M,
sm_count=sm_count,
key=key,
plan=plan,
entry=module.run,
arguments=arguments,
ws_numel=partial_ws_numel(plan),
outputs=(logits, latent, shared_act),
device_index=index,
)
def prepare_front(
x: torch.Tensor,
router_weight: torch.Tensor,
routed_weight: torch.Tensor,
shared_gate_up_weight: torch.Tensor,
logits: torch.Tensor,
latent: torch.Tensor,
shared_act: torch.Tensor,
) -> KimiK3LatentFrontRunner:
"""Validate the operands, plan the launch and bind it into a reusable runner.
Args:
x: Contiguous BF16 input ``[rows, 7168]``, at least 513 rows.
router_weight: Contiguous BF16 router weight ``[896, 7168]``.
routed_weight: Contiguous BF16 latent projection ``[3584, 7168]``.
shared_gate_up_weight: Contiguous BF16 shared gate rows followed by up rows
``[12288, 7168]``.
logits: Caller-owned FP32 output ``[rows, 896]``.
latent: Caller-owned BF16 output ``[rows, 3584]``.
shared_act: Caller-owned BF16 output ``[rows, 6144]``.
Returns:
A runner whose ``launch()`` fills the three outputs. The program is built and loaded
and the runner's control words are taken here: prepare before CUDA Graph capture.
"""
return _prepare(
x,
router_weight,
routed_weight,
shared_gate_up_weight,
logits,
latent,
shared_act,
lane=False,
)
def front(
x: torch.Tensor,
router_weight: torch.Tensor,
routed_weight: torch.Tensor,
shared_gate_up_weight: torch.Tensor,
logits: torch.Tensor,
latent: torch.Tensor,
shared_act: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Complete front operator into the caller-owned outputs; arguments as :func:`prepare_front`.
Eager calls share one set of control words per device, stream and plan size and the
stream's partial workspace; a call under CUDA Graph capture takes fresh words, which are
never freed, and a workspace block of the graph's memory pool.
Returns:
``(logits, latent, shared_act)``.
"""
return _prepare(
x,
router_weight,
routed_weight,
shared_gate_up_weight,
logits,
latent,
shared_act,
lane=True,
)()
@@ -0,0 +1,173 @@
# 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 current_platform
from tokenspeed_kernel.selection import NoKernelFoundError, kernel_override
from tokenspeed_kernel.thirdparty.cuda import kimi3_latent_front
@pytest.fixture(scope="module")
def weights():
if not (current_platform().is_nvidia and kimi3_latent_front.available()):
pytest.skip("requires an SM100/SM103 part with 148 or 152 SMs")
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, 16385, 32768])
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="cuda_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.fixture(scope="module")
def packed_weights(weights):
"""The same weights as consecutive rows of one tensor, as the model stores them."""
packed = torch.cat(weights, dim=0)
offset = 0
views = []
for weight in weights:
views.append(packed.narrow(0, offset, weight.shape[0]))
offset += weight.shape[0]
return tuple(views)
@pytest.mark.parametrize("rows", [1, 128, 1024, 2047])
def test_front_declines_small_rows(weights, packed_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
)
# The model stores the weights packed; the generic packed Triton kernel is
# AMD-only, so on NVIDIA nothing matches below the front's row bound.
assert (
try_latent_moe_input_projections(
x, *packed_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="cuda",
)
@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)
@@ -0,0 +1,164 @@
# 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.
"""Host plan rules of the vendored Kimi-K3 front, checked without a GPU.
The expected values are those FlashInfer v0.7.3's planner
(``flashinfer.experimental.kimi_k3_latent_moe.cake_backend.prefill_front_plan``)
produces for the same rows, so a drift in the port shows up here.
"""
import pytest
from tokenspeed_kernel.thirdparty.cuda import kimi3_latent_front as front
@pytest.mark.parametrize(
"rows,sm_count,expected",
[
# 16 row tiles, 8 pair rows: 528 pair tiles over 76 resident clusters leave 72, more
# than half a wave, so the plan stays whole; 152-SM parts stream evict_first up to
# eight pair rows.
(
2048,
152,
dict(
m_tiles=16,
num_items=528,
full_items=528,
sk_ipc=112,
sk_max_seg=1,
sk_total=0,
sk_tiles=0,
evict_first=True,
grid=1056,
),
),
# One more row rounds the tile count up to the next pair (18 tiles, 9 pair rows) and
# leaves the evict_first bound.
(
2049,
152,
dict(
m_tiles=18,
num_items=594,
full_items=594,
sk_ipc=112,
sk_max_seg=1,
sk_total=0,
sk_tiles=0,
evict_first=False,
grid=1188,
),
),
# 1024 rows, 4 pair rows: 264 pair tiles are three full waves plus 36, whose two K
# halves fit one wave (72 items), so the trailing wave is split and its tiles share
# the FP32 partial workspace.
(
1024,
152,
dict(
m_tiles=8,
num_items=300,
full_items=228,
sk_ipc=56,
sk_max_seg=2,
sk_total=4032,
sk_tiles=36,
evict_first=True,
grid=600,
),
),
# 148-SM parts: 74 resident clusters and evict_first only up to two pair rows.
(
8192,
148,
dict(
m_tiles=64,
num_items=2112,
full_items=2112,
sk_ipc=112,
sk_max_seg=1,
sk_total=0,
sk_tiles=0,
evict_first=False,
grid=4224,
),
),
# Above 16384 rows the same rules apply: 16385 rows round up to 130 tiles (65 pair
# rows), and 32768 rows are 256 tiles; both are whole plans without evict_first.
(
16385,
152,
dict(
m_tiles=130,
num_items=4290,
full_items=4290,
sk_ipc=112,
sk_max_seg=1,
sk_total=0,
sk_tiles=0,
evict_first=False,
grid=8580,
),
),
(
32768,
152,
dict(
m_tiles=256,
num_items=8448,
full_items=8448,
sk_ipc=112,
sk_max_seg=1,
sk_total=0,
sk_tiles=0,
evict_first=False,
grid=16896,
),
),
],
)
def test_front_plan_matches_flashinfer_rules(rows, sm_count, expected):
plan = front.front_plan(rows, sm_count)
assert {key: plan[key] for key in expected} == expected
assert plan["cluster_tiles"] == (plan["m_tiles"] // 2) * 66
assert front.front_kernel_key(plan) == (
"front:i6144e1" if expected["evict_first"] else "front:i6144"
)
slots = expected["sk_tiles"] * expected["sk_max_seg"] * 2
assert front.partial_ws_numel(plan) == slots * 128 * 256
assert front.arrival_counter_words(plan) == max(2, expected["sk_tiles"] * 2)
def test_front_plan_is_a_private_copy():
plan = front.front_plan(4096, 152)
plan["grid"] = 0
assert front.front_plan(4096, 152)["grid"] == 32 * 66
@pytest.mark.parametrize("rows", [0, 1, 128, 512])
def test_front_plan_refuses_rows_below_the_vendored_programs(rows):
with pytest.raises(ValueError, match="at least 513 rows"):
front.front_plan(rows, 152)
def test_front_plan_refuses_unqualified_sm_counts():
with pytest.raises(ValueError, match="validated for"):
front.front_plan(4096, 132)