M6-001M6: Multimodal & Generative ModelsVision Encoders (ViT / ConvNeXt)Easy
⚡Flashcard Drill➔Mastery:
ViT Patch Embedding Formulation and Token Count Calculation
📐 Mathematical Definition
⚡ One-Sentence Core Answer
Vision Transformers partition 2D images into non-overlapping patches, map flattened patches to latent vectors via linear projection or 2D convolution, prepend a class token, and inject positional embeddings.
📌 Key Takeaways
- •Patch decomposition: maps an image into patches of spatial size
- •Linear projection: flattens patches into vectors of dimension and projects them to hidden dimension via projection matrix
- •Token sequence assembly: prepends a learnable
[CLS]token and adds 1D learnable or 2D sinusoidal positional embeddings, yielding tokens
📐 Mathematical Derivations
Mathematical Mechanism: 1. Patch Flattening & Projection: Given an input image and patch size , the spatial grid is divided into: non-overlapping patches . A learnable linear projection maps each flattened patch to the model hidden dimension : where is the learnable classification token (
[CLS]), and is the positional embedding matrix. 2. Convolutional Implementation Equivalence: In deep learning frameworks (PyTorch), patch projection is executed as a single 2D convolution: producing an output tensor , which is flattened along spatial dimensions to . 3. Standard Configurations: For standard images: \begin{array}{l|c|c|c|c} \textbf{Model} & \textbf{Patch Size } P & \textbf{Spatial Patches } N & \textbf{Tokens } (N+1) & \textbf{Dimension } D \\ \hline \text{ViT-Base/16} & 16 \times 16 & 14 \times 14 = 196 & 197 & 768 \\ \text{ViT-Base/14} & 14 \times 14 & 16 \times 16 = 256 & 257 & 768 \\ \text{ViT-Large/14} & 14 \times 14 & 16 \times 16 = 256 & 257 & 1024 \end{array} At higher resolution ( with ), token count scales to .🏭 Production Trade-offs
Deep Dive & Engineering Trade-offs: ① Patch Size vs Attention Scaling: Reducing patch size from to increases spatial token count by . Because standard self-attention complexity scales quadratically , this 31% token increase inflates attention FLOPs and KV memory by , but captures finer spatial details vital for small-object detection and text OCR. ② Convolutional Kernel Optimization: Using
nn.Conv2d with stride equal to kernel size leverages highly optimized cuDNN Winograd/implicit GEMM algorithms, avoiding explicit tensor slicing, memory copies, and reshape overhead. ③ Positional Embedding Interpolation: When changing input resolution during fine-tuning (e.g., ), pre-trained positional embeddings cannot be indexed directly; they must undergo 2D bicubic grid interpolation to preserve geometric inductive biases. ④ Global Average Pooling (GAP) vs `[CLS]`: Modern vision architectures (CLIP-ViT, DINOv2) frequently complement or replace [CLS] with Multi-Head Attention Pooling (MAP) or GAP over all patch tokens, which eliminates spatial bias towards the arbitrary class token position. ⑤ Interview Strategy: Formulate , derive the Conv2d stride/kernel equivalence, compute token counts for standard resolutions ( and ), and articulate the quadratic attention trade-off governed by patch size.⚠️ Common Interview Pitfalls
- ✕Overlooking the quadratic scaling of attention memory and compute when reducing patch size from to
- ✕Applying naive 1D linear interpolation to positional embeddings instead of 2D bicubic spatial grid interpolation during resolution upscaling
- ✕Forgetting to account for the
[CLS]token offset when slicing or reshaping spatial feature maps for downstream vision heads
🎯 Interviewer Follow-up Inquiries
- ?How does 2D bicubic interpolation mathematically remap positional embeddings when adapting a pre-trained 224x224 ViT to 448x448 inputs?
- ?Why does a 2D convolution with kernel size P and stride P compute an identical linear transformation to patch flattening plus matrix multiplication?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
Explore the comprehensive technical article, exam cards, and global architecture tree.
中文速览与面试要点
解释 ViT 的 patch embedding 与 token 数计算。
把图像切成 P×P 的 patch,线性投影为 token;token 数 = (H/P)×(W/P),故随分辨率平方增长。
核心要点
- 数学机理: patch embedding ——把 H×W×3 的图像切成 P×P 的非重叠 patch(共 N=(H/P)×(W/P) 个),每个 patch 展平为 P²·3 维向量,经 线性投影 W_p 映射到 d 维(模型的隐维度),得到 N 个 token。 token 数 ——N = (H/P)×(W/P) = HW/P², 随分辨率平方增长 :224×224、P=16 → N=196;448×448 → N=784(4 倍);1024×1024 → N=4096(约 21 倍)。这直接决定注意力的成本(O(N²))与后续 LLM 的上下文占用。 patch 大小 P 的权衡 ——(a) P 小 (如 8)——token 更多(更细的粒度、更强的细节能力),但成本 ∝1/P² 增长;(b) P 大 (如 32)——token 少(成本低),但细节丢失;(c) 常用 P=14 或 16(与预训练配置匹配)。 实现 ——patch embedding 通常用 stride=P 的卷积 实现(等价于切分 + 线性投影,但更高效);此外常加一个 可学习的 [CLS] token (用于分类)与 位置编码 (因为注意力对位置无先验)。 注意 ——ViT 的 patch 划分是 固定网格 的,故对'非方形图像'或'任意分辨率'需特殊处理(见动态分辨率题);且 patch 边界可能切断物体(对细粒度任务不利)。 与 CNN 的对比 ——CNN 用滑动窗口(重叠、局部),ViT 用非重叠 patch(全局注意力);前者保留更多空间连续性,后者 token 化更彻底(便于与文本 token 统一处理)。
- 深度剖析与工程权衡:① 'token 数 ∝ HW/P²'是所有成本分析的起点 ——它决定了注意力的 O(N²) 成本、LLM 的上下文占用、以及 KV cache 的规模;故'图像分辨率的成本是平方级的'。② 'P=14 vs 16'的实践 ——CLIP-ViT-L/14 用 P=14(224/14=16,N=256);SigLIP 常用 P=16。P 与预训练一致很重要(否则需重新适配)。③ '[CLS] token'的用途 ——在分类任务中作为全局表示;在 VLM 中通常 不用 (因为要保留所有 patch token 供 LLM 使用),但保留位置以兼容预训练。④ 'patch 切断物体'的问题 ——非重叠网格可能把物体切成两半(对细粒度识别、OCR 不利);故有'重叠 patch'、'可变 patch'、以及动态分辨率(按原生分辨率切分)的改进。⑤ '与 LLM 的 token 对齐' ——ViT 的 patch token 与文本 token 都是 d 维向量,故可拼接后送入 LLM(这是 VLM 的基础);但视觉 token 数通常远多于文本(一张 448² 图 = 784 token),故需 token 压缩 (见连接器架构与视觉 token 压缩题)。⑥ 面试要点 ——被问'ViT 的 token 数怎么算',应给出' N=HW/P² '并指出' 成本随分辨率平方增长 ';能说明'patch 非重叠会切断物体'与'视觉 token 远多于文本'是深度理解的标志。
- patch 大小 P 决定 token 数(P 越小 token 越多、越细)
- token 数 = HW/P²,随分辨率平方增长
- patch embedding 可用线性投影或卷积实现
常见陷阱
- 忽略 token 数随分辨率平方增长
- patch 大小与预训练配置不一致