0 The whole pipeline in one file
The Transformer module explained a decoder as a diagram. This tutorial builds one end to end and runs every stage. Each stage is a subcommand of build_llm.py, and all runs them in order:
Notation (as in the Transformer module): N = tokens in a context, d = width, h = heads, L = layers, V = vocab. T is used only for the sampling temperature; the code keeps nanoGPT's B, T, C for batch, tokens and width.
The seven stages and the subcommand that runs each. Everything after training reads the checkpoint, so you can re-run sampling or SFT without retraining.
A 0.87M-parameter model on 2.5M training tokens (12.6 passes over a 195K-token corpus) costs about 6 × 0.87M × 2.46M ≈ 12.8 TFLOP, about a minute of CPU time. That is enough to watch every mechanism work. The code is the same shape as a real LLM; the last section lists what changes when you scale it up.
1 Data: a tiny world you can check
Real pretraining reads trillions of tokens of web text. Here the corpus is generated by make_corpus() from a dozen made-up people, each with a town, a pet, a job and a favourite colour. The facts never change across the corpus, so you can test later whether the model learned them. Nothing is downloaded and every sentence was written for this repo.
Three kinds of document are mixed: fact sheets (35%), Q&A notes (15%, the toy version of the FAQ pages that real web text contains) and short stories (50%) that combine people, places and pets at random.
$ python build_llm.py data
4,000 documents, 663,222 characters, 235 distinct words
- On a windy morning, Ada left Riverton and went to the bakery. She painted a yellow sign for the bakery. She bought some fish at the bakery. Biscuit the dog barked at a duck. It was a good day for Ada the painter.
- Kiwi is Lena's parrot. Lena works as a teacher. Lena has a parrot named Kiwi.
- In Fernwick, everyone knows Priya the doctor. Priya works as a doctor. Priya's favorite color is purple.
- Nora works as a nurse. Luna is Nora's cat. Nora has a cat named Luna. ...
The stories are random combinations, so even a perfect model cannot predict them exactly: the loss has a floor above zero. The vocabulary is tiny (235 words), so the model learns grammar in about a hundred steps. Real text has a long tail of rare words and facts, which is why real models need so much more data and so many more parameters.
2 Tokenizer: byte-level BPE from scratch
A model reads integers, not text. Byte-pair encoding (BPE, Sennrich et al., 2015) builds the vocabulary bottom-up:
- Start with the 256 byte values. Any string is a sequence of UTF-8 bytes, so any string can be encoded: nothing is ever "unknown".
- Pre-tokenize the text into chunks (a word with its leading space, a number, punctuation, whitespace) with a GPT-2-style regex. Merges never cross chunk boundaries.
- Count every adjacent pair of tokens, merge the most frequent pair into a new token, and repeat until the vocabulary is full.
Encoding replays the merges in the order they were learned. Decoding concatenates each token's bytes. Training counts each distinct chunk once, weighted by its frequency, so 252 merges take 0.1 s here.
Edit the text and press "Next merge". Orange chips are the tokens created by the latest merge; ␣ is a space. Watch the token count fall as frequent pairs such as "␣c" + "at" become one token.
$ python build_llm.py tokenizer
merge 1: b'h' + b'e' -> b'he' (seen 14,906x)
merge 2: b' ' + b't' -> b' t' (seen 11,069x)
...
merge 8: b' t' + b'he' -> b' the' (seen 7,249x)
trained 252 merges in 0.1s -> vocab 512 (256 bytes + 252 merges + 4 specials)
212 bytes -> 71 tokens: On| a| w|in|d|y| morning|,| Ada| left| Riverton| and| went| to| the| baker|y|.| ...
round-trip OK on 202 strings, incl. unseen unicode (58 tokens, mostly raw bytes)
compression: 3.11 bytes/token on the corpus
The round-trip test
The one property a tokenizer must have is decode(encode(s)) == s for every string. The script asserts it on 200 documents, on text the tokenizer never saw (accents, CJK, an emoji, tabs and newlines) and on the special tokens. Unseen characters fall back to their raw bytes: "Café 🙂" is 10 bytes and 10 tokens, but it round-trips exactly.
tests = docs[:200] + ["Café ☕, naïve résumé, 東京, emoji 🙂, tabs\tand\nnewlines",
"<|user|>hi<|assistant|>ok<|end|>"]
for s in tests:
assert tok.decode(tok.encode(s)) == s, f"round-trip failed for {s!r}"Special tokens and the leading-space trap
Four ids are reserved after the merges: <|endoftext|> separates documents, and <|user|>, <|assistant|>, <|end|> form the chat template used in SFT. They are matched literally before BPE runs, so user text can never produce them by accident.
Notice that " Ada" (with its space) is one token, while "Mira" at the very start of a string becomes M|ira. To BPE, a word with and without a leading space are different tokens. This matters in step 7: the chat template puts a space before the answer so that the answer's first word is the same token the model saw in pretraining.
GPT-2's byte-level BPE has 50,257 tokens (config); recent models use larger vocabularies. A larger vocabulary means fewer tokens per sentence (cheaper attention and KV cache) but a larger embedding table and output layer. On edge devices the [d, V] output projection can be a noticeable share of decode time.
3 Model: a modern GPT decoder
The block is the decoder from the Transformer module with the changes that most open LLMs have adopted since GPT-2. Each is a few lines in build_llm.py:
The grey bar is the residual stream; each branch reads a normalized copy and adds its result back. Compare with the post-norm block, LayerNorm and sinusoidal positions in the original Transformer.
def apply_rope(x, cos, sin):
"""Rotate each (x1, x2) pair of channels by a position-dependent angle. x: [B, n_head, T, head_dim]."""
x1, x2 = x.chunk(2, dim=-1)
return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
class Attention(nn.Module):
def forward(self, x, cos, sin, cache=None):
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2) # one fused GEMM for Q, K, V
q, k, v = (t.view(B, T, self.n_head, self.head_dim).transpose(1, 2) for t in (q, k, v))
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
if cache is not None:
k, v = cache.update(k, v) # all keys/values so far
y = F.scaled_dot_product_attention(q, k, v, is_causal=T > 1)
return self.proj(y.transpose(1, 2).reshape(B, T, C))
class Block(nn.Module):
def forward(self, x, cos, sin, cache=None):
x = x + self.attn(self.norm1(x), cos, sin, cache) # pre-norm
return x + self.mlp(self.norm2(x))The code follows nanoGPT: B, T, C = batch, tokens, width, so the code's T is the N (tokens) of the prose and diagrams, and C is d. In apply_rope, x is [B, h, N, d_k].
Where the 869,504 parameters are
| Part | Shape | Parameters | Note |
|---|---|---|---|
| Token embedding (= lm_head) | 512 × 128 | 65,536 | counted once because it is tied |
| Attention per layer | qkv 128×384, proj 128×128 | 65,536 | 4·d², no biases |
| SwiGLU per layer | 3 × 128×352 | 135,168 | d_ff = 352 (8/3·d rounded up to 32) |
| 2 RMSNorm gains per layer | 2 × 128 | 256 | |
| × 4 layers + final norm | 803,840 + 128 | ||
| Total | 869,504 | printed as 0.87M |
4 Pretraining: next-token prediction
The training signal is free: every position predicts the token that follows it. get_batch samples 32 windows of 128 tokens; the targets are the same windows shifted by one. The loss is the average cross-entropy over all 4,096 positions.
for step in range(args.steps):
for g in opt.param_groups:
g["lr"] = lr_at(step, args.steps, peak=3e-3, warmup=30) # linear warmup, cosine decay to 10%
x, y = get_batch(train_data, batch_size, cfg.ctx, gen) # y = x shifted left by one token
_, loss = model(x, y)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # cap rare large updates
opt.step() # AdamW, weight decay on matrices only- AdamW (Loshchilov & Hutter) with β = (0.9, 0.95) and weight decay 0.1 on matrices, none on norm gains.
- Warmup then cosine decay. Adam's moment estimates are noisy for the first steps, so the learning rate ramps up over 30 steps.
- Gradient clipping at norm 1.0 keeps a single bad batch from undoing progress.
- Initialization: N(0, 0.02), with the output projections of each residual branch scaled down by √(2·layers), as in GPT-2.
Reading the loss curve
What to notice: the loss starts at ln V, as an untrained model's uniform guess should, falls about 14× in the first 100 steps, and then creeps down. Validation tracks training closely, so there is little overfitting despite 12.6 epochs.
- Start at ln V. An initial loss far from ln 512 = 6.24 points to an initialization bug. This one starts at 6.257.
- Plateau above zero. The final validation loss is 0.297 nats/token, a perplexity of e0.297 ≈ 1.35: on average the model hesitates between about 1.35 equally likely tokens, because the stories are random (which friend, which place).
- Train vs. validation. If validation rose while training fell, the model would be memorizing the training windows. Here the gap is about 0.04 at the end.
| Measured run (i7-13700H, torch 2.1, CPU) | Pretraining, 600 steps | Whole all pipeline | Throughput |
|---|---|---|---|
--threads 4 | 63 s | 66 s | ≈ 39,000 tok/s |
--threads 1 | 176 s | 180 s | ≈ 14,000 tok/s |
Training compute ≈ 6 × params × tokens (Chinchilla writes this 6·N·D, with N = parameters and D = tokens; elsewhere on this page N counts the tokens in a context). With 869,504 parameters and 2,457,600 training tokens it is 12.8 TFLOP, so the 4-thread run sustained about 0.2 TFLOP/s. The same arithmetic tells you what a real run costs; see At scale.
5 Sampling: from logits to text
The model outputs a score (logit) for every token in the vocabulary. Generation repeatedly turns the last position's logits into one token and appends it. How you choose that token changes the text a lot:
- Greedy (T = 0): always the argmax. Deterministic, and prone to loops in larger models.
- Temperature T: divide the logits by T before the softmax. T < 1 sharpens the distribution, T > 1 flattens it.
- Top-k: keep only the k most likely tokens.
- Top-p (nucleus, Holtzman et al.): keep the smallest set of tokens whose probabilities add up to at least p. The set adapts: narrow when the model is confident, wide when it is not.
Move the sliders. Grey bars are tokens removed by top-k or top-p; the remaining probabilities are renormalized. At T = 0 everything goes to the argmax. Watch how T = 2 hands real probability to "cat" and "Oakvale", which make no sense here.
def sample_next(logits, temperature=1.0, top_k=None, top_p=None, gen=None):
if temperature == 0:
return logits.argmax(-1, keepdim=True) # greedy
logits = logits / temperature
if top_k is not None:
kth = torch.topk(logits, min(top_k, logits.size(-1))).values[..., -1:]
logits = logits.masked_fill(logits < kth, float("-inf"))
probs = F.softmax(logits, dim=-1)
if top_p is not None and top_p < 1.0:
p_sorted, idx_sorted = probs.sort(-1, descending=True)
outside = p_sorted.cumsum(-1) - p_sorted >= top_p # mass before this token already >= top_p
p_sorted = p_sorted.masked_fill(outside, 0.0)
choice = torch.multinomial(p_sorted / p_sorted.sum(-1, keepdim=True), 1, generator=gen)
return idx_sorted.gather(-1, choice)
return torch.multinomial(probs, 1, generator=gen)$ python build_llm.py sample
[greedy (T=0)]
One morning, Mira walked to the hill with Pip. She bought some cheese at the hill. Pip the cat chased a leaf. Then Mira went home to Oakvale.
[T=0.8, top-k=20]
One morning, Mira walked to the park with Pip. She bought some fish at the park. The weather was windy, so she stayed near the park. Mira said hello to Pip. It was a good day for Mira the baker.
[T=2.0 (too hot)]
One morning, Mira walked to the park with Pip. Sheer the bakery the rabbit�� everyone Kenji went to Fernwick. bakery afternoon, ...
fact recall (greedy): 'Mira lives in' -> ' Oakvale'
fact recall (greedy): 'Tomas lives in' -> ' Riverton'
The model has learned grammar, the story templates and the facts: Mira's pet is Pip and she goes home to Oakvale. At T = 2 the flattened distribution gives weight to tokens that never follow each other, and it even emits single bytes of a multi-byte character (the � marks).
6 KV cache: fast decoding, tested
Without a cache, generating token t re-runs the model on all t tokens, recomputing keys and values that have not changed. With a cache, each layer stores K and V for past positions; a decode step computes q, k, v for the one new token only, appends k and v, and attends over everything cached.
Rows are decode steps 1–6, cells are token positions. Attention still reads all cached keys at each step, so long contexts make decode memory-bandwidth bound: the KV cache is what you pay for in memory.
The test: cached decode must equal the full forward
An optimization you cannot verify is a bug waiting to happen. cmd_kvcache runs the full causal forward over 128 tokens once, then runs a 16-token prefill into an empty cache followed by 112 single-token decode steps, and compares every logit:
full, _ = model(idx) # [1, T, V], one causal pass
caches = model.new_kv_cache(1)
steps = [model(idx[:, :16], caches=caches)[0]] # prefill 16 tokens
for t in range(16, idx.shape[1]): # then decode one token at a time
steps.append(model(idx[:, t:t + 1], caches=caches)[0])
inc = torch.cat(steps, dim=1)
assert torch.allclose(full, inc, atol=1e-4)$ python build_llm.py kvcache logits: full forward vs prefill(16) + 112 cached decode steps: max |diff| = 7.63e-06 greedy generation of 119 tokens is identical with and without the cache no cache: 925.9 tok/s (re-runs all N tokens every step: O(N^2) GEMM work) KV cache: 1809.4 tok/s (one new token per step: O(N) GEMM work; attention reads still grow as O(N^2)) KV cache size = 2 (K,V) x 4 layers x 128 positions x 128 dims x 4 B = 512 KiB per sequence (fp32) PASS: KV-cache decode matches the full forward
The difference is floating-point noise (different summation order), far below the tolerance. The speedup is only about 2× here because the model is tiny and the context is 128 tokens, so per-step overheads dominate. The gap grows with model size and context length.
Positions: a decode step must use the absolute position of the new token for RoPE (start = caches[0].pos), not position 0. Masking: PyTorch's is_causal=True assumes a square N × N mask aligned at the top-left. It is right for a prefill into an empty cache, and a single decode query needs no mask, but a multi-token chunk on top of an existing cache needs an explicit mask. The minimal cache here asserts against that case instead of silently computing the wrong thing.
Size = 2 × L × N × batch × (KV heads × head_dim) × bytes. The defaults are a 7B-class shape (L = 32, d = 4096) at N = 8192 in FP16: 4 GiB per sequence. Set KV heads to 8 (grouped-query attention, Ainslie et al.) or bytes to 1 (FP8 cache) to see the levers serving systems use.
7 SFT: teaching the format, not the facts
The pretrained model is a document continuer. Asked in plain text, it already knows the answer, but it never stops:
base model, plain text prompt 'Where does Ada live?' -> " Ada lives in Riverton. What is Ada's favorite color?"
Supervised fine-tuning (SFT) trains on conversations written in a chat template, so the model learns where the user's turn ends, where its answer starts, and when to stop. Here: 24 question-answer pairs about people 1–6 only. People 7–12 are held out to test whether the model generalizes.
These are the real tokens from the trained tokenizer. Note " W" + "here": the merges never learned " Where". The answer starts with " Mira", the same token the model saw mid-sentence in pretraining.
Three details that decide whether SFT works
- Loss masking. Prompt positions get label −100, which
cross_entropyignores. The model is graded only on producing the answer and<|end|>. - Leading spaces. Without the space after
<|assistant|>, the answer starts withM|ira, a token sequence the model rarely saw. A template that fights the tokenizer makes SFT much harder. - New tokens need a starting point. The template tokens never appeared in pretraining, so their embeddings are untrained.
warm_start_special_tokenscopies the embedding of a token that plays the same role:<|assistant|>starts as "?" (an answer follows),<|user|>and<|end|>as the document boundary.
$ python build_llm.py sft before SFT, chat template (held-out): Q: Where does Ada live? -> "Ada lives in Riverton. What is Ada's favorite color? Ada's f" expected 'Ada lives in Riverton.' sft step 10 loss 0.074 sft step 20 loss 0.035 sft step 30 loss 0.016 SFT: 30 steps in 0.5s after SFT (held-out people, never seen in SFT): Q: Where does Ada live? -> 'Ada lives in Riverton.' OK Q: What pet does Felix have? -> 'Felix has a parrot named Ziggy.' OK Q: What is Nora's job? -> 'Nora works as a nurse.' OK Q: What is Kenji's favorite color? -> "Kenji's favorite color is green." OK ... exact-match accuracy held-out: 0% -> 100% SFT pairs: 100% $ python build_llm.py sft --cold-start # same, without warm-starting the template tokens exact-match accuracy held-out: 0% -> 4% SFT pairs: 100%
With warm-started template tokens, 30 steps on 24 pairs make the model answer correctly and stop for all 24 held-out questions: the facts came from pretraining, and SFT only taught the format. Cold-started, the model fits the 24 training pairs perfectly but mostly answers held-out questions with a training person's name: it memorized instead of learning the format. Across three pretraining runs (1, 4 and 14 threads, which differ only in floating-point summation order) cold start scored 4%, 8% and 29% on the held-out questions; warm start scored 100% every time. This is the toy version of an observation from LIMA: almost all knowledge is learned in pretraining, and a small, clean instruction set mostly teaches the response format.
They fine-tune on hundreds of thousands of diverse conversations, often after a "mid-training" phase that already includes chat-formatted data, and then run preference optimization or reinforcement learning (InstructGPT is the classic recipe). Diversity plays the role that warm-starting plays here: with enough different prompts, memorizing answers stops being the easiest solution.
8 What changes at scale
The loop above is the real algorithm. Scaling it to billions of parameters changes the engineering around it in four places.
| This tutorial | A real pretraining run | |
|---|---|---|
| Data | 4,000 generated docs, 195K tokens, 12.6 epochs | Trillions of tokens of filtered, deduplicated web, code and books, mixed by domain; usually under one epoch. Data quality filtering is a large part of the work. |
| Size vs. tokens | 0.87M params, 2.5M tokens | Chinchilla (Hoffmann et al.) found that compute-optimal training scales params and tokens together, about 20 tokens per parameter (70B params on 1.4T tokens). Models meant for cheap inference are trained far past that point. |
| Precision | FP32 on CPU | BF16 matmuls with FP32 master weights and optimizer state (mixed precision); FP8 matmuls on Hopper/Blackwell GPUs for more throughput. Loss scaling is needed for FP16, not BF16. |
| Parallelism | one process | Mixed-precision AdamW keeps about 16 bytes per parameter (weights, grads, FP32 master + two moments; ZeRO): 112 GB for 7B, more than one 80 GB GPU. FSDP / ZeRO shards these across GPUs (14 GB each on 8 GPUs), and tensor, pipeline and sequence parallelism split the model further (PyTorch FSDP). |
| Evaluation | val loss + exact match on 24 questions | Held-out loss per domain, many benchmarks (checked for contamination with the training data), long-context and safety tests, and human or model-graded comparisons after post-training. |
# torchrun --nproc_per_node=8 train.py
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
model = FSDP(GPT(cfg).cuda()) # shard params, grads and optimizer state
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
for step in range(max_steps):
x, y = next(loader) # each rank reads a different shard of data
with torch.autocast("cuda", dtype=torch.bfloat16): # matmuls in BF16, master weights stay FP32
_, loss = model(x.cuda(), y.cuda())
loss.backward()
model.clip_grad_norm_(1.0)
opt.step(); opt.zero_grad(set_to_none=True)A useful habit is to do the 6 × params × tokens arithmetic before launching anything: a 1B-parameter model on 20B tokens needs 6 × 10⁹ × 2×10¹⁰ = 1.2×10²⁰ FLOP. At 40% utilization of a GPU with 989 TFLOP/s of dense BF16 (H100 SXM), that is about 84 GPU-hours.
✓ Review
Key takeaways
- Byte-level BPE can encode any string; its one hard requirement is an exact round trip.
- To a tokenizer, a word with a leading space is a different token. Templates must respect that.
- A modern decoder block is pre-norm RMSNorm → RoPE attention → residual, then RMSNorm → SwiGLU → residual, with tied embeddings.
- An untrained model's loss is ln V. A loss curve that does not start there, or a validation curve that rises, is the first thing to check.
- Temperature reshapes the distribution; top-k and top-p cut its tail. Greedy is deterministic.
- A KV cache trades memory for compute; test it against the full forward pass, and get RoPE positions and masks right.
- SFT mostly teaches format and stopping; the knowledge comes from pretraining.
- At scale the algorithm is the same; data, precision, sharding and evaluation become the work.
Self-check
1. Why can a byte-level BPE tokenizer encode any Unicode string, even one with characters it never saw?
Answer
2. With a vocabulary of 512, what loss should a freshly initialized model have, and why?
Answer
3. Logits [2, 1, 0]. What are the probabilities at T = 1 and at T = 0.5?
Answer
4. Probabilities [0.5, 0.3, 0.1, 0.06, 0.04] and top-p = 0.85. Which tokens survive and with what renormalized probabilities?
Answer
5. In the cached decode step, the single new query attends with is_causal=False. Why is that correct and not a leak of future tokens?
Answer
6. A model has L = 32, d = 4096, MHA with 32 heads. How big is the FP16 KV cache for one 8,192-token sequence? And with 8 KV heads (GQA)?
Answer
7. Why does the SFT loss ignore the prompt tokens?
Answer
8. Cold-start SFT reaches 100% on the 24 training pairs but only 4–29% on held-out people. What does that gap tell you, and what are two ways to close it?
Answer
9. How much memory does mixed-precision AdamW need for the model states of a 7B model, and how does FSDP on 8 GPUs change that?
Answer
10. Using 6 × params × tokens, how many FLOPs did the 600-step run take, and what throughput did the 63-second run achieve?
Answer
Hands-on exercises
- Vocabulary size.easy Run
python build_llm.py tokenizer --vocab 300and--vocab 1024. Record bytes/token for each. Self-check: the round-trip assertion still passes, and bytes/token rises with vocabulary size until merges run out. - Determinism.easy In a Python shell,
from build_llm import *, load the checkpoint withtok, model = load(argparse.Namespace(out="out"))and callgenerate(model, tok.encode("One morning,"), 40)twice. Self-check:assert a == bfor greedy; withtemperature=1.0the outputs differ unless you pass the sameseed. - Ablate RoPE.medium Make
apply_ropereturnxunchanged and retrain. Compare the validation loss at step 600 with 0.297 and look at the samples. Self-check: the KV-cache test must still pass; explain why a causal model can still learn something about order without position encodings. - Grouped-query attention.medium Add
n_kv_head = 2: project K and V to 2 heads andrepeat_interleavethem to 4 before SDPA, and store only the 2 heads inKVCache. Self-check:cmd_kvcachestill passestorch.allclose, andcaches[0].k.numel()is half of what it was. - Cold start vs. LoRA.medium Run
sft --cold-start, then try freezing everything except the embedding matrix, or adding rank-4 LoRA adapters toqkvandproj. Self-check: report held-out accuracy for each and the number of trainable parameters. - Gradient accumulation.hard Replace one batch of 32 with two micro-batches of 16 whose losses are each divided by 2. Self-check: with the same 32 sequences, the accumulated gradients match the single-batch gradients,
torch.allclose(g1, g2, atol=1e-6)for every parameter.
What next
Continue the main track: Vision Transformer (Module 2), which reuses this block on image patches. Optional side trip: Build a personal agent needs only this tutorial; the learning path suggests it after Robot Foundation Models.
↗ Resources and references
Go further: build-from-scratch courses
- Andrej Karpathy, "Let's build GPT: from scratch, in code, spelled out": a two-hour video that builds a character-level GPT step by step. Watch it if you want each line of the model motivated.
- nanoGPT: a compact, fast GPT-2 training repo; the natural next step to train a real-sized model on GPUs. minbpe and its tokenizer video cover BPE in more depth than section 2.
- nanochat: a newer full pipeline from tokenizer through pretraining, SFT and chat UI, sized for a single GPU node.
- Sebastian Raschka, LLMs-from-scratch: the code for his book, with notebooks on attention, pretraining, classification and instruction fine-tuning. Good for a slower, chapter-by-chapter path.
- Stanford CS336: Language Modeling from Scratch: a full course with assignments on tokenizers, training systems, scaling laws, data and alignment. The most thorough option.
Papers
- Attention Is All You Need (Vaswani et al., 2017)
- Neural Machine Translation of Rare Words with Subword Units (BPE; Sennrich et al., 2015)
- RoFormer: Rotary Position Embedding (Su et al., 2021)
- Root Mean Square Layer Normalization (Zhang & Sennrich, 2019)
- GLU Variants Improve Transformer (SwiGLU; Shazeer, 2020)
- Decoupled Weight Decay Regularization (AdamW; Loshchilov & Hutter, 2017)
- The Curious Case of Neural Text Degeneration (top-p; Holtzman et al., 2019)
- GQA: Grouped-Query Attention (Ainslie et al., 2023)
- LIMA: Less Is More for Alignment (Zhou et al., 2023)
- Training language models to follow instructions with human feedback (InstructGPT; Ouyang et al., 2022)
- Scaling Laws for Neural Language Models (Kaplan et al., 2020) and Training Compute-Optimal LLMs (Chinchilla; Hoffmann et al., 2022)
- Mixed Precision Training (Micikevicius et al., 2017), ZeRO (Rajbhandari et al., 2019), PyTorch FSDP (Zhao et al., 2023)