Decoder-only models: one probability at a time
解码器型语言模型
Train 19 causal-attention weights, enumerate a normalized joint and verify chunked key/value caching.
decoder-only-modelsWrite a distribution one continuation at a time
After reading “The train will arrive at,” a model can assign probabilities to possible next tokens. Once one token is selected, it becomes part of the context for the following prediction. A decoder-only model repeats this conditional prediction with one causal stack, without a separate encoder stack providing cross-attention states.
The GPT-2 report frames language modeling as sequence distribution estimation and discusses tasks expressed through a shared text sequence. Its released implementation shows the causal attention, residual blocks and cache conventions. This chapter explains that architecture and tests a small original model. It does not reproduce GPT-2 pretraining. Read causal masking, positional encoding and backpropagation first.
The chain rule supplies a normalized joint
For a fixed-length sequence over a finite vocabulary, define one normalized conditional distribution at each step:
Summing over the last token removes the final factor because that conditional sums to one. Repeating this argument removes every factor, leaving total mass one. This property does not depend on good training. A poorly fitted autoregressive model can still define a perfectly normalized distribution. Variable-length generation also needs an end-of-sequence convention; normalization over finite strings additionally depends on termination behavior.
The input at each prediction position must contain only known context. Under teacher forcing, the training inputs are shifted relative to the targets:
A causal mask permits each position to read its own shifted input and earlier inputs. Training can evaluate all positions together because the target sequence is already known. Sampling cannot obtain an unknown continuation in advance; it feeds generated tokens back into later positions. A prompt is simply an initial context, although particular systems may use additional training objectives or visibility patterns.
To make the calculation inspectable, the program uses width two and one causal attention head. The first input coordinate is a shifted bit represented by minus one or one, with zero for BOS; the second is the absolute position divided by four. Four two-by-two matrices and a binary output head are trained:
There are sixteen projection parameters, two readout weights and one bias: nineteen in total. The model has a residual path but no feed-forward sublayer, normalization, learned token embeddings or full vocabulary softmax. Those omissions define a small attention decoder, not a complete Transformer. The GPT-2 source, for comparison, has pre-normalized residual attention and MLP blocks, learned token/position embeddings and a tied output embedding map.
For a soft binary target y, use a numerically stable logistic cross-entropy. Averaging over B sequences and N positions gives the logit derivative D:
The residual input is fixed in this experiment. The output-head and output-projection derivatives are:
Matrix products that accumulate parameter gradients sum over batch and sequence rows. The attention derivative then follows the row-wise softmax Jacobian:
Blocked weights are zero, so blocked score derivatives are zero. The implementation checks every one of the nineteen parameter derivatives by centered finite differences at a separate nonzero test point. The equations are an explanation of those calculations, not a substitute for the numerical check.
The artificial target distribution starts with a fair bit, then repeats the preceding bit with probability 0.8. Training enumerates all sixteen length-four binary strings and gives each sequence-position pair equal weight, with the true conditional probability as its soft target. Its minimum conditional loss is:
A two-state Markov lookup already represents this task exactly. We use attention to inspect a causal architecture and its gradients, not because it is the simplest or fastest solver. Equal weighting of the enumerated contexts is part of the declared training objective; it is not a sampled natural-language corpus.
Train, enumerate and compare the cache
Save as decoder_only_models.py and run with Python 3 and NumPy. The program trains all nineteen parameters and then performs actual full and cached forward passes.
"""Original 19-parameter causal attention decoder; no MLP, norm or language data."""
import itertools
import json
import numpy as np
def unpack(theta):
t=np.asarray(theta,dtype=float)
if t.shape!=(19,) or not np.isfinite(t).all():raise ValueError('19 finite parameters required')
return [t[i:i+4].reshape(2,2) for i in range(0,16,4)]+[t[16:18],t[18]]
def inputs(x):
a=np.asarray(x,dtype=float)
if a.ndim!=3 or a.shape[2]!=2 or not 1<=a.shape[0]<=128 or not 1<=a.shape[1]<=16 or not np.isfinite(a).all():
raise ValueError('finite batch1..128, length1..16, width2 required')
return a
def probabilities(z):return np.exp(-np.logaddexp(0.,-z))
def forward(theta,x):
x=inputs(x);wq,wk,wv,wo,w,b=unpack(theta);q=x@wq;k=x@wk;v=x@wv
n=x.shape[1];scores=q@k.transpose(0,2,1)/np.sqrt(2);mask=np.arange(n)[None,:]<=np.arange(n)[:,None]
scores=np.where(mask,scores,-np.inf);a=np.exp(scores-scores.max(axis=-1,keepdims=True));a/=a.sum(axis=-1,keepdims=True)
z=a@v;h=x+z@wo;logits=h@w+b
return logits,(x,q,k,v,a,z,h)
def objective(theta,x,target):
logits,cache=forward(theta,x);y=np.asarray(target,dtype=float)
if y.shape!=logits.shape or not np.isfinite(y).all() or np.any((y<0)|(y>1)):raise ValueError('matching soft targets in [0,1] required')
x,q,k,v,a,z,h=cache;wq,wk,wv,wo,w,b=unpack(theta);d=(probabilities(logits)-y)/y.size
dh=d[...,None]*w;gw=np.einsum('bnd,bn->d',h,d);gb=d.sum();gwo=np.einsum('bni,bnj->ij',z,dh)
dz=dh@wo.T;da=dz@v.transpose(0,2,1);dv=a.transpose(0,2,1)@dz
ds=a*(da-(da*a).sum(axis=-1,keepdims=True));dq=ds@k/np.sqrt(2);dk=ds.transpose(0,2,1)@q/np.sqrt(2)
gradients=[np.einsum('bni,bnj->ij',x,g).ravel() for g in (dq,dk,dv)]+[gwo.ravel(),gw,np.array([gb])]
loss=float(np.mean(np.logaddexp(0.,logits)-y*logits))
return loss,np.concatenate(gradients)
def cached(theta,x,past=None):
x=inputs(x);wq,wk,wv,wo,w,b=unpack(theta);q=x@wq;k=x@wk;v=x@wv;offset=0
if past is not None:
pk,pv=[np.asarray(a,dtype=float) for a in past]
if pk.ndim!=3 or pk.shape!=pv.shape or pk.shape[0]!=len(x) or pk.shape[2]!=2 or not 1<=pk.shape[1] or pk.shape[1]+x.shape[1]>16 or not np.isfinite(pk).all() or not np.isfinite(pv).all():
raise ValueError('matching finite cache, combined length<=16 required')
offset=pk.shape[1];k=np.concatenate([pk,k],axis=1);v=np.concatenate([pv,v],axis=1)
mask=np.arange(k.shape[1])[None,:]<=offset+np.arange(x.shape[1])[:,None]
scores=np.where(mask,q@k.transpose(0,2,1)/np.sqrt(2),-np.inf);a=np.exp(scores-scores.max(axis=-1,keepdims=True));a/=a.sum(axis=-1,keepdims=True)
return (x+(a@v)@wo)@w+b,(k,v)
def dataset():
bits=np.array(list(itertools.product([0,1],repeat=4)));x=np.zeros((16,4,2));x[:,1:,0]=2*bits[:,:-1]-1;x[:,:,1]=np.arange(4)/4
y=np.full((16,4),.5);y[:,1:]=.5+.3*x[:,1:,0]
return x,y,bits
def train(steps=600):
if not isinstance(steps,int) or not 1<=steps<=2000:raise ValueError('bounded positive steps required')
x,y,_=dataset();theta=np.random.default_rng(19).normal(0,.1,19);curve=[]
for i in range(steps+1):
loss,g=objective(theta,x,y)
if i%100==0 or i==steps:curve.append([i,loss])
if i<steps:theta-=.5*g
return theta,curve
def demo():
x,y,bits=dataset();theta,curve=train();z,_=forward(theta,x);p=probabilities(z);mass=np.prod(np.where(bits==1,p,1-p),axis=1)
parts=[];past=None
for start,end in [(0,1),(1,3),(3,4)]:
zi,past=cached(theta,x[:,start:end],past);parts.append(zi)
changed=x.copy();changed[:,2:,0]*=-1;zc,_=forward(theta,changed)
floor=.25*np.log(2)+.75*(-.8*np.log(.8)-.2*np.log(.2))
return dict(curve=curve,parameters=19,conditional_loss=objective(theta,x,y)[0],optimal_conditional_loss=float(floor),
joint_mass=float(mass.sum()),joint_probabilities=mass.tolist(),cached_error=float(np.max(np.abs(np.concatenate(parts,axis=1)-z))),
prefix_change=float(np.max(np.abs(z[:,:2]-zc[:,:2]))),
maximum_conditional_probability_error=float(np.max(np.abs(p-y))),cache_scalars=int(sum(a.size for a in past)),
scope='All16 binary length-four sequences; conditional targets .5 then .8 repeat probability. All19 attention/readout weights trained. No full Transformer or language benchmark.')
if __name__=='__main__':print(json.dumps(demo(),indent=2))
After 600 full-batch updates, conditional loss is about 0.54859256, slightly above the 0.54858861 optimum. The largest conditional-probability error is about 0.002749. Preserve that nonzero fitting error: a normalized joint is not necessarily the target joint.
Multiplying the trained conditionals for all sixteen strings gives total mass one. The program also processes each input in chunks of lengths one, two and one. Concatenating those cached outputs matches the full logits exactly in this run. Changing input rows two and three leaves earlier logits unchanged.
Caching reuses previously computed keys and values because a causal layer’s old states do not acquire new future information. A new query still attends over all allowed past keys. For one layer, B sequences of cached length P and key/value width d need 2BPd stored numbers. The demonstration stores 256 numbers for B=16, P=4 and d=2. A multilayer model has separate layer caches.
A new token costs order d² for projections plus Pd for attention against a P-token cache, before any additional feed-forward or vocabulary-head costs. Caching avoids projecting and processing the entire prefix again; it does not make access to a growing history free. Dense prefill still involves a quadratic attention matrix.
A decoder defines probabilities, not correctness
Next-token likelihood rewards predicting the training distribution. It does not by itself guarantee factual answers, calibrated confidence, useful instruction following or reliable reasoning. Those are separate behaviors with separate data, objectives and evaluations.
Cache equivalence assumes fixed parameters and matching positional conventions. Appending tokens preserves earlier causal states under those conditions; changing earlier tokens, resetting positions or mixing incompatible caches does not. The example contains no dropout. A comparison involving stochastic training-time operations needs an explicitly controlled randomness policy.
The toy task contains only four positions and two symbols. The model can use its residual access to the last observed bit, so the experiment does not prove that its attention mechanism is necessary. Generation quality or long-context behavior cannot be inferred from these sixteen cases.
Check normalization and conditioning separately
- For targets
[0,1,1,0], what are the first-coordinate inputs and soft target probabilities in this experiment?
Answer: Inputs are [0,-1,1,1]: BOS zero, followed by the previous three bits mapped to minus or plus one. The target probabilities of bit one are [0.5,0.2,0.8,0.8]. The last actual label is zero even though its target probability of one is 0.8; a probability is not a deterministic rule.
- Count the trained parameters and compute the optimal average loss.
Answer: Four two-by-two projections contribute sixteen, the readout vector contributes two and the bias one, totaling nineteen. The loss floor is one quarter of log two plus three quarters of the binary entropy at 0.8, about 0.54858861. The reported trained loss remains slightly larger.
- Must the product of conditionals sum to one only after the model has learned the target distribution?
Answer: No. For fixed length, nested summation removes each normalized conditional in reverse order regardless of parameter quality. The code’s mass check and its conditional-error check answer different questions.
- Could you use the same cache after modifying an earlier token while leaving its stored keys and values untouched?
Answer: In general no. Those keys and values were computed from a different prefix; in deeper layers later cached states may depend on the changed token too. Recompute the affected states. The successful chunk comparison assumes identical inputs, weights and absolute position coordinates.
Use the architecture name precisely
The GPT-2 report connects a shared sequence model with multiple text tasks. The fixed implementation exposes architectural choices such as pre-norm, cache offsets and tied output embeddings; none is established merely by the phrase “decoder-only.” This chapter isolates causal probability construction and a small differentiable implementation. The later GPT chapter covers its specific pretraining lineage, while encoder–decoder language models introduce a separate source representation and cross-attention.
Make a prediction, then check
When may a causal model reuse old key/value states after appending a token?
Learning objectives
- Derive the shifted causal objective and gradients.
- Verify conditional products sum to one.
- Match cached inference with full-prefix computation.
Prerequisites & connections
Explore related knowledge →References
- Language Models are Unsupervised Multitask Learners
Alec Radford; Jeffrey Wu; Rewon Child; David Luan; Dario Amodei; Ilya Sutskever · 2019 - openai/gpt-2: src/model.py @9b63575
openai/gpt-2 contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read GPT-2 report section2/2.3 and fixed model/cache source. Seven paired equations and four explained exercises; original19-parameter causal attention decoder, all parameter finite differences, shifted soft targets, entropy floor,16-sequence probability enumeration and chunked caches. No MLP/norm or natural-language training; a Markov table already solves the synthetic task.
- Single AI author read GPT-2 report section2/2.3 and fixed model/cache source. Seven paired equations and four explained exercises; original19-parameter causal attention decoder, all parameter finite differences, shifted soft targets, entropy floor,16-sequence probability enumeration and chunked caches. No MLP/norm or natural-language training; a Markov table already solves the synthetic task.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial text-coordinate precision assertion and visual-label refinements preserved. Full article acceptance recorded separately.
Source locations checked:
- Language Models are Unsupervised Multitask Learners · Read section2 probability factorization and task-conditioning discussion, section2.3 model changes; PDF3/4 viewed. No benchmark scores adopted or GPT-2 training.
- openai/gpt-2: src/model.py @9b63575 · Read58-110,123-173: lower-right cache mask, QKV cache, pre-norm/residuals, offset positions and tied output weights. Modified MIT license opening only; no upstream execution or copying.
Related topics