AI Wiki中文/EN

Encoder-only models: read both sides, then choose a task

编码器型语言模型

Train a small masked-token readout and distinguish bidirectional representations from a normalized joint model.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The missing word may need the words that follow it

Compare “She sat by the [MASK] of the river” with “She deposited money at the [MASK].” A useful representation of the missing position should be able to read both sides of the gap. That is a natural role for a bidirectional encoder: it builds contextual representations of an input that is already available.

An encoder-only language model is a stack used without a separate autoregressive decoder. The name describes an architecture, not one mandatory training objective. BERT combines a bidirectional Transformer encoder with selected-token prediction and a sentence-pair objective. RoBERTa studies changes to that training recipe while holding the architecture fixed in its ablations. Read multi-head attention and cross-entropy first.

Fixed attention changes the information available to a two-parameter readout; multiplying conditionals is a separate normalization question.
Fixed attention changes the information available to a two-parameter readout; multiplying conditionals is a separate normalization question.

Separate the representation from the learning task

At a high level, an encoder maps token, position and possibly segment embeddings into one contextual vector per position. A task head then reads the appropriate vectors:

H=Encoder⁡(E+P+T; Mvalid),y^i=gϕ(hi),y^sequence=gψ(haggregate).H=\operatorname{Encoder}(E+P+T;\,M_{\mathrm{valid}}),\qquad \widehat y_i=g_\phi(h_i),\qquad \widehat y_{\mathrm{sequence}}=g_\psi(h_{\mathrm{aggregate}}).

A token-labeling task can use h_i, a span task can score boundary positions, and a sequence classifier can use a designated aggregate representation. Those heads and their training matter. A vector attached to a special token is not automatically a high-quality similarity embedding for arbitrary retrieval tasks.

With unrestricted valid-token self-attention, the representation of position i can depend on both earlier and later input tokens. That is legitimate when the whole input is available, as in reading a completed document. For forecasting an unavailable future, the data and computation need different constraints; “bidirectional” is not a universal advantage.

Masked language modeling, or MLM, corrupts selected input positions and trains predictions of their original tokens:

LMLM=Ex,S,CS[−1∣S∣∑i∈Slog⁡pθ(xi∣CS(x))],∣S∣>0.\mathcal L_{\mathrm{MLM}}=\mathbb E_{x,S,C_S}\left[-\frac1{|S|}\sum_{i\in S}\log p_\theta(x_i\mid C_S(x))\right],\qquad |S|>0.

Here S is the set of selected targets and C_S is the corruption process. BERT selects 15% of token positions; among selected positions it uses [MASK] 80% of the time, a random token 10% and the original token 10%. Selection for loss and replacement by a mask token are therefore different events. The attention mask is another object: it determines visibility, rather than replacing a token’s identity.

The BERT key-padding implementation also illustrates that blocking padded keys does not force padded query outputs to zero. Task losses should count the intended valid targets. Our small experiment has no padding and leaves the middle [MASK] position visible to attention.

Consider three positions: a left bit, a masked middle token and a right bit. The bits are independent and balanced. The target at the middle has probability 0.9 of being one when the right bit is one, and 0.1 otherwise. To isolate the information supplied by visibility, keep attention scores fixed:

a=softmax⁡([−4,0,4]),h=∑j=02ajvj,v1=0.a=\operatorname{softmax}([-4,0,4]),\qquad h=\sum_{j=0}^{2}a_jv_j,\qquad v_1=0.

Bit zero has value minus one, bit one has value one, and the mask token has value zero. The encoder representation h is passed to a logistic head with only two learned parameters, slope w and intercept b. For a soft target y, its loss and derivatives are:

z=wh+b,p=σ(z),ℓ=log⁡(1+ez)−yz,∂ℓ∂w=(p−y)h,∂ℓ∂b=p−y.z=wh+b,\quad p=\sigma(z),\quad \ell=\log(1+e^z)-yz,\quad \frac{\partial\ell}{\partial w}=(p-y)h,\quad \frac{\partial\ell}{\partial b}=p-y.

The soft targets are specified population probabilities, not observed labels from a real dataset. In the left-only variant the right key is blocked; the left bit gives no information about the target. In the bidirectional variant, the representation is dominated by the right bit, allowing the head to approach the corresponding conditional entropy:

H(0.9)=−0.9log⁡0.9−0.1log⁡0.1≈0.325083,H(0.5)=log⁡2≈0.693147.H(0.9)=-0.9\log0.9-0.1\log0.1\approx0.325083,\qquad H(0.5)=\log2\approx0.693147.

This comparison isolates a particular information constraint on a particular task. It is not a benchmark showing that encoder-only models are always better than causal models, nor a full BERT implementation.

MLM predictions also need not supply a normalized joint sequence distribution by multiplying all token conditionals together. Even conditionals derived from a genuine joint can fail that test. Take a two-bit joint with diagonal probabilities 0.45 and off-diagonal probabilities 0.05:

P=[0.450.050.050.45],Q(x,y)=P(x∣y)P(y∣x),∑x,yQ(x,y)=2(0.92+0.12)=1.64.P=\begin{bmatrix}0.45&0.05\\0.05&0.45\end{bmatrix},\quad Q(x,y)=P(x\mid y)P(y\mid x),\quad \sum_{x,y}Q(x,y)=2(0.9^2+0.1^2)=1.64.

Both conditionals prefer agreement with probability 0.9, yet their product sums to 1.64. This product is a pseudo-likelihood expression, not the ordered chain-rule factorization used by an autoregressive model. An MLM can support scoring or generation procedures, but their definitions and guarantees require separate work.

Train the head and keep the visibility comparison fair

Save as encoder_only_models.py; run with Python 3 and NumPy. The attention scores are fixed and only two readout parameters are trained.

"""Fixed positional attention plus a trained two-parameter MLM readout, not BERT."""
import itertools
import json
import numpy as np


def context(tokens, bidirectional=True):
    t=np.asarray(tokens)
    if t.ndim!=2 or t.shape[1]!=3 or not 1<=len(t)<=128 or t.dtype.kind not in 'iu' or not np.isin(t,[0,1,2]).all():
        raise ValueError('1..128 three-token rows; token2 is MASK')
    scores=np.array([-4.,0.,4.])
    if not bidirectional:scores[2]=-np.inf
    a=np.exp(scores-np.max(scores));a/=a.sum()
    values=np.array([-1.,1.,0.])[t]
    return values @ a,a


def loss_gradient(theta,h,target):
    theta=np.asarray(theta,dtype=float);h=np.asarray(h,dtype=float);y=np.asarray(target,dtype=float)
    if theta.shape!=(2,) or h.ndim!=1 or not h.size or y.shape!=h.shape or not all(np.isfinite(a).all() for a in (theta,h,y)) or np.any((y<0)|(y>1)):
        raise ValueError('finite two-parameter head and matching bounded targets required')
    z=theta[0]*h+theta[1];p=np.exp(-np.logaddexp(0.,-z));d=(p-y)/len(y)
    return float(np.mean(np.logaddexp(0.,z)-y*z)),np.array([d @ h,d.sum()]),p


def train(h,y,steps=400):
    if not isinstance(steps,int) or not 1<=steps<=2000:raise ValueError('bounded positive integer steps required')
    theta=np.zeros(2);curve=[]
    for step in range(steps+1):
        loss,grad,p=loss_gradient(theta,h,y)
        if step%50==0 or step==steps:curve.append([step,loss])
        if step<steps:theta-=.5*grad
    return theta,curve


def demo():
    bits=np.array(list(itertools.product([0,1],repeat=2)));tokens=np.column_stack([bits[:,0],np.full(4,2),bits[:,1]])
    target=.1+.8*bits[:,1];records={}
    for name,bidir in [('bidirectional',True),('left_only',False)]:
        h,a=context(tokens,bidir);w,curve=train(h,target);loss,_,p=loss_gradient(w,h,target)
        records[name]=dict(weights=a.tolist(),readout=w.tolist(),loss=loss,probabilities=p.tolist(),curve=curve)
    # Compatible binary conditionals do not become a normalized joint by multiplication.
    joint=np.array([[.45,.05],[.05,.45]])
    cond_x_given_y=joint/joint.sum(axis=0,keepdims=True)
    cond_y_given_x=joint/joint.sum(axis=1,keepdims=True)
    pseudo=cond_x_given_y*cond_y_given_x
    original=context(tokens)[0];changed=tokens.copy();changed[:,2]=1-changed[:,2]
    return dict(models=records,masked_inputs=tokens.tolist(),soft_targets=target.tolist(),
                conditional_entropy=float(-.9*np.log(.9)-.1*np.log(.1)),
                right_context_change=float(np.max(np.abs(original-context(changed)[0]))),
                joint_mass=float(joint.sum()),product_of_conditionals_mass=float(pseudo.sum()),
                scope='Four artificial contexts; target probabilities specified, no held-out language data. Only readout slope and intercept are trained.')


if __name__=='__main__':print(json.dumps(demo(),indent=2))

The four contexts enumerate both left and right bits. After 400 updates, the bidirectional loss is about 0.325082998, close to the 0.325082973 conditional-entropy target. The left-only head remains at log two, about 0.693147. These are exact expectations over the four artificial contexts and their soft targets, not held-out language performance.

Changing the right token changes the bidirectional representation by about 1.96338. The mask token still receives a positive attention weight, although its value is zero. That makes the distinction between token corruption and attention visibility concrete.

A dense n-token encoder layer with model width d and feed-forward width proportional to d typically costs order n²d plus nd², excluding task-specific output heads. Attention weights require quadratic storage when explicitly materialized. All input positions can be processed in parallel, but adding a new suffix may change earlier contextual representations. Ordinary causal-model key/value reuse cannot simply be copied across all encoder layers.

A training objective is not the architecture’s definition

The toy reader omits learned attention projections, multiple layers, normalization and a full vocabulary. The attention calculation is real, but its fixed preference for the right position is part of the declared construction. The learned head tests whether the available signal supports the target; it does not discover a language representation from text.

BERT’s MLM and sentence-pair objective are historical design choices. RoBERTa’s input-format and NSP experiments should be read together: changing the loss alongside the way examples are constructed does not isolate a universal effect of that loss. Downstream fine-tuning, pooling and evaluation still determine whether the resulting representation suits a task.

What exactly has been hidden?

  1. Does replacing a token by [MASK] imply that other tokens cannot attend to its position?

Answer: No. A mask token is an input symbol with a representation. An attention mask separately controls visible pairs. In the program, the middle token has value zero and a positive attention weight.

  1. Why is the best left-only probability one half in the artificial task, even though a bidirectional reader can approach 0.9 or 0.1?

Answer: The independent right bit is equally likely to be zero or one for either left context. Averaging its two target probabilities gives one half. Log loss is minimized by that conditional probability, giving log two; reading the right bit changes the available conditioning information.

  1. At w=b=0, h=1 and y=0.9, what are the two loss derivatives?

Answer: The predicted probability is one half. Both derivatives are minus 0.4: the slope derivative multiplies the residual by h, and the intercept derivative is the residual. A gradient step increases the predicted probability for this example.

  1. Could you normalize the pseudo-likelihood product in the two-bit example and thereby recover the original conditionals?

Answer: Normalizing gives some valid joint, but not the original one. Its agreement conditional becomes 0.81 divided by 0.82, about 0.987805, rather than 0.9. Multiplying overlapping conditionals counts information differently; division by a single global constant does not undo that change.

Read three contracts separately

BERT specifies representations and pretraining objectives; RoBERTa probes parts of the training recipe; the fixed BERT source exposes the concrete key-padding convention. Keep those contracts separate from the downstream task head. Continue with decoder-only models to compare ordered conditional probabilities, or the later BERT chapter for the model’s specific history and experiments.

Make a prediction, then check

Do compatible token conditionals multiply into a normalized joint automatically?

Choose one answer

Learning objectives

  • Separate architecture, corruption and learning objective.
  • Measure which context identifies the masked token.
  • Explain why multiplying conditionals need not normalize.

Prerequisites & connections

Explore related knowledge →

References

  1. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
    Jacob Devlin; Ming-Wei Chang; Kenton Lee; Kristina Toutanova · 2019
  2. RoBERTa: A Robustly Optimized BERT Pretraining Approach (v1)
    Yinhan Liu; Myle Ott; Naman Goyal; Jingfei Du; Mandar Joshi; Danqi Chen; Omer Levy; Mike Lewis; Luke Zettlemoyer; Veselin Stoyanov · 2019
  3. google-research/bert: modeling.py @eedf571
    google-research/bert contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read BERT architecture/input/MLM sections, RoBERTa selected objective/input-format comparisons and fixed BERT key-padding implementation. Six paired equations and four explained exercises; two readout parameters gradient-checked, fixed-attention visibility experiment, conditional-entropy limits and incompatible use of a conditional product as a normalized joint. No full BERT training or held-out language result.

  • Single AI author read BERT architecture/input/MLM sections, RoBERTa selected objective/input-format comparisons and fixed BERT key-padding implementation. Six paired equations and four explained exercises; two readout parameters gradient-checked, fixed-attention visibility experiment, conditional-entropy limits and incompatible use of a conditional product as a normalized joint. No full BERT training or held-out language result.
  • 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.