Inferensys

Glossary

Patch Embedding

The process of dividing an input image into a grid of fixed-size 2D patches and linearly projecting each flattened patch into a vector to create the input token sequence for a Vision Transformer.
Engineer reviewing vector database search results on laptop, embeddings visualization on screen, home office coding session.
VISION TRANSFORMER INPUT TOKENIZATION

What is Patch Embedding?

Patch embedding is the foundational preprocessing step in Vision Transformer (ViT) architectures that converts a raw 2D image into a sequence of vector representations suitable for a Transformer encoder.

Patch embedding is the process of dividing an input image into a grid of fixed-size, non-overlapping 2D patches, flattening each patch into a one-dimensional vector, and linearly projecting these vectors into a lower-dimensional embedding space. This operation transforms an image of dimensions H × W × C into a sequence of N tokens, each of dimension D, where N = (H/P) × (W/P) for a patch size of P × P. The resulting sequence of patch embeddings, prepended with a learnable [CLS] token and summed with positional encodings, serves as the direct input to the standard Transformer encoder, entirely replacing the hierarchical feature maps produced by convolutional neural networks.

The linear projection is implemented as a single 2D convolution with a kernel size and stride equal to the patch size, making it computationally efficient. Unlike convolutional architectures that build local receptive fields gradually, patch embedding imposes a coarse, grid-based tokenization from the outset, forcing the subsequent self-attention mechanism to learn all spatial relationships globally. The patch size is a critical hyperparameter: smaller patches yield a longer token sequence with finer spatial resolution at the cost of quadratic complexity in self-attention, while larger patches reduce computational load but may sacrifice fine-grained detail necessary for dense prediction tasks like medical image segmentation.

INPUT TOKENIZATION

Key Features of Patch Embedding

Patch embedding is the fundamental tokenization step that converts a raw 2D image into a sequence of vectors suitable for a Transformer encoder. It replaces the convolutional stem of traditional CNNs with a learned linear projection of flattened pixel grids.

01

Image Patching and Flattening

The input image x ∈ R^(H×W×C) is divided into a grid of N = (H/P) × (W/P) non-overlapping 2D patches, each of size P×P×C. Each patch is then flattened into a 1D vector of length P²·C. For a standard ViT-B/16 on a 224×224 image, this produces 196 patches, each of dimension 768 (16×16×3). The patch size P is a critical hyperparameter that controls the sequence length and granularity of the visual tokens.

02

Linear Projection to Embedding Dimension

Each flattened patch vector is multiplied by a learnable embedding matrix E ∈ R^((P²·C)×D) to project it into a D-dimensional latent space. This operation is mathematically equivalent to a 2D convolution with kernel size P and stride P, using D output filters. The resulting sequence of N patch embeddings forms the input tokens to the Transformer, alongside a prepended learnable [class] token for classification tasks.

03

Positional Encoding Injection

Since self-attention is permutation-invariant, spatial information must be explicitly added. Standard learnable 1D positional embeddings of shape (N+1)×D are summed with the patch tokens. Without this step, the model cannot distinguish between a patch in the top-left corner and one in the bottom-right. Alternatives include 2D-aware positional encodings, relative position biases, and Rotary Position Embeddings (RoPE) for improved spatial reasoning.

04

Convolutional Patch Embedding Variants

While the original ViT uses a single large-kernel projection, modern architectures employ overlapping convolutional patch embeddings for smoother feature extraction:

  • ConvStem: A stack of small 3×3 convolutions replaces the single large stride, improving optimization stability.
  • Overlapping patches: Using stride smaller than kernel size creates redundant tokens that capture finer local structure.
  • Multi-scale embeddings: Hierarchical models like Swin Transformer extract patch tokens at multiple resolutions using patch merging layers.
05

Computational Complexity and Trade-offs

The patch size P directly governs the sequence length N and thus the O(N²) cost of self-attention:

  • Smaller P (e.g., 8): More tokens (e.g., 784 for 224×224), finer granularity, higher compute cost.
  • Larger P (e.g., 32): Fewer tokens (e.g., 49), coarser granularity, faster inference. This trade-off is critical in medical imaging, where high-resolution scans (e.g., 1024×1024 pathology tiles) require careful patch sizing or hierarchical architectures to remain computationally tractable.
06

Relationship to Token Merging

Patch embedding creates the initial token set, but many tokens—especially in background regions—are redundant. Token Merging (ToMe) is a training-free technique that operates downstream of patch embedding to progressively combine similar tokens, reducing sequence length by 40-60% with negligible accuracy loss. This is particularly valuable in medical image analysis, where large uniform tissue regions generate many near-identical patch embeddings that can be safely merged.

PATCH EMBEDDING

Frequently Asked Questions

Clear, technically precise answers to the most common questions about the patch embedding mechanism—the critical first step that converts raw medical images into token sequences for Vision Transformer analysis.

Patch embedding is the process of dividing an input image into a grid of fixed-size, non-overlapping 2D patches and linearly projecting each flattened patch into a high-dimensional vector space to create the input token sequence for a Vision Transformer (ViT). The mechanism operates by first reshaping an image of dimensions H × W × C into a sequence of N flattened 2D patches, where N = (H × W) / P² and P is the patch size. Each flattened patch—now a 1D vector of length P² × C—is multiplied by a learned weight matrix E to produce a D-dimensional embedding. A learnable [CLS] token is prepended, and positional encodings are added to inject spatial location information. This transforms the raw pixel grid into a sequence of semantically meaningful vectors that the self-attention mechanism can process, entirely replacing the convolutional inductive bias with a global relational model.

INPUT TOKENIZATION STRATEGY

Patch Embedding vs. Convolutional Stem

A comparison of the two primary methods for converting raw images into token sequences for Transformer-based vision models.

FeaturePatch EmbeddingConvolutional StemHybrid CNN-Transformer

Core Mechanism

Divides image into non-overlapping grid; linear projection of each patch

Applies a sequence of strided convolutions to downsample feature maps

Uses a standard CNN backbone for initial feature extraction, then projects final feature map into tokens

Inductive Bias

Minimal; relies entirely on data-driven self-attention

Strong locality and translation equivariance priors

Moderate; inherits CNN biases in early layers, global attention in later layers

Overlapping Receptive Fields

Typical Patch/Stride Size

16x16 or 14x14 pixels

4x4 initial stride, followed by 3x3 convolutions

Variable; depends on CNN backbone output stride

Computational Complexity

O(N^2) for self-attention on N patches; N is small for 224x224 images

O(K^2 * C_in * C_out * H * W); linear with respect to spatial dimensions

Hybrid; CNN cost is linear, Transformer cost is quadratic on reduced token count

Trainable Parameters in Stem

Very low; a single linear projection matrix

Moderate; multiple convolutional filter banks

High; entire pre-trained CNN backbone parameters

Performance on Small Datasets

Lower without pre-training; lacks useful priors

Higher; convolutional inductive bias aids generalization from limited data

Highest; leverages pre-trained CNN features, often fine-tuned end-to-end

Original Architecture

Vision Transformer (ViT)

ResNet, ConvNeXt stems

DeiT, CvT, Swin Transformer with patch merging

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.