Module contents
Lesson 19 of 24Core 100 min

Multiplicative attention and variants: Luong, local, monotonic and pointers

Compare multiplicative attention scores, global and local windows, monotonic variants, pointer networks, and copy mechanisms under explicit protocols.

After this lesson you can

  • Implement dot, general, and concat scores and batch matrix computation.
  • Implement local attention with predicted position and Gaussian window and compare it with global attention.
  • Explain input feeding and computation order in Bahdanau and Luong attention.
  • Describe location-aware and monotonic attention and their uses.
  • Build a pointer network for sorting and a pointer-generator that copies rare words.

Before you start

Change how scores are computed

Additive attention uses a perceptron to compare query and annotation. Multiplicative attention also turns scores into weights, but can obtain all scores through matrix products. Luong, Pham and Manning propose, for state sts_t and annotation hjh_j:

etjdot=st⊤hj,etjgeneral=st⊤Whj,etjconcat=v⊤tanh⁡(Wc[st;hj]).e_{tj}^{\rm dot}=s_t^\top h_j,\qquad e_{tj}^{\rm general}=s_t^\top W h_j,\qquad e_{tj}^{\rm concat}=v^\top\tanh(W_c[s_t;h_j]).

Direct dot product requires equal dimensions; general permits W∈Rds×dhW\in\R^{d_s\times d_h}. With batch S∈RB×dsS\in\R^{B\times d_s} and H∈RB×T×dhH\in\R^{B\times T\times d_h}, einsum('bi,ij,btj->bt', S, W, H) computes table (B,T)(B,T). Size and scale matter too: large-magnitude scores can concentrate softmax and leave small gradients. Scaled dot product and separating keys from values are studied in the next module.

Dot asks whether two vectors point in similar directions, but its value also depends on their norms. General transforms an annotation before comparing it: WW can amplify, suppress, or mix directions. The identity matrix reproduces dot when dimensions match. Concat introduces a nonlinearity before scalar reduction; it is not necessarily more accurate on every dataset, and its cost includes forming and transforming a representation per pair. Multiple queries can be stacked along time to compute the score table with matrix multiplication, without a Python loop per position.

InteractiveThree ways to score
h1h2h3h4h5s
h1: 0.067
h2: 0.184
h3: 0.106
h4: 0.277
h5: 0.366

Concat uses a fixed two-unit perceptron; all three options share query and annotations.

Score
Highest weighth5: 0.366
Explicit two-dimensional model with five annotations. In general mode, drag W's columns or use sliders and observe weights.

Computation order matters. Luong first computes sts_t from the previous input, then attention and ctc_t, combines s~t=tanh⁡(Wo[ct;st])\tilde s_t=\tanh(W_o[c_t;s_t]), and produces output. In Bahdanau, the previous example’s query was st−1s_{t-1} and context computed sts_t. With input feeding, s~t−1\tilde s_{t-1} is concatenated to the next step’s input. This communicates previous attention information but introduces a sequential dependency: the entire decoder cannot run as one recurrent call independent of intermediate contexts.

For a step, write dependencies first: previous input and previous attentional vector produce the new state; it scores the source; the weighted sum forms context; state and context produce logits. Training can feed the previous reference word, but the previous attentional vector still depends on the previous step. Inference replaces reference with the model’s choice and stops on <eos> or a limit. Confusing these orders can create a circular dependency or use unavailable information.

Global and local

Global and local attention differ in the set consulted. Global scores all valid positions. Local-m fixes pt=tp_t=t; local-p predicts a real position, for example pt=Txσ(vp⊤tanh⁡(Wpst))p_t=T_x\sigma(v_p^\top\tanh(W_p s_t)), and consults a window of radius DD. Luong multiplies content weights by exp⁡[−(j−pt)2/(2σ2)]\exp[-(j-p_t)^2/(2\sigma^2)] with σ=D/2\sigma=D/2. Nonexistent positions beyond the boundaries are discarded.

The published equation multiplies weights by the Gaussian and does not specify a second normalization. Modified weights can therefore sum to less than one. A useful variant adds the log Gaussian to logits and renormalizes in the window, producing a convex mean but not the published equation. The next cell implements multiplication and shows the sum. Within a fixed window it is differentiable with respect to ptp_t; when window membership changes, truncation jumps and an ordinary boundary derivative must not be assumed.

For example, if a four-position window has equal scores, content softmax assigns one quarter to each. The Gaussian reduces the ends more than positions near the center. Without a second normalization context magnitude also decreases; with it, the distribution sums to one. Comparing implementations requires specifying this convention, window definition, and boundary handling.

Scoring only a window costs proportionally to examined positions, at most approximately 2D+12D+1, versus TxT_x globally. Computing all global scores and masking outside the window afterward does not obtain that saving. A window can miss a distant match: reducing compute changes the model hypothesis and can hurt languages with long reorderings.

InteractiveThe local window

The constructed signal has two relevant regions near positions 10 and 31. Move the center to see when a region falls outside the window.

  • global
  • local-p

The stated savings count content scores; they exclude center prediction cost and do not guarantee a measured speedup.

10.0
4
Positions examined9 / 40
Global mass outside0.517
Local sum0.635
Two constructed relevant regions in a 40-position source. Compare global softmax and local-p multiplied by the Gaussian without a second normalization.

Evidence and variants

In table 4 of Luong and colleagues, for their English–German configuration, global-dot achieved tokenized BLEU 18.6 and local-p-general 19.0 before unknown-word replacement. These are particular systems and choices, not a universal ranking. In table 5 of Britz and colleagues, under their own protocol and newstest2013, additive attention of dimension 512 scored 22.47 ± 0.27 and multiplicative attention of dimension 256 scored 22.33 ± 0.28. Do not directly compare across papers or extrapolate to other architectures.

Location-aware and monotonic attention incorporates previous positions or restricts progress. In speech outputs often follow signal time approximately, and streaming lacks all future inputs. Raffel and colleagues’ monotonic attention allows online advance decisions; Chorowski and colleagues’ location-aware attention uses previous alignments. Neither is synonymous with a fixed window or automatically suitable for translation requiring large inversions.

Attention as output and copying

In a pointer network or copy mechanism, the distribution over positions can form part of the output. A pointer network selects indices of variable-length input; sorting a list masks previously emitted indices. Selected index and value differ: repeated values can occupy different positions. Vinyals and colleagues applied this idea to problems with input-dependent output size.

A pointer-generator mixes a fixed-vocabulary distribution with copying. For each word ww:

P(w)=pgenPvocab(w)+(1−pgen)∑j:xj=wαj.P(w)=p_{\rm gen}P_{\rm vocab}(w)+(1-p_{\rm gen})\sum_{j:x_j=w}\alpha_j.

The sum groups all occurrences of the same word. An out-of-vocabulary name can receive copy mass if present in the source; otherwise that route cannot produce it. The formula is from See, Liu and Manning, applied there to summarization. A switch near copying guarantees neither selecting the right position nor understanding the entity.

The mixture must cover the union of fixed vocabulary and source tokens. A word in both receives mass from both routes. If repeated in the input, its positions’ mass is aggregated before choosing the word. The model can attend to a position useful for context without copying it; the switch and joint distribution determine output. To evaluate copying, hold out names or numbers, retain original strings, and count literal matches alongside the global metric.

Scores and derivatives in NumPy

The next cell computes all three scores by batch. It then implements local-p with Luong’s Gaussian multiplication and differentiates scores, annotations, and predicted position. Gradcheck uses a position away from window changes and holds DD fixed. With g=∂L/∂cg=\partial L/\partial c, aˉj=g⊤hj Gj\bar a_j=g^\top h_j\,G_j holds before the softmax VJP, and pˉ=∑j(g⊤hj)ajGj(j−p)/σ2\bar p=\sum_j(g^\top h_j)a_jG_j(j-p)/\sigma^2.

[ ]Scores and local-window backwardBrowser
import numpy as np

def score_dot(s,h):
    if s.shape[-1]!=h.shape[-1]: raise ValueError('dot necesita dimensiones iguales')
    return np.einsum('bd,btd->bt',s,h)
def score_general(s,h,W): return np.einsum('bi,ij,btj->bt',s,W,h)
def score_concat(s,h,W,v):
    B,T,_=h.shape
    both=np.concatenate((np.broadcast_to(s[:,None,:],(B,T,s.shape[-1])),h),axis=-1)
    return np.tanh([email protected])@v
def dot_backward(d,s,h):
    return np.einsum('bt,btd->bd',d,h),d[:,:,None]*s[:,None,:]
def general_backward(d,s,h,W):
    ds=np.einsum('bt,ij,btj->bi',d,W,h)
    dh=np.einsum('bt,bi,ij->btj',d,s,W)
    dW=np.einsum('bt,bi,btj->ij',d,s,h)
    return ds,dh,dW
def concat_backward(d,s,h,W,v):
    B,T,_=h.shape;both=np.concatenate((np.broadcast_to(s[:,None,:],(B,T,s.shape[-1])),h),axis=-1)
    q=np.tanh([email protected]);dz=d[:,:,None]*v*(1-q*q)
    dboth=dz@W
    return dboth[:,:,:s.shape[-1]].sum(axis=1),dboth[:,:,s.shape[-1]:],np.einsum('bta,btk->ak',dz,both),np.einsum('bt,bta->a',d,q)

def local_forward(e,h,p,D,mask):
    if D<=0: raise ValueError('D debe ser positivo')
    positions=np.arange(1,len(e)+1); valid=mask & (np.abs(positions-p)<=D)
    if not valid.any(): raise ValueError('ventana vacía')
    logits=np.where(valid,e,-np.inf); a=np.exp(logits-np.max(logits));a/=a.sum()
    gaussian=np.exp(-.5*((positions-p)/(D/2))**2); weights=a*gaussian
    return weights@h,weights,(a,gaussian,h,p,D,positions)
def local_backward(dc,cache):
    a,g,h,p,D,positions=cache
    da=(h@dc)*g; de=a*(da-(a*da).sum())
    dh=(a*g)[:,None]*dc
    dp=np.sum((h@dc)*a*g*(positions-p)/(D/2)**2)
    return de,dh,dp

rng=np.random.default_rng(1919)
s=rng.normal(size=(2,3));h_batch=rng.normal(size=(2,5,4));W=rng.normal(size=(3,4))
scores=score_general(s,h_batch,W)
assert np.allclose(scores, np.stack([h_batch[b]@W.T@s[b] for b in range(2)]))
d=rng.normal(size=scores.shape);M=rng.normal(size=(6,7));v=rng.normal(size=6)
hs=rng.normal(size=(2,5,3))
checks=[(lambda: (score_dot(s,hs)*d).sum(),(s,hs),dot_backward(d,s,hs)),
        (lambda: (score_general(s,h_batch,W)*d).sum(),(s,h_batch,W),general_backward(d,s,h_batch,W)),
        (lambda: (score_concat(s,h_batch,M,v)*d).sum(),(s,h_batch,M,v),concat_backward(d,s,h_batch,M,v))]
score_error=0.
for f,arrays,grads in checks:
    for array,grad in zip(arrays,grads):
        for index in np.ndindex(array.shape):
            old=array[index];array[index]=old+1e-5;plus=f();array[index]=old-1e-5;minus=f();array[index]=old
            score_error=max(score_error,abs((plus-minus)/2e-5-grad[index]))
assert score_error<1e-7
e=rng.normal(size=10);h=rng.normal(size=(10,3));p=7.3;D=2;mask=np.ones(10,dtype=bool);dc=rng.normal(size=3)
c,w,cache=local_forward(e,h,p,D,mask);de,dh,dp=local_backward(dc,cache)
def objective():return float(local_forward(e,h,p,D,mask)[0]@dc)
worst=0.
for array,grad in ((e,de),(h,dh)):
    for index in np.ndindex(array.shape):
        old=array[index];array[index]=old+1e-5;plus=objective();array[index]=old-1e-5;minus=objective();array[index]=old
        worst=max(worst,abs((plus-minus)/2e-5-grad[index]))
plus=local_forward(e,h,p+1e-5,D,mask)[0]@dc;minus=local_forward(e,h,p-1e-5,D,mask)[0]@dc
worst=max(worst,abs((plus-minus)/2e-5-dp))
assert worst<1e-7 and np.all(w[~(mask & (np.abs(np.arange(1,11)-p)<=D))]==0)
print('Suma de pesos locales:',w.sum(),'error máximo local:',worst,'puntuaciones:',score_error)

Sorting by indices

This small pointer network encodes each number with a learned transformation, scores annotations with a recurrent state, and masks chosen positions. During training it receives the previous correct index; at inference it uses its own choice. Manual backward accumulates score and recurrent-state paths and is checked with central differences. The cell runs 50 steps to check flow; train_pointer(10000) runs the full trial.

[ ]Pointer network from scratchBrowser
import numpy as np

class PointerSorter:
    def __init__(self,width=12,seed=19):
        r=np.random.default_rng(seed);self.width=width
        self.p={'E':r.normal(0,.2,(2,width)), 'A':r.normal(0,.2,(width,width)),
                'B':r.normal(0,.2,(width,width)), 'b':np.zeros(width),
                'W':r.normal(0,.2,(width,width)), 'U':r.normal(0,.2,(width,width)),
                'v':r.normal(0,.2,width)}
    def encode(self,values):
        features=np.stack(((np.asarray(values)-50)/50,np.ones(len(values))),axis=1)
        return features,np.tanh([email protected]['E'])
    def loss_grad(self,values):
        features,h=self.encode(values);n=len(values);order=np.argsort(values,kind='stable');p=self.p
        state=np.zeros(self.width);used=np.zeros(n,dtype=bool);steps=[];loss=0.
        for target in order:
            q=np.tanh(h@p['U'].T+(p['W']@state)[None,:]);e=q@p['v'];e=np.where(used,-np.inf,e)
            prob=np.exp(e-e.max());prob/=prob.sum();loss-=np.log(prob[target])/n
            next_state=np.tanh(p['A']@state+p['B']@h[target]+p['b'])
            steps.append((state,q,prob,int(target),next_state));used[target]=True;state=next_state
        grads={k:np.zeros_like(v) for k,v in p.items()};dh=np.zeros_like(h);ds=np.zeros(self.width)
        for state,q,prob,target,next_state in reversed(steps):
            dt=ds*(1-next_state**2)
            grads['A']+=np.outer(dt,state);grads['B']+=np.outer(dt,h[target]);grads['b']+=dt;dh[target]+=p['B'].T@dt
            prev=p['A'].T@dt
            de=prob.copy();de[target]-=1;de/=n
            grads['v']+=q.T@de;dz=de[:,None]*p['v']*(1-q*q)
            grads['W']+=np.outer(dz.sum(0),state);grads['U']+=dz.T@h
            dh+=dz@p['U'];ds=prev+p['W'][email protected](0)
        grads['E']=features.T@(dh*(1-h*h))
        return loss,grads
    def predict(self,values):
        _,h=self.encode(values);n=len(values);state=np.zeros(self.width);used=np.zeros(n,dtype=bool);indices=[];rows=[]
        for _ in range(n):
            q=np.tanh([email protected]['U'].T+(self.p['W']@state)[None,:]);[email protected]['v'];e=np.where(used,-np.inf,e)
            prob=np.exp(e-e.max());prob/=prob.sum();target=int(prob.argmax());rows.append(prob.tolist());indices.append(target);used[target]=True
            state=np.tanh(self.p['A']@state+self.p['B']@h[target]+self.p['b'])
        return {'values':list(values),'indices':indices,'ordered':[values[i] for i in indices],'rows':rows}

def pointer_gradcheck():
    model=PointerSorter(width=3,seed=19);values=[70,12,49];_,grads=model.loss_grad(values);worst=0.
    for name,array in model.p.items():
        for index in np.ndindex(array.shape):
            old=array[index];array[index]=old+1e-5;plus=model.loss_grad(values)[0]
            array[index]=old-1e-5;minus=model.loss_grad(values)[0];array[index]=old
            worst=max(worst,abs((plus-minus)/2e-5-grads[name][index]))
    assert worst<1e-7
    return worst

def train_pointer(steps=100,seed=1919):
    model=PointerSorter();rng=np.random.default_rng(seed);first={k:np.zeros_like(v) for k,v in model.p.items()};second={k:np.zeros_like(v) for k,v in model.p.items()}
    for step in range(1,steps+1):
        n=int(rng.integers(2,7));values=rng.choice(100,size=n,replace=False).tolist();loss,grads=model.loss_grad(values)
        norm=np.sqrt(sum((g*g).sum() for g in grads.values()));scale=min(1.,1./max(norm,1e-12))
        for key in model.p:
            d=scale*grads[key];first[key]=.9*first[key]+.1*d;second[key]=.999*second[key]+.001*d*d
            model.p[key]-=.003*(first[key]/(1-.9**step))/(np.sqrt(second[key]/(1-.999**step))+1e-8)
    return model,loss

def evaluate_pointer(model,seed=1920):
    rng=np.random.default_rng(seed);result={}
    for n in (3,5,6,7,8,10):
        ok=0
        for _ in range(100):
            values=rng.choice(100,size=n,replace=False).tolist();output=model.predict(values)
            ok+=output['ordered']==sorted(values)
        result[n]=ok
    return result

print('Error de gradiente del puntero:',pointer_gradcheck())
small,loss=train_pointer(50)
print('Prueba de flujo, 50 pasos:',small.predict([70,12,49]))

In one NumPy run of 10 000 steps, training lengths 2 through 6 and distinct numbers from 0 through 99, it sorted 100 of 100 new lists at each length 3, 5, 6, 7, 8, and 10. Longer lists test length extrapolation within the same numeric range, not arbitrary generalization. Those weights load into the next figure and its output is computed in the browser; the cell lets you train other weights.

Repeating in Pyodide with the same seeds also achieved 100/100 at each of those six lengths. This confirms that particular run; other distributions, repeated values, or longer lists need their own evaluations.

InteractiveA network that points

Recorded weights after 10,000 steps; real inference in the browser.

Full output: 12, 35, 49, 70

Position 1, value 70: 0.0000
Position 2, value 12: 1.0000
Position 3, value 49: 0.0000
Position 4, value 35: 0.0000

Repeated values remain distinct positions. Training lists contained two to six distinct integers from 0 to 99.

1
Selected index2
Selected value12
Real inference with weights trained for 10 000 steps. Change list and step to inspect the distribution over indices and try lengths and values outside training.

Compare scores on dates

To separate scoring from other changes, the two models below share bidirectional encoder, decoder, data, batch, and optimizer; only additive scoring changes to a general matrix. Date vocabulary and split are from the previous lesson. Reference code is included so the lab is standalone. It compares exact whole-date accuracy on 220 held-out combinations and training time; a clock depends on the environment and measures more than attention. The short check uses 50 steps. For the larger trial run compare_date_models(5000).

[ ]General attention and date comparisonBrowser
import calendar,time

def general_forward(state,ann,M):
    [email protected]@state;prob=np.exp(score-score.max());prob/=prob.sum()
    return prob@ann,(state,ann,M,prob)
def general_backward(dc,cache):
    state,ann,M,prob=cache;c=prob@ann;de=prob*((ann-c)@dc)
    return M@(de@ann),prob[:,None]*dc[None,:]+de[:,None]*(state@M)[None,:],np.outer(state,de@ann)

class GeneralSeq2Seq(AttentionSeq2Seq):
    def __init__(self,vocab,width=24,seed=18):
        super().__init__(vocab,width,width,seed);rng=np.random.default_rng(seed+1)
        self.att={'M':rng.normal(0,.12,(width,2*width))}
    def loss_grad(self,src,target,bos):
        ann,cf,cb=self.encode(src);state=np.zeros(self.width);previous=bos;steps=[];loss=0.
        for token in target:
            context,ac=general_forward(state,ann,self.att['M'])
            state,dc=gru(np.concatenate((self.eye[previous],context)),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,dM=general_backward(dx[self.vocab:],ac);dh+=ds;dann+=da;ga['M']+=dM
        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=4):
        ann,_,_=self.encode(src);state=np.zeros(self.width);previous=bos;out=[]
        for _ in range(limit):
            context,_=general_forward(state,ann,self.att['M'])
            state,_=gru(np.concatenate((self.eye[previous],context)),state,self.dec)
            previous=int(np.argmax([email protected]['w']+self.out['b']))
            if previous==eos:break
            out.append(previous)
        return out

def check_general_model():
    m=GeneralSeq2Seq(8,width=3);src=[0,1,2];target=[2,1,0,7];_,grads=m.loss_grad(src,target,6);worst=0.
    for p,g in zip(m.params(),grads):
        for key,a in p.items():
            for idx in np.ndindex(a.shape):
                old=a[idx];a[idx]=old+1e-5;plus=m.loss_grad(src,target,6)[0];a[idx]=old-1e-5;minus=m.loss_grad(src,target,6)[0];a[idx]=old
                worst=max(worst,abs((plus-minus)/2e-5-g[key][idx]))
    assert worst<1e-7
    return worst

def compare_date_models(steps=50):
    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=np.random.default_rng(1818).permutation(len(dates));cut=int(.8*len(dates));train=[dates[i] for i in split[:cut]];test=[dates[i] for i in split[cut:]]
    rng=np.random.default_rng(1819);models=[AttentionSeq2Seq(48,width=24,align=24,seed=18),GeneralSeq2Seq(48,width=24,seed=18)]
    moments=[[zeros(p) for p in model.params()] for model in models];vars_=[[zeros(p) for p in model.params()] for model in models];elapsed=[0.,0.]
    for step in range(1,steps+1):
        day,month,year=train[int(rng.integers(len(train)))];src=[day-1,30+month,43+year-2024];target=[src[2],src[1],src[0],47]
        for i,(model,first,second) in enumerate(zip(models,moments,vars_)):
            start=time.perf_counter();loss,grads=model.loss_grad(src,target,46)
            norm=np.sqrt(sum((a*a).sum() for g in grads for a 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=scale*g[key];m[key]=.9*m[key]+.1*d;v[key]=.999*v[key]+.001*d*d
                    p[key]-=.003*(m[key]/(1-.9**step))/(np.sqrt(v[key]/(1-.999**step))+1e-8)
            elapsed[i]+=time.perf_counter()-start
    scores=[]
    for model in models:
        correct=0
        for day,month,year in test:
            src=[day-1,30+month,43+year-2024];expected=[src[2],src[1],src[0]]
            output=model.predict(src,46,47,limit=4)
            if isinstance(output,tuple):output=output[0]
            correct+=output==expected
        scores.append({'correct':int(correct),'total':len(test)})
    return {'steps':steps,'additive':scores[0],'general':scores[1], 'seconds':elapsed}

print('Gradcheck del modelo general:',check_general_model())
print('Comparación breve:',compare_date_models(50))

In one local NumPy run of 5 000 steps per model, both got all 220 held-out combinations of the same years and categories right. Accumulated loop times were 15.08 s additive and 13.21 s general in that process; they include forward, backward, and update and depend on load, hardware, and the task’s tiny size. They establish no universal speed or quality advantage. Seed and split are in the cell; rerun the trial to measure your environment.

The same comparison in Pyodide also gave 220/220 for both, with 18.78 s and 16.20 s respectively in that run. Measurements include the same operations but are not isolated kernel benchmarks, and timing differences are not device-independent constants.

Copy unseen names and numbers

This local lab adapts an attention encoder-decoder to the controlled task N123 tiene 223 → N123 has 223. The encoder represents every name and number as <unk>; original strings are retained for the extended vocabulary and copying. Train on 200 synthetic pairs and test 100 distinct compound names and numbers. Pattern and positions are fixed, so the experiment demonstrates structural copying capacity, not general translation or entity recognition. A no-copy baseline can emit only its fixed vocabulary; it cannot literally produce an out-of-vocabulary name.

The cell uses local PyTorch, five steps per model by default, and COPY_STEPS for a larger budget. COPY_DEVICE=cpu forces CPU. Output, attention, vocabulary distribution, and pgenp_{\rm gen} are recorded per step. The mixture groups positions with the same string: if a name appears twice, copy probabilities sum.

[ ]Train and evaluate copyingLocal GPU
import json, os, random
import torch
from torch import nn
from torch.nn import functional as F

SOURCE=['<pad>','<unk>','tiene']; TARGET=['<pad>','<bos>','<eos>','<unk>','has']
SINDEX={w:i for i,w in enumerate(SOURCE)};TINDEX={w:i for i,w in enumerate(TARGET)}
PAD,BOS,EOS,UNK=0,1,2,3
device=torch.device(os.environ.get('COPY_DEVICE','cuda' if torch.cuda.is_available() else 'cpu'))
torch.set_num_threads(1)

class CopyTranslator(nn.Module):
    def __init__(self,copy=True,width=32):
        super().__init__();self.copy=copy;self.width=width
        self.source=nn.Embedding(len(SOURCE),width,padding_idx=0);self.target=nn.Embedding(len(TARGET),width,padding_idx=0)
        self.encoder=nn.GRU(width,width//2,batch_first=True,bidirectional=True)
        self.decoder=nn.GRU(width,width,batch_first=True)
        self.W=nn.Linear(width,width,bias=False);self.U=nn.Linear(width,width,bias=False);self.v=nn.Linear(width,1,bias=False)
        self.head=nn.Linear(2*width,len(TARGET));self.gate=nn.Linear(3*width,1)
    def encode(self,x):
        ann,_=self.encoder(self.source(x));return ann,self.U(ann)
    def step(self,token,state,ann,pre):
        emb=self.target(token);out,state=self.decoder(emb[:,None,:],state);s=out[:,0]
        attention=self.v(torch.tanh(self.W(s)[:,None,:]+pre)).squeeze(-1).softmax(-1)
        context=torch.bmm(attention[:,None,:],ann).squeeze(1)
        vocab=self.head(torch.cat((s,context),-1)).softmax(-1)
        gate=self.gate(torch.cat((s,context,emb),-1)).sigmoid().squeeze(-1) if self.copy else torch.ones(len(token),device=token.device)
        return vocab,attention,gate,state
    def loss(self,x):
        ann,pre=self.encode(x);B=x.shape[0];state=ann.new_zeros((1,B,self.width));previous=torch.full((B,),BOS,device=x.device,dtype=torch.long)
        # Objetivo: nombre, «has», número, eos; nombre y número son desconocidos para el vocabulario fijo.
        targets=[UNK,TINDEX['has'],UNK,EOS];copy_positions=[0,None,2,None];loss=0.
        for target,pos in zip(targets,copy_positions):
            vocab,attention,gate,state=self.step(previous,state,ann,pre)
            if self.copy:
                pv=vocab[:,target] if pos is None else torch.zeros(B,device=x.device)
                pc=attention[:,pos] if pos is not None else torch.zeros(B,device=x.device)
                probability=gate*pv+(1-gate)*pc
            else:probability=vocab[:,target]
            loss-=torch.log(probability.clamp_min(1e-12)).mean()/len(targets)
            previous=torch.full((B,),target,device=x.device,dtype=torch.long)
        return loss
    @torch.no_grad()
    def translate(self,source,limit=6):
        self.eval();x=torch.tensor([[SINDEX.get(w,1) for w in source]],device=device)
        ann,pre=self.encode(x);state=ann.new_zeros((1,1,self.width));previous=torch.tensor([BOS],device=device);out=[];trace=[]
        for _ in range(limit):
            vocab,attention,gate,state=self.step(previous,state,ann,pre);pv=vocab[0].cpu().tolist();a=attention[0].cpu().tolist();g=float(gate[0])
            distribution={word:g*pv[i] for i,word in enumerate(TARGET)}
            if self.copy:
                for word,weight in zip(source,a):distribution[word]=distribution.get(word,0.)+(1-g)*weight
            word=max(distribution,key=distribution.get)
            trace.append({'output':word,'p_gen':g,'vocab':dict(zip(TARGET,pv)),'attention':a,'distribution':distribution})
            if word=='<eos>':break
            out.append(word);previous=torch.tensor([TINDEX.get(word,UNK)],device=device)
        return {'source':source,'output':out,'steps':trace}

def fit_copy(copy,steps=500,seed=19):
    torch.manual_seed(seed);random.seed(seed);model=CopyTranslator(copy).to(device);opt=torch.optim.Adam(model.parameters(),lr=.003)
    # El contenido de nombre y número se representa como <unk> en el encoder; sus cadenas se conservan para copiar.
    training=[(f'N{i:03d}',str(100+i)) for i in range(200)];rng=random.Random(seed)
    for step in range(steps):
        examples=rng.choices(training,k=32)
        x=torch.tensor([[SINDEX.get(name,1),SINDEX['tiene'],SINDEX.get(number,1)] for name,number in examples],dtype=torch.long,device=device)
        model.train();loss=model.loss(x);opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
    return model,float(loss.detach())

def evaluate_copy(model):
    name_ok=number_ok=both=0
    first=['Alba','Lucía','María','Jorge','Hugo','Nuria','Inés','Diego','Sara','Mateo']
    last=['Paz','Sol','Luz','Cruz','Díaz','Ríos','Vega','Rosa','León','Gil']
    for i in range(100):
        name=first[i//10]+'_'+last[i%10];number=str(300+i);result=model.translate([name,'tiene',number])['output']
        name_ok+=len(result)>0 and result[0]==name;number_ok+=len(result)>2 and result[2]==number
        both+=result==[name,'has',number]
    return {'names':int(name_ok),'numbers':int(number_ok),'exact':int(both),'total':100}

steps=int(os.environ.get('COPY_STEPS','5'))
baseline,loss_base=fit_copy(False,steps);pointer,loss_copy=fit_copy(True,steps)
print('Pasos por modelo:',steps,'pérdidas:',loss_base,loss_copy)
print('Nombres y números reservados, base:',evaluate_copy(baseline),'puntero:',evaluate_copy(pointer))
example=pointer.translate(['Alba_Paz','tiene','337']);base_example=baseline.translate(['Alba_Paz','tiene','337'])
print('Ejemplo puntero:',json.dumps(example,ensure_ascii=False))
print('Ejemplo base:',json.dumps(base_example,ensure_ascii=False))
repeat=pointer.translate(['N237','tiene','N237'])['steps'][0]
expected=(1-repeat['p_gen'])*(repeat['attention'][0]+repeat['attention'][2])
assert abs(repeat['distribution']['N237']-expected)<1e-6
print('Dos apariciones: suma de copia comprobada.')
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, the pointer copied all 100 held-out names and 100 numbers, with 100/100 exact sequences. The baseline produced 0/100 names and 0/100 literal numbers because both types were outside its vocabulary. The task has a fixed template and one seed: it does not measure open-sentence translation. The figure shows four actual steps of example Alba_Paz tiene 337 and can query another input after the local cell runs. A five-step run checks flow and need not reproduce the recorded example’s quality.

InteractiveGenerate or copy?

Recorded example: model trained for 1,000 steps on the synthetic task.

Source: Alba_Paz tiene 337
Output: Alba_Paz has 337

Blue: generation; orange: copy. Vocabulary distribution before mixing:

<pad> 0.003 · <bos> 0.003 · <eos> 0.002 · <unk> 0.005 · has 0.988

Copy attention by position: Alba_Paz 1.000 · tiene 0.000 · 337 0.000.

Final probability of the emitted token: 0.9998.

1
p_gen0.0001
Copy weight0.9999
Emitted tokenAlba_Paz
Recorded distributions from a model trained 1 000 steps on a synthetic template. Change step or query the real model from your local lab.

Check copying in real translation

The template above does not measure open translation. This second test adds a copy gate to the previous lesson’s attention translator and compares it with a fixed-vocabulary encoder-decoder on real ManyThings/Tatoeba sentences. Download spa-eng.zip and configure SEQ_DATA; PyTorch and sacrebleu==2.5.1 are needed. SEQ2SEQ_FULL=1 uses 30 000 training sources, 2 000 validation and 2 000 test; REAL_COPY_STEPS sets budget and defaults to five steps per model. This short run checks flow, not quality.

Test is searched for tokens shared by source and reference that occur in neither training sources nor references and are outside output vocabulary: numbers and capitalization candidates in both original texts. This automatic rule can include place names or words capitalized by position; it is not a perfect proper-name tagger. Count whether the literal token appears in the generated hypothesis. The corpus is grouped by source before splitting, but this does not guarantee semantic independence. The baseline uses fixed context and the copy variant bidirectional attention, so comparison does not isolate the switch. The code sums attention for repeated occurrences and exposes examples and denominator; rates on few cases are highly uncertain.

In one local run with file SHA-256 07bb8aaaf1458abbcdc8a3a51ce5b9f8a2643c829dcb7c2a63b3fec8dde934dc, one seed, and 1 000 updates per model, baseline produced 0 of 9 capitalization candidates and 0 of 7 numbers; copy produced 3 of 9 and 1 of 7. For example, for “yukio mishima se suicidó en 1970,” the latter generated the <unk> mishima is <unk> .: it neither copied the number nor translated correctly. These are literal-presence results, not translation quality; small sample size and differing architectures prevent attribution solely to the gate. The baseline cannot generate those out-of-vocabulary tokens.

[ ]Copying in held-out Tatoeba sentencesLocal 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

import json
class RealCopyTranslator(AttentiveTranslator):
    def __init__(self,hidden=128):
        super().__init__(hidden);self.copy_gate=nn.Linear(hidden*3,1)
    def loss_extended(self,examples):
        x,lengths,y=batch(examples,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);loss=0.;count=0
        for t in range(y.shape[1]):
            context,a=self.attend(state[0][-1],ann,valid,pre);emb=self.tgt_emb(token)
            out,state=self.decoder(torch.cat((emb,context),-1)[:,None,:],state);state_out=out[:,0]
            vocab=self.head(state_out).softmax(-1);gate=self.copy_gate(torch.cat((state_out,context,emb),-1)).sigmoid().squeeze(-1)
            masks=[];allowed=[];active=[]
            for src,tgt in examples:
                word=tgt[t] if t<len(tgt) else ('<eos>' if t==len(tgt) else None)
                match=[float(word is not None and word==w) for w in src]+[0.]*(x.shape[1]-len(src))
                masks.append(match);active.append(word is not None)
                allowed.append(word is not None and (word in ti or not any(match)))
            match=torch.tensor(masks,device=x.device);active=torch.tensor(active,device=x.device,dtype=torch.bool)
            allowed=torch.tensor(allowed,device=x.device,dtype=torch.float32)
            probability=gate*vocab.gather(1,y[:,t,None]).squeeze(1)*allowed+(1-gate)*(a*match).sum(1)
            loss-=torch.log(probability.clamp_min(1e-12))[active].sum();count+=int(active.sum());token=y[:,t]
        return loss/count
    @torch.no_grad()
    def generate_words(self,src,limit=24):
        x,lengths,_=batch([(src,())],False);ann,valid,pre=self.encode(x,lengths)
        state=(ann.new_zeros((2,1,self.hidden)),ann.new_zeros((2,1,self.hidden)));token=torch.tensor([BOS],device=device);words=[];trace=[]
        for _ in range(limit):
            context,a=self.attend(state[0][-1],ann,valid,pre);emb=self.tgt_emb(token)
            out,state=self.decoder(torch.cat((emb,context),-1)[:,None,:],state);s=out[:,0]
            vocab=self.head(s).softmax(-1)[0];gate=float(self.copy_gate(torch.cat((s,context,emb),-1)).sigmoid()[0,0]);a=a[0]
            best={tv[int(i)]:gate*float(vocab[i]) for i in torch.topk(vocab,min(100,len(tv))).indices.tolist()}
            for i,word in enumerate(src):
                base=gate*float(vocab[ti[word]]) if word in ti else 0.
                if word not in best:best[word]=base
                best[word]+=(1-gate)*float(a[i])
            word=max(best,key=best.get);trace.append({'word':word,'p_gen':gate,'attention':a[:len(src)].cpu().tolist()})
            if word=='<eos>':break
            words.append(word);token=torch.tensor([ti.get(word,UNK)],device=device)
        return words,trace

def train_real_copy(steps):
    torch.manual_seed(1919);rng=random.Random(1919);model=RealCopyTranslator().to(device);opt=torch.optim.Adam(model.parameters(),lr=.001)
    for step in range(steps):
        examples=rng.sample(train,32);model.train();loss=model.loss_extended(examples)
        opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
        if (step+1)%500==0:print('copia real',step+1,'pérdida',round(float(loss.detach()),4),flush=True)
    return model

original={}
for row in rows:
    parts=row.split('\t')
    if len(parts)>=3:
        es,en=tokenize(parts[1]),tokenize(parts[0])
        if 2<=len(es)<=18 and 2<=len(en)<=18:original.setdefault(tuple(es),(parts[0],parts[1]))
cases={'capitalizados':[],'números':[]}
seen_train={word for src,tgt in train for word in (*src,*tgt)}
for src,tgt in test:
    english,spanish=original[src]
    capitals={x.lower() for x in re.findall(r'(?<![\w])[A-ZÁÉÍÓÚÑ][a-záéíóúñ]+',english)} & {x.lower() for x in re.findall(r'(?<![\w])[A-ZÁÉÍÓÚÑ][a-záéíóúñ]+',spanish)}
    for word in sorted(set(src)&set(tgt)):
        if word in ti or word in seen_train:continue
        if word.isdigit():cases['números'].append((src,tgt,word))
        elif word in capitals and word!='i':cases['capitalizados'].append((src,tgt,word))
def evaluate_real_copy(model,copy):
    model.eval();results={}
    for kind,items in cases.items():
        correct=0;examples=[]
        for src,tgt,word in items:
            if copy:pred,trace=model.generate_words(src)
            else:
                x,lengths,_=batch([(src,tgt)],False);pred=[tv[k] for k in model.generate(x,lengths)[0]];trace=[]
            correct+=word in pred
            if len(examples)<2:examples.append({'fuente':' '.join(src),'referencia':' '.join(tgt),'token':word,'salida':' '.join(pred)})
        results[kind]={'correct':int(correct),'total':len(items),'examples':examples}
    return results

real_steps=int(os.environ.get('REAL_COPY_STEPS','5'))
def train_real_baseline(steps):
    torch.manual_seed(1919);rng=random.Random(1919);model=Seq2Seq(128).to(device);opt=torch.optim.Adam(model.parameters(),lr=.001)
    for step in range(steps):
        examples=rng.sample(train,32);x,lengths,y=batch(examples,False);model.train();logits=model(x,lengths,y)
        loss=nn.functional.cross_entropy(logits.reshape(-1,len(tv)),y.reshape(-1),ignore_index=PAD)
        opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
    return model
base_real=train_real_baseline(real_steps);copy_real=train_real_copy(real_steps)
print('Candidatos compartidos fuera del vocabulario; pasos por modelo:',real_steps)
print('Sin copia:',json.dumps(evaluate_real_copy(base_real,False),ensure_ascii=False))
print('Con copia:',json.dumps(evaluate_real_copy(copy_real,True),ensure_ascii=False))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: General scoring factorizes as a product of projections.
0
Let A have shape (k, dₛ), B shape (k, dₕ), and W=AᵀB.

Step 1 of 3. What shape does W have?

Numeric
With p=7.3, D=2, σ=D/2 and equal scores at integer positions 6, 7, 8 and 9, calculate the weight at position 7 under Luong's formula: window softmax multiplied by the Gaussian without renormalizing.
Numeric
If p_gen=0.3, P_vocab(Madrid)=0.01, and total attention on all occurrences of Madrid is 0.8, calculate the final probability of Madrid.
Quiz
Which initial choices best respect constraints of translation with long reordering, streaming speech, and approximately monotonic transliteration, respectively?
Code
Implement luong_general_attention(S,H,W,mask). S has shape (B,U,dₛ), H (B,T,dₕ), W (dₛ,dₕ), and mask (B,T). Return weights (B,U,T) and contexts (B,U,dₕ); normalize over T and reject batch rows without a valid source.
import numpy as np
def luong_general_attention(S,H,W,mask):
  pass
Shift+Enter to run