Unroll a seq2seq decoder with scheduled teacher forcing
Why it matters Training any autoregressive decoder, from old NMT systems to LLMs, relies on this shifted teacher-forcing setup.
Seq2seq decoders are trained by feeding the correct previous token (teacher forcing), sometimes mixed with the model's own guess (scheduled sampling). The off-by-one is easy to get wrong.
Write decode(h0, targets, E, W, U, b, V, c, tf_mask, bos). h0 is (h,), targets is a list of T token ids, E is the (vocab, e) embedding table, W (e, h), U (h, h), b (h,), V (h, vocab), c (vocab,). At step t the input token is bos when t = 0; otherwise targets[t - 1] if tf_mask[t] is True, else the model's own prediction from step t - 1. Then h = tanh(E[token] @ W + h @ U + b), logits = h @ V + c, pred = argmax(logits). Return (preds, loss): preds is the list of T predicted ids and loss is the mean over steps of cross-entropy -log softmax(logits)[targets[t]].
def decode(h0, targets, E, W, U, b, V, c, tf_mask, bos)Example
with h = e = 1, vocab 2, E = [[1], [-1]], W = [[1]], U = [[0]], b = [0], V = [[1, -1]], c = [0, 0], h0 = [0], bos = 0, targets = [1, 0] and tf_mask = [True, True], preds are [0, 1] and loss is about 1.7204.
Understand the idea
A decoder writes one token at a time, each time using the token before it. During training we can give it the correct previous token (teacher forcing), which is fast and stable, or let it use its own guess, which is what happens at test time. Mixing the two, scheduled sampling, reduces the gap. Like a learner driver: sometimes the instructor's hands guide the wheel, sometimes the learner drives alone.
Tiny example: step 0 reads BOS (token 0, embedding 1): h = tanh(1) = 0.76, logits [0.76, -0.76], prediction 0, gold 1, so the loss is log(1 + e^1.52) = 1.72. Step 1 reads the gold previous token 1 (embedding -1): logits [-0.76, 0.76], prediction 1, gold 0, loss 1.72 again, so the mean is 1.72.
Rule: input_t = BOS if t = 0, else targets[t - 1] (teacher) or pred_{t-1} (own guess); loss_t = -log p(targets[t]).
LLM pre-training uses full teacher forcing: the input is the target sequence shifted right by one.
Shapes and data flow
h (h,), E[token] (e,), logits (vocab,); T steps