Qwen3 Omni vs VL MoE: a list of experts or one tensor
Qwen3 Omni stores each expert as its own MLP module and loops over them. Qwen3 VL stacks all experts into two tensors and, at inference, runs them with two batched matmuls. That storage choice decides how easily the layer shards across GPUs.
The MoE layer and its router
A Mixture-of-Experts (MoE) layer replaces the single feed-forward block of a transformer layer with smaller feed-forward blocks, the experts. A small linear layer, the router (called gate in the code), scores every expert for every token. Each token then goes only to its best experts (top-k), and the layer output is the weighted sum of those expert outputs.
Qwen3 Omni and Qwen3 VL compute the routing in the same way. For a token :
Here is the activation (SiLU in the source’s example). The renormalisation step is optional in Omni (a config flag, norm_topk_prob) and always on in VL.
The difference is in what the router hands to the experts. Omni returns two [T, k] tensors, where is the number of tokens: selected_experts (which experts) and routing_weights (how much). VL computes the same two tensors and then runs one more line:
router_weights = torch.zeros_like(router_logits).scatter_(1, router_indices, routing_weights)
scatter_ writes each top-k weight into its expert’s column of a zero matrix. The result is a dense [T, E] matrix: each row has exactly non-zero entries. VL passes this dense matrix and the sparse indices to the experts.
playground
One router, two output formats
Drag a logit bar up or down. Change top-k. Turn off Omni's renormalisation.
norm_topk_prob and Omni's weights stop summing to 1, while VL's still do (toy logits).The dense form costs numbers instead of . It buys two things that the later sections use. First, an expert’s weight for every token is one column, so “all weights for experts 2 and 3” is a column slice. Second, a weight of 0 is a valid multiplier, so the layer can run a token through an expert it did not pick and cancel the result.
Two ways to store the experts
Qwen3 Omni (HuggingFace). Qwen3OmniMoeThinkerTextExperts subclasses nn.ModuleList. Its constructor appends num_experts copies of Qwen3OmniMoeThinkerTextMLP, each with its own gate_proj, up_proj and down_proj nn.Linear layers. Expert is self[e], and the forward pass calls it like any module: self[e](x). With 4 experts the layer holds 4 modules and 12 linear layers, each a separate parameter.
Qwen3 VL (HuggingFace). Qwen3VLMoeTextExperts holds two nn.Parameter tensors:
gate_up_projwith shape[E, H, 2I]: dimension 0 is the expert, dimension 1 the hidden size , dimension 2 the gate and up projections side by side, each of width (moe_intermediate_size).down_projwith shape[E, I, H].
Expert is not an object. It is row of both tensors: x @ gate_up_proj[e], then chunk(2, dim=-1) to split gate from up.
lmms-engine’s re-stacked Omni. The lmms-engine training code replaces HuggingFace’s Omni ModuleList with its own Qwen3OmniMoeExperts: three stacked parameters gate_proj [E, I, H], up_proj [E, I, H] and down_proj [E, H, I]. It keeps Omni’s math (gate and up are separate, and the code multiplies by the transpose) but takes the storage idea that VL uses.
diagram
Where expert 2 lives
Hover or tab to an expert. Switch the layout, then set 2 GPUs.
Shard(0)). The ModuleList must be split module by module.The source sums up why this matters: stacked tensors are contiguous, you can index an expert with plain slicing, and a DTensor (PyTorch’s distributed tensor) with placement Shard(0) splits all experts across GPUs in one declaration. In the expert module, self.down_proj.to_local() then returns only this GPU’s experts, and the same forward code runs with or without expert parallelism.
The expert loop
Omni’s expert forward pass loops over experts, not over tokens. Line by line:
expert_mask = one_hot(top_k_index, num_classes=E).permute(2, 1, 0). The one-hot has shape[T, k, E]. The permute reorders it to[E, k, T], soexpert_mask[e]is a[k, T]mask of the tokens that picked expert .expert_hit = (expert_mask.sum(dim=(-1, -2)) > 0).nonzero(). Experts with no tokens drop out of the loop.- For each hit expert:
idx, top_x = torch.where(expert_mask[e])gives the top-k slot and the token index of every assignment. current_state = hidden_states[top_x]gathers those rows: shape[n_e, H].self[e](current_state) * top_k_weights[top_x, idx, None]runs the expert and applies the routing weight.final_hidden_states.index_add_(0, top_x, ...)adds the result back into the token rows. It adds, not assigns: a token with receives two contributions.
VL’s training path runs the same loop. The only change is the weight access: current_state @ self.gate_up_proj[e] slices the stacked tensor instead of calling a module, and the routing weight comes from the dense matrix, routing_weights[token_idx, e].
The batched path
VL’s inference path drops the loop. It does more math, but in fewer and larger calls:
hidden_states = hidden_states.repeat(E, 1).view(E, -1, H) # [E, T, H]
gate_up = torch.bmm(hidden_states, self.gate_up_proj) # [E, T, 2I]
gate, up = gate_up.chunk(2, dim=-1) # [E, T, I] each
next_states = torch.bmm(up * self.act_fn(gate), self.down_proj) # [E, T, H]
next_states = next_states.reshape(E, B, -1, H)
next_states = next_states * routing_weights.transpose(0, 1).view(E, B, -1)[..., None]
next_states = next_states.sum(dim=0) # [B, S, H]
torch.bmm is a batched matrix multiply: for each it computes hidden_states[e] @ gate_up_proj[e], all in one call. Every token goes through every expert. The dense routing matrix then multiplies each expert’s output by that token’s weight, which is 0 for the experts the token did not pick, and the sum over dimension 0 collapses the experts. Here the dense matrix is not a convenience: the batched path cannot work without a weight for every (token, expert) pair.
animation
Same batch, two forward paths
Press Play on Loop, then switch to Batched and play again. Step goes one operation at a time.
What the batched path costs
From the shapes, each token-expert row costs about floating-point operations: for gate_up and for down. The loop computes rows. The batched path computes rows. The ratio is exactly , whatever the batch size.
Memory grows the same way. The batched path holds the repeated input [E, T, H], the [E, T, 2I] gate-up result, the [E, T, I] gated activation and the [E, T, H] output at the same time. The loop holds those tensors for one expert’s rows at a time. The source calls this the trade-off of the VL design: “higher memory (repeats hidden states), but acceptable for inference”.
What the batched path saves is the loop itself. The loop runs one Python iteration per hit expert, and each iteration launches its own gather, matmuls, multiply and index_add_ on a slice of rows. With large batches almost every expert is hit, so the loop length is close to . The batched path issues two bmm calls whatever is.
calculator
The price of skipping the loop
Raise the number of experts at a fixed top-k. Then raise the token count.
Grouping tokens by sorting
The lmms-engine version of Omni does not use the mask loop. Its moe_sparse_layer_forward groups token rows by expert with a sort:
num_tokens_per_expert = torch.histc(selected_experts, bins=E, min=0, max=E)counts the rows for each expert.- A stable
argsortofselected_experts.view(-1)orders the assignments by expert id. Integer division by turns each sorted position back into a token index. torch.gatherbuildsrouted_input: token rows in expert order, one copy per assignment.- Without expert parallelism,
torch.split(routed_input, num_tokens_per_expert.tolist())gives one chunk per expert, and the experts loop over the chunks. With expert parallelism, the fullrouted_inputand the counts go to the expert module, and the parallel wrapper sends each chunk to the GPU that owns that expert. - The outputs are multiplied by their sorted routing scores and
scatter_addputs them back into token order.
playground
Sort, count, split, scatter back
Click a grid cell to move a token to that expert (each token keeps 2). Then press Play or Step.
One sort replaces the per-expert masks: the source puts it as once against masking. The cost is bookkeeping. The code has to carry num_tokens_per_expert across the expert-parallel boundary and undo the permutation at the end.
Expert parallelism: three schedules
Expert parallelism (EP) puts different experts on different GPUs. A token that lives on one GPU but picked an expert on another must reach that expert, and the result must come back. The source compares three ways to do it. The animation uses 2 GPUs, 4 experts, 6 tokens and top-2.
HF loop with per-expert communication. The vanilla HuggingFace Qwen3 MoE (transformers 4.57.1) loops over all experts with a mask for each. A reviewer quoted in the source calls this “hard to perform all to all”. If you keep the loop, each expert needs its own dispatch and its own return: two all-to-all operations per expert. The source’s example counts 16 all-to-alls for 8 experts on 2 GPUs.
Token distribution (lmms-engine today). Sort first, then one all-to-all sends each expert’s chunk to the GPU that owns it. Each GPU computes only the rows it received, and a second all-to-all returns the results. That is two collectives per layer, no wasted math, and variable-size messages that depend on the routing. The source calls this the right choice for training, where activation memory matters and redundant math would also need gradients.
Replicated input (the VL-based proposal). Every GPU keeps all tokens. The input function only slices the dense matrix: router_weights[:, local_start:local_end]. Each GPU runs the batched path on its local experts, which produces a partial [T, H] output, and one all-reduce (sum) combines the partials. The message has a fixed size, whatever the routing. The price is redundant math: every GPU runs every token through its local experts, including rows with weight 0. The source calls this the right choice for inference.
animation
Two GPUs, three schedules
Play each schedule. Reseed changes the routing: watch which numbers change and which stay fixed.
The VL code itself chooses by mode: the training branch keeps the loop, which matches token distribution, and the inference branch is the batched path, which matches replicated input. The source’s point is that the dense matrix supports both. A per-GPU slice of columns is all the replicated schedule needs, and the sparse router_indices are still there for the loop.
Side by side
| HF Qwen3 MoE / Omni | lmms-engine Omni | HF Qwen3 VL | |
|---|---|---|---|
| Expert storage | nn.ModuleList of MLPs | 3 stacked nn.Parameter | 2 stacked nn.Parameter |
| Router output to experts | sparse [T, k] | sparse [T, k] | dense [T, E] + sparse indices |
| Token grouping | per-expert mask + torch.where | argsort + histc + split | mask loop (train), none (inference) |
| Inference compute | loop over hit experts | loop over experts | 2 bmm, redundant |
| EP communication | per-expert all-to-all | 2 all-to-alls per layer | slice + 1 all-reduce (proposed) |
Points to keep in mind when you read the source:
- The VL EP path is a proposal. The
_input_fn/_output_fncode with the column slice and the all-reduce is the source’s migration plan, not code that is merged and measured. - The gains are estimates. The plan lists “20–30% faster training”, “2–3× faster inference”, “40–50% less communication” and “~15–20%” less setup overhead from dropping the sort. The source gives no benchmark setup for any of them.
- Replicated input trades math for simple communication. With large, the redundant compute can cost more than the all-to-all it removes. The calculator above shows the size of that factor.
- The source’s own wording conflicts in one place. One step of its plan says “add all-to-all communication in
_input_fnand_output_fn”, but the code it then gives does a column slice and an all-reduce, with no all-to-all.