M6-001M6: Multimodal & Generative ModelsVision Encoders (ViT / ConvNeXt)Easy
⚡Flashcard Drill➔Mastery:

ViT Patch Embedding Formulation and Token Count Calculation

📐 Mathematical Definition
N=HP×WP;xi=Wp⋅flatten(patchi)+bN=\frac{H}{P}\times\frac{W}{P};\qquad x_i=W_p\cdot\mathrm{flatten}(\text{patch}_i)+b
⚡ 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 H×W×CH \times W \times C into N=HWP2N = \frac{HW}{P^2} patches of spatial size P×PP \times P
  • •
    Linear projection: flattens patches into vectors of dimension P2CP^2 C and projects them to hidden dimension DD via projection matrix EE
  • •
    Token sequence assembly: prepends a learnable [CLS] token and adds 1D learnable or 2D sinusoidal positional embeddings, yielding N+1N + 1 tokens

📐 Mathematical Derivations

Mathematical Mechanism: 1. Patch Flattening & Projection: Given an input image x∈RH×W×Cx \in \mathbb{R}^{H \times W \times C} and patch size P×PP \times P, the spatial grid is divided into: N=H⋅WP2N = \frac{H \cdot W}{P^2} non-overlapping patches xp∈RN×(P2C)x_p \in \mathbb{R}^{N \times (P^2 C)}. A learnable linear projection E∈R(P2C)×DE \in \mathbb{R}^{(P^2 C) \times D} maps each flattened patch to the model hidden dimension DD: z0=[xclass;xp1E;xp2E;… ;xpNE]+Eposz_0 = [x_{\text{class}} ; x_p^1 E ; x_p^2 E ; \dots ; x_p^N E] + E_{\text{pos}} where xclass∈R1×Dx_{\text{class}} \in \mathbb{R}^{1 \times D} is the learnable classification token ([CLS]), and Epos∈R(N+1)×DE_{\text{pos}} \in \mathbb{R}^{(N+1) \times D} is the positional embedding matrix. 2. Convolutional Implementation Equivalence: In deep learning frameworks (PyTorch), patch projection is executed as a single 2D convolution: Conv2d(in_channels=C,  out_channels=D,  kernel_size=P,  stride=P)\text{Conv2d}(\text{in\_channels}=C, \; \text{out\_channels}=D, \; \text{kernel\_size}=P, \; \text{stride}=P) producing an output tensor RB×D×HP×WP\mathbb{R}^{B \times D \times \frac{H}{P} \times \frac{W}{P}}, which is flattened along spatial dimensions to RB×N×D\mathbb{R}^{B \times N \times D}. 3. Standard Configurations: For standard 224×224224 \times 224 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 (448×448448 \times 448 with P=14P=14), token count scales to (448/14)2+1=1025(448/14)^2 + 1 = 1025.

🏭 Production Trade-offs

Deep Dive & Engineering Trade-offs: ① Patch Size vs Attention Scaling: Reducing patch size from P=16P=16 to P=14P=14 increases spatial token count by (16/14)2≈1.31×(16/14)^2 \approx 1.31\times. Because standard self-attention complexity scales quadratically O(N2D)\mathcal{O}(N^2 D), this 31% token increase inflates attention FLOPs and KV memory by ≈1.71×\approx 1.71\times, 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., 224→448224 \to 448), pre-trained positional embeddings EposE_{\text{pos}} 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 NN patch tokens, which eliminates spatial bias towards the arbitrary class token position. ⑤ Interview Strategy: Formulate N=HWP2N = \frac{HW}{P^2}, derive the Conv2d stride/kernel equivalence, compute token counts for standard resolutions (224224 and 448448), 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 P=16P=16 to P=14P=14
  • ✕
    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.
🎯 Drill This Card Now➔
📚

Associated Knowledge Base Guides & Mindmaps

Explore the comprehensive technical article, exam cards, and global architecture tree.

← PreviousM5-136: LoRA Architectural Variants (DoRA, LoRA+, rsLoRA) and Rank Selection Strategies📋Back to BankNext →M6-002: Inductive Biases and Data Efficiency: CNN vs. Vision Transformer
中文速览与面试要点

解释 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 大小与预训练配置不一致