Exercises — Handling variable-length sequences
This page is a graded workout for the parent note. Every problem is stated cleanly, then hidden behind a collapsible solution so you can test yourself first. Levels climb from L1 Recognition (do you know the vocabulary?) up to L5 Mastery (can you invent and prove?). After each level a [!mistake] callout steel-mans the trap that snares most people there.
Before you start, let us agree on the picture we keep coming back to: a batch is a rectangular grid. Rows are separate sequences (a sentence, an audio clip). Columns are time steps. Throughout this page we index time steps starting at in the mathematics (so ), matching the parent note's masked-loss formula. The one exception is PyTorch's batch_sizes list, which — like every Python list — is indexed from ; we will flag that switch explicitly the moment it appears (Exercise 2.3). Because the grid must be rectangular but real sequences have different lengths, we glue on filler cells called padding. A mask is a second grid of the same shape, holding where a cell is real and where it is filler.
Figure s01 — read this before Exercise 1.1. The left panel is the padded token grid for lengths : orange cells are real tokens, grey cells are PAD. The right panel is the matching mask grid: violet (real), background (pad). Notice the row sums on the right (sum=4,7,2) recover the true lengths — that is the whole point of a mask.

Level 1 — Recognition
Exercise 1.1 (L1)
A batch has three sequences of token lengths , , . What is , and after padding, what is the shape of the token grid (rows columns)?
Recall Solution 1.1
What we do: is just the biggest of the true lengths. The grid has one row per sequence () and columns. Shape: . Row 1 has real cells and pad cells; row 3 has real cells and pad cells — exactly the left panel of figure s01.
Exercise 1.2 (L1)
For the same batch, write the full mask matrix (a grid of s and s).
Recall Solution 1.2
Row has ones followed by pad zeros (this is the right panel of figure s01):
row 1 (L=4): 1 1 1 1 0 0 0
row 2 (L=7): 1 1 1 1 1 1 1
row 3 (L=2): 1 1 0 0 0 0 0
Check: the ones in each row count its true length: . ✓
Exercise 1.3 (L1)
True or false: attention (the weighted sum , where is the value at position and the attention weight, both defined in the vocabulary box above) needs padding inside the summation math itself. Explain in one sentence.
Recall Solution 1.3
False. The sum runs to , the actual length, so the math handles any length directly. Padding only appears because we store sequences in a rectangular tensor; we use a mask to stop attention from looking at those pad cells, but the formula never requires padding.
Level 2 — Application
Exercise 2.1 (L2)
Sequence has real tokens in a batch padded to . The per-position losses are (the last two positions are padding, with garbage loss values). Compute the masked, length-normalised loss .
Recall Solution 2.1
Recall the formula (time steps run ): What each piece does: the mask zeroes out the padding losses in the numerator, and the denominator divides by the real length. The garbage pad values vanish because their mask is .
Exercise 2.2 (L2)
Same batch as 2.1 has a second sequence with (fully real), per-position losses . With , compute the batch loss .
Recall Solution 2.2
Sequence 1: (from 2.1). Sequence 2: mask is all ones, .
Exercise 2.3 (L2)
Given lengths (already sorted descending), fill in the batch_sizes list that PyTorch's packing produces. Explain what batch_sizes[t] counts.
Recall Solution 2.3
Indexing note: everywhere else on this page time runs , but batch_sizes is an ordinary Python list, so it is read from index . Below, "" means the list index, i.e. the -th time step. The story is identical; only the starting number differs.
batch_sizes[t] = how many sequences are still alive (have a real token) at that step. This is exactly the "alive count" glyph shown above each column in figure s02.
- (1st step): all alive →
- (2nd step): all still have tokens →
- (3rd step): the length- one ended, remain →
- (4th step): the length- one ended, remains →
- (5th step): still remains (the length- one) → Check: the sum equals the number of real tokens: . ✓
Figure s02 — the packing picture for Exercise 2.3. Each coloured row is one sequence (lengths ); each cell is a real token. The number stamped above column is batch_sizes[t]: it drops as shorter sequences run out, and the numbers sum to , the total real-token count. This is why packing skips all the pad cells.

Level 3 — Analysis
Exercise 3.1 (L3)
A query scores three keys, giving raw dot products where the third position is padding. We mask padding by setting before softmax. Compute the attention weights . (Take so scaling by changes nothing.)
Recall Solution 3.1
Why ? After softmax, , so the padding key gets exactly zero weight and never leaks into the output. Denominator . Check: . The distribution is valid and padding is fully ignored. ✓
Exercise 3.2 (L3)
Why do we scale scores by before softmax and not after? Show what happens to the variance of for when , and argue why large scores hurt.
Recall Solution 3.2
Variance: each term has variance (product of two independent unit-variance zero-mean values), and there are independent terms, so Standard deviation . So raw scores routinely swing by or more. Why that hurts: softmax of scores like gives — it saturates, meaning the gradient through softmax is nearly zero and learning stalls. Scaling gives , keeping scores in a range where softmax stays responsive. Why before, not after: softmax is nonlinear; dividing its output by would break the "sums to 1" property and would not undo the saturation, which already happened inside the . You must tame the input to the exponential.
Exercise 3.3 (L3)
Two batching plans for the same 3 sequences (lengths ): (A) pad all to ; (B) pack them. Count how many RNN cell evaluations each performs, and give the "wasted work" fraction of plan A.
Recall Solution 3.3
Plan A (padding): the RNN steps over every cell of a grid evaluations. Plan B (packing): it only touches real cells evaluations. Wasted work in A: pad evaluations, a fraction Packing eliminates that of pointless computation.
Level 4 — Synthesis
Exercise 4.1 (L4)
Design a mask-aware mean pooling layer: given hidden states for and mask , produce a single vector summarising sequence that ignores padding. Write the formula, then evaluate it for a 1-D case with and mask .
Recall Solution 4.1
Design reasoning: a naive mean would average in the garbage pad values. Multiply by the mask to zero pads, then divide by the real count : Evaluate: numerator ; denominator . The pads never entered the answer.
Exercise 4.2 (L4)
Combine masked loss with dynamic length. A batch has lengths , padded to . Per-position cross-entropy losses are row 1: (last two are pad garbage), row 2: . Compute , , and .
Recall Solution 4.2
Masks: , .
Exercise 4.3 (L4)
You must bucket 6 sequences of lengths into two mini-batches of 3 each to minimise total padding. Give the buckets and compute total pad cells, comparing against the worst split.
Recall Solution 4.3
Idea: pad cells in a batch . To shrink padding, group similar lengths so is close to each member. Good split: and .
- Batch 1: , pad .
- Batch 2: , pad .
- Total pad . Worst split (mix short with long): and .
- Batch 1: ; Batch 2: ; total . Length-bucketing cuts padding from down to — an -cell (about ) reduction.
Level 5 — Mastery
Exercise 5.1 (L5)
Prove that with padding + masking, the value of the per-sequence loss is independent of the chosen (as long as ). This is the property that makes padding safe.
Recall Solution 5.1
Claim: for any , depends only on the real losses . Proof. Split the sum at : By the mask definition for every , so the second sum is identically regardless of how many pad columns exist or what garbage they hold. Likewise the denominator is also independent of . Therefore which contains no reference to . What it means: you can re-batch the same sequence with any longer padding and its loss (and gradient) will not change — the mask makes padding a no-op.
Exercise 5.2 (L5)
Degenerate cases. For each, decide what the correct behaviour is and why: (a) a sequence of length ; (b) an entire attention row where every key is padding; (c) a batch where all sequences already share the same length.
Recall Solution 5.2
(a) : the denominator , so is undefined. Correct handling: exclude empty sequences from the batch entirely (or guard the division). An empty sequence carries no supervision signal, so it must not contribute to the average — and dividing by zero would produce NaN gradients that poison the whole update.
(b) all-padding attention row: every score becomes , so softmax computes → NaN. Correct handling: never let a query attend over a fully-empty key set; if it can happen, force the output to (or a learned default). This is the attention twin of case (a).
(c) all sequences share the same length: then for every , so every mask entry is (there are no pad columns at all). Masking therefore multiplies each loss by and the normaliser is the same for all rows. The masked-loss formula collapses to the ordinary unmasked mean , and packing's batch_sizes becomes of length (no sequence ever "dies early"). Conclusion: in the equal-length case all our machinery gracefully reduces to plain fixed-length training — masking never hurts, it simply becomes a no-op. This is the reassurance that the variable-length tools are a strict generalisation.
Exercise 5.3 (L5)
Efficiency law. For a batch of sequences with lengths , prove that packing performs exactly RNN-cell evaluations while padding performs , and that the ratio (packing / padding) equals where is the mean length. Then compute this ratio for lengths .
Recall Solution 5.3
Padding count: the grid is rows by columns and the RNN visits every cell → .
Packing count: batch_sizes[t] counts sequences alive at step , and (each real token counted once). So packing does evaluations.
Ratio:
Numbers: , , so ratio . Packing does about of the work — the more your lengths vary, the smaller and the bigger the win.
Recall Quick self-check ledger (numeric answers)
L1: shape ; masks as shown ::: see solutions 2.1 ::: 2.2 ::: 2.3 batch_sizes 3.1 ::: 3.2 Var ::: 3.3 waste 4.1 pool ::: 4.2 ::: 4.3 pad vs 5.3 ratio
Related: Masking in Deep Learning · Batch Processing · Attention Mechanism · Recurrent Neural Networks · LSTM and GRU · Transformers · Sequence-to-Sequence Models