Embeddings and patch embeddings
Turning words into vectors by looking up a row, and images into tokens by cutting them into patches.
- Explain nn.Embedding as a learnable lookup table
- Follow a 224×224 image to a sequence of 196 tokens, shape by shape
- Show that a strided convolution and a per-patch linear layer are the same operation
Networks compute with real numbers, but much of the world comes in discrete pieces: words, characters, product IDs. An embedding gives each item its own learnable vector.
n, d = 10, 3
embedding_layer = nn.Embedding(num_embeddings=n, embedding_dim=d)
input = torch.tensor([[1, 2, 4, 5, 6],
[4, 3, 2, 9, 5]])
output = embedding_layer(input) # shape (2, 5, 3)
embedding_layer.weight is a 10×3 table, and the layer simply returns row i for index i. Every input index gains a trailing dimension of size 3, so (2, 5) becomes (2, 5, 3). It is equivalent to multiplying a one-hot vector by the table — but a lookup is far cheaper than a matrix product with a vector that is almost all zeros. As the readme notes, only rows that are looked up receive gradient, so rare items learn slowly.
Images as sequences
A Vision Transformer treats an image as a sentence whose words are patches. The image is cut into \(P \times P\) tiles; each tile is flattened and projected by one shared linear layer to a \(D\)-dimensional token.
patch_embedding_using_conv.ipynb does all of it in three lines, with the standard ViT-Base sizes:
patch_embed = nn.Conv2d(3, 768, kernel_size=16, stride=16)
x = patch_embed(x) # (1, 3, 224, 224) -> (1, 768, 14, 14)
x = x.flatten(2) # (1, 768, 14, 14) -> (1, 768, 196)
x = x.transpose(1, 2) # (1, 768, 196) -> (1, 196, 768)
224 / 16 = 14 patches per side, so 196 tokens, each of dimension 768. The final transpose puts the sequence dimension second, where attention layers expect it.
Two notebooks, one operation
patch_embedding_using_linear_proj.ipynb does the same for a single patch by hand: flatten a 16×16×3 patch into 768 numbers and apply nn.Linear(768, 768).
These are the same computation. When the kernel size equals the stride, the kernel never overlaps itself: each output position sees exactly one patch, and computes a dot product between that patch’s 768 numbers and each of the 768 kernels — which is precisely a linear layer applied to the flattened patch, with the conv’s weight (768, 3, 16, 16) reshaped to (768, 768). Checked numerically with random weights on a 32×32 image: the two agree to machine precision.
One practical difference: flattening order. The convolution’s weight is laid out channel-first (3, 16, 16), while the notebook’s patch is (16, 16, 3), so copying weights between the two forms needs a permute first.
Try it yourself. Build conv = nn.Conv2d(3, 8, 4, 4) and lin = nn.Linear(48, 8), then set lin.weight.data = conv.weight.data.reshape(8, 48) and lin.bias.data = conv.bias.data. Cut a random (1, 3, 8, 8) image into four patches with unfold or by slicing, and check that lin on each flattened patch matches the corresponding column of conv(x).flatten(2).