72 min total

Computer Vision & OpenCV

Transformers

Transformers
Transformer encoder–decoder architecture

Transformer: Is a seq-seq model based on self-attention that transforms input sequence into context aware token representations that model global and local dependencies. Originally made for translation.

The encoder converts input tokens into contextual representations using multi-head self-attention and a feed-forward network, with residual connections and layer normalization.

Transformer encoder

With n tokens and embedding dimension d_model, rows of X contain token embeddings plus positional information.

In the original post-normalization architecture, each sublayer is followed by a residual connection and layer normalization:

Encoder dimensions and the role of each operation

n is the number of tokens. Example embedding widths are 512, 768, and 1024; the selected width must be compatible with the head configuration.

QKᵀ contains a score for every token pair. Dividing by √dₖ controls score scale; very large logits can saturate softmax. Softmax normalizes each score row, and multiplication by V produces a weighted sum of value vectors.

For example, eight heads with d_model=512 use 64-dimensional keys and values per head. Twelve heads are another possible configuration when the width is chosen accordingly.

The output projection maps the concatenated heads back to the model width. Residual connections retain input information and provide a path for gradients. The same two-layer FFN is applied separately to every token position, in parallel; it does not flatten all tokens into one vector.

Both encoder sublayers preserve the n×d_model shape, so their residual additions are well defined.

Why Apply same FNN at every position?

  • Parameter sharing just like CNNs
  • Parallelization
  • Attention already lets each token see the entire sequence (global information), FNN refines what the token already knows by applying non-linear transformations

Why positional Encodings? Transformers don’t have recurrence, they treat each input token as a set (not sequence). We add positional information to each token embedding at that position

Sinusoidal positional encoding

For d = 6, the three frequency denominators are approximately 1, 21.5443, and 464.1589. Add the positional vector to each token embedding.

TokenPositionEmbedding
I0[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
love1[0.5, 0.4, 0.3, 0.2, 0.1, 0.0]
AI2[0.9, 0.8, 0.7, 0.6, 0.5, 0.4]
TokenEmbedding + positional encoding
I[0.10000, 1.20000, 0.30000, 1.40000, 0.50000, 1.60000]
love[1.34147, 0.94030, 0.34640, 1.19892, 0.10215, 1.00000]
AI[1.80930, 0.38385, 0.79270, 1.59569, 0.50431, 1.39999]

Positional encoding: every component

i2i/d with d=610000^(2i/d)
001
12/6 = 1/321.54434690
24/6 = 2/3464.15888336
PositioniDenominatorSine calculationCosine calculation
001.000000sin(0/1.000000) = 0.00000000cos(0/1.000000) = 1.00000000
0121.544347sin(0/21.544347) = 0.00000000cos(0/21.544347) = 1.00000000
02464.158883sin(0/464.158883) = 0.00000000cos(0/464.158883) = 1.00000000
101.000000sin(1/1.000000) = 0.84147098cos(1/1.000000) = 0.54030231
1121.544347sin(1/21.544347) = 0.04639922cos(1/21.544347) = 0.99892298
12464.158883sin(1/464.158883) = 0.00215443cos(1/464.158883) = 0.99999768
201.000000sin(2/1.000000) = 0.90929743cos(2/1.000000) = -0.41614684
2121.544347sin(2/21.544347) = 0.09269850cos(2/21.544347) = 0.99569422
22464.158883sin(2/464.158883) = 0.00430886cos(2/464.158883) = 0.99999072

For position zero, all three sine terms are zero and all three cosine terms are one. Each positional vector is added component by component to its token embedding.

Rounding is deferred until display; the source’s final “AI” vector had small rounding/arithmetic differences. The final vectors above use the stated embeddings and sinusoidal formula.

The autoregressive decoder attends to previous output tokens and, in an encoder–decoder model, to the encoder’s representations.

Transformer decoder

The decoder receives the previous output tokens, shifted right during training. Causal self-attention prevents a position from seeing future tokens.

In encoder–decoder cross-attention, queries come from the decoder and keys and values come from encoder outputs. A feed-forward sublayer follows, with residual connections and normalization around the sublayers.

Decoder-only models such as GPT omit the encoder and encoder–decoder cross-attention.

Decoder projections and shapes

Let N be the number of target tokens and S the number of source tokens. The input contains the previously generated targets, shifted right during training.

For a single head, Z_self has N×d_v entries. Concatenating heads and applying the output projection restores N×d_model before the next sublayer.

Cross-attention retrieves source information using queries from the decoder and keys/values from encoder memory. The decoder FFN then operates independently at each target position:

Each row of P is a distribution over the vocabulary for one target position. The next-token distribution determines the probabilities of the possible next words.

Adding −∞ to future positions before softmax gives them zero attention weight.

Attention: Umbrella term, means to focus on different parts of input data when producing an output.

Cross-Attention: one sequence uses its elements as queries to attend and extract relevant information from another sequence by using their keys and values

Self-Attention: elements of a single sequence attend to each other to gather contextual information before generating the output

Causal masks allow all target positions to be processed together during teacher-forced training without revealing future tokens. Autoregressive inference still generates successive tokens using the available prefix.

Sinusoidal positional encoding heatmap