TExcelTAD

One-Stage Detectors: YOLO and SSD

Faster R-CNN first proposes regions and then looks at each one again. A one-stage detector skips the second look: one network pass produces, at every position of a few feature maps, class scores and a box directly, and the only step after the network is a decode and NMS. SSD and YOLO (both 2016) started the family; RetinaNet (2017) showed with the focal loss that one stage can be as accurate as two; YOLOv8 (2023) and YOLO11 (2024) are the versions you will most likely deploy, and YOLO26 (released January 2026) drops the DFL distributions and NMS for an end-to-end head. This lesson follows the ideas from YOLOv1's grid to YOLOv8's anchor-free head, decodes raw outputs to boxes from scratch, and then does the same with a real YOLOv8 network.

YOLOv1: the grid is responsible

YOLOv1 divides the image into an S×SS \times S grid (S=7S = 7 at 448 x 448 input). The cell that contains an object's centre is responsible for it. Each cell predicts B=2B = 2 boxes (centre offset within the cell, width and height relative to the image, a confidence) and one set of class probabilities, so the whole output is a 7×7×(2⋅5+20)=7×7×307 \times 7 \times (2 \cdot 5 + 20) = 7 \times 7 \times 30 tensor for the 20 VOC classes. That makes detection a single regression problem, and fast: 45 images per second in 2016. Its weaknesses follow from the grid: one class per cell, at most two objects per cell, and few boxes overall, so groups of small objects (a flock of birds) are lost.

YOLOv1: the cell withthe centre predicts 80 x 80stride 8small objects 40 x 40stride 16 20 x 20stride 32large objects YOLOv8 at 640 x 640:6400 + 1600 + 400 = 8400 positions

How often does "one object per cell" bite? On the course's generated scenes (64 x 64 images with 1 to 3 shapes of 12 to 24 pixels that never touch), count the objects whose centre falls in a cell that already holds another centre:

python · try it yourself
import numpy as np
import numpy as np, cv2

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

rng = np.random.default_rng(0)
scenes = [make_scene(rng) for _ in range(1000)]
n_obj = sum(len(b) for _, b, _, _ in scenes)
for grid in [2, 4, 8, 16]:
    cell = 64 / grid
    clashes = 0
    for _, boxes, _, _ in scenes:
        cx, cy = (boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2
        cells = list(zip((cx // cell).astype(int).tolist(), (cy // cell).astype(int).tolist()))
        clashes += len(cells) - len(set(cells))
    print(f"grid {grid:2d} x {grid:<2d} (cell {cell:4.1f} px): {clashes:3d} of {n_obj} objects share a cell")
grid  2 x 2  (cell 32.0 px):  67 of 2029 objects share a cell
grid  4 x 4  (cell 16.0 px):   0 of 2029 objects share a cell
grid  8 x 8  (cell  8.0 px):   0 of 2029 objects share a cell
grid 16 x 16 (cell  4.0 px):   0 of 2029 objects share a cell

On a 2 x 2 grid, 67 of the 2,029 objects in 1,000 scenes (3.3%) share a cell with another and a one-object-per-cell model would lose them. From 4 x 4 on there are none, but only because make_scene never lets shapes touch: two centres are always at least 14 pixels apart. Real photos have no such rule (a person holding a cup, cars in a queue), which is why later designs put several predictors in each cell (anchors) or use finer grids.

SSD, YOLOv2 and v3: anchors on several scales

Two fixes followed quickly. SSD (2016) predicted from several feature maps of decreasing resolution, each with its own set of default boxes (anchors) of a few shapes, so small objects are handled on fine maps and large ones on coarse maps. YOLOv2 (2017) adopted anchors, choosing their shapes by k-means on the training boxes, and YOLOv3 (2018) used three scales with three anchors each. A v3-style head outputs, per anchor, (tx,ty,tw,th)(t_x, t_y, t_w, t_h), an objectness logit and one logit per class, decoded as

bx=(σ(tx)+cx) d,by=(σ(ty)+cy) d,bw=pwetw,bh=pheth,scorek=σ(o) σ(zk)b_x = (\sigma(t_x) + c_x)\, d, \qquad b_y = (\sigma(t_y) + c_y)\, d, \qquad b_w = p_w e^{t_w}, \qquad b_h = p_h e^{t_h}, \qquad \text{score}_k = \sigma(o) \, \sigma(z_k)

where (cx,cy)(c_x, c_y) is the cell, dd the stride and (pw,ph)(p_w, p_h) the anchor size. The sigmoid keeps the centre inside its cell, and the final score multiplies "there is an object here" by "it is of class kk". RetinaNet (2017) kept this dense design and fixed its training problem: tens of thousands of candidates per image (76,725 at 640 x 640, counted below), nearly all easy background, swamp a cross-entropy loss. The focal loss down-weights well-classified examples, and with it a one-stage detector matched two-stage accuracy for the first time.

The number of candidates each design scores per image:

python · try it yourself
designs = {
    "YOLOv1 448": [(7, 2)],                                                   # (grid size, boxes per cell)
    "SSD300": [(38, 4), (19, 6), (10, 6), (5, 6), (3, 4), (1, 4)],
    "YOLOv3 416": [(13, 3), (26, 3), (52, 3)],
    "RetinaNet 640": [(80, 9), (40, 9), (20, 9), (10, 9), (5, 9)],
    "YOLOv8 640": [(80, 1), (40, 1), (20, 1)],
}
for name, levels in designs.items():
    n = sum(g * g * k for g, k in levels)
    print(f"{name:14s} {n:6d} candidates  " + " + ".join(f"{g}x{g}x{k}" for g, k in levels))
YOLOv1 448         98 candidates  7x7x2
SSD300           8732 candidates  38x38x4 + 19x19x6 + 10x10x6 + 5x5x6 + 3x3x4 + 1x1x4
YOLOv3 416      10647 candidates  13x13x3 + 26x26x3 + 52x52x3
RetinaNet 640   76725 candidates  80x80x9 + 40x40x9 + 20x20x9 + 10x10x9 + 5x5x9
YOLOv8 640       8400 candidates  80x80x1 + 40x40x1 + 20x20x1

From 98 boxes in YOLOv1 to 8,732 in SSD and 76,725 in RetinaNet: more candidates mean higher recall for small and crowded objects, and more post-processing. YOLOv8 at 640 x 640 is back to 8,400 because each position predicts one box instead of nine anchors, and the assigner, not the anchor shapes, decides which positions learn which object.

YOLOv8 and YOLO11: anchor-free and decoupled

The current Ultralytics models changed the head in three ways:

  1. Anchor-free. One anchor point per position (the cell centre), and the box as four distances to its sides, in units of the stride (anchor-free encoding). No anchor shapes to tune.
  2. Decoupled head. Separate convolution branches for the box and for the classes, instead of one shared output, because localisation and classification want different features.
  3. No objectness. The class scores themselves (sigmoid, one per class) are trained to reflect box quality, using the task-aligned assigner, so the score is σ(zk)\sigma(z_k) alone. Each distance is predicted as a 16-bin distribution (DFL), so the box branch outputs 4⋅16=644 \cdot 16 = 64 channels.

The loss is a binary cross-entropy for the classes plus a CIoU loss (an IoU-based box loss with penalties for centre distance and aspect ratio) and the DFL term for the boxes. At inference: decode, keep scores above a threshold, NMS.

Decoding raw outputs from scratch

To see the decode end to end, here is a hand-made raw output of a YOLOv8-style head for a 64 x 64 input (strides 8, 16 and 32, so 64+16+4=8464 + 16 + 4 = 84 points), with 3 classes. The logits are random noise except at two points, where they encode a known box. The decoder must find exactly those two boxes:

python · try it yourself
import numpy as np

def softmax(z, axis=-1):
    z = np.exp(z - z.max(axis, keepdims=True)); return z / z.sum(axis, keepdims=True)

def anchor_points(img_size, strides):
    pts, st = [], []
    for d in strides:
        g = img_size // d
        ys, xs = np.mgrid[0:g, 0:g]
        pts.append(np.stack([xs.ravel() + 0.5, ys.ravel() + 0.5], 1)); st.append(np.full(g * g, d))
    return np.concatenate(pts), np.concatenate(st)

def nms(boxes, scores, thr):
    order, keep = np.argsort(-scores, kind="stable"), []
    while order.size:
        i, order = order[0], order[1:]
        keep.append(int(i))
        b = boxes[order]
        iw = (np.minimum(boxes[i, 2], b[:, 2]) - np.maximum(boxes[i, 0], b[:, 0])).clip(0)
        ih = (np.minimum(boxes[i, 3], b[:, 3]) - np.maximum(boxes[i, 1], b[:, 1])).clip(0)
        a = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
        order = order[iw * ih / (a(boxes[i]) + a(b) - iw * ih) <= thr]
    return keep

def decode_v8(box_logits, cls_logits, points, strides, conf=0.25, iou=0.7):
    """box_logits (N, 4, 16): l, t, r, b as 16-bin distributions; cls_logits (N, C)."""
    dist = (softmax(box_logits) * np.arange(16)).sum(-1)                 # expected bin = distance in strides
    xy1 = (points - dist[:, :2]) * strides[:, None]
    xy2 = (points + dist[:, 2:]) * strides[:, None]
    boxes = np.c_[xy1, xy2]
    scores = 1 / (1 + np.exp(-cls_logits))                               # sigmoid per class, no objectness
    cls, best = scores.argmax(1), scores.max(1)
    m = best > conf
    boxes, best, cls = boxes[m], best[m], cls[m]
    keep = nms(boxes + cls[:, None] * 1000, best, iou)                  # class-aware NMS by the offset trick
    return boxes[keep], best[keep], cls[keep]

points, strides = anchor_points(64, [8, 16, 32])
rng = np.random.default_rng(0)
box_logits = rng.normal(0, 1, (len(points), 4, 16))
cls_logits = rng.normal(-6, 1, (len(points), 3))                         # background everywhere ...
def plant(i, box, k):                                                    # ... except at point i
    d = np.array([points[i, 0] * strides[i] - box[0], points[i, 1] * strides[i] - box[1],
                  box[2] - points[i, 0] * strides[i], box[3] - points[i, 1] * strides[i]]) / strides[i]
    for side in range(4):                                                # DFL: two neighbouring bins
        lo = int(d[side]); w = d[side] - lo
        p = np.full(16, 1e-6); p[lo] += 1 - w; p[min(lo + 1, 15)] += w
        box_logits[i, side] = np.log(p)
    cls_logits[i, k] = 3.0
plant(27, [20, 10, 44, 34], 0)                                           # stride-8 point 27 is cell (3, 3)
plant(64 + 5, [10, 14, 33, 46], 1)                                       # stride-16 point 5 is cell (1, 1)
print("points per stride:", {int(d): int((strides == d).sum()) for d in [8, 16, 32]}, "| total", len(points))
boxes, scores, cls = decode_v8(box_logits, cls_logits, points, strides)
for b, s, c in zip(boxes, scores, cls):
    print(f"class {int(c)} score {s:.3f} box {np.round(b, 1).tolist()}")
points per stride: {8: 64, 16: 16, 32: 4} | total 84
class 0 score 0.953 box [20.0, 10.0, 44.0, 34.0]
class 1 score 0.953 box [10.0, 14.0, 33.0, 46.0]

Of the 84 points, only the two planted ones pass the 0.25 threshold, and the decoded boxes are exactly the planted ones, [20, 10, 44, 34] from a stride-8 point and [10, 14, 33, 46] from a stride-16 point; the score 0.953 is σ(3)\sigma(3). The decode has four steps, the same in YOLOv8 and YOLO11 (YOLO26 predicts the distances directly and, by default, needs no NMS): expected distance per side from the 16-bin softmax, point plus or minus distance, times stride, sigmoid for the class scores, then threshold and class-aware NMS.

The same decode on a real YOLOv8

The pretrained yolov8n.pt (COCO, 80 classes) is cached in this course's Docker image, so this example is recorded. The network's Detect head already performs the DFL expectation and the multiplication by the stride inside its forward pass, and returns a (1, 84, 8400) tensor: for each of the 8,400 points the box as centre, width and height in input pixels, then 80 class scores after the sigmoid. Everything after that is done here by hand and compared with model.predict:

python · try it yourself
import numpy as np
import cv2
import torch
from ultralytics import YOLO
from skimage import data

def nms(boxes, scores, thr):
    order, keep = np.argsort(-scores, kind="stable"), []
    while order.size:
        i, order = order[0], order[1:]
        keep.append(int(i))
        b = boxes[order]
        iw = (np.minimum(boxes[i, 2], b[:, 2]) - np.maximum(boxes[i, 0], b[:, 0])).clip(0)
        ih = (np.minimum(boxes[i, 3], b[:, 3]) - np.maximum(boxes[i, 1], b[:, 1])).clip(0)
        a = lambda z: (z[..., 2] - z[..., 0]) * (z[..., 3] - z[..., 1])
        order = order[iw * ih / (a(boxes[i]) + a(b) - iw * ih) <= thr]
    return keep

model = YOLO("yolov8n.pt")
net = model.model.eval()
head = net.model[-1]
print("head:", type(head).__name__, "| strides", net.stride.tolist(), "| classes", head.nc, "| DFL bins", head.reg_max,
      "| box branch out", head.cv2[0][-1].out_channels, "| class branch out", head.cv3[0][-1].out_channels)

rgb = data.astronaut()                                            # 512 x 512, so resizing to 640 needs no padding
x = cv2.resize(rgb, (640, 640), interpolation=cv2.INTER_LINEAR)
t = torch.tensor(x).permute(2, 0, 1)[None].float() / 255           # RGB, 0..1, (1, 3, 640, 640)
with torch.no_grad():
    y = net(t)[0][0].T.numpy()                                    # (8400, 84)
print("raw output:", y.shape, "= 4 box values + 80 class scores per point")
cls_scores = y[:, 4:]
best, cls = cls_scores.max(1), cls_scores.argmax(1)
m = best > 0.25
print("points with a class score above 0.25:", int(m.sum()), "of", len(y))
cx, cy, w, h = y[m, 0], y[m, 1], y[m, 2], y[m, 3]
boxes = np.c_[cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2] * (512 / 640)   # back to the original pixels
keep = nms(boxes + cls[m][:, None] * 10000, best[m], 0.7)
for i in keep:
    print(f"  by hand : {model.names[int(cls[m][i])]} {best[m][i]:.2f} {np.round(boxes[i]).astype(int).tolist()}")
r = model.predict(rgb[:, :, ::-1].copy(), conf=0.25, verbose=False)[0]   # predict wants BGR for arrays
for b, c, s in zip(r.boxes.xyxy.tolist(), r.boxes.cls.tolist(), r.boxes.conf.tolist()):
    print(f"  predict : {model.names[int(c)]} {s:.2f} {np.round(b).astype(int).tolist()}")
head: Detect | strides [8.0, 16.0, 32.0] | classes 80 | DFL bins 16 | box branch out 64 | class branch out 80
raw output: (8400, 84) = 4 box values + 80 class scores per point
points with a class score above 0.25: 10 of 8400
  by hand : person 0.71 [5, 14, 363, 511]
  predict : person 0.71 [5, 14, 363, 511]

The head confirms the description above: three strides, 80 classes, a box branch with 4⋅16=644 \cdot 16 = 64 output channels (the DFL distributions) and a separate class branch with 80. Of the 8,400 points only 10 have a class score above 0.25 on the astronaut photo, all of them "person" boxes around the same woman; NMS turns them into one. The hand-written post-processing (scale from 640 back to 512 pixels, convert centre format to corners, class-aware NMS at 0.7, which is Ultralytics' default iou) gives the same box and score as model.predict, to the pixel. Two details made that work: the input is RGB scaled to 0 to 1 (predict converts the BGR array itself), and the image is square, so the resize needs no letterbox padding (Ultralytics YOLO handles the general case).

Choosing between them

Two-stage (Faster R-CNN) One-stage (RetinaNet, YOLOv8, YOLO11)
Passes backbone + RPN, then a head per proposal one dense pass
Post-processing NMS twice (proposals, detections) NMS once (none in NMS-free variants)
Speed slower, varies with the number of proposals fast and constant; nano models run on a CPU
Strengths precise boxes, masks and keypoints in the same framework real time, simple export (ONNX, TensorRT, mobile)
Typical use today research baselines, Mask R-CNN pipelines most production detection

Pitfalls

  • BGR versus RGB, 0 to 255 versus 0 to 1. The network was trained on RGB in [0,1][0, 1]; feeding OpenCV's BGR or unscaled values to model.model directly gives poor but plausible-looking results. predict handles it for you; hand-written pipelines must do it themselves.
  • Forgetting the resize when mapping boxes back. Outputs are in network-input pixels (640 x 640 here); multiply back to the original size, and subtract the letterbox padding first when there is any.
  • Thresholding the wrong score. In v3-style heads the score is objectness times class probability; in v8 the class sigmoid alone. Mixing the two conventions in a custom decoder halves or squares your scores.
  • Expecting more than one object per position. An anchor-free head predicts one box per point and level; two objects with the same centre at the same scale compete for it.
  • Grid-size limits. Objects much smaller than the finest stride (8 pixels) cover less than a cell and are often missed; increase the input size or add a finer level.

Practice

  1. A YOLOv3-style head at stride 16 outputs, for cell (cx,cy)=(5,2)(c_x, c_y) = (5, 2) and an anchor of size 40×8040 \times 80: tx=0t_x = 0, ty=0t_y = 0, tw=ln⁡2t_w = \ln 2, th=0t_h = 0. Decode the box.
Answer

bx=(σ(0)+5)⋅16=5.5⋅16=88b_x = (\sigma(0) + 5) \cdot 16 = 5.5 \cdot 16 = 88, by=2.5⋅16=40b_y = 2.5 \cdot 16 = 40, bw=40⋅2=80b_w = 40 \cdot 2 = 80, bh=80b_h = 80. As corners: [48, 0, 128, 80].

  1. How many output positions does a YOLOv8 head have for a 320 x 320 input? For 1280 x 1280?
Answer

320: 402+202+102=2,10040^2 + 20^2 + 10^2 = 2{,}100. 1280: 1602+802+402=33,600160^2 + 80^2 + 40^2 = 33{,}600. Quadrupling the area quadruples the positions; small objects gain resolution, at four times the compute.

  1. In the hand-made decode, change the class logit of the first planted point from 3.0 to −1.5-1.5. What happens and why?
Answer

Its score becomes σ(−1.5)≈0.18<0.25\sigma(-1.5) \approx 0.18 < 0.25, so the box is dropped before NMS: only one detection is printed. The box itself is still decoded correctly; the confidence threshold removed it.

Test yourself

In YOLOv1, which grid cell predicts an object?

  1. Every cell the box overlaps
  2. The cell that contains the centre of the object
  3. The top-left cell of the box
  4. The cell with the highest objectness, wherever it is

How many output positions does YOLOv8 have at 640 x 640 input, and why?

  1. 8,732: SSD's default boxes
  2. 8,400: 80 x 80 + 40 x 40 + 20 x 20 at strides 8, 16, 32, one point each
  3. 25,200: three anchors per position
  4. 640

Why did RetinaNet need the focal loss?

  1. To predict masks
  2. Tens of thousands of candidates per image are mostly easy background, which dominates a plain cross-entropy loss
  3. To remove NMS
  4. Because it has no backbone

What does the 64-channel box branch of the YOLOv8 head predict at each point?

  1. 64 anchors
  2. Four 16-bin distributions, one per box side (DFL)
  3. An 8 x 8 mask
  4. 64 class scores