Modern Decoder-Only LLM Block (Llama / Mistral Style)
Grouped-Query Attention (GQA), SwiGLU FFN, Pre-RMSNorm, and KV Caching.
Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.
Inspect Architecture: Decoder-only language models (GPT series)1. The idea
Modern frontier Large Language Models (Llama 3, Mistral, Gemma) share an optimized autoregressive decoder block combining Pre-RMSNorm, Grouped-Query Attention (GQA) for 4x KV-cache memory compression, SwiGLU gated activations, and residual streams.
2. The math
3. How it works
4. The code (python)
import torch
import torch.nn as nn
import torch.nn.functional as F
class RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x * rms * self.weight
class SwiGLU(nn.Module):
def __init__(self, dim: int, hidden_dim: int):
super().__init__()
self.w_gate = nn.Linear(dim, hidden_dim, bias=False)
self.w_up = nn.Linear(dim, hidden_dim, bias=False)
self.w_down = nn.Linear(hidden_dim, dim, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
class ModernLLMBlock(nn.Module):
"""Complete Llama 3 / Mistral style Transformer Decoder Block."""
def __init__(self, dim: int, n_heads: int, hidden_dim: int):
super().__init__()
self.attn_norm = RMSNorm(dim)
self.attn = nn.MultiheadAttention(dim, n_heads, batch_first=True)
self.ffn_norm = RMSNorm(dim)
self.ffn = SwiGLU(dim, hidden_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
normed = self.attn_norm(x)
attn_out, _ = self.attn(normed, normed, normed, need_weights=False)
x = x + attn_out
x = x + self.ffn(self.ffn_norm(x))
return x5. Check yourself
In the catalog
Finished this chapter?
The Epoch Zero newsletter
What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.