TensorTonic
Study Plans
Study Plan
Top-k MoE Router with Load Statistics
Language ModelsNeural Networks
Hard

Implement top-k mixture-of-experts routing from precomputed expert outputs. For token ttt and expert eee, xtx_txt​ is the token vector, wew_ewe​ is column e of w_router, and st,es_{t,e}st,e​ is the router score. Superscript T denotes transpose.

st,e=xtTwe.s_{t,e}=x_t^{\mathsf T}w_e.st,e​=xtT​we​.

Select k experts by descending score, breaking ties by lower expert index. Let et,je_{t,j}et,j​ be the expert at selected position j and αt,j\alpha_{t,j}αt,j​ its weight; j and r range over the selected experts.

αt,j=exp⁡(st,et,j)∑r=1kexp⁡(st,et,r).\alpha_{t,j}=\frac{\exp(s_{t,e_{t,j}})}{\sum_{r=1}^{k}\exp(s_{t,e_{t,r}})}.αt,j​=∑r=1k​exp(st,et,r​​)exp(st,et,j​​)​.

For expert output ut,eu_{t,e}ut,e​ and shared output utsharedu_t^{\mathrm{shared}}utshared​, the routed result yty_tyt​ is

yt=utshared+∑j=1kαt,jut,et,j.y_t=u_t^{\mathrm{shared}}+\sum_{j=1}^{k}\alpha_{t,j}u_{t,e_{t,j}}.yt​=utshared​+j=1∑k​αt,j​ut,et,j​​.

For T tokens, fef_efe​ is the fraction selecting expert e and mem_eme​ is its mean probability under softmax over all E experts. The indicator is one when its condition holds and zero otherwise.

fe=1T∑t=1T1[e is selected for t].f_e=\frac{1}{T}\sum_{t=1}^{T}\mathbf{1}[e\text{ is selected for }t].fe​=T1​t=1∑T​1[e is selected for t]. me=1T∑t=1Tsoftmax⁡(st)e.m_e=\frac{1}{T}\sum_{t=1}^{T}\operatorname{softmax}(s_t)_e.me​=T1​t=1∑T​softmax(st​)e​.

Return a dictionary of PyTorch tensors: output with shape (T, Dout), selected_experts and selected_weights with shape (T, k), and token_fraction and probability_mass with shape (E,). These contain y, the selected zero-based indices, their weights, f, and m, respectively. selected_experts is int64; all other results match x's dtype, and all results stay on x's device.

Loading visualization...

Examples

Input: x = [[1,0],[0,1]], w_router = [[1,0,1],[0,1,1]], expert_outputs = [[[10,0],[0,0],[0,10]],[[0,0],[5,5],[1,1]]], shared_output = [[1,1],[2,2]], k = 2

Output: {"output":[[6,6],[5,5]],"selected_experts":[[0,2],[1,2]],"selected_weights":[[0.5,0.5],[0.5,0.5]],"token_fraction":[0.5,0.5,1],"probability_mass":[0.288841,0.288841,0.422319]}

Explanation: Both tokens tie their own specialist with expert 2, so stable index order selects [0,2] and [1,2]. Equal selected weights average those outputs before the shared output is added.

Input: x = [[2]], w_router = [[1,0.5]], expert_outputs = [[[7],[3]]], shared_output = [[1]], k = 1

Output: {"output":[[8]],"selected_experts":[[0]],"selected_weights":[[1]],"token_fraction":[1,0],"probability_mass":[0.731059,0.268941]}

Input: x = [[0]], w_router = [[0,0]], expert_outputs = [[[2],[4]]], shared_output = [[1]], k = 2

Output: {"output":[[4]],"selected_experts":[[0,1]],"selected_weights":[[0.5,0.5]],"token_fraction":[1,1],"probability_mass":[0.5,0.5]}

Hint 1

Stable sorting preserves the original index order for tied scores.

Hint 2

torch.gather selects values using per-token indices.

Hint 3

torch.scatter can mark selected experts in a Boolean mask.

Requirements

  • Use PyTorch with float32 routing calculations, then cast floating-point results to the input dtype.
  • Keep selected experts and their weights in descending score order, with lower-index tie breaking.
  • Do not modify any input tensor.

Constraints

  • x has shape (T, D), w_router has shape (D, E), expert_outputs has shape (T, E, Dout), and shared_output has shape (T, Dout).
  • T is token count, D is input width, E is expert count, and Dout is output width; all are positive.
  • k is a Python integer from 1 through E.
  • All tensor inputs are PyTorch tensors sharing a device and dtype, either float32 or bfloat16.
  • Inputs contain finite values and may be noncontiguous.
Try Similar Problems
Gated DeltaNet State UpdateHardParallel and Recurrent Linear AttentionMediumMamba 2 Gated State ScanMediumRMSNorm Forward PassEasyDecode Attention with a KV CacheHardRecover an IsoFLOP Compute-Optimal FrontierHardFit a Data Power Law with a Noise FloorHardFit Elo Ratings from Pairwise VotesHardVision Transformer Patch EmbeddingHardLSTM Cell from ScratchHardEarly StoppingHardBackpropagation Through a Computation GraphHard

Accepts: array

Accepts: array

Accepts: array

Accepts: array

Accepts: number

You must run your code first.

Top-k MoE Router with Load Statistics

Language ModelsNeural Networks
Hard

Implement top-k mixture-of-experts routing from precomputed expert outputs. For token ttt and expert eee, xtx_txt​ is the token vector, wew_ewe​ is column e of w_router, and st,es_{t,e}st,e​ is the router score. Superscript T denotes transpose.

st,e=xtTwe.s_{t,e}=x_t^{\mathsf T}w_e.st,e​=xtT​we​.

Select k experts by descending score, breaking ties by lower expert index. Let et,je_{t,j}et,j​ be the expert at selected position j and αt,j\alpha_{t,j}αt,j​ its weight; j and r range over the selected experts.

αt,j=exp⁡(st,et,j)∑r=1kexp⁡(st,et,r).\alpha_{t,j}=\frac{\exp(s_{t,e_{t,j}})}{\sum_{r=1}^{k}\exp(s_{t,e_{t,r}})}.αt,j​=∑r=1k​exp(st,et,r​​)exp(st,et,j​​)​.

For expert output ut,eu_{t,e}ut,e​ and shared output utsharedu_t^{\mathrm{shared}}utshared​, the routed result yty_tyt​ is

yt=utshared+∑j=1kαt,jut,et,j.y_t=u_t^{\mathrm{shared}}+\sum_{j=1}^{k}\alpha_{t,j}u_{t,e_{t,j}}.yt​=utshared​+j=1∑k​αt,j​ut,et,j​​.

For T tokens, fef_efe​ is the fraction selecting expert e and mem_eme​ is its mean probability under softmax over all E experts. The indicator is one when its condition holds and zero otherwise.

fe=1T∑t=1T1[e is selected for t].f_e=\frac{1}{T}\sum_{t=1}^{T}\mathbf{1}[e\text{ is selected for }t].fe​=T1​t=1∑T​1[e is selected for t]. me=1T∑t=1Tsoftmax⁡(st)e.m_e=\frac{1}{T}\sum_{t=1}^{T}\operatorname{softmax}(s_t)_e.me​=T1​t=1∑T​softmax(st​)e​.

Return a dictionary of PyTorch tensors: output with shape (T, Dout), selected_experts and selected_weights with shape (T, k), and token_fraction and probability_mass with shape (E,). These contain y, the selected zero-based indices, their weights, f, and m, respectively. selected_experts is int64; all other results match x's dtype, and all results stay on x's device.

Loading visualization...

Examples

Input: x = [[1,0],[0,1]], w_router = [[1,0,1],[0,1,1]], expert_outputs = [[[10,0],[0,0],[0,10]],[[0,0],[5,5],[1,1]]], shared_output = [[1,1],[2,2]], k = 2

Output: {"output":[[6,6],[5,5]],"selected_experts":[[0,2],[1,2]],"selected_weights":[[0.5,0.5],[0.5,0.5]],"token_fraction":[0.5,0.5,1],"probability_mass":[0.288841,0.288841,0.422319]}

Explanation: Both tokens tie their own specialist with expert 2, so stable index order selects [0,2] and [1,2]. Equal selected weights average those outputs before the shared output is added.

Input: x = [[2]], w_router = [[1,0.5]], expert_outputs = [[[7],[3]]], shared_output = [[1]], k = 1

Output: {"output":[[8]],"selected_experts":[[0]],"selected_weights":[[1]],"token_fraction":[1,0],"probability_mass":[0.731059,0.268941]}

Input: x = [[0]], w_router = [[0,0]], expert_outputs = [[[2],[4]]], shared_output = [[1]], k = 2

Output: {"output":[[4]],"selected_experts":[[0,1]],"selected_weights":[[0.5,0.5]],"token_fraction":[1,1],"probability_mass":[0.5,0.5]}

Hint 1

Stable sorting preserves the original index order for tied scores.

Hint 2

torch.gather selects values using per-token indices.

Hint 3

torch.scatter can mark selected experts in a Boolean mask.

Requirements

  • Use PyTorch with float32 routing calculations, then cast floating-point results to the input dtype.
  • Keep selected experts and their weights in descending score order, with lower-index tie breaking.
  • Do not modify any input tensor.

Constraints

  • x has shape (T, D), w_router has shape (D, E), expert_outputs has shape (T, E, Dout), and shared_output has shape (T, Dout).
  • T is token count, D is input width, E is expert count, and Dout is output width; all are positive.
  • k is a Python integer from 1 through E.
  • All tensor inputs are PyTorch tensors sharing a device and dtype, either float32 or bfloat16.
  • Inputs contain finite values and may be noncontiguous.
Try Similar Problems
Gated DeltaNet State UpdateHardParallel and Recurrent Linear AttentionMediumMamba 2 Gated State ScanMediumRMSNorm Forward PassEasyDecode Attention with a KV CacheHardRecover an IsoFLOP Compute-Optimal FrontierHardFit a Data Power Law with a Noise FloorHardFit Elo Ratings from Pairwise VotesHardVision Transformer Patch EmbeddingHardLSTM Cell from ScratchHardEarly StoppingHardBackpropagation Through a Computation GraphHard

Accepts: array

Accepts: array

Accepts: array

Accepts: array

Accepts: number

You must run your code first.