HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 8 of 25 — Generative AI Fundamentals
intermediate Chapter 8 of 25

Transformer Architecture Explained: Encoder, Decoder and Why It Powers GenAI

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

What Is Transformer Architecture in AI?

Transformer architecture is a neural network design that uses attention to decide which other positions in a sequence should influence each position's representation. An encoder builds contextual representations of an input, while an autoregressive decoder predicts the next token from a prefix. A transformer model can use an encoder, a decoder, or both, depending on its task.

Sequence modelling applies wherever order carries meaning: words in a sentence, events in a time series, audio frames, and tokens in source code. A recurrent neural network computes a hidden state h_t = f(x_t, h_(t-1)), so it needs the previous state before updating the current one. An LSTM uses gates to control what information persists, but its recurrent dependency remains. A signal from position 1 to position 100 still passes through successive state updates.

In a full self-attention layer, position 100 can read from position 1 directly if the mask allows that connection. Each position can compute its attention output from the same layer input, so hardware can process the positions in parallel. This makes training easier to parallelise across a sequence. It does not mean a trained model will reliably identify every distant dependency, and standard autoregressive generation still produces one token at a time per sequence because the next input depends on the token just selected.

How Does a Transformer Model Represent a Sequence?

Start with The cat is sitting on a chair. To make the shapes easy to see, suppose it becomes seven tokens: The, cat, is, sitting, on, a, chair. This is an illustrative split. Actual tokenization depends on the vocabulary and may encode spaces with tokens or split a word into several pieces. The tokenizer returns integer IDs, which act as row indices in the learned embedding table.

A seven-token example shows how token embeddings and position vectors combine into the input matrix X.
In this additive position scheme, each row of X combines a token embedding with its position vector.

With vocabulary size V and hidden width d_model, the token embedding table has shape [V, d_model]. Looking up seven rows gives a matrix of shape [7, d_model]. In an additive position scheme, the model adds a position vector to each row: x_i = E[token_id_i] + P_i. The resulting rows x₁ through x₇ form the input matrix X. For d_model = 512, this matrix contains 7 × 512 = 3,584 scalar entries. Including a batch axis gives the common layout [B, T, d_model].

The position signal matters because unmasked self-attention by itself is permutation equivariant. Shuffle the input rows and the output rows undergo the same shuffle; the operation has no independent notion of which word came first. An additive position scheme gives the same token different input vectors at different positions. The original Transformer used sinusoidal position vectors. Other models use learned position vectors or rotary position embeddings, which rotate query and key components rather than adding position vectors to the input. See multi-head attention and positional encoding for how those choices affect attention scores.

A token lookup is the same for every occurrence of a given ID. A contextual representation is different: it is the hidden state after attention and other block operations have incorporated context. In the river bank and the bank approved it, the same ID for bank, if the tokenizer assigns one, can produce different final hidden states.

How Does Encoder Decoder Architecture Work?

The original Transformer has two stacks. The encoder reads the source sequence and returns one hidden state per source position. The decoder reads a shifted target sequence during training or a generated prefix during inference. It can attend to the final encoder states at each decoder block. Source and target lengths may differ because cross-attention takes its queries from one sequence and its keys and values from the other.

An encoder and decoder diagram shows the encoder states entering decoder cross-attention as keys and values.
The decoder combines its target prefix with encoder states before scoring the next target token.
Model layoutAttention patternTypical output and useExample
Encoder-onlyBidirectional self-attention over valid input positionsContextual states for a task head, such as token labelling or classificationBERT
Decoder-onlyCausal self-attention over the prompt and generated prefixVocabulary logits at each position for text or code generationGPT, Llama
Encoder-decoderBidirectional encoder self-attention, causal decoder self-attention, and decoder cross-attentionTarget vocabulary logits conditioned on a separate source sequence, useful for translation and summarisationOriginal Transformer, T5

What happens inside an encoder block?

Each head of the attention mechanism projects its input into queries, keys and values: Q = XW_Q, K = XW_K and V = XW_V. For one head, Q and K have shape [T, d_k] and V has shape [T, d_v]. The operation softmax(QKᵀ / sqrt(d_k) + M)V produces an output of shape [T, d_v]. Softmax runs across the key positions for each query. The scale factor controls the typical growth of dot-product magnitudes with the head dimension; very large logits can make softmax saturate. The additive mask M is zero for allowed positions and negative infinity for blocked ones.

Different heads have separate learned projections. Their outputs are concatenated and projected back to d_model. A position-wise feed-forward network then applies the same learned transformation to each row, typically expanding the hidden width, applying a nonlinearity, and projecting back down. Attention mixes information across positions. The feed-forward network transforms features within each position independently.

The original block applies a residual addition followed by layer normalisation around each sublayer, written as LayerNorm(x + Sublayer(x)) when dropout is omitted. This is the Add & Norm shown in the original diagram. Many modern models normalise before the sublayer, as in x + Sublayer(Norm(x)). Both forms preserve an additive path for the block input, but the ordering changes the computation and where normalisation acts on that path.

What changes inside a decoder block?

First, causal self-attention lets target position i read only target positions j ≤ i. Second, in an encoder-decoder model, cross-attention projects queries from the decoder states and keys and values from the final encoder states. With target length T_tgt and source length T_src, the cross-attention score matrix per head is [T_tgt, T_src]. A target query can normally read all valid source positions, even if the decoder's own prefix is short. Third, the feed-forward network transforms each decoder row. A decoder-only block omits the encoder cross-attention sublayer.

After the final decoder layer, a linear vocabulary projection maps each hidden state to V logits. Softmax over those logits yields next-token probabilities. During training, cross-entropy is usually computed directly from the logits with a numerically stable log-softmax. During inference, a decoding rule such as greedy selection or sampling chooses a token, and the prefix grows.

For translation, suppose the source is The cat is sitting on a chair and the target begins Le chat. A simplified decoder training input is [BOS, Le, chat], with labels [Le, chat, EOS] for this shortened target. The row that reads BOS predicts Le; it cannot already read Le from the target sequence. All three rows can be computed in one forward pass because the reference prefix tokens are available and the causal mask blocks future ones. This training setup is called teacher forcing.

Worked Example: How Does Causal Self-Attention Change the Output?

Take one head with three positions and scalar queries, keys and values, so d_k = d_v = 1. Use Q = [1, 1, 1]ᵀ, K = [0, ln(2), ln(4)]ᵀ and V = [2, 4, 8]ᵀ. Every query initially scores the keys as [0, ln(2), ln(4)], since the scale factor is one. Exponentiating gives [1, 2, 4]. Apply the mask before the softmax so each row normalises over only the keys it can read.

Query positionScores after maskingSoftmax weightsWeighted sum of values
1[0, −∞, −∞][1, 0, 0]2
2[0, ln(2), −∞][1/3, 2/3, 0](2 + 8)/3 = 10/3
3[0, ln(2), ln(4)][1/7, 2/7, 4/7](2 + 8 + 32)/7 = 6

With no mask, all three rows would output 6 because their queries are identical. At position 2, the unmasked output would therefore depend on the value at position 3. During next-token training, that would let the representation read information from the very token it is supposed to predict. With a causal mask, changing the third value from 8 to 80 leaves the first two outputs unchanged. This prefix invariance should hold for the whole decoder when every block respects causality.

How Do You Build a Transformer Block in PyTorch?

The model below makes the main operations visible: token and position lookup, query/key/value projection, causal masking, residual paths and next-token loss. It uses one pre-normalised decoder block, four attention heads, learned absolute positions and GELU. It assumes fixed-length, unpadded examples. The small batch uses integer token IDs directly so you can run it without downloading a tokenizer or model.

import torch
from torch import nn
from torch.nn import functional as F

torch.manual_seed(7)


class TinyDecoder(nn.Module):
    def __init__(self, vocab=32, width=64, heads=4, max_len=32):
        super().__init__()
        assert width % heads == 0
        self.heads = heads
        self.head_dim = width // heads
        self.token = nn.Embedding(vocab, width)
        self.position = nn.Embedding(max_len, width)
        self.norm1 = nn.LayerNorm(width)
        self.qkv = nn.Linear(width, 3 * width)
        self.attn_out = nn.Linear(width, width)
        self.norm2 = nn.LayerNorm(width)
        self.ff = nn.Sequential(
            nn.Linear(width, 4 * width), nn.GELU(),
            nn.Linear(4 * width, width),
        )
        self.final_norm = nn.LayerNorm(width)
        self.lm_head = nn.Linear(width, vocab, bias=False)

    def forward(self, ids):
        b, t = ids.shape
        pos = torch.arange(t, device=ids.device)
        x = self.token(ids) + self.position(pos)

        # Each of q, k, v has shape [B, heads, T, head_dim].
        q, k, v = (
            self.qkv(self.norm1(x))
            .reshape(b, t, 3, self.heads, self.head_dim)
            .permute(2, 0, 3, 1, 4)
            .unbind(dim=0)
        )
        scores = (q @ k.transpose(-1, -2)) / self.head_dim**0.5
        future = torch.ones(t, t, dtype=torch.bool, device=x.device).triu(1)
        weights = scores.masked_fill(future, float("-inf")).softmax(dim=-1)
        context = (weights @ v).transpose(1, 2).reshape(b, t, -1)
        x = x + self.attn_out(context)
        x = x + self.ff(self.norm2(x))
        return self.lm_head(self.final_norm(x))


model = TinyDecoder()
opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
seq = torch.tensor([[1, 5, 9, 2], [1, 7, 8, 2]])
inputs, labels = seq[:, :-1], seq[:, 1:]
logits = model(inputs)  # [2, 3, 32]
loss = F.cross_entropy(logits.reshape(-1, 32), labels.reshape(-1))
opt.zero_grad()
loss.backward()
opt.step()

# Changing a suffix must leave logits for the shared prefix unchanged.
model.eval()
with torch.no_grad():
    a = model(torch.tensor([[1, 5, 9]]))
    b = model(torch.tensor([[1, 5, 17]]))
torch.testing.assert_close(a[:, :2], b[:, :2])
print(logits.shape, loss.item())

In the first sequence, the input [1, 5, 9] is paired with labels [5, 9, 2]. Flattening the batch and time axes gives six vocabulary distributions to score against six labels. Cross-entropy averages the negative log probabilities of those labels; the model does not need an explicit vocabulary softmax before the loss. The attention softmax is separate and runs over key positions inside each head. Confusing these two axes is a common implementation error.

The suffix test checks the mask through the entire block. If you remove the masking operation, the prefix rows can read token 9 in one sequence and token 17 in the other, so their logits will generally differ. For a larger implementation, PyTorch's F.scaled_dot_product_attention can take is_causal=True for this unpadded case and may select a fused kernel. The explicit matrix here makes the mask easy to inspect. A single optimiser step demonstrates the mechanics; it does not train a useful language model.

Why Do Transformers Power Generative AI?

Transformers combine a short path between eligible positions with matrix operations suited to GPUs and TPUs. Given a training sequence, a causal language model can compute logits at all positions in parallel within each layer and backpropagate from many next-token targets in one step. Layers still run in stack order. The chapter on pretraining, training and inference explains how repeating this update across large datasets turns the same local objective into a general-purpose model.

The cost of full self-attention limits that parallelism at long sequence lengths. Across heads, computing scores and mixing values takes work on the order of T² × d_model per layer when the combined head width is d_model. The simple implementation materialises T × T scores per head. Doubling T makes that matrix four times as large. Memory-efficient kernels can avoid storing the full score matrix without changing the quadratic arithmetic of exact dense attention. Even when a position can attend to distant tokens, the model may still fail to use the relevant evidence.

At inference, decoder-only systems typically process the prompt in a parallel prefill pass, then generate tokens in serial steps for each request. A key-value cache stores earlier keys and values per layer. Each newly processed position can then read those cached entries without recomputing the whole prefix. With full attention, the number of cached entries and the work of attending to them per new token still grow with prefix length. That distinction helps explain why both prompt length and generated length affect latency and why the context window and sampling parameters matter for deployment.

The same attention operation accepts vectors derived from text tokens, image patches, or audio frames. An application can change the input representation, mask and prediction objective while keeping the underlying block design. GPT and Llama illustrate causal text generation, BERT illustrates bidirectional text encoding, and Gemini models illustrate multimodal use. A transformer component does not imply a next-token objective: classic Stable Diffusion uses a U-Net denoiser with attention and a transformer-based text encoder, while some diffusion systems use a transformer as the denoiser itself. The chapter on diffusion models explains why the denoising process differs from autoregressive decoding.

Key Takeaways

  • Self-attention lets positions read directly from other eligible positions instead of routing all information through successive recurrent states.
  • Token embeddings represent token IDs, while positional information helps the model distinguish order and distance.
  • Encoders usually use bidirectional attention. Autoregressive decoders use causal attention, and encoder-decoder models add cross-attention to the source.
  • Attention mixes information across positions; the feed-forward network transforms each position independently.
  • Shifted targets and a causal mask let next-token training compute many predictions in parallel without future-token leakage.
  • Full attention has quadratic work in sequence length. A key-value cache saves prefix recomputation during generation, but each request still grows token by token.

Frequently Asked Questions

What is a transformer in AI, in simple terms?

A transformer is a neural network that updates each position by combining information from other permitted positions. It uses learned query and key projections to score those positions, then uses the scores to weight their values. Several layers repeat this process, producing contextual states that can support tasks such as classification, translation or next-token prediction.

Is BERT a generative transformer like GPT?

BERT is an encoder-only transformer. Its masked language modelling objective trains it to recover hidden tokens using context on both sides. GPT-style models use a causal decoder to predict the next token from the prefix. BERT can fill in masked positions, but its standard architecture and pretraining objective differ from those used to generate a left-to-right continuation.

What is the difference between causal self-attention and cross-attention?

In causal self-attention, queries, keys and values come from the same sequence, and each query can read only its current and earlier positions. In encoder-decoder cross-attention, queries come from the decoder and keys and values come from the encoder. The decoder can normally read the full valid source sequence, regardless of its current target position.

Why can transformer training run in parallel while generation is sequential?

During teacher-forced training, the correct prefix tokens are already available at every position. A causal mask lets a single forward pass score all positions without exposing future tokens to earlier predictions. During standard generation, the token chosen at one step becomes part of the input for the next step, so those steps depend on one another.

Does a larger context window make a transformer better at long-range reasoning?

A larger context window allows more tokens to fit, so relevant evidence can remain available instead of being truncated. It does not ensure that the model will find that evidence, connect facts across distant positions, or ignore distractors. Evaluate long-context performance on the actual task, and vary where the evidence appears instead of testing only near the end of the prompt.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course