72 min total

Computer Vision & OpenCV

Attention

Attention

Problem: traditional seq-to-seq models faced two challenges:

  • long range dependencies
  • bottle neck problem, encoder compresses all information in a single fixed length vector which is insufficient for long information dense sequences
  • sequential nature of model prevent parallelization
Sequence-to-sequence encoder and decoder

Each input word generates hidden vector in encoder these hidden vectors are passed sequentially and summarized into a single context vector.

Attention: a fancy name for weighted average, Allows model to focus on relevant parts of input sequence, dynamically re-weight the importance of input tokens for each output token

Sequence-to-sequence model with attention

Additive Attention/Bahdanau Attention

Worked additive-attention example

jWₛs₀ + WₕhⱼScore eⱼSoftmax weight
1[2, 3]1.9590.358
2[2, 1]1.7260.284
3[3, 2]1.9590.358

Additive attention: the full worked calculation

We are translating a sequence at decoder timestep i=1. The encoder has hidden states h₁=[1,0]ᵀ, h₂=[0,1]ᵀ, h₃=[1,1]ᵀ. The previous decoder state is s₀=[1,2]ᵀ. Let Wₛ=I, Wₕ=[[1,1],[1,−1]], and the attention vector v=[1,1]ᵀ.

For h₁:

For h₂:

For h₃:

Apply softmax to the three scores:

jScore e₁ⱼexp(e₁ⱼ)Normalized weight
11.9590827.0928150.358193
21.7256225.6160120.283613
31.9590827.0928150.358193

Multiply every hidden vector by its own attention weight, then add the vectors:

The notebook rounded scores and exponentials early, giving weights near [0.358,0.283,0.358] and context [0.716,0.641]. Retaining precision until the end gives the values above. The score, softmax, and weighted-vector steps are the same.

The similarity score uses the previous decoder state lᵢ₋₁ when forming the context for timestep i. The earlier conversion incorrectly changed this to lᵢ; the index is restored here.

Attention as weighted lookup

Box volume (cubic inches)Weight (pounds)
30030
40040

For a query volume of 360, inverse-distance scores are 1/60 and 1/40. Normalizing these scores gives weights 0.4 and 0.6.

This is an illustrative normalized similarity lookup, not the softmax dot-product rule used by a Transformer.

This predicts the weight of a box with volume 360 cubic inches using the two stored key–value pairs.

Attention scores and weighted values

Compare a query with each key, normalize the scores, and use the resulting weights to aggregate values. In self-attention a token can also attend to itself unless a mask excludes it.

Query, key, score, softmax, and weighted-value attention flow, clean redraw

Step 1 compares a query q with every input key kᵢ, including its own key in unmasked self-attention. Step 2 normalizes the scores jointly with softmax. Step 3 multiplies each value vᵢ by its weight aᵢ and sums the weighted values. Dot-product, scaled dot-product, and learned bilinear scores are alternatives; the scale uses the key/query dimension.

Self-Attention: Words must be understood in relation to others. Self-Attention builds composite representations by scoring and weighting word relations. This process influenced from key-value lookup in a database for each word. For a given query word q, self-attention is:

Matrices involved

Here token embeddings are columns. d is the embedding dimension, n the sequence length, and p the projection dimension.

In this column-oriented convention, each column is one projected token. d is the input embedding dimension, n is the number of tokens, and p is the projection dimension.

This conventional form uses tokens as rows. With column-oriented embeddings, transpose the corresponding matrix layout consistently.

Projection maps an embedding to a smaller learned representation. For example, a 512-dimensional token can be projected into 64 dimensions.

Queries, keys, and values are learned projections that let the model compare tokens and retrieve information in different representation spaces. Queries represent what a token looks for, keys determine how it can be matched, and values carry the information to aggregate.

A linear subspace is a subset of a vector space closed under addition and scalar multiplication. The notebook uses “subspace” informally for the smaller learned representations obtained by projection. A 512-dimensional embedding can be projected to a 64-dimensional representation. Separate learned projections let queries, keys, and values encode different views: what to look for, what a token offers, and what information to pass forward. These roles are learned jointly rather than being fixed semantic dimensions.

CNN–LSTM image-captioning architecture

Attention in Image Captioning

A CNN produces spatial image annotations a₁, …, aL, each of dimension d. The caption decoder attends to these locations when generating each word.

Visual attention maps over image regions

The CNN supplies L annotation vectors, one for each spatial location in its feature map. Each annotation has dimension d. The caption decoder selects a different weighted combination of these locations for each generated word.

Visual attention

The alignment network scores each image-region annotation aᵢ against the previous decoder state hₜ₋₁. Softmax normalizes the scores, and their weighted sum forms the visual context for the decoder.

Step 1: compute an alignment score between image-region annotation aᵢ and the previous decoder hidden state hₜ₋₁. Step 2: apply softmax over spatial locations, producing weights αₜᵢ in [0,1] that sum to one. Step 3: form the weighted sum of annotation vectors and pass that visual context to the decoder at time t.