{"notes":[{"id":"object-detection/deformable-detr","category":"object-detection","legacyPath":"object-detection/2010-deformable-detr","legacySlug":"2010-deformable-detr","legacyPaths":[],"title":"Deformable DETR","subtitle":"Deformable Attention Mechanism","author":"Z. Yuan","paperDate":"2020-10-08","publishedOn":"2024-09-20","paperTitle":"Deformable DETR: Deformable Transformers for End-to-End Object Detection","paperUrl":"https://arxiv.org/abs/2010.04159","bibliography":{"title":"Deformable DETR: Deformable Transformers for End-to-End Object Detection","authors":["Xizhou Zhu","Weijie Su","Lewei Lu","Bin Li","Xiaogang Wang","Jifeng Dai"],"url":"https://arxiv.org/abs/2010.04159","pdfUrl":"https://arxiv.org/pdf/2010.04159","codeUrl":null,"preprint":{"id":"2010.04159","submittedOn":"2020-10-08","url":"https://arxiv.org/abs/2010.04159"},"publication":{"venue":"ICLR","year":2021,"kind":"conference","url":"https://arxiv.org/abs/2010.04159"},"citation":"@misc{objectdetectiondeformabledetr2020,\n  title = {{Deformable DETR: Deformable Transformers for End-to-End Object Detection}},\n  author = {Xizhou Zhu and Weijie Su and Lewei Lu and Bin Li and Xiaogang Wang and Jifeng Dai},\n  year = {2020},\n  eprint = {2010.04159},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2010.04159}\n}\n","citationPath":"/content/papers/citations/object-detection/deformable-detr.df721a30472e.bib"},"thumbnail":{"src":"/content/papers/assets/36edfc5595a85c73fcdc9a4bbb9e1ca512e1f100676eb7c37203d71c84905c05.jpg","width":1224,"height":752},"locale":"en","path":"/content/papers/en/object-detection/deformable-detr.68972544ff9b.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"problem-solution","text":"Problem Solution","depth":2},{"id":"deformable-attention","text":"Deformable Attention","depth":3},{"id":"multi-scale-computation","text":"Multi-Scale Computation","depth":3},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"code-breakdown","text":"Code Breakdown","depth":3},{"id":"training-strategy","text":"Training Strategy","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"comparison-with-detr","text":"Comparison with DETR","depth":3},{"id":"ablation-studies","text":"Ablation Studies","depth":3},{"id":"sota-comparison","text":"SOTA Comparison","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"object-detection/detr","relation":"background","topic":"Set prediction and attention-based detection"},{"id":"object-detection/h-detr","relation":"next","topic":"Set prediction and attention-based detection"},{"id":"object-detection/smca-detr","relation":"comparison","topic":"Faster convergence for Transformer detectors"}]},{"id":"object-detection/detr","category":"object-detection","legacyPath":"object-detection/2005-detr","legacySlug":"2005-detr","legacyPaths":[],"title":"DETR","subtitle":"A Cross-Domain Pioneer","author":"Z. Yuan","paperDate":"2020-05-26","publishedOn":"2024-06-04","paperTitle":"End-to-End Object Detection with Transformers","paperUrl":"https://www.ecva.net/papers/eccv_2020/papers_ECCV/html/832_ECCV_2020_paper.php","bibliography":{"title":"End-to-End Object Detection with Transformers","authors":["Nicolas Carion","Francisco Massa","Gabriel Synnaeve","Nicolas Usunier","Alexander Kirillov","Sergey Zagoruyko"],"url":"https://www.ecva.net/papers/eccv_2020/papers_ECCV/html/832_ECCV_2020_paper.php","pdfUrl":"https://www.ecva.net/papers/eccv_2020/papers_ECCV/papers/123460205.pdf","codeUrl":"https://github.com/facebookresearch/detr","preprint":{"id":"2005.12872","submittedOn":"2020-05-26","url":"https://arxiv.org/abs/2005.12872"},"publication":{"venue":"ECCV","year":2020,"kind":"conference","url":"https://www.ecva.net/papers/eccv_2020/papers_ECCV/html/832_ECCV_2020_paper.php"},"citation":"@misc{objectdetectiondetr2020,\n  title = {{End-to-End Object Detection with Transformers}},\n  author = {Nicolas Carion and Francisco Massa and Gabriel Synnaeve and Nicolas Usunier and Alexander Kirillov and Sergey Zagoruyko},\n  year = {2020},\n  eprint = {2005.12872},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2005.12872}\n}\n","citationPath":"/content/papers/citations/object-detection/detr.5258ffe0b9a0.bib"},"thumbnail":{"src":"/content/papers/assets/dd7e8441e6460ff562cf558374789924518fafaed7ecde0e3e35ee778c316330.jpg","width":1024,"height":266},"locale":"en","path":"/content/papers/en/object-detection/detr.493e749cd884.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solution","text":"Solution","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"loss-design","text":"Loss Design","depth":3},{"id":"dataset","text":"Dataset","depth":3},{"id":"technical-details","text":"Technical Details","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"how-does-it-perform-this-time","text":"How does it perform this time?","depth":3},{"id":"component-analysis-of-the-model","text":"Component Analysis of the Model","depth":3},{"id":"model-behavior-analysis","text":"Model Behavior Analysis","depth":3},{"id":"generalization-to-unseen-object-counts","text":"Generalization to Unseen Object Counts","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{"defining-the-problem":"problem-definition","solving-the-problem":"solution","from-an-image-to-a-set-of-objects":"model-architecture","match-first-then-compute-the-loss":"loss-design","experimental-results-and-discussion":"discussion","how-did-it-do-start-with-the-conditions":"how-does-it-perform-this-time","which-components-matter":"component-analysis-of-the-model","what-did-the-queries-learn":"model-behavior-analysis"},"guide":null,"relatedReading":[{"id":"object-detection/deformable-detr","relation":"next","topic":"Set prediction and attention-based detection"},{"id":"object-detection/smca-detr","relation":"comparison","topic":"Faster convergence for Transformer detectors"}]},{"id":"object-detection/h-detr","category":"object-detection","legacyPath":"object-detection/2207-h-detr","legacySlug":"2207-h-detr","legacyPaths":[],"title":"H-DETR","subtitle":"The Rebellion of Silent Queries","author":"Z. Yuan","paperDate":"2022-07-26","publishedOn":"2025-07-06","paperTitle":"DETRs with Hybrid Matching","paperUrl":"https://arxiv.org/abs/2207.13080","bibliography":{"title":"DETRs with Hybrid Matching","authors":["Ding Jia","Yuhui Yuan","Haodi He","Xiaopei Wu","Haojun Yu","Weihong Lin","Lei Sun","Chao Zhang","Han Hu"],"url":"https://arxiv.org/abs/2207.13080","pdfUrl":"https://openaccess.thecvf.com/content/CVPR2023/papers/Jia_DETRs_With_Hybrid_Matching_CVPR_2023_paper.pdf","codeUrl":"https://github.com/HDETR/H-Deformable-DETR","preprint":{"id":"2207.13080","submittedOn":"2022-07-26","url":"https://arxiv.org/abs/2207.13080"},"publication":{"venue":"CVPR","year":2023,"kind":"conference","url":"https://openaccess.thecvf.com/content/CVPR2023/html/Jia_DETRs_With_Hybrid_Matching_CVPR_2023_paper.html"},"citation":"@misc{objectdetectionhdetr2022,\n  title = {{DETRs with Hybrid Matching}},\n  author = {Ding Jia and Yuhui Yuan and Haodi He and Xiaopei Wu and Haojun Yu and Weihong Lin and Lei Sun and Chao Zhang and Han Hu},\n  year = {2022},\n  eprint = {2207.13080},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2207.13080}\n}\n","citationPath":"/content/papers/citations/object-detection/h-detr.822184101757.bib"},"thumbnail":{"src":"/content/papers/assets/63f1bc60b92f58d360457c0e3bbef0a3d4b3bd2a07377983b2dc5f5591ce28c2.jpg","width":1784,"height":350},"locale":"en","path":"/content/papers/en/object-detection/h-detr.005f94461932.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solution","text":"Solution","depth":2},{"id":"main-branch-one-to-one-supervision","text":"Main Branch: One-to-One Supervision","depth":3},{"id":"auxiliary-branch-one-to-many-supervision","text":"Auxiliary Branch: One-to-Many Supervision","depth":3},{"id":"total-loss-and-implementation-details","text":"Total Loss and Implementation Details","depth":3},{"id":"more-forms-of-hybrid-supervision","text":"More Forms of Hybrid Supervision","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"coco-benchmark","text":"COCO Benchmark","depth":3},{"id":"lvis-benchmark","text":"LVIS Benchmark","depth":3},{"id":"sota-benchmark","text":"SOTA Benchmark","depth":3},{"id":"ablation-study","text":"Ablation Study","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{"auxiliary-branch-more-positive-slots":"auxiliary-branch-one-to-many-supervision","change-when-supervision-happens":"more-forms-of-hybrid-supervision","experimental-results-and-discussion":"discussion","coco-what-happens-when-more-queries-learn":"coco-benchmark","lvis-how-far-does-the-long-tail-evidence-go":"lvis-benchmark","system-comparison-the-conditions-behind-594-ap":"sota-benchmark","ap-training-time-and-inference-cost-across-the-three-schemes":"ablation-study"},"guide":null,"relatedReading":[{"id":"object-detection/deformable-detr","relation":"background","topic":"Set prediction and attention-based detection"}]},{"id":"object-detection/smca-detr","category":"object-detection","legacyPath":"object-detection/2101-smca-detr","legacySlug":"2101-smca-detr","legacyPaths":[],"title":"SMCA DETR","subtitle":"Add Some Gaussian!","author":"Z. Yuan","paperDate":"2021-01-19","publishedOn":"2024-09-21","paperTitle":"Fast Convergence of DETR with Spatially Modulated Co-Attention","paperUrl":"https://arxiv.org/abs/2101.07448","bibliography":{"title":"Fast Convergence of DETR with Spatially Modulated Co-Attention","authors":["Peng Gao","Minghang Zheng","Xiaogang Wang","Jifeng Dai","Hongsheng Li"],"url":"https://arxiv.org/abs/2101.07448","pdfUrl":"https://openaccess.thecvf.com/content/ICCV2021/papers/Gao_Fast_Convergence_of_DETR_With_Spatially_Modulated_Co-Attention_ICCV_2021_paper.pdf","codeUrl":"https://github.com/gaopengcuhk/SMCA-DETR","preprint":{"id":"2101.07448","submittedOn":"2021-01-19","url":"https://arxiv.org/abs/2101.07448"},"publication":{"venue":"ICCV","year":2021,"kind":"conference","url":"https://openaccess.thecvf.com/content/ICCV2021/html/Gao_Fast_Convergence_of_DETR_With_Spatially_Modulated_Co-Attention_ICCV_2021_paper.html"},"citation":"@misc{objectdetectionsmcadetr2021,\n  title = {{Fast Convergence of DETR with Spatially Modulated Co-Attention}},\n  author = {Peng Gao and Minghang Zheng and Xiaogang Wang and Jifeng Dai and Hongsheng Li},\n  year = {2021},\n  eprint = {2101.07448},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2101.07448}\n}\n","citationPath":"/content/papers/citations/object-detection/smca-detr.bd7ba32cd46b.bib"},"thumbnail":{"src":"/content/papers/assets/203dc068f589d0931e83b6156954b5b803b20c0d178d5b7c557b1dc6f8a8aa13.jpg","width":1210,"height":740},"locale":"en","path":"/content/papers/en/object-detection/smca-detr.63eebc2bb37d.md","headings":[{"id":"add-some-gaussian","text":"Add Some Gaussian!","depth":2},{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"spatially-modulated-co-attention","text":"Spatially Modulated Co-Attention","depth":3},{"id":"initial-predictions","text":"Initial Predictions","depth":3},{"id":"gaussian-weight-map","text":"Gaussian Weight Map","depth":3},{"id":"multi-head-smca","text":"Multi-Head SMCA","depth":3},{"id":"training-strategy","text":"Training Strategy","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"comparison-with-detr","text":"Comparison with DETR","depth":3},{"id":"ablation-studies","text":"Ablation Studies","depth":3},{"id":"head-shared-smca","text":"Head-shared SMCA","depth":3},{"id":"multi-head-smca-1","text":"Multi-head SMCA","depth":3},{"id":"comparison-with-other-sota-architectures","text":"Comparison with Other SOTA Architectures","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{"problem-definition":"defining-the-problem","solution":"solving-the-problem","guess-a-location-then-inspect-image-content":"spatially-modulated-co-attention","bring-three-scales-into-the-encoder":"multi-head-smca","read-the-training-settings-too":"training-strategy","experimental-results-and-discussion":"discussion","convergence-accuracy-and-per-image-cost":"comparison-with-detr","what-do-the-gaussian-map-heads-and-scales-contribute":"ablation-studies","read-the-full-model-comparison":"comparison-with-other-sota-architectures"},"guide":null,"relatedReading":[{"id":"object-detection/detr","relation":"comparison","topic":"Faster convergence for Transformer detectors"},{"id":"object-detection/deformable-detr","relation":"comparison","topic":"Faster convergence for Transformer detectors"}]}],"text":"DETR leaves a lot of room for researchers to innovate.\n\nIt uses only the most basic Transformer architecture to perform the simplest object detection. There are no score-boosting tricks inside; it simply takes the image as input and outputs the object locations and classes.\n\nWhat a beautiful paper!\n\nSubsequent researchers can improve the model based on this idea, and papers will keep coming out rapidly.\n\n## Problem Definition\n\nCompared with other detectors, DETR feels painfully slow to train. What about inference? That depends on the variant: the paper's ordinary DETR runs at 28 FPS against Faster R-CNN + FPN's 26 FPS, while the high-resolution DETR-DC5 runs at 12 FPS.\n\nSo is inference really the problem? Not here. The troubling part is **convergence**: DETR takes 500 epochs in the paper's COCO comparison, versus 109 for Faster R-CNN + FPN and 50 for Deformable DETR. The often-quoted “10–20 times” refers to training schedules in epochs, not a guaranteed multiplication of elapsed days; Table 1 reports 2,000 versus 380 GPU hours for DETR and Faster R-CNN + FPN.\n\nTime flies; youth fades. We cannot wait until our hair turns white for a model to converge. This has to change.\n\n## Problem Solution\n\nThe authors believe the problem lies in the Transformer’s attention mechanism.\n\nIn DETR’s encoder, global attention links every feature-map position to all other positions. Its attention cost grows quadratically with their count, making high-resolution features expensive; training must also learn to focus from initially diffuse weights.\n\nSo the original Transformer attention over dense image features is too costly here. Inspired by “deformable convolution,” the authors modify it into a “deformable attention mechanism.”\n\n\n> [!TIP]\n> \n> “Pixels” here are positions on CNN feature maps, not individual pixels of the raw image. This differs from directly embedding image patches as in ViT.\n\n\n### Deformable Attention\n\n\n\n![deformable attention](/content/papers/assets/afd16d6c3cafc26ce43e498bd396a22b1965610ad3fbe96ae88e3668e9f8bdd3.jpg)\n\n\n\nIn the image feature map, given each query element, the authors use a reference point as a base, predict a few sampling offsets and weights from the query feature, then aggregate the sampled features. The offsets need not stay within a fixed local window.\n\nAssuming the input feature map is:\n\n$$\nx\n\\in \\mathbb{R}^{C \\times H \\times W}\n$$\n\nwhere $C$ is the number of channels, and $H$, $W$ are the height and width of the feature map, respectively.\n\nThe query element $q$ contains a content feature $z_q$ and a 2D reference point $p_q$. The deformable attention feature is computed as follows:\n\n$$\n\\text{DeformAttn}(z_q, p_q, x) = \\sum_{m=1}^{M} W_m \\sum_{k=1}^{K} A_{mqk} \\cdot W_m^{\\prime} x(p_q + \\Delta p_{mqk})\n$$\n\nwhere:\n\n- $M$ is the number of attention heads.\n- $K$ is the number of samples per query and per attention head. Learned offsets from the reference point determine their positions; they are not confined to a fixed small window.\n- $A_{mqk}$ is the attention weight for the $k$-th sampling point of the $m$-th attention head, ranging in $[0, 1]$. For fixed $m,q$, these $K$ weights sum to 1.\n- $\\Delta p_{mqk}$ is the offset of the $k$-th sampling point of the $m$-th head; these offsets can be arbitrary real numbers.\n- $W_m$ and $W_m^{\\prime}$ are learnable weight matrices responsible for linear transformations of the input features.\n- $x(p_q + \\Delta p_{mqk})$ denotes the feature value at location $p_q + \\Delta p_{mqk}$. Since this position is fractional (non-integer), bilinear interpolation is used to compute it.\n\nThe query feature $z_q$ undergoes a linear projection outputting a tensor with $3MK$ channels:\n\n- The first $2MK$ channels encode the offsets $\\Delta p_{mqk}$ of each sampling point.\n- The remaining $MK$ channels pass through a softmax to produce the attention weights $A_{mqk}$.\n\nThis design ensures that both the offsets and attention weights are learned from the query element’s features rather than being fixed by a predetermined rule.\n\n### Multi-Scale Computation\n\nModern object detection frameworks usually use multi-scale feature maps for detection.\n\nThe deformable attention module naturally supports a multi-scale version, allowing sampling and operations on multiple feature map layers simultaneously.\n\nAssuming the multi-scale feature maps as $\\{x_l\\}_{l=1}^L$, where each feature map $x_l \\in \\mathbb{R}^{C \\times H_l \\times W_l}$.\n\nThe query element’s reference point is represented by normalized coordinates $\\hat{p}_q \\in [0, 1]^2$. The multi-scale computation formula is:\n\n$$\n\\text{MSDeformAttn}(z_q, \\hat{p}_q, \\{x_l\\}_{l=1}^L) =\n$$\n\n$$\n\\sum_{m=1}^{M} W_m \\sum_{l=1}^{L} \\sum_{k=1}^{K} A_{mlqk} \\cdot W_m^{\\prime} x_l(\\phi_l(\\hat{p}_q) + \\Delta p_{mlqk})\n$$\n\n- $L$ is the number of input feature map levels.\n- $\\phi_l(\\hat{p}_q)$ is a scaling function that converts normalized coordinates to actual coordinates on the $l$-th feature map layer.\n- Each query samples $K$ points per head per level. Within a head, softmax normalizes jointly over all $L K$ samples, so their weights sum to 1.\n\n### Model Architecture\n\n\n\n![model](/content/papers/assets/36edfc5595a85c73fcdc9a4bbb9e1ca512e1f100676eb7c37203d71c84905c05.jpg)\n\n\n\nThe replacement affects encoder self-attention over image features and decoder cross-attention reading those features. Decoder self-attention among object queries remains standard; not every Transformer module is replaced. The encoder receives ResNet C3–C5 features plus a downsampled C6 from C5, without FPN's top-down fusion.\n\n\n> [!NOTE]\n> \n> If theoretical knowledge is not your focus, you can also directly access their official implementation on Github:\n> \n> - [**fundamentalvision/Deformable-DETR**](https://github.com/fundamentalvision/Deformable-DETR)\n\n\n### Code Breakdown\n\nLet's take a closer look at the authors' MSDeformAttn implementation. What differs from ordinary attention? This excerpt is for reading: imports, helpers and the custom CUDA operator are omitted, so it is not a standalone script. See the official repository above for the complete environment.\n\n```python\nclass MSDeformAttn(nn.Module):\n\n    def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4):\n        \"\"\"\n        Multi-Scale Deformable Attention Module\n        :param d_model      hidden dimension\n        :param n_levels     number of feature levels\n        :param n_heads      number of attention heads\n        :param n_points     number of sampling points per attention head per feature level\n        \"\"\"\n        super().__init__()\n        if d_model % n_heads != 0:\n            raise ValueError('d_model must be divisible by n_heads, but got {} and {}'.format(d_model, n_heads))\n        _d_per_head = d_model // n_heads\n        # you'd better set _d_per_head to a power of 2 which is more efficient in our CUDA implementation\n        if not _is_power_of_2(_d_per_head):\n            warnings.warn(\"You'd better set d_model in MSDeformAttn to make the dimension of each attention head a power of 2 \"\n                          \"which is more efficient in our CUDA implementation.\")\n\n        self.im2col_step = 64\n\n        self.d_model = d_model\n        self.n_levels = n_levels\n        self.n_heads = n_heads\n        self.n_points = n_points\n\n        self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)\n        self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points)\n        self.value_proj = nn.Linear(d_model, d_model)\n        self.output_proj = nn.Linear(d_model, d_model)\n\n        self._reset_parameters()\n\n    def _reset_parameters(self):\n        constant_(self.sampling_offsets.weight.data, 0.)\n        thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads)\n        grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)\n        grid_init = (grid_init / grid_init.abs().max(-1, keepdim=True)[0]).view(self.n_heads, 1, 1, 2).repeat(1, self.n_levels, self.n_points, 1)\n        for i in range(self.n_points):\n            grid_init[:, :, i, :] *= i + 1\n        with torch.no_grad():\n            self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))\n        constant_(self.attention_weights.weight.data, 0.)\n        constant_(self.attention_weights.bias.data, 0.)\n        xavier_uniform_(self.value_proj.weight.data)\n        constant_(self.value_proj.bias.data, 0.)\n        xavier_uniform_(self.output_proj.weight.data)\n        constant_(self.output_proj.bias.data, 0.)\n\n    def forward(self, query, reference_points, input_flatten, input_spatial_shapes, input_level_start_index, input_padding_mask=None):\n        \"\"\"\n        :param query                       (N, Length_{query}, C)\n        :param reference_points            (N, Length_{query}, n_levels, 2), range in [0, 1], top-left (0,0), bottom-right (1, 1), including padding area\n                                        or (N, Length_{query}, n_levels, 4), add additional (w, h) to form reference boxes\n        :param input_flatten               (N, \\sum_{l=0}^{L-1} H_l \\cdot W_l, C)\n        :param input_spatial_shapes        (n_levels, 2), [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]\n        :param input_level_start_index     (n_levels, ), [0, H_0*W_0, H_0*W_0+H_1*W_1, H_0*W_0+H_1*W_1+H_2*W_2, ..., H_0*W_0+H_1*W_1+...+H_{L-1}*W_{L-1}]\n        :param input_padding_mask          (N, \\sum_{l=0}^{L-1} H_l \\cdot W_l), True for padding elements, False for non-padding elements\n\n        :return output                     (N, Length_{query}, C)\n        \"\"\"\n        N, Len_q, _ = query.shape\n        N, Len_in, _ = input_flatten.shape\n        assert (input_spatial_shapes[:, 0] * input_spatial_shapes[:, 1]).sum() == Len_in\n\n        value = self.value_proj(input_flatten)\n        if input_padding_mask is not None:\n            value = value.masked_fill(input_padding_mask[..., None], float(0))\n        value = value.view(N, Len_in, self.n_heads, self.d_model // self.n_heads)\n        sampling_offsets = self.sampling_offsets(query).view(N, Len_q, self.n_heads, self.n_levels, self.n_points, 2)\n        attention_weights = self.attention_weights(query).view(N, Len_q, self.n_heads, self.n_levels * self.n_points)\n        attention_weights = F.softmax(attention_weights, -1).view(N, Len_q, self.n_heads, self.n_levels, self.n_points)\n        # N, Len_q, n_heads, n_levels, n_points, 2\n        if reference_points.shape[-1] == 2:\n            offset_normalizer = torch.stack([input_spatial_shapes[..., 1], input_spatial_shapes[..., 0]], -1)\n            sampling_locations = reference_points[:, :, None, :, None, :] \\\n                                 + sampling_offsets / offset_normalizer[None, None, None, :, None, :]\n        elif reference_points.shape[-1] == 4:\n            sampling_locations = reference_points[:, :, None, :, None, :2] \\\n                                 + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5\n        else:\n            raise ValueError(\n                'Last dim of reference_points must be 2 or 4, but get {} instead.'.format(reference_points.shape[-1]))\n        output = MSDeformAttnFunction.apply(\n            value, input_spatial_shapes, input_level_start_index, sampling_locations, attention_weights, self.im2col_step)\n        output = self.output_proj(output)\n        return output\n```\n\nThis interface flattens and concatenates projected ResNet C3–C6 features into `input_flatten`, using `input_spatial_shapes` and `input_level_start_index` to identify levels. These are not FPN-fused outputs. Standard attention can also receive multi-scale tokens, but its cost differs from sparse sampling.\n\n- **Each Query Learns Its Own Offsets**\n\n  ```python\n  self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)\n  ```\n\n  This means for each query, the model outputs multiple offsets (dx, dy), representing directions and distances offset from the reference point — essentially \"where to look.\" These sampling offsets are learned rather than fixed predefined grids.\n\n  ***\n\n- **Reference Points Determine the “Base Location”**\n\n  ```python\n  if reference_points.shape[-1] == 2:\n      ...\n  elif reference_points.shape[-1] == 4:\n      ...\n  ```\n\n  Attention no longer compares each query with every feature-map position. It samples at learned offsets from the `reference_points`, without a fixed window. Encoder reference points correspond to feature-map positions; decoder reference points are predicted from object queries.\n\n  ***\n\nThat's roughly it. One more essential difference: the sampling positions and weights both come from the query, without computing every query-key dot product. The softmax spans all levels and sampling points within each head; decoder query self-attention still uses the standard form.\n\n### Training Strategy\n\nThe authors conducted experiments on the **COCO 2017** dataset.\n\nThe backbone is **ResNet-50**, pretrained on **ImageNet**. Its C3–C5 features and a downsampled C6 feed the encoder without FPN's top-down fusion.\n\nDeformable Attention settings:\n\n- Number of attention heads: **M = 8**\n- Samples per query, per head and per feature level: **K = 4**\n\nParameters in the deformable transformer encoder are shared across different feature levels.\n\nHyperparameters and training strategy mostly follow DETR’s setup, with these exceptions:\n\n- Bounding box classification uses Focal Loss with a loss weight of 2.\n- Number of object queries increased from 100 to 300.\n\nThe model is trained for 50 epochs by default; at epoch 40, the learning rate is reduced to 0.1 times the original. The official implementation defaults to AdamW with a base learning rate of $2 \\times 10^{-4}$, $\\beta_1 = 0.9$, $\\beta_2 = 0.999$, and weight decay of $10^{-4}$.\n\nThe linear projections predicting object query reference points and sampling offsets have their learning rates scaled by an additional factor of 0.1.\n\n## Discussion\n\n### Comparison with DETR\n\n\n\n![table1](/content/papers/assets/feaf8114181a3f1d27dffefb49b933a7122bc0d0658e677d6fa5fe3e409f085a.jpg)\n\n\n\nTable 1 makes the comparison concrete. Faster R-CNN + FPN reaches **42.0 AP and 26.6 AP_S** after **109 epochs / 380 GPU hours**. DETR reaches the same **42.0 AP** only after **500 epochs / 2,000 GPU hours**, with **20.5 AP_S**. Deformable DETR reaches **43.8 AP and 26.4 AP_S** after **50 epochs / 325 GPU hours**. The “10 times fewer” comparison is about epochs versus DETR, not GPU hours.\n\nDetailed convergence curves are shown below:\n\n\n\n![convergence](/content/papers/assets/44941305e93a2230c58aea591583189a58e0df43d7ee9a5a3a3591cbc1f424c2.jpg)\n\n\n\nAt the same 50-epoch schedule in Table 1, iterative bounding box refinement raises AP from **43.8 to 45.4**; adding the two-stage mechanism raises it to **46.2**. The different curves above also vary the learning-rate drop epoch, so they are not all the same 50-epoch run.\n\nOn the paper's **Tesla V100**, Deformable DETR uses **173G FLOPs and runs at 19 FPS**, compared with Faster R-CNN + FPN's **180G / 26 FPS** and DETR-DC5's **187G / 12 FPS**. Its throughput is about **1.6 times** DETR-DC5's and about **27% below** Faster R-CNN + FPN's under those conditions.\n\nThe slower speed of DETR-DC5 mainly stems from extensive memory access in the Transformer attention mechanism. Deformable Attention mitigates this issue at the cost of irregular memory access, still slightly slower than traditional convolutions.\n\n### Ablation Studies\n\n\n\n![table2](/content/papers/assets/c266c951f4c3ff4d426be7133fd7e68bb63ad205767d02d4899ac447dff11c15.jpg)\n\n\n\nThe table shows ablation studies of different design choices within the deformable attention module.\n\nWithout cross-scale attention and at $K=1$, adding multi-scale input raises AP **39.7→41.4** and $AP_S$ **21.2→24.1**, gains of **1.7 and 2.9 percentage points**. Raising $K$ from 1 to 4 then raises AP **41.4→42.3**, another **0.9 point**.\n\nWith multi-scale input and $K=4$, adding cross-scale attention raises AP **42.3→43.8**, a **1.5-point** gain. Adding FPN to that configuration leaves AP at **43.8**; BiFPN reaches **43.9**, a small gain. With no cross-scale attention and $K=1$, the module approaches deformable convolution's single-sample form and reports **41.4 AP**, below the complete multi-scale attention's **43.8**.\n\n### SOTA Comparison\n\n\n\n![table3](/content/papers/assets/5ca60e40907572afd7904b78a8570b21437fc12906d6f1967135019ce6b91db8.jpg)\n\n\n\nIn the table above, Deformable DETR uses iterative bounding box refinement and a two-stage mechanism.\n\nWith iterative refinement and two-stage detection already included, the ResNet-101 and ResNeXt-101 rows reach **48.7 and 49.0 AP** without TTA. ResNeXt-101 with DCN reaches **50.1 AP**. These backbone differences are not an isolated attention-module effect.\n\nWith test-time augmentations (TTA), the **ResNeXt-101 + DCN** configuration reaches **52.3 AP**.\n\n\n> [!NOTE]\n> \n> Here TTA uses test-time horizontal flips and multiple image scales, then merges their predictions. The **52.3 AP** row has TTA as well as the DCN backbone, so it is a different evaluation setting from the rows above.\n\n\n## Conclusion\n\nCompared to the original DETR, Deformable DETR significantly shortens required training time. It shows more evident advantages in small object detection.\n\nAlthough deformable attention speeds up computation, its irregular memory access still leaves throughput slightly below Faster R-CNN + FPN in the paper’s comparison. Thus, speed remains a consideration for real-time applications.\n\nDeformable DETR’s design opens new directions for exploring more efficient and practical end-to-end object detector variants, with broad research and application potential.\n","imageSizes":{"/content/papers/assets/afd16d6c3cafc26ce43e498bd396a22b1965610ad3fbe96ae88e3668e9f8bdd3.jpg":{"width":1194,"height":670},"/content/papers/assets/36edfc5595a85c73fcdc9a4bbb9e1ca512e1f100676eb7c37203d71c84905c05.jpg":{"width":1224,"height":752},"/content/papers/assets/feaf8114181a3f1d27dffefb49b933a7122bc0d0658e677d6fa5fe3e409f085a.jpg":{"width":1224,"height":360},"/content/papers/assets/44941305e93a2230c58aea591583189a58e0df43d7ee9a5a3a3591cbc1f424c2.jpg":{"width":1148,"height":596},"/content/papers/assets/c266c951f4c3ff4d426be7133fd7e68bb63ad205767d02d4899ac447dff11c15.jpg":{"width":1224,"height":332},"/content/papers/assets/5ca60e40907572afd7904b78a8570b21437fc12906d6f1967135019ce6b91db8.jpg":{"width":1224,"height":428}}}
