---
title: "Rethinking Transformer-based Set Prediction for Object Detection"
description: "Rethinking Transformer-based Set Prediction for Object Detection explains why DETR trains slowly and tests two faster ways to predict object sets."
canonical: "https://research.elamur.ai/free/en/papers/sun-2021-rethinking-transformer-based-set-prediction/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/sun-2021-rethinking-transformer-based-set-prediction/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2021](https://md.research.elamur.ai/free/en/papers/2021/) / Rethinking Transformer-based Set Prediction for Object Detection

# Rethinking Transformer-based Set Prediction for Object Detection

Paper · 2021 · Zhiqing Sun, Shengcao Cao, Yiming Yang et al.

**Authors:** [Zhiqing Sun](https://md.research.elamur.ai/free/en/authors/zhiqing-sun/), [Shengcao Cao](https://md.research.elamur.ai/free/en/authors/shengcao-cao/), [Yiming Yang](https://md.research.elamur.ai/free/en/authors/yiming-yang/) and [Kris Kitani](https://md.research.elamur.ai/free/en/authors/kris-kitani/) · **Year:** 2021 · **Venue:** IEEE/CVF International Conference on Computer Vision (ICCV) · **Licence:** [CC BY 4.0 (arXiv)](https://creativecommons.org/licenses/by/4.0/)

[**356** citations OpenAlex, 2026-10-14](https://openalex.org/works?filter=cites:W3107331169) · [Cited by **14** papers in our library of more than 163,000 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/sun-2021-rethinking-transformer-based-set-prediction/cited-by/) · [IEEE/CVF International Conference on Computer Vision (ICCV)](https://openalex.org/S4363607764) · [licence](https://creativecommons.org/licenses/by/4.0/)

- [PDF](https://arxiv.org/pdf/2011.10881)
- [DOI 10.1109/iccv48922.2021.00359](https://doi.org/10.1109/iccv48922.2021.00359)
- [arXiv 2011.10881](https://arxiv.org/abs/2011.10881)
- [OpenAlex](https://openalex.org/W3107331169)

Citations: OpenAlex, 2026-10-14.

## Summary

An object detector has to say what is in an image and where each object is. If it draws several boxes around the same object, it also has to decide which box to keep. Many detectors learn to score individual boxes and leave that last decision to a separate cleanup step. DETR, short for Detection Transformer, learns to produce a final set directly. During training, each annotated object gets a single prediction as its partner. This gives the detector a reason to produce distinct detections, but makes it expensive to train. The paper asks which parts of [DETR](https://md.research.elamur.ai/free/en/papers/carion-2020-end-end-object-detection-transformers/) account for that cost and whether they can be changed while keeping the set-based objective.

The authors investigate two stages at which learning can get off to a slow start. During matching, the identity of the prediction assigned to an object can change as training progresses. Providing fixed assignments from a trained detector helps in the first few epochs, but the effect becomes small after around 15 epochs in the COCO validation experiment. The other difficulty is how the detector reads the image. DETR’s decoder uses cross-attention to gather image information for each prospective detection. The authors find that these attention weights continue to become more concentrated even after 100 training epochs. When they remove the decoder and predict from image features directly, overall average precision stays broadly comparable in their experiment, with better results for small objects and worse results for large ones.

The paper turns that simpler architecture into two detectors. Both gather image features at several scales and give a selected subset to a Transformer encoder, which lets candidates exchange information before predicting object categories and boxes. TSP-FCOS selects promising locations. TSP-RCNN selects preliminary boxes and refines them. Both limit which predictions can be assigned to which annotations during training. For a location, eligibility depends on where it lies and the scale of its feature map. For a preliminary box, eligibility depends on how well it overlaps the annotation. The detector still chooses its assignments by optimizing a cost across the set of eligible pairs.

On COCO 2017, both approaches learn faster than the original DETR and outperform the conventional detectors they draw on. TSP-RCNN has better overall and small-object average precision than TSP-FCOS in the main validation comparison, with slightly higher inference latency. A longer run with crop augmentation improves the comparison with strong DETR configurations, though TSP-RCNN still trails the enhanced DETR-DC5 on large objects. The results show that a detector can preserve one-to-one supervision while giving its predictions a spatial starting point, and that this combination can produce competitive detections on a substantially shorter training schedule.

## Deep dive: Rethinking Transformer-based Set Prediction for Object Detection

Rethinking Transformer-based Set Prediction for Object Detection explains why DETR trains slowly and tests two faster ways to predict object sets. · about 35 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### Why a detector has to reason about the whole image

A bounding box answers a question about one region of an image. A set of detections has to answer a question about the image as a whole. Picture a scene in which several nearby windows contain enough of the same object to support a confident prediction. Each window can make a sensible local decision and still contribute to a bad answer for the image: several reported instances where there is only one. The reverse difficulty appears when separate objects are close together. Their boxes can overlap even when both detections belong in the answer. The desired output is a collection of category labels and boxes with one entry for each detected instance. There is no meaningful requirement to report the entries in a particular order.

The paper describes the prevailing approach as detection followed by merging. A detector first considers locations, windows or region proposals derived from the image. It makes predictions for these candidates and applies a rule to reduce redundancy. Non-maximum suppression, typically abbreviated NMS, is one such rule. It keeps high-scoring detections and suppresses other detections with sufficiently overlapping boxes. Its job starts once the detector has produced scores and coordinates. The authors’ concern is that a detector trained to make those local predictions is optimized without taking the final merging decision into account. A learning objective for the final set would give the detector a direct training signal about which predictions should coexist.

The paper distinguishes one-stage detectors, which predict from feature-map locations, from two-stage detectors, which form proposals and then refine them. A feature map is a grid of vectors computed from the image. The vectors summarize visual evidence near corresponding locations. A proposal adds explicit box geometry to that evidence, giving a later stage a preliminary estimate of an object’s extent. In the paper’s account, two-stage methods generally trade additional computation for better accuracy. Both families ordinarily depend on a merging step. Their stage count describes the organization of candidate prediction, rather than how the final set is supervised.

[FCOS](https://md.research.elamur.ai/free/en/papers/tian-2019-fcos-fully-convolutional-one-stage/) is the one-stage example most relevant to the new design. It makes predictions at feature-map positions without using pre-defined reference boxes, or anchors. A location can become a positive training example when it projects inside an annotated box. When boxes overlap at a location, the FCOS description in the paper favors the smaller box. Its regression branch estimates distances to the sides of the box, while the classification branch also estimates how centrally the location lies within the object it is responsible for. That center score can reduce the influence of boxes predicted from less central locations when NMS is applied. The design gives each prediction an interpretable spatial origin.

[Faster R-CNN](https://md.research.elamur.ai/free/en/papers/ren-2015-faster-r-cnn-towards-real/) gives its final predictor a different kind of starting point. A region proposal network first estimates candidate boxes and their objectness, meaning the likelihood that they contain an object of some category. The refinement stage extracts a fixed-size representation of each selected region and uses it to improve the box and assign a class. The paper describes suppression both when passing proposals to refinement and when producing final detections in conventional Faster R-CNN. The useful distinction for the new work is between producing a pool of plausible regions and deciding which predictions belong in the final set. The conventional detector packages those jobs together, but set-based supervision can change the second job while retaining a proposal stage.

#### What DETR changes

DETR builds a detection system around a [Transformer](https://md.research.elamur.ai/free/en/concepts/transformer/). A convolutional backbone first turns the image into a map of features. The encoder processes that map, and the decoder starts from learned vectors called object queries. Each query is a slot from which the decoder can produce a category and a box. The decoder processes the slots in parallel. Through cross-attention, each slot can draw on different parts of the image representation. Through self-attention, slots can exchange information with one another. The former operation brings evidence from the image into a prospective detection. The latter gives a prospective detection access to the state of other prospective detections.

The training objective needs to connect these slots to annotations. A particular slot has no required correspondence with the first entry in the annotation file, and there may be more slots than visible objects. The solution is bipartite matching, an assignment between the set of annotation targets and the set of predictions. Each real object is paired with a distinct prediction. Remaining predictions are supervised as having no object. Since the choice is made for the image as a whole, a second prediction for an already assigned object gains no extra positive target. The paper presents that supervision, together with self-attention, as the reason DETR can learn to handle duplicate detections without final NMS.

An assignment rule also shapes what the system sees during learning. The paper notes that earlier detectors often used heuristic rules to decide which anchors, windows or proposals should receive a particular object label. FreeAnchor sought to learn associations between windows and objects through maximum likelihood. The authors also cite a better way to score box geometry, [Generalized Intersection Over Union](https://md.research.elamur.ai/free/en/papers/rezatofighi-2019-generalized-intersection-over-union-metric/). They distinguish these developments from optimizing the predicted set itself. A better way to pick or score local positives can improve supervision while leaving the detector dependent on downstream merging.

Attention had a history in detection before DETR as well. The paper describes a relation module that lets detections account for other objects, a spatial attention module that increases the weight of foreground features, and a Transformer-like module that connects different representations. Those examples establish several jobs that attention can do inside a detector. The open question is how to combine it with an objective that treats the detections as a single output. DETR supplies such a design, but the presence of attention in earlier detectors gives no reason to assume that all the attention operations in its encoder and decoder are necessary for that objective.

#### Why slow training is hard to diagnose

In DETR, a newly initialized query has to learn where to look before it can make a reliable spatial prediction. At the same time, the quality of its current prediction helps determine whether it gets assigned to an object. These are different sources of difficulty. If assignments change, the same output slot can receive different supervision across visits to a training image. If cross-attention is diffuse, a slot can receive a broad mixture of evidence that makes it hard to localize an object, even when its intended target has been assigned consistently. An early error in either process can affect what the optimizer has to work with in the next step.

The authors place their investigation alongside two concurrent attempts to improve DETR. Deformable DETR uses sparse attention over multilevel feature maps. UP-DETR prepares the detector through unsupervised pretraining on a task involving random query patches. Both retain a route for queries to acquire visual information. The present paper asks whether the detection head can be simpler. A feature position already has image content and a location. A proposal carries content and approximate box geometry. Either can provide the basis for a prediction, with a shared encoder handling relationships among candidates and a set objective deciding their training assignments. The challenge is to preserve those advantages when the image contains objects of very different sizes.

### The method, step by step

#### From the image to a set of predictions

The authors first construct an encoder-only DETR to test what happens when features take the place of decoder queries. They then build TSP-FCOS and TSP-RCNN on the same basic principle. In both proposed detectors, a convolutional backbone and a feature pyramid supply image evidence at several resolutions. A scoring stage reduces this pool to a manageable group of candidates. Each selected candidate enters the encoder with a representation of its position. The encoder lets candidates share information, and a prediction head turns each updated representation into a category decision and a box.

The candidate and its eventual prediction are distinct. A selected point in TSP-FCOS is an input to the encoder, with the final box estimated downstream. A selected proposal in TSP-RCNN already has a box, which the final head can improve. During training, the candidate’s original geometry determines which annotations it is eligible to match. The predicted category and box contribute to evaluating the available assignments and incur losses after matching. At inference, the detector uses the image-derived candidates and the learned prediction head. The annotated objects are needed to supervise training.

Candidate selection and set prediction in TSP The steps in order.

#### The original and encoder-only versions of DETR

In the original architecture, the image features are flattened into a sequence for the encoder. Each encoder output can include information gathered from other image positions. The decoder receives this encoded image and a collection of learned object queries. It produces a detection from each query’s final representation. The query provides an address in the output set, while cross-attention supplies image-specific information about what might occupy that address. A prediction head then estimates the category and box. For box coordinates, the original DETR is described as reference-free: it directly predicts a normalized center and size relative to the image.

In the encoder-only version, the detection head operates on every output position of the encoder. For the image resolution and feature stride described by the authors, the encoder’s grid has the following spatial shape.

```
(H ÷ 32) × (W ÷ 32)
```

Here H is the image height and W is its width. The divisions describe the relation between image size and feature-map size. The multiplication symbol separates the height and width of the feature grid. Each feature on that grid is the starting point for a prediction. Self-attention still connects positions across the grid, allowing a detection to reflect evidence beyond the feature from which it originates.

A feature point provides a reference for box regression. The appendix specifies how the detector combines the reference coordinates with learned offsets to obtain the box center. For the horizontal coordinate, the paper gives the following relationship.

```
cx = σ(b₁ + σ⁻¹(xᵣ))
```

Here cx is the predicted normalized horizontal center, xᵣ is the horizontal coordinate of the reference feature point, and b₁ is the corresponding output of the regression head. The symbol σ denotes the sigmoid function, which maps its input into the normalized coordinate range. The inverse function σ⁻¹ converts a normalized reference coordinate to the space in which the offset is added.

```
cy = σ(b₂ + σ⁻¹(yᵣ))
```

Here cy is the predicted normalized vertical center, yᵣ is the vertical coordinate of the reference feature point, and b₂ is the vertical output of the regression head. The inverse sigmoid σ⁻¹ and sigmoid σ play the same roles as for the horizontal coordinate. With no offset, each coordinate returns to its reference value. An offset changes the center relative to the starting point supplied by the image grid.

This diagnostic architecture continues to use the Hungarian loss. It therefore tests whether an encoder can participate in the same kind of set supervision while using spatially grounded predictions. It also changes the origin of the predictions and how their box centers are parameterized. Those changes matter when interpreting the comparison with the original DETR: the experiment evaluates a working replacement for the decoder’s detection path.

#### Multiscale features and the selection budget

Using one grid puts the encoder-only detector in a difficult position. The same representation has to serve objects whose image sizes differ widely. A coarse grid may offer few useful starting positions for a small object. A large object can cover many candidate positions, making it difficult to choose which should get credit for it. The authors use feature maps at several resolutions to give the prediction system a better range of spatial starting points. Both new detectors build their pyramid with a [Feature Pyramid Network](https://md.research.elamur.ai/free/en/papers/lin-2016-feature-pyramid-networks-object-detection/).

The backbone is a residual convolutional network, or ResNet. The experiments use ResNet-50 and ResNet-101. The pyramid takes features from the backbone stages designated C₃ through C₅ and produces levels P₃ through P₇. The letters distinguish backbone outputs from pyramid outputs, and the subscripts identify their levels. The pyramid maps have 256 channels. Some runs also use deformable convolutions in the last three stages of the backbone. In the paper’s terminology, DCN denotes the deformable convolution variant. The underlying family of backbones comes from [Deep Residual Learning for Image Recognition](https://md.research.elamur.ai/free/en/papers/he-2015-deep-residual-learning-image-recognition/).

Multiscale features create a computational problem of their own. In dense self-attention, each input can be compared with every input. The amount of work in that operation grows quadratically with the number of inputs. Passing every position of every pyramid level to the encoder would make the attention stage expensive. Both methods make an image-dependent selection before that stage. The scoring system can examine the pyramid using convolutional operations, while the encoder receives a much smaller group whose members can interact directly.

The important consequence is that the encoder can pool evidence across scales through the selected candidates. A fine-level candidate and a coarser one can each carry information that helps interpret the other. The selected group also determines the opportunities for detection. If the preliminary ranking misses all useful candidates for an object, there is less opportunity for the final encoder and head to detect it. Increasing the budget provides more opportunities and increases attention work. The paper tests how sensitive its results are to that budget.

#### TSP-FCOS selects locations

TSP-FCOS applies a classification subnet and an auxiliary subnet to the feature pyramid. Each subnet shares its parameters across pyramid levels. Both contain four convolutional layers with 3×3 kernels, 256 channels and group normalization. The detector concatenates the two outputs at each location to make the feature available for selection. The classification subnet also supplies the information used by a binary classifier to estimate which locations are promising. The authors call selected vectors Features of Interest, or FoIs.

The FoI score answers whether a position is worth passing forward as a possible source of an object prediction. It is trained using the assignment rule borrowed from FCOS. The selection stage takes the 700 highest-scoring feature positions in the default configuration. Their representations and position encodings become the input to the Transformer encoder. Each encoder output goes to a shared feed-forward prediction head, which produces a category, including a no-object option, and a bounding box. A promising location can therefore survive the binary screening stage and still be judged a duplicate or assigned to the no-object class by the final predictor.

There are two distinct uses of geometric supervision in this path. The first trains the binary selector to recognize promising locations. The second restricts the assignments used to train the final detection set. To be eligible for a real object in the second stage, the initial feature position must lie inside the annotated box and come from the appropriate pyramid level. The position and level act together. A position inside the right box can still be ineligible if its scale is wrong. When more than one eligible candidate can represent an object, the set-based assignment decides which one receives the target. This preserves a way to compare competing candidates even though their search space has been narrowed.

The proposal borrows spatial conventions from FCOS without requiring the final head to make decisions independently at each location. A candidate carries the feature extracted at its original point. After attention, it also carries information from other selected points. This creates a path for the final classifier to use the presence of several plausible detections of the same instance. The local geometry helps choose where to look, and the set objective supplies a training signal about how many answers for that instance should survive.

#### TSP-RCNN selects boxes

TSP-RCNN starts the candidate selection stage with a region proposal network, or RPN. It uses two separate convolutional subnets for proposal classification and regression on P₃ through P₇. Its anchors follow the style of RetinaNet. An anchor gives the network a reference box from which to predict a proposal. The resulting proposal has both an objectness score and preliminary box coordinates. The 700 highest-scoring proposals are selected in the default configuration. As in the point-based detector, this is a ranking of potential inputs to the encoder.

For each selected box, the detector uses RoIAlign to extract a fixed-size feature representation from the multilevel maps. RoI stands for Region of Interest. The feature is flattened and passed through a fully connected layer to form the proposal representation. This means a candidate can carry visual evidence drawn from across its box, including an estimate of how much of the object the box covers. The encoder updates the proposal vectors together, and the final head classifies and refines each proposal.

The eligibility rule uses intersection over union, abbreviated IoU. This quantity divides the area shared by two boxes by the area covered by their union. A proposal is eligible to match an annotated object only if the IoU between the preliminary proposal and the annotated box is greater than 0.5. The threshold applies to the geometry with which the proposal enters refinement. The head can then learn from supervision attached to candidates that already cover a meaningful portion of the object.

The point and box variants place spatial constraints at a comparable point in training. TSP-FCOS asks whether the feature origin is inside an object and at a suitable scale. TSP-RCNN asks whether the proposed extent overlaps the object sufficiently. An image location can support a detection without furnishing an initial estimate of its size. A proposal makes that estimate early and requires extra work to produce and represent it. In both cases, it gives the matching procedure image-derived evidence before the final detection head has learned consistently accurate outputs.

#### How candidates represent their positions

An encoder needs a way to tell where its inputs originated. A feature vector can encode visual appearance, but similar-looking inputs from different parts of an image have different spatial meanings for detection. The paper represents each normalized coordinate by a pattern of sinusoidal components and combines coordinate patterns to describe the position of a candidate. Using different frequencies gives each coordinate several components through which it can affect attention.

```
PE(x)₂ᵢ = sin(x ÷ 10000^(2i ÷ dₘₒdₑₗ))
```

Here PE is the positional encoding function, x is the normalized input coordinate, and i indexes a pair of components in its encoding. The subscript 2i identifies the even component. The abbreviation dₘₒdₑₗ denotes the dimension of the feature representation, given as the FoI dimension in the paper’s definition. The constant 10,000 and the exponent determine the scale of the sine argument. The caret indicates exponentiation, and sin is the sine function.

```
PE(x)₂ᵢ₊₁ = cos(x ÷ 10000^(2i ÷ dₘₒdₑₗ))
```

Here PE again denotes positional encoding, x is the normalized coordinate, and i is the index of the component pair. The subscript 2i + 1 identifies the odd component paired with the preceding even component. The constant 10,000, the exponent and the feature dimension dₘₒdₑₗ give it the same argument scale as its partner. The function cos takes the cosine of that argument.

```
[PE(x) : PE(y)]
```

This expression is the position vector for a TSP-FCOS candidate. The quantities x and y are the normalized horizontal and vertical coordinates of its feature point. PE encodes each coordinate by the preceding rule. The colon inside brackets denotes concatenation, so both coordinate encodings appear in one vector.

```
[PE(cx) : PE(cy) : PE(w) : PE(h)]
```

This is the position vector for a TSP-RCNN proposal. The quantities cx and cy are the normalized horizontal and vertical coordinates of its center. The quantities w and h are its normalized width and height. PE is the same encoding function, and the colons concatenate the four encodings. Consequently, proposals centered in similar places can carry different positional information when their extents differ.

#### How the encoder combines evidence

The appendix gives scaled dot-product attention as the common operation behind self-attention and cross-attention. Queries determine what each input is looking for. Keys describe what can be matched against each query. Values are the vectors from which the output is assembled. In self-attention, these roles originate in the same group of inputs. In DETR’s decoder cross-attention, queries come from the decoder and the keys and values come from the encoded image.

```
Attention(Q, K, V) = softmax(QKᵀ ÷ √dₘₒdₑₗ) · V
```

Here Q, K and V are the query, key and value matrices. The superscript T transposes K, so QKᵀ contains the dot products between queries and keys. The square root of the hidden representation dimension dₘₒdₑₗ scales those scores in the paper’s general expression. The softmax function turns each query’s scores into weights across keys. The dot before V indicates matrix multiplication, which combines the value vectors with those weights. Attention is the resulting operation.

A single attention operation brings together evidence using a single set of projections. The multi-head version creates several projected representations, allowing separate comparisons among the same candidates. The paper expresses the calculation within a head as follows.

```
headₕ = Attention((P_Q + Q)W_Qₕ, (P_K + K)W_Kₕ, VW_Vₕ)
```

Here headₕ is the output of attention head h. The matrices Q, K and V are the query, key and value representations before the head’s projections. P_Q and P_K are the position encodings added to queries and keys. W_Qₕ and W_Kₕ are the query and key projection matrices for head h, and W_Vₕ is its value projection matrix. The positions enter the query-key comparison through the first two arguments. The third argument supplies projected values. Attention performs the weighting operation defined above.

```
MultiHead(Q, K, V) = Concat(head₁, …, head_H) Wᴼ
```

Here MultiHead is the operation on query, key and value inputs Q, K and V. The function Concat places the outputs of the attention heads side by side. The ellipsis runs from the first head, head₁, through head_H, where H is the number of heads in this formula. The shared output projection Wᴼ maps the concatenation back to the hidden representation width. Within a head, the query and key projections map from dₘₒdₑₗ to dₖ, the per-head query and key width, and the value projection maps to dᵥ, the per-head value width. The input width of the output projection is H times dᵥ.

After attention, a feed-forward network processes each position independently. This changes which components of the contextualized input are available to later layers. The paper gives the position-wise operation in the following form.

```
FFN(x) = max(0, xW₁ + b₁) W₂ + b₂
```

Here FFN names the feed-forward network and x is the vector at one position. W₁ and b₁ are the first linear transformation’s weight matrix and bias. The maximum with 0 is applied component by component, implementing the rectified linear activation. W₂ and b₂ are the second transformation’s weight matrix and bias. The first transformation maps from dₘₒdₑₗ to d_FFN, the intermediate width, and the second maps back. The bias vectors have the widths of their respective outputs.

The authors alternate attention and feed-forward operations, with residual connections and layer normalization. Residual connections carry an earlier representation forward by addition. Layer normalization rescales its components within the layer. Both proposed detectors use an encoder with 6 layers, a hidden width of 512, and 8 attention heads. The intermediate feed-forward width is 2048. The authors choose this encoder size to make the computational comparison with DETR-DC5 more comparable. During training, they randomly drop 70% of the encoder inputs to improve robustness. This exposes the predictor to different subsets of the selected group.

#### Matching predictions and applying the loss

To describe the loss, let y be the set of annotated objects and ŷ the set of candidate predictions. The paper writes M for the number of real objects and N for the number of predictions. In the usual case M is smaller than N. The annotation set is padded with no-object entries to obtain ȳ, a set with the same size as ŷ. The use of padding gives every prediction a classification target while allowing a distinction between real and empty entries.

```
σ̂ = argmin_(σ ∈ 𝔖_N) ∑ᵢ₌₁ᴺ ℒₘₐₜcₕ(ȳᵢ, ŷσ₍ᵢ₎)
```

Here σ is a proposed pairing, represented as a permutation of the prediction indices. The symbol 𝔖_N denotes the set of permutations of N indices. The index i runs from the first padded target to the last. The entry ȳᵢ is target i, and ŷσ₍ᵢ₎ is the prediction that permutation σ assigns to it. The function ℒₘₐₜcₕ assigns a cost to that pair. The summation adds costs across the image and argmin selects a permutation with the lowest total. The result is σ̂. In the proposed detectors, the geometric rules restrict which real-target pairings the optimizer can consider.

The assignment is a joint decision. If the same prediction would work well for several targets, the matcher can give it to only one. Its choice can depend on what other predictions are available to cover those targets. A point inside overlapping annotations, or a proposal that overlaps several nearby annotations, illustrates why an admissibility rule can help without fully determining the result. Geometry narrows the candidate pairs. The costs rank the remaining possibilities in the context of the whole image.

```
ℒ_Hungarian(ȳ, ŷ) = ∑ᵢ₌₁ᴺ [ℒ_class(i, σ̂(i)) + 𝟙{ȳᵢ ≠ ∅} ℒ_box(i, σ̂(i))]
```

Here ℒ_Hungarian is the total loss on the padded targets ȳ and prediction set ŷ. The index i runs over the N padded targets. The selected partner for i is prediction σ̂(i). The term ℒ_class is the classification loss for the matched pair, and ℒ_box is its box regression loss. The symbol ∅ marks a no-object entry. The indicator 𝟙{ȳᵢ ≠ ∅} activates the regression term for a real object and suppresses it for an empty entry. The outer sum accumulates the contributions of the pairs.

The appendix specifies focal loss for the classification terms in both proposed detectors. Its role is to weight examples in the presence of many negative candidates. For regression, the authors combine L1 loss, which penalizes absolute coordinate differences, with Generalized IoU loss, which scores box geometry. The use of a box loss is separate from the use of proposal IoU in the TSP-RCNN eligibility rule. The former tells the matched prediction how far its box is from the target. The latter decides whether the starting proposal is eligible to receive that target. The authors use the final encoder output for set supervision and omit intermediate auxiliary losses after encoder layers. The classification weighting follows [Focal Loss for Dense Object Detection](https://md.research.elamur.ai/free/en/papers/lin-2017-focal-loss-dense-object-detection/).

#### Data augmentation and optimization

The default training procedure uses the 36-epoch schedule described as 3×. Image scaling selects the shortest side from 640, 672, 704, 736, 768 and 800, with the longest side capped at 1333. Training also uses random horizontal flips. Scaling changes the image resolution at which the detector sees an object, while flipping changes the spatial arrangement of the same visual content. The pyramid and candidate selection have to work under both changes.

The authors use AdamW for the Transformer and stochastic gradient descent with momentum 0.9 for the rest of the detector. The default run uses a batch size of 16 and lasts 2.7×10⁵ iterations. The initial learning rates are 10⁻⁴ for AdamW and 10⁻² for stochastic gradient descent. Both are multiplied by 0.1 at 1.8×10⁵ and 2.4×10⁵ iterations. Learning rates warm up linearly during the first 1000 iterations. Weight decay is 10⁻⁴, and the Transformer gradients have a maximum L₂ norm of 0.1. The norm cap limits the magnitude of an update’s gradient signal from that part of the detector. AdamW follows [Decoupled Weight Decay Regularization](https://md.research.elamur.ai/free/en/papers/loshchilov-2017-decoupled-weight-decay-regularization/).

The longer procedure is a 96-epoch schedule labeled 8×. It resumes from the checkpoint at epoch 24 of the default run, at 1.8×10⁵ iterations, and continues for 72 epochs, described as 5.4×10⁵ iterations. The learning rate drops by the factor 0.1 at 4.8×10⁵ and 6.4×10⁵ iterations. The longer schedule also adds random crop augmentation. With probability 0.5 a training image is cropped to a random rectangle and then resized to the paper’s stated 800-1333 range. The authors release the implementation under the name TSP-Detection.

### Experiments and results

#### What the benchmark measures

The experiments use COCO 2017 detection. The dataset has 80 object classes. The authors report training on the 115k images of trainval35k and using the 5k images in minival for validation. For test results, they submit predictions on test-dev to the evaluation server. Validation provides the basis for the comparisons of training curves and design choices. The test-server comparisons address how the completed detectors rank against other systems under the paper’s stated backbone and evaluation conditions. The benchmark is [Microsoft COCO](https://md.research.elamur.ai/free/en/papers/lin-2014-microsoft-coco-common-objects-context/).

Average precision, abbreviated AP, is the primary detection metric. It reflects how well the detector ranks predictions that identify objects with sufficiently accurate boxes. An incorrect category, an inaccurate box or a duplicate can affect the results. The paper also reports AP separately for small, medium and large objects using COCO’s definitions. These splits matter because a change in the architecture can help one size range and hurt another. An overall result can obscure that change even when it is important for understanding how a detector operates.

The authors also compare computational quantities. FLOPs describe the number of floating-point operations and give an indication of arithmetic cost. FPS expresses throughput in frames per second. Inference latency measures how long prediction takes under a particular measurement setup. The paper uses Detectron2 to measure FLOPs and FPS and specifies a single Nvidia GeForce RTX 2080 Ti for inference latency measurements. The epoch count addresses a different question. It measures the training schedule in passes over the training data, which can differ in runtime across architectures and hardware.

#### How the main comparisons are organized

The main validation comparisons put TSP-FCOS alongside FCOS and TSP-RCNN alongside Faster R-CNN, as well as comparing the new systems with DETR. Those are comparisons with conventional detector families that supply the new candidates and an end-to-end set predictor that supplies the original objective. The experiments also include Deformable DETR and UP-DETR, the concurrent approaches to better DETR training. The main evaluation distinguishes results the authors reproduced and configurations using longer schedules with crop augmentation. It also marks a comparison involving Deformable DETR without iterative refinement, which the appendix follows up under a common training setup.

On COCO 2017 validation, the authors report that TSP-FCOS improves on FCOS and TSP-RCNN improves on Faster R-CNN. Between the two proposed detectors, TSP-RCNN leads on overall AP and small-object AP. It incurs slightly higher inference latency. The region-based detector has to produce boxes and extract their region features before the encoder can compare them. Its higher AP is therefore associated with a different prediction path and a measurable cost at inference, even though both proposed detectors use the same default count of encoder candidates.

The paper introduces the convergence problem with an original DETR run of 500 epochs. It says that run takes at least 10 days on 8 V100 GPUs. The proposed detectors’ default schedule is 36 epochs. The enhanced TSP-RCNN+ uses the 96-epoch schedule and random crops. The stated schedules put the differences in expected training length in perspective. The AP curves discussed below are the evidence that the shorter training can yield strong detections.

Training schedules for DETR and the proposed detectors on COCO detection The proposed detectors use shorter schedules in both their default and extended training configurations.

**The numbers**

| System or setting | epochs |
| --- | --- |
| Original DETR | 500 |
| TSP-FCOS and TSP-RCNN, default (this paper) | 36 |
| TSP-RCNN+, extended | 96 |

The comparison with Faster R-CNN frames the practical motivation from another direction. The introduction puts its convergence at about 30 epochs, close to the training regime of the proposed detectors in the sense relevant to the authors’ question. The validation curve comparison uses DETR-DC5, which serves as the reference for both training progress and the encoder’s computational sizing. In that comparison, TSP-FCOS and TSP-RCNN improve their detection performance sooner and finish ahead of the DETR-DC5 curve reported by the authors. Neither inference latency nor training wall time follows from the schedule chart. The reported wall time belongs to the original DETR configuration.

#### Longer training and test comparisons

For stronger validation comparisons, the authors extend TSP-RCNN training and apply the crop augmentation used in the DETR setting. This variant is TSP-RCNN+. They include the enhanced Faster R-CNN results from the DETR study in the same comparison. The authors report that enhanced TSP-RCNN reaches competitive results with a shorter schedule than the DETR configurations they compare against. Enhanced DETR-DC5+ retains the advantage on large-object AP. This is a specific exception to the overall comparison, consistent with the earlier observation that the way candidates are generated can have different consequences for different object sizes.

The COCO 2017 test comparison uses individual detectors at a single image scale. It compares TSP-RCNN with one-stage and two-stage approaches using ResNet-101 and, in a separate group, the deformable convolution version of that backbone. The proposed detector uses the 8× schedule and random crops in these experiments. The paper reports that TSP-RCNN has the highest overall AP among the entries in each backbone group. The separate groups matter because changing to a deformable backbone also changes how the convolutional part of the detector samples spatial information.

The appendix applies the same test protocol to TSP-FCOS. It reports that TSP-FCOS leads the one-stage entries on AP and trails TSP-RCNN slightly. This narrows the interpretation of the validation result. The point-based design remains competitive within the one-stage family on the test split. The proposal-based design has the stronger overall result of the two under the test protocol, consistent with the direction of the main validation comparison. The paper’s account of these comparisons gives the rankings by AP. Its numerical statements about the overall program also include the training budgets, the compute budgets in the expanded baseline experiments, and the refinement gain reported in the appendix.

### What the ablations show

#### Stabilizing assignments helps early training

The diagnostic experiments use a ResNet-50 backbone and measure AP on COCO 2017 validation. The first experiment asks whether DETR’s predictions are slow to improve because their assignment to objects varies early in training. At initialization, poor predictions offer little reason to prefer one assignment over another. During optimization, changes in prediction quality or stochastic behavior can also alter which slot receives a target. That gives the authors two reasons to test stable assignments directly.

They train a student DETR using the matches made by a previously trained DETR. In this procedure, called matching distillation, the student receives the teacher’s assignments as label correspondences. The teacher operates deterministically, with stochastic behavior disabled in modules such as dropout and batch normalization. The intervention fixes the source of the assignments. The student still has to learn the object categories and boxes associated with them.

The comparison covers the first 25 epochs. The student using distilled matches improves faster in the first few epochs, and the difference becomes small after around 15 epochs. The authors interpret this as evidence that assignment instability contributes to the early difficulty. It does not account for the much longer training course on its own. The experiment also motivates a practical distinction between obtaining a stable target from an already trained detector and obtaining a more plausible target from geometry available during training. The proposed TSP detectors take the second approach.

#### Cross-attention keeps changing after the early phase

The second diagnostic follows the attention with which decoder queries read image features. Near the start of training, the authors describe the attention as nearly uniform. They collect cross-attention maps during validation at several training stages and use negative entropy as a measure of how concentrated the weights are. Their calculation for a source position is as follows.

```
sᵢ = (1 ÷ m) ∑ⱼ₌₁ᵐ P(aᵢ,ⱼ) log P(aᵢ,ⱼ)
```

Here sᵢ names the sparsity score for source position i. The attention map has n source positions and m target positions. The index j runs over target positions. The entry aᵢ,ⱼ denotes the attention score from source i to target j, and P(aᵢ,ⱼ) denotes the corresponding probability weight. The function log takes its logarithm. The sum combines the weighted logarithms and the factor 1 ÷ m scales the result as specified by the authors. Masked positions are excluded. The authors average the resulting scores across source positions and heads within each layer.

When a row of the attention map spreads weight broadly, it has higher entropy and lower negative entropy. When the weight is concentrated, negative entropy increases. This gives the authors a common measure for comparing layers and training stages. Cross-attention concentration keeps increasing even after 100 training epochs, with an especially clear change in the first cross-attention layer. The authors take the longer-running change as evidence that learning how queries should read the image is a more persistent difficulty than the instability addressed by distillation. The measurement tracks the evolution of attention, while the architecture comparison tests whether a detector can make useful predictions without that readout process.

#### Removing the decoder changes which objects are easiest

The encoder-only DETR comparison retains the Hungarian loss but moves the prediction head from decoder query outputs to encoder feature outputs. It obtains broadly comparable overall AP to the original DETR on validation. The differences become clearer in the size-specific curves. The encoder-only detector learns small-object detection faster and achieves better AP on small objects in this comparison. The paper reports some benefit for medium objects, while large-object AP is worse.

The authors suggest two possible reasons for the large-object result. A large annotated box can encompass many plausible grid locations, and deciding which sliding point should represent the object may be difficult. A single feature map may also provide too narrow a basis for predictions across scales. Both explanations lead towards a multiscale architecture, but the experiment changes several aspects of the prediction path together. Its direct result is that feature-based predictions with encoder self-attention can work under the set objective, and that their size profile differs from the decoder-based one.

The role of small objects is especially informative for the authors’ account. A feature point gives a local source of evidence for a candidate. A decoder query needs a useful attention pattern to gather that evidence from the encoded image. When relevant visual evidence occupies little of the image representation, changing the route through which it reaches the prediction head can make a difference early in training. The stronger small-object curve fits that explanation in the tested architecture.

#### Restricting matching helps both proposed detectors

The convergence study compares each proposed detector using its spatially restricted matching with its counterpart trained using a DETR-like set loss. In both the point and proposal designs, the restricted version improves AP sooner. The direction of the result is consistent across the two eligibility rules. This is a more focused comparison than changing original DETR into a TSP system, because the candidate architecture remains the same within each pair.

Matching distillation and restricted matching probe related issues with different interventions. The distilled experiment supplies a finished assignment from a teacher and shows a brief early benefit for original DETR. Restricted matching limits the available assignments using information from the candidate and the annotation. The learner can still make different admissible choices as it improves. Its consistent benefit shows that a useful geometric constraint can accelerate training within the new candidate-based architectures. The result does not require assignments to remain fixed.

#### Which components matter in the finished detector

The paper’s component ablation evaluates the set prediction loss and positional encoding in TSP-RCNN with both ResNet-50 and ResNet-101. The experiments use the default 36-epoch schedule without random cropping. Both components contribute to validation performance, and the effect reported for set prediction loss is larger. This supports the authors’ decision to use proposals as inputs to a set predictor. The value of the architecture in their experiments depends substantially on how those inputs are jointly supervised. Position encodings make their own contribution by giving the encoder explicit information about which regions its inputs represent.

A separate comparison strengthens the conventional detectors to check whether the gain can be explained by more computation and parameters. The authors give Faster R-CNN a stronger proposal network and a larger fully connected detection head. The resulting baseline uses roughly 200 GFLOPs and has 65.3M parameters. They deepen both heads in FCOS to obtain a baseline of approximately 199 GFLOPs. On COCO 2017 validation with ResNet-50, the stronger baselines improve slightly. The authors report larger gains from their set prediction designs. This comparison tests straightforward increases in conventional detector capacity against the proposed changes within a similar range of computation.

The deformable convolution experiments test another explanation. If the benefits of encoder attention were exhausted by a backbone that could sample more flexibly, adding the proposed detection heads to ResNet-101-DCN would yield little benefit. The paper reports improvements for the TSP designs over their conventional counterparts with that backbone on COCO 2017 validation. That comparison shows that the benefits can coexist. It leaves open which particular interactions within the backbone and encoder account for the combined result.

The candidate-count ablation examines whether the default 700 inputs are essential to the ResNet-50 validation results. The authors report that prediction accuracy remains high when using half the candidates. This suggests that the top-ranked part of the pool already contains much of the useful evidence in the tested setup. The default count is an implementation choice, and the ablation demonstrates some tolerance for reducing it without establishing a generally best count.

#### Refining boxes and inspecting attention

The appendix gives TSP-RCNN an additional stage of box refinement and compares it with Deformable DETR on COCO 2017 validation. Both use a 50-epoch training schedule and batch size 32. The authors reduce the widths of the detection head and encoder feed-forward network in the cascade to keep the number of parameters and FLOPs similar to the original TSP-RCNN. The comparison therefore asks what an extra refinement stage can contribute within approximately the same resource budget for TSP-RCNN.

Without iterative refinement, TSP-RCNN leads the corresponding Deformable DETR under this training setup. The refinement cascade improves TSP-RCNN by 1 AP point on validation. When both detectors refine boxes iteratively, Deformable DETR is slightly ahead. The authors point to the different refinement depths as a possible explanation. Their TSP-RCNN experiment uses two refinement iterations, while Deformable DETR uses 6 decoder refinement iterations. The result establishes that the proposal-based detector can benefit from iterative refinement and that the ranking depends on which variants are compared.

The qualitative study inspects one attention head in TSP-RCNN on six validation images. It uses region proposals as the boxes in the visualization and highlights the top-5 attended boxes for selected proposals. The displayed relationships frequently connect boxes referring to the same instance. That behavior offers a concrete way the encoder could help resolve redundancy: a proposal representation has access to other views of the same object before the final classification decision. The illustration gives examples of the relationship the head learns. The AP and component comparisons establish performance at the level of the whole detector.

### Limitations

#### Limits the authors identify

Large-object detection remains a weakness in important comparisons. Encoder-only DETR is worse than original DETR for large objects in the diagnostic experiment. The multiscale proposal-based approach improves the overall results, but TSP-RCNN+ still trails DETR-DC5+ on large-object AP in the enhanced comparison. The authors suggest that the encoder-decoder architecture has a helpful inductive bias for large objects and that its longer training schedule may contribute. Their results show where the difference persists. Those explanations are hypotheses about its cause.

The authors also leave proposal and refinement choices open. The default candidate count need not be optimal, as indicated by the reduction experiment. The cascade comparison shows a gain from refinement for TSP-RCNN, with the strongest refined Deformable DETR still slightly ahead under the matched training schedule. Efficiently adding more refinement steps to TSP-RCNN is left for future work. The conclusion likewise identifies sparse attention as a direction for modeling relations among multilevel features directly. The proposed systems use selection followed by attention, so their results concern that way of making multiscale attention tractable.

#### Limits of interpretation

The main comparisons establish outcomes on the COCO detection setup. Matching distillation controls the assignments given to the student, but those assignments originate in a trained teacher. Its early benefit can reflect both their stability and the quality of the pairings. It is evidence that replacing the student’s own early matching can help. The experiment does not estimate separately how much improvement comes from making a given assignment deterministic and how much comes from substituting assignments grounded in a stronger predictor.

The attention evidence also has a specific scope. Negative entropy measures how weight is distributed, rather than whether the most strongly attended feature is the best feature for localization. A concentrated head could still attend to an unhelpful part of the image. Conversely, some detections may benefit from gathering evidence across several locations. In the removal experiment, taking away the decoder also changes the source and parameterization of predictions. Together, the analyses support a practical alternative to decoder cross-attention and suggest why it trains more readily. They do not allocate a separate causal contribution to each architectural change.

The schedule comparisons concern optimization on the reported detection task. The results with TSP-RCNN+ combine a longer schedule with random crop augmentation, so that comparison does not isolate the value of additional epochs. The original DETR wall-time figure and the single-GPU inference measurements describe different operations in different settings. Training epochs, inference latency and arithmetic cost each answer a different resource question. The shorter schedules and validation curves establish improved training progress by epoch. The paper’s stated hardware figures cannot be used to infer a general training-time ratio between the systems.

Finally, candidate selection places a dependence on the early stages that is specific to these designs. The promising points and proposals that reach attention are chosen by their scores. Spatial eligibility can simplify supervision whenever the appropriate candidate exists, while a missed location or poor proposal can remove a useful match from consideration. The candidate-count ablation shows resilience to using fewer inputs in the tested setting. It leaves open how the same rule would behave under different image distributions or annotation conventions. The qualitative attention examples likewise show what a particular head can learn, with no estimate of how often that behavior occurs across all heads and images.

### What came after

[Tokens-to-Token ViT](https://md.research.elamur.ai/free/en/papers/yuan-2021-tokens-token-vit-training-vision/) cites the paper and addresses training vision Transformers from scratch on ImageNet. Its stated training problem differs from the one here. Rethinking Transformer-based Set Prediction studies where detection candidates come from, how they interact, and how they receive category and box supervision. Tokens-to-Token ViT places the question of training visual Transformers in the setting of ImageNet. The citation establishes a connection between the two works. It leaves the role of TSP’s candidate selection and matching rules in the later work unspecified.

## Cite

Cite as Zhiqing Sun, Shengcao Cao, Yiming Yang and Kris Kitani. 2021. Rethinking Transformer-based Set Prediction for Object Detection. IEEE/CVF International Conference on Computer Vision (ICCV).

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.1109/iccv48922.2021.00359](https://doi.org/10.1109/iccv48922.2021.00359) · [arXiv 2011.10881](https://arxiv.org/abs/2011.10881)

```bibtex
@inproceedings{sun2021rethinking,
  title = {{Rethinking Transformer-based Set Prediction for Object Detection}},
  author = {Zhiqing Sun, Shengcao Cao, Yiming Yang and Kris Kitani},
  booktitle = {IEEE/CVF International Conference on Computer Vision (ICCV)},
  year = {2021},
  doi = {10.1109/iccv48922.2021.00359},
  eprint = {2011.10881},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1109/iccv48922.2021.00359}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
