
Encoder blocks
- Positional Encoding
Add context of positions in the sentence
inputs word embeddings
outputs positional embeddings
- Multi-head attention
generates attention vectors - Add and Norm
adds matrices
normalizes the layer - Feed Forward
The position-wise feed-forward network transforms each token representation between attention layers.
Residual paths and parallel computation

These 4 features allows transformers to
- Encode the words into numbers
- Encode position of words
- Encode the relationships of words
- Train quickly in parallel

Within a layer, embeddings, positional encodings, projections, attention outputs, and residual operations can be computed across token positions in parallel during training. Autoregressive generation still produces new tokens sequentially.
Residual connections
Purpose:
- Knowledge preservation, forward propagation modifies input considerably by time it reaches last layer. Results in loss of information
- To solve Vanishing gradient problem
Decoder blocks
- Masked Multi-head attention
attention block on decoder side, generates attention vector for every word in output language.
This attention vector represents how much each word in output sentence is related to every word in the same sentence
Decoders multi-head attention is masked to ensure each position only attends to previous positions
- Encoder decoder attention block
takes input from encoder and input from decoder's Masked attention block
Determines attention vector from input to output
Outputs attention vectors
- Linear layer
expands dimensions for output language - Softmax layer
transforms output into probablility distribution
word with highest probability is selected
Encoder decoder model is executed several time steps until we reach the end of sentence
Causal masking
To ensure that the prediction for a given position only depends on the positions before it, not on the future positions.


Cross-attention: connecting encoder and decoder

Make query for word 'x' in decoder
Create keys for each word in encoder
Calculate similarities between word 'x' and keys by calculating Dot products
We run similarities through SoftMax function
The softmax weights determine how strongly the decoder attends to each encoder position.


Ek Tareeqy se Encoder Decoder ki attention values ka bhi ek cell bnjata

We then pass the encoder decoder attention values to a fully connected layer, we get the output translation for let's go = vamos


Types of transformers
- Encoder only
BERT
code Bert
Med Bert - Decoder only
ChatGPT - Encoder Decoder
Text-to-Text transformer
Architecture reference: Attention Is All You Need