liveBook · Manning

Attention matrix

As explained in Build a Text-to-Image Generator (from Scratch)

An attention map is a matrix of attention probabilities showing how strongly tokens attend to one another.

An attention matrix is a probability matrix showing how strongly each token attends to every token in a sequence. In a vision transformer, each head produces one matrix for an image. section 3.4.3

A ViT attention matrix has these implementation-level properties:

  • A batch of 32 images produces tensors shaped [32, 4, 65, 65] for each encoder layer. section 3.4.3
  • Each 65 × 65 matrix represents one image’s CLS token and 64 image-patch tokens. section 3.4.3
  • Each column sums to 1, representing a complete attention distribution. section 3.4.3

For visualization, attention maps from four layers are concatenated, CLS-to-patch values are selected, and values are averaged across heads and layers. The resulting 64 values become an 8 × 8 grid and are upscaled to 32 × 32.

How Build a Text-to-Image Generator (from Scratch) covers it

How deep it goes
Explains tensor dimensions, normalization, token selection, aggregation, reshaping, and interpolation, but not attention-score computation.
Examples
Uses CIFAR-10 images, 65-token matrices, 8 × 8 patch grids, and overlays comparing actual and predicted labels.
What it assumes
Assumes familiarity with vision transformers, image patches, encoder layers, tensor shapes, and PyTorch model inference.
What you can do after
Diagnose attention behavior with PyTorch by extracting, validating, aggregating, reshaping, and visualizing attention maps.
How it connects
Connects attention maps with vision transformers, encoder layers, attention heads, CLS tokens, image patches, and image classification.

Also explained in

Compare how 3 books explain attention matrix →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Text-to-Image Generator (from Scratch). The section links point to the parts of the book it draws on.