Vectorized Mixture-of-Experts with Top-k Gating

Quick Overview

Implement top-k gating for a mixture of experts in NumPy: a per-row softmax over only the k largest logits, then a gate-weighted sum of precomputed expert outputs. It tests vectorized indexing, numerically stable softmax, deterministic tie-breaking and shape validation.

Vectorized Mixture-of-Experts with Top-k Gating

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `top_k_gate(logits, k)`, which takes `logits` of shape `(n_samples, n_experts)` and returns dense gate weights of the same shape: in each row, a softmax over only the top-`k` logits, with zeros elsewhere. Then implement `moe_combine(expert_outputs, logits, k)`, which returns the gate-weighted sum of `expert_outputs` (shape `(n_experts, n_samples, ...)`) with shape `(n_samples, ...)`. The functions must meet these requirements: - Each gate row has exactly `k` nonzero entries summing to 1. `k == n_experts` equals a full softmax. - Ties in logits select the lower expert index first. - The computation is numerically stable for large logits (for example `1000.0`): outputs must be finite. - Raise `ValueError` if `k` is not an integer in `[1, n_experts]`, or if the shape of `expert_outputs` does not match the logits. - Use vectorized NumPy only, with no Python loops over samples. Expert outputs are precomputed and passed in. Training, load balancing and capacity limits are out of scope. For example: ```python top_k_gate([[1.0, 2.0, 3.0]], 2) # [[0.0, 1/(1+e), e/(1+e)]] ~ [[0.0, 0.2689, 0.7311]] top_k_gate([[5.0, 5.0, 5.0, 5.0]], 2) # [[0.5, 0.5, 0.0, 0.0]] # ties -> lowest indices outputs = [[[1, 0], [2, 2]], [[0, 1], [4, 0]], [[10, 10], [0, 8]]] # (3 experts, 2 samples, 2) logits = [[0, 0, -5], [-1, 3, 3]] moe_combine(outputs, logits, 2) # [[0.5, 0.5], [2.0, 4.0]] ``` In the first call the top two logits are 3 and 2, and a softmax over just those two gives $e/(1+e)$ and ${1/(1+e)}$. In the last call, sample 0 picks experts 0 and 1 (tied at 0) and averages `[1, 0]` and `[0, 1]`, while sample 1 picks experts 1 and 2 (tied at 3) and averages `[4, 0]` and `[0, 8]`. ```hint Selecting the top k You need the k largest logits in each row, with a deterministic order for equal values. Check which NumPy sort guarantees that order, and what to sort so the largest values come first. ``` ```hint Large logits A softmax does not change when the same constant is subtracted from every logit in a row. Choose the constant so that no exponent can overflow. ``` ### Constraints & Assumptions - `logits` is 2-D with shape `(n_samples, n_experts)`. `expert_outputs` has shape `(n_experts, n_samples, ...)` with any number of trailing output dimensions, including none. - `k` is an integer with `1 <= k <= n_experts`. - Inputs may be nested lists or NumPy arrays, and the computation runs in float64. ### What a Strong Answer Covers - A vectorized per-row top-k selection that breaks ties toward the lower expert index. - A softmax over the selected logits only, stable for large values, with the weights written back into a dense matrix that is zero elsewhere. - Validation of `k` and of the `expert_outputs` shape, raising `ValueError`. - A loop-free weighted sum over the expert axis that works for scalar and vector outputs. - Time and space complexity in terms of samples, experts and output size. ### Follow-up Questions - Why add a load-balancing auxiliary loss when training a top-k MoE? - How would you avoid computing every expert for every sample? - What does noisy top-k gating add, and how does it affect gradients?

Overview: Implement top-k gating for a mixture of experts in NumPy: a per-row softmax over only the k largest logits, then a gate-weighted sum of precomputed expert outputs. It tests vectorized indexing, numerically stable softmax, deterministic tie-breaking and shape validation.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement top_k_gate(logits, k), which takes logits of shape (n_samples, n_experts) and returns dense gate weights of the same shape: in each row, a softmax over only the top-k logits, with zeros elsewhere. Then implement moe_combine(expert_outputs, logits, k), which returns the gate-weighted sum of expert_outputs (shape (n_experts, n_samples, ...)) with shape (n_samples, ...).

The functions must meet these requirements:

  • Each gate row has exactly k nonzero entries summing to 1. k == n_experts equals a full softmax.
  • Ties in logits select the lower expert index first.
  • The computation is numerically stable for large logits (for example 1000.0 ): outputs must be finite.
  • Raise ValueError if k is not an integer in [1, n_experts] , or if the shape of expert_outputs does not match the logits.
  • Use vectorized NumPy only, with no Python loops over samples.

Expert outputs are precomputed and passed in. Training, load balancing and capacity limits are out of scope.

For example:

top_k_gate([[1.0, 2.0, 3.0]], 2)
# [[0.0, 1/(1+e), e/(1+e)]]  ~ [[0.0, 0.2689, 0.7311]]

top_k_gate([[5.0, 5.0, 5.0, 5.0]], 2)
# [[0.5, 0.5, 0.0, 0.0]]   # ties -> lowest indices

outputs = [[[1, 0], [2, 2]], [[0, 1], [4, 0]], [[10, 10], [0, 8]]]  # (3 experts, 2 samples, 2)
logits  = [[0, 0, -5], [-1, 3, 3]]
moe_combine(outputs, logits, 2)
# [[0.5, 0.5], [2.0, 4.0]]

In the first call the top two logits are 3 and 2, and a softmax over just those two gives e/(1+e)e/(1+e) and 1/(1+e){1/(1+e)}. In the last call, sample 0 picks experts 0 and 1 (tied at 0) and averages [1, 0] and [0, 1], while sample 1 picks experts 1 and 2 (tied at 3) and averages [4, 0] and [0, 8].

Constraints & Assumptions

  • logits is 2-D with shape (n_samples, n_experts) . expert_outputs has shape (n_experts, n_samples, ...) with any number of trailing output dimensions, including none.
  • k is an integer with 1 <= k <= n_experts .
  • Inputs may be nested lists or NumPy arrays, and the computation runs in float64.

What a Strong Answer Covers Guidance

  • A vectorized per-row top-k selection that breaks ties toward the lower expert index.
  • A softmax over the selected logits only, stable for large values, with the weights written back into a dense matrix that is zero elsewhere.
  • Validation of k and of the expert_outputs shape, raising ValueError .
  • A loop-free weighted sum over the expert axis that works for scalar and vector outputs.
  • Time and space complexity in terms of samples, experts and output size.

Follow-up Questions Guidance

  • Why add a load-balancing auxiliary loss when training a top-k MoE?
  • How would you avoid computing every expert for every sample?
  • What does noisy top-k gating add, and how does it affect gradients?