Encoder-only, decoder-only and prefix LM: architecture families
Compare encoder-only, decoder-only, encoder-decoder, and prefix language models by attention pattern, outputs, tasks, training, inference, and cache costs.
After this lesson you can
- Classify architectures by attention mask and output type.
- Implement bidirectional, causal, and prefix masks in one parameterized model.
- Explain the limits of an encoder-only model for autoregressive generation and identify its task heads.
- Compare encoder-decoder and decoder-only parameters, token costs, and cache reuse.
- Discuss evidence for the prevalence of decoder-only language models.
Before you start
The mask determines what each position can know
The same sentence can classify a message, fill a gap, or generate an answer. Before choosing a model, ask what information is available when each output must be produced. The taxonomy of attention patterns distinguishes who can query whom; projections, output heads, and objectives complete the architecture.
Rows represent queries and columns keys. Bidirectional attention allows every valid pair; causal attention only . A prefix language model with prefix length allows bidirectional attention among the first positions. Each later position can see the full prefix and continuation positions through itself, but the prefix cannot see the continuation. The generative objective usually applies to the continuation, not necessarily the prefix.
In a combined diagram, encoder-decoder source and target connectivity has the same block pattern as that prefix LM: source to source, target to source, and target to past. This does not make the models identical. The encoder-decoder uses separate stacks and cross-projections; a prefix LM can use a single shared stack. Connectivity alone does not determine parameters, paths, or the computed function. UniLM studies several masks with a shared transformer.
Formally, for zero-based indices and , the prefix rule permits if or if . In the second case already includes all prefix keys. With only the causal triangle remains; with every query sees all keys. The mask describes dependencies between states, but label shifting determines which token is predicted: without shifting, a position that sees itself could copy its label during training.
Three families and their outputs
An encoder-only architecture computes bidirectional representations: each position can incorporate context on both sides, as in a bidirectional RNN, although the mechanism and parallelism differ. BERT pretrains a bidirectional representation and uses a head to complete masked tokens; it can be fine-tuned with another head for a particular task.
A task head transforms states into outputs: sequence classification may read a special token state or an aggregation; labeling produces a distribution per token; a vocabulary head produces logits per position. Attention mask and head are separate decisions. A classification head initialized from scratch is not automatically a trained spam or sentiment classifier.
For document retrieval, one option turns each text into a vector through pooling and compares vectors with a dot product or cosine. That interface alone does not guarantee distances encode relevance: the head, training objective, and negatives matter. Labeling instead retains an output per token; if tokenization divides a word into pieces, one must decide how to aggregate or project labels. Classification produces one distribution per sequence and does not require generating a sentence.
Pretrained bidirectional BERT does not directly provide the causal factorization used by a left-to-right generator. Iterative filling procedures can be designed, or the model modified and trained with a causal mask, but that does not turn its original masked head into GPT’s autoregressive distribution.
A decoder-only architecture uses a causal mask and predicts the next token. Its name does not mean it contains the cross-attention of an encoder-decoder decoder: the basic variant has only causal self-attention. Prefix, instructions, question, and answer are represented as one sequence and can be distinguished by tokens or the chosen loss.
During causal training the full sequence can be computed in parallel because the mask prevents state from reading later tokens. In generation, the token chosen at enters the context at , making decisions sequential. Saving previous keys and values avoids recomputing their projections, but does not eliminate reading the cache or dependence on its size. This difference between training parallelism and generation matters when comparing costs.
The encoder-decoder family computes the source bidirectionally and produces output with a causal decoder and cross-attention. T5 expresses tasks as text-to-text transformations. Classification can be written as generation of a label, but an encoder with a specific head may be more appropriate when many representations or a fixed output per input are needed.
The popularity of decoder-only architectures in many generative models can be understood through practical advantages: a single causal factorization, next-token signal at many positions, parallel masked training, and cached generation. GPT-3 and LLaMA are examples of this line. Those observations do not identify a single cause or prove superiority for all tasks: data, size, compute, objective, and evaluation also change. The popularity of generative models does not eliminate the usefulness of encoders and encoder-decoders.
Cost: decide what to equalize
The figure compares an approximate block-weight budget, not the whole model. With width and FFN , each encoder or decoder-only block contributes approximately weights; a decoder with cross-attention adds four more projections and contributes . With a fixed ceiling, the integer decoder layer count may fall below budget because of rounding. Embeddings, output head, biases, and norms are excluded.
With source tokens, target tokens, width , encoder blocks, and decoder blocks, assuming two FLOPs for multiplication and addition, an encoder-decoder’s dense and attention operations are approximately
The first term includes encoder bidirectional self-attention. In the decoder appear FFN and causal self-attention, cross Q/O projections over target and K/V over source, and the two cross-attention multiplications. The causal triangle is approximated by half the matrix; softmax and normalization are excluded. For a decoder-only model with layers over a concatenation of length , the same convention gives . This is not a comparison of actual time or equal quality.
In cached inference, a decoder-only model stores K and V per layer for all processed positions. An encoder-decoder can cache encoder memory and cross K/V, as well as generated-prefix K/V. The counter assumes FP16 and one sequence, without paging, beam search, or overhead. Its latency divides estimated one-token FLOPs by assumed effective throughput: it ignores memory, kernels, synchronization, and preprocessing. Short output or long source can change the choice, and models with equal parameter counts need not consume the same FLOPs or have seen the same data.
If each K and V has components using two bytes, self-attention cache for layers and tokens occupies approximately bytes. The first factor 2 represents K and V; the second, bytes per component. Variants with fewer key and value heads reduce that term, but the counter assumes ordinary multi-head attention. For encoder-decoder it also adds source K/V per decoder layer and one copy of encoder memory. It excludes weights, temporary activations, and fragmentation: this is cache accounting, not total GPU memory.
Lab: same network, different masks
The toy model has two layers with single-head self-attention, a tanh FFN, and residual connections. Token and position embeddings are fixed; projections and head are trained. The mask is parameterized with make_mask, which returns True for allowed pairs. The encoder variant classifies whether a string of eight parentheses is balanced. Causal and prefix-LM variants learn to reverse four symbols from a prefix and are evaluated by generating four tokens, not only with teacher forcing.
A string is balanced if cumulative depth is never negative and ends at zero. Classification uses the final row as output; in the encoder that row can query the whole input. For reversal, labels apply after the delimiter: input contains the source and previous output tokens, and the target is the next symbol or EOS. Backward propagates loss through the head, FFN, residual sum, and softmax in each layer. The directional check perturbs all weights simultaneously and compares that product with a central difference; it does not by itself show optimization generalizes.
For parentheses, all 256 possible strings are enumerated and unique training and test examples separated; there are only four test positives, so sensitivity is very noisy. For reversal, random sequences are drawn from a finite space of 256 combinations: training and evaluation can overlap. Accuracy does not demonstrate generalization to new lengths. The three experiments use one seed and a small budget, not a definitive family comparison.
import itertools
import numpy as np
def make_mask(kind,prefix_len,T):
i=np.arange(T)[:,None];j=np.arange(T)[None,:]
if not 0<=prefix_len<=T: raise ValueError('prefijo fuera de rango')
if kind=='encoder': return np.ones((T,T),dtype=bool)
if kind=='causal': return j<=i
if kind in ('prefix','encdec'): return np.where(i<prefix_len,j<prefix_len,(j<prefix_len)|(j<=i))
raise ValueError(kind)
def softmax(x):
e=np.exp(x-x.max(-1,keepdims=True));return e/e.sum(-1,keepdims=True)
def init(kind,seed=4):
rng=np.random.default_rng(seed);d=12;V=7
E=rng.normal(0,.3,(V,d));positions=np.eye(12)[:,:d]*0.7
layers=[]
for _ in range(2):
mats=[rng.normal(0,.18,(d,d)) for __ in range(6)]
layers.append(mats)
C=rng.normal(0,.18,(d,V));params=[w for layer in layers for w in layer]+[C]
return {'rng':rng,'E':E,'positions':positions,'layers':layers,'C':C,'params':params,'m':[np.zeros_like(w) for w in params],'v':[np.zeros_like(w) for w in params],'step':0,'kind':kind}
def forward(state,tokens):
B,T=tokens.shape;d=state['E'].shape[1];kind=state['kind']
x=state['E'][tokens]+state['positions'][:T][None,:,:]
mask=make_mask('encoder' if kind=='balance' else kind,5,T);cache=[]
for Wq,Wk,Wv,Wo,W1,W2 in state['layers']:
q=x@Wq;k=x@Wk;v=x@Wv
[email protected](0,2,1)/np.sqrt(d);a=softmax(np.where(mask,s,-1e9))
z=a@v;u=x+z@Wo;h=np.tanh(u@W1);y=u+h@W2
cache.append((x,q,k,v,a,z,u,h,Wq,Wk,Wv,Wo,W1,W2));x=y
return x@state['C'],cache,x
def loss_grad(state,tokens,labels):
logits,cache,last=forward(state,tokens);p=softmax(logits);valid=labels>=0
index=np.maximum(labels,0);pick=np.take_along_axis(p,index[...,None],axis=-1)[...,0]
loss=-np.log(pick[valid].clip(1e-12)).mean()
g=p.copy();bi,ti=np.indices(labels.shape);g[bi,ti,index]-=1;g*=valid[...,None]/valid.sum()
gradsC=np.einsum('bti,btj->ij',last,g);dx=g@state['C'].T;allgrads=[]
for item in reversed(cache):
x,q,k,v,a,z,u,h,Wq,Wk,Wv,Wo,W1,W2=item
gW2=np.einsum('bti,btj->ij',h,dx);dh=([email protected])*(1-h*h);gW1=np.einsum('bti,btj->ij',u,dh);[email protected]
gWo=np.einsum('bti,btj->ij',z,du);[email protected];[email protected](0,2,1);dv=a.transpose(0,2,1)@dz
ds=a*(da-(da*a).sum(-1,keepdims=True));d=x.shape[-1];dq=ds@k/np.sqrt(d);dk=ds.transpose(0,2,1)@q/np.sqrt(d)
gq=np.einsum('bti,btj->ij',x,dq);gk=np.einsum('bti,btj->ij',x,dk);gv=np.einsum('bti,btj->ij',x,dv)
[email protected][email protected][email protected];allgrads.append([gq,gk,gv,gWo,gW1,gW2])
return float(loss),[w for layer in reversed(allgrads) for w in layer]+[gradsC]
def update(state,tokens,labels):
loss,grads=loss_grad(state,tokens,labels);state['step']+=1;step=state['step']
for i,(w,g) in enumerate(zip(state['params'],grads)):
state['m'][i]=.9*state['m'][i]+.1*g;state['v'][i]=.999*state['v'][i]+.001*g*g
w-=.003*(state['m'][i]/(1-.9**step))/(np.sqrt(state['v'][i]/(1-.999**step))+1e-8)
return loss
def balanced(seq):
depth=0
for t in seq:
depth+=1 if t==0 else -1
if depth<0:return False
return depth==0
def balance_data():
allseq=np.array(list(itertools.product((0,1),repeat=8)),dtype=int)
labels=np.array([int(balanced(row)) for row in allseq]);rng=np.random.default_rng(123)
pos=np.flatnonzero(labels==1);neg=np.flatnonzero(labels==0);rng.shuffle(pos);rng.shuffle(neg)
train=np.concatenate((pos[:10],neg[:170]));test=np.concatenate((pos[10:],neg[170:]));return allseq,labels,train,test
def train_balance(state,steps=100):
seq,labels,train,test=balance_data();rng=state['rng'];pools=[train[labels[train]==k] for k in (0,1)]
for _ in range(steps):
ix=np.concatenate((rng.choice(pools[0],16),rng.choice(pools[1],16)));tok=seq[ix]
y=np.full(tok.shape,-1);y[:,-1]=labels[ix];loss=update(state,tok,y)
return loss
def eval_balance(state):
seq,labels,train,test=balance_data();pred=forward(state,seq[test])[0][:,-1].argmax(-1)
return [float((pred[labels[test]==k]==k).mean()) for k in (0,1)],len(test)
def reverse_batch(rng,B=32):
source=rng.integers(0,4,(B,4));rev=source[:,::-1];tokens=np.concatenate((source,np.full((B,1),4),rev),axis=1)
labels=np.full((B,9),-1);labels[:,4:8]=rev;labels[:,8]=5
return tokens,labels
def train_reverse(state,steps=100):
for _ in range(steps):
tok,y=reverse_batch(state['rng']);loss=update(state,tok,y)
return loss
def eval_reverse(state):
rng=np.random.default_rng(99);source=rng.integers(0,4,(256,4));tok=np.concatenate((source,np.full((256,1),4)),axis=1)
produced=[]
for _ in range(4):
logits,_,_=forward(state,tok);next_token=logits[:,-1].argmax(-1);produced.append(next_token);tok=np.concatenate((tok,next_token[:,None]),axis=1)
pred=np.stack(produced,axis=1);truth=source[:,::-1]
return float((pred==truth).mean()),float((pred==truth).all(-1).mean())
def grad_check():
state=init('prefix');rng=np.random.default_rng(81);tokens,labels=reverse_batch(rng,3)
loss,grads=loss_grad(state,tokens,labels);directions=[rng.normal(size=w.shape) for w in state['params']]
analytic=sum(float((g*d).sum()) for g,d in zip(grads,directions));h=1e-6
for w,d in zip(state['params'],directions):w+=h*d
pos=loss_grad(state,tokens,labels)[0]
for w,d in zip(state['params'],directions):w-=2*h*d
neg=loss_grad(state,tokens,labels)[0]
for w,d in zip(state['params'],directions):w+=h*d
err=abs(analytic-(pos-neg)/(2*h));print('error de derivada direccional:',err);assert err<1e-7assert np.array_equal(make_mask('prefix',0,5),make_mask('causal',0,5))
assert np.array_equal(make_mask('prefix',5,5),make_mask('encoder',5,5))
grad_check()state_balance=init('balance')loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))state_causal=init('causal')loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))state_prefix=init('prefix')loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))In a run with these seeds, after 600 steps test sensitivity for unbalanced and balanced classes was 0.875 and 1.0 respectively, with only four positive examples. In reversal, both masks achieved accuracy 1.0 on the four symbols and the complete sequence of the evaluation sample. That evaluation does not check EOS and may contain sequences already seen during training. These figures come from this small experiment, not BERT or GPT-2.
Real pretrained models
The previous toys reveal the mechanism but do not replace a pretrained model. This comparison uses real BERT base and GPT-2 with fixed revisions: in BERT a gap queries both left and right; GPT-2 predicts a causal continuation. Change “France” to “Texas” in the BERT sentence: the same candidate’s probability depends on that right context. These are model scores, not factual guarantees.
The local cell needs PyTorch and Transformers and approximately 1 GB for weights. The first time, permit downloading by setting ORYON_HF_ONLINE=1 in the environment; by default it uses only the local cache. Fixed revisions make the files reproducible; output may vary slightly with numerical versions. The final test changes the last token and checks that earlier logits are invariant, a consequence of the causal mask.
import os
import torch
from transformers import AutoTokenizer, AutoModelForMaskedLM, AutoModelForCausalLM
offline = os.environ.get('ORYON_HF_ONLINE', '0') != '1'
bert_id = 'google-bert/bert-base-uncased'
bert_rev = '86b5e0934494bd15c9632b12f734a8a67f723594'
gpt_id = 'openai-community/gpt2'
gpt_rev = '607a30d783dfa663caf39e06633721c8d4cfcd7e'
bt = AutoTokenizer.from_pretrained(bert_id, revision=bert_rev, local_files_only=offline)
bert = AutoModelForMaskedLM.from_pretrained(bert_id, revision=bert_rev, local_files_only=offline).eval()
def fill(text):
inputs = bt(text, return_tensors='pt')
index = (inputs.input_ids[0] == bt.mask_token_id).nonzero().item()
with torch.no_grad():
probabilities = bert(**inputs).logits[0, index].softmax(-1)
top = probabilities.topk(5)
return [(bt.decode([int(i)]), float(p)) for p, i in zip(top.values, top.indices)]
print('BERT Francia:', fill('Paris is the [MASK] of France.'))
print('BERT Texas:', fill('Paris is the [MASK] of Texas.'))
del bert
import gc
gc.collect()
gt = AutoTokenizer.from_pretrained(gpt_id, revision=gpt_rev, local_files_only=offline)
gpt = AutoModelForCausalLM.from_pretrained(gpt_id, revision=gpt_rev, local_files_only=offline).eval()
inputs = gt('The capital of France is', return_tensors='pt')
with torch.no_grad():
generated = gpt.generate(**inputs, max_new_tokens=12, do_sample=False, pad_token_id=gt.eos_token_id)
before = gpt(**inputs).logits
changed = inputs.input_ids.clone()
changed[0, -1] = (changed[0, -1] + 1) % gpt.config.vocab_size
after = gpt(input_ids=changed, attention_mask=inputs.attention_mask).logits
print('GPT-2:', repr(gt.decode(generated[0])))
print('Diferencia máxima anterior al cambio:', float((before[:, :-1] - after[:, :-1]).abs().max()))
assert torch.allclose(before[:, :-1], after[:, :-1], atol=1e-5, rtol=1e-5)npm run lab and open the connection link.In the local BERT run, capital received probability 0.99694 with France and 0.95133 with Texas. The change shows sensitivity to text on the right; it does not imply the Texas sentence is true. GPT-2 continued “The capital of France is the capital of the French Republic, and the capital of the” with twelve-token greedy decoding. This is a generated continuation, not a validated answer; on changing the final input token, the maximum difference in earlier logits was zero.
Exercises
import numpy as np
def make_mask(kind,prefix_len,T):
passStep 1 of 3. If p=0, which queries belong to the prefix?