Open AI IT TCET Pinwheel Logo
OPEN AI ITTCET-IT COMMITTEE
Paper Reproductions15 min read • June 2026

AttentionIsAllYouNeed:TransformerArchitecturefromScratch

Line-by-line PyTorch reproduction of scaled dot-product attention, multi-head projection matrices, and sinusoidal positional embeddings.

Reference / Authors: Vaswani et al. (Google Brain / Research, 2017)
Interactive ToolVaswani et al. 2017 Reproduction

Self-Attention Mechanism Visualizer

Explore how transformer tokens calculate pairwise relevance to resolve context and coreference.

Interactive Sentence TokensSelect a highlighted token to inspect attention flow
Query Token: “it”
Attention Scores for Query: “it”Attention(Q, K, V) = softmax(QKᵀ / √dₖ) V
animal
85%
tired
72%
cross
35%
street
12%
because
8%

Coreference Intuition: When evaluating “it”, the model computes high dot-product similarity with “animal” (85%), dynamically pulling information from the correct referent without requiring recurrent sequential steps.

TCET-IT • 2026Active Query Token: “it”

Start Here: Beginner Primer & Intuition

No heavy equations required — grasp the core mechanics in plain English first.

Quick TL;DR: Understand how the core engine of modern generative AI (ChatGPT, Claude, Gemini) works by allowing every word to connect directly and simultaneously to every other word.

THE BOTTLENECK

Why the Old Approach Broke Down

Before the Transformer, older AI models (RNNs & LSTMs) processed sentences like an old cassette tape: one word at a time from left to right. This was agonizingly slow on GPUs, and models often forgot earlier sentences by the time they reached the end.

THE BREAKTHROUGH

The Elegant Engineering Fix

Self-Attention looks at the entire sentence simultaneously in a single parallel GPU pass. For every token, it computes attention scores determining which other tokens provide the most important context.

REAL-WORLD ANALOGY

The Library Catalog System (Query, Key, Value)

Think of self-attention as searching in a library: your Query (Q) is what you're looking for, the Key (K) is the label on book spines, and the Value (V) is the actual content inside. When Query matches Key, the library hands you the Value.

Concept 01
Parallel Processing

Because there are no step-by-step loops, thousands of GPU cores process long documents concurrently.

Concept 02
Multi-Head Attention

Instead of a single attention score, the model uses multiple 'heads' (e.g. 8 or 32) so different heads can track grammar, subject-verb connections, or pronouns at the same time.

Concept 03
Positional Encodings

Because self-attention reads all words at once, it adds mathematical sine and cosine wave signals to track word positions in the sequence.

Abstract & Theoretical Context

Prior to the Transformer architecture, state-of-the-art sequence modeling relied primarily on Recurrent Neural Networks (RNNs, LSTMs, GRUs) and Convolutional Neural Networks (CNNs). However, recurrent models inherently process sequences sequentially (token by token at steps t_1 to t_n), creating a severe computational bottleneck that prevents parallelization across GPU cores. Additionally, LSTMs suffer from gradient vanishing when modeling long-range dependencies over hundreds of tokens. The Transformer architecture fundamentally solved this by discarding recurrence entirely in favor of Self-Attention mechanisms. Self-attention computes dynamic context representations by allowing every token in a sequence to directly attend to every other token in O(1) sequential operations, reducing maximum path length for long-range interactions to constant time. In this open-source reproduction, we build the Transformer encoder-decoder components from first principles using native PyTorch. We implement Scaled Dot-Product Attention, Multi-Head Linear Projections, Sinusoidal Positional Encodings, and Masked Decoder Self-Attention without relying on torch.nn.Transformer high-level abstractions.

Mathematical Formulations & Variables

1. Scaled Dot-Product Attention:
   Attention(Q, K, V) = softmax( (Q * K^T) / sqrt(d_k) ) * V
   - Q in R^(B x N x d_k) : Query matrix
   - K in R^(B x N x d_k) : Key matrix
   - V in R^(B x N x d_v) : Value matrix
   - d_k : Dimensionality of keys (scaling by sqrt(d_k) prevents large values from pushing softmax into regions with vanishing gradients)

2. Multi-Head Attention:
   MultiHead(Q, K, V) = Concat(head_1, ..., head_h) * W^O
   where head_i = Attention(Q * W_i^Q, K * W_i^K, V * W_i^V)
   - W_i^Q in R^(d_model x d_k)
   - W_i^K in R^(d_model x d_k)
   - W_i^V in R^(d_model x d_v)
   - W^O   in R^(h*d_v x d_model)

3. Sinusoidal Positional Encoding:
   PE_(pos, 2i)   = sin(pos / 10000^(2i / d_model))
   PE_(pos, 2i+1) = cos(pos / 10000^(2i / d_model))
   - Enables the model to learn relative position relationships via trigonometric identity:
     PE_(pos + k) can be represented as a linear function of PE_(pos).

PyTorch Implementation Code

attention-is-all-you-need-reproduction.py
1import torch
2import torch.nn as nn
3import math
4
5class ScaledDotProductAttention(nn.Module):
6 """
7 Computes Scaled Dot-Product Attention.
8 Input shapes: Q, K, V -> (Batch, Heads, SeqLen, d_k)
9 """
10 def __init__(self, d_k: int):
11 super().__init__()
12 self.scale = 1.0 / math.sqrt(d_k)
13
14 def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor = None):
15 # Calculate attention scores via matrix multiplication: (B, H, N, d_k) x (B, H, d_k, N) -> (B, H, N, N)
16 scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
17
18 # Apply causal or padding mask if provided
19 if mask is not None:
20 scores = scores.masked_fill(mask == 0, -1e9)
21
22 attn_weights = torch.softmax(scores, dim=-1)
23 # Compute weighted sum of values: (B, H, N, N) x (B, H, N, d_v) -> (B, H, N, d_v)
24 output = torch.matmul(attn_weights, v)
25 return output, attn_weights
26
27class MultiHeadAttention(nn.Module):
28 """
29 Multi-Head Attention module with projection matrices.
30 """
31 def __init__(self, d_model: int = 512, num_heads: int = 8):
32 super().__init__()
33 assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
34 self.d_k = d_model // num_heads
35 self.num_heads = num_heads
36
37 self.w_q = nn.Linear(d_model, d_model, bias=False)
38 self.w_k = nn.Linear(d_model, d_model, bias=False)
39 self.w_v = nn.Linear(d_model, d_model, bias=False)
40 self.w_o = nn.Linear(d_model, d_model, bias=False)
41 self.attention = ScaledDotProductAttention(self.d_k)
42
43 def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor = None):
44 batch_size = q.size(0)
45
46 # 1. Linear projections & reshape for multi-head parallel attention
47 q_proj = self.w_q(q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
48 k_proj = self.w_k(k).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
49 v_proj = self.w_v(v).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
50
51 # 2. Scaled dot-product attention per head
52 out, attn = self.attention(q_proj, k_proj, v_proj, mask)
53
54 # 3. Concatenate heads and apply final linear output projection
55 out = out.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_k)
56 return self.w_o(out)

Step-by-Step Reproduction Guide

11. Environment Setup: Install PyTorch 2.x and NumPy using `pip install torch numpy`.
22. Tensor Verification: Instantiate ScaledDotProductAttention and verify output shape (Batch, Heads, SeqLen, d_k).
33. Positional Embedding Verification: Compute sinusoidal embeddings and verify PE matrix addition to token input embeddings.
44. Causal Mask Construction: Construct lower-triangular mask (`torch.tril(torch.ones(seq_len, seq_len))`) for decoder self-attention.
55. Gradient Flow Sanity Check: Run backward pass (`loss.backward()`) and confirm non-zero gradients on W_q, W_k, W_v, W_o projection layers.

Key Insights & Operator Insights

  • Scaling Factor sqrt(d_k): Without scaling, for large d_k dot products grow large in magnitude, pushing softmax into extreme regions with tiny gradients.
  • Parallel Training: Unlike RNNs which require seq_len sequential GPU calls, Transformers compute all token representations simultaneously in parallel.
  • Multi-head projections allow the model to attend to information from different representation subspaces at different positions simultaneously.
  • Causal Masking: Prevents leftward information flow in decoder layers during autoregressive token generation.
HARDWARE & SYSTEM REQUIREMENTS

NVIDIA RTX 3060 (8GB VRAM), T4, or Apple M-Series Silicon