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)
return jax.nn.softmax(top_k_logits), 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:
B, L, D = x.shape
x_flat = x.reshape(-1, D)
weights, indices = self.gate(x_flat)
def compute_expert(token_idx):
token = x_flat[token_idx]
selected = indices[token_idx]
outputs = jnp.stack([self.experts[i](token[None])[0] for i in range(self.num_experts)])
return (outputs[selected] * weights[token_idx, :, None]).sum(0)
out = jax.vmap(compute_expert)(jnp.arange(B * L))
return out.reshape(B, L, D)