Lesson 6.1 — Large Language Models and Model Adaptation
Previous lesson · 5.6 Conditional Generation & Guidance · Course overview · Next lesson · 6.2 Vision-Language Models
Foundation Models and Model Scale
Lesson 4.4 trained a language model from scratch. Here, the starting point is a pretrained model whose representations can be reused across tasks. Pretraining typically learns from the token sequence itself. Post-training can use demonstrations, preferences, or rewards to change how the model responds.
Take a decoder-only Transformer with vocabulary size , width , and layers. Assume full multi-head attention, an ordinary feedforward layer of width , two RMSNorm weights per block, no linear biases, and a tied input and output embedding shared across the model.
The term counts the Q, K, V, and output projections. The term counts the two feedforward matrices. The final counts the last normalization. Training cost for a dense model can be estimated using the multiply-add convention in which a multiply and an add count as two FLOPs.
This estimate covers the leading linear-layer work in the forward and backward passes. It omits the context-dependent attention operations, optimizer work, and hardware efficiency. Architectures using grouped or multi-query attention and gated feedforward layers require different parameter counts.
Work out a parameter and training-compute budget
Model Parameter & Compute Calculator
Pretraining, SFT, and Post-training
Pretraining usually supervises each valid next token in a document. In supervised fine-tuning (SFT), the prompt and demonstrated response form a training sequence. This example masks prompt targets while keeping the prompt visible to the model. Other SFT implementations can choose different supervision.
The loss averages over targets with and assumes at least one selected target. Causal masking constrains which tokens a query can read. Padding masks remove padded positions from attention. The loss mask decides which target errors enter the objective. In the toy sequence, only the modifier and end token are supervised during SFT.
Preference optimization is a separate choice of training objective. RLHF can train a reward model and optimize a policy against it. DPO uses preference pairs and log-probability ratios relative to a reference policy. Any such objective still leaves a separate choice of which parameters to train.
Pretraining vs. SFT Dataflow
| Position | Input token | Next target | Pretrain loss | SFT loss |
|---|---|---|---|---|
| 0 | BOS | robot | Included | Masked |
| 1 | robot | move | Included | Masked |
| 2 | move | left | Included | Masked |
| 3 | left | fast | Included | Included |
| 4 | fast | EOS | Included | Included |
Frozen Parameters and Gradient Flow
Full fine-tuning updates every weight. Head-only tuning updates the output head. Parameter-efficient fine-tuning trains a subset of weights or adds adapter parameters. A frozen layer can still pass gradients to trainable components earlier in the graph.
The derivative with respect to the input depends on the value of the frozen matrix. Its parameter gradient can be skipped when the weight is frozen. Wrapping a frozen layer in a no-gradient block cuts the input gradient too, which is appropriate for fixed feature extraction only when earlier computation needs no gradient.
Parameter Freeze & Gradient Inspector
| Operation | Selected case |
|---|---|
| First linear activation h | 1.4000 |
LoRA and Low-rank Weight Updates
Start with one projection in a pretrained network. Pass four different inputs through it. Each open circle below marks an original output in the two-dimensional output space. The arrow from that circle is the correction made by a rank-one adapter.

A and B move in opposite directions along the same line. C stays put. The right panel lays the corrections along a common axis so you can see what varies across inputs. For rank one, reads one scalar from the input. The column of supplies the output direction, and the scalar sets the signed distance up to a fixed scale. An input with takes the base path alone.
For rank , the columns of supply up to independent correction directions. Every input can use a different mixture of them. The low-rank restriction applies to the change . The original outputs can still span the full output space.
LoRA represents a trainable update to a frozen matrix with a pair of smaller matrices. Use the output-by-input weight convention and a column-vector input.
This geometry also explains the first training step. Write for the upstream gradient. If starts at zero, changing the scalar read by cannot yet move the output. A nonzero can still teach which way to move. Once has learned a direction, a gradient can reach through it.
A random and zero leave the initial output unchanged. With this initialization, the first gradient for is zero and can change. Initializing both matrices to zero makes both gradients zero. The update has rank at most and uses trainable parameters. The combined weight can retain full rank.
An adapter can be merged into the base weight for inference. Before merging into quantized weights, account for rounding and the desired way of switching adapters. The teaching code stores transposed weights and uses row vectors; its effective weight is .
Inspect the two factors and their first gradients
LoRA Matrix Factorization Explorer
| Row | 0 | 1 | 2 |
|---|---|---|---|
| 0 | 0.8000 | 0.6000 | -0.5000 |
| Row | 0 |
|---|---|
| 0 | -0.2200 |
LoRA Across Transformer Layers
Use the original Gemma v1 2B configuration as a shape example. It has 18 layers, hidden width 2048, eight query heads, one key/value head, and head dimension 256. This is the 2024 Gemma model. The lab exposes how the chosen projection and layer affect adapter size.
| Projection | Weight (out × in) | Output shape | r=16 adapter params |
|---|---|---|---|
| Q | 2048×2048 | B,T,8,256 | 65536 |
| K | 256×2048 | B,T,1,256 | 36864 |
| V | 256×2048 | B,T,1,256 | 36864 |
| O | 2048×2048 | B,T,2048 | 65536 |
The query and key projections affect attention scores. The value projection changes what those weights aggregate. The output projection maps the combined heads back into the residual stream. Since later blocks receive the earlier blocks' new outputs, the effect of modifying several blocks composes through the network.
The Google implementation cited below uses a fused projection with output width . Split by the head configuration and apply RoPE to queries and keys. The separate-projection implementation exposes Q, K, and V as distinct modules. A rank- update on the fused matrix shares its input-side factor across slices. Separate adapters can choose different factors or target just Q and V.
At rank 16, adapting Q and V across all 18 layers adds 1,843,200 parameters. Adapting all four projections adds 3,686,400. The runnable two-layer experiment uses ordinary multi-head attention.
Multi-layer Q/K/V/O LoRA Dataflow
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 0 | -0.7729 | 1.9082 | 2.4871 | 1.0454 | -0.8965 | -0.5953 | -1.1299 | 0.4393 |
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 0 | -0.7729 | 1.9082 | 2.4871 | 1.0454 | -0.8965 | -0.5953 | -1.1299 | 0.4393 |
| Row | 0 | 1 |
|---|---|---|
| 0 | -1.3716 | -0.8799 |
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 0 | -1.5729 | 1.1067 | -1.4565 | -1.4633 | -0.6734 | -0.9024 | -0.9998 | 1.1583 |
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 0 | -2.3458 | 3.0149 | 1.0306 | -0.4179 | -1.5699 | -1.4977 | -2.1297 | 1.5977 |
| Row | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 | 1.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| 1 | 0.26 | 0.74 | 0.00 | 0.00 | 0.00 |
| 2 | 0.00 | 0.00 | 1.00 | 0.00 | 0.00 |
| 3 | 0.00 | 0.00 | 0.32 | 0.68 | 0.00 |
| 4 | 0.00 | 0.00 | 0.00 | 0.13 | 0.87 |
| Projection | W (out × in) | A (r × in) | B (out × r) |
|---|---|---|---|
| Q | 2048 × 2048 | r × 2048 | 2048 × r |
| K, V | 256 × 2048 | r × 2048 | 256 × r |
| O | 2048 × 2048 | r × 2048 | 2048 × r |
PEFT, Quantization, and Training Memory
LoRA reduces memory for trainable parameters, gradients, and optimizer states while retaining the frozen weights. QLoRA stores a quantized base, dequantizes it for computation, and trains higher-precision adapters. Its original design combines NF4, double quantization, and paged optimizers.
The lab counts the chosen Gemma attention weights and adapters, using two FP32 Adam moments per trainable parameter. It assumes BF16 adapter weights and gradients. It excludes other model layers, activations, quantization metadata and temporary buffers, master weights, and allocator overhead. A device budget comes from measuring peak memory for the complete run.
LoRA / QLoRA Memory Calculator
| Storage | Size |
|---|---|
| Frozen attention weights | 81.00 MiB |
| BF16 adapter weights | 7.03 MiB |
| FP32 Adam moments | 28.13 MiB |
KV Cache and Autoregressive Inference
Prefill processes the prompt and stores each layer's keys and values. A decode step computes projections for the new token. Its query reads prior keys and values, so past queries need not be cached. The number of scores per query head grows with the attended context length.
Here counts bytes per scalar. At batch one, context length 2048, and BF16, the original Gemma v1 2B configuration gives 36 MiB for the ideal cache contents. Cache validity also depends on the prompt, positions, masking, and the model weights used to produce the keys and values. The lab compares cached output against a full causal forward pass using the teaching model.
KV Cache & Autoregressive Inference
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| BOS | 2.0042 | -1.9204 | -1.9380 | 0.4588 | 0.5752 | 0.9490 | 0.9763 | -1.1440 |
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| BOS | 2.0580 | 0.5066 | 0.5957 | 0.0976 | -0.4787 | -0.1268 | -0.7928 | -1.3668 |
Engineering Experiment · Adapting a Two-layer GPT
The pre-norm model uses width 8, two attention heads, two layers, FFN width 16, and a vocabulary of 15. It has fixed sinusoidal positions, GELU, affine LayerNorms, and an output bias. Its 1343 base parameters start from a shared checkpoint pretrained for 160 Adam updates on six general-domain sequences.
A robot-domain token introduces a reversed modifier rule. Adapt on four combinations for 80 Adam updates at learning rate 0.02 and hold out two combinations. Old-domain accuracy measures retention on the original six training sequences. For zero-based input indices, the suffix loss reads positions 3 and 4, which predict the modifier and end token.
The default adapters have rank two and scale one. One strategy targets Q and V in both layers, and the other targets all four projections. Compare these with frozen, output-head-only, and full updates. The browser begins from the shared pretrained checkpoint and computes adaptation checkpoints from its own updates.
Live Tiny GPT Fine-tuning
PyTorch benchmark · Seed 3
| Method | Trainable | Train suffix CE | Held-out suffix CE | Held-out modifier acc. | Old modifier acc. |
|---|---|---|---|---|---|
| frozen | 0 | 4.034371 | 3.349166 | 0.00% | 100.00% |
| head | 135 | 0.001557 | 0.172454 | 100.00% | 0.00% |
| full | 1343 | 0.000967 | 2.922349 | 0.00% | 33.33% |
| lora_qv | 128 | 0.011942 | 3.953012 | 0.00% | 16.67% |
| lora_all | 256 | 0.002972 | 2.922498 | 0.00% | 16.67% |
Head-only adaptation predicts both held-out modifiers and loses the original rule on the six old training combinations. Full adaptation and both LoRA configurations fit the four new training combinations but miss the two held-out modifiers. Freezing the LoRA base keeps its stored weights fixed while changing the effective function. These outcomes are for this small domain reversal and one seed.
Reproducible PyTorch implementation
The script uses CPU float64, trains the shared base and all adaptation variants, and checks frozen weight changes and merge behavior.
import math, json, copy
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(1)
torch.set_default_dtype(torch.float64)
D,H,V=8,2,15
VOC=['BOS','EOS','move','pick','place','left','right','red','blue','slow','fast','gentle','firm','general','robot']
def data(domain):
return torch.tensor([[0,domain,2+v,(5 if v==0 else 7)+o,(9 if v==0 else 11)+(o if v!=2 else 1-o if domain==13 else o),1] for v in range(3) for o in range(2)],dtype=torch.long)
# robot domain flips modifier for move/pick/place relative to general
OLD=data(13); NEW=OLD.clone();NEW[:,1]=14;NEW[:,4]=torch.where(NEW[:,4]%2==1,NEW[:,4]+1,NEW[:,4]-1)
TRAIN=NEW[[0,1,2,4]]; HOLD=NEW[[3,5]]
def pos(T):
i=torch.arange(T)[:,None];j=torch.arange(D)[None,:];x=i/10000**(2*(j//2)/D);return torch.where(j%2==0,x.sin(),x.cos())
class GPT(nn.Module):
def __init__(self,seed=3):
super().__init__(); g=torch.Generator().manual_seed(seed);self.p=nn.ParameterDict();self.adapters=nn.ParameterDict();self.rank=0
def put(n,shape):
x=(torch.rand(shape,generator=g)-.5)*.8
if n.endswith(('g1','g2')):x=torch.ones(shape)
if n.endswith(('b1','b2','rb')):x=torch.zeros(shape)
self.p[n]=nn.Parameter(x)
put('E',(V,D));put('R',(D,V));put('rb',(1,V))
for l in range(2):
for n,shape in [('Q',(D,D)),('K',(D,D)),('V',(D,D)),('O',(D,D)),('U',(D,2*D)),('W',(2*D,D)),('g1',(1,D)),('b1',(1,D)),('g2',(1,D)),('b2',(1,D))]:put(f'{l}{n}',shape)
def eff(self,n):
if n+'A' in self.adapters:return self.p[n]+self.adapters[n+'A']@self.adapters[n+'B'] # row convention alpha/r=1
return self.p[n]
def forward(self,ids):
B,T=ids.shape;x=self.p['E'][ids]+pos(T)
for l in range(2):
p=lambda n:self.eff(f'{l}{n}')
n=F.layer_norm(x,(D,),p('g1').flatten(),p('b1').flatten(),1e-5)
q,k,v=[(n@p(k)).reshape(B,T,H,D//H).transpose(1,2) for k in ['Q','K','V']]
a=F.scaled_dot_product_attention(q,k,v,is_causal=True).transpose(1,2).reshape(B,T,D)
y=x+a@p('O');m=F.layer_norm(y,(D,),p('g2').flatten(),p('b2').flatten(),1e-5)
x=y+F.gelu(m@p('U'),approximate='tanh')@p('W')
return x@self.p['R']+self.p['rb']
def configure(self,mode,rank=2,seed=7):
for n,p in self.p.items():p.requires_grad_(mode=='full' or mode=='head' and n in ['R','rb'])
if mode.startswith('lora'):
self.rank=rank;g=torch.Generator().manual_seed(seed)
for l in range(2):
for k in ('QV' if mode=='lora_qv' else 'QKVO'):
n=f'{l}{k}';self.adapters[n+'A']=nn.Parameter((torch.rand((D,rank),generator=g)-.5)*.4);self.adapters[n+'B']=nn.Parameter(torch.zeros(rank,D))
def merge(self):
q=copy.deepcopy(self)
with torch.no_grad():
for n in q.p:
if n+'A' in q.adapters:q.p[n].copy_(q.eff(n))
q.adapters=nn.ParameterDict();return q
def loss(m,ds,suffix=True):
z=m(ds[:,:-1]);y=ds[:,1:];z=z[:,3:] if suffix else z;y=y[:,3:] if suffix else y
return F.cross_entropy(z.reshape(-1,V),y.reshape(-1))
@torch.no_grad()
def metrics(m,ds):
z=m(ds[:,:-1])[:,3:];y=ds[:,4:];return {'ce':float(F.cross_entropy(z.reshape(-1,V),y.reshape(-1))), 'acc':float((z.argmax(-1)==y).double().mean()),'modifier_acc':float((z[:,0].argmax(-1)==y[:,0]).double().mean())}
def weights(m):return {n:v.detach().tolist() for n,v in m.p.items()}
def run(seed=3,pre=160,updates=80,rank=2,lr=.02):
m=GPT(seed);opt=torch.optim.Adam(m.parameters(),lr=.02)
for _ in range(pre):
opt.zero_grad();loss(m,OLD,False).backward();opt.step()
base=weights(m);res={};init={}
for mode in ['frozen','head','full','lora_qv','lora_all']:
a=copy.deepcopy(m);a.configure(mode,rank,seed+4);init[mode]={n:p.detach().tolist() for n,p in a.adapters.items()};params=[p for p in a.parameters() if p.requires_grad];opt=torch.optim.Adam(params,lr=lr) if params else None;hist=[]
for i in range(updates+1):
if i%10==0 or i==updates:hist.append({'t':i,'train':metrics(a,TRAIN),'held':metrics(a,HOLD),'old':metrics(a,OLD)})
if i==updates:break
if opt:opt.zero_grad();loss(a,TRAIN).backward();opt.step()
merge=float((a(NEW[:,:-1])-a.merge()(NEW[:,:-1])).abs().max().detach());drift=max(float((a.p[n]-m.p[n]).abs().max().detach()) for n in a.p)
res[mode]={'params':sum(p.numel() for p in params),'hist':hist,'merge':merge,'drift':drift,'p':weights(a),'adapters':{n:v.detach().tolist() for n,v in a.adapters.items()}}
return {'base':base,'init':init,'results':res,'old':OLD.tolist(),'train':TRAIN.tolist(),'hold':HOLD.tolist(),'total':sum(p.numel() for p in m.parameters())}
if __name__=='__main__':
r=run();print('Base parameters',r['total'])
for k,v in r['results'].items():print(k,v['params'],v['hist'][-1], 'merge',v['merge'],'drift',v['drift'])
with open('/tmp/result0601.json','w') as f:json.dump(r,f)
References and Projection Source Code
- Model scaling and training cost. Stanford CS336
- The Transformer architecture. Attention Is All You Need
- Low-rank adaptation and quantized-base fine-tuning. LoRA · QLoRA · PEFT
- Original Gemma architecture and fused projection. Gemma · Configuration · Attention source
- Separate projections and weight conversion. Transformers Gemma source · PaliGemma conversion source
The next lesson connects a visual encoder to a language model through projected patch tokens and a prefix attention mask.
Previous lesson · 5.6 Conditional Generation & Guidance · Course overview · Next lesson · 6.2 Vision-Language Models