{
  "id": "vision-transformers",
  "module": "multimodal",
  "level": 3,
  "minutes": 45,
  "audiences": [
    "developer",
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Vision Transformers and Self-Supervised Vision: ViT, Contrastive Learning, MAE, and Segmentation and Detection",
      "description": "A systematic account from convolutional networks to vision transformers: image patches and positional encodings, Swin window attention, Faster R-CNN / YOLO / DETR detection, U-Net and SAM segmentation, and self-supervised methods including SimCLR, MAE, DINOv2 and I-JEPA. Claims follow the original papers and official documentation, with a CPU-reproducible patch-grid and NT-Xent example.",
      "updated": "2026-11-23",
      "takeaways": [
        "ViT cuts an image into fixed-size patches, projects them linearly, and prepends a learnable classification token with positional encodings before a standard Transformer encoder. With the paper’s formula N = HW/P², a 224×224 image and patch size 16 yield a 14×14 grid of 196 patches, or a sequence length of 197 once the classification token is added. This lesson’s script checks several common resolutions.",
        "Compared with CNNs, ViT builds in little translation equivariance or locality. The paper states that, on mid-sized datasets such as ImageNet and without strong regularisation, accuracy lags ResNets of comparable size by a few percentage points; pre-training on 14M–300M images lets scale outweigh that missing inductive bias. The best model pre-trained on ImageNet-21k or JFT-300M reaches 88.55% on ImageNet.",
        "SimCLR uses NT-Xent (normalised temperature-scaled cross-entropy) to pull together two augmented views of the same image and push away the other samples in the batch; the projection head is discarded after training and only the encoder output is kept. MAE feeds only visible patches to the encoder and reconstructs pixels with a lightweight decoder; because images are spatially redundant, a 75% masking ratio is commonly used so the task cannot be solved by local interpolation. DINOv2 performs self-distillation on the curated LVD-142M collection to obtain general-purpose features that can be frozen; I-JEPA predicts target-block representations rather than pixels.",
        "For detection, Faster R-CNN uses a Region Proposal Network that shares features with the detection head; with VGG-16 on a K40 GPU the full system runs at 5 fps and uses 300 proposals per image. YOLO casts detection as a single regression: on PASCAL VOC it uses a 7×7 grid, 2 boxes per cell and 20 classes, hence a 7×7×30 tensor; the original paper reports 45 fps for the base model on a Titan X with no batching, and 155 fps for Fast YOLO. DETR uses a set of learned object queries and bipartite matching (the Hungarian algorithm) to predict a set directly, without non-maximum suppression; a model with a parameter count comparable to Faster R-CNN reaches 42 AP on COCO val.",
        "For segmentation, U-Net uses a symmetric contracting path and expansive path, concatenating cropped high-resolution maps back into the decoder, with 23 convolutional layers in total. SAM treats segmentation as a promptable task; prompts may be points, boxes or masks, among others, and the accompanying SA-1B dataset has more than one billion masks on 11M images. In practice one can load pre-trained backbones with timm for a linear probe or fine-tuning, use SAM for prompted or automatic annotation, and train a detector on one’s own photos with Ultralytics YOLO."
      ],
      "faq": [
        {
          "q": "How does ViT turn an image into a sequence, and how many tokens does a 224×224 image with patch size 16 produce?",
          "a": "Following Dosovitskiy et al., a resolution-(H, W) image is cut into non-overlapping patches of side P and each patch is projected linearly. The number of patches is N = HW/P². For 224×224 and P=16 that is a 14×14 grid, or 196 patches. For classification a learnable classification token is prepended and positional encodings are added, so the encoder sees a sequence of length 197. This lesson’s script also checks P=32 (49 patches) and 384×384 with P=16 (576 patches)."
        },
        {
          "q": "Why does the MAE paper mask as much as 75% of the image, rather than a small fraction as in BERT?",
          "a": "The paper notes that images are natural signals with heavy spatial redundancy: a missing patch can often be recovered from its neighbours with little high-level understanding. Masking a very high proportion of random patches (for example 75%) yields a nontrivial self-supervisory task and forces a more holistic representation. The same design works with the asymmetric architecture: the encoder sees only the visible quarter of the patches, and mask tokens appear only in the lightweight decoder. Figure 2 of the paper also illustrates 80% masking, leaving 39 of 196 patches."
        },
        {
          "q": "Why does SimCLR discard the projection head after training?",
          "a": "SimCLR places a learnable nonlinear projection head g(·) (an MLP with one hidden layer and ReLU) after the encoder f(·), and applies the contrastive loss to z=g(h). Ablations show that a nonlinear projection outperforms a linear one by about 3 points and outperforms no projection by more than 10 points; even with a nonlinear projection, the hidden representation h before the head remains a better downstream feature than z (again by more than 10 points). After training, g(·) is discarded and h is used as the image representation."
        },
        {
          "q": "MAE and I-JEPA both hide parts of the image. What is the difference in what they predict?",
          "a": "MAE is generative: the decoder reconstructs masked patches in pixel space. I-JEPA is a non-generative joint-embedding predictive architecture: from a single context block it predicts the representations of several target blocks in the same image, not the pixels. The authors argue that this avoids treating unpredictable pixel detail as a learning target and reduces reliance on hand-crafted data augmentations. Meta AI’s introductory post (13 June 2023; curl returned 400 on the day of writing, confirmed by a separate fetch) agrees with the paper: prediction is in an abstract representation space rather than a comparison or reconstruction of pixels."
        },
        {
          "q": "What can a SAM prompt be, and how does that differ from what U-Net is for?",
          "a": "SAM defines a promptable segmentation task: given any prompt, return a valid mask. The paper states that a prompt can include spatial or text information identifying an object; the public implementation and usual interface emphasise points, boxes and masks. The model is trained to transfer zero-shot given a prompt. U-Net is an encoder–decoder designed for biomedical images, with skip connections that concatenate cropped maps from the contracting path onto the upsampled path, and is typically trained end-to-end on a labelled dataset rather than used as a general prompted segmenter."
        }
      ],
      "sources": [
        {
          "title": "Dosovitskiy, Beyer, Kolesnikov et al. (2020), An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale, arXiv:2010.11929 (ICLR 2021)",
          "url": "https://arxiv.org/abs/2010.11929"
        },
        {
          "title": "Chen, Kornblith, Norouzi, and Hinton (2020), A Simple Framework for Contrastive Learning of Visual Representations, arXiv:2002.05709",
          "url": "https://arxiv.org/abs/2002.05709"
        },
        {
          "title": "He, Chen, Xie et al. (2021), Masked Autoencoders Are Scalable Vision Learners, arXiv:2111.06377",
          "url": "https://arxiv.org/abs/2111.06377"
        },
        {
          "title": "Kirillov, Mintun, Ravi et al. (2023), Segment Anything, arXiv:2304.02643",
          "url": "https://arxiv.org/abs/2304.02643"
        },
        {
          "title": "Liu, Lin, Cao et al. (2021), Swin Transformer: Hierarchical Vision Transformer using Shifted Windows, arXiv:2103.14030",
          "url": "https://arxiv.org/abs/2103.14030"
        },
        {
          "title": "Oquab, Darcet, Moutakanni et al. (2023), DINOv2: Learning Robust Visual Features without Supervision, arXiv:2304.07193",
          "url": "https://arxiv.org/abs/2304.07193"
        },
        {
          "title": "Assran, Duval, Misra et al. (2023), Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture, arXiv:2301.08243",
          "url": "https://arxiv.org/abs/2301.08243"
        },
        {
          "title": "Ren, He, Girshick, and Sun (2015), Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks, arXiv:1506.01497",
          "url": "https://arxiv.org/abs/1506.01497"
        },
        {
          "title": "Redmon, Divvala, Girshick, and Farhadi (2015), You Only Look Once: Unified, Real-Time Object Detection, arXiv:1506.02640",
          "url": "https://arxiv.org/abs/1506.02640"
        },
        {
          "title": "Carion, Massa, Synnaeve et al. (2020), End-to-End Object Detection with Transformers, arXiv:2005.12872",
          "url": "https://arxiv.org/abs/2005.12872"
        },
        {
          "title": "Ronneberger, Fischer, and Brox (2015), U-Net: Convolutional Networks for Biomedical Image Segmentation, arXiv:1505.04597",
          "url": "https://arxiv.org/abs/1505.04597"
        },
        {
          "title": "van den Oord, Li, and Vinyals (2018), Representation Learning with Contrastive Predictive Coding, arXiv:1807.03748",
          "url": "https://arxiv.org/abs/1807.03748"
        },
        {
          "title": "Caron, Touvron, Misra et al. (2021), Emerging Properties in Self-Supervised Vision Transformers, arXiv:2104.14294",
          "url": "https://arxiv.org/abs/2104.14294"
        },
        {
          "title": "facebookresearch/mae (official implementation)",
          "url": "https://github.com/facebookresearch/mae"
        },
        {
          "title": "facebookresearch/segment-anything (official implementation)",
          "url": "https://github.com/facebookresearch/segment-anything"
        },
        {
          "title": "facebookresearch/dinov2 (official implementation)",
          "url": "https://github.com/facebookresearch/dinov2"
        },
        {
          "title": "facebookresearch/ijepa (official implementation)",
          "url": "https://github.com/facebookresearch/ijepa"
        },
        {
          "title": "facebookresearch/detr (official implementation)",
          "url": "https://github.com/facebookresearch/detr"
        },
        {
          "title": "microsoft/Swin-Transformer (official implementation)",
          "url": "https://github.com/microsoft/Swin-Transformer"
        },
        {
          "title": "google-research/simclr (official implementation)",
          "url": "https://github.com/google-research/simclr"
        },
        {
          "title": "Hugging Face timm documentation (PyTorch image models)",
          "url": "https://huggingface.co/docs/timm/index"
        },
        {
          "title": "Ultralytics YOLO official documentation",
          "url": "https://docs.ultralytics.com/"
        },
        {
          "title": "Ultralytics documentation: Train mode",
          "url": "https://docs.ultralytics.com/modes/train/"
        },
        {
          "title": "Hugging Face Computer Vision Course",
          "url": "https://huggingface.co/learn/computer-vision-course/unit0/welcome/welcome"
        },
        {
          "title": "Stanford CS231n course notes (cs231n.github.io)",
          "url": "https://cs231n.github.io/"
        },
        {
          "title": "U-Net authors’ page (Ronneberger et al., Freiburg LMB)",
          "url": "https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/"
        },
        {
          "title": "YOLO authors’ project page (Darknet)",
          "url": "https://pjreddie.com/darknet/yolo/"
        },
        {
          "title": "Segment Anything project page",
          "url": "https://segment-anything.com/"
        },
        {
          "title": "Hugging Face Transformers documentation: ViTMAE",
          "url": "https://huggingface.co/docs/transformers/model_doc/vit_mae"
        },
        {
          "title": "Meta AI: I-JEPA introductory post (13 June 2023; curl returned 400 on the day of writing, confirmed by a separate fetch)",
          "url": "https://ai.meta.com/blog/yann-lecun-ai-model-i-jepa/"
        },
        {
          "title": "Meta AI: DINOv2 introductory post (17 April 2023; curl returned 400 on the day of writing, confirmed by a separate fetch)",
          "url": "https://ai.meta.com/blog/dino-v2-computer-vision-self-supervised-learning/"
        }
      ],
      "url": "https://aimap.page/en/learn/multimodal/vision-transformers/",
      "markdown": "**Summary.** Once an image is cut into patches, a standard Transformer can be used for recognition: that is the basic idea of the Vision Transformer (ViT). To serve as a general-purpose backbone for dense tasks such as detection and segmentation, hierarchical features and local attention (Swin) are also needed. Detection and segmentation themselves have moved from region proposals and single-stage regression to set prediction and promptable segmentation. In parallel, contrastive learning, masked reconstruction, self-distillation and prediction in representation space let visual models learn transferable features from unlabelled images. This lesson follows the path “ViT tokenisation and scale → Swin’s hierarchical window attention → representative detectors and segmenters → four lines of self-supervision → linear probes, fine-tuning and readily available tools”. Figures taken from papers were checked against the source; figures produced by this lesson’s script are reported at the end with the environment and seed: Python 3.13.5, NumPy 2.5.4, random seed 0.\n\nThis lesson belongs to the unit [Vision Transformers and Self-Supervised Vision](/learn/unit/u70-vision). It assumes [Transformers and Attention](/learn/transformer-attention) and [From CNNs and RNNs to Transformers](/learn/cnn-rnn-to-transformer). Related algorithm cards: [ViT](/learn/algorithms/vit), [SimCLR](/learn/algorithms/simclr), [MAE](/learn/algorithms/mae), [JEPA](/learn/algorithms/jepa), [SAM](/learn/algorithms/sam), [Contrastive Learning and InfoNCE](/learn/algorithms/contrastive-learning), [U-Net](/learn/algorithms/unet), [Faster R-CNN](/learn/algorithms/faster-rcnn), [YOLO](/learn/algorithms/yolo), [DETR](/learn/algorithms/detr), [Swin](/learn/algorithms/swin), [DINOv2](/learn/algorithms/dinov2).\n\n## From convolutional networks to the Vision Transformer\n\nBefore ViT, convolutional networks were the default visual models: local receptive fields, weight sharing and translation equivariance are built into the architecture. Dosovitskiy, Beyer, Kolesnikov et al. (2020; ICLR 2021) showed that a convolutional backbone around the Transformer is not required: cutting the image into fixed-size patches, projecting them linearly and feeding the sequence to a standard Transformer encoder is already enough for image recognition.\n\nLet the image have resolution (H, W) and C channels, and let each patch have side P. After the image is reshaped into a sequence of patches, the length is\n\n```text\nN = H W / P²\n```\n\nwhich is the encoder’s effective input length. For the common setting 224×224 and P=16, 224/16=14, so there are 14×14=196 patches. Each patch is projected to the model width D by a shared linear layer, and a learnable classification token (x_class) is prepended. Positional information is added as learnable one-dimensional position embeddings; the authors report no significant gain from more two-dimension-aware encodings. For classification one takes the encoder output that corresponds to x_class and attaches a classification head (an MLP with one hidden layer at pre-training time).\n\nThe script in this lesson checks several common sizes against that formula.\n\n| Image H×W | Patch side P | Grid | Patches N | Sequence length with class token | Note |\n|---|---|---|---|---|---|\n| 224×224 | 16 | 14×14 | 196 | 197 | Usual input for ViT-B/16 and ViT-L/16 |\n| 224×224 | 32 | 7×7 | 49 | 50 | ViT-B/32 and ViT-L/32 |\n| 224×224 | 14 | 16×16 | 256 | 257 | Patch size used with ViT-H/14 |\n| 384×384 | 16 | 24×24 | 576 | 577 | A common higher-resolution fine-tuning size |\n\nWhen fine-tuning at a resolution different from pre-training, the paper interpolates the pre-trained position embeddings on a 2D grid rather than reinitialising them at random.\n\nViT encodes almost no image-specific inductive bias: locality, two-dimensional neighbourhood structure and translation equivariance appear only in the initial patching step and in the interpolation of position embeddings at fine-tuning time. All other spatial relations have to be learned from data. The authors therefore write that, on mid-sized datasets such as ImageNet and without strong regularisation, these models yield accuracies a few percentage points below ResNets of comparable size, and that they “do not generalize well when trained on insufficient amounts of data”. When pre-training data reach 14M–300M images, “large scale training trumps inductive bias”. Pre-training may be done on the public ImageNet-21k set or on the in-house JFT-300M set. The best model reported in the paper reaches 88.55% on ImageNet, 90.72% on ImageNet-ReaL, 94.55% on CIFAR-100, and 77.63% on the 19-task VTAB suite. Those figures are from the paper, not a reproduction in this lesson.\n\n## Hierarchical vision transformers: Swin\n\nA standard ViT applies global self-attention among all patches and keeps a single-resolution feature map, so the cost grows quadratically with the number of patches and the model is an awkward general-purpose backbone for detection and segmentation. The Swin Transformer of Liu, Lin, Cao et al. (2021) makes two changes.\n\nFirst, it builds hierarchical features: it starts from smaller patches (4×4 by default in the paper) and then uses patch merging to reduce resolution and increase the channel width, producing multi-scale maps at successive stages. Second, self-attention is restricted to non-overlapping local windows, which makes the cost approximately linear in image size; to allow information to cross window boundaries, the window partition is shifted between consecutive blocks (shifted windows), corresponding to W-MSA and SW-MSA in the paper. The default window side is M=7.\n\nFor a 224×224 input, patch size 4 and M=7, the four stages have token grids 56×56, 28×28, 14×14 and 7×7. The attention-score counts below assume that each token forms a dot product with M² positions inside its window, or with every token under global attention. They illustrate how the two complexity scalings diverge as the feature map grows; they are not measured runtimes.\n\n| Stage | Token grid | Tokens | Windows (M=7) | Window attention scores | Global attention scores | Global / window |\n|---|---|---|---|---|---|---|\n| 1 | 56×56 | 3136 | 64 | 153664 | 9834496 | 64 |\n| 2 | 28×28 | 784 | 16 | 38416 | 614656 | 16 |\n| 3 | 14×14 | 196 | 4 | 9604 | 38416 | 4 |\n| 4 | 7×7 | 49 | 1 | 2401 | 2401 | 1 |\n\nAt stage 1 the windowed score count is 1/64 of the global count, matching the number of windows; at stage 4 the whole feature map is a single window and the two counts coincide. The paper reports a best ImageNet-1K top-1 accuracy of 87.3 for Swin as a backbone, and 58.7 box AP and 51.1 mask AP on COCO test-dev. Those figures are again from the paper and were not reproduced here.\n\n## A short history of object detection\n\nThis unit already lists Faster R-CNN, YOLO and DETR. The remarks below only state the problem each method addresses; they are not a second course on detection.\n\n**Two stages: Faster R-CNN.** After R-CNN and Fast R-CNN, region proposal itself became the speed bottleneck. Ren, He, Girshick and Sun (2015) introduced a Region Proposal Network (RPN): a fully convolutional network that shares full-image convolutional features with the detection head and predicts object bounds and objectness at each position. The authors describe the proposals as nearly cost-free, with a marginal cost of about 10 ms per image. With VGG-16, the detection system runs at 5 fps on a GPU including all steps and uses 300 proposals per image; Table 5 of the paper reports 198 ms in total for RPN + Fast R-CNN on a K40 GPU (10 ms of that for proposals). The RPN covers multiple scales and aspect ratios with a set of anchors.\n\n**Single stage: YOLO.** Redmon, Divvala, Girshick and Farhadi (2015) cast detection as a regression problem: a single network predicts bounding boxes and class probabilities from the full image in one evaluation, so the whole pipeline can be optimised end-to-end. The image is divided into an S×S grid; the cell that contains an object’s centre is responsible for it. Each cell predicts B boxes and their confidences, plus C class probabilities, and the output is an S×S×(B×5+C) tensor. On PASCAL VOC, S=7, B=2 and C=20, so the final prediction is a 7×7×30 tensor. The input is resized to 448×448. The paper reports that the base YOLO model runs at 45 fps on a Titan X with no batch processing; the faster Fast YOLO model is given as 155 fps in the abstract and as more than 150 fps in the body. The paper also reports 63.4% mAP under the setting used there. The Ultralytics YOLO family used today is a later line of models; follow the official documentation for the interface and training recipe, and do not treat the 2015 figure of 45 fps as the speed of a current model on current hardware.\n\n**Set prediction: DETR.** Carion, Massa, Synnaeve et al. (2020) treat detection as direct set prediction. A CNN backbone produces a 2D feature map, which is flattened, supplemented with a positional encoding and passed to a Transformer encoder. The decoder takes N learned object queries (N=100 in the paper’s experiments) together with the encoder output; a shared feed-forward network then predicts a class and box, or a “no object” label. Training uses the Hungarian algorithm to compute a bipartite matching between predictions and ground truth, so the loss is permutation-invariant and duplicate detections are discouraged, removing the need for non-maximum suppression and hand-designed anchors. The paper reports that a model with a parameter count comparable to Faster R-CNN reaches 42 AP on COCO val, with a gain on large objects (AP_L +7.8) and a remaining deficit on small objects (AP_S −5.5).\n\n| Method | Year | Core structure | Post-processing | Speed or accuracy in the paper (original setting) |\n|---|---|---|---|---|\n| Faster R-CNN | 2015 | Feature-sharing RPN + detection head | Classify and regress after proposals | VGG-16, K40 GPU, 5 fps including all steps; 300 proposals |\n| YOLO (v1) | 2015 | Single-network regression, S×S grid | Thresholding and de-duplication | 45 fps for the base model on Titan X; 7×7×30 on VOC |\n| DETR | 2020 | Encoder–decoder + object queries | Bipartite matching, no NMS | 42 AP on COCO val (parameter count close to Faster R-CNN) |\n\n## Segmentation: U-Net and Segment Anything\n\n**U-Net.** Ronneberger, Fischer and Brox (2015) designed a U-shaped encoder–decoder for biomedical images. The contracting path repeats two 3×3 convolutions, ReLU and 2×2 max-pooling; the expansive path upsamples, applies a 2×2 up-convolution that halves the number of channels, concatenates the correspondingly cropped map from the contracting path, and applies two 3×3 convolutions. These skip connections give the decoder both context and high-resolution localisation. The network has no fully connected layers and 23 convolutional layers in total. Because valid convolutions are used, the segmentation map covers only those pixels whose full context lies inside the input, and large images can be processed with an overlap-tile strategy. The authors stress elastic-deformation augmentation so that the network can be trained end-to-end from very few annotated images.\n\n**SAM.** Kirillov, Mintun, Ravi et al. (2023) define a promptable segmentation task: given any prompt, return at least one valid mask; when the prompt is ambiguous (a point on a shirt may also refer to the person), the output should be a reasonable mask for one of those readings. A prompt can include spatial or text information; points, boxes and masks are the usual interface in the public implementation. The model comprises an image encoder, a prompt encoder and a mask decoder, and is trained to transfer zero-shot given a prompt. The accompanying SA-1B dataset contains 11M licensed, privacy-respecting images and more than one billion masks; the project page is [segment-anything.com](https://segment-anything.com/). The dataset and model-scale figures are from the paper; this lesson does not download SA-1B or the official weights.\n\n## Self-supervised vision\n\nLabelled images are typically far scarcer than unlabelled ones. Self-supervised learning builds a task from the image itself, first obtaining a transferable representation and then attaching a linear probe or a fine-tuned head. The four lines below cover the algorithms already listed for this unit.\n\n### Contrastive learning and InfoNCE\n\nvan den Oord, Li and Vinyals (2018) introduced InfoNCE in Contrastive Predictive Coding. Given a set X={x_1,…,x_N} that contains one positive sample from the conditional p(x_{t+k}|c_t) and N−1 negatives from a proposal distribution p(x_{t+k}), one optimises\n\n```text\nL_N = − E[  log  f_k(x_{t+k}, c_t) / Σ_{x_j ∈ X} f_k(x_j, c_t)  ]\n```\n\nMinimising L_N maximises a lower bound on the mutual information: I(x_{t+k}, c_t) ≥ log(N) − L_N, which tightens as N grows. The intuition is that the model must recognise the sample compatible with the current context among a batch of distractors.\n\n### SimCLR\n\nChen, Kornblith, Norouzi and Hinton (2020) turned that idea into a deliberately simple visual framework. Two augmentations are sampled independently for each example, yielding two correlated views; an encoder f(·) and a projection head g(·) are trained to maximise agreement. The main augmentations are random cropping with resize back to the original size, colour distortion and Gaussian blur. The contrastive loss is NT-Xent (normalised temperature-scaled cross-entropy). For 2N views from a batch of N images, the loss of a positive pair (i, j) is\n\n```text\nℓ_{i,j} = − log  exp(sim(z_i, z_j)/τ) / Σ_{k=1, k≠i}^{2N} exp(sim(z_i, z_k)/τ)\n```\n\nwhere sim is cosine similarity after ℓ₂ normalisation and τ is a temperature. A batch of size 8192 supplies 16382 negatives per positive pair (the number given in the paper). The authors sweep batch sizes from 256 to 8192; the default ablation uses batch size 4096 for 100 epochs, LARS and global batch normalisation. They emphasise three findings: the composition of augmentations matters; a learnable nonlinear projection between the representation and the loss is important; and contrastive learning benefits from larger batches and more steps than supervised training. In the abstract, a linear classifier on SimCLR representations reaches 76.5% top-1 on ImageNet. As already noted, the representation actually used is the hidden vector h before the projection head.\n\n### MAE\n\nThe masked autoencoder of He, Chen, Xie et al. (2021) takes a different path: random patches of the input are masked and the missing pixels are reconstructed. Two design choices are central. The first is an asymmetric architecture: the encoder sees only visible patches and no mask tokens; mask tokens are introduced after the encoder, and a lightweight decoder processes the full set and reconstructs in pixel space. After pre-training the decoder is discarded, and for recognition the encoder is applied to the uncorrupted image. The second is a high masking ratio, for example 75%: images are spatially redundant, so a low ratio is often too easy; a high ratio both creates a harder task and lets the encoder process only about 25% of the patches, which the paper says can accelerate pre-training by 3× or more. For 196 patches and 75% masking, 49 patches remain visible and 147 are masked; Figure 2 of the paper uses 80% masking and leaves 39 of 196 patches, which matches 196×0.20=39.2 rounded to 39. The authors also report that a vanilla ViT-Huge trained only on ImageNet-1K reaches 87.8%, the best accuracy among methods using only that dataset at the time. That figure is from the paper; this lesson does not train an MAE.\n\n### DINOv2 and self-distillation\n\nDINO, by Caron, Touvron, Misra et al. (2021), casts self-supervision as student–teacher self-distillation. The two networks share an architecture but not parameters; they process two random transformations of the same image. The teacher output is centred over the batch, both sides are passed through a temperature softmax, and agreement is measured with a cross-entropy; gradients flow only through the student, and the teacher is an exponential moving average of the student. No class labels are used.\n\nDINOv2, by Oquab, Darcet, Moutakanni et al. (2023), scales that line of work in data and model size. An automatic pipeline builds a curated collection, LVD-142M (142 million images), from about 1.2 billion source images, rather than training on uncurated data directly. A ViT with about 1 billion parameters is trained and then distilled into a family of smaller models; the ViT-g backbone in the paper has 1.1 billion parameters (embedding dimension 1536 and 24 attention heads). The aim is general-purpose features that work across image distributions and tasks without fine-tuning. The official introductory post (17 April 2023) likewise stresses that the features can feed a linear classifier directly, and that linear evaluation lies within about 2 percentage points of fine-tuning on ImageNet-1k. Concrete accuracies should be read from the paper’s tables; this lesson does not reproduce them.\n\n### I-JEPA\n\nAssran, Duval, Misra et al. (2023) proposed an image-based joint-embedding predictive architecture, I-JEPA: from a single context block, predict the representations of several target blocks in the same image. The method is non-generative and does not reconstruct pixels; the authors also state that it does not rely on hand-crafted data augmentations to form multiple views. To encourage semantic representations, the target blocks should be large enough in scale and the context block should be spatially informative. The encoder is a ViT that processes only the visible context patches; the predictor is a narrower ViT conditioned on positional tokens of the target; the target-encoder weights are an exponential moving average of the context encoder. The paper reports training a ViT-H/14 on ImageNet with 16 A100 GPUs in under 72 hours, with strong downstream results including linear classification. Meta AI’s introduction of 13 June 2023 describes the same structure: what is compared is an abstract representation of the image, not the pixels themselves.\n\n| Method | Year | Learning signal | What is compared or predicted | What is usually kept after training |\n|---|---|---|---|---|\n| SimCLR | 2020 | Agreement of two augmented views of one image | Cosine similarity in the projection space (NT-Xent) | The encoder f(·); the projection head is dropped |\n| MAE | 2021 | Random masking at a high ratio | Pixels of the masked patches | The encoder; the decoder is dropped |\n| DINO / DINOv2 | 2021 / 2023 | Student–teacher self-distillation | Agreement of output distributions | The teacher or a distilled backbone, which may be frozen |\n| I-JEPA | 2023 | Context block predicts target blocks | Target embeddings in representation space | The context / target encoders; no pixel reconstruction |\n\n## Practice: linear probes, fine-tuning and readily available tools\n\nPre-training only yields a representation. Two common ways to attach it to a task are as follows.\n\n- **Linear probe.** The backbone is frozen and only a linear classification head is trained. This measures whether the representation is linearly separable, is relatively cheap, and is a standard comparison among pre-training methods. The SimCLR, MAE, I-JEPA and DINOv2 papers all report linear evaluation as a headline figure.\n- **Fine-tuning.** The backbone and the task head are updated together. Task accuracy is usually higher, but the representation moves towards that task and is no longer equally general. The official DINOv2 introduction emphasises that its linear evaluation is already close to fine-tuning (within about 2 percentage points on ImageNet-1k), which suits using one frozen feature for several tasks.\n\nDo not treat ImageNet numbers from a paper as the accuracy on your own data. When transferring, fix the random seed, record the backbone name and whether it was frozen, and compare a linear probe with fine-tuning on the same split.\n\nIn practice, [timm](https://huggingface.co/docs/timm/index) provides a uniform interface for loading pre-trained ViT, Swin, DINOv2 and other backbones, for classification or as a feature extractor on a small dataset. The [official SAM repository](https://github.com/facebookresearch/segment-anything) accepts point and box prompts and can also generate automatic masks on a batch of images, which is useful for preparing detection or segmentation labels. [Ultralytics YOLO](https://docs.ultralytics.com/) documents [how to train](https://docs.ultralytics.com/modes/train/) a detector on custom images. This lesson does not download multi-gigabyte weights and does not report accuracies that were not run.\n\n## Worked examples in this lesson\n\nThe script `_work/daily/2026-11-23/vision_demo.py` uses only NumPy and downloads no weights. The environment is `/workspace/.venv-learn`, Python 3.13.5, NumPy 2.5.4, `seed=0`. Output is in `vision_demo_results.json` in the same directory.\n\n1. **Patch arithmetic** matches the table above: for 224×224 and P=16, N=196 and the sequence length with a class token is 197; at a 75% MAE mask, 49 patches are visible and 147 are masked; at 80%, 196×0.20=39.2, which rounds to 39, matching “39 out of 196 patches” in Figure 2 of the MAE paper.\n2. **NT-Xent on synthetic vectors.** Eight 16-dimensional unit latent vectors are drawn, and two views of each are formed by adding Gaussian noise of standard deviation 0.15 (16 vectors in total). The mean cosine similarity is 0.735972 for positive pairs and 0.000257 for negative pairs. The batch-mean loss is 0.014323 at τ=0.05, 0.127325 at τ=0.1, 1.542188 at τ=0.5 and 2.071892 at τ=1.0. After the pairing is shuffled, the loss at τ=0.1 rises to 7.402600. If every vector is identical, the loss is 2.708050, which matches the closed form log(2N−1)=log(15)=2.708050. A smaller temperature sharpens the gap between positives and negatives and therefore lowers the loss on already separable samples; this only illustrates the formula, and is not a tuning recommendation on real images.\n3. **Swin window counts** are those in the earlier table, used to check the counting relation “window attention is approximately linear in image size, global attention is quadratic”.\n\n## Exercises\n\n1. **Unit project.** On a small image-classification dataset, compare a linear probe and fine-tuning of a pre-trained ViT, recording accuracy and training settings on the same split; then use SAM with point or box prompts (or automatic mask generation) to annotate a batch of pictures, and inspect whether the masks match the prompted objects.\n2. Complete the hands-on units of the [Hugging Face Computer Vision Course](https://huggingface.co/learn/computer-vision-course/unit0/welcome/welcome), and compare them with the patching and encoder usage in this lesson.\n3. Load ViT, Swin, DINOv2 or similar backbones with [timm](https://huggingface.co/docs/timm/index) and transfer them on a small dataset, comparing a frozen backbone with full fine-tuning.\n4. Following the [Ultralytics training documentation](https://docs.ultralytics.com/modes/train/), train a YOLO detector on your own photos, and record the model version, image size and number of epochs.\n\n## Suggested reading order\n\nStart by reviewing self-attention and positional encodings in [Transformers and Attention](/learn/transformer-attention), and compute the 224×224 sequence length with the patch formula in this lesson. For ViT, read Section 3 of Dosovitskiy et al.; when a hierarchical backbone is needed, read the window and shifted-window sections of the Swin paper, or the official repository. For detection, follow Faster R-CNN → YOLO v1 → DETR to see how the problem is restated; for modern YOLO usage, follow the [Ultralytics documentation](https://docs.ultralytics.com/). For segmentation, start with U-Net skip connections and then SAM’s promptable task and official repository. For self-supervision, compare InfoNCE / SimCLR → MAE → DINO / DINOv2 → I-JEPA along the four lines “compare views, reconstruct pixels, self-distil, predict representations”, and try a linear probe on frozen features in timm. The same stage’s lesson on [vision-language models](/learn/vision-language) then attaches the image encoders from this lesson to a language model."
    },
    "zh-hans": {
      "title": "视觉 Transformer 与自监督视觉：ViT、对比学习、MAE 与分割检测",
      "description": "从卷积网络到视觉 Transformer 的系统说明：图像分块与位置编码、Swin 的窗口注意力、Faster R-CNN / YOLO / DETR 检测、U-Net 与 SAM 分割，以及 SimCLR、MAE、DINOv2 与 I-JEPA 等自监督方法。依据原始论文与官方文档、仓库，并给出可在 CPU 上复现的分块算术与 NT-Xent 示例。",
      "updated": "2026-11-23",
      "takeaways": [
        "ViT 把图像切成固定大小的 patch，线性投影后再加上可学习的分类标记与位置编码，送入标准 Transformer 编码器。按论文中的公式 N = HW/P²，224×224、patch 边长 16 得到 14×14=196 个 patch，加上分类标记后序列长度为 197。本课脚本对若干常见分辨率做了核对。",
        "与 CNN 相比，ViT 几乎不内置平移等变性与局部性。论文写明：在 ImageNet 这类中等规模数据上、且没有很强正则时，精度会比同类规模的 ResNet 低几个百分点；在 14M–300M 张图像上预训练后，这种归纳偏置上的差距可以被规模抵消。预训练于 ImageNet-21k 或 JFT-300M 的最佳模型在 ImageNet 上达到 88.55%。",
        "SimCLR 用 NT-Xent（温度缩放的归一化交叉熵）拉近同一图像两个增强视图、推开批次中的其他样本，训练结束后丢掉投影头，只用编码器输出。MAE 只把可见 patch 送进编码器，用轻量解码器重建像素；由于图像空间冗余高，常用 75% 的遮盖率，使任务不再能靠邻域插值轻易完成。DINOv2 在精心构造的 LVD-142M 上做自蒸馏，得到可冻结使用的通用特征；I-JEPA 则在表示空间预测目标块，而不是重建像素。",
        "检测方面，Faster R-CNN 用与检测头共享特征的区域建议网络（RPN）产生候选框，VGG-16 在 K40 GPU 上含全部步骤为 5 fps、每张图 300 个建议。YOLO 把检测写成一次回归：在 PASCAL VOC 上为 7×7 网格、每格 2 个框、20 类，输出 7×7×30 张量；原论文在 Titan X 上报告基础模型 45 fps（无批处理），Fast YOLO 为 155 fps。DETR 用一组可学习的 object query 与二分图匹配（匈牙利算法）直接预测集合，不再依赖非极大值抑制，论文中与 Faster R-CNN 参数量相近的模型在 COCO val 上达到 42 AP。",
        "分割方面，U-Net 用对称的收缩路径与扩张路径，并通过拼接把高分辨率特征送回解码器，全文共 23 个卷积层。SAM 把分割做成可提示任务，提示可以是点、框、掩码等；配套数据集 SA-1B 含 11M 张图像上的超过 10 亿个掩码。实践中可用 timm 加载预训练骨干做线性探针或微调，用 SAM 做提示式或自动标注，用 Ultralytics YOLO 在自己的照片上训练检测器。"
      ],
      "faq": [
        {
          "q": "ViT 怎样把一张图像变成序列？224×224、patch 为 16 时有多少个 token？",
          "a": "按 Dosovitskiy 等人的公式，把分辨率为 (H, W) 的图像切成边长为 P 的不重叠 patch，再经线性投影。patch 个数为 N = HW/P²。对 224×224、P=16，得到 14×14=196 个 patch。分类时再在序列前端加入一个可学习的 classification token，位置编码加在这些嵌入上，因此送入编码器的序列长度是 197。本课脚本也核对了 P=32（49 个 patch）和 384×384、P=16（576 个 patch）。"
        },
        {
          "q": "为什么论文把 MAE 的遮盖率取到 75%，而不是像 BERT 那样只遮一小部分？",
          "a": "MAE 论文指出，图像是具有高度空间冗余的自然信号，缺失的一小块往往可以从邻域恢复，几乎不需要高层语义。把随机 patch 遮到很高比例（例如 75%）才能构成有意义的自监督任务，并迫使模型做整体理解。该设计还与非对称结构配合：编码器只处理可见的约 25% patch，掩码标记只出现在轻量解码器中。论文还在图 2 用 80% 遮盖（196 个 patch 中留下 39 个）做了重建示意。"
        },
        {
          "q": "SimCLR 训练完成后为什么要丢掉投影头？",
          "a": "SimCLR 在编码器 f(·) 之后接一个可学习的非线性投影头 g(·)（一层隐层的 MLP 加 ReLU），对比损失加在 z=g(h) 上。消融表明，有非线性投影比线性投影高约 3 个百分点，比没有投影高 10 个百分点以上；但即使用了非线性投影，投影之前的 h 仍比 z 更适合做下游表示（同样超过 10 个百分点）。因此训练结束后丢掉 g(·)，用 h 作为图像表示。"
        },
        {
          "q": "MAE 和 I-JEPA 都对图像做了遮挡，二者的预测目标有何不同？",
          "a": "MAE 是生成式的：解码器在像素空间重建被遮盖的 patch。I-JEPA 是非生成式的联合嵌入预测：从图像中的一个上下文块出发，预测同一图像中若干目标块的表示，而不是像素。作者强调这样可以避免把不可预测的像素细节当作学习目标，并减少对人工设计数据增强的依赖。Meta AI 的介绍博客（2023-06-13，当天用抓取复核）与论文一致：在表示空间做抽象预测，而不是比较或重建像素本身。"
        },
        {
          "q": "SAM 的提示可以是什么？它和 U-Net 解决的问题有何不同？",
          "a": "SAM 把分割定义为可提示任务：给定任意提示，返回一个有效的掩码。论文写明提示可以包含空间或文本信息以指明对象，公开实现与常用接口以点、框、掩码为主。模型按提示做零样本迁移。U-Net 则是为生物医学影像设计的编码器–解码器，用跳跃连接（把收缩路径的特征图裁剪后与上采样结果拼接）做像素级分割，通常在带标注的特定数据集上端到端训练，而不是按提示做通用分割。"
        }
      ],
      "sources": [
        {
          "title": "Dosovitskiy、Beyer、Kolesnikov 等（2020），An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale，arXiv:2010.11929（ICLR 2021）",
          "url": "https://arxiv.org/abs/2010.11929"
        },
        {
          "title": "Chen、Kornblith、Norouzi、Hinton（2020），A Simple Framework for Contrastive Learning of Visual Representations，arXiv:2002.05709",
          "url": "https://arxiv.org/abs/2002.05709"
        },
        {
          "title": "He、Chen、Xie 等（2021），Masked Autoencoders Are Scalable Vision Learners，arXiv:2111.06377",
          "url": "https://arxiv.org/abs/2111.06377"
        },
        {
          "title": "Kirillov、Mintun、Ravi 等（2023），Segment Anything，arXiv:2304.02643",
          "url": "https://arxiv.org/abs/2304.02643"
        },
        {
          "title": "Liu、Lin、Cao 等（2021），Swin Transformer: Hierarchical Vision Transformer using Shifted Windows，arXiv:2103.14030",
          "url": "https://arxiv.org/abs/2103.14030"
        },
        {
          "title": "Oquab、Darcet、Moutakanni 等（2023），DINOv2: Learning Robust Visual Features without Supervision，arXiv:2304.07193",
          "url": "https://arxiv.org/abs/2304.07193"
        },
        {
          "title": "Assran、Duval、Misra 等（2023），Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture，arXiv:2301.08243",
          "url": "https://arxiv.org/abs/2301.08243"
        },
        {
          "title": "Ren、He、Girshick、Sun（2015），Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks，arXiv:1506.01497",
          "url": "https://arxiv.org/abs/1506.01497"
        },
        {
          "title": "Redmon、Divvala、Girshick、Farhadi（2015），You Only Look Once: Unified, Real-Time Object Detection，arXiv:1506.02640",
          "url": "https://arxiv.org/abs/1506.02640"
        },
        {
          "title": "Carion、Massa、Synnaeve 等（2020），End-to-End Object Detection with Transformers，arXiv:2005.12872",
          "url": "https://arxiv.org/abs/2005.12872"
        },
        {
          "title": "Ronneberger、Fischer、Brox（2015），U-Net: Convolutional Networks for Biomedical Image Segmentation，arXiv:1505.04597",
          "url": "https://arxiv.org/abs/1505.04597"
        },
        {
          "title": "van den Oord、Li、Vinyals（2018），Representation Learning with Contrastive Predictive Coding，arXiv:1807.03748",
          "url": "https://arxiv.org/abs/1807.03748"
        },
        {
          "title": "Caron、Touvron、Misra 等（2021），Emerging Properties in Self-Supervised Vision Transformers，arXiv:2104.14294",
          "url": "https://arxiv.org/abs/2104.14294"
        },
        {
          "title": "facebookresearch/mae（官方实现）",
          "url": "https://github.com/facebookresearch/mae"
        },
        {
          "title": "facebookresearch/segment-anything（官方实现）",
          "url": "https://github.com/facebookresearch/segment-anything"
        },
        {
          "title": "facebookresearch/dinov2（官方实现）",
          "url": "https://github.com/facebookresearch/dinov2"
        },
        {
          "title": "facebookresearch/ijepa（官方实现）",
          "url": "https://github.com/facebookresearch/ijepa"
        },
        {
          "title": "facebookresearch/detr（官方实现）",
          "url": "https://github.com/facebookresearch/detr"
        },
        {
          "title": "microsoft/Swin-Transformer（官方实现）",
          "url": "https://github.com/microsoft/Swin-Transformer"
        },
        {
          "title": "google-research/simclr（官方实现）",
          "url": "https://github.com/google-research/simclr"
        },
        {
          "title": "Hugging Face timm 文档（PyTorch 图像模型库）",
          "url": "https://huggingface.co/docs/timm/index"
        },
        {
          "title": "Ultralytics YOLO 官方文档",
          "url": "https://docs.ultralytics.com/"
        },
        {
          "title": "Ultralytics 文档：训练模式",
          "url": "https://docs.ultralytics.com/modes/train/"
        },
        {
          "title": "Hugging Face 计算机视觉课程",
          "url": "https://huggingface.co/learn/computer-vision-course/unit0/welcome/welcome"
        },
        {
          "title": "Stanford CS231n 课程笔记（cs231n.github.io）",
          "url": "https://cs231n.github.io/"
        },
        {
          "title": "U-Net 作者页（Ronneberger 等，Freiburg LMB）",
          "url": "https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/"
        },
        {
          "title": "YOLO 作者项目页（Darknet）",
          "url": "https://pjreddie.com/darknet/yolo/"
        },
        {
          "title": "Segment Anything 项目页",
          "url": "https://segment-anything.com/"
        },
        {
          "title": "Hugging Face Transformers 文档：ViTMAE",
          "url": "https://huggingface.co/docs/transformers/model_doc/vit_mae"
        },
        {
          "title": "Meta AI：I-JEPA 介绍博客（2023-06-13；当天 curl 返回 400，已用抓取复核）",
          "url": "https://ai.meta.com/blog/yann-lecun-ai-model-i-jepa/"
        },
        {
          "title": "Meta AI：DINOv2 介绍博客（2023-04-17；当天 curl 返回 400，已用抓取复核）",
          "url": "https://ai.meta.com/blog/dino-v2-computer-vision-self-supervised-learning/"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/multimodal/vision-transformers/",
      "markdown": "**概要**：把图像切成 patch 后，标准 Transformer 就可以做识别，这是 Vision Transformer（ViT）的基本想法。要在检测、分割等密集任务上作为通用骨干，还需要分层特征与局部注意力（Swin）；检测与分割本身则经历了从区域建议、单阶段回归，到集合预测和提示式分割的变化。与此同时，对比学习、掩码重建、自蒸馏和表示空间预测，使视觉模型可以在未标注图像上先学到可迁移的特征。本课按“ViT 的序列化与规模 → Swin 的分层窗口注意力 → 检测与分割的代表性方法 → 自监督的四条主线 → 线性探针、微调与现成工具”展开。文中属于论文的数字均对照原文；属于本课脚本的数字在文末给出环境与种子，环境为 Python 3.13.5、NumPy 2.5.4，随机种子 0。\n\n本课属于[视觉 Transformer 与自监督视觉](/learn/unit/u70-vision)单元，前置为[Transformer 与注意力](/learn/transformer-attention)和[从 CNN、RNN 到 Transformer](/learn/cnn-rnn-to-transformer)。相关算法卡：[ViT](/learn/algorithms/vit)、[SimCLR](/learn/algorithms/simclr)、[MAE](/learn/algorithms/mae)、[JEPA](/learn/algorithms/jepa)、[SAM](/learn/algorithms/sam)、[对比学习与 InfoNCE](/learn/algorithms/contrastive-learning)、[U-Net](/learn/algorithms/unet)、[Faster R-CNN](/learn/algorithms/faster-rcnn)、[YOLO](/learn/algorithms/yolo)、[DETR](/learn/algorithms/detr)、[Swin](/learn/algorithms/swin)、[DINOv2](/learn/algorithms/dinov2)。\n\n## 从卷积网络到视觉 Transformer\n\n在 ViT 之前，视觉模型的主流是卷积网络：局部感受野、权值共享和平移等变性被写进结构里。Dosovitskiy、Beyer、Kolesnikov 等人（2020；ICLR 2021）表明，不必在 Transformer 外围保留卷积骨架，把图像切成固定大小的 patch、线性投影后直接送入标准 Transformer 编码器，也可以做图像识别。\n\n设图像分辨率为 (H, W)、通道数为 C，每个 patch 的边长为 P。把图像展成 patch 序列后，长度为\n\n```text\nN = H W / P²\n```\n\n这就是编码器的有效输入长度。对常用设定 224×224、P=16：224/16=14，因此有 14×14=196 个 patch。每个 patch 经同一线性层投影到模型宽度 D，再在序列前端加入一个可学习的 classification token（记为 x_class）。位置信息用可学习的一维位置编码加在这些嵌入上；作者写明，并未观察到更“二维感知”的位置编码带来显著收益。分类时取编码器输出中对应于 x_class 的那个向量，接上分类头（预训练时为带一个隐层的 MLP）。\n\n本课用脚本按上述公式核对了几组常见尺寸，结果如下。\n\n| 图像 H×W | patch 边长 P | 网格 | patch 数 N | 加分类标记后的序列长度 | 说明 |\n|---|---|---|---|---|---|\n| 224×224 | 16 | 14×14 | 196 | 197 | ViT-B/16、ViT-L/16 的常用输入 |\n| 224×224 | 32 | 7×7 | 49 | 50 | ViT-B/32、ViT-L/32 |\n| 224×224 | 14 | 16×16 | 256 | 257 | ViT-H/14 的 patch 设定 |\n| 384×384 | 16 | 24×24 | 576 | 577 | 常见的更高分辨率微调尺寸 |\n\n微调到与预训练不同的分辨率时，论文对预训练位置编码做二维插值，而不是重新随机初始化。\n\nViT 几乎不把图像特有的归纳偏置写进结构：局部性、二维邻域和平移等变性只出现在分块这一步，以及微调时对位置编码的插值。其余的空间关系都要由数据学到。因此，作者在引言中写明：在 ImageNet 这类中等规模数据上、且没有很强正则时，这些模型的精度比同类规模的 ResNet 低几个百分点；“在数据不足时，它们泛化不好”。当预训练数据达到 14M–300M 张图像时，“大规模训练超过了归纳偏置”。预训练既可以在公开的 ImageNet-21k 上做，也可以在内部的 JFT-300M 上做。文中报告的最佳模型在 ImageNet 上达到 88.55%，在 ImageNet-ReaL 上 90.72%，在 CIFAR-100 上 94.55%，在 VTAB 的 19 项任务上 77.63%。这些数字来自论文，不是本课复现的结果。\n\n## 分层视觉 Transformer：Swin\n\n标准 ViT 在整幅图像的所有 patch 之间做全局自注意力，计算量随 patch 数二次增长，特征图也始终是单尺度的，这使它不太适合作为检测、分割的通用骨干。Liu、Lin、Cao 等人（2021）的 Swin Transformer 做了两处改动。\n\n第一，构造分层特征：以较小的 patch（论文默认 4×4）起步，随后通过 patch merging 逐步降低分辨率、增大通道，从而在不同阶段得到多尺度特征图。第二，把自注意力限制在互不重叠的局部窗口内，使计算量对图像尺寸近似线性；为了让窗口之间也能交换信息，相邻块之间把窗口划分平移一次（shifted window），即论文中的 W-MSA 与 SW-MSA。默认窗口边长为 M=7。\n\n对 224×224 的输入、patch 为 4、M=7，四个阶段的 token 网格为 56×56、28×28、14×14、7×7。下面的注意力分数个数是按“每个 token 在窗口内与 M² 个位置计算点积、或在全局注意力中与全部 token 计算点积”得到的计数，用来说明复杂度随特征图变大如何分叉；它不是运行时间实测。\n\n| 阶段 | token 网格 | token 数 | 窗口数（M=7） | 窗口注意力分数 | 全局注意力分数 | 全局/窗口 |\n|---|---|---|---|---|---|---|\n| 1 | 56×56 | 3136 | 64 | 153664 | 9834496 | 64 |\n| 2 | 28×28 | 784 | 16 | 38416 | 614656 | 16 |\n| 3 | 14×14 | 196 | 4 | 9604 | 38416 | 4 |\n| 4 | 7×7 | 49 | 1 | 2401 | 2401 | 1 |\n\n在第 1 阶段，窗口注意力的分数个数是全局注意力的 1/64，与窗口数目一致；到第 4 阶段，整幅特征图恰好是一个窗口，两者相同。论文报告 Swin 作为骨干时，ImageNet-1K 上最高 top-1 为 87.3，COCO test-dev 上框 AP 为 58.7、掩码 AP 为 51.1。这些同样是论文数字，本课未复现。\n\n## 目标检测简史\n\n本单元挂了 Faster R-CNN、YOLO 与 DETR，下面只说明它们各自解决的问题，不展开成另一门检测课。\n\n**两阶段：Faster R-CNN。** 在 R-CNN 与 Fast R-CNN 之后，区域建议本身成了速度瓶颈。Ren、He、Girshick 与 Sun（2015）引入区域建议网络（Region Proposal Network，RPN）：它是一个与检测头共享整图卷积特征的全卷积网络，在每个位置同时预测物体边界与 objectness。作者把这种共享称为“几乎免费”的建议，边际成本约为每张图 10 ms。对 VGG-16，检测系统在 GPU 上含全部步骤为 5 fps，每张图使用 300 个建议；论文表 5 在 K40 GPU 上给出 RPN + Fast R-CNN 的合计 198 ms（其中建议 10 ms）。RPN 用一组锚框覆盖不同尺度与宽高比。\n\n**单阶段：YOLO。** Redmon、Divvala、Girshick 与 Farhadi（2015）把检测写成一次回归：单个网络在一次前向中同时给出边界框和类别概率，整条流水线可以端到端优化。图像被划分成 S×S 网格，物体中心落在哪一格，就由那一格负责；每格预测 B 个边界框及其置信度，以及 C 个类别概率，输出张量为 S×S×(B×5+C)。在 PASCAL VOC 上，S=7、B=2、C=20，因此最终预测是 7×7×30 张量。输入先被调整到 448×448。论文报告：基础 YOLO 在 Titan X 上无批处理时为 45 fps；更快的 Fast YOLO 在摘要中为 155 fps，正文写为超过 150 fps。论文还给出当时设定下 63.4% 的 mAP。今日常用的 Ultralytics YOLO 是后续多代模型的工程实现，接口与训练流程以官方文档为准，不要把 2015 年的 45 fps 直接当成当前硬件与模型的速度。\n\n**集合预测：DETR。** Carion、Massa、Synnaeve 等人（2020）把检测看成对集合的直接预测。图像先经 CNN 骨干得到二维特征，展平并加上位置编码后进入 Transformer 编码器；解码器以 N 个可学习的 object query（论文实验中 N=100）为输入，结合编码器输出，再由共享的前馈网络预测类别与框，或预测“无物体”。训练用匈牙利算法做预测与真值之间的二分图匹配，从而使损失对排列不变，并避免一对多的重复框，因此不必再依赖非极大值抑制与锚框设计。论文写明，参数量与 Faster R-CNN 相近的模型在 COCO val 上达到 42 AP，对大物体更好（AP_L 提高 7.8），对小物体仍落后（AP_S 低 5.5）。\n\n| 方法 | 年份 | 核心结构 | 后处理 | 论文中的速度或精度（原文设定） |\n|---|---|---|---|---|\n| Faster R-CNN | 2015 | 共享特征的 RPN + 检测头 | 建议后再分类、回归 | VGG-16，K40 GPU，全部步骤 5 fps；300 个建议 |\n| YOLO（v1） | 2015 | 单网络回归，S×S 网格 | 阈值与去重 | Titan X 上基础模型 45 fps；VOC 上 7×7×30 |\n| DETR | 2020 | 编码器–解码器 + object query | 二分图匹配，无需 NMS | COCO val 上 42 AP（与 Faster R-CNN 相近参数） |\n\n## 分割：U-Net 与 Segment Anything\n\n**U-Net。** Ronneberger、Fischer 与 Brox（2015）为生物医学影像设计了 U 形编码器–解码器。收缩路径重复“两个 3×3 卷积 + ReLU + 2×2 最大池化”，扩张路径则上采样并用 2×2 上卷积减半通道，再与收缩路径中经裁剪的对应特征图拼接，然后接两个 3×3 卷积。这种跳跃连接让解码器同时利用上下文与高分辨率定位信息。网络没有全连接层，共 23 个卷积层；因使用 valid 卷积，分割图只覆盖输入中具有完整上下文的像素，并可用重叠切片（overlap-tile）拼接大图。训练上，作者强调用弹性形变等增强，以便在标注很少时仍能端到端训练。\n\n**SAM。** Kirillov、Mintun、Ravi 等人（2023）把分割定义成可提示任务：给定任意提示，返回至少一个合理的掩码；当提示有歧义时（例如落在衬衫上的一个点也可能指人），输出应对其中一种读法成立。提示可以包含空间或文本信息，公开实现里最常用的是点、框和掩码。模型由图像编码器、提示编码器和掩码解码器组成，并按提示做零样本迁移。配套数据集 SA-1B 含 11M 张经过许可、顾及隐私的图像，以及超过 10 亿个掩码，项目页为 [segment-anything.com](https://segment-anything.com/)。这些数据与模型规模上的数字来自论文，本课未下载 SA-1B 或官方权重。\n\n## 自监督视觉\n\n有标注的图像往往比未标注图像少得多。自监督学习用图像自身构造任务，先得到可迁移的表示，再用线性探针或微调接到下游。下面四条主线覆盖本单元已挂的算法。\n\n### 对比学习与 InfoNCE\n\nvan den Oord、Li 与 Vinyals（2018）在 Contrastive Predictive Coding 中给出 InfoNCE。给定集合 X={x_1,…,x_N}，其中包含一个来自条件分布 p(x_{t+k}|c_t) 的正样本，以及 N−1 个来自提议分布 p(x_{t+k}) 的负样本，优化\n\n```text\nL_N = − E[  log  f_k(x_{t+k}, c_t) / Σ_{x_j ∈ X} f_k(x_j, c_t)  ]\n```\n\n最小化 L_N 等价于最大化互信息 I(x_{t+k}, c_t) 的一个下界：I(x_{t+k}, c_t) ≥ log(N) − L_N，且 N 越大界越紧。直觉是：让模型把“与当前上下文相容”的样本从一批干扰项里认出来。\n\n### SimCLR\n\nChen、Kornblith、Norouzi 与 Hinton（2020）把这一思想做成一个尽量简单的视觉框架。对每个样本独立采样两种增强，得到两个相关视图；编码器 f(·) 与投影头 g(·) 被训练来最大化一致。增强主要包括随机裁剪并缩放回原尺寸、颜色扰动和高斯模糊。对比损失是 NT-Xent（normalized temperature-scaled cross entropy）：对批次中 N 张图像的 2N 个视图，正对 (i, j) 的损失为\n\n```text\nℓ_{i,j} = − log  exp(sim(z_i, z_j)/τ) / Σ_{k=1, k≠i}^{2N} exp(sim(z_i, z_k)/τ)\n```\n\n其中 sim 是 ℓ₂ 归一化后的余弦相似度，τ 是温度。一个大小为 8192 的批次给每个正对提供 16382 个负例（论文原数）；作者在研究中把批次从 256 扫到 8192，默认消融常用批次 4096、训练 100 个周期，并使用 LARS 与全局 Batch Normalization。他们强调三点：增强的组合很关键；表示与损失之间要有可学习的非线性投影；对比学习比监督训练更需要大批次和更多步数。摘要中，线性分类器加在 SimCLR 学到的表示上，ImageNet top-1 为 76.5%。如前所述，实际使用的是投影头之前的 h。\n\n### MAE\n\nHe、Chen、Xie 等人（2021）的掩码自编码器走另一条路：随机遮盖输入 patch，并重建缺失像素。两个设计最关键。第一是非对称结构：编码器只看到可见 patch，不包含掩码标记；掩码标记在编码器之后才加入，由轻量解码器处理完整集合并在像素空间重建。预训练结束后丢掉解码器，识别时编码器处理全部未遮盖的 patch。第二是很高的遮盖率，例如 75%：图像空间冗余大，低遮盖往往太容易；高遮盖既构成更难的任务，又让编码器只处理约 25% 的 patch，论文称预训练可加速 3 倍或更多。对 196 个 patch、75% 遮盖，可见 49 个、被遮 147 个；论文图 2 用 80% 遮盖，196 个中留下 39 个，与 196×0.20=39.2 四舍五入一致。作者还报告，仅在 ImageNet-1K 上训练的普通 ViT-Huge 达到 87.8%，是当时只用该数据集的方法中最高的。这是论文结果，本课未训练 MAE。\n\n### DINOv2 与自蒸馏\n\nCaron、Touvron、Misra 等人（2021）的 DINO 把自监督做成学生–教师自蒸馏：两个网络结构相同但参数不同，学生与教师分别处理同一图像的不同随机变换；教师输出在批次上做中心化，两边经温度 softmax 后用交叉熵衡量一致；梯度只通过学生，教师参数是学生的指数滑动平均。无需类别标签。\n\nOquab、Darcet、Moutakanni 等人（2023）的 DINOv2 在这一路线上扩大数据与模型。他们用自动流水线从约 12 亿张来源图像中构造精心筛选的 LVD-142M（1.42 亿张），而不是直接使用未筛选数据。模型方面，训练约 10 亿参数的 ViT，再蒸馏到一系列更小的模型；文中 ViT-g 骨干为 11 亿参数（嵌入维 1536、24 个注意力头）。目标是得到可在多种图像分布和任务上使用、不必微调的通用特征。官方介绍（2023-04-17）也强调：特征可直接接线性分类器，线性评估与微调的差距在 ImageNet-1k 上约在 2 个百分点以内。具体精度以论文表格为准，本课不做复现。\n\n### I-JEPA\n\nAssran、Duval、Misra 等人（2023）提出图像版的联合嵌入预测架构 I-JEPA：从单一上下文块预测同一图像中若干目标块的表示。它是非生成式的，不在像素空间重建；作者还写明，不必依赖人工设计的数据增强来构造多视图。为了让表示更有语义，目标块需要有足够大的尺度，上下文块则应有足够的空间覆盖。编码器是只处理可见上下文 patch 的 ViT，预测器是较窄的 ViT，并在目标位置编码的条件下做预测；目标编码器的权重由上下文编码器的指数滑动平均更新。论文报告，在 ImageNet 上用 16 块 A100 在 72 小时内训练 ViT-H/14，即可在线性分类等到下游任务上取得较强结果。Meta AI 在 2023-06-13 的介绍中用同样的结构说明：比较的是图像的抽象表示，而不是像素本身。\n\n| 方法 | 年份 | 学习信号 | 预测或比较的对象 | 训练后通常保留的部分 |\n|---|---|---|---|---|\n| SimCLR | 2020 | 同一图像两个增强视图的一致 | 投影空间中的余弦相似度（NT-Xent） | 编码器 f(·)，丢掉投影头 |\n| MAE | 2021 | 随机高比例遮盖 | 被遮 patch 的像素 | 编码器，丢掉解码器 |\n| DINO / DINOv2 | 2021 / 2023 | 学生–教师自蒸馏 | 输出分布的一致 | 教师或蒸馏得到的骨干，可冻结 |\n| I-JEPA | 2023 | 上下文块预测目标块 | 表示空间中的目标嵌入 | 上下文/目标编码器，不重建像素 |\n\n## 实践：线性探针、微调与现成工具\n\n预训练只给出表示，接到具体任务时常见两种做法。\n\n- **线性探针（linear probe）**：冻结骨干，只训练一个线性分类头。它衡量表示本身是否线性可分，计算量较小，也便于比较不同预训练方法。SimCLR、MAE、I-JEPA、DINOv2 的论文都把线性评估作为标准读数之一。\n- **微调（fine-tuning）**：骨干与任务头一起更新，通常能得到更高的任务精度，但表示会向该任务靠拢，不再同样通用。DINOv2 的官方介绍强调，其线性评估已接近微调（ImageNet-1k 上约 2 个百分点以内），适合把同一组冻结特征接到多个任务。\n\n不要把论文里的 ImageNet 数字直接当成自己数据上的结果。迁移时应固定随机种子，写明骨干名称与是否冻结，并在同一划分上比较线性探针与微调。\n\n工程上，[timm](https://huggingface.co/docs/timm/index) 提供统一接口，可加载 ViT、Swin、DINOv2 等预训练骨干，在小型数据集上做分类或作为特征提取器。[SAM 官方仓库](https://github.com/facebookresearch/segment-anything) 支持点、框等提示，也可在一批图像上做自动掩码生成，为检测或分割准备标注。[Ultralytics YOLO](https://docs.ultralytics.com/) 的[训练文档](https://docs.ultralytics.com/modes/train/)说明了如何在自定义图像上训练检测器。本课不下载数 GB 的预训练权重，也不报告未运行过的精度。\n\n## 本课可运行示例\n\n脚本 `_work/daily/2026-11-23/vision_demo.py` 只使用 NumPy，不下载权重。环境为 `/workspace/.venv-learn`，Python 3.13.5，NumPy 2.5.4，`seed=0`。输出见同目录 `vision_demo_results.json`。\n\n1. **分块算术**与上一节表格一致：224×224、P=16 时 N=196、加分类标记为 197；MAE 75% 遮盖时可见 49、被遮 147；80% 时 196×0.20=39.2，四舍五入为 39，与论文图 2 的“196 中留下 39 个”一致。\n2. **合成向量上的 NT-Xent**。构造 N=8 个 16 维单位潜向量，每个加标准差 0.15 的高斯噪声形成两个视图（共 16 个向量）。正对的平均余弦为 0.735972，负对为 0.000257。不同温度下的批次平均损失为：τ=0.05 时 0.014323，τ=0.1 时 0.127325，τ=0.5 时 1.542188，τ=1.0 时 2.071892。把配对打乱后，τ=0.1 的损失升至 7.402600。若所有向量完全相同，损失为 2.708050，与解析值 log(2N−1)=log(15)=2.708050 一致。温度变小会更尖锐地放大正负差距，从而降低已经可分样本上的损失；这只说明公式行为，不是在真实图像上的调参建议。\n3. **Swin 窗口计数**见上一节表格，用于核对“窗口注意力对图像尺寸近似线性、全局注意力为二次”的计数关系。\n\n## 动手练习\n\n1. **单元项目**：用预训练 ViT 在小型图像分类数据上比较线性探针与微调，记录同一划分上的精度与训练设置；再用 SAM 按点或框提示（或自动掩码生成）标注一批图片，抽查掩码是否与提示对象一致。\n2. 完成 [Hugging Face 计算机视觉课](https://huggingface.co/learn/computer-vision-course/unit0/welcome/welcome) 的动手单元，对照本课的分块与编码器用法。\n3. 用 [timm](https://huggingface.co/docs/timm/index) 加载 ViT、Swin、DINOv2 等骨干，在小数据集上做迁移学习，比较冻结骨干与全部微调。\n4. 按照 [Ultralytics 训练文档](https://docs.ultralytics.com/modes/train/)，用 YOLO 在自己的照片上训练一个目标检测器，写明模型版本、图像尺寸与训练周期。\n\n## 推荐学习顺序\n\n先复习 [Transformer 与注意力](/learn/transformer-attention) 中的自注意力与位置编码，并用本课的分块公式算一遍 224×224 的序列长度。ViT 读 Dosovitskiy 等人的原文第 3 节；需要分层骨干时读 Swin 论文中窗口与平移窗口两节，或官方仓库。检测可按 Faster R-CNN → YOLO v1 → DETR 的顺序看问题如何被重新表述，现代 YOLO 的用法以 [Ultralytics 文档](https://docs.ultralytics.com/) 为准。分割先看 U-Net 的跳跃连接，再看 SAM 的提示式任务与官方仓库。自监督建议按 InfoNCE / SimCLR → MAE → DINO / DINOv2 → I-JEPA 对照“比较视图、重建像素、自蒸馏、预测表示”四条线，并在 timm 上用线性探针体会冻结特征。随后同一阶段的[视觉语言模型](/learn/vision-language)会把这里的图像编码器接到语言模型。"
    }
  }
}