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.
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):
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:
The key property: the dot product between two RoPE-transformed vectors depends only on their relative position:
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.
SwiGLU (Shazeer, 2020) replaces the standard FFN with a gated variant that outperforms ReLU and GELU:
Compared to standard FFN:
| Architecture | Formula | Parameters |
|---|---|---|
| Standard FFN | max(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.
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.
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 Model | Layers | d_model | Q Heads | KV Heads | Params |
|---|---|---|---|---|---|
| 0.5B | 24 | 896 | 14 | 2 | 0.5B |
| 1.5B | 28 | 1536 | 12 | 2 | 1.5B |
| 7B | 28 | 3584 | 28 | 4 | 7.6B |
| 32B | 64 | 5120 | 40 | 8 | 32.5B |
| 72B | 80 | 8192 | 64 | 8 | 72.7B |
RMSNorm (Zhang & Sennrich, 2019) simplifies LayerNorm by removing the mean-centering step:
Compared to LayerNorm:
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.
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:
| Model | Vocab Size | Tokenizer |
|---|---|---|
| GPT-2 | 50,257 | BPE (byte-level) |
| LLaMA 2 | 32,000 | SentencePiece BPE |
| Mistral | 32,000 | SentencePiece BPE |
| Qwen2.5 | 151,936 | tiktoken BPE |
Qwen follows a multi-stage training pipeline:
Qwen excels at chain-of-thought (CoT) reasoning — breaking complex problems into intermediate steps. The QwQ model variant is specifically optimized for extended reasoning:
| Model | Type | Key Feature |
|---|---|---|
| Qwen2.5 | Base + Chat | General-purpose LLM, 0.5B–72B |
| Qwen2.5-Coder | Code-focused | State-of-the-art code generation |
| Qwen2.5-Math | Math-focused | Mathematical reasoning |
| QwQ | Reasoning | Extended chain-of-thought reasoning |
| Qwen2-VL | Multimodal | Vision-language understanding |
| Qwen2-Audio | Audio | Speech and audio understanding |
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.
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:
GQA broadcasts each KV head across 7 query heads (28Q / 4KV = 7×):
After attention + residual + RMSNorm, the SwiGLU FFN computes:
After 28 layers, RMSNorm, and output projection → causal LM loss (same as GPT-2). But backprop through Qwen's novel components is worth understanding:
Simpler than LayerNorm gradient (no mean subtraction), which is why it's ~15% faster in backward pass too.
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.
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.
Qwen Team. "Qwen2.5 Technical Report." Alibaba Cloud, 2024. arxiv.org/abs/2412.15115
Qwen models can extend their context window without retraining thanks to RoPE's mathematical properties:
| Method | How It Works | Extension | Quality |
|---|---|---|---|
| Position Interpolation | Scale position indices: pos × (L_train / L_target) | 2-4× | Needs brief fine-tuning |
| NTK-aware Scaling | Increase RoPE base frequency: 10000 → 500000 | 4-16× | Works zero-shot! |
| YaRN | NTK + attention temperature scaling | 32-64× | Best quality |
| LongRoPE | Learned per-dimension scaling factors | 128×+ | Near-lossless |
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.
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
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])
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
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!