Guided project: an attention-based neural translator on your GPU
Build and assess a small Spanish-English neural translator using attention, coverage, copying, length-stratified metrics, paired bootstrap and controlled attention interventions.
After this lesson you can
- Integrate a BiLSTM encoder and recurrent decoder with attention, copying and coverage.
- Evaluate translation quality by source length using paired bootstrap and multiple seeds.
- Describe the published GNMT architecture and its parallel execution.
- Test what attention weights explain using controlled interventions.
Before you start
- 17Multiplicative attentionAdditive attentionAttention as soft alignmentInput feeding and attention computation orderPointer networks and copy mechanismVariable-length batching: padding, masking and packingStacked (deep) RNNsBLEU and chrFScheduled sampling
- 00Canonical training and evaluation loopExperiment metric trackingMulti-seed evaluation
- 05Nonparametric bootstrapBootstrap percentile and basic intervals
Integrate and measure
In this project you build a small Spanish-to-English translator from the earlier components: a BiLSTM encoder, a recurrent decoder, additive or general attention, context feedback, copying and coverage. The aim is to learn how to control a comparison, not to reproduce the quality of a commercial system. The tests on this machine use an RTX 3060; the original design proposes an 8 GB RTX 4060. Do not extrapolate time or memory across devices. Batching sources of similar lengths reduces padding; pack_padded_sequence avoids recurrent steps over padding, and the mask prevents attention from assigning mass to it.
The ManyThings/Tatoeba archive is downloaded separately. The cell reports its SHA-256, groups sentences by source before splitting, fits vocabularies on training data only, and fixes 30 000/2 000/2 000 sources when SEQ2SEQ_FULL=1. Test is not used to choose variants or hyperparameters. The archive changes over time: record its hash, split, seeds and metric signature before comparing runs. PyTorch and sacrebleu==2.5.1 are required; the device is detected at runtime. Batch size, width and number of steps are experimental choices: begin with a few steps to check shapes and memory, then run the planned budget.
Coverage and copying
At step , attention distributes mass across valid source positions. Coverage accumulates previous reads. A projection of can be added to the additive score and overlap penalized. Each valid step adds exactly one unit to total coverage. This quantity records attention rather than literal translations: a word may need multiple reads or have no one-to-one counterpart. Consequently, less than one suggests a possible omission and more than one a possible repetition; neither establishes an error label.
The copy gate mixes vocabulary probability with attention over positions whose source token matches the target; repeated words contribute the sum over those positions. An out-of-vocabulary token can therefore appear in the output if it is in the source. The decoder represents it as <unk> on the next input; this is an explicit approximation, not a complete dynamic vocabulary. Input feeding concatenates the previous context with the embedding and current context. Training coverage and GNMT’s search penalty are distinct: the latter adds to a complete hypothesis score; zero coverage gives in the ideal formula.
The two translator figures show 5 000 updates for each of five variants and three seeds, with 200 resamples per bucket. They use 30 000 training sources and 2 000 test sources from the archive with SHA-256 07bb8aaaf1458abbcdc8a3a51ce5b9f8a2643c829dcb7c2a63b3fec8dde934dc. PyTorch peak allocation was 130 389 504 bytes on the RTX 3060. The budget and quality remain modest and do not represent a commercial system.
A production reference: GNMT
The published GNMT architecture described in its paper uses eight LSTM layers on each side, 1 024 units per layer and an attention network with 1 024 hidden units. The encoder’s first layer is bidirectional; upper layers are unidirectional so later layers can begin work without waiting for an entire additional backward pass. Residual connections start at the third layer from the bottom. Attention takes the output of the decoder’s bottom layer and queries the encoder’s top layer; context is passed to the decoder’s upper layers. This arrangement increases parallelism between layers. The paper describes depth-wise partitioning across GPUs and a partitioned softmax, in addition to data replicas; the exact number of devices depends on deployment.
GNMT’s wordpieces address rare words with subwords, unlike the laboratory’s word vocabulary and copy mechanism. A stack of 1 024 units does not imply every tensor always has that shape: concatenating the two bidirectional passes doubles the width, and projections or concatenated inputs determine each matrix’s actual size. For a conventional LSTM without projection and with one pair of biases, input width and hidden width require parameters. Some libraries store two biases per gate, changing this count. This illustrative count is distinct from the production model’s total.
Train and diagnose
The next cell can change configuration using a JSON file specified by PROJECT_CONFIG; when the variable is absent it uses five declared variants. PROJECT_STEPS sets updates per variant and seed, PROJECT_BOOTSTRAPS sets the number of resamples and PROJECT_OUT stores outputs and results. PROJECT_CHECKPOINT_DIR can save weights, configuration and vocabularies per variant; PROJECT_PARTIAL_OUT saves progress after each. Five steps run by default, a functionality check rather than a quality run. Architecture, examples and seeds are paired when possible; copying and coverage introduce different mechanisms, and a score difference alone cannot identify which component caused it.
For example, save this content as config.json and set its path in PROJECT_CONFIG to compare additive attention, coverage and scheduled sampling. To obtain difference intervals against the additive baseline, keep an entry named additive:
{
"additive": {"attention": "additive", "input_feeding": true},
"coverage": {"attention": "additive", "input_feeding": true, "coverage": true, "coverage_lambda": 0.1},
"scheduled": {"attention": "additive", "input_feeding": true, "scheduled": true}
}
Allowed attention values are none, additive and general. With none the context is the fixed mean of valid positions; with the other two it changes at each step. The scheduled-input schedule decreases linearly to a 0.5 probability of using the reference, and the coverage loss is added with the specified weight. JSON labels name experiments and do not automatically alter the model.
The batch is sorted by length, PAD is ignored in the loss and the gradient norm is clipped. In copy mode the probabilities of all positions containing the same token are summed, while an OOV reference absent from the source is represented as unknown. scheduled can be enabled in the configuration to use the previous lesson’s curriculum. Autoregressive output ends at EOS or a limit of 24 steps, and metrics must be interpreted with that truncation in mind. The code records BLEU, chrF, bigram repetition and literal absence of rare reference tokens: the last indicator cannot distinguish a correct synonym from an omission.
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)
import json, numpy as np
from torch.nn.utils.rnn import pad_packed_sequence
torch.set_num_threads(1)
class ConfigurableNMT(nn.Module):
def __init__(self,cfg,hidden=128):
super().__init__();self.cfg=cfg;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*3,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.coverage_weight=nn.Linear(1,hidden,bias=False);self.head=nn.Linear(hidden,len(tv));self.gate=nn.Linear(hidden*3,1)
def encode(self,x,lengths):
packed=pack_padded_sequence(self.src_emb(x),lengths.cpu(),batch_first=True,enforce_sorted=False)
h,_=self.encoder(packed);h,_=pad_packed_sequence(h,batch_first=True,total_length=x.shape[1])
mask=torch.arange(x.shape[1],device=x.device)[None,:]<lengths.to(x.device)[:,None]
return h,mask
def step(self,token,state,previous,h,mask,coverage):
mode=self.cfg['attention'];query=state[0][-1]
if mode=='none':
a=mask.float()/mask.sum(1,keepdim=True)
else:
if mode=='additive':
energy=self.W(query)[:,None,:]+self.U(h)
if self.cfg.get('coverage'):energy=energy+self.coverage_weight(coverage[:,:,None])
energy=self.v(torch.tanh(energy)).squeeze(-1)
elif mode=='general':
energy=torch.bmm(h,self.W(query)[:,:,None]).squeeze(-1)
if self.cfg.get('coverage'):energy=energy+self.coverage_weight(coverage[:,:,None]).mean(-1)
else:raise ValueError('atención desconocida')
a=energy.masked_fill(~mask,float('-inf')).softmax(-1)
context=torch.bmm(a[:,None,:],h).squeeze(1);emb=self.tgt_emb(token)
feed=previous if self.cfg.get('input_feeding',True) else torch.zeros_like(previous)
out,state=self.decoder(torch.cat((emb,context,feed),-1)[:,None,:],state);s=out[:,0]
v=self.head(s).softmax(-1);gate=self.gate(torch.cat((s,context,emb),-1)).sigmoid()
return state,context,a,v,gate
def initial(self,h):
B=len(h);return (h.new_zeros((2,B,self.hidden)),h.new_zeros((2,B,self.hidden))),h.new_zeros((B,self.hidden)),h.new_zeros(h.shape[:2])
def loss(self,examples,eps,generator):
x,lengths,y=batch(examples,False);h,mask=self.encode(x,lengths);state,prev,cov=self.initial(h);token=torch.full((len(x),),BOS,dtype=torch.long,device=device)
extended=[]
for src,_ in examples:
seen={};row=[]
for j,word in enumerate(src):
if word in ti:row.append(ti[word])
else:
if word not in seen:seen[word]=len(tv)+j
row.append(seen[word])
extended.append(row+[PAD]*(x.shape[1]-len(src)))
extended=torch.tensor(extended,device=device,dtype=torch.long)
loss=h.new_tensor(0.);penalty=h.new_tensor(0.);count=0
for t in range(y.shape[1]):
state,prev,a,v,gate=self.step(token,state,prev,h,mask,cov);active=y[:,t]!=PAD
if self.cfg.get('copy'):
matches=[];allow=[]
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))
matches.append(match);allow.append(word is not None and (word in ti or not any(match)))
matches=torch.tensor(matches,device=device);allow=torch.tensor(allow,device=device,dtype=v.dtype)
prob=gate.squeeze(1)*v.gather(1,y[:,t,None]).squeeze(1)*allow+(1-gate.squeeze(1))*(a*matches).sum(1)
else:prob=v.gather(1,y[:,t,None]).squeeze(1)
loss-=torch.log(prob.clamp_min(1e-12))[active].sum()
if self.cfg.get('coverage'):penalty+=torch.minimum(a,cov).sum(1)[active].sum()
cov=cov+a;count+=int(active.sum())
if eps>=1:token=y[:,t]
else:
if self.cfg.get('copy'):
sample_probs=torch.cat((gate*v,v.new_zeros((len(x),x.shape[1]))),dim=1)
sample_probs=sample_probs.scatter_add(1,extended,(1-gate)*a)
else:sample_probs=v
sampled=torch.multinomial(sample_probs.detach(),1,generator=generator).squeeze(1)
sampled=torch.where(sampled<len(tv),sampled,UNK)
token=torch.where(torch.rand(len(x),device=device,generator=generator)<eps,y[:,t],sampled)
return (loss+float(self.cfg.get('coverage_lambda',.1))*penalty)/count
@torch.no_grad()
def generate(self,examples,limit=24,trace=False):
x,lengths,_=batch(examples,False);h,mask=self.encode(x,lengths);state,prev,cov=self.initial(h);token=torch.full((len(x),),BOS,dtype=torch.long,device=device)
done=torch.zeros(len(x),dtype=torch.bool,device=device);outputs=[[] for _ in examples];align=[[] for _ in examples]
extended=[]
for src,_ in examples:
seen={};row=[]
for j,word in enumerate(src):
if word in ti:row.append(ti[word])
else:
if word not in seen:seen[word]=len(tv)+j
row.append(seen[word])
extended.append(row+[PAD]*(x.shape[1]-len(src)))
extended=torch.tensor(extended,device=device,dtype=torch.long)
for _ in range(limit):
state,prev,a,v,gate=self.step(token,state,prev,h,mask,cov);cov+=a;next_ids=[]
if self.cfg.get('copy'):
probs=torch.cat((gate*v,v.new_zeros((len(x),x.shape[1]))),dim=1)
probs.scatter_add_(1,extended,(1-gate)*a)
else:probs=v
indices=probs.argmax(-1);chosen=indices.tolist();finished=done.tolist();attention=a.cpu().tolist() if trace else None
for i,(src,_) in enumerate(examples):
k=chosen[i];word=tv[k] if k<len(tv) else src[k-len(tv)]
if not finished[i]:
if trace:align[i].append(attention[i][:lengths[i]])
if word!='<eos>':outputs[i].append(word)
if word=='<eos>':finished[i]=True
next_ids.append(ti.get(word,UNK) if not finished[i] else EOS)
done=torch.tensor(finished,device=device,dtype=torch.bool);token=torch.tensor(next_ids,device=device)
if done.all():break
return outputs,align
DEFAULTS={
'fixed':{'attention':'none','input_feeding':False},
'additive':{'attention':'additive','input_feeding':True},
'general':{'attention':'general','input_feeding':True},
'copy':{'attention':'additive','input_feeding':True,'copy':True},
'coverage':{'attention':'additive','input_feeding':True,'coverage':True,'coverage_lambda':.1}}
def load_project_checkpoint(path):
saved=torch.load(path,map_location=device,weights_only=False)
if saved['source_vocab']!=sv or saved['target_vocab']!=tv:raise ValueError('Los vocabularios no corresponden a esta partición')
model=ConfigurableNMT(saved['config']).to(device);model.load_state_dict(saved['state_dict']);model.eval()
return model,saved
def train_model(cfg,seed,steps):
torch.manual_seed(seed);rng=random.Random(seed);gen=torch.Generator(device=device).manual_seed(seed+2121)
model=ConfigurableNMT(cfg).to(device);optim=torch.optim.Adam(model.parameters(),lr=.001)
for step in range(steps):
examples=sorted(rng.sample(train,32),key=lambda pair:len(pair[0]),reverse=True);model.train()
eps=max(.5,1-.5*(step+1)/steps) if cfg.get('scheduled') else 1.
loss=model.loss(examples,eps,gen);optim.zero_grad();loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);optim.step()
if (step+1)%500==0:print('semilla',seed,'configuración',cfg,'paso',step+1,'pérdida',round(loss.item(),4),flush=True)
return model
def predict_all(model,examples):
model.eval();out=[]
for i in range(0,len(examples),32):out+=model.generate(examples[i:i+32])[0]
return out
def score_system(examples,pred):
refs=[' '.join(t) for _,t in examples];hyps=[' '.join(p) for p in pred]
def repeats(p):
pairs=list(zip(p,p[1:]));return len(pairs)!=len(set(pairs))
counts=Counter(w for _,t in train for w in t)
def group(low,high):
ids_=[i for i,(s,_) in enumerate(examples) if low<=len(s)<=high]
if not ids_:return {'n':0}
bleu=BLEU(tokenize='none',force=True);chrf=CHRF()
b=bleu.corpus_score([hyps[i] for i in ids_],[[refs[i] for i in ids_]]).score
c=chrf.corpus_score([hyps[i] for i in ids_],[[refs[i] for i in ids_]]).score
rare=[(i,w) for i in ids_ for w in set(examples[i][1]) if counts[w]<=2]
return {'n':len(ids_),'bleu':b,'chrf':c,'repetitions':sum(repeats(pred[i]) for i in ids_)/len(ids_), 'rare_n':len(rare),'rare_absent':sum(w not in pred[i] for i,w in rare)/len(rare) if rare else None}
return {f'{a}-{b}':group(a,b) for a,b in [(2,5),(6,9),(10,13),(14,18)]}
steps=int(os.environ.get('PROJECT_STEPS','5'));config_path=os.environ.get('PROJECT_CONFIG')
configs=json.loads(Path(config_path).read_text(encoding='utf8')) if config_path else DEFAULTS
seeds=[21,22,23];runs=[]
if device.type=='cuda':torch.cuda.reset_peak_memory_stats()
for seed in seeds:
row={'seed':seed,'variants':{}}
for name,cfg in configs.items():
print('Iniciar variante',name,'semilla',seed,'pasos',steps,flush=True)
model=train_model(cfg,seed,steps);pred=predict_all(model,test)
row['variants'][name]={'scores':score_system(test,pred),'hypotheses':[' '.join(x) for x in pred]}
if seed==seeds[0] and name in ('additive','coverage'):
_,align=model.generate([test[0]],trace=True)
row['variants'][name]['example']={'source':' '.join(test[0][0]),'reference':' '.join(test[0][1]),'hypothesis':' '.join(pred[0]),'attention':align[0]}
if os.environ.get('PROJECT_CHECKPOINT_DIR'):
directory=Path(os.environ['PROJECT_CHECKPOINT_DIR']);directory.mkdir(parents=True,exist_ok=True)
safe=re.sub(r'[^a-zA-Z0-9_-]','_',name)
torch.save({'state_dict':model.state_dict(),'config':cfg,'source_vocab':sv,'target_vocab':tv,'seed':seed,'steps':steps},directory/f'{safe}-{seed}.pt')
if os.environ.get('PROJECT_PARTIAL_OUT'):
partial={'archive_sha256':hashlib.sha256(archive).hexdigest(),'steps':steps,'references':[' '.join(t) for _,t in test],'source_lengths':[len(s) for s,_ in test],'runs':runs+[row]}
Path(os.environ['PROJECT_PARTIAL_OUT']).write_text(json.dumps(partial,ensure_ascii=False),encoding='utf8')
print('Variante terminada',name,'semilla',seed,flush=True)
runs.append(row);print('semilla terminada:',seed,json.dumps({k:v['scores'] for k,v in row['variants'].items()},ensure_ascii=False),flush=True)
output={'archive_sha256':hashlib.sha256(archive).hexdigest(),'steps':steps,'seeds':seeds,'configs':configs,'references':[' '.join(t) for _,t in test],'source_lengths':[len(s) for s,_ in test],'runs':runs,'signature':'sacreBLEU 2.5.1 tok:none; chrF por defecto'}
if device.type=='cuda':print('Pico de memoria asignada por PyTorch, bytes:',torch.cuda.max_memory_allocated())
def bootstrap_buckets(output,samples=200):
refs=output['references'];lengths=output['source_lengths']
for row in output['runs']:
if 'additive' not in row['variants']:continue
for low,high in [(2,5),(6,9),(10,13),(14,18)]:
idx=[i for i,n in enumerate(lengths) if low<=n<=high]
if not idx:continue
rs=[refs[i] for i in idx];draw=np.random.default_rng(2121).integers(0,len(idx),(samples,len(idx)))
for label,metric in [('bleu',BLEU(tokenize='none',force=True)),('chrf',CHRF())]:
stats={}
for name,v in row['variants'].items():
h=[v['hypotheses'][i] for i in idx]
stats[name]=np.array(metric._extract_corpus_statistics(h,[rs]),dtype=np.float64)
sampled={name:np.array([metric._compute_score_from_stats(x[d].sum(0)).score for d in draw]) for name,x in stats.items()}
for name,v in row['variants'].items():
cell=v['scores'][f'{low}-{high}'];cell[label+'_ci']=np.percentile(sampled[name],[2.5,97.5]).tolist()
cell[label+'_difference_ci']=np.percentile(sampled[name]-sampled['additive'],[2.5,97.5]).tolist()
return output
bootstrap_buckets(output,int(os.environ.get('PROJECT_BOOTSTRAPS','200')))
print('Bootstrap emparejado por frase y cubeta:',os.environ.get('PROJECT_BOOTSTRAPS','200'),'réplicas.')
if os.environ.get('PROJECT_OUT'):
Path(os.environ['PROJECT_OUT']).write_text(json.dumps(output,ensure_ascii=False),encoding='utf8')
npm run lab and open the connection link.The 6-to-9-token bucket contains 1 092 sentences. With seed 21, BLEU was 9.047 for fixed context, 14.368 for additive attention, 11.552 for general attention, 14.261 for copying and 7.904 for coverage; bigram repetition was 8.4 %, 6.8 %, 6.0 %, 5.3 % and 10.7 %, respectively. For example, tengo que estudiar francés . produced i have to see french . with the additive variant and i have a lot of time . with coverage. The copying-minus-additive difference interval includes zero for seeds 21 and 23, but not 22. The figure lets you inspect the other buckets; sentence bootstrap does not measure stability across training runs or demonstrate that coverage improves results at this budget.
Translation error analysis starts by recognizing that one global BLEU score can hide a decline on long sentences or rare vocabulary. The six challenges identified by Koehn and Knowles include domain shift, data quantity, rare words, length, alignment and beam search. The bucket table helps formulate questions rather than answering all of them: measure each bucket’s size, inspect translations and repeat seeds. Test sentences are not independent if they share context or provenance; sentence bootstrap assumes resampling approximates the target population.
BLEU bootstrap from scratch
Paired resampling selects sentence indices and uses exactly those indices for both outputs and their references. Corpus BLEU is recalculated from aggregate n-gram counts; averaging sentence BLEU is not equivalent. The small example below uses one reference per hypothesis, whitespace tokenization, exponential smoothing and four orders. The centered test reproduces sacreBLEU 2.5.1’s convention in this case; the percentile interval for the difference is another description of the resampling. Neither measures variation across training seeds.
import math
from collections import Counter
import numpy as np
def sentence_stats(hyp,ref):
h=hyp.split();r=ref.split();correct=[];total=[]
for n in range(1,5):
hc=Counter(tuple(h[i:i+n]) for i in range(len(h)-n+1))
rc=Counter(tuple(r[i:i+n]) for i in range(len(r)-n+1))
correct.append(sum(min(v,rc[k]) for k,v in hc.items()));total.append(sum(hc.values()))
return np.array([len(h),len(r),*correct,*total],dtype=float)
def bleu(stats):
h,r=stats[:2];correct=stats[2:6];total=stats[6:10]
if h==0 or not np.any(correct) or np.any(total==0):return 0.
smooth=1.;prec=[]
for c,t in zip(correct,total):
if c==0:smooth*=2;prec.append(1/(smooth*t))
else:prec.append(c/t)
bp=math.exp(min(0,1-r/h));return 100*bp*math.exp(sum(math.log(p) for p in prec)/4)
def paired_bootstrap(refs,a,b,samples=1000,seed=21):
if not(len(refs)==len(a)==len(b)) or len(refs)==0:raise ValueError('listas no vacías e iguales')
sa=np.stack([sentence_stats(x,r) for x,r in zip(a,refs)]);sb=np.stack([sentence_stats(x,r) for x,r in zip(b,refs)])
rng=np.random.default_rng(seed);indices=rng.choice(len(refs),size=(samples,len(refs)),replace=True)
scores_a=np.array([bleu(sa[idx].sum(0)) for idx in indices]);scores_b=np.array([bleu(sb[idx].sum(0)) for idx in indices]);delta=scores_b-scores_a
observed=bleu(sb.sum(0))-bleu(sa.sum(0));absolute=np.abs(delta);centered=absolute-absolute.mean()
p=(np.count_nonzero(centered>abs(observed))+1)/(samples+1)
return {'a':bleu(sa.sum(0)),'b':bleu(sb.sum(0)),'difference':observed, 'ci_a':np.percentile(scores_a,[2.5,97.5]),'ci_b':np.percentile(scores_b,[2.5,97.5]),'ci_difference':np.percentile(delta,[2.5,97.5]),'p_centered':p,'delta':delta}
refs=['the red car is new','the museum is in town','she has a blue bicycle','a small dog runs fast','they read this book today']
a=['the car is new','the museum is in town','she has blue bicycle','a small dog runs fast','they read the book today']
b=['the red car is new','the museum is at town','she has a blue bicycle','a dog runs very fast','they read this book today']
result=paired_bootstrap(refs,a,b,1000,21)
print('BLEU A/B y diferencia:',round(result['a'],3),round(result['b'],3),round(result['difference'],3))
print('IC percentil de la diferencia:',np.round(result['ci_difference'],3))
print('Contraste bootstrap centrado:',round(result['p_centered'],4))
The five-sentence comparison is deliberately small: an interval crossing zero does not establish that the systems are identical. A real comparison requires more sentences and seeds; the best test result must not be selected. The next local cell checks the example’s values against sacreBLEU and its paired resampling using the same indices and seed.
from sacrebleu.metrics import BLEU
from sacrebleu.significance import Result, _paired_bs_test
import numpy as np
refs=['the red car is new','the museum is in town','she has a blue bicycle','a small dog runs fast','they read this book today']
a=['the car is new','the museum is in town','she has blue bicycle','a small dog runs fast','they read the book today']
b=['the red car is new','the museum is at town','she has a blue bicycle','a dog runs very fast','they read this book today']
metric=BLEU(tokenize='none',force=True);baseline=metric.corpus_score(a,[refs]);stats=np.array(metric._extract_corpus_statistics(a,[refs]))
_,result=_paired_bs_test({'BLEU':(stats,Result(baseline.score))},'B',b,[refs],{'BLEU':metric},n_samples=1000,seed=21)
print('sacreBLEU:',round(baseline.score,6),round(result['BLEU'].score,6),'p:',result['BLEU'].p_value)
print('firma:',metric.get_signature())
npm run lab and open the connection link.Does attention explain a decision?
The limits of attention as an explanation arise because a distribution of weights participates in the computation but does not by itself determine which word caused a prediction. Jain and Wallace found cases with different attention distributions and similar predictions; Wiegreffe and Pinter argued that the conclusion depends on the definition of explanation and the controls. The following test freezes the encoder of a BiLSTM trained to detect a question mark in real Tatoeba sentences. It reverses attention or makes it uniform and recomputes the same linear head. It also displays gradient norms with respect to embeddings. Intervened activations may be outside the learned distribution; neither the sentence nor the trained model is changed.
The recorded run performed 1 000 CPU updates with one seed and correctly classified 2 000 of 2 000 held-out sentences. This task is deliberately trivial: the label is defined by the literal presence of ? in the tokens. That number verifies the punctuation classifier, not question understanding or semantic generalization. The gradients are for the “question” logit with respect to each position’s embedding.
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)
from torch.nn.utils.rnn import pad_packed_sequence
import json
torch.set_num_threads(1)
class AttentiveClassifier(nn.Module):
def __init__(self):
super().__init__();self.emb=nn.Embedding(len(sv),32,padding_idx=PAD);self.rnn=nn.LSTM(32,24,batch_first=True,bidirectional=True);self.score=nn.Linear(48,1);self.head=nn.Linear(48,1)
def forward(self,x,lengths,return_trace=False):
emb=self.emb(x)
if return_trace:emb.retain_grad()
packed=pack_padded_sequence(emb,lengths.cpu(),batch_first=True,enforce_sorted=False);h,_=self.rnn(packed);h,_=pad_packed_sequence(h,batch_first=True,total_length=x.shape[1]);mask=torch.arange(x.shape[1],device=x.device)[None,:]<lengths.to(x.device)[:,None]
a=self.score(h).squeeze(-1).masked_fill(~mask,float('-inf')).softmax(-1)
logit=self.head(torch.bmm(a[:,None,:],h).squeeze(1)).squeeze(-1)
return (logit,h,a,emb) if return_trace else logit
def make_cls_batch(examples):
src=[s for s,_ in examples];labels=torch.tensor([float('?' in s) for s in src],device=device)
xs=[torch.tensor(ids(s,si),dtype=torch.long) for s in src];lengths=torch.tensor([len(x) for x in xs])
return pad_sequence(xs,batch_first=True,padding_value=PAD).to(device),lengths,labels
torch.manual_seed(2121);rng=random.Random(2121);classifier=AttentiveClassifier().to(device);optim=torch.optim.Adam(classifier.parameters(),lr=.001)
steps=int(os.environ.get('CLASSIFIER_STEPS','5'))
for i in range(steps):
examples=rng.sample(train,32);x,l,y=make_cls_batch(examples);classifier.train();logit=classifier(x,l);loss=nn.functional.binary_cross_entropy_with_logits(logit,y)
optim.zero_grad();loss.backward();nn.utils.clip_grad_norm_(classifier.parameters(),1.);optim.step()
if (i+1)%250==0:print('clasificador',i+1,'loss',round(loss.item(),4),flush=True)
classifier.eval();correct=0
with torch.no_grad():
for k in range(0,len(test),32):
group=test[k:k+32];x,l,y=make_cls_batch(group);correct+=int(((classifier(x,l)>0)==y.bool()).sum())
print('Clasificador test:',correct,'/',len(test),'frases, pasos:',steps,flush=True)
samples=[]
for label in (False,True):
group=next(item for item in test if ('?' in item[0])==label and len(item[0])>=5)
x,l,y=make_cls_batch([group]);classifier.zero_grad();logit,h,a,emb=classifier(x,l,True);logit.sum().backward()
weights=a[0,:l[0]].detach().cpu().tolist();hidden=h[0,:l[0]].detach().cpu().tolist();gradient=emb.grad[0,:l[0]].norm(dim=-1).detach().cpu().tolist()
samples.append({'tokens':list(group[0]),'reference_question':label,'weights':weights,'hidden':hidden,'gradient':gradient,'logit':float(logit[0].detach())})
record={'samples':samples,'head':classifier.head.weight.detach().cpu()[0].tolist(),'bias':float(classifier.head.bias.detach()),'steps':steps,'correct':correct,'total':len(test)}
print('Ejemplos:',json.dumps([{'tokens':s['tokens'],'logit':s['logit']} for s in samples],ensure_ascii=False))
if os.environ.get('CLASSIFIER_OUT'):
with open(os.environ['CLASSIFIER_OUT'],'w',encoding='utf8') as f:json.dump(record,f,ensure_ascii=False,separators=(',',':'))
npm run lab and open the connection link.This classifier’s states are contextual: a word’s state can contain information about distant punctuation. Keeping them fixed while changing the weights answers a particular intervention question, distinct from deleting a word or reconstructing the whole sentence. A stable result after permuting weights does not establish that all attention is useless. Compare uniform attention, gradients and several initializations, and define in advance which explanatory property you want to measure.
Exercises
import numpy as np
def coverage_attention_step(s,H,coverage,params,mask):
passStep 1 of 3. Why does α+tδ still sum to one?