AI Wiki中文/EN

Contextual embeddings: one spelling, different representations

上下文词表示

Train a small bidirectional language model, prevent target leakage, derive layer mixing and distinguish context sensitivity from demonstrated semantic quality.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A river bank and a central bank share a spelling

Consider the invented phrases river bank floods and central bank lends. A static word lookup uses the same row for bank in both. A contextual representation instead computes a vector for this occurrence from the surrounding input. The question changes from “which vector belongs to this spelling?” to “which vector describes this token in this sequence?”

Word2vec learns useful static rows by pooling evidence across contexts. The basic lookup still returns one row per word type. Contextual encoding retains distinctions between occurrences instead of requiring that one row to serve every context. ELMo builds such representations from internal states of a bidirectional language model and combines multiple layers for a downstream task. ELMo, §§3.1–3.2

Different vectors do not prove that a model understands the different meanings. Even an untrained recurrent network changes its output when the input changes. A useful experiment must ask whether those changes help a task such as tagging, sense discrimination or retrieval under a specified evaluation protocol. Our small program makes context dependence visible without claiming to establish semantic competence.

The same word receives different vectors in two contexts. Loss and vector distance describe this tiny training run; they do not establish semantic quality.
The same word receives different vectors in two contexts. Loss and vector distance describe this tiny training run; they do not establish semantic quality.

Train predictions, then extract representations

Two directions with different information

For a token sequence x_1,…,x_n, a forward language model predicts each token from its prefix, while a backward model predicts it from its suffix:

P→(x1:n)=∏i=1np→(xi∣x<i),P←(x1:n)=∏i=1np←(xi∣x>i).P_{\rightarrow}(x_{1:n})=\prod_{i=1}^{n}p_{\rightarrow}(x_i\mid x_{<i}),\qquad P_{\leftarrow}(x_{1:n})=\prod_{i=1}^{n}p_{\leftarrow}(x_i\mid x_{>i}).

ELMo trains both directional objectives, sharing input-representation and output parameters between directions while keeping their recurrent parameters separate. Sharing the input table across directions does not mean tying that input table to the output table. Our implementation has distinct E and O arrays of the same shape; each array is used by both directions. ELMo, §3.1

The teaching model works over a fixed vocabulary of mapped classes, including UNK, and a fixed sequence length. It has no EOS prediction or distribution over lengths. Each directional product normalizes over the V^n mapped sequences of that fixed length. Different unknown spellings all map to UNK; the model does not assign its UNK probability independently to infinitely many raw spellings.

Across a corpus containing T observed tokens, minimize the mean loss over its 2T directional prediction targets:

L=−12T∑x in corpus∑i=1∣x∣[log⁡p→(xi∣x<i)+log⁡p←(xi∣x>i)].L=-\frac1{2T}\sum_{x\text{ in corpus}}\sum_{i=1}^{|x|}\left[\log p_{\rightarrow}(x_i\mid x_{<i})+\log p_{\leftarrow}(x_i\mid x_{>i})\right].

Longer sentences contribute more prediction targets. Averaging already-normalized sentence losses without length weights would optimize a different objective. Empty sentences add no targets; a corpus with no tokens is rejected.

A two-layer tanh model, not a miniature copy of ELMo

Let E have V rows of dimension D and let e_i be the input row for token x_i. For the forward direction, define h_i^(0)=e_i and initialize both recurrent layers at zero. With layer-specific input matrices A, recurrent matrices R and biases b:

hi(ℓ)=tanh⁡(A(ℓ)hi(ℓ−1)+R(ℓ)hi−1(ℓ)+b(ℓ)),ℓ∈{1,2}.h_i^{(\ell)}=\tanh\left(A^{(\ell)}h_i^{(\ell-1)}+R^{(\ell)}h_{i-1}^{(\ell)}+b^{(\ell)}\right),\qquad \ell\in\{1,2\}.

These matrices are D×D and the biases have D entries. The backward network applies the same construction to reversed token order with its own A, R and b. Its states are reversed back before aligning them with the original positions.

To predict x_i, use the top forward state before consuming x_i. With an output table O of shape V×D and output bias c:

zi=Ohi−1(2)+c,p→(xi=v∣x<i)=ezi,v∑u=1Vezi,u.z_i=O h_{i-1}^{(2)}+c,\qquad p_{\rightarrow}(x_i=v\mid x_{<i})=\frac{e^{z_{i,v}}}{\sum_{u=1}^{V}e^{z_{i,u}}}.

The analogous backward prediction uses the state built from x_(i+1),…,x_n. Giving either predictor a state that already contains its current target would let the answer leak into the input. The representation extracted after reading a token can include the token itself, but it cannot be reused as a target-blind predictor of that same token without changing the task.

ELMo uses character-based inputs and LSTM layers rather than this lookup/tanh network. The simpler network makes every derivative small enough to check directly; it does not reproduce ELMo’s gates, projection, pretraining scale or benchmark performance. ELMo model description

Backpropagation must follow both time and layers

For one unaveraged softmax loss, let δ_i=p_i−onehot(x_i). The output contributions are:

∂ℓi∂O=δi(hi−1(2))⊤,∂ℓi∂c=δi,∂ℓi∂hi−1(2)=O⊤δi.\frac{\partial\ell_i}{\partial O}=\delta_i\left(h_{i-1}^{(2)}\right)^\top,\qquad \frac{\partial\ell_i}{\partial c}=\delta_i,\qquad \frac{\partial\ell_i}{\partial h_{i-1}^{(2)}}=O^\top\delta_i.

That final contribution is added to any gradient already reaching the same state through later recurrent steps. For an accumulated state gradient g_i^(ℓ), the local preactivation gradient is d_i^(ℓ)=g_i^(ℓ) elementwise multiplied by 1−(h_i^(ℓ))². Its parameter and input contributions are:

∇A(ℓ)L+=di(ℓ)(hi(ℓ−1))⊤,∇R(ℓ)L+=di(ℓ)(hi−1(ℓ))⊤,∇b(ℓ)L+=di(ℓ).\nabla_{A^{(\ell)}}L\mathrel{+}=d_i^{(\ell)}\left(h_i^{(\ell-1)}\right)^\top,\quad \nabla_{R^{(\ell)}}L\mathrel{+}=d_i^{(\ell)}\left(h_{i-1}^{(\ell)}\right)^\top,\quad \nabla_{b^{(\ell)}}L\mathrel{+}=d_i^{(\ell)}.

Propagate Aᵀd to the lower layer at the same time and Rᵀd to the same layer at the preceding time. Traverse time backward and, at each step, visit the top layer before the lower one. Repeated word indices add into the same embedding row. Sum both directions’ contributions to shared parameters and apply the target-count normalization; separate directional matrices keep their own gradients. This is backpropagation through time, with both dependency axes made explicit.

The code removes common output components before computing logits and forms cross entropy from shifted logits. Softmax is invariant to a constant added to every class score; subtracting two huge absolute log values after the fact can lose the small difference that defines the loss. This numerical choice preserves the objective, but cannot recover information already rounded away in the supplied parameter arrays.

Extract layers and mix them for a task

After a token has been consumed, concatenate its forward and backward states to obtain a 2D-dimensional representation at each recurrent layer. Our input layer duplicates the D-dimensional lookup row to reach the same width:

ri,0=[ei;ei],ri,ℓ=[hi,→(ℓ);hi,←(ℓ)],ℓ=1,2.r_{i,0}=[e_i;e_i],\qquad r_{i,\ell}=[h_{i,\rightarrow}^{(\ell)};h_{i,\leftarrow}^{(\ell)}],\quad \ell=1,2.

Duplicating the input row is a stated teaching dimension convention, not a claim about ELMo’s character encoder. It leaves the static row identical for the same known spelling across contexts. The two recurrent layers can change with the surrounding sequence.

Let a_0,a_1,a_2 be learned scalar logits shared across the positions of a task, and γ a separate scalar scale. The mixed representation is:

sℓ=eaℓ∑j=02eaj,mi=∑ℓ=02sℓri,ℓ,vi=γmi.s_\ell=\frac{e^{a_\ell}}{\sum_{j=0}^{2}e^{a_j}},\qquad m_i=\sum_{\ell=0}^{2}s_\ell r_{i,\ell},\qquad v_i=\gamma m_i.

The s values are nonnegative and sum to one; γ is a free finite scale, not constrained to be positive. These global layer weights are different from token-to-token attention. The original ELMo formulation permits task-specific mixing and optionally layer normalization. The pinned bilm/elmo.py implements these choices; our example omits layer normalization. ELMo, equation 1 Pinned layer mixing

Given a downstream gradient g_i=∂J/∂v_i, differentiating the softmax mixture gives:

∂J∂aℓ=γsℓ∑igi⊤(ri,ℓ−mi),∂J∂γ=∑igi⊤mi,∂J∂ri,ℓ=γsℓgi.\frac{\partial J}{\partial a_\ell}=\gamma s_\ell\sum_i g_i^\top(r_{i,\ell}-m_i),\qquad \frac{\partial J}{\partial\gamma}=\sum_i g_i^\top m_i,\qquad \frac{\partial J}{\partial r_{i,\ell}}=\gamma s_\ell g_i.

For frozen encoder features, only the desired downstream parameters are updated; the layer-gradient expression is useful for checking the chain rule or for an explicitly fine-tuned variant. The program returns these derivatives but does not train a downstream task. Its default mixture has equal weights and γ=1, so the demo is not using task-learned layer weights.

For one token, take layers [1,0], [0,2], [2,1], equal weights and γ=2. Their mean is [1,1], the output is [2,2], and with upstream gradient [1,−1], the logit gradients are [2/3,−4/3,2/3] while the γ gradient is zero. A zero γ also makes the layer-logit and layer-value gradients zero, but need not make the γ gradient zero.

Two normalized directions do not make a normalized product

Adding the directional log likelihoods is equivalent to taking the log of their product. That product is not generally a normalized sentence model. For three vocabulary classes and length two, two uniform directions each assign 1/9 to each sequence. Their product assigns 1/81 to each of nine sequences, totaling 1/9 rather than one.

To interpret the product as a conditional-on-length sentence distribution, it would need its own normalizer:

P~(x∣n)=P→(x)P←(x)∑z∈VnP→(z)P←(z).\widetilde P(x\mid n)=\frac{P_{\rightarrow}(x)P_{\leftarrow}(x)}{\sum_{z\in\mathcal V^n}P_{\rightarrow}(z)P_{\leftarrow}(z)}.

The denominator depends on the parameters, so the sum of two directional training losses is not the negative log likelihood of this newly normalized model. Our program enumerates all nine mapped sequences in a tiny case to make that distinction observable; it does not train the normalized product.

Where BERT changes the setup

ELMo’s two directional recurrent models are combined when representations are extracted. BERT instead uses a bidirectional Transformer with a masked-language-model training task, so its hidden representation can combine available left and right context within its layers. The original BERT recipe selects 15% of token positions for prediction; among selected positions, 80% are replaced by MASK, 10% by a random token and 10% remain unchanged. These are conditional replacement proportions, not three percentages of the entire sequence. BERT, §3.1

The original paper also uses next-sentence prediction and discusses downstream fine-tuning. Those recipe details do not define every later contextual encoder. A masked-token loss is not automatically a left-to-right generative likelihood, just as combining two directional losses above is not automatically a normalized product model. No BERT encoder or masking trainer is implemented here. BERT method

Train and inspect two occurrences of bank

Save the following as contextual.py and run python contextual.py with Python 3.12.4 and NumPy 1.26.4. The invented training corpus has six sentences, 18 tokens, ten vocabulary classes including UNK, and 36 directional targets. The encoder uses D=3 and seed 31. It has 154 scalar parameters across 15 arrays; the separate finite-difference fixture uses D=2 and three classes, totaling 55 parameters.

"""Original two-layer bidirectional tanh LM and frozen layer mixing.

ELMo motivates the distinction between static and contextual representations.
This toy uses lookup inputs, tanh cells and fixed sequence length, not ELMo's
character CNN, projected LSTMs, large pretraining corpus or semantic benchmark.
"""
import itertools,json,math
import numpy as np
DIRECTIONS=('forward','backward')
PARAMETERS=('embedding','output','output_bias')+tuple(f'{direction}_{part}{layer}' for direction in DIRECTIONS for layer in (0,1) for part in ('x','h','b'))
UNK='<UNK>'


def word(value):
    if not isinstance(value,str) or not value or value==UNK or any(c.isspace() or 0xD800<=ord(c)<=0xDFFF for c in value):raise ValueError('Pretokenized nonempty words without reserved UNK required')
    return value


def initialize(sentences,dim=3,seed=31):
    if type(dim) is not int or dim<1 or type(seed) is not int or seed<0:raise ValueError('Positive dimension and nonnegative seed required')
    if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Training sentences required')
    tokens=set()
    for row in sentences:
        if not isinstance(row,(list,tuple)):raise ValueError('Pretokenized sentences required')
        tokens.update(word(w) for w in row)
    if not tokens:raise ValueError('At least one training token required')
    vocabulary=[UNK]+sorted(tokens);v=len(vocabulary);rng=np.random.default_rng(seed)
    model={'vocabulary':vocabulary,'embedding':rng.normal(0,.15,(v,dim)),'output':rng.normal(0,.15,(v,dim)),'output_bias':np.zeros(v)}
    for direction in DIRECTIONS:
        for layer in (0,1):
            for part in ('x','h'):model[f'{direction}_{part}{layer}']=rng.normal(0,.15,(dim,dim))
            model[f'{direction}_b{layer}']=np.zeros(dim)
    return model


def checked(model,words):
    if not isinstance(words,(list,tuple)):raise ValueError('Pretokenized sentence required')
    words=[word(w) for w in words];vocab=model['vocabulary'];p={k:np.asarray(model[k],dtype=float) for k in PARAMETERS}
    if not vocab or vocab[0]!=UNK or len(set(vocab))!=len(vocab) or p['embedding'].ndim!=2 or not all(p['embedding'].shape):raise ValueError('Vocabulary and embedding table required')
    v,d=p['embedding'].shape
    if len(vocab)!=v:raise ValueError('Vocabulary dimension mismatch')
    for key,value in p.items():
        expected=(v,d) if key in ('embedding','output') else (v,) if key=='output_bias' else (d,) if '_b' in key else (d,d)
        if value.shape!=expected or not np.isfinite(value).all():raise ValueError('Finite matching parameter arrays required')
    index={w:i for i,w in enumerate(vocab)};return p,[index.get(w,0) for w in words]


def softmax(values):
    a=np.asarray(values,dtype=float)
    if a.ndim!=1 or not len(a) or not np.isfinite(a).all():raise ValueError('Finite score vector required')
    shifted=a-a.max();weights=np.exp(shifted);return weights/weights.sum(),float(a.max()+math.log(float(weights.sum())))


def states(p,ids,direction):
    d=p['embedding'].shape[1];h=[np.zeros((len(ids)+1,d)),np.zeros((len(ids)+1,d))]
    try:
        with np.errstate(over='raise',invalid='raise'):
            for t,index in enumerate(ids):
                x=p['embedding'][index]
                for layer in (0,1):
                    h[layer][t+1]=np.tanh(p[f'{direction}_x{layer}']@x+p[f'{direction}_h{layer}']@h[layer][t]+p[f'{direction}_b{layer}']);x=h[layer][t+1]
    except FloatingPointError as error:raise ValueError('Recurrent state arithmetic overflow') from error
    return h


def centered_output(p):
    # A common output row and a common bias do not affect softmax probabilities.
    try:
        with np.errstate(over='raise',invalid='raise'):
            return p['output']-p['output'][0],p['output_bias']-p['output_bias'].max()
    except FloatingPointError as error:raise ValueError('Output contrast exceeds floating-point range') from error


def direction_loss(p,ids,direction):
    h=states(p,ids,direction);g={k:np.zeros_like(v) for k,v in p.items()};dh=[np.zeros_like(x) for x in h];total=0.;output,bias=centered_output(p)
    for t,index in enumerate(ids):
        logits=output@h[1][t]+bias;prob,_=softmax(logits)
        shifted=logits-logits.max();total+=math.log(float(np.exp(shifted).sum()))-shifted[index]
        delta=prob.copy();delta[index]-=1
        g['output']+=np.outer(delta,h[1][t]);g['output_bias']+=delta;dh[1][t]+=output.T@delta
    for t in range(len(ids)-1,-1,-1):
        for layer in (1,0):
            delta=dh[layer][t+1]*(1-h[layer][t+1]**2);x=p['embedding'][ids[t]] if layer==0 else h[0][t+1]
            xkey=f'{direction}_x{layer}';hkey=f'{direction}_h{layer}';bkey=f'{direction}_b{layer}'
            g[xkey]+=np.outer(delta,x);g[hkey]+=np.outer(delta,h[layer][t]);g[bkey]+=delta;dh[layer][t]+=p[hkey].T@delta
            if layer:dh[0][t+1]+=p[xkey].T@delta
            else:g['embedding'][ids[t]]+=p[xkey].T@delta
    return float(total),g,h


def loss_gradient(model,words):
    p,ids=checked(model,words)
    try:
        with np.errstate(over='raise',invalid='raise'):
            left,lg,_=direction_loss(p,ids,'forward');right,rg,_=direction_loss(p,ids[::-1],'backward')
            denominator=max(1,2*len(ids));gradient={k:(lg[k]+rg[k])/denominator for k in p}
    except FloatingPointError as error:raise ValueError('LM arithmetic exceeds the floating-point range') from error
    return (left+right)/denominator,gradient,{'forward_log_probability':-left,'backward_log_probability':-right,'targets':2*len(ids)}


def token_probabilities(model,words,direction='forward'):
    if direction not in DIRECTIONS:raise ValueError('Forward or backward required')
    p,ids=checked(model,words);ordered=ids if direction=='forward' else ids[::-1];h=states(p,ordered,direction);output,bias=centered_output(p)
    probabilities=np.array([softmax(output@h[1][i]+bias)[0] for i in range(len(ids))]).reshape(len(ids),len(model['vocabulary']))
    return probabilities if direction=='forward' else probabilities[::-1]


def mix(layers,logits=(0.,0.,0.),gamma=1.):
    layers=np.asarray(layers,dtype=float);scores=np.asarray(logits,dtype=float)
    if layers.ndim!=3 or scores.ndim!=1 or layers.shape[0]!=len(scores) or not layers.shape[0] or not layers.shape[2] or not np.isfinite(layers).all():raise ValueError('Finite layer/token/feature tensor required')
    if isinstance(gamma,bool) or not isinstance(gamma,(int,float)) or not math.isfinite(gamma):raise ValueError('Finite scalar scale required')
    weights,_=softmax(scores)
    try:
        with np.errstate(over='raise',invalid='raise'):
            average=np.tensordot(weights,layers,axes=(0,0));output=gamma*average
    except FloatingPointError as error:raise ValueError('Mixture arithmetic overflow') from error
    if not np.isfinite(output).all():raise ValueError('Nonfinite mixture')
    return output,weights,average


def mix_gradient(layers,upstream,logits=(0.,0.,0.),gamma=1.):
    layers=np.asarray(layers,dtype=float);upstream=np.asarray(upstream,dtype=float);output,weights,average=mix(layers,logits,gamma)
    if upstream.shape!=output.shape or not np.isfinite(upstream).all():raise ValueError('Finite matching output gradient required')
    return {'logits':gamma*weights*np.sum((layers-average[None])*upstream[None],axis=(1,2)),
            'gamma':float(np.sum(average*upstream)),'layers':gamma*weights[:,None,None]*upstream[None]}


def represent(model,words,logits=(0.,0.,0.),gamma=1.):
    p,ids=checked(model,words);left=states(p,ids,'forward');right=states(p,ids[::-1],'backward')
    static=p['embedding'][ids];layers=np.stack([np.concatenate([static,static],axis=1)]+[np.concatenate([left[layer][1:],right[layer][1:][::-1]],axis=1) for layer in (0,1)])
    vector,weights,_=mix(layers,logits,gamma)
    return {'layers':layers,'vectors':vector,'weights':weights,'gamma':gamma}


def train(initial,sentences,steps=80,rate=.8):
    if not isinstance(sentences,(list,tuple)) or not sentences or not sum(len(row) for row in sentences):raise ValueError('Nonempty token corpus required')
    if type(steps) is not int or steps<0 or isinstance(rate,bool) or not isinstance(rate,(int,float)) or not math.isfinite(rate) or rate<=0:raise ValueError('Nonnegative steps and positive finite rate required')
    model={k:(np.array(v,dtype=float,copy=True) if k in PARAMETERS else list(v)) for k,v in initial.items()}
    def batch(current):
        total=0.;targets=0;g={k:np.zeros_like(current[k]) for k in PARAMETERS}
        for words in sentences:
            loss,part,info=loss_gradient(current,words);count=info['targets'];total+=count*loss;targets+=count
            for k in g:g[k]+=count*part[k]
        return total/targets,{k:v/targets for k,v in g.items()}
    value,g=batch(model);trace=[value]
    for _ in range(steps):
        norm=sum(float(np.sum(v*v)) for v in g.values())
        if norm<1e-24:break
        step=rate
        for _ in range(40):
            candidate=dict(model)
            for k in PARAMETERS:candidate[k]=model[k]-step*g[k]
            try:new,ng=batch(candidate)
            except (ValueError,FloatingPointError):new=math.inf
            if new<=value-1e-4*step*norm:break
            step*=.5
        else:raise ValueError('No decreasing step found')
        model,value,g=candidate,new,ng;trace.append(value)
    return model,trace


def demo():
    corpus=[['river','bank','floods'],['river','bank','erodes'],['central','bank','lends'],['central','bank','closes'],['the','river','flows'],['the','bank','lends']]
    initial=initialize(corpus);model,trace=train(initial,corpus);queries=[corpus[0],corpus[2]];representations=[]
    for words in queries:
        before=represent(initial,words);after=represent(model,words)
        representations.append({'tokens':words,'before_bank_layers':before['layers'][:,1,:].tolist(),'after_bank_layers':after['layers'][:,1,:].tolist(),
             'mixed_bank_vector':after['vectors'][1].tolist(),'weights':after['weights'].tolist()})
    tiny=initialize([['a','b']],dim=2);mass={'forward':0.,'backward':0.,'product':0.}
    canonical=['unseen','a','b']
    for ids in itertools.product(range(3),repeat=2):
        _,_,info=loss_gradient(tiny,[canonical[i] for i in ids]);f=math.exp(info['forward_log_probability']);b=math.exp(info['backward_log_probability']);mass['forward']+=f;mass['backward']+=b;mass['product']+=f*b
    return {'training':corpus,'vocabulary':model['vocabulary'],'loss_trace':trace,'queries':representations,
            'mapped_length_two_mass':mass,'target_tokens':2*sum(map(len,corpus)),
            'scope':'Original two-layer tanh biLM with separate directional recurrence and shared input/output tables across directions. Fixed-length mapped-vocabulary likelihood, no EOS; token layer duplicated to match concatenated state dimensions. Frozen scalar layer mixing; no character CNN, LSTM, BERT implementation or semantic-quality claim.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

Full-batch backtracking takes up to 80 steps, starting each search at rate 0.8. Mean target loss decreases from about 2.302585 to 1.377451. This is a training-objective result on the supplied corpus, not a held-out language-model or semantic evaluation.

The static bank layer has distance zero between the two selected contexts, before and after training. For the first contextual layer, the Euclidean distance changes from about 0.017212 to 0.014709; the second changes from 0.003989 to 0.005057. Context differences existed even before training, and training did not increase every distance. Larger distance is not automatically better disambiguation. Coordinate scale, layer choice and downstream performance matter.

The tiny length-two enumeration sums each directional probability to approximately one, but the product to about 0.111111. The result concerns the three mapped vocabulary classes, not all possible raw words. Inspect the printed tensors and prediction probabilities rather than treating a loss curve as proof of word-sense learning.

With fixed two-layer depth, a length-n forward/backward pass costs O(nD²+nVD) arithmetic operations: recurrence plus full-vocabulary output. Stored hidden states cost O(nD); the implementation accumulates output gradients without retaining an n×V probability table during training. Parameters and their gradients cost O(VD+D²). Calling the separate token_probabilities helper does materialize n×V probabilities. An all-sequence normalization of the product by naive enumeration would instead involve V^n sequences, and is used only in the tiny diagnostic.

A useful representation needs a test beyond changing coordinates

The tanh network lacks LSTM gates, a character encoder and a Transformer’s attention. All unseen spellings share UNK, so changing one unknown spelling to another in the same context leaves the mapped input and resulting vectors unchanged. Subword or character inputs address a different limitation from contextualization itself; both choices must be stated.

A contextual cache must include the encoder version, tokenization and relevant context/window, not just a word string. Changing the sentence can change the answer for the same spelling. Truncation, subword pooling and which layer is extracted also change the representation supplied to a downstream model.

For a comparison, keep train/validation/test boundaries intact. Compare a static baseline, frozen contextual features and any fine-tuned system under the same data and supervision budget. State how token or sentence vectors are pooled and which similarity metric is used. Measure the actual task and inspect ambiguity/OOV/domain-shift cases; an attractive two-dimensional projection or one pair of cosine values does not establish general semantic quality.

The layer-mixing interface makes a clean experiment possible: freeze the same encoder and change only which layers the downstream task can use. In the ELMo setup discussed here, the encoder is fixed while task-specific capacity is added. That is a particular transfer protocol, not a rule that contextual encoders must always be frozen. ELMo transfer setup

Check what the vector and the loss mean

  1. Understanding. Should the forward prediction of the last token in [a,b,a] change when that last token becomes c, with all preceding tokens and parameters fixed?

Answer: No. It must use only the prefix [a,b]. The loss can change because the target class changes, but the predicted distribution cannot. The representation extracted after consuming the last token may change, because it serves a different purpose.

  1. Hand calculation. Mix [1,0], [0,2], [2,1] with equal weights and γ=2. What are the output and layer-logit gradients for upstream [1,−1]?

Answer: The mean is [1,1], so the output is [2,2]. Subtracting the mean from each layer and taking its dot product with the upstream vector gives 1,−2,1. Multiplying by 2/3 yields [2/3,−4/3,2/3]; these sum to zero, consistent with invariance to adding a constant to every mixing logit.

  1. Counterexample. Two uniform directional models each normalize over nine possible sequences. Does multiplying their probabilities preserve normalization?

Answer: Each product is (1/9)²=1/81, so the total is 9/81=1/9. A separate normalizer is needed. Its parameter dependence means simply adding the two training losses is not the same as fitting that normalized product.

  1. Method choice. A plotted bank pair is farther apart after fine-tuning. What additional evidence would support the claim that disambiguation improved?

Answer: Use a held-out, clearly labeled sense or downstream task with a matched baseline; record context windows, tokenization, layer, pooling and metric. Check multiple examples and relevant domain/OOV cases. A larger raw distance can come from a scale change, and looking at selected examples after fitting can overstate performance.

Representations, objectives and transfer protocols

The 2018 ELMo paper by Matthew E. Peters and colleagues supplies the directional LM and task-specific layer-mixing ideas. The inspected scope covers §§3.1–3.2 and the transfer description, with the relevant PDF page checked earlier; it does not certify a reproduction of the paper’s corpus, training configuration or benchmark tables. ELMo

The 2019 conference version of BERT by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova supplies the comparison of masked bidirectional pretraining and the original replacement recipe. The method scope is §3.1 and input representations; no BERT results are adopted as this project’s experiments. BERT

The ELMo mixing code is pinned to allenai/bilm-tf commit 7cffee2b0986be51f5e2a747244836e1047657f4, with bilm/elmo.py lines 1–115 inspected. It includes free γ, softmax weights and optional normalization. No upstream training program was run. The original example here is checked with complete-parameter finite differences, directional non-leakage, reversal symmetry, exact small normalization sums and mixture derivatives. Fixed code

Make a prediction, then check

Two uniform directional models each assign1/9 to nine possible sequences. What is the total mass of their pointwise product?

Choose one answer

Learning objectives

  • Separate static word types from contextual token occurrences.
  • Train two directional objectives without revealing the current target.
  • Derive full BPTT and scalar layer-mixture gradients.
  • Distinguish directional likelihoods, their product and semantic evaluation.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep contextualized word representations
    Matthew E. Peters; Mark Neumann; Mohit Iyyer; Matt Gardner; Christopher Clark; Kenton Lee; Luke Zettlemoyer · 2018
  2. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
    Jacob Devlin; Ming-Wei Chang; Kenton Lee; Kristina Toutanova · 2019
  3. ELMo scalar layer mixing, pinned author code
    Allen Institute for Artificial Intelligence and bilm-tf contributors · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Codex single-AI-author technical check: scoped ELMo/BERT methods and pinned bilm-tf scalar mix; ten paired equations and four explained exercises. Two-layer bidirectional tanh teaching LM differs from ELMo LSTM/character CNN and BERT. Before-token prediction versus after-token representation, 55-parameter complete finite differences, 154-parameter toy training, frozen softmax layer mix/free gamma gradients, directional probability masses versus unnormalized product, conditional 80/10/10 masking and explicit dense costs. Toy loss/vector distances do not establish semantic quality.

  • Codex single-AI-author technical check: scoped ELMo/BERT methods and pinned bilm-tf scalar mix; ten paired equations and four explained exercises. Two-layer bidirectional tanh teaching LM differs from ELMo LSTM/character CNN and BERT. Before-token prediction versus after-token representation, 55-parameter complete finite differences, 154-parameter toy training, frozen softmax layer mix/free gamma gradients, directional probability masses versus unnormalized product, conditional 80/10/10 masking and explicit dense costs. Toy loss/vector distances do not establish semantic quality.
  • Four original SVGs bind the exact MDX program. Nine figure tests validate numeric results, encodings and dependency arc geometry. Thirty standalone language/width cases and four fallback fonts passed; ten desktop/mobile screenshots were actually inspected. The original false arc crossing and its correction evidence are preserved. Complete article browser acceptance is separate; no human peer review or upstream execution.

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.