MoE Operators¶
Every op on this page is used the same way: construct it once, then call it. The
constructor takes what the kernel is compiled with; the call takes the tensors.
Both are documented under each op — __init__ and forward, where forward is
what runs when you call op(...).
A routed mixture-of-experts layer is available two ways here. FusedMoEFwdOp runs
the whole FFN, and FusedMoESharedExpertFwdOp adds a shared expert beside the routed ones. The rest are its stages, callable on their own: the op that picks
each token's experts, the ops that move tokens into an expert-contiguous layout and
back, and the expert GEMMs that run on it. MoEGroupedGEMMFwdOp is one grouped
GEMM; MoEExpertMLPFwdOp is the pair of them with the gated activation fused into
the first; FusedMoEExpertsFwdOp is that MLP with the permutes around it, on the
tight (no-pad) layout, and IndexedExpertMLPFwdOp is the backend it picks instead when
the routes are few enough to read the weights once per route rather than once per expert. SharedExpertMLPFwdOp is the dense gated MLP of the shared expert. The routing has to produce the layout the GEMM expects.
Fused forward¶
tileops.moe.FusedMoEFwdOp
¶
Routed Mixture-of-Experts (MoE) FFN.
Covers Qwen3 (softmax) style configurations where top-k comes straight from
the gating scores, and Kimi K2 / DeepSeek-V3 style ones where a per-expert
correction_bias is passed: top-k is then selected from
sigmoid(score) + correction_bias while the final weights use the
original (unbiased) scores, renormalized.
num_expert_group > 1 routes as DeepSeek-V3 does: the experts split into
num_expert_group groups of consecutive experts, each scored by the sum of its
two best biased scores when correction_bias is passed and by its best score
otherwise, and top-k is selected inside the topk_group best groups. A group or
an expert within 1e-5 relative plus 1e-6 absolute of the last one kept may be kept
in its place, as in FusedTopKFwdOp, and the output is then that of the routing
taken. The output is multiplied by routed_scaling_factor once (the routing itself
is not scaled).
gpt-oss is scoring_func="softmax", renormalize=True, activation="swigluoai"
and both expert biases. activation, and the row order of w_gate_up and
b_gate_up it reads, are as MoEGroupedGEMMFwdOp defines them; the optional expert
biases b_gate_up and b_down join each route as FusedMoEExpertsFwdOp states.
__init__
¶
__init__(
top_k,
scoring_func="softmax",
renormalize=False,
routed_scaling_factor=1.0,
num_expert_group=1,
topk_group=1,
*,
activation="silu_and_mul",
target=None,
experts=None
)
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
top_k(int) –K -- experts selected per token.
-
scoring_func(str, default:'softmax') –"softmax" (Qwen3) or "sigmoid" (Kimi K2 / DeepSeek-V3).
-
renormalize(bool, default:False) –Renormalize top-k weights to sum to 1.
-
routed_scaling_factor(float, default:1.0) –Multiplier on expert output (Kimi K2: 2.827, DeepSeek-V3: 2.5).
-
num_expert_group(int, default:1) –Groups of consecutive experts the routing is restricted by; must divide E. 1 selects over all experts. DeepSeek-V3: 8.
-
topk_group(int, default:1) –Groups kept per token, holding at least
top_kexperts. DeepSeek-V3: 4. -
activation(str, default:'silu_and_mul') –Gated activation applied to gate_up:
"silu_and_mul"or"gelu_and_mul"over a stackedw_gate_up,"swigluoai"over an interleaved one. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device. -
experts(FusedMoEExpertsFwdOp | None, default:None) –A configured
FusedMoEExpertsFwdOpto run the experts;Nonebuilds one fromactivationandrouted_scaling_factor.
forward
¶
forward(
hidden_states,
gating_output,
w_gate_up,
w_down,
correction_bias=None,
b_gate_up=None,
b_down=None,
)
Route each token to its top-k experts and return the [T, H] weighted sum.
Parameters:
-
hidden_states(Tensor) –[T, H]tokens. -
gating_output(Tensor) –[T, E]float32 router logits. -
w_gate_up(Tensor) –[E, 2F, H]gate and up weights, stacked or interleaved asactivationreads them. -
w_down(Tensor) –[E, H, F]down weights. -
correction_bias(Tensor | None, default:None) –Optional
[E]float32 bias added to the sigmoid scores for the selection only. -
b_gate_up(Tensor | None, default:None) –Optional
[E, 2F]gate/up bias inw_gate_up's row order. -
b_down(Tensor | None, default:None) –Optional
[E, H]down bias.
Returns:
-
Tensor–A new tensor \([T \times H]\): the routed experts' weighted sum for each token.
tileops.moe.FusedMoESharedExpertFwdOp
¶
Routed MoE FFN plus an optional shared expert, with tensor parallelism (TP) for the shared expert.
The routed half routes and computes as FusedMoEFwdOp does;
routed_scaling_factor scales the routed output only, once. Passing the shared
expert's weights enables the shared expert, a silu_and_mul MLP.
When tp_size > 1 the op takes the full shared weights and uses this rank's shard:
shared_w_gate_up \([2F_s \times H]\) split along dim 0 (column parallel, gate and
up halves sharded alike) and shared_w_down \([H \times F_s]\) split along dim 1
(row parallel). The shared output is then a partial sum that the caller all-reduces
across TP ranks. The routed experts are not sharded.
__init__
¶
__init__(
top_k,
scoring_func="softmax",
renormalize=False,
routed_scaling_factor=1.0,
num_expert_group=1,
topk_group=1,
tp_size=1,
tp_rank=0,
*,
activation="silu_and_mul",
target=None,
experts=None
)
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
top_k(int) –K -- experts selected per token.
-
scoring_func(str, default:'softmax') –"softmax" (Qwen3) or "sigmoid" (Kimi K2 / DeepSeek-V3).
-
renormalize(bool, default:False) –Renormalize top-k weights to sum to 1.
-
routed_scaling_factor(float, default:1.0) –Multiplier on the routed expert output.
-
num_expert_group(int, default:1) –Groups of consecutive experts the routing is restricted by; must divide E. 1 selects over all experts. DeepSeek-V3: 8.
-
topk_group(int, default:1) –Groups kept per token, holding at least
top_kexperts. DeepSeek-V3: 4. -
tp_size(int, default:1) –Tensor parallel world size. Default 1 (no TP).
-
tp_rank(int, default:0) –This rank's index in the TP group. Default 0.
-
activation(str, default:'silu_and_mul') –Gated activation of the routed experts; the shared expert supports
silu_and_mulonly. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device. -
experts(FusedMoEExpertsFwdOp | None, default:None) –A configured
FusedMoEExpertsFwdOpto run the experts;Nonebuilds one fromactivationandrouted_scaling_factor.
forward
¶
forward(
hidden_states,
gating_output,
w_gate_up,
w_down,
correction_bias=None,
shared_w_gate_up=None,
shared_w_down=None,
)
Run shared + routed MoE FFN.
Parameters:
-
hidden_states(Tensor) –[T, H] input hidden states.
-
gating_output(Tensor) –[T, E] gating logits.
-
w_gate_up(Tensor) –[E, 2F, H] routed expert gate+up weights.
-
w_down(Tensor) –[E, H, F] routed expert down weights.
-
correction_bias(Tensor | None, default:None) –Optional [E] bias for Kimi K2 / DeepSeek-V3 routing.
-
shared_w_gate_up(Tensor | None, default:None) –[2*F_s, H] shared expert gate+up weights (full, unsharded); passing it enables the shared expert.
-
shared_w_down(Tensor | None, default:None) –[H, F_s] shared expert down weight (full, unsharded), passed with
shared_w_gate_up.
Returns:
-
(shared_output, routed_output)–tuple of [T, H] tensors. shared_output is None when the shared weights are not passed, and a partial sum when tp_size > 1; the caller all-reduces across TP ranks.
Routing and layout¶
tileops.moe.FusedTopKFwdOp
¶
Mixture-of-Experts (MoE) top-k routing operator: each token's expert weights and ids.
Applies scoring (softmax, sigmoid or sqrt(softplus(x))) to router logits and selects
the top-k experts per token, or takes each token's experts from expert_ids. Scoring
and selection run in float32 whatever the logits dtype, with fast-math transcendentals,
so a score can differ from torch's float32 score by a few ulp: an expert, or a group,
whose selection score is within 1e-5 relative plus 1e-6 absolute of the last one kept
may be kept in its place; a selection that is not that close matches the float32
reference, ties to the lower index. A NaN score ranks above every number, as in
torch.topk, and every row returns top_k distinct experts. The weights are
within 1e-4 (relative) of the float32 scores of the experts returned.
With num_expert_group > 1 it is DeepSeek grouped routing: the E experts split into
num_expert_group groups of E / num_expert_group consecutive experts, each group is
scored by the sum of its two best biased scores when correction_bias is passed and by
its best score otherwise, the topk_group best groups are kept (ties to the lower group
index), and the top-k experts are selected inside them; an expert of a dropped group scores
-inf there, so it ties with a kept expert scoring -inf. The returned weights are the
unbiased scores of the selected experts, renormalized when renormalize, times
routed_scaling_factor. num_expert_group=1 selects over all experts.
scoring_func="sqrtsoftplus" and expert_ids follow DeepSeek-V4-Flash's gate. With
expert_ids nothing is selected, the correction bias is not read, and the weights are the
scores of the given experts. Under sigmoid scoring a logit below about -87, whose float32
score is subnormal, scores 0, and a renormalized row of only such logits returns NaN
weights. The in-tree kernel adds a correction bias to sigmoid and sqrt-softplus scores only:
a softmax call that selects with a bias raises OpNotAvailableError when a kernel is
selected.
Example
__init__
¶
__init__(
top_k,
scoring_func="softmax",
renormalize=False,
num_expert_group=1,
topk_group=1,
routed_scaling_factor=1.0,
*,
target=None
)
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
top_k(int) –Number of experts to select per token K.
-
scoring_func(str, default:'softmax') –"softmax" (Qwen3/Qwen2), "sigmoid" (DeepSeek-V3/GLM-4/Kimi K2) or "sqrtsoftplus" (DeepSeek-V4). A
correction_biaspassed toforwardis added to the scores for selection only, and the output weights stay the original scores. -
renormalize(bool, default:False) –If True, normalize top-k weights to sum to 1.
-
num_expert_group(int, default:1) –Groups of consecutive experts the selection is restricted by; must divide E. 1 (the default) selects over all experts. DeepSeek-V3: 8.
-
topk_group(int, default:1) –Groups kept per token, at most
num_expert_group; they must hold at leasttop_kexperts. DeepSeek-V3: 4. -
routed_scaling_factor(float, default:1.0) –Positive multiplier on the returned weights, applied after renormalization. DeepSeek-V3: 2.5.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Run top-k routing.
Parameters:
-
gating_output(Tensor) –[T, E] router logits (bf16, fp16, or float32).
-
correction_bias(Tensor | None, default:None) –[E] float32 per-expert bias, or None.
-
expert_ids(Tensor | None, default:None) –[T, K] int32 experts chosen by the caller, or None to select them.
Returns:
-
topk_weights(Tensor) –[T, K] float32, times
routed_scaling_factor. -
topk_ids(Tensor) –[T, K] int32.
tileops.moe.MoEPrePermuteFwdOp
¶
Materialize rank-grouped activations into a local expert layout.
local_expert_ids must already be in [0, num_local_experts).
The order of rows within one expert is not guaranteed: it may differ between calls on
the same input, and inverse_indices names the row each route's result sits in.
__init__
¶
Configure a pre-permute boundary for one layout and expert domain.
Parameters:
-
layout(ContiguousLayoutSpec | MaskedLayoutSpec) –How the expert rows are materialized.
-
num_local_experts(int) –Number of local experts the ids index.
-
target(object, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Return (expert_input, layout_metadata, inverse_indices).
Parameters:
-
hidden_states(Tensor) –Tokens, \([T \times H]\),
float16orbfloat16. -
local_expert_ids(Tensor) –int32local expert of each route, \([T \times K]\), each in[0, num_local_experts).
Returns:
-
Tensor–(expert_input, layout_metadata, inverse_indices).expert_inputis the -
Tensor–rows grouped by expert, \([P \times H]\), in the dtype of
hidden_states. -
Tensor–layout_metadataisint32: \([E]\) segment end rows under -
tuple[Tensor, Tensor, Tensor]–physical_psum, \([P]\) expert ids underper_row.inverse_indicesis -
tuple[Tensor, Tensor, Tensor]–int32, \([T \cdot K]\), the row each route sits in.
tileops.moe.MoEPermuteAlignFwdOp
¶
Route tokens to experts and pad each expert's token count to block_size.
With numel = T * K routes and count[e] of them on expert e, the result is:
num_tokens_post_pad: the sum over experts ofcount[e]rounded up toblock_size.sorted_token_ids[:num_tokens_post_pad]: one range per expert, in expert order, of that rounded-up length. The firstcount[e]slots of the range hold the indices of the routes one, each once, in an order that is unspecified and may differ between calls on the same input; the rest of the range holdsnumel.expert_ids[:num_tokens_post_pad // block_size]: the owner of eachblock_sizeblock of those ranges.- Past those lengths, every entry of
sorted_token_idsisnumeland every entry ofexpert_idslies outside[0, num_experts).
Example
__init__
¶
Build the op. The routed extents are taken from each call.
Parameters:
-
num_experts(int) –Number of experts.
-
block_size(int, default:64) –GEMM tile size (M dimension); default 64.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Run permute-align.
Parameters:
-
topk_ids(Tensor) –[T, K] int32 expert indices (0-indexed).
Returns:
-
sorted_token_ids(Tensor) –[T * K + (num_experts + 1) * (block_size - 1)] int32
-
expert_ids(Tensor) –[ceil_div(that, block_size)] int32
-
num_tokens_post_pad(Tensor) –[1] int32
tileops.moe.MoEPostPermuteFwdOp
¶
Restore token order and apply the declared local routing epilogue.
A caller-provided out must not overlap expert_output, topk_weights,
inverse_indices or residual. Overlap raises ValueError before any write;
disjoint views of one buffer are accepted.
A residual (for example a shared-expert output) is added to the scaled float32
reduction before the one cast.
__init__
¶
Configure inverse permutation and the exactly-once routing epilogue.
Parameters:
-
layout(ContiguousLayoutSpec | MaskedLayoutSpec) –How the expert rows are materialized.
-
epilogue(RoutingEpilogueSpec | None, default:None) –The routing epilogue;
Nonetakes the default one. -
out_dtype(dtype | None, default:None) –The dtype the reduced result is written in;
Nonekeeps the expert output's own. -
target(object, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Restore token order, apply routing weights, reduce top-k, and cast.
Parameters:
-
expert_output(Tensor) –Expert rows in
layout,float16orbfloat16: \([P \times H]\) when contiguous, \([E \times \text{max\_m} \times H]\) when masked. -
topk_weights(Tensor) –float32routing weights, \([T \times K]\). -
inverse_indices(Tensor) –int32row ofexpert_outputeach route sits in, \([T \cdot K]\). -
out(Tensor | None, default:None) –Buffer \([T \times H]\) to write the result into, or
None. -
residual(Tensor | None, default:None) –\([T \times H]\) in the dtype of
expert_output, added before the cast, orNone.
Returns:
-
Tensor–The reduced result, \([T \times H]\), in
out_dtypeor else the dtype of -
Tensor–expert_output:outwhen given, else a new tensor.
Expert GEMMs¶
tileops.moe.MoEGroupedGEMMFwdOp
¶
M-grouped GEMM over expert-materialized rows: out[rows of g] = a[rows of g] @ b[g]^T.
layout fixes how the rows of a are organised by expert and what the
layout_metadata tensor means; E is read off b, M/N/K off
the operands. Accumulation is fp32; the output is written in the operand dtype
unless out_dtype asks for fp32.
With activation set, b holds the gate and up projections along N ([E, 2 * ffn,
K]) and out has ffn columns: the gated activation is fused into the GEMM's
epilogue. The gated activations every MoE op's activation names are defined here.
silu_and_mul and gelu_and_mul read b stacked, the ffn gate rows then the
ffn up rows, and keep act(gate) * up. swigluoai (gpt-oss) reads it interleaved,
row 2j gate j and row 2j + 1 up j, and keeps g * sigmoid(1.702 * g) * (u +
1) with g = min(gate, 7) and u = clamp(up, -7, 7); the constants are fixed.
An optional bias ([E, N], or [E, 2 * ffn] in b's row order when an
activation is fused) is added to each expert's fp32 product before the activation and
the cast to the output dtype.
Per layout the operands are (trans-free, b is [E, N, K]):
| layout | a |
layout_metadata |
out |
|---|---|---|---|
| contiguous · physical_psum | [M, K] |
[E] segment end rows |
[M, N] |
| contiguous · per_row | [M, K] |
[M] expert id per row |
[M, N] |
| masked | [E, max_m, K] |
[E] valid rows per expert |
[E, max_m, N] |
Rows an aligned layout pads with, and a masked slab's rows past its valid
count, hold unspecified values in out. The metadata's values must satisfy
the layout (ordering, segment ends, ranges); the op does not check them, since
doing so would synchronise.
__init__
¶
Fix the expert layout, the fused activation and the output dtype policy.
Parameters:
-
layout(ContiguousLayoutSpec | MaskedLayoutSpec) –How
a's rows are grouped by expert. -
activation(str | None, default:None) –Nonefor a plain GEMM, or a gated activation fused into the epilogue, which halves the output width:"silu_and_mul"or"gelu_and_mul"over a stacked gate||upb,"swigluoai"over an interleaved one. -
out_dtype(dtype | None, default:None) –Nonewrites the operand dtype,torch.float32keeps the fp32 accumulator. -
target(object, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Run one GEMM per expert over the rows the layout assigns it.
Parameters:
-
a(Tensor) –Expert-materialized activations,
[M, K]or[E, max_m, K]per the layout. -
b(Tensor) –Per-expert weights,
[E, N, K]. -
layout_metadata(Tensor) –int32metadata whose shape and meaning the layout fixes. -
out(Tensor | None, default:None) –Optional preallocated output in the resolved output dtype. It must not overlap an input, or a
ValueErroris raised before anything runs; disjoint views of one buffer are accepted. -
bias(Tensor | None, default:None) –Optional per-expert bias in
b's dtype and row order,[E, N]; keyword-only.
Returns:
-
Tensor–[M, N]or[E, max_m, N]in the operand dtype, or fp32 when asked for.
tileops.moe.MoEGroupedGEMMFP8FwdOp
¶
Block-scaled FP8 GEMM per expert over its rows: out[rows of g] = a[rows of g] @ b[g]^T.
b is [E, N, K] and a holds the expert rows, both float8_e4m3fn. a_scale
holds one float32 scale per row and 128 columns of a, b_scale one per 128x128
block of b ([E, N / 128, K / 128]); K and N are multiples of 128. The
layout places the rows and fixes layout_metadata as MoEGroupedGEMMFwdOp's does;
a_scale is a's shape with K / 128 columns and out with N columns. Rows
an aligned layout pads with, and a masked slab's rows past its valid count, hold
unspecified values in out.
Each 128-wide K block is contracted from the raw FP8 values, then multiplied by its
two scales and added to a float32 accumulator. The result is written in bfloat16. The
metadata is not checked, since checking would synchronise: a masked count past max_m
is read as max_m and a negative one as 0, and nothing outside out is written.
Accuracy: on the valid rows the output matches an fp32 reference that dequantizes both
operands under their scales to atol = 2e-2 * sqrt(max(1, K / 1024)) and
rtol = 2e-2.
__init__
¶
Fix the expert layout.
Parameters:
-
layout(ContiguousLayoutSpec | MaskedLayoutSpec) –The masked slab capacity
max_meach expert's rows are padded to, or the packing and metadata of contiguous expert rows. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Run one block-scaled GEMM per expert over its rows.
Parameters:
-
a(Tensor) –float8_e4m3fnactivations,[M, K], or[E, max_m, K]when masked. -
a_scale(Tensor) –float32per-row scales ofa,a's shape withK / 128columns. -
b(Tensor) –float8_e4m3fnper-expert weights,[E, N, K]. -
b_scale(Tensor) –float32per-block scales ofb,[E, N / 128, K / 128]. -
layout_metadata(Tensor) –int32metadata of the layout (see the class docstring). -
out(Tensor | None, default:None) –Optional preallocated contiguous
bfloat16output,a's shape withNcolumns, written in place and returned;Noneallocates one. Must not overlap any input, or aValueErroris raised before writing.
Returns:
-
Tensor–a's shape withNcolumns inbfloat16; the rows no expert owns are -
Tensor–undefined.
tileops.moe.MoEGroupedGEMMMXFP4FwdOp
¶
MXFP4 GEMM per expert over its rows: out[rows of g] = a[rows of g] @ b[g]^T.
a holds the expert rows in float8_e4m3fn with one scale per row and 128 columns
(a_scale, a's shape with K / 128 columns). b is [E, N, K / 2] uint8,
two e2m1 (FP4) codes per byte along K, the even k in the low nibble, with one scale per 32
of K (b_scale, [E, N, K / 32]). Both scales are float8_e8m0fnu (Microscaling,
MX, power-of-two scales) or both float32; K is a multiple of 128. The layout places
the rows and fixes layout_metadata as MoEGroupedGEMMFwdOp's does; out is
a's shape with N columns.
Rows an aligned layout pads with, and a masked slab's rows past its valid count, hold
unspecified values in out. The metadata is not checked, since checking would
synchronise: a masked count past max_m is read as max_m and a negative one as 0,
and nothing outside out is written.
Each 128-wide K block is contracted on the tensor core, the weights decoded to e4m3 (which
holds every e2m1 value), and added into a float32 accumulator under its scales; under
float32 scales each 32-wide sub-block is added under its own two scales. No scale product
overflows or flushes before it is added. An a_scale of e8m0 code 0 (2 ** -127) may
be flushed to zero, and a row under it then loses results below K * 2 ** -52; the
accumulator may flush terms and sums below 2 ** -126 to zero. The result is written in
bfloat16.
Accuracy: on the valid rows the output matches an fp32 reference that dequantizes both
operands under their scales to atol = 2e-2 * sqrt(max(1, K / 1024)) and
rtol = 2e-2, the FP8 GEMM bound, where the products do not cancel far below their
magnitude. The scales apply to each block's contraction, not to the operands, so the
products round apart from the reference's: where large products cancel, the error is
relative to their magnitude and may pass that bound, as in MoEGroupedGEMMFP8FwdOp. Where
a dequantized value itself passes float32's range (an e8m0 scale of 2 ** 127 on a value of
2 or more), the reference is not finite (infinite, or NaN where that value meets a zero)
and the output is the sum of the scaled block products, each of which may overflow,
rounded to bfloat16.
__init__
¶
Fix the expert layout.
Parameters:
-
layout(ContiguousLayoutSpec | MaskedLayoutSpec) –The masked slab capacity
max_meach expert's rows are padded to, or the packing and metadata of contiguous expert rows. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Run one MXFP4 GEMM per expert over its rows.
Parameters:
-
a(Tensor) –float8_e4m3fnactivations,[M, K], or[E, max_m, K]when masked. -
a_scale(Tensor) –float8_e8m0fnuorfloat32scales ofa,a's shape withK / 128columns. -
b(Tensor) –uint8per-expert weights,[E, N, K / 2], two e2m1 codes per byte. -
b_scale(Tensor) –Scales of
bina_scale's dtype,[E, N, K / 32]. -
layout_metadata(Tensor) –int32metadata of the layout (see the class docstring). -
out(Tensor | None, default:None) –Optional preallocated contiguous
bfloat16output,a's shape withNcolumns, written in place and returned;Noneallocates one. Must not overlap any input, or aValueErroris raised before writing.
Returns:
-
Tensor–a's shape withNcolumns inbfloat16; the rows no expert owns are -
Tensor–undefined.
tileops.moe.MoEExpertMLPFwdOp
¶
Two grouped GEMMs on one expert layout, the gated activation fused into the first.
Rows already grouped by expert in, one unweighted result row per input row out:
out = act(expert_input @ w_gate_up[g]^T + b_gate_up[g]) @ w_down[g]^T + b_down[g]
per expert g, where act is the gated activation and w_gate_up holds the
gate and up projections along N.
activation, and the order of w_gate_up's gate and up rows it reads, are as
MoEGroupedGEMMFwdOp defines them.
The biases are optional and independent of each other and of the activation:
b_gate_up ([E, 2 * ffn], in w_gate_up's row order) is added to the fp32
gate/up product before the activation, b_down ([E, hidden]) to the fp32 down
product before its cast.
__init__
¶
Configure two grouped GEMMs on layout, the first fusing the gated activation.
Parameters:
-
layout(ContiguousLayoutSpec | MaskedLayoutSpec) –Shared by both GEMMs and the metadata.
-
activation(str, default:'silu_and_mul') –"silu_and_mul","gelu_and_mul"(stackedw_gate_up) or"swigluoai"(interleavedw_gate_up), fused into the gate_up GEMM's epilogue. -
target(object, default:None) –Which backend serves the delegates.
forward
¶
forward(
expert_input,
w_gate_up,
w_down,
layout_metadata,
*,
out=None,
b_gate_up=None,
b_down=None
)
Run the gate/up GEMM with its fused activation, then the down GEMM.
Parameters:
-
expert_input(Tensor) –[M, hidden]or[E, max_m, hidden]per the layout. -
w_gate_up(Tensor) –[E, 2 * ffn, hidden], gate and up along the output axis, stacked or interleaved asactivationreads them. -
w_down(Tensor) –[E, hidden, ffn]. -
layout_metadata(Tensor) –int32metadata the layout fixes; shared by both GEMMs. -
out(Tensor | None, default:None) –Optional preallocated
[.., hidden]output in the operand dtype. It must not overlapw_down,layout_metadataorb_down, which the down GEMM reads while it writesout, or aValueErroris raised; disjoint views of one buffer are accepted. -
b_gate_up(Tensor | None, default:None) –Optional
[E, 2 * ffn]bias inw_gate_up's row order; keyword-only. -
b_down(Tensor | None, default:None) –Optional
[E, hidden]bias; keyword-only.
Returns:
-
Tensor–[M, hidden]or[E, max_m, hidden]in the operand dtype.
tileops.moe.FusedMoEExpertsFwdOp
¶
Routed expert MLP: tokens and their routing in, the routing-weighted sum per token out.
output[t] = scale * sum_k w[t, k] * (down_k(act(gate_up_k(h[t]) + b_gate_up[k]))
+ b_down[k]) over each token's routed experts k, where scale is
routed_scaling_factor. Each bias joins its GEMM's result before the activation or the
cast; the routing weight then scales the biased down output. The biases are optional and
independent of each other and of the activation.
act is the gated activation activation names, and w_gate_up and
b_gate_up hold gate and up rows in the order it reads, both as
MoEGroupedGEMMFwdOp defines them.
A call with T * K <= 2 * E on silu_and_mul with no bias, H % 128 == 0 and
F % 256 == 0 runs IndexedExpertMLPFwdOp; every other call runs the staged
pipeline.
__init__
¶
Build the op. Shapes and dtype are taken from each call.
Parameters:
-
routed_scaling_factor(float, default:1.0) –Scalar applied to the final reduced output.
-
activation(str, default:'silu_and_mul') –Gated activation applied to gate_up: 'silu_and_mul' or 'gelu_and_mul' over a stacked
w_gate_up, 'swigluoai' over an interleaved one. -
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
forward(
hidden_states,
w_gate_up,
w_down,
topk_weights,
topk_ids,
b_gate_up=None,
b_down=None,
*,
out=None
)
Run the local expert pipeline and reduce each token's routes.
Parameters:
-
hidden_states(Tensor) –\([T \times H]\) tokens.
-
w_gate_up(Tensor) –\([E \times 2F \times H]\) gate and up weights, stacked or interleaved as
activationreads them. -
w_down(Tensor) –\([E \times H \times F]\) down weights.
-
topk_weights(Tensor) –\([T \times K]\) float32 routing weights.
-
topk_ids(Tensor) –\([T \times K]\) int32 expert of each route.
-
b_gate_up(Tensor | None, default:None) –Optional \([E \times 2F]\) gate/up bias in
w_gate_up's row order. -
b_down(Tensor | None, default:None) –Optional \([E \times H]\) down bias.
-
out(Tensor | None, default:None) –Optional \([T \times H]\) buffer the reduced result is written into. It must not overlap
topk_weights, which the reduction reads while it writesout, or aValueErroris raised before anything runs.
Returns:
-
Tensor–The \([T \times H]\) reduced result:
outwhen given, else a new tensor.
tileops.moe.IndexedExpertMLPFwdOp
¶
Route-major expert MLP: what FusedMoEExpertsFwdOp computes for silu_and_mul
without biases, with each of the T * K routes a row of its expert's GEMM.
Routes that share an expert read its weights once, so the roofline prices one weight read per distinct expert. Suited to calls with few routes per expert.
__init__
¶
Fix the scalar applied to the reduced output; the route extents come per call.
Parameters:
-
routed_scaling_factor(float, default:1.0) –Scalar applied to the final reduced output.
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
forward
¶
Run the routed expert MLP and reduce each token's routes.
Parameters:
-
hidden_states(Tensor) –\([T \times H]\) tokens.
-
w_gate_up(Tensor) –\([E \times 2F \times H]\) stacked gate and up weights.
-
w_down(Tensor) –\([E \times H \times F]\) down weights.
-
topk_weights(Tensor) –\([T \times K]\) float32 routing weights.
-
topk_ids(Tensor) –\([T \times K]\) int32 expert of each route.
-
out(Tensor | None, default:None) –Optional \([T \times H]\) buffer the result is written into. It must not overlap
topk_weights, which the reduction reads while it writesout, or aValueErroris raised before anything runs.
Returns:
-
Tensor–The \([T \times H]\) weighted and reduced result:
outwhen given, else a new -
Tensor–tensor.
tileops.moe.SharedExpertMLPFwdOp
¶
Dense gated MLP: down(silu(hidden @ gate.T) * (hidden @ up.T)).
w_gate_up stacks the gate rows over the up rows. Both GEMMs accumulate in float32;
the gated activation is rounded to the input dtype before the down projection.
__init__
¶
Build the op; shapes and dtypes arrive with each call. A subclass with manifest parameters assigns them first and then calls this.
It selects and builds no kernel and reads no device property: an op constructs wherever it is imported, and a device it cannot run on is refused at the first call.
Parameters:
-
target(Target, default:None) –Which set of kernels serves this op — a target name,
BUILTINfor the in-tree kernels, orNoneto decide from the input device.
Raises:
-
ValueError–A manifest parameter is outside its signature, or an implementation breaks its kernel interface's contract.
-
TypeError–An implementation breaks its kernel interface's contract.
forward
¶
Apply the shared expert to every token.
Parameters:
-
hidden_states(Tensor) –\([T \times H]\),
float16orbfloat16. -
w_gate_up(Tensor) –\([2S \times H]\), the gate rows then the up rows.
-
w_down(Tensor) –\([H \times S]\).
Returns:
-
Tensor–\([T \times H]\) in the dtype of
hidden_states.
Layout and epilogue specs¶
MoEPrePermuteFwdOp, MoEGroupedGEMMFwdOp, MoEExpertMLPFwdOp and
MoEPostPermuteFwdOp take a layout, a ContiguousLayoutSpec or a MaskedLayoutSpec;
MoEGroupedGEMMFP8FwdOp takes a MaskedLayoutSpec. MoEPostPermuteFwdOp also takes an
epilogue, a RoutingEpilogueSpec.
tileops.moe.ContiguousLayoutSpec
dataclass
¶
Compile-time packing and metadata policy for contiguous expert rows.
selection_key
property
¶
Return the concrete specialization key recorded in CallSpecs.
aligned_per_row
classmethod
¶
Use aligned expert segments described by one expert ID per row.
aligned_physical_psum
classmethod
¶
Use aligned expert segments described by per-expert physical segment ends.
tight_per_row
classmethod
¶
Use tight rows described by one expert ID per materialized row.
tight_physical_psum
classmethod
¶
Use tight rows described by per-expert physical segment ends.
tileops.moe.MaskedLayoutSpec
dataclass
¶
tileops.moe.RoutingEpilogueSpec
dataclass
¶
Exactly-once local routing epilogue: the weighted expert rows of a token are reduced in
float32, scaled by routed_scaling_factor and cast once.