Inside a Modern Language Model 现代大语言模型原理解析:从文本到下一个词的完整旅程
Explore the 6 core stages of an LLM interactively—pick any module below to inspect its explanation, math, and live lab without endless scrolling. 点击下方模块即可切换浏览大语言模型的六大核心环节(分词、词嵌入、注意力、前馈块、训练目标、采样)与实时交互实验。
Tokenisation · 分词(Token 化)
English Explanation
Neural networks operate on numbers, not characters. Splitting by whole words creates an enormous vocabulary and fails on typos or new scientific terms (e.g., bioinformatics). Splitting by single characters keeps the vocabulary tiny, but makes sequences very long and hard to learn.
Modern LLMs use subword tokenisation (most commonly Byte-Pair Encoding, BPE): frequent words stay intact as one token, while rare or compound words are split into reusable pieces. Each piece maps to an integer ID in a fixed vocabulary of size |V| (typically 50k–128k).
- BPE Training: start from bytes/characters, repeatedly merge the most frequent adjacent pair.
- Zero OOV: operating at the UTF-8 byte level guarantees any text—English, Chinese, DNA strings, or emojis—can be encoded.
中文原理解析
神经网络只能处理数字,无法直接理解文本。如果按整词切分,词表会无限膨胀且遇到生词或专业术语(如 bioinformatics)就会报错;如果按单字符切分,序列长度会暴增,增加注意力计算开销。
现代大语言模型普遍采用子词分词(Subword Tokenisation),以 BPE(字节对编码) 最具代表性:高频词保留为完整 Token,低频词或复合词拆分为有意义的子词片段,每个片段对应固定词表(通常 5 万~12.8 万)中的一个整数 ID。
- BPE 构建过程:从基础字符/字节出发,不断统计并将出现频率最高的相邻符号对合并成新词元。
- 无未登录词(Zero OOV):基于 UTF-8 字节回退机制,确保中英文、代码、生物序列等任意字符都可被编码。
Embeddings & Positional Encoding · 词嵌入与位置编码
English Explanation
Token IDs are arbitrary indices: ID 501 is not semantically closer to 502 than to 9812. An embedding matrix E ∈ ℝ^(|V|×d) looks up a learned dense vector for every token ID (e.g., d = 4096 in a 7B model).
During training, tokens that appear in similar contexts drift into nearby regions of this space, turning meaning into geometry—so cosine similarity measures semantic closeness and directions encode relationships (like king − man + woman ≈ queen).
Because self-attention treats inputs as a set, we also inject positional information (sinusoidal vectors or RoPE rotary embeddings) so the model knows "gene regulates protein" differs from "protein regulates gene".
中文原理解析
Token ID 只是任意编号:编号 501 并不比 9812 更接近 502。模型通过可学习的词嵌入矩阵 E ∈ ℝ^(|V|×d),查表将每个整数 ID 映射为一个连续的稠密向量(例如 7B 模型中 d = 4096)。
在海量语料训练中,上下文相似的词会在向量空间中彼此靠近,语义被转化为几何结构:余弦相似度衡量语义相关性,向量方向甚至编码了类比关系(如 king − man + woman ≈ queen)。
由于自注意力本身对顺序不敏感,还必须叠加位置编码(正弦位置编码或现代常用的旋转位置编码 RoPE),使模型能够区分词序。
Multi-Head Self-Attention · 多头自注意力机制
English Explanation
A static embedding cannot tell what "it" refers to in "The animal didn't cross the street because it was tired". Self-attention solves this by projecting each token vector into three roles:
- Query (Q): what context am I looking for?
- Key (K): what information do I advertise to others?
- Value (V): what content do I pass along if attended to?
Dot products QKᵀ score compatibility, dividing by √dₖ keeps gradients stable, a causal mask M sets future positions to −∞ so a decoder cannot peek ahead, and softmax turns scores into weights summing to 1. Running multiple heads in parallel captures syntax, coreference, and locality simultaneously.
中文原理解析
静态词向量无法判断句子 "The animal didn't cross the street because it was tired" 中的 "it" 究竟指代谁。自注意力机制通过线性投影为每个 Token 生成三种角色:
- Query(查询向量 Q):当前词在寻找什么上下文?
- Key(键向量 K):当前词能提供什么特征标签?
- Value(值向量 V):被关注后要传递出的实际信息内容。
通过 QKᵀ 计算相似度,除以 √dₖ 防止方差过大导致梯度消失;因果掩码 M 将未来位置设为 −∞,确保自回归模型只能看前文;再经 softmax 归一化为权重对 V 加权求和。多头机制允许不同注意力头并行学习指代、语法、局部依赖等不同关系。
it or tired/wide) to inspect what it attends to:
点击下方任意 Query 词(推荐点击 it 或句尾词),观察注意力弧线与矩阵权重变化:
The Feed-Forward Block (FFN / MLP) · 前馈网络块
English Explanation
Attention moves information between tokens, but it is largely a weighted average. Right after attention, every Transformer block passes each token vector independently through a two-layer Feed-Forward Network (FFN) (often gated as SwiGLU in Llama/DeepSeek/Gemma).
- Expand (d → 4d): projects the vector into a wider hidden space where specialized feature neurons live.
- Non-linearity (GELU / SiLU / ReLU): gates neurons selectively—without non-linearity, stacked layers would collapse into one linear matrix.
- Project & Residual Add (4d → d): writes refined features back onto the residual stream via
x + FFN(Norm(x)), which also preserves gradient flow across dozens of layers.
Research shows FFN layers hold roughly 2/3 of a Transformer's parameters and behave like associative key–value memory storing world knowledge.
中文原理解析
注意力层负责在词与词之间搬运信息,但其本质仍是加权平均。紧随其后的前馈网络块(FFN / MLP)会对序列中的每个 Token 独立地进行非线性特征加工(现代模型常采用门控变体 SwiGLU)。
- 升维扩展(d → 4d):将隐向量投影到更宽的中间空间,激活专门的特征检测神经元。
- 非线性激活(GELU / SiLU / ReLU):对神经元进行选择性门控;若无非线性函数,再多层的网络也等价于单层线性变换。
- 降维与残差连接(4d → d):通过
x + FFN(Norm(x))将新特征写回残差流,结合归一化(LayerNorm / RMSNorm)保障深层网络稳定训练。
FFN 通常占据 Transformer 约 2/3 的参数量,在机制可解释性研究中被视为存储事实知识的联想记忆库。
The Training Objective · 训练目标:下一词预测与交叉熵损失
English Explanation
How can a model learn grammar, biology, coding, and math without manual labels? By turning every document into millions of Next-Token Prediction puzzles using the chain rule of probability: given prefix x₁…xₜ₋₁, predict a probability distribution over the vocabulary for xₜ.
The loss is Cross-Entropy (Negative Log-Likelihood): if the model assigns high probability to the true next token (e.g., 0.90), loss is tiny (−ln 0.90 = 0.11). If it assigns low probability (e.g., 0.05), loss spikes (−ln 0.05 = 3.00), sending a strong gradient via backpropagation to boost the correct logit and suppress wrong ones.
Perplexity (PPL = exp(Loss)) gives an intuitive yardstick: a perplexity of 4 means the model is as uncertain as choosing uniformly among 4 equally likely words.
中文原理解析
模型无需人工标注答案,就能从海量文本中学会语法、代码与科学知识,秘诀在于自监督的下一词预测(Next-Token Prediction):基于概率链式法则,利用任意一段文本的前文 x₁…xₜ₋₁ 去预测下一个真实词 xₜ 的概率分布。
训练最小化交叉熵损失(负对数似然):若模型给真实目标词分配高概率(如 0.90),损失极低(0.11);若分配极低概率(如 0.05),损失剧增(3.00),反向传播会产生强梯度,拉高正确词的 logit 并压低错误词的 logit。
困惑度(Perplexity = e^Loss)直观衡量不确定性:困惑度为 4 意味着模型每一步的犹豫程度相当于在 4 个等概率候选词中随机猜测。
y = "DNA"
How a Token is Sampled · Token 采样与文本生成
English Explanation
After the final Transformer block, an unembedding matrix projects the last hidden state into logits z ∈ ℝ^|V|—one raw score for every word in the vocabulary. Always picking the highest-scoring token (greedy decoding) often produces repetitive, bland text.
- Temperature (T): divides logits before softmax (
z / T). LowTsharpens peaks (focused, deterministic); highTflattens probabilities (diverse, creative, or chaotic). - Top-k Sampling: truncates the distribution to the
kmost likely tokens and re-normalizes. - Top-p (Nucleus) Sampling: keeps the smallest top set whose cumulative probability reaches
p, automatically adapting to both confident and uncertain contexts.
Finally, one token is randomly drawn from the filtered distribution, appended to the prompt, and the entire loop repeats autoregressively until an end-of-sequence (<EOS>) token appears.
中文原理解析
经过最后一层 Transformer 后,输出头将隐向量投影为覆盖整个词表的原始分数 Logits(z ∈ ℝ^|V|)。如果每一步都只选分数最高的词(贪心解码),文本容易陷入单调重复。
- 温度系数(Temperature, T):在 softmax 前将 logits 除以
T。T越低分布越尖锐(严谨确定);T越高分布越平缓(富有创意但也更易出错)。 - Top-k 采样:仅保留概率最高的
k个候选词并重新归一化,截断低概率长尾噪声。 - Top-p(核采样 Nucleus):按概率从高到低累加,仅保留累计概率刚好达到
p的最小候选集合,能随语境确定性动态伸缩候选数量。
最后按归一化后的概率随机抽取一个 Token,拼接回输入序列末尾,循环往复直到生成结束符 <EOS>。
Architecture Recap · 六大核心组件速查表
How all six components connect in a modern decoder-only Transformer (e.g., GPT, Claude, Gemini, Llama). 现代自回归 Transformer 语言模型中六个核心环节的张量形状与作用对照。
| Stage / 环节 | Input → Output Shape | Core Mechanism / 核心机制 | Role in the Model / 关键作用 |
|---|---|---|---|
| 01 Tokenisation 分词 |
String → [T] |
BPE / Unigram subword merges | Compresses arbitrary text into integer IDs without out-of-vocabulary errors. |
| 02 Embeddings 词嵌入与位置编码 |
[T] → [T, d] |
Lookup matrix E + Positional / RoPE |
Encodes semantic similarity and word order in continuous vector geometry. |
| 03 Attention 多头自注意力 |
[T, d] → [T, d] |
softmax(QKᵀ/√dₖ + M)V |
Dynamically routes context across earlier tokens (coreference, syntax, logic). |
| 04 Feed-Forward 前馈网络块 |
[T, d] → [T, 4d] → [T, d] |
Linear expand + GELU/SwiGLU + Residual | Transforms per-token representations and stores associative factual knowledge. |
| 05 Training Objective 训练目标 |
[T, |V|] → Scalar ℒ |
Next-token Cross-Entropy (−log P) |
Self-supervised signal driving backpropagation across billions of parameters. |
| 06 Token Sampling Token 采样 |
[|V|] → xₜ₊₁ |
Temperature, Top-k, Top-p decoding | Balances coherence and creativity when generating text one token at a time. |