We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← CNNs from Scratch step 11 of 15
Patch Embedding with CLS Token
Turn a batch of images into an ordered sequence of vectors: one class token followed by one embedding for each square image patch. This is an input stage for a vision transformer, before any attention layers run.
Inputs and output
Implement patch_embed_with_cls(x, w_proj, cls_token, pos_embed).
All inputs are floating-point tensors with the same dtype and device.
x:(N, C, H, W), using channels-first image layout.w_proj:(C * P * P, d_model), the projection shared by all patches.cls_token:(d_model,), the shared class-token vector.pos_embed:(num_patches + 1, d_model), one position vector per sequence slot.- Return
(N, num_patches + 1, d_model), preserving the input dtype.
P is a positive square patch size, not a separate argument. Infer it from
P * P = w_proj.shape[0] // C. Inputs are consistent: P divides both H
and W, and num_patches = (H // P) * (W // P). Images need not be square.
Build the sequence
- Split each image into non-overlapping
PbyPpatches. Visit patches left to right across each patch row, then top to bottom. - Flatten each patch in channel-first order: all pixels of channel 0, then
channel 1, and so on. Within a channel, visit rows top to bottom and pixels
left to right. Each flattened patch has
C * P * Pvalues. - Multiply each flattened patch by
w_proj. There is no projection bias. - Prepend
cls_tokento each image's sequence. Do not project the class token. - Add
pos_embedto every sequence, including slot 0 for the class token.
Use reshaping, axis reordering and matrix multiplication, not a convolution layer. Leave all inputs unchanged. Do not add padding, normalization, an activation or attention.
For example, a one-channel image with rows [1, 2, 3, 4] and [5, 6, 7, 8]
has two size-2 patches. Their flattened vectors, in order, are
[1, 2, 5, 6] and [3, 4, 7, 8]. After projection, these occupy slots 1
and 2. Slot 0 is cls_token + pos_embed[0].
What does the class token contain?
At this stage, the class-token output is identical across the batch and does not depend on the image. Later attention layers can mix patch information into that position for a classification head to use. Those layers are outside this exercise. Position embeddings give each sequence slot its own supplied vector; they are shared across images rather than generated separately for each image.
The diagram below illustrates non-overlapping windows along one image axis with size and stride both 4. It does not show channel flattening, projection or the class token. Keep padding at 0 and dilation at 1 for this exercise.
Loading visualization…
Understand the ideas behind this exercise. The Problem tab contains the exact implementation requirements.
Turn image patches into tokens
A Vision Transformer divides an image into patches, flattens each patch, and
projects it into a feature vector called a token. For image height H, width
W, and non-overlapping square patches of side P, the number of patches is
(H/P) * (W/P) when both dimensions are divisible by P.
For an 8-by-8 image with 4-by-4 patches, there are four patch tokens. With
three color channels, each patch contains 4 * 4 * 3 = 48 values before
projection. Preserve the required pixel, channel, and patch order: obtaining the
right final shape does not prove that each token contains the right pixels.
Position embeddings identify where the patches came from. Some models also prepend a learned class token, making the example above a five-token sequence. Attention allows this token to gather information from the patch tokens. A classifier can then use its final representation; other architectures pool the patch tokens instead.
Transformer blocks combine attention with feed-forward layers. Follow the task's normalization placement and classification head, since these choices change the model.
Mix images and labels with the same coefficient
Mixup forms a training image as
$$\tilde x=\lambda x_a+(1-\lambda)x_b.$$
It combines the two label distributions with the same weights. At lambda = 0.25,
the image and target each contain one quarter of example a and three quarters
of example b. For this one model prediction, ordinary cross-entropy with the
mixed target equals the weighted sum of the losses against the two original
targets.
During manual backpropagation, shared class-token and position-embedding parameters receive contributions from every example. Add those contributions, including any scaling already required by the batch loss. Remember the extra class-token position when checking sequence lengths.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
PyTorch reference solution
Sign in to track your attempts toward unlocking the reference solution.