Embed patches, prepend a CLS token and add position embeddings
After patchifying, a ViT projects every patch to the model width, prepends a learned CLS token whose final state is used for classification, and adds a learned position embedding so the model knows where each patch came from.
Write vit_embed(patches, W, b, cls, pos). patches is (B, N, Dp), W is (Dp, D), b is (D,), cls is (D,), pos is (N+1, D). Return (B, N+1, D):
- token 0 of every image is cls + pos[0],
- token i (i >= 1) is patches[:, i-1] @ W + b + pos[i].
def vit_embed(patches, W, b, cls, pos)Example
with N = 1, Dp = D = 1, W = [[2]], b = [1], cls = [5], pos = [[10], [20]] and patch value 3, the output is [[[15], [27]]].
Understand the idea
After patchify, every patch vector is projected to the model width D with a linear layer. A learned CLS token is placed in front of the patch tokens, and its final state is used for classification. A learned position table is then added so the model knows which slot each token sits in. CLS takes slot 0, patch 1 takes slot 1, and so on. Worked example: N = 2 patches with values [2] and [4], W = [[3]], b = [0], cls = [1], pos = [[0], [10], [20]]. Token 0 = 1 + 0 = 1. Token 1 = 2 * 3 + 0 + 10 = 16. Token 2 = 4 * 3 + 0 + 20 = 32. Output [[1], [16], [32]] for that image. Rule: token 0 = cls + pos[0], token i = patches[i - 1] @ W + b + pos[i] for i from 1 to N, giving shape (B, N + 1, D). The easy bug is adding pos before inserting CLS, which shifts every patch to the wrong slot. This is the embedding layer of ViT and of CLIP's image tower.