Chapter 05 — Modern LLMs

Qwen: Alibaba's Reasoning-Focused LLM

How Alibaba built a frontier language model with Rotary Position Embeddings, SwiGLU activations, Grouped-Query Attention, and advanced chain-of-thought reasoning — competing with the best models worldwide.

Overview

Qwen (通义千问) is Alibaba Cloud's family of large language models. Starting from Qwen-7B in 2023, the series has grown to include Qwen2.5 models from 0.5B to 72B parameters, with state-of-the-art performance across coding, math, and reasoning benchmarks.

Qwen follows the modern decoder-only GPT architecture but incorporates several innovations that have become standard across frontier LLMs (LLaMA, Mistral, Gemma also use many of these):

Architecture

Linear + Softmax → Next Token
↑
RMSNorm (final)
↑
× N layers (e.g., 32 for 7B)
RMSNorm
↑
SwiGLU FFN (8/3 × d)
↑ + residual
RMSNorm
↑
GQA + RoPE
↑ + residual
Token Embedding (no position emb added here)
Fig 1. Qwen's architecture. Key differences from GPT-2: RMSNorm replaces LayerNorm, SwiGLU replaces FFN+ReLU, GQA replaces MHA, RoPE replaces learned position embeddings.

RoPE: Rotary Position Embeddings

RoPE (Su et al., 2021) encodes position information by rotating the query and key vectors in 2D subspaces. Instead of adding position information, RoPE multiplies it in:

Where the rotation matrix operates on pairs of dimensions:

Why RoPE is Elegant

The key property: the dot product between two RoPE-transformed vectors depends only on their relative position:

⚡ Benefits over Learned Positions

RoPE enables length extrapolation — the model can handle sequences longer than it was trained on. Combined with techniques like NTK-scaling or YaRN, Qwen can extend from 8K training length to 32K+ at inference.

Rotation Visualization
Each pair of dimensions is rotated by an angle proportional to the position. Lower dimensions rotate slowly (capturing long-range patterns), higher dimensions rotate fast (capturing nearby patterns).

SwiGLU Activation

SwiGLU (Shazeer, 2020) replaces the standard FFN with a gated variant that outperforms ReLU and GELU:

Compared to standard FFN:

ArchitectureFormulaParameters
Standard FFNmax(0, xW₁ + b₁)W₂ + b₂2 × d × d_ff
SwiGLU FFN(Swish(xW₁) ⊗ xV) W₂3 × d × d_ff

SwiGLU uses 3 weight matrices instead of 2, but with a smaller to keep the same parameter count as a standard 4d FFN. The gating mechanism lets the model selectively filter information.

💡 Why Gating Helps

The gate learns to suppress or amplify different features. Think of it as the model learning "what to keep" (gate) vs "what to compute" (Swish branch). This additive mixture consistently outperforms single-branch activations.

Grouped-Query Attention in Qwen

Qwen uses GQA to reduce the KV cache during inference. For example, Qwen2.5-7B uses 28 query heads but only 4 KV heads — a 7× reduction in KV cache memory:

Qwen2.5 ModelLayersd_modelQ HeadsKV HeadsParams
0.5B248961420.5B
1.5B2815361221.5B
7B2835842847.6B
32B64512040832.5B
72B80819264872.7B

RMSNorm

RMSNorm (Zhang & Sennrich, 2019) simplifies LayerNorm by removing the mean-centering step:

Compared to LayerNorm:

⚡ Simpler & Faster

RMSNorm removes the mean computation and the bias term β, making it ~10-15% faster than LayerNorm with no measurable quality loss. This adds up across billions of tokens and dozens of layers.

Tokenizer

Qwen2.5 uses a large BPE tokenizer with ~152K tokens, supporting Chinese, English, code, and multilingual text. The large vocabulary means fewer tokens per text, improving efficiency:

ModelVocab SizeTokenizer
GPT-250,257BPE (byte-level)
LLaMA 232,000SentencePiece BPE
Mistral32,000SentencePiece BPE
Qwen2.5151,936tiktoken BPE

Training Pipeline

Qwen follows a multi-stage training pipeline:

  1. Pre-training: ~18 trillion tokens of text and code data, trained on clusters of NVIDIA A100/H100 GPUs.
  2. Supervised Fine-Tuning (SFT): High-quality instruction-following data.
  3. RLHF/DPO: Reinforcement Learning from Human Feedback or Direct Preference Optimization to align with human values.
Pre-training
18T tokens
→
SFT
Instructions
→
RLHF/DPO
Alignment
→
Qwen2.5-Chat

Chain-of-Thought Reasoning

Qwen excels at chain-of-thought (CoT) reasoning — breaking complex problems into intermediate steps. The QwQ model variant is specifically optimized for extended reasoning:

Problem: If a train travels at 60 km/h for 2.5 hours, then at 80 km/h for 1.5 hours, what is the average speed for the entire journey?

Step 1: Calculate distance for each segment
d₁ = 60 × 2.5 = 150 km
d₂ = 80 × 1.5 = 120 km

Step 2: Total distance and time
Total distance = 150 + 120 = 270 km
Total time = 2.5 + 1.5 = 4 hours

Step 3: Average speed
Average speed = 270 / 4 = 67.5 km/h

Qwen Model Family

ModelTypeKey Feature
Qwen2.5Base + ChatGeneral-purpose LLM, 0.5B–72B
Qwen2.5-CoderCode-focusedState-of-the-art code generation
Qwen2.5-MathMath-focusedMathematical reasoning
QwQReasoningExtended chain-of-thought reasoning
Qwen2-VLMultimodalVision-language understanding
Qwen2-AudioAudioSpeech and audio understanding
🔥 Full Forward Pass Pipeline

Forward Pass: See Every Innovation in Action

Let's trace "Hello, how are you" through one Qwen2.5-7B layer, seeing how each modern innovation (RoPE, GQA, SwiGLU, RMSNorm) works with concrete numbers.

Full Qwen2.5-7B Architecture: Data Flow

"Hello, how are you"
↓ ① tiktoken BPE (151,936 vocab)
Token Embedding (151,936 × 3,584)
NO position emb added here!
h⁰ ∈ ℝ5×3584
× 28 Decoder Layers
RMSNorm (no mean, no β)
↓
② GQA + RoPE
28 Q-heads | 4 KV-heads | dk=128
RoPE applied to Q,K only (not V)
↓ + residual
RMSNorm
↓
③ SwiGLU FFN
3 matrices: W₁, V (gate), W₂
3584 → 9557 (×2 paths) → 3584
↓ + residual
h28 ∈ ℝ5×3584
Final RMSNorm
↓ × EmbT (tied weights)
④ Logits ∈ ℝ5×151936 → Softmax → Loss
↓ ④ Backprop (RoPE⁻¹, SwiGLU product rule, RMSNorm grad)
Qwen2.5-7B: Modern decoder-only. Every innovation is highlighted: RMSNorm (faster), GQA+RoPE (memory-efficient + length extrapolation), SwiGLU (gated FFN). Steps ①-④ detailed below.

Step 1: tiktoken BPE Tokenization

"Hello, how are you"
↓ tiktoken BPE (vocab: 151,936)
"Hello" → 9707
"," → 11
" how" → 1246
" are" → 525
" you" → 498
Token Emb lookup: 151,936 × 3584 table → h⁰ ∈ ℝ5×3584 (no pos emb added!)

Step 2: GQA + RoPE (Inside One Layer)

After RMSNorm, Q/K/V projections are computed. RoPE is applied to Q and K only (not V!):

RoPE rotates each pair of dimensions in Q and K by position-dependent angles:

For token at position m=2 ("how"), dim pair (0,1):

θ₀ = 10000-0/3584 = 1.0
angle = m × θ₀ = 2 × 1.0 = 2.0 rad

q[0] = q₀·cos(2) − q₁·sin(2) = 0.35·(−0.42) − 0.72·(0.91) = -0.80
q[1] = q₀·sin(2) + q₁·cos(2) = 0.35·(0.91) + 0.72·(−0.42) = 0.017

Same rotation applied to K → dot product depends on relative position!

GQA broadcasts each KV head across 7 query heads (28Q / 4KV = 7×):

Step 3: SwiGLU FFN (with Gating)

After attention + residual + RMSNorm, the SwiGLU FFN computes:

For one token's hidden state x (d=3584):

gate = x × W₁  → (3584 → 9557) → Swish activation
up   = x × V  → (3584 → 9557)
out  = (gate ⊗ up) × W₂ → (9557 → 3584)

Example values for one neuron:
gate[42] = Swish(0.85) = 0.85 × σ(0.85) = 0.85 × 0.70 = 0.595
up[42] = 1.23
product = 0.595 × 1.23 = 0.732 ← gate selectively amplifies

Step 4: Loss, Backprop & Training

After 28 layers, RMSNorm, and output projection → causal LM loss (same as GPT-2). But backprop through Qwen's novel components is worth understanding:

Backprop Through SwiGLU (Product Rule)

out = (Swish(x·W₁) ⊗ x·V) · W₂

Product rule for the gate:
∂L/∂(x·W₁) = ∂L/∂out · W₂ᵀ · (x·V) · Swish'(x·W₁)
∂L/∂(x·V) = ∂L/∂out · W₂ᵀ · Swish(x·W₁)

Swish'(x) = σ(x) + x·σ(x)·(1−σ(x))
At x=0.85: σ(0.85)=0.70
Swish'(0.85) = 0.70 + 0.85×0.70×0.30 = 0.879

Two gradient paths (gate + up) means richer learning signals!

Backprop Through RoPE (Rotation Inverse)

Forward: q_rot = R(θ,m) · q
Backward: ∂L/∂q = R(θ,m)ᵀ · ∂L/∂q_rot

Since R is orthogonal: R(θ,m)ᵀ = R(−θ,m)
= Just rotate by the negative angle!

For position m=2, ∂L/∂q_rot = [0.015, −0.008]:
∂L/∂q[0] = 0.015·cos(−2) − (−0.008)·sin(−2)
= 0.015·(−0.42) + 0.008·(−0.91) = −0.0136

RoPE backprop is computationally free — just reverse rotate!

Backprop Through RMSNorm

Simpler than LayerNorm gradient (no mean subtraction), which is why it's ~15% faster in backward pass too.

Cosine LR Schedule

η_max = 3e-4, η_min = 3e-5, T = 2M steps

At step 0: η = 3e-4 (peak)
At step 500K: η = 1.97e-4
At step 1M: η = 1.65e-4 (midpoint)
At step 2M: η = 3e-5 (minimum)
💡 Every Forward Innovation Has a Backward Story

RoPE's backward is just a reverse rotation (free). SwiGLU's backward uses the product rule (two gradient paths). RMSNorm's backward skips the mean gradient. GQA's backward sums gradients from 7 Q-heads into each shared K/V head — concentrating the learning signal and making KV weights update 7× faster than Q weights.

Impact

Qwen has become the most widely adopted open-source model family from a Chinese lab, with millions of downloads. It demonstrates that the recipe of (RoPE + SwiGLU + GQA + RMSNorm + massive data) produces frontier-quality models across languages and tasks.

📄 Citation

Qwen Team. "Qwen2.5 Technical Report." Alibaba Cloud, 2024. arxiv.org/abs/2412.15115

Context Window Extension

Qwen models can extend their context window without retraining thanks to RoPE's mathematical properties:

MethodHow It WorksExtensionQuality
Position InterpolationScale position indices: pos × (L_train / L_target)2-4×Needs brief fine-tuning
NTK-aware ScalingIncrease RoPE base frequency: 10000 → 5000004-16×Works zero-shot!
YaRNNTK + attention temperature scaling32-64×Best quality
LongRoPELearned per-dimension scaling factors128×+Near-lossless
Qwen-2.5 context scaling:
Trained on: 8,192 tokens
NTK-scaled to: 32,768 tokens (free!)
YaRN fine-tuned to: 131,072 tokens (brief FT)

NTK-aware RoPE scaling formula:
base' = base × (target_len / train_len)^(d/(d-2))
= 10000 × (128K / 8K)^(128/126)
= ~500,000
💡 Why RoPE Enables This

Sinusoidal position embeddings (original Transformer) and learned embeddings (GPT-2) cannot extrapolate — they've never seen position 9000 if trained on 8192. RoPE's rotation-based encoding degrades gracefully at unseen positions, making scaling possible with simple frequency adjustments.

💻 PyTorch Code

Code: Qwen Building Blocks

RMSNorm (replaces LayerNorm)

Python
class RMSNorm(nn.Module):
    """No mean centering, no beta — just scale by RMS"""
    def __init__(self, d, eps=1e-6):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(d))
        self.eps = eps

    def forward(self, x):
        rms = torch.sqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + self.eps)
        return x / rms * self.weight

RoPE (Rotary Position Embedding)

Python
def apply_rope(x, freqs):
    """Rotate pairs of dimensions by position-dependent angles"""
    d = x.shape[-1]
    x1 = x[..., :d//2]
    x2 = x[..., d//2:]
    cos = freqs.cos()
    sin = freqs.sin()
    # Rotation: [x1, x2] → [x1·cos - x2·sin, x1·sin + x2·cos]
    return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)

def precompute_freqs(d, max_len=8192, base=10000.0):
    freqs = 1.0 / (base ** (torch.arange(0, d, 2).float() / d))
    t = torch.arange(max_len)
    return torch.outer(t, freqs)  # (max_len, d//2)

# Apply to Q and K (NOT to V!)
freqs = precompute_freqs(d_head)
Q_rotated = apply_rope(Q, freqs[:seq_len])
K_rotated = apply_rope(K, freqs[:seq_len])

SwiGLU FFN

Python
class SwiGLU(nn.Module):
    """3-matrix gated FFN: SwiGLU(x) = (xW₁ ⊙ Swish(xV)) W₂"""
    def __init__(self, d_model=3584, d_ff=9557):
        super().__init__()
        self.W1 = nn.Linear(d_model, d_ff, bias=False)  # gate
        self.V  = nn.Linear(d_model, d_ff, bias=False)  # value
        self.W2 = nn.Linear(d_ff, d_model, bias=False) # project back

    def forward(self, x):
        gate = F.silu(self.W1(x))  # Swish activation
        value = self.V(x)
        return self.W2(gate * value)  # Element-wise gating

Grouped-Query Attention (GQA)

Python
class GQA(nn.Module):
    def __init__(self, d=3584, q_heads=28, kv_heads=4, d_head=128):
        super().__init__()
        self.q_heads = q_heads
        self.kv_heads = kv_heads
        self.group_size = q_heads // kv_heads  # 7 Q heads per KV head

        self.W_q = nn.Linear(d, q_heads * d_head, bias=False)
        self.W_k = nn.Linear(d, kv_heads * d_head, bias=False)
        self.W_v = nn.Linear(d, kv_heads * d_head, bias=False)
        self.W_o = nn.Linear(q_heads * d_head, d, bias=False)

    def forward(self, x):
        B, T, _ = x.shape
        Q = self.W_q(x).view(B, T, self.q_heads, -1)
        K = self.W_k(x).view(B, T, self.kv_heads, -1)
        V = self.W_v(x).view(B, T, self.kv_heads, -1)

        # Repeat KV heads to match Q heads: 4 KV → 28 Q
        K = K.repeat_interleave(self.group_size, dim=2)
        V = V.repeat_interleave(self.group_size, dim=2)

        # Standard attention from here...
        # Saves 7× KV cache memory vs standard MHA!