AI Logic

Architectures

SSD

Updated:

SSD architecture. Left: the overall flow. A 300×300 input image passes through VGG-16; 3×3 convolutional predictors are applied to each of six feature maps — conv4_3 (38×38), conv7 (19×19), and the added conv8_2 (10×10), conv9_2 (5×5), conv10_2 (3×3), and conv11_2 (1×1) — and the resulting 8732 boxes are collected and filtered by per-class non-maximum suppression. Right: default boxes and predictions. Each cell of a feature map holds 4 or 6 default boxes with different aspect ratios, and each box outputs c class scores and 4 offsets; also shown are the per-layer scale formula and the loss (classification + localization, and how positives and negatives are chosen)

Background and Overview

SSD (Single Shot MultiBox Detector) is an object detection method that places boxes of fixed sizes and aspect ratios (default boxes) at every location of several feature maps of different sizes, and predicts the class scores and box offsets for each box in one pass with small convolutions. It was proposed in 2016 by Liu et al. at the University of North Carolina at Chapel Hill and Google (ECCV 2016).

Until then, accurate detectors took a two-stage form, like Faster R-CNN: generate candidate regions, then re-extract features for each candidate and classify it. This is accurate, but even Faster R-CNN processes only about 7 images per second. YOLO, which has no proposal stage, is fast at 45 images per second but loses much accuracy. SSD removed both the proposal stage and feature re-extraction while matching the accuracy of two-stage detectors.

The paper's main results are as follows.

  • SSD300, with a 300×300 input, achieved 74.3% mAP on PASCAL VOC 2007 test at 59 fps (Titan X, batch 8). It is both faster and more accurate than Faster R-CNN (73.2%, 7 fps) and YOLO (63.4%, 45 fps).
  • SSD512, with a 512×512 input, reached 76.8%, outperforming Faster R-CNN with the same VGG-16 backbone.
  • According to the paper, SSD300 was the first real-time detector (tens of images per second) to exceed 70% mAP.

SSD's layout (a backbone network → several feature maps of different sizes → convolutional predictors on each) became the basic template for later one-stage detectors.

The Problem: Keeping Accuracy Without a Proposal Stage

The problem SSD addressed is that removing candidate regions and the re-extraction of their features makes detection faster but greatly reduces accuracy.

A two-stage detector re-crops features from the feature map for each candidate region (RoI pooling) and redoes classification and box refinement. This re-extraction underpins its accuracy, but computation grows with the number of candidates. OverFeat and YOLO attempted to remove the proposal stage, but fell short of two-stage detectors in accuracy. The paper identifies one cause of the gap in YOLO predicting boxes with fully connected layers from only a single top-level feature map.

The paper combined three ideas to raise accuracy without a proposal stage.

  • Predict with small convolutions: Instead of fully connected layers, a 3×3 convolution at each feature-map location outputs class scores and box offsets.
  • Use separate predictors for each aspect ratio: Several default boxes with different aspect ratios are placed at each location, each predicted by its own filters.
  • Predict from several feature maps of different sizes: High-resolution maps handle small objects and low-resolution maps handle large ones.

As an everyday analogy, a two-stage detector puts sticky notes on suspicious spots and then examines each one again with a magnifying glass. SSD casts several nets with different mesh sizes at once, and each cell of each net immediately answers "what is here" and "how much to shift the box".

Theory: Default Boxes and Multi-Scale Feature Maps

SSD is a network that for each default box placed at each cell of a feature map, outputs cc class scores and 4 offsets from the box to the object's bounding box using a 3×3 convolution. The left side of the figure at the top of the article shows the overall flow, and the right side shows default boxes and predictions.

SSD300 processes an image as follows.

  1. The image is resized to 300×300 and passed through VGG-16. VGG-16's fully connected layers fc6 and fc7 are converted to convolutional layers (conv6 and conv7), and the downsampling in pool5 is removed, with dilated convolution preserving the receptive field.
  2. After conv7, convolutional layers (pairs of 1×1 and 3×3) that progressively shrink the feature map are added.
  3. Six feature maps of different sizes are used for prediction: conv4_3 (38×38), conv7 (19×19), conv8_2 (10×10), conv9_2 (5×5), conv10_2 (3×3), and conv11_2 (1×1). Because conv4_3 has a different feature scale from the other layers, it is L2-normalized at each location before use.
  4. kk default boxes are placed at each cell of each feature map, and a 3×3×pp convolution outputs cc class scores (including background) and 4 offsets per box. An m×nm \times n feature map yields (c+4)kmn(c + 4)kmn outputs.
  5. From the 8732 boxes across the six layers, boxes with scores below 0.01 are discarded, per-class non-maximum suppression with IoU 0.45 is applied, and the top 200 per image are kept as detections.

kk is 4 for conv4_3, conv10_2, and conv11_2, and 6 for the other layers. The number of boxes is 382×4+192×6+102×6+52×6+32×4+12×4=873238^2 \times 4 + 19^2 \times 6 + 10^2 \times 6 + 5^2 \times 6 + 3^2 \times 4 + 1^2 \times 4 = 8732.

The scale of the default boxes at the kk-th layer, when mm feature maps are used for prediction, is given by the following formula. Scale is expressed as a fraction of the image side.

sk=smin⁡+smax⁡−smin⁡m−1(k−1),k∈[1,m]s_k = s_{\min} + \frac{s_{\max} - s_{\min}}{m - 1}(k - 1), \quad k \in [1, m]

With smin⁡=0.2s_{\min} = 0.2 and smax⁡=0.9s_{\max} = 0.9, the lowest layer has scale 0.2, the highest has 0.9, and the layers in between are evenly spaced (for SSD300 on PASCAL VOC, conv4_3 alone is set to 0.1). The width and height of a box with aspect ratio ar∈{1,2,3,12,13}a_r \in \{1, 2, 3, \tfrac{1}{2}, \tfrac{1}{3}\} are set to preserve its area:

wka=skar,hka=skarw_k^a = s_k \sqrt{a_r}, \quad h_k^a = \frac{s_k}{\sqrt{a_r}}

For aspect ratio 1, an extra box of scale sk′=sksk+1s'_k = \sqrt{s_k s_{k+1}} is added, giving 6 boxes per location (layers with k=4k = 4 boxes per location omit aspect ratios 3 and 1/3). The center of each box is (i+0.5∣fk∣,j+0.5∣fk∣)\left(\frac{i + 0.5}{|f_k|}, \frac{j + 0.5}{|f_k|}\right), where ∣fk∣|f_k| is the number of cells along one side of the kk-th feature map.

Default boxes are essentially the same idea as the anchors in Faster R-CNN. There are two differences. First, they are placed not on a single feature map but on several feature maps of different resolutions. Second, while the RPN outputs only "object or not" to generate proposals, SSD directly outputs scores for every class per box and uses them as the final detections.

Training: Matching and Loss

Training SSD starts by deciding which default box is responsible for which ground-truth box, and then minimizes classification and localization losses. Unlike two-stage detectors, it must decide in advance which of a fixed set of outputs each ground truth is assigned to.

Matching is decided by IoU (the overlap ratio of two boxes) as follows.

  • Each ground-truth box is matched to the default box with the highest IoU.
  • In addition, any default box with IoU above 0.5 with some ground-truth box is also matched to it.
  • Boxes not matched to any ground truth become negatives (background).

The second rule makes several overlapping boxes positives for a single object. The paper explains that this simplifies learning compared with forcing the network to pick only the single best-overlapping box.

The loss is a weighted sum of the classification loss LconfL_{conf} and the localization loss LlocL_{loc}, divided by the number of matched boxes NN (the loss is 0 if N=0N = 0).

L(x,c,l,g)=1N(Lconf(x,c)+αLloc(x,l,g))L(x, c, l, g) = \frac{1}{N}\left(L_{conf}(x, c) + \alpha L_{loc}(x, l, g)\right)

xijp∈{0,1}x_{ij}^p \in \{0, 1\} indicates whether the ii-th default box is matched to the jj-th ground-truth box of class pp. The localization loss is the Smooth L1 loss (Huber loss with δ=1\delta = 1) between the predicted offsets ll and g^\hat{g}, the ground-truth box gg expressed relative to the default box dd, computed over positives only.

Lloc(x,l,g)=∑i∈PosN∑m∈{cx,cy,w,h}xijk smoothL1(lim−g^jm)L_{loc}(x, l, g) = \sum_{i \in Pos}^{N} \sum_{m \in \{cx, cy, w, h\}} x_{ij}^k \, \mathrm{smooth}_{L1}\left(l_i^m - \hat{g}_j^m\right) g^jcx=gjcx−dicxdiw,g^jcy=gjcy−dicydih,g^jw=log⁡gjwdiw,g^jh=log⁡gjhdih\hat{g}_j^{cx} = \frac{g_j^{cx} - d_i^{cx}}{d_i^w}, \quad \hat{g}_j^{cy} = \frac{g_j^{cy} - d_i^{cy}}{d_i^h}, \quad \hat{g}_j^w = \log\frac{g_j^w}{d_i^w}, \quad \hat{g}_j^h = \log\frac{g_j^h}{d_i^h}

The classification loss is softmax cross-entropy. Positives learn to predict their ground-truth class, and negatives learn to predict background (class 0).

Lconf(x,c)=−∑i∈PosNxijplog⁡c^ip−∑i∈Neglog⁡c^i0,c^ip=exp⁡(cip)∑pexp⁡(cip)L_{conf}(x, c) = -\sum_{i \in Pos}^{N} x_{ij}^p \log \hat{c}_i^p - \sum_{i \in Neg} \log \hat{c}_i^0, \quad \hat{c}_i^p = \frac{\exp(c_i^p)}{\sum_p \exp(c_i^p)}

The weight α\alpha is set to 1 by cross-validation.

Choosing negatives (hard negative mining): After matching, most boxes are negatives. Using all of them would heavily skew the ratio of positives to negatives, so negatives are sorted by classification loss and only the top ones are kept, so that the ratio of negatives to positives is at most 3:1. According to the paper, this leads to faster optimization and more stable training.

Data augmentation: To make the model robust to object sizes and shapes, one of the following is chosen at random for each training image.

  • Use the entire original image.
  • Sample a patch so that the minimum IoU with the objects is 0.1, 0.3, 0.5, 0.7, or 0.9.
  • Randomly sample a patch.

The patch size is 0.1–1 times the original image, and its aspect ratio is between 1/2 and 2. Only ground-truth boxes whose centers fall inside the patch are kept. After sampling, the patch is resized to a fixed size, flipped horizontally with probability 0.5, and photometrically distorted (brightness and color).

SSD's accuracy depends heavily on data augmentation. In the paper's experiments, removing the patch sampling above dropped VOC 2007 test mAP from 74.3% to 65.5%, a loss of 8.8 points. Reusing Faster R-CNN's training recipe (original images and horizontal flips only) as is will not reproduce the paper's accuracy.

Why It Is Fast and Accurate

The reasons SSD achieves high accuracy without a proposal stage can be summarized from the paper's experiments (SSD300, VOC 2007 test) as follows.

  • Fast because there is no proposal stage or feature re-extraction: Box prediction is just a 3×3 convolution over feature maps. According to the paper, about 80% of the computation time is spent in the backbone (VGG-16); the added layers take 2.4 ms in total, and non-maximum suppression about 1.7 ms. Swapping in a faster backbone makes it faster still.
  • Predicting from multi-scale feature maps catches objects of different sizes: Reducing the number of layers used for prediction (while keeping the total number of boxes roughly the same) steadily lowered mAP from 74.3%, down to 62.4% with conv7 alone. Assigning boxes of different sizes to different layers matters.
  • More default boxes with different aspect ratios make boxes easier to fit: Removing boxes with aspect ratios 3 and 1/3 dropped mAP to 73.7% (−0.6 points), and also removing 2 and 1/2 dropped it to 71.6% (a further −2.1 points).
  • Learning localization and classification in one pass reduces localization errors: In an analysis that breaks false positives down by type, SSD had fewer localization errors than R-CNN, which the paper attributes to learning regression to object shapes and classification together rather than in two separate stages.

VGG-16 was modified with dilated convolution mainly for speed. Keeping the original VGG-16 (pool5 at 2×2 with stride 2, fc6 and fc7 not subsampled) and also using conv5_3 for prediction gave nearly the same mAP (74.2%) but was about 20% slower.

Experimental Results

PASCAL VOC 2007 test (mAP %; Fast R-CNN and Faster R-CNN use inputs with a shorter side of 600 pixels)

MethodTraining data: 0707+1207+12+COCO
Fast R-CNN66.970.0―
Faster R-CNN69.973.278.8
SSD30068.074.379.6
SSD51271.676.881.6

"07" is VOC 2007 trainval, "07+12" is the union of VOC 2007 and 2012 trainval, and "07+12+COCO" means training on COCO and then fine-tuning on 07+12.

Speed and accuracy (VOC 2007 test, Titan X)

MethodmAP %fpsBatchNumber of boxesInput size
Faster R-CNN (VGG-16)73.271~6000~1000×600
Fast YOLO52.7155198448×448
YOLO (VGG-16)66.421198448×448
SSD30074.34618732300×300
SSD51276.819124564512×512
SSD30074.35988732300×300
SSD51276.822824564512×512

COCO test-dev2015 (%)

MethodAP@[.5:.95]AP@0.5AP@0.75AP (small objects)AP (large objects)
Faster R-CNN (value from the Faster R-CNN paper)21.942.7―――
Faster R-CNN (another report trained on trainval, listed in Table 5 of the paper)24.245.323.57.737.1
SSD30023.241.223.45.339.6
SSD51226.846.527.89.041.9

SSD512 beats the stronger Faster R-CNN in Table 5 by 4.3 points in AP@0.75 and 4.8 points in AP for large objects, while its margin on small objects is only 1.3 points. The paper speculates that Faster R-CNN's two rounds of box refinement (in the RPN and in the detector) give it an advantage on small objects.

Data augmentation for small objects (the reverse of zooming in): Patch sampling acts as a "zoom in" that makes objects appear larger. Conversely, the paper added a "zoom out" augmentation that makes objects appear smaller: the original image is placed at a random position on a canvas up to 16 times its size filled with the mean color, before patch sampling (with twice as many training iterations).

ModelVOC 2007 test (07+12)COCO test-dev AP@[.5:.95]
SSD30074.323.2
SSD300 (with added augmentation)77.225.1
SSD51276.826.8
SSD512 (with added augmentation)79.828.8

Practical Considerations

Keep the following points in mind when using SSD.

  • Weak on small objects: The paper's own analysis shows that SSD is sensitive to object size, with much lower accuracy on small objects than on large ones. Information about small objects is hard to retain in the coarse feature maps of the upper layers. Remedies include enlarging the input from 300×300 to 512×512 and adding the zoom-out data augmentation.
  • Prone to confusing similar classes: The paper's analysis shows frequent confusion, especially among animals, attributed in part to sharing one location across multiple classes.
  • Tune default boxes to the data: The paper itself notes that scales and aspect ratios can be designed to fit the data and that optimal tiling remains an open question. On COCO, where objects are smaller, smin⁡s_{\min} is lowered to 0.15 and the scale of conv4_3 to 0.07.
  • Imbalance between positives and negatives: Nearly all of the 8732 boxes are background. SSD limits negatives to three times the positives with hard negative mining, and Focal Loss, which handles this imbalance through the form of the loss, was proposed later.

The num_classes passed to torchvision's ssd300_vgg16 includes the background (21 for 20 object classes). The model also resizes images to 300×300 and normalizes them internally. The paper's data augmentation (patch sampling, zoom out, photometric distortion) is not included in the model, so it must be provided separately in the training data loader. In model.train() mode it returns a dictionary of losses, and in model.eval() mode it returns detections.

Comparison with Other Methods

SSD is one of the one-stage detectors without a proposal stage. Compared on the same terms, they line up as follows (times are each paper's reported values and only a rough guide, since GPU types differ).

MethodStagesHow boxes are predictedFeature maps used for predictionVOC 2007 test mAP (07+12) and speed
Faster R-CNNTwo-stageRoI pooling per RPN proposal, then classification and refinement173.2%, 7 fps (VGG-16)
YOLOOne-stageFully connected layers output boxes and classes for each cell of a 7×7 grid163.4%, 45 fps
SSDOne-stage3×3 convolutions per default box at each layer6 (different sizes)74.3%, 59 fps (SSD300)
FPN (with Faster R-CNN)Two-stageRPN and detector at each level of a feature pyramid5 (with top-down information added)― (evaluated on COCO)
DETROne-stageA Transformer outputs a fixed number of boxes as a set1― (evaluated on COCO)

SSD and FPN both predict from feature maps of different sizes, but build them differently. SSD uses the intermediate maps of the backbone as they are, so the high-resolution conv4_3 carries little semantic information, making SSD weak on small objects. FPN upsamples the semantically strong features from upper levels and adds them to lower levels before predicting.

Rough guidelines for choosing:

  • Speed matters and objects are not very small: SSD is an easy-to-use choice. The backbone is not limited to VGG-16; the MobileNet paper also reports detection results combining it with SSD that greatly reduce computation.
  • Many small objects, or localization accuracy matters: Two-stage detectors such as Faster R-CNN with FPN are better suited.
  • You want to skip post-processing (non-maximum suppression) and default-box design: Set-prediction approaches such as DETR are also candidates.

PyTorch example

Show code
python
import math
import torch
from torchvision import datasets, transforms
from torchvision.models import VGG16_Weights
from torchvision.models.detection import ssd300_vgg16
from torch.utils.data import DataLoader
from tqdm import tqdm

'''
Object detection on PASCAL VOC with torchvision's SSD300 (VGG-16).
Like the paper, torchvision's implementation picks positives at IoU 0.5 and keeps negatives to at most 3x the positives (hard negative mining)
'''

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
VOC_CLASSES = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
               'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor']
epochs = 120
learning_rate = 1e-3        # Section 3 of the paper: initial 10^-3, momentum 0.9, weight decay 0.0005, batch 32


# Eq. (4) of the paper: default box scales for m feature maps (as a fraction of the image side)
def default_box_scales(m, s_min=0.2, s_max=0.9):
  return [s_min + (s_max - s_min) * (k - 1) / (m - 1) for k in range(1, m + 1)]


# Default boxes (cx, cy, w, h) for one feature map. s_next is used for the extra aspect-ratio-1 box s'_k = √(s_k s_{k+1})
def default_boxes(fmap_size, s_k, s_next, aspect_ratios=(2, 3)):
  boxes = []
  for i in range(fmap_size):
    for j in range(fmap_size):
      cx, cy = (j + 0.5) / fmap_size, (i + 0.5) / fmap_size
      boxes.append([cx, cy, s_k, s_k])                                       # aspect ratio 1
      s_prime = math.sqrt(s_k * s_next)
      boxes.append([cx, cy, s_prime, s_prime])                               # aspect ratio 1, scale s'_k
      for ar in aspect_ratios:                                               # aspect ratios ar and 1/ar
        boxes.append([cx, cy, s_k * math.sqrt(ar), s_k / math.sqrt(ar)])
        boxes.append([cx, cy, s_k / math.sqrt(ar), s_k * math.sqrt(ar)])
  return torch.tensor(boxes)


# The six layers of SSD300: map side length and aspect ratios (4-box layers use only 2 and 1/2; 6-box layers also 3 and 1/3)
fmap_sizes = [38, 19, 10, 5, 3, 1]
ratios = [(2,), (2, 3), (2, 3), (2, 3), (2,), (2,)]
scales = [0.1] + default_box_scales(5)       # SSD300 on VOC sets only conv4_3 to 0.1 (Section 3.1 of the paper)
scales_next = scales[1:] + [1.0]             # s_{k+1} for the last layer is not given in the paper; 1.0 is used here
priors = torch.cat([default_boxes(f, s, s2, r) for f, s, s2, r in zip(fmap_sizes, scales, scales_next, ratios)])
print(priors.shape)                          # torch.Size([8732, 4])


# torchvision's SSD300. The VGG-16 backbone starts from ImageNet-trained weights
model = ssd300_vgg16(weights=None, weights_backbone=VGG16_Weights.IMAGENET1K_FEATURES,
                     num_classes=len(VOC_CLASSES) + 1).to(device)   # include background (20 + 1)


# Convert PASCAL VOC annotations into the format torchvision detection models expect (boxes and labels)
def to_target(annotation):
  objects = annotation['annotation']['object']
  boxes = [[float(o['bndbox'][k]) for k in ('xmin', 'ymin', 'xmax', 'ymax')] for o in objects]
  labels = [VOC_CLASSES.index(o['name']) + 1 for o in objects]   # 0 is background
  return {'boxes': torch.tensor(boxes), 'labels': torch.tensor(labels)}


# The paper's data augmentation (patch sampling, horizontal flip, photometric distortion) is omitted here. Add it separately to reach the paper's accuracy
dataset = datasets.VOCDetection('./data', year='2007', image_set='trainval', download=True,
                                transform=transforms.ToTensor(), target_transform=to_target)
loader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=lambda b: tuple(zip(*b)))

optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=0.0005)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[80, 100], gamma=0.1)

for epoch in tqdm(range(epochs)):
  model.train()                            # returns a dictionary of losses during training
  for images, targets in loader:
    images = [img.to(device) for img in images]
    targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
    losses = model(images, targets)        # bbox_regression (Smooth L1) and classification (cross-entropy)
    loss = sum(losses.values())
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
  scheduler.step()

model.eval()                               # in evaluation, returns a list of boxes, labels, and scores (non-maximum suppression already applied)
with torch.no_grad():
  image, _ = dataset[0]
  detections = model([image.to(device)])[0]
  keep = detections['scores'] > 0.5
  for box, label in zip(detections['boxes'][keep], detections['labels'][keep]):
    print(VOC_CLASSES[label - 1], [round(v) for v in box.tolist()])

FAQ

Q. What is a default box?
A.

A default box is a reference box of fixed size and aspect ratio placed at each cell of a feature map. SSD300 places 4 or 6 per cell, for a total of 8732 across six layers. For each box, the network predicts "a score for each class" and "the offset to the object's box Δ(cx,cy,w,h)\Delta(cx, cy, w, h)". The idea is the same as the anchors in Faster R-CNN, but SSD places them on several feature maps of different resolutions.

Q. What is the difference between SSD and YOLO?
A.

Both are one-stage detectors without a proposal stage, but they predict differently. YOLO outputs boxes with fully connected layers from a single top-level feature map. SSD predicts with 3×3 convolutions for each default box of different aspect ratios at every location of six feature maps of different sizes. On VOC 2007 test in the paper, SSD300 scored 74.3% (59 fps) versus 63.4% (45 fps) for YOLO.

Q. What do the "300" and "512" in SSD mean?
A.

They are the side length of the input image in pixels. SSD300 takes 300×300 images, and SSD512 takes 512×512 images. Larger inputs make small objects easier to detect and raise accuracy, but are slower. In the paper, on VOC 2007 test, SSD300 scored 74.3% (59 fps) and SSD512 76.8% (22 fps) (both with batch 8).

References

  1. Liu, W., Anguelov, D., Erhan, D., Szegedy, C., Reed, S., Fu, C.-Y., & Berg, A. C. (2016). SSD: Single Shot MultiBox Detector. European Conference on Computer Vision (ECCV), 21–37. arXiv:1512.02325.
  2. Ren, S., He, K., Girshick, R., & Sun, J. (2015). Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks. NeurIPS 28. arXiv:1506.01497.
  3. Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You Only Look Once: Unified, Real-Time Object Detection. CVPR 2016. arXiv:1506.02640.
  4. PyTorch. torchvision.models.detection.ssd300_vgg16.