Transformer Architecture Explained: How Attention Works, with PyTorch Code

Why Attention Replaced Recurrence

Before 2017, sequence models were dominated by RNNs and LSTMs. A recurrent model reads token one, updates a hidden state, reads token two, and so on. That design is strictly sequential, so training cannot be parallelized across the sequence, and information from early tokens has to survive dozens of hidden-state updates to reach later ones.

The transformer architecture, introduced in the 2017 paper “Attention Is All You Need” by Vaswani et al., replaces recurrence with self-attention: every token looks directly at every other token in a single step. Understand that, and the rest is scaffolding.

Self-Attention in Plain Words: Query, Key, Value

Take the sentence “the animal didn’t cross the street because it was too tired”. To resolve what “it” refers to, you check each other word and weigh how relevant it is. Self-attention does that with vectors.

Every token embedding is projected into three roles via learned linear layers:

  • Query (Q): what this token is looking for, like a search request.
  • Key (K): what each token offers, like the label on a file in a cabinet.
  • Value (V): the actual content each token carries.

Each query is compared against every key with a dot product, producing a score per token pair. High score means “this token is relevant to me”. Softmax turns the scores into weights that sum to one, and each token’s output is the weighted sum of all the values:

Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V

That division is the “scaled” in scaled dot-product attention. Without it, dot products grow with dimension, the softmax saturates onto a single token, and gradients die. The scaling keeps training moving.

Self-Attention in PyTorch

Here is the smallest working self-attention module. The comments annotate tensor shapes, because the shapes are where people get lost:

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

class SingleHeadAttention(nn.Module):
    def __init__(self, d_model):
        super().__init__()
        self.q = nn.Linear(d_model, d_model, bias=False)
        self.k = nn.Linear(d_model, d_model, bias=False)
        self.v = nn.Linear(d_model, d_model, bias=False)
        self.d = d_model

    def forward(self, x):
        # x: (batch, seq_len, d_model)
        Q, K, V = self.q(x), self.k(x), self.v(x)
        scores = Q @ K.transpose(-2, -1) / (self.d ** 0.5)
        # scores: (batch, seq_len, seq_len) - every token vs every token
        weights = F.softmax(scores, dim=-1)
        return weights @ V, weights

Feed it a toy input and inspect the weight matrix. Each row is one token, each column is how much that token attends to each other token, and every row sums to one:

torch.manual_seed(7)
attn = SingleHeadAttention(d_model=16)
x = torch.randn(1, 5, 16)          # 5 tokens, 16-dim embeddings
out, w = attn(x)
print(w.shape)                     # torch.Size([1, 5, 5])
print(w[0].sum(-1))                # tensor([1., 1., 1., 1., 1.])

With random weights the pattern is noise, but the mechanics show: parallel, fully connected, one step between any two tokens. Training teaches the Q/K/V projections which pairings matter.

Multi-Head Attention: Why One Head Is Not Enough

One head computes one relevance pattern. But tokens relate to each other in several ways at once: syntax, coreference, subject-verb agreement. Multi-head attention runs several heads in parallel, each with its own Q/K/V projections, then concatenates their outputs and projects back to the model dimension. Each head learns a different kind of relationship.

The original paper used d_model = 512 with 8 heads, so each head works in 64 dimensions. The reshape below runs all heads as one batched matrix multiply:

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, n_heads):
        super().__init__()
        assert d_model % n_heads == 0
        self.n_heads = n_heads
        self.head_dim = d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model)
        self.out = nn.Linear(d_model, d_model)

    def forward(self, x, mask=None):
        B, T, _ = x.shape
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        # (B, T, C) -> (B, T, H, D) -> (B, H, T, D)
        q = q.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
        k = k.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
        v = v.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
        scores = q @ k.transpose(-2, -1) / (self.head_dim ** 0.5)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, float('-inf'))
        weights = F.softmax(scores, dim=-1)
        out = weights @ v                       # (B, H, T, D)
        out = out.transpose(1, 2).reshape(B, T, -1)  # concat heads
        return self.out(out), weights

Learn this reshape-transpose pattern once; it shows up in every transformer codebase.

Positional Encodings: Giving the Model a Sense of Order

Self-attention treats the input as a set, not a sequence. Shuffle the tokens and the scores do not change. So the original paper adds position information directly to the token embeddings, using sine and cosine waves of different frequencies:

PE(pos, 2i)   = sin(pos / 10000^(2i / d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model))

Each position gets a unique vector, and nearby positions get similar ones. The model learns to read these patterns during training:

import math

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_len=512):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        pos = torch.arange(max_len).unsqueeze(1).float()
        div = torch.exp(torch.arange(0, d_model, 2).float()
                        * -(math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(pos * div)
        pe[:, 1::2] = torch.cos(pos * div)
        self.register_buffer('pe', pe.unsqueeze(0))

    def forward(self, x):
        # x: (batch, seq_len, d_model)
        return x + self.pe[:, :x.size(1)]

Modern models often use learned embeddings or RoPE instead, but this shows what position info is: a fixed coordinate system added before anything else runs.

The Transformer Block: Attention Plus Thinking Time

Attention mixes information between tokens. After mixing, each token still needs to process what it gathered. That is the position-wise feed-forward network: two linear layers with a nonlinearity between them, applied independently at each position. Two pieces of scaffolding make deep stacks trainable:

  • Residual connections: each sub-layer adds its output to its input (x + sublayer(x)) instead of replacing it, so gradients flow through dozens of layers and each block refines rather than rebuilds.
  • Layer normalization: applied after each residual addition to keep activations in a stable range.
class TransformerBlock(nn.Module):
    def __init__(self, d_model, n_heads, d_ff=2048, p=0.1):
        super().__init__()
        self.attn = MultiHeadAttention(d_model, n_heads)
        self.ln1 = nn.LayerNorm(d_model)
        self.ln2 = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.GELU(), nn.Dropout(p),
            nn.Linear(d_ff, d_model), nn.Dropout(p),
        )
        self.drop = nn.Dropout(p)

    def forward(self, x, mask=None):
        a, _ = self.attn(x, mask)
        x = self.ln1(x + self.drop(a))   # attention sub-layer
        x = self.ln2(x + self.ffn(x))    # feed-forward sub-layer
        return x

Tokens talk to each other, add what they learned, think privately, add that too. Stack this block N times (the paper used 6) and the representations grow richer.

Encoder, Decoder, and the Causal Mask

The full 2017 architecture has two stacks. The encoder reads the whole input sequence at once (a sentence to translate, say) and produces a rich representation. The decoder generates output one token at a time, and each of its blocks adds a second attention layer, cross-attention, whose queries come from the decoder while keys and values come from the encoder output. That keeps the generated words grounded in the source sentence.

The decoder has one strict rule: when predicting token five, it may only look at tokens one through four. Training enforces this with a causal mask, a lower-triangular matrix of ones:

T = x.size(1)
causal = torch.tril(torch.ones(T, T))   # 1 where attending is allowed
# [[1, 0, 0, 0],
#  [1, 1, 0, 0],
#  [1, 1, 1, 0],
#  [1, 1, 1, 1]]
block = TransformerBlock(d_model=64, n_heads=4)
out = block(x, mask=causal)             # token i sees only tokens <= i

Where the mask is zero, the code fills negative infinity before the softmax, which becomes an exact zero weight. No peeking at the future.

GPT-style models are decoder-only (masked blocks, next-token prediction); BERT-style models are encoder-only (unmasked bidirectional attention). The blocks are identical either way.

What to Build Next

You now own every piece: embeddings plus positional encoding, a stack of identical blocks, and a final linear layer for next-token prediction. Cement it with a tiny character-level language model trained on a few megabytes of text, then toggle the mask off and on and compare the outputs.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.