Reads, Shreejal Trivedi
Series: Transformers in Vision, part 1 of 12
S. Trivedi
6 Oct 2026

Attention Before Transformers — Score, Squash, Multiply

  1. 1Attention Before Transformers — Score, Squash, Multiply
  2. 2Query, Key, Value — Dot-Product Attention from Scratch
  3. 3Attention Is All You Need — The Transformer, Block by Block
  4. 4Attention Meets Pixels — Windows, Axes and the First Fully Attentional Networks
  5. 5DETR — Detection as Set Prediction, No Anchors and No NMS
  6. 6An Image Is Worth 16×16 Words — ViT, Patch by Patch
  7. 7DeiT — Training a Vision Transformer on ImageNet Alone
  8. 8Swin Transformer — Windows, Shifts and a Pyramid for Dense Prediction
  9. 9Convolutions Strike Back — Was It the Attention or the Recipe?
  10. 10Masked Autoencoders — Hide 75 %, Encode the Rest
  11. 11CLIP — Learning Pictures From the Words Next to Them
  12. 12Vision Transformers Today — May 2022 to October 2026, Year by Year

Summary

Three attention mechanisms from before the transformer, Bahdanau's soft search, the SE channel gate and the non-local block, read as one recipe: score each piece of the input, squash the scores into weights, multiply the weights back in. After this read you will know what is being scored in each of them and why the last one is already self-attention inside a CNN.

Table of Contents

  1. 1. The Template: Score, Squash, Multiply2
  2. 2. Bahdanau 2014 — Attention as a Soft Search2
  3. 3. Squeeze-and-Excitation — Attention over Channels3
  4. 4. Non-local Neural Networks — Pairwise Attention over Positions4
  5. 5. Three Mechanisms, One Recipe5
  6. 6. What Came Next5
  7. 7. References5
  8. 8. Connections5
TrivediInformational[Page 1]
S. TrivediOct 2026

Everybody says attention and means something slightly different. Before the transformer there were already three things called attention, and they look nothing alike on paper: one lives between an RNN encoder and decoder, one is a tiny MLP bolted on a ResNet block, one is an N×N matrix the size of a feature map squared. The problem statement of this read is to make them look alike, because they are.

Every attention mechanism before the transformer does the same three things: score how relevant each piece of the input is, squash the scores into weights, and multiply the weights back into the features. What changes between papers is what gets scored (a source word, a channel, a pair of pixels) and what the score is a function of.

features1. scoreeach piece2. squashinto weights3. multiplyback inweightedfeaturesthe features themselves ride along the skip and get multipliedBahdanau 2014a source wordagainst the decoder statesoftmax overthe source wordsweighted sum ofthe word annotationsSENet 2017a channel, from the pooledmeans of all channelssigmoid, one gateper channelscale the wholechannelNon-local 2017a pair of positions,from the content of bothsoftmax overall positions jweighted sum ofall positions1.2.3.
Fig. 1 The template every mechanism in this read follows, and what each of the three papers plugs into the three steps.

This is the first read of the Transformers in Vision series, so there is little to brush up on. Skim my write-up of Understanding Attention Modules: CBAM and BAM — A Quick Read if you have not: BAM and CBAM are the channel gate of Section 3 with a spatial gate next to it, and I will not re-derive them here. Residual blocks I assume you know. The maths is light but the numbers are many :)

1. The Template: Score, Squash, Multiply

Let me state the recipe once, so that every later section is just filling in blanks.

  • Score. For each piece of the input (a word, a channel, a position), one number saying how relevant it is relative to something: a decoder state, the other channels, another position.
  • Squash. Turn the scores into weights: a softmax across the pieces (weights compete and sum to 1) or an independent sigmoid per piece (gates in (0,1) that do not compete).
  • Multiply. Scale the features by their weights and, if the pieces are many, sum them up.

Watch the last column of Fig. 1. When the pieces are pairs of positions and the score depends on the content at both, the recipe stops being a gate and becomes a conversation.

2.1 The Bottleneck

The RNN encoder-decoder of 2014 read a sentence into one vector and wrote the translation out of it. The encoder must "compress all the necessary information of a source sentence into a fixed-length vector", and the authors "conjecture that the use of a fixed-length vector is a bottleneck" [BAHD14]. Their Fig. 2 is the evidence: BLEU drops steeply as sentences get longer.

The fix is to stop compressing. Keep every encoder state and let the decoder pick, at every output word, which source words to look at. The paper calls this a (soft-)search: the decoder "(soft-)searches for a set of positions in a source sentence where the most relevant information is concentrated" [BAHD14]. Think of a translator who keeps a finger on the source text and slides it along as they speak, instead of reading the page once and reciting from memory.

2.2 Let's Devise It Step by Step

Start from the plain encoder-decoder: the decoder state si is updated from the previous state, the previous word and one fixed context vector c, the same c for the whole sentence:

si=f(si−1,yi−1,c)(1)

The first change is tiny on paper and is the whole idea: let the context depend on i.

si=f(si−1,yi−1,ci)(2)

Now ci must be built from the encoder. A bidirectional RNN gives one annotation hj∈ℝ2n per source word (n = 1000 units each way, §4.2 of [BAHD14]), and ci is a weighted average of all of them. The three lines below are the template of Section 1 written out (Eqs. 5–6 of the paper and the alignment model under them):

eij=a(si−1,hj)=va⊤tanh(Wasi−1+Uahj)αij=exp(eij)∑k=1Txexp(eik)ci=∑j=1Txαijhj(3)
  • Score. eij says how well source word j matches the decoder's current state si−1∈ℝn. The paper calls a(·) the alignment model: a one-hidden-layer MLP with Wa∈ℝn×n, Ua∈ℝn×2n and va∈ℝn (App. A.1.2). Every (target step, source word) pair gets a score: Tx×Ty of them per sentence pair.
  • Squash. The softmax turns a row of scores into weights αij∈(0,1) that sum to 1 over the source words. Nothing is pooled or thrown away.
  • Multiply. ci∈ℝ2n is the average of the annotations under those weights, "the expected annotation" in the paper's words. Attention "relieve[s] the encoder from the burden of having to encode all information… into a fixed-length vector" [BAHD14].

2.3 The Numbers

Numbers are always satisfying to justify something. Table 1 of the paper is WMT'14 English→French test BLEU; models are named by the longest training sentence.

ModelBLEU
RNNencdec-50 (fixed vector)17.82
RNNsearch-30 (attention, trained on ≤ 30 words)21.50
RNNsearch-50 (attention)26.75
RNNsearch-50, trained longer28.45
Moses (phrase-based system)33.30

Table. 1 WMT'14 En→Fr test BLEU, from Table 1 of [BAHD14].

  • RNNsearch-30, which never saw a sentence longer than 30 words in training, beats RNNencdec-50. That is the bottleneck argument in one row.
  • Their Fig. 2: RNNsearch-50 "shows no performance deterioration even with sentences of length 50 or more".
  • Their Fig. 3 draws the αij matrices in grey-scale, source words on one axis, target words on the other: the first attention map, and every heat map in this series descends from it.

NOTE: The paper's word for these matrices is alignment. They are the weights αij, nothing more; reading them as "what the model looks at" in a causal sense is our habit, not theirs.

2.4 Where It Sits, and One Shortcut

Between the encoder and the decoder: the thing being compared is a decoder state, the things being averaged are encoder annotations.

NOTE: This is cross-attention, not self-attention. Nothing in the source sentence is scored against anything else in the source sentence yet.

A year later Luong, Pham and Manning asked whether the MLP in the score was needed and tried plain products (§3.1 of [LUON15]):

score(ht,h¯s)=ht⊤h¯s (dot),ht⊤Wah¯s (general)(4)

Same softmax, same weighted sum; only the first line of Eq. 3 changed (ht is the target state, h¯s a source state). File this away: the dot product is the bridge to the next read.

TrivediInformational[Page 1]
S. TrivediOct 2026

3. Squeeze-and-Excitation — Attention over Channels

3.1 Why Gate Channels?

A convolution mixes space and channels inside one local receptive field; nothing in a plain ResNet lets a layer use global context to decide which channels matter for this image. Squeeze-and-Excitation [HU17] calls the fix feature recalibration: "use global information to selectively emphasise informative features and suppress less useful ones" (§1), a gating mechanism (§3.2). The picture in my head is a mixing desk: one fader per channel, set after listening to the whole mix.

3.2 Let's Devise It Step by Step

Take the output of a residual branch, U∈ℝH×W×C, one map uc per channel. Eqs. 2–4 of the paper are the three steps:

zc=Fsq(uc)=1HW∑i=1H∑j=1Wuc(i,j)s=Fex(z,W)=σ(W2δ(W1z))x~c=Fscale(uc,sc)=scuc(5)
  • Squeeze. Global-average-pool each channel to a single number; z∈ℝC is a summary of the whole image, one entry per channel.
  • Excitation. A two-layer MLP looks at all C numbers at once and outputs one gate per channel: W1∈ℝ(C/r)×C squeezes to width C/r, δ is a ReLU, W2∈ℝC×(C/r) expands back, σ is a sigmoid, so s∈(0,1)C. The reduction ratio is r = 16.
  • Scale. Multiply every map by its gate. The scaled x~ goes on to the residual add.

Compare with Eq. 3 and two things have changed. The score for channel c depends on the whole input through z, not on a pair. And the squash is a sigmoid, so the C gates are independent: they neither compete nor sum to 1. All gates at 1 is the identity.

XresidualbranchUH × W × CSqueeze-and-Excitationz, C × 1C/rC × 1s, gatesglobal avg poolFCFCReLUX̃s_c · U_c, every channel scaled by its gateidentity skip
Fig. 2 An SE block inside a residual unit: squeeze U to a vector, a two-layer MLP with a sigmoid turns it into one gate per channel, the gates scale U before the skip connection is added.

Let's watch the gate work on a toy map of eight channels. Slide β and see the gates separate:

28
A gate per channel, applied to the whole channel. Rows are the 8 channels, columns the 16 positions of a 4×4 map. The middle column is the gate vector s; the real block gets it from a learned 2-layer MLP, here it is a sigmoid of how far each channel's mean sits from the others. β = 0 gives every channel 0.5; large β drives the gates to 0 or 1.

At β = 0 every gate is 0.5 and the block halves the whole map; as β grows the gates separate into a hard on/off per channel. The real block learns where on that axis to sit, per channel, per image.

3.3 The Numbers

How much does the gate cost? Eq. 5 of the paper counts the two FC layers over S stages, with Ns blocks and Cs channels in stage s (biases ignored):

#params=2r∑s=1SNsCs2(6)
  • One block at C = 256, r = 16. W1 is 256 × 16 = 4,096 weights, W2 is 16 × 256 = 4,096: 8,192 weights (2·2562/16) plus 272 biases. A 3×3 convolution at that width has 256 × 256 × 9 = 589,824 weights, so the gate costs 1.4 % of one conv.
  • SE-ResNet-50. Summing Eq. 6 over the four stages gives ≈ 2.5 M on top of ResNet-50's ~25 M, the ~10 % of §4 [HU17]; 63 % of it sits in the last stage, which is why the last-stage blocks can be dropped cheaply.
  • FLOPs barely move: 3.86 → 3.87 GFLOPs (+0.26 %).
Modeltop-1 err.top-5 err.GFLOPs
ResNet-50 (re-implementation)24.807.483.86
SE-ResNet-5023.296.623.87

Table. 2 ImageNet validation, single crop, from Table 2 of [HU17].

  • SE-ResNet-50 (6.62 top-5) "approach[es]" ResNet-101 (6.52) at half the FLOPs; SE-ResNet-101 (6.07) beats ResNet-152 (6.34) (§5.1 of [HU17]).
  • The reduction ratio hardly matters: Table 10 has r = 2 … 32 all between 22.25 and 22.72 top-1 error against 23.30 plain; r = 16 (28.1 M params) is the chosen balance.
  • Dropping the squeeze (Table 16) costs 22.93 vs 22.28: the global pooling does work, not just the MLP.
  • The SENet entry won ILSVRC 2017 with 2.251 % top-5 error.

3.4 Where It Sits

After the residual branch and before the add, once per block (Fig. 2). Along the depth (§7.2, their Fig. 7) the early gates are nearly the same for every class, the gates at SE_4_6 and SE_5_1 become class-specific, SE_5_2 saturates with most gates near 1, the identity, and SE_5_3 shows one pattern for every class up to a scale. The paper reads this as the last stage mattering least, hence the cheap removal above.

NOTE: SE is not self-attention. The gate depends on pooled statistics, not on pairs; it is a sigmoid, not a softmax; the C gates never compete. The paper's own words are "a simple self-gating mechanism" (§1) and "a lightweight gating mechanism" (§2) [HU17].

SE's channel gate plus a spatial gate is BAM and CBAM [PARK18] [WOO18]; everything about them is in Understanding Attention Modules: CBAM and BAM — A Quick Read.

TrivediInformational[Page 2]
S. TrivediOct 2026

4. Non-local Neural Networks — Pairwise Attention over Positions

4.1 Why Compare Every Position with Every Other?

"Convolutional and recurrent operations both process a local neighborhood… long-range dependencies can only be captured when these operations are applied repeatedly" [WANG17]: "computationally inefficient", prone to "optimization difficulties", and "messages need to be delivered back and forth between distant positions" (§1). The fix is a block in which every position reads every other position in one step, "a generalization of the classical non-local means" filter that averages similar patches from anywhere in the image. If SE is a mixing desk, the non-local block is a group chat: every pixel reads every other pixel's message and weighs it by how much it sounds like its own.

4.2 Let's Devise It Step by Step

Flatten the feature map to N positions (N=THW for video, HW for an image), each with a feature xi∈ℝC. Eqs. 1, 3 and 6 of the paper, in the embedded-Gaussian form:

yi=1C(x)∑∀jf(xi,xj)g(xj)f(xi,xj)=exp(θ(xi)⊤ϕ(xj)),C(x)=∑∀jf(xi,xj)θ(xi)=Wθxi,ϕ(xj)=Wϕxj,g(xj)=Wgxjzi=Wzyi+xi(7)
  • Score. Compare position i with every position j: embed both with 1×1 convolutions (Wθ,Wϕ∈ℝ(C/2)×C), take the dot product, exponentiate. Every ordered pair (i,j) gets a score that depends on the content at both ends.
  • Squash. Divide by the row sum C(x). The authors note that "(1/C(x))f becomes the softmax along j", so the whole thing is y=softmax(x⊤Wθ⊤Wϕx)g(x), "the self-attention form in [49]" [WANG17], and reference 49 is the transformer paper. That sentence makes this block the hinge of the series.
  • Multiply. Average the projected features g(xj)∈ℝC/2 under those weights, project back up with Wz∈ℝC×(C/2), add the input.

In matrix form (their Fig. 2): Y=softmax(θϕ⊤)G with θ,ϕ,G∈ℝN×C/2; the thing in the middle is N×N.

xN × CN = THWθ: 1×1φ: 1×1g: 1×1N × C/2C/2 × NN × C/2transposematmulN × Nsoftmaxover jf(x_i, x_j) / C(x)matmulyN × C/2W_z: 1×1BN, zero-initzz_i = W_z y_i + x_i — starts as the identity
Fig. 3 The non-local block (embedded Gaussian). θ, φ and g are 1×1 convolutions to C/2 channels; θφᵀ is the N × N affinity; the softmax runs along j; W_z brings y back to C channels before the skip.

Here is one row of that N×N matrix on a toy image. Slide the query along the middle row and watch who it listens to:

50.15
One pixel against every other pixel. A 24×24 toy image: a bright blob on the left (col 5), a mid-grey blob in the middle (col 12) and a copy of the bright blob on the right (col 19). The marked cell is the query; every cell is shaded by the weight the query gives it. Slide the query through the left blob and watch its far-away twin light up. Put it on the grey blob and the bright blobs win instead: a plain dot product rewards brightness, not sameness, which is why the paper puts learned θ and φ in front of it.

The temperature slider (the next read names this knob) stands in for the scale of θ and ϕ: small τ picks one or two positions, large τ averages the whole image. And the plain dot product rewards bright pixels rather than similar ones, which is what the learned Wθ,Wϕ are there to fix.

4.3 Does the Softmax Matter?

The paper tries four pairwise functions f (Table 2a, Kinetics top-1, one block on a ResNet-50 C2D): Gaussian exp(xi⊤xj) 72.5, embedded Gaussian 72.7, dot product with C(x)=N and no softmax at all 72.9, concatenation 72.8. Their conclusion: "the attentional behavior (due to softmax) is not essential" [WANG17].

NOTE: Only the embedded-Gaussian version is softmax attention. The dot-product version divides by N, has no softmax, and works just as well. "Non-local = self-attention" is true of one version out of four.

4.4 The Numbers

  • Parameters, one block on a 1024-channel map. Wθ,Wϕ,Wg: 3 × 1024 × 512 = 1,572,864; Wz: 512 × 1024 = 524,288; 2,097,152 ≈ 2.1 M.
  • The pairwise cost at the paper's size, T = 4 frames of 14 × 14: N = 784, so the affinity matrix has 784² = 614,656 entries (2.46 MB in fp32). θϕ⊤ costs 614,656 × 512 ≈ 315 M multiply-adds, multiplying by G another 315 M, the four 1×1 projections ≈ 1.64 G. Here the projections dominate, not the pairs; a 2×2 max-pool after φ and g (§3.3) cuts the pairs by 4× more.
  • Why nobody did this on pixels. At 224 × 224, N = 50,176 and N2=2.52×109 affinities: 10 GB in fp32 for one map. Attention Meets Pixels — Windows, Axes and the First Fully Attentional Networks starts from this number, so I say it once and stop.
Model (Kinetics, top-1)acc.
C2D ResNet-50 baseline71.8
+ 1 non-local block72.7
+ 5 blocks73.8
+ 10 blocks74.3
C2D ResNet-101 + 5 blocks75.1

Table. 3 Kinetics top-1 accuracy, from Table 2 of [WANG17].

  • One block on a ResNet-50 gives +0.9 on Kinetics; ten give +2.5.
  • On COCO (Table 5 of the paper, Mask R-CNN, one block) APbox goes 38.0 → 39.0 on ResNet-50 and 44.1 → 45.0 on ResNeXt-152, APmask 34.6 → 35.5 on ResNet-50, all for "<5 % computation" [WANG17].
  • Their Fig. 1 and Fig. 3 show the weights on video: the ball in the first frame is related to "the ball in the last two frames". Content found content, across time, in one step.

4.5 Where It Sits

  • Inside a residual unit, with the BN after Wz zero-initialised, so the block starts as the identity (zi=xi) and drops into a pre-trained network without disturbing it (§4.1). SE and non-local are plug-and-play for the same reason: they sit on a skip and begin as "do nothing".
  • Not everywhere. Table 2b puts one block in res2 / res3 / res4 / res5 and gets 72.7 / 72.9 / 72.7 / 72.3; res5 gains least because a 7 × 7 map leaves little to look at. The paper uses 1, 5 or 10 blocks in res3 and res4.
TrivediInformational[Page 3]
S. TrivediOct 2026

5. Three Mechanisms, One Recipe

Closing the loop on Fig. 1: in Bahdanau's attention the thing being compared (a decoder state) and the things being averaged (encoder annotations) come from two different sequences. In SE nothing is compared with anything; a summary of the whole input sets a gate per channel. In the non-local block both come from the same feature map, every position against every position, softmax across them. That is self-attention, running inside a ResNet months after the transformer paper, with the authors saying so. The next read gives the two things their proper names. Two? Actually three, thanks to a small trick with projections, but let's wait for that ;)

6. What Came Next

Luong showed that the score in Eq. 3 can be a plain dot product and nothing is lost. Vaswani and colleagues then asked what happens if the dot product is all you keep: no RNN, no convolution, just scores, a softmax and a weighted sum, run many times in parallel. That is Query, Key, Value — Dot-Product Attention from Scratch, and it starts where Eq. 4 and Eq. 7 leave off.

7. References

  1. [BAHD14] Bahdanau, Cho, Bengio. Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015.
  2. [LUON15] Luong, Pham, Manning. Effective Approaches to Attention-based Neural Machine Translation. EMNLP 2015.
  3. [HU17] Hu, Shen, Albanie, Sun, Wu. Squeeze-and-Excitation Networks. CVPR 2018.
  4. [WANG17] Wang, Girshick, Gupta, He. Non-local Neural Networks. CVPR 2018.
  5. [PARK18] Park, Woo, Lee, Kweon. BAM: Bottleneck Attention Module. BMVC 2018.
  6. [WOO18] Woo, Park, Lee, Kweon. CBAM: Convolutional Block Attention Module. ECCV 2018.

8. Connections

What this page builds on, cites or links to, and what points back at it. A plain box is a “builds on”; “cited” and “linked in the text” are the lighter links. Hover a box for a preview.

POINTS AT THIS PAGEREADQuery, Key, Value — Dot-ProductAttention from ScratchREADAttention Meets Pixels — Windows, Axesand the First Fully Attentional NetworksREAD · LINKED IN THE TEXTConvolutions Strike Back — Was It theAttention or the Recipe?PAPER · LINKED IN THE TEXTAttention Is All You Need — TheTransformer, Block by BlockThis pageTHIS PAGE POINTS ATPAPERUnderstanding Attention Modules: CBAMand BAM — A Quick ReadREFERENCE · CITEDNeural Machine Translation by JointlyLearning to Align and TranslateREFERENCE · CITEDEffective Approaches to Attention-basedNeural Machine TranslationREFERENCE · CITEDSqueeze-and-Excitation NetworksREFERENCE · CITEDNon-local Neural NetworksREAD · LINKED IN THE TEXTQuery, Key, Value — Dot-ProductAttention from ScratchREAD · LINKED IN THE TEXTAttention Meets Pixels — Windows, Axesand the First Fully Attentional Networks

Related

Go deeper

  1. Start with
    Read
  2. Paper
  3. Paper
  4. Paper
  5. Paper
  6. You are here
    Attention Before Transformers — Score, Squash, Multiply
    Read
  7. Then
    Read
  8. Paper
  9. Read
  10. Paper
  11. Paper
  12. Paper
  13. Paper
  14. Read
  15. Paper
  16. Paper
  17. Read
  18. Paper
  19. Paper
  20. Paper
  21. Paper
  22. Paper
  23. Paper
  24. Paper
  25. Paper

Go broader

<- Older [Page 5] Newer ->