Sub topic 5
Predicting offsets instead of raw coordinates
This chapter assumes you know how anchors work (the previous chapter), how a convolutional head produces per-location outputs, and what a regression loss is. It covers why detectors predict small corrections to an anchor instead of absolute box coordinates, how those corrections are defined, and where the encoding goes wrong.
The problem with raw coordinates
Suppose a detection head outputs (x1, y1, x2, y2) directly for every anchor. This is hard to learn for three reasons.
- Absolute values vary widely. A coordinate can be anywhere from 0 to the image width. A convolutional head shares weights across all positions, so the same filter would have to output a different number at each location for the same visual pattern.
- Errors do not scale with the object. A 5-pixel error is a disaster for a 20-pixel box and negligible for a 400-pixel box. A plain L1 or L2 loss on pixels treats them the same, so large objects dominate the gradient.
- Nothing guarantees a valid box. A network can output
x2 < x1.
The fix is to make the target relative to the anchor. The head then answers a local question: "how should this reference box be nudged and stretched?" The answer for a well-matched anchor is close to zero, and it looks the same wherever the object sits in the image.
The standard parameterization
Faster R-CNN, and most anchor-based detectors after it, use boxes in center format (cx, cy, w, h). Let the anchor be (cx_a, cy_a, w_a, h_a) and the ground-truth box be (cx, cy, w, h). The regression targets are:
| Target | Formula | Meaning |
|---|---|---|
| `tx` | `(cx - cx_a) / w_a` | Horizontal shift, in anchor widths |
| `ty` | `(cy - cy_a) / h_a` | Vertical shift, in anchor heights |
| `tw` | `log(w / w_a)` | Log of the width ratio |
| `th` | `log(h / h_a)` | Log of the height ratio |
Dividing the shift by the anchor size makes the target scale invariant. A shift of 0.1 means "one tenth of the anchor's width" for a small anchor and a large one alike.
The log on width and height turns a multiplicative change into an additive one. Doubling a box gives log 2 ≈ 0.693 and halving it gives -0.693, so growing and shrinking are symmetric around zero. Decoding applies exp, which always returns a positive number, so widths and heights can never go negative.
Encoding and decoding in code
Training uses encode to build targets from ground-truth boxes. Inference uses decode to turn network outputs back into boxes. The two must be exact inverses.
import math
def encode(anchor, gt):
"""Targets (tx, ty, tw, th) for a ground-truth box, both as (cx, cy, w, h)."""
cx_a, cy_a, w_a, h_a = anchor
cx, cy, w, h = gt
return (
(cx - cx_a) / w_a,
(cy - cy_a) / h_a,
math.log(w / w_a),
math.log(h / h_a),
)
def decode(anchor, deltas, clip=math.log(1000 / 16)):
"""Apply (tx, ty, tw, th) to an anchor given as (cx, cy, w, h)."""
cx_a, cy_a, w_a, h_a = anchor
tx, ty, tw, th = deltas
tw = min(tw, clip) # guard against exp() overflow early in training
th = min(th, clip)
cx = cx_a + tx * w_a
cy = cy_a + ty * h_a
w = w_a * math.exp(tw)
h = h_a * math.exp(th)
return (cx, cy, w, h)
anchor = (50, 50, 20, 40)
gt = (52, 48, 20, 80)
deltas = encode(anchor, gt)
print([round(d, 6) for d in deltas])
# [0.1, -0.05, 0.0, 0.693147]
print([round(v, 6) for v in decode(anchor, deltas)])
# [52.0, 48.0, 20.0, 80.0]The round trip recovers the ground-truth box. The ground truth is 2 pixels right of and 2 pixels above the anchor center, the same width, and twice the height. That gives tx = 2/20 = 0.1, ty = -2/40 = -0.05, tw = 0, and th = log 2.
The clip argument is a safeguard. Early in training the network can output a large tw, and exp of a large number gives an enormous box or a floating-point overflow. Detectron and torchvision clamp at log(1000/16), which limits growth to about 62 times the anchor size.
The full path from anchor to box
Practical details
Delta scaling
Raw deltas are small. A typical tx is within a few hundredths, while a classification loss works on a scale near 1. Detectors rescale the targets so the regression outputs have roughly unit variance.
- Faster R-CNN in torchvision multiplies the targets by weights
(10, 10, 5, 5). The head's outputs are divided by the same weights when decoding. - SSD uses "variances" of
0.1for the center and0.2for the size, which is the same idea written as a divisor.
These constants are part of the model. A checkpoint trained with one set of weights gives wrong boxes if you decode with another, and no error is raised.
The loss
The regression loss is usually Smooth L1 (Huber) on the deltas. It is quadratic near zero, which gives gentle gradients for small errors. It is linear for large errors, so a badly placed anchor does not produce an outsized gradient. Some newer detectors apply an IoU-based loss to the decoded boxes instead, which measures the quantity that evaluation cares about.
Only positives are regressed
Box loss is computed only for anchors matched to a ground-truth box (the next chapters cover how this matching is decided). A background anchor has no meaningful target, so it contributes to the classification loss only. Applying a box loss to all anchors would teach the network to move empty regions toward arbitrary objects.
Common errors
- Mixing box formats.
encodeanddecodeabove use(cx, cy, w, h). Matching and IoU often use(x1, y1, x2, y2). Convert explicitly at the boundary and keep one format inside each function. - Taking the log of zero. A ground-truth box with zero width or height gives
log(0). Filter out degenerate boxes before encoding. - Using the wrong anchor on decode. Predictions are tied to the anchor at the same location, scale, and aspect ratio. A mismatch in anchor ordering between training and inference silently shifts every box.
- Forgetting the size units. Shifts are divided by anchor width and height, not by image size. Dividing by image size gives a different parameterization and the checkpoint will not decode correctly.
- Skipping the clamp. Without a limit on
twandth, one unstable batch can produceinfand ananloss.
Where this idea goes next
The offset idea carries across detector families, with the reference changing.
- Two-stage detectors apply it twice: once to refine anchors into region proposals, and again to refine proposals into final boxes.
- Single-stage detectors such as SSD and RetinaNet apply it once, directly from anchors.
- Anchor-free detectors such as FCOS predict distances from a point to the four box sides. This is the same relative-target idea with a point as the reference instead of a box.
- DETR has no anchors, so its queries predict normalized box coordinates directly. Deformable DETR later added a reference point for each query and predicts offsets from it, which shows how useful a local reference is for fast training.
Exercise
An anchor is (cx, cy, w, h) = (100, 80, 50, 30). The network outputs deltas (tx, ty, tw, th) = (0.2, -0.1, log(0.5), 0). What box does decode return, and why can the width never come out negative?
Show answer
cx = 100 + 0.2 × 50 = 110. cy = 80 + (-0.1) × 30 = 77. w = 50 × exp(log 0.5) = 25. h = 30 × exp(0) = 30. The box is (110, 77, 25, 30). The width is the anchor width multiplied by exp(tw), and exp of any real number is positive, so w cannot be negative whatever the network outputs.
Exercise
Why is a 5-pixel error in raw coordinates a poor training signal across objects of different sizes, and how does the (tx, ty, tw, th) parameterization address it?
Show answer
A 5-pixel error is large for a small object and small for a large one, but a pixel loss weighs them equally, so large objects dominate. Dividing the center shifts by the anchor size and using log size ratios makes the targets relative to the object's scale, so the same fractional error produces the same loss at any size.