Search

Search papers and lessons

Deformable Attention

Level 4 · 13 min read

Deformable attention lets each query look at a few learned sampling points near its reference location, instead of at every position, so dense image features can be read cheaply and in a flexible pattern.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Linear algebra
  • Neural network basics
  • Signal processing
  • Architectures
  • ReadReady to readNot yet

TL;DR

Deformable attention is an attention layer for grids of image features in which each query reads only a few points, and it learns where those points go. For every query it predicts small offsets from a reference location, samples the feature map at the shifted points with Bilinear Interpolation, and averages the samples with learned weights. Because a query touches a handful of points rather than every position, the cost stays small even for large feature maps, and the pattern adapts to each image.

Builds on: Multi-Head Attention, Bilinear Interpolation · Leads to: Deformable DETR, Sparse Attention

Where it's used

Object detection with transformers. DETR (2020) turned Object Detection into predicting the full set of boxes in one pass with a Transformer, and it removed several hand-designed steps that earlier detectors depended on. Its dense attention over every feature position converged slowly, and the original paper trained for hundreds of epochs. Deformable DETR (2020) replaced the dense attention over image features with deformable attention, and the paper reports that it outperforms DETR, especially on small objects, with about ten times fewer training epochs.

Multi-scale feature maps in detectors. Detectors usually compute features at several resolutions, from coarse maps that see large objects to fine maps that see small ones. Deformable attention reads all of these levels with one set of sampling points per query, so a single layer can gather evidence across scales. The Deformable DETR paper uses this in its encoder and decoder.

Dense prediction tasks. Segmentation and pose estimation also need features at many positions and at precise locations. Here the sampling points let each query find the parts of an image that belong to its object, even when the object is not aligned with a fixed grid.

How it works

Take the smallest case: one head, one query, one feature map, and two sampling points. The feature map is a 3 by 3 grid of numbers. Each grid cell has a position (x,y)(x, y), with xx running left to right and yy running top to bottom. The value at position (x,y)(x, y) is

row y, column x012
0123
1456
2789

The query sits at the reference point p=(1,1)p = (1, 1), which is the centre cell with value 5. Between grid points, the map is read with bilinear interpolation.

  1. Predict an offset for each point. The query is turned into two offsets, Δ1=(0.5,0)\Delta_1 = (0.5, 0) and Δ2=(0,−0.5)\Delta_2 = (0, -0.5). These say where the two points go relative to pp. Check: the offsets are small, so both points stay near the reference point.
  2. Place the sampling points. The first point is p+Δ1=(1.5,1)p + \Delta_1 = (1.5, 1) and the second is p+Δ2=(1,0.5)p + \Delta_2 = (1, 0.5). Check: neither point is a grid point, so bilinear interpolation is needed.
  3. Sample each point. The first point lies on the row y=1y = 1 halfway between 5 and 6, so its value is 5.5. The second lies on the column x=1x = 1 halfway between 2 and 5, so its value is 3.5. Check: each sample lies between the two grid values it came from.
  4. Predict the weights. The query also gives one raw score per point (a logit), and a Softmax turns the two scores into weights. Here the scores are equal, so the weights are (0.5,0.5)(0.5, 0.5). Check: the weights add to 1.
  5. Weighted sum. The output is 0.5×5.5+0.5×3.5=4.50.5 \times 5.5 + 0.5 \times 3.5 = 4.5. Check: the output lies between the two samples, as an average must.
  6. Several heads and levels. Each head repeats steps 1 to 5 with its own offsets and weights, and the heads are concatenated and mixed exactly as in Multi-Head Attention. With several feature levels, each head also samples on each level.

The flow of one head is shown below.

flowchart LR
  Q[Query and reference point] --> O[Predict offsets]
  Q --> W[Predict weights, softmax over points]
  O --> S[Sample the feature map at each shifted point]
  S --> A[Weighted sum of samples]
  W --> A
  A --> H[Head output]

The math

Let xx be a feature map with values at grid positions, and let zqz_q be the feature vector of query qq. The reference point pqp_q is a position on the feature map's grid, in the same coordinates as the walkthrough. There are MM heads, indexed by mm, and KK sampling points per head, indexed by kk.

Definition: Deformable attention

For each head mm and point kk, the query predicts an offset Δpmqk\Delta p_{mqk} and a weight logit. The weights are normalised with a Softmax over the KK points, giving AmqkA_{mqk} that sum to 1 for each head. The output is

DeformAttn(zq,pq,x)=∑m=1MWm[∑k=1KAmqk x ⁣(pq+Δpmqk)],\mathrm{DeformAttn}(z_q, p_q, x) = \sum_{m=1}^{M} W_m \left[ \sum_{k=1}^{K} A_{mqk}\, x\!\left(p_q + \Delta p_{mqk}\right) \right],

where x(⋅)x(\cdot) means the feature map read at a real-valued position by Bilinear Interpolation, and WmW_m is a learned matrix that mixes the head output back into the model width.

Read it from the inside out: x(pq+Δpmqk)x(p_q + \Delta p_{mqk}) is the sample in step 3, AmqkA_{mqk} is the weight in step 4, and the sum over kk is step 5. The outer sum over mm and the matrix WmW_m are the Multi-Head Attention combination from step 6.

Steps 1 and 2 in symbols

The offsets and the weight logits are both produced by linear maps of the query, Δpmqk=Linear(zq)\Delta p_{mqk} = \mathrm{Linear}(z_q) and the logits are another linear map of zqz_q. Because they are computed from the query, the sampling pattern changes with the image. A convolution uses the same fixed grid of offsets at every position. Deformable attention keeps the shape of that idea but learns it per query. The idea of sampling at moved positions was used in deformable convolution (Dai and colleagues, 2017), where the offsets are learned per position but the sampled values are then combined with fixed weights.

Step 3 in symbols

The sampling positions pq+Δpmqkp_q + \Delta p_{mqk} are real numbers, so xx at those points is found by bilinear interpolation of the four grid values around them. For the example, pq+Δ1=(1.5,1)p_q + \Delta_1 = (1.5, 1) has tx=0.5t_x = 0.5 and ty=0t_y = 0, which gives 5+0.5×(6−5)=5.55 + 0.5 \times (6 - 5) = 5.5.

Steps 4 and 5 in symbols

The weights AmqkA_{mqk} come from the softmax over the points, so for each head ∑kAmqk=1\sum_{k} A_{mqk} = 1. The inner sum is a weighted average of the samples. For the example, 0.5×5.5+0.5×3.5=4.50.5 \times 5.5 + 0.5 \times 3.5 = 4.5.

Shapes and cost

In dense attention each query compares with all NN positions of the feature map, so one head costs about NN comparisons per query. In deformable attention each query uses KK points per level and LL levels, so one head costs LKL K samples per query, and MLKM L K over all heads. The cost per query no longer grows with the size of the map, which is the reason the method scales to high-resolution features.

Worked examples

Example
1. One head, two points on a 3 by 3 map

Use the grid above with M=1M = 1, K=2K = 2, and the reference point p=(1,1)p = (1, 1). Both points get weight A=(0.5,0.5)A = (0.5, 0.5).

  1. Point 1 is p+Δ1=(1.5,1)p + \Delta_1 = (1.5, 1). On the row y=1y = 1 the values are 5 at x=1x = 1 and 6 at x=2x = 2. Halfway gives 5.55.5.
  2. Point 2 is p+Δ2=(1,0.5)p + \Delta_2 = (1, 0.5). On the column x=1x = 1 the values are 2 at y=0y = 0 and 5 at y=1y = 1. Halfway gives 3.53.5.
  3. Weighted sum: 0.5×5.5+0.5×3.5=2.75+1.75=4.50.5 \times 5.5 + 0.5 \times 3.5 = 2.75 + 1.75 = 4.5.

Interpretation: the output is the average of two nearby samples, one to the right and one above. The query never looked at the other six cells.

Example
2. The standard case: unequal weights and a point inside a cell

Use the top-left 2×22 \times 2 block of the grid: F00=1F_{00} = 1, F10=2F_{10} = 2, F01=4F_{01} = 4, F11=5F_{11} = 5. Let p=(0.5,0.5)p = (0.5, 0.5), with two offsets Δ1=(0.5,0)\Delta_1 = (0.5, 0) and Δ2=(−0.25,−0.25)\Delta_2 = (-0.25, -0.25). Suppose the softmax gives A=(0.75,0.25)A = (0.75, 0.25).

  1. Point 1 is (1.0,0.5)(1.0, 0.5). On the column x=1x = 1 the values are 2 and 5, so the sample is 2+0.5×3=3.52 + 0.5 \times 3 = 3.5.
  2. Point 2 is (0.25,0.25)(0.25, 0.25). Here tx=ty=0.25t_x = t_y = 0.25. Across the top: 1+0.25×1=1.251 + 0.25 \times 1 = 1.25. Across the bottom: 4+0.25×1=4.254 + 0.25 \times 1 = 4.25. Up: 1.25+0.25×3=2.01.25 + 0.25 \times 3 = 2.0.
  3. Check point 2 with the four weights: 0.75⋅0.75⋅1+0.25⋅0.75⋅2+0.75⋅0.25⋅4+0.25⋅0.25⋅5=0.5625+0.375+0.75+0.3125=2.00.75 \cdot 0.75 \cdot 1 + 0.25 \cdot 0.75 \cdot 2 + 0.75 \cdot 0.25 \cdot 4 + 0.25 \cdot 0.25 \cdot 5 = 0.5625 + 0.375 + 0.75 + 0.3125 = 2.0. Both routes agree.
  4. Weighted sum: 0.75×3.5+0.25×2.0=2.625+0.5=3.1250.75 \times 3.5 + 0.25 \times 2.0 = 2.625 + 0.5 = 3.125.

Interpretation: the query trusts the first point more, and the output sits between the two sampled values. Changing the offsets moves the samples, and changing the logits changes the weights, so the same layer can read different patterns on different images.

Example
3. A realistic detector layer: cost against dense attention

Take a single 50×5050 \times 50 feature map, so N=2,500N = 2{,}500 positions. Compare one query in dense attention with one query in deformable attention using the Deformable DETR default setting: M=8M = 8 heads, L=4L = 4 levels and K=4K = 4 points per level.

  1. Dense attention for one head compares the query with all positions: 2,5002{,}500 scores. Over 8 heads that is 8×2,500=20,0008 \times 2{,}500 = 20{,}000 scores.
  2. Deformable attention uses K=4K = 4 points on each of L=4L = 4 levels, so LK=16L K = 16 samples per head.
  3. Over 8 heads: 8×16=1288 \times 16 = 128 samples per query.
  4. The ratio is 20,000/128=156.2520{,}000 / 128 = 156.25. A dense query does about 156 times as many comparisons on this map.

Interpretation: the saving comes from the number of points, not from a smaller map. The sampled values also need bilinear interpolation, which costs a few multiplications each, so the real speed-up depends on the implementation. This is a comparison of counts, not a benchmark.

Try it: a 40×4040 \times 40 map, one level, M=4M = 4 heads and K=4K = 4 points per head. How many points does one query sample in total, and how many scores would dense attention compute over the same heads? Answer: deformable attention samples 4×4=164 \times 4 = 16 points. Dense attention computes 4×1,600=6,4004 \times 1{,}600 = 6{,}400 scores. The ratio is 6,400/16=4006{,}400 / 16 = 400.

Common mistakes and tradeoffs

It is tempting to think that deformable attention looks at the whole image. In fact each query reads only LKL K points per head, and the whole-image view comes from stacking layers and from the offsets moving across the image over several layers.

It is tempting to think that the offsets are a fixed kernel, as in a convolution. In fact they are predicted from the query, so the pattern differs for each query and each image.

It is tempting to think that the sampling positions cannot be learned because they are not differentiable. In fact bilinear interpolation is piecewise linear in the position, so the gradient (the signal that tells each value which way to move) flows back into the offsets, and the network learns where to look. The gradient is only defined within each cell, so the learning signal is local.

When to use it: dense image features where the relevant evidence is local but its location varies, such as detection, segmentation and tracking, and where dense attention is too expensive.

When not to use it: language, where tokens do not sit on a grid and the relevant context may be anywhere in the sequence; and small inputs, where dense attention is cheap and the extra machinery adds nothing. A fixed local pattern such as Sparse Attention with a window is simpler when the relevant positions are known in advance.

SituationProblemBetter choice
Large image feature mapsDense scores grow with the number of positionsDeformable attention with a few learned points
Relevant context is a fixed neighbourhoodLearned offsets add complexityA fixed window or a convolution
Tokens with no grid positionThere is no spatial sample to moveStandard Multi-Head Attention or Sparse Attention
Need to run on hardware with no custom kernelThe sampling is slower without a specialised implementationDense attention on a small map, or a convolution

History

Convolutional networks use a fixed grid of weights at every position, and they were the default for vision for many years. Dai and colleagues introduced deformable convolution in 2017, which learns offsets for the grid so that the kernel can follow object shape. A later version added learned weights for each sample.

The transformer brought dense attention to vision. ViT split images into patches and attended over all of them, and DETR in 2020 used dense attention in an encoder-decoder for detection. DETR removed hand-designed detection steps but converged slowly, and dense attention over high-resolution features was costly. Zhu and colleagues published Deformable DETR in 2020, combining the sampling of deformable convolution with the attention of the transformer, and it became a common way to make detection with transformers faster to train.

Recap

  • Each query predicts a few offsets and weights, samples the feature map at the shifted points, and takes a weighted sum.
  • Sampling at real-valued positions uses Bilinear Interpolation, which gives a smooth and differentiable read.
  • Learned offsets let the pattern change with the query and the image, which is the main difference from a convolution.
  • The cost per query depends on the number of points, not on the size of the map, so high-resolution features are affordable.
  • It is the core of Deformable DETR, and related ideas appear in Sparse Attention.

What to read next: End-to-End Object Detection with Transformers shows the detection setting that motivated the design, and Object Detection explains the task it serves.

Check yourself

QuestionIn deformable attention, what does the query predict, and what two things are then computed from those predictions?Show answer

The query predicts offsets for each sampling point and a logit for each point. The offsets place the points near the reference location, and the bilinear samples are read at those positions. The softmax of the logits gives the weights, and the output is the weighted sum of the samples, combined across heads.

QuestionA query uses one head, two points with weights (0.25,0.75)(0.25, 0.75), and the samples are 8 and 4. What is the output?Show answer

0.25×8+0.75×4=2+3=50.25 \times 8 + 0.75 \times 4 = 2 + 3 = 5. The output is a weighted average of the samples, so it lies between 4 and 8, and the point with the larger weight pulls it closer to its sample.

QuestionWhy does the cost per query in deformable attention not grow with the number of positions in the feature map, while dense attention cost does?Show answer

Dense attention compares the query with every position, so its score count equals the number of positions. Deformable attention samples a fixed number of points per head and level, chosen by the offsets, so its count depends only on the number of heads, levels and points. The map can grow without adding samples per query.

QuestionApplied: a designer replaces a convolution with a fixed 3×33 \times 3 grid by deformable attention, but the new model is slower on a small 8×88 \times 8 feature map. Explain why this is expected, and what would make the choice worthwhile.Show answer

On an 8×88 \times 8 map there are only 64 positions, so dense attention is already cheap, and the learned offsets, the bilinear sampling and the extra weights add overhead. The benefit grows with the map size and with the need for spatially varying patterns. On large feature maps, where dense attention would need thousands of scores per query, the few sampled points become the cheaper option.

Sources