Transformer Neural Networks Explained
Transformer Neural Networks
Transformer neural networks are a type of deep learning architecture originally designed for sequence-to-sequence tasks like machine translation. They form the foundation of modern large language models such as ChatGPT. This guide explains how a Transformer translates a simple English sentence into Spanish, covering every component from word embedding to decoding.
Word Embedding
Neural networks require numerical inputs, so the first step is converting words into numbers. The technique used is word embedding.
A simple neural network is created with one input node for each token in the vocabulary (words, word fragments, and special symbols like
EOSfor end of sentence).Each input is connected to a small number of activation functions (e.g., two) via weighted connections.
To embed a specific word, set its input to 1 and all other inputs to 0. The input values are multiplied by the weights, and the sums pass through an activation function (often the identity function for simplicity). The resulting outputs are the embedding numbers for that word.
The same set of weights is reused for every word in the input sentence. This allows the network to handle sentences of any length by simply copying the embedding unit for each word.
All weights in the Transformer are learned via backpropagation during training. Initially random, the weights are iteratively optimized using pairs of English sentences and their correct Spanish translations.
Word embedding converts each token into a dense vector of real numbers, enabling the neural network to process language.
Positional Encoding
Because word embeddings alone contain no information about word order, Transformers use positional encoding to keep track of where each word appears in the sequence.
Positional encoding works by adding a set of fixed pattern values to the word embedding of each token.
These values come from alternating sine and cosine functions of different frequencies. For each dimension of the embedding, a different frequency is used.
For example, the first dimension uses a slow sine wave, the second a slightly faster cosine wave, and so on. The position of a word determines the y‑axis value on each wave, giving a unique combination of numbers for each position.
Even though some individual values may repeat across positions, the combination across all dimensions creates a unique positional signature for each token.
The positional values are added element‑wise to the word embeddings. If the word order changes, the embeddings for the moved words change, while the positional values for their new positions remain fixed, allowing the Transformer to distinguish “Squatch eats pizza” from “pizza eats Squatch.”
Positional encoding adds a unique sequence of values to each word’s embedding based on its position, enabling the model to leverage word order.
Self-Attention
Self-attention is the mechanism that allows the Transformer to understand how words relate to each other within a sentence. For example, in “the pizza came out of the oven and it tasted good,” self-attention helps associate “it” with “pizza” instead of “oven.”
Queries, Keys, and Values
Self-attention works by computing three vectors for each token: query, key, and value. These are obtained by multiplying the position-encoded embedding by three separate sets of learned weight matrices.
Query for a word: used to compare against all other words.
Key for a word: used as a reference for similarity comparisons.
Value for a word: the actual information that will be weighted and summed.
Calculating Attention Scores
For each word, the similarity between its query and every key (including its own) is computed, typically using the dot product:
The raw similarity scores are passed through a softmax function, which converts them into a probability distribution (all positive, sum to 1). The softmax output indicates how much each word should influence the encoding of the current word.
The softmax weights are then multiplied by the corresponding value vectors, and the weighted values are summed to produce the self-attention output for that word.
Because self-attention uses the same weight matrices for all tokens, the computations for every word can be performed in parallel, enabling efficient processing on GPUs.
Illustration of Self-Attention
For a sentence “let’s go” (after positional encoding), self-attention might determine that “let’s” is more similar to itself than to “go.” Consequently, the self-attention output for “let’s” will be heavily influenced by its own value and very little by “go.” This contextual encoding enriches each word’s representation with information from the entire sentence.
Self-attention allows each token to attend to every other token, encoding contextual relationships within the input.
Multi-Head Attention
In practice, a Transformer uses not just one set of query, key, and value weight matrices, but multiple heads (often 8). Each head learns a different type of relationship among words. The outputs of all heads are concatenated and linearly transformed. This multi-head attention enables the model to capture diverse linguistic patterns.
Residual Connections
After each sub‑layer (such as self-attention), the input to that sub‑layer is added to its output. This is called a residual connection.
Mathematically: Output=SubLayer(Input)+Input.
Residual connections make training deeper networks easier by allowing gradients to flow directly through the network, preventing vanishing gradients.
They also free the sub‑layer from having to preserve the original embedding and positional information; the sub‑layer can focus solely on learning the relationships.
The Encoder
The encoder is the first half of the Transformer. Its job is to transform the input sentence into a rich, context‑aware representation.
Components of the encoder (in order):
Word embedding – convert each token to a vector.
Positional encoding – add position information.
Multi‑head self-attention – compute contextual relationships.
Residual connection – add input of step 3 to its output.
(Optionally, after self-attention, layer normalization is applied – see Additional Details.)
The output of the encoder is a sequence of vectors, one per input token, each encoding the meaning of that token in the context of the whole sentence.
The Decoder
The decoder generates the output sequence (e.g., the Spanish translation) based on the encoder’s output. It also starts with word embedding and positional encoding, but its structure is more elaborate.
Decoder Self-Attention (Masked)
The decoder first applies self-attention to its own generated output tokens (beginning with a special
EOSorSOStoken).However, during training, the decoder must not “see” future tokens. Therefore, masked self-attention is used: the similarity scores for positions after the current token are set to −∞ before softmax, so those tokens receive zero attention weight.
This preserves the autoregressive nature of generation.
Encoder-Decoder Attention
This is the critical component that allows the decoder to focus on relevant parts of the input sentence. It works similarly to self-attention, but:
The queries come from the decoder’s current representation.
The keys and values come from the encoder’s final output.
The dot product similarities between decoder queries and encoder keys determine which input words are most relevant for the next output word.
As a result, the decoder can attend to significant input words (e.g., “don’t” in “don’t eat the pizza”) and avoid omitting them in translation.
Encoder-decoder attention lets the decoder retrieve information from the input sequence, ensuring important content is preserved.
Fully Connected Layer and Output
After self-attention, encoder-decoder attention, and residual connections, the decoder’s representation for the current token passes through a fully connected (feed‑forward) network with one hidden layer. This network adds more capacity and is followed by a softmax layer.
The softmax layer has one output neuron for each token in the output vocabulary.
It converts the final decoder vector into a probability distribution over all possible output tokens.
The token with the highest probability is chosen as the next word in the translation.
Iterative Decoding
The decoder starts with a special start‑of‑sequence token (often
EOS).After generating the first word (e.g., “vamos”), that word is fed back into the decoder (with positional encoding for the second position), and the process repeats.
The decoder continues generating tokens until it outputs an
EOStoken, signaling the end of the translation.
Training and Weight Optimization
All weights in the Transformer (for embeddings, self‑attention, encoder‑decoder attention, fully connected layers, etc.) are learned through backpropagation.
Initially, weights are set to small random numbers.
For each training example (English sentence, Spanish translation), the Transformer computes its output.
The discrepancy between the output and the correct translation is measured by a loss function (e.g., cross‑entropy).
Gradients of the loss with respect to every weight are calculated, and weights are updated in the direction that reduces the loss.
This process is repeated over many iterations (epochs) until convergence.
Training optimizes all parameters to minimize translation error, enabling the Transformer to learn linguistic patterns.
Additional Details
Layer Normalization
In the original Transformer paper, layer normalization is applied after each sub‑layer (self‑attention, feed‑forward) and before the residual connection. Normalization stabilizes training by keeping the activation values within a consistent range, especially important for long sequences and large vocabularies.
Scaled Dot-Product Attention
The attention similarity is often computed as:
where dk is the dimension of the key vectors. Dividing by dk prevents the dot products from growing too large, which would push the softmax into regions with extremely small gradients, hindering training.
Feed‑Forward Networks
Both the encoder and decoder contain a fully connected feed‑forward network after the attention sub‑layers. This network applies the same transformation to each position independently and typically consists of two linear transformations with a ReLU activation in between. It increases the model’s capacity to learn complex transformations.
Stacking Layers
The original Transformer stacks 6 identical encoder layers and 6 identical decoder layers. Stacking allows the model to capture hierarchical patterns. The outputs of one layer become the inputs to the next, with residual connections between them.
Summary
The Transformer achieves sequence‑to‑sequence translation through the following core mechanisms:
Word embedding converts tokens to numerical vectors.
Positional encoding adds order information.
Self-attention captures relationships among words in the same sequence.
Multi-head attention learns diverse relational patterns.
Encoder-decoder attention aligns the output with the input.
Residual connections and layer normalization enable training deep networks.
A fully connected layer and softmax produce the final token distribution.
All weights are learned end‑to‑end using backpropagation. By processing tokens in parallel and reusing weight matrices, Transformers are both powerful and computationally efficient, forming the backbone of modern language models.

Ask anything
We've read this whole study set, so questions about it get the best answers.