Search

Search papers and lessons

The Llama 3 Herd of Models

Aaron Grattafiori, Abhimanyu Dubey, Abhinav Jauhri et al. · 2024

Llama 3 is a family of dense Transformer language models with 8B, 70B and 405B parameters, where the 405B flagship saw about 15.6T tokens and is aligned mainly with supervised finetuning and DPO.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Reinforcement learning
  • Sign in to see your progress

TL;DR

Llama 3 is a family of three language models, with 8B, 70B and 405B parameters. All three are dense Transformers trained to predict the next token. The flagship 405B model was pre-trained on 15.6T text tokens, first with an 8K context window and then extended to 128K. Post-training used several rounds of supervised finetuning, rejection sampling and direct preference optimization (DPO), not a reinforcement learning loop.

Where you'll see it: as the reference recipe for training and post-training a 405B-parameter open-weight language model, and as the source of the 128K-context and FP8 inference details.

The problem

Llama 2 was the previous generation, with a 70B largest model. The authors ask how to build a much larger model, using almost 50 times the training compute of the largest Llama 2, without the project breaking down. They name three levers: data, scale, and managing complexity. The paper is an account of how each lever was pulled, and of the choices made to keep the process stable.

The hard parts are not only the model. Training at this scale runs on up to 16K GPUs, so communication, hardware failures and parallelism layout become design problems. Post-training also has to stay stable across several alignment rounds.

Key idea

The model is deliberately ordinary. The authors say the architecture "does not deviate significantly" from Llama 2, and that the gains come "primarily" from better data and from more training scale. Where they did choose differently, the choice was for stability: a dense Transformer rather than a mixture-of-experts model, and DPO rather than a more complex reinforcement learning algorithm.

flowchart LR
  A[Web and other sources, up to end of 2023] --> B[Filter and deduplicate]
  B --> C[Pre-train 8K context, 15.6T tokens]
  C --> D[Extend to 128K context, about 800B tokens]
  D --> E[Anneal on high quality data]
  E --> F[Reward model and rejection sampling]
  F --> G[SFT then DPO, six rounds]
  G --> H[Llama 3 chat model]

The method

Architecture

Llama 3 is a standard decoder-only Transformer. The paper lists four changes from Llama 2:

  • Grouped-query attention with 8 key-value heads in every model size. This shrinks the key-value cache during decoding. See Grouped-Query Attention and KV Cache.
  • An attention mask that stops tokens from attending across document boundaries inside one packed sequence. The authors say this matters little in standard pre-training but matters in continued pre-training on very long sequences.
  • A 128K-token vocabulary, made of 100K tokens from the tiktoken tokenizer and 28K extra tokens for non-English text. On English data this raised compression from 3.17 to 3.94 characters per token, so the model reads more text for the same compute. See Subword Tokenization.
  • A RoPE base frequency of 500,000, which the authors chose to support longer contexts.

The paper's Table 3 gives the sizes. The 405B model has 126 layers, a model dimension of 16,384, a feedforward dimension of 53,248, 128 attention heads, and 8 key-value heads. The feedforward layers use SwiGLU. The peak learning rates are 3×10−43\times 10^{-4} for 8B, 1.5×10−41.5\times 10^{-4} for 70B and 8×10−58\times 10^{-5} for 405B.

Scaling laws

The team fitted scaling laws in two steps. First, they trained compute-optimal models with budgets from 6×10186\times 10^{18} to 102210^{22} FLOPs and sizes from 40M to 16B parameters. For each budget they fitted a parabola to validation loss against model size and took its minimum as the compute-optimal size. Then they fitted a power law for the optimal number of training tokens, N⋆(C)=ACαN^{\star}(C)=AC^{\alpha}, and reported (α,A)=(0.53,0.29)(\alpha, A)=(0.53, 0.29). The paper says this extrapolates to a 402B-parameter model trained on 16.55T tokens at 3.8×10253.8\times 10^{25} FLOPs. The flagship was then built at 405B because the IsoFLOPs curves are flatter near the minimum as compute grows, so small changes in the size-to-tokens tradeoff matter little.

The second step predicts benchmark accuracy. The authors fit a linear relation between normalized negative log-likelihood on a benchmark and log compute, and a sigmoidal relation between that log-likelihood and accuracy, using the small models and the Llama 2 family. On ARC Challenge this extrapolated over four orders of magnitude and only slightly underestimated the final flagship score.

Infrastructure

The 405B model was trained on up to 16K H100 GPUs in Meta's production clusters. Each server has eight GPUs connected by NVLink. Storage is a 240 PB distributed file system. Model parallelism combines four kinds of parallelism: tensor, pipeline, context and data parallelism, with fully sharded data parallelism for the optimizer state and gradients. This is 4D parallelism. The model FLOPs utilization is 38 to 43 percent in the configurations the paper reports. The utilization is 41 percent on 16K GPUs and 43 percent on 8K GPUs, and the authors attribute the small drop to a smaller batch per data-parallel group.

Training recipe

Initial pre-training used AdamW with a peak learning rate of 8×10−58\times 10^{-5}, a linear warmup over 8,000 steps, and a cosine decay to 8×10−78\times 10^{-7} over 1,200,000 steps. The batch started at 4M tokens with sequences of 4,096 tokens, doubled to 8M tokens with sequences of 8,192 after 252M tokens, and doubled again to 16M tokens after 2.87T tokens. The authors report few loss spikes and no interventions needed for divergence.

Long-context pre-training extended the window in six stages, from 8K to 128K, using about 800B tokens. The authors do not train on long sequences from the start because attention compute grows quadratically with sequence length. A stage ends when short-context scores recover and the model solves needle-in-a-haystack tasks at that length.

The last 40M tokens anneal the learning rate linearly to zero at 128K context, with a higher-quality data mix. The final model is an average of checkpoints taken during annealing.

Post-training

Each round has three steps. A reward model is trained on human preference rankings. Its scores are used for rejection sampling of prompts, and the resulting data is combined with other data for supervised finetuning. Then the checkpoint is trained with DPO on recent preference data from the previous round's model.

The reward model follows the Llama 2 objective, with the margin term removed because the authors saw diminishing returns after data scaling. Annotators sometimes write a third, edited response, so a ranking can be edited over chosen over rejected.

Supervised finetuning uses cross-entropy loss on the target tokens, with the prompt tokens masked. The largest models use a learning rate of 10−510^{-5} for 8.5K to 9K steps.

For DPO the standard loss, from the DPO paper, is

LDPO=−E[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))]\mathcal{L}_{\text{DPO}} = -\mathbb{E}\left[\log \sigma\left(\beta \log \frac{\pi_\theta(y_w \mid x)}{\pi_{\text{ref}}(y_w \mid x)} - \beta \log \frac{\pi_\theta(y_l \mid x)}{\pi_{\text{ref}}(y_l \mid x)}\right)\right]

where ywy_w is the chosen response, yly_l the rejected one, and πref\pi_{\text{ref}} the reference model. Llama 3 uses β=0.1\beta = 0.1 and a learning rate of 10−510^{-5}, with two changes. First, the special header and termination tokens are masked out of the loss on both responses, because the authors saw tail repetition and abrupt early stopping when they contributed. Second, a negative log-likelihood term on the chosen response is added with coefficient 0.2, to keep the chosen formatting and stop its probability from falling. The paper also says it tried PPO, an on-policy method, and found DPO needed less compute at this scale and did better on IFEval.

The paper calls the whole procedure six rounds, and averages models from different data and hyperparameter runs at each stage.

Capabilities

The chat format uses several header and termination tokens so one dialog turn can contain several messages sent to different destinations, such as the user or an interpreter. The authors put extra effort into code, multilinguality, math and reasoning, long context, tool use, factuality and steerability. Their human evaluation prompt set is described under Results.

Inference

The 405B model does not fit in BF16 on one server of eight 80 GB GPUs. It is split across two machines with 16 GPUs: tensor parallelism inside each machine over NVLink, and pipeline parallelism across machines. Micro-batching improves throughput because inference has no backward pass that needs a flush.

For FP8 the authors quantize most feedforward matrix multiplications, which take about half of inference time. Attention parameters are not quantized, and neither are the first and last layers. They use dynamic row-wise scaling factors and cap them at 1200, because high-perplexity tokens such as dates can produce large activations that cause underflow. Benchmarks alone did not reveal the damage, so they compared reward-model score distributions over 100,000 responses in FP8 and BF16. The paper reports up to 50 percent higher prefill throughput with FP8.

Results

The paper reports results for the post-trained models. The table below uses the scores from the paper's Table 2 for a subset of benchmarks. The paper's table also carries footnote markers for some scores (5-shot without chain-of-thought, zero-shot), which are omitted here, so use the paper for the exact settings.

BenchmarkLlama 3 8BLlama 3 70BLlama 3 405BGPT-4oClaude 3.5 Sonnet
MMLU (5-shot)69.483.687.389.189.9
MATH (0-shot, CoT)51.968.073.876.671.1
GSM8K (8-shot, CoT)84.595.196.896.196.4
HumanEval (0-shot)72.680.589.090.292.0
IFEval80.487.588.685.688.0
GPQA (0-shot, CoT)32.846.751.153.659.4
NIH multi-needle98.897.598.1100.090.8

The paper's own summary is that the flagship "performs on par with leading language models such as GPT-4" and is "close to matching the state-of-the-art". The table supports this for some rows and not others. On MMLU, HumanEval and GPQA the 405B model trails both GPT-4o and Claude 3.5 Sonnet. On MATH it trails GPT-4o but is ahead of Claude 3.5 Sonnet, and on GSM8K and IFEval it is ahead of both.

The paper also runs human evaluations on about 7,000 prompts spanning six single-turn capabilities (English, reasoning, coding, Hindi, Spanish, Portuguese) and three multi-turn ones, with roughly 10 percent easy, 30 percent medium and 60 percent hard prompts. In a separate tool-use study the 405B model is compared with GPT-4o: it outperforms GPT-4o on code execution without plotting or file uploads and on plot generation, but lags on file upload use. The paper does not give one headline win rate, so none is quoted here.

Why it mattered

The paper reports the release itself: the 8B, 70B and 405B models, pre-trained and post-trained, under an updated community license, together with a new Llama Guard model for input and output safety. The authors hope the open flagship "will spur a wave of innovation" and push toward responsible AGI. Multimodal extensions for image, video and speech are described but, at the time of the paper, not released.

The paper does not describe what followed from the release, so this lesson does not claim any downstream effect.

Reading guide

Read the paper in this order, using these prerequisite lessons:

  1. Section 1, Introduction. Needs Language Model, Autoregressive Model and the idea of Neural Scaling Laws. The paper builds on the post-training approach of Llama 2: Open Foundation and Fine-Tuned Chat Models and uses Direct Preference Optimization as its main alignment step, so skim RLHF first.
  2. Section 2, General Overview. Needs Transformer for the architecture in Figure 1 and Instruction Tuning for the post-training stage.
  3. Section 3.1 and 3.2, Data and Architecture. Needs Subword Tokenization, Multi-Head Attention, Grouped-Query Attention, KV Cache and Rotary Position Embedding. The tokenizer and RoPE sections are the most important for the numbers in Table 3.
  4. Section 3.2.1, Scaling Laws. Needs Neural Scaling Laws and Compute-Optimal Training. Read the IsoFLOPs argument slowly, because it justifies the choice of 405B.
  5. Section 3.3, Infrastructure. Needs GPU Memory Hierarchy for why the parallelism and memory layout matter. The main ideas are the 4D parallelism split and MFU.
  6. Section 3.4, Training Recipe. Needs Stochastic Gradient Descent, Adam Optimizer and Attention Mechanism for the context extension, which the paper motivates by quadratic cost.
  7. Section 4.1.2 to 4.1.4, Reward Model, SFT and DPO. Needs Reward Model, Cross-Entropy Loss, Rejection Sampling and Direct Preference Optimization. Read the DPO modifications in 4.1.4 after the standard DPO lesson.
  8. Section 4.3, Capabilities. Needs Chain-of-Thought Prompting for the CoT evaluations and In-Context Learning for the few-shot settings.
  9. Section 5, Results. Needs In-Context Learning for the shot counts and Chain-of-Thought Prompting for CoT. Results are reported as averages and one-number scores, so read the table footnotes.
  10. Section 6, Inference. Needs KV Cache for decoding and Mixture of Experts only for the design choice the authors rejected in Section 2.

Check yourself

QuestionThe paper names three levers for building a foundation model. What are they?Show answer
Data, scale, and managing complexity. The authors improved data quality and quantity, trained at about 50 times the compute of the largest Llama 2, and chose simpler, more stable designs such as a dense Transformer and DPO.
QuestionThe flagship has 405B parameters and was trained on 15.6T tokens. Using the rule of thumb C approximately equal to 6ND, which is outside this paper, what is the training compute? Does it match the paper's figure?Show answer
C = 6 times 405 times 10^9 times 15.6 times 10^12, which is about 3.79 times 10^25 FLOPs. This matches the 3.8 times 10^25 that the paper reports, so the rule of thumb is consistent with the paper's accounting.
QuestionWhy does the paper extend the context window from 8K to 128K in stages instead of training on long sequences from the start?Show answer
Self-attention compute grows quadratically with sequence length, so long sequences are expensive. The authors increase the window in six stages, and at each stage they check that short-context scores have recovered and that the model solves needle-in-a-haystack tasks at that length, before moving on.
QuestionThe 405B model has 405 billion parameters stored in BF16. Why does inference need 16 GPUs across two machines rather than one server of eight 80 GB GPUs?Show answer
Each parameter takes 2 bytes in BF16, so the weights alone are about 810 GB. An 8-GPU server with 80 GB per GPU has 640 GB, before the key-value cache and activations. The paper therefore splits the model over two machines, with tensor parallelism inside each machine and pipeline parallelism between them.

Sources

Read the full paper

Aaron Grattafiori, Abhimanyu Dubey, Abhinav Jauhri et al., 2024. arXiv:2407.21783