UgaDeep logo
UGADEEP UG · AF · WORLD
← Back to Tutorials
Deep Learning Core Intermediate 15 min read

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.

By UgaDeep Labs ·
Run in Google Colab ↗

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 TT token embeddings X∈RT×dmodelX \in \mathbb{R}^{T \times d_{\text{model}}}, we linearly project queries Q=XWQQ = XW_Q, keys K=XWKK = XW_K, and values V=XWVV = XW_V:

Attention(Q,K,V)=softmax(QK⊤dk+M)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V
  • Dividing by dk\sqrt{d_k} keeps dot-product variance near 11, preventing softmax saturation and vanishing gradients.
  • Adding the causal mask MM (00 on and below the diagonal, −∞-\infty above) ensures token tt 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, O(T2)O(T^2), and KV-cache memory scales linearly with TT.

LanguageSample PhraseTypical English-Centric TokenizerCost & Latency Impact
English“Good morning, how is the harvest?”~8 tokens1.0x baseline
Luganda“Wasuze otya, amakungula gali gatya?”~18–22 tokens2.4x slower & pricier
Runyankole“Oraire ota, ekyesha kiri kita?”~19–24 tokens2.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.