Sub topic 14
Attention as the Building Block of DETR
DETR replaces anchors and non-maximum suppression with a transformer. This chapter covers the one operation that transformer is built from, attention, and where DETR uses it. We assume you know what a backbone feature map is, and that you can read NumPy matrix code. Prior knowledge of Transformers is not required.
Why detection needs attention
A convolution mixes only a small neighborhood. A detector that must decide "this region is a person, and that other region is the same person's bag" benefits from letting every position look at every other position directly. Attention does this in one step.
Attention also gives DETR a way to produce a fixed number of outputs from a variable-size image. A small set of learned vectors, called object queries, can each ask the image a question. Each query returns one candidate box and class.
Scaled dot-product attention
Attention takes three sets of vectors:
- Queries (Q): what each output position is looking for.
- Keys (K): what each input position offers for matching.
- Values (V): the content that is actually passed along.
Each query is compared to every key with a dot product. The scores are divided by the square root of the vector size d. A softmax turns each row of scores into weights that sum to 1. The output for each query is the weighted sum of the values:
Attention(Q, K, V) = softmax(Q Kᵀ / sqrt(d)) V
The division by sqrt(d) keeps the dot products from growing with d. Without it, the softmax saturates and gradients become tiny.
import numpy as np
def softmax(x, axis=-1):
x = x - x.max(axis=axis, keepdims=True)
e = np.exp(x)
return e / e.sum(axis=axis, keepdims=True)
def attention(q, k, v):
"""q: (n_q, d), k: (n_k, d), v: (n_k, d_v). Returns output and weights."""
d = q.shape[-1]
scores = q @ k.T / np.sqrt(d)
weights = softmax(scores, axis=-1)
return weights @ v, weights
rng = np.random.default_rng(0)
d = 8
features = rng.normal(size=(6, d)) # 6 image positions (a flattened 2x3 feature map)
queries = rng.normal(size=(3, d)) # 3 object queries
out_self, w_self = attention(features, features, features)
print(out_self.shape, w_self.shape) # (6, 8) (6, 6)
out_cross, w_cross = attention(queries, features, features)
print(out_cross.shape, w_cross.shape) # (3, 8) (3, 6)
print(np.allclose(w_cross.sum(axis=-1), 1.0)) # TrueThe only difference between the two calls is where Q comes from. That difference is the next topic.
Self-attention versus cross-attention
| Kind | Q comes from | K and V come from | Output shape | DETR uses it in |
|---|---|---|---|---|
| Self-attention | Set A | Set A | One vector per element of A | Encoder (image tokens), decoder (queries) |
| Cross-attention | Set A | Set B | One vector per element of A | Decoder (queries read image tokens) |
In self-attention, every element of a set updates itself using the others. In cross-attention, one set reads from another. The weight matrix has shape (n_q, n_k), so its cost grows with the product of the two set sizes.
Learned projections and multiple heads
Real attention layers do not use the raw features as Q, K and V. Each is produced by a learned linear layer, so the model can learn what to match on separately from what to pass along.
Multi-head attention runs several attention operations in parallel, each on a smaller slice of the vector. DETR uses 8 heads on 256-dimensional vectors, so each head works with 32 dimensions. The head outputs are concatenated and mixed by one more linear layer. Different heads can specialize. In trained DETR models, some heads attend to object extremities such as edges and limbs, which helps with box regression.
Turning a feature map into tokens
Attention works on a set of vectors, not a grid. DETR converts the backbone output into a set like this:
- The backbone (for example ResNet-50 at stride 32) produces a map of shape
C × H × W. - A 1×1 convolution reduces
C(2048 for ResNet-50) tod = 256. - The map is flattened into
H·Wtokens of size 256.
For an 800×1333 image at stride 32, the map is about 25×42, so there are roughly 1050 tokens. Self-attention over them builds a 1050×1050 weight matrix per head.
Attention has no built-in sense of order, so flattening throws away where each token came from. DETR fixes this with a fixed 2D sine positional encoding, which gives each token a position signal. In DETR this encoding is added to the queries and keys at every attention layer, but not to the values.
Where attention sits in DETR
Each part has a distinct job:
- Encoder self-attention lets every image position gather context from every other. This helps separate overlapping instances, because tokens can account for what neighbors already explain.
- Decoder self-attention lets queries communicate. A query can learn to stay quiet when another query already claimed an object.
- Decoder cross-attention is where a query pulls evidence from the image. Its weights over the tokens show which region that query is reading.
The decoder runs 6 layers, and each layer repeats self-attention then cross-attention. By the last layer, each of the 100 query vectors is passed to a small feed-forward network for the class and to another for the box. Every query always produces a prediction, including a "no object" class. The Hungarian matching chapter explains how those predictions are paired with ground truth during training.
What attention replaces
Earlier chapters used hand-designed pieces that attention-based set prediction removes or reduces:
- Anchors: a query does not need a prior box at a fixed grid location. It predicts a box directly, as normalized center and size, through the box head.
- NMS: duplicate suppression is partly learned. Decoder self-attention lets queries coordinate, and one-to-one matching in the loss penalizes duplicates. DETR needs no NMS step.
- Local receptive fields: the encoder gives every token a global view from the first layer.
Costs and failure modes
Attention costs more than convolution in two ways.
- Quadratic cost. The encoder's weight matrix has
(H·W)²entries per head. Doubling the image side length multiplies the token count by 4 and the weight matrix by 16. This is why DETR runs on the stride-32 map only, and why it struggles with small objects, which need higher-resolution features. - Slow learning of locality. Softmax attention starts nearly uniform, spread over all tokens. The model must learn which positions matter, and this contributes to DETR's long training schedule (500 epochs in the original paper, against about 12 to 36 for typical Faster R-CNN setups).
The final chapter covers Deformable DETR and other fixes that attack both costs by attending to only a few sampled positions per query.
Summary of the model
- Attention is a weighted average of values, with weights from query-key similarity.
- Self-attention uses one set for Q, K and V. Cross-attention takes Q from one set and K and V from another.
- DETR flattens a feature map into tokens, adds positional encoding to queries and keys, and runs an encoder and a decoder.
- Object queries are learned vectors, and each produces one prediction.
- The price is quadratic cost in the number of tokens and slow convergence.
Exercise
In the code above, queries has 3 rows and features has 6 rows. What are the shapes of the weight matrix and the output when the call is attention(queries, features, features), and what would the weight matrix shape be if you used 100 queries and a 25×42 feature map?
Show answer
With 3 queries and 6 tokens, the weights are (3, 6) and the output is (3, 8), one row per query. With 100 queries and 25×42 = 1050 tokens, the weights are (100, 1050), so each query has one weight per image token and each row sums to 1.
Exercise
The encoder applies self-attention to 1050 tokens. If the input image is resized so that both sides are twice as long, with the same stride 32, how many tokens are there and by what factor does the encoder's attention weight matrix grow?
Show answer
Doubling both sides gives 4 times as many tokens, about 4200. The weight matrix has tokens squared entries per head, so it grows by 4² = 16 times, from about 1.1 million to about 17.6 million entries per head.