---
title: "Learning Affinity from Attention — paper by Ru et al. (2022)"
description: "Affinity from Attention turns image tags into training masks for semantic segmentation by learning which image regions should share a label."
canonical: "https://research.elamur.ai/free/en/papers/ru-2022-learning-affinity-attention-end-end/"
---
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/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/ru-2022-learning-affinity-attention-end-end/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2022](https://md.research.elamur.ai/free/en/papers/2022/) / Learning Affinity from Attention: End-to-End Weakly-Supervised Semantic Segmentation with Transformers

# Learning Affinity from Attention: End-to-End Weakly-Supervised Semantic Segmentation with Transformers

Paper · 2022 · Lixiang Ru, Yibing Zhan, Baosheng Yu et al.

**Authors:** Lixiang Ru, Yibing Zhan, [Baosheng Yu](https://md.research.elamur.ai/free/en/authors/baosheng-yu/) and [Bo Du](https://md.research.elamur.ai/free/en/authors/bo-du/) · **Year:** 2022 · **Venue:** IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings · **Licence:** [CC BY 4.0 (arXiv)](https://creativecommons.org/licenses/by/4.0/)

[**281** citations OpenAlex, 2026-10-14](https://openalex.org/works?filter=cites:W4313153210) · Cited by **3** papers in our library of the 163,136 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](https://creativecommons.org/licenses/by/4.0/)

- [PDF](https://arxiv.org/pdf/2203.02664)
- [DOI 10.1109/cvpr52688.2022.01634](https://doi.org/10.1109/cvpr52688.2022.01634)
- [arXiv 2203.02664](https://arxiv.org/abs/2203.02664)
- [OpenAlex](https://openalex.org/W4313153210)

Citations: OpenAlex, 2026-10-14.

## Summary

An image tag can tell a computer that a dog is present. A segmentation mask must also say which pixels belong to the dog, including parts that are easy to overlook and edges where the dog meets the background. Drawing those masks for training takes more work than tagging whole images. This paper asks how to train a system to draw them using the cheaper labels. The authors start by finding regions that help a classifier identify each tagged object category. They then learn which other regions should receive the same label, using relationships already computed by a [Transformer](https://md.research.elamur.ai/free/en/concepts/transformer/).

The classifier’s first estimate is a class activation map, a grid that shows where the image supports a category. It can highlight a distinctive part and leave much of the object uncovered. The authors use self-attention, the operation that lets image patches exchange information, to address that gap in two ways. It gives the classifier features that already incorporate information from elsewhere in the image. It also supplies pairwise scores from which the authors learn semantic affinity, an estimate of whether two locations belong to the same category. Their Affinity from Attention module, or AFA, learns to combine those scores using provisional examples of which locations agree or disagree. Using the original attention scores directly to spread labels weakened the provisional masks in the authors’ comparison.

The other new component, Pixel-Adaptive Refinement, uses nearby colors and positions to make the masks better follow visible boundaries. It runs before affinity learning, where it helps produce the provisional examples, and again after learned affinities have spread the class scores across the image. The resulting masks supervise the segmentation branch while it trains in the same network as the classifier and the affinity branch. The targets are generated from image tags and the network’s own computations. The training images do not need human-drawn masks.

The final system reaches 66.0% mean intersection over union on the PASCAL VOC 2012 validation set with conditional random field post-processing, and 38.9% on the MS COCO 2014 validation set. Mean intersection over union measures how closely predicted areas match annotated areas across categories. On PASCAL VOC, the reported validation score is 63.8% before that post-processing step. The paper reports gains over earlier end-to-end approaches and competitive results against systems trained in separate stages. The comparisons within the method explain where those gains come from. Teaching attention to represent category agreement improves the provisional masks even before propagation, and propagation with the learned affinities improves them further.

## Deep dive: Learning Affinity from Attention: End-to-End Weakly-Supervised Semantic Segmentation with Transformers

Affinity from Attention turns image tags into training masks for semantic segmentation by learning which image regions should share a label. · about 35 minutes to read

**In this deep dive**

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

### The problem and its context

#### An image label leaves the location open

Semantic segmentation assigns a category to every pixel. A successful prediction must cover the parts of a visible object that are hard to recognize in isolation and stop where a different category begins. The task is semantic because pixels receive category labels. Two objects of the same category can receive the same label even when they are separate objects. The training burden comes from the spatial detail required in the annotations. An image tag is enough to record that a category occurs. A segmentation annotation records where it occurs.

The paper situates image tags at the sparse end of a range of weak supervision. A marked point supplies a location. A scribble identifies some pixels along a region. A bounding box restricts the area in which an object can be found. An image tag leaves all of this to be inferred. It does, however, supply a useful constraint. The categories named by the tags give the procedure a set of foreground candidates to look for in the image. The hard part is assigning those candidates to locations and deciding how much of the image belongs to background.

A classification network offers a natural starting point because it can learn directly from the tags. Once it has learned to recognize a category, its spatial features and classification weights can be used to estimate where the evidence lay. There is a gap between evidence for recognition and evidence about extent. An image may be easy to classify from a small, distinctive part. The classification objective has little reason to insist that adjoining, less distinctive parts contribute equally. Conversely, pixels outside the object can help identify the category if they provide useful context. An activation map can therefore omit part of an object or extend beyond it while the classifier still gives the correct image-level answer.

This gap matters because the activation maps take the place of human annotations in training. If the training target repeatedly misses parts of an object, the segmentation branch may learn to miss those parts too. If the target extends over a nearby region of another category, the predictor is asked to reproduce that mistake. An improved training mask must deal with both incomplete coverage and incorrect coverage. Expanding every strong response would address the former at the risk of worsening the latter. The authors are looking for a basis on which to decide where expansion makes sense.

#### How earlier methods built training masks

The paper describes a common workflow in which a classifier is trained first. Its class activation maps serve as initial masks. A refinement procedure improves them, and a separate segmentation network is then trained on the revised targets. This arrangement lets researchers develop recognition, mask generation, and dense prediction as different stages. It also means maintaining separate training procedures and training networks for different jobs. The appeal of an end-to-end approach is that a single training run can support classification, generate the training masks and fit the segmentation branch.

Many of the multi-stage methods discussed by the authors address the tendency of activation maps to concentrate on distinctive regions. Erasing methods remove such a region so that a classifier has to find additional evidence. Other approaches collect activations over training, taking advantage of the fact that a classifier can attend to different parts at different points in optimization. Cross-image methods search for regions with shared semantics in multiple images. Auxiliary tasks give the classifier additional reasons to discover parts of the object. The paper also discusses work that approaches mask generation through causal inference, information bottlenecks or changes to classifier attributions. These approaches intervene at different points, but each responds to the same practical difficulty of turning recognition evidence into spatial coverage.

Earlier end-to-end work developed several ways to make training possible under sparse supervision. One approach used adaptive expectation maximization to infer missing segmentation targets during training. Another treated an image as a collection of locations and used Log-Sum-Exp aggregation to connect predictions at those locations to the image tag. That connection lets a prediction at a location receive a training signal through its contribution to image classification. The 1Stage system combined its own pooling rule with refinement guided by image appearance and a mechanism for passing low-level information into the predictor. RRM refined class activation maps with a conditional random field and used a regularization loss to encourage neighboring predictions to agree with the image’s appearance. The paper also describes an adaptive affinity approach that weights neighborhood relationships and aligns features with category prototypes.

These earlier systems already made use of neighboring pixels, related regions and inferred mask labels. The point of departure here is the architecture that produces the features and pairwise relationships. The authors argue that the convolutional networks commonly used by prior end-to-end approaches have difficulty making effective use of relationships across the whole image. A convolution computes from a neighborhood at each application, while self-attention provides a mechanism for a location to draw information from a much broader set of locations. For weak supervision, the authors expect that difference to matter even before a mask is refined. A response at a less distinctive patch can incorporate information from a more recognizable part of the object.

#### From recognition and localization to affinity

The paper traces the use of pure Transformer architectures in visual recognition to the Vision Transformer. Its representation starts from image patches, which can be processed as a sequence while still being mapped back to the image grid. The authors note that variants had already been applied to dense vision tasks, including segmentation, as well as depth estimation and video understanding. Their proposal takes that architecture into segmentation trained from whole-image tags. The earlier recognition architecture is described in [An Image Is Worth 16x16 Words](https://md.research.elamur.ai/free/en/papers/dosovitskiy-2020-image-worth-16x16-words-transformers/).

TS-CAM is a closer precedent in the paper’s account because it also learns from image tags. Its task is weakly supervised object localization. TS-CAM combines category-specific activation maps with attention from a class token to image patches. That attention gives a spatial cue about where the image representation gathers information. AFA asks a different question of attention. It begins with the scores between patch locations and tries to turn them into a reliable estimate of whether those locations should receive the same semantic label. An estimate for every relevant pair can then govern how a class response moves from one part of the image to another.

That change of purpose creates a supervision problem of its own. A self-attention score is useful to the encoder when it helps construct a feature. Two locations can help each other for reasons other than shared category membership. An object and the context around it may be useful to each other for recognition. In addition, a location can draw heavily on another location without the reverse being equally important. Semantic affinity, as defined for this paper, is a statement about the pair and should be the same in either direction. The method therefore needs both a way to combine and symmetrize the attention scores and a source of examples that gives the combination its intended meaning.

### The method, step by step

#### How the training targets are built

The method starts with an image and its tags. An encoder produces a grid of features and records attention between image locations. A classification branch uses the features to predict which categories are present. Its weights also give a way to score each category separately at every location. This produces the first spatial estimate, the class activation map, or CAM. It is a collection of class scores before it is a set of hard labels.

Pixel-Adaptive Refinement, abbreviated PAR, first improves those scores locally. Locations with compatible colors and positions can contribute to one another’s scores. The refined maps are then screened for confidence. Strong responses provide examples of foreground, very weak responses provide examples of background, and intermediate responses are withheld from affinity supervision. The procedure compares the remaining labels in nearby pairs. Locations assigned the same label give a positive example for AFA, while locations assigned different labels give a negative one.

AFA learns to predict pairwise agreement from the encoder’s attention. That prediction is used in a random walk, which redistributes the initial class scores according to connections between locations. This can carry evidence from a well-recognized part of an object to a region that the classifier scored weakly. It can also reduce a response that receives little support from its connections. PAR is applied again to the propagated scores to bring them into closer agreement with local appearance. These refined targets train the segmentation branch.

How image tags guide training-mask generation The steps in order.

The sequence describes the dependencies between computations inside training. It contains distinct prediction tasks. Classification concerns the image as a whole. Affinity prediction concerns pairs of spatial locations. Segmentation concerns the category of each location. The outputs have different shapes and receive different targets, even though the encoder provides features for all of them. The training schedule gives the classifier time to produce a usable starting map and then gives the affinity branch time to learn from it.

#### Encode the image and retain pairwise scores

The paper begins its mathematical description with a grid of image patches. In its generic notation, the grid has height h and width w, with hw patch locations when the grid is flattened. Patches are projected into vectors called tokens. A token represents the features at a location. The attention operations can combine information across locations, and their outputs retain a position in the grid so that the eventual activation map can be interpreted spatially.

In an attention head, each token is projected into a query, a key and a value. A query is used to score what the token can draw from other locations. A key is the representation against which queries are compared. A value carries information that gets combined once the attention weights have been computed. The paper writes the score operation as follows.

```
Sᵢ = QᵢKᵢᵀ / √dₖ
```

The subscript i identifies the attention head. Qᵢ and Kᵢ are its query and key matrices, with a row at each of the hw locations and dₖ features per row. The superscript ᵀ transposes the key matrix so that matrix multiplication compares every query row against the key rows. Sᵢ is the resulting grid of pairwise scores in flattened coordinates. The square root of the query and key feature dimension dₖ is the divisor that scales the dot products.

```
Xᵢ = softmax(Sᵢ)Vᵢ
```

Xᵢ is the feature output for head i and Sᵢ is its score matrix. For each query, softmax turns the scores over keys into normalized weights. Vᵢ is the value matrix of head i, with dᵥ value features per location. Multiplication combines those values with the normalized weights. The result at each query location can therefore carry information from the locations to which that query attends.

```
Xₒ = FFN(X₁ ∥ X₂ ∥ … ∥ Xₙ)
```

Xₒ is the output of the Transformer block in the paper’s description. X₁ through Xₙ are the outputs of its n attention heads. The double bar indicates concatenation along the feature dimension, and the ellipsis stands for the intervening head outputs. FFN is the feed-forward network applied to those concatenated features in the paper’s account. Its description includes a multilayer perceptron, or MLP, and [Layer Normalization](https://md.research.elamur.ai/free/en/papers/ba-2016-layer-normalization/).

The implementation uses MiT-B1, a Mix Transformer from SegFormer. Its patch embeddings overlap, which helps preserve relationships at the edges of neighboring patches. Its spatially reduced attention is intended to lower the cost of the attention computation, and its feed-forward layers incorporate convolutions to handle spatial information in place of explicit position embeddings. Its successive stages give feature maps at different spatial scales. The segmentation decoder takes features from several stages and combines them with MLP layers for dense prediction.

In the implementation discussion, the paper uses h and w for input image height and width. Using those dimensions, it gives the original last-stage feature resolution as follows.

```
(h/32) × (w/32)
```

The slash divides the corresponding input dimension by the spatial reduction factor, and × separates the height and width of the grid. The authors reduce the stride of the last patch-merging layer from 2 to 1 so that the initial activation maps can use a finer grid. A stride is the spacing between successive applications of the patch-merging operation. The resulting last-stage resolution is as follows.

```
(h/16) × (w/16)
```

Here h and w again denote input height and width. The divisions give the revised spatial dimensions, and × denotes the grid shape. The final stage supplies the high-level features used for activation maps and the attention channels used for affinity prediction. The paper concatenates the heads from the blocks in that stage and describes their shape as follows.

```
S ∈ ℝ^((hw/256) × (hw/256) × nk)
```

S is the stack of attention matrices used for affinity prediction. The symbol ∈ means that it belongs to the indicated space of real-valued arrays, denoted by ℝ with the array dimensions written above it. The entries on the first spatial axis represent query locations and those on the second represent key locations. Each axis has hw/256 locations, with hw the product of input height and width. The final axis has nk channels, the product of the number of blocks n and the number of heads k in each block. In this implementation description n counts blocks, whereas in the earlier formula for a single block it counts heads. The purpose of retaining the channel axis is to let the affinity predictor learn what each attention channel contributes.

#### Find class evidence on the grid

For image classification, the network pools the spatial feature maps to obtain a vector for the whole image. The paper evaluates different degrees of pooling and favors global max pooling. This takes the strongest spatial response in each feature channel. The classification layer maps the resulting vector to category probabilities. Because an image can contain several categories, the target is a set of present categories, with a separate confidence for each.

The same classification layer can be used on the unpooled feature maps to recover spatial evidence. A class activation map weights each feature channel by its contribution to the chosen category and combines the weighted channels location by location.

```
Mᶜ = ReLU(∑ᵈᵢ₌₁ Wⁱ˒ᶜ Fⁱ)
```

Mᶜ is the activation map for category c. The index i runs from 1 through d over the feature channels. Fⁱ is the grid of responses in channel i, and Wⁱ˒ᶜ is the classification weight from that channel to category c. The sum combines the weighted feature grids. ReLU, the rectified linear unit, removes negative responses by replacing them with zero.

The paper then uses minimum–maximum normalization to put each map on the stated score scale from 0 to 1. It also introduces a background score, called beta, so that a location can be treated as background when foreground evidence is weak. A background score is a decision parameter, separate from the classifier’s evidence for a particular object category. Later, the affinity targets use a lower and an upper cutoff so that intermediate responses can remain undecided.

A high CAM score says that the feature at a location supports a category. The score has been learned through image-level classification, so it is an initial estimate of what is there. It need not fill the entire visible area of an object. The authors’ design uses the feature grid to localize evidence, then uses different information to decide which other locations should be treated in the same way.

#### Refine scores with color and position

PAR changes the category scores by consulting a neighborhood around each location. It compares the RGB values at the center and at a candidate neighbor, and separately compares their spatial positions. These are appearance and geometry cues. They require no decision about whether the location is part of a dog, a vehicle or the background. The class scores that are being refined supply that semantic information.

The two comparisons are written as separate expressions.

```
κᵢⱼ,ₖₗ(rgb) = −(|Iᵢⱼ − Iₖₗ| / (w₁σᵢⱼ(rgb)))²
```

The symbol κᵢⱼ,ₖₗ(rgb) is the color comparison score from the location at row i and column j to the location at row k and column l. The parentheses marked rgb distinguish the color quantity. Iᵢⱼ and Iₖₗ are the RGB values at those locations, and the vertical bars denote the magnitude of their difference as written by the authors. The quantity σᵢⱼ(rgb) is the standard deviation of color differences associated with the center location. The weight w₁ controls the smoothness of the color comparison. The negative square makes a larger scaled difference yield a lower score.

```
κᵢⱼ,ₖₗ(pos) = −(|Pᵢⱼ − Pₖₗ| / (w₂σᵢⱼ(pos)))²
```

The symbol κᵢⱼ,ₖₗ(pos) is the position comparison score for the same locations. The pos marker identifies the positional quantity. Pᵢⱼ and Pₖₗ contain their spatial coordinates, which the implementation represents with XY positions. The vertical bars denote the magnitude of the coordinate difference. The quantity σᵢⱼ(pos) is the standard deviation of positional differences for the center, and w₂ controls the smoothness of this comparison. The negative square gives closer positions a higher score for a fixed scale.

A small difference in color makes a neighbor more compatible under the RGB term. The positional term provides an additional preference for nearby locations. This matters when the neighborhood contains points sampled at different distances. The paper normalizes each comparison over the neighborhood, then adds the resulting weights with a separate coefficient for position.

```
κᵢⱼ,ₖₗ = exp(κᵢⱼ,ₖₗ(rgb)) / ∑₍ₓ,ᵧ₎ exp(κᵢⱼ,ₓᵧ(rgb))
        + w₃ exp(κᵢⱼ,ₖₗ(pos)) / ∑₍ₓ,ᵧ₎ exp(κᵢⱼ,ₓᵧ(pos))
```

The combined weight κᵢⱼ,ₖₗ indicates how much the neighbor at row k and column l contributes to the update at row i and column j. In each fraction, exp is the exponential function. The numerator uses the comparison score for the chosen neighbor, and the denominator sums exponential scores over the candidate neighbor locations, indexed by x and y. The rgb and pos markers distinguish the terms normalized by color and position. The weight w₃ sets the contribution of the already normalized position term. The equation adds that scaled distribution to the normalized color distribution.

With these weights, the map update simply gathers the scores from nearby locations. The paper repeats the update so that a location can benefit from information that has already been incorporated by its neighbors.

```
Mₜ(i,j,c) = ∑₍ₖ,ₗ₎∈𝒩₍ᵢ,ⱼ₎ κᵢⱼ,ₖₗ Mₜ₋₁(k,l,c)
```

Mₜ(i,j,c) is the updated class score at row i and column j for class c in iteration t. The sum runs over positions k and l in the neighborhood 𝒩₍ᵢ,ⱼ₎ of the center. Each term multiplies the neighbor’s score for that same class from the preceding iteration, Mₜ₋₁(k,l,c), by the weight κᵢⱼ,ₖₗ. The membership sign ∈ restricts the sum to the selected neighborhood. The update applies each neighbor weight to the class scores at that location without mixing different class channels.

PAR uses the 8-way neighborhood at multiple dilation rates. Dilation changes the spacing between the center and the sampled locations, so that the operation can reach farther while keeping the directional sampling pattern. The authors implement the extraction with 3 × 3 dilated convolutions and use the rates [1, 2, 4, 8, 12, 24]. They set the color scale w₁ to 0.3, the position scale w₂ to 0.3, and the relative weight w₃ for position to 0.01. The neighborhood operation is intended to be practical inside training, which is why the authors choose it in place of running a dense conditional random field each time a provisional target is needed.

#### Choose pairwise targets and fit affinity

The first PAR pass gives the method a better starting point for selecting locations it can treat as foreground or background. AFA needs examples of agreement and disagreement between locations, so one wrong class guess could affect several pairwise targets. The authors address this by requiring stronger evidence to make a foreground assignment and weaker evidence to make a background assignment, leaving a band of scores between the cutoffs unused.

```
Yₚ(i,j) = {
  argmax M(i,j,:)   if max M(i,j,:) ≥ βₕ
  0                 if max M(i,j,:) ≤ βₗ
  255               otherwise
}
```

Yₚ(i,j) is the provisional label at row i and column j. M is the class activation array, refined by PAR at this point in the training procedure. The colon selects the class axis at the indicated location, and max gives the strongest score on that axis. The expression argmax returns the category that supplied that score. The symbol βₕ is the upper background threshold, and ≥ includes a score equal to that cutoff in the foreground case. The symbol βₗ is the lower threshold, and ≤ includes a score equal to it in the background case. The value 0 identifies background, and 255 marks a location to ignore. The authors use 0.55 for the upper cutoff and 0.35 for the lower one.

If two retained locations carry the same provisional label, their target affinity is positive. That rule includes pairs whose locations are both assigned background. A pair with different labels gives a negative target. A pair is left out if either location has the ignore label. The rule asks for equality of semantic labels, which is a different criterion from whether the two locations belong to the same individual object. It can also assign a wrong pairwise target when a provisional category is wrong. The confidence screening reduces the opportunities for that error.

The authors also restrict the affinity loss to pairs inside a local window and use radius 8 in the main configuration. The restriction determines which predictions are evaluated in the loss. The implementation applies a mask over the pairwise entries, instead of extracting separate lists of image patches for every center location. Local supervision uses pairs that the authors consider easier to judge reliably from an incomplete mask. The attention representation still gives the affinity predictor access to relationships beyond the pairs selected for that loss.

The input to the affinity predictor is the collection of attention channels. A score from one location to another can differ from the reverse-direction score. The paper adds the two directions within each channel so that the affinity function receives the same input for the pair regardless of order.

```
A = MLP(S + Sᵀ)
```

A is the predicted semantic affinity matrix. S is the stacked attention tensor, and Sᵀ transposes the two spatial axes in each channel without exchanging the channels themselves. The addition gives each ordered pair the sum of the scores in both directions. MLP denotes the layer that combines those channel values. The authors describe the affinity prediction as a learned linear combination of the symmetrized attention channels. The resulting affinity is symmetric because reversing the pair leaves the layer’s input unchanged.

A learned combination can give a channel substantial influence, a small influence, or influence of the opposite sign. Symmetry alone would not determine the importance of any channel. The provisional pair labels supply that information through a loss that separately averages errors for positive and negative pairs.

```
ℒₐff = (1/N⁺) ∑₍ᵢⱼ,ₖₗ₎∈ℛ⁺ [1 − sigmoid(Aᵢⱼ,ₖₗ)]
     + (1/N⁻) ∑₍ᵢⱼ,ₖₗ₎∈ℛ⁻ sigmoid(Aᵢⱼ,ₖₗ)
```

The symbol ℒₐff is the affinity loss. Aᵢⱼ,ₖₗ is the prediction for the locations at row i and column j and at row k and column l. The sigmoid function maps a raw score to a value between 0 and 1. The set ℛ⁺ contains the positive pairs, ℛ⁻ contains the negative pairs, and ∈ restricts each sum to its indicated set. N⁺ and N⁻ are the counts of pairs in the respective sets. The first average penalizes positive pairs whose sigmoid score falls below 1. The second penalizes negative pairs whose score is high.

The separate averages mean that the weight given to a sign of supervision does not rise just because that kind of pair is more common. This matters when many locations share a broad background region. The loss can also influence the attention that supplied A, since the affinity scores depend on the attention channels. Consequently, the authors evaluate the module both as a way to learn links for propagation and as supervision that can improve the features and initial masks upstream.

#### Propagate the initial maps and refine them again

The affinity prediction supplies the weights for redistributing the category evidence. A location should gain support when it has strong links to other locations that already carry the category. A strong activation with little support from its linked locations can lose influence. The authors implement the redistribution using a transition matrix for a random walk, following earlier work on weakly supervised segmentation.

```
Dᵢᵢ = ∑ₖ (Aᵢₖ)ᵅ
```

Dᵢᵢ is the diagonal entry associated with flattened spatial location i in the diagonal normalization matrix D. The sum runs over flattened destination locations k. Aᵢₖ is the learned affinity between i and k. The exponent α is a setting used to emphasize strong affinities relative to weak affinities. The paper requires α to exceed 1 and uses 2 in its experiments.

```
T = D⁻¹Aᵅ
```

T is the transition matrix. Aᵅ denotes the entrywise power of the learned affinity matrix A. D⁻¹ is the inverse of the diagonal matrix D, so multiplication by it divides each powered affinity row by the sum for that row. The resulting row weights determine the contribution of locations in the propagation update. Row normalization is a separate operation from making the original affinities symmetric. Two locations can have the same affinity in either direction while having different total affinity to all other locations.

```
Mₐff = T × vec(M)
```

Mₐff is the propagated activation array, with its spatial locations represented on a flattened axis. T is the transition matrix, and vec flattens the spatial axes of the initial class activation maps M so that every category retains a column of scores. The × denotes matrix multiplication. For every class, the output at a location is a weighted combination of input scores, with the weights determined by the corresponding transition row.

The two PAR passes serve different uses. The earlier pass helps determine which provisional labels should supervise the affinity predictor. The propagation equation uses the initial class maps and the learned affinities; the later PAR pass then improves the local alignment of the propagated class scores before they supervise segmentation. A region can thus pick up support from semantically related locations through attention-derived affinity and still have its boundary adjusted using local color and position.

#### Train the branches together

The image tag directly supervises classification. The paper reports a multi-label soft-margin objective on the category probabilities produced from pooled features. Its displayed expression is reproduced with the sign as printed.

```
ℒ꜀ₗₛ = (1/C) ∑ᶜ⁼ᶜᶜ⁼¹ [yᶜ log(p꜀ₗₛᶜ) + (1 − yᶜ) log(1 − p꜀ₗₛᶜ)]
```

The sum is over category index c from 1 to C, where capital C is the number of categories averaged in the classification objective. The classification term is ℒ꜀ₗₛ. The value yᶜ is the image tag for category c and p꜀ₗₛᶜ is its predicted probability. The function log is the logarithm. The first term supplies the log probability for a present class and the second supplies the log probability for an absent class. The prefactor averages the terms over categories. As written, the expression is a mean log likelihood. Under loss minimization, the usual sign for the stated classification objective would be its negative. The displayed expression and the paper’s description therefore leave a sign ambiguity.

The segmentation branch uses cross-entropy to compare its dense class predictions with the final provisional labels. Cross-entropy penalizes low probability on the category specified by the target. The affinity branch uses the pairwise loss above. The paper also includes a regularization loss that encourages local consistency in the segmentation predictions themselves. This regularizer and PAR act on different quantities. PAR modifies the provisional targets, while the regularizer applies to the predictions being trained against those targets.

```
ℒ = ℒ꜀ₗₛ + λ₁ℒₛₑg + λ₂ℒₐff + λ₃ℒᵣₑg
```

The symbol ℒ is the total objective. The term ℒ꜀ₗₛ is the classification contribution, ℒₛₑg is the segmentation cross-entropy, ℒₐff is the pairwise affinity loss, and ℒᵣₑg is the local-consistency regularizer. The coefficients λ₁, λ₂ and λ₃ scale the segmentation, affinity and regularization terms in that order. The main setup lists those coefficients as 0.1, 0.1 and 0.01. The supplementary weight study reports a different preference with a repeated coefficient subscript, so the main defaults give the clearest assignment of these values.

The encoder begins with weights pretrained on ImageNet-1k. The remaining parameters start from random initialization. The optimizer is AdamW, with a backbone learning rate beginning at 6 × 10⁻⁵ and decreasing each iteration according to a polynomial schedule. Other parameters use a learning rate 10 times the backbone rate. The weight decay factor is 0.01. The training procedure randomly rescales images over the range [0.5, 2.0], randomly flips them horizontally and takes crops of size 512 × 512. The batch size is 8.

On PASCAL VOC the schedule comprises 20,000 iterations, starting with 2,000 iterations of classification warm-up and then 4,000 of affinity warm-up. On MS COCO it comprises 80,000 iterations, with 5,000 for classification warm-up and 15,000 for affinity warm-up. The ordering follows the dependencies between targets. The classifier first becomes a plausible source of spatial class scores. Then the affinity branch learns from selected pairs before its output is used to supply the segmentation branch with propagated supervision. The authors make the implementation available under the name AFA.

### Experiments and results

#### Datasets and what the metric measures

The authors use two datasets for evaluation, PASCAL VOC 2012 and MS COCO 2014. PASCAL VOC has 21 semantic categories including background. The training data is augmented with SBD, and the paper gives 10,582 training images, 1,449 validation images and 1,464 test images. MS COCO has 81 categories, with 82,081 training images and 40,137 validation images. For the weakly supervised training on both datasets, the supplied annotations are image-level category labels. The evaluation of final segmentation uses spatial annotations to determine how well the predicted areas agree with the labeled areas.

The default measure is mean intersection over union, abbreviated mIoU. For a category, the intersection is the area assigned that category in both the prediction and the annotation. The union is the area assigned that category in either one. A region the prediction leaves out reduces the overlap, and an extra region included by the prediction increases the union without increasing the intersection. Mean intersection over union averages the category-level overlap scores. It can be used to assess the training masks as well as the final segmentation output, provided that the object being scored and the split are identified.

This distinction matters in the paper’s experiments. The segmentation branch produces a prediction after being trained on generated targets. It is scored against annotated masks on validation or test images. A provisional mask is itself another candidate to be compared against annotated regions, which the authors do to diagnose its quality on training and validation images. A provisional-mask score and a segmentation score may look similar numerically while measuring different outputs. In particular, a score on PASCAL VOC training masks cannot establish the accuracy of a segmentation prediction on validation images.

#### PASCAL VOC 2012

The reported final validation result is 66.0% mIoU. That configuration includes conditional random field post-processing, abbreviated CRF. A CRF here is an operation applied to the segmentation output to improve spatial consistency after prediction. Before that step, the configuration with PAR, AFA and the auxiliary regularizer scores 63.8% mIoU on the same validation split. The paper attributes a further 2.2% mIoU improvement to CRF post-processing. The numerical comparison below shows how the final result relates to the authors’ own Transformer baseline and the intervening configurations.

Segmentation mIoU by configuration on PASCAL VOC 2012 validation Validation overlap improves as the authors add refinement, learned affinity, regularization and post-processing.

**The numbers**

| System or setting | mIoU % |
| --- | --- |
| Transformer baseline | 46.7 |
| With Pixel-Adaptive Refinement | 56.2 |
| With learned affinity added | 62.6 |
| With auxiliary regularization added | 63.8 |
| With CRF post-processing (this paper) | 66.0 |

The external comparison covers the PASCAL VOC validation and test sets. The paper reports that the proposed system surpasses earlier end-to-end competitors and is competitive with multi-stage systems including CDA, SC-CAM, SEAM and OAA+. These are comparisons between complete training and prediction pipelines. The comparison distinguishes image-level supervision from full supervision and from settings that use saliency maps as an additional cue. Those distinctions affect what information a training procedure receives, even when all predictions are scored against the same evaluation masks.

One comparison keeps the encoder choice close by running RRM with MiT-B1. The paper reports that its method still comes out ahead of this implementation, which supports a contribution from the new treatment of provisional labels beyond choosing a Transformer encoder. Other compared systems use different backbones. The labels R101 and WR38 in the paper refer to ResNet101 and WideResNet38, respectively. The earlier work associated with the ResNet comparison is [Deep Residual Learning for Image Recognition](https://md.research.elamur.ai/free/en/papers/he-2015-deep-residual-learning-image-recognition/).

The authors also compare each of several weakly supervised systems with a fully supervised counterpart. In the PASCAL VOC comparison, AFA reaches 83.8% of the segmentation performance of fully supervised SegFormer. The corresponding figures reported for 1Stage and AA&LR, with fully supervised WideResNet38 as their reference, are 77.6% and 79.1%, respectively. These figures express relative performance against the named counterparts. The sentence reporting them does not assign them individually to validation or test. The paper discusses category-level results on the PASCAL VOC validation set separately and says that its method leads the comparison for most categories. It also identifies the official PASCAL VOC evaluation as the source of its test results.

#### MS COCO 2014 and the visual comparisons

On the MS COCO 2014 validation set, the proposed system achieves 38.9% mIoU. The paper describes that result as ahead of most of the recent multi-stage approaches in its comparison. It identifies RIB as the exception. This matters because the authors are assessing whether a single training procedure can produce sufficiently good masks to compete with more elaborate pipelines. The COCO comparison shows that its advantage extends beyond PASCAL VOC within the evaluated settings, while leaving an example of a multi-stage approach that the reported score does not surpass.

The authors show predicted masks on validation images from both datasets. On PASCAL VOC, their side-by-side examples with 1Stage illustrate predictions that follow object outlines more closely. On COCO, the examples compare the prediction with the annotated mask and show areas of close agreement. Such pictures reveal whether a score is accompanied by a plausible-looking spatial correction, such as filling in an object or aligning a border. The validation mIoU aggregates agreement across the evaluation set. The pictured examples show how some of that agreement looks at the level of individual images.

### What the ablations show

#### What changes when components are added

The segmentation ablation on PASCAL VOC validation starts from the Transformer baseline at 46.7% mIoU. Adding PAR gives 56.2%, and the configuration with the proposed affinity module reaches 62.6%. The progression separates the contribution of improving local target consistency from the contribution of learning and using pairwise semantic links. The stages build on one another. In particular, the affinity module uses targets derived from the earlier refinement, so this sequence tests the effect of adding AFA in the proposed pipeline.

The auxiliary regularization loss takes the score to 63.8% mIoU on that split. It adds a local-consistency constraint on the predictions after the target-generating procedure is already in place. The final 66.0% mIoU includes CRF post-processing. This order helps identify what comes from the learned segmentation branch and what comes from modifying its output after prediction. It also clarifies the role of PAR in the paper’s efficiency argument. The authors avoid using a dense CRF repeatedly to build supervision during training while still showing the gain available from applying a CRF to the final output.

#### Does attention already work as affinity?

To address this question, the paper compares variants with no AFA, with the affinity training signal but without its random walk, and with the full module. The comparison without the walk is especially informative. AFA can change the attention and other learned features through the affinity loss, which can improve activation maps before an explicit redistribution of scores. On the PASCAL VOC training set, the authors report that the affinity loss improves provisional-mask mIoU from 54.4% to 66.3%. They report further improvements when learned-affinity propagation is used. The provisional-mask study includes both the training and validation splits.

The paper also runs the random walk using averaged, unmodified multi-head attention as its affinity source. That substitution reduces provisional-mask accuracy. Holding the idea of propagation in place while changing the source of the links addresses a central ambiguity in the method. If any broad mixing of class scores had produced the gain, averaging attention might have been sufficient. The observed drop shows that this particular untrained combination is a poor choice for deciding where to send the scores. The benefit depends on how the links are estimated.

The visual comparisons use a marked query location and display its relationships to other image locations. The authors compare an attention map from the last Transformer block with the learned affinity map for the query. An attention map can contain a rough indication of related regions while also responding strongly elsewhere. The learned map in their examples is more selective about semantically related locations. The paper shows the corresponding masks as well. With affinity supervision alone, the maps already look more coherent in the examples. With propagation added, scores can fill in regions linked by high affinity and recede where the links give little support.

In the supplementary analysis, the focus is on the coefficients learned for all eight heads in the final Transformer block. The heads receive unequal weights, and the contributions of head #2, head #3 and head #5 have a negative sign. Those signs describe coefficients in the learned combination. A single coefficient does not by itself say whether a particular pair of locations has negative affinity. The result does show that treating all heads as interchangeable would discard distinctions the fitted layer uses. Separate visualizations of attention with and without AFA also show how pairwise supervision can change what the encoder attends to.

#### What position adds to local refinement

The authors apply PAR to the Transformer baseline’s initial activation maps to see how much it can do at the mask level. The reported CAM comparison improves from 48.2% to 52.9% mIoU. This pair of values is reported for the CAM comparison without a split specified in the sentence that gives the values. The supplementary PAR configuration study separately identifies its evaluation split as PASCAL VOC training images. The authors report that PAR outperforms PAMR, a previous refinement method that also uses dilated, pixel-adaptive neighborhoods.

The experiments with matching dilation rates help isolate the position term. Both procedures can consult neighbors at the same spacings, so the improvement in that comparison is evidence for adding position information to the local weighting. A color comparison can favor a similarly colored neighbor farther away within the sampled neighborhood. The positional comparison supplies a separate spatial preference even when the colors are alike. In the paper’s visual examples, the combined refinement suppresses responses that extend into an incompatible area and makes the provisional masks follow visible boundaries more closely.

The supplementary study examines dilation, use of the position term, and the number of refinement iterations. These settings affect different parts of the operation. Dilation determines which locations can be consulted on an update. The position term changes their relative influence. Repetition allows a score altered at one location to be used in a subsequent update at another. The paper also varies the weights. It ties the color and position scale weights together in that study and favors 0.3 for each, with 0.01 for the coefficient on the normalized position term. This supports the chosen setting for the tested training-mask comparison.

#### Pooling, which pairs to trust, and loss weights

The pooling experiment asks how the classifier should aggregate locations when the ultimate aim is to recover spatial evidence. The authors evaluate activation-map mIoU on the PASCAL VOC training and validation sets while changing how much of each feature map is included in the pooled response. Their top-k pooling family averages a selected group of high responses. The underlying comparison spans the behavior of a maximum, which uses the strongest response, and an average over the whole grid.

The paper notes earlier observations that max pooling in convolutional classifiers tends to pick out too little of an object and average pooling can activate too much. In the Transformer configuration, the authors favor global max pooling. Their interpretation is that the strongest features can already incorporate information from other locations through self-attention. The strongest spatial response therefore need not depend solely on the content immediately around it. The measurement concerns the CAM produced from the trained classifier. Changing the pooling rule changes what the classifier learns to recognize and can affect the spatial map even though pooling itself returns a single value per feature channel.

The affinity-window study varies the radius of the pairs used to compute the affinity loss and evaluates the resulting segmentation on PASCAL VOC validation. With a small window, fewer pairs contribute to supervision. Broadening it adds examples, but the authors expect labels of distant pairs to be less reliable. They select radius 8 as a reasonable point in that tradeoff. The study is about the selection of supervised pairs. It does not test only a short-range form of self-attention.

The background-threshold study addresses a related tradeoff. A higher foreground cutoff and a lower background cutoff place more locations in the ignored band. That can make the surviving labels more reliable while reducing how many pairs can be used. Moving the thresholds closer together keeps more locations at the risk of including incorrect labels. The authors keep the average of the thresholds at 0.45 in this study, which they identify as their preferred background score in preliminary CAM experiments. By fixing that average, the comparison focuses on how much uncertainty to leave around the background decision.

The paper also varies the weights on the losses and evaluates final segmentation on PASCAL VOC validation. The main settings give the affinity term a weight of 0.1. In the supplementary discussion, a preferred setting lists 0.2 for the affinity coefficient, then uses the same subscript again for a value of 0.01. The total objective assigns distinct symbols to affinity and regularization. The supplementary line therefore gives evidence that the authors tried different balances, while the main setup remains the unambiguous account of its defaults.

### Limitations

#### Limits raised by the authors

The paper identifies the quality of the first masks as a condition for obtaining useful affinity supervision. The targets come from class scores inferred from image tags. Refinement and thresholding can make those targets more selective, but the availability of examples depends on the original classifier identifying usable regions. The authors schedule warm-up for this reason, first for classification and then for affinity. They also screen out uncertain locations. Their own threshold discussion explains the cost of strict screening. More certainty about an individual retained label can come at the expense of having enough locations to supervise useful pairs.

The authors raise a similar concern about spatial distance. Wider windows supply more pairs while raising doubts about the reliability of the extra targets. This is one reason the pairwise loss uses local windows even though the attention can carry information across a wider area. They also emphasize the limited reliability of raw attention as an affinity estimate. A classification encoder has a reason to associate regions that are useful together, which is broader than the same-category relation needed for label propagation. Their experiment with averaged attention shows a concrete consequence of using that broader relation as if it were a class agreement signal.

The paper presents PAR as a more practical operation for repeated use during training than a dense CRF. Its validation ablation also shows that CRF post-processing still improves the result. Thus the 66.0% PASCAL VOC validation result applies to the configuration with the additional prediction step. The paper gives the score before that step as well. The segmentation comparison should preserve this distinction when the purpose is to assess what the learned branch supplies by itself.

#### What follows from the experimental design

The evidence concerns supervision through image tags on two datasets, PASCAL VOC 2012 and MS COCO 2014, using an encoder whose initialization came from ImageNet-1k. The experiments establish what can be achieved without human-drawn training masks for those segmentation datasets under that initialization. They do not establish performance from random encoder weights, on other image collections, or with other annotation regimes such as scribbles and boxes. Those regimes appear in the paper’s account of the field. They are outside its experimental comparisons.

The final end-to-end result belongs to a combination of design choices. The encoder’s last stride changes, the classification branch uses a particular pooling rule, and the training procedure adds refinement, affinity supervision, propagation and regularization. The matched-backbone comparison with RRM helps address the effect of choosing MiT-B1, and the ablations isolate several additions within the authors’ implementation. They leave open whether different backbones would respond in the same way, or whether the same hyper-parameters would remain favorable on another dataset. Likewise, the reported practical advantage of a single training pipeline describes its organization. The results discussed in the paper do not quantify a complete runtime and resource comparison across the competing pipelines.

The learned affinity represents semantic agreement. That definition permits links between distinct objects with the same label, and its positive targets can connect locations labeled background. The experiments support using this relation for semantic masks. They do not establish that the affinities identify separate object instances or serve as a general measure of spatial correspondence. Local PAR has a related limit. Color and position are cues for aligning a boundary. Similar colors can occur on opposite sides of a semantic border, and the same object can have dissimilar colors. The method depends on class evidence and learned affinity to resolve cases in which appearance is insufficient.

Finally, the written method leaves a few implementation details to resolve. The classification expression is printed as a log likelihood although the prose describes a minimized loss, and the supplementary loss settings reuse a coefficient subscript. The propagation formulas also leave implicit the precise conversion, if any, between the affinity scores used with sigmoid in the loss and the affinities used to construct transition weights. The reported segmentation and mask scores are associated with the authors’ implemented procedure. Reproducing that procedure exactly requires resolving these points from the implementation.

### What came after

The paper identifies a direction for subsequent research in its conclusion. Pairwise category supervision can change the attention used to aggregate image features, so the authors see a possible role for it beyond generating better masks for this particular training procedure. Their experiments establish that connection in weakly supervised segmentation. They do not follow it into another task.

There are no documented follow-up works to discuss here. The paper’s comparisons with earlier segmentation and localization systems establish where its approach came from, while its experiments show how it uses their ingredients. Neither establishes which later systems adopted its affinity learning, its propagation procedure or its use of local refinement.

## Cite

Cite as Lixiang Ru, Yibing Zhan, Baosheng Yu and Bo Du. 2022. Learning Affinity from Attention: End-to-End Weakly-Supervised Semantic Segmentation with Transformers. 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/cvpr52688.2022.01634](https://doi.org/10.1109/cvpr52688.2022.01634) · [arXiv 2203.02664](https://arxiv.org/abs/2203.02664)

```bibtex
@inproceedings{ru2022learning,
  title = {{Learning Affinity from Attention: End-to-End Weakly-Supervised Semantic Segmentation with Transformers}},
  author = {Lixiang Ru, Yibing Zhan, Baosheng Yu and Bo Du},
  booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings - IEEE Computer Society Conference on Computer Vision and Pattern Recognition/Proceedings},
  year = {2022},
  doi = {10.1109/cvpr52688.2022.01634},
  eprint = {2203.02664},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1109/cvpr52688.2022.01634}
}
```

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