Zucchetti LLM Course — Lecture 10
Mixture of Experts • Vision • Audio • Video
Two revolutions: how models SCALE and what they can PERCEIVE
Kamyar Zeinalipour
2 hours full theory • 10 min break at 60 min
§1 — MoE: From Dense to Sparse
§2 — MoE: The Router & Its Math
§3 — MoE: Models, Practice & Limitations
☕ Break — 10 minutes
§4 — Multimodal: The Universal Pattern (Image, Audio, Video)
§5 — Production Essentials — KV Cache, Serving, Cost
Section 1
Why dense models hit a wall — and how MoE fixes it
Every model in L1–L9 was dense — every param fires for every token
L1 — Transformer — attention + FFN
L2–3 — Tokenization, Prompting
L4–6 — RAG, Advanced RAG, Graph RAG
L7 — Agentic RAG
L8 — Evaluation
L9 — Fine-Tuning (LoRA)
L10 — MoE + Multimodal ⬅ TODAY
L1’s FFN block is where MoE happens
For a 7B model: $W_1$ + $W_2$ ≈ 4.7B params. ALL fire for EVERY token.
| Model | Params | Relative Cost |
|---|---|---|
| Llama 3 8B | 8B | 1× |
| Llama 3 70B | 70B | 8.75× |
| Llama 3 405B | 405B | 50× |
Can we have 400B of KNOWLEDGE but pay for 40B of COMPUTE?
Yes. MoE.
Replace ONE big FFN with N small expert FFNs — activate only K per token
Mixtral 8×7B: 47B total, ~13B active per token
47B knowledge. 13B compute. 3.6× efficiency.
“The” → E2, E6 • “cat” → E1, E5 • “sat” → E3, E7
Each token independently picks its own K experts. Same sequence, different experts.
📄 Shazeer et al. (ICLR 2017) — “Outrageously Large Neural Networks”
| Property | Dense 13B | MoE 47B (8×7B) |
|---|---|---|
| Active params | 13B | ~13B |
| Total params | 13B | 47B |
| Inference speed | Baseline | ~Same |
| Quality | Good | Better |
| Memory (FP16) | 26 GB | 94 GB |
Section 2
How tokens get routed to experts
$W_g \in \mathbb{R}^{N \times D}$ • Output: probability over N experts, sums to 1
Softmax output: [0.35, 0.28, 0.12, 0.08, 0.07, 0.05, 0.03, 0.02]
Expert 1 scored highest (0.35). Expert 8 lowest (0.02).
Adds noise to encourage exploration. Prevents router from converging too early. Removed at inference.
Mixtral: K=2 out of N=8. Top-2: [0.35, 0.28] → renormalized: [0.556, 0.444]
Experts 3–8 do ZERO computation. That’s the efficiency.
You get a dense model back. No sparsity. K must be << N.
Switch Transformer (Fedus 2022). Maximum sparsity, riskier.
Each active expert runs its FFN independently. Outputs weighted by gating score and summed.
Without regularization → 90% of tokens go to 1–2 experts → other experts learn nothing → 75% of params wasted
$f_i$ = fraction of tokens routed to expert i • $P_i$ = avg gating probability • $\alpha \approx 0.01$
Minimized when $f_i = P_i = 1/N$ — perfectly balanced.
📄 Switch Transformers (Fedus et al., JMLR 2022)
Within one MoE layer — what do the 8 experts learn?
| Token | Routed to | Pattern |
|---|---|---|
. , ; ! | E3 | Punctuation & delimiters |
42 3.14 2024 | E1 | Numbers & quantities |
the a an | E6 | Function words |
Bonjour café | E2 | French tokens |
def class import | E5 | Code syntax |
Not exclusive — E3 handles ~70% of punctuation, not 100%. Other experts share the load. And some experts are “generalists” that fire for many token types.
| L5: Semantic Router | L10: MoE Router | |
|---|---|---|
| What | Routes queries → data sources | Routes tokens → expert FFNs |
| How | Cosine similarity | Softmax gating |
| Where | Once per query | Every layer, every token |
| Learned? | Manual descriptions | Fully learned end-to-end |
Section 3
Real models, deployment, and limitations
| Model | N | K | Total | Active |
|---|---|---|---|---|
| Mixtral 8×7B | 8 | 2 | 47B | ~13B |
| Mixtral 8×22B | 8 | 2 | 141B | ~39B |
| DeepSeek-V2 | 160 | 6 | 236B | ~21B |
| DeepSeek-V3 | 256 | 8 | 671B | ~37B |
| Qwen2.5-MoE | 64 | 8 | 57B | ~14B |
| GPT-4 (rumored) | 16 | 2 | ~1.8T | ~220B |
Shared expert handles common knowledge (grammar, reasoning) for EVERY token. Routed experts specialize in niche knowledge.
📄 Mixtral (Jiang 2024) • DeepSeek-V2 (2024) • GShard (Lepikhin 2020)
Most common misconception about MoE
WRONG.
ALL N experts must be loaded. MoE saves COMPUTE, not MEMORY.
Mixtral 8×7B:
Memory: [E1][E2][E3][E4][E5][E6][E7][E8] = 47B loaded
Compute: [E1][E2] only = 13B active
4-bit quantized Mixtral ≈ 25 GB → fits on one A100.
① Replaces FFN from L1 with N experts + router. Attention stays identical.
② Router = softmax gating → top-K → weighted sum of expert outputs.
③ Load balancing loss prevents expert collapse.
④ MoE saves COMPUTE, not MEMORY. All experts must be loaded.
⑤ GPT-4, DeepSeek-V3, Mixtral all use MoE. This is the future.
10 minutes
Next: Multimodal — images, audio, video — any signal becomes tokens
Section 4
Any signal → encoder → projection → Transformer Decoder
ONE architecture for images, audio, video — everything
| Modality | Encoder | Tokens per Unit | Cost | Models |
|---|---|---|---|---|
| Text | BPE tokenizer | ~1.3 / word | Low | All LLMs |
| Image | ViT / SigLIP | ~576 / image | Medium | LLaVA, Qwen-VL |
| Audio | Whisper encoder | ~1,500 / 30s | High | Qwen2-Audio |
| Video | ViT + temporal | ~5,000+ / 10s | Very High | Gemini, GPT-4o |
Attention is $O(n^2)$. More tokens = quadratically more compute. This is the cost challenge.
Cutting a photo into post-it notes
Each patch (14×14×3 = 588 values) → flattened → multiplied by E (linear projection matrix) → one token vector
ViT output dimension ≠ decoder dimension — we need a bridge
One matrix multiply per token.
Keeps all 576 tokens.
→ Maximum information, higher cost.
32 learnable queries attend to 576 ViT features.
Compresses 576 → 32 (18×).
→ Less info, much lower cost.
Contrastive learning aligns images with text — this is WHY projection works
Maximize similarity of matching pairs. Minimize non-matching. $\tau$ = learned temperature.
Pairwise sigmoid → more memory-efficient, scales to larger batches.
📄 CLIP (Radford, ICML 2021) • SigLIP (Zhai, ICCV 2023) • BLIP-2 (Li, ICML 2023)
Whisper encoder = “ViT for audio”
📄 Radford et al. (2023) — Whisper
Human hearing is logarithmic — the spectrogram must respect that
A linear frequency axis wastes resolution. Humans perceive 100→200 Hz as the same “jump” as 1000→2000 Hz. Low frequencies (speech fundamentals) need more detail. High frequencies (hissing, noise) need less.
Maps linear Hz to perceived pitch. More frequency bins for low frequencies, fewer for high — matching how we actually hear.
30s speech = 1,500 tokens. Text query = 20–50 tokens. Audio is 30–75× more expensive.
Qwen2-Audio • Gemini 2.0 • GPT-4o
Video = sequence of images. Each image is hundreds of tokens.
| Sampling | Frames | Tokens |
|---|---|---|
| 10s @ 1fps | 10 | 5,760 |
| 10s @ 3fps | 30 | 17,280 |
| 1min @ 1fps | 60 | 34,560 |
① Universal pattern: Any Signal → Encoder → Projection → Transformer Decoder. Same architecture for all modalities. It’s now an LMM, not an LLM.
② CLIP/SigLIP contrastive training is WHY projection works — ViT features are already close to text.
③ Token costs explode: text (1/word) → image (576) → audio (1,500) → video (5,000+). Attention is $O(n^2)$.
④ In MoE models, different modalities may activate different experts. MoE + multimodal = synergy.
⑤ Practical tip: always validate multimodal extraction with business rules. Never trust raw output.
Scan → OCR → Cleanup → NLP → Output
5 failure points
Image → Model → JSON
Sees layout, structure
Role + Task + Schema + Rules → reliable structured extraction
Section 5
The 3 things you must know for serving
Naive MHA formula. But modern models use GQA:
$G = n_{heads}/n_{kv\_heads}$. Llama 3 8B: G=4 → KV cache 4× smaller (0.5 GB vs 2 GB per seq).
~40% memory waste
~4% waste → 2–4× more users
📄 vLLM (Kwon, SOSP 2023) • GQA (Ainslie, EMNLP 2023)
New requests join as old finish
2–10× throughput
2–3× speedup
| Engine | Key Feature | Best For |
|---|---|---|
| vLLM | PagedAttention | GPU serving |
| Ollama | One-command | Dev/edge |
| llama.cpp | C++, quantized | Embedded |
$0.28 / 1M
$2.50 / 1M
| Concept | Formula | L |
|---|---|---|
| Attention | $\text{softmax}(QK^T\!/\!\sqrt{d_k})\!\cdot\!V$ | 1 |
| Cosine Sim | $A\!\cdot\!B/(\|A\|\|B\|)$ | 1,4 |
| BM25 | $\Sigma\text{IDF}\!\cdot\!\text{TF}(k_1\!+\!1)/(...)$ | 4 |
| RRF | $\Sigma 1/(k+\text{rank}_i)$ | 5 |
| LoRA | $W'\!=\!W\!+\!(\alpha/r)BA$ | 9 |
| Dense FFN | $W_2\!\cdot\!\text{ReLU}(W_1 x)$ | 1,10 |
| MoE Gate | $\text{softmax}(W_g x)$ | 10 |
| Noisy Gate | $g(x)+\mathcal{N}(0,\text{SP}(W_n x))$ | 10 |
| MoE Out | $\Sigma G_i E_i$ | 10 |
| Shared Expert | $E_{sh}(x)+\Sigma G_i E_i$ | 10 |
| Balance | $\alpha N\Sigma f_i P_i$ | 10 |
| CLIP Loss | $-\frac{1}{N}\Sigma\log\frac{e^{s/\tau}}{\Sigma e^{s'/\tau}}$ | 10 |
| Mel Scale | $2595\log_{10}(1+f/700)$ | 10 |
| ViT Patches | $HW/P^2$ | 10 |
| KV Cache | $2LDSb$ | 10 |
| KV (GQA) | $2L(D/G)Sb$ | 10 |
| Spec Decode | $\min(1,p_t/p_d)$ | 10 |
| Cost/1M | $c/(t\!\times\!3600)\!\times\!10^6$ | 10 |
① MoE replaces FFN with N experts + router. Attention stays identical. Most frontier models use it.
② Universal pattern: Any Signal → Encoder → Projection → same attention from L1.
③ Token costs explode: text (1/word) → image (576) → audio (1,500) → video (5,000+).
④ KV cache + PagedAttention = serving bottleneck + solution.
⑤ Every lecture maps to a production component. Start simple, measure, iterate.
10 lectures — from attention to multimodal MoE systems.
Kamyar Zeinalipour — Zucchetti LLM Course