Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 5 min read

Self-Attention Implementation from Scratch!

Watch the full visual breakdown on YouTube here Imagine standing in a noisy, crowded room where dozens of conversations create a wall of background noise, until someone across the room speaks your name and your brain ze

Self-Attention Implementation from Scratch!

Watch the full visual breakdown on YouTube here

Imagine standing in a noisy, crowded room where dozens of conversations create a wall of background noise, until someone across the room speaks your name and your brain zeroes in on that specific sound. Older recurrent neural networks processed text sequentially step-by-step, inevitably forgetting early context as sequences grew longer. The Transformer's attention mechanism fundamentally changed natural language processing by allowing models to inspect all words simultaneously, transforming raw text into dynamic, context-aware representations using vectors.

1. Attention Mechanism Meaning: From Words to Vector Spaces

To make language computable, we must map words into a dense mathematical space where semantic concepts live as coordinates. Think of these embeddings as high-dimensional GPS coordinates for human language, where directional relationships capture semantic meaning (famously illustrated by vector arithmetic: king - man + woman = queen).

Mathematically, an input sequence is represented as a matrix X in R^N x d_model, where N is the sequence length and d_model is the embedding dimension. In Python, we can initialize this sequence using NumPy:

import numpy as np

# Set random seed for reproducibility
np.random.seed(42)

N, d_model = 4, 8  # 4 tokens, 8-dimensional embeddings
X = np.random.randn(N, d_model)
print("Input Matrix X shape:", X.shape)

2. Queries, Keys, and Values: The Core Abstraction

Math behind Attention

Once words are represented as baseline vectors, the model projects them into three functional roles: Queries (Q), Keys (K), and Values (V). This setup mirrors a digital filing cabinet or a database search:

  • Query (Q): What am I looking for?
  • Key (K): What tags do the available entries have?
  • Value (V): What actual information is stored inside the entry?

Mathematically, we project our input embedding matrix X using learned weight matrices W_Q, W_K, W_V in R^d_model x d_k:

Q = XW_Q, K = XW_K, V = XW_V

In NumPy, this matrix projection is computed cleanly using the @ operator:

d_k = 4  # Projection dimension for attention space

W_q = np.random.randn(d_model, d_k)
W_k = np.random.randn(d_model, d_k)
W_v = np.random.randn(d_model, d_k)

Q = X @ W_q
K = X @ W_k
V = X @ W_v

print("Query shape:", Q.shape)
print("Key shape:", K.shape)
print("Value shape:", V.shape)

3. Self-Attention Mechanism Explained: Dot Product Similarity

Dot Product

With Queries and Keys established, how does the model measure how much two words relate to each other? This process functions much like a compatibility score on a dating app, measuring how closely two profile vectors point in the same directional space.

Mathematically, we compute the dot product between every Query vector and every Key vector. The raw similarity matrix S is calculated by multiplying Q with the transpose of K:

S = QK^T

In NumPy, executing this gives an N x N relational grid quantifying the raw affinity between every single word pair:

# Raw similarity scores
scores = Q @ K.T
print("Raw Similarity Scores shape:", scores.shape)

4. The Scaling Factor and Softmax Normalization

If feature dimensions are large, raw dot products grow massively in magnitude. Without intervention, these huge numbers push the upcoming normalization function into flat regions with near-zero gradients, halting neural network training entirely.

To prevent this, we divide our raw similarity matrix by the square root of d_k:

Scaled Scores = QK^T sqrt(d_k)

Next, we pass these scaled scores through the Softmax function to convert them into a strict probability distribution where every row sums to 1.0:

Attention Weights = softmax(QK^T sqrt(d_k))

Here is the robust NumPy implementation for scaling and Softmax:

def softmax(x, axis=-1):
    # Subtract max for numerical stability
    exp_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
    return exp_x / np.sum(exp_x, axis=axis, keepdims=True)

# Scale by sqrt(d_k)
scaled_scores = scores / np.sqrt(d_k)

# Apply softmax normalization
attention_weights = softmax(scaled_scores, axis=-1)
print("Attention Weights sum per row (should be 1.0):", np.sum(attention_weights, axis=-1))

5. Blending Values & Decoder Causal Masking

Now comes the core transformation: blending the Values. The Softmax attention weights act as a percentage recipe, while the Value matrix holds the raw information vectors. The contextual output Z is computed as:

Z = Attention Weights x V

# Compute final context vectors
Z = attention_weights @ V
print("Contextual Output Z shape:", Z.shape)

Decoder Causal Masking

When generating text sequentially in autoregressive decoders like GPT, we must enforce a strict temporal rule preventing models from peeking into future tokens. We construct a causal mask filled with negative infinities for upper-triangular indices where j > i:


# Create a causal mask for decoder models
mask = np.triu(np.ones((N, N)), k=1) * -1e9
masked_scores = scaled_scores + mask

# Softmax turns -1e9 into 0 probability
masked_attention_weights = softmax(masked_scores, axis=-1)
print("Masked Attention Weights:\n", np.round(masked_attention_weights, 3))

6. Multi-Head Attention & Full NumPy Implementation

A single attention calculation captures only one relational subspace at a time. To capture multiple syntactic and semantic relationships simultaneously, Multi-Head Attention projects Queries, Keys, and Values into multiple lower-dimensional subspaces across parallel heads.

Here is the complete, production-grade 10-line scaled dot-product attention function in pure NumPy:

def scaled_dot_product_attention(Q, K, V, mask=None):
    d_k = Q.shape[-1]
    scores = (Q @ K.T) / np.sqrt(d_k)
    if mask is not None:
        scores += mask
    weights = softmax(scores, axis=-1)
    return weights @ V, weights

# Run full verified pipeline
output, weights = scaled_dot_product_attention(Q, K, V, mask=mask)
print("Final Output Vectors:\n", np.round(output, 3))

Resources & Next Steps

Continue your deep dive into Transformer internals with these official companion assets from Sirius AI Lab:

  1. Free GitHub Starter Repo: Clone starter_code.py on GitHub for structured # TODO exercises and shape checks.
  2. Free $0+ 1-Page Visual Cheat Sheet (PDF): Grab the quick-reference equations and matrix dimensions on Gumroad.
  3. Complete $7 Interactive Colab Notebook + Solution Pack: Get the 4-step runnable Jupyter/Colab notebook, full NumPy implementation, PDF cheat sheet, and all 10 HD reference slides on Gumroad.
πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.