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.
Glossary
Patch Embedding

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Patch Embedding vs. Convolutional Stem
A comparison of the two primary methods for converting raw images into token sequences for Transformer-based vision models.
| Feature | Patch Embedding | Convolutional Stem | Hybrid 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 |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Core concepts that interact with patch embedding to form the input pipeline and architectural backbone of Vision Transformers.
Self-Attention Mechanism
The core operation that processes the sequence of patch embeddings by computing a weighted sum of all token representations. For each patch, query (Q), key (K), and value (V) vectors are derived via learned linear projections. The attention weight between any two patches is the scaled dot-product of their Q and K vectors, enabling every patch to globally attend to every other patch.
- Computational complexity: O(N²) where N is the number of patches, making it expensive for high-resolution images
- Multi-head attention: Runs multiple attention operations in parallel, allowing the model to focus on different relationship types simultaneously
- Global receptive field: Unlike CNNs, every patch can directly interact with every other patch from the first layer
Hybrid CNN-Transformer
An architecture variant where the input to the Transformer is not raw image patches but feature maps extracted by a convolutional neural network. Instead of flattening pixel patches, a CNN backbone processes the image first, and the resulting feature map is treated as a grid of patch embeddings. This blends the local inductive bias of convolutions with the global modeling capacity of self-attention.
- Early convolution stages: Capture low-level features like edges and textures efficiently
- Reduced sequence length: CNN downsampling produces fewer tokens than raw patching, lowering attention cost
- Example: The original ViT paper explored a hybrid model using ResNet feature maps, showing competitive performance on smaller datasets

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us