Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~9 min readMeta · 2023

Llama 2,
explained.

The best language models of 2023 were locked behind APIs — you could rent them, but never open the hood. Then Meta did something the frontier labs wouldn't: it trained a family of strong models and gave away the weights, chat alignment included. Overnight, anyone could run a capable LLM on their own hardware, fine-tune it, and build on it. Llama 2 is the paper that made open the default.

The delta

What changes here: the weights and the recipe are both published

Rung 1, so the comparison is against the frontier practice of the time, which was to release a capable model as an API and a capability report. This rung publishes the weights, in three sizes, with a licence permitting commercial use, together with an unusually detailed account of how the chat version was aligned. The predecessor family had shipped only to approved researchers under a research-only licence, then leaked widely; the change here is that building on it was permitted.

The architecture is worth reading as a summary of what had settled by then, because every choice is a rung from another ladder: RMSNorm in place of LayerNorm, a gated feed-forward activation, rotary positions, and — in the 34B and 70B models — grouped-query attention, which lets several query heads share one set of keys and values and so shrinks the cache that dominates serving memory. Pretraining runs to 2 trillion tokens, which is the number the next rung multiplies.

The post-training contribution is the part that is genuinely new here, and it is a design response to a problem rung 1 of the post-training ladder left. A single reward model has to score helpfulness and harmlessness together, which forces it to encode a trade-off at every point. This release trains two separate reward models and combines them, so the tension lives somewhere explicit and adjustable instead of being baked into one learned function.

01

The closed-model wall

By mid-2023, the most capable models — GPT-4, Claude, PaLM — were all accessed the same way: through a paid API, weights hidden. That's fine for using a model, but it walls off almost everything else. You can't inspect what it learned, run it offline or on private data, fine-tune it deeply, or study its failure modes. Researchers and builders were renting intelligence they could never own.

The first Llama had cracked the door — its weights leaked and the community erupted with fine-tunes — but it was research-only. Llama 2's move was deliberate: release a strong, chat-aligned family with a license that permits commercial use. Not a leak, a policy. The bet was that an open foundation would unleash more innovation than any single lab could produce alone.

02

What Llama 2 actually is

Llama 2 is a family, not a single model. It ships in three sizes — 7B, 13B, and 70B parameters — each in two flavors: a raw pretrained base (a next-word predictor, like GPT-3) and a chat version (Llama 2-Chat) aligned to hold a conversation and follow instructions.

The sizes matter. A 7B model runs on a single consumer GPU; the 70B rivals much larger closed models on many tasks. That range is what made Llama 2 a platform: hobbyists ran the 7B on laptops, startups fine-tuned the 13B, and serious deployments reached for the 70B — all from the same released weights.

03

Pretraining: 2 trillion tokens

The base models are trained on roughly 2 trillion tokens of publicly available text — 40% more data than the first Llama — with a longer 4,096-token context window. The objective is the same humble one every GPT-style model uses: predict the next token. No magic, just a lot of high-quality data and compute, with deliberate up-weighting of the most factual sources.

This is the expensive, once-per-model stage that produces raw capability. Everything downstream — the chat tuning, the community's thousands of fine-tunes — starts from these pretrained weights. Meta's contribution here is less a new idea than a well-executed, openly-shared one: a clean, strong base others could build on.

04

The architecture, and one efficiency trick

Llama 2 is a standard Transformer decoder with three now-common refinements: RMSNorm for cheaper, stabler normalization, SwiGLU activations in the feed-forward layers, and RoPE (rotary positional embeddings) that encode position by rotating query/key vectors. None are new to Llama 2, but together they define the modern open-model recipe.

The larger models — the released 70B and the held-back 34B; the 7B and 13B keep full multi-head attention — add a genuinely important inference trick: grouped-query attention (GQA). Normally each attention head keeps its own keys and values, and during generation those pile up in a memory-hungry KV cache. GQA lets several query heads share one key/value head — shrinking the cache and the memory bandwidth per token, so the big model generates faster with almost no quality cost.

Why GQA matters

At inference, LLM speed is often bottlenecked by memory bandwidth moving the KV cache, not by raw compute. GQA is a middle ground between full multi-head attention (best quality, biggest cache) and multi-query attention (smallest cache, some quality loss) — most of the savings, little of the pain.

05

Llama 2-Chat: helpful and harmless

A pretrained base only predicts text; making it a good chat assistant takes alignment. Llama 2-Chat follows the RLHF playbook InstructGPT established, with a distinctive twist: it trains two separate reward models — one scoring helpfulness, one scoring safety — so the two goals can be balanced explicitly rather than blurred into a single score.

Llama 2-Chat alignment — iterated over several rounds
1
SFT. Fine-tune the base on high-quality human dialogue demonstrations.
2
Two reward models. Train separate helpfulness and safety reward models from human preference rankings.
3
Rejection sampling + PPO. Sample many answers, keep the best-scored, and reinforce — iterating over multiple rounds.

Why two models rather than one blended score? Because a single reward is a soft tradeoff — a big helpfulness gain can outweigh a safety loss, and an unsafe-but-impressive answer wins. Two models let safety be a hard floor instead of a bargaining chip:

Gate on safety first, then maximize helpfulness among what's left — so the unsafe answer never wins no matter how helpful it looks. The runnable version below shows the two picks diverge.

It also introduced Ghost Attention (GAtt), a training trick that helps the model keep obeying a system instruction ("always answer in French") across many turns instead of forgetting it after a couple of messages. Small, but it's the kind of multi-turn control real assistants need.

07

The limits and the fine print

Llama 2 is not GPT-4. It hallucinates, its knowledge is frozen at training time, the 4K context is short by today's standards, and it is heavily English-centric — weaker in other languages. As a chat model it can be overcautious, refusing benign requests because the safety training erred toward caution.

And "open" deserves an asterisk. The license is permissive but not true open source: companies with over 700 million monthly active users need a special license, and you may not use Llama 2 to train competing models. It's best called open weights — you get the model, under terms — rather than open source in the strict sense.

08

Why it still matters

Llama 2 lit the fuse on the open-model ecosystem. Because the weights were free and commercially usable, a Cambrian explosion followed: quantized versions that run on laptops, thousands of domain fine-tunes, tooling like llama.cpp and Ollama, and a research community that could finally poke at a real, strong model. Much of today's local and open-source AI traces directly to this release.

It also normalized the pattern of shipping a model family with a proper technical report — architecture, data, and a candid safety section — rather than a closed black box. Later open models (Mistral, Llama 3, and beyond) build on the template Llama 2 set: strong pretraining, RLHF alignment, and open weights as a strategy, not an accident.

Worth knowing

When you run a model locally with Ollama or fine-tune an open LLM for your own data, you're standing on Llama 2's shoulders — it's the release that made "just download the weights" a normal thing to say.

How it works

How Meta built Llama 2 and aligned Llama 2-Chat

Llama 2 comes from Hugo Touvron, Louis Martin, Kevin Stone and a large team at Meta, released in July 2023. The report covers pretraining briefly and alignment at length, and most of what is new is in how Llama 2-Chat was trained.

Weekly human preference batches two reward models Helpfulness RM Safety RM SFT 27.5k V1 RS V2 RS V3 RS V4 RS V5 RS, then PPO GAtt added after V3 Rejection sampling: best of K samples, drawn from the 70B model PPO: use the safety reward if the prompt is risky or safety is below 0.15
Llama 2-Chat was aligned in five rounds. Rejection sampling alone carried V1 to V4; PPO arrived only in V5, on top of a rejection-sampling checkpoint, with both reward models retrained along the way.

Pretraining

Three released sizes, 7B, 13B and 70B, trained on about 2 trillion tokens of publicly available data with a 4,096-token context. A 34B model was trained as well and held back because there had not been time to red-team it sufficiently. Optimization is AdamW with β1 = 0.9 and β2 = 0.95, a cosine schedule with 2,000 warmup steps decaying to 10% of the peak rate, weight decay 0.1 and gradient clipping at 1.0. The peak rate is 3×10^−4 for 7B and 13B and 1.5×10^−4 for the larger models. The tokenizer is the original Llama's 32k-token BPE, and grouped-query attention is used in the 34B and 70B models.

Alignment, step by step

  1. Supervised fine-tuning. 27,540 high-quality annotated prompt-and-response pairs. The authors found that tens of thousands of clean examples beat millions of noisier third-party ones. The loss covers answer tokens only; prompt tokens are masked out.
  2. Collect preferences in weekly batches. Annotators write a prompt, compare two responses sampled from different model variants, pick one, and grade how much better it is: significantly better, better, slightly better, or negligibly better or unsure. Safety annotation adds a label for whether each response is safe. Over the project this came to more than 1.4 million comparisons.
  3. Train two reward models. One for helpfulness and one for safety, both initialized from pretrained chat-model checkpoints so they know what the policy knows, with the language-modeling head replaced by a scalar output. Each is trained for one epoch on its own mix: helpfulness on all helpfulness data plus some safety and open-source data, safety on all safety data plus Anthropic's harmless set with a smaller share of helpfulness data.
  4. Rejection sampling fine-tuning. For each prompt, sample K responses from the current model, score them with the reward model, and fine-tune on the best. Only the 70B model was sampled; the smaller models were fine-tuned on its selected outputs, which distills the large model into them.
  5. Iterate, then add PPO. Five rounds, RLHF-V1 to V5, each with refreshed reward models. Through V4 the method was rejection sampling alone. In V5, PPO ran on top of the rejection-sampling checkpoint, with a KL penalty to the starting policy and a combined reward that switches to the safety score when a prompt is safety-related or a response looks unsafe.
  6. Keep earlier wins. When a round trained only on the previous round's samples, some skills regressed; RLHF-V3 got worse at writing rhyming poems. The fix was to keep the top samples from every earlier round in the training pool.

Ghost Attention and context distillation

Ghost Attention, or GAtt, targets instructions that should hold for a whole conversation, such as answering in French or playing a character. The authors attach the instruction to every user turn of synthetic multi-turn dialogues, sample responses from the latest RLHF model, then train on those dialogues with the instruction kept only in the first turn and the loss zeroed on earlier turns. The model learns to keep obeying an instruction it no longer sees repeated. Applied after RLHF-V3, it held for 20 or more turns, up to the context limit.

Context distillation is the safety counterpart: generate answers to adversarial prompts with a safety preprompt in front, fine-tune on those answers without the preprompt, and keep a distilled answer only where the safety reward model scores it above the original.

The math

The margin ranking loss and the piecewise RLHF reward

Each reward model scores a prompt x and response y as rθ(x, y) and is trained on pairs of a chosen response yc and a rejected one yr, with a margin set by how strongly the annotator preferred yc:

Lranking = −log σ( rθ(x, yc) − rθ(x, yr) − m(r) )

PPO then maximizes a reward that switches between the two models, minus a KL penalty to the starting policy π0:

Rc(g | p) = Rs(g | p) if p is safety-tagged or Rs(g | p) < 0.15, else Rh(g | p)
R(g | p) = R̃c(g | p) − β DKL( πθ(g | p) ‖ π0(g | p) )
  • m(r) — a fixed margin per preference grade: largest for significantly better, zero for negligibly better
  • Rs, Rh — the safety and helpfulness reward models
  • 0.15 — the safety threshold, chosen for 0.89 precision and 0.55 recall on the safety test set
  • R̃c — the combined score after a logit transform and whitening, which stabilizes PPO
  • β — 0.01 for the 7B and 13B models, 0.005 for the larger ones

With m = 0 the loss is the plain pairwise ranking loss. A margin forces a wider score gap on clear-cut pairs, and the authors found it helped most on exactly those pairs and little on near-ties. The switch means a response can never buy back a low safety score with helpfulness: below 0.15, the helpfulness model is not consulted at all.

The evidence

What Meta measured, and what it showed

Llama 2-Chat was judged mainly by human raters on about 4,000 single- and multi-turn prompts, against open models (MPT, Vicuna, Falcon) and closed ones (ChatGPT, PaLM). The base models were also scored on standard academic benchmarks.

MeasureResult
Llama 2-Chat 70B vs ChatGPT, human helpfulness ratings36% win, 31.5% tie
Llama 2 70B base, MMLU (5-shot)68.9
Released sizes7B, 13B, 70B (34B withheld)
Pretraining2T tokens, 4,096 context, about 3.3M A100 GPU-hours across the family
Alignment data27,540 SFT annotations; more than 1.4M preference comparisons

The 70B base model came close to GPT-3.5 on MMLU and GSM8K but showed a large gap on coding benchmarks. Llama 2-Chat beat the open chat models of its time by a wide margin in the human evaluations, and its rate of safety violations on adversarial prompts was among the lowest of the models compared.

Negative results and caveats. Reward-model accuracy was highest on pairs graded significantly better and fell toward chance on near-ties, which is the problem the margin addresses. Adding more safety data improved safety without measurably hurting helpfulness, but it raised false refusals on borderline prompts, the over-caution the paper shows with examples. Training each round only on the previous round's samples caused regressions, such as RLHF-V3 losing rhyming ability, until earlier rounds' best samples were kept. And the authors flag the limits of their human evaluation: about 4,000 prompts, no coding or reasoning prompts, only the final turn of multi-turn conversations rated, and rater subjectivity.

Trade-offs

Llama 2 trade-offs: what open weights and a two-reward recipe cost

Downloading the weights moves the bill from a per-token API price to hardware you run. The memory floor is simple arithmetic: weights take parameters × bytes per parameter, so the 70B needs about 140 GB in 16-bit and about 35 GB at 4 bits, before any KV cache. Grouped-query attention shrinks that cache by the ratio of query heads to key-value heads, which is why only the larger models got it: the 7B's cache is small enough that full multi-head attention costs little.

The alignment recipe is the expensive part to reproduce. Rejection sampling pays K full generations per prompt, and PPO keeps several large networks in memory at once.

Preference methodNetworks held during trainingGives up
Rejection sampling fine-tuningPolicy for sampling, reward model(s) for scoringK generations per prompt; improves only toward samples the model can already produce
PPO with two reward modelsPolicy, frozen reference, value model, helpfulness and safety reward modelsMemory, tuning effort and stability
DPO-style direct preference lossPolicy and frozen referenceThe explicit, adjustable safety threshold that a separate safety score gives you
Watch for

Common mistakes when fine-tuning or deploying Llama 2

  • Ignoring the chat format

    Llama 2-Chat was trained on turns wrapped in [INST] … [/INST], with the system prompt inside a <<SYS>> block. Send it plain text or another model's template and it still answers, just worse and less safely, which is easy to misread as a weak model.

  • Training on the prompt tokens

    Meta's SFT computed loss on answer tokens only. A fine-tune that also scores the user's text spends capacity learning to imitate prompts, and on short-answer data the answer is a small share of the loss.

  • Stretching the 4,096-token window

    Rotary positions do not extrapolate on their own. Feeding longer inputs without position scaling plus fine-tuning at the new length degrades output sharply past the trained window rather than failing loudly.

  • Assuming a benign fine-tune keeps the safety tuning

    Qi and colleagues (2023) showed that fine-tuning an aligned chat model, even on harmless data, can erode its refusals. Re-run safety and over-refusal evaluations after every fine-tune of the chat model, measuring both failure directions.

  • Calling it open source in a product decision

    The licence carries an acceptable-use policy and a clause for the very largest deployers. Read it before shipping, rather than assuming the freedoms of an OSI licence.

In the wild

Where Llama 2 shows up in production

  • The default local-inference architecture

    llama.cpp, named after the family, runs quantised Llama-architecture models on CPUs and laptops through its GGUF format, and Ollama wraps it. Hugging Face transformers exposes the architecture as LlamaForCausalLM, a class many later open models reuse.

  • A template other model families copied

    RMSNorm, SwiGLU, rotary positions and grouped-query attention became the baseline decoder block; Mistral 7B, for one, kept that block and added sliding-window attention.

  • Base for domain fine-tunes

    Teams that cannot send data to an API start from an open base or chat checkpoint and adapt it in-house, keeping weights and data on their own hardware.

  • In interviews

    Expect to size a KV cache and explain how GQA cuts it, to walk through SFT, reward modelling, rejection sampling and PPO, and to say why open weights and open source are not the same claim.

Since then

What the authors admit, and what happened next

The safety work's cost is reported rather than hidden: the aligned chat model over-refuses, declining benign requests that pattern-match to something disallowed, and the paper shows examples. Read next to the principles-based approach, it is a clean illustration of why refusing with a reason became the goal — a model trained on preferences alone learns that the safest output is the shortest one.

Two limits on the openness are worth stating precisely, because the word does a lot of unexamined work. The licence is not an open-source licence by the usual definition — it carries an acceptable-use policy and a clause restricting the very largest deployers — and the training data mixture is not disclosed, so the artefact is reproducible in architecture and not in provenance. "Open weights" is the accurate term and "open source" is not.

How it held up: it created the ecosystem this ladder describes. Nearly everything downstream — the quantisation toolchains, the local inference runtimes, the single-GPU fine-tuning wave, the thousands of derived models — dates from this release being usable, and the secondary effect was to establish that a published account of alignment methodology is something a lab can do without losing its position. Grouped-query attention became standard. The two-reward-model design was largely superseded by simpler preference methods, but the diagnosis it responded to did not go away.

SOLVE IT YOURSELF

One reward vs two: why safety needs its own model

Llama 2-Chat scores answers with two separate reward models — helpfulness and safety — instead of blending them. Here's why it matters, runnable: rejection sampling produces a very-helpful-but-unsafe answer alongside a safe one. A single blended reward lets the impressive-but-unsafe answer win; a safety gate plus a helpfulness model filters it out first, then picks the most helpful of what survives. Watch the two strategies choose differently — and the two-model one stay safe. Change the scores.

YOUR TASK

Write the body of dual_pick. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. A single blended reward can pick an unsafe answer
  2. The safety gate keeps only safe candidates
  3. The two-model policy picks a safe answer
  4. The two strategies diverge in the unsafe case
  5. Among safe candidates the dual policy maximizes helpfulness
CPython · WebAssembly
Questions

Questions people ask about Llama 2

How does Ghost Attention (GAtt) work in Llama 2?

Ghost Attention is a data trick, not a change to the attention mechanism. The problem it solves is that chat models forget a standing instruction, such as always answer in French or act as a given character, after a few turns. Meta built synthetic multi-turn dialogues, attached the instruction to every user message, and sampled responses from the latest RLHF model, so every response obeys it. It then trained on those dialogues with the instruction removed from every turn except the first and the loss zeroed on earlier turns. The model learns to follow an instruction that appears only at the start. Applied after RLHF-V3, it held for 20 or more turns, up to the context limit.

How does the margin in Llama 2's reward model loss work?

Llama 2's reward models use the standard pairwise ranking loss, the negative log-sigmoid of the score difference between the chosen and the rejected response, with one addition: a margin subtracted from that difference. The margin is a fixed value per preference grade. Annotators labeled each comparison significantly better, better, slightly better, or negligibly better or unsure, and the margin is largest for significantly better and zero for negligibly better. So the model must open a wider score gap on clear-cut pairs than on near-ties. Meta found the margin improves accuracy mainly on clearly separable pairs. For Llama 3, Meta removed it again, reporting diminishing improvements once the preference data was scaled.

Why did Llama 2 train separate helpfulness and safety reward models?

Because the two goals pull against each other, and a single reward model struggles to score both well. A refusal is safe but unhelpful, and a detailed answer to a harmful request is helpful but unsafe, so one learned score has to encode a trade-off everywhere. Meta trained a helpfulness model and a safety model on different data mixes and combined them with a simple rule during PPO: if the prompt is tagged as risky, or the safety score is below 0.15, use the safety score; otherwise use the helpfulness score. That keeps safety from being traded away for helpfulness, while ordinary prompts are optimized purely for helpfulness.

What is the difference between rejection sampling and PPO in Llama 2-Chat?

Rejection sampling fine-tuning draws K responses per prompt from the current model, scores them with the reward model, and fine-tunes on the best one, so the model improves by imitating its own best outputs. PPO updates the model directly against the reward with small policy-gradient steps, while a KL penalty keeps it near the starting policy. Rejection sampling explores breadth, many samples per prompt, while PPO takes many small steps per sample. Meta used rejection sampling alone for RLHF-V1 to V4 and applied PPO only in V5, on top of the rejection-sampling checkpoint. Only the 70B model was sampled; the smaller models trained on its selected outputs.

How does context distillation make Llama 2-Chat safer?

Context distillation moves the effect of a prompt into the weights. Meta prefixed adversarial prompts with a safety preprompt, for example telling the model it is a safe and responsible assistant, generated the safer answers that the preprompt induces, and then fine-tuned the model on those answers with the preprompt removed. The model learns to answer safely without being told to. Meta also tailored preprompts to specific risk categories with answer templates. Because context distillation can make answers vaguer or more evasive, it was applied selectively: a distilled answer was kept only when the safety reward model scored it higher than the model's original answer to the same prompt.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

A PPO sample has safety score 0.12 and helpfulness score 0.95 on a prompt that is not tagged as risky. Which reward does Llama 2's PPO optimize for it, and why?

Show answer

The safety score, 0.12. The combined reward switches to the safety model whenever the prompt is tagged risky or the safety score is below 0.15, and 0.12 is below the threshold. The 0.95 helpfulness is never consulted, so an unsafe answer cannot win on helpfulness.

Two preference pairs get margins of 1 (significantly better) and 0 (negligibly better). What score gap r(chosen) − r(rejected) makes each pair's loss exactly log 2, and what does that teach the reward model?

Show answer

The loss is log 2 when σ(Δ − m) = 0.5, so Δ = m: a gap of 1 for the significantly-better pair and 0 for the near-tie. Clear-cut pairs must open a wider gap before their loss falls, so scores spread out in proportion to how strong the preference was.

In RLHF-V1 to V4 only the 70B model ran rejection sampling. How did the 7B and 13B chat models improve during those rounds?

Show answer

They were fine-tuned on the 70B model's rejection-sampled outputs, the best of K responses as judged by the reward model. That is distillation: the small models learn from the large one's selected answers instead of their own samples, which also avoids sampling K responses per prompt from every size.

Why does Ghost Attention train with the instruction left only in the first turn, rather than in every turn?

Show answer

At inference the instruction appears once, at the start. If training kept it in every turn, the model would learn to obey an instruction that is always nearby, which teaches nothing about remembering it. Dropping it from later turns forces the model to carry the first-turn instruction through the conversation, the behavior that otherwise decays after a few turns.

Where this sits

The open-weights line

Five releases you can actually download, in the order each one answered the last. This is where "what does a frontier recipe look like" is documented in public.

  1. 1Llama 22023
  2. 2Llama 32024
  3. 3Qwen32025
  4. 4Kimi K22025
  5. 5Kimi K32026

All 110 papers, in 19 ladders →

Finished this one? 0 / 110 Paper Breakdowns done
NextLlama 3 Next on the “The open-weights line” ladder · rung 2 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns