DETR: predict a set, then decide who matches whom
DETR
Follow image features through parallel object queries, solve global assignment, and derive GIoU and the normalized set loss with a runnable small model.
detrTwo people, four prediction slots
Imagine a photograph containing two people. A detector emits four boxes. Which prediction should learn about the person on the left? If all four predictions learn from that person independently, the model can duplicate one detection while missing the other. Sorting annotations from left to right is also fragile: people can move past one another, and the task does not require an ordered answer.
DETR, short for DEtection TRansformer, treats the answer as a set. A fixed number of learned object queries produces class scores and boxes in parallel. During training, a global assignment pairs each annotated object with one distinct prediction; unmatched predictions receive the “no object” class. The assignment may change on the next forward pass. A query is a learned slot, not a permanent label saying “leftmost person.” Original method, §§3.1–3.2
This changes the division of work in a detector. SSD begins with geometric default boxes and can assign several defaults to one object. DETR learns its query vectors and uses one-to-one set supervision. Its original design removes anchor generation and the usual NMS stage. That is an architectural and training choice, not a mathematical guarantee that every untrained or failed model produces distinct correct boxes.
Carion and colleagues submitted the first preprint on 26 May 2020. This chapter reads the v3 method dated 28 May and selected official code at commit 29901c51d7fe8712168b8d0d64351170bc0f83e0. The code snapshot is later than the paper; it supplies an explicit implementation profile, not proof of the exact software installed for the original experiments. Submission history
Separate the forward model, matching cost and learning loss
What information reaches an object query?
A CNN converts an image into a feature map. A 1×1 projection changes its channel width to D, and flattening the spatial axes gives L image tokens. Image position vectors retain the two-dimensional layout. The encoder lets each token attend to image context; the decoder uses N learned query-position vectors to read that encoded image. The class head produces K foreground logits plus one no-object logit per query. A three-layer MLP produces four numbers, followed by sigmoid for normalized center coordinates and sizes. Paper architecture, fixed model and heads
For one attention head, let Q contain projected queries, K contain projected keys and V contain projected values; here K in an equation is a matrix, while the preceding K used for a class count is a scalar. The head width is d. Attention forms a weighted sum of values:
Multi-head attention runs this calculation on several projected channel groups, concatenates their outputs and projects again. A key marked as padding receives a score of negative infinity before softmax, hence zero probability when at least one valid key remains. Masking padded keys matters: a zero feature vector can still have a nonzero position vector and attract attention.
In the fixed post-norm path, position vectors enter the inputs used to form Q and K, while V carries content. Encoder Q/K receive image content plus image position. Decoder self-attention Q/K receive query content plus learned query position. Decoder cross-attention Q receives query content plus query position, K receives encoder memory plus image position, and V receives memory alone. Each attention or feed-forward sublayer is followed by a residual addition and LayerNorm; the decoder stack also has a final normalization. Transformer implementation
The decoder’s initial content is zero. Its query-position vectors are learned parameters, not zero. This distinction explains how different slots can start reading different parts of the same image without autoregressive generation or a causal mask. In our one-layer, zero-bias demonstration, the first self-attention has zero values and therefore returns zero even though its attention weights differ. The following cross-attention is where the slots first acquire image-dependent content. A deeper decoder can then exchange that acquired content across queries.
The normalized sine position profile counts valid pixels cumulatively along each axis, divides by the final valid count plus 1e-6, and scales to approximately 2π. It interleaves sine and cosine at frequencies derived from 10,000, then concatenates y features before x features. Our float64 implementation follows that recipe, without claiming bit-identical float32 results. Position encoding
Boxes have geometry, not just four independent numbers
Write a predicted box as b=(cx,cy,w,h), with horizontal center cx, vertical center cy, width w and height h relative to image dimensions. Convert to corners by subtracting and adding half the width and height. For example, [0.5,0.5,0.4,0.2] becomes [0.3,0.4,0.7,0.6]. A sigmoid constrains the four center/size components, but a center near an edge plus a large width can still produce corners outside the image.
The fixed model’s forward docstring swaps the words height and width. Its conversion function and loss use cx,cy,w,h, which is the contract used here. This is why checking executable geometry matters more than copying a comment. Box conversion and GIoU
Ordinary IoU divides intersection area by union area. Two disjoint boxes have IoU zero regardless of how far apart they are. For positive-area, axis-aligned boxes A and B, let C be their smallest enclosing axis-aligned rectangle. Generalized IoU adds a penalty for the unused area inside C:
Identical boxes give GIoU=1. Take A=[0,0,1,1] and B=[t,0,t+1,1] with t greater than 1, in arbitrary shared units. Their intersection is empty, their union has area 2, and the enclosing rectangle has area t+1. Thus
At t=2, GIoU is −1/3 and the loss slope is 2/9. Unlike zero IoU on this disjoint interval, the loss changes with horizontal separation. This example does not prove a useful nonzero gradient in every configuration. The min/max operations make the expression piecewise differentiable, and branch boundaries require a derivative convention. GIoU approaches −1 in the distant-box limit here. Original GIoU paper, algorithms 1–2
Match using a global cost
Suppose an image has M annotated objects and N predictions, with M no larger than N. Target i has foreground class and box ; query j predicts probabilities and box . Our target-row, query-column cost is
The GIoU calculation first converts center-size boxes to corners. Replacing its negative with one minus GIoU adds the same constant per matched target and leaves the optimal assignment unchanged. No-object labels are not additional rows in the rectangular cost. They will be assigned to unused predictions after matching. The fixed official defaults use coefficients (1,5,2); the program adopts these values for both matching and the corresponding training terms, though the official arguments allow them to be configured separately. Matcher, default arguments
Let σ map each target to a distinct query. The assignment minimizes the sum over all targets:
For the matrix [[1,2],[2,100]], greedily taking the smallest entry first gives total 101. Assigning row 0 to column 1 and row 1 to column 0 gives total 4. A local best edge need not belong to the globally best combination.
Our solver maintains row prices u and column prices v. Feasibility requires and . Starting with each row minimum and zero column prices satisfies these constraints. It grows an alternating tree through occupied columns, reduces slack until another edge is tight, and reverses an alternating path when it reaches a free column. Matched edges remain tight. Unused columns have zero price. These conditions give a checkable optimality certificate:
To see the lower bound, sum the feasible-price inequality over any assignment. The selected column prices are at least the sum of all column prices because the omitted prices are nonpositive. Equality for our matching follows from tight matched edges and zero unused-column prices. This proves optimality independently of whether the program happens to pass a few examples.
The routine is a modern rectangular primal-dual Hungarian variant. For M≤N it uses O(M²N) time and O(M+N) auxiliary storage beyond its cost matrix: the kth search visits at most k occupied rows and scans N columns for each. Kuhn’s original paper gives the historical assignment/dual-budget context in a square maximum-score formulation; we do not attribute this exact rectangular routine or bound to its 1955 code. The official DETR matcher calls SciPy. The fixed SciPy 1.12 documentation identifies its internal method as modified Jonker–Volgenant, which solves the same assignment problem but is a different implementation. Kuhn, introduction and printed p.87, SciPy 1.12
Why negative probability and negative log probability are different
Matching uses negative probability; classification training uses negative log probability. This distinction can change the matching, even though logarithm is monotone for positive inputs. Consider two predictions with the following valid class distributions and identical boxes:
| Query | Class 0 | Class 1 | No object |
|---|---|---|---|
| 0 | 0.60 | 0.35 | 0.05 |
| 1 | 0.25 | 0.05 | 0.70 |
There is one target of each foreground class. Matching target 0→query 0 and target 1→query 1 gives a negative-probability sum of −0.65; swapping gives −0.60, so the first assignment wins. Negative log probability instead compares −log(0.60×0.05)=3.506558 with −log(0.25×0.35)=2.436116, so the swap wins. A monotone transform preserves the ordering of individual edges, not sums of different edges. The identical box terms contribute the same total in both cases. Paper matching discussion
Normalize the training loss in the right places
Once matching is selected, define as the matched foreground class or no object for every query. Let be 1 for foreground and ε=0.1 for no object. For a single image, the weighted-mean class loss is
The denominator is the sum of target-class weights, not simply N. If every target is absent, all weights equal ε and cancel between numerator and denominator. For three queries with two equally probable classes, the result is log 2≈0.693147, not zero and not 0.1 log 2. No object is a supervised class, not an ignored label. Fixed criterion, PyTorch 2.2 class-index weighted mean
Only matched foreground boxes contribute localization. With normalization by the number of targets, clamped to at least one, our one-image loss is
With no targets the box sums are empty and zero, while classification still trains background. In the official batched criterion the class reduction runs over the combined predictions; the box normalizer uses the object count aggregated across devices and divided by device count, clamped to one. Averaging independently normalized per-image losses is generally different. Auxiliary decoder outputs are matched again at their own layer; this example has one layer and no auxiliary terms. Criterion forward and auxiliary losses
The assignment is computed outside differentiation. Holding it fixed, the class-logit derivative for class k is
That derivative follows from log-softmax; the fixed boxes contribute no class-logit derivative. At a matching switch the selected branch may change. Do not backpropagate through discrete query indices as though they were ordinary continuous outputs. Our finite-difference test holds the matching fixed so that it tests the stated derivative.
Run the whole small forward path
The following standalone program uses Python 3.12 and NumPy 1.26.4. Save it as detr.py and run python detr.py in an environment with NumPy. It accepts a supplied 2×2 feature map with three channels, masks one padded position, projects to D=8, and uses two heads, one encoder layer, one decoder layer, four queries and two foreground classes. The feed-forward hidden width is 16. Random seed 13 fixes the example.
The original fixed defaults are much larger: six encoder and six decoder layers, D=256, eight heads, 100 queries and feed-forward width 2048. Here LayerNorm has unit gain and zero bias; attention projection biases are zero and dropout is omitted. The example contains no CNN feature extractor, pretrained recognition, auxiliary decoder losses, box gradients or Transformer backpropagation. It computes the forward model, exact assignment and all three loss terms, then takes one step on the class logits themselves, leaving the model weights and boxes fixed. That is a gradient demonstration, not detector training. Fixed configuration
At inference, matching needs no targets because it is not used. The fixed postprocessor takes softmax across all classes, then selects each query’s largest foreground probability without renormalizing away the no-object probability. It converts boxes to corners and multiplies horizontal coordinates by image width and vertical coordinates by image height. That routine returns a score and box for every query; it does not itself apply a score threshold or NMS. A display’s threshold is a separate choice. PostProcess
"""Original small DETR-style forward and set loss from supplied image features, using NumPy."""
import numpy as np
def minimum_assignment(cost):
"""Assign every target row to a distinct query column; return assignment and dual prices.
Finite, moderate-magnitude costs; target count must not exceed query count.
This is a primal-dual augmenting-path Hungarian variant, not SciPy's JV implementation.
"""
c = np.asarray(cost,float)
if c.ndim != 2 or not np.isfinite(c).all():
raise ValueError('finite two-dimensional assignment costs required')
targets,queries = c.shape
if targets > queries:
raise ValueError('more targets than query slots; cannot cover every target')
if targets == 0:
return np.empty(0,dtype=int),np.empty(0),np.zeros(queries)
# Feasible prices: u_i + v_j <= c_ij, with v_j <= 0.
u = np.r_[0.,c.min(axis=1)]
v = np.zeros(queries+1)
owner = np.zeros(queries+1,dtype=int)
predecessor = np.zeros(queries+1,dtype=int)
for target in range(1,targets+1):
owner[0] = target # Column zero is the alternating-tree root, not a query.
used = np.zeros(queries+1,dtype=bool)
slack = np.full(queries+1,np.inf)
column = 0
while True:
used[column] = True
row = owner[column]
delta,next_column = np.inf,-1
for j in range(1,queries+1):
if used[j]:
continue
reduced = c[row-1,j-1]-u[row]-v[j]
if reduced < slack[j]:
slack[j] = reduced
predecessor[j] = column
if slack[j] < delta:
delta,next_column = slack[j],j
if next_column < 0 or not np.isfinite(delta):
raise ValueError('assignment exceeds numerical range')
for j in range(queries+1):
if used[j]:
u[owner[j]] += delta
v[j] -= delta
else:
slack[j] -= delta
column = next_column
if owner[column] == 0:
break
# Reverse matched/unmatched edges along the path to a free query.
while column:
previous = predecessor[column]
owner[column] = owner[previous]
column = previous
assigned = np.full(targets,-1,dtype=int)
for j in range(1,queries+1):
if owner[j]:
assigned[owner[j]-1] = j-1
return assigned,u[1:],v[1:]
def softmax(values):
z = np.asarray(values,float)
shifted = z-z.max(axis=-1,keepdims=True)
exp = np.exp(shifted)
return exp/exp.sum(axis=-1,keepdims=True)
def sigmoid(values):
z = np.asarray(values,float)
exp = np.exp(-np.abs(z))
return np.where(z >= 0,1/(1+exp),exp/(1+exp))
def layer_norm(values, epsilon=1e-5):
"""Per-token normalization; unit gain and zero bias in this small forward profile."""
z = np.asarray(values,float)
centered = z-z.mean(axis=-1,keepdims=True)
return centered/np.sqrt(np.mean(centered**2,axis=-1,keepdims=True)+epsilon)
def sine_positions(padding, width=8):
"""Normalized cumulative valid-pixel coordinates, y features before x features."""
mask = np.asarray(padding)
if mask.ndim != 2 or mask.dtype.kind != 'b' or min(mask.shape) < 1:
raise ValueError('a nonempty boolean H-by-W padding mask is required')
if type(width) is not int or width < 4 or width % 4:
raise ValueError('position width must be a positive multiple of four')
valid = ~mask
y,x = valid.cumsum(axis=0,dtype=float),valid.cumsum(axis=1,dtype=float)
y = y/(y[-1:,:]+1e-6)*(2*np.pi)
x = x/(x[:,-1:]+1e-6)*(2*np.pi)
half = width//2
frequency = 10000.**(2*(np.arange(half)//2)/half)
axes=[]
for coordinate in [y,x]:
phase=coordinate[...,None]/frequency
axes.append(np.stack([np.sin(phase[...,0::2]),np.cos(phase[...,1::2])],axis=-1).reshape(*mask.shape,half))
return np.concatenate(axes,axis=-1).reshape(-1,width)
def attention(query, key, value, matrices, heads=2, padding=None):
"""Multi-head attention with zero projection biases; padding marks ignored keys."""
q,k,v = (np.asarray(a,float) for a in [query,key,value])
if q.ndim != 2 or k.ndim != 2 or v.shape != k.shape or q.shape[1] != k.shape[1] or len(k) == 0:
raise ValueError('compatible nonempty-key attention matrices required')
width=q.shape[1]
if type(heads) is not int or heads < 1 or width == 0 or width % heads:
raise ValueError('head count must divide model width')
if len(matrices) != 4 or any(np.shape(w) != (width,width) for w in matrices):
raise ValueError('four square attention projection matrices required')
if not all(np.isfinite(a).all() for a in [q,k,v,*matrices]):
raise ValueError('finite attention inputs required')
mask=np.zeros(len(k),dtype=bool) if padding is None else np.asarray(padding)
if mask.shape != (len(k),) or mask.dtype.kind != 'b' or mask.all():
raise ValueError('padding must leave at least one valid key')
dim=width//heads
q,k,v=[(a @ w).reshape(len(a),heads,dim).transpose(1,0,2) for a,w in zip([q,k,v],matrices[:3])]
scores=q @ k.transpose(0,2,1)/np.sqrt(dim)
scores[...,mask]=-np.inf
probabilities=softmax(scores)
result=(probabilities @ v).transpose(1,0,2).reshape(-1,width) @ matrices[3]
return result,probabilities
def initialize(input_width=3,width=8,classes=2,queries=4,seed=13):
"""Small random weights, not pretrained recognition; each decoder query is a parameter."""
if any(type(n) is not int or n < 1 for n in [input_width,width,classes,queries]):
raise ValueError('positive integer dimensions required')
rng=np.random.default_rng(seed)
def linear(a,b):return rng.normal(0,1/np.sqrt(a),(a,b)),np.zeros(b)
def attn():return [linear(width,width)[0] for _ in range(4)]
return {'input':linear(input_width,width),'queries':rng.normal(size=(queries,width)),
'encoder':attn(),'encoder_ff':[linear(width,2*width),linear(2*width,width)],
'self':attn(),'cross':attn(),'decoder_ff':[linear(width,2*width),linear(2*width,width)],
'classes':linear(width,classes+1),'box':[linear(width,width),linear(width,width),linear(width,4)]}
def affine(x,weights):
w,b=weights
return x @ w+b
def feed_forward(x,layers):
for layer in layers[:-1]:x=np.maximum(affine(x,layer),0)
return affine(x,layers[-1])
def forward(features,positions,parameters,heads=2,padding=None,query_positions=None):
"""One post-norm encoder and one parallel decoder; no CNN backbone or training dropout."""
x,pos=np.asarray(features,float),np.asarray(positions,float)
queries=np.asarray(parameters['queries'] if query_positions is None else query_positions,float)
if x.ndim != 2 or len(x) == 0 or pos.ndim != 2 or len(pos) != len(x) or queries.ndim != 2 or len(queries) == 0:
raise ValueError('nonempty image-feature, position and query matrices required')
if not all(np.isfinite(a).all() for a in [x,pos,queries]):raise ValueError('finite inputs required')
memory=affine(x,parameters['input'])
if memory.shape != pos.shape or queries.shape[1] != memory.shape[1]:
raise ValueError('projected features, positions and queries must share model width')
encoded,encoder_weights=attention(memory+pos,memory+pos,memory,parameters['encoder'],heads,padding)
memory=layer_norm(memory+encoded)
memory=layer_norm(memory+feed_forward(memory,parameters['encoder_ff']))
content=np.zeros_like(queries)
decoded,self_weights=attention(content+queries,content+queries,content,parameters['self'],heads)
content=layer_norm(content+decoded)
decoded,cross_weights=attention(content+queries,memory+pos,memory,parameters['cross'],heads,padding)
content=layer_norm(content+decoded)
content=layer_norm(content+feed_forward(content,parameters['decoder_ff']))
content=layer_norm(content) # The outer decoder also applies its final normalization.
return {'logits':affine(content,parameters['classes']),
'boxes':sigmoid(feed_forward(content,parameters['box'])),
'memory':memory,'hidden':content,'encoder_attention':encoder_weights,
'self_attention':self_weights,'cross_attention':cross_weights}
def corners(center_size):
b=np.asarray(center_size,float)
if b.ndim != 2 or b.shape[1] != 4 or not np.isfinite(b).all() or (b[:,2:] <= 0).any():
raise ValueError('finite cx,cy,w,h with positive sizes required')
return np.c_[b[:,:2]-b[:,2:]/2,b[:,:2]+b[:,2:]/2]
def generalized_iou(first,second):
"""Pairwise GIoU for positive-area xyxy boxes and their smallest enclosing rectangle."""
a,b=np.asarray(first,float),np.asarray(second,float)
for boxes in [a,b]:
if boxes.ndim != 2 or boxes.shape[1] != 4 or not np.isfinite(boxes).all() or (boxes[:,2:] <= boxes[:,:2]).any():
raise ValueError('positive-area finite xyxy boxes required')
lower=np.maximum(a[:,None,:2],b[None,:,:2])
upper=np.minimum(a[:,None,2:],b[None,:,2:])
intersection=np.maximum(upper-lower,0).prod(axis=-1)
union=(a[:,2:]-a[:,:2]).prod(axis=1)[:,None]+(b[:,2:]-b[:,:2]).prod(axis=1)[None,:]-intersection
enclosure=(np.maximum(a[:,None,2:],b[None,:,2:])-np.minimum(a[:,None,:2],b[None,:,:2])).prod(axis=-1)
return intersection/union-(enclosure-union)/enclosure
def validate_set(logits,predictions,truth,labels,weights):
z,b,g,y,w=(np.asarray(a) for a in [logits,predictions,truth,labels,weights])
if z.ndim != 2 or len(z) < 1 or z.shape[1] < 2 or not np.isfinite(z).all():
raise ValueError('finite query-by-class logits including no-object required')
corners(b);corners(g)
if b.shape != (len(z),4) or len(g) > len(b) or y.shape != (len(g),):
raise ValueError('box/label counts must fit the query capacity')
if any(((a < 0) | (a > 1)).any() for a in [b,g]):
raise ValueError('set-loss cxcywh coordinates must be image-normalized')
if len(y) and (y.dtype.kind not in 'iu' or (y < 0).any() or (y >= z.shape[1]-1).any()):
raise ValueError('target labels must be foreground integer class indices')
if w.shape != (3,) or not np.isfinite(w).all() or (w < 0).any() or not w.any():
raise ValueError('nonnegative class/L1/GIoU weights, at least one positive, required')
return z.astype(float),b.astype(float),g.astype(float),y.astype(int),w.astype(float)
def matching_cost(logits,predictions,truth,labels,weights=(1.,5.,2.)):
z,b,g,y,w=validate_set(logits,predictions,truth,labels,weights)
probability=softmax(z)
l1=np.abs(g[:,None,:]-b[None,:,:]).sum(axis=-1)
giou=generalized_iou(corners(g),corners(b))
return -w[0]*probability[:,y].T+w[1]*l1-w[2]*giou
def set_loss(logits,predictions,truth,labels,eos=.1,weights=(1.,5.,2.),assignment=None):
"""Actual normalized losses and class-logit gradient; no Transformer/box backprop here."""
z,b,g,y,w=validate_set(logits,predictions,truth,labels,weights)
if not np.isfinite(eos) or eos <= 0:raise ValueError('positive no-object class weight required')
selected=minimum_assignment(matching_cost(z,b,g,y,w))[0] if assignment is None else np.asarray(assignment)
if selected.shape != (len(g),) or selected.dtype.kind not in 'iu' or len(set(selected)) != len(g) or ((selected < 0) | (selected >= len(b))).any():
raise ValueError('one distinct valid query per target required')
target=np.full(len(z),z.shape[1]-1,dtype=int)
target[selected]=y
sample_weight=np.where(target == z.shape[1]-1,eos,1.)
shifted=z-z.max(axis=1,keepdims=True)
logp=shifted-np.log(np.exp(shifted).sum(axis=1,keepdims=True))
classification=-w[0]*np.sum(sample_weight*logp[np.arange(len(z)),target])/sample_weight.sum()
gradient=np.exp(logp)
gradient[np.arange(len(z)),target]-=1
gradient*=w[0]*sample_weight[:,None]/sample_weight.sum()
normalizer=max(len(g),1)
l1=w[1]*np.abs(b[selected]-g).sum()/normalizer
giou=w[2]*np.sum(1-np.diag(generalized_iou(corners(b[selected]),corners(g))))/normalizer
parts={'classification':float(classification),'L1':float(l1),'GIoU':float(giou)}
return float(sum(parts.values())),parts,selected,gradient
if __name__ == '__main__':
features=np.array([[1.,0,.2],[.3,.8,.1],[.1,.1,1.],[0,0,0]])
padding=np.array([[False,False],[False,True]])
positions=sine_positions(padding)
parameters=initialize()
result=forward(features,positions,parameters,padding=padding.ravel())
truth=np.array([[.25,.3,.2,.2],[.7,.65,.3,.25]])
labels=np.array([0,1])
value,parts,assignment,gradient=set_loss(result['logits'],result['boxes'],truth,labels)
updated=set_loss(result['logits']-.2*gradient,result['boxes'],truth,labels,assignment=assignment)[0]
print('query boxes cxcywh:',np.round(result['boxes'],6).tolist())
print('queries per target:',assignment.tolist())
print('loss parts:',{k:round(v,6) for k,v in parts.items()})
print('fixed-assignment logit step:',round(value,6),'->',round(updated,6))
print('first cross-attention row:',np.round(result['cross_attention'][0,0],6).tolist())
empty=set_loss(np.zeros((3,2)),np.tile([.5,.5,.2,.2],(3,1)),np.empty((0,4)),[])[0]
print('empty-target loss:',round(empty,6))
Actual output in that environment:
query boxes cxcywh: [[0.411589, 0.34556, 0.450477, 0.531124], [0.405195, 0.368582, 0.446128, 0.519977], [0.433959, 0.383451, 0.46347, 0.523163], [0.409145, 0.342303, 0.448986, 0.531673]]
queries per target: [1, 2]
loss parts: {'classification': 0.945795, 'L1': 4.397764, 'GIoU': 2.137218}
fixed-assignment logit step: 7.480777 -> 7.438932
first cross-attention row: [0.192459, 0.395386, 0.412155, 0.0]
empty-target loss: 0.693147
The last cross-attention weight is zero because the fourth image position is padding. Queries 1 and 2 are matched to the two targets; the other queries receive no object. The logit step lowers classification loss, so the total falls even though L1 and GIoU cannot improve when boxes are fixed. The four random boxes cluster together: a functioning forward path has not learned to recognize the two people in the opening example.
Tests compare small assignments with exhaustive enumeration and check a 31×44 floating-point assignment using the dual certificate. Further checks use hand attention averages, scalar-loop multi-head calculations, literal box geometry, the disjoint-box slope, fixed-matching logit finite differences, and query/target permutations. Permuting image features together with their positions and mask leaves the predicted set unchanged; permuting only the features is a different input. Changing padded contents leaves valid outputs unchanged. Replacing all query-position vectors with the same vector produces identical predictions, exposing the absence of a hard geometric uniqueness constraint.
Where the cost and capacity go
With L image tokens, N queries and width D, dense attention-score work scales as O(L²D) in the encoder, O(N²D) in decoder self-attention and O(NLD) in cross-attention. Materialized attention matrices use O(L²+N²+NL) entries per head. Projections and feed-forward layers add their own costs, and the omitted CNN is not free. Increasing spatial resolution can therefore become expensive even with few queries. The assignment matrix has MN entries and the local solver adds O(M²N) time. These bounds describe this dense implementation, not measured wall-clock speed.
N is a capacity limit for one-to-one supervision. If an image has more than N targets, no injection can cover them all. The teaching code rejects that input. A rectangular solver that merely returns the smaller number of pairs can silently leave annotations unmatched; increasing capacity or changing the training design is then necessary.
Removing NMS does not eliminate missed detections, duplicates, localization error or poorly calibrated scores. Adding NMS later changes the inference pipeline and should be evaluated as such. Nor does replacing anchors with learned queries make image resolution, feature quality and optimization unimportant. The original paper reports experiments; this chapter has not reproduced their datasets, training budgets or benchmark numbers.
For a default-box comparison, use SSD. For the reusable building block, use Transformer. For the detector evaluation problem shared by both, use object detection. Those connections explain alternatives without treating one architecture as universally superior.
Check the decisions, not just the names
1. Understanding: is a query tied to an object identity?
A slot matched the left person in one training image. Must it match the left person in the next image?
Answer: No. The learned query is a parameter used to read image content, while assignment is recomputed from the current predictions and targets. Slot indices are not annotation identities or a required left-to-right order. Queries can learn preferences without becoming fixed labels for individual objects.
2. Calculation: which assignment is actually cheaper?
Use the two-query probability table above with identical boxes. Compute both assignments under negative probability and negative log probability.
Answer: Direct target-to-query order gives −0.65 and 3.506558 respectively; the swap gives −0.60 and 2.436116. Negative probability selects direct order, while negative log probability selects the swap. Box costs cancel in this comparison. Monotonicity of each edge cost does not preserve the ordering of total assignment costs.
3. Boundary: an empty image
Three queries predict two equally likely classes, foreground and no object. There are no targets and ε=0.1. What are class loss and box loss? What changes if ε becomes 0.01?
Answer: Class loss is log 2≈0.693147 and both box terms are zero. The positive common no-object weight cancels from the weighted mean, so changing it to 0.01 leaves this all-background loss unchanged. In a batch mixing foreground and background it changes their relative contribution. Treating no object as ignored would be a different objective.
4. Transfer: a crowded image and a repeated box
A detector has four queries but an image has six targets. Another image has two targets and all four queries predict the same box. Can global assignment alone solve either problem?
Answer: It cannot cover six targets with four distinct slots; capacity or the design must change. With two targets it can assign distinct query indices, but the coordinates can still coincide. Set supervision supplies a training signal rather than a hard coordinate constraint. Examine capacity, features, learning and predictions; the solver’s optimality proves only that the current cost matrix was minimized.
Read each artifact for the question it answers
The original paper’s §§3.1–3.2 explain set matching and parallel prediction. The fixed matcher specifies negative probability, L1 and negative GIoU. The fixed criterion specifies class weighting, box normalization and auxiliary rematching. The Transformer, position encoding and box utilities resolve where positions enter attention and what the coordinate order means. The GIoU paper supplies the geometric construction; Kuhn and the fixed SciPy manual distinguish the assignment problem from a particular solver.
The recorded reading covers the DETR v3 method on physical pages 4–7, selected official forward/criterion routines and configuration, GIoU physical pages 3–4, and the stated Kuhn introduction/duality passages. It does not establish full experimental reproduction, all later DETR variants or every optional code path. The complete code above and numerical counterexamples are original teaching material; no upstream implementation was copied or executed. These reading boundaries are part of the evidence, not gaps that a smooth narrative should hide.
Make a prediction, then check
An empty image has three queries and two equally probable classes. With no-object weight0.1 and weighted-mean CE, what is the class loss?
Learning objectives
- Trace image positions and learned object queries through a parallel encoder-decoder forward.
- Solve global one-to-one assignment and distinguish probability costs from logarithmic training loss.
- Derive GIoU, weighted class normalization and empty-target behavior, and validate a complete small forward model.
Prerequisites & connections
Explore related knowledge →References
- End-to-End Object Detection with Transformers — v3 set prediction method
Nicolas Carion; Francisco Massa; Gabriel Synnaeve; Nicolas Usunier; Alexander Kirillov; Sergey Zagoruyko · 2020 - DETR Transformer — fixed post-norm forward
Facebook Research DETR contributors · 2024 - DETR model, set criterion and postprocessing at fixed commit
Facebook Research DETR contributors · 2024 - DETR HungarianMatcher — fixed probability and geometry costs
Facebook Research DETR contributors · 2024 - DETR normalized sine image position encoding
Facebook Research DETR contributors · 2024 - DETR fixed model and loss default arguments
Facebook Research DETR contributors · 2024 - DETR cxcywh conversion and generalized box IoU
Facebook Research DETR contributors · 2024 - Generalized Intersection over Union: A Metric and A Loss for Bounding Box Regression — method
Hamid Rezatofighi; Nathan Tsoi; JunYoung Gwak; Amir Sadeghian; Ian Reid; Silvio Savarese - The Hungarian Method for the Assignment Problem — introduction and dual budget
Harold W. Kuhn · 1955 - SciPy1.12 linear_sum_assignment — rectangular assignment
SciPy contributors - PyTorch2.2 CrossEntropyLoss — class-index weighted mean
PyTorch contributors - End-to-End Object Detection with Transformers — arXiv submission history
Nicolas Carion and coauthors · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded DETR/GIoU/Kuhn primary reading, fixed official forward/criterion, global dual certificates, hand geometry/attention, permutation invariants, class-logit finite differences and complete bilingual comparison. Not independent human review, full detector training or benchmark reproduction.
- Twenty-one numerical checks: exhaustive assignment comparison and dual certificates, greedy and probability counterexamples, hand and scalar-loop attention, positions/masks, query and image-token permutations, coincident queries, literal cxcywh/GIoU and disjoint-box slope, weighted/empty CE, fixed-assignment class-logit finite differences and loss decrease, invalid inputs. Tests extract the code from the formal article.
- Compared all bilingual sections: nine display formulas, code and output, coordinate and positional contracts, probability versus log costs, single-image versus batch normalizers, capacity/inference limits, four explained answers and twelve bounded source records. One additional structural bilingual test. Explicitly no CNN, box/Transformer backprop or benchmark claim.
Source locations checked:
- End-to-End Object Detection with Transformers — v3 set prediction method · Read physical pages 4–7, especially §§3.1–3.2; page 5 equations visually checked. Parallel query architecture, probability-based assignment and class/box losses; auxiliary-loss continuation and experiments not fully read.
- DETR Transformer — fixed post-norm forward · Read lines 1–170 and 180–283: model/stack forward, post-norm encoder and decoder, zero target content, positional Q/K additions and final decoder norm. Pre-norm only partly read; no execution or code reuse.
- DETR model, set criterion and postprocessing at fixed commit · Read 1–166,185–286 and MLP definition 289–301: heads/forward, labels and boxes, weighted CE, object normalization and auxiliary rematching; postprocess foreground maxima and pixel scaling. Segmentation loss and full training not audited; no code reuse or execution.
- DETR HungarianMatcher — fixed probability and geometry costs · Read all 86 lines: no_grad, softmax, negative class probability, L1, negative GIoU and SciPy assignment. No explicit no-object targets; query/target orientation transposed in the teaching program.
- DETR normalized sine image position encoding · Read PositionEmbeddingSine and build selection: valid-mask cumulative coordinates, normalization with 1e-6, 2pi scale, temperature10000, y then x. Learned alternative not used; original NumPy float64 adaptation, no upstream code copied.
- DETR fixed model and loss default arguments · Read argument block 32–82: ResNet50, sine, six/six layers, width256, FFN2048, eight heads,100 queries, post-norm default, class/L1/GIoU matching1/5/2, box losses5/2 and eos0.1. Full main/training loop unread.
- DETR cxcywh conversion and generalized box IoU · Read first67 lines: center-size coordinate contract, pairwise intersection/union and axis-aligned enclosure. Positive-area guards in teaching code are explicit stricter requirements.
- Generalized Intersection over Union: A Metric and A Loss for Bounding Box Regression — method · Read title/authors and physical pages3–4, algorithms1–2; page4 visually checked. Axis-aligned enclosure and loss; no benchmark, supplemental metric proof or universal nonzero-gradient claim.
- The Hungarian Method for the Assignment Problem — introduction and dual budget · Read physical1–2 and5 (printed87), with page5 visually checked. Original square maximum-score/budget formulation; full section4 routines unread, not the exact modern rectangular teaching implementation.
- SciPy1.12 linear_sum_assignment — rectangular assignment · Read API, rectangular notes, modified Jonker–Volgenant statement and the3x3 example with optimum5. Rechecked online2026-09-07; no SciPy runtime installed or original DETR environment inferred.
- PyTorch2.2 CrossEntropyLoss — class-index weighted mean · Read CrossEntropyLoss1037–1080 and1168–1181: class-index-target reduction divides by summed target weights. Fixed semantic reference, not installed torch or original DETR software version.
- End-to-End Object Detection with Transformers — arXiv submission history · Read title/authors, abstract and dated history; first submission26May2020, v3 revision28May2020. Rechecked online2026-09-07; no abstract benchmark claim adopted.
Related topics