LM Language Model · 语言模型原理
钱坤 · M260100031
Interactive Architecture Guide · Transformer Decoder

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. 点击下方模块即可切换浏览大语言模型的六大核心环节(分词、词嵌入、注意力、前馈块、训练目标、采样)与实时交互实验。

钱
姓名 / Name:钱坤(Qian Kun)
学号 / Student ID:M260100031
Bioinformatics · Homework 1
Select Module to Browse · 选择模块切换浏览
STAGE 01 · TEXT → INTEGERS

Tokenisation · 分词(Token 化)

Turning raw strings into compact subword units and integer IDs via Byte-Pair Encoding (BPE). 通过字节对编码(BPE)将原始文本切分为紧凑的子词单元并映射为整数 ID。

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 字节回退机制,确保中英文、代码、生物序列等任意字符都可被编码。
Encode(s) = [id1, id2, …, idT],   idt ∈ {0, 1, …, |V| − 1}
A string of characters is compressed into T discrete token IDs drawn from vocabulary V. 原始字符串被压缩映射为长度为 T 的离散整数序列,每个 ID 均属于词表 V。
Interactive Lab 1A: Live Subword Tokeniser 交互实验 1A:实时子词分词器
Lab 1B: How BPE Learns Merges Step-by-Step · 实验 1B:BPE 迭代合并演示
STAGE 02 · INTEGERS → CONTINUOUS VECTORS

Embeddings & Positional Encoding · 词嵌入与位置编码

Mapping discrete token IDs into a continuous semantic geometry and injecting word order. 将离散整数 ID 映射到连续高维语义空间,并注入词序位置信息。

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),使模型能够区分词序。

xt = E[idt] + pt ∈ ℝd,    cos(u, v) = (u · v) / (‖u‖ ‖v‖)
Token embedding lookup plus position vector forms the initial residual stream entering Layer 1. 词向量查表叠加位置向量,构成进入第一层 Transformer 的初始隐状态表示。
Interactive Lab 2: 2D Semantic Space & Cosine Similarity 交互实验 2:二维语义嵌入空间与余弦相似度
Click any two words on the map to compare their vectors: 点击左侧任意两个词点,实时计算夹角与相似度:
DNA ↔ RNA
Cosine Similarity / 余弦相似度
0.986
Simulated 8-dim Embedding Preview / 8 维向量示意
STAGE 03 · CONTEXT ROUTING ACROSS TOKENS

Multi-Head Self-Attention · 多头自注意力机制

Letting every token dynamically gather relevant context from earlier tokens via Query–Key–Value matching. 通过 Query–Key–Value 匹配,让每个 Token 动态聚合前文中的关键上下文信息。

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 加权求和。多头机制允许不同注意力头并行学习指代、语法、局部依赖等不同关系。

Attention(Q, K, V) = softmax( (QK⊤) / √dk + M ) V
Causal mask Mᵢⱼ = −∞ for j > i ensures token i only attends to tokens 1…i. 当 j > i 时掩码 Mᵢⱼ = −∞,保证位置 i 只能关注自身及之前的词。
Interactive Lab 3: Causal Attention Heatmap & Coreference Explorer 交互实验 3:因果自注意力矩阵与指代消歧
Select a Query token below (try clicking it or tired/wide) to inspect what it attends to: 点击下方任意 Query 词(推荐点击 it 或句尾词),观察注意力弧线与矩阵权重变化:
STAGE 04 · PER-TOKEN COMPUTATION & KNOWLEDGE

The Feed-Forward Block (FFN / MLP) · 前馈网络块

Expanding each token into a high-dimensional non-linear space to process features and recall factual memory. 对每个 Token 独立进行高维升维、非线性激活与回投影,执行深度特征变换与知识存储。

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 的参数量,在机制可解释性研究中被视为存储事实知识的联想记忆库。

FFN(x) = W2 · σ(W1x + b1) + b2,    h = x + FFN(RMSNorm(x))
Pre-Norm residual block: normalize → expand & activate → project back → add skip connection. Pre-Norm 残差结构:先归一化,再经升维非线性变换与降维,最后与原始输入相加。
Interactive Lab 4: Expand → Activate → Project Neuron Flow 交互实验 4:升维激活与残差连接模拟器
Input Token Features (d = 4) · 输入特征向量
Activation Curve σ(z) / 当前激活函数曲线
STAGE 05 · SELF-SUPERVISED LEARNING

The Training Objective · 训练目标:下一词预测与交叉熵损失

Learning language, facts, and reasoning simply by minimizing cross-entropy loss on the next token. 通过最小化下一个 Token 的交叉熵损失(负对数似然),从无标注文本中涌现语言与推理能力。

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 个等概率候选词中随机猜测。

ℒ(θ) = −(1/T) ∑t=1..T log Pθ(xt | x<t),    PPL = eℒ
Gradient with respect to logits is remarkably clean: ∂ℒ/∂zᵢ = pᵢ − yᵢ (predicted prob minus 1 for truth, 0 otherwise). 损失对 logit 的梯度形式极为简洁:∂ℒ/∂zᵢ = pᵢ − yᵢ,直接推动正确词概率上升、错误词概率下降。
Interactive Lab 5: Cross-Entropy Loss & Gradient Descent Simulator 交互实验 5:交叉熵损失与梯度下降实时演示
Context: "The genetic code is stored in ___"  →  Ground-Truth Target y = "DNA"
Predicted Probabilities & Logit Gradients (∂ℒ/∂zᵢ = pᵢ − yᵢ)
Tip: Negative gradient (green) pushes the logit UP; positive gradient (red) pushes the logit DOWN. 提示:负梯度(绿色)使对应词 logit 增大,正梯度(红色)使其 减小。
Cross-Entropy Loss / 交叉熵
1.95
Perplexity / 困惑度 (e^ℒ)
7.03
Loss Curve Over Training Steps / 训练损失下降曲线 (Step 0)
STAGE 06 · DECODING & GENERATION

How a Token is Sampled · Token 采样与文本生成

Shaping raw logits into a probability distribution with Temperature, Top-k, and Top-p (Nucleus) sampling. 利用温度(Temperature)、Top-k 与核采样(Top-p)控制生成结果的确定性与创造力。

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). Low T sharpens peaks (focused, deterministic); high T flattens probabilities (diverse, creative, or chaotic).
  • Top-k Sampling: truncates the distribution to the k most 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>。

pi = exp(zi / T) / ∑j∈S exp(zj / T),    xt+1 ~ Categorical(p)
S is the active candidate pool after applying Top-k and Top-p truncation. S 为经过 Top-k 与 Top-p 截断后保留的有效候选词集合,最终按重归一化分布抽样。
Interactive Lab 6: Temperature, Top-k & Top-p Sampling Playground 交互实验 6:温度、Top-k 与 Top-p 采样游乐场
"In the quiet laboratory, the scientist discovered a new protein."
Click "Sample 1 Token" or "Sample 100×" to draw from the active distribution.

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.
01 / 07 · Tokenisation (分词)