Unit 7 of 7 · about 5 hours · implement, measure

Decoding, variable-length batches and leak tests

Decoding and masking turn a trained seq2seq net into honest predictions. One unmasked pad token or one peeking future input invalidates every number above it.

You'll be able to

  • Implement greedy decoding and describe how beam search trades compute for sequence score.
  • Implement masked variable-length loss so padding contributes nothing to loss or metrics.
  • Prove with leak tests that padding, hidden-state carry and future tokens cannot change valid outputs.

Covers

Autoregressive greedy decoding and beam-search recognitionVariable-length batches, padding and loss masksPacked sequences at recognition depthSpatial, hidden-state and future-token leak tests
1

Read

In this order, only the parts listed

0 of 3 done

  1. Masked loss, greedy prediction and BLEUD2L - convolutional and recurrent architecture route

    Sections 10.7.5, 10.7.7 and 10.7.8: Loss Function with Masking ((l times mask).sum() over mask.sum()), greedy predict_step, and the BLEU measure

    Use D2L bleu() as a relative probe only. It weights n-grams by , unlike the uniform of Papineni et al.

  2. Greedy, exhaustive and beam searchD2L - convolutional and recurrent architecture route

    Sections 10.8.1 to 10.8.4: Greedy Search with the 0.048 and 0.054 examples, Exhaustive Search cost, Beam Search, and the length penalty with 0.75

  3. Packed sequences at recognition depthPyTorch sequence packing utilities

    pack_padded_sequence: the lengths argument, enforce_sorted and batch-first

    Recognition only. Know what packing skips and what contract it demands; do not reimplement the packed format.

2

Focus on

  • Greedy decoding feeds each argmax back with <bos> start and <eos> stop. Beam search keeps hypotheses with length normalization, so larger costs linearly more for usually better sequences.
  • Masked loss divides by valid tokens, not by batch times steps. Dividing by the padded size silently down-weights short-sequence batches.
  • Packing skips pad steps in the RNN so pads cost nothing and contribute no state. It needs lengths and, by default, length-sorted batches.
  • A leak test perturbs what should not matter, such as pad values, future tokens or carried state, and asserts that valid outputs do not change: bit-identical for a causal RNN on CPU, and within a tight tolerance wherever a kernel may reorder sums.
Common mistakes · 3
  • Averaging masked loss over all positions including pads. Short sequences then count less per token, so always divide by the mask sum.
  • Sorting by length for packing and forgetting to unsort for metrics. Either restore the original order yourself or pass enforce_sorted=False and let PyTorch track the permutation.
  • Stopping generation at fixed num_steps instead of <eos>. Tail pads then enter BLEU and length statistics as fake content.
3

Try it yourself

Closed-book, before checking anything

Closed-book, implement masked cross-entropy with mask equal to targets-not-pad and sum-over-sum reduction, plus a greedy loop. Then pass three leak probes: random pad ids, changed tokens after position (outputs up to must not move), and carried versus reset hidden state.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Batch of lengths 5 and 2 padded to 5. What is the masked-loss denominator?Answer

    7: valid tokens. Summing over 10 positions would dilute the short sequence.

  2. 2.In D2L's greedy-search example, greedy scores 0.048 while picking a different second token gives 0.054. Why does greedy miss it, and what does beam search change?Answer

    Greedy takes the most likely token at each step and never revisits. The other second token is less likely by itself but makes the later tokens more likely. Beam search keeps partial sequences, so it can keep that branch alive long enough to see the payoff, though it is not guaranteed to find the best sequence.

  3. 3.The D2L beam score divides the log-probability by , with 0.75. What does raising do?Answer

    It favors longer outputs. Log-probabilities are negative and grow in magnitude with length, so a larger divisor for long sequences offsets more of that penalty. 0 recovers the raw log-probability, which favors short outputs.

  4. 4.Leak probe: all <pad> ids replaced with random ids, and valid outputs change. Is that a bug?Answer

    Yes. Valid outputs must not depend on pad contents, so the change shows padding leaking into the representation or the loss.

5

Practice

You're done when

Your masked loss matches a manual per-sequence mean, beam search beats greedy on a held-out sentence, and all three leak probes pass.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 5 more in the section
  • D2L - convolutional and recurrent architecture routeD2L authors · primary

    Use why convolution, convolution layer, padding and strides, pooling, channels, batch normalization and ResNet, then RNN, BPTT, scratch RNN, GRU, LSTM, encoder-decoder and seq2seq. Work through the scratch mechanisms before concise APIs.

  • PyTorch sequence packing utilitiesPyTorch · reference

    Read pack_padded_sequence for lengths, enforce_sorted and batch-first at recognition depth: what packing skips and what contract it demands. Do not reimplement the packed format; pair it with the masked-loss implementation in D2L seq2seq.

Also in this section

  • Understanding Deep Learning - convolution and residual networksSimon J. D. Prince · required

    Use Chapters 10 and 11 to sharpen convolutional invariance, receptive-field reasoning, residual paths and normalization. D2L remains the recurrent implementation route.

  • Stanford CS231n - Assignments 1 and 2Stanford University · support

    Use only the neural network, normalization, dropout, convolution and PyTorch components that match this section. Do not complete the course or unrelated vision tasks.

  • Deep-ML candidate - convolution and recurrence problemsDeep-ML · optional

    After the platform admission check, use at most one of 41 Conv2D, 62 RNN with BPTT, 287 GRU or 59 LSTM as a changed-prompt drill.

  • TrenTorch - convolution cost and recurrent cellsTrenTorch · support

    Solve FLOPs Estimation, GRU Forward and LSTM Forward after the D2L scratch models. Each reference cell matches torch.nn.GRUCell or LSTMCell.

  • PyTorch nn.Conv2d referencePyTorch · reference

    Read Signature and Shape for the exact floor formula with dilation, the groups divisibility rule with grouped and depthwise examples, and the weight layout . D2L and UDL teach the mechanism; this page is the shape contract to code against.