Transformers & Scaled Dot-Product Attention — From Equations to PyTorch
Demystify multi-head self-attention, causal masking, and why subword tokenization fertility disproportionately affects African languages.
Modern frontier AI—from GPT and Gemini to open-weights Llama, Qwen, and Gemma—rests on a surprisingly clean mathematical primitive: Scaled Dot-Product Attention.
1. Attention Equation Explained
For a sequence of token embeddings , we linearly project queries , keys , and values :
- Dividing by keeps dot-product variance near , preventing softmax saturation and vanishing gradients.
- Adding the causal mask ( on and below the diagonal, above) ensures token cannot peek at future tokens during autoregressive language modeling.
2. Clean Multi-Head Self-Attention in PyTorch
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalSelfAttention(nn.Module):
def __init__(self, d_model: int = 256, n_heads: int = 8, dropout: float = 0.1):
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, bias=False)
self.proj = nn.Linear(d_model, d_model, bias=False)
self.dropout = dropout
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, T, C = x.shape
qkv = self.qkv(x).view(B, T, 3, self.n_heads, self.head_dim)
q, k, v = qkv.unbind(dim=2)
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
# Uses FlashAttention automatically on modern GPUs
out = F.scaled_dot_product_attention(
q, k, v,
dropout_p=self.dropout if self.training else 0.0,
is_causal=True,
)
out = out.transpose(1, 2).contiguous().view(B, T, C)
return self.proj(out)
x = torch.randn(2, 32, 256)
attn = CausalSelfAttention(d_model=256, n_heads=8)
print("Output shape:", attn(x).shape) # torch.Size([2, 32, 256])
3. The African Language Tokenization Tax
Self-attention scales quadratically with sequence length, , and KV-cache memory scales linearly with .
| Language | Sample Phrase | Typical English-Centric Tokenizer | Cost & Latency Impact |
|---|---|---|---|
| English | “Good morning, how is the harvest?” | ~8 tokens | 1.0x baseline |
| Luganda | “Wasuze otya, amakungula gali gatya?” | ~18–22 tokens | 2.4x slower & pricier |
| Runyankole | “Oraire ota, ekyesha kiri kita?” | ~19–24 tokens | 2.6x slower & pricier |
Key takeaway for East African AI builders: When training or adapting open-weights models for Ugandan languages, vocabulary extension (adding high-frequency Luganda/Swahili morphemes before continual pretraining) dramatically cuts inference latency and API cost.