Exposure bias: training the way you generate
Study the mismatch between reference and generated prefixes, measure conditional behavior in a known HMM, and evaluate scheduled sampling and sequence-level alternatives.
After this lesson you can
- Formalize exposure bias as a difference between training and generation prefix distributions.
- Measure error accumulation and self-recovery in a model with known truth.
- Implement scheduled sampling schedules and evaluate their effects.
- Explain the statistical consistency critique of scheduled sampling.
- Describe professor forcing and sequence-level training and assess their tradeoffs.
Before you start
- 17Teacher forcingAncestral sampling from an autoregressive modelSequence-to-sequence learningGreedy decodingBLEU and chrFSoft versus hard attention
- 07Forward versus reverse KL
- 14Hidden Markov modelForward algorithm (filtering)
- 05Confidence interval and coveragePaired design and paired test
- 00Multi-seed evaluation
Two prefix distributions
A translator beginning “the museum is…” may later produce repetition or a wrong word. During teacher forcing the decoder receives the previous reference token. During generation it receives its own choice. Exposure bias names this context mismatch: real-prefix distribution need not match . Evaluation visits contexts training may rarely have seen. An unexpected continuation does not establish this mismatch as the sole cause: data, capacity, and decoding rule also matter.
A worst case illustrates the risk. If while the prefix is correct a first error occurs with probability per step and every later step fails, probability that step is wrong is . Summing over steps gives . For small the first-order expansion is : quadratic order is an illustrative bound under extreme assumptions, not a law of all generation. With always-correct prefixes the expected count is . Open tasks can have multiple valid continuations, so comparing every token with a single reference is insufficient to declare error.
A world with computable truth
To measure the mismatch use an HMM with three states and three symbols. Transition has high persistence and emission favors a different symbol per state. The forward algorithm provides even for generated prefixes. Compare with a GRU’s distribution using in nats. Both models are conditioned on the same prefix, avoiding confusion between prefix quality and continuation quality. Every HMM probability is positive, so every alphabet prefix has positive probability.
If is the state distribution before observing symbol , the exact prediction is , with emission matrix . Then multiply each component of by its probability of emitting , normalize, and apply the transition matrix to obtain . KL is zero only if both distributions agree on the three symbols; it is asymmetric and truth is the first argument here. To verify the filter, enumerate hidden paths for short prefixes and compare normalized probabilities.
Mean KL at each position also depends on prefix selection. References come from the HMM; free prefixes come from the GRU, which may visit other contexts. Comparing those means is not a token-by-token comparison of the same sentence. The free intervention instead uses the same seeds to compare trajectories with and without substitution, although later divergence can change symbols selected in both. Neither the average nor one trajectory establishes uncertainty in another domain.
The intervention replaces a generated symbol with the next in the circular alphabet. It does not claim one true answer in a random process: it is controlled perturbation. Generation continues from the modified prefix and is compared with an unperturbed trajectory using the same seed. KL can fall after the change: that is compatible with conditional recovery in this world, not proof of universal recovery. Changing the final position can affect only later predictions, which are not drawn here.
The cell implements GRU steps and backward in NumPy without an autodifferentiation framework. Each batch performs BPTT over twelve symbols and an Adam update. The scheduled variant independently chooses the real or sampled symbol; the discrete index carries no gradient. Figures record a local run of 1 200 updates per condition, batch 32, and 128 evaluation trajectories. This is a small HMM and one seed. The default cell run is a short ten-step test: change the argument of fit to repeat a longer trial.
import os, json, numpy as np
transition=np.array([[.88,.08,.04],[.06,.88,.06],[.05,.1,.85]])
emission=np.array([[.82,.12,.06],[.10,.8,.10],[.08,.12,.8]])
prior=np.array([1/3]*3)
def data(rng,n,T=12):
z=rng.choice(3,size=n,p=prior); out=np.empty((n,T),int)
for t in range(T):
u=rng.random(n);out[:,t]=(u[:,None]>np.cumsum(emission[z],axis=1)).sum(1)
u=rng.random(n);z=(u[:,None]>np.cumsum(transition[z],axis=1)).sum(1)
return out
def sigmoid(x):return 1/(1+np.exp(-np.clip(x,-40,40)))
def softmax(x):
q=np.exp(x-x.max(axis=-1,keepdims=True));return q/q.sum(axis=-1,keepdims=True)
class Model:
def __init__(self,seed=20,H=12):
r=np.random.default_rng(seed);self.H=H
self.p={'wx':r.normal(0,.12,(4,3*H)), 'wh':r.normal(0,.12,(H,3*H)), 'bi':np.zeros(3*H), 'bh':np.zeros(3*H), 'w':r.normal(0,.12,(H,3)), 'b':np.zeros(3)}
self.m={k:np.zeros_like(v) for k,v in self.p.items()};self.v={k:np.zeros_like(v) for k,v in self.p.items()};self.step=0
def call(self,tok,h):
p=self.p;x=np.eye(4)[tok];xr,xz,xn=np.split(x@p['wx']+p['bi'],3,axis=-1);hr,hz,hn=np.split(h@p['wh']+p['bh'],3,axis=-1)
ar=xr+hr;az=xz+hz;r=sigmoid(ar);z=sigmoid(az);n=np.tanh(xn+r*hn);h1=(1-z)*n+z*h
return h1,(x,h,r,z,n,hn,abs(ar)<40,abs(az)<40),softmax(h1@p['w']+p['b'])
def train(self,truth,rng,eps):
p=self.p;B,T=truth.shape;h=np.zeros((B,self.H));token=np.full(B,3);caches=[];probs=[];loss=0.
for t in range(T):
h,c,prob=self.call(token,h);caches.append((c,h));probs.append(prob)
loss-=np.log(prob[np.arange(B),truth[:,t]]+1e-15).mean()/T
sampled=(rng.random(B)[:,None]>np.cumsum(prob,axis=1)).sum(1)
token=np.where(rng.random(B)<eps,truth[:,t],sampled)
g={k:np.zeros_like(v) for k,v in p.items()};dh=np.zeros_like(h)
for t in range(T-1,-1,-1):
c,h1=caches[t];x,h,r,z,n,hn,active_r,active_z=c;d=probs[t].copy();d[np.arange(B),truth[:,t]]-=1;d/=B*T
g['w']+=h1.T@d;g['b']+=d.sum(0);dh+=d@p['w'].T
dan=dh*(1-z)*(1-n*n);dar=dan*hn*r*(1-r)*active_r;daz=dh*(h-n)*z*(1-z)*active_z
di=np.concatenate((dar,daz,dan),axis=1);dr=np.concatenate((dar,daz,dan*r),axis=1)
g['wx']+=x.T@di;g['wh']+=h.T@dr;g['bi']+=di.sum(0);g['bh']+=dr.sum(0);dh=dh*z+dr@p['wh'].T
self.step+=1
for k in p:
self.m[k]=.9*self.m[k]+.1*g[k];self.v[k]=.999*self.v[k]+.001*g[k]**2
p[k]-=.01*(self.m[k]/(1-.9**self.step))/(np.sqrt(self.v[k]/(1-.999**self.step))+1e-8)
return loss
def fit(steps=10):
models=[]
for mode in (0,1):
m=Model();r=np.random.default_rng(2020)
for i in range(steps):
batch=data(r,32);eps=1. if not mode else max(.5,1-.5*(i+1)/max(1,steps))
loss=m.train(batch,r,eps)
models.append(m)
print('modelo',mode,'pasos',steps,'pérdida del último lote',round(loss,5),flush=True)
return models
def assess(models,n=128,T=12):
curves=[];ordinary=[];real=[];all_states=[]
for model in models:
modecurves=[]
for inject in range(-2,T):
r=np.random.default_rng(3000);truth=data(r,n,T);h=np.zeros((n,model.H));token=np.full(n,3);belief=np.tile(prior,(n,1));kl=[]
for t in range(T):
q=belief@emission;h,_,p=model.call(token,h);kl.append(float(np.mean(np.sum(q*np.log(q/p),axis=1))))
token=truth[:,t] if inject==-2 else (r.random(n)[:,None]>np.cumsum(p,axis=1)).sum(1)
if t==inject:token=(token+1)%3
belief=belief*emission[:,token].T;belief/=belief.sum(1,keepdims=True);belief=belief@transition
if inject==-2:real.append(kl)
elif inject==-1:ordinary.append(kl)
else:modecurves.append(kl)
curves.append(modecurves)
r=np.random.default_rng(4400);truth=data(r,80,T);group=[]
for free in (False,True):
h=np.zeros((len(truth),model.H));token=np.full(len(truth),3);states=[]
for t in range(T):
h,_,p=model.call(token,h);states.append(h.copy())
token=(r.random(len(truth))[:,None]>np.cumsum(p,axis=1)).sum(1) if free else truth[:,t]
group.append(np.stack(states,axis=1))
all_states.append(group)
# Same PCA basis for all regimes and conditions, fitted on their pooled hidden states.
flat=np.concatenate([x.reshape(-1,models[0].H) for pair in all_states for x in pair]);center=flat.mean(0);_,_,v=np.linalg.svd(flat-center,full_matrices=False);basis=v[:2].T
clouds=[[(x-center)@basis for x in pair] for pair in all_states]
return {'curves':curves,'ordinary':ordinary,'real':real,'clouds':[[a.tolist() for a in pair] for pair in clouds], 'n':n,'T':T}
models=fit(10)
res=assess(models,n=10)
print('KL final tras perturbar paso 4:', [round(res['curves'][i][3][-1],5) for i in range(2)])In that run, intervening after the fourth symbol, final mean KL was 0.00067 nats for teacher forcing and 0.01820 for scheduled sampling. Differences describe these runs and schedule, not a general method ranking. Curves have sampling uncertainty; both conditions share initialization, generator, and budget, but optimization trajectories diverge.
Schedule the input
In scheduled sampling one starts with high probability of using the reference and decreases it by iteration . Bengio and colleagues proposed this curriculum to bring some training contexts closer to generation. A schedule may be linear, exponential, or inverse sigmoid. The figure’s scale is adjustable; the last uses . Selection is per element and step; the first symbol remains BOS. One can sample logits or choose their maximum, but both discrete decisions prevent ordinary differentiation through the index.
The intuition does not guarantee a statistically consistent estimator. In Huszár’s two-step counterexample, if the first model input is generated independently of the real pair, the second target comes from a different sequence. When the first symbol is always replaced, this loss’s optimum learns the second symbol’s marginal, not the true conditional preserving its dependence on the first. Mixing references and samples may improve a particular metric, but it is no longer simply maximum likelihood of observed sequences.
For example, if data pairs are always AA or BB equally often, the true conditional copies the first symbol. Combining an independently generated first symbol with the second from a real pair means observing A as input gives no information about that second symbol: A and B remain equally likely, 1/2 each. A sufficiently flexible model can minimize this loss without learning the data-generating dependence. This objective-level observation does not rule out empirical benefits on a particular task or budget; it calls for measurement against a comparable baseline.
What happens inside the state?
In professor forcing, a discriminator tries to distinguish hidden trajectories with references from free trajectories; the generator is also trained to make this harder. The adversarial objective adds complexity and does not by itself prove two full distributions match. Lamb and colleagues studied it across domains. Here we only visualize states from the two GRUs above; we did not train a discriminator.
PCA can hide differences in discarded dimensions or show separation without functional loss. The cloud is a descriptive diagnostic. To examine recovery, add metrics on conditionals and generated sequences; do not conclude from projected centroid distance alone.
Compare in translation
The next cell reuses the previous lesson’s attention architecture and the real ManyThings/Tatoeba file. Install PyTorch and sacrebleu==2.5.1, download spa-eng.zip, and configure SEQ_DATA. With SEQ2SEQ_FULL=1 the source-based split uses 30 000/2 000/2 000 sources; otherwise a subset checks the flow. Each seed pairs initialization, examples, and budget: pure teacher forcing versus a linear schedule decreasing to 0.5. The default SCHEDULE_STEPS is five steps per condition, a technical test rather than a quality conclusion.
Evaluation uses identical greedy decoding, corpus BLEU by source length, and fraction of hypotheses containing a repeated bigram. BLEU depends on corpus and tokenization; repetition does not identify its cause either. Three seeds show variation but are not by themselves robust evidence of significance. Pairing permits seedwise differences and repetition with more seeds and intervals; do not select only the best.
One RTX 3060 run used 1 000 updates per condition, file SHA-256 07bb8aaaf1458abbcdc8a3a51ce5b9f8a2643c829dcb7c2a63b3fec8dde934dc, and 2 000 held-out sources. In the table TF means teacher forcing and SS the schedule; repetition is the fraction with at least one repeated bigram. BLEU uses sacreBLEU 2.5.1 with tok:none.
| Seed | Total BLEU TF | Total BLEU SS | Repetition TF | Repetition SS | BLEU TF / SS, 6–9 tokens |
|---|---|---|---|---|---|
| 20 | 0.463 | 0.489 | 18.1 % | 27.5 % | 0.538 / 0.571 |
| 21 | 1.271 | 0.603 | 8.1 % | 26.8 % | 1.122 / 0.722 |
| 22 | 0.476 | 0.658 | 4.2 % | 27.0 % | 0.557 / 0.767 |
The 6–9-token bucket contains 1 092 sentences. Scores are low and budget short: this is not a competitive translator. Total BLEU SS minus TF differences are about +0.026, -0.668, and +0.182; the exact two-sided sign-flip test across three seeds gives under its assumptions. Repetition was higher with SS in all three runs, but this identifies neither cause nor behavior under other schedules, models, or budgets.
A two-sided sign-flip test on three paired differences has only eight possible assignments; without ties its smallest attainable p-value is 0.25. Thus three seeds cannot reject at 5% with that test even when all differences point the same way. The test assumes sign exchangeability under the null; thousands of test sentences do not turn three models into thousands of independent training trials. A paired sentence bootstrap addresses another uncertainty source and does not replace variation between training runs.
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.set_num_threads(1)
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
import json
class ScheduledTranslator(AttentiveTranslator):
def mixed(self,x,lengths,target,eps,generator):
ann,valid,pre=self.encode(x,lengths);B=len(x)
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)
pred=self.head(out[:,0]);logits.append(pred)
# Both random choices are discrete; no gradient passes through sampled IDs.
if eps>=1:
token=target[:,i]
else:
sampled=torch.multinomial(pred.detach().softmax(-1),1,generator=generator).squeeze(1)
use_real=torch.rand(B,device=device,generator=generator)<eps
token=torch.where(use_real,target[:,i],sampled)
return torch.stack(logits,1)
def train_scheduled(seed,steps,scheduled):
torch.manual_seed(seed);rng=random.Random(seed);generator=torch.Generator(device=device).manual_seed(seed+999)
model=ScheduledTranslator(128).to(device);optimizer=torch.optim.Adam(model.parameters(),lr=.001)
for i in range(steps):
examples=rng.sample(train,32);x,lengths,y=batch(examples,False);model.train()
eps=max(.5,1-.5*(i+1)/max(1,steps)) if scheduled else 1.
logits=model.mixed(x,lengths,y,eps,generator)
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 (i+1)%500==0:print('semilla',seed,'scheduled',scheduled,'paso',i+1,'loss',round(loss.item(),4),flush=True)
return model
def evaluate(model,examples):
model.eval();pred=[];ref=[];length=[]
for start in range(0,len(examples),32):
group=examples[start:start+32];x,l,_=batch(group,False)
pred += [[tv[k] for k in row] for row in model.generate(x,l)]
ref += [list(t) for _,t in group];length += [len(s) for s,t in group]
def repeated(xs):
pairs=list(zip(xs,xs[1:]));return len(pairs)!=len(set(pairs))
def scores(idx):
if not idx:return {'n':0}
metric=BLEU(tokenize='none',force=True);b=metric.corpus_score([' '.join(pred[i]) for i in idx],[[' '.join(ref[i]) for i in idx]])
return {'n':len(idx),'bleu':b.score,'repetition':sum(repeated(pred[i]) for i in idx)/len(idx),'signature':str(metric.get_signature())}
return {'total':scores(list(range(len(ref)))),'2-5':scores([i for i,n in enumerate(length) if 2<=n<=5]),'6-9':scores([i for i,n in enumerate(length) if 6<=n<=9]),'10-13':scores([i for i,n in enumerate(length) if 10<=n<=13]),'14-18':scores([i for i,n in enumerate(length) if 14<=n<=18])}
steps=int(os.environ.get('SCHEDULE_STEPS','5'));runs=[]
for seed in (20,21,22):
item={'seed':seed}
for scheduled in (False,True):
model=train_scheduled(seed,steps,scheduled)
item['scheduled' if scheduled else 'teacher']=evaluate(model,test)
runs.append(item)
print(json.dumps(item,ensure_ascii=False),flush=True)
from itertools import product
deltas=[r['scheduled']['total']['bleu']-r['teacher']['total']['bleu'] for r in runs]
observed=abs(sum(deltas));permuted=[abs(sum(d*s for d,s in zip(deltas,signs))) for signs in product((-1,1),repeat=len(deltas))]
p=sum(x>=observed-1e-12 for x in permuted)/len(permuted)
print('Diferencias pareadas de BLEU:',deltas,'p bilateral por cambios de signo:',p)
if os.environ.get('SCHEDULE_OUT'):
with open(os.environ['SCHEDULE_OUT'],'w',encoding='utf-8') as f:json.dump(runs,f,ensure_ascii=False,indent=2)
npm run lab and open the connection link.Optimize complete sequences
Sequence-level training can optimize a reward such as BLEU using REINFORCE: , with baseline independent of the evaluated action. Sequence reward reduces mismatch with the final metric, but the estimator can have high variance and the metric may miss quality aspects. MIXER starts with cross-entropy and progressively hands final steps to REINFORCE to avoid starting with almost useless rewards. Minimum risk training approximates expected risk over candidates; beam search optimization incorporates search into global score learning. Wiseman and Rush studied the latter for sequence-to-sequence tasks. Cost and metric dependence need justification against a strong baseline.
He and colleagues found in their open-generation experiments that prefix-attributed distortion was limited and did not seem to accumulate; they observed signs of self-recovery. Schmidt frames the issue as generalization to contexts. These results are configuration-specific, not proof mismatch is irrelevant to all models. In long LLM text, observed and generated prefixes again differ; comparing prefixes, decoders, and seeds helps separate that from search-induced repetition or insufficient capacity.
Exercises
Step 1 of 3. What is the probability that no error has occurred through step t?
The next exercise mixes given predictions to practice indexing and sampling. Actual training must obtain predictions step by step from the state produced by mixed inputs, as the lab does; preparing the whole prediction sequence with teacher forcing is not equivalent.
import numpy as np
def scheduled_sampling_inputs(targets, model_preds, eps, rng):
pass