MCPcopy Create free account
hub / github.com/pytorch/executorch / forward

Method forward

backends/mlx/llm/switch.py:220–271  ·  view source on GitHub ↗

Forward pass through the gated MoE MLP. Args: x: Input activations [N, D] expert_weights: Routing weights [N, top_k] (already softmaxed) expert_indices: Expert assignments [N, top_k] top_k: Number of experts per token sort_experts:

(
        self,
        x: torch.Tensor,
        expert_weights: torch.Tensor,
        expert_indices: torch.Tensor,
        top_k: int,
        sort_experts: bool = False,
    )

Source from the content-addressed store, hash-verified

218 )
219
220 def forward(
221 self,
222 x: torch.Tensor,
223 expert_weights: torch.Tensor,
224 expert_indices: torch.Tensor,
225 top_k: int,
226 sort_experts: bool = False,
227 ) -> torch.Tensor:
228 """Forward pass through the gated MoE MLP.
229
230 Args:
231 x: Input activations [N, D]
232 expert_weights: Routing weights [N, top_k] (already softmaxed)
233 expert_indices: Expert assignments [N, top_k]
234 top_k: Number of experts per token
235 sort_experts: Sort tokens by expert index for coalesced memory
236 access during prefill. No effect on decode (single token).
237
238 Returns:
239 Output tensor [N, D]
240 """
241 N = x.shape[0]
242
243 if sort_experts:
244 flat_indices = expert_indices.flatten()
245 order = flat_indices.argsort().to(torch.int32)
246 inv_order = order.argsort().to(torch.int32)
247 sorted_idx = flat_indices[order].to(torch.int32)
248 x_sorted = x[(order // top_k).to(torch.int64)]
249 x_input = x_sorted.unsqueeze(-2)
250 idx = sorted_idx
251 else:
252 x_input = x.unsqueeze(-2).unsqueeze(-2)
253 idx = expert_indices
254
255 if self.fuse_gate_up:
256 gate_up = self.gate_up_proj(x_input, idx, sorted_indices=sort_experts)
257 gate = gate_up[..., : self.intermediate_size]
258 up = gate_up[..., self.intermediate_size :]
259 else:
260 gate = self.gate_proj(x_input, idx, sorted_indices=sort_experts)
261 up = self.up_proj(x_input, idx, sorted_indices=sort_experts)
262 h = self.activation(gate) * up
263 down = self.down_proj(h, idx, sorted_indices=sort_experts)
264
265 if sort_experts:
266 down = down.squeeze(-2)
267 down = down[inv_order].reshape(N, top_k, -1)
268 else:
269 down = down.squeeze(-2)
270
271 return (down * expert_weights.unsqueeze(-1)).sum(dim=-2)
272
273
274def pack_all_switch_linears(model: nn.Module) -> int:

Callers

nothing calls this directly

Calls 3

flattenMethod · 0.80
activationMethod · 0.80
toMethod · 0.45

Tested by

no test coverage detected