CS58700 - Foundations of Deep Learning¶

Spring 2026¶

Instructor and Copyright: Bruno Ribeiro¶


Transformers (Part 2)¶

1. Rotary Position Embeddings (RoPE)¶

Rotary Position Embeddings (RoPE) encode positional information by applying rotational transformations directly to embedding vectors.

  • Instead of adding fixed or learned position encodings, RoPE rotates pairs of embedding dimensions using position-dependent angles.
  • This approach naturally preserves vector norms and encodes relative positions through rotational invariance.

Core idea:

  • Let $\text{SO}(2)$ be the group of $2$-dimensional rotations.
  • RoPE creates positional embeddings for the $m$-th token by applying multiple $2\times 2$ rotations $R_{m,i} \in \text{SO}(2)$ to the embeddings of token $m$, $i \in \{0,1,\ldots,d/2-1\}$.
  • This use of $\text{SO}(2)$ transformations induces some useful properties to the positional embeddings.

Mathematical Formulation¶

1.1. Rotary Encoding Function¶

For a token at position $m$ and (pairwise) dimension index $i \in \{0,1,\ldots,d/2-1\}$, the rotation angle is defined as: $$ \theta_{m,i} = m \cdot 10000^{-2i/d} $$ where:

  • $m$ is the token's position in the sequence,
  • $d$ is the full embedding dimension of the token, and
  • $10000^{-2i/d}$ sets geometrically spaced frequencies across the dimensions.

1.2. Rotational Positional Encoding (RoPE): Mathematical Formulation¶

Rotation Operation¶

For an embedding vector $h_m$ of token $m$, the rotational transformation is applied to each dimension pairwise. This rotation encodes the positional information directly into the embedding space.

Individual Pair Rotation: For the $i$-th pair of dimensions in the embedding vector: $$ R_{\theta_{m,i}} \circ \begin{bmatrix} h_{m,2i} \\ h_{m,2i+1} \end{bmatrix} = \begin{bmatrix} \cos \theta_{m,i} & -\sin \theta_{m,i} \\ \sin \theta_{m,i} & \cos \theta_{m,i} \end{bmatrix} \begin{bmatrix} h_{m,2i} \\ h_{m,2i+1} \end{bmatrix} $$

The full transformation can be expressed as a block-diagonal matrix operation: $$ \text{RoPE}_\theta(h_m) = R_{\theta_m} \, h_m, $$ where $R_{\theta_m}$ is the block-diagonal matrix: $$ R_{\theta_m} = \begin{bmatrix} \cos \theta_{m,0} & -\sin \theta_{m,0} & 0 & 0 & \cdots & 0 & 0 \\ \sin \theta_{m,0} & \cos \theta_{m,0} & 0 & 0 & \cdots & 0 & 0 \\ 0 & 0 & \cos \theta_{m,1} & -\sin \theta_{m,1} & \cdots & 0 & 0 \\ 0 & 0 & \sin \theta_{m,1} & \cos \theta_{m,1} & \cdots & 0 & 0 \\ \vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ 0 & 0 & 0 & 0 & \cdots & \cos \theta_{m,d/2-1} & -\sin \theta_{m,d/2-1} \\ 0 & 0 & 0 & 0 & \cdots & \sin \theta_{m,d/2-1} & \cos \theta_{m,d/2-1} \end{bmatrix}. $$

Group Theoretic Properties¶

1.2.1. Closed under Composition + Translation Equivariance¶

For any shift $s$ in the sequence: $$\text{RoPE}_\theta(h, m+s) = R_{\theta_m+\theta_s} h = R_{\theta_m} R_{\theta_s} h = \text{RoPE}_\theta(\text{RoPE}_\theta(h, m), s)$$

  • This property ensures that the model's behavior is consistent under translations.
  • It also allows the model to more easily learn to relocate elements of the sequence.

1.2.2. Identity¶

  • $R_{\theta_0} = I$.

1.2.3. Inverse¶

For any shift $s$ in the sequence:

  • $R_{\theta_{-s}} = R_{\theta_s}^T$, since $R_{\theta_s} R_{\theta_{s}}^T = I$.
  • $\text{RoPE}_\theta(h, m-s) = \text{RoPE}_\theta(h, m) R^T_{\theta_s}$
  • This property ensures that we can compute the relative positions between two $\text{RoPE}$ rotated vectors.

1.2.4. Distance Preservation¶

Since the rotation matrices are orthogonal: $$\|\text{RoPE}_\theta(h, m)\| = \|h\|$$

  • This ensures that the positional encoding doesn't change the magnitude of the vectors, only their direction.
  • Gradient Stability: Orthogonal rotations ensure that gradients remain stable during backpropagation.

1.2.5. $G$-Invariance of RoPE in Attention¶

  • Let the group $G = (\mathbb{Z}, +)$ act on token positions via translation: $g \circ m = m + g$.
  • The map $s \mapsto R_{\theta_s}$ is a group representation $G \to \mathbb{R}^{d \times d}$, since:
    • (Homomorphism) $R_{\theta_{s_1}} R_{\theta_{s_2}} = R_{\theta_{s_1 + s_2}}$ — composition of two position shifts equals the shift of the sum (Section 1.2.1).
    • (Identity) $R_{\theta_0} = I$ (Section 1.2.2).
    • (Inverse) $R_{\theta_{-s}} = R_{\theta_s}^T = R_{\theta_s}^{-1}$ (Section 1.2.3).
  • RoPE encodes position $m$ into query and key vectors via this representation: $$q_m \mapsto R_{\theta_m}\, q_m, \qquad k_n \mapsto R_{\theta_n}\, k_n.$$

$G$-Invariance of the Attention Kernel¶

  • Recall that a function is $G$-invariant iff $\forall g \in G$, transforming the input does not change the output.

    • Define the attention score function $\kappa: \mathbb{R}^d \times \mathbb{R}^d \times \mathbb{Z} \times \mathbb{Z} \to \mathbb{R}$: $$\kappa(q, k, m, n) = \langle R_{\theta_m}\, q,\; R_{\theta_n}\, k \rangle = q^\top R_{\theta_m}^\top R_{\theta_n}\, k = q^\top R_{\theta_{n-m}}\, k.$$
  • The last equality uses the homomorphism and inverse properties: $R_{\theta_m}^{-1} = R_{\theta_{-m}}$ and $R_{\theta_{-m}} R_{\theta_n} = R_{\theta_{n-m}}$.

  • The group $G$ acts on position pairs by diagonal translation: $g \cdot (m, n) = (m+g,\, n+g)$.

  • We can verify the $G$-invariance directly: $$\forall g \in G, \quad \kappa(q, k, m+g, n+g) = q^\top R_{\theta_{(n+g)-(m+g)}}\, k = q^\top R_{\theta_{n-m}}\, k = \kappa(q, k, m, n).$$

  • This is exactly the special case from our earlier lectures where $\rho_2(g) = I$ (the trivial representation on the output):

  • Invariance is equivariance with a trivial output representation.

  • The attention score is $G$-invariant under position translation — it depends only on the relative offset $n - m$.

Norm Preservation (Orthogonality of $R_{\theta_s}$)¶

  • Since $R_{\theta_s} \in SO(2)^{d/2}$, we have $R_{\theta_s}^{-1} = R_{\theta_s}^\top$, so: $$\|R_{\theta_s}\, q\| = \|q\|, \quad \forall s \in \mathbb{Z}, \; \forall q \in \mathbb{R}^d.$$
  • The representation preserves the geometry of the embedding space:
    • Positional encoding introduces no distortion to norms or inner products between vectors at the same position.
    • The transformation is invertible — no information is lost.

1.3. Implementation Considerations¶

1.3.1. Example Python Implementation¶

Below is a simplified code snippet that demonstrates applying RoPE to an embedding matrix:

import numpy as np

def apply_rope(x, freqs):
    """
    Apply RoPE to the input embeddings.
    
    Parameters:
      x: numpy array of shape (seq_len, d)
      freqs: numpy array of shape (seq_len, d/2) containing precomputed rotation angles
      
    Returns:
      A numpy array with rotary position encoding applied to x.
    """
    seq_len, d = x.shape
    cos_vals = np.cos(freqs)  # shape: (seq_len, d/2)
    sin_vals = np.sin(freqs)  # shape: (seq_len, d/2)
    
    # Split the embeddings into pairs
    x_even = x[:, 0::2]
    x_odd = x[:, 1::2]
    
    # Apply rotation to each pair
    rotated_even = x_even * cos_vals - x_odd * sin_vals
    rotated_odd = x_even * sin_vals + x_odd * cos_vals
    
    # Interleave the rotated components
    x_rotated = np.empty_like(x)
    x_rotated[:, 0::2] = rotated_even
    x_rotated[:, 1::2] = rotated_odd
    
    return x_rotated

2. Supervised Fine-Tuning (SFT)¶

Pre-training produces a language model that is excellent at predicting the next token over the training distribution (mostly web text). However, this does not automatically make the model a useful assistant. Supervised Fine-Tuning (SFT) is the first and most fundamental step in aligning a pre-trained base model to follow instructions, answer questions, and engage in helpful dialogue.

Pre-trained Base Model  ──SFT──►  Instruction-Following Model  ──RLHF/DPO──►  Aligned Assistant
   (next-token prediction)           (follows user intent)                       (safe, helpful)

2.1. Pre-training vs. Supervised Fine-Tuning¶

It is important to understand the distinction between pre-training and SFT before describing their objectives:

Pre-training Supervised Fine-Tuning
Data Massive unlabeled web corpora (trillions of tokens) Curated (prompt, response) pairs (thousands–millions)
Objective Next-token prediction on raw text Next-token prediction only on the response portion
Duration Weeks on thousands of GPUs Hours to days on tens of GPUs
Goal Learn world knowledge and language structure Teach the model to follow the instruction format
Risk Underfitting (need more data/compute) Overfitting (need regularization / PEFT)

A pre-trained base model (e.g., Llama 3 base) completes text but does not "know" it is supposed to answer a question. SFT teaches it the input–output contract: given a user instruction, produce a helpful response.

2.2. Instruction Tuning¶

Instruction tuning (Wei et al., 2022 FLAN; Longpre et al., 2023 FLAN-v2) is the most basic form of SFT, where the model is trained on a large collection of (instruction, response) pairs that cover diverse tasks:

  • Summarization: "Summarize the following article: ..." → "The article discusses ..."
  • Translation: "Translate to French: ..." → "..."
  • Classification: "Is this review positive or negative? ..." → "Positive"
  • Question answering: "Who wrote Hamlet?" → "William Shakespeare"

Key insight: Training on diverse tasks in an instruction format leads to generalization to unseen task types at test time — even tasks not present in the fine-tuning set. This is because the model learns the meta-skill of "read the instruction carefully and respond accordingly."

2.2.1. Data Format¶

Each SFT example is a pair $(x_i, y_i)$ where $x_i$ is the prompt (instruction + optional context) and $y_i$ is the target response. These are concatenated into a single sequence for training:

$$\underbrace{x_i}_{\text{prompt (masked)}}\;\underbrace{y_i}_{\text{response (trained on)}}$$

A critical implementation detail: the loss is computed only on the response tokens $y_i$, not on the prompt tokens $x_i$. This is called prompt masking (or response-only loss):

$$\mathcal{L}_{\text{SFT}}(\theta) = -\frac{1}{N} \sum_{i=1}^{N} \sum_{t=1}^{|y_i|} \log p\!\left(y_{i,t} \;\middle|\; x_i, y_{i,<t};\, \theta\right)$$

Without prompt masking, the model wastes capacity learning to predict the instruction tokens, which are not what we care about — and in practice this slightly harms convergence.

# Simplified illustration of prompt-masked SFT loss in PyTorch
import torch
import torch.nn.functional as F

def sft_loss(logits, labels, prompt_lengths):
    """
    logits: (batch, seq_len, vocab_size)
    labels: (batch, seq_len)  -- token ids
    prompt_lengths: (batch,)  -- number of prompt tokens per example
    """
    batch_size, seq_len, vocab_size = logits.shape
    loss_mask = torch.zeros(batch_size, seq_len, dtype=torch.bool)
    for i, pl in enumerate(prompt_lengths):
        loss_mask[i, pl:] = True   # only compute loss on response tokens

    shift_logits = logits[:, :-1].contiguous()
    shift_labels = labels[:, 1:].contiguous()
    shift_mask   = loss_mask[:, 1:].contiguous()

    loss = F.cross_entropy(
        shift_logits.view(-1, vocab_size),
        shift_labels.view(-1),
        reduction='none'
    )
    loss = loss.view(batch_size, -1)
    return (loss * shift_mask).sum() / shift_mask.sum()

2.3. Chat Fine-Tuning and Instruction Templates¶

Modern LLM assistants are conversational (multi-turn). Chat fine-tuning trains the model on multi-turn dialogue datasets using a structured chat template that separates system instructions, user turns, and assistant turns.

2.3.1. Chat Template Structure¶

A chat template wraps each turn with special tokens (e.g. Qwen 3.5):

<|im_start|>system
You are a helpful, harmless, and honest AI assistant.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
The capital of France is Paris.<|im_end|>
<|im_start|>user
What is its population?<|im_end|>

The model is trained to predict only the <|im_start|>assistant turns; all other tokens are masked out in the loss. Different models use different special tokens (e.g., Llama 3 uses <|begin_of_text|>, <|start_header_id|>user<|end_header_id|>, etc.), but the principle is the same.

2.3.2. SFT Datasets¶

Key open-source datasets used for SFT:

Dataset Size Description
FLAN (Wei et al., 2022) ~1.8K tasks Templates over 62 NLP datasets
Alpaca (Taori et al., 2023) 52K GPT-3.5-generated instruction pairs
ShareGPT ~90K Real user–ChatGPT conversations
OpenAssistant (Kopf et al., 2023) 161K Human-annotated dialogue trees
Dolly (Conover et al., 2023) 15K Human-written instructions

In practice, the highest-quality SFT data is human-written or carefully human-curated. Data quality matters far more than quantity for SFT — a few thousand high-quality examples often outperform millions of noisy ones.

Announcement¶

  • No class this Thursday (final report due, no-penalty extension until May 1st)

A. Add Diffusion Models

B. Keep focus on RL for LLMs.

Question¶

You are post-training an autoregressive LLM. Your goal is to learn three new tasks — A, B, and C — while also preserving the model's general language capabilities from pretraining. Which procedure best achieves both goals?

A. Train sequentially: fine-tune on task A until convergence, then fine-tune the result on task B until convergence, then fine-tune the result on task C until convergence.

B. Multi-task training: at every step, compute the average loss across A, B, and C, and backpropagate a single combined gradient. Train until convergence.

C. Multi-task training with a PCGrad-like method: at every step, compute per-task gradients for A, B, and C; project away conflicting components; then update. Train until convergence.

D. Multi-task training with a PCGrad-like method: same as C, but stop training after a limited number of gradient steps — well before convergence on A, B, and C.

E. Multi-task training with a PCGrad-like method: same as C, but add the original next-token prediction objective as a fourth task, treating all four task gradients separately with PCGrad. Train until convergence.

Answer and explanation¶

Correct answer: E

Option Multi-task? Handles gradient conflict? Preserves pretraining? Trains to convergence?
A ✗ ✗ ✗ —
B ✓ ✗ ✗ ✓
C ✓ ✓ ✗ ✓
D ✓ ✓ ✗ (heuristic) ✗
E ✓ ✓ ✓ ✓
  • A — Sequential meta-learning is difficult than parallel meta-learning. Fine-tuning causes catastrophic forgetting: each stage overwrites weights from prior stages, and the final model has largely forgotten tasks A and B and drifted far from its pretraining distribution.
  • B — Summing raw task gradients means conflicting gradients cancel or interfere. Training to convergence also erases the pretraining distribution; nothing anchors the model to general language knowledge.
  • C — PCGrad eliminates destructive interference between A, B, and C. However, training to convergence without a pretraining anchor still causes the model to forget its general language capabilities.
  • D — Early stopping limits weight drift, reducing forgetting of pretraining, but it is an unprincipled heuristic: training stops not because the tasks are learned, but to limit drift. Task performance is sacrificed without a principled reason.
  • E — Re-introducing next-token prediction as a fourth PCGrad task anchors the model to its pretraining distribution in a principled way. Gradient conflicts between the new tasks and the pretraining objective are resolved by projection rather than ignored. The model can train to convergence on all tasks without forgetting general language capabilities.

2.4. Full Fine-Tuning vs. Parameter-Efficient Fine-Tuning¶

With the SFT objective defined, there are two broad strategies for how to update model weights:

Full Fine-Tuning updates all model parameters $\theta$: $$\theta \leftarrow \theta - \alpha \nabla_\theta \mathcal{L}_{\text{SFT}}(\theta)$$

  • Pros: maximum expressivity; the model can fully adapt to the target distribution.
  • Cons: requires storing a full copy of gradients and optimizer states (e.g., Adam stores $2|\theta|$ additional values), making it ~3× the model size in memory. For a 70B model, this requires hundreds of GB of GPU memory.

Parameter-Efficient Fine-Tuning (PEFT) freezes most parameters and updates only a small subset: $$\theta' = \theta_{\text{frozen}} + \Delta\theta_{\text{trainable}}, \quad |\Delta\theta| \ll |\theta|$$

  • Pros: drastically reduced memory and storage; less overfitting risk; multiple task-specific adapters can share one base model.
  • Cons: slightly lower ceiling than full fine-tuning, especially for distribution shift tasks.

Rule of thumb: For tasks similar to the pre-training distribution (e.g., general chat, summarization), PEFT methods like LoRA achieve near full fine-tuning performance. For large distribution shifts (e.g., fine-tuning a text model on code or math), full fine-tuning is preferred when compute allows.

2.4.1. Supervised Fine-Tuning's Negative Log-Likelihood (NLL) Objective¶

The full NLL objective of SFT applies to both full fine-tuning and PEFT:

  • Given a fine-tuning dataset $\mathcal{D} = \{(x_i, y_i)\}_{i=1}^N$, where $x_i$ represents the input prompt and $y_i$ the target response, the NLL objective is:

$$\mathcal{L}_{NLL}(\mathbf{W}_1,\ldots,\mathbf{W}_m) = -\frac{1}{N} \sum_{i=1}^N \log p(y_i | x_i; \mathbf{W}_1,\ldots,\mathbf{W}_m)$$

where $p(y_i | x_i; \mathbf{W}_1,\ldots,\mathbf{W}_m)$ is the probability of the target response $y_i$ given the prompt $x_i$ and model parameters.

  • The goal of SFT is to minimize the NLL objective without significantly altering the model's pre-trained knowledge representations.
  • Generally, in fine-tuning, only a limited number of gradient steps are taken (typically 1–3 epochs).
  • Fine-tuning is a form of sequential meta-learning as described earlier in the course.

Challenges with NLL in SFT¶

While the NLL objective is widely used in SFT, there are some known challenges:

  1. Overfitting: With large models and small datasets, the model can memorize training examples. Parameter-Efficient Fine-Tuning (Section 2.5) directly mitigates this by reducing the number of trainable parameters.
  2. Exposure bias: The model is trained on ground-truth tokens but must generate its own tokens at inference. Errors compound since generated tokens may fall outside the training distribution.
  3. Data biases: When $y_i$ is heavily skewed toward certain answers, techniques like weighted cross-entropy or data resampling help address imbalance.
  4. Forgetting: Aggressive SFT can cause catastrophic forgetting of pre-trained capabilities. This motivates PEFT methods and conservative learning rate schedules.

2.5. Parameter-Efficient Fine-Tuning: Low-Rank Adaptation (LoRA)¶

  • State-of-the-art LLMs contain hundreds of billions of parameters.
  • Full fine-tuning updates all parameters — expensive in compute and storage.
  • Key insight: not all parameters need to be updated.

Which Parameters to Fine-Tune?¶

  • Most common: fine-tune the upper (closer to output) transformer blocks.
    • Reduces the depth of backpropagation required.
    • Recent work suggests lower layers can yield better results, but at higher cost.
  • LoRA is typically applied selectively to specific weight matrices:
    • Attention layers only (query, key, value projections) — often the best efficiency/performance ratio.
    • Specific transformer blocks (e.g., later layers).
    • Both attention and feed-forward layers.

2.5.1. LoRA Fine-Tuning¶

  • In standard fine-tuning, we update a pre-trained weight matrix $W_i \in \mathbb{R}^{d \times k}$: $$W'_i = W_i + \Delta W_i.$$
  • For LLMs, $\Delta W_i \in \mathbb{R}^{d \times k}$ has $d \times k$ parameters — very expensive to compute and store.

Low-Rank Hypothesis¶

  • Eckart–Young–Mirsky theorem (from the graph representations lecture): the best rank-$r$ approximation to any matrix $M$ is: $$M_r = \sum_{j=1}^{r} \sigma_j \, u_j \, v_j^\top,$$
    • where $\sigma_j$, $u_j$, $v_j$ are the $j$-th singular value and corresponding left/right singular vectors of $M$.
  • Hypothesis: the weight update $\Delta W_i$ needed for task adaptation has low intrinsic rank.

LoRA Decomposition¶

  • Decompose the update as a product of two low-rank matrices: $$\Delta W_i = B_i \, A_i, \qquad B_i \in \mathbb{R}^{d \times r}, \quad A_i \in \mathbb{R}^{r \times k}, \quad r \ll \min(d, k).$$
  • The adapted forward pass for input $h_1$: $$h_2 = W'_i \, h_1 = W_i \, h_1 + B_i \, A_i \, h_1.$$
  • Parameter count:
    • Full update: $d \times k$ parameters.
    • LoRA update: $r \times (d + k)$ parameters.
    • Since $r \ll \min(d, k)$, this is a significant reduction.

2.5.1.1. Connecting LoRA to SVD¶

  • Consider the SVD of the weight update: $$\Delta W_i = U_i \, \Sigma_i \, V_i^\top,$$
    • $U_i \in \mathbb{R}^{d \times d}$: left singular vectors.
    • $\Sigma_i \in \mathbb{R}^{d \times k}$: diagonal matrix of singular values.
    • $V_i \in \mathbb{R}^{k \times k}$: right singular vectors.
  • Retain only the top $r$ singular values: $$\Delta W_i \approx U_i^{(r)} \, \Sigma_i^{(r)} \, (V_i^{(r)})^\top.$$
  • Split the singular values symmetrically to obtain the LoRA matrices: $$B_i = U_i^{(r)} \, (\Sigma_i^{(r)})^{1/2}, \qquad A_i = (\Sigma_i^{(r)})^{1/2} \, (V_i^{(r)})^\top.$$
  • Interpretation: LoRA learns updates along the most important eigenvector directions in the parameter space for the target task.

Impact of Rank $r$¶

  • $r$ controls the trade-off between adaptation capacity and parameter efficiency:
    • Higher $r$ → more capacity to adapt, but more parameters.
    • Lower $r$ → more efficient, but may limit adaptation.
  • Empirically, small ranks ($r = 4, 8, 16$) often suffice — supporting the low intrinsic dimensionality hypothesis.

2.5.3. Variants of LoRA¶

QLoRA (Quantized LoRA)¶

  • Combines quantization of $W_i$ with low-rank adaptation of $\Delta W_i$:
    • Pre-trained weights $W_i$: quantized to 4-bit or 8-bit.
    • LoRA parameters $B_i$, $A_i$: kept in higher precision (e.g., 16-bit).
    • Additional techniques: paged optimizers, double quantization.
  • Effect: enables fine-tuning of larger models on limited hardware with minimal performance loss.

Rank-Adaptive LoRA¶

  • Instead of a fixed rank $r$ for all layers, dynamically determine $r$ per layer:
    • SVD-based: use the singular value distribution of gradients to set per-layer ranks.
    • Pruning-based: start with high $r$, prune less important directions during training.
    • Progressive growth: gradually increase $r$ during training.
  • Effect: allocates more capacity to layers that need more adaptation.

GLoRA (Grouped LoRA)¶

  • Organizes parameters into groups, each with its own low-rank adaptation:
    • Enables different adaptation strategies for different components (e.g., attention vs. feed-forward).
    • More flexible than a single global rank.

3. Beyond the Standard Transformer: MoE, SSMs, and Linear Attention¶

Core tension in standard transformers: all parameters active for every token, every layer, every forward pass — hard coupling of capacity and compute.

Two complementary approaches break this:

  • MoE — decouple storage from compute via sparse expert routing.
  • Linear sequence models — replace $O(n^2)$ attention with $O(n)$ recurrence.

3.1. Mixture-of-Experts (MoE)¶

3.1.1. Motivation¶

  • Scaling laws (Kaplan et al. 2020; Hoffmann et al. 2022) show quality $\propto$ params and compute.
  • Dense transformers tie them: doubling params $\Rightarrow$ doubling FLOPs per token.
  • MoE insight: not all knowledge needed for every token — route each token to a specialist subset.

3.1.2. Architecture¶

Replace the single FFN with $E$ parallel expert FFNs + a router:

$$\text{MoE}(\mathbf{z}_i) = \sum_{e=1}^{E} g_e(\mathbf{z}_i)\cdot\text{FFN}_e(\mathbf{z}_i)$$

Router (top-$k$ gating):

$$\mathbf{g}(\mathbf{z}_i) = \text{softmax}\!\left(\text{top-}k\!\left(\mathbf{z}_i \mathbf{W}_{\text{router}}\right)\right)$$

  • Top-$k$ sets all but $k$ largest logits to $-\infty$ before softmax $\Rightarrow$ exactly $k$ experts active.
  • Typical: $k=1$ or $k=2$.

Shared expert (DeepSeek-V2/V3, Jamba):

$$\text{MoE+shared}(\mathbf{z}_i) = \text{FFN}_{\text{shared}}(\mathbf{z}_i) + \sum_{e \in \text{top-}k} g_e(\mathbf{z}_i)\cdot\text{FFN}_e(\mathbf{z}_i)$$

  • Always-active residual path for universally useful transformations.
  • Routed experts specialize; shared expert stabilizes.

3.1.3. Load Balancing¶

Problem: naïve routing collapses — router sends all tokens to the same few experts (expert collapse).

Auxiliary loss (Switch Transformer, Fedus et al. 2021):

$$\mathcal{L}_{\text{bal}} = \alpha \cdot E \sum_{e=1}^{E} f_e \cdot p_e$$

  • $f_e$ = fraction of tokens routed to expert $e$ (routing decision).
  • $p_e$ = mean routing probability for expert $e$ (differentiable).
  • Minimized when load is uniform; $\alpha \approx 10^{-2}$ keeps it from dominating NLL.
  • Expert capacity: hard token budget per expert per batch; overflowing tokens are dropped (pass via residual).

3.1.4. Dense vs. MoE — Summary¶

Dense Sparse MoE
FFN params per block $8d^2$ $E\cdot 8d^2$
Active params per token $8d^2$ $k\cdot 8d^2,\; k\ll E$
FLOPs per token $\propto d^2$ $\propto k\cdot d^2$
Memory Small Large ($E\times$)
Training stability High Needs load-balancing
Examples Llama 3, Gemma Mixtral 8×7B, DeepSeek-V3

3.2. State Space Models (SSMs) and Mamba¶

3.2.1. Why Replace Attention?¶

  • Self-attention: $O(n^2 d)$ FLOPs, $O(n^2)$ memory (attention matrix).
  • Flash Attention 2: reduces memory to $O(n)$ via tiling, but FLOPs still $O(n^2)$.
  • At $n=128$K: $128000^2 \approx 1.6\times 10^{10}$ entries per head per layer.
  • SSMs offer $O(n)$ FLOPs and $O(1)$ state memory at inference via recurrence.

3.2.2. Linear SSM¶

Maps input $u_t \in \mathbb{R}$ to output $y_t \in \mathbb{R}$ through latent state $\mathbf{h}_t \in \mathbb{R}^N$:

$$\mathbf{h}_t = \bar{\mathbf{A}}\mathbf{h}_{t-1} + \bar{\mathbf{B}}u_t, \qquad y_t = \mathbf{C}\mathbf{h}_t$$

Discretized from continuous-time $(\mathbf{A},\mathbf{B},\mathbf{C})$ with step size $\Delta$ (zero-order hold):

$$\bar{\mathbf{A}} = e^{\Delta\mathbf{A}},\qquad \bar{\mathbf{B}} = (\Delta\mathbf{A})^{-1}(e^{\Delta\mathbf{A}}-\mathbf{I})\,\Delta\mathbf{B}$$

Two equivalent views:

  • Recurrent (inference): update fixed-size state $\mathbf{h}_t$ one token at a time — $O(1)$ memory, $O(n)$ total.
  • Convolutional (training): output = global convolution with kernel $\bar{\mathbf{K}} = (\mathbf{C}\bar{\mathbf{B}},\,\mathbf{C}\bar{\mathbf{A}}\bar{\mathbf{B}},\ldots)$ — computed in $O(n\log n)$ via FFT.

Weakness: $\mathbf{A},\mathbf{B},\mathbf{C}$ are input-independent (time-invariant) — cannot selectively remember/forget based on content.

3.2.3. Mamba: Selective SSM (Gu & Dao, 2023)¶

Make $\mathbf{B},\mathbf{C},\Delta$ input-dependent via learned projections:

$$\mathbf{B}_t = s_B(u_t),\quad \mathbf{C}_t = s_C(u_t),\quad \Delta_t = \text{softplus}(s_\Delta(u_t))$$

Selective forgetting via $\Delta_t$:

  • Large $\Delta_t$ $\Rightarrow$ $\bar{\mathbf{A}} \approx \mathbf{0}$ — forget past state, focus on current input.
  • Small $\Delta_t$ $\Rightarrow$ $\bar{\mathbf{A}} \approx \mathbf{I}$ — preserve past state, ignore current input.

Training: selectivity breaks convolutional equivalence $\Rightarrow$ use hardware-aware parallel scan (GPU prefix sums).

Attention vs. Mamba:

Self-Attention Mamba
Time complexity $O(n^2 d)$ $O(nd^2)$
Memory (training) $O(n^2)$ $O(d)$ fixed state
Inference cost/token $O(nd)$ (KV cache grows) $O(d^2)$ constant in $n$
In-context retrieval Exact Lossy (compressed state)
Position encoding Required (RoPE etc.) Not needed (recurrence is ordered)

Trade-off: attention = exact but expensive; Mamba = constant-memory but lossy compression.

3.3. Gated DeltaNet (GDN)¶

3.3.1. From SSMs to DeltaNet¶

DeltaNet (Schlag et al. 2021; Yang et al. 2024) frames the SSM state as a key-value memory matrix $\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}$ and updates it using the delta rule — a Hebbian-style associative memory update that corrects the current stored value rather than merely accumulating:

$$\mathbf{S}_t = \beta_t\,\mathbf{S}_{t-1} + \mathbf{v}_t\mathbf{k}_t^\top - \beta_t(\mathbf{S}_{t-1}\mathbf{k}_t)\mathbf{k}_t^\top$$

  • $\mathbf{v}_t, \mathbf{k}_t$ — value/key projections of $\mathbf{x}_t$.
  • The third term $\beta_t(\mathbf{S}_{t-1}\mathbf{k}_t)\mathbf{k}_t^\top$ erases the old value stored at key $\mathbf{k}_t$ before writing the new one — a "surgical" overwrite rather than additive accumulation.
  • Scalar $\beta_t \in (0,1)$ controls global decay.

3.3.2. Gated DeltaNet: Input-Dependent Gates¶

Gated DeltaNet (Yang et al. 2024) replaces the scalar $\beta_t$ with two input-dependent gate vectors:

$$\mathbf{g}_\Delta = \sigma\!\big(\mathbf{W}_\Delta[\mathbf{h}_{t-1};\mathbf{x}_t]\big), \qquad \mathbf{g}_{\text{upd}} = \sigma\!\big(\mathbf{W}_{\text{upd}}[\mathbf{h}_{t-1};\mathbf{x}_t]\big)$$

($\sigma$ = sigmoid; $[\cdot;\cdot]$ = concatenation along feature dim.)

State update:

$$\mathbf{S}_t = \mathbf{g}_\Delta \odot \mathbf{S}_{t-1} + \mathbf{g}_{\text{upd}} \odot \Big(\mathbf{V}_t\mathbf{K}_t^\top - \mathbf{S}_{t-1}\mathbf{K}_t\mathbf{K}_t^\top\Big)$$

  • $\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}$ — memory state (often low-rank factorised as $\mathbf{S}_t = \mathbf{U}_t\mathbf{V}_t^\top$ to reduce cost).
  • $\mathbf{V}_t \in \mathbb{R}^{d_v \times 1}$, $\mathbf{K}_t \in \mathbb{R}^{d_k \times 1}$ — value/key projections of $\mathbf{x}_t$.
  • $\mathbf{g}_\Delta$ — decay gate: per-element control of how much old memory to retain ($\approx 0$ = forget, $\approx 1$ = keep).
  • $\mathbf{g}_{\text{upd}}$ — update gate: per-element control of how large a correction to apply.

Output:

$$y_t = \mathbf{C}\,\mathbf{S}_t\,\mathbf{Q}_t$$

where $\mathbf{Q}_t$ is a query projection of $\mathbf{x}_t$ and $\mathbf{C}$ is a learned output mixing matrix.

3.3.3. Connection to Mamba and Attention¶

Mamba GDN Softmax Attention
State type Vector $\mathbf{h}_t \in \mathbb{R}^N$ Matrix $\mathbf{S}_t \in \mathbb{R}^{d_v \times d_k}$ Explicit KV cache (grows with $n$)
Input dependence $\mathbf{B}_t,\mathbf{C}_t,\Delta_t$ via linear proj Forget gate $\mathbf{g}_\Delta$, update gate $\mathbf{g}_{\text{upd}}$ Full $n\times n$ attention scores
Write mechanism Additive accumulation Delta-rule correction (erase then write) No write — read-only over stored KV
Read mechanism $y_t = \mathbf{C}_t\mathbf{h}_t$ $y_t = \mathbf{C}\mathbf{S}_t\mathbf{Q}_t$ Softmax-weighted sum of $\mathbf{V}$
FLOPs/token $O(Nd)$ $O(d^2)$ $O(nd)$ (grows with context)
Memory $O(N)$ $O(d^2)$ $O(nd)$ (KV cache)
Precise recall Weak Better than Mamba Exact

Key distinction from Mamba:

  • Mamba's state $\mathbf{h}_t$ is a vector — scalar mixing of all past inputs.
  • GDN's state $\mathbf{S}_t$ is a matrix — associative key-value store that can address specific memories via $\mathbf{Q}_t$.
  • The delta-rule correction gives GDN the ability to overwrite stale associations, not just decay them — closer in spirit to attention's exact lookup.

3.3.4. Complexity¶

Type FLOPs Inference memory Training parallelism
Softmax attention $O(n^2 d)$ $O(nd)$ KV cache Full parallel (matmul)
Mamba $O(nd^2)$ $O(d)$ fixed Parallel scan
GDN $O(nd^2)$ $O(d^2)$ fixed Chunk-wise scan
  • GDN state size $O(d^2)$ is larger than Mamba's $O(d)$ vector state, but still independent of $n$.
  • Training: chunk the sequence into blocks; within each chunk use parallel matmul; across chunks use sequential state passing.

3.3.5. Architecture Comparison¶

Dense Transformer MoE Transformer Mamba GDN
Attention Every layer, $O(n^2)$ Every layer, $O(n^2)$ None None
Sequence FLOPs $O(n^2 d)$ $O(n^2 d)$ $O(nd^2)$ $O(nd^2)$
Inference mem/layer $O(nd)$ KV $O(nd)$ KV $O(d)$ state $O(d^2)$ state
Write mechanism Read-only KV Read-only KV Additive+decay Delta-rule erase+write
Retrieval quality Exact Exact Lossy Better than Mamba
Long-context cost Expensive Expensive Cheap Cheap
Examples Llama 3, GPT-4 Mixtral, DeepSeek Mamba-2 GDN, HGRN2

¶

3.3.6. When to Use Which¶

  • Short context, quality-critical (≤32K): Dense transformer. Quadratic cost manageable; best retrieval.
  • Large capacity, same compute budget: MoE transformer. Activate less per token for same parameter size. Not as factual as a dense model with same parameter size (due to reduction in FFN hidden layer size).
  • Long context, smooth integration: Mamba. $O(d)$ constant state; strong on summarization, weak on precise recall.
  • Long context + associative recall: GDN. Matrix state enables key-addressed reads; better recall than Mamba at same $O(n)$ cost.

Research frontier: Hybrid models combining a small number of attention layers with GDN layers (analogous to Jamba for Mamba) are an active area — the open questions are the optimal attention:GDN ratio, whether GDN's matrix state can be low-rank approximated without quality loss, and how GDN interacts with MoE routing.

In [ ]: