目录0. 预训练 Pipeline 总览1. 语料工程大规模文本数据的采集与治理1.1 设计目标与约束1.2 数据源Common Crawl 与种子扩展策略1.3 多级数据治理 PipelineStage 1: URL-Level FilteringStage 2: Content Extraction Boilerplate RemovalStage 3: Language Identification FilteringStage 4: Document-Level Passage-Level DeduplicationStage 5: PII Redaction1.4 语料统计特征2. Tokenization从连续文本到离散符号序列2.1 问题定义与核心 Trade-off2.2 编码层级与压缩递进2.3 Byte Pair Encoding 算法2.4 Tokenization 的工程特性3. 神经网络训练基于 Transformer 的自监督预训练3.1 训练范式Causal Language Modeling3.2 Transformer 架构Multi-Head Self-Attention 机制Feed-Forward Network (SwiGLU Variant)3.3 训练动态与收敛行为3.4 模型规模与计算需求计算基础设施3.5 模型发布与 Artifact 构成4. 推断自回归解码与采样策略4.1 自回归生成Autoregressive Generation4.2 解码策略与采样超参数Temperature ScalingTop-k SamplingTop-p (Nucleus) Sampling4.3 Base Model 的行为特征本质定位Emergent Capabilities已知局限参数即有损压缩5. 从 Base Model 到 Assistant后训练路径附录核心术语索引关键数值参考本文系统性地梳理当前 Large Language Model (LLM) 预训练阶段的核心技术栈涵盖语料采集与数据治理、子词分词算法、基于 Transformer 架构的自监督训练范式以及推断阶段的解码策略。全文以工程实践为导向结合 GPT-2、LLaMA 3.1 等公开模型的技术细节旨在为读者提供一份兼具理论深度与工程视角的参考。0. 预训练 Pipeline 总览大规模语言模型的预训练可抽象为一条四阶段串行 pipeline每一阶段的输出即为下一阶段的输入Raw Internet ──▶ [Stage 1: Corpus Curation] ──▶ Clean Text │ ▼ [Stage 2: Tokenization] ──▶ Token Sequence │ ▼ [Stage 3: Pre-training] ──▶ Base Model θ* │ ▼ [Stage 4: Inference] ──▶ Generated TextPre-training 产出的 Base Model 本质上是一个 next-token probability estimator其参数 θ* 编码了训练语料的分布特征。需经过后续 Post-training 阶段Supervised Fine-Tuning / RLHF / DPO 等 alignment 技术方可作为对话式 assistant 部署。1. 语料工程大规模文本数据的采集与治理1.1 设计目标与约束预训练语料的构建需同时满足三个互相制约的优化目标维度目标工程约束规模(Scale)覆盖足够大的知识面与语言模式存储、带宽、处理吞吐质量(Quality)高信噪比排除有害/低质内容需要多级 heuristic 与 classifier多样性(Diversity)领域、文体、语言的均衡分布避免 distribution shift 与 mode collapse这三者之间存在天然的张力——追求规模往往引入噪声过度过滤则损害多样性。工业级语料工程的核心挑战在于在这组 Pareto frontier 上找到最优平衡点。1.2 数据源Common Crawl 与种子扩展策略当前主流 LLM 的语料基底几乎均源自Common Crawl——一个自 2007 年持续运作的大规模 web archiving 项目。截至 2024 年其索引规模已达2.7 billion web pages采用 breadth-first crawling strategy 从种子 URL 集出发递归扩展。原始 Common Crawl archive 以 WARC (Web ARChive) 格式存储包含完整的 HTTP response含 header、HTML body、embedded resources 等信噪比极低不可直接用于模型训练。各 LLM 厂商OpenAI、Anthropic、Google DeepMind、Meta FAIR 等均在此基础上构建了各自的 proprietary data pipeline。1.3 多级数据治理 Pipeline以 HuggingFace 公开的FineWeb数据集为参考实现工业级语料治理通常包含以下级联阶段Stage 1: URL-Level Filtering基于预维护的 domain blocklist 实施粗粒度过滤目标排除以下类别Malicious contentmalware distribution sites、phishing domainsLow-quality sourcescontent farms、SEO spam、auto-generated pagesPolicy-violating contentadult material、hate speech domainsCommercial noiseaggressive marketing、affiliate link aggregators该阶段的 precision-recall trade-off 倾向于 high recall宁可误杀因后续阶段可进一步过滤。Stage 2: Content Extraction Boilerplate Removal原始 HTML 文档包含大量非内容元素navigation bars、sidebars、footers、CSS/JS inline code、ad scripts 等需要通过main content extraction算法提取正文常用方案包括Trafilatura、Readability等基于 DOM tree analysis 的启发式提取器需处理的边界情况多栏布局、动态加载内容SPA/CSR、table-heavy pages提取质量直接影响下游模型对语言模式的学习是整个 pipeline 中 ROI 最高的环节之一Stage 3: Language Identification Filtering使用fastText-based language classifier对每个文档进行语言识别依据预设的语言分布策略进行过滤FineWeb 采用English ≥ 65%的阈值策略属于 English-centric 设计该阈值是一个关键的hyperparameter直接决定模型的多语言能力multilingual capability工业实践中通常采用 stratified sampling 策略按语言族群设定不同的配比权重Stage 4: Document-Level Passage-Level Deduplication互联网存在大量 near-duplicate contentsyndication、scraping、templated pages去重是提升语料有效信息密度的关键步骤Exact deduplication基于 document hashSHA-256 / MD5的精确匹配Near-duplicate detection基于MinHash LSH (Locality-Sensitive Hashing)的近似去重Passage-level dedup对文档内部的重复段落进行检测处理 boilerplate paragraphs充分去重可有效缓解模型的memorization tendency降低 training data extraction attack 的风险Stage 5: PII Redaction为满足 GDPR 等数据隐私法规要求需检测并移除Personally Identifiable Information采用 NER (Named Entity Recognition) 模型识别 addresses、phone numbers、SSN、email addresses 等高敏感文档直接从语料中剔除低敏感文档进行 entity-level masking该阶段需平衡隐私保护与数据可用性redaction 过度会引入分布偏差1.4 语料统计特征以 FineWeb 为例的最终产出MetricValueNotesDisk footprint44 TB纯文本未压缩Token count (GPT-4 tokenizer)~15 Trillion15 × 10¹²Document countBillions经过去重后Dominant languageEnglish≥65% thresholdKnowledge cutoffEnd of 2023时效性上界值得注意的是尽管原始互联网规模庞大经过多级过滤后的高质量文本语料在存储空间上相当紧凑——44 TB 已可容纳于单块企业级 HDD 中。这一事实反映了互联网文本的高冗余度与低信噪比特征。2. Tokenization从连续文本到离散符号序列2.1 问题定义与核心 Trade-offNeural Language Model 要求输入为有限符号集上的一维离散序列。Tokenization 即为建立从原始文本到此表示的 bijective mapping 的过程。该过程面临一个根本性的 trade-offVocabulary Size ↑ ⟺ Sequence Length ↓ ⟺ Computational Efficiency ↑ Vocabulary Size ↓ ⟺ Sequence Length ↑ ⟺ Computational Efficiency ↓Sequence length 是 Transformer 架构中最为稀缺的计算资源self-attention 的时空复杂度为 O(n²)因此需要在 vocabulary size 与 sequence length 之间寻找 Pareto-optimal 的平衡点。2.2 编码层级与压缩递进文本到 token 序列的转换可分解为多个层级的表示变换每一级在 vocabulary cardinality 与 sequence length 之间实现不同的压缩比LevelRepresentationVocabulary SizeSequence LengthCompression RatioL0Raw Unicode Text~150K codepointsBaseline1xL1UTF-8 Bitstream2 (binary)~8x longer0.125xL2Byte Sequence256Baseline1xL3BPE Tokens~100K~4x shorter~4x从 L2 到 L3 的压缩由Byte Pair Encoding (BPE)算法实现是当前工业标准。2.3 Byte Pair Encoding 算法BPE 是一种bottom-up subword segmentation算法其核心思想是通过迭代合并高频相邻符号对bigram来构建 vocabulary算法流程Input: byte sequence B [b₁, b₂, ..., bₙ], initial vocab V {0, 1, ..., 255} Repeat K times: 1. 统计 B 中所有 adjacent pair (bᵢ, bᵢ₊₁) 的频次 2. 选取频次最高的 pair (bₐ, bᵦ) 3. 创建新符号 s |V|加入 V 4. 将 B 中所有 (bₐ, bᵦ) 替换为 s 5. |V| 1, len(B) - count(bₐ, bᵦ) Output: compressed sequence B, vocabulary V with |V| 256 K每次迭代的效果vocabulary cardinality 1sequence length −NN 为该 bigram 的出现次数。实践中 K 的取值约为 ~100,000使最终 vocabulary size 达到 ~100K 量级。GPT-4 的 tokenizercl100k_basevocabulary size 为100,277。2.4 Tokenization 的工程特性BPE tokenization 具有以下值得关注的特性Case-sensitiveHello与hello映射到不同的 token IDWhitespace-aware前导空格通常被编码进 token 内部e.g., world是一个完整 tokenSubword granularity常见词为单一 token罕见词被拆分为多个 subword unitsCompression ratio典型英文文本的 tokens/characters 比约为1:4即一行文本约编码为 ~60 tokensDeterministic给定 vocabulary 和 merge rulestokenization 过程是确定性的3. 神经网络训练基于 Transformer 的自监督预训练3.1 训练范式Causal Language Modeling预训练采用Causal Language Modeling (CLM)目标函数即在给定前文 context 的条件下最大化 next token 的 log-likelihood目标函数 max_θ Σᵢ log P(xᵢ | x₁, x₂, ..., xᵢ₋₁ ; θ) 等价地最小化 cross-entropy loss L(θ) -1/T Σᵢ log P_θ(xᵢ | xᵢ) 其中 θ 模型参数weights biases xᵢ 第 i 个 tokenground truth xᵢ 前 i-1 个 token 构成的 context T 序列长度context window size P_θ 模型的条件概率估计训练流程的每个 optimization step从语料中随机采样一个 token window[x₁, ..., x_T]T 通常为 2K~128K模型对每个位置 i 输出 next-token probability distributionP_θ(· | xᵢ) ∈ R^|V|计算 cross-entropy loss 并通过backpropagation求参数梯度使用AdamW optimizer更新参数 θlearning rate 通常遵循 cosine annealing schedule该过程在每个 window 内的所有 token 位置并行执行teacher forcing单次 forward-backward pass 可同时优化 T 个 next-token prediction。3.2 Transformer 架构当前所有主流 LLM 均采用decoder-only Transformer架构Vaswani et al., 2017 的变体其 forward pass 可概括为Input Token IDs: [x₁, x₂, ..., x_T] ∈ Z^T │ ▼ ┌──────────────────────┐ │ Token Embedding │ E(xᵢ) ∈ R^d_model │ Positional Encoding│ (RoPE / ALiBi / Learned) └──────────────────────┘ │ ▼ ┌──────────────────────┐ │ Transformer Block │ ─┐ │ ┌─ RMSNorm │ │ │ ├─ Multi-Head │ │ │ │ Causal Attention │ │ │ ├─ Residual Add │ │ × N layers │ ├─ RMSNorm │ │ (N 32~128) │ ├─ SwiGLU FFN │ │ │ └─ Residual Add │ │ └──────────────────────┘ ─┘ │ ▼ ┌──────────────────────┐ │ Final RMSNorm │ │ Linear → R^|V| │ (projection to vocab size) │ Softmax → P(next) │ output ∈ R^|V|, Σ 1 └──────────────────────┘Multi-Head Self-Attention 机制Attention 是 Transformer 的核心计算单元。其作用对象是当前输入序列中的 token representations而非 vocabulary 中的全部 token对于序列中的每个 position iattention 机制执行以下计算Q X · W_Q, K X · W_K, V X · W_V (线性投影) Attention(Q, K, V) softmax( Q · K^T / √d_k ) · V 其中 Q (Query): 当前位置 在寻找什么信息 K (Key): 每个位置 携带什么信息标签 V (Value): 每个位置 实际提供的信息内容 Q · K^T: query-key 点积相似度 → attention score matrix √d_k: scaling factor防止点积值过大导致 softmax 饱和 softmax: 归一化为概率权重 · V: 按权重聚合所有位置的 valueMulti-Head指将 d_model 维度拆分为 h 个独立的 attention head每个 head 在不同的 subspace 中学习不同类型的 dependency patternsyntactic、coreference、positional 等最终 concatenate 后通过线性投影合并。Causal Mask为确保自回归属性attention score matrix 应用下三角 mask使得 position i 只能 attend to positions ≤ i防止信息泄漏。Feed-Forward Network (SwiGLU Variant)FFN(x) (Swish(x · W₁) ⊙ (x · W₃)) · W₂ 其中 ⊙ 为 element-wise productSwish(z) z · σ(z)FFN 在每个 position 独立执行可理解为对 attention 聚合后的表示进行非线性特征变换。隐层维度通常为 d_model 的8/3 倍SwiGLU 的标准配置。3.3 训练动态与收敛行为预训练过程的 loss 曲线呈现典型的power-law decay特征Loss 5.0 │● │ ●● 4.0 │ ●●● │ ●●●● 3.0 │ ●●●●●● │ ●●●●●●●●● 2.0 │ ●●●●●●●●●●●●●● │ ●●●●●●●●●●●●●●● 1.5 │ ────── └───────────────────────────────────────────────────────────────── Step 0 5K 10K 15K 20K 25K 30K不同训练阶段模型 generation quality 的质变过程阶段模型行为语言学层面的习得Step 1(初始化)输出近似 uniform random tokens无任何语言知识~1% training出现局部 token co-occurrence patterns习得 character-level 与 subword-level statistics~10% training句子基本通顺语法大致正确习得 syntactic structure 与 common collocations~50% training段落连贯具备基础世界知识习得 semantic coherence 与 discourse structure100% training生成高质量、多样化的连贯文本习得 long-range dependency 与 factual knowledge该现象与Scaling Laws(Kaplan et al., 2020) 的理论预测一致loss 随 compute budget 的增长呈 power-law 下降但 marginal improvement 递减。3.4 模型规模与计算需求SpecificationGPT-2 (2019)LLaMA 3.1 405B (2024)Scale FactorParameters1.5B405B~270×Training tokens100B15T~150×Context length1,024128K~125×ArchitectureTransformer (GPT-style)Transformer (LLaMA-style)同系Training cost (est.)~$600 (2024 reproduction)~$100M-Training hardware8× V100 (original)10,000 H100 clusters-计算基础设施LLM 训练的计算密集度使其成为当前 HPCHigh-Performance Computing领域最具挑战性的 workload 之一计算单元NVIDIA H100 SXM80GB HBM3, 989 TFLOPS BF16为当前主力训练芯片单节点配置8× H100 通过 NVLink/NVSwitch 全互联节点内带宽 900 GB/s集群规模主流训练集群规模从数千到100,000 GPU通过 InfiniBand/RoCE 网络互联并行策略综合使用 Data Parallelism (DP)、Tensor Parallelism (TP)、Pipeline Parallelism (PP)、Sequence Parallelism (SP) 等混合并行方案云端租赁以 Lambda Labs 为例8× H100 节点按需价格约 24/hr (3/GPU/hr)GPU 集群的核心计算负载可归结为一个简洁的循环在大规模 token 序列上反复执行 forward pass → loss computation → backward pass → parameter update。这一 workload 的天文级算力需求是驱动 NVIDIA 市值突破$3.4T的根本技术因素。3.5 模型发布与 Artifact 构成一个完整的 base model release 包含两个核心 artifactModel Architecture Code定义 Transformer forward pass 的计算图通常仅数百行 Python/PyTorch 代码Model Weights (Parameters)经过训练优化后的参数张量集合是全部计算投入的结晶Model Architecture(code) Parameters(weights) 数百行 Python 数十亿个 float16/bfloat16 数值 标准化的 核心价值所在4. 推断自回归解码与采样策略4.1 自回归生成Autoregressive Generation推断阶段的 generation 过程遵循严格的autoregressive factorizationP(x₁, x₂, ..., x_T) ∏ᵢ P(xᵢ | x₁, ..., xᵢ₋₁)具体的 decoding loopInitialize: sequence S [prompt tokens] For t 1, 2, ..., max_length: 1. Forward pass: logits Model(S)[-1] ∈ R^|V| 2. Apply temperature scaling: logits logits / τ 3. Apply top-k / top-p filtering 4. Compute distribution: P softmax(logits) 5. Sample: x_t ~ Categorical(P) 6. Append: S S ∥ [x_t] 7. If x_t EOS: break Return S每一步仅生成一个 token然后将其追加至 context 中作为下一步的输入。这一 sequential dependency 是当前 LLM inference 延迟的主要瓶颈。4.2 解码策略与采样超参数Softmax 输出的 probability distribution 可通过多种策略调控生成行为Temperature Scaling在 softmax 之前对 logits 进行缩放P(xᵢ) softmax(zᵢ / τ)τ效果数学性质应用场景τ → 0退化为 argmaxgreedy decoding分布坍缩为 one-hot确定性任务代码生成、数学推理τ 1.0保持原始分布无变换通用对话τ 1.0分布熵增大趋向 uniform增加 exploration创意写作、brainstormingTop-k Sampling将概率排序后仅保留 top-k 个 token其余 token 的概率置零后重新归一化P(xᵢ) P(xᵢ) / Σⱼ∈top-k P(xⱼ) if xᵢ ∈ top-k P(xᵢ) 0 otherwiseTop-p (Nucleus) Sampling保留累积概率达到阈值 p 的最小 token 集合Holtzman et al., 2020V_p argmin_{V ⊂ V} |V| s.t. Σ_{x∈V} P(x) ≥ p P(xᵢ) P(xᵢ) / Σⱼ∈V_p P(xⱼ) if xᵢ ∈ V_p P(xᵢ) 0 otherwiseTop-p 相较 top-k 的优势在于其自适应性当模型对 next token 高度确定时distribution sharpV_p 自动收缩反之则自动扩展。重要以上所有采样超参数仅在 inference 阶段生效与 training 过程完全正交。Training 阶段使用 teacher forcing不涉及任何采样操作。4.3 Base Model 的行为特征Pre-training 阶段产出的 base model 具有以下 characteristic behaviors本质定位Base model 是一个conditional token distribution estimator而非 conversational agent。其行为模式为document completion——给定任意 token prefix模型输出符合训练语料分布特征的 continuation。Emergent Capabilities尽管训练目标仅为 next-token predictionbase model 展现出多种 emergent abilitiesCapability机制实现方式In-context Learning (ICL)模型在 forward pass 中隐式地从 context 中提取 task specification在 prompt 中提供 input-output exemplarsFew-shot PromptingICL 的具体应用形式通过 K 个示例定义任务构造 K-shot prompt templateKnowledge Retrieval参数中编码的训练语料知识可通过特定 prompt 格式引出使用 elicitation prompts如列表格式、问答格式Format Following模型可延续 prompt 中建立的格式模式构造目标格式的 prefix如 JSON、Markdown、对话体已知局限局限技术根因表现Hallucination训练目标是 distribution matching 而非 factual grounding生成事实性错误的内容尤其在低频知识领域Knowledge Cutoff参数仅编码训练数据截止日期前的信息无法回答训练截止后的时事问题Verbatim Memorization高频文档如 Wikipedia被多次采样导致 overfitting逐字复现训练语料片段regurgitationNon-assistant Behavior未经 alignment模型行为是 document completion 而非 instruction following直接提问不会得到结构化回答参数即有损压缩从信息论视角base model 的 parameter set θ* 可理解为训练语料的一种lossy compression405B float16 参数 ≈810 GB的存储空间训练语料15T tokens≈44 TB的原始文本压缩比约54:1这一压缩是 lossy 的——模型保留了语料的 statistical regularities语法、常识、推理模式但丢失了精确的 verbatim content除高频重复文档外。生成内容是训练分布的stochastic sample在统计性质上近似训练语料但并非其子集。5. 从 Base Model 到 Assistant后训练路径Pre-training 产出的 base model 需经过 post-training alignment 方可作为实用的 conversational assistant 部署Base Model (document completion) │ ├── SFT (Supervised Fine-Tuning) │ 使用人工标注的 instruction-response pairs 进行有监督微调 │ ├── RLHF (Reinforcement Learning from Human Feedback) │ 训练 reward model → 使用 PPO 优化 policy │ ├── DPO (Direct Preference Optimization) │ 直接从 preference pairs 优化绕过显式 reward model │ └── 其他 alignment 技术Constitutional AI, RLAIF, etc. │ ▼ Instruct / Chat Model (instruction following)当终端用户在 ChatGPT 等产品中进行对话时其交互过程完全处于 inference 阶段——模型参数已 frozen不发生任何 gradient update。用户输入被 tokenize 后作为 context prefix模型执行 autoregressive decoding 生成 response tokens。附录核心术语索引术语全称定义CLMCausal Language Modeling自回归语言建模预测 next tokenBPEByte Pair Encoding子词分词算法迭代合并高频 bigramICLIn-Context Learning模型从 prompt 中的示例隐式学习任务SFTSupervised Fine-Tuning使用标注数据的有监督微调RLHFReinforcement Learning from Human Feedback基于人类偏好反馈的强化学习DPODirect Preference Optimization直接偏好优化RLHF 的简化替代RoPERotary Position Embedding旋转位置编码RMSNormRoot Mean Square Normalization均方根归一化SwiGLUSwish-Gated Linear UnitFFN 中的门控激活函数变体NVLinkNVIDIA NVLinkGPU 间高速互联总线TP / DP / PPTensor / Data / Pipeline Parallelism分布式训练的三种并行策略LSHLocality-Sensitive Hashing局部敏感哈希用于近似最近邻搜索WARCWeb ARChiveWeb 归档文件格式关键数值参考数值含义44 TBFineWeb 数据集磁盘占用15 × 10¹²FineWeb token 总量2.7 × 10⁹Common Crawl 索引网页数 (2024)100,277GPT-4 tokenizer vocabulary size1.5 × 10⁹GPT-2 parameter count405 × 10⁹LLaMA 3.1 largest model parameter countO(n²)Self-attention 的时空复杂度 (n sequence length)$3/GPU/hrH100 按需云租赁参考价格
大规模语言模型预训练全链路深度解析:从语料工程到自回归推断
发布时间:2026/5/31 20:19:15
目录0. 预训练 Pipeline 总览1. 语料工程大规模文本数据的采集与治理1.1 设计目标与约束1.2 数据源Common Crawl 与种子扩展策略1.3 多级数据治理 PipelineStage 1: URL-Level FilteringStage 2: Content Extraction Boilerplate RemovalStage 3: Language Identification FilteringStage 4: Document-Level Passage-Level DeduplicationStage 5: PII Redaction1.4 语料统计特征2. Tokenization从连续文本到离散符号序列2.1 问题定义与核心 Trade-off2.2 编码层级与压缩递进2.3 Byte Pair Encoding 算法2.4 Tokenization 的工程特性3. 神经网络训练基于 Transformer 的自监督预训练3.1 训练范式Causal Language Modeling3.2 Transformer 架构Multi-Head Self-Attention 机制Feed-Forward Network (SwiGLU Variant)3.3 训练动态与收敛行为3.4 模型规模与计算需求计算基础设施3.5 模型发布与 Artifact 构成4. 推断自回归解码与采样策略4.1 自回归生成Autoregressive Generation4.2 解码策略与采样超参数Temperature ScalingTop-k SamplingTop-p (Nucleus) Sampling4.3 Base Model 的行为特征本质定位Emergent Capabilities已知局限参数即有损压缩5. 从 Base Model 到 Assistant后训练路径附录核心术语索引关键数值参考本文系统性地梳理当前 Large Language Model (LLM) 预训练阶段的核心技术栈涵盖语料采集与数据治理、子词分词算法、基于 Transformer 架构的自监督训练范式以及推断阶段的解码策略。全文以工程实践为导向结合 GPT-2、LLaMA 3.1 等公开模型的技术细节旨在为读者提供一份兼具理论深度与工程视角的参考。0. 预训练 Pipeline 总览大规模语言模型的预训练可抽象为一条四阶段串行 pipeline每一阶段的输出即为下一阶段的输入Raw Internet ──▶ [Stage 1: Corpus Curation] ──▶ Clean Text │ ▼ [Stage 2: Tokenization] ──▶ Token Sequence │ ▼ [Stage 3: Pre-training] ──▶ Base Model θ* │ ▼ [Stage 4: Inference] ──▶ Generated TextPre-training 产出的 Base Model 本质上是一个 next-token probability estimator其参数 θ* 编码了训练语料的分布特征。需经过后续 Post-training 阶段Supervised Fine-Tuning / RLHF / DPO 等 alignment 技术方可作为对话式 assistant 部署。1. 语料工程大规模文本数据的采集与治理1.1 设计目标与约束预训练语料的构建需同时满足三个互相制约的优化目标维度目标工程约束规模(Scale)覆盖足够大的知识面与语言模式存储、带宽、处理吞吐质量(Quality)高信噪比排除有害/低质内容需要多级 heuristic 与 classifier多样性(Diversity)领域、文体、语言的均衡分布避免 distribution shift 与 mode collapse这三者之间存在天然的张力——追求规模往往引入噪声过度过滤则损害多样性。工业级语料工程的核心挑战在于在这组 Pareto frontier 上找到最优平衡点。1.2 数据源Common Crawl 与种子扩展策略当前主流 LLM 的语料基底几乎均源自Common Crawl——一个自 2007 年持续运作的大规模 web archiving 项目。截至 2024 年其索引规模已达2.7 billion web pages采用 breadth-first crawling strategy 从种子 URL 集出发递归扩展。原始 Common Crawl archive 以 WARC (Web ARChive) 格式存储包含完整的 HTTP response含 header、HTML body、embedded resources 等信噪比极低不可直接用于模型训练。各 LLM 厂商OpenAI、Anthropic、Google DeepMind、Meta FAIR 等均在此基础上构建了各自的 proprietary data pipeline。1.3 多级数据治理 Pipeline以 HuggingFace 公开的FineWeb数据集为参考实现工业级语料治理通常包含以下级联阶段Stage 1: URL-Level Filtering基于预维护的 domain blocklist 实施粗粒度过滤目标排除以下类别Malicious contentmalware distribution sites、phishing domainsLow-quality sourcescontent farms、SEO spam、auto-generated pagesPolicy-violating contentadult material、hate speech domainsCommercial noiseaggressive marketing、affiliate link aggregators该阶段的 precision-recall trade-off 倾向于 high recall宁可误杀因后续阶段可进一步过滤。Stage 2: Content Extraction Boilerplate Removal原始 HTML 文档包含大量非内容元素navigation bars、sidebars、footers、CSS/JS inline code、ad scripts 等需要通过main content extraction算法提取正文常用方案包括Trafilatura、Readability等基于 DOM tree analysis 的启发式提取器需处理的边界情况多栏布局、动态加载内容SPA/CSR、table-heavy pages提取质量直接影响下游模型对语言模式的学习是整个 pipeline 中 ROI 最高的环节之一Stage 3: Language Identification Filtering使用fastText-based language classifier对每个文档进行语言识别依据预设的语言分布策略进行过滤FineWeb 采用English ≥ 65%的阈值策略属于 English-centric 设计该阈值是一个关键的hyperparameter直接决定模型的多语言能力multilingual capability工业实践中通常采用 stratified sampling 策略按语言族群设定不同的配比权重Stage 4: Document-Level Passage-Level Deduplication互联网存在大量 near-duplicate contentsyndication、scraping、templated pages去重是提升语料有效信息密度的关键步骤Exact deduplication基于 document hashSHA-256 / MD5的精确匹配Near-duplicate detection基于MinHash LSH (Locality-Sensitive Hashing)的近似去重Passage-level dedup对文档内部的重复段落进行检测处理 boilerplate paragraphs充分去重可有效缓解模型的memorization tendency降低 training data extraction attack 的风险Stage 5: PII Redaction为满足 GDPR 等数据隐私法规要求需检测并移除Personally Identifiable Information采用 NER (Named Entity Recognition) 模型识别 addresses、phone numbers、SSN、email addresses 等高敏感文档直接从语料中剔除低敏感文档进行 entity-level masking该阶段需平衡隐私保护与数据可用性redaction 过度会引入分布偏差1.4 语料统计特征以 FineWeb 为例的最终产出MetricValueNotesDisk footprint44 TB纯文本未压缩Token count (GPT-4 tokenizer)~15 Trillion15 × 10¹²Document countBillions经过去重后Dominant languageEnglish≥65% thresholdKnowledge cutoffEnd of 2023时效性上界值得注意的是尽管原始互联网规模庞大经过多级过滤后的高质量文本语料在存储空间上相当紧凑——44 TB 已可容纳于单块企业级 HDD 中。这一事实反映了互联网文本的高冗余度与低信噪比特征。2. Tokenization从连续文本到离散符号序列2.1 问题定义与核心 Trade-offNeural Language Model 要求输入为有限符号集上的一维离散序列。Tokenization 即为建立从原始文本到此表示的 bijective mapping 的过程。该过程面临一个根本性的 trade-offVocabulary Size ↑ ⟺ Sequence Length ↓ ⟺ Computational Efficiency ↑ Vocabulary Size ↓ ⟺ Sequence Length ↑ ⟺ Computational Efficiency ↓Sequence length 是 Transformer 架构中最为稀缺的计算资源self-attention 的时空复杂度为 O(n²)因此需要在 vocabulary size 与 sequence length 之间寻找 Pareto-optimal 的平衡点。2.2 编码层级与压缩递进文本到 token 序列的转换可分解为多个层级的表示变换每一级在 vocabulary cardinality 与 sequence length 之间实现不同的压缩比LevelRepresentationVocabulary SizeSequence LengthCompression RatioL0Raw Unicode Text~150K codepointsBaseline1xL1UTF-8 Bitstream2 (binary)~8x longer0.125xL2Byte Sequence256Baseline1xL3BPE Tokens~100K~4x shorter~4x从 L2 到 L3 的压缩由Byte Pair Encoding (BPE)算法实现是当前工业标准。2.3 Byte Pair Encoding 算法BPE 是一种bottom-up subword segmentation算法其核心思想是通过迭代合并高频相邻符号对bigram来构建 vocabulary算法流程Input: byte sequence B [b₁, b₂, ..., bₙ], initial vocab V {0, 1, ..., 255} Repeat K times: 1. 统计 B 中所有 adjacent pair (bᵢ, bᵢ₊₁) 的频次 2. 选取频次最高的 pair (bₐ, bᵦ) 3. 创建新符号 s |V|加入 V 4. 将 B 中所有 (bₐ, bᵦ) 替换为 s 5. |V| 1, len(B) - count(bₐ, bᵦ) Output: compressed sequence B, vocabulary V with |V| 256 K每次迭代的效果vocabulary cardinality 1sequence length −NN 为该 bigram 的出现次数。实践中 K 的取值约为 ~100,000使最终 vocabulary size 达到 ~100K 量级。GPT-4 的 tokenizercl100k_basevocabulary size 为100,277。2.4 Tokenization 的工程特性BPE tokenization 具有以下值得关注的特性Case-sensitiveHello与hello映射到不同的 token IDWhitespace-aware前导空格通常被编码进 token 内部e.g., world是一个完整 tokenSubword granularity常见词为单一 token罕见词被拆分为多个 subword unitsCompression ratio典型英文文本的 tokens/characters 比约为1:4即一行文本约编码为 ~60 tokensDeterministic给定 vocabulary 和 merge rulestokenization 过程是确定性的3. 神经网络训练基于 Transformer 的自监督预训练3.1 训练范式Causal Language Modeling预训练采用Causal Language Modeling (CLM)目标函数即在给定前文 context 的条件下最大化 next token 的 log-likelihood目标函数 max_θ Σᵢ log P(xᵢ | x₁, x₂, ..., xᵢ₋₁ ; θ) 等价地最小化 cross-entropy loss L(θ) -1/T Σᵢ log P_θ(xᵢ | xᵢ) 其中 θ 模型参数weights biases xᵢ 第 i 个 tokenground truth xᵢ 前 i-1 个 token 构成的 context T 序列长度context window size P_θ 模型的条件概率估计训练流程的每个 optimization step从语料中随机采样一个 token window[x₁, ..., x_T]T 通常为 2K~128K模型对每个位置 i 输出 next-token probability distributionP_θ(· | xᵢ) ∈ R^|V|计算 cross-entropy loss 并通过backpropagation求参数梯度使用AdamW optimizer更新参数 θlearning rate 通常遵循 cosine annealing schedule该过程在每个 window 内的所有 token 位置并行执行teacher forcing单次 forward-backward pass 可同时优化 T 个 next-token prediction。3.2 Transformer 架构当前所有主流 LLM 均采用decoder-only Transformer架构Vaswani et al., 2017 的变体其 forward pass 可概括为Input Token IDs: [x₁, x₂, ..., x_T] ∈ Z^T │ ▼ ┌──────────────────────┐ │ Token Embedding │ E(xᵢ) ∈ R^d_model │ Positional Encoding│ (RoPE / ALiBi / Learned) └──────────────────────┘ │ ▼ ┌──────────────────────┐ │ Transformer Block │ ─┐ │ ┌─ RMSNorm │ │ │ ├─ Multi-Head │ │ │ │ Causal Attention │ │ │ ├─ Residual Add │ │ × N layers │ ├─ RMSNorm │ │ (N 32~128) │ ├─ SwiGLU FFN │ │ │ └─ Residual Add │ │ └──────────────────────┘ ─┘ │ ▼ ┌──────────────────────┐ │ Final RMSNorm │ │ Linear → R^|V| │ (projection to vocab size) │ Softmax → P(next) │ output ∈ R^|V|, Σ 1 └──────────────────────┘Multi-Head Self-Attention 机制Attention 是 Transformer 的核心计算单元。其作用对象是当前输入序列中的 token representations而非 vocabulary 中的全部 token对于序列中的每个 position iattention 机制执行以下计算Q X · W_Q, K X · W_K, V X · W_V (线性投影) Attention(Q, K, V) softmax( Q · K^T / √d_k ) · V 其中 Q (Query): 当前位置 在寻找什么信息 K (Key): 每个位置 携带什么信息标签 V (Value): 每个位置 实际提供的信息内容 Q · K^T: query-key 点积相似度 → attention score matrix √d_k: scaling factor防止点积值过大导致 softmax 饱和 softmax: 归一化为概率权重 · V: 按权重聚合所有位置的 valueMulti-Head指将 d_model 维度拆分为 h 个独立的 attention head每个 head 在不同的 subspace 中学习不同类型的 dependency patternsyntactic、coreference、positional 等最终 concatenate 后通过线性投影合并。Causal Mask为确保自回归属性attention score matrix 应用下三角 mask使得 position i 只能 attend to positions ≤ i防止信息泄漏。Feed-Forward Network (SwiGLU Variant)FFN(x) (Swish(x · W₁) ⊙ (x · W₃)) · W₂ 其中 ⊙ 为 element-wise productSwish(z) z · σ(z)FFN 在每个 position 独立执行可理解为对 attention 聚合后的表示进行非线性特征变换。隐层维度通常为 d_model 的8/3 倍SwiGLU 的标准配置。3.3 训练动态与收敛行为预训练过程的 loss 曲线呈现典型的power-law decay特征Loss 5.0 │● │ ●● 4.0 │ ●●● │ ●●●● 3.0 │ ●●●●●● │ ●●●●●●●●● 2.0 │ ●●●●●●●●●●●●●● │ ●●●●●●●●●●●●●●● 1.5 │ ────── └───────────────────────────────────────────────────────────────── Step 0 5K 10K 15K 20K 25K 30K不同训练阶段模型 generation quality 的质变过程阶段模型行为语言学层面的习得Step 1(初始化)输出近似 uniform random tokens无任何语言知识~1% training出现局部 token co-occurrence patterns习得 character-level 与 subword-level statistics~10% training句子基本通顺语法大致正确习得 syntactic structure 与 common collocations~50% training段落连贯具备基础世界知识习得 semantic coherence 与 discourse structure100% training生成高质量、多样化的连贯文本习得 long-range dependency 与 factual knowledge该现象与Scaling Laws(Kaplan et al., 2020) 的理论预测一致loss 随 compute budget 的增长呈 power-law 下降但 marginal improvement 递减。3.4 模型规模与计算需求SpecificationGPT-2 (2019)LLaMA 3.1 405B (2024)Scale FactorParameters1.5B405B~270×Training tokens100B15T~150×Context length1,024128K~125×ArchitectureTransformer (GPT-style)Transformer (LLaMA-style)同系Training cost (est.)~$600 (2024 reproduction)~$100M-Training hardware8× V100 (original)10,000 H100 clusters-计算基础设施LLM 训练的计算密集度使其成为当前 HPCHigh-Performance Computing领域最具挑战性的 workload 之一计算单元NVIDIA H100 SXM80GB HBM3, 989 TFLOPS BF16为当前主力训练芯片单节点配置8× H100 通过 NVLink/NVSwitch 全互联节点内带宽 900 GB/s集群规模主流训练集群规模从数千到100,000 GPU通过 InfiniBand/RoCE 网络互联并行策略综合使用 Data Parallelism (DP)、Tensor Parallelism (TP)、Pipeline Parallelism (PP)、Sequence Parallelism (SP) 等混合并行方案云端租赁以 Lambda Labs 为例8× H100 节点按需价格约 24/hr (3/GPU/hr)GPU 集群的核心计算负载可归结为一个简洁的循环在大规模 token 序列上反复执行 forward pass → loss computation → backward pass → parameter update。这一 workload 的天文级算力需求是驱动 NVIDIA 市值突破$3.4T的根本技术因素。3.5 模型发布与 Artifact 构成一个完整的 base model release 包含两个核心 artifactModel Architecture Code定义 Transformer forward pass 的计算图通常仅数百行 Python/PyTorch 代码Model Weights (Parameters)经过训练优化后的参数张量集合是全部计算投入的结晶Model Architecture(code) Parameters(weights) 数百行 Python 数十亿个 float16/bfloat16 数值 标准化的 核心价值所在4. 推断自回归解码与采样策略4.1 自回归生成Autoregressive Generation推断阶段的 generation 过程遵循严格的autoregressive factorizationP(x₁, x₂, ..., x_T) ∏ᵢ P(xᵢ | x₁, ..., xᵢ₋₁)具体的 decoding loopInitialize: sequence S [prompt tokens] For t 1, 2, ..., max_length: 1. Forward pass: logits Model(S)[-1] ∈ R^|V| 2. Apply temperature scaling: logits logits / τ 3. Apply top-k / top-p filtering 4. Compute distribution: P softmax(logits) 5. Sample: x_t ~ Categorical(P) 6. Append: S S ∥ [x_t] 7. If x_t EOS: break Return S每一步仅生成一个 token然后将其追加至 context 中作为下一步的输入。这一 sequential dependency 是当前 LLM inference 延迟的主要瓶颈。4.2 解码策略与采样超参数Softmax 输出的 probability distribution 可通过多种策略调控生成行为Temperature Scaling在 softmax 之前对 logits 进行缩放P(xᵢ) softmax(zᵢ / τ)τ效果数学性质应用场景τ → 0退化为 argmaxgreedy decoding分布坍缩为 one-hot确定性任务代码生成、数学推理τ 1.0保持原始分布无变换通用对话τ 1.0分布熵增大趋向 uniform增加 exploration创意写作、brainstormingTop-k Sampling将概率排序后仅保留 top-k 个 token其余 token 的概率置零后重新归一化P(xᵢ) P(xᵢ) / Σⱼ∈top-k P(xⱼ) if xᵢ ∈ top-k P(xᵢ) 0 otherwiseTop-p (Nucleus) Sampling保留累积概率达到阈值 p 的最小 token 集合Holtzman et al., 2020V_p argmin_{V ⊂ V} |V| s.t. Σ_{x∈V} P(x) ≥ p P(xᵢ) P(xᵢ) / Σⱼ∈V_p P(xⱼ) if xᵢ ∈ V_p P(xᵢ) 0 otherwiseTop-p 相较 top-k 的优势在于其自适应性当模型对 next token 高度确定时distribution sharpV_p 自动收缩反之则自动扩展。重要以上所有采样超参数仅在 inference 阶段生效与 training 过程完全正交。Training 阶段使用 teacher forcing不涉及任何采样操作。4.3 Base Model 的行为特征Pre-training 阶段产出的 base model 具有以下 characteristic behaviors本质定位Base model 是一个conditional token distribution estimator而非 conversational agent。其行为模式为document completion——给定任意 token prefix模型输出符合训练语料分布特征的 continuation。Emergent Capabilities尽管训练目标仅为 next-token predictionbase model 展现出多种 emergent abilitiesCapability机制实现方式In-context Learning (ICL)模型在 forward pass 中隐式地从 context 中提取 task specification在 prompt 中提供 input-output exemplarsFew-shot PromptingICL 的具体应用形式通过 K 个示例定义任务构造 K-shot prompt templateKnowledge Retrieval参数中编码的训练语料知识可通过特定 prompt 格式引出使用 elicitation prompts如列表格式、问答格式Format Following模型可延续 prompt 中建立的格式模式构造目标格式的 prefix如 JSON、Markdown、对话体已知局限局限技术根因表现Hallucination训练目标是 distribution matching 而非 factual grounding生成事实性错误的内容尤其在低频知识领域Knowledge Cutoff参数仅编码训练数据截止日期前的信息无法回答训练截止后的时事问题Verbatim Memorization高频文档如 Wikipedia被多次采样导致 overfitting逐字复现训练语料片段regurgitationNon-assistant Behavior未经 alignment模型行为是 document completion 而非 instruction following直接提问不会得到结构化回答参数即有损压缩从信息论视角base model 的 parameter set θ* 可理解为训练语料的一种lossy compression405B float16 参数 ≈810 GB的存储空间训练语料15T tokens≈44 TB的原始文本压缩比约54:1这一压缩是 lossy 的——模型保留了语料的 statistical regularities语法、常识、推理模式但丢失了精确的 verbatim content除高频重复文档外。生成内容是训练分布的stochastic sample在统计性质上近似训练语料但并非其子集。5. 从 Base Model 到 Assistant后训练路径Pre-training 产出的 base model 需经过 post-training alignment 方可作为实用的 conversational assistant 部署Base Model (document completion) │ ├── SFT (Supervised Fine-Tuning) │ 使用人工标注的 instruction-response pairs 进行有监督微调 │ ├── RLHF (Reinforcement Learning from Human Feedback) │ 训练 reward model → 使用 PPO 优化 policy │ ├── DPO (Direct Preference Optimization) │ 直接从 preference pairs 优化绕过显式 reward model │ └── 其他 alignment 技术Constitutional AI, RLAIF, etc. │ ▼ Instruct / Chat Model (instruction following)当终端用户在 ChatGPT 等产品中进行对话时其交互过程完全处于 inference 阶段——模型参数已 frozen不发生任何 gradient update。用户输入被 tokenize 后作为 context prefix模型执行 autoregressive decoding 生成 response tokens。附录核心术语索引术语全称定义CLMCausal Language Modeling自回归语言建模预测 next tokenBPEByte Pair Encoding子词分词算法迭代合并高频 bigramICLIn-Context Learning模型从 prompt 中的示例隐式学习任务SFTSupervised Fine-Tuning使用标注数据的有监督微调RLHFReinforcement Learning from Human Feedback基于人类偏好反馈的强化学习DPODirect Preference Optimization直接偏好优化RLHF 的简化替代RoPERotary Position Embedding旋转位置编码RMSNormRoot Mean Square Normalization均方根归一化SwiGLUSwish-Gated Linear UnitFFN 中的门控激活函数变体NVLinkNVIDIA NVLinkGPU 间高速互联总线TP / DP / PPTensor / Data / Pipeline Parallelism分布式训练的三种并行策略LSHLocality-Sensitive Hashing局部敏感哈希用于近似最近邻搜索WARCWeb ARChiveWeb 归档文件格式关键数值参考数值含义44 TBFineWeb 数据集磁盘占用15 × 10¹²FineWeb token 总量2.7 × 10⁹Common Crawl 索引网页数 (2024)100,277GPT-4 tokenizer vocabulary size1.5 × 10⁹GPT-2 parameter count405 × 10⁹LLaMA 3.1 largest model parameter countO(n²)Self-attention 的时空复杂度 (n sequence length)$3/GPU/hrH100 按需云租赁参考价格