Vision Foundation Models, Self-Supervised Visual Representation Learning, Promptable Image-Video Segmentation, and Monocular Depth Estimation in 2026: Masked Autoencoders (MAE), DINOv2, Segment Anything (SAM & SAM 2), and Depth Anything V2

Vision Foundation Models, Self-Supervised Visual Representation Learning, Promptable Image-Video Segmentation, and Monocular Depth Estimation in 2026: Masked Autoencoders (MAE), DINOv2, Segment Anything (SAM & SAM 2), and Depth Anything V2

Vision Foundation Models, Self-Supervised Visual Representation Learning, Promptable Image-Video Segmentation, and Monocular Depth Estimation in 2026: Masked Autoencoders (MAE), DINOv2, Segment Anything (SAM & SAM 2), and Depth Anything V2

How did computer vision evolve from domain-specific convolutional networks trained on 1.28 million manually labeled ImageNet-1K categories into task-agnostic vision foundation models that pre-train on 75% randomly masked pixel patches at $3.3\times$ lower FLOPs (MAE), extract linearly separable frozen features across 142 million self-curated web images (DINOv2), segment arbitrary open-world objects in 50 milliseconds in a browser across 1.1 billion masks (SAM), track spatio-temporal video masklets through streaming Hiera memory attention at 43.8 to 130.1 FPS (SAM 2), and recover razor-sharp monocular geometry across transparent and reflective surfaces via 595K synthetic scenes bridged to 62 million pseudo-labeled real images (Depth Anything V2)?

For over a decade, visual perception pipelines suffered from two structural bottlenecks that prevented them from scaling like Natural Language Processing (NLP) foundation models:

  1. Spatial Signal Redundancy vs. Discrete Semantic Tokenization: In autoregressive and masked language modeling (GPT and BERT), masking 15% of discrete word tokens forces a Transformer to learn deep syntactic and semantic reasoning because human language is highly information-dense (arXiv:2111.06377, Section 1). Natural images, by contrast, are continuous 2D projections of light with extreme local spatial redundancy—a single missing $16 \times 16$ pixel patch can be trivially interpolated from its 8 immediate spatial neighbors using low-level edge and texture statistics without understanding object parts, boundaries, or 3D scene topology. Furthermore, passing [MASK] tokens through a deep Vision Transformer (ViT) encoder wastes up to 75% of quadratic self-attention compute on empty placeholder vectors while creating a distribution shift between pre-training and uncorrupted deployment (arXiv:2111.06377, Section 3 & Table 1c).
  2. Annotation Scarcity and Sensor Noise in Dense Pixel Supervision: While text-image contrastive models (CLIP, OpenCLIP, ALIGN) align global image embeddings with web captions across hundreds of millions of pairs, caption supervision fails to encode dense pixel-level geometry, part correspondence, or depth (arXiv:2304.07193, Section 1 & Table 10–11). Meanwhile, manual polygon segmentation on datasets like COCO takes ~91 seconds per mask ($6.5\times$ slower than SAM's assisted 14-second loop; arXiv:2304.02643, Section 4), and physical RGB-D depth sensors (Time-of-Flight, structured light, stereo matching, and Structure-from-Motion) systematically fail on transparent glass, specular mirrors, thin mesh structures, and textureless surfaces—causing models trained on real depth datasets to inherit blurred boundaries and catastrophic depth holes (arXiv:2406.09414v2, Section 2 & Figure 3).

Between 2021 and 2026, five foundational mathematical and systems breakthroughs dismantled both the supervision bottleneck and the dense geometric fidelity ceiling in computer vision:

  1. Asymmetric 75% Masked Autoencoding on Visible Patch Subsets (MAE, He et al., arXiv:2111.06377): Removing 75% of random image patches without replacement and restricting the heavyweight ViT encoder exclusively to the 25% visible unmasked patches (with zero [M] mask tokens in the encoder), while deferring mask tokens to a lightweight 8-block, 512-d Transformer decoder consuming just 9% FLOPs per token vs. ViT-L. By reconstructing per-patch normalized pixel values under Mean Squared Error (MSE) computed strictly on masked patches, MAE cuts pre-training FLOPs by $3.3\times$, accelerates wall-clock training by $2.8\times$ to $4.1\times$ on 128 TPU-v3 cores, and enables a vanilla ViT-Huge/14 ($448 \times 448$) trained using only ImageNet-1K data to reach 87.8% top-1 accuracy while boosting COCO Mask R-CNN transfer to $53.3\text{ AP}^{\text{box}} / 47.2\text{ AP}^{\text{mask}}$ and ADE20K semantic segmentation to 53.6 mIoU (arXiv:2111.06377, Tables 1–5).
  2. Curated Self-Supervised Discriminative Pre-Training at Scale (DINOv2, Oquab et al., arXiv:2304.07193): Building an automated Faiss GPU retrieval pipeline that filters 1.2 billion unique web images into the balanced 142-million-image LVD-142M corpus in under 2 days without text metadata or human labels, and training a 1.1-billion-parameter ViT-g/14 backbone (1536-d, 24 heads, 64 dim/head) under untied image-level DINO + patch-level iBOT cross-entropy objectives stabilized by 3-iteration Sinkhorn-Knopp batch centering, the Kozachenko-Leonenko (KoLeo) differential entropy regularizer, sequence packing, and PyTorch FSDP mixed-precision sharding ($2\times$ faster and $3\times$ less memory than iBOT). Frozen DINOv2 ViT-g/14 features achieve 86.5% linear-probe top-1 accuracy on ImageNet-1K (89.6% on ImageNet-ReaL, 78.4% on ImageNet-V2, and 88.9% fine-tuned), 75.9% on ImageNet-A (+34.4 points over iBOT), +8.3% Oxford-M retrieval gain from KoLeo regularization, and 60.2 mIoU on ADE20K with 66% of weights frozen (arXiv:2304.07193, Tables 1–11).
  3. Ambiguity-Aware Promptable Image Segmentation and the 1.1-Billion-Mask Data Engine (SAM, Kirillov et al., arXiv:2304.02643): Decoupling an MAE pre-trained ViT-H/16 high-resolution image encoder from a ~50 ms browser-executable Prompt Encoder and Two-Way Transformer Mask Decoder that predicts 3 nested masks (whole, part, subpart) and per-mask IoU confidence scores per prompt under minimum-loss backpropagation (Focal Loss + Dice Loss across 11 simulated interactive rounds). Co-developed through a 3-stage data engine (assisted-manual $\to$ semi-automatic $\to$ fully automatic $32 \times 32$ point grid with stability filtering $0.5 \pm \delta$), SAM generated SA-1B: 1.1 billion masks across 11 million high-resolution ($3300 \times 4950$) licensed images ($400\times$ more masks than Open Images, with 94% of audited masks exceeding 90% IoU against human refinement; arXiv:2304.02643, Sections 3–7).
  4. Unified Image-Video Promptable Visual Segmentation with Streaming Hiera Memory (SAM 2, Ravi et al., arXiv:2408.00714v2): Generalizing SAM to spatio-temporal video masklets by pairing an RPB-free MAE pre-trained Hiera hierarchical encoder (with stride-4 and stride-8 high-resolution skip connections) with $L=4$ 2d-RoPE Memory Attention blocks, an Occlusion Prediction Head, and a FIFO Memory Bank retaining up to $N=6$ recent frames, $M$ prompted frames (64-d spatial features), and 256-d Object Pointers (split into $4 \times 64\text{-d}$ tokens). Trained on the SA-V dataset (35.5 million masks and 642.6K masklets across 50.9K videos, $53\times$ larger than prior VOS datasets) collected at 4.5 seconds/frame ($8.4\times$ faster than per-frame SAM), SAM 2 achieves 75.3 $\mathcal{J}\&\mathcal{F}$ (3-click) and 79.3 $\mathcal{J}\&\mathcal{F}$ (GT mask) across 17 zero-shot video benchmarks with $>3\times$ fewer interactions, 90.7 $\mathcal{J}\&\mathcal{F}$ on DAVIS 2017, 77.9 $\mathcal{J}\&\mathcal{F}$ on MOSE, and 61.9 1-click mIoU across SA-23 at 130.1 FPS ($6\times$ faster than SAM; arXiv:2408.00714v2, Tables 1–6).
  5. Synthetic-Teacher to Pseudo-Real-Student Monocular Depth Foundation Models (Depth Anything V2, Yang et al., arXiv:2406.09414v2): Eliminating real-sensor depth corruption by training a 1.3B DINOv2-G + DPT teacher exclusively on 595K pixel-perfect synthetic images (BlendedMVS, Hypersim, IRS, TartanAir, VKITTI 2) under scale-and-shift-invariant and gradient-matching losses ($\mathcal{L}{\text{ssi}} : \mathcal{L}{\text{gm}} = 1:2$), generating dense pseudo-depth across 62 million unlabeled real images (including SA-1B, ImageNet-21K, BDD100K, Open Images V7), and distilling student models (25M ViT-S to 1.3B ViT-G) purely on pseudo-labeled real images with top-10% loss-region masking. Depth Anything V2 surges from 53.5% (V1) and 25.9% (MiDaS) to 83.6% zero-shot accuracy on the Transparent Surface Challenge, reaches 95.3% (ViT-S) to 97.4% (ViT-G) on the DA-2K benchmark (+10.6% over diffusion-based Marigold at $>10\times$ higher speed), and sets state-of-the-art metric depth records on NYU-D ($\delta_1 = 0.984, \text{AbsRel} = 0.056, \text{RMSE} = 0.206$) and KITTI ($\delta_1 = 0.983, \text{AbsRel} = 0.045, \text{RMSE} = 1.861$) (arXiv:2406.09414v2, Tables 2–8).
📌 Key Takeaways & Empirical Vision Foundation Model Benchmarks
  • ✓MAE Asymmetric 75% Patch Masking & Pixel Reconstruction (arXiv:2111.06377): Encoding only the 25% visible patches without [M] mask tokens and reconstructing per-patch normalized pixels via an 8-block, 512-d decoder (9% FLOPs/token vs. ViT-L) reduces FLOPs by 3.3×, speeds up 128-core TPU-v3 pre-training by 2.8×–4.1×, boosts linear probing by +13.9% (73.5% vs. 59.6% with encoder mask tokens), and reaches 87.8% ImageNet-1K top-1 accuracy (ViT-H/14448), 53.3 APbox / 47.2 APmask on COCO, and 53.6 mIoU on ADE20K using only ImageNet-1K pre-training data.
  • ✓DINOv2 LVD-142M Self-Supervised Curation & KoLeo Regularization (arXiv:2304.07193): Retrieving 142M curated images from 1.2B web images via Faiss GPU k-means and training a 1.1B ViT-g/14 with untied DINO + iBOT heads, Sinkhorn-Knopp centering, and KoLeo differential entropy regularization achieves 86.5% frozen linear-probe accuracy on ImageNet-1K (89.6% ReaL, 78.4% V2; 88.9% fine-tuned), 75.9% on ImageNet-A (+12.1% over OpenCLIP-G), +8.3% Oxford-M retrieval mAP from KoLeo, and 0.279 RMSE on NYUd depth with a frozen backbone.
  • ✓Segment Anything (SAM) 50ms Ambiguity-Aware Decoder & SA-1B Dataset (arXiv:2304.02643): Combining a one-time MAE ViT-H/16 image embedding with a ~50 ms browser mask decoder outputting 3 nested masks (whole, part, subpart) powered a 3-stage data engine that generated 1.1B masks on 11M images (SA-1B, 400× larger than Open Images, 94% >90% IoU vs. professional correction), achieving 0.768 ODS / 0.928 R50 zero-shot edge detection on BSDS500 and 65.8 rare-object AR@1000 on LVIS v1 (surpassing supervised ViTDet-H's 58.3).
  • ✓SAM 2 Streaming Hiera Memory & SA-V 35.5M-Masklet Video Dataset (arXiv:2408.00714v2): Conditioning an RPB-free Hiera encoder on a FIFO Memory Bank ($N=6$ recent frames, $M$ prompted frames, $4\times 64\text{-d}$ Object Pointers, and an occlusion head) via 2d-RoPE Memory Attention cuts video annotation time by 8.4× (37.8s → 4.5s/frame) across 35.5M masks in 50.9K videos (SA-V), delivering 76.6–77.9 $\mathcal{J}\&\mathcal{F}$ on MOSE val, 90.2–90.7 on DAVIS 2017, and 61.9 1-click mIoU on SA-23 at 130.1 FPS (6× faster than SAM).
  • ✓Depth Anything V2 Synthetic Teacher + 62M Pseudo-Labeled Bridge (arXiv:2406.09414v2): Training a 1.3B DINOv2-G teacher purely on 595K synthetic images ($\mathcal{L}_{\text{ssi}}:\mathcal{L}_{\text{gm}}=1:2$) to pseudo-label 62M real images lifts Transparent Surface Challenge accuracy from 53.5% to 83.6%, achieves 95.3% (25M ViT-S) to 97.4% (1.3B ViT-G) on DA-2K (+10.6% over Marigold at >10× speed), and reaches 0.984 $\delta_1$ / 0.206 RMSE on NYU-D and 0.983 $\delta_1$ / 1.861 RMSE on KITTI.
3.3× FLOPs → 87.8%
MAE 75% Asymmetric Masking

Encoding only 25% visible patches cuts FLOPs 3.3× (2.8–4.1× wall-clock speedup) and reaches 87.8% on ImageNet-1K with ViT-H/14448 (arXiv:2111.06377).

142M → 86.5% Lin
DINOv2 Frozen ViT-g/14

LVD-142M self-supervised retrieval + KoLeo entropy regularizer achieves 86.5% frozen linear probe on IN1K and 75.9% on IN-A (arXiv:2304.07193).

1.1B + 35.5M Masks
SA-1B & SA-V Data Engines

SAM & SAM 2 collected 1.1B image masks (11M images) and 35.5M video masks (50.9K videos), running 6× faster at 130.1 FPS (arXiv:2408.00714v2).

97.4% DA-2K
Depth Anything V2 Teacher-Student

595K synthetic teacher + 62M pseudo-labeled real images beats Marigold (86.8%) by +10.6% at >10× speed and hits 83.6% on transparent glass (arXiv:2406.09414v2).


Asymmetric Masked Autoencoding, 75% Random Patch Sampling, and Normalized Pixel Reconstruction (MAE, arXiv:2111.06377)

In Masked Autoencoders Are Scalable Vision Learners (arXiv:2111.06377, CVPR 2022), Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, and Ross Girshick diagnosed why masked autoencoding in computer vision had historically lagged behind BERT in NLP across three fundamental dimensions (arXiv:2111.06377, Section 1):

  1. Grid Convolution vs. Tokenized Sequence Architectures: Standard Convolutional Neural Networks (CNNs) operate on dense regular 2D pixel grids where injecting discrete mask indicators ([M]) or 2D positional embeddings introduces artificial boundary artifacts. Vision Transformers (ViT, Dosovitskiy et al., 2021) eliminate this barrier by partitioning an input image $\mathbf{I} \in \mathbb{R}^{H \times W \times C}$ into a sequence of $N = (H/P) \times (W/P)$ non-overlapping patches of size $P \times P$ (typically $14 \times 14 = 196$ patches of $16 \times 16$ pixels for a $224 \times 224$ image).
  2. Spatial Information Redundancy vs. Linguistic Density: Whereas masking 15% of words in a sentence removes high-entropy semantic concepts, masking 15% to 50% of image patches leaves enough adjacent pixels for a network to solve the pretext task via local bilinear or texture extrapolation. Only by pushing the masking ratio $r$ to 75% (or 80% in Figure 2, leaving just 39 out of 196 patches visible) does MAE destroy local spatial redundancy and compel the encoder to learn holistic object gestalt and scene semantics.
  3. Semantic Level of the Decoder Output: In BERT, the decoder predicts discrete vocabulary words that are inherently semantic, so a trivial one-layer MLP suffices. In vision, reconstructing raw pixel intensities operates at a low semantic abstraction level; unless the autoencoder employs a dedicated multi-block Transformer decoder to absorb the low-level pixel reconstruction burden, the encoder's top layers specialize in local pixel interpolation rather than transferable object recognition (arXiv:2111.06377, Section 1 & Section 4.1).

1. Asymmetric Encoder-Decoder Mathematical Formulation and Zero-Sparse-Op Shuffle Implementation

Given an image partitioned into $N$ non-overlapping patches $\{\mathbf{x}1, \mathbf{x}_2, \dots, \mathbf{x}_N\}$ with $\mathbf{x}_i \in \mathbb{R}^{P^2 C}$, MAE draws a uniform random permutation $\pi$ of $\{1, \dots, N\}$ without replacement—avoiding center bias—and partitions the indices into a visible subset $\mathcal{V}$ of size $N{\text{vis}} = \lfloor(1 - r)N\rfloor$ (with default masking ratio $r = 0.75$, so $N_{\text{vis}} = 0.25 N = 49$ patches for ViT-L/16 at $224 \times 224$) and a masked subset $\mathcal{M}$ of size $N_{\text{mask}} = N - N_{\text{vis}} = 0.75 N = 147$ patches (arXiv:2111.06377, Section 3):

$$\mathbf{z}0^{\text{enc}} = \Big[\mathbf{W}_E \mathbf{x}_i + \mathbf{p}_i^{\text{enc}}\Big]{i \in \mathcal{V}} \in \mathbb{R}^{N_{\text{vis}} \times D_{\text{enc}}}, \qquad \mathbf{z}_L^{\text{enc}} = \text{ViT-Encoder}\big(\mathbf{z}_0^{\text{enc}}\big)$$

Crucially, no mask tokens [M] enter the encoder. Because the ViT encoder processes only $N_{\text{vis}} = 0.25 N$ real image patches, its linear projections scale by $0.25\times$ and its quadratic self-attention matrices $\mathbf{A} = \text{softmax}(\mathbf{Q}\mathbf{K}^T / \sqrt{d_k}) \in \mathbb{R}^{N_{\text{vis}} \times N_{\text{vis}}}$ scale by $(0.25)^2 = 0.0625\times$ ($1/16\text{th}$ of full sequence attention!).

After the encoder produces latent representations $\mathbf{z}L^{\text{enc}} \in \mathbb{R}^{N{\text{vis}} \times D_{\text{enc}}}$, a linear projection $\mathbf{W}{\text{proj}} \in \mathbb{R}^{D{\text{enc}} \times D_{\text{dec}}}$ maps them to the narrower decoder width $D_{\text{dec}} = 512$, appends $N_{\text{mask}}$ copies of a shared learnable mask token $\mathbf{m} \in \mathbb{R}^{D_{\text{dec}}}$, applies the inverse permutation $\pi^{-1}$ (unshuffle) to restore every token to its exact 2D spatial grid coordinate, and adds 2D sine-cosine positional embeddings $\mathbf{p}j^{\text{dec}} \in \mathbb{R}^{D{\text{dec}}}$ (arXiv:2111.06377, Section 3 & Appendix A.1):

$$\mathbf{z}0^{\text{dec}} = \text{Unshuffle}{\pi^{-1}}\!\Big(\big[\mathbf{W}{\text{proj}}\mathbf{z}_L^{\text{enc}};\; \underbrace{\mathbf{m}, \dots, \mathbf{m}}{N_{\text{mask}}}\big]\Big) + \mathbf{P}^{\text{dec}} \in \mathbb{R}^{N \times D_{\text{dec}}}$$

The lightweight decoder (default 8 Transformer blocks, width $D_{\text{dec}} = 512$, requiring only 9% FLOPs per token compared to ViT-L's 24 blocks at $D_{\text{enc}} = 1024$) transforms $\mathbf{z}0^{\text{dec}}$ and projects each token through a linear head $\mathbf{W}{\text{head}} \in \mathbb{R}^{D_{\text{dec}} \times P^2 C}$ to predict patch pixel vectors $\hat{\mathbf{y}}_j \in \mathbb{R}^{P^2 C}$. The pre-training objective is the Mean Squared Error (MSE) evaluated exclusively over the masked patches $j \in \mathcal{M}$ against per-patch locally normalized ground-truth pixel targets (arXiv:2111.06377, Section 3 & Table 1d):

$$\mathcal{L}{\text{MAE}} = \frac{1}{|\mathcal{M}|\,P^2 C} \sum{j \in \mathcal{M}} \left\| \hat{\mathbf{y}}_j - \frac{\mathbf{x}_j - \mu(\mathbf{x}_j)}{\sigma(\mathbf{x}_j) + \epsilon} \right\|_2^2$$

where $\mu(\mathbf{x}_j)$ and $\sigma(\mathbf{x}_j)$ are the empirical mean and standard deviation of all pixel values within patch $j$. As He et al. note in Footnote 1 and Table 1d, computing the loss on all pixels (like classical denoising autoencoders) degrades accuracy by ~0.5%, whereas computing MSE solely on masked patches with per-patch contrast normalization boosts ViT-L/16 fine-tuning accuracy from 84.9% to 85.4% and linear probing from 73.5% to 73.9%—matching or outperforming a discrete dVAE tokenizer (85.3% ft / 71.6% lin, Table 1d & Table 7) without needing a 250-million-image pre-trained DALLE dVAE stages that add 40% of ViT-L's FLOPs in tokenizer overhead (arXiv:2111.06377, Section 4.1).

2. Complete Empirical Ablations and ImageNet-1K / COCO / ADE20K Scaling Laws

The empirical ablations in Tables 1, 2, 3, 4, 5, 6, and 13 of arXiv:2111.06377 establish six structural laws for self-supervised vision encoders:

  • Skipping [M] in the Encoder Yields Both +13.9% Higher Linear Accuracy and $3.3\times$ Lower FLOPs (Table 1c & Table 2): Including mask tokens [M] inside the ViT-L encoder causes a severe pretrain-deploy distribution mismatch, collapsing linear probing accuracy from 73.5% down to 59.6% (-13.9 points) and dropping fine-tuning from 84.9% to 84.2% while consuming $3.3\times$ more FLOPs. Removing [M] from the encoder cuts 800-epoch wall-clock training time on 128 TPU-v3 cores from 42.4 hours to 15.4 hours ($2.8\times$ speedup) with an 8-block decoder and 11.6 hours ($3.7\times$ speedup) with a 1-block decoder (84.8% ft). On ViT-Huge, wall-clock time drops from 119.6 hours to 34.5 hours ($3.5\times$ speedup, 85.8% ft) with an 8-block decoder and 29.3 hours ($4.1\times$ speedup, 85.9% ft) with a 1-block decoder.
  • Augmentation Independence via Random Masking (Table 1e & Table 1f): Unlike contrastive methods (SimCLR and BYOL, whose accuracy drops by 28% and 13% respectively under cropping-only augmentation), MAE achieves 84.9% ft / 73.5% lin with random resized cropping alone, 84.0% ft / 65.7% lin with zero data augmentation (center-crop only, no horizontal flipping), and actually degrades to 84.3% ft / 71.9% lin when color jittering is added. Why? Because drawing a fresh random 75% mask every epoch generates a combinatorially distinct view ($\binom{196}{49} \approx 3.7 \times 10^{47}$ possible patch subsets) without distorting color statistics. Uniform random sampling at 75% (84.9% ft / 73.5% lin) decisively outperforms block-wise masking at 50% (83.9% / 72.3%) or 75% (82.8% / 63.9%) and grid-wise sampling at 75% (84.0% / 66.0%).
  • Non-Linear Feature Strength under Partial Fine-Tuning (Section 4.3, Figure 9): While contrastive MoCo v3 achieves slightly higher 0-block linear probing on ViT-L (77.6% vs. 75.8% at 1600 epochs, Appendix B Table 12), tuning just half of the last Transformer block (its MLP sub-block) jumps MAE from 73.5% to 79.1%, tuning 1 Transformer block reaches 81.0%, and tuning 4 blocks gives MAE a +2.6% lead over MoCo v3.
Pre-Training Method & Data (`arXiv:2111.06377` Tables 3, 4, 5, 6, 13) ImageNet-1K Fine-Tune (ViT-B / ViT-L / ViT-H / ViT-H448) COCO Mask R-CNN APbox / APmask (ViT-B | ViT-L) ADE20K UperNet mIoU (ViT-B | ViT-L) OOD Robustness ViT-H (IN-C↓ / IN-A / IN-R / IN-S)
Supervised Scratch (IN1K w/ labels, EMA) 82.3% / 82.6% / 83.1% / — 47.9 / 42.9 | 49.3 / 43.9 47.4 | 49.9 41.3 / 33.1% / 50.3% / 38.0%
DINO (IN1K, self-supervised) 82.8% / — / — / — — — —
MoCo v3 (IN1K, 300 ep, 36h on 128 TPU-v3) 83.2% / 84.1% / — / — 47.9 / 42.7 | 49.3 / 44.0 47.3 | 49.1 —
BEiT (IN1K + 250M DALLE dVAE tokens) 83.2% / 85.2% / — / — 49.8 / 44.4 | 53.3 / 47.1 47.1 | 53.3 —
MAE (IN1K only, 1600 ep, 31h on 128 TPU-v3) 83.6% / 85.9% / 86.9% / 87.8% 50.3 / 44.9 | 53.3 / 47.2 48.1 | 53.6 33.8 / 68.2% (76.7%448) / 64.4% / 49.6%

Discriminative Self-Supervised Pre-Training at Scale: LVD-142M Curation, Sinkhorn-Knopp Centering, and KoLeo Entropy Regularization (DINOv2, arXiv:2304.07193)

While MAE excels as a high-capacity initialization for supervised fine-tuning (serving as the pre-trained backbone inside both SAM ViT-H and SAM 2 Hiera), its raw frozen features are not linearly separable out-of-the-box (49.4% k-NN and 76.6% linear probe on ImageNet-1K for MAE ViT-H/14, and only 33.3 mIoU under a frozen linear segmentation head on ADE20K; arXiv:2304.07193, Table 4 & Table 10). In DINOv2: Learning Robust Visual Features without Supervision (arXiv:2304.07193, TMLR 2024), Maxime Oquab, Timothée Darcet, Théo Moutakanni, and the Meta AI Research / Inria team demonstrated that discriminative self-supervised learning can produce universal frozen visual features that match or surpass weakly-supervised text-image models (OpenCLIP ViT-G/14 trained on LAION-2B and EVA-CLIP ViT-g/14) across both image-level and dense pixel-level tasks without any fine-tuning.

1. Automated Self-Supervised Dataset Curation (LVD-142M) via Faiss GPU Retrieval

Previous attempts to scale self-supervised learning beyond ImageNet-1K onto raw uncurated web crawls degraded representation quality because uncurated web dumps suffer from extreme concept imbalance and near-duplicate spam (arXiv:2304.07193, Section 1 & Table 2). Training a ViT-g/14 on 142 million random uncurated web images drops ImageNet-1K linear accuracy from 85.8% to 83.3%, crashes ImageNet-A robustness by -14.5 points (73.9% $\to$ 59.4%), drops Oxford-M retrieval by -10.3 points (64.6% $\to$ 54.3%), and plunges iNaturalist-2018 by -14.3 points (82.3% $\to$ 68.0%) (arXiv:2304.07193, Table 2).

To construct LVD-142M (142 million curated images) without using any text captions, hashtags, or supervised classifiers (arXiv:2304.07193, Section 3):

  1. 1.2-Billion-Image Web Pool & Copy-Detection Deduplication: Raw <img> URLs extracted from a public web crawl undergo PCA hash deduplication, NSFW filtering, and identifiable face blurring to yield 1.2B unique images. The copy-detection pipeline of Pizzi et al. (2022) removes near-duplicates inside the web pool and strictly purges any near-duplicates of validation/test images across every downstream evaluation benchmark.
  2. Self-Supervised ViT-H/16 Embedding & Faiss Inverted-File Product Quantization (IVF-PQ): Every uncurated and seed image (from ImageNet-22k, ImageNet-1k train, Google Landmarks, and fine-grained datasets) is embedded by a self-supervised ViT-H/16 pretrained on ImageNet-22k. The uncurated pool is clustered via $k$-means using GPU-accelerated Faiss inverted file indices with product quantization codes.
  3. Collision-Controlled Nearest-Neighbor Retrieval ($N = 4$): For large query datasets, the pipeline retrieves the $N = 4$ nearest neighbors by cosine similarity per query image (choosing $N=4$ to avoid multi-query collision saturation); for small query datasets, it samples $M$ images from the cluster corresponding to each query image. Distributed across 20 compute nodes equipped with 8 NVIDIA V100-32GB GPUs, the entire 1.2B $\to$ 142M curation pipeline completes in less than 2 days (arXiv:2304.07193, Section 3).

2. Untied Dual-Level Self-Distillation, Sinkhorn-Knopp Centering, and KoLeo Differential Entropy

DINOv2 unifies image-level and patch-level discriminative self-distillation between a student network $g_{\theta_s}$ and an Exponential Moving Average (EMA) teacher network $g_{\theta_t}$ ($\theta_t \leftarrow \lambda \theta_t + (1 - \lambda)\theta_s$ with teacher momentum $\lambda = 0.994$; arXiv:2304.07193, Section 4 & Table 1):

  1. Image-Level DINO Objective on Global/Local Crop [CLS] Tokens: Given multiple views (2 global crops at $224 \times 224$ and local crops at $98 \times 98$) of the same image, the student [CLS] token is projected through a learnable MLP DINO head (with 128,000 prototype scores) and softmax-normalized with temperature $\tau_s$ to obtain $p_s$. The teacher [CLS] token from global views is projected through the EMA teacher DINO head and centered via 3 iterations of the Sinkhorn-Knopp (SK) batch normalization algorithm (from SwAV, replacing moving-average softmax centering) to yield $p_t$:

$$\mathcal{L}_{\text{DINO}} = -\sum p_t \log p_s$$

  1. Patch-Level iBOT Masked Image Modeling Objective with Untied Heads: Random input patches are masked in the student view but kept visible in the teacher view. Applying the student iBOT MLP head to masked student patch tokens $p_{si}$ and the teacher iBOT MLP head (with 3-iteration Sinkhorn-Knopp centering) to the corresponding visible teacher patch tokens $p_{ti}$ yields:

$$\mathcal{L}{\text{iBOT}} = -\sum{i \in \mathcal{M}} p_{ti} \log p_{si}$$

While iBOT (Zhou et al., 2022a) shared weights between the [CLS] and patch projection heads at small scale, Oquab et al. (arXiv:2304.07193, Section 4 & Table 1) discovered that at large scale, untying the DINO and iBOT head weights boosts ImageNet-1k k-NN accuracy to 82.0% (a cumulative +9.1% k-NN gain over baseline iBOT's 72.9% on ViT-Large / INet-22k). Ablating the iBOT MIM term in Table 3b proves it is indispensable for dense pixel tasks, lifting ADE-20K linear segmentation by +2.9 mIoU (44.2 $\to$ 47.1).

  1. Kozachenko-Leonenko (KoLeo) Differential Entropy Regularizer: To prevent feature clustering collapse and force representations to span the hypersphere uniformly within every batch of $n$ $\ell_2$-normalized feature vectors $(\mathbf{x}_1, \dots, \mathbf{x}_n)$ where $\hat{\mathbf{x}}_i = \mathbf{x}_i / \|\mathbf{x}_i\|_2$, DINOv2 adds the non-parametric Kozachenko-Leonenko differential entropy estimator (arXiv:2304.07193, Section 4):

$$\mathcal{L}{\text{koleo}} = -\frac{1}{n}\sum{i=1}^{n} \log(d_{n,i}), \qquad \text{where} \quad d_{n,i} = \min_{j \neq i} \|\hat{\mathbf{x}}_i - \hat{\mathbf{x}}_j\|_2$$

As shown in Table 1 and Table 3a, adding $\mathcal{L}_{\text{koleo}}$ provides the single largest single-step jump in k-NN classification (+2.3%, from 76.6% to 78.9%), improves ImageNet-A linear generalization by +2.2% (70.6% $\to$ 72.8%), and surges Oxford-Medium instance retrieval mAP by +8.3 points (55.6% $\to$ 63.9%) without hurting segmentation.

💡 Hardware-Aligned ViT-g/14 (1.1B), Block-Diagonal Sequence Packing, and FSDP Sharding

Standard ViT-g (Zhai et al., 2022) uses an embedding dimension of 1408 across 16 heads (88 dim/head), which misaligns with NVIDIA TensorCore 64-byte/256-byte memory coalescing boundaries. DINOv2 redesigns ViT-g/14 (1.1B parameters) with an embedding dimension of 1536 (a multiple of 256) and 24 heads (64 dim/head) alongside a SwiGLU FFN, LayerScale, and patch size 14. Combined with xFormers sequence packing (concatenating $224\times 224$ global tokens and $98\times 98$ local tokens into one single tensor with a block-diagonal self-attention mask), slice-based stochastic depth (skipping d = 40% of residual block compute via batch shuffling and $(1-d)\times B$ slicing rather than post-compute masking), PyTorch FSDP mixed-precision sharding (splitting 16 GB of fp32 student/teacher/AdamW states across GPUs while broadcasting weights and reducing backbone gradients in fp16 for a ~50% communication savings over DDP), and a short end-of-training high-resolution phase at 518×518, DINOv2 runs 2× faster using 1/3 of the memory of iBOT (arXiv:2304.07193, Sections 4–5).

Frozen Model & Pre-Train Data (`arXiv:2304.07193` Tables 4, 6, 7, 8, 9, 10, 11) IN1K kNN / Linear / ReaL / V2 OOD Linear (Im-A / Im-R / Im-C↓ / Sketch) Oxford-M / Oxford-H / Paris-H mAP ADE20K / Cityscapes / VOC (lin | +ms mIoU) Depth DPT RMSE↓ (NYUd / KITTI / SUN)
OpenCLIP ViT-G/14 (LAION-2B, text-sup) 83.2 / 86.2 / 89.4 / 77.2 63.8 / 87.8 / 45.3 / 66.4 50.7 / 19.7 / 60.2 39.3|46.0 / 60.3|70.3 / 71.4|79.2 0.414 / 2.56 / 0.408
MAE ViT-H/14 (INet-1k, self-sup) 49.4 / 76.6 / 83.3 / 64.8 10.2 / 34.4 / 61.4 / 21.9 11.7 / 2.2 / 4.7 33.3|30.7 / 58.4|61.0 / 67.6|63.3 0.415 / 2.59 / 0.506
iBOT ViT-L/16 (INet-22k, self-sup) 72.9 / 82.3 / 87.5 / 72.4 41.5 / 51.0 / 43.9 / 38.5 39.0 / 12.7 / 47.0 44.6|47.5 / 64.8|74.5 / 82.3|84.3 0.358 / 2.55 / 0.426
DINOv2 ViT-S/14 (LVD-142M, distilled) 79.0 / 81.1 / 86.6 / 70.9 33.5 / 53.7 / 54.4 / 41.2 68.8 / 43.2 / 68.5 44.3|47.2 / 66.6|77.1 / 81.1|82.6 0.356 / 2.34 / 0.409
DINOv2 ViT-B/14 (LVD-142M, distilled) 82.1 / 84.5 / 88.3 / 75.1 55.1 / 63.3 / 42.7 / 50.6 72.9 / 49.5 / 78.6 47.3|51.3 / 69.4|80.0 / 82.5|84.9 0.317 / 2.23 / 0.377
DINOv2 ViT-L/14 (LVD-142M, distilled) 83.5 / 86.3 / 89.5 / 78.0 71.3 / 74.4 / 31.5 / 59.3 75.1 / 54.0 / 83.5 47.7|53.1 / 70.3|80.9 / 82.1|86.0 0.293 / 2.14 / 0.360
DINOv2 ViT-g/14 (LVD-142M, 1.1B teacher) 83.5 / 86.5 / 89.6 / 78.4 75.9 / 78.8 / 28.2 / 62.5 73.6 / 52.3 / 82.6 49.0|53.0 (60.2*) / 71.3|81.0 / 83.0|86.2 0.279 / 2.11 / 0.338

Promptable Image Segmentation, Ambiguity-Aware Two-Way Decoders, and the 1.1B-Mask Data Engine (SAM, arXiv:2304.02643)

In Segment Anything (arXiv:2304.02643, ICCV 2023), Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, and the Meta FAIR team translated the NLP paradigm of prompt-engineered zero-shot generalization into spatial computer vision. Rather than training a closed-set multi-task segmenter restricted to a fixed vocabulary of classes, SAM defines the Promptable Segmentation Task: given any segmentation prompt—a single foreground/background point, a rough bounding box, a low-resolution mask, or free-form text—the model must always return a valid segmentation mask, even when the prompt is inherently ambiguous (arXiv:2304.02643, Section 2).

Pixel-Level Image Segmentation Partitioning Foreground Object Masks and Scene Boundaries (Wikimedia Commons CC0)
Ambiguity-Aware Hierarchical Mask Decomposition: A single point prompt on an object can legitimately refer to the whole entity, a structural part, or a fine-grained subpart. Instead of averaging competing hypotheses into an invalid blurry mask, Segment Anything (`arXiv:2304.02643`) predicts $K=3$ nested mask outputs alongside estimated IoU confidence scores in ~50 ms in a web browser (MartinThoma, Wikimedia Commons, CC0 Public Domain, verified HTTP 200).

1. Decoupled Amortization, Two-Way Transformer Mask Decoder, and Minimum-Loss Ambiguity Resolution

To support interactive real-time prompting at $1024 \times 1024$ input resolution, SAM decouples heavy spatial feature extraction from lightweight prompt conditioning (arXiv:2304.02643, Section 3):

  1. Heavyweight Amortized Image Encoder (MAE Pre-Trained ViT-H/16): Runs once per image prior to user interaction, mapping a high-resolution image into a $64 \times 64 \times 256$ spatial image embedding $\mathbf{F}_{\text{img}}$ (stride 16).
  2. Sparse and Dense Prompt Encoder: Sparse prompts—points $(x, y, l)$ with foreground/background label $l \in \{0, 1\}$ and bounding boxes $(x_{\min}, y_{\min}, x_{\max}, y_{\max})$—are encoded via 2D random Fourier positional encodings summed with learned prompt-type embedding vectors, while free-form text prompts are encoded via CLIP's text encoder. Dense mask prompts $\mathbf{M}{\text{in}}$ are downsampled via strided convolutions and summed element-wise with $\mathbf{F}{\text{img}}$.
  3. Two-Way Transformer Mask Decoder (~50 ms on Browser CPU): Appends learnable output tokens (3 mask tokens $\mathbf{t}1, \mathbf{t}_2, \mathbf{t}_3$ plus an IoU prediction token $\mathbf{t}{\text{IoU}}$) to the sparse prompt embeddings $\mathbf{T}{\text{prompt}}$ and runs 2 modified Two-Way Transformer decoder blocks. Every block executes four sequential steps: - Self-attention over the prompt/output tokens $\mathbf{T}{\text{prompt}}$; - Cross-attention from tokens (as queries) to the spatial image embedding $\mathbf{F}{\text{img}}$; - A point-wise MLP updating the tokens; - Cross-attention in the reverse direction—from every spatial location in $\mathbf{F}{\text{img}}$ (as queries) back to the updated prompt/output tokens $\mathbf{T}_{\text{prompt}}$—so the spatial feature map itself adapts dynamically to the geometric prompt (arXiv:2304.02643, Section 3 & Figure 4).

After two blocks, $\mathbf{F}{\text{img}}$ is upsampled $4\times$ via transposed convolutions to $\mathbf{F}{\text{up}} \in \mathbb{R}^{256 \times 256 \times C}$, each output mask token $\mathbf{t}k$ ($k \in \{1, 2, 3\}$) is passed through a 3-layer MLP to produce dynamic linear classifier weights $\mathbf{w}_k \in \mathbb{R}^C$, and the foreground probability map $\hat{\mathbf{M}}_k = \sigma(\mathbf{w}_k^T \mathbf{F}{\text{up}})$ is computed via spatially pointwise inner products.

To prevent the decoder from averaging valid nested masks (e.g., shirt vs. person wearing the shirt) into an invalid blended region, SAM supervises the $K=3$ mask predictions against ground-truth mask $\mathbf{M}^*$ using hindsight minimum-loss backpropagation over a linear combination of Focal Loss and Dice Loss across 11 simulated interactive prompting rounds per mask (arXiv:2304.02643, Section 3):

$$\mathcal{L}{\text{SAM}} = \min{k \in \{1, 2, 3\}} \Big(\lambda_{\text{focal}}\,\mathcal{L}{\text{focal}}\big(\hat{\mathbf{M}}_k, \mathbf{M}^\big) + \lambda{\text{dice}}\,\mathcal{L}{\text{dice}}\big(\hat{\mathbf{M}}_k, \mathbf{M}^\big)\Big) + \mathcal{L}{\text{IoU}}\Big(\hat{s}{k^},\, \text{IoU}\big(\hat{\mathbf{M}}{k^}, \mathbf{M}^*\big)\Big)$$

2. The 3-Stage Segment Anything Data Engine, SA-1B (1.1B Masks), and Zero-Shot Transfer

Because web-scale segmentation masks did not exist on the internet, Kirillov et al. (arXiv:2304.02643, Sections 4–5) co-developed SAM inside a 3-stage model-in-the-loop data engine across 11 million licensed high-resolution images (average $3300 \times 4950$ pixels, released with shortest side 1500 px and faces/license plates blurred):

1
Stage 1 — Assisted-Manual Annotation (4.3M Masks across 120k Images)

Professional annotators labeled both “things” and “stuff” in a browser using SAM foreground/background clicks plus pixel-precise brush/eraser tools. Across 6 model retraining iterations (scaling the image encoder from ViT-B to ViT-H), average annotation time per mask plummeted from 34 seconds to 14 seconds (6.5× faster than COCO mask annotation and only 2× slower than extreme-point bounding boxes) while density rose from 20 to 44 masks per image (arXiv:2304.02643, Section 4).

2
Stage 2 — Semi-Automatic Diversity Expansion (+5.9M Masks in 180k Images = 10.2M Total)

A generic single-class object detector trained on Stage 1 masks pre-filled images with confident prominent objects, directing human annotators to label smaller, less prominent objects (34 seconds per manual mask across 5 model retraining rounds), expanding density from 44 to 72 masks per image.

3
Stage 3 — Fully Automatic 32×32 Grid Prompting & Stability Filtering (1.1B Masks across 11M Images)

Prompting ambiguity-aware SAM with a 32×32 regular point grid on full images and overlapping zoomed-in crops generates whole, part, and subpart masks, retaining only confident masks (via the IoU head) and stable masks (where thresholding the probability map at $0.5 - \delta$ and $0.5 + \delta$ yields nearly identical polygons) followed by NMS deduplication. This produced SA-1B: 1.1 billion masks (~100 masks/image, 99.1% automatic, 400× more masks than Open Images), where 94% of audited pairs exceed 90% IoU and 97% exceed 75% IoU against human refinement (arXiv:2304.02643, Section 5).

Trained exclusively on the automatically generated masks of SA-1B (which matches full Stage 1+2+3 data within ~0.5 mIoU, Section 7.6), SAM delivers strong zero-shot generalization across 23 diverse datasets and 4 structural tasks via prompt engineering (arXiv:2304.02643, Tables 1–5):

  • Zero-Shot Single-Point Segmentation (23 Datasets, Section 7.1): Outperforms RITM on 16 of 23 datasets (by up to ~47 IoU), beats RITM on all 23 datasets under the 3-mask ambiguity oracle, achieves human mask quality ratings between 7 and 9 out of 10, and shows overlapping 95% confidence intervals across perceived gender (54.4 vs. 55.7 mIoU at 1 point; 90.4 vs. 90.1 at 3 points), age groups (90.2–92.6 mIoU at 3 points), and Fitzpatrick skin tones 1–6 (91.0–92.5 mIoU at 3 points, Table 2).
  • Zero-Shot Edge Detection on BSDS500 (Table 3): Prompted with a $16 \times 16$ grid (768 predicted masks) + Sobel filtering + edge NMS, SAM reaches 0.768 ODS / 0.786 OIS / 0.794 AP / 0.928 R50, crushing classical zero-shot Canny (0.600 ODS / 0.640 OIS / 0.580 AP) and Felzenszwalb-Huttenlocher (0.610 ODS) and approaching supervised HED (0.788 ODS / 0.923 R50) without ever seeing a BSDS500 training image.
  • Zero-Shot Object Proposals on LVIS v1 (Table 4) & Box-Prompted Instance Segmentation (Table 5): On LVIS v1 mask AR@1000, zero-shot SAM achieves 59.3 all / 45.5 small / 81.6 medium / 86.9 large / 59.1 frequent / 63.9 common / 65.8 rare—outperforming a fully-supervised ViTDet-H detector on medium (81.6 vs. 80.8), common (63.9 vs. 63.3), and rare categories (65.8 vs. 58.3), and gaining +4.4 AR overall over single-output SAM (54.9). When prompted with ViTDet-H bounding boxes (Table 5), zero-shot SAM achieves 46.5 mask AP on COCO and 44.7 mask AP on LVIS v1 (vs. supervised ViTDet-H's 51.0 and 46.6), while beating supervised ViTDet-H in human boundary quality studies (Figure 11) because SAM avoids COCO/LVIS polygon-simplification biases.

Promptable Visual Segmentation Across Time: Streaming Hiera Encoders, 2d-RoPE Memory Attention, and the SA-V 35.5M-Mask Dataset (SAM 2, arXiv:2408.00714v2)

While SAM solved promptable segmentation on static images, extending foundation segmentation to video requires resolving appearance deformation, camera motion blur, heavy occlusion, disappearance/re-appearance, and real-time throughput across thousands of frames. In SAM 2: Segment Anything in Images and Videos (arXiv:2408.00714v2, Meta FAIR, October 2024), Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu, Ronghang Hu, Chaitanya Ryali, et al. formulated Promptable Visual Segmentation (PVS)—treating a static image as a single-frame video and accepting positive/negative clicks, boxes, or masks on any frame to predict and iteratively refine a spatio-temporal masklet across the entire video (arXiv:2408.00714v2, Sections 3–4).

1. RPB-Free Hierarchical Hiera Backbone, 2d-RoPE Streaming Memory Attention, and Occlusion Heads

Unlike stitched SAM + XMem++ or SAM + Cutie pipelines—which must restart spatial segmentation from scratch whenever a tracker loses an object—SAM 2 processes video frames in a single unified streaming pass (arXiv:2408.00714v2, Section 4 & Appendix A.2, D.1):

  1. MAE Pre-Trained Hiera Multi-Scale Image Encoder (Zero Relative Positional Biases): Runs once per video frame at $1024 \times 1024$ resolution. Unlike SAM's isotropic ViT-H (which added expensive Relative Positional Biases RPB to every layer), SAM 2 uses a hierarchical Hiera encoder (Hiera-T, S, B+, L) with windowed absolute positional embeddings and removes all RPB from the image encoder (Table 10), unlocking FlashAttention-2 and making single-image segmentation $6\times$ faster than SAM (130.1 FPS vs. 21.7 FPS on A100) while improving SA-23 1-click accuracy from 58.1 to 58.9 mIoU on identical SA-1B training data (Table 5). An FPN fuses stride 16 and stride 32 features (Stages 3 & 4) into the per-frame embedding $\mathbf{F}_t$, while high-resolution stride 4 and stride 8 features (Stages 1 & 2) bypass memory attention via direct skip connections into the mask decoder's upsampling layers (Appendix D.1 & Figure 8).
  2. FIFO Memory Bank ($N=6$ Recent Frames, $M$ Prompted Frames, and $4 \times 64\text{-d}$ Object Pointers): After predicting a mask $\hat{\mathbf{M}}t$ on frame $t$, the Memory Encoder downsamples $\hat{\mathbf{M}}_t$ with a convolutional module, sums it element-wise with the unconditioned Hiera frame embedding $\mathbf{F}_t$ (reusing the Hiera backbone rather than running a second image encoder!), fuses them via lightweight convolutions, and projects the spatial memory feature map to $C{\text{mem}} = 64$ channels ($4\times$ smaller storage than 256-d with zero accuracy loss; Table 9d & Appendix D.1). The Memory Bank maintains: - A FIFO queue of spatial memories from up to $N = 6$ recent unprompted frames (embedded with temporal positional encodings to model short-term motion); - A FIFO queue of spatial memories from up to $M$ user-prompted frames (without temporal positional encodings so prompts generalize across arbitrary temporal distances); - A list of lightweight Object Pointers—taking each frame's 256-dim mask decoder output token and splitting it into 4 tokens of 64-dim—which boosts SA-V val accuracy from 64.5 to 68.3 $\mathcal{J}\&\mathcal{F}$ (+3.8 points) and long-term LVOSv2 val from 67.0 to 71.6 (+4.6 points) without needing a recurrent GRU (Table 11).
  3. $L = 4$ Memory Attention Blocks with 2d-RoPE and the Occlusion Prediction Head: Before entering the Two-Way Mask Decoder, current frame features $\mathbf{F}_t$ pass through $L = 4$ Memory Attention transformer blocks (each performing self-attention with 2d spatial Rotary Positional Embeddings 2d-RoPE, followed by 2d-RoPE cross-attention to the Memory Bank's spatial memories and un-rotated cross-attention to Object Pointers, followed by an MLP). Inside the Mask Decoder, SAM 2 adds a dedicated Occlusion Prediction Token and MLP Head that predicts the probability that the target object is visible in frame $t$ (Section 4 & Figure 8). Whenever an object is occluded/invisible, a learned occlusion embedding is added to that frame's memory features in the Memory Bank.

2. The 3-Phase Video Data Engine, SA-V (35.5M Masks), and State-of-the-Art VOS Benchmarks

Through its 3-phase interactive data engine (arXiv:2408.00714v2, Section 5.1 & Table 1), SAM 2 reduced per-frame video masklet annotation latency by $8.4\times$ while increasing mask alignment quality:

  • Phase 1 (Per-Frame SAM at 6 FPS + manual brush/eraser): Took 37.8 seconds/frame, required editing 100.00% of frames with 4.80 clicks per clicked frame, collecting 16K masklets across 1.4K videos (and defining the unbiased SA-V val split of 293 masklets / 155 videos and SA-V test split of 278 masklets / 150 videos).
  • Phase 2 (SAM + SAM 2 Mask temporal propagation): Dropped annotation time to 7.4 seconds/frame ($5.1\times$ speedup), reduced edited frames to 23.25% (3.61 clicks/frame), achieved 86.4% Phase 1 Mask Alignment ($\text{IoU} > 0.75$), and collected 63.5K masklets.
  • Phase 3 (Unified SAM 2 with interactive refinement clicks & memory): Cut annotation time to 4.5 seconds/frame ($8.4\times$ speedup over Phase 1), dropped edited frames to 19.04% (2.68 clicks/frame), lifted Phase 1 Mask Alignment to 89.1% (72.8% small, 81.8% medium, 100.0% large), and collected 197.0K manual masklets.

Combined with automatic first-frame grid masklet generation and human verification, the released SA-V dataset (Table 3) contains 50.9K crowd-captured videos (196.0 hours, 4.2M frames, 54% indoor / 46% outdoor, 14s average length), 642.6K masklets (190.9K manual + 451.7K auto), and 35.5 million masks (10.0M manual)—$53\times$ more masks ($15\times$ without auto) than the largest prior VOS dataset (UVO-dense at 667.1K masks or BURST at 600.2K masks)—with a 42.5% object disappearance/re-appearance rate on SA-V Manual.

Model / Method (`arXiv:2408.00714v2` Tables 4, 5, 6) 17 Zero-Shot VOS (1-Click / 3-Click / 5-Click / Box / GT Mask) MOSE val / DAVIS 2017 val / LVOS val ($\mathcal{J}\&\mathcal{F}$) SA-V val / SA-V test / YTVOS 2019 ($\mathcal{J}\&\mathcal{F}$ / $\mathcal{G}$) SA-23 All 1(5)-Click mIoU & A100 Speed
SAM (ViT-H, SA-1B only) — — — 58.1 (81.3) mIoU @ 21.7 image FPS
SAM + XMem++ (Modular Tracker Baseline) 56.9 / 68.4 / 70.6 / 67.6 / 72.7 59.6 / 86.0 / — (XMem) 60.1 / 62.3 / 85.6 (XMem) —
SAM + Cutie / Cutie-base+ 56.7 / 70.1 / 72.2 / 69.4 / 74.1 71.7 / 88.1 / 66.0 (base) 61.3 / 62.8 / 87.5 —
SAM 2 (Hiera-B+, SA-1B + Video Mix) 64.7 / 75.3 / 77.6 / 74.4 / 79.3 76.6 / 90.2 / 78.0 76.8 / 77.0 / 88.6 61.9 (83.5) @ 130.1 img / 43.8 vid FPS
SAM 2 (Hiera-L, SA-1B + Video Mix) — 77.9 / 90.7 / 78.0 77.9 / 78.4 / 89.3 30.2 video FPS on single A100

Synthetic-to-Real Monocular Depth Foundation Models: 595K Synthetic Teacher, 62M Pseudo-Labeled Real Bridge, and DA-2K (Depth Anything V2, arXiv:2406.09414v2)

In Depth Anything V2 (arXiv:2406.09414v2, NeurIPS 2024), Lihe Yang, Bingyi Kang, Zilong Huang, Zhen Zhao, Xiaogang Xu, Jiashi Feng, and Hengshuang Zhao resolved a central paradox in Monocular Depth Estimation (MDE): why did heavyweight generative diffusion depth models like Marigold (CVPR 2024, built on Stable Diffusion) produce crisp thin-structure geometry (basketball nets, chair legs) and valid transparent/reflective depth while lightweight discriminative encoders (MiDaS V3.1 and Depth Anything V1) produced over-smoothed boundaries and failed on glass and mirrors?

Monocular Depth Map Estimation and 3D Geometric Silhouette Reconstruction Pipeline (Wikimedia Commons CC BY-SA 4.0)
From Noisy Sensor Depth to Pixel-Exact Synthetic-to-Real Distillation: Real RGB-D sensors (NYU-D), stereo matchers (HRWSI, DIML), and Structure-from-Motion pipelines (MegaDepth) systematically fail on transparent glass, specular mirrors, and fine mesh holes. Depth Anything V2 (`arXiv:2406.09414v2`) trains a 1.3B DINOv2-G teacher purely on 595K synthetic images and bridges the real-world domain gap via 62M pseudo-labeled real images (Arsi Warrior, Wikimedia Commons, CC BY-SA 4.0, verified HTTP 200).

1. Why Real Labeled Depth Corrupts Fine Geometry—and Why Direct Synthetic Training Fails on Small Encoders

Yang et al. (arXiv:2406.09414v2, Sections 2–3) proved that the coarse boundaries of discriminative MDE models do not stem from discriminative modeling itself, but from label noise and ignored details in real labeled depth datasets:

  1. Three Hardware Failure Modes in Real "Ground-Truth" Depth (Figure 3 & Figure 4): - Active infrared/ToF depth sensors (NYU-D) shoot right through transparent glass and reflect erroneously off mirrors; - Stereo matching algorithms (HRWSI, DIML) hallucinate false disparities on textureless walls and repetitive patterns; - Multi-view SfM (MegaDepth) produces outliers on dynamic objects and blurs thin structures (leaves, wire mesh, chair legs). As a result, MiDaS and Depth Anything V1 score only 25.9% and 53.5% on the Transparent Surface Challenge (Section 2).
  2. Why Naive Synthetic-Only Training Fails (Section 3, Figures 5–6): Graphics engine synthetic datasets carry pixel-exact ground-truth depth for every leaf, hole, glass vase, and mirror, yet suffer from (i) color/layout distribution shift (too clean and ordered compared to in-the-wild photos) and (ii) restricted scene coverage (fixed living rooms and street scenes lacking crowded humans or diverse cloud/sky formations). When Yang et al. trained four vision encoders (BEiT, SAM, SynCLR, and DINOv2) purely on synthetic images, only the 1.3B-parameter DINOv2-G achieved acceptable synthetic-to-real transfer, while smaller DINOv2-S/B/L models and all other encoders collapsed—and even DINOv2-G failed on underrepresented real-world sky clouds and human heads (Figure 6). Worse still, mixing real labeled images with synthetic images destroys fine-grained boundary sharpness (Section 3 & Section B.9).

2. The 3-Stage Teacher-Pseudo-Student Pipeline, 1:2 Gradient-Matching Loss, and Top-10% Loss Masking

Depth Anything V2 solves both precision and scene coverage without compromise via a 3-stage pipeline built on DINOv2 encoders + DPT depth decoders trained at $518 \times 518$ resolution (arXiv:2406.09414v2, Sections 4, 5, 7.1 & Table 7):

  1. Stage 1 — 1.3B DINOv2-G Teacher Trained Purely on 595K Synthetic Images: Trained with batch size 64 for 160K iterations (Adam optimizer, encoder lr $5\times 10^{-6}$, decoder lr $5\times 10^{-5}$) across five concatenated synthetic datasets totaling 595,000 images: BlendedMVS (115K, indoor/outdoor bird's-eye), Hypersim (60K, indoor), IRS (103K, indoor), TartanAir (306K, indoor/outdoor), and VKITTI 2 (20K, outdoor fine foliage). The teacher predicts affine-invariant inverse depth $d$ supervised by a 1:2 weighted combination of scale-and-shift-invariant loss $\mathcal{L}{\text{ssi}}$ and multi-scale gradient-matching loss $\mathcal{L}{\text{gm}}$ (Section 5.2 & Section 7.1):

$$\mathcal{L}{\text{teacher}} = 1.0\,\mathcal{L}{\text{ssi}}\big(\hat{d}, d^\big) + 2.0\,\mathcal{L}_{\text{gm}}\big(\hat{d}, d^\big)$$

Because synthetic depth maps have noise-free object boundaries, weighting the gradient-matching term $\mathcal{L}{\text{gm}}$ at $2\times$ $\mathcal{L}{\text{ssi}}$ directly sharpens sub-pixel depth discontinuities (Section 5.2 & Section B.7).

  1. Stage 2 — Labeling 62 Million Unlabeled Real Images Across 8 Public Datasets: The frozen 1.3B synthetic teacher assigns dense pseudo-depth maps to 62,000,000 raw real images: ImageNet-21K (13.1M), SA-1B (11.1M), LSUN (9.8M), BDD100K (8.2M), Open Images V7 (7.8M), Places365 (6.5M), Google Landmarks (4.1M), and Objects365 (1.7M) (Table 7).
  2. Stage 3 — Student Distillation Purely on 62M Pseudo-Labeled Real Images (25M ViT-S to 1.3B ViT-G): Four student scales (ViT-S 25M, ViT-B, ViT-L, ViT-G 1.3B) are trained exclusively on the 62M pseudo-labeled real images (batch size 192 for 480K iterations)—removing synthetic images entirely during student training, which actually improves ViT-S DA-2K accuracy from 94.1% to 95.3% and ViT-B from 96.7% to 97.0% (Table 5). For every pseudo-labeled image, the top $n = 10\%$ largest-loss pixels are masked out as potentially noisy pseudo-labels, while a DINOv2 feature alignment loss preserves semantic awareness (Section 5.2).
⚡ Empirical Proof: Synthetic Teacher Pseudo-Labels Crush Real Sensor Manual Labels on Identical Images (`Table 6`)

To prove that their synthetic teacher's pseudo-labels are superior to physical RGB-D / stereo ground truth, Yang et al. took the exact same real images from the DIML dataset and trained two identical models: one on DIML's original manual depth labels, and one on Depth Anything V2's pseudo-labels (arXiv:2406.09414v2, Table 6). Replacing real manual labels with synthetic-teacher pseudo-labels cut KITTI AbsRel error from 0.122 to 0.099 ($\delta_1$: 0.882 → 0.901), NYU-D AbsRel from 0.074 to 0.062 ($\delta_1$: 0.952 → 0.963), Sintel AbsRel from 0.581 to 0.514, ETH3D AbsRel from 0.159 to 0.147, DIODE AbsRel from 0.126 to 0.084 ($\delta_1$: 0.890 → 0.929), and boosted DA-2K relative depth accuracy by +9.5 percentage points (80.2% → 89.7%).

Depth Model & Backbone (`arXiv:2406.09414v2` Tables 2, 3, 4, 8) DA-2K Benchmark Accuracy (%) Zero-Shot KITTI / NYU-D / DIODE (AbsRel↓ | $\delta_1$↑) Metric NYU-D ($\delta_1$↑ / AbsRel↓ / RMSE↓) Metric KITTI ($\delta_1$↑ / AbsRel↓ / RMSE↓) Mask2Former Segm. (Cityscapes / ADE20K mIoU)
Marigold (Stable Diffusion Denominator) 86.8% — — — —
GeoWizard / DepthFM (Generative SD / FM) 88.1% / 85.8% — — — —
MiDaS V3.1 (ViT-L) / ZoeDepth (ViT-L) 25.9% Transp. 0.127|0.850 / 0.048|0.980 / 0.075|0.942 0.951 / 0.077 / 0.282 (Zoe) 0.971 / 0.054 / 2.281 (Zoe) —
Depth Anything V1 (ViT-L, 1.5M real + 62M) 88.5% (53.5% Transp.) 0.076|0.947 / 0.043|0.981 / 0.066|0.952 — — —
Depth Anything V2 (ViT-S, 25M params) 95.3% 0.078|0.936 / 0.053|0.973 / 0.073|0.942 0.961 / 0.073 / 0.261 0.973 / 0.053 / 2.235 82.9 / 53.9 mIoU
Depth Anything V2 (ViT-B) 97.0% 0.078|0.939 / 0.049|0.976 / 0.068|0.950 0.977 / 0.063 / 0.228 0.979 / 0.048 / 1.999 83.9 / 57.1 mIoU
Depth Anything V2 (ViT-L) 97.1% (83.6% Transp.) 0.074|0.946 / 0.045|0.979 / 0.066|0.952 0.984 / 0.056 / 0.206 0.983 / 0.045 / 1.861 85.6 / 58.6 mIoU
Depth Anything V2 (ViT-G, 1.3B params) 97.4% 0.075|0.948 / 0.044|0.979 / 0.065|0.954 — — —

Reference PyTorch Implementation: MAE Shuffle-Unshuffle Masking, DINOv2 KoLeo + Sinkhorn-Knopp Loss, SAM 3-Mask Ambiguity Loss, and Depth Anything V2 Top-10%-Masked Gradient Matching

The following self-contained PyTorch module implements the exact mathematical primitives of all five vision foundation architectures:

  1. MAE Zero-Sparse-Op Patch Shuffling, Visible-Only Encoding, and Per-Patch Normalized Masked MSE (arXiv:2111.06377, Section 3);
  2. DINOv2 3-Iteration Sinkhorn-Knopp Teacher Centering and Kozachenko-Leonenko (KoLeo) Differential Entropy Regularization (arXiv:2304.07193, Section 4);
  3. SAM / SAM 2 Hindsight Minimum-Loss Ambiguity Resolution (Focal + Dice + IoU Head) with Streaming Memory Bank FIFO Queues (arXiv:2304.02643, Section 3 & arXiv:2408.00714v2, Section 4);
  4. Depth Anything V2 Scale-and-Shift-Invariant ($\mathcal{L}{\text{ssi}}$) + Multi-Scale Gradient-Matching ($\mathcal{L}{\text{gm}}$) Loss with Top-10% Noisy Pseudo-Label Trimming (arXiv:2406.09414v2, Section 5.2).
from __future__ import annotations

from collections import deque
from dataclasses import dataclass, field
from typing import Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F

# ============================================================================
# 1. MAE: Zero-Sparse-Op Shuffle/Unshuffle & Per-Patch Normalized Masked MSE
#    (He et al., arXiv:2111.06377, Section 3)
# ============================================================================
def mae_random_masking(
    x: torch.Tensor,
    mask_ratio: float = 0.75,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Randomly keep (1 - mask_ratio) visible patches without replacement.

    Args:
        x: Patch token tensor of shape (B, N, D_enc) with positional embeddings added.
        mask_ratio: Fraction of patches removed before encoder (default 0.75 -> 25% visible).

    Returns:
        x_vis: Visible patch subset of shape (B, N_vis, D_enc) entering the ViT encoder.
        mask: Binary mask in original spatial order (B, N), where 1 = masked, 0 = visible.
        ids_restore: Inverse permutation indices (B, N) used to unshuffle tokens for decoder.
    """
    bsz, num_patches, dim = x.shape
    num_vis = int(num_patches * (1.0 - mask_ratio))

    noise = torch.rand(bsz, num_patches, device=x.device)
    ids_shuffle = torch.argsort(noise, dim=1)
    ids_restore = torch.argsort(ids_shuffle, dim=1)

    ids_keep = ids_shuffle[:, :num_vis]
    x_vis = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, dim))

    mask = torch.ones(bsz, num_patches, device=x.device)
    mask[:, :num_vis] = 0.0
    mask = torch.gather(mask, dim=1, index=ids_restore)
    return x_vis, mask, ids_restore

def mae_normalized_pixel_loss(
    pred_patches: torch.Tensor,
    target_patches: torch.Tensor,
    mask: torch.Tensor,
    norm_pix_loss: bool = True,
    eps: float = 1e-6,
) -> torch.Tensor:
    """Compute MAE MSE reconstruction loss strictly on masked patches (Table 1d).

    Args:
        pred_patches: Decoder pixel predictions of shape (B, N, P*P*C).
        target_patches: Ground-truth image patches of shape (B, N, P*P*C).
        mask: Binary mask of shape (B, N), 1 = masked patch, 0 = visible patch.
        norm_pix_loss: Normalize each target patch by its local pixel mean and std.

    Returns:
        Scalar MSE loss averaged exclusively over the masked patches.
    """
    if norm_pix_loss:
        mean = target_patches.mean(dim=-1, keepdim=True)
        var = target_patches.var(dim=-1, unbiased=True, keepdim=True)
        target_patches = (target_patches - mean) / torch.sqrt(var + eps)

    per_patch_mse = ((pred_patches - target_patches) ** 2).mean(dim=-1)  # (B, N)
    return (per_patch_mse * mask).sum() / mask.sum().clamp(min=1.0)

# ============================================================================
# 2. DINOv2: 3-Iteration Sinkhorn-Knopp Centering & KoLeo Entropy Regularizer
#    (Oquab et al., arXiv:2304.07193, Section 4)
# ============================================================================
@torch.no_grad()
def sinkhorn_knopp_teacher_centering(
    teacher_logits: torch.Tensor,
    temp_t: float = 0.04,
    num_iters: int = 3,
) -> torch.Tensor:
    """Apply 3-iteration Sinkhorn-Knopp batch normalization to teacher prototype scores.

    Args:
        teacher_logits: Raw teacher prototype logits of shape (B, K) where K = 128,000.
        temp_t: Teacher softmax temperature.
        num_iters: Number of alternating row/column normalization steps (default 3).

    Returns:
        Centered doubly-stochastic teacher probability distribution p_t of shape (B, K).
    """
    bsz, num_prototypes = teacher_logits.shape
    q = torch.exp(teacher_logits / temp_t).t()  # (K, B)
    q = q / q.sum().clamp(min=1e-12)

    for _ in range(num_iters):
        # Row normalization across prototypes K
        q = q / (q.sum(dim=1, keepdim=True).clamp(min=1e-12) * num_prototypes)
        # Column normalization across batch samples B
        q = q / (q.sum(dim=0, keepdim=True).clamp(min=1e-12) * bsz)

    return (q * bsz).t()  # (B, K), each row sums to 1.0

def koleo_entropy_regularizer(features: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
    """Kozachenko-Leonenko (KoLeo) differential entropy estimator (arXiv:2304.07193, Sec 4).

    L_koleo = - (1 / n) * sum_{i=1}^n log(min_{j != i} ||x_i - x_j||_2)
    on L2-normalized batch features.
    """
    x = F.normalize(features, p=2, dim=-1)  # (B, D)
    pairwise_dist = torch.cdist(x, x, p=2)  # (B, B)
    bsz = x.shape[0]
    eye_mask = torch.eye(bsz, device=x.device, dtype=torch.bool)
    pairwise_dist = pairwise_dist.masked_fill(eye_mask, float("inf"))
    min_dist, _ = pairwise_dist.min(dim=1)
    return -torch.log(min_dist + eps).mean()

# ============================================================================
# 3. SAM & SAM 2: 3-Mask Hindsight Minimum-Loss & Streaming Memory Bank FIFO
#    (Kirillov et al., arXiv:2304.02643 & Ravi et al., arXiv:2408.00714v2)
# ============================================================================
def sam_ambiguity_aware_loss(
    pred_mask_logits: torch.Tensor,
    pred_ious: torch.Tensor,
    gt_mask: torch.Tensor,
    focal_weight: float = 20.0,
    dice_weight: float = 1.0,
) -> torch.Tensor:
    """Backpropagate only the minimum loss across K=3 nested mask predictions (Whole/Part/Subpart).

    Args:
        pred_mask_logits: Predicted mask logits of shape (B, K=3, H, W).
        pred_ious: Predicted IoU confidence scores in [0, 1] of shape (B, K=3).
        gt_mask: Ground-truth binary mask of shape (B, 1, H, W).

    Returns:
        Scalar combined loss (minimum Focal+Dice mask loss + L1 IoU supervision loss).
    """
    bsz, num_masks, h, w = pred_mask_logits.shape
    gt_expanded = gt_mask.expand(-1, num_masks, -1, -1)

    probs = torch.sigmoid(pred_mask_logits)
    # Dice loss per candidate mask (B, K)
    inter = (probs * gt_expanded).flatten(2).sum(dim=-1)
    union = probs.flatten(2).sum(dim=-1) + gt_expanded.flatten(2).sum(dim=-1)
    dice_loss = 1.0 - (2.0 * inter + 1.0) / (union + 1.0)

    # Focal loss per candidate mask (B, K)
    bce = F.binary_cross_entropy_with_logits(pred_mask_logits, gt_expanded, reduction="none")
    p_t = probs * gt_expanded + (1.0 - probs) * (1.0 - gt_expanded)
    focal_loss = ((1.0 - p_t) ** 2 * bce).flatten(2).mean(dim=-1)

    total_mask_loss = focal_weight * focal_loss + dice_weight * dice_loss  # (B, K)
    min_mask_loss, _ = total_mask_loss.min(dim=1)  # Hindsight minimum over K=3 masks

    # True IoU for L1 IoU supervision (SAM 2 uses L1 loss on sigmoid IoU predictions, Sec D.2.1)
    pred_bin = (probs > 0.5).float()
    iou_inter = (pred_bin * gt_expanded).flatten(2).sum(dim=-1)
    iou_union = (pred_bin + gt_expanded - pred_bin * gt_expanded).flatten(2).sum(dim=-1)
    true_ious = (iou_inter + 1e-6) / (iou_union + 1e-6)
    iou_loss = F.l1_loss(pred_ious, true_ious)

    return min_mask_loss.mean() + iou_loss

@dataclass
class SAM2StreamingMemoryBank:
    """SAM 2 FIFO Memory Bank storing N=6 recent frames, M prompted frames, and 4x64-d Object Pointers."""

    max_recent_frames: int = 6
    max_prompted_frames: int = 8
    recent_memories: deque = field(init=False)
    prompted_memories: deque = field(init=False)
    object_pointers: deque = field(init=False)

    def __post_init__(self) -> None:
        self.recent_memories = deque(maxlen=self.max_recent_frames)
        self.prompted_memories = deque(maxlen=self.max_prompted_frames)
        self.object_pointers = deque(maxlen=self.max_recent_frames + self.max_prompted_frames)

    def write_frame_memory(
        self,
        spatial_memory_64d: torch.Tensor,
        mask_output_token_256d: torch.Tensor,
        occlusion_logit: torch.Tensor,
        occlusion_embedding_64d: torch.Tensor,
        is_prompted: bool,
    ) -> None:
        """Store 64-d spatial memory and 4x64-d object pointer tokens (arXiv:2408.00714v2, Sec 4 & D.1)."""
        is_occluded = (torch.sigmoid(occlusion_logit) < 0.5).float().view(-1, 1, 1, 1)
        conditioned_mem = spatial_memory_64d + is_occluded * occlusion_embedding_64d

        if is_prompted:
            self.prompted_memories.append(conditioned_mem)
        else:
            self.recent_memories.append(conditioned_mem)

        # Split 256-dim mask decoder output token into 4 object pointer tokens of 64-dim
        bsz = mask_output_token_256d.shape[0]
        pointer_tokens = mask_output_token_256d.view(bsz, 4, 64)
        self.object_pointers.append(pointer_tokens)

# ============================================================================
# 4. Depth Anything V2: 1:2 SSI + Gradient-Matching Loss & Top-10% Loss Masking
#    (Yang et al., arXiv:2406.09414v2, Section 5.2 & Section 7.1)
# ============================================================================
def depth_anything_v2_loss(
    pred_depth: torch.Tensor,
    target_depth: torch.Tensor,
    is_pseudo_labeled: bool = True,
    top_loss_ignore_ratio: float = 0.10,
) -> torch.Tensor:
    """Compute 1:2 weighted Scale-Shift-Invariant (L_ssi) + Gradient-Matching (L_gm) loss.

    For pseudo-labeled real images (62M corpus), ignores the top-10% largest-loss regions.
    """
    bsz, _, h, w = pred_depth.shape
    pred_flat = pred_depth.view(bsz, -1)
    targ_flat = target_depth.view(bsz, -1)

    # Scale- and shift-invariant alignment via median and mean absolute deviation
    def align_ssi(d: torch.Tensor) -> torch.Tensor:
        t_d = torch.median(d, dim=1, keepdim=True).values
        s_d = (d - t_d).abs().mean(dim=1, keepdim=True).clamp(min=1e-6)
        return (d - t_d) / s_d

    pred_aligned = align_ssi(pred_flat).view(bsz, 1, h, w)
    targ_aligned = align_ssi(targ_flat).view(bsz, 1, h, w)

    pixel_error = (pred_aligned - targ_aligned).abs()  # (B, 1, H, W)
    if is_pseudo_labeled and top_loss_ignore_ratio > 0.0:
        # Mask out top-10% largest-loss regions per sample as potential pseudo-label noise
        flat_err = pixel_error.view(bsz, -1)
        cutoff_idx = int(flat_err.shape[1] * (1.0 - top_loss_ignore_ratio))
        sorted_err, _ = torch.sort(flat_err, dim=1)
        thresholds = sorted_err[:, cutoff_idx : cutoff_idx + 1].view(bsz, 1, 1, 1)
        valid_mask = (pixel_error <= thresholds).float()
    else:
        valid_mask = torch.ones_like(pixel_error)

    l_ssi = (pixel_error * valid_mask).sum() / valid_mask.sum().clamp(min=1.0)

    # Multi-scale spatial gradient matching loss L_gm across 4 dyadic resolution scales
    l_gm = torch.tensor(0.0, device=pred_depth.device)
    for scale in range(4):
        step = 2 ** scale
        diff = (pred_aligned - targ_aligned) * valid_mask
        grad_x = (diff[:, :, :, step:] - diff[:, :, :, :-step]).abs().mean()
        grad_y = (diff[:, :, step:, :] - diff[:, :, :-step, :]).abs().mean()
        l_gm = l_gm + (grad_x + grad_y) / 4.0

    # Weight ratio L_ssi : L_gm = 1 : 2 (arXiv:2406.09414v2, Section 7.1)
    return 1.0 * l_ssi + 2.0 * l_gm

Production Engineering Blueprint: Composing Vision Foundation Models in Real-Time Systems

When architecting production visual perception pipelines in 2026, combining the complementary strengths of MAE, DINOv2, SAM / SAM 2, and Depth Anything V2 follows four empirical design rules:

  1. Use DINOv2 Frozen Backbones for Zero-Fine-Tuning Retrieval, Linear Probing, and Dense Feature Adapters, and MAE When Full End-to-End Task Fine-Tuning Is Budgeted: As demonstrated in arXiv:2304.07193 (Tables 4, 9, 10, 11), DINOv2 features work out-of-the-box without touching backbone weights—achieving 86.5% ImageNet-1K linear accuracy, 54.0% Oxford-Hard instance retrieval mAP (vs. 2.2% for frozen MAE and 19.7% for OpenCLIP-G), and 0.279 NYUd depth RMSE. Conversely, when pre-training a brand-new architecture (such as Hiera inside SAM 2 or a domain-specific medical/satellite ViT) from scratch for end-to-end supervised fine-tuning, MAE's 75% visible-only pre-training provides a $3.3\times$ FLOP reduction and $2.8\times\text{–}4.1\times$ wall-clock speedup (arXiv:2111.06377, Table 2).
  2. Replace Vanilla SAM (ViT-H) with SAM 2 (Hiera-B+ or Hiera-L) Even for Static Single-Image Segmentation: SAM 2 treats a static image as a 1-frame video with an empty Memory Bank (arXiv:2408.00714v2, Section 1 & Section 6.3). Because SAM 2 replaces SAM's RPB-heavy ViT-H with an RPB-free hierarchical Hiera encoder compatible with FlashAttention-2 and stride-4/8 high-resolution skip connections, SAM 2 (Hiera-B+) achieves higher single-image zero-shot accuracy (61.9 vs. 58.1 1-click mIoU on SA-23) while running $6\times$ faster (130.1 FPS vs. 21.7 FPS on A100; Table 5).
  3. Never Train or Fine-Tune Fine-Grained Monocular Depth Models on Raw Real RGB-D / Stereo Sensor Datasets: As Depth Anything V2 (arXiv:2406.09414v2, Sections 2–4 & Table 6) proved, mixing real sensor depth (NYU-D, DIML, HRWSI) into training corrupts transparent glass, specular mirrors, and thin mesh structures. Always generate dense pseudo-depth using the synthetic-trained DINOv2-G teacher or fine-tune metric depth heads on pixel-exact synthetic benchmarks (Hypersim for indoor, Virtual KITTI 2 for outdoor; Section 7.3).
  4. Couple SAM 2 Object Pointers with Depth Anything V2 Metric Depth for 2.5D/3D Embodied Perception: Prompting SAM 2 to segment and track target masklets at 43.8 FPS (Hiera-B+) while running Depth Anything V2 (ViT-S, 25M params, 95.3% DA-2K accuracy) in parallel yields real-time occlusion-aware 3D object masks with reliable depth across glass doors, mirrors, and thin manipulators.

Frequently Asked Questions (FAQ)

1. Why does MAE mask 75% of image patches during pre-training whereas BERT only masks 15% of word tokens—and why must [M] mask tokens be excluded from the MAE encoder? Natural images exhibit heavy spatial redundancy where a missing patch can be extrapolated from neighboring patches without high-level object understanding, whereas human language is information-dense (arXiv:2111.06377, Section 1). Masking 75% of random patches eliminates local interpolation shortcuts and creates a holistic gestalt reconstruction task, boosting ViT-L/16 linear probing from 54.6% to 73.5% (Section 4.1, Figure 5). Excluding [M] mask tokens from the encoder constrains the encoder to process only the 25% visible real patches, cutting total training FLOPs by $3.3\times$, accelerating wall-clock training by $2.8\times$ to $4.1\times$ (Table 1c & Table 2), and avoiding a pretrain-deploy distribution gap that otherwise collapses linear probing accuracy by -13.9 percentage points (from 73.5% down to 59.6%).

2. Why does MAE perform strongly without data augmentation or discrete dVAE tokenization? In contrastive learning (SimCLR, BYOL), two views of an unaugmented image are identical and collapse to a trivial solution; removing color jittering drops SimCLR accuracy by 28% (arXiv:2111.06377, Section 4.1). In MAE, random 75% patch masking generates a different sparse training view every iteration, enabling ViT-L/16 to achieve 84.0% fine-tuning accuracy with zero data augmentation (center-crop only) and 84.9% with cropping-only augmentation (Table 1e). Furthermore, predicting per-patch locally normalized pixels (85.4% ft / 73.9% lin, Table 1d) matches or outperforms predicting discrete dVAE tokens (85.3% ft / 71.6% lin, Table 7) while eliminating the need for an extra 250M-image dVAE pre-training stage and saving 40% of ViT-L's FLOPs in convolutional tokenizer overhead.

3. How does DINOv2 build the LVD-142M dataset without human labels or text metadata, and what does the KoLeo regularizer do? DINOv2 starts from 1.2 billion unique web images, removes near-duplicates and benchmark test/val leaks via copy detection, embeds images using a self-supervised ViT-H/16 pretrained on ImageNet-22k, clusters the uncurated pool with GPU-accelerated Faiss inverted-file product quantization indices, and retrieves the $N=4$ nearest neighbors per query image from curated seed datasets (ImageNet-22k, ImageNet-1k, Google Landmarks, and fine-grained datasets) in under 2 days on 20 nodes of 8 V100-32GB GPUs (arXiv:2304.07193, Section 3). During training, the Kozachenko-Leonenko (KoLeo) differential entropy regularizer $\mathcal{L}{\text{koleo}} = -\frac{1}{n}\sum{i=1}^n \log(\min_{j \neq i}\|\hat{\mathbf{x}}_i - \hat{\mathbf{x}}_j\|_2)$ forces $\ell_2$-normalized features within each batch to spread uniformly across the representation space, boosting Oxford-Medium instance retrieval mAP by +8.3 points (55.6% $\to$ 63.9%) (Table 3a).

4. Why do frozen DINOv2 features outperform weakly-supervised OpenCLIP ViT-G/14 (trained on 2 billion text-image pairs) on dense segmentation, depth estimation, and instance retrieval? Image captions only approximate global scene semantics and omit fine pixel-level boundaries, 3D geometry, and instance-specific details (arXiv:2304.07193, Section 1 & Section 7.4). By combining image-level DINO loss with patch-level iBOT masked image modeling across untied heads (+2.9 mIoU on ADE20K from MIM, Table 3b) and a short $518 \times 518$ high-resolution phase, frozen DINOv2 ViT-g/14 outperforms frozen OpenCLIP ViT-G/14 by +9.7/+7.0 mIoU on ADE20K (49.0/53.0 vs. 39.3/46.0, Table 10), cuts NYUd DPT depth RMSE from 0.414 to 0.279 (Table 11), boosts Oxford-Hard landmark retrieval mAP by +34.3 points (54.0% on ViT-L/14 vs. 19.7%, Table 9), and surpasses OpenCLIP-G on iNaturalist-2018/2021 by +8.6% and +9.7% (Table 7).

5. How does Segment Anything (SAM) resolve single-point prompt ambiguity and execute interactive mask prediction in ~50 ms inside a web browser? First, SAM amortizes heavy computation by running its MAE pre-trained ViT-H/16 image encoder only once per image; given the precomputed image embedding, the lightweight Prompt Encoder and 2-block Two-Way Transformer Mask Decoder run in ~50 ms on a browser CPU (arXiv:2304.02643, Section 3). Second, because a single point can validly refer to a whole object, a part, or a subpart, SAM predicts $K=3$ nested mask outputs per prompt and backpropagates only the minimum loss (linear combination of Focal Loss and Dice Loss) across the 3 predictions while training an IoU confidence head to rank them (Section 3). In LVIS v1 zero-shot object proposal ablations (Table 4), this 3-mask ambiguity-aware design improves mask AR@1000 from 54.9 to 59.3 overall and from 74.4 to 86.9 on large objects.

6. How does SAM 2 achieve $6\times$ faster image segmentation than SAM while tracking video objects through full occlusions at 43.8 FPS? SAM 2 replaces SAM's isotropic ViT-H encoder with an MAE pre-trained hierarchical Hiera image encoder that removes all Relative Positional Biases (RPB) to enable FlashAttention-2 and feeds high-resolution stride-4 and stride-8 features directly to mask decoder upsampling layers (arXiv:2408.00714v2, Section 4 & Appendix A.2.2, D.1)—increasing single-image speed on an A100 GPU by $6\times$ (130.1 FPS vs. 21.7 FPS) while raising SA-23 1-click accuracy from 58.1 to 61.9 mIoU (Table 5). For video streaming (43.8 FPS on Hiera-B+ and 30.2 FPS on Hiera-L, Section 7), SAM 2 conditions each frame via $L=4$ 2d-RoPE Memory Attention blocks on a FIFO Memory Bank ($N=6$ recent frames, $M$ prompted frames, 64-d spatial features, and $4 \times 64\text{-d}$ Object Pointers) and uses a dedicated Occlusion Prediction Head to inject learned occlusion embeddings when an object temporarily disappears (Section 4 & Appendix D.1).

7. Why does Depth Anything V2 replace all labeled real depth images with 595K synthetic images and train student models exclusively on 62M pseudo-labeled real images? Real depth datasets created via depth sensors (NYU-D), stereo matching (HRWSI, DIML), or SfM (MegaDepth) contain heavy label noise on transparent objects, reflective mirrors, textureless surfaces, and thin structures—causing MiDaS and Depth Anything V1 to score only 25.9% and 53.5% on the Transparent Surface Challenge (arXiv:2406.09414v2, Section 2). Conversely, synthetic images (BlendedMVS, Hypersim, IRS, TartanAir, VKITTI 2 = 595K images) provide pixel-exact ground truth for fine meshes and glass, but suffer from domain shift and narrow scene diversity when training small models directly (Section 3). By training a 1.3B DINOv2-G teacher purely on the 595K synthetic images ($\mathcal{L}{\text{ssi}} : \mathcal{L}{\text{gm}} = 1:2$) and using it to generate dense pseudo-labels across 62M diverse real images, student models (25M ViT-S to 1.3B ViT-G) trained purely on pseudo-labeled real images reach 83.6% on transparent surfaces and 95.3% to 97.4% on DA-2K (Tables 3, 5, 7).

8. How does Depth Anything V2 compare against diffusion-based Marigold and metric depth baselines like ZoeDepth? On the high-resolution 8-scenario DA-2K benchmark (arXiv:2406.09414v2, Table 3), even the smallest 25M-parameter Depth Anything V2 (ViT-S) achieves 95.3% accuracy and ViT-G achieves 97.4%, outperforming Stable-Diffusion-based Marigold (86.8%) by +10.6 percentage points and GeoWizard (88.1%) by +9.3 percentage points while running more than $10\times$ faster. When fine-tuned for in-domain metric depth (Table 4), Depth Anything V2 (ViT-L) achieves $\delta_1 = 0.984, \text{AbsRel} = 0.056, \text{RMSE} = 0.206$ on NYU-D (vs. ZoeDepth's $0.951 / 0.077 / 0.282$) and $\delta_1 = 0.983, \text{AbsRel} = 0.045, \text{RMSE} = 1.861$ on KITTI (vs. ZoeDepth's $0.971 / 0.054 / 2.281$).


Sources

  1. Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, & Ross Girshick (Facebook AI Research / FAIR, CVPR 2022): Masked Autoencoders Are Scalable Vision Learners (MAE, 75% random patch masking, visible-only ViT encoder without mask tokens, lightweight 8-block 512-d decoder at 9% FLOPs/token, $3.3\times$ FLOP reduction, $2.8\times\text{–}4.1\times$ TPU-v3 wall-clock speedup, 87.8% ImageNet-1K top-1 accuracy with ViT-H/14 at $448 \times 448$, COCO Mask R-CNN 53.3 $\text{AP}^{\text{box}}$ / 47.2 $\text{AP}^{\text{mask}}$, ADE20K 53.6 mIoU) — https://ar5iv.labs.arxiv.org/html/2111.06377 and https://arxiv.org/abs/2111.06377
  2. Maxime Oquab, Timothée Darcet, Théo Moutakanni, Huy V. Vo, Marc Szafraniec, Vasil Khalidov, et al. (Meta AI Research & Inria, TMLR 2024): DINOv2: Learning Robust Visual Features without Supervision (DINOv2, automated Faiss GPU retrieval pipeline curating 1.2B web images into LVD-142M in $<2$ days, 1.1B ViT-g/14 architecture with 1536-d / 24 heads, untied DINO + iBOT heads, 3-iteration Sinkhorn-Knopp centering, KoLeo differential entropy regularizer, 86.5% frozen linear probe on ImageNet-1K and 75.9% on ImageNet-A) — https://ar5iv.labs.arxiv.org/html/2304.07193 and https://arxiv.org/abs/2304.07193
  3. Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alexander C. Berg, Wan-Yen Lo, Piotr Dollár, & Ross Girshick (Meta AI Research / FAIR, ICCV 2023): Segment Anything (SAM, promptable segmentation task, ~50 ms browser Two-Way Transformer mask decoder predicting 3 ambiguity-aware masks under minimum Focal+Dice loss, 3-stage data engine producing SA-1B with 1.1B masks across 11M images, 94% $>90\%$ IoU audit quality, and 23-dataset zero-shot transfer benchmarks) — https://ar5iv.labs.arxiv.org/html/2304.02643 and https://arxiv.org/abs/2304.02643
  4. Nikhila Ravi, Valentin Gabeur, Yuan-Ting Hu, Ronghang Hu, Chaitanya Ryali, Tengyu Ma, Haitham Khedr, Roman Rädle, Chloe Rolland, Laura Gustafson, Eric Mintun, Junting Pan, Kalyan Vasudev Alwala, Nicolas Carion, Chao-Yuan Wu, Ross Girshick, Piotr Dollár, & Christoph Feichtenhofer (Meta FAIR, 2024): SAM 2: Segment Anything in Images and Videos (SAM 2, Promptable Visual Segmentation task, RPB-free MAE pre-trained Hiera encoder, $L=4$ 2d-RoPE Memory Attention, FIFO Memory Bank with $N=6$ recent frames and $4 \times 64\text{-d}$ Object Pointers, Occlusion Head, SA-V dataset of 35.5M masks across 50.9K videos at $8.4\times$ faster annotation, and 130.1 FPS image / 43.8 FPS video benchmarks) — https://arxiv.org/html/2408.00714v2 and https://arxiv.org/abs/2408.00714
  5. Lihe Yang, Bingyi Kang, Zilong Huang, Zhen Zhao, Xiaogang Xu, Jiashi Feng, & Hengshuang Zhao (HKU & TikTok, NeurIPS 2024): Depth Anything V2 (Depth Anything V2, 1.3B DINOv2-G teacher trained on 595K synthetic images with $\mathcal{L}{\text{ssi}}:\mathcal{L}{\text{gm}}=1:2$, 62M pseudo-labeled real images across 8 datasets with top-10% loss masking, 83.6% Transparent Surface Challenge accuracy, DA-2K benchmark 95.3%–97.4% accuracy, and NYU-D / KITTI metric depth & Cityscapes / ADE20K segmentation transfer) — https://arxiv.org/html/2406.09414v2 and https://arxiv.org/abs/2406.09414
🔗 Share Post

Reading next story...

العودة إلى المنشورات