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

Architecture trade-offs and attention correctness tests

Attention fails quietly: transposed axes still run, padding still mixes, fused kernels still return. Only deliberate tests separate a correct block from a plausible one.

You'll be able to

  • Compare convolution, recurrence and attention by invariance, path length, parallelism, state and scaling, and pick the simplest adequate mechanism.
  • Run an intervention battery (future-token, padding, permutation) that proves mask and position semantics.
  • Diagnose axis, contiguity and dtype hazards in a multi-head implementation.
  • State which behaviors need measurement (backend, dtype, length regime) versus derivation.

Covers

Convolution, recurrence and attention trade-offsHead, sequence and batch axis hazardsCausal, padding and low-precision correctness testsNoncontiguous and variable-length input behavior
1

Read

In this order, only the parts listed

0 of 3 done

  1. Architecture comparison and hazard sitesD2L - attention and transformer implementation route

    Comparing CNNs, RNNs, and Self-Attention with its figure, plus the transpose_qkv and transpose_output pair and the valid_lens repeat in the multi-head implementation for the axis checklist

  2. Transformer summary and long-sequence galleryUnderstanding Deep Learning - Transformers

    Section 12.11 (p. 232) for parallel computation with quadratic scaling; Section 12.9 gallery (pp. 227 to 228) for sparsification patterns at recognition depth; Section 12.10 (pp. 228 to 231) for convolutional inductive bias versus data scale

    Stop at recognition of the gallery patterns; sparse and image architectures are not built here.

  3. Backend selection and determinism limitsPyTorch - scaled dot product attention

    Backend selection functions, the outputs-may-differ paragraph, and the cuDNN nondeterminism Note with its deterministic flag

2

Focus on

  • Choose by mechanism, not fashion: CNNs share local filters with translation structure, RNNs carry fixed state through sequential steps, attention pays for content-based paths. The D2L table makes the trade exact.
  • The axis checklist is short: which axis the softmax sums to 1, whether head splitting precedes the transpose, whether valid_lens repeats per head, and whether transposed tensors are contiguous before any view.
  • Interventions beat inspections: perturb future tokens, change padded content, permute the batch (and the sequence, for an unmasked block without positions), and require matching outputs. UDL Section 12.7.2 explains how a decoder that sees the future can cheat; only the intervention proves yours cannot.
  • Some claims need a run: fused-backend numerics, half-precision intermediates, and the length where materialization binds. Derive the model, then measure the regime.
Common mistakes · 3
  • Asserting bitwise equality across backends. The docs say outputs may differ by backend and that cuDNN may pick a nondeterministic algorithm; tolerance plus a pinned backend is the valid test.
  • Using view on a freshly transposed tensor. Head-fold transposes are noncontiguous; view fails where reshape, or contiguous plus view, succeeds.
  • Reading causality off one layer weights. Dropout, residuals and later layers remix paths; the intervention on the composed block is the proof.
3

Try it yourself

Closed-book, before checking anything

On your own block, run the three-test battery: changing future tokens leaves earlier outputs unchanged; changing padded content leaves valid outputs unchanged; permuting the batch permutes the outputs the same way. Also show that permuting the sequence permutes outputs for an unmasked block without positions, and fails once the causal mask is on. Then differential-test forward and backward against the SDPA math backend within tolerance, excluding fully masked rows.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Fill the D2L trade-off row for CNNs, RNNs and self-attention: compute order, sequential ops, max path.Answer

    CNN: , , . RNN: , , . Self-attention: , , .

  2. 2.Which D2L line protects multi-head masking, and what is the failure without it?Answer

    torch.repeat_interleave(valid_lens, num_heads, dim=0). Without it D2L masked_softmax fails with a mask shape error. Tiling with repeat instead runs but gives heads another example's length, because the fold is batch-major.

  3. 3.Why must the SDPA differential test exclude fully masked rows?Answer

    Conventions disagree there: D2L -1e6 gives uniform weights, all -inf through plain softmax gives NaN, and SDPA on CPU returned zeros in PyTorch 2.14. Assert your convention in a separate test.

  4. 4.transpose_qkv ends with reshape after permute. Why not view?Answer

    Permuted tensors are noncontiguous, and view requires contiguity. reshape copies when needed; view would raise. Call contiguous first if a later view matters.

You're done when

The battery passes on shapes you did not tune for, including all-padded rows under your stated convention, and you can attribute any mismatch to mask, axis, dtype or backend.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 2 more in the section
  • Understanding Deep Learning - TransformersSimon J. D. Prince · primary

    Use Chapter 12.1-12.11 and the matching notebooks for dot-product self-attention, extension to transformers, transformer layers and vision transformers.

  • D2L - attention and transformer implementation routeD2L authors · required

    Use queries-keys-values, attention-scoring-functions, multihead-attention, self-attention-and-positional-encoding, transformer and vision-transformer. Implement masked single-head attention, multi-head attention and one pre-normalized block before comparing with PyTorch.

  • PyTorch - scaled dot product attentionPyTorch · reference

    Use the official function documentation as a differential oracle for shapes, masks, dropout and backend behavior after the manual version passes intervention tests.

Also in this section

  • Deep-ML candidate - attention problemsDeep-ML · optional

    Use 490 Scaled Dot-Product Attention as the fifth platform admission sample. If the judge catches a seeded masking error, use at most one of 490, 491, 53, 904 or 905 as a changed-prompt drill.

  • TrenTorch - attention and block questionsTrenTorch · support

    Solve the multi-head split, sinusoidal positional encoding, causal mask and pre-norm versus post-norm questions the units name, then carry the same checks into your own block.