Module contents
Lesson 10 of 22Core 85 min

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.

InteractivePatterns and rows with loss
Columns: keys
Rows: queries
Family
10
5
Example taskContinue from prefix
Rows with loss5
Choose a family and adjust the prefix. Blue cells are allowed keys; magenta dots indicate rows with loss in an illustrative task. Encoder-decoder shows connectivity over concatenated source and target, not weight equivalence to a prefix LM.

Rows represent queries and columns keys. Bidirectional attention allows every valid pair; causal attention only j≤ij\le i. A prefix language model with prefix length pp allows bidirectional attention among the first pp 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 0≤p≤T0\le p\le T, the prefix rule permits (i,j)(i,j) if (i<p y j<p)(i<p\text{ y }j<p) or if (i≥p y j≤i)(i\ge p\text{ y }j\le i). In the second case j≤ij\le i already includes all prefix keys. With p=0p=0 only the causal triangle remains; with p=Tp=T 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 p(x1)∏tp(xt∣x<t)p(x_1)\prod_t p(x_t\mid x_{<t}) 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 tt from reading later tokens. In generation, the token chosen at tt enters the context at t+1t+1, 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.

InteractiveFamily milestones
2017: Transformer

Encoder and decoder stacks with cross-attention and self-attention.

Primary source
0
Year2017
ModelTransformer
Step through the works and open their sources. Sharing the transformer name does not imply sharing mask, objective, or head.

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 dd and FFN 4d4d, each encoder or decoder-only block contributes approximately 12d212d^2 weights; a decoder with cross-attention adds four more projections and contributes 16d216d^2. With a fixed ceiling, the integer decoder layer count may fall below budget because of rounding. Embeddings, output head, biases, and norms are excluded.

InteractiveOne budget, two paths
020.0 B40.0 B60.0 B80.0 B100 B120 BEncoder-decoder62.5 BDecoder-only116 B
12
6
768
512
128
Encoder + decoder layers6 + 4
Encoder-decoder block weights80.2 M
Decoder-only block weights84.9 M
Encoder-decoder / decoder-only cache8.25 MiB / 22.5 MiB
Modeled latency per token0.0007 / 0.0019 ms
Allocate budget between encoder and decoder and change lengths. The figure computes approximate FLOPs, FP16 cache, and per-token latency using an assumed effective throughput of 100 TFLOP/s; these are not measured times. In the bars, B represents one billion operations.

With SS source tokens, TT target tokens, width dd, EE encoder blocks, and DD decoder blocks, assuming two FLOPs for multiplication and addition, an encoder-decoder’s dense and attention operations are approximately

E(24Sd2+4S2d)+D(24Td2+2T2d+4(S+T)d2+4STd).E(24Sd^2+4S^2d)+D(24Td^2+2T^2d+4(S+T)d^2+4STd).

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 LL layers over a concatenation of length S+TS+T, the same convention gives L[24(S+T)d2+2(S+T)2d]L[24(S+T)d^2+2(S+T)^2d]. 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 dd components using two bytes, self-attention cache for LL layers and nn tokens occupies approximately 2⋅2Lnd2\cdot2Lnd 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.

[ ]Two mask-parameterized layersBrowser
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-7
[ ]Check masks and gradientsBrowser
assert 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()
[ ]Initialize balanceBrowser
state_balance=init('balance')
[ ]balance: 100 stepsBrowser
loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))
[ ]balance: 200 stepsBrowser
loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))
[ ]balance: 300 stepsBrowser
loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))
[ ]balance: 400 stepsBrowser
loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))
[ ]balance: 500 stepsBrowser
loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))
[ ]balance: 600 stepsBrowser
loss=train_balance(state_balance,100)
print('balance',state_balance['step'],'pérdida',loss,'sensibilidad por clase y tamaño',eval_balance(state_balance))
[ ]Initialize causalBrowser
state_causal=init('causal')
[ ]causal: 100 stepsBrowser
loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))
[ ]causal: 200 stepsBrowser
loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))
[ ]causal: 300 stepsBrowser
loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))
[ ]causal: 400 stepsBrowser
loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))
[ ]causal: 500 stepsBrowser
loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))
[ ]causal: 600 stepsBrowser
loss=train_reverse(state_causal,100)
print('causal',state_causal['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_causal))
[ ]Initialize prefixBrowser
state_prefix=init('prefix')
[ ]prefix: 100 stepsBrowser
loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))
[ ]prefix: 200 stepsBrowser
loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))
[ ]prefix: 300 stepsBrowser
loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))
[ ]prefix: 400 stepsBrowser
loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))
[ ]prefix: 500 stepsBrowser
loss=train_reverse(state_prefix,100)
print('prefix',state_prefix['step'],'pérdida',loss,'precisión token y secuencia',eval_reverse(state_prefix))
[ ]prefix: 600 stepsBrowser
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.

[ ]PythonLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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

Code
Implement make_mask(kind, prefix_len, T), returning a Boolean (T,T) matrix whose row is query and column is key. kind is 'encoder', 'causal', or 'prefix'; for prefix, the first prefix_len positions see each other bidirectionally and the continuation sees the prefix and its past. Reject prefixes outside [0,T] and unknown names.
import numpy as np
def make_mask(kind,prefix_len,T):
  pass
Shift+Enter to run
Quiz
Which combination is a reasonable choice, without claiming it is the only one?
Proof
Prove: The prefix-LM mask with p=0 is causal and with p=T is bidirectional.
0
Queries i<p see j<p; queries i≥p see j<p or j≤i.

Step 1 of 3. If p=0, which queries belong to the prefix?

Numeric
With E=D=6, S=512, T=128, and d=768, calculate encoder-decoder block FLOPs from the formula in the text, excluding embeddings and head.
Numeric
With L=12, S=512, T=128, and d=768, calculate decoder-only block FLOPs over the concatenation, under the same convention.
Key idea
A family is identified by information flow, stack structure, and heads, not merely its name. Equal parameter counts do not equalize attention volume or generation cost.