7 routes42 sections324 units

Unit 4.7 · about 5 h

199 / 324

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.

  • implement
  • measure

You can now

  • 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 recognition
  • Variable-length batches, padding and loss masks
  • Packed sequences at recognition depth
  • Spatial, hidden-state and future-token leak tests

Study, in this order

3 steps

  1. Masked loss, greedy prediction and BLEU
    D2L - 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

    Depth · Use D2L bleu() as a relative probe only. It weights n-grams by \((1/2)^n\), unlike the uniform \(1/k\) of Papineni et al.

  2. Greedy, exhaustive and beam search
    D2L - 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 \(\alpha\) 0.75

  3. Packed sequences at recognition depth
    PyTorch sequence packing utilities

    pack_padded_sequence: the lengths argument, enforce_sorted and batch-first

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

Focus on

  • Greedy decoding feeds each argmax back with <bos> start and <eos> stop. Beam search keeps \(k\) hypotheses with length normalization, so larger \(k\) 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.

Reproduce closed-book

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 \(t\) (outputs up to \(t\) must not move), and carried versus reset hidden state.

Traps

  • 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.

Practice

CS231n Assignment 2 Q5: image captioning with vanilla RNNs

Q5: Image Captioning with Vanilla RNNs. Implement vanilla RNNs and apply them to image captioning on COCO in RNN_Captioning_pytorch.ipynb.

D2L beam-search Exercise 2: beam size versus quality and speed

Exercises: question 2 (beam size effects on translation quality and prediction speed in the seq2seq MT problem)

Self-test

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

  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?

  3. The D2L beam score divides the log-probability by \(L^{\alpha}\), with \(\alpha\) 0.75. What does raising \(\alpha\) do?

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

Completion criterion

Stop 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.

Mark passed, then open 5.1 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • D2L - convolutional and recurrent architecture route
    D2L authorsprimarycourse
    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 utilities
    PyTorchreferencereference
    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 networks
    Simon J. D. Princerequiredtheory
    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 2
    Stanford Universitysupportpractice
    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 problems
    Deep-MLoptionalpractice
    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 cells
    TrenTorchsupportpractice
    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 reference
    PyTorchreferencereference
    Read Signature and Shape for the exact floor formula with dilation, the groups divisibility rule with grouped and depthwise examples, and the weight layout \((C_{\text{out}}, C_{\text{in}}/\text{groups}, kH, kW)\). D2L and UDL teach the mechanism; this page is the shape contract to code against.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels