一句话总结:Llama 3 是 Meta 在 2024 年 7 月发布的开源基础模型群——以 405B 参数 dense Transformer(GQA + RoPE θ=500K + 128K 词表)为旗舰,在精心清洗的 15.6T 多语言 token 上预训练,通过"标准 8K + 六阶段长上下文"扩到 128K context,再用"SFT → 拒绝采样 → DPO"为骨干的 6 轮迭代 post-training 对齐;论文还以"组合式适配器"(image / video / speech)给出多模态实验结果。一句话:数据质量 + 规模 + 工程简化(dense 而非 MoE、DPO 而非 PPO)三条路线同时推到底。
🎯 面试考点(高频):
① 图说明:论文的"骨架图"。从左到右展示 Llama 3 训练全流程:原始文本 → tokenization → 405B dense Transformer 在 15.6T token 上预训练 → 长上下文继续预训练扩到 128K → post-training(SFT + RS + DPO,六轮) → 对齐后的 Llama 3;下方分支接入 image encoder / video adapter / speech adapter,组合成多模态模型。
② 关键数据:预训练 15.6T tokens、context 8K → 128K、3.8 × 10²⁵ FLOPs(≈ 50× Llama 2);post-training 走 SFT → RS → DPO 三件套 ×6 轮;多模态走组合式(cross-attn 适配器),冻结 LM,不联合预训练。
③ 启示:Llama 3 把"复杂度"从架构(MoE / 多模态联合预训练)和算法(PPO)里挪到了数据 + 训练规模 + 工程稳定性;图中没有 RL,只有 DPO——这是 405B 体量上"DPO 跑赢 PPO"的一次公开背书。
① 图说明:Scaling-law IsoFLOPs 曲线。横轴是训练 token 数(10¹⁰–10¹²),纵轴是 hold-out 验证集上的 NLL;每条曲线对应一个 FLOPs 预算(6 × 10¹⁸ 到 10²²),作者在每个预算下扫多个模型规模,二次多项式拟合得到该预算的最优(N, D)。
② 关键数据:预算从 6e18 到 1e22 共 10 档;每档取抛物线极小值即"compute-optimal"模型。把这些极小点的 N 与 C 做幂律拟合,得到 $N^*(C) = A\,C^\alpha$,$\alpha \approx 0.53$、$A \approx 0.29$,外推到 3.8 × 10²⁵ FLOPs 给出 ≈ 402B 参数 / 16.55T tokens。
③ 启示:关键观察是预算越大、IsoFLOPs 抛物线越平——意味着模型大小的最优解附近性能很鲁棒。Llama 团队因此把 token 数从 compute-optimal 的 16.55T 调到 15.6T、把 N 从 402B 取整到 405B,几乎不影响最终质量,却换来推理友好性。
① 图说明:"compute-optimal token 数 vs 训练预算"幂律拟合图。横轴是预算 C(FLOPs,10¹⁹–10²²),纵轴是该预算下最优 token 数 N*(C);蓝点来自图 2 抛物线极小值,直线是幂律 $N^*(C) = A\,C^\alpha$ 的拟合。
② 关键数据:拟合得 $(\alpha, A) = (0.53, 0.29)$;斜率 0.53 接近 Chinchilla 的 0.5,但略偏"token-heavy"。把直线外推到 Llama 3 旗舰预算 3.8 × 10²⁵ FLOPs,落点是 ≈ 16.55T tokens × ≈ 402B 参数。
③ 启示:这给 405B 大小提供了可外推 4 个数量级的依据——直接训那么大模型成本太高,只能用小预算扫 scaling law 反推。该流程后来也用来挑数据 mixture(在小模型上扫 mixture → 拟合 → 选最优配比)。
① 图说明:把 scaling-law 预测"延伸到下游 benchmark"的两步法,以 ARC Challenge 为例。左:横轴训练 FLOPs,纵轴 ARC 正确答案的归一化 NLL —— 用 scaling-law 小模型拟合一条线;右:横轴归一化 NLL,纵轴 ARC 准确率 —— 用小模型 + Llama 2 一起拟合 sigmoid,把"loss → acc"映射出来。
② 关键数据:预测覆盖 10²⁰–10²⁵ FLOPs(≈ 5 个数量级);最终 Llama 3 405B 在 ARC 上的实际表现略高于外推预测,说明大模型有"突变收益"未被 scaling-law 捕获,反过来证明数据 mixture 选择正确。
③ 启示:用"FLOPs → NLL → benchmark acc"两步拼接,是开源界目前最稳的"在跑大模型之前先估 benchmark"方法,直接对标 GPT-4 那种"emergent capability"宣称。对 Meta 自己来说:它给了去训 405B 一个量化承诺,而不是赌大小。
① 图说明:Post-training 全流程示意。每一轮按 偏好数据 → 训 RM → 用 RM 做拒绝采样(RS)给提示挑最优响应 → SFT 把 RS 数据 + 合成数据混进去训 → DPO 在最近一批策略采样的偏好对上对齐 串联;末尾对多组 (RM/SFT/DPO) checkpoint 做模型平均,得到本轮模型,然后再用它去给下一轮挖偏好。
② 关键数据:共 6 轮迭代;每轮 RM 训练沿用 Llama 2 BT loss 但去掉 margin 项,新增"edited > chosen > rejected"三档排序;SFT 用 LR 1e-5、8.5–9K step;DPO 用 β = 0.1、LR 1e-5,并对格式 token mask 出 loss、外加 0.2 × NLL 正则。
③ 启示:这张图是"开源界第一次把 Anthropic / OpenAI 的 RLHF 串联在 405B 上用 DPO 替代 PPO 跑通"的可视化定稿。多轮 + 拒绝采样 + 模型平均是 Llama 3 做 instruct 的三件法宝——比单跑 DPO 更稳、比 PPO 更便宜。
① 图说明:多模态"组合式(compositional)"训练流程图。从下到上 5 个阶段:① 语言模型预训练(主线 Llama 3 405B)→ ② 多模态编码器预训练(图像编码器 + 自监督语音编码器分头训)→ ③ Vision adapter 训练(在 LM 与 image encoder 之间插 cross-attn 层,只训 adapter + image encoder,LM 冻结)→ ④ 模型微调 → ⑤ Speech adapter 训练(语音 encoder 输出经 adapter 转 token 喂给 LM,LM 冻结)。
② 关键数据:Image encoder 用大量 image-text pair 训(CLIP 风格质量过滤 + SSCD 去重 + OCR);Video 在 image encoder 之上叠 temporal aggregator + video cross-attn;Speech 用 mask-and-reconstruct 自监督,再加 TTS。关键约束:vision adapter 训练期间 不更新 LM 参数。
③ 启示:组合式优于联合预训练的核心理由:① 文本能力零损失;② 避开多模态 token 化与困惑度冲突;③ cross-attn 推理时不必把图像走 FFN,省算力。代价是 image token 不能像 Flamingo / GPT-4V 那样深度交错——这也是后来 Llama 3.2/3.3 调整路线的伏笔。
① 图说明:推理阶段的 micro-batching 性能曲线。左:prefill 阶段(time-to-first-token vs prefill throughput)的 latency–throughput 前沿;右:decode 阶段(每 token latency vs decode throughput);两条曲线对比 TP8/PP2 BF16 与 TP8/PP2 BF16 + micro-batching。
② 关键数据:405B 在 BF16 下无法塞进单机 8 × H100,只能跨 2 机 16 GPUs 用 tensor parallel (机内 NVLink) + pipeline parallel (机间);加 micro-batching 后,prefill 与 decode 阶段在相同本地 batch下吞吐都提升(curve 整体右移)、latency 略增,但 latency-throughput 前沿被推到外侧。
③ 启示:Llama 3 推理工程的两板斧:PP + micro-batching 解决"装不进单机"的吞吐问题,FP8 quant 解决 FFN 计算瓶颈(self-attn 不 quant 防数值漂移)。这也是社区跑 405B 时实际复制的 recipe。
① 图说明:语音端到端处理流程。语音输入 → self-supervised speech encoder(对部分语音帧 mask 后,通过离散 token 表示重建被 mask 的部分)→ speech adapter(把语音表示转成 LM token 表示)→ 冻结的 Llama 3 LM → 文本回复;反向链路接 TTS 系统输出语音。
② 关键数据:speech encoder + adapter 联合训练,但 LM 仍冻结;encoder 学到的是"语音信号结构"而非"语音 → 文本"对齐(后者交给 adapter 完成)。这种解耦让 ASR 数据不必直接进 LM。
③ 启示:与 vision 是同一思路:让 LM 主权重不动,所有跨模态适配压到一个轻量 adapter 上,既保护文本能力,又方便分阶段迭代。代价是无法做语音原生 reasoning(语音 token 没进 self-attention 的 KV cache 主流),后续 Llama 3.2 Voice 路线会调整。
The Llama 3 Herd of Models. Llama Team, AI @ Meta. A detailed contributor list can be found in the appendix of this paper. Modern artificial intelligence (AI) systems are powered by foundation models.
《Llama 3 模型群》。Meta AI 的 Llama 团队;详细贡献者名单见论文附录。现代 AI 系统由"基础模型"驱动。
Foundation models are general models of language, vision, speech, and/or other modalities that are designed to support a large variety of AI tasks. The development of modern foundation models consists of two main stages: (1) a pre-training stage in which the model is trained at massive scale using straightforward tasks such as next-word prediction or captioning, and (2) a post-training stage in which the model is tuned to follow instructions, align with human preferences, and improve specific capabilities.
In this paper, we present a new set of foundation models for language, called Llama 3. The Llama 3 Herd of models natively supports multilinguality, coding, reasoning, and tool usage. Our largest model is a dense Transformer with 405B parameters, processing information in a context window of up to 128K tokens.
基础模型(foundation model)是面向语言、视觉、语音及其他模态的通用模型,设计用来支撑多种多样的 AI 任务。现代基础模型的发展分两大阶段:① 预训练——用"下一个词预测"或图像描述等朴素任务在大规模数据上训;② post-training——把模型调成会跟随指令、与人类偏好对齐、并在特定能力(如编码、推理)上更强。
本文提出一组新的语言基础模型 Llama 3。这一"模型群"原生支持多语言、代码、推理与工具使用;最大的旗舰是一个 405B 参数的 dense Transformer,context window 最长 128K tokens。
We believe there are three key levers in the development of high-quality foundation models: data, scale, and managing complexity. Data. We improved both the quantity and quality of the data we use for pre-training and post-training. We pre-train Llama 3 on a corpus of about 15T multilingual tokens, compared to 1.8T tokens for Llama 2. Scale. Our flagship language model was pre-trained using $3.8 \times 10^{25}$ FLOPs, almost 50× more than the largest version of Llama 2; we pre-trained a flagship model with 405B trainable parameters on 15.6T text tokens. Managing complexity. We opt for a standard dense Transformer model architecture rather than a mixture-of-experts model to maximize training stability, and we adopt a relatively simple post-training procedure based on supervised finetuning (SFT), rejection sampling (RS), and direct preference optimization (DPO).
我们认为做高质量基础模型有三个关键杠杆:数据、规模、控制复杂度。数据:比 Llama 2 显著提升预/后训练数据的"量"与"质"——Llama 3 的预训练语料约 15T 多语言 token,而 Llama 2 只有 1.8T(约 8.7×)。规模:旗舰模型用 $3.8 \times 10^{25}$ FLOPs 预训练,几乎是 Llama 2 最大版本的 50×;具体为 405B 参数 × 15.6T 文本 token。控制复杂度:架构上选标准 dense Transformer 而不上 MoE 以最大化训练稳定性;post-training 采用相对简单的 SFT + 拒绝采样(RS)+ DPO,而非更复杂、更难规模化的 RL 算法。
The development of our Llama 3 language models comprises two main stages. Language model pre-training: we pre-train a model with 405B parameters on 15.6T tokens using a context window of 8K tokens; this is followed by a continued pre-training stage that increases the supported context window to 128K tokens. Language model post-training: the pre-trained language model has a rich understanding of language but it does not yet follow instructions or behave in the way we would expect an assistant to. We align the model with human feedback in several rounds, each of which involves supervised finetuning (SFT) on instruction tuning data and Direct Preference Optimization (DPO).
We also perform experiments in which we add image, video, and speech capabilities to Llama 3 using a compositional approach. The approach we study comprises three additional stages: multi-modal encoder pre-training, vision adapter training, and speech adapter training.
Llama 3 语言模型分两大训练阶段。预训练:在 8K context window 下用 15.6T tokens 预训 405B 模型;continued pre-training 把支持的 context window 扩到 128K。Post-training:预训练模型对语言理解很丰富,但还不会按指令行事、也不像一个 assistant;我们用"人类反馈"对模型做多轮对齐,每轮包括 SFT(指令微调数据)+ DPO。
我们还做了多模态扩展实验,采用"组合式(compositional)"方法,把图像、视频、语音能力加到 Llama 3 上,共 3 个附加阶段:多模态编码器预训练、vision adapter 训练、speech adapter 训练。
We create our dataset for language model pre-training from a variety of data sources containing knowledge until the end of 2023. We apply several de-duplication methods and data cleaning mechanisms on each data source to obtain high-quality tokens. We remove domains that contain large amounts of personally identifiable information (PII), and domains with known adult content.
Web Data Curation. We implement filters designed to remove data from websites that are likely to contain unsafe content or high volumes of PII. We process the raw HTML content with a custom parser that optimizes for precision in boilerplate removal and content recall; we carefully preserve mathematics and code structure and maintain image alt attribute text. We find that markdown is harmful to performance and remove all markdown markers.
预训练数据集涵盖到 2023 年底的多源数据;对每个数据源都做了若干去重(de-duplication)与清洗,以拿到高质量 token。我们移除两类站点:含大量 PII(个人可识别信息)的站点,以及已知含成人内容的站点。
Web 数据清洗。首先用过滤器剔除可能含不安全内容或大量 PII 的网站。HTML 处理走自研 parser,目标是"精确去 boilerplate、召回正文"——对数学与代码结构特别小心保留,图像 alt 属性也保留(因为数学常以图像 + alt 给出)。实验发现:对主要在 web 上训的模型,markdown 标记反而是负面的,因此一律去掉。
De-duplication. We apply several rounds of de-duplication at the URL, document, and line level. URL-level: we keep the most recent version for each URL. Document-level: global MinHash de-duplication across the entire dataset to remove near duplicates. Line-level: we remove lines that appeared more than 6 times in each bucket of 30M documents (similar to ccNet).
Heuristic filtering. We use duplicated n-gram coverage ratio to remove repeated content; "dirty word" counting to filter adult sites not covered by block lists; and token-distribution KL divergence to filter documents with excessive outlier tokens.
Model-based quality filtering. We use fasttext-based classifiers trained to recognize text that would be referenced by Wikipedia, as well as Roberta-based classifiers trained on Llama 2 predictions; for efficiency we use DistilRoberta to score each document. We also build domain-specific pipelines for code and reasoning, trained on web data annotated by Llama 2.
三级去重。(1) URL 级:同 URL 保留最新版本;(2) document 级:对全量做 MinHash 全局去重以剔近重文档;(3) line 级:类似 ccNet,在每 30M 文档桶内移除"出现 6 次以上"的行——人工检查发现这虽然会误删一些 boilerplate 中混着的高质量句,但实证效果仍是显著提升。
启发式过滤。① 用"重复 n-gram 覆盖比"剔除"日志/报错"类的重复内容;② 用"脏词计数"过滤 blocklist 没覆盖到的成人站点;③ 用"token 分布 KL 散度"过滤含过多 outlier token 的文档。
模型质量分类器。用 fasttext(预测"是否会被 Wikipedia 引用")与基于 Llama 2 标注训的 RoBERTa 分类器筛高质量;实际打分用 DistilRoBERTa 提速。代码与数学走单独管线:领域分类器同样是 DistilRoBERTa,但训练时prompt 调优定向到含"数学推导/STEM 推理/代码 + 自然语言"的页。
Multilingual data. Our multilingual text processing pipeline has several unique features: we use a fasttext-based language identification model to categorize documents into 176 languages; we perform document-level and line-level de-duplication within data for each language; we apply language-specific heuristics and model-based filters to remove low-quality documents; we perform quality ranking of multilingual documents using a multilingual Llama 2-based classifier.
Data Mix. Our main tools in determining this data mix are knowledge classification and scaling law experiments. Our final data mix contains roughly 50% of tokens corresponding to general knowledge, 25% of mathematical and reasoning tokens, 17% code tokens, and 8% multilingual tokens.
Annealing Data. We find that annealing on small amounts of high-quality code and mathematical data can boost the performance of pre-trained models on key benchmarks; annealing improved the performance of a pre-trained Llama 3 8B model on the GSM8k and MATH validation sets by 24.0% and 6.4%, respectively. However, the improvements on the 405B model are negligible.
多语言数据。用 fasttext 语言识别把文档分到 176 种语言;对每种语言各自做文档级与行级去重;按语言定制启发式 + 模型过滤;再用多语言 Llama 2 分类器做质量排序。多语言占比靠"小模型在不同英文/多语比例下的下游表现"实验来选,以平衡英文 benchmark 与多语 benchmark。
预训练混合配比。选 mixture 的两大工具:知识分类器(把 web 内容按主题分类,以便下采样过度代表的类目如"娱乐")+ scaling-law 实验(在不同 mixture 上训小模型、拟合并外推大模型表现)。最终配比:50% 通用知识 / 25% 数学+推理 / 17% 代码 / 8% 多语言。
Annealing 数据。实证发现:在预训练末段用少量"高质量代码+数学"数据做退火,可显著抬升 benchmark——8B 在 GSM8k / MATH 验证集上分别 +24.0% / +6.4%;但 405B 上提升微乎其微,说明旗舰模型的 in-context 学习与推理已足够强,不再依赖领域内训练样本。
Llama 3 uses a standard, dense Transformer architecture. It does not deviate significantly from Llama and Llama 2 in terms of model architecture; our performance gains are primarily driven by improvements in data quality and diversity as well as by increased training scale. We make a few small modifications compared to Llama 2: we use grouped query attention (GQA) with 8 key-value heads to improve inference speed and to reduce the size of key-value caches during decoding; we use an attention mask that prevents self-attention between different documents within the same sequence; we use a vocabulary with 128K tokens (100K from tiktoken plus 28K additional non-English tokens), improving compression rates from 3.17 to 3.94 characters per token; we increase the RoPE base frequency hyperparameter to 500,000 to better support longer contexts.
Llama 3 405B uses an architecture with 126 layers, a token representation dimension of 16,384, and 128 attention heads.
Llama 3 使用标准 dense Transformer,架构相对 Llama / Llama 2 没大变;主要的性能提升来自数据质量、数据多样性、训练规模。与 Llama 2 相比的小改动:① GQA(grouped query attention)用 8 个 KV head,加快推理、缩小 KV cache;② 引入 document-level attention mask,防止同一序列内跨文档的 self-attention(标准预训练影响有限,但长序列继续预训练下很关键);③ 词表 128K = tiktoken 的 100K + 额外 28K 非英语 token,英文压缩率从 3.17 → 3.94 chars/token;④ RoPE base 频率从默认调到 500,000 以支持更长 context。
Llama 3 405B 的具体超参:126 层 / d=16,384 / 128 attention heads。
Scaling Laws. We develop scaling laws to determine the optimal model size for our flagship model given our pre-training compute budget. We implement a two-stage methodology to develop scaling laws that accurately predict downstream benchmark performance: (1) we first establish a correlation between the compute-optimal model's negative log-likelihood on downstream tasks and the training FLOPs; (2) next, we correlate the negative log-likelihood on downstream tasks with task accuracy, utilizing both the scaling law models and older models trained with higher compute FLOPs.
We construct our scaling laws by pre-training models using compute budgets between $6 \times 10^{18}$ FLOPs and $10^{22}$ FLOPs. We assume a power-law relation between compute budget $C$ and the optimal number of training tokens $N^\star(C)$:
Extrapolation of the resulting scaling law to $3.8 \times 10^{25}$ FLOPs suggests training a 402B parameter model on 16.55T tokens. An important observation is that IsoFLOPs curves become flatter around the minimum as the compute budget increases — this implies that performance of the flagship model is relatively robust to small changes in the trade-off between model size and training tokens. Based on this observation, we ultimately decided to train a flagship model with 405B parameters.
Scaling Laws。在确定旗舰模型尺寸时,作者搞了一套两步法预测下游 benchmark 表现:① 先把"compute-optimal 模型在下游任务上的 NLL"与"训练 FLOPs"做线性关联;② 再把"NLL"与"任务准确率"用 sigmoid 关联(同时用 scaling-law 小模型 + 高算力的 Llama 2 拟合)。
scaling-law 实验在 $6 \times 10^{18}$ 到 $10^{22}$ FLOPs 间扫;假设最优 token 数与算力是幂律关系:
把这条幂律外推到 $3.8 \times 10^{25}$ FLOPs,建议训 402B × 16.55T tokens。一个关键观察:算力越大,IsoFLOPs 抛物线越平,意味着旗舰模型的最优解附近"模型大小 vs token 数"的取舍很鲁棒——所以最终取整到 405B × 15.6T,几乎不损失质量却便于推理。
Initial Pre-Training. We pre-train Llama 3 405B using AdamW with a peak learning rate of $8 \times 10^{-5}$, a linear warm up of 8,000 steps, and a cosine learning rate schedule decaying to $8 \times 10^{-7}$ over 1,200,000 steps. We use a lower batch size early in training to improve training stability, and increase it subsequently to improve efficiency. Specifically, we use an initial batch size of 4M tokens and sequences of length 4,096, and double these values to a batch size of 8M sequences of 8,192 tokens after pre-training 252M tokens. We double the batch size again to 16M after pre-training on 2.87T tokens.
初始预训练。405B 用 AdamW,peak LR $8 \times 10^{-5}$,线性 warmup 8,000 步,cosine 衰减到 $8 \times 10^{-7}$,共 120 万步。batch size 渐进放大以稳住早期训练:开局 4M token、序列长 4,096;训 252M token 后 batch 翻倍到 8M、序列长翻到 8,192;训到 2.87T token 再翻一次到 16M token / batch。
Long Context Pre-Training. In the final stages of pre-training, we train on long sequences to support context windows of up to 128K tokens. We do not train on long sequences earlier because the compute in self-attention layers grows quadratically in the sequence length. We increase the supported context length in increments, pre-training until the model has successfully adapted to the increased context length. We assess successful adaptation by measuring whether (1) model performance on short-context evaluations has recovered completely and (2) the model perfectly solves "needle in a haystack" tasks up to that length. In Llama 3 405B pre-training, we increased context length gradually in six stages, starting from the original 8K context window and ending in the final 128K context window. This long-context pre-training stage was performed using approximately 800B training tokens.
长上下文预训练。预训练末段才上长序列,因为 self-attention 算力随序列长度平方增长。作者把支持的 context length 分档渐进扩张,每档训到模型"适应"了再进下一档——判定标准是:(1) 短 context 评测完全恢复到原水平;(2) "针在草堆中(NIH)"任务在该长度下完全通过。在 Llama 3 405B 里,context 从原始 8K → 16K → 32K → 64K → 96K → 128K,共 6 个阶段;整个长 context 预训练共烧 ≈ 800B token。
Annealing. During pre-training on the final 40M tokens, we linearly annealed the learning rate to 0, maintaining a context length of 128K tokens. During this annealing phase, we also adjusted the data mix to upsample data sources of very high quality. Finally, we compute the average of model checkpoints (Polyak averaging) during annealing to produce the final pre-trained model.
退火(Annealing)。预训练的最后 40M token,LR 线性退火到 0,context 维持 128K;退火期间把"超高质量数据"上采样进 mixture。最后对退火阶段的多个 checkpoint 做 Polyak 平均,得到最终的预训练模型。
We produce the aligned Llama 3 models by applying several rounds of post-training, or aligning the model with human feedback on top of a pre-trained checkpoint. Each round of post-training involves supervised finetuning (SFT) followed by Direct Preference Optimization (DPO) on examples collected either via human annotations or generated synthetically. The backbone of our post-training strategy is a reward model and a language model. We first train a reward model on top of the pre-trained checkpoint using human-annotated preference data. We then finetune pre-trained checkpoints with supervised finetuning (SFT), and further align the checkpoints with Direct Preference Optimization (DPO).
"对齐版"Llama 3 是在预训练 checkpoint 上做若干轮 post-training 得到的。每一轮 = SFT → DPO,数据来自人工标注或合成。post-training 的骨干是两个模型:一个奖励模型(RM) + 一个语言模型。流程上:先在预训练 checkpoint 上用人工标注的偏好数据训 RM;再做 SFT 微调;最后用 DPO 把 SFT checkpoint 进一步对齐到人类偏好。
Reward Modeling. The training objective is the same as Llama 2 except that we remove the margin term in the loss, as we observe diminishing improvements after data scaling. Annotations also create a third "edited response" for some prompts, where the chosen response from the pair is further edited for improvement. Hence, each preference ranking sample has two or three responses with clear ranking (edited > chosen > rejected). The standard reward model objective is the Bradley–Terry pairwise loss:
where $(y_w, y_l)$ is a preferred / rejected pair and $\sigma$ is the logistic function. We concatenate the prompt and multiple responses into a single row during training with responses randomly shuffled — this approximates the standard scenario but improves training efficiency without a loss in accuracy.
奖励建模(RM)。训练目标沿用 Llama 2,但去掉了 margin 项——作者观察到数据扩张后 margin 的收益递减。标注里对部分 prompt 引入第三档"edited response"(由标注员把 chosen 进一步改得更好),使得每条偏好样本可有2 或 3 档排序:edited > chosen > rejected。标准 RM 目标是 Bradley–Terry pairwise loss:
其中 $(y_w, y_l)$ 是被偏好/被拒绝的回答对,$\sigma$ 为 sigmoid。训练时把 prompt 与多个响应拼成一行(响应顺序随机打乱),近似"分别打分"的写法但提升训练吞吐、且不损精度。
Supervised Finetuning (SFT). The reward model is then used to perform rejection sampling on our human annotation prompts. Together with this rejection-sampled data and other data sources (including synthetic data), we finetune the pre-trained language model using a standard cross entropy loss on the target tokens (while masking loss on prompt tokens). We refer to this stage as supervised finetuning even though many of the training targets are model-generated. Our largest models are finetuned with a learning rate of $10^{-5}$ over the course of 8.5K to 9K steps.
监督微调(SFT)。RM 训好后用来做"拒绝采样(rejection sampling)"——对每个 prompt 采 N 个候选,只留 RM 打分最高的那条作为 SFT target。这些拒绝采样数据 + 其他数据源(含合成)汇总后,用标准交叉熵在 target token 上微调(prompt token 上的 loss 被 mask 掉)。这一阶段仍叫"SFT",虽然很多 target 其实是模型自己生成的。旗舰用 LR $10^{-5}$ × 8.5K–9K 步。
Direct Preference Optimization (DPO). We further train our SFT models with DPO for human preference alignment. For training, we primarily use the most recent batches of preference data collected using the best performing models from the previous alignment rounds. We also explored on-policy algorithms such as PPO, but found that DPO required less compute for large-scale models and performed better, especially on instruction following benchmarks like IFEval. For Llama 3, we use a learning rate of $10^{-5}$ and set the $\beta$ hyper-parameter to be $0.1$. The DPO objective is:
We apply two algorithmic modifications to DPO. Masking out formatting tokens in DPO loss: we mask out special formatting tokens (header and termination tokens) from both chosen and rejected responses in the loss; we observe that having these tokens contribute to the loss may lead to undesired model behaviors such as tail repetition or abruptly generating termination tokens. Regularization with NLL loss: we add an additional negative log-likelihood loss term with a scaling coefficient of $0.2$ on the chosen sequences, which helps stabilize DPO training by maintaining desired formatting and preventing the decrease of log probability of chosen responses.
直接偏好优化(DPO)。SFT 模型之后再用 DPO 做人类偏好对齐。训练数据主要来自上一轮最佳模型采集的最新偏好批次——这样训练数据更贴近当前策略分布。作者也试过 on-policy 算法(如 PPO),但发现 DPO 在大模型上计算更省、表现更好,尤其在 IFEval 等指令跟随评测上。超参 $\beta = 0.1$,LR $10^{-5}$。DPO 目标:
Llama 3 对 DPO 加了两个改动:① 把格式 token 从 loss 里 mask 掉——chosen 与 rejected 里共有的 header / termination 等 special token 不计入 loss,否则模型会被推向"既要增大又要减小同一 token 的似然",出现尾部重复或突然终止;② NLL 正则:对 chosen 序列额外加 $0.2 \cdot \mathcal{L}_{\mathrm{NLL}}(y_w)$,稳定训练,避免 chosen 的 logprob 反向下降。
Model Averaging. Finally, we average models obtained from experiments using various versions of data or hyperparameters at each RM, SFT, or DPO stage. Iterative Rounds. Following Llama 2, we apply the above methods in six rounds. In each cycle, we collect new preference annotations and SFT data, sampling synthetic data from the latest models.
模型平均。每个阶段(RM / SFT / DPO)都跑多组实验(不同数据版本 / 超参),最后把这些 checkpoint 做权重平均。多轮迭代。沿用 Llama 2 的迭代式 alignment,前述流程跑 6 轮;每一轮都收集新偏好标注与 SFT 数据,合成数据从最新模型采。
Preference Data. Our preference data annotation process is similar to Llama 2. We deploy multiple models for annotation after each round and sample two responses from two different models for each user prompt. We ask annotators to rate the strength of their preference by categorizing it into one of four levels (significantly better, better, slightly better, marginally better). We also incorporate an editing step after preference ranking to encourage annotators to further improve the preferred response. Consequently, a portion of our preference data has three responses ranked (edited > chosen > rejected).
In each round of post-training, we use all the preference data that is available at the time for reward modeling, while only using the latest batches from various capabilities for DPO training. For both reward modeling and DPO, we use samples that are labeled as the chosen response being significantly better or better than the rejected counterpart for training and discard samples with similar responses.
偏好数据。采集流程接近 Llama 2:每轮后部署多个模型,对每个 user prompt 从两个不同模型各采一条响应。让标注员用四档强度表达偏好(显著更好 / 更好 / 略好 / 边际好),再加一个"编辑"步骤——让标注员对 chosen 进一步精修,从而产生第三档"edited"。
每轮 post-training:RM 用当时所有可用偏好数据训(累计);DPO 只用最新一批且各能力均有覆盖。对 RM 与 DPO,只保留"显著更好"或"更好"的样本——相似的对子被丢掉,避免噪声。
SFT Data. Our finetuning data is largely comprised of the following sources: (1) Prompts from our human annotation collection with rejection-sampled responses; (2) Synthetic data targeting specific capabilities; (3) Small amounts of human-curated data. We refer to this stage as supervised finetuning even though many of the training targets are model-generated. Our finetuning data is meticulously curated to ensure quality.
Data Processing and Quality Control. Given that most of our training data is model-generated, it requires careful cleaning and quality control. We perform topic classification, quality scoring (using both reward-model scores and Llama-based rubric scores), difficulty scoring, and semantic de-duplication (using RoBERTa-based embeddings + clustering) to keep only high-quality, diverse examples.
SFT 数据来源。主要三类:① 人工标注的 prompt + RM 拒绝采样得到的 response;② 针对具体能力(代码、推理、工具、长 context 等)的合成数据;③ 少量人工 curate 数据。"SFT"这名字其实名不副实——绝大多数 target 都是模型自己生成的。
数据处理与质量控制。因为绝大多数 SFT 数据是模型生成的,清洗与质控很关键:做主题分类、质量打分(同时用 RM 分与 Llama 自评 rubric 分)、难度打分、语义去重(RoBERTa embedding + 聚类,每簇只保留最高分若干条),最终只留"高质 × 多样"的样本。
Code. We train an expert via continued pre-training on a code-heavy data mix, then run multiple rounds of SFT on it. We use the expert to generate high-quality SFT data for code and to back-translate code documentation and tests. We also use execution feedback to filter out generations that fail to compile, run, or pass unit tests.
Reasoning. For mathematical reasoning, we (1) generate step-by-step solutions and verify them with answer-checking, (2) use Llama 3 itself as a reward signal to filter reasoning chains, and (3) sample long chains-of-thought during rejection sampling.
代码。用"代码 heavy" mixture 做 continued pre-training 训出一个 code 专家模型,再对其多轮 SFT;然后用这个专家生成高质代码 SFT 数据、把代码反向翻译成文档与测试。再用执行反馈过滤掉编译/运行/单元测试失败的生成,保证 SFT 数据可执行。
推理。数学推理上:① 让模型生成 step-by-step 解,再用 answer-check 验证;② 用 Llama 3 自身作为 reward signal,过滤错误推理链;③ 在拒绝采样时偏向长 CoT。
Tool Use. We train Llama 3 to use search engines, a Python interpreter, and Wolfram Alpha. We generate synthetic data for tool use, including single-turn and multi-turn function calling. We use multiple agents to generate domains, APIs, user queries, API calls, and responses, while also ensuring that the generated data covers a set of diverse domains and realistic APIs.
Factuality. We follow the principle that post-training should align the model to "know what it knows" rather than add knowledge. Our primary approach involves generating data that aligns model generations with subsets of factual data present in the pre-training data: extract pre-training snippets → generate factual questions about them → sample answers → score correctness (Llama-as-judge against the original context) → score informativeness → generate refusals for "confidently wrong" outputs.
Steerability. For Llama 3, we focus on enhancing its steerability through system prompt with natural language instructions, especially around response length, format, tone and character/persona. We collect steerability preference samples by asking annotators to design different system prompts and evaluate conversations against them.
工具使用。训 Llama 3 用搜索引擎、Python 解释器、Wolfram Alpha;合成工具使用数据(含单轮 + 多轮 function calling)——用多个 agent 分别扮演"领域 / API / 用户 query / API 调用 / 响应"角色,逐步对话,确保覆盖多样领域与真实 API。
事实性(Factuality)。原则是 post-training 应让模型"知道自己知道什么",而不是往里塞新知识。具体做法:从预训练数据抽一段 snippet → 让 Llama 3 基于它出事实问题 → 采样回答 → 用原 snippet 作为 reference 由 Llama 3 评对错 → 评"信息量" → 对"自信但错"的答案生成拒答(refusal)样本,以鼓励模型对不确定问题说"我不知道"。
可控性(Steerability)。主要靠 system prompt 中的自然语言指令(响应长度、格式、语气、人设)。让标注员针对 Llama 3 设计不同 system prompt,然后多轮对话评估模型对这些 prompt 的一致跟随能力,采到的偏好数据进入 RM / RS / SFT / DPO 各阶段。
We performed an extensive series of evaluations of Llama 3, investigating the performance of: (1) the pre-trained language model, (2) the post-trained language model, and (3) the safety characteristics of Llama 3. The evaluations cover eight top-level categories: commonsense reasoning; knowledge; reading comprehension; math, reasoning, and problem solving; long context; code; adversarial evaluations; and aggregate evaluations.
Llama 3 8B outperforms competing models in virtually every category. Llama 3 70B outperforms its predecessor Llama 2 70B by a large margin on most benchmarks, with the exception of commonsense benchmarks that are likely saturated. Our flagship Llama 3 405B model performs on par with leading language models such as GPT-4 across a variety of tasks, and is close to matching the state-of-the-art on some benchmarks.
对 Llama 3 做了三大类全面评测:① 预训练模型;② 对齐后(instruct)模型;③ 安全特性。覆盖 8 大类:常识推理、知识、阅读理解、数学&推理、长上下文、代码、对抗、聚合指标。
结论:8B 在几乎所有类目上都跑赢同档竞品;70B 在大多数 benchmark 上显著超过 Llama 2 70B(只有"已饱和"的常识类例外);旗舰 405B 与 GPT-4 等头部模型在多任务上持平,部分接近 SOTA。
Selected benchmarks for Llama 3 405B Instruct vs GPT-4 (0125) / GPT-4o / Claude 3.5 Sonnet: MMLU (5-shot) 87.3 / 85.1 / 89.1 / 89.9; MMLU-Pro (5-shot, CoT) 73.3 / 64.8 / 74.0 / 77.0; IFEval 88.6 / 84.3 / 85.6 / 88.0; HumanEval 89.0 / 86.6 / 90.2 / 92.0; GSM8K 96.8 / 94.2 / 96.1 / 96.4; MATH 73.8 / 64.5 / 76.6 / 71.1; ARC-C 96.9 / 96.4 / 96.7 / 96.7; GPQA 51.1 / 41.4 / 53.6 / 59.4; MGSM 91.6 / 85.9 / 90.5 / 91.6.
For long context: Llama 3 405B reaches 95.2 on ZeroSCROLLS/QuALITY, 83.4 on InfiniteBench/En.MC, and 98.1 on NIH/Multi-needle. We also conduct human evaluations comparing Llama 3 against competing models.
核心 benchmark(405B Instruct vs GPT-4 / GPT-4o / Claude 3.5 Sonnet):MMLU 87.3 / 85.1 / 89.1 / 89.9;MMLU-Pro 73.3 / 64.8 / 74.0 / 77.0;IFEval 88.6 / 84.3 / 85.6 / 88.0;HumanEval 89.0 / 86.6 / 90.2 / 92.0;GSM8K 96.8 / 94.2 / 96.1 / 96.4;MATH 73.8 / 64.5 / 76.6 / 71.1;ARC-C 96.9 / 96.4 / 96.7 / 96.7;GPQA 51.1 / 41.4 / 53.6 / 59.4;MGSM 91.6 / 85.9 / 90.5 / 91.6。
长上下文:Llama 3 405B 在 ZeroSCROLLS / QuALITY 上 95.2、InfiniteBench / En.MC 83.4、NIH multi-needle 98.1。除自动评测外,作者还做了与竞品的人工评测。
Safety. We conducted extensive measurement and mitigation on a wide variety of risks to safe usage of Llama 3. However, no testing can be guaranteed to be exhaustive in identifying every possible risk. Llama 3 may still generate harmful content due to training on various datasets, particularly for languages beyond English and when prompt engineered by skilled adversarial red teamers. We released Llama Guard for input and output safety, and a Prompt Guard classifier for jailbreak / prompt-injection detection (jailbreaks TPR 99.9%, indirect injections TPR 71.4%).
安全。对 Llama 3 做了大量风险测量与缓解,但没有任何测试能穷尽所有风险:模型仍可能产出有害内容,在非英文语言和有经验的红队 prompt 工程下尤甚。Meta 同步开源了 Llama Guard(输入/输出安全分类器)与 Prompt Guard(越狱与 prompt-injection 检测):jailbreak TPR 99.9%、间接注入 TPR 71.4%。
Inference. We investigate two main techniques to make inference with the Llama 3 405B model efficient: pipeline parallelism and FP8 quantization. When using a BF16 number representation for the model parameters, Llama 3 405B does not fit in the GPU memory of a single machine with 8 Nvidia H100 GPUs. To address this issue, we parallelize model inference using BF16 precision across 16 GPUs on two machines. Within each machine, the high NVLink bandwidth enables the use of tensor parallelism. Across nodes, however, connectivity has lower bandwidth and higher latency, so we use pipeline parallelism instead.
For FP8 quantization, we apply FP8 quantization to most matrix multiplications inside the model. In particular, we quantize most parameters and activations in the feedforward network layers in the model, which account for roughly 50% of the inference compute time. We do not quantize parameters in the self-attention layers of the model. We have publicly released our implementation of FP8 quantization.
推理。让 405B 跑起来的两件套:pipeline parallelism + FP8 量化。BF16 下 405B 装不进单机 8×H100,所以跨 2 机 16 GPU——机内靠 NVLink 高带宽走 tensor parallel,机间靠较慢链路走 pipeline parallel。训练时 pipeline 的"气泡"是效率杀手;但推理没有反传,作者引入 micro-batching 把多个微批次塞进 prefill / decode 阶段并发执行,牺牲少量 latency 换更高吞吐。
FP8 量化:把模型中大多数矩阵乘改成 FP8——主要量化 FFN 的参数与激活(约占推理算力 50%);self-attention 层不量化,避免数值不稳。该 FP8 实现已开源。
We perform a series of experiments in which we incorporate visual-recognition capabilities into Llama 3 via a compositional approach that consists of two main stages. First, we compose a pre-trained image encoder and the pre-trained language model by introducing and training a set of cross-attention layers between the two models on a large number of image-text pairs. Second, we introduce temporal aggregator layers and additional video cross-attention layers that operate on a large collection of video-text pairs to learn the model to recognize and process temporal information from videos.
A compositional approach has several advantages: (1) it enables us to parallelize the development of the vision and language modeling capabilities; (2) it circumvents complexities of joint pre-training on visual and language data; (3) it guarantees that model performance on text-only tasks is not affected by the introduction of visual-recognition capabilities; (4) the cross-attention architecture ensures that we do not have to expend compute passing full-resolution images through the increasingly large LLM backbones, making it more efficient during inference.
视觉能力走"组合式(compositional)"两阶段:① 预训练的 image encoder + 预训练的 LM,中间插一组 cross-attention 层,在大量 image–text pair 上训这套 cross-attn(LM 主权重不动);② 再叠 temporal aggregator 与额外的 video cross-attention,在大量 video–text pair 上训,让模型能聚合视频跨帧的时序信息。
组合式 vs 联合预训练的好处:① 视觉与语言可并行研发;② 避开"图文混合预训练"的复杂性(token 化差异、跨模态困惑度冲突);③ 引入视觉不会影响文本任务的表现;④ cross-attention 推理时不必把全分辨率图像送进 LLM 的 FFN,推理更省。
Image Data Pipeline. Our image encoder and adapter are trained on image-text pairs. We construct this dataset via a complex data processing pipeline that consists of four main stages: (1) quality filtering (using CLIP-score based heuristics), (2) perceptual de-duplication (using an internal SSCD copy-detection model), (3) resampling (n-gram based to favor richer descriptions), and (4) optical character recognition. We also apply a series of safety mitigations, including PhotoDNA scanning for CSAM, NSFW filtering, and face blurring.
Annealing data. We create an annealing dataset by resampling the image-caption pairs to ∼350M examples using n-grams, augmented with ∼150M examples from five additional sources: visual grounding (linking noun phrases to bounding boxes / masks), screenshot parsing (HTML rendering ↔ code), question-answer pairs, synthetic captions, and synthetically-generated structured images (charts, tables, math equations).
图像数据管线。图像编码器与 adapter 在 image–text pair 上训。整个管线 4 步:① 质量过滤(用 CLIP 分数等启发式,丢非英文 caption 与低对齐对);② 感知去重(用内部 SSCD copy-detection 模型);③ 重采样(n-gram 选偏好"更丰富描述"的子集);④ OCR。安全侧:用 PhotoDNA 与内部分类器扫 CSAM;NSFW 过滤;对所有训练图片做人脸打码。
退火数据:用 n-gram 重采约 350M image-caption pair,再补 150M 来自 5 类:① visual grounding(把名词短语对应到 bbox/mask,要么用 marks-on-image,要么用文本内的归一化坐标);② screenshot parsing(渲 HTML 截图,让模型预测某元素对应的 HTML);③ QA 对;④ 合成 caption(用早期模型生成,常比原 caption 更全面);⑤ 合成结构化图像(图表/表格/流程图/数学公式/纯文字),并配套 markdown 或 LaTeX 标注。
Speech encoder. Our speech encoder is trained using a self-supervised approach that masks out parts of the speech inputs and tries to reconstruct the masked out parts via a discrete-token representation. As a result, the model learns the structure of speech signals.
Speech adapter. We integrate the speech encoder into the model via an adapter that converts speech encodings into token representations that can be fed directly into the finetuned language model. The parameters of the adapter and encoder are jointly updated in a supervised finetuning stage to enable high-quality speech understanding. We do not change the language model during speech adapter training. We also integrate a text-to-speech system.
语音编码器。用自监督方法训:对部分语音输入做 mask,再用离散 token 表示重建被 mask 的部分——结果是编码器学到"语音信号的结构",而不直接做语音→文本对齐(后者留给 adapter)。
语音适配器。用一个 adapter 把语音编码转成"可直接喂 LM 的 token 表示";encoder 与 adapter 联合微调来获得高质量语音理解,但 LM 主权重不变。系统还集成了 TTS 作为反向(text → speech)出口。
The development of Llama 3 builds on a large body of prior work studying foundation models for language, images, videos, and speech. A comprehensive overview of that work is outside the scope of this paper. Llama 3 inherits ideas from PaLM, Chinchilla scaling laws, the GQA family for efficient inference, RoPE positional embeddings, RLHF / DPO for alignment, Flamingo-style cross-attention for vision-language models, and self-supervised audio representations for speech.
Llama 3 站在大量已有基础模型工作的肩上(语言 / 图像 / 视频 / 语音),全面综述不在论文范围内。它直接继承了若干路线:PaLM 风格 Transformer、Chinchilla scaling laws、GQA(高效推理)、RoPE 位置编码、RLHF / DPO 对齐范式、Flamingo 式 cross-attention 视觉–语言模型,以及自监督音频表征。
In many ways, the development of high-quality foundation models is still in its infancy. Our experience in developing Llama 3 suggests that substantial further improvements of these models are on the horizon. Throughout the development of the Llama 3 model family, we found that a strong focus on high-quality data, scale, and simplicity consistently yielded the best results. The open release of Llama 3 reaffirms the importance of making such models broadly available to the research community to accelerate progress on AI in a responsible way.
从多方面看,高质量基础模型的发展还处在早期。开发 Llama 3 的经验告诉我们:大幅进一步的提升已经在地平线上。整个 Llama 3 家族的研发过程中,我们一直发现——专注于"高质量数据 × 规模 × 简洁性"这三件事,持续地产出最佳结果。Llama 3 的开放发布,再次强调了"把这类模型广泛开放给研究社区"对加速 AI 负责任发展的重要性。
参考文献从略 —— 见原论文 p.75 起,合计 ~30 页、800+ 条引用。