Article 2 : Inside a GPT Block: Attention, Position, and Stable Training
From the publisher’s feed, collected in the ZeroLabs newsroom.
When the original Transformer architecture was introduced in the seminal 2017 paper “Attention Is All You Need”, it was designed as a dual-component system consisting of an Encoder and a Decoder. The encoder processed the input text in parallel, while the decoder generated the output text token-by-token, relying on a complex sub-layer called Cross-Attention to look back at the encoder’s data.Modern Large Language Models (LLMs) like GPT, Llama, Mistral, and DeepSeek have stripped away this complexity. They utilize a streamlined, pure decoder-only architecture. By removing the encoder and the cross-attention mechanisms entirely, the model is optimized for a single, highly efficient task: predicting the next token in a sequence.Today, when engineers talk about a “Transformer block” or a “GPT block,” they are referring to this modern decoder-only variant.A decoder-only language model stacks dozens or hundreds of these blocks. Each individual block takes a sequence of vectors, gives tokens a chance to exchange information through self-attention, and then processes each token’s updated representation independently through a feed-forward network.In a small teaching model, we choose an embedding width d_model = 128. This represents the number of dimensions in which a token has been passed through a trained embedding model to get its vector representation. In layman’s terms, this means we attempt to comprehend 128 different features of a given token (which is not always a word or a character). We then use four attention heads (heads = 4), which parallelizes learning across four threads. This allows each head to learn its own set of weights independently.Once these features are learned, they are combined back together to pass through a feed-forward network, which first expands and then later contracts the representation to yield a final output of the exact same size. In a nutshell, we pass an embedding through these learning blocks to interpret its context relative to all other tokens in the sequence. In a production model, these architectural choices vary significantly; the numbers provided here are concrete examples rather than a universal recipe.1. High School Concept: Matrix Foundations & ProjectionsBefore exploring the core mechanics, let us review a foundational mathematical concept: a matrix represents data arranged in rows and columns.In an LLM, the input data matrix X has dimensions of (Context Length × d_model). For a production workload, this could mean a matrix of 32,000 × 512, where 32,000 is the context length (number of tokens) and 512 is the input embedding size.Matrix multiplication requires that the columns of the first matrix match the rows of the second matrix. Multiplying a matrix of size (A × B) by a matrix of size (B × C) yields a new matrix of size (A × C).For each embedding representation X, the layer applies learned linear projections to generate the Queries (Q), Keys (K), and Values (V):Q = X · WqK = X · WkV = X · WvHere, X is our input embedding matrix, which is multiplied by the learned weight matrices Wq, Wk, and Wv. These weights are initialized randomly (using frameworks like PyTorch via torch.tensor(requires_grad=True)) and are optimized during training via backpropagation.Concrete Mathematical ExampleLet our sequence length be 4 tokens and d_model = 4. Let the input matrix X be: X= [ 1 0 1 2 ] [ 0 2 1 0 ] [ 1 1 0 1 ] [ 2 0 2 1 ]Assume a learned query projection matrix Wq of size (4 × 4) looks like this: [ 1 0 1 0 ]Wq = [ 0 1 0 1 ] [ 1 -1 0 0 ] [ 0 1 1 -1 ]To find the Query matrix Q, we compute X × Wq. For example:Row 1 Calculation (Token 1)Col 1: (1·1) + (0·0) + (1·1) + (2·0) = 1 + 0 + 1 + 0 = 2Col 2: (1·0) + (0·1) + (1·(-1)) + (2·1) = 0 + 0–1 + 2 = 1Col 3: (1·1) + (0·0) + (1·0) + (2·1) = 1 + 0 + 0 + 2 = 3Col 4: (1·0) + (0·1) + (1·0) + (2·(-1)) = 0 + 0 + 0–2 = -2Result for Row 1: [ 2 1 3 -2 ]Row 2 Calculation (Token 2)Col 1: (0·1) + (2·0) + (1·1) + (0·0) = 0 + 0 + 1 + 0 = 1Col 2: (0·0) + (2·1) + (1·(-1)) + (0·1) = 0 + 2–1 + 0 = 1Col 3: (0·1) + (2·0) + (1·0) + (0·1) = 0 + 0 + 0 + 0 = 0Col 4: (0·0) + (2·1) + (1·0) + (0·(-1)) = 0 + 2 + 0 + 0 = 2Result for Row 2: [ 1 1 0 2 ]Row 3 Calculation (Token 3)Col 1: (1·1) + (1·0) + (0·1) + (1·0) = 1 + 0 + 0 + 0 = 1Col 2: (1·0) + (1·1) + (0·(-1)) + (1·1) = 0 + 1 + 0 + 1 = 2Col 3: (1·1) + (1·0) + (0·0) + (1·1) = 1 + 0 + 0 + 1 = 2Col 4: (1·0) + (1·1) + (0·0) + (1·(-1)) = 0 + 1 + 0–1 = 0Result for Row 3: [ 1 2 2 0 ]Row 4 Calculation (Token 4)Col 1: (2·1) + (0·0) + (2·1) + (1·0) = 2 + 0 + 2 + 0 = 4Col 2: (2·0) + (0·1) + (2·(-1)) + (1·1) = 0 + 0–2 + 1 = -1Col 3: (2·1) + (0·0) + (2·0) + (1·1) = 2 + 0 + 0 + 1 = 3Col 4: (2·0) + (0·1) + (2·0) + (1·(-1)) = 0 + 0 + 0–1 = -1Result for Row 4: [ 4 -1 3 -1 ]Performing this calculation across all rows yields the final projected matrix: [ 2 1 3 -2 ]Q = [ 1 1 0 2 ] [ 1 2 2 1 ] [ 4 1 3 -1 ]Initially, all weight matrices are populated with small random values near zero. Over the course of training, they learn to capture distinct features. The three transformed vectors represent three different functional aspects of the same input:Query (Q): Asks what this token position is looking for.Key (K): Describes what this token position offers to the context.Value (V): Carries the actual semantic information to be combined.Visualizing Projection DimensionsInput Matrix X Weight Matrix W_q Query Matrix Q[Context x d_model] × [d_model x d_out] = [Context x d_out]┌─────────────────┐ ┌───────────────┐ ┌───────────────┐│ 32,000 │ │ 512 │ │ 32,000 ││ × │ │ × │ │ × ││ 512 │ │ 4,096 │ │ 4,096 │└─────────────────┘ └───────────────┘ └───────────────┘2. The Core Mechanics: Scaled Dot-Product Attention & Causal MaskingThe attention mechanism allows token embeddings to calculate their mutual similarities across the provided context window. For a single head, the mathematical equation is defined as:Attention(Q, K, V) = Softmax( (Q · Kᵀ / √d_head) + Causal Mask ) · VBreaking Down the Math Step-by-StepSimilarity Matrix (Q · Kᵀ): If Q is of size (32,000 × 4,096), it is multiplied by the transpose of the Key matrix Kᵀ, which has dimensions of (4,096 × 32,000). This matrix multiplication results in an attention score matrix of size (32,000 × 32,000), mapping the raw relationship score between every pair of positions.Scaling by √d_head: As the head dimension grows larger, the dot products grow larger in magnitude. This pushes the softmax function into regions with extremely small gradients. Dividing by √d_head scales these values down, stabilizing the gradient flow during backpropagation.Why Causal Masking is Required: In an autoregressive decoder, the model must not look into the future. When predicting the next word, it should only have access to current and past tokens. To enforce this condition, a causal mask is added to the scaled scores before applying the softmax function. This mask sets all upper-triangular positions (representing future tokens) to negative infinity (-∞). Since e^(-∞) = 0, the softmax operation assigns a probability of exactly 0 to those future tokens.Raw Attention Matrix (QKᵀ) After Causal Masking (-∞) Post-Softmax Probabilities ┌───────────┐ ┌───────────┐ ┌───────────┐ │ 12 4 8 │ │ 12 -∞ -∞ │ │1.0 0.0 0.0│ │ 3 9 2 │ ───> │ 3 9 -∞ │ ───> │.002.998 0 │ │ 7 6 11 │ │ 7 6 11 │ │.02 .01 .97│ └───────────┘ └───────────┘ └───────────┘Softmax Layer as a Probability DistributionApplying the softmax function guarantees that the weights across each row sum exactly to 1.0, turning them into a valid probability distribution.For instance, at token position 4, the model might assign the weights [0.05, 0.15, 0.70, 0.10] to positions 1 through 4. The final output vector for position 4 is computed as a weighted mixture of those historical value vectors:Output_4 = 0.05·V₁ + 0.15·V₂ + 0.70·V₃ + 0.10·V₄3. PyTorch Code: Building the Attention Mechanisms From ScratchBelow is the complete, self-contained implementation of the four major attention variants used across the industry.pythonimport torchimport torch.nn as nnimport torch.nn.functional as Fclass MultiHeadAttention(nn.Module): def __init__(self, d_model, num_heads): super().__init__() assert d_model % num_heads == 0, "d_model must be divisible by num_heads" self.d_model = d_model self.num_heads = num_heads self.d_head = d_model // num_heads # MHA allocates distinct W_q, W_k, W_v for every single head self.W_q = nn.Linear(d_model, d_model, bias=False) self.W_k = nn.Linear(d_model, d_model, bias=False) self.W_v = nn.Linear(d_model, d_model, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False) def forward(self, x): B, T, C = x.shape # Batch size, Sequence length, Embedding dimension # 1. Project the input tensor x through the learned weight matrix (W_q) # 2. Reshape (view) the flat dimensions into separate parallel attention heads # 3. Swap (transpose) dimensions so the 'heads' dimension comes before the 'sequence length' (T) # This allows us to perform fast, parallel matrix multiplication across all batches and heads at once. q = self.W_q(x).view(B, T, self.num_heads, self.d_head).transpose(1, 2) k = self.W_k(x).view(B, T, self.num_heads, self.d_head).transpose(1, 2) v = self.W_v(x).view(B, T, self.num_heads, self.d_head).transpose(1, 2) # Multiplying q and K^T and dividing by sqrt(d_head) scores = (q @ k.transpose(-2, -1)) / (self.d_head ** 0.5) # Applying causal mask so that it does not learn from future tokens # 1. Create a square matrix of size (T, T) completely filled with negative infinity (-inf). # 2. Extract the upper triangular part (triu) of this matrix, starting 1 slot above the main diagonal. # 3. The zeros on the lower half allow past tokens to talk, while -inf blocks future tokens. mask = torch.triu(torch.full((T, T), float('-inf'), device=x.device), diagonal=1) scores = scores + mask attn_weights = F.softmax(scores, dim=-1) # 1. Multiply attention weights by values (v) to get context vectors for each head # 2. Swap 'heads' and 'sequence length' (T) back to the original order # 3. Force PyTorch to arrange the data sequentially in memory (contiguous) # 4. Collapse the parallel head dimensions back into the single combined channel (C) context = (attn_weights @ v).transpose(1, 2).contiguous().view(B, T, C) return self.out_proj(context)# Another technique where Query heads together so they can share a single Key and Value head. class GroupedQueryAttention(nn.Module): def __init__(self, d_model, num_query_heads, num_kv_groups): super().__init__() self.num_query_heads = num_query_heads # The number of distinct Key and Value heads. # Instead of matching the number of Query heads, we restrict this # to a smaller number to compress our memory footprint. self.num_kv_groups = num_kv_groups self.d_head = d_model // num_query_heads self.queries_per_group = num_query_heads // num_kv_groups self.W_q = nn.Linear(d_model, num_query_heads * self.d_head, bias=False) self.W_k = nn.Linear(d_model, num_kv_groups * self.d_head, bias=False) self.W_v = nn.Linear(d_model, num_kv_groups * self.d_head, bias=False) self.out_proj = nn.Linear(d_model, d_model, bias=False) def forward(self, x): B, T, _ = x.shape q = self.W_q(x).view(B, T, self.num_query_heads, self.d_head).transpose(1, 2) k = self.W_k(x).view(B, T, self.num_kv_groups, self.d_head).transpose(1, 2) v = self.W_v(x).view(B, T, self.num_kv_groups, self.d_head).transpose(1, 2) # Duplicates (clones) each Key head sequentially across the head dimension (dim=1). # This expands the shared Key matrix so it matches the exact shape of the Query matrix, # allowing us to perform fast, parallel batch matrix multiplication. k = k.repeat_interleave(self.queries_per_group, dim=1) v = v.repeat_interleave(self.queries_per_group, dim=1) scores = (q @ k.transpose(-2, -1)) / (self.d_head ** 0.5) mask = torch.triu(torch.full((T, T), float('-inf'), device=x.device), diagonal=1) scores = scores + mask attn_weights = F.softmax(scores, dim=-1) context = (attn_weights @ v).transpose(1, 2).contiguous().view(B, T, -1) return self.out_proj(context)DeepSeek’s Multi-head Latent Attention (MLA)Multi-head Latent Attention (MLA) compresses the Key-Value cache during generation. Instead of caching large KV matrices, MLA compresses keys and values into a low-dimensional latent vector vector during inference. This reduces memory traffic overhead, speeding up generation times across long contexts.4. The Geometry of Space: Sinusoidal vs. Rotary Positional Embeddings (RoPE)Because self-attention processes tokens in parallel, it is inherently permutation-invariant. Without explicit positional context, the sequence "Dog eats fish" maps to the exact same attention presentation as "Fish eats dog".Sinusoidal Encodings: In the original 2017 Transformer paper, the authors faced a core dilemma: Attention treats tokens like a bag of words with no inherent order. To fix this, they introduced Sinusoidal Positional Encodings — a method that assigns a unique, mathematically calculated vector to each position in a sentence using sine and cosine waves.Instead of forcing the model to learn positions during training, they hard-coded a fixed geometric blueprint.The Intuition: The Structural ClockThink of sinusoidal encoding like a high-precision binary clock or an odometer, where each slot moves at a different speed:The first few dimensions fluctuate incredibly fast (like seconds).The middle dimensions change moderately (like minutes).The last dimensions change incredibly slowly (like hours).By looking at the combined values across all dimensions, the model can instantly tell exactly what “time” (position) it is, and exactly how far apart two tokens are.The Mathematical FormulaFor a token at position pos and a feature column index i inside the embedding :If the index is Even (2i): PE(pos, 2i) = sin( pos / 10000^(2i / d_model) )If the index is Odd (2i+1): PE(pos, 2i+1) = cos( pos / 10000^(2i / d_model) )The reason i only goes up to 1 for an embedding size of 4 is because every single value of i populates two positions at the same time — one even position using Sine, and one odd position using Cosine.Step-by-Step Concrete ExampleLet’s calculate the positional embedding vector for the first two tokens in a sentence using a small teaching setup where d_model = 4 (four dimensions).Our frequency base denominator for the dimensions is calculated as:For the first pair of dimensions (i=0): 10000^(0/4) = 1For the second pair of dimensions (i=1): 10000^(2/4) = √10000 = 1001. Calculating Token at Position 0 (First Word)Dim 0 (Even, i=0): sin(0 / 1) = sin(0) = 0.0Dim 1 (Odd, i=0): cos(0 / 1) = cos(0) = 1.0Dim 2 (Even, i=1): sin(0 / 100) = sin(0) = 0.0Dim 3 (Odd, i=1): cos(0 / 100) = cos(0) = 1.0Position 0 Vector: [ 0.0, 1.0, 0.0, 1.0 ]2. Calculating Token at Position 1 (Second Word)Dim 0 (Even, i=0): sin(1 / 1) = sin(1 radian) ≈ 0.841Dim 1 (Odd, i=0): cos(1 / 1) = cos(1 radian) ≈ 0.540Dim 2 (Even, i=1): sin(1 / 100) = sin(0.01 radians) ≈ 0.010Dim 3 (Odd, i=1): cos(1 / 100) = cos(0.01 radians) ≈ 0.999Position 1 Vector: [ 0.841, 0.540, 0.010, 0.999 ]How the Model Uses ItOnce these fixed vectors are calculated, they are directly added to the token’s semantic word embeddings:text[ Word Embedding ] + [ Positional Vector ] = [ Final Input Vector ](Carries Word Meaning) (Carries Token Order) (Carries Meaning + Order)Use code with caution.Because sine and cosine follow strict linear rotation properties, the attention mechanism can easily calculate the dot product between two tokens and determine their distance. For example, the relationship between position pos and position pos + k can be completely broken down as a linear function of the offset k.Why Modern Models Moved Away From ItWhile beautiful, sinusoidal encodings are absolute — they attach a specific coordinate to a specific slot. Modern architectures prefer Rotary Position Embeddings (RoPE) because RoPE injects this positioning directly into the attention scores as relative angles, making it vastly superior at handling dynamically scaled, ultra-long context windows.Rotary Position Embeddings (RoPE): Instead of adding absolute vectors to the embeddings, RoPE treats pairs of coordinates in the Query and Key vectors as 2D complex numbers, rotating them in the complex plane by a position-dependent angle.RoPE Geometric Intuition DiagramA 2D vector coordinate pair [q_0, q_1] is rotated by an angle dependent on its exact sequence position m:Mathematically, the rotation matrix for a single 2D coordinate pair at position \(m\) is written as:$$R_{\theta, m}^{2} = \begin{pmatrix} \cos(m\theta) & -\sin(m\theta) \\ \sin(m\theta) & \cos(m\theta) \end{pmatrix}When we calculate the dot product between a shifted Query vector at position \(m\) and a shifted Key vector at position \(n\), the absolute positions drop out. The remaining calculation depends entirely on their relative distance \((m — n)\):\((R_{m}Q)\cdot (R_{n}K)=Q^{T}R_{m}^{T}R_{n}K=Q^{T}R_{n-m}K\)This formulation allows the network to naturally generalize to long context lengths during inference.When we calculate the dot product between a shifted Query vector at position m and a shifted Key vector at position n, the absolute positions drop out. The remaining calculation depends entirely on their relative distance (m — n). This formulation allows the network to naturally generalize to long context lengths during inference.5. Stable Deep Stacking: LayerNorm vs. RMSNormNormalization stabilizes internal activation scales across deep network architectures.LayerNorm centers the input activations by subtracting their mean, and then scales them using their variance.RMSNorm operates under the premise that centering the data by subtracting the mean is computationally redundant. It simplifies the operation by scaling exclusively by the Root Mean Square, saving significant overhead on hardware.Numerical Walkthrough ComparisonLet our hidden activation vector be x = [1.0, 2.0, 3.0].LayerNorm Calculations:Mean = (1 + 2 + 3) / 3 = 2.0Centered Vector (x — Mean) = [-1.0, 0.0, 1.0]Variance = ( (-1)² + ⁰² + ¹² ) / 3 = 0.666Output (Divided by √Variance) = [-1.22, 0.0, 1.22]RMSNorm Calculations:Mean Square = (¹² + ²² + ³²) / 3 = (1 + 4 + 9) / 3 = 4.666Root Mean Square (RMS) = √4.666 = 2.16Output (x / RMS) = [1/2.16, 2/2.16, 3/2.16] = [0.46, 0.93, 1.39]6. Regularization and Nonlinearities: Dropout, SwiGLU, and Feed-Forward NetworksOnce the attention layer completes its calculation, the token representations pass through a position-wise Feed-Forward Network (FFN).Why and How Dropout OperatesDropout acts as a regularizer during training by randomly setting a fraction p of hidden activations to exactly 0.0. If p = 0.1, roughly 10% of the neurons are disabled on each forward pass. This prevents co-adaptation of features, ensuring the model does not overfit to specific training patterns. During inference and evaluation, dropout is completely disabled.Gated Nonlinearities: SwiGLUWhile classic architectures relied on standard activations like ReLU or GELU, modern frontier networks use SwiGLU (Swish Gated Linear Units). SwiGLU uses a gated mechanism where one linear layer modulates the output of another:SwiGLU(x) = Swish(x · W_gate) ⊙ (x · W_up) · W_downWhere ⊙ represents an element-wise multiplication. This gating mechanism allows the model to control information flow dynamically, determining which features to pass forward down the network stack.7. PyTorch Block Construction: Putting It All Together From ScratchBelow is the complete implementation of a modern, production-grade Pre-LN Transformer decoder block using RMSNorm, Grouped-Query Attention, and SwiGLU nonlinearities.pythonclass RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.gamma = nn.Parameter(torch.ones(dim)) def forward(self, x): rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) return x * rms * self.gammaclass SwiGLUFFN(nn.Module): def __init__(self, d_model, d_ffn): super().__init__() self.W_gate = nn.Linear(d_model, d_ffn, bias=False) self.W_up = nn.Linear(d_model, d_ffn, bias=False) self.W_down = nn.Linear(d_ffn, d_model, bias=False) def forward(self, x): # Element-wise multiplication of the Swish-gated branch and the up-projection branch return self.W_down(F.silu(self.W_gate(x)) * self.W_up(x))class CompleteGPTBlock(nn.Module): def __init__(self, d_model, num_heads, num_kv_groups, d_ffn, dropout_p=0.1): super().__init__() self.attn_norm = RMSNorm(d_model) self.attn = GroupedQueryAttention(d_model, num_heads, num_kv_groups) self.attn_dropout = nn.Dropout(dropout_p) self.ffn_norm = RMSNorm(d_model) self.ffn = SwiGLUFFN(d_model, d_ffn) self.ffn_dropout = nn.Dropout(dropout_p) def forward(self, x): # Clean Pre-LN Residual Highway Layout x = x + self.attn_dropout(self.attn(self.attn_norm(x))) x = x + self.ffn_dropout(self.ffn(self.ffn_norm(x))) return x# Instantiate a single complete block matching our architectural layoutif __name__ == "__main__": example_input = torch.randn(2, 64, 128) # Batch=2, Sequence=64 tokens, d_model=128 block = CompleteGPTBlock(d_model=128, num_heads=4, num_kv_groups=2, d_ffn=384) output = block(example_input) print("Execution successful! Output shape matches input tensor exactly:", output.shape)When you read a model cardLook for the specific choices it actually discloses: positional method, normalization, attention variant, feed-forward function, dense versus mixture-of-experts layers, and context length. Do not infer these from a brand name. Some commercial model vendors publish extensive model cards but not the full weight architecture.Article 2 : Inside a GPT Block: Attention, Position, and Stable Training was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.