---
title: "Differentiable Patch Selection for Image Recognition (2021)"
description: "Differentiable patch selection learns where to look in large images, keeping fine detail in a few regions and combining evidence across them."
canonical: "https://research.elamur.ai/free/en/papers/cordonnier-2021-differentiable-patch-selection-image-recognition/"
---
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/cordonnier-2021-differentiable-patch-selection-image-recognition/)

[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/) / Differentiable Patch Selection for Image Recognition

# Differentiable Patch Selection for Image Recognition

Paper · 2021 · Jean-Baptiste Cordonnier, Aravindh Mahendran, Alexey Dosovitskiy et al.

**Authors:** Jean-Baptiste Cordonnier, [Aravindh Mahendran](https://md.research.elamur.ai/free/en/authors/aravindh-mahendran/), [Alexey Dosovitskiy](https://md.research.elamur.ai/free/en/authors/alexey-dosovitskiy/), [Dirk Weissenborn](https://md.research.elamur.ai/free/en/authors/dirk-weissenborn/), [Jakob Uszkoreit](https://md.research.elamur.ai/free/en/authors/jakob-uszkoreit/) and [Thomas Unterthiner](https://md.research.elamur.ai/free/en/authors/thomas-unterthiner/) · **Year:** 2021 · **Venue:** IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings · **Licence:** [arXiv — non-exclusive license to distribute](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

[**102** citations OpenAlex, 2026-10-14](https://openalex.org/works?filter=cites:W3146838169) · Cited by **8** papers in our library of more than 163,000 papers whose bibliographies we read · [IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings](https://openalex.org/S4210176548) · [licence](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

- [PDF](https://arxiv.org/pdf/2104.03059)
- [DOI 10.1109/cvpr46437.2021.00238](https://doi.org/10.1109/cvpr46437.2021.00238)
- [arXiv 2104.03059](https://arxiv.org/abs/2104.03059)
- [OpenAlex](https://openalex.org/W3146838169)

Citations: OpenAlex, 2026-10-14.

## Summary

A small part of a large image can determine its label. A distant speed-limit sign may occupy little of a street scene, yet its digits are precisely the details that disappear when the entire image is shrunk. Processing the original at full resolution preserves those details at a higher computational cost. *Differentiable Patch Selection for Image Recognition* asks whether a system can use a cheap first look to decide which parts deserve a closer one, then learn to make that decision from the same class labels it uses for recognition.

The authors divide the work between a lightweight scorer and a more expensive feature extractor. The scorer ranks candidate locations, frequently using a reduced copy of the image. The feature extractor receives a small set of patches from the higher-resolution input. Choosing the highest-scoring patches is a discrete operation, so the authors add Gaussian noise to the scores during training and repeat the choice. Averaging the resulting selections gives a smooth rule through which the classification error can update the scorer. At inference, the system can dispense with the noise and simply crop the highest-scoring patches.

On the Swedish traffic-sign task, the method matched the mean accuracy reported for Attention Sampling, with greater variation across runs. A small convolutional network that processed the full image fit the training examples perfectly but performed at the majority-class level on the test set. In a separate throughput benchmark on a single V100 GPU, using a ResNet50 on selected regions rather than the whole megapixel image gave a 5 fold speedup in the configuration described by the authors. That comparison concerns the cost of processing a small fraction of an image. The traffic-sign experiment separately tests whether the selected detail is enough for recognition.

The billiard-ball experiment shows why the system leaves the combination of patches open. The task is to compare the numbers on the leftmost and rightmost balls. Averaging patch representations performed poorly, whereas the strongest variant used a [Transformer](https://md.research.elamur.ai/free/en/concepts/transformer/) to combine evidence across patches. On fine-grained bird classification, the authors replaced the separate ranking loss of NTS-Net with gradients passed through patch selection. Their variant performed slightly worse than NTS-Net and frequently selected overlapping crops. Together, the experiments show where learned selection can save work, where the way of combining patches matters, and why learning to select a few useful regions remains difficult even when the selection rule is differentiable.

## Deep dive: Differentiable Patch Selection for Image Recognition

Differentiable patch selection learns where to look in large images, keeping fine detail in a few regions and combining evidence across them. · about 36 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

#### The difference between finding something and recognizing it

An image can be large in two distinct senses. It can contain many pixels, and it can contain a wide field of view with many things in it. The paper is interested in cases where the first kind of size makes recognition costly while the second offers opportunities to save work. The photographer may have captured a whole street, but distinguishing among speed-limit labels depends on what is written on a small sign. A rough view may be enough to locate a plausible sign and too coarse to read it. The detail needed to answer the question can therefore be examined at a different resolution from the evidence needed to decide where to look.

A full-resolution convolutional network makes its expensive feature calculations throughout the image. A smaller input cuts that cost by throwing away spatial detail everywhere. Both are reasonable approaches when information is distributed widely or survives downsampling. The authors focus on the setting in which only a small fraction of the available locations is useful, the useful locations vary with the image, and fine detail matters once a location has been found. A predetermined center crop would solve the selection problem in a setting where the evidence was reliably centered. It offers little assurance that a distant sign elsewhere in the scene will be included.

Patch selection introduces a budget. A system can define a grid of possible crops, score each crop, and pass only the most promising crops to a second stage. The number of places that get an expensive inspection stays small even when the number of candidates is large. The budget also introduces a failure mode. If an important location falls below the cutoff, the recognizer loses access to it through that route. Learning what to retain is consequently part of the task. The image label identifies the desired answer but does not indicate which crop contains the evidence or how several crops should be used together.

The paper treats this as a classification problem with weak supervision. In these experiments, weak supervision means training from image-level class labels without needing boxes that identify the object or its parts. A useful crop can be smaller than the object, and some tasks require evidence from several places. The authors therefore frame the goal around recovering evidence for a label within a small budget. They set aside tasks such as object detection and semantic segmentation, where finding all relevant objects or assigning labels across the image places different demands on coverage.

#### How earlier attention methods allocate work

Region proposal methods already separate the choice of promising locations from their deeper processing. In the two-stage detectors discussed by the paper, either a learned proposal network or a hand-designed procedure supplies candidate regions to a later stage. RoI Pooling and RoI Align are ways of obtaining features for those regions. The latter is differentiable, but extracting features from a proposed region and learning which regions to propose are distinct problems. The examples of large-scale detection in the paper use box supervision and are designed to retain many candidates so that objects are seldom missed. Those design choices fit detection. An image classifier trained from labels alone can afford a smaller crop budget if enough evidence survives to determine the label.

Soft attention supplies continuous weights over locations or features. These weights can help the recognizer give more influence to relevant material, or help a reader see spatial emphasis. The paper observes that an attention mask frequently comes with computation over the whole image at the chosen resolution. Applying a small weight to a region after its expensive features have already been calculated does not recover the work spent calculating them. The authors also describe approaches that process several resolutions and use attention to choose among features, as well as work that trains region selection with a separate loss. Those choices can change what detail is available and what signals train selection.

In multiple-instance learning, the system receives a group of inputs and predicts a label for the group. The paper points to medical images and collections of scan slices as settings where such groups arise naturally. Attention can indicate which members carry more evidence. In the example the authors discuss, all members still receive the same depth of feature processing. The distinction matters for this paper because a learned estimate of relevance can serve two roles. It can say how much to trust a representation after computing it, or it can decide whether to pay for that representation in the first place.

Sequential visual attention allocates work through a succession of glimpses. A later choice can use what an earlier glimpse revealed, making it a different way to search an image. The paper describes discrete glimpse mechanisms trained with reinforcement learning and notes the difficulty of training them. One example in that tradition is [Multiple Object Recognition with Visual Attention](https://md.research.elamur.ai/free/en/papers/ba-2014-multiple-object-recognition-visual-attention/).

Spatial transformers offer a differentiable approach to moving or reshaping a region. A localization network predicts transformation parameters, and a sampler extracts the corresponding view. Earlier systems reviewed by the paper also used such transformations repeatedly. The authors identify a difficulty for large images. The derivative of the sampled image with respect to the transformation depends on local pixel interpolation, so the information available to move a crop can come from a narrow neighborhood. The paper also discusses a multiple-instance extension that represents interest points through a heat map and introduces an auxiliary function. Its own method instead starts with scores for a collection of candidates and seeks a way to send a training signal back across that collection.

#### Why attention sampling is the closest comparison

Attention Sampling, abbreviated ATS, starts from a similar division of labor. A scorer supplies a distribution over locations, a small number of locations are sampled, and a feature extractor handles their patches. In the formulation described in the paper, the overall representation is an expected value of patch representations. A sample average estimates that value. This supplies a way to train with a small number of expensive feature computations, while giving the mean a specific mathematical role in the method.

The authors want to keep the crop budget while making the aggregation rule a design choice. Averaging can be appropriate when several patches offer similar or independent evidence about the answer. It can be less suitable when the question distinguishes the role of one patch from that of another. A spatial comparison, for instance, needs to retain enough information about the positions associated with the features being compared. A system can attempt to encode roles before averaging, but the mean gives the aggregation stage limited access to the individual representations. Preserving a list of patch embeddings gives a later stage more freedom to compare or prioritize them.

The paper also places its architecture alongside a patch-based vision Transformer. In the comparison it draws, the vision Transformer forms patches exhaustively and lets the network process the resulting sequence. Dividing an image into patches determines the units of computation. Choosing a small subset additionally determines which units receive that computation. The earlier vision architecture described in the paper is [ViT](https://md.research.elamur.ai/free/en/papers/dosovitskiy-2020-image-worth-16x16-words-transformers/).

A final line of prior work concerns the discrete operator itself. The paper mentions continuous subset sampling based on Gumbel-Softmax and approaches to ranking and sorting based on optimal transport. It builds on Berthet and colleagues’ perturbed-optimizer method. That approach allows the individual choices to remain ordinary discrete Top-K selections while making their average respond smoothly to the underlying scores. The particular advantage for this application is that the expensive feature stage can receive a fixed number of inputs and use an aggregation rule chosen for the recognition task.

### The method, step by step

#### A cheap view and a detailed view

The system first predicts whether each candidate location is worth a closer look. Its scorer is intended to be relatively inexpensive. For a large input, it can read a downscaled copy that preserves the arrangement and appearance of larger structures. It does not have to classify the contents of every crop from that copy. A coarse image may contain enough structure to identify a plausible ball or sign without preserving the number written on it. The scorer's job is to make the information lost at low resolution available selectively at the next stage.

The selection module takes the scores and uses them to obtain patches from the image. The score for a location and the crop extracted there are related by position, but the crop need not have the same size as the region of the image that influenced the score. The authors give an example in which scoring is associated with a 32 × 32 pixel region and extraction uses a 50 × 50 pixel patch. Conceptually, a score answers where to look and a crop specification answers how much of the surrounding image to read.

Each extracted patch is then passed through a feature network, usually the more expensive part of the recognition pipeline. The network produces an embedding, a vector of learned features. An aggregation network receives the patch embeddings and turns them into a prediction. It might average them, retain the largest activation in each feature dimension, or preserve patch-to-patch interactions through self-attention. The selection module can sit in front of any of these choices because it hands over patch images rather than imposing a particular estimator of the final prediction.

How differentiable patch selection classifies an image The steps in order.

The evaluation path differs at selection and extraction. With hard Top-K, the network ranks the unperturbed scores once and directly crops the chosen locations. During training, the combination of repeated choices can produce patch inputs that blend several crops. Both paths give the feature network the same number of inputs. That fixed interface is important because the rest of the system can be built around a small patch budget without knowing which image locations will fill it.

#### The shapes of the inputs and outputs

In the simplest presentation, there is a regular score grid and all extracted patches have a common shape. The bird experiment extends the setup to proposals with different sizes and aspect ratios. The common-shape notation lets the authors describe selection as an operation on a stack of candidate patches.

```
S = sθ(X) ∈ ℝʰˣʷ
```

Here `X` is the input image. The notation `sθ` denotes the scorer with learnable parameters `θ`, and `S` is its array of relevance scores. The symbol `∈` means that `S` belongs to the space that follows it. The symbol `ℝ` denotes real-valued entries, while `h` and `w` are the height and width of the score grid. The scorer can use a reduced version of `X` internally even though its scores refer to locations in the original image.

```
N = h × w
```

Here `N` is the total number of candidate locations, and `h` and `w` are the dimensions of the score grid. The multiplication sign combines those dimensions to give the number of scores after flattening the grid. The resulting order assigns a numerical index to each candidate. Later, that index provides a consistent way to order the selected subset across repeated rankings.

```
X̃ = p(X, S) ∈ ℝᴷˣᴾʰˣᴾʷˣᶜ
```

Here `p` is the selection module, `X` is the image, and `S` contains the scores. `X̃` denotes its extracted patch inputs. `K` is the chosen number of patch slots, `Pʰ` and `Pʷ` denote patch height and width, and `C` is the number of image channels. The superscript after `ℝ` lists the dimensions of the resulting real-valued array. The term *slot* is useful during training because a slot can contain a blend of different candidate locations.

```
H ∈ ℝᴷˣᴰʰ
```

Here `H` is the matrix formed by stacking the patch embeddings. `K` is the number of embeddings, and `Dʰ` denotes the number of features in each embedding. The feature extractor `fφ`, with learnable parameters `φ`, is applied to individual patch inputs to produce the rows of `H`. The paper notes that different feature extractors could be assigned to different patches but uses a shared extractor in its account of the architecture.

```
y = aψ(H) ∈ ℝᴰᵒ
```

Here `y` is the output vector, `aψ` is the aggregation network with parameters `ψ`, and `H` contains the patch representations. `Dᵒ` denotes the dimension of the output. The form of `aψ` determines what relationships it can represent directly. A mean treats the embeddings symmetrically and returns a single averaged representation. An attention-based aggregator can keep the embeddings available separately while letting each representation draw on the others.

#### What the hard selection actually returns

Given the flattened scores, Top-K identifies which candidates have the largest values. The paper makes a deliberate distinction between which candidates qualify and how they are ordered. Scores determine membership in the set. Candidate indices determine the order in which the members are returned. The first output slot therefore corresponds to the lowest index among the selected patches. It need not contain the highest-scoring patch.

```
Top-K(x ∈ ℝᴺ) = y ∈ ℕᴷ
```

Here `Top-K` is the selection operator, `x` is an input vector of `N` real scores, and `K` is the requested number of selections. `ℝ` denotes real numbers, and `ℕ` denotes natural-number indices. In this formula, `y` is the vector of selected indices instead of the classification output in the preceding formula. The membership symbol `∈` indicates the space to which each vector belongs.

```
y₁ < y₂ < ⋯ < yₖ
```

Here `y₁`, `y₂`, and `yₖ` stand for the first, second, and last returned indices, with the final subscript denoting the last of the `K` slots. The ellipsis covers the intervening indices, and `<` requires strict increase. If different perturbations choose the same subset, this convention assigns its members to the same slots. When subsets differ, each slot still has a consistent meaning as a position in the index ordering. That gives the averaged assignments a spatial interpretation even though they may cover several locations.

The authors represent each choice as a one-hot vector. A one-hot vector contains a unit entry at the chosen index and zeros everywhere else. Stacking the vectors as columns gives one matrix for the entire selection. The matrix can then be applied to the candidate patches in much the same way that a row of weights would be applied to a stack of images.

```
Y = [Iᵧ₁, Iᵧ₂, …, Iᵧₖ] ∈ {0, 1}ᴺˣᴷ
```

Here `Y` is the selection matrix, and `Iᵧ₁`, `Iᵧ₂`, and `Iᵧₖ` denote the vectors associated with the corresponding selected indices. The ellipsis stands for the other selected columns. The set `{0, 1}` gives the allowed entries of a hard selection, and the dimensions `N` and `K` give one row per candidate and one column per selected slot.

```
X̃ = YᵀP
```

Here `X̃` is the stack of extracted patches, `Yᵀ` is the transpose of the selection matrix, and `P` is the conceptual stack of all candidate crops. The multiplication acts along the candidate dimension, so each output patch is a weighted sum over the candidates at corresponding pixel and channel positions. A one-hot row of `Yᵀ` copies one crop. A row of fractional entries instead blends several. The paper describes a scan-based implementation for the weighted computation to manage memory and uses direct slicing when it makes a hard choice at inference.

The obstacle to training through hard selection is the response to a change in a score. If the change leaves the chosen subset intact, the crop is unchanged. If it swaps a candidate across the selection boundary, the crop can change abruptly. Applying a classification loss to the result can train the feature extractor and aggregator, but the hard operator supplies no ordinary local derivative telling the scorer how to improve the choice. The perturbed rule changes the object being differentiated. It gives the training loss access to how the average choice responds to shifts in the scores.

#### Why the authors formulate Top-K as an optimization

The perturbed-optimizer method starts from a choice that maximizes a linear objective over an admissible set. In the paper's generic notation, it returns an optimizing assignment.

```
argmax among Y ∈ 𝒞 of ⟨Y, η⟩
```

Here `Y` is the variable to be selected, `𝒞` is the admissible constraint set, and `η` contains the coefficients of the objective. The angular brackets denote an inner product, which multiplies corresponding entries and adds the products. The word `argmax` means that the operation returns a maximizing assignment `Y`. Its result is the selected assignment instead of the value of the objective.

For patch selection, the coefficient array is made by copying the flattened score vector into every slot. Accordingly, a candidate contributes the same score regardless of which column selects it. The ordering comes from the constraints rather than from a preference for a high score in any particular column.

```
max among Y ∈ 𝒞 of ⟨Y, s1ᵀ⟩
```

Here `max` denotes maximization of the objective. `Y` is the candidate assignment, `𝒞` is the constraint set, and `s` is the vector of `N` candidate scores. The symbol `1` denotes an all-ones vector, and `ᵀ` denotes its transpose. The outer product `s1ᵀ` repeats the score vector over the `K` slots. The inner product `⟨Y, s1ᵀ⟩` treats both arrays as flattened vectors before taking their dot product.

```
𝒞 = {Y ∈ ℝᴺˣᴷ : Yᵢₖ ≥ 0, 1ᵀY = 1, Y1 ≤ 1, Σᵢ iYᵢₖ < Σⱼ jYⱼₖ′ whenever k < k′}
```

Here `𝒞` is the set of allowable real matrices with `N` rows and `K` columns. The entry `Yᵢₖ` is the weight of candidate `i` in slot `k`. The nonnegativity inequality permits zero and positive weights. The expression `1ᵀY = 1` requires each column sum to equal one, and `Y1 ≤ 1` caps each row sum at one, with all-ones vectors sized to their roles. The symbols `Σᵢ` and `Σⱼ` sum across the candidate indices `i` and `j`. Each sum weights an index by its assignment to a column. The final inequality requires the weighted index in column `k` to be strictly smaller than the weighted index in a later column `k′`.

On integral assignments, these constraints have a simple interpretation. Each column selects exactly one patch, and each patch can appear at most once. The objective adds the scores of the selected patches. Maximizing it therefore amounts to choosing the largest scores. The index constraint fixes the order of the resulting columns. If a larger candidate index occupied an earlier column than a smaller one, the corresponding weighted sums would recover those two indices and violate the order condition. This is the reasoning used in the paper's appendix.

The objective can also admit fractional optima. The authors' construction uses the integral optimizer that the index-sorted Top-K operation returns. This distinction matters because their practical algorithm specifies a particular way of solving the selection problem and producing assignments. It does not require a general optimizer to find or choose among arbitrary real-valued solutions. The soft assignments that reach the feature network arise from averaging the hard solutions across noise draws.

#### How perturbing scores lets the classifier train the scorer

In each forward pass, the training rule adds independently sampled Gaussian noise to the input of the selection operation. It runs the hard solver on each perturbed input. The output of the differentiable module is the average of these solutions. The perturbation scale controls how readily a different ordering of scores can bring a new candidate into the subset.

```
Yσ = 𝔼Z[argmax among Y ∈ 𝒞 of ⟨Y, η + σZ⟩]
```

Here `Yσ` is the expected assignment at noise scale `σ`. The notation `𝔼Z` means an expectation over draws of `Z`, and `Z` is standard Gaussian noise in the input space under discussion. `η` contains the unperturbed objective coefficients. The sum `η + σZ` gives a perturbed input. The `argmax` returns a solution `Y` inside `𝒞`, and the angular brackets denote the objective's inner product.

The expectation is approximated by the mean of `n` independent trials. The paper uses `n = 500` in its experiments and tunes `σ` among `0.01`, `0.05`, and `0.5`. These repeats apply to the ranking and assignment calculation. The feature network receives the patch slots extracted from the averaged assignments, so it need not encode each set of crops separately for each draw. Making ranking cheap relative to deep patch processing is part of what allows the method to use many perturbations.

For the actual implementation, the noise goes into the vector of patch scores. Applying independent noise to the entire objective coefficient matrix could make the same candidate have a different score in each slot. A single ordinary Top-K operation would then cease to solve the resulting assignment problem. By perturbing the score vector before copying it across columns, the authors preserve the structure of the objective and can use Top-K to get each solution. They explicitly describe this as a departure from the general matrix formulation. The scorer's outputs are normalized to `[0, 1]`, with `ε = 10⁻⁵` used to keep the normalization from dividing by zero. A fixed scale makes the chosen noise magnitudes interpretable across images with different raw score ranges.

When the scorer strongly favors particular candidates, those candidates can be selected in most of the draws. In that case the averaged assignments resemble the hard result. When the scores are close, the set of selected candidates changes more often. Each slot can then combine pixels from a range of crops. The paper's example at initialization shows visibly blended patch inputs before the scorer has learned clear preferences. The authors suggest that this mixing might have a regularizing effect, but their experiment does not isolate a contribution from blending itself.

The backward rule uses the same relationship between the random input change and the resulting assignment. It estimates how the expected assignment varies with the input scores. The paper gives the Gaussian case in terms of a Jacobian, the collection of derivatives of the output entries with respect to the input entries.

```
J = 𝔼Z[(argmax among Y ∈ 𝒞 of ⟨Y, η + σZ⟩) Zᵀ / σ]
```

Here `J` is the Jacobian of the expected selection with respect to the perturbed operator's input coefficients. `𝔼Z` denotes expectation over the Gaussian draw `Z`, `Zᵀ` is its transposed form, and `σ` is the positive perturbation scale. `η` is the original input to the objective. The optimizing `Y` is chosen from `𝒞` using the inner product in brackets. Interpreting the assignment and noise in vector form, the product with `Zᵀ` pairs output entries with input perturbations. Division by `σ` scales that product for the magnitude of the input noise.

Intuitively, an assignment that appears more frequently when a score receives positive noise carries information about how an increase in that score would affect selection. The gradient from the classification loss can use that sensitivity, along with the derivative of the weighted patch extraction, to update the scorer. A patch need not win under the original scores to be considered by this estimator. This creates a route to learning about candidates early in training, when the scorer has yet to discover dependable locations. An individual finite set of draws can still supply little information about candidates it rarely selects.

There is an implementation distinction in the appendix. The displayed expectation has the form of a full Jacobian, in which an output weight for a patch can respond to perturbations of other patches' scores. The supplemental PyTorch code multiplies each candidate's indicator by the noise coordinate for that same candidate. Its backward contraction uses these matched contributions instead of forming every output-candidate and input-candidate pairing. The general equation and the computation in the appendix thus describe derivatives at different levels of detail. The appendix also provides a concrete implementation of the forward operation, including the separate sort by candidate index after each choice.

#### Moving from training to inference

At inference, the authors use hard Top-K for efficiency and determinism. A direct crop from a chosen location avoids the weighted patch combination, and a single ranking takes the place of the repeated rankings. The paper reports that hard selection processes 3-10% more images per second than the perturbed inference path. This comparison concerns two ways to run patch selection. The larger throughput gains reported elsewhere compare patch processing with running a feature network over the whole image.

Replacing soft assignments with hard crops can change what the feature extractor sees. A training input blended from several locations may differ considerably from the single patch that fills the same slot at test time. To bring the two paths closer together, the authors linearly decrease the perturbation scale during training. As the noise weakens, the same subset is more likely to recur across trials, and the slots become more like actual crops.

```
σ = 0
```

Here `σ` is the perturbation magnitude and `0` is the endpoint of the decay schedule. At that endpoint, the forward operation agrees numerically with hard selection because the scores are unperturbed. The scorer receives no gradient through hard selection at that point. The Gaussian backward expression above describes the positive-noise regime and cannot be evaluated by substituting zero into its denominator. The schedule uses the differentiable regime to learn what to look for and approaches the hard regime in which the trained system will be evaluated.

### Experiments and results

#### Reading speed limits in street scenes

The traffic-sign experiment uses the Swedish dataset subset adopted by Attention Sampling. It contains 747 training images and 684 test images, each measuring 960 × 1280 pixels. The image label indicates a speed limit of 50, 70, or 80 kilometers per hour, or the absence of a speed-limit sign. The data augmentation follows ATS and gives each training image a random translation and a random affine change to its colors. The comparison asks whether two ways of choosing patches can solve the same recognition problem with broadly matched feature processing.

The scorer sees a 3× downscaled copy of the input. Its 4 convolutional layers are followed by max pooling with stride 8, meaning that the pooling window advances by 8 positions at a time. The scorer supplies a 39 × 52 grid with 2028 candidates. The selection module extracts 100 × 100 patches, with the experiments using `K` values of 5 and 10. The feature extractor is the narrow ResNet18 used in ATS. Mean pooling combines the outputs, so the method does not rely on a more expressive aggregation network to compete on this task.

The paper reports test classification accuracy using the mean and standard deviation across 9 runs for the patch comparisons and 5 runs for the full-image CNN. Differentiable selection matches the mean performance that ATS reported, with a larger spread. The authors also report their best stable attempts to reproduce ATS from its released code. Those attempts used entropy regularization with coefficient 0.05 and trained for 300k iterations. One variant changed the learning rate at 12,000 epochs. This distinction matters because the published ATS result and the paper's reproduction are different comparison points.

A shorter ATS schedule with entropy regularization of 0.01 could achieve higher accuracy, but the authors observed runs that failed badly under that setting. Roughly 20-25% had test accuracy below approximately 60%. A comparison based entirely on a successful run would hide that instability. The paper accordingly uses repeated runs to show the spread of performance and separates the reproduction settings from the original ATS result.

The full-image control applies the small ResNet directly to the image. It reaches 100% training accuracy but falls to the level of a majority-class prediction on the test set. Processing every region therefore does not help this particular small network generalize from the available training data. The authors interpret the gap as evidence that patch extraction can impose a useful bias towards localized evidence in this setting. That claim rests on the comparison within this setup, including the choice of feature network and the amount of training data.

#### Finding the decisive numbers on a billiard table

The authors generated the billiard-ball dataset with Kubric. Each image contains four to eight randomly positioned, randomly colored balls. Their numbers range from 1 to 9, are sampled uniformly, and face the camera. The arrangement prevents a ball from being completely hidden by another. The label is the larger of the numbers on the leftmost and rightmost balls. A large number on an interior ball can be visually apparent and still irrelevant to the answer.

The dataset contains 20k images at 1000 × 1000 pixels. Its splits contain 8k training images, 2k validation images, and 10k test images. The paper makes the generated dataset available for download and identifies the experiment code in the Google Research repository. The task was constructed so that a low-resolution view could show where the balls were while leaving their digits unreadable. It tests a situation in which a rough global view and a detailed local view can contribute different information.

The 4-layer scoring CNN operates on a 250 × 250 view. A standard ResNet18 encodes the extracted crops. The authors compare mean pooling, max pooling, and a Transformer with 3 self-attention layers and 8 heads. The Transformer takes the patch embeddings as a sequence and adds learned positional information to them. The controls include ATS and a ResNet18 that works directly on the image. The authors also add positional information to some baseline inputs using fixed coordinate channels normalized to `[0, 1]`. Those channels make location information explicitly available to the baseline feature calculations.

The methods use Adam with decoupled weight decay of 10⁻⁴ and a tuned learning rate of 10⁻⁴. Repetition reveals substantial differences in whether a training run learns the task at all. The results are reported as median top-1 accuracy and median absolute deviation. Top-1 accuracy measures whether the most highly ranked class is correct. Median absolute deviation measures how much the runs typically depart from their median. The general comparison uses 5 runs, with 4 for ATS and 9 for the differentiable selection variants.

Without the added coordinate channels, only 1 out of 4 ATS runs solves the task to a meaningful degree, reaching a test accuracy of 53.25 %. The other runs perform at the level of predicting the majority class. With the coordinate channels, 3 out of 4 ATS runs learn a meaningful solution. The remaining run predicts the majority class throughout. The improvement shows that making spatial position accessible helps ATS on this target. The paper still finds its performance below that of the Transformer variant.

Differentiable selection with a Transformer yields the best performance among the compared aggregation methods. Max pooling can also solve the task with high accuracy, but 2 out of 9 max-pooling runs collapse to the majority-class prediction. Mean pooling is relatively stable across repeats and performs poorly compared with the stronger aggregators. The fact that it trains consistently does not mean that it learns the intended comparison well. The full-image ResNet18 can solve the task at its original resolution, with training time reported as 24 % higher than that of the patch-selection system using the Transformer. Reducing the full-image input to save time damages recognition because the numbers become too small to read.

The authors also vary the training and inference treatment of perturbations while keeping the Transformer aggregation head. The chart gives the accuracy change for each successive comparison. The first row compares hard inference with perturbed inference after constant-noise training. The second compares decayed-noise training with constant-noise training when both use hard inference. The gains have separate reference settings.

Billiard balls test accuracy gains from hard inference and noise decay Hard inference improved accuracy, and decaying the training noise improved it further.

**The numbers**

| System or setting | reported accuracy gain % |
| --- | --- |
| Hard inference after constant-noise training | +1.3 |
| Hard inference after decayed-noise training (this paper) | +1.4 |

#### Recognizing bird species from small visual differences

The CUB-200 task uses 11,788 images of birds from 200 species. The authors use it to test whether differentiable extraction can replace the patch-ranking procedure in NTS-Net, a system designed to recognize fine distinctions among species. A region such as the head or torso can contain visual features that become easier to distinguish when inspected at greater detail. In this experiment, the system also processes a whole-image view. The primary question is how to incorporate useful close-ups into recognition under image-level supervision.

The NTS-Net procedure described in the paper begins with an image resized and cropped to 448 × 448. A ResNet supplies full-image activations to a proposal scorer, which scores regions at several scales and aspect ratios. Greedy non-maximum suppression filters out redundant candidates, then the remaining regions are scaled to 224 × 224 and encoded with the same ResNet backbone. The baseline uses classification heads for the full image, individual patches, and their joined representations. It also uses a ranking loss to teach the scorer how to order the candidate patches.

The adaptation uses ResNet50 and substitutes differentiable Top-K for the selection procedure. It omits the dedicated ranking loss because classification gradients can pass through extraction and back to the proposal scorer. Its scorer adds Squeeze-Excitation layers in the proposal network. Those layers let information from across the feature map influence local scoring, which gives the scorer a way to favor different areas without a hard overlap rule. The appendix describes normalization across 1614 proposal scores. The region scorer uses entropy regularization with a coefficient of 0.05, applied to a softmax of the proposal scores before their normalization for selection.

The paper compares two ways to combine features. Concatenation places the image vector and each patch vector next to one another, preserving a separate block of features for each patch. Mean aggregation averages the patch embeddings and then adds the full-image embedding.

```
R = Rᵢ + (Rₚ₁ + ⋯ + Rₚₖ) / K
```

Here `R` is the aggregate representation. `Rᵢ` denotes the embedding of the entire image, and `Rₚ₁` through `Rₚₖ` denote the embeddings of the individual selected patches. The ellipsis covers the remaining patch embeddings. The sum in parentheses divided by `K`, the number of selected patches, is the mean patch embedding. Adding that mean to `Rᵢ` preserves the embedding size. In this experiment, the resulting representation has 2048 dimensions.

To tune the model, the authors set aside 994 images from the training portion for validation and use the other 5000 for training. After choosing optimization and regularization settings, they train on all 5994 training images and evaluate on the official test set. They use SGD with momentum 0.9 and report standard deviations over 5 repeats. The ResNet50 was pretrained on ImageNet ILSVRC12, and pixel values during training are rescaled to `[-1, 1]` to match that pretraining setup. Other augmentation follows NTS-Net. Describing the pretraining separately matters because the image-level supervision claim concerns the bird task's patch selection and classification, for which the experiments use neither object boxes nor boxes marking parts.

The adaptation performs slightly worse than NTS-Net overall. Mean aggregation improves on the concatenation variant of differentiable selection. The best seed using mean aggregation and `K = 4` attains 87.3% top-1 accuracy on the official test split. The paper presents that accuracy as the result of the best seed, alongside its separate comparison across 5 repeats. Qualitative examples from that seed show crops around the bird's eyes and torso as well as substantial overlap among some selected regions.

#### How much processing the crops save

The appendix measures inference throughput in images per second on a single V100 GPU. It compares a full-image ResNet50 with a ResNet50 applied to selected patches and uses mean pooling for aggregation. The authors vary the patch count and patch dimensions, and each plotted point uses the highest throughput among feasible batch sizes. The measurement therefore captures what the tested configurations can process under batching on that device.

In the configuration with `K = 10` and 100 × 100 crops on a megapixel image, the authors report a 5 fold speedup with patch processing. They relate the example to recognition problems whose useful information is localized within 10% of the image pixels. Roughly 28 % of inference time in that configuration goes to the feature network. Most of the remaining time goes to calculating the patch scores, and the Top-K calculation itself has little effect on runtime. As the feature network sees less of the image, the system's cheap first look becomes a more prominent part of the compute budget.

The appendix also compares full-image processing by a smaller ResNet18. On 1000 × 1000 images, that configuration is no faster than the patch system with a ResNet50 in the tested setup. This makes concrete the tradeoff the paper proposes. Cutting the amount of image passed to the expensive stage can make room for a stronger local recognizer. The throughput result quantifies that opportunity separately from the classification experiments, which establish how well a chosen set of crops serves particular recognition tasks.

### What the ablations show

#### Selection changes what the learner can fit

The full-image control on street scenes tests the effect of removing the crop-selection stage and letting the feature network see everything. Its 100% training accuracy establishes that the narrow network has enough capacity to memorize or fit the training labels in that setting. Its majority-class-level test performance shows that fitting the examples did not yield a reliable recognition rule. The patch-based comparisons show better generalization once the pipeline has to route the prediction through a few regions. The control connects that difference to the whole selection setup, which changes the inputs and how the recognizer combines them.

The authors' manual examination of traffic-sign errors adds a separate kind of evidence. They found that the scorer typically retrieved relevant regions in the cases they inspected. A recurring localization mistake involved patches whose colors resembled those of traffic signs. The authors suspect that other mistakes often came from the feature extractor or aggregator. That interpretation is qualitative. A correctly placed crop can still be misread, and the inspection does not measure the relative contributions of those errors systematically.

The bird experiments give a counterexample to treating patch selection as a general safeguard against overfitting. A small crop can expose an incidental watermark or a background pattern just as readily as it can expose a beak or an eye. The authors observed that the scorer could exploit such regions when fitting the training images. The contrast between the two tasks suggests that the effect of selection depends on what compact evidence is available and how reliably that evidence agrees with the label beyond the training set.

#### Aggregation matters once the label depends on relationships

The billiard task keeps the crop-based framework in place while varying how it combines patch embeddings. Mean pooling retains the average activation in each feature dimension. Max pooling retains the strongest activation in each dimension. A Transformer can let one patch representation influence how another is interpreted. The task's label requires a decision about spatial extremes followed by a comparison of the digits that appear there, giving those alternatives different ways to represent the necessary evidence.

Over 9 repetitions per setting, the Transformer is the strongest of the three. Mean pooling is comparatively stable but weak. Max pooling can achieve high accuracy and also yields runs that collapse to the most frequent label. These outcomes distinguish the ability to express a solution from the reliability with which training finds it. The max-pooling result also shows that solving this synthetic task does not uniquely require attention. The Transformer provides the best combination of performance and observed stability among the tested heads.

Adding coordinate channels to the baselines is a related but distinct comparison. It asks whether weak performance reflects a lack of explicit access to position. ATS improves when those channels are present, which is consistent with the task's dependence on locating the extreme balls. Its remaining difficulty is consistent with a limitation of combining patch embeddings through a mean. The evidence supports both explanations without assigning all of the performance difference to one architectural decision. The Transformer variant uses a particular positional representation and a different method of feature interaction, while the coordinate-augmented baselines incorporate positions into the image input.

The bird aggregation comparison makes the role of the task especially clear. A mean is more competitive there because the patch embeddings can contribute evidence about the same species and can be added to the whole-image representation. Concatenation preserves more information about individual slots, but it produces a large input to the linear classification head. The authors associate the better performance of the mean variant with lower overfitting. The comparison changes both the combination rule and the dimensionality of the classifier input, so it does not isolate one of those factors from the other.

#### Hard selection and noise decay make separate contributions

On the billiard task, the appendix compares constant perturbation during training and inference, constant perturbation during training followed by hard inference, and decaying perturbation during training followed by hard inference. The Transformer head and the other hyper-parameters are held fixed, with 9 repeats for each setting. The first change affects only what the trained system does at test time. The second affects the patch inputs that the feature network and aggregator encounter as training progresses.

The authors report an accuracy gain of +1.3% when switching from perturbed to hard inference after constant-noise training. Decaying the training noise provides a further +1.4% under hard inference. The first comparison shows that, in this setup, a deterministic crop was beneficial even when the recognizer had learned on softly extracted patches. The second shows that the training schedule affects how well the final system uses those deterministic crops. The design supports a claim about this transition on the billiard task. The paper does not run the same controlled experiment across all three datasets.

The traffic-sign experiments also compare a different way of relaxing Top-K. The Sinkhorn approach uses an optimal-transport formulation of selection. It produces good traffic-sign results in the paper's tests, with means and standard deviations calculated across 5 runs, but it loses performance when switched to hard selection at inference. The authors prefer their perturbed-optimizer approach on the strength of the comparisons they ran. This experiment illustrates that how a relaxation behaves during training and how successfully it transfers to discrete cropping are separate properties.

#### Overlap persists even with a more expressive scorer

For bird classification, greedy non-maximum suppression in NTS-Net enforces a form of diversity by discarding candidates that overlap strongly with a better-scoring region. The authors explain that the greedy procedure does not fit their perturbed linear optimization formulation. They consider a non-greedy counterpart expressible through additional constraints, but judge the resulting optimization too expensive to solve `n = 500` times per forward pass. Their practical adaptation instead gives the scorer a broader view of the image through Squeeze-Excitation.

The learned scorer can use that broader context when assigning scores, but Top-K still permits different candidates with overlapping footprints. The examples show that the selector frequently spends several slots around the same bird head. This is a qualitative observation about what the adaptation learns, instead of a controlled measurement of how much the Squeeze-Excitation layers help. The visualizations also show examples in which useful body regions are selected. Taken together, they show that relevance and diversity are different properties. Candidates can all be relevant and still duplicate evidence that a small crop budget could have used to cover more of the bird.

### Limitations

#### Limits identified by the authors

The authors describe a basic difficulty in learning where to look. A system that knew the full contents of the image could make a better decision about where to allocate its computation. The point of the method is to avoid paying for that knowledge before deciding. A lightweight global view can break the dependency when useful locations are recognizable from coarse cues, as they are for visible balls. It offers less help where a region's relevance can be determined only from the detail the scorer cannot afford to inspect. A downstream network can reason flexibly about the patches it has received, but it has limited means to recover detail at locations excluded upstream.

The authors also report unstable training. Some runs settle on the most common label. In other cases the scorer becomes confident about the wrong regions, either early in training or after initially making progress. A smooth training operator provides gradients across selection choices, but useful supervision still depends on what those choices expose to the classifier. If a classification head can make progress using a shortcut, its loss can reinforce the selection of that shortcut. The paper points to more adaptive optimization as a possible direction for improving stability.

The same issue appears in the account of bird overfitting. The selector can discover watermarks or backgrounds that correlate with labels on the training set. Adapting the NTS-Net framework reduced overfitting in the authors' experiments, yet the adaptation still trailed NTS-Net and repeatedly selected overlapping areas. The authors suggest larger training datasets and self-supervised learning as possible ways to address overfitting. They also recognize that selection alone does not ensure the type of broad coverage required by segmentation or detection. The task and the patch budget define what the system is being asked to retain.

The perturbation method adds an inference choice of its own. Using the soft rule at test time preserves the type of extraction seen during training but retains the cost and randomness of repeated selection. Using the hard rule is cheaper and deterministic, and it changes the patch inputs. The noise schedule helps bridge this gap on the tested task. At its endpoint, however, the loss ceases to send a selection gradient to the scorer. The authors' construction uses the training schedule to manage that tradeoff rather than removing it from the learning problem.

#### Limits visible in the experimental setup

The tasks establish several uses for patch selection under particular conditions. They do not measure comprehensive localization. A correctly classified street image can count as a success even if other visible signs are never selected. Likewise, a bird species label can be correct even if the selected patches omit most of the bird. Classification accuracy measures whether the retained information led to the right answer. It leaves questions about regional coverage, the completeness of evidence, and which shortcut cues the system used to qualitative analysis or separate evaluation.

The billiard task makes spatial reasoning testable by construction. The correct answer depends on the extreme positions and the numbers written there, and the generated scenes give the scorer a clear coarse cue for locating candidate balls. That is a strong setup for distinguishing aggregation methods on a specific spatial rule. It establishes less about performance when the relevant entities are ambiguous, when relative roles are harder to specify, or when useful context is spread throughout an image. The experiment also does not verify that each successful run internally follows the intended sequence of locating, reading, and comparing. The output metric tests the answer to that rule.

The comparisons differ in what is held fixed. The street-sign study matches much of ATS's feature processing and aggregation, yet the authors could not reproduce its published results exactly. Comparisons against their stable reproductions consequently have a different interpretation from the comparison with the published mean. The bird adaptation changes the proposal network, the suppression mechanism, and the loss used to train the scorer as well as the selection operator. Its test result demonstrates the performance of that complete adaptation. It cannot determine how much of the gap to NTS-Net is caused by overlap, the supervision change, or the other architectural choices.

The throughput comparison is also bounded by its configuration. It uses batched inference on one GPU and exploits a favorable crop budget. Larger crops, more crops, and a more expensive scorer would change the balance between scoring and feature extraction. Crops may overlap, so the nominal amount of processed patch data and the amount of distinct image content examined can differ. The measurements show that a large gain is possible when a small part of the image carries the answer. They do not establish an equivalent gain for arbitrary settings, end-to-end latency requirements, or tasks in which the scorer must inspect the input in detail.

Finally, the mathematical formulation and the implemented choice involve distinctions worth preserving. The appendix's index-order argument applies to integral assignments, while the relaxed objective can also have fractional optima. The practical algorithm selects a specific integral answer with ordinary Top-K and perturbs shared scores to preserve that solver. The displayed general Jacobian and the matched-coordinate calculation in the supplemental code describe different derivative structures. The experiments establish the practical performance of the selection procedure under the tested arrangements. They leave the behavior of alternative noise structures and backward calculations open.

### What came after

No subsequent studies are documented here.

## Cite

Cite as Jean-Baptiste Cordonnier, Aravindh Mahendran, Alexey Dosovitskiy, Dirk Weissenborn, Jakob Uszkoreit and Thomas Unterthiner. 2021. Differentiable Patch Selection for Image Recognition. IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings.

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

```bibtex
@inproceedings{cordonnier2021differentiable,
  title = {{Differentiable Patch Selection for Image Recognition}},
  author = {Jean-Baptiste Cordonnier, Aravindh Mahendran, Alexey Dosovitskiy, Dirk Weissenborn, Jakob Uszkoreit and Thomas Unterthiner},
  booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings},
  year = {2021},
  doi = {10.1109/cvpr46437.2021.00238},
  eprint = {2104.03059},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1109/cvpr46437.2021.00238}
}
```

> 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)
