LLaMA is a family of decoder-only Transformer language models with 7 to 65 billion parameters, trained only on publicly available data and on more tokens than usual (1.0 to 1.4 trillion). Touvron et al. at Meta AI introduced it in 2023 in the paper "LLaMA: Open and Efficient Foundation Language Models" and released the models to researchers.
At the time, research on large language models was moving toward ever more parameters, based on the idea that bigger models perform better. The Chinchilla study countered this by showing that for a fixed compute budget, a smaller model trained on more data outperforms the largest possible model.
The LLaMA paper adds one more perspective.
The Chinchilla approach optimizes for training compute and ignores the compute needed when the model is used after training (inference).
For a model that many people use, inference speed matters more than training speed. For the same performance, a smaller model trained longer is cheaper to use.
In the paper's example, the Chinchilla approach recommends 200 billion tokens for a 10-billion-parameter model, yet even a 7-billion-parameter model kept improving beyond 1 trillion tokens.
As a result, LLaMA-13B outperforms GPT-3 (175 billion), which is more than 10 times larger, on most benchmarks, and LLaMA-65B is competitive with Chinchilla-70B and PaLM-540B. The 13B model can run inference on a single GPU. Restricting the training data to public data also makes it easier for other researchers to verify results under the same conditions.
Architecture: Changes from the Transformer
LLaMA has the same architecture as GPT: a stack of decoders with causal self-attention. In the figure at the top of the article, the left side shows the overall flow and the range attention can see, and the right side shows the inside of one decoder layer. The changes from the original Transformer are the three listed in Section 2.2 of the paper (the model that inspired each change is in parentheses).
Apply RMSNorm on the input side (GPT-3): Normalize the input of each sub-layer rather than its output (the same ordering as Pre-LN in Pre-LN vs. Post-LN). Normalization uses RMSNorm, which rescales only the magnitude without subtracting the mean. This stabilizes training.
Use SwiGLU as the feed-forward activation function (PaLM): Replace ReLU with the gated SwiGLU. This improves performance.
Use RoPE for positional information (GPT-Neo): Drop the absolute positional embeddings added to the input and apply RoPE (Rotary Position Embedding) in the attention of every layer.
RMSNorm in item 1 divides d values a1โ,โฆ,adโ by their root mean square and multiplies by a gain giโ.
Each sub-layer computes xโx+Sublayer(RMSNorm(x)). The input x bypasses normalization and is added directly to the next layer through the residual path. The official implementation also places one RMSNorm after the last layer before the linear layer that predicts the next token.
The SwiGLU feed-forward network in item 2 follows the formula of Shazeer (2020), without biases.
โ is the element-wise product and ฯ is the sigmoid function. xW, passed through SiLU (Swish with ฮฒ=1), acts as a "gate" that decides how much of each component of the other branch xV passes through. The original feed-forward network has two weight matrices, whereas SwiGLU has three: W,V,W2โ. To keep the parameter count and compute the same, the hidden size is set to 32โโ 4d instead of the original 4d.
The official implementation rounds the hidden size 32โโ 4d up to a multiple of 256. For example, in LLaMA-7B (d=4096), 10,922 is rounded up to 11,008. This makes the size easier to compute on GPUs.
The paper trains four models of different sizes (Table 2 of the paper).
Parameters
Layers
Vector size d
Heads
Peak learning rate
Training tokens
6.7B (7B)
32
4096
32
3.0ร10โ4
1.0T
13.0B (13B)
40
5120
40
3.0ร10โ4
1.0T
32.5B (33B)
60
6656
52
1.5ร10โ4
1.4T
65.2B (65B)
80
8192
64
1.5ร10โ4
1.4T
All models are trained with 4 million tokens per step.
Tokenization uses BPE from SentencePiece. All numbers are split into individual digits, and UTF-8 characters not in the vocabulary are decomposed into bytes (the same idea as byte-level tokenization). The vocabulary has 32,000 tokens and the context length is 2048 tokens (both confirmed in Section 2.2 and Table 1 of the Llama 2 paper).
Training: Public Data and Training Setup
The training data is a mixture of only publicly available data that is compatible with open sourcing (Table 1 of the paper). After tokenization it contains about 1.4 trillion tokens.
Data
Sampling proportion
Epochs over 1.4T tokens
Disk size
Main preprocessing
CommonCrawl (English)
67.0%
1.10
3.3 TB
Deduplicate at the line level and remove non-English and low-quality pages. Keep only pages likely to be used as Wikipedia references
C4
15.0%
1.06
783 GB
Filter quality with heuristics such as punctuation and word counts
GitHub
4.5%
0.64
328 GB
Only Apache, BSD, and MIT licenses. Deduplicate at the file level
Wikipedia
4.5%
2.45
83 GB
20 languages from June to August 2022. Remove hyperlinks and comments
Books (Gutenberg, Books3)
4.5%
2.23
85 GB
Remove books with more than 90% content overlap
arXiv
2.5%
1.06
92 GB
Remove everything before the first section and the bibliography
Stack Exchange
2.0%
1.03
78 GB
The 28 largest sites. Sort answers by score
Most of the data is used only once. Only Wikipedia and books are used about twice.
The optimization setup (Section 2.3 of the paper) is as follows.
Training is also accelerated (Section 2.4 of the paper).
An implementation of causal attention that neither stores attention weights nor computes scores for masked positions (the xformers library, using the backward pass of FlashAttention). This reduces memory and time.
Reduce the amount of recomputation in the backward pass (in gradient checkpointing, expensive activations such as the outputs of linear layers are saved).
Use model parallelism and sequence parallelism, overlapping communication between GPUs with computation.
The 65B model used 2,048 A100 GPUs with 80 GB each, processing about 380 tokens per second per GPU. Training on 1.4 trillion tokens takes about 21 days.
Why Train Smaller Models Longer
The core idea of LLaMA is to minimize total cost, including how the model is used.
The cost of a language model splits into a one-time training cost and an inference cost incurred every time the model is used.
Training cost is roughly proportional to "parameters ร training tokens". For the same cost, one can train a large model briefly or a small model for longer.
Inference cost is proportional to the parameter count and is paid every time the model is used. It does not depend on the number of training tokens.
The Chinchilla study found the combination of model size and token count that maximizes performance for a fixed training cost. For a model that many people use repeatedly, however, inference cost becomes far larger. LLaMA therefore chooses to reach a target performance with the smallest possible model and trains it on far more tokens than Chinchilla recommends.
As a cooking analogy: when a restaurant develops a new dish, a recipe that takes some extra effort to develop (training) but is quick to cook hundreds of times a day (inference) is the better deal overall.
In fact, Figure 1 of the paper shows that the training loss of the 7B and 13B models keeps decreasing up to 1 trillion tokens.
Training a small model for longer yields smaller performance gains per unit of training compute. LLaMA is designed to favor inference efficiency over training efficiency, so when the compute budget is limited and the model will be used only once, the Chinchilla approach is the better fit.
Experimental Results
The paper evaluates on 20 benchmarks in zero-shot (only a task description and the question) and few-shot (1 to 64 examples) settings.
Common sense reasoning (zero-shot, accuracy %. Excerpt from Table 3 of the paper)
Model
BoolQ
PIQA
HellaSwag
WinoGrande
ARC-e
ARC-c
OBQA
GPT-3 175B
60.5
81.0
78.9
70.2
68.8
51.4
57.6
Chinchilla 70B
83.7
81.8
80.8
74.9
-
-
-
PaLM 540B
88.0
82.3
83.4
81.1
76.6
53.0
53.4
LLaMA 7B
76.5
79.8
76.1
70.1
72.8
47.6
57.2
LLaMA 13B
78.1
80.1
79.2
73.0
74.8
52.7
56.4
LLaMA 65B
85.3
82.8
84.2
77.0
78.9
56.0
60.2
LLaMA-65B outperforms Chinchilla-70B on every benchmark except BoolQ, and PaLM-540B on every benchmark except BoolQ and WinoGrande.
Knowledge, reading comprehension, math, code, and general (all in % such as accuracy. Tables 4 to 9 of the paper)
On knowledge-intensive question answering (NaturalQuestions, TriviaQA), LLaMA-65B achieves the state of the art at the time in both zero-shot and few-shot settings. The 13B model is also competitive with GPT-3 and Chinchilla, which are 5 to 10 times larger.
On MMLU, however, LLaMA-65B falls a few points short of Chinchilla-70B and PaLM-540B on average. The paper attributes this to the small amount of books and academic papers in the training data (arXiv, Gutenberg, and Books3 total only 177 GB), compared with other models trained on up to 2 TB of books.
A brief instruction fine-tuning further improves MMLU (Section 4 and Table 10 of the paper). LLaMA-I (65B), briefly fine-tuned on instruction data, reaches 68.9%, outperforming instruction-tuned models of similar size (such as Flan-PaLM-cont 62B at 66.1%).
Practical Considerations
Keep the following points in mind when using LLaMA.
Context is limited to 2048 tokens: Split long documents, or extend the context with methods such as position interpolation.
Not trained to follow instructions: LLaMA is a foundation model trained only to predict the next token. Using it for dialogue or responding to instructions requires, for example, fine-tuning on instruction data.
Bias and toxic output: In the paper's evaluation, larger models tend to generate more toxic text (RealToxicityPrompts), and biases related to religion, age, gender, and so on are observed (CrowS-Pairs, WinoGender). The paper attributes these to the web data (CommonCrawl).
Factual accuracy: On TruthfulQA, the share of truthful and informative answers is only 0.53 even for 65B, so the model may produce plausible but incorrect answers (hallucinations).
Relatively little knowledge from books and papers: On tasks that broadly test expert knowledge, such as MMLU, it can be weaker than other models of the same size.
The LLaMA models were released to researchers under restricted conditions. If you need a model for commercial use, consider its successor Llama 2, which was released for both research and commercial use. In either case, check the distributor's license terms before use.
Comparison with Other Models
Comparing large language models from the same period from the same perspectives gives the following (MMLU is 5-shot, from Table 9 of the LLaMA paper).
Even LLaMA's largest model is smaller than the others, and it falls a step short on MMLU. In return, by using only public training data and releasing the models, it lets other researchers verify and improve on the work under the same conditions.
Rough guidelines for choosing are as follows.
To research and experiment with large language models on your own GPUs: LLaMA 7B and 13B can run inference on a single GPU. The architecture is simple and serves as the basis for many successors (such as Llama 2 and Mistral 7B).
For commercial use or long contexts: Llama 2, which extends the context to 4096 tokens and was released for commercial use as well, is a better fit.
To learn the basic architecture of language models: Read GPT and GPT-2 first, then look at LLaMA's three changes (RMSNorm, SwiGLU, RoPE) as modifications to them; this makes the differences easier to understand.
PyTorch example
โถShow code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of the LLaMA components, following Section 2.2 of the paper and the official implementation (facebookresearch/llama)
- RMSNorm: no mean subtraction; divide by the root mean square and multiply by a gain
- SwiGLU feed-forward: (SiLU(xW) * xV) W2. The hidden size is (2/3)ยท4d rounded up to a multiple of 256
- RoPE: rotate queries and keys by angles proportional to the position (not applied to values)
- Decoder layer: x + Attention(RMSNorm(x)), x + FFN(RMSNorm(x)). Linear layers have no bias
No dropout is used, so model.train() and model.eval() compute the same thing
"""
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim)) # gain g (initialized to 1)
def forward(self, x):
rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x / rms * self.weight
class SwiGLUFeedForward(nn.Module):
def __init__(self, dim, multiple_of=256):
super().__init__()
hidden = int(2 * (4 * dim) / 3) # (2/3)ยท4d
hidden = multiple_of * ((hidden + multiple_of - 1) // multiple_of) # 11008 for 7B (d=4096)
self.w = nn.Linear(dim, hidden, bias=False) # gate branch (passed through SiLU)
self.v = nn.Linear(dim, hidden, bias=False)
self.w2 = nn.Linear(hidden, dim, bias=False)
def forward(self, x):
return self.w2(F.silu(self.w(x)) * self.v(x))
def rope_angles(head_dim, max_len, theta=10000.0):
# set the rotation speed ฮธ_i = 10000^(-2(i-1)/d) for each pair of dimensions and build the angle mยทฮธ_i for position m
freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs) # [max_len, head_dim/2]
return torch.cos(angles), torch.sin(angles)
def apply_rope(x, cos, sin):
# x: [batch, heads, n, head_dim]. Rotate each pair of adjacent values
x1, x2 = x[..., 0::2], x[..., 1::2]
out = torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
return out.flatten(-2)
class Attention(nn.Module):
def __init__(self, dim, n_heads):
super().__init__()
self.n_heads, self.head_dim = n_heads, dim // n_heads
self.wq = nn.Linear(dim, dim, bias=False)
self.wk = nn.Linear(dim, dim, bias=False)
self.wv = nn.Linear(dim, dim, bias=False)
self.wo = nn.Linear(dim, dim, bias=False)
def forward(self, x, cos, sin):
b, n, _ = x.shape
split = lambda t: t.view(b, n, self.n_heads, self.head_dim).transpose(1, 2)
q, k, v = split(self.wq(x)), split(self.wk(x)), split(self.wv(x))
q, k = apply_rope(q, cos[:n], sin[:n]), apply_rope(k, cos[:n], sin[:n])
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # causal mask
return self.wo(out.transpose(1, 2).reshape(b, n, -1))
class DecoderLayer(nn.Module):
def __init__(self, dim, n_heads):
super().__init__()
self.attn_norm, self.attn = RMSNorm(dim), Attention(dim, n_heads)
self.ffn_norm, self.ffn = RMSNorm(dim), SwiGLUFeedForward(dim)
def forward(self, x, cos, sin):
x = x + self.attn(self.attn_norm(x), cos, sin) # normalize the input (Pre-LN)
return x + self.ffn(self.ffn_norm(x))
class TinyLLaMA(nn.Module):
def __init__(self, vocab=32000, dim=512, n_layers=4, n_heads=8, max_len=2048):
super().__init__()
self.embed = nn.Embedding(vocab, dim) # no positional embedding
self.layers = nn.ModuleList(DecoderLayer(dim, n_heads) for _ in range(n_layers))
self.norm = RMSNorm(dim) # one at the end
self.out = nn.Linear(dim, vocab, bias=False)
cos, sin = rope_angles(dim // n_heads, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens):
h = self.embed(tokens)
for layer in self.layers:
h = layer(h, self.cos, self.sin)
return self.out(self.norm(h)) # next-token logits
model = TinyLLaMA()
tokens = torch.randint(0, 32000, (2, 16))
logits = model(tokens)
print(logits.shape) # torch.Size([2, 16, 32000])
# Pretrained weights can be loaded with LlamaForCausalLM in Hugging Face transformers
# (convert weights obtained after accepting the distributor's license before use)
FAQ
Q. How does LLaMA differ from GPT-3?
A.
Both are decoder-only Transformers, but LLaMA uses RMSNorm for normalization, SwiGLU as the activation function, and RoPE for positional information. It also trains models smaller than GPT-3 on more tokens (up to 1.4 trillion) and restricts the training data to public data. As a result, LLaMA-13B outperforms GPT-3 (175 billion) on most benchmarks despite having more than 10 times fewer parameters.
Q. Why does SwiGLU use a hidden size of $\frac{2}{3} \cdot 4d$?
A.
The SwiGLU feed-forward network has three weight matrices, W,V,W2โ, which is 1.5 times as many as the original feed-forward network (two). Setting the hidden size to 32โ of 4d makes the parameter count and compute roughly the same as the original feed-forward network, allowing a fair comparison.
Q. Should I use LLaMA or Llama 2?
A.
For new projects, Llama 2 is usually the better choice. Llama 2 increases the training data to 2 trillion tokens, extends the context to 4096 tokens, and was released for both research and commercial use. There is also Llama 2-Chat, fine-tuned for dialogue. LLaMA is suited to research that reproduces the paper's results or compares architectural differences.