#462ViT Patch EmbeddingMediumTransformersComputer VisionEmbeddingsAsked atGoogle · Meta · OpenAI
ViT Patch Embedding
Background
Vision Transformer (ViT) treats an image as a sequence of fixed-size patches. Each patch is flattened, linearly projected to the embedding dimension, and fed into a standard transformer encoder. The patching + projection step is the only thing different from a text transformer's tokeniser.
Problem statement
Implement patch_embed(image, patch_size, projection):
- Verify and are divisible by
patch_size. - Reshape → → flatten each patch to .
- Project:
flat @ projection→ .
Input
image—np.ndarrayshape .patch_size—int >= 1, must divide both and .projection—np.ndarrayshape , the linear projection matrix.
Output
Returns np.ndarray shape where .
Examples
Example 1 — 8x8 image, 2x2 patches, 3 channels, embed 16
Input: image=(8, 8, 3); patch_size=2; projection=(12, 16)
Output: (16, 16)
Example 2 — single-patch image of ones, all-ones projection
Input: image=ones((4,4,1)); patch_size=4; projection=ones((16, 8))
Output: shape (1, 8), all values = 16 (sum of 16 ones)
Example 3 — non-divisible patch size
Input: image=(5, 5, 3); patch_size=4
Output: ValueError
Constraints
- and must be divisible by
patch_size. - Patches are emitted in row-major order: top-left to bottom-right.
- Returns
np.ndarrayshape .
Notes
- CLS token + positional embeddings. Production ViTs prepend a learned
[CLS]row and add learned positional embeddings before the transformer. Out of scope for this patching kernel. - Why patches not pixels. Pixel-level attention is — astronomical at 224x224. Patching cuts the sequence by
patch_size^2.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example: uniform 8x8x3 image, all-ones projection
- •Sample: single 4x4x1 patch with all-ones projection
- •Example: row-major order, left patch precedes right patch