Now, using the same principles as before, I want you to write the MOST clean, short, pythonic, yet efficient and "wow" implementation of a Mixture of Experts (MoE) layer in JAX & Flax.
You must write 3 separate classes : MoE, Expert, and Gate. Do not write the implementation for any boilerplate layers like MLP or RMSNorm, but you are free to use them as if they were defined elsewhere.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a clean, efficient MoE implementation with a "wow" factor using JAX's advanced indexing and vectorization:
python
import jax
import jax.numpy as jnp
import flax.linen as nn
from typing import Tuple
class Expert(nn.Module):
hidden_dim: int
@nn.compact
def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
return MLP(self.hidden_dim)(x)
class Gate(nn.Module):
num_experts: int
top_k: int = 2
@nn.compact
def __call__(self, x: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray]:
logits = nn.Dense(self.num_experts, use_bias=False)(x)
top_k_logits, top_k_indices = jax.lax.top_k(logits, self.top_k)
top_k_weights = jax.nn.softmax(top_k_logits, axis=-1)
return top_k_weights, top_k_indices
class MoE(nn.Module):
num_experts: int
hidden_dim: int
top_k: int = 2
def setup(self):
self.gate = Gate(self.num_experts, self.top_k)
self.experts = [Expert(self.hidden_dim) for _ in range(self.num_experts)]
@nn.compact
def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
batch_size, seq_len, d_model = x.shape
x_flat = x.reshape(-1, d_model)
weights, indices = self.gate(x_flat)
# Vectorized expert computation using advanced indexing
expert_outputs = jnp.stack([expert(x_flat) for expert in self.experts])
selected_outputs = expert_outputs[indices]
# Weighted combination with broadcasting magic
weighted_outputs = (selected_outputs * weights[..., None]).sum(axis=-2)
return weighted_outputs.reshape(batch_size, seq_len, d_model)
The "wow" factors:
Vectorized Expert Selection: Uses jnp.stack + advanced indexing expert_outputs[indices] to avoid loops and gather operations efficiently.
Broadcasting Magic: The weighted combination (selected_outputs * weights[..., None]).sum(axis=-2) leverages JAX's broadcasting to handle the top-k weighting in a single vectorized operation.
Minimal Reshaping: Only flattens once for gating, then reshapes back at the end, minimizing memory operations.
Clean Separation: Each class has a single, focused responsibility with minimal coupling.
This implementation is both highly readable and XLA-optimized, avoiding explicit loops while maintaining the mathematical clarity of MoE routing.