Module contents
Lesson 18 of 24Core 120 min

Additive attention: jointly learning to align and translate

Derive additive attention and its gradient, interpret soft and hard alignment, and examine recurrent sequence-to-sequence experiments with careful empirical limits.

After this lesson you can

  • Write additive-attention equations with explicit shapes inside a decoder step.
  • Derive the backward pass through weighted sum, softmax, and scoring network.
  • Implement a NumPy seq2seq with additive attention and check gradients.
  • Interpret soft alignment and compare it with hard alignment.
  • Explain direct gradient paths and the limits of attention's bottleneck relief.
  • Distinguish soft and hard attention and explain score-function estimators.

Before you start

Consult the entire source

In the fixed-context encoder-decoder, every output word depends on a summary that must traverse the whole sentence. As input grows, that path becomes more demanding. Attention gives the decoder a different read at each step: it compares its state with every encoder annotation and combines relevant ones. Bahdanau, Cho and Bengio learned these comparisons jointly with translation, without alignment labels for each word pair.

A predecessor is the Gaussian window Graves used to condition handwriting generation on text. That window advances through the text; here a network scores every source position and may revisit it. They are related, not identical mechanisms.

Shapes and computation order

A bidirectional encoder produces hj=[h→j;h←j]∈Rdhh_j=[\overrightarrow h_j;\overleftarrow h_j]\in\R^{d_h}. At step ii the query is previous state si−1∈Rdss_{i-1}\in\R^{d_s}. Additive attention uses W∈Rda×dsW\in\R^{d_a\times d_s}, U∈Rda×dhU\in\R^{d_a\times d_h} and v∈Rdav\in\R^{d_a}:

eij=v⊤tanh⁡(Wsi−1+Uhj),αij=exp⁡eij∑k∈vaˊlidosexp⁡eik,ci=∑jαijhj.e_{ij}=v^\top\tanh(Ws_{i-1}+Uh_j),\qquad \alpha_{ij}=\frac{\exp e_{ij}}{\sum_{k\in\mathrm{válidos}}\exp e_{ik}},\qquad c_i=\sum_j\alpha_{ij}h_j.

In a batch, ss has shape (B,ds)(B,d_s) and annotations (B,Tx,dh)(B,T_x,d_h); scores and weights are (B,Tx)(B,T_x) and context (B,dh)(B,d_h). Softmax acts over source, not batch. Mask padding before applying it; every row must have a valid position. Annotations are reused throughout output, so UhjUh_j can be computed once per sentence. The next step uses si=f(si−1,yi−1,ci)s_i=f(s_{i-1},y_{i-1},c_i) and produces logits from its new state. If scoring requested sis_i while that needed cic_i, there would be a circular dependency: sis_i requires a different step organization.

The encoder can traverse the source both ways because the whole input sentence is available before generation. Its two states at a position collect information from both sides; the decoder has only previous output words. Training uses the previous reference word and generation uses the previous prediction. The difference can accumulate errors even when training alignments look correct.

For a batch with varying lengths, first calculate a valid indicator per position. Assigning −∞-\infty to padding logits before softmax makes their exponentials zero. Setting weights to zero after normalization instead stops them summing to one unless renormalized. A row without valid words has no defined distribution: rejecting it is clearer than turning division by zero into an apparently valid answer. Subtracting the valid maximum before exponentiation prevents overflow without changing weights.

If UhUh is cached, each query computes WsWs once and v⊤qjv^\top q_j for each position. These multiplications cost dsda+Txdad_s d_a+T_xd_a per step; vector addition, tanh, and context formation also cost work growing with TxdhT_xd_h. Without caching, projections UhjUh_j add TxdhdaT_xd_hd_a per step. Cache occupies memory and must be recomputed when parameters or annotations change; within one sentence and model pass both stay fixed.

Weights form a soft alignment: each row sums to one and context lies in the convex hull of valid annotations. It is a learned reading distribution, not causal proof that one word determined another. A position can receive high weight yet an intervention on it can have a different effect due to vector content and the rest of the network.

InteractiveThe score field
h1h2h3contextquery
h1: 0.272
h2: 0.589
h3: 0.140

Darker blue indicates a higher score. W = [[1, 0.4], [−0.3, 1]], U = [[1, −0.3], [0.5, 1]] and v = (1.2, −0.9) are used. The triangle bounds convex combinations of the annotations.

0.20
0.20
Context x0.267
Context y−0.289
A fixed two-unit perceptron scores three annotations. Drag the query or use sliders; the background shows possible scores and the triangle is the convex hull of the three values.

Derive the backward path

Let g=∂L/∂cig=\partial L/\partial c_i. The weighted sum gives direct contributions αijg\alpha_{ij}g to each hjh_j and ∂L/∂αij=g⊤hj\partial L/\partial\alpha_{ij}=g^\top h_j. The softmax vector–Jacobian product gives

∂L∂eij=αij g⊤(hj−ci),∑j∂L∂eij=0.\frac{\partial L}{\partial e_{ij}}=\alpha_{ij}\,g^\top(h_j-c_i), \qquad \sum_j\frac{\partial L}{\partial e_{ij}}=0.

The equality follows by substituting ci=∑jαijhjc_i=\sum_j\alpha_{ij}h_j and ∑jαij=1\sum_j\alpha_{ij}=1. Masked positions receive zero weight and gradient. The additive backward pass continues through qj=tanh⁡(Ws+Uhj)q_j=\tanh(Ws+Uh_j): qˉj=eˉjv\bar q_j=\bar e_jv, zˉj=qˉj⊙(1−qj2)\bar z_j=\bar q_j\odot(1-q_j^2); accumulate Wˉ\bar W, Uˉ\bar U, vˉ\bar v, the query, and a second contribution to each annotation. Encoder gradients sum this path with other model routes.

The zero sum has a useful interpretation: adding the same constant to all valid scores leaves softmax unchanged, so loss is unchanged in that common direction. This does not mean every individual gradient is zero; some may be positive and others negative. If an annotation matches context along gg, its contribution to eˉj\bar e_j is zero for that particular loss.

The central-difference check perturbs every query, annotation, and parameter component while holding the mask fixed. It independently tests the analytic derivative but depends on scale and perturbation size. It also checks sum one, padding zeros, and zero sum of eˉ\bar e. In a real model repeat at small dimensions and then compare a complete batch’s loss and gradients; a shape test misses some indexing errors.

[ ]Masked additive attention and gradientBrowser
import numpy as np

def attention_forward(s, h, mask, W, U, v, uh=None):
    if not np.all(mask.any(axis=1)): raise ValueError('cada fila necesita una fuente válida')
    if uh is None: uh = h @ U.T
    z = (s @ W.T)[:, None, :] + uh
    q = np.tanh(z)
    e = q @ v
    e = np.where(mask, e, -np.inf)
    a = np.exp(e - e.max(axis=1, keepdims=True))
    a /= a.sum(axis=1, keepdims=True)
    c = np.einsum('bt,bth->bh', a, h)
    return c, a, (s, h, W, U, v, q, a, c)

def attention_backward(dc, cache):
    s, h, W, U, v, q, a, c = cache
    de = a * np.einsum('bh,bth->bt', dc, h-c[:, None, :])
    dz = de[:, :, None] * v * (1-q*q)
    ds = dz.sum(axis=1) @ W
    dh = a[:, :, None]*dc[:, None, :] + dz @ U
    dW = dz.sum(axis=1).T @ s
    dU = np.einsum('bta,bth->ah', dz, h)
    dv = np.einsum('bt,bta->a', de, q)
    return ds, dh, dW, dU, dv, de

rng = np.random.default_rng(18)
s = rng.normal(size=(2,3)); h = rng.normal(size=(2,4,5))
W = rng.normal(size=(6,3)); U = rng.normal(size=(6,5)); v = rng.normal(size=6)
mask = np.array([[1,1,1,0], [1,1,0,0]], dtype=bool)
dc = rng.normal(size=(2,5))
c, a, cache = attention_forward(s,h,mask,W,U,v)
grads = attention_backward(dc,cache)
def objective(): return float((attention_forward(s,h,mask,W,U,v)[0]*dc).sum())
largest = 0.
for array, grad in zip((s,h,W,U,v), grads[:5]):
    for idx in np.ndindex(array.shape):
        old = array[idx]; array[idx] = old+1e-5; plus = objective()
        array[idx] = old-1e-5; minus = objective(); array[idx] = old
        largest = max(largest, abs((plus-minus)/2e-5-grad[idx]))
assert np.allclose(a.sum(1),1) and np.all(a[~mask] == 0)
assert np.allclose(grads[-1].sum(1),0) and largest < 1e-7
print('Error absoluto máximo de diferencias centrales:', largest)

Read an average or sample a position

In soft and hard attention, the same probability vector supports two different operations. The first uses c=∑jαjhjc=\sum_j\alpha_jh_j and permits differentiating loss through that sum. The second samples a discrete position J∼αJ\sim\alpha and uses hJh_J; ordinary differentiation cannot pass through the sampled index. A score-function estimator, known as REINFORCE, uses ℓ(hJ)∇θlog⁡αJ\ell(h_J)\nabla_\theta\log\alpha_J to estimate the gradient of E[ℓ(hJ)]\E[\ell(h_J)]. A baseline independent of JJ can reduce variance without changing expectation. Xu and colleagues studied both variants for image captioning.

Distinguish ℓ(E[hJ])\ell(\E[h_J]) from E[ℓ(hJ)]\E[\ell(h_J)]: for nonlinear loss they usually differ. The next experiment uses h=(−1,0,2)h=(-1,0,2), ej=θhje_j=\theta h_j, and squared loss against a target. It enumerates the expected hard-loss gradient and compares it with the sample average; the soft gradient belongs to another objective. The variance of the mean is divided by NN under independent sampling. A seeded pseudorandom sequence makes the demonstration repeatable.

InteractiveExpectation versus sample

Attention values: −1, 0 and 2. Their probabilities are 0.172 · 0.257 · 0.571. Loss is squared distance to the target.

-102Blue: soft · orange: sample

Variance of the mean of 50 independent samples is 0.1243. Seed 18 determines this reproducible sequence.

0.4
0.5
50
Soft context0.970
Last hard sample2
Exact soft gradient1.426
Exact hard gradient0.498
REINFORCE mean−0.188
Single-sample variance6.214
Explicit three-position model. Change scores, target, and sample count; compare two distinct objectives and the hard estimator's variance.

A complete sequential model

The lab maintains two independent GRUs to traverse the source in opposite directions; it concatenates their states and computes context before each decoder update. Decoder input joins the previous symbol and context. Backward accumulates gradients from every query onto each annotation and traverses both GRUs in reverse computation order. Sigmoid preactivations are clipped to ±60 to avoid overflow; backward zeros derivatives outside that interval and takes zero at the boundary. Output uses a linear head and per-symbol loss. The next check visits every parameter of a small model with central differences; it tests code numerically, not quality.

[ ]Bidirectional encoder, decoder, and backwardBrowser
import numpy as np

def init_gru(rng, din, width):
    return {'wx':rng.normal(0,.12,(din,3*width)), 'wh':rng.normal(0,.12,(width,3*width)),
            'bi':np.zeros(3*width), 'bh':np.zeros(3*width)}

def gru(x,h,p):
    xr,xz,xn=np.split(x@p['wx']+p['bi'],3)
    hr,hz,hn=np.split(h@p['wh']+p['bh'],3)
    ar=xr+hr; az=xz+hz
    r=1/(1+np.exp(-np.clip(ar,-60,60)))
    z=1/(1+np.exp(-np.clip(az,-60,60)))
    n=np.tanh(xn+r*hn)
    return (1-z)*n+z*h,(x,h,r,z,n,hn,p,abs(ar)<60,abs(az)<60)

def gru_back(dh,cache):
    x,h,r,z,n,hn,p,active_r,active_z=cache
    dan=dh*(1-z)*(1-n*n); dar=dan*hn*r*(1-r)*active_r; daz=dh*(h-n)*z*(1-z)*active_z
    di=np.concatenate((dar,daz,dan)); dr=np.concatenate((dar,daz,dan*r))
    grads={'wx':np.outer(x,di),'wh':np.outer(h,dr),'bi':di,'bh':dr}
    return di@p['wx'].T, dh*z+dr@p['wh'].T, grads

def zeros(p): return {k:np.zeros_like(v) for k,v in p.items()}
def add(a,b):
    for k in a: a[k]+=b[k]

class AttentionSeq2Seq:
    def __init__(self, vocab, width=12, align=12, seed=18):
        rng=np.random.default_rng(seed); self.vocab=vocab; self.width=width; self.eye=np.eye(vocab)
        self.enc_f=init_gru(rng,vocab,width); self.enc_b=init_gru(rng,vocab,width)
        self.dec=init_gru(rng,vocab+2*width,width)
        self.att={'W':rng.normal(0,.12,(align,width)), 'U':rng.normal(0,.12,(align,2*width)), 'v':rng.normal(0,.12,align)}
        self.out={'w':rng.normal(0,.12,(width,vocab)), 'b':np.zeros(vocab)}
    def params(self): return (self.enc_f,self.enc_b,self.dec,self.att,self.out)
    def encode(self,src):
        width=self.width; states_f=[]; states_b=[None]*len(src); caches_f=[]; caches_b=[None]*len(src)
        h=np.zeros(width)
        for token in src:
            h,cache=gru(self.eye[token],h,self.enc_f); states_f.append(h); caches_f.append(cache)
        h=np.zeros(width)
        for i in range(len(src)-1,-1,-1):
            h,cache=gru(self.eye[src[i]],h,self.enc_b); states_b[i]=h; caches_b[i]=cache
        return np.concatenate((np.array(states_f),np.array(states_b)),axis=1),caches_f,caches_b
    def loss_grad(self,src,target,bos):
        ann,cf,cb=self.encode(src); state=np.zeros(self.width); previous=bos; steps=[]; loss=0.
        mask=np.ones((1,len(src)),dtype=bool); projected=([email protected]['U'].T)[None,:,:]
        for token in target:
            context,alpha,ac=attention_forward(state[None,:],ann[None,:,:],mask,**self.att,uh=projected)
            state,dc=gru(np.concatenate((self.eye[previous],context[0])),state,self.dec)
            [email protected]['w']+self.out['b']; p=np.exp(logits-logits.max()); p/=p.sum()
            loss-=np.log(p[token])/len(target); steps.append((state,p,token,dc,ac)); previous=token
        gf,gb,gd,ga,go=(zeros(p) for p in self.params()); dann=np.zeros_like(ann); dh=np.zeros(self.width)
        for state,p,token,dc,ac in reversed(steps):
            dl=p.copy(); dl[token]-=1; dl/=len(target)
            go['w']+=np.outer(state,dl); go['b']+=dl; [email protected]['w'].T
            dx,dh,g=gru_back(dh,dc); add(gd,g)
            ds,da,dW,dU,dv,_=attention_backward(dx[self.vocab:][None,:],ac)
            dh+=ds[0]; dann+=da[0]; ga['W']+=dW; ga['U']+=dU; ga['v']+=dv
        dh=np.zeros(self.width)
        for i in range(len(src)-1,-1,-1):
            _,dh,g=gru_back(dh+dann[i,:self.width],cf[i]); add(gf,g)
        dh=np.zeros(self.width)
        for i in range(len(src)):
            _,dh,g=gru_back(dh+dann[i,self.width:],cb[i]); add(gb,g)
        return loss,(gf,gb,gd,ga,go)
    def predict(self,src,bos,eos,limit=24):
        ann,_,_=self.encode(src); state=np.zeros(self.width); previous=bos; out=[]; weights=[]
        mask=np.ones((1,len(src)),dtype=bool); projected=([email protected]['U'].T)[None,:,:]
        for _ in range(limit):
            context,alpha,_=attention_forward(state[None,:],ann[None,:,:],mask,**self.att,uh=projected)
            state,_=gru(np.concatenate((self.eye[previous],context[0])),state,self.dec)
            previous=int(np.argmax([email protected]['w']+self.out['b'])); weights.append(alpha[0].copy())
            if previous==eos: break
            out.append(previous)
        return out,np.array(weights)
    def update(self,grads,lr=.05):
        norm=np.sqrt(sum((x*x).sum() for g in grads for x in g.values()))
        scale=min(1.,1./max(norm,1e-12))
        for p,g in zip(self.params(),grads):
            for name in p: p[name]-=lr*scale*g[name]

def check_model():
    m=AttentionSeq2Seq(8,width=3,align=3); src=[0,2,3]; target=[3,2,0,7]
    loss,grads=m.loss_grad(src,target,6); worst=0.
    for p,g in zip(m.params(),grads):
        for name in p:
            a=p[name]
            for index in np.ndindex(a.shape):
                old=a[index]; a[index]=old+1e-5; plus=m.loss_grad(src,target,6)[0]
                a[index]=old-1e-5; minus=m.loss_grad(src,target,6)[0]; a[index]=old
                worst=max(worst,abs((plus-minus)/2e-5-g[name][index]))
    assert worst<1e-7
    return worst

print('Error máximo del modelo secuencial:', check_model())

Normalize dates and observe alignments

The next example tokenizes a Spanish date into three categories: day, month, year. The decoder learns to return year, month, day, and a stop token. It accepts only valid dates in 2024 through 2026 and is not a general text parser. Training and validation combinations are split using a fixed seed, although individual components appear in both sets. The cell takes 30 steps to check flow; continue in blocks with train_dates_block and evaluate exact match using evaluate_dates.

[ ]Train dates in blocksBrowser
import calendar
MONTHS=['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre']
BOS,EOS,VOCAB=46,47,48
def date_tokens(day,month,year): return [day-1,31+month-1,43+year-2024]
def date_pair(day,month,year):
    source=date_tokens(day,month,year)
    return source,[source[2],source[1],source[0],EOS]
dates=[(d,m,y) for y in range(2024,2027) for m in range(1,13) for d in range(1,calendar.monthrange(y,m)[1]+1)]
split_rng=np.random.default_rng(1818); order=split_rng.permutation(len(dates)); cut=int(.8*len(dates))
train_dates=[dates[i] for i in order[:cut]]; test_dates=[dates[i] for i in order[cut:]]
date_rng=np.random.default_rng(1819); date_model=AttentionSeq2Seq(VOCAB,width=24,align=24,seed=18); date_steps=0; optimizer_steps=0
first=[zeros(p) for p in date_model.params()]; second=[zeros(p) for p in date_model.params()]
def train_dates_block(n=100):
    global date_steps,optimizer_steps
    last=0.
    for _ in range(n):
        day,month,year=train_dates[int(date_rng.integers(len(train_dates)))]
        src,target=date_pair(day,month,year); last,g=date_model.loss_grad(src,target,BOS); date_steps+=1; optimizer_steps+=1
        norm=np.sqrt(sum((x*x).sum() for group in g for x in group.values())); scale=min(1.,1./max(norm,1e-12))
        for p,grad,m,v in zip(date_model.params(),g,first,second):
            for name in p:
                d=grad[name]*scale; m[name]=.9*m[name]+.1*d; v[name]=.999*v[name]+.001*d*d
                p[name]-=.003*(m[name]/(1-.9**optimizer_steps))/(np.sqrt(v[name]/(1-.999**optimizer_steps))+1e-8)
    return {'step':date_steps,'last_loss':float(last)}
def evaluate_dates(rows=test_dates):
    correct=0
    for day,month,year in rows:
        src,target=date_pair(day,month,year); result,_=date_model.predict(src,BOS,EOS,limit=4)
        correct+=result==target[:-1]
    return {'correct':correct,'total':len(rows)}
def infer_date(day,month,year):
    if year not in range(2024,2027) or month not in range(1,13) or day not in range(1,calendar.monthrange(year,month)[1]+1):
        raise ValueError('fecha fuera del vocabulario o no válida')
    src=date_tokens(day,month,year); result,weights=date_model.predict(src,BOS,EOS,limit=4)
    names=[str(day),MONTHS[month-1],str(year)]
    def render(token):
        if 0<=token<31: return str(token+1).zfill(2)
        if 31<=token<43: return str(token-30).zfill(2)
        if 43<=token<46: return str(token-43+2024)
        return '<otro>'
    words=[render(token) for token in result]
    text='-'.join(words) if len(words)==3 else ' '.join(words)
    labels=words+(['<eos>'] if len(words)<len(weights) else [])
    return {'input':names,'output':labels,'text':text,'weights':weights.tolist(),'steps':date_steps,'finished':len(words)<len(weights)}

def load_date_weights(data):
    global date_steps,optimizer_steps,first,second
    for group,saved in zip(date_model.params(),data['weights']):
        if set(group)!=set(saved): raise ValueError('parámetros incompatibles')
        for key in group:
            value=np.asarray(saved[key],dtype=float)
            if value.shape!=group[key].shape or not np.isfinite(value).all(): raise ValueError('forma o valor inválido')
            group[key][...]=value
    date_steps=int(data['steps']); optimizer_steps=0
    first=[zeros(p) for p in date_model.params()]; second=[zeros(p) for p in date_model.params()]
    return {'step':date_steps}
print('Comprobación corta:', train_dates_block(30))

In one 10 000-update run, model seed 18 and split 1818, the model got all 220 held-out combinations from 2024 through 2026 right. All share categories with training: this does not test generalization to new years, words, or formats. For 25 de octubre de 2026 it produced 2026-10-25; its first three rows assigned greatest weight to year, month, and day respectively. The figure can load those recorded weights in the same NumPy code or query the model trained in your session. Loading resets Adam moments; continuing does not exactly reproduce the original trajectory.

InteractiveLive alignments

Run the three NumPy cells, then load recorded weights or query your model.

After running the three cells, load recorded 10 000-step weights or query your own model. The parser accepts only the displayed format and years 2024 through 2026.

A direct path, cautiously interpreted

Attention lets a step’s loss reach each annotation directly through context, as well as through recurrent paths. In the simplified graph below, an input passes to its encoder state, then context, decoder state, and logits: four edges. The baseline passes through the final encoder state and decoder chain. Counting edges does not guarantee gradient magnitude: attention weights, recurrent Jacobians, and cancellations matter. Nor does it remove every capacity limitation.

The attached measurement compares a fixed-context encoder-decoder from the previous lesson’s family with this lesson’s bidirectional model, both untrained, on one synthetic sequence and with different seeds. It computes the gradient of one step’s loss with respect to each source position’s one-hot vector. This inspects those initializations, not a controlled quality comparison or proof of superiority. The cell reproduces the values with manual backward passes.

InteractiveGradient shortcuts

A synthetic sample of five symbols and two models initialized with seeds 1718 and 1818. Each norm is the gradient of one output-step loss with respect to the selected position’s input vector.

SourceOutput1122334455
Fixed path
x1h1h2h3h4h5s1logits1
Direct attention path
x1h1c1s1logits1

The comparison counts from input to logits and includes the direct value edge to context. Weights, architecture and seed also affect the norm; a short path does not guarantee a large gradient.

1
1
Edges, fixed context7
Edges, attention4
Fixed-context norm0.00218
Attention norm0.00839
Select positions. Distances correspond to the described graph; norms are from two untrained initialized models on one synthetic sample.
[ ]Measure gradients toward the sourceBrowser
def baseline_input_grad(src,target,output_index,enc,dec,head,eye):
    width=enc['wh'].shape[0]; state=np.zeros(width); ec=[]; dc=[]; logits_list=[]; previous=14
    for token in src:
        state,cache=gru(eye[token],state,enc); ec.append(cache)
    for token in target:
        state,cache=gru(eye[previous],state,dec); logits=state@head['w']+head['b']
        p=np.exp(logits-logits.max());p/=p.sum();dc.append(cache);logits_list.append(p);previous=token
    dh=np.zeros(width)
    for i in range(len(target)-1,-1,-1):
        dl=np.zeros_like(logits_list[i])
        if i==output_index: dl=logits_list[i].copy();dl[target[i]]-=1
        dh+=dl@head['w'].T; _,dh,_=gru_back(dh,dc[i])
    dx=np.zeros((len(src),eye.shape[1]))
    for i in range(len(src)-1,-1,-1): dx[i],dh,_=gru_back(dh,ec[i])
    return np.linalg.norm(dx,axis=1)

def attentive_input_grad(model,src,target,output_index):
    ann,cf,cb=model.encode(src); state=np.zeros(model.width); previous=14; steps=[]
    mask=np.ones((1,len(src)),dtype=bool); projected=([email protected]['U'].T)[None,:,:]
    for token in target:
        context,_,ac=attention_forward(state[None,:],ann[None,:,:],mask,**model.att,uh=projected)
        state,cache=gru(np.concatenate((model.eye[previous],context[0])),state,model.dec)
        [email protected]['w']+model.out['b'];p=np.exp(logits-logits.max());p/=p.sum()
        steps.append((p,token,cache,ac));previous=token
    dh=np.zeros(model.width);dann=np.zeros_like(ann)
    for i in range(len(target)-1,-1,-1):
        p,token,cache,ac=steps[i]; dl=np.zeros_like(p)
        if i==output_index:dl=p.copy();dl[token]-=1
        [email protected]['w'].T;dx,dh,_=gru_back(dh,cache)
        ds,da,*_=attention_backward(dx[model.vocab:][None,:],ac);dh+=ds[0];dann+=da[0]
    dx=np.zeros((len(src),model.vocab));dh=np.zeros(model.width)
    for i in range(len(src)-1,-1,-1):
        part,dh,_=gru_back(dh+dann[i,:model.width],cf[i]);dx[i]+=part
    dh=np.zeros(model.width)
    for i in range(len(src)):
        part,dh,_=gru_back(dh+dann[i,model.width:],cb[i]);dx[i]+=part
    return np.linalg.norm(dx,axis=1)

def measure_paths():
    rng=np.random.default_rng(1718); width=12; size=16; eye=np.eye(size)
    enc=init_gru(rng,size,width); dec=init_gru(rng,size,width)
    head={'w':rng.normal(0,.12,(width,size)),'b':np.zeros(size)}
    attentive=AttentionSeq2Seq(size,width=width,align=width,seed=1818)
    src=[0,1,2,3,4]; target=[4,3,2,1,0]
    fixed=np.array([baseline_input_grad(src,target,i,enc,dec,head,eye) for i in range(5)])
    bypass=np.array([attentive_input_grad(attentive,src,target,i) for i in range(5)])
    return {'fixed':fixed.tolist(),'attention':bypass.tolist(),'source':src,'target':target,
            'description':'Inicialización de modelos sin entrenar, una muestra y semillas 1718 y 1818.'}
path_measurements=measure_paths()
print('Normas para fuente 1 y salida 1:', path_measurements['fixed'][0][0], path_measurements['attention'][0][0])

Reversing long sequences

This experiment compares the manual attention model with a fixed-context baseline from the previous lesson’s family. Both receive the same sequences and Adam updates; architectures and seeds differ, so the result does not isolate every effect. Training uses lengths 2 through 5 with distinct held-out sequences at those lengths; lengths 6 through 9 test extrapolation. Success requires reproducing the entire reversed sequence and stopping. The default run takes 50 steps to check flow; call train_reversal(10000) for a longer trial and record results.

[ ]Reversal with and without attentionBrowser
import itertools
class FixedSeq2Seq:
    def __init__(self,vocab=16,width=12,seed=18):
        rng=np.random.default_rng(seed); self.eye=np.eye(vocab);self.width=width
        self.enc=init_gru(rng,vocab,width);self.dec=init_gru(rng,vocab,width)
        self.out={'w':rng.normal(0,.12,(width,vocab)),'b':np.zeros(vocab)}
    def params(self):return (self.enc,self.dec,self.out)
    def loss_grad(self,src,target,bos=14):
        h=np.zeros(self.width);ec=[];dc=[];states=[];prob=[];previous=bos;loss=0.
        for token in src:h,cache=gru(self.eye[token],h,self.enc);ec.append(cache)
        for token in target:
            h,cache=gru(self.eye[previous],h,self.dec);[email protected]['w']+self.out['b'];p=np.exp(logit-logit.max());p/=p.sum()
            loss-=np.log(p[token])/len(target);states.append(h);prob.append(p);dc.append(cache);previous=token
        ge,gd,go=(zeros(p) for p in self.params());dh=np.zeros(self.width)
        for i in range(len(target)-1,-1,-1):
            dl=prob[i].copy();dl[target[i]]-=1;dl/=len(target)
            go['w']+=np.outer(states[i],dl);go['b']+=dl;[email protected]['w'].T
            _,dh,g=gru_back(dh,dc[i]);add(gd,g)
        for cache in reversed(ec):_,dh,g=gru_back(dh,cache);add(ge,g)
        return loss,(ge,gd,go)
    def predict(self,src,bos=14,eos=15,limit=12):
        h=np.zeros(self.width)
        for token in src:h,_=gru(self.eye[token],h,self.enc)
        prev=bos;out=[]
        for _ in range(limit):
            h,_=gru(self.eye[prev],h,self.dec);prev=int(np.argmax([email protected]['w']+self.out['b']))
            if prev==eos:break
            out.append(prev)
        return out

def reversal_split():
    rng=np.random.default_rng(1718); training=[];test={}
    for length in range(2,10):
        if length<=5:
            population=list(itertools.product(range(5),repeat=length)); order=rng.permutation(len(population))
            count={2:15,3:80,4:300,5:600}[length]
            training.extend([population[i] for i in order[:count]])
            test[length]=[population[i] for i in order[count:count+min(100,len(population)-count)]]
        else:
            seen=set()
            while len(seen)<100:seen.add(tuple(rng.integers(0,5,size=length)))
            test[length]=sorted(seen)
    return training,test

def train_reversal(steps=50):
    training,test=reversal_split(); models=[FixedSeq2Seq(seed=1718),AttentionSeq2Seq(16,width=12,align=12,seed=1818)]
    moments=[[zeros(p) for p in m.params()] for m in models]; variances=[[zeros(p) for p in m.params()] for m in models]
    rng=np.random.default_rng(1918)
    for step_index in range(1,steps+1):
        src=training[int(rng.integers(len(training)))]; target=list(src[::-1])+[15]
        for model,first,second in zip(models,moments,variances):
            loss,grads=model.loss_grad(src,target,14)
            norm=np.sqrt(sum((x*x).sum() for g in grads for x in g.values()));scale=min(1.,1./max(norm,1e-12))
            for p,g,m,v in zip(model.params(),grads,first,second):
                for key in p:
                    d=g[key]*scale;m[key]=.9*m[key]+.1*d;v[key]=.999*v[key]+.001*d*d
                    p[key]-=.003*(m[key]/(1-.9**step_index))/(np.sqrt(v[key]/(1-.999**step_index))+1e-8)
    scores=[]
    for model in models:
        per_length={}
        for length,items in test.items():
            correct=0
            for src in items:
                if isinstance(model,FixedSeq2Seq):out=model.predict(src,limit=length+1)
                else:out,_=model.predict(src,14,15,limit=length+1)
                correct+=out==list(src[::-1])
            per_length[length]={'correct':correct,'total':len(items)}
        scores.append(per_length)
    return scores

print('Prueba breve de inversión:',train_reversal(50))

In a local NumPy run of 10 000 updates, the baseline got 74 of 100 held-out length-5 sequences right and 17 of 100 at length 6; attention got 100 and 90 respectively. At length 8 both got 0 of 100. These are one seed and split, not an extrapolation guarantee: the difference also includes bidirectionality and initialization. Greater lengths were not in training.

Repeating the same code and seeds in Pyodide, baseline got 82/100 and 18/100 at lengths 5 and 6, attention 100/100 and 69/100; at length 8 both again got 0/100. Optimization trajectories can diverge due to numerical differences between environments. The comparison illustrates why environment and repeated seeds matter even when example generators use the same seed.

Translation with attention in PyTorch

For comparison with the previous lesson’s fixed model, use the same ManyThings/Tatoeba Spanish–English file, source-based splits, training vocabulary, and BLEU with tok:none. Install PyTorch and sacrebleu==2.5.1, download spa-eng.zip to the laboratory directory or configure SEQ_DATA. The cell records SHA-256 and signatures. SEQ2SEQ_FULL=1 expands splits to 30 000/2 000/2 000; ATT_STEPS fixes budget, defaulting to five steps per model. That short test checks flow only.

The baseline has an LSTM encoder and the attention model uses a bidirectional encoder with the same total width and an LSTM decoder receiving context each step. These differ architecturally: a quality difference does not isolate attention alone. Both receive the same examples and steps and are evaluated autoregressively. To inspect potential reordering, test is searched for Boston es una ciudad grande and reference Boston is a big city, Tatoeba #4811756 and #5752621. If the source is absent from test under the chosen split or version, tengo un coche rojo nuevo is used, records #259020 and #949045, and the report states whether it appears in training and how many tokens are unknown. A map for a sentence seen in training is not independent evaluation.

[ ]Real translation and alignmentsLocal GPU
import hashlib, io, os, random, re, zipfile
from pathlib import Path
from collections import Counter
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence
from sacrebleu.metrics import BLEU, CHRF

torch.manual_seed(1717); random.seed(1717)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
archive = Path(os.environ.get('SEQ_DATA', 'spa-eng.zip')).read_bytes()
print('SHA-256 del archivo:', hashlib.sha256(archive).hexdigest())
with zipfile.ZipFile(io.BytesIO(archive)) as z:
    rows = z.read('spa.txt').decode('utf-8').splitlines()
def tokenize(s):
    return re.findall(r'\w+|[^\w\s]', s.lower(), flags=re.UNICODE)
groups = {}
for row in rows:
    parts = row.split('\t')
    if len(parts) < 3: continue
    en, es = tokenize(parts[0]), tokenize(parts[1])
    if 2 <= len(es) <= 18 and 2 <= len(en) <= 18:
        groups.setdefault(tuple(es), []).append(tuple(en))
keys = list(groups); random.shuffle(keys)
full = os.environ.get('SEQ2SEQ_FULL') == '1'
ntrain, nval, ntest = (30000, 2000, 2000) if full else (512, 64, 64)
assert len(keys) >= ntrain+nval+ntest
train_keys = keys[:ntrain]
val_keys = keys[ntrain:ntrain+nval]
test_keys = keys[ntrain+nval:ntrain+nval+ntest]
train = [(s, groups[s][0]) for s in train_keys]
valid = [(s, groups[s][0]) for s in val_keys]
test = [(s, groups[s][0]) for s in test_keys]
special = ['<pad>', '<bos>', '<eos>', '<unk>']
def vocab(seqs):
    counts = Counter(token for seq in seqs for token in seq)
    return special + sorted(token for token, count in counts.items() if count >= 2)
sv = vocab(s for s, t in train); tv = vocab(t for s, t in train)
si = {w:i for i,w in enumerate(sv)}; ti = {w:i for i,w in enumerate(tv)}
PAD, BOS, EOS, UNK = range(4)
def ids(seq, vocab): return [vocab.get(w, UNK) for w in seq]
def batch(examples, reverse):
    sources = [list(reversed(s)) if reverse else list(s) for s, _ in examples]
    x = [torch.tensor(ids(s, si), dtype=torch.long) for s in sources]
    y = [torch.tensor(ids(t, ti)+[EOS], dtype=torch.long) for _, t in examples]
    lengths = torch.tensor([len(s) for s in x], dtype=torch.long)
    return pad_sequence(x, batch_first=True, padding_value=PAD).to(device), lengths, pad_sequence(y, batch_first=True, padding_value=PAD).to(device)

class Seq2Seq(nn.Module):
    def __init__(self, hidden, context_each=False):
        super().__init__()
        self.context_each = context_each
        self.src_emb = nn.Embedding(len(sv), hidden, padding_idx=PAD)
        self.tgt_emb = nn.Embedding(len(tv), hidden, padding_idx=PAD)
        self.encoder = nn.LSTM(hidden, hidden, 2, batch_first=True)
        self.decoder = nn.LSTM(hidden*(2 if context_each else 1), hidden, 2, batch_first=True)
        self.head = nn.Linear(hidden, len(tv))
    def encode(self, x, lengths):
        packed = pack_padded_sequence(self.src_emb(x), lengths.cpu(), batch_first=True, enforce_sorted=False)
        _, state = self.encoder(packed)
        return state
    def forward(self, x, lengths, target):
        state = self.encode(x, lengths); context = state[0][-1]
        bos = torch.full((len(x), 1), BOS, dtype=torch.long, device=x.device)
        shifted = torch.cat((bos, target[:, :-1]), dim=1)
        inp = self.tgt_emb(shifted)
        if self.context_each: inp = torch.cat((inp, context[:, None, :].expand(-1, inp.shape[1], -1)), dim=-1)
        out, _ = self.decoder(inp, state)
        return self.head(out)
    @torch.no_grad()
    def generate(self, x, lengths, limit=24, return_finished=False):
        state = self.encode(x, lengths); context = state[0][-1]
        token = torch.full((len(x),), BOS, dtype=torch.long, device=x.device)
        done = torch.zeros(len(x), dtype=torch.bool, device=x.device)
        result = [[] for _ in range(len(x))]
        for _ in range(limit):
            inp = self.tgt_emb(token)[:, None, :]
            if self.context_each: inp = torch.cat((inp, context[:, None, :]), dim=-1)
            out, state = self.decoder(inp, state)
            token = self.head(out[:, 0]).argmax(-1)
            token = torch.where(done, torch.full_like(token, EOS), token)
            for i, k in enumerate(token.tolist()):
                if not done[i] and k != EOS: result[i].append(k)
            done |= token == EOS
            if done.all(): break
        return (result, done.tolist()) if return_finished else result

def metrics(model, examples, reverse):
    model.eval(); hypotheses = []; references = []
    for start in range(0, len(examples), 32):
        group = examples[start:start+32]; x, lengths, _ = batch(group, reverse)
        predictions = model.generate(x, lengths)
        hypotheses.extend(' '.join(tv[k] for k in p) for p in predictions)
        references.extend(' '.join(t) for _, t in group)
    bleu, chrf = BLEU(tokenize='none', force=True), CHRF()
    b = bleu.corpus_score(hypotheses, [references])
    c = chrf.corpus_score(hypotheses, [references])
    return b.score, c.score, str(bleu.get_signature()), str(chrf.get_signature())

from torch.nn.utils.rnn import pad_packed_sequence

class AttentiveTranslator(nn.Module):
    def __init__(self, hidden=128):
        super().__init__()
        self.hidden=hidden
        self.src_emb=nn.Embedding(len(sv),hidden,padding_idx=PAD)
        self.tgt_emb=nn.Embedding(len(tv),hidden,padding_idx=PAD)
        self.encoder=nn.LSTM(hidden,hidden//2,2,batch_first=True,bidirectional=True)
        self.decoder=nn.LSTM(hidden*2,hidden,2,batch_first=True)
        self.W=nn.Linear(hidden,hidden,bias=False); self.U=nn.Linear(hidden,hidden,bias=False); self.v=nn.Linear(hidden,1,bias=False)
        self.head=nn.Linear(hidden,len(tv))
    def encode(self,x,lengths):
        packed=pack_padded_sequence(self.src_emb(x),lengths.cpu(),batch_first=True,enforce_sorted=False)
        out,_=self.encoder(packed); out,_=pad_packed_sequence(out,batch_first=True,total_length=x.shape[1])
        valid=torch.arange(x.shape[1],device=x.device)[None,:]<lengths.to(x.device)[:,None]
        return out,valid,self.U(out)
    def attend(self,query,annotations,valid,pre):
        e=self.v(torch.tanh(self.W(query)[:,None,:]+pre)).squeeze(-1).masked_fill(~valid,float('-inf'))
        a=e.softmax(dim=1);return torch.bmm(a[:,None,:],annotations).squeeze(1),a
    def forward(self,x,lengths,target):
        ann,valid,pre=self.encode(x,lengths); B=x.shape[0]
        state=(ann.new_zeros((2,B,self.hidden)),ann.new_zeros((2,B,self.hidden)))
        token=torch.full((B,),BOS,dtype=torch.long,device=x.device); logits=[]
        for i in range(target.shape[1]):
            context,_=self.attend(state[0][-1],ann,valid,pre)
            out,state=self.decoder(torch.cat((self.tgt_emb(token),context),dim=-1)[:,None,:],state)
            logits.append(self.head(out[:,0]));token=target[:,i]
        return torch.stack(logits,dim=1)
    @torch.no_grad()
    def generate(self,x,lengths,limit=24,return_attention=False):
        ann,valid,pre=self.encode(x,lengths);B=x.shape[0]
        state=(ann.new_zeros((2,B,self.hidden)),ann.new_zeros((2,B,self.hidden)))
        token=torch.full((B,),BOS,dtype=torch.long,device=x.device);done=torch.zeros(B,dtype=torch.bool,device=x.device)
        outputs=[[] for _ in range(B)]; alignments=[[] for _ in range(B)]
        for _ in range(limit):
            context,a=self.attend(state[0][-1],ann,valid,pre)
            out,state=self.decoder(torch.cat((self.tgt_emb(token),context),dim=-1)[:,None,:],state)
            token=self.head(out[:,0]).argmax(-1);token=torch.where(done,torch.full_like(token,EOS),token)
            for i,k in enumerate(token.tolist()):
                if not done[i]:
                    alignments[i].append(a[i,:lengths[i]].cpu().tolist())
                    if k!=EOS:outputs[i].append(k)
            done |= token==EOS
            if done.all():break
        return (outputs,alignments,done.tolist()) if return_attention else outputs

def train_translation(attention,steps):
    torch.manual_seed(1818);rng=random.Random(1818)
    model=(AttentiveTranslator(128) if attention else Seq2Seq(128)).to(device)
    optimizer=torch.optim.Adam(model.parameters(),lr=.001)
    for step_index in range(steps):
        sample=rng.sample(train,32); x,lengths,y=batch(sample,False); model.train()
        logits=model(x,lengths,y);loss=nn.functional.cross_entropy(logits.reshape(-1,len(tv)),y.reshape(-1),ignore_index=PAD)
        optimizer.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);optimizer.step()
        if (step_index+1)%500==0: print('atención',attention,'paso',step_index+1,'pérdida',round(loss.item(),4),flush=True)
    return model

steps=int(os.environ.get('ATT_STEPS','5'))
models_attention={False:train_translation(False,steps),True:train_translation(True,steps)}
for condition,model in models_attention.items():
    print('Condición',condition,'pasos',steps,'validación',metrics(model,valid,False),flush=True)
    for low,high in [(2,5),(6,9),(10,13),(14,18)]:
        subset=[(s,t) for s,t in test if low<=len(s)<=high]
        if subset:print('test',low,high,'n',len(subset),'BLEU',metrics(model,subset,False)[0],flush=True)
model=models_attention[True];model.eval()
probe=tuple(tokenize('boston es una ciudad grande .'))
chosen=next(((s,t) for s,t in test if s==probe), (tuple(tokenize('tengo un coche rojo nuevo .')),tuple(tokenize('i have a new red car .'))))
x,lengths,_=batch([chosen],False)
out,alignment,done=model.generate(x,lengths,return_attention=True)
print('Fuente:', ' '.join(chosen[0]),'referencia:', ' '.join(chosen[1]))
print('Fuente en entrenamiento:', chosen[0] in train_keys, 'tokens fuente desconocidos:',sum(t not in si for t in chosen[0]))
print('Hipótesis:', ' '.join(tv[k] for k in out[0]),'terminó:',done[0])
print('Alineamiento:',alignment[0])
import matplotlib.pyplot as plt
labels=[tv[k] for k in out[0]]+(['<eos>'] if done[0] else [])
fig,ax=plt.subplots(figsize=(max(5,len(chosen[0])*.8),max(2,len(labels)*.4)),constrained_layout=True)
image=ax.imshow(alignment[0],aspect='auto',vmin=0,vmax=1,cmap='Blues')
ax.set_xticks(range(len(chosen[0])),chosen[0],rotation=45,ha='right')
ax.set_yticks(range(len(labels)),labels);ax.set(xlabel='fuente',ylabel='salida')
fig.colorbar(image,ax=ax,label='peso');plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one run of 1 000 steps per model with 30 000 training sources and sacreBLEU 2.5.1 signature tok:none, baseline validation BLEU was 5.063 and attention 0.600. On test, the 6–9-token bucket contains 1 092 sentences and scored 4.207 versus 0.640. This short budget and one seed do not establish a definitive architecture comparison. The car sentence was in training and the attention model’s hypothesis was wrong, so its map does not show that it learned reordering. Studying this requires more training, held-out sentences, and further controls.

In another 5 000-step-per-model trial with the same split, validation BLEU was 13.764 for baseline and 13.346 for attention; in the 6–9-token bucket it was 14.247 and 13.220. For the car sentence, which belonged to training, output was i have a new car .: it omits the color, and the attention map does not necessarily assign each word to its intuitive translation. This example examines a failure, not reliable reordering learning.

A repeated 5 000-step attention run also examined held-out sentence boston es una ciudad grande .. The reference contains big city but the hypothesis was a <unk> is a <unk> .; the map could be drawn but did not establish the expected reordering. The model emitted <unk> even though the reference words are in the output vocabulary. The date alignment above is a different task and must not be interpreted as an English–Spanish translation result.

Exercises

Proof
Prove: For each query, score gradients sum to zero.
0
Let g be the loss gradient with respect to context and c the weighted mean of valid annotations.

Step 1 of 3. What is the gradient with respect to position j's weight?

Numeric
For scores (1, 2, 0.5), calculate the second softmax weight.
Numeric
With those weights and annotations h₁=(1,0), h₂=(0,2), h₃=(1,1), calculate the first context coordinate.
Numeric
With T=50 and dimensions dₛ=dₕ=512, dₐ=256, how many multiplications per step do Ws and vᵀq use for the 50 positions if Uh is already computed? Count only those projections and scores.
Numeric
Under the same conditions, add the cost of recomputing U hⱼ for every position at every step. How many multiplications do projections and scores use?
Quiz
Why does this decoder score using sᵢ₋₁ rather than sᵢ?
Code
Implement attention_forward(s,h,mask,W,U,v) and attention_backward(dc,cache). Use shapes s=(B,ds), h=(B,T,dh), W=(da,ds), U=(da,dh), v=(da,). Forward returns context, weights, and cache; backward returns gradients of s, h, W, U, and v. Reject rows with no valid positions and zero padding weights.
import numpy as np
def attention_forward(s,h,mask,W,U,v):
  pass
def attention_backward(dc,cache):
  pass
Shift+Enter to run