Mixture of Experts as a Latent Distribution — and How It Refines with Depth
1. Is Mixture-of-Experts (MoE) a Latent Distribution Model?
At its mathematical core, a Mixture-of-Experts (MoE) is a latent-variable model.
It introduces a hidden variable that decides which expert processes each input :
- — the gating distribution, representing a probability over experts.
- — the expert conditional, representing each expert’s contribution.
Even when implemented deterministically (as in Transformers), the gating network’s softmax weights define a latent distribution over experts:
and the layer output becomes an expected mixture under that distribution:
Thus, MoE is not just an ensemble — it is a latent distribution model, where each layer learns a conditional distribution over computational pathways.
The gating mechanism is essentially a learned posterior over experts.
2. Latent Distribution Refinement with Depth
When you apply MoE at multiple layers, each layer defines its own gating distribution:
These combine into a hierarchical chain:
Empirically, we observe that as we go deeper in the network:
- The entropy of the gating distribution decreases
- The routing becomes sharper and more deterministic
That is,
This means the model’s latent distribution is refining with depth — uncertainty about which expert to use diminishes as representations become more semantically structured.
2.1 When Entropy Increases with Depth — The Full Picture
While entropy typically decreases with depth, this is not universal.
In complex, high-entropy tasks — or under deliberate regularization — gating entropy can rise in deeper layers:
| Scenario | Why Entropy ↑ |
|---|---|
| Multi-modal or ambiguous tasks | Final layers must combine diverse features → multiple valid expert paths |
| Load-balancing regularization | Training forces uniform routing → entropy preserved or increased |
| Expert under-specialization | Too few or weak experts → gate cannot collapse |
| Meta-learning or exploration | Model incentivized to maintain routing diversity |
Example: In a 12-layer MoE trained on ImageNet, entropy may drop from 1.38 → 0.8 in mid-layers, then rise to 1.1 in the final layer — reflecting the need for flexible part-to-object assembly.
This forms a U-shaped entropy curve: Layer 1: 1.38 → Layer 6: 0.80 → Layer 12: 1.10
Refinement ≠ monotonic collapse.
High entropy in deep layers = strategic diversity, not failure.
3. Why Entropy Decreases — The Intuition
| Mechanism | Explanation |
|---|---|
| 1. Representation refinement | Shallow layers process raw signals where multiple experts may overlap. Deeper layers see more separable latent features → gating becomes more confident. |
| 2. Information bottleneck | As the model compresses information through layers, redundant experts are pruned by specialization. |
| 3. Self-organization | Training naturally drives experts to specialize on different regions of the latent manifold, leading to lower entropy (less overlap). |
4. A Small Experiment: Gating Entropy Falls with Depth
Let’s verify this behavior with a small PyTorch experiment.
We’ll:
- Build a tiny MoE-every-layer MLP
- Train it on a 2D toy classification task
- Measure average gating entropy per layer per epoch
# pip install torch matplotlib (if needed)
import math, numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
import matplotlib.pyplot as plt
torch.manual_seed(0); np.random.seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# --- 1) Toy data: two Gaussian blobs (binary classification) ---
def blobs(n=6000):
n2 = n // 2
means = np.array([[2.5, 0.0], [-2.5, 0.0]])
cov = np.array([[1.0, 0.2], [0.2, 1.0]])
X0 = np.random.multivariate_normal(means[0], cov, size=n2)
X1 = np.random.multivariate_normal(means[1], cov, size=n2)
X = np.vstack([X0, X1]).astype(np.float32)
y = np.hstack([np.zeros(n2), np.ones(n2)]).astype(np.int64)
p = np.random.permutation(n); return X[p], y[p]
X, y = blobs(4000)
split = int(0.8 * len(X))
Xtr, ytr = X[:split], y[:split]
Xva, yva = X[split:], y[split:]
train_loader = DataLoader(TensorDataset(torch.from_numpy(Xtr), torch.from_numpy(ytr)),
batch_size=512, shuffle=True)
val_loader = DataLoader(TensorDataset(torch.from_numpy(Xva), torch.from_numpy(yva)),
batch_size=512, shuffle=False)
# --- 2) MoE block: K experts + softmax gate + residual ---
class Expert(nn.Module):
def __init__(self, d, h):
super().__init__()
self.fc1, self.fc2 = nn.Linear(d, h), nn.Linear(h, d)
nn.init.xavier_uniform_(self.fc1.weight); nn.init.zeros_(self.fc1.bias)
nn.init.xavier_uniform_(self.fc2.weight); nn.init.zeros_(self.fc2.bias)
def forward(self, x): return self.fc2(F.relu(self.fc1(x)))
class MoEBlock(nn.Module):
def __init__(self, d, h, K):
super().__init__()
self.experts = nn.ModuleList([Expert(d, h) for _ in range(K)])
self.gate = nn.Linear(d, K)
self.res = nn.Linear(d, d)
nn.init.xavier_uniform_(self.gate.weight); nn.init.zeros_(self.gate.bias)
nn.init.xavier_uniform_(self.res.weight); nn.init.zeros_(self.res.bias)
def forward(self, x, collect_entropy=False):
logits = self.gate(x) # [B, K]
probs = F.softmax(logits, dim=-1) # [B, K]
outs = torch.stack([e(x) for e in self.experts], dim=-1) # [B, d, K]
mix = torch.einsum("bk,bdk->bd", probs, outs)
y = mix + self.res(x)
ent = None
if collect_entropy:
p = probs.clamp_min(1e-9)
ent = -(p * p.log()).sum(dim=-1).mean().detach()
return y, ent
# --- 3) Deep MoE: MoE at every layer ---
class DeepMoE(nn.Module):
def __init__(self, d_in=2, d_hidden=64, n_layers=4, K=4):
super().__init__()
self.inp = nn.Linear(d_in, d_hidden)
self.blocks = nn.ModuleList([MoEBlock(d_hidden, d_hidden, K) for _ in range(n_layers)])
self.norm = nn.LayerNorm(d_hidden)
self.head = nn.Linear(d_hidden, 2)
nn.init.xavier_uniform_(self.inp.weight); nn.init.zeros_(self.inp.bias)
nn.init.xavier_uniform_(self.head.weight); nn.init.zeros_(self.head.bias)
def forward(self, x, collect_entropy=False):
h = F.relu(self.inp(x))
ents = []
for b in self.blocks:
h, e = b(h, collect_entropy=collect_entropy)
h = F.relu(h)
if collect_entropy: ents.append(e)
h = self.norm(h)
logits = self.head(h)
return logits, ents
model = DeepMoE().to(device)
opt = torch.optim.Adam(model.parameters(), lr=3e-3, weight_decay=1e-5)
def eval_entropy_and_acc():
model.eval()
with torch.no_grad():
layer_sum, n_batches, correct, total = None, 0, 0, 0
for xb, yb in val_loader:
xb, yb = xb.to(device), yb.to(device)
logits, ents = model(xb, collect_entropy=True)
correct += (logits.argmax(dim=-1) == yb).sum().item(); total += yb.numel()
e = [float(x.cpu()) for x in ents]
layer_sum = np.array(e) if layer_sum is None else layer_sum + np.array(e)
n_batches += 1
return (layer_sum / n_batches).tolist(), correct / total
# --- 4) Train + track entropy by layer ---
epochs = 25
entropy_hist, acc_hist = [], []
# initial (epoch 0)
e0, acc0 = eval_entropy_and_acc()
entropy_hist.append(e0); acc_hist.append(acc0)
for ep in range(1, epochs + 1):
model.train()
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
logits, _ = model(xb, collect_entropy=False)
loss = F.cross_entropy(logits, yb)
opt.zero_grad(); loss.backward(); opt.step()
e, acc = eval_entropy_and_acc()
entropy_hist.append(e); acc_hist.append(acc)
entropy_hist = np.array(entropy_hist) # shape [epochs+1, n_layers]
print("Final validation accuracy:", acc_hist[-1])
print("Final per-layer entropies:", entropy_hist[-1])
# --- 5) Plot: entropy vs. epoch per layer ---
import matplotlib.pyplot as plt
plt.figure(figsize=(7,4.5))
for li in range(entropy_hist.shape[1]):
plt.plot(range(entropy_hist.shape[0]), entropy_hist[:, li], label=f"Layer {li+1}")
plt.xlabel("Epoch"); plt.ylabel("Gating entropy (nats)")
plt.title("MoE gating entropy vs. epoch (per layer)")
plt.legend(); plt.tight_layout()
plt.show()
# Optional: final bar chart
plt.figure(figsize=(6,4))
plt.bar(np.arange(1, entropy_hist.shape[1]+1), entropy_hist[-1])
plt.xlabel("Layer"); plt.ylabel("Final gating entropy (nats)")
plt.title("Final gating entropy by layer")
plt.tight_layout(); plt.show()
Expected Output
A plot where gating entropy decreases over epochs — and deeper layers stabilize at lower entropy.
This confirms that the latent distribution becomes more deterministic with depth, as each layer’s experts specialize and the gating network’s uncertainty collapses.
5. Conceptual Summary
| Layer | Gating Entropy | Routing Behavior | Interpretation |
|---|---|---|---|
| Shallow | High | Diffuse routing (shared load) | Model exploring latent allocation |
| Middle | Moderate | Emerging specialization | Experts forming distinct functions |
| Deep | Low | Deterministic routing | Experts encode separate regions |
6. Takeaway
Mixture-of-Experts is a latent distribution model — and its latent distribution refines with depth.
As the network grows deeper:
- Gating entropy decreases
- Routing becomes more deterministic
- Experts self-organize into distinct functional modules
This dynamic — latent distribution refinement — is a hallmark of modular deep learning and a key to scalable, interpretable architectures.