Computer vision: CNNs & Vision Transformers

In one sentence

A backbone (a CNN sliding small filters, or a ViT attending over image patches) turns pixels into features; task heads turn them into labels, boxes or masks. Start from a pretrained backbone.

Analogy: A CNN reads a photo with a magnifying glass, building up from strokes to shapes to objects. A ViT cuts the photo into puzzle pieces and lets every piece compare notes with every other.

Two backbone families, one interface: features in, task heads out. You can swap the backbone and keep the heads.

How it works

  • CNNs reuse small filters at every position, so an edge detector finds edges anywhere with few parameters.
  • Pooling and stacked layers grow the receptive field: edges → textures → parts → objects.
  • ResNet skip connections let gradients flow through 100+ layers; ResNet-50 is still the standard baseline.
  • ViTs treat 16×16 patches as tokens: global context from layer one, but they need more data or pretraining.
  • Transfer learning plus augmentation (crops, flips, color jitter) gets strong results from a few thousand labeled images.

Check yourself

Answer to mark it learned; your answers aren't scored.

A defect classifier scores 96% offline but ~80% in production on the same camera line. You rerun a day of logged production images through your training data loader and the model scores 95%. Most likely cause?

Go deeper

Full explanation

Vision models turn pixels into features with a backbone; a task head turns features into an answer.

CNNs slide small learned filters (e.g. 3×3) over the image, reusing the same weights at every position: an edge detector finds edges anywhere, with few parameters. Pooling (or strided convs) halves the resolution, and stacking layers grows the receptive field, the input area one unit sees: edges → textures → parts → objects. ResNet added skip connections, output = F(x) + x, so gradients flow through 100+ layers; ResNet-50 is still the standard baseline.

Vision Transformers (ViT) cut the image into 16×16 patches and embed each as a token (224×224 → 196 tokens) for a standard Transformer architecture. Every patch attends to every other from layer one: global context, but no built-in locality, so ViTs need more data or pretraining to beat CNNs, and attention cost grows quadratically with patch count.

Tasks: classification (one label per image), detection (boxes + classes; YOLO-style single-stage detectors predict every box in one forward pass, then non-max suppression drops duplicates) and segmentation (a class per pixel).

You rarely train from scratch: transfer learning from an ImageNet- or CLIP-pretrained backbone, plus data augmentation (crops, flips, color jitter) that teaches invariances, gets strong results from a few thousand labeled images.

Code Transfer learning with augmentation, and ViT patchify
pythonTransfer learning with augmentation, and ViT patchify
import torch, torch.nn as nn
from torchvision import models, transforms

# Augment at train time only: the label survives a crop or flip, so the model learns invariance
train_tf = transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(0.2, 0.2, 0.2),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),  # ImageNet stats
])

# Transfer learning: ImageNet backbone, new head for 5 defect classes
model = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V2)
for p in model.parameters():
    p.requires_grad = False                        # freeze the features first
model.fc = nn.Linear(model.fc.in_features, 5)      # 2048 -> 5: the only trainable layer
opt = torch.optim.AdamW(model.fc.parameters(), lr=1e-3)

# ViT's view of an image: 224 / 16 = 14, so 14 x 14 = 196 patch tokens
img = torch.randn(1, 3, 224, 224)
patches = img.unfold(2, 16, 16).unfold(3, 16, 16)   # (1, 3, 14, 14, 16, 16)
tokens = patches.permute(0, 2, 3, 1, 4, 5).reshape(1, 196, 3 * 16 * 16)
print(tokens.shape)  # (1, 196, 768) -> linear projection -> transformer
Real example

Tesla's Autopilot stack, as presented at AI Day 2021: 8 cameras feed one shared backbone (a RegNet CNN with a BiFPN for multi-scale features). A transformer then fuses all cameras into a single bird's-eye-view (BEV) space around the car, a video module adds memory across frames, and many task heads share the result in a "HydraNet" (vehicles, lanes, traffic lights). Why BEV: a truck spanning three cameras becomes one object in 3D instead of three partial boxes, and the planner reasons top-down anyway. The shared backbone means one expensive pass serves dozens of tasks inside the car's latency budget.

Trade-offs +4 · −3

+ You gain

  • Pretrained backbones transfer well: a few thousand labeled images are often enough for a strong model.
  • CNNs are efficient and mature on edge hardware: phones, cameras, cars.
  • ViTs scale with data and share the transformer stack with LLMs, which makes multimodal models natural.
  • One backbone can feed many heads, amortizing compute across tasks.

− You pay

  • Labels are expensive, especially boxes and pixel masks.
  • ViT attention cost grows quadratically with patches: high-resolution inputs get expensive.
  • Domain shift (lighting, weather, a new camera) silently degrades accuracy.

Use it when

Any pixel input at volume or under latency limits: inspection, retail shelves, medical scans, document images, driving. CNN or small ViT for edge and real time; large ViT when data and compute are plentiful.

Avoid it when

Don't train a custom model first if a multimodal LLM or zero-shot CLIP already meets accuracy at your volume and cost. Don't ship a large ViT under tight edge latency without distilling it.

Numbers to know 5
  • AlexNet (2012): 15.3% top-5 ImageNet error vs 26.2% for the runner-up, the start of deep learning in vision.
  • ResNet won ILSVRC 2015 at 3.57% top-5 error with up to 152 layers; ResNet-50: ~25.6M params, ~3.8 GFLOPs per image.
  • ViT-B/16 at 224×224: 196 patch tokens (+1 [CLS]), ~86M params.
  • Original YOLO: 45 FPS on a Titan X GPU; Fast YOLO: 155 FPS.
  • Two stacked 3×3 convs see 5×5 and three see 7×7, with 27C² weights vs 49C² for one 7×7.
Common pitfalls 4
  • Train/serve preprocessing mismatch: a different resize, BGR vs RGB or normalization silently costs accuracy.
  • Augmentations that change the label: flipping text or left/right signs, cropping out the defect.
  • Leakage: near-duplicate frames of the same video or patient in train and test. Split by video, scene or patient.
  • Judging a detector by accuracy: report mAP at a stated IoU and recall on rare, safety-critical classes.
Interview questions 3

Answer out loud first, then reveal.

CNN or Vision Transformer: how do you choose?Show answer

It comes down to data and constraints. CNNs bake in locality and weight sharing, so they're data-efficient and fast on edge hardware; for small datasets or tight latency, a ResNet- or ConvNeXt-class model is my default. ViTs have weaker built-in assumptions, so from scratch they need far more data, but pretrained at scale they match or beat CNNs, see global context from layer one and plug into multimodal models. In practice I fine-tune a pretrained backbone of each type and compare on my own eval set under the latency budget, watching attention cost at high resolution.

Why do residual connections matter?Show answer

Before ResNet, adding layers beyond ~20 made training error go up: an optimization problem, not overfitting. A residual block outputs F(x) + x, so the identity is the default: a useless block can push F toward zero, and gradients flow straight through the skip path to early layers. That let He et al. train 152 layers in 2015 and win ImageNet. The same trick sits inside every transformer block today and is a big reason deep LLMs train stably.

Why fuse a car's cameras into bird's-eye view instead of detecting per camera?Show answer

Per-camera detections live in image space, and stitching them is brittle: a truck spanning three cameras becomes three partial boxes, and depth from one image is ambiguous. Fusing features from all cameras into one top-down grid lets the network resolve objects in 3D directly, handle occlusion across views and output the space the planner actually uses. A video module adds memory, so a car hidden for a second isn't forgotten. The cost: you need 3D labels at scale, which pushes you to auto-labeling, and camera calibration must be precise.