STAT 453: Introduction to Deep Learning and Generative Models (Fall 2026)
Instructor: Ben Lengerich
Course website: https://adaptinfer.org/dgm-fall-2026/
How to Submit¶
- Run every cell top to bottom before exporting, so your output isn't stale:
- Jupyter:
Kernel → Restart & Run All - Colab:
Runtime → Restart and run all
- Jupyter:
- Export this notebook to PDF or HTML:
- Colab:
File → Print → Save as PDF - Local Jupyter:
File → Save and Export Notebook As → PDF - Local Jupyter:
File → Download As → HTML
- Colab:
- Check the PDF or HTML — make sure plots aren't cut off at page edges and every cell that should have output actually shows it.
- Name the file
<netid>_hw5.pdfor<netid>_hw5.html(e.g.lengerich_hw5.pdf). - Submit the PDF or HTML on Canvas by the deadline listed on the homework page.
HW 5: A Tiny LLM, From Attention to Alignment (70 pts)¶
This assignment walks through the whole life cycle of a (very) small language model:
- Part A (35 pts) — Attention and a tiny GPT. Implement causal self-attention, multi-head attention, and a transformer block, each checked against PyTorch's built-ins. See why attention scores are scaled by $1/\sqrt{d_k}$. Train a character-level GPT on Shakespeare and sample from it with temperature and top-$k$ sampling.
- Part B (20 pts) — Parameter-efficient fine-tuning. Implement LoRA and adapt your Shakespeare model to Jane Austen, comparing it with full fine-tuning. Then merge the LoRA update back into the base weights, the way adapters are deployed.
- Part C (15 pts) — Alignment with DPO. Implement Direct Preference Optimization and use it to teach your model a preference (avoid the letter "e"). See what the strength parameter $\beta$ does, including what happens when it's too small.
How it's graded. Everything you hand in is code. Cells marked # <your code> are the parts you fill in, and each one is followed by a self-check cell built from assert statements. If it runs without an AssertionError and prints looks good!, you're on the right track (passing the self-checks does not guarantee full credit). Cells marked No modification required run experiments for you to look at; they aren't graded.
Runtime: about 5–6 minutes on a laptop CPU, or about 1–2 minutes on a Colab GPU (Runtime → Change runtime type → T4 GPU). The code uses a GPU automatically if one is available. Numbers will differ slightly between CPU and GPU.
Important!¶
Due Friday, December 4 at 11:59 PM. The homework assignment should be submitted via Canvas.
See the submission checklist above. If you need help, come to office hours (times are on the logistics page) or contact the TA or the instructor.
0) Imports and data¶
No modification required. This downloads two public-domain texts: Tiny Shakespeare (about 1.1 MB) and Jane Austen's Pride and Prejudice from Project Gutenberg (used in Part B). It cleans the Austen text and maps both texts to the same character vocabulary, the 65 characters that appear in Shakespeare.
import math
import copy
import re
import os
import urllib.request
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
%matplotlib inline
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('device:', device)
torch.manual_seed(453)
def download(urls, path):
# Try the course-site copy first, then the original source.
for url in urls:
if os.path.exists(path):
break
try:
urllib.request.urlretrieve(url, path)
except Exception as e:
print(f'could not download {url} ({e}); trying the next source')
with open(path, encoding='utf-8') as f:
return f.read()
shakespeare = download(['https://adaptinfer.org/dgm-fall-2026/assets/data/tinyshakespeare.txt',
'https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt'],
'shakespeare.txt')
austen = download(['https://adaptinfer.org/dgm-fall-2026/assets/data/pride_and_prejudice.txt',
'https://www.gutenberg.org/cache/epub/1342/pg1342.txt'], 'austen.txt')
# Keep only the novel itself, normalize typography, and drop characters Shakespeare never uses.
austen = austen.replace('\r', '')
austen = austen[austen.index('It is a truth universally'):austen.index('*** END OF THE PROJECT')]
for a, b in [('“', '"'), ('”', '"'), ('‘', "'"), ('’', "'"), ('—', '--'), ('_', '')]:
austen = austen.replace(a, b)
austen = re.sub(r'\[Illustration[^\]]*\]', '', austen)
austen = re.sub(r'\n{3,}', '\n\n', austen)
chars = sorted(set(shakespeare))
stoi = {c: i for i, c in enumerate(chars)}
austen = ''.join(c for c in austen if c in stoi)
def encode_chars(text):
return torch.tensor([stoi[c] for c in text], dtype=torch.long)
def decode_chars(ids):
return ''.join(chars[i] for i in ids)
def split(text):
data = encode_chars(text).to(device)
n = int(0.9 * len(data))
return data[:n], data[n:]
shakespeare_train, shakespeare_val = split(shakespeare)
austen_train, austen_val = split(austen)
print(f'vocab size: {len(chars)} | Shakespeare: {len(shakespeare):,} chars | Austen: {len(austen):,} chars')
print('-' * 60 + '\n' + shakespeare[:250] + '\n' + '-' * 60 + '\n' + austen[:250])
Part A: Attention and a Tiny GPT (35 pts)¶
We use a character-level model: one token per character, with the 65-character vocabulary from Section 0. Real LLMs use subword tokenizers such as byte-pair encoding, which would simply replace encode_chars; at this tiny scale, characters give more readable samples.
A.1) Causal scaled dot-product attention (10 pts)¶
Complete causal_attention(q, k, v) for tensors of shape (..., T, d) (any leading batch/head dimensions):
$$\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d}} + M\right)V, \qquad M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i\end{cases}$$
The causal mask $M$ stops position $i$ from attending to future positions $j > i$, so the model can be trained to predict every next token in parallel without cheating. mask below is True exactly where $j > i$. Use masked_fill with float('-inf').
def causal_attention(q, k, v):
T, d = q.shape[-2], q.shape[-1]
scores = # <your code>
mask = torch.triu(torch.ones(T, T, dtype=torch.bool, device=q.device), diagonal=1)
scores = # <your code>
weights = # <your code>
return # <your code>
torch.manual_seed(0)
q, k, v = torch.randn(2, 3, 7, 8), torch.randn(2, 3, 7, 8), torch.randn(2, 3, 7, 8)
out = causal_attention(q, k, v)
assert out.shape == (2, 3, 7, 8)
assert torch.allclose(out, F.scaled_dot_product_attention(q, k, v, is_causal=True), atol=1e-5), \
"doesn't match F.scaled_dot_product_attention"
k2, v2 = k.clone(), v.clone()
k2[..., 4:, :] += 10.0
v2[..., 4:, :] -= 10.0
assert torch.allclose(causal_attention(q, k2, v2)[..., :4, :], out[..., :4, :], atol=1e-5), \
"changing future keys/values must not change earlier outputs"
print('looks good!')
A.2) Why divide by $\sqrt{d}$?¶
If $q, k \in \mathbb{R}^d$ have independent entries with mean 0 and variance 1, then $q^\top k = \sum_{j=1}^d q_j k_j$ has mean 0 and variance $d$, so $q^\top k/\sqrt{d}$ has variance 1 whatever $d$ is. (This is the same variance argument that motivates Xavier/He weight initialization.)
No modification required. The cell below measures the attention weights over 64 keys for random $q, k$ at several dimensions $d$, with and without the scaling. It reports the softmax's largest weight and its entropy (the maximum possible entropy is $\log 64 \approx 4.16$).
torch.manual_seed(0)
print(f"{'d':>5s} {'var(q.k)':>10s} {'unscaled: max wt':>17s} {'entropy':>8s} {'scaled: max wt':>15s} {'entropy':>8s}")
for d in [4, 16, 64, 256, 1024]:
q, k = torch.randn(2000, 1, d), torch.randn(2000, 64, d)
s = (q @ k.transpose(-2, -1)).squeeze(1) # (2000, 64) scores
stats = []
for scores in [s, s / math.sqrt(d)]:
p = scores.softmax(-1)
stats += [p.max(-1).values.mean().item(), -(p * p.clamp_min(1e-12).log()).sum(-1).mean().item()]
print(f'{d:5d} {s.var().item():10.1f} {stats[0]:17.3f} {stats[1]:8.2f} {stats[2]:15.3f} {stats[3]:8.2f}')
What to look for (not graded). Without the scaling, the scores' variance grows like $d$, so for large $d$ the softmax becomes nearly one-hot: the largest weight approaches 1 and the entropy collapses. A saturated softmax has a vanishing Jacobian, $\partial p_i/\partial s_j = p_i(\delta_{ij} - p_j) \approx 0$, so almost no gradient reaches the queries and keys, and attention can't learn where to look. With the scaling, the attention weights look the same at every $d$.
A.3) Multi-head attention and a transformer block (10 pts)¶
Complete:
CausalSelfAttention.forward: one linear layer produces $q, k, v$ for all heads at once (shape(B, T, 3C), already split for you). Reshape each to(B, n_head, T, C // n_head), call yourcausal_attention, put the heads back together into(B, T, C), and apply the output projection. (Hint:.view(B, T, n_head, head_dim).transpose(1, 2), and the reverse:.transpose(1, 2).reshape(B, T, C).)Block.forward: a pre-LayerNorm transformer block (as in GPT-2), with two residual connections: $$x \leftarrow x + \mathrm{Attn}(\mathrm{LN}_1(x)), \qquad x \leftarrow x + \mathrm{MLP}(\mathrm{LN}_2(x))$$
class CausalSelfAttention(nn.Module):
def __init__(self, d_model, n_head):
super().__init__()
assert d_model % n_head == 0
self.n_head = n_head
self.qkv = nn.Linear(d_model, 3 * d_model)
self.proj = nn.Linear(d_model, d_model)
def forward(self, x):
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2)
q = # <your code> # (B, n_head, T, head_dim)
k = # <your code>
v = # <your code>
out = # <your code>
out = # <your code>
return self.proj(out)
class Block(nn.Module):
def __init__(self, d_model, n_head):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = CausalSelfAttention(d_model, n_head)
self.ln2 = nn.LayerNorm(d_model)
self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))
def forward(self, x):
x = # <your code>
x = # <your code>
return x
The self-check copies your layer's weights into PyTorch's nn.MultiheadAttention (which packs $W_q, W_k, W_v$ in the same order as our qkv layer) and compares the outputs.
torch.manual_seed(0)
attn = CausalSelfAttention(32, 4)
mha = nn.MultiheadAttention(32, 4, batch_first=True)
with torch.no_grad():
mha.in_proj_weight.copy_(attn.qkv.weight); mha.in_proj_bias.copy_(attn.qkv.bias)
mha.out_proj.weight.copy_(attn.proj.weight); mha.out_proj.bias.copy_(attn.proj.bias)
x = torch.randn(2, 10, 32)
future = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1)
ref, _ = mha(x, x, x, attn_mask=future, need_weights=False)
assert torch.allclose(attn(x), ref, atol=1e-5), "multi-head attention doesn't match nn.MultiheadAttention"
block = Block(32, 4)
x2 = x.clone()
x2[:, 6:] = torch.randn(2, 4, 32)
assert torch.allclose(block(x)[:, :6], block(x2)[:, :6], atol=1e-5), "the block must be causal"
with torch.no_grad():
for p in list(block.attn.proj.parameters()) + list(block.mlp[2].parameters()):
p.zero_()
assert torch.allclose(block(x), x), "with zeroed output layers, the residual connections should make the block the identity"
print('looks good!')
A.4) Sampling with temperature (8 pts)¶
Complete generate(). Starting from token ids idx of shape (B, T0), repeat max_new_tokens times:
- crop the context to the last
model.block_sizetokens (the model can't see more than that), - run the model and take the logits at the last position, divided by
temperature, - turn them into probabilities and sample one token per row (
torch.multinomial), - append it to
idx.
Leave the top_k lines alone for now; you'll implement top_k_filter in A.5.
No modification required for the GPT class: it stacks your Blocks between token + position embeddings and a final LayerNorm and output layer.
class GPT(nn.Module):
def __init__(self, vocab_size, block_size=64, d_model=128, n_head=4, n_layer=4):
super().__init__()
self.block_size = block_size
self.tok_emb = nn.Embedding(vocab_size, d_model)
self.pos_emb = nn.Embedding(block_size, d_model)
self.blocks = nn.Sequential(*[Block(d_model, n_head) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(d_model)
self.head = nn.Linear(d_model, vocab_size)
def forward(self, idx): # idx: (B, T) -> logits: (B, T, vocab_size)
pos = torch.arange(idx.shape[1], device=idx.device)
return self.head(self.ln_f(self.blocks(self.tok_emb(idx) + self.pos_emb(pos))))
@torch.no_grad()
def generate(model, idx, max_new_tokens, temperature=1.0, top_k=None):
was_training = model.training
model.eval()
for _ in range(max_new_tokens):
context = # <your code>
logits = # <your code>
if top_k is not None:
logits = top_k_filter(logits, top_k)
probs = # <your code>
next_id = # <your code>
idx = # <your code>
model.train(was_training)
return idx
torch.manual_seed(0)
tiny = GPT(len(chars), block_size=16, d_model=32, n_head=4, n_layer=2).to(device)
start = encode_chars('ROMEO:\n').to(device)[None]
out = generate(tiny, start, 30)
assert out.shape == (1, 37) and torch.equal(out[:, :7], start), "should append exactly max_new_tokens tokens"
greedy = start.clone()
with torch.no_grad():
for _ in range(30):
greedy = torch.cat([greedy, tiny(greedy[:, -16:])[:, -1].argmax(-1, keepdim=True)], dim=1)
assert torch.equal(generate(tiny, start, 30, temperature=1e-4), greedy), \
"temperature -> 0 should give greedy decoding (also check that you crop to block_size)"
print('looks good!')
No modification required. Now train the GPT on Shakespeare: 4 layers, 4 heads, width 128, context of 64 characters, about 0.8M parameters, with AdamW. It takes about 2 minutes on a CPU or 20 seconds on a GPU.
The loss is in nats (natural log). Dividing by $\ln 2$ gives bits per character, and $e^{\text{loss}}$ is the perplexity: the model is as uncertain as a uniform choice among that many characters. A model that guessed uniformly over 65 characters would have loss $\ln 65 \approx 4.17$ nats $= \log_2 65 \approx 6.02$ bits, perplexity 65.
BLOCK = 64
def get_batch(data, batch_size=32):
ix = torch.randint(len(data) - BLOCK - 1, (batch_size,))
x = torch.stack([data[i:i + BLOCK] for i in ix])
y = torch.stack([data[i + 1:i + BLOCK + 1] for i in ix])
return x, y
@torch.no_grad()
def estimate_loss(model, data, n_batches=25):
was_training = model.training
model.eval()
g = torch.Generator().manual_seed(0) # the same evaluation batches every time
losses = []
for _ in range(n_batches):
ix = torch.randint(len(data) - BLOCK - 1, (32,), generator=g)
x = torch.stack([data[i:i + BLOCK] for i in ix])
y = torch.stack([data[i + 1:i + BLOCK + 1] for i in ix])
losses.append(F.cross_entropy(model(x).flatten(0, 1), y.flatten()).item())
model.train(was_training)
return sum(losses) / len(losses)
def train_lm(model, data, steps, lr, params=None, log_every=None):
opt = torch.optim.AdamW(params if params is not None else model.parameters(), lr=lr)
model.train()
for step in range(1, steps + 1):
x, y = get_batch(data)
loss = F.cross_entropy(model(x).flatten(0, 1), y.flatten())
opt.zero_grad()
loss.backward()
opt.step()
if log_every and step % log_every == 0:
print(f'step {step:5d}: val loss {estimate_loss(model, shakespeare_val):.3f}')
torch.manual_seed(453)
gpt = GPT(len(chars), block_size=BLOCK).to(device)
print(f'{sum(p.numel() for p in gpt.parameters()):,} parameters | initial val loss {estimate_loss(gpt, shakespeare_val):.3f}')
train_lm(gpt, shakespeare_train, steps=2500, lr=1e-3, log_every=500)
val = estimate_loss(gpt, shakespeare_val)
print(f'final val loss {val:.3f} nats/char = {val / math.log(2):.3f} bits/char | perplexity {math.exp(val):.2f} (uniform guessing: 65)')
A.5) Top-$k$ sampling (7 pts)¶
Even a well-trained model puts a little probability on thousands of bad tokens, and sampling occasionally picks one. Top-$k$ sampling keeps only the $k$ most likely tokens at each step and renormalizes over them.
Complete top_k_filter(logits, k): for logits of shape (B, V), keep the $k$ largest logits in each row and set all the others to float('-inf') (so the softmax gives them probability 0). If k is None or at least V, return the logits unchanged. (Hint: torch.topk(logits, k, dim=-1).values gives each row's $k$ largest values, in descending order.) generate(..., top_k=k) already calls your function.
def top_k_filter(logits, k):
if k is None or k >= logits.shape[-1]:
return logits
kth = # <your code> # (B, 1): each row's k-th largest logit
return # <your code>
torch.manual_seed(0)
logits = torch.randn(4, 65)
for k in [1, 3, 10]:
out = top_k_filter(logits, k)
kept = torch.isfinite(out)
assert out.shape == logits.shape and torch.all(kept.sum(-1) == k), f"k={k}: each row should keep exactly k logits"
top = torch.zeros_like(kept).scatter_(1, logits.topk(k, dim=-1).indices, True)
assert torch.equal(kept, top), f"k={k}: the kept logits should be the k largest in each row"
assert torch.equal(out[kept], logits[kept]), "kept logits should be unchanged"
assert torch.equal(top_k_filter(logits, None), logits) and torch.equal(top_k_filter(logits, 65), logits)
samples = torch.multinomial(torch.softmax(top_k_filter(logits, 3), dim=-1), 2000, replacement=True)
assert all(set(samples[i].tolist()) <= set(logits[i].topk(3).indices.tolist()) for i in range(4)), \
"sampling should only ever produce one of the top-k tokens"
assert torch.equal(generate(tiny, start, 30, top_k=1), greedy), "top_k=1 should give greedy decoding"
print('looks good!')
No modification required. Sample from your trained model at three temperatures, and once more at the highest temperature with top-$k$ sampling.
for temperature, top_k in [(0.5, None), (1.0, None), (1.5, None), (1.5, 5)]:
torch.manual_seed(1)
out = generate(gpt, encode_chars('ROMEO:\n').to(device)[None], 250, temperature=temperature, top_k=top_k)
print(f'===== temperature = {temperature}, top_k = {top_k} =====\n{decode_chars(out[0].tolist())}\n')
What to look for (not graded). Dividing the logits by $\tau$ gives $p_i \propto \exp(z_i/\tau)$. As $\tau \to 0$ all the probability goes to the most likely token (greedy decoding), and as $\tau \to \infty$ the distribution becomes uniform. Low temperature gives safe, repetitive text; high temperature gives misspellings and broken format. Top-$k$ cuts off the long tail of unlikely characters, so even at $\tau = 1.5$ the text stays mostly word-like. The model gets spelling, line breaks, and the NAME: format right but not meaning: it has about 0.8M parameters, saw about 1M characters, and sees only 64 characters of context. (Attention compares every position with every earlier one, so its cost grows like $T^2$ in the context length. In exchange, all next-token predictions in a sequence are trained in parallel, unlike an RNN's step-by-step updates.)
Part B: Fine-Tuning with LoRA (20 pts)¶
Now adapt the Shakespeare model to write like Jane Austen. Full fine-tuning updates all the weights. LoRA (Hu et al., 2021) freezes the pretrained weight $W \in \mathbb{R}^{d_\text{out}\times d_\text{in}}$ and learns a low-rank correction instead:
$$h = W x + \frac{\alpha}{r}\, B A\, x, \qquad A \in \mathbb{R}^{r \times d_\text{in}}, \;\; B \in \mathbb{R}^{d_\text{out} \times r}, \;\; r \ll \min(d_\text{in}, d_\text{out}).$$
B.1) Implement LoRA (11 pts)¶
Complete:
LoRALinear.__init__: create the trainable parametersA, initialized from $\mathcal{N}(0, 1/d_\text{in})$, andB, initialized to zeros. Create them on the same device as the base layer (device=base.weight.device).LoRALinear.forward: the base layer's output plusself.scale * x A^T B^T.add_lora(model, r, alpha): freeze every existing parameter of the model (requires_grad_(False)), then replace each block's attentionqkvandprojlayers withLoRALinearwrappers around them.
class LoRALinear(nn.Module):
def __init__(self, base, r=4, alpha=8):
super().__init__()
self.base = base
self.scale = alpha / r
self.A = # <your code>
self.B = # <your code>
def forward(self, x):
return # <your code>
def add_lora(model, r=4, alpha=8):
for p in model.parameters():
p.requires_grad_(False)
for block in model.blocks:
block.attn.qkv = # <your code>
block.attn.proj = # <your code>
return model
torch.manual_seed(0)
base = nn.Linear(20, 30)
lora = LoRALinear(base, r=4)
x = torch.randn(5, 20)
assert torch.allclose(lora(x), base(x)), "at initialization LoRA should not change the layer's output"
assert lora.A.shape == (4, 20) and lora.B.shape == (30, 4)
with torch.no_grad():
lora.B.normal_()
assert torch.allclose(lora(x), base(x) + 2.0 * x @ lora.A.T @ lora.B.T, atol=1e-5), "forward should add scale * x A^T B^T"
test_model = add_lora(copy.deepcopy(gpt), r=4)
trainable = [n for n, p in test_model.named_parameters() if p.requires_grad]
assert all(n.endswith('.A') or n.endswith('.B') for n in trainable) and len(trainable) == 4 * 2 * 2, \
"only the LoRA A and B matrices (2 per wrapped layer, 2 layers per block, 4 blocks) should be trainable"
xb, _ = get_batch(shakespeare_val)
with torch.no_grad():
assert torch.allclose(test_model(xb), gpt(xb), atol=1e-5), "adding LoRA should not change the model's outputs"
print('looks good!')
No modification required. Fine-tune two copies of your Shakespeare model on Austen for 400 steps: one with full fine-tuning and one with LoRA ($r = 4$). For each, report the number of trainable parameters, the validation loss on Austen (did it learn the new style?) and on Shakespeare (how much of the old style did it forget?), and a sample. About 1 minute on a CPU.
results = {'before fine-tuning': (gpt, 0)}
for name in ['full fine-tuning', 'LoRA (r=4)']:
torch.manual_seed(453)
model = copy.deepcopy(gpt)
if name.startswith('LoRA'):
add_lora(model, r=4)
params = [p for p in model.parameters() if p.requires_grad]
train_lm(model, austen_train, steps=400, lr=1e-3, params=params)
results[name] = (model, sum(p.numel() for p in params))
print(f"{'':20s} {'trainable params':>17s} {'Austen val loss':>16s} {'Shakespeare val loss':>21s}")
for name, (model, n_params) in results.items():
print(f'{name:20s} {n_params:17,d} {estimate_loss(model, austen_val):16.3f} {estimate_loss(model, shakespeare_val):21.3f}')
for name, (model, _) in results.items():
torch.manual_seed(2)
print(f'\n===== {name} =====\n' + decode_chars(generate(model, encode_chars('\n').to(device)[None], 250, temperature=0.8)[0].tolist()))
What to look for (not graded). Full fine-tuning gets the lowest Austen loss but trains every parameter, and it forgets the most Shakespeare. LoRA trains about 1.5% of the parameters ($r(d_\text{in} + d_\text{out})$ per wrapped layer instead of $d_\text{in} d_\text{out}$), still gets much of the improvement, and forgets less, because the original weights stay frozen and only a rank-$r$ update to the attention layers is learned. $B$ starts at zero so training starts exactly at the pretrained model. $A$ starts random because if both were zero, both gradients ($\partial L/\partial B \propto (Ax)^\top$ and $\partial L/\partial A \propto B^\top$) would be zero forever.
B.2) Merging LoRA for deployment (9 pts)¶
A LoRA layer computes $Wx + \frac{\alpha}{r} BAx = \big(W + \frac{\alpha}{r}BA\big)x$. So once fine-tuning is done, the update can be folded into the base weight and the wrapper thrown away. The merged model is an ordinary GPT with exactly the original architecture and no extra inference cost. A service with many customers can instead keep one base model in memory and swap in each customer's small $A, B$ matrices.
Complete merge_lora(model): for every LoRALinear in the blocks' attention layers, add scale * B @ A to its base layer's weight (inside torch.no_grad()), then replace the wrapper with the base nn.Linear itself (setattr(block.attn, name, layer.base)).
def merge_lora(model):
for block in model.blocks:
for name in ['qkv', 'proj']:
layer = getattr(block.attn, name)
if isinstance(layer, LoRALinear):
# <your code>
return model
lora_model = results['LoRA (r=4)'][0]
xb, _ = get_batch(austen_val)
with torch.no_grad():
before = lora_model(xb)
merged = merge_lora(copy.deepcopy(lora_model))
with torch.no_grad():
after = merged(xb)
assert not any(isinstance(m, LoRALinear) for m in merged.modules()), "no LoRALinear wrappers should remain"
assert sum(p.numel() for p in merged.parameters()) == sum(p.numel() for p in gpt.parameters()), \
"the merged model should have exactly the original GPT's parameters"
assert torch.allclose(before, after, atol=1e-4), "merging should not change the model's outputs"
assert not torch.allclose(merged.blocks[0].attn.qkv.weight, gpt.blocks[0].attn.qkv.weight), \
"the fine-tuned update should end up in the base weights"
print(f'merged model: {sum(p.numel() for p in merged.parameters()):,} parameters | '
f'Austen val loss {estimate_loss(merged, austen_val):.3f} (LoRA model: {estimate_loss(lora_model, austen_val):.3f})')
print(f'the adapter alone is {results["LoRA (r=4)"][1]:,} numbers to store per fine-tuned version')
print('looks good!')
Part C: Alignment with DPO (15 pts)¶
Direct Preference Optimization (Rafailov et al., 2023) fine-tunes a policy $\pi_\theta$ from pairs $(x, y_w, y_l)$, where a human (or a rule) preferred completion $y_w$ over $y_l$ for prompt $x$. It needs no reward model and no RL loop. It keeps a frozen copy of the starting model, the reference $\pi_\text{ref}$, and minimizes
$$\mathcal{L}_\text{DPO} = -\,\mathbb{E}\left[\log \sigma\!\Big(\beta\Big[\underbrace{\log\tfrac{\pi_\theta(y_w\mid x)}{\pi_\text{ref}(y_w\mid x)}}_{\text{chosen log-ratio}} - \underbrace{\log\tfrac{\pi_\theta(y_l\mid x)}{\pi_\text{ref}(y_l\mid x)}}_{\text{rejected log-ratio}}\Big]\Big)\right].$$
This is the exact solution of the RLHF objective "maximize reward $-\;\beta \cdot \mathrm{KL}(\pi_\theta \,\|\, \pi_\text{ref})$", rewritten so the reward is implicit.
Our "human" is a simple rule: prefer the completion that uses the letter e less often (a lipogram). Our Shakespeare model writes e about 8% of the time.
C.1) Sequence log-probabilities (7 pts)¶
Complete sequence_logprob(model, prompt, completion): the total log-probability $\log \pi(y \mid x) = \sum_j \log \pi(y_j \mid x, y_{<j})$ of each completion (shape (B, L)) given its prompt (shape (B, P)). The model is run once on the concatenation. Logits at position $j$ predict token $j+1$, so keep only the positions that predict completion tokens, take log_softmax, and pick out each actual completion token's log-probability with torch.gather. Return shape (B,).
def sequence_logprob(model, prompt, completion):
x = torch.cat([prompt, completion], dim=1)
logits = model(x[:, :-1]) # position j predicts token j + 1
logits = # <your code> # positions that predict the completion tokens
logp = # <your code>
return # <your code>
torch.manual_seed(0)
prompt, completion = shakespeare_val[:20][None].repeat(2, 1), shakespeare_val[20:30][None].repeat(2, 1)
completion[1, 3] = stoi['z']
with torch.no_grad():
lp = sequence_logprob(gpt, prompt, completion)
ref = torch.zeros(2, device=device)
for j in range(completion.shape[1]): # one token at a time, the slow way
ctx = torch.cat([prompt, completion[:, :j]], dim=1)
ref += gpt(ctx)[:, -1].log_softmax(-1).gather(1, completion[:, j:j + 1]).squeeze(1)
assert lp.shape == (2,) and torch.allclose(lp, ref, atol=1e-3), "sequence_logprob doesn't match the token-by-token computation"
assert lp[1] < lp[0], "an unusual character should make the completion less likely"
print('looks good!')
C.2) The DPO loss (8 pts)¶
Complete dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected, beta): the formula above, averaged over the batch. The inputs are sequence log-probabilities of shape (B,). (Use F.logsigmoid for numerical stability.)
def dpo_loss(pi_chosen, pi_rejected, ref_chosen, ref_rejected, beta):
margin = # <your code>
return # <your code>
torch.manual_seed(0)
pc, pr_, rc, rr = (torch.randn(8, requires_grad=True) for _ in range(4))
for beta in [0.1, 0.5, 2.0]:
loss = dpo_loss(pc, pr_, rc, rr, beta)
# the same objective written as a binary cross-entropy: "chosen beats rejected" with logit = beta * (implicit reward gap)
logit = beta * ((pc - rc) - (pr_ - rr))
ref = F.binary_cross_entropy_with_logits(logit, torch.ones_like(logit))
assert loss.dim() == 0 and torch.allclose(loss, ref, atol=1e-6), f"beta={beta}: dpo_loss doesn't match"
z = torch.zeros(3)
assert torch.allclose(dpo_loss(z, z, z, z, beta=0.5), torch.tensor(math.log(2))), "policy == reference should give log 2"
assert torch.isfinite(dpo_loss(torch.tensor([-500.0]), torch.tensor([500.0]), z[:1], z[:1], beta=1.0)), \
"use F.logsigmoid so large margins don't overflow"
loss = dpo_loss(pc, pr_, rc, rr, 1.0)
loss.backward()
assert torch.all(pc.grad <= 0) and torch.all(pr_.grad >= 0), \
"minimizing the loss should raise the chosen log-probs and lower the rejected ones"
print('looks good!')
No modification required. First, build a preference dataset: take 1,024 prompts (32 characters each) from Shakespeare's validation text, sample two 31-character completions per prompt from the Shakespeare model, and label the one with fewer e's as chosen (ties are dropped). Then run DPO from the Shakespeare model with three values of $\beta$. For each, report how often samples use e, the Shakespeare validation loss (how far it drifted from the original model), and a few samples. About 2 minutes on a CPU.
P, L = 32, 31 # prompt and completion lengths (P + L - 1 <= BLOCK)
E = stoi['e']
def e_rate(completions):
return (completions == E).float().mean().item()
torch.manual_seed(453)
ix = torch.randint(len(shakespeare_val) - P, (1024,))
prompts = torch.stack([shakespeare_val[i:i + P] for i in ix])
comp_a = generate(gpt, prompts, L)[:, P:]
comp_b = generate(gpt, prompts, L)[:, P:]
n_a, n_b = (comp_a == E).sum(1), (comp_b == E).sum(1)
keep = n_a != n_b
a_wins = (n_a < n_b)[:, None]
pref_prompts = prompts[keep]
chosen = torch.where(a_wins, comp_a, comp_b)[keep]
rejected = torch.where(a_wins, comp_b, comp_a)[keep]
print(f'{len(pref_prompts)} preference pairs | e-rate: chosen {e_rate(chosen):.3f}, rejected {e_rate(rejected):.3f}')
print('example prompt: ', repr(decode_chars(pref_prompts[0].tolist())))
print(' chosen: ', repr(decode_chars(chosen[0].tolist())))
print(' rejected: ', repr(decode_chars(rejected[0].tolist())))
def train_dpo(beta, steps=250, batch_size=32, lr=1e-4):
torch.manual_seed(453)
policy, reference = copy.deepcopy(gpt), copy.deepcopy(gpt).eval()
for p in reference.parameters():
p.requires_grad_(False)
opt = torch.optim.AdamW(policy.parameters(), lr=lr)
policy.train()
hist = {'chosen': [], 'rejected': [], 'loss': []}
for _ in range(steps):
b = torch.randint(len(pref_prompts), (batch_size,))
with torch.no_grad():
ref_c = sequence_logprob(reference, pref_prompts[b], chosen[b])
ref_r = sequence_logprob(reference, pref_prompts[b], rejected[b])
pi_c = sequence_logprob(policy, pref_prompts[b], chosen[b])
pi_r = sequence_logprob(policy, pref_prompts[b], rejected[b])
loss = dpo_loss(pi_c, pi_r, ref_c, ref_r, beta)
opt.zero_grad()
loss.backward()
opt.step()
hist['chosen'].append((pi_c - ref_c).mean().item()) # log-ratio vs. the reference, averaged over the batch
hist['rejected'].append((pi_r - ref_r).mean().item())
hist['loss'].append(loss.item())
return policy, hist
test_prompts = torch.stack([shakespeare_val[i:i + P] for i in torch.randint(len(shakespeare_val) - P, (256,),
generator=torch.Generator().manual_seed(1))])
def report(name, model):
torch.manual_seed(3)
samples = generate(model, test_prompts, L)[:, P:]
print(f'{name:22s} e-rate {e_rate(samples):.3f} | Shakespeare val loss {estimate_loss(model, shakespeare_val):.3f}')
for s in samples[:3]:
print(' ', repr(decode_chars(s.tolist())))
report('reference (no DPO)', gpt)
histories = {}
for beta in [0.1, 0.5, 2.0]:
policy, histories[beta] = train_dpo(beta)
report(f'DPO, beta = {beta}', policy)
What to look for (not graded). All three runs cut the e-rate, and the smaller $\beta$, the more. At the smallest $\beta$ the text degenerates into capital-letter strings and non-words and the Shakespeare validation loss jumps: reward hacking. DPO's optimal policy is $\pi^*(y\mid x) \propto \pi_\text{ref}(y\mid x)\exp(r(x,y)/\beta)$, so a small $\beta$ is a weak leash. The reward only measures "fewer e's", and the cheapest way to get that is to abandon English. A larger $\beta$ keeps the model closer to the reference and fluent. The reference model is what anchors the loss: without it, the loss could be driven down forever by pushing rejected completions' probabilities toward 0. Unlike RLHF with PPO, this DPO run only ever sees pairs sampled from the original model, never from the policy as it changes.
No modification required. The training curves for $\beta = 0.5$. The left panel shows the average log-ratio $\log \pi_\theta(y \mid x) - \log \pi_\text{ref}(y \mid x)$ for the chosen and the rejected completions in each batch; the right panel shows the DPO loss.
def smooth(v, k=15):
v = torch.tensor(v)
return torch.nn.functional.avg_pool1d(v[None, None], k, stride=1, padding=k // 2, count_include_pad=False)[0, 0][:len(v)]
h = histories[0.5]
fig, axes = plt.subplots(1, 2, figsize=(11, 3.6))
axes[0].plot(smooth(h['chosen']), label='chosen', color='C0')
axes[0].plot(smooth(h['rejected']), label='rejected', color='C3')
axes[0].axhline(0, color='gray', lw=0.8)
axes[0].set(xlabel='step', ylabel='log-ratio vs. reference', title='log-ratios')
axes[0].legend(frameon=False)
axes[1].plot(h['loss'], color='0.8', lw=0.8)
axes[1].plot(smooth(h['loss']), color='k')
axes[1].axhline(math.log(2), color='gray', ls='--', lw=0.8)
axes[1].set(xlabel='step', ylabel='DPO loss', title='loss (gray: raw; dashed: log 2)')
plt.tight_layout()
plt.show()
print(f"last 25 steps: chosen {sum(h['chosen'][-25:]) / 25:+.2f}, rejected {sum(h['rejected'][-25:]) / 25:+.2f}, "
f"margin {sum(c - r for c, r in zip(h['chosen'][-25:], h['rejected'][-25:])) / 25:+.2f}, loss {sum(h['loss'][-25:]) / 25:.3f}")
What to look for (not graded). The loss starts at exactly $\log 2$, because $\pi_\theta = \pi_\text{ref}$ makes both log-ratios 0, and falls toward 0. But both log-ratios fall: by the end, the policy finds even the chosen completions less likely than the reference did. That is not a bug. The loss depends only on the margin $\beta\,[(\log\pi_\theta - \log\pi_\text{ref})(y_w) - (\log\pi_\theta - \log\pi_\text{ref})(y_l)]$, and the rejected completions fall much faster, so the margin grows. The probability that leaves both goes to other completions, here ones with even fewer e's than the chosen ones. When you read DPO curves, look at the margin, not at whether the chosen log-probability went up.
Attribution: Ben Lengerich