in mixture of experts frameworks for transformer architecture, is mixture of experts applied on each layer? is it applied on the feedforward, multihead attention, or both?
Assistant
User
are there examples in literature where researchers used MoE ideas (like the gating framework) to introduce sharp discontinuities in the learned function rather than for efficiency purposes
Assistant
User
are there such hard gating mechanisms with topK (say K=2) that rely on the gradient pass-through to provide gradients? if not, why is this not used in practice?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In Mixture of Experts (MoE) frameworks for Transformer architectures, the application of MoE is layer-specific and component-specific. Here's a detailed breakdown:
1. Is MoE Applied to Each Layer?
Not necessarily. MoE is typically applied selectively to certain layers, not every layer.
Common designs include:
Every other layer: For example, the Switch Transformer uses MoE in alternating layers (e.g., layers 1, 3, 5, ...), while others remain standard.
Deeper layers only: Some models (e.g., GLaM) use MoE primarily in later layers where representations are more abstract.
All layers: Rarely used due to computational overhead and diminishing returns. Most implementations avoid this to balance efficiency and performance.
Why selective? Applying MoE to every layer increases memory/compute costs significantly and may not improve performance proportionally. Strategic placement optimizes the trade-off.
2. Is MoE Applied to Feed-Forward (FFN), Multi-Head Attention (MHA), or Both?
Primarily Feed-Forward Networks (FFN):
Standard practice: MoE replaces the dense FFN in Transformer blocks. Each "expert" is a small FFN (e.g., a 2-layer MLP), and a gating router routes tokens to a subset of experts (e.g., top-2).
Why FFN? FFNs account for ~2/3 of Transformer parameters. Sparsifying them with MoE drastically increases model capacity with minimal compute cost (since only a few experts activate per token).
Examples: Switch Transformer, GLaM, GShard, and most open-source MoE models (e.g., Mixtral 8x7B) use MoE only for FFNs.
Multi-Head Attention (MHA):
Rarely used: MHA is almost always kept dense (non-MoE) in mainstream models.
Why avoid MoE for MHA?
Attention requires global token interactions; sparse routing could hinder critical relationships.
MHA has lower parameter counts than FFN, so MoE offers less capacity gain.
Routing overhead in attention could negate efficiency benefits.
Exceptions: Research papers (e.g., Mixture-of-Experts Attention) explore MoE for attention, but these are not standard in production models.
Both Components:
Extremely rare. No major MoE Transformer (e.g., from Google, Meta, Mistral) applies MoE to both FFN and MHA. The complexity and cost outweigh benefits.
Key Architecture Summary:
Component
MoE Applied?
Rationale
Feed-Forward (FFN)
✅ Yes
High parameter count; MoE boosts capacity efficiently.
Multi-Head Attention (MHA)
❌ No (typically)
Global interactions needed; sparse routing risks performance.
All Layers
⚠️ Selective
Applied to specific layers (e.g., every other layer) to balance cost/performance.
Practical Example: Mixtral 8x7B
MoE in FFN: Each layer has 8 experts (FFNs), but only 2 experts activate per token.
Dense MHA: Standard multi-head attention in all layers.
Layer Strategy: MoE applied to every layer in this case, but this is an exception (most models use selective layers).
Why This Design?
Efficiency: FFN-MoE increases model capacity without proportional compute (e.g., Mixtral 8x7B has ~47B params but uses ~13B compute per token).
Performance: Dense MHA preserves token interactions critical for tasks like translation or reasoning.
In summary, MoE is typically applied to feed-forward networks in select Transformer layers, while multi-head attention remains dense. This design maximizes capacity gains while maintaining computational efficiency and model stability.
Yes, absolutely. While MoE is widely known for scaling model capacity efficiently in Transformers, the core gating mechanism is fundamentally a tool for partitioning the input space and creating piecewise-defined functions. This makes it inherently capable of modeling sharp discontinuities or abrupt transitions in the learned function, even when efficiency isn't the primary goal. Here are key examples and concepts from the literature where MoE gating is used explicitly or implicitly for this purpose:
1. Foundational MoE Work: Modeling Discontinuities from the Start
The original MoE frameworks were designed precisely to handle functions with sharp transitions:
Jacobs et al. (1991) - "Adaptive Mixtures of Local Experts":
Core Idea: Partition the input space into regions, each handled by a specialized "expert" network. A gating network decides which expert(s) to use for a given input.
Discontinuity Mechanism: The gating network outputs probabilities (soft gating) or a hard selection (hard gating). Hard gating (e.g., winner-takes-all) creates abrupt discontinuities at decision boundaries between expert regions. Even soft gating (e.g., softmax) can create sharp transitions if the gating function is steep.
Purpose: Explicitly model non-stationary data or regime-switching behavior (e.g., systems with distinct operating modes like flight dynamics vs. ground dynamics in robotics).
2. System Identification & Hybrid Dynamical Systems
MoE gating is a natural fit for modeling systems with abrupt state changes:
Johansen & Murray-Smith (1997) - "Operating Regime Based System Identification":
Application: Model complex physical systems (e.g., aircraft engines, chemical processes) that operate in distinct regimes (e.g., startup, steady-state, shutdown).
MoE Role: Each expert is a linear/nonlinear model of a specific regime. The gating network (often a classifier) switches abruptly between experts based on input features (e.g., temperature, pressure).
Discontinuity: The overall model output jumps discontinuously when the gating network switches from one expert to another at regime boundaries.
MoE gating helps generative models model discontinuous data distributions:
Sparse VAEs & Discrete Latent Variables:
Concept: Variational Autoencoders (VAEs) with a mixture-of-experts prior or discrete latent variables use gating to select among distinct generative pathways.
Discontinuity: The discrete selection of a latent code or expert path leads to abrupt changes in the generated output. For example, a VAE generating faces might use gating to switch between "glasses" vs. "no glasses" experts.
Example: "Sparse VAE" (Kingma et al., 2014) uses a spike-and-slab prior, inducing sparsity and discontinuous latent representations.
Mixture-of-Experts GANs (MoE-GANs):
Mechanism: The generator or discriminator uses MoE gating. The generator might have multiple expert networks specializing in different data modes (e.g., different object classes in images).
Discontinuity: The gating router's hard selection creates sharp boundaries between generative modes. A small change in input noise could trigger a switch to a completely different expert, drastically altering the output.
4. Reinforcement Learning (RL): Policy & Value Function Discontinuities
MoE gating models abrupt changes in behavior or state values:
Options Framework & Hierarchical RL:
Concept: "Options" are temporally extended actions. A gating network (called the "option selector") chooses which option/policy to execute.
Discontinuity: Switching between options (e.g., "explore" vs. "exploit" policies) creates discontinuities in the policy function. The value function can also jump abruptly when switching between options.
Example: "The Option-Critic Architecture" (Bacon et al., 2017) uses gating to select options, leading to piecewise-continuous policies.
MoE for Value Function Approximation:
Application: In complex environments (e.g., robotics), the optimal value function might have discontinuities at state boundaries (e.g., near obstacles or goal regions).
Mechanism: An MoE value function uses experts for different state regions. Hard gating creates jumps in the value estimate when crossing region boundaries.
5. Theoretical Work: Universal Approximation of Discontinuous Functions
Research explicitly leverages MoE gating to approximate discontinuous functions:
Poggio & Girosi (1990) - "Networks for Approximation and Learning":
Key Insight: Standard neural nets with continuous activations (e.g., sigmoid, tanh) can only approximate continuous functions. To approximate discontinuous functions, you need mechanisms like hard gating or discrete switches.
MoE Role: MoE with hard gating is proven to be a universal approximator for discontinuous functions, as it can partition the input space and assign independent experts to each partition.
"Neural Networks with Discontinuous Activations" (e.g., ReLU, Step Functions):
While ReLU networks can approximate discontinuities, they require many layers/neurons. MoE gating provides a more structured way to introduce discontinuities via explicit input-space partitioning.
6. Control Theory & Hybrid Systems
MoE gating is used to model and control systems with abrupt dynamics:
Hybrid System Identification:
Problem: Systems governed by both continuous dynamics and discrete logic (e.g., a thermostat switching heating on/off).
MoE Solution: Each expert models a continuous dynamic mode. The gating network models the discrete switching logic.
Discontinuity: The state trajectory jumps discontinuously when the system switches modes (e.g., temperature derivative changes abruptly when the heater turns on).
Why MoE Gating Creates Discontinuities: The Mechanism
Input Space Partitioning: The gating network divides the input space into regions (e.g., via hyperplanes or Voronoi tessellation).
Expert Specialization: Each expert learns a function only within its assigned region.
Boundary Behavior: At the boundary between regions:
Hard Gating (e.g., argmax): Output jumps abruptly from one expert's function to another.
Parameter Isolation: Experts have independent parameters. A small input change crossing a boundary can trigger a complete switch in the active parameters, leading to output discontinuity.
Key Distinction: Hard vs. Soft Gating
Gating Type
Continuity
Use Case for Discontinuities
Hard Gating (e.g., top-1, winner-takes-all)
Discontinuous
Explicit modeling of regime switches, hybrid systems, discrete decisions.
Soft Gating (e.g., softmax)
Continuous (but can be sharp)
Blending experts; discontinuities only if gating is very steep or used with discrete latents.
Conclusion
While modern MoE in Transformers (e.g., Mixtral, Switch Transformer) prioritizes efficiency, the foundational and theoretical use of MoE gating is deeply rooted in modeling discontinuities. Key domains include:
System Identification (hybrid dynamical systems),
Generative Modeling (multimodal distributions),
Reinforcement Learning (policy/value function switches),
Control Theory (mode transitions),
Approximation Theory (universal approximation of discontinuous functions).
In these contexts, MoE gating is not just a scalability trick but a fundamental tool for representing piecewise functions with sharp transitions, enabling models to capture complex, non-smooth phenomena that homogeneous networks struggle with.
Yes, hard gating with top-K selection (e.g., K=2) can use gradient pass-through tricks (like the Straight-Through Estimator, STE) to enable backpropagation. However, this approach is rarely used in practice for large-scale MoE models (e.g., Transformers). Below, I break down the mechanics, why it's theoretically possible, and the practical reasons it's avoided.
1. How Hard Top-K Gating with Gradient Pass-Through Works
Mechanism:
Forward Pass:
Compute gating scores (logits) for all experts.
Select the top-K experts (e.g., K=2) with the highest scores.
Zero-out all other experts (hard selection).
Combine outputs only from the top-K experts.
Backward Pass:
Use a Straight-Through Estimator (STE) to approximate gradients:
Forward: Hard selection (discrete, non-differentiable).
Backward: Pretend the gating was soft (e.g., softmax) during gradient calculation.
Gradients flow only to the top-K experts, as if they were selected softly.
∂Loss/∂g_i ≈ ∂Loss/∂(softmax(g))_i # Treat hard selection as soft softmax
Gradients for non-top-K experts are ignored (masked to zero).
2. Why This Is Rarely Used in Practice
Despite theoretical feasibility, hard top-K gating with STE is not the default in modern MoE frameworks (e.g., Switch Transformer, Mixtral, GLaM). Here’s why:
(a) Training Instability
Noisy Gradients: STE introduces bias because gradients are estimated using a soft approximation of a hard decision. This creates a mismatch between forward/backward passes, leading to unstable training.
Oscillations: Small changes in input can abruptly flip the top-K selection, causing large gradient jumps. This is especially problematic for K=1 (winner-takes-all) but persists for K=2.
Example: If Expert A and Expert B are close in score, tiny noise might swap their rankings. STE would then route gradients to the "wrong" expert, confusing the optimizer.
(b) Inefficient Hardware Utilization
Sparse Computation ≠ Efficient Execution:
Hard gating dynamically activates only K experts per token, creating irregular computation patterns.
Modern hardware (GPUs/TPUs) thrives on dense, regular operations. Dynamic routing causes:
Memory fragmentation.
Load imbalance across experts.
Underutilization due to "no-op" cycles for non-selected experts.
Contrast with Soft Gating: Even if K experts are used, soft gating computes all experts (but weights their outputs). This is computationally wasteful but hardware-friendly.
(c) Redundancy with Soft Gating
Soft Top-K is "Good Enough":
Soft gating (e.g., softmax) with top-K selection (e.g., routing to top-2 experts) provides a smooth approximation of hard gating.
By adjusting the temperature of the softmax, you can control sharpness:
Low temperature → near-hard selection.
High temperature → smoother blending.
This avoids STE instability while still achieving sparse activation.
Example: Mixtral 8x7B uses soft top-2 gating with temperature scaling. It behaves almost like hard gating but trains stably.
(d) Load-Balancing Challenges
Expert Imbalance: Hard gating exacerbates the "rich-get-richer" problem:
Popular experts receive more tokens → better trained → attract even more tokens.
Less popular experts "starve" and degrade.
Soft Gating Mitigates This: Small probabilities assigned to non-top-K experts allow auxiliary losses (e.g., load-balancing loss) to redistribute tokens gently.
STE Complicates Balancing: With hard gating, gradients for non-top-K experts are zeroed out, making it harder to train auxiliary losses that encourage fairness.
(e) Limited Benefits Over Soft Gating
Discontinuities Are Overrated: In practice, most tasks (e.g., language modeling) benefit more from smooth expert blending than sharp discontinuities. Abrupt switches can harm performance in tasks requiring continuous reasoning.
Efficiency Gains Are Marginal: Hard gating saves computation by skipping non-top-K experts, but:
Soft gating with top-K already skips most experts (e.g., 6/8 in Mixtral).
The overhead of dynamic routing often negates savings.
3. When Hard Gating Is Used (Niche Cases)
Despite these issues, hard gating with STE appears in:
Small-Scale Research: Proof-of-concept studies (e.g., robotics, control) where discontinuities are critical and model size is manageable.
Hybrid Systems: Models combining neural nets with symbolic logic, where discrete decisions are unavoidable.
Specialized Hardware: Custom accelerators designed for sparse computation (e.g., Cerebras, SambaNova), though these are rare.
4. The Dominant Alternative: Soft Top-K Gating
Modern MoE frameworks use soft top-K gating for stability and efficiency:
While hard top-K gating with gradient pass-through (STE) is technically possible, it is rarely used in large-scale MoE models due to:
Training instability from noisy STE gradients.
Hardware inefficiency from irregular computation.
Redundancy with soft gating, which provides tunable sharpness without STE.
Load-balancing challenges exacerbated by discrete selection.
Instead, soft top-K gating dominates because it balances sparsity, stability, and efficiency. The trade-off is a small computational overhead (computing all experts), but this is outweighed by smoother training and better hardware utilization. For tasks requiring true discontinuities, hybrid architectures (e.g., neural-symbolic systems) or specialized hardware may be more viable than hard-gated MoE.