DaZu / PyTorchDaZu home

5 · Course 3 / Quick guide

Advanced architectures and attention

Choose how information flows: reusable image features, interpretable CNN outputs, generated images and contextual token representations.

Builds on Fundamentals, Training, Vision and Text. Follow architectures → saved state → compression → validated inference.

How it works

RepresentA shared encoder maps images to reusable embeddings.
ConnectResidual addition preserves paths; DenseNet concatenates features.
Inspect or generateExplain a chosen score, or learn to reverse a noise process.
ContextualizeAttention mixes permitted token information for understanding or generation.

A classifier predicts a fixed label set; a Siamese model learns similarity between inputs. Both can use the same CNN backbone with different objectives. Residual and dense connections help deep networks propagate information; compact depthwise architectures reduce computation by design.

Hooks expose intermediate feature maps. Saliency uses a chosen score's input gradient; CAM combines class-specific feature maps. These show model behavior, not a proof of causality. Diffusion learns denoising, often in a smaller latent space; generated images still need independent review.

Transformers use queries and keys to choose how value vectors are mixed. Encoders read bidirectionally, decoder-only models read a causal prefix, and translation decoders also attend to encoder output.

Code and functions

MechanismRemember
TripletMarginLossBring an anchor closer to a positive than a negative; retrieval quality needs its own evaluation.
x + F(x) / catResNet adds compatible shapes; DenseNet concatenation increases channels.
register_forward_hookCapture a layer output, detach stored features, and remove the hook after use.
autograd.gradSaliency needs gradients even when the model uses eval().
MultiheadAttentionFor batch_first=True, inputs are [batch, length, embedding]; embedding size must divide into heads.
Shifted targets + causal maskAt position t, predict t+1 using the current and earlier tokens.

Boolean mask conventions differ: MultiheadAttention uses True to block; functional scaled dot-product attention uses True to permit.

Check your understanding

What can query 1 read?

Bidirectional
Rows = queries · columns = keys
✓✓✓✓✓✓✓✓✓

Keys 0, 1 and 2.

Causal
Rows = queries · columns = keys
✓××✓✓×✓✓✓

Keys 0 and 1; future key 2 blocked.

✓ = permitted, × = blocked; no PAD. Mask → softmax weights → mix values.

A four-token causal row at position 1 can use keys 0 and 1. It must not read 2 or 3. During translation, cross-attention may read the source sentence while target self-attention stays causal.

Common mistakes