Cross-attention and the original encoder-decoder transformer
Reconstruct an encoder-decoder transformer, implement cross-attention and its masks, train a synthetic sequence-to-sequence task, and compare it with recurrent attention and greedy decoding.
After this lesson you can
- Implement cross-attention with different query and key lengths and source and target padding masks.
- Assemble encoder and decoder blocks with shared embeddings.
- Train a synthetic sequence-to-sequence model with parallel teacher forcing and greedy decoding.
- Compare transformer and recurrent attention on accuracy, training speed, and length robustness.
- Explain label smoothing and the original paper's learning-rate schedule.
Before you start
One sequence queries another
To convert 31/12/1998 into 1998-12-31, the target must query different parts of the source as it generates. The recurrent encoder-decoder already separated input memory from an output state. In a transformer, memory is an entire sequence of vectors and the decoder queries it through cross-attention. Source and target need not have the same length.
Rows are queries and columns are keys. The encoder can look at all valid source keys; the decoder only looks at the past and present of its shifted input; cross-attention looks at all valid source keys. Target padding is also excluded from the loss and from decoder keys when variable-length examples are batched. A padding query row should not be interpreted as a valid prediction even if it has a numerical output.
Target queries, source memory
Cross-attention takes and . For each head, , , and have shapes , , and . Scores and result are
The mask matrix broadcasts to . Its padding mask excludes source columns, not target columns. The causal mask applies to target self-attention, not cross-attention in ordinary translation: the whole source is already available. If a query has no valid key, softmax over only values does not define a distribution; the implementation must reject that row or adopt an explicit convention.
Shape is a quick check against a common error. If the target has three positions and source five, the cross-map has three rows and five columns; it need not be square. A row sums to one over valid keys. Heads have their own projections and their concatenated outputs are mixed by the final projection, as in the previous block.
Backward through query and memory
Let and consider one head without dropout. Attention backward applies identically when :
The memory gradient has two paths, , and the decoder gradient is . Masked positions receive zero weight and gradient in exact arithmetic. The lab checks both the query gradient and the sum of both memory contributions with central differences; it includes one padding key and unequal lengths.
Three attention mechanisms in two stacks
An original encoder block applies bidirectional self-attention and then an FFN, with residual addition and normalization after each branch. A decoder block applies causal self-attention, cross-attention over encoder output, and an FFN, in that order, also with residuals and post-norm. The first path cannot see future target tokens; the second can see the entire source. A stack may have several layers, each with its own parameters.
The encoder-decoder transformer of Vaswani et al. combines those stacks with sinusoidal positions and embeddings. In the paper’s configuration embedding matrices and output projection are shared, with a common vocabulary. Two tables with incompatible vocabulary indices cannot be tied directly. Pre-norm variants and other positional mechanisms are later or alternative choices, not the original block’s exact equation.
The encoder computes a representation for each valid source position. In the decoder, comes from the state after self-attention, while come from that memory. Encoder memory reuse avoids rerunning it for each generated token. An efficient implementation can also precompute source K and V per layer and save previously computed decoder self-attention keys and values. The lab example reuses memory but recalculates the decoder prefix; it therefore does not represent a complete KV cache or its optimal cost.
Train in parallel, generate step by step
With teacher forcing, decoder input is [BOS, y1, ..., y_{T-1}] and labels are [y1, ..., yT]. A triangular mask allows all positions to be computed at once without leaking future labels. In greedy generation the previously chosen token is fed back until EOS or the limit. An error can change the prefix of later steps: this difference is part of the training-generation mismatch, and is not removed by measuring teacher-forced loss.
The paper uses label smoothing with : rather than requiring probability one for the correct class, it distributes a small mass among alternatives. This is a training-objective decision; the smoothed reference probability is not a model prediction. Conventions distribute mass among all classes or only incorrect ones: record which is implemented and exclude PAD when appropriate.
The original schedule, with step and warmup steps, is
It rises linearly until and then falls as . In the paper ; Adam uses , , and . This lesson’s small task uses a different optimizer and horizon so it can run on a home GPU: it does not reproduce the paper’s translation training.
The local lab saves real snapshots of the custom model on a validation date. Each map row uses the correct target prefix to construct the query: this is teacher forcing, not a generated sequence. Positions may align the year, month, or day without one isolated head explaining the whole model; residuals, values, and projections also participate.
The next figure uses the same example after training, but now the prefix contains model-chosen outputs. At each step it shows probabilities of five candidates and one head’s self-attention and cross-attention rows. If an error occurs, that symbol may influence subsequent steps.
NumPy lab: gradients and reversal
The first experiment implements cross-attention with a source mask, forward and backward. The toy encoder combines each one-hot symbol with its position and adds fixed self-attention; the decoder has residual causal self-attention over learned positional queries and uses cross-attention over that memory. Only queries are trained: the isolated task lets us verify the mechanism but does not replace full PyTorch encoder-decoder training. The output mixes one-hot values and must reverse sequences of four symbols. Loss calculation sums mass over all keys with the correct symbol, allowing repetitions. Central differences verify both cross-attention backward and query gradients through both attention operations.
import numpy as np
def softmax(z):
e=np.exp(z-z.max(axis=-1,keepdims=True));return e/e.sum(axis=-1,keepdims=True)
def cross_forward(query,memory,valid):
if not np.all(valid.any(axis=1)): raise ValueError('Cada ejemplo necesita al menos una clave válida')
logits=query@memory.transpose(0,2,1)/np.sqrt(query.shape[-1])
logits=np.where(valid[:,None,:],logits,-1e9)
p=softmax(logits)
return p@memory,(query,memory,p)
def cross_backward(up,cache):
query,memory,p=cache;d=query.shape[-1]
dp=up@memory.transpose(0,2,1);ds=p*(dp-(dp*p).sum(-1,keepdims=True))
return ds@memory/np.sqrt(d),p.transpose(0,2,1)@up+ds.transpose(0,2,1)@query/np.sqrt(d)
def encoder(tokens):
b,t=tokens.shape
values=np.eye(4)[tokens];position=np.broadcast_to(np.eye(t),(b,t,t))
x=np.concatenate((values,position),axis=-1)
y,_=cross_forward(x,x,np.ones((b,t),dtype=bool))
return x+0.1*y,values
def init(seed=12):
rng=np.random.default_rng(seed)
return {'q':rng.normal(0,0.15,(4,8)),'m':np.zeros((4,8)),'v':np.zeros((4,8)),'step':0,'rng':rng}
def loss_gradient(q,tokens):
B=len(tokens);mem,values=encoder(tokens)
scores=q@q.T/np.sqrt(8); scores=np.where(np.tri(4,dtype=bool),scores,-1e9);s=softmax(scores)
dec=q+0.1*s@q;query=np.broadcast_to(dec,(B,4,8))
a=softmax(query@mem.transpose(0,2,1)/np.sqrt(8));target=tokens[:,::-1]
match=tokens[:,None,:]==target[:,:,None];mass=(a*match).sum(-1).clip(1e-12);loss=-np.log(mass).mean()
da=-match.astype(float)/mass[:,:,None]/(B*4);ds=a*(da-(da*a).sum(-1,keepdims=True))
dd=(ds@mem/np.sqrt(8)).sum(0)
dq=dd+0.1*s.T@dd;dp=0.1*dd@q.T;dh=s*(dp-(dp*s).sum(-1,keepdims=True))
dq+=(dh@q+dh.T@q)/np.sqrt(8)
return float(loss),dq
def train_step(state,B=32):
q=state['q'];tokens=state['rng'].integers(0,4,(B,4));loss,dq=loss_gradient(q,tokens)
state['step']+=1;state['m']=0.9*state['m']+0.1*dq;state['v']=0.999*state['v']+0.001*dq*dq
m=state['m']/(1-0.9**state['step']);v=state['v']/(1-0.999**state['step'])
state['q']-=0.03*m/(np.sqrt(v)+1e-8)
return loss
def evaluate(state,B=512):
rng=np.random.default_rng(333);tokens=rng.integers(0,4,(B,4));mem,values=encoder(tokens);q=state['q']
s=q@q.T/np.sqrt(8);s=softmax(np.where(np.tri(4,dtype=bool),s,-1e9));dec=q+0.1*s@q
a=softmax(np.broadcast_to(dec,(B,4,8))@mem.transpose(0,2,1)/np.sqrt(8))
pred=(a@values).argmax(-1);target=tokens[:,::-1]
return float((pred==target).mean()),float((pred==target).all(-1).mean())
def grad_check():
rng=np.random.default_rng(4);q=rng.normal(size=(1,2,3));m=rng.normal(size=(1,4,3));valid=np.array([[True,True,True,False]])
up=rng.normal(size=(1,2,3));out,c=cross_forward(q,m,valid);dq,dm=cross_backward(up,c);h=1e-5;errors=[]
for arr,grad in ((q,dq),(m,dm)):
err=0
for idx in np.ndindex(arr.shape):
old=arr[idx];arr[idx]=old+h;p=(cross_forward(q,m,valid)[0]*up).sum();arr[idx]=old-h;n=(cross_forward(q,m,valid)[0]*up).sum();arr[idx]=old
err=max(err,abs((p-n)/(2*h)-grad[idx]))
errors.append(err)
print('error máximo query/memoria:',errors);assert max(errors)<1e-8
queries=rng.normal(0,0.2,(4,8));tokens=rng.integers(0,4,(3,4));loss,dq=loss_gradient(queries,tokens);worst=0.0
for idx in np.ndindex(queries.shape):
old=queries[idx];queries[idx]=old+h;pos=loss_gradient(queries,tokens)[0];queries[idx]=old-h;neg=loss_gradient(queries,tokens)[0];queries[idx]=old
worst=max(worst,abs((pos-neg)/(2*h)-dq[idx]))
print('error de gradiente del decoder:',worst);assert worst<1e-8grad_check()
state=init()for _ in range(400): loss=train_step(state)
print('paso',state['step'],'pérdida del último lote',loss,'precisión token y secuencia',evaluate(state))for _ in range(400): loss=train_step(state)
print('paso',state['step'],'pérdida del último lote',loss,'precisión token y secuencia',evaluate(state))for _ in range(400): loss=train_step(state)
print('paso',state['step'],'pérdida del último lote',loss,'precisión token y secuencia',evaluate(state))for _ in range(400): loss=train_step(state)
print('paso',state['step'],'pérdida del último lote',loss,'precisión token y secuencia',evaluate(state))Local lab: dates and comparison
Train three models from scratch on 6000 unique dates generated with a seed and reserve 500 different dates. Each model runs 1200 steps; compare symbol and sequence accuracy, and repeat evaluation with the source doubled from 10 to 20 characters. The custom model records alignments with the correct target and actual greedy generation for a held-out date. PyTorch is required; CUDA is used by default, and ORYON_DATE_DEVICE=cpu enables CPU reproduction. On CPU, ORYON_DATE_THREADS configures PyTorch threads for performance comparison. Durations measure this machine and workload, not a universal architecture comparison. The file alignment.json retains matrices and probabilities.
import json, math, os, random, time
from datetime import date, timedelta
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
device=os.environ.get('ORYON_DATE_DEVICE','cuda')
assert device in ('cpu','cuda') and (device=='cpu' or torch.cuda.is_available())
if device=='cpu' and 'ORYON_DATE_THREADS' in os.environ:
torch.set_num_threads(int(os.environ['ORYON_DATE_THREADS']))
def sync():
if device=='cuda':torch.cuda.synchronize()
chars='0123456789/-x'; PAD=len(chars); BOS=PAD+1; EOS=PAD+2; V=PAD+3
stoi={c:i for i,c in enumerate(chars)}; itos={i:c for c,i in stoi.items()}
def make_data():
rng=random.Random(21); first=date(1980,1,1); all_dates=list(range(365*30));rng.shuffle(all_dates)
def fmt(i):
x=first+timedelta(days=i);return x.strftime('%d/%m/%Y'),x.strftime('%Y-%m-%d')
return [fmt(i) for i in all_dates[:6000]],[fmt(i) for i in all_dates[6000:6500]]
train,valid=make_data(); probe=valid[0]
def batch(examples, prefix=False):
src=[[stoi[c] for c in ((a+a) if prefix else a)] for a,b in examples]
target=[[stoi[c] for c in b]+[EOS] for a,b in examples]
return torch.tensor(src,device=device),torch.tensor(target,device=device)
def positions(n,d,dev):
p=torch.arange(n,device=dev,dtype=torch.float32)[:,None];f=torch.exp(torch.arange(0,d,2,device=dev)*(-math.log(10000)/d))
a=p*f;result=torch.empty(n,d,device=dev);result[:,0::2]=a.sin();result[:,1::2]=a.cos();return result
def pad_to_limit(y,limit):
if y.shape[1]<limit:
y=torch.cat((y,torch.full((len(y),limit-y.shape[1]),EOS,device=y.device,dtype=torch.long)),1)
return y
class Attention(nn.Module):
def __init__(self,d,h):
super().__init__();self.h=h;self.d=d
self.q=nn.Linear(d,d);self.k=nn.Linear(d,d);self.v=nn.Linear(d,d);self.o=nn.Linear(d,d)
def forward(self,query,memory,causal=False,key_valid=None,query_valid=None):
b,t,d=query.shape;s=memory.shape[1]; h=self.h;dh=d//h
q=self.q(query).view(b,t,h,dh).transpose(1,2);k=self.k(memory).view(b,s,h,dh).transpose(1,2);v=self.v(memory).view(b,s,h,dh).transpose(1,2)
scores=q@k.transpose(-1,-2)/math.sqrt(dh)
if causal: scores=scores.masked_fill(torch.arange(s,device=query.device)[None,:]>torch.arange(t,device=query.device)[:,None],float('-inf'))
if key_valid is not None:
if not bool(key_valid.any(-1).all()): raise ValueError('Una secuencia no tiene claves válidas')
scores=scores.masked_fill(~key_valid[:,None,None,:],float('-inf'))
if query_valid is not None: scores=torch.where(query_valid[:,None,:,None],scores,0.0)
weights=scores.softmax(-1);result=(weights@v).transpose(1,2).contiguous().view(b,t,d)
result=self.o(result)
if query_valid is not None:
result=result*query_valid[:,:,None];weights=weights*query_valid[:,None,:,None]
return result,weights
class Own(nn.Module):
def __init__(self,d=48,h=4):
super().__init__();self.d=d;self.emb=nn.Embedding(V,d);self.enc=Attention(d,h);self.selfatt=Attention(d,h);self.cross=Attention(d,h)
nn.init.normal_(self.emb.weight,std=d**-0.5)
self.ef=nn.Sequential(nn.Linear(d,2*d),nn.ReLU(),nn.Linear(2*d,d));self.df=nn.Sequential(nn.Linear(d,2*d),nn.ReLU(),nn.Linear(2*d,d))
self.en1=nn.LayerNorm(d);self.en2=nn.LayerNorm(d);self.dn1=nn.LayerNorm(d);self.dn2=nn.LayerNorm(d);self.dn3=nn.LayerNorm(d)
def embed(self,x):return self.emb(x)*math.sqrt(self.d)+positions(x.shape[1],self.d,x.device)
def encode(self,x):
valid=x!=PAD;z=self.embed(x);z=self.en1(z+self.enc(z,z,key_valid=valid,query_valid=valid)[0]);return self.en2(z+self.ef(z))*valid[:,:,None]
def decode(self,y,mem,src_valid=None):
valid=y!=PAD;z=self.embed(y);a,selfweights=self.selfatt(z,z,True,key_valid=valid,query_valid=valid);z=self.dn1(z+a)
a,crossweights=self.cross(z,mem,key_valid=src_valid,query_valid=valid);z=self.dn2(z+a);z=self.dn3(z+self.df(z))*valid[:,:,None]
return F.linear(z,self.emb.weight),selfweights,crossweights
def forward(self,x,y):return self.decode(y,self.encode(x),x!=PAD)[0]
@torch.no_grad()
def generate(self,x,limit=11,trace=False):
memory=self.encode(x); y=torch.full((len(x),1),BOS,device=x.device,dtype=torch.long);rows=[];done=torch.zeros(len(x),device=x.device,dtype=torch.bool)
for _ in range(limit):
logits,selfw,crossw=self.decode(y,memory,x!=PAD);p=logits[:,-1].softmax(-1);tok=p.argmax(-1);tok=torch.where(done,EOS,tok)
if trace: rows.append({'p':p[0].cpu().tolist(),'self':selfw[0,:,-1].cpu().tolist(),'cross':crossw[0,:,-1].cpu().tolist()})
y=torch.cat((y,tok[:,None]),1);done|=tok==EOS
if bool(done.all()): break
return pad_to_limit(y[:,1:],limit),rows
class Standard(nn.Module):
def __init__(self,d=48,h=4):
super().__init__();self.d=d;self.emb=nn.Embedding(V,d)
nn.init.normal_(self.emb.weight,std=d**-0.5)
self.net=nn.Transformer(d,h,1,1,2*d,dropout=0,batch_first=True,norm_first=False,activation='relu')
def embed(self,x):return self.emb(x)*math.sqrt(self.d)+positions(x.shape[1],self.d,x.device)
def forward(self,x,y):
T=y.shape[1];mask=torch.triu(torch.ones(T,T,device=x.device,dtype=torch.bool),diagonal=1)
z=self.net(self.embed(x),self.embed(y),tgt_mask=mask);return F.linear(z,self.emb.weight)
@torch.no_grad()
def generate(self,x,limit=11,trace=False):
mem=self.net.encoder(self.embed(x));y=torch.full((len(x),1),BOS,device=x.device,dtype=torch.long);done=torch.zeros(len(x),device=x.device,dtype=torch.bool)
for _ in range(limit):
T=y.shape[1];mask=torch.triu(torch.ones(T,T,device=x.device,dtype=torch.bool),diagonal=1)
z=self.net.decoder(self.embed(y),mem,tgt_mask=mask);tok=F.linear(z[:,-1],self.emb.weight).argmax(-1);tok=torch.where(done,EOS,tok);y=torch.cat((y,tok[:,None]),1);done|=tok==EOS
if bool(done.all()): break
return pad_to_limit(y[:,1:],limit),[]
class Recurrent(nn.Module):
def __init__(self,d=48):
super().__init__();self.d=d;self.emb=nn.Embedding(V,d);self.encoder=nn.LSTM(d,d//2,batch_first=True,bidirectional=True)
self.decoder=nn.LSTM(d*2,d,batch_first=True);self.W=nn.Linear(d,d,bias=False);self.U=nn.Linear(d,d,bias=False);self.v=nn.Linear(d,1,bias=False);self.out=nn.Linear(d,V)
def encode(self,x):
memory,_=self.encoder(self.emb(x));return memory,self.U(memory)
def step(self,tok,state,mem,keys):
q=state[0][-1];scores=self.v(torch.tanh(self.W(q)[:,None,:]+keys)).squeeze(-1);a=scores.softmax(-1)
ctx=(a[:,:,None]*mem).sum(1);out,state=self.decoder(torch.cat((self.emb(tok),ctx),-1)[:,None,:],state)
return self.out(out[:,0]),state
def forward(self,x,y):
mem,keys=self.encode(x);B=len(x);state=(mem.new_zeros(1,B,self.d),mem.new_zeros(1,B,self.d));outputs=[]
for i in range(y.shape[1]):
out,state=self.step(y[:,i],state,mem,keys);outputs.append(out)
return torch.stack(outputs,dim=1)
@torch.no_grad()
def generate(self,x,limit=11,trace=False):
mem,keys=self.encode(x);B=len(x);state=(mem.new_zeros(1,B,self.d),mem.new_zeros(1,B,self.d));tok=torch.full((B,),BOS,device=x.device,dtype=torch.long);out=[];done=torch.zeros(B,device=x.device,dtype=torch.bool)
for _ in range(limit):
logits,state=self.step(tok,state,mem,keys);tok=logits.argmax(-1);tok=torch.where(done,EOS,tok);out.append(tok);done|=tok==EOS
if bool(done.all()): break
return pad_to_limit(torch.stack(out,dim=1),limit),[]
def shifted(y):return torch.cat((torch.full((len(y),1),BOS,device=y.device,dtype=torch.long),y[:,:-1]),1)
@torch.no_grad()
def evaluate(model,examples,prefix=False):
model.eval();n=correct=exact=0
for start in range(0,len(examples),64):
x,y=batch(examples[start:start+64],prefix);pred,_=model.generate(x)
correct+=(pred==y).sum().item();exact+=(pred==y).all(-1).sum().item();n+=len(y)
return {'token_accuracy':correct/(n*11),'sequence_accuracy':exact/n,'n':n}
def train_one(kind,steps=1200):
torch.manual_seed(31);random.seed(31);rng=random.Random(31)
model={'own':Own,'standard':Standard,'rnn':Recurrent}[kind]().to(device)
opt=torch.optim.Adam(model.parameters(),lr=.001);sample_x,sample_y=batch([probe]);align=[]
sync();start=time.perf_counter();snapshot_time=0.
order=list(range(len(train)));batches=(len(train)+31)//32
for step in range(steps+1):
if kind=='own' and (step%batches==0 or step==steps):
sync();snapshot_start=time.perf_counter();model.eval()
with torch.no_grad():
_,_,weights=model.decode(shifted(sample_y),model.encode(sample_x))
prediction,trace=model.generate(sample_x,trace=True)
align.append({'step':step,'teacher_cross':weights[0].cpu().tolist(),
'prediction':prediction[0].cpu().tolist(),'trace':trace})
sync();snapshot_time+=time.perf_counter()-snapshot_start
if step==steps:break
if step%batches==0:rng.shuffle(order)
index=(step%batches)*32;chosen=order[index:min(index+32,len(train))]
model.train();x,y=batch([train[i] for i in chosen]);logits=model(x,shifted(y))
loss=F.cross_entropy(logits.reshape(-1,V),y.reshape(-1))
opt.zero_grad(set_to_none=True);loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(),1.0);opt.step()
if (step+1)%300==0:print(kind,'paso',step+1,'pérdida',float(loss.detach()))
sync();elapsed=time.perf_counter()-start-snapshot_time
return {'kind':kind,'device':device,'threads':torch.get_num_threads() if device=='cpu' else None,'params':sum(p.numel() for p in model.parameters()),
'normal':evaluate(model,valid),'long':evaluate(model,valid,prefix=True),
'seconds':elapsed,'alignment':align}
npm run lab and open the connection link.test=Attention(8,2).to(device);q=torch.randn(2,3,8,device=device);memory=torch.randn(2,5,8,device=device)
keys=torch.tensor([[True,True,True,False,False],[True,True,True,True,False]],device=device)
queries=torch.tensor([[True,True,False],[True,True,True]],device=device)
changed=memory.clone();changed[~keys]+=100
a,_=test(q,memory,key_valid=keys,query_valid=queries);b,_=test(q,changed,key_valid=keys,query_valid=queries)
assert torch.allclose(a,b,atol=1e-6) and torch.equal(a[~queries],torch.zeros_like(a[~queries]))
net=Own().to(device).eval();sx,sy=batch([probe]);given=shifted(sy);altered=given.clone()
altered[:,-1]=(altered[:,-1]+1)%10
with torch.no_grad(): before=net(sx,given);after=net(sx,altered)
assert torch.allclose(before[:,:-1],after[:,:-1],atol=1e-6,rtol=1e-6)
print('Máscaras de relleno y causalidad comprobadas; ejemplo:',probe)
del test,net
npm run lab and open the connection link.own=train_one('own'); print({k:v for k,v in own.items() if k!='alignment'})
Path('alignment.json').write_text(json.dumps({'probe':probe,'alignment':own['alignment']}),encoding='utf-8')
print('Instantáneas guardadas:',len(own['alignment']))npm run lab and open the connection link.standard=train_one('standard'); print({k:v for k,v in standard.items() if k!='alignment'})npm run lab and open the connection link.rnn=train_one('rnn'); print({k:v for k,v in rnn.items() if k!='alignment'})npm run lab and open the connection link.A run with PyTorch 2.11, seed 31, and one CPU thread produced the following results. Sequence accuracy requires all ten characters and EOS to be correct; the doubled source contains two consecutive copies of the date, an out-of-training perturbation. The timer covers 1200 steps and excludes snapshot capture and final evaluation.
| Model | Parameters | Exact sequences, normal source | Exact sequences, doubled source | Training time |
|---|---|---|---|---|
| Custom encoder-decoder | 48 192 | 500/500 | 346/500 | 19.05 s |
nn.Transformer | 48 384 | 500/500 | 277/500 | 18.06 s |
| LSTM with attention | 48 448 | 500/500 | 171/500 | 27.07 s |
All three architectures learned this small transformation with this recipe. The drop with doubled source shows that getting ten-character dates right does not guarantee robustness to longer input. It does not prove one family is generally superior: implementation details differ, the dataset is synthetic, there is only one seed, and times depend on machine and workload. The figures use the custom model trace from this CPU run; other platforms may produce somewhat different weights and times.
Exercises
import numpy as np
def cross_attention(x_dec, mem_enc, src_valid):
passStep 1 of 3. On which target positions does the first self-attention at t depend?