AI Logic

Architectures

Llama 2

Updated:

Architecture of Llama 2. Left: the overall flow (a token sequence of up to 4096 tokens, token embeddings, repeated decoder layers, a final RMSNorm, and next-token prediction), plus a schematic comparing how K and V heads are held in multi-head attention for 7B and 13B versus GQA for 34B and 70B. Right: inside a decoder layer (causal self-attention and a SwiGLU feed-forward, each with RMSNorm on the input side) and the inside of SwiGLU

Background and Overview

Llama 2 is the family of language models with 7 to 70 billion parameters that Meta released in 2023 as the successor to LLaMA, together with Llama 2-Chat, its version tuned for dialogue. Touvron et al. presented it in the paper "Llama 2: Open Foundation and Fine-Tuned Chat Models" and released it for both research and commercial use.

LLaMA showed that a foundation model trained only on public data can compete with large proprietary models. However, "product-ready" chat models such as ChatGPT invest heavy compute and human labor in tuning to human preferences (alignment), and those methods were largely unpublished. A major goal of the Llama 2 paper is to describe this tuning process in detail.

The paper falls into two main parts.

  • The foundation model Llama 2: It keeps almost all of the LLaMA architecture, increases the training data by 40% to 2 trillion tokens, and doubles the context length from 2048 to 4096 tokens. The 34B and 70B models use grouped-query attention (GQA) to speed up generation.
  • The chat model Llama 2-Chat: After supervised fine-tuning (SFT), it repeatedly applies reinforcement learning from human feedback (RLHF) using reward models trained on human preference data.

In human evaluations, Llama 2-Chat far outperformed other open chat models, and the largest, 70B, was rated on par with ChatGPT. The 7B, 13B, and 70B models were released; 34B was not, because its safety testing (red teaming) was not finished in time.

Architecture: Changes from LLaMA

The architecture of Llama 2 is almost the same as LLaMA. In the figure at the top of the article, the left side shows the overall flow and how key and value heads are held, and the right side shows the inside of a single decoder layer.

Inherited from LLaMA (Section 2.2 of the paper)

  • A decoder-only Transformer
  • RMSNorm applied on the input side of each sublayer (the Pre-LN arrangement)
  • SwiGLU as the activation in the feed-forward network
  • RoPE for positional information
  • Tokenizer: SentencePiece BPE. Numbers are split into individual digits, and characters outside the vocabulary are decomposed into bytes. The vocabulary size is 32,000

Changes from LLaMA (Section 2.2 and Appendix A.2.1 of the paper)

  1. Context extended to 4096 tokens: To help with long dialogue histories, summarization, and understanding long documents.
  2. GQA in 34B and 70B: Query heads are split into groups, and each group shares one key head and one value head. When generating text one token at a time, the memory that stores the keys and values of past tokens (the KV cache) becomes smaller, enabling fast generation with large batches.
ModelContext lengthGQATraining tokensPeak learning rate
LLaMA 7B, 13B2048No1.0T3.0Γ—10βˆ’43.0 \times 10^{-4}
LLaMA 33B, 65B2048No1.4T1.5Γ—10βˆ’41.5 \times 10^{-4}
Llama 2 7B, 13B4096No2.0T3.0Γ—10βˆ’43.0 \times 10^{-4}
Llama 2 34B, 70B4096Yes2.0T1.5Γ—10βˆ’41.5 \times 10^{-4}

(Table 1 of the paper. All models are trained with 4 million tokens per step.)

The paper verifies the effect of the two changes in smaller experiments trained on only 150 billion tokens (Appendix A.2.1).

  • Context length: Comparing 2048 and 4096, the 4096 model was far better on long-document tasks (SCROLLS, with an average input length of about 3,500 tokens), while general tasks (HellaSwag, NaturalQuestions, etc.) were nearly unchanged (Tables 16 and 17).
  • Attention variant: On a 30-billion-parameter model, the paper compared standard multi-head attention (MHA), multi-query attention (MQA), and GQA with 8 key-value heads. To match parameter counts, MQA and GQA widen the feed-forward network (by 1.33Γ— and 1.3Γ—). GQA was on par with MHA on most tasks and better than MQA on average (Table 18).

A large model such as 70B is run by splitting its heads across 8 GPUs. MQA has only one key-value head, fewer than the number of GPUs, so it cannot be split by head. The same keys and values end up duplicated on every GPU, and the KV cache becomes no smaller than with GQA. Based on this point and the performance results, the paper chose GQA over MQA.

The training settings are almost the same as LLaMA: AdamW (Ξ²1=0.9\beta_1 = 0.9, Ξ²2=0.95\beta_2 = 0.95, Ο΅=10βˆ’5\epsilon = 10^{-5}), a learning rate with 2,000 steps of warmup followed by cosine decay down to 10% of the peak, weight decay of 0.1, and gradient clipping at 1.0. Even after 2 trillion tokens, the training loss was still decreasing (Figure 5).

Training Llama 2-Chat: SFT and RLHF

Llama 2-Chat is built from the foundation model Llama 2 through the following steps (Figure 4 and Section 3 of the paper).

  1. Supervised fine-tuning (SFT): Train on high-quality prompts and responses written by people.
  2. Collect human comparison data: People write prompts and choose the better of two responses produced by the model.
  3. Train reward models: Train models that return a numerical score for response quality, separately for helpfulness and safety.
  4. Train with rejection sampling: Generate KK responses for each prompt and train on the one with the highest reward as the target.
  5. Train with PPO: Update the model with the reinforcement learning method PPO to maximize the reward.
  6. Iterate: Collect new comparison data from the new model's responses, update the reward models, and repeat steps 2–5 (RLHF-V1 through V5).

The figure below shows this flow. The left side is training the chat model; the right side is training the reward models.

Training flow of Llama 2-Chat. Left: pretraining on public data, SFT, and RLHF with rejection sampling and PPO, resulting in Llama 2-Chat. Right: training two reward models, for helpfulness and safety, from human comparison data and feeding rewards to RLHF, plus the loop of collecting new data from the new model's responses

1. SFT (Section 3.1): The team initially started from public instruction data, but found that quality mattered more than quantity, so instead of millions of third-party examples they used high-quality data they collected themselves. They collected 27,540 examples, and tens of thousands were enough to reach high-quality results. During training, each prompt and response are concatenated into a sequence of 4096 tokens, and the loss on the prompt tokens is set to zero so that only the response tokens are learned. The learning rate is 2Γ—10βˆ’52 \times 10^{-5}, for 2 epochs.

2–3. Reward models (Sections 3.2.1 and 3.2.2): Besides choosing the better of two responses, annotators also select how much better it is (significantly better, better, slightly better, or negligibly better). Meta collected 1,418,091 comparisons. The reward model has the same architecture as Llama 2-Chat, with the next-token prediction head replaced by a head that outputs a single number (the reward). With rΞΈ(x,y)r_\theta(x, y) as the reward for prompt xx and response yy, ycy_c as the chosen response, and yry_r as the rejected response, it is trained with the following loss (Eq. (2) of the paper).

Lranking=βˆ’log⁑(Οƒ(rΞΈ(x,yc)βˆ’rΞΈ(x,yr)βˆ’m(r)))\mathcal{L}_{\text{ranking}} = -\log\Bigl(\sigma\bigl(r_\theta(x, y_c) - r_\theta(x, y_r) - m(r)\bigr)\Bigr)

Οƒ\sigma is the sigmoid function. The larger the chosen response's reward is relative to the rejected response's, the smaller the loss. m(r)m(r) is a margin that depends on the size of the preference gap, so pairs rated "significantly better" are pushed to have a larger reward difference.

4. Rejection sampling (Section 3.2.3): The largest 70B model generates KK responses per prompt, the response with the highest reward-model score is selected, and the model is trained on it in the same way as SFT. Smaller models (7B, 13B, etc.) are trained on responses selected by 70B, effectively a form of knowledge distillation that transfers the larger model's capabilities to the smaller ones.

5. PPO (Section 3.2.3): It maximizes the reward of the generation gg produced by the model Ο€\pi for prompt pp. The reward includes a penalty (KL divergence) that keeps the model from drifting too far from the original model Ο€0\pi_0 (Eqs. (3)(4)).

arg⁑max⁑π Ep∼D, gβˆΌΟ€[R(g∣p)],R(g∣p)=R~c(g∣p)βˆ’Ξ²β€‰DKL(πθ(g∣p) βˆ₯ π0(g∣p))\arg\max_{\pi}\ \mathbb{E}_{p \sim \mathcal{D},\, g \sim \pi}\bigl[R(g \mid p)\bigr], \qquad R(g \mid p) = \tilde{R}_c(g \mid p) - \beta\, D_{\mathrm{KL}}\bigl(\pi_\theta(g \mid p) \,\|\, \pi_0(g \mid p)\bigr)

R~c\tilde{R}_c combines the two reward models. If the prompt is likely to elicit an unsafe response, or the safety reward RsR_s is below 0.15, the safety reward is used; otherwise the helpfulness reward RhR_h is used. Ξ²\beta is 0.01 for 7B and 13B and 0.005 for 34B and 70B. Up to RLHF-V4, only rejection sampling was used; after that, PPO was applied on top of rejection sampling.

Ghost Attention (GAtt) (Section 3.3): The first RLHF models forgot an initial instruction such as "act as ..." after a few turns. With GAtt, the instruction is attached to every user message in a training dialogue when generating responses; during training, the instruction is kept only in the first message and the loss on earlier turns is set to zero. This let the model follow the instruction for more than 20 turns.

Why Use Two Reward Models

The core of Llama 2-Chat training is teaching human preferences to reward models and then using those reward models to evaluate and improve the model at scale. People cannot score every response, but comparing two responses is easy for them and their judgments are more consistent.

The reward model is split into helpfulness and safety because the two objectives can conflict. A response that "explains in detail how to build a bomb" is helpful in the sense that it answers the question, but it is not safe. If one reward model learns both, it is torn between being as helpful as possible and refusing dangerous requests, and it becomes hard to improve accuracy on either. In the paper's results, each reward model was the most accurate on the evaluation data for its own domain (Table 7).

The reward models are also initialized from the pretrained weights of the chat model. Because both models share the same knowledge, this prevents mismatches in which the reward model rates highly "things the chat model does not know", which could encourage hallucination.

Aiming only to raise the reward model's score can lead the model to learn responses that get high rewards but are not good in human judgment (reward hacking). Llama 2 counters this by including a penalty in the PPO reward that keeps the model close to the original, and by continually updating the data and reward models with the new model's responses. The paper mentions Goodhart's lawβ€”"when a measure becomes a target, it ceases to be a good measure"β€”and also checks results with a reward model trained on different data.

Experimental Results

Foundation models (Table 3 of the paper; average over the benchmarks in each category, %)

ModelCodeCommonsense reasoningWorld knowledgeReading comprehensionMathMMLUBBH
LLaMA 7B14.160.846.258.56.9535.130.3
Llama 2 7B16.863.948.961.314.645.332.6
LLaMA 13B18.966.152.662.310.946.937.0
Llama 2 13B24.566.955.465.828.754.839.4
LLaMA 65B30.770.760.568.630.863.443.5
Llama 2 70B37.571.963.669.435.268.951.2

At the same size, Llama 2 outperformed LLaMA in every category. The 70B model scores about 5 points higher than 65B on MMLU and about 8 points higher on BBH.

Comparison with proprietary models (Table 4 of the paper)

BenchmarkGPT-3.5GPT-4PaLM 540BPaLM-2-LLlama 2 70B
MMLU (5-shot)70.086.469.378.368.9
GSM8K (8-shot)57.192.056.580.756.8
HumanEval (zero-shot)48.167.026.2-29.9

Llama 2 70B comes close to GPT-3.5 on MMLU and GSM8K, and matches or exceeds PaLM 540B. On code, however, the gap with GPT-3.5 is large, and it remains far behind GPT-4 and PaLM-2-L.

Chat models

  • Human evaluation (about 4,000 prompts, Section 3.4.2): Against ChatGPT, Llama 2-Chat 70B had a 36% win rate and a 31.5% tie rate. Llama 2-Chat 34B had a win rate above 75% against similarly sized Vicuna-33B and Falcon 40B.
  • Truthfulness and toxicity (Tables 11 and 14; TruthfulQA is the percentage of answers that are both truthful and informative, higher is better; ToxiGen is the percentage of toxic generations, lower is better):
ModelTruthfulQAToxiGen
Llama 2 70B (foundation model)50.1824.60
Llama 2-Chat 70B64.140.01
ChatGPT78.460.20

Chat tuning brought the toxic-generation rate of the 70B model to effectively 0% and substantially improved truthfulness.

Practical Considerations

Keep the following points in mind when using Llama 2.

  • Trained mostly on English: 89.70% of the pretraining data is English, and Japanese is 0.10% (Table 10 of the paper). The paper itself warns that performance in other languages is unreliable and should be used with care. For Japanese, consider a model that has been further trained on Japanese data.
  • It can refuse too often: Because the tuning prioritizes safety, it may refuse harmless requests or add lengthy safety caveats (Section 5.2). For example, the 13B chat model with Llama 2's recommended system prompt was reported to refuse "how to kill a Linux process" (Table 5 of the Mistral 7B paper).
  • Do not deploy the foundation model as-is in a public service: The foundation model's training data was not aggressively filtered for harmful text (Section 4.1). The paper asks users of the foundation model to apply additional tuning and safety measures before deployment.
  • Context is limited to 4096 tokens: For longer documents, use context-extension methods such as position interpolation or YaRN.
  • Knowledge stops at the time of pretraining: It can give factually incorrect answers (hallucinations) or unqualified professional advice.

Llama 2 is released for both research and commercial use, but you must follow the distributor's license and Acceptable Use Policy. The paper also asks developers to perform safety testing and tuning tailored to their use case before deploying applications built on Llama 2-Chat.

Comparison with Other Models

The LLaMA lineage and a model influenced by it compare as follows.

ModelSizeTraining tokensContext lengthAttentionChat modelLicense
LLaMA7B–65B1.0–1.4T2048Multi-headNone (the paper experiments with instruction-tuned LLaMA-I)For researchers
Llama 27B–70B2T4096GQA for 34B and 70BLlama 2-Chat (SFT + RLHF)Research and commercial (custom license)
Mistral 7B7BNot stated in the paper8192GQA + sliding windowMistral 7B Instruct (SFT on public instruction data)Apache 2.0

The Mistral 7B paper reports that Mistral 7B outperformed Llama 2 13B on every benchmark (Table 2 of the Mistral 7B paper). However, each paper uses its own evaluation procedure, so compare numbers only within the same table.

Rough guidelines for choosing:

  • If you want a chat model whose safety tuning is documented in detail: The SFT and RLHF procedures and safety evaluations of Llama 2-Chat are described thoroughly in the paper, so you can use it with an understanding of its behavior.
  • If you want the highest performance for the same compute: Among small models, Mistral 7B is reported to outperform Llama 2 13B.
  • If you want the performance of a larger model with less compute: A mixture-of-experts model such as Mixtral is also an option.
  • If you want to learn the architectural basics: Start with LLaMA to understand RMSNorm, SwiGLU, and RoPE, then view Llama 2 as the differences from it (context length and GQA).

PyTorch example

Show code
python
import torch
import torch.nn.functional as F

"""
A small example of the two equations used in training Llama 2-Chat, written as in the paper
1. Reward model loss (Eq. (2)): -log Οƒ(r(x, y_c) - r(x, y_r) - m(r))
2. Reward maximized by PPO (Eq. (4)): R = R~c - Ξ²Β·KL(Ο€_ΞΈ || Ο€_0)
Finally, an example of using a pretrained Llama 2-Chat with Hugging Face transformers
"""

# --- 1. Reward model loss (ranking loss with a margin) ---
def ranking_loss(r_chosen, r_rejected, margin):
  # r_chosen, r_rejected: [batch]. Rewards of the chosen and rejected responses
  # margin: [batch]. Larger for pairs rated "significantly better" (a discrete value set by the size of the gap)
  return -F.logsigmoid(r_chosen - r_rejected - margin).mean()

r_c = torch.tensor([1.2, 0.3, 0.8])
r_r = torch.tensor([0.1, 0.4, 0.7])
m = torch.tensor([1.0, 0.0, 0.33])
print(f"ranking loss: {ranking_loss(r_c, r_r, m).item():.3f}")


# --- 2. PPO reward: combine safety and helpfulness rewards + KL penalty ---
def combined_reward(r_safety, r_help, is_safety_prompt, threshold=0.15):
  # Use the safety reward if the prompt may elicit an unsafe response or the safety reward is below 0.15
  use_safety = is_safety_prompt | (r_safety < threshold)
  r = torch.where(use_safety, r_safety, r_help)
  # The paper inverts the sigmoid (logit) and then whitens (mean 0, variance 1)
  z = torch.logit(r.clamp(1e-6, 1 - 1e-6))
  return (z - z.mean()) / (z.std() + 1e-6)

def ppo_reward(r_tilde, logp_policy, logp_ref, beta=0.01):
  # logp_*: [batch, generation length]. Log probabilities of the generated tokens under the current and original (SFT) models
  kl = (logp_policy - logp_ref).sum(-1)      # KL estimate over the generated sequence
  return r_tilde - beta * kl                  # Ξ² is 0.01 for 7B/13B and 0.005 for 34B/70B

r_s = torch.tensor([0.9, 0.1, 0.6])
r_h = torch.tensor([0.7, 0.8, 0.5])
flag = torch.tensor([False, False, True])
print(ppo_reward(combined_reward(r_s, r_h, flag), torch.randn(3, 5), torch.randn(3, 5)))


# --- 3. Generate a response with a pretrained Llama 2-Chat ---
# Using the weights requires accepting the license from the distributor
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.float16, device_map="auto")
model.eval()

messages = [
  {"role": "system", "content": "You are a helpful assistant."},   # instruction placed at the start of the dialogue (system message)
  {"role": "user", "content": "Explain grouped-query attention in two sentences."},
]
# Arrange in the same format as during training (leave the format to the tokenizer's template)
ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
with torch.no_grad():
  out = model.generate(ids, max_new_tokens=128, do_sample=True, top_p=0.9, temperature=0.6)
print(tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True))   # context up to 4096 tokens

FAQ

Q. What is the difference between Llama 2 and Llama 2-Chat?
A.

Llama 2 is a foundation model trained only on next-token prediction, and Llama 2-Chat is that model tuned for dialogue. Llama 2-Chat is tuned with supervised fine-tuning (SFT) on human-written prompts and responses and with reinforcement learning (RLHF) using reward models that learned human preferences. Use Llama 2-Chat for dialogue out of the box, and start from Llama 2 if you plan to train further on your own data.

Q. What is the benefit of GQA?
A.

During text generation, the memory that stores the keys and values of past tokens (the KV cache) becomes smaller. For example, with 8 key-value heads, the cache is only 8/h8/h of what it would be with all hh heads. This allows larger batches and faster generation. In the paper's experiments, performance was nearly the same as standard multi-head attention. See grouped-query attention for details.

Q. Why include a KL penalty in the PPO reward?
A.

A reward model is only an approximation of human preferences, so maximizing reward alone leads the model to learn unnatural responses that exploit the reward model's weaknesses (reward hacking). Subtracting the KL divergence from the original model as a penalty keeps improvements within a range close to the original model and also stabilizes training.

References

  1. Touvron, H., Martin, L., Stone, K., et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv:2307.09288.
  2. Touvron, H., Lavril, T., Izacard, G., et al. (2023). LLaMA: Open and Efficient Foundation Language Models. arXiv:2302.13971.
  3. Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., LebrΓ³n, F., & Sanghai, S. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP 2023.
  4. Ouyang, L., Wu, J., Jiang, X., et al. (2022). Training language models to follow instructions with human feedback. NeurIPS 2022.
  5. Schulman, J., Wolski, F., Dhariwal, P., Radford, A., & Klimov, O. (2017). Proximal Policy Optimization Algorithms. arXiv:1707.06347.
  6. Jiang, A. Q., Sablayrolles, A., Mensch, A., et al. (2023). Mistral 7B. arXiv:2310.06825.