AI & Machine Learning Master Course — 118. Vision transformers and patch representations
Smartyfy AI & Machine Learning Master Course
Course ID: smartyfy-ai-ml-master-200
Lesson 118: Vision transformers and patch representations
Prerequisites: Lesson 117. Learning outcome: Trace patch embeddings, attention, and computational trade-offs.
Turn an image into a sequence without losing the contract
A vision transformer can represent an image as a sequence of patch tokens. Divide an image into fixed-size patches, flatten each patch, and project its values into an embedding dimension. The resulting token is a learned representation of a region, not a word and not necessarily an object. A patch may contain background, part of an object, or several small objects.
For an image of height H and width W, square patch size P, and C channels, the simple non-overlapping construction gives N=(H/P)(W/P) patches when both dimensions are divisible by P. Each flattened patch has P²C entries. A shared linear projection maps those entries to D features. Its weight matrix has shape (P²C,D), with an optional D-element bias.
Define how non-divisible dimensions are handled before training: cropping, padding, or resizing changes the input. Maintain channel order and patch order consistently. Array reshaping alone can silently interleave pixels from different patches; use a known small grid to verify the spatial layout.
Positions and attention solve different problems
Patch contents do not by themselves identify where those patches were located. Positional information gives the network access to spatial arrangement. A basic implementation adds a position embedding to each token. Other designs use different positional mechanisms, but the conceptual need remains: image layout carries information beyond the collection of local appearances.
Self-attention forms queries Q, keys K, and values V from tokens. Scores are QK-transpose divided by the square root of the key dimension. Applying a row-wise softmax produces nonnegative weights that sum to one for each query. The output is a weighted sum of value vectors. Different learned projections let matching behavior differ from the information being retrieved.
The lab simplifies this to Q=K=V=tokens so that the array operations stay visible. That is a mechanics demonstration, not a trained vision transformer. Real transformer blocks also include learned projections, feedforward transformations, normalization, and residual connections that add a block’s input back to its output. Multiple attention heads can learn distinct projections; they are not guaranteed to correspond to clean human concepts.
Classification and computational trade-offs
A classification model needs a fixed-size representation after processing the patch sequence. One approach introduces a learned class token whose final representation feeds a classifier. Another pools patch representations. Neither choice makes every patch individually supervised as an object detector. Image-level labels still supervise an image-level objective unless additional targets are supplied.
For dense attention, the score matrix contains N² entries per head, before accounting for batches and other tensors. At resolution 224 by 224, patches of size 16 give 196 tokens; patches of size 8 give 784. Four times as many tokens means sixteen times as many pairwise score entries. This does not prove total runtime rises exactly sixteen-fold: projections, feedforward layers, kernels, memory layout, and implementation all contribute.
Smaller patches retain finer spatial detail but increase sequence cost. Larger patches reduce token count while potentially discarding useful local structure during compression. Training data, pretraining, architectural inductive biases, and compute budgets also matter. A toy forward pass cannot establish that transformers outperform convolutional networks for a particular application.
CPU lab: inspect four patches and one attention operation
The image contains integers zero through fifteen arranged in a 4 by 4 grid. Patch size two gives four tokens. The first patch must flatten to [0,1,4,5], not [0,1,2,3]. We reshape into patch-row, within-patch-row, patch-column, and within-patch-column axes, then transpose to group each patch’s pixels.
A fixed projection compresses four pixel values to two features, and explicit position offsets distinguish locations. Stabilized softmax subtracts the maximum score from each row before exponentiation. This leaves the mathematical distribution unchanged while reducing overflow risk. The output has four rows and two columns, matching one retrieved representation per query.
The script checks patch membership, row-sum normalization, finite outputs, and the sixteen-fold score-entry ratio. No parameters are trained, no pretrained weights are downloaded, and PyTorch is not required. Treat the output as verification of shapes and operations rather than recognition accuracy.
import numpy as np
image = np.arange(16, dtype=float).reshape(4, 4)
patches = image.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3).reshape(4, 4)
# Fixed projection for a mechanics demo, not trained weights.
W = np.array([[1., 0.], [0., 1.], [1., 0.], [0., 1.]]) / 20
position = np.array([[0., 0.], [0., .1], [.1, 0.], [.1, .1]])
tokens = patches @ W + position
scores = tokens @ tokens.T / np.sqrt(2)
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
out = weights @ tokens
print('Patches:', patches.astype(int).tolist())
print('Token shape:', tokens.shape)
print('Attention row sums:', weights.sum(axis=1).round(6).tolist())
print('Output shape:', out.shape)
assert np.array_equal(patches[0], [0, 1, 4, 5])
assert np.allclose(weights.sum(axis=1), 1)
assert np.isfinite(out).all()
print('224-square patches 16 / 8:', (224 // 16) ** 2, (224 // 8) ** 2)
print('Score-entry ratio:', ((224 // 8) ** 2 / (224 // 16) ** 2) ** 2)
What a useful experiment would control
To compare patch choices, fix the source-level train, development, and test partitions first. Document resolution, normalization, augmentation, pretraining data, optimization steps, and trainable parameter counts. If one model saw substantially more pretraining data, the comparison addresses the whole system rather than architecture alone.
Inspect image resizing carefully. Increasing resolution changes token count, and learned positional embeddings may require a documented adaptation strategy. Never assume a model accepts arbitrary resolutions simply because matrix multiplication is flexible. Also distinguish attention visualizations from faithful causal explanations: a large attention weight describes one operation inside a network, not proof that an image region caused the final decision.
A practical report should include an appropriate CNN or simpler baseline, resource measurements under comparable conditions, and errors on meaningful image subgroups. Select model settings using development data and reserve final data for evaluation after choices are frozen.
Four practice questions with worked answers
Practice 1
How many 16 by 16 patches fit a 224 by 224 image without padding?
Answer: There are 224/16 = 14 patches along each axis, so N = 14×14 = 196. Channel count changes each patch vector’s length, not the number of spatial patches.
Practice 2
An RGB patch is 8 by 8 and is projected to 32 features with a bias. How many projection parameters are used?
Answer: The flattened patch has 8×8×3 = 192 entries. Shared weights contain 192×32 = 6144 parameters, and the bias adds 32, for 6176. The same projection is reused for every patch.
Practice 3
Why subtract the maximum before a row-wise softmax?
Answer: Subtracting the same constant from every score leaves their normalized exponential ratios unchanged. It reduces the largest exponent to zero, avoiding unnecessarily large exponentials while preserving the attention weights.
Practice 4
Token count increases from 100 to 400. What happens to dense attention score entries?
Answer: They increase from 10000 to 160000, a factor of sixteen. This is a count of score entries, not a complete runtime or memory benchmark for every part of the model.
Five multiple-choice questions
Question 1
What does a patch token necessarily represent?
- A. Exactly one complete object instance.
- B. A projected region of input pixels.
- C. A class label assigned independently to that patch.
Correct: B. Patches follow a spatial partition and may cut across objects. Object identity and patch-level supervision are additional modeling choices.
Question 2
What is the first 2 by 2 patch in the lab’s flattened representation?
- A. [0,1,2,3]
- B. [0,4,8,12]
- C. [0,1,4,5]
Correct: C. The patch contains the first two columns of the first two rows. A full image row or column is a different grouping.
Question 3
Which quantity is normalized by a row-wise attention softmax?
- A. Each feature coordinate across the output embedding.
- B. The key weights for each individual query.
- C. All score entries across every query into one shared sum.
Correct: B. Each query receives its own distribution over available keys. Normalizing across all queries or feature dimensions changes the operation.
Question 4
Why add positional information?
- A. Patch content alone does not specify the original spatial arrangement.
- B. Position embeddings guarantee translation invariance.
- C. Position embeddings replace the need for value vectors.
Correct: A. Location information distinguishes arrangements. It does not automatically impose invariance or eliminate the content retrieval pathway.
Question 5
Which conclusion is supported by this executed lab?
- A. The position offsets make the four-to-two patch projection invertible.
- B. Every attention row selects exactly one patch with weight one.
- C. The patch layout and attention normalization match the stated construction.
Correct: C. The assertions verify mechanics only. Soft attention can mix several patches, and adding position offsets does not recover information discarded by the projection.
Common pitfalls
Watch for incorrect patch ordering, omitted positional information, normalization over the wrong axis, and claims that score-matrix scaling equals total runtime scaling. Do not present fixed illustrative projections as trained representations or attention maps as complete explanations.
Summary
A patch-based vision model turns spatial regions into tokens, supplies positional information, and exchanges information through attention. Shape checks and cost estimates make that pipeline understandable. Recognition performance still requires a controlled training and evaluation experiment.