NN LAB 🧠

Foundational Deep Learning Laboratory

Transformer Self-Attention & Layer Architecture Studio

Interact with the mathematical core of modern Large Language Models and genomic foundation models. Explore scaled dot-product attention, multi-head projection subspaces, Grouped-Query Attention (GQA) routing, and Pre-LN normalization dynamics. Click any cell in the attention heatmap to inspect its exact arithmetic trace.

Attention(Q,K,V)=softmax(QKTdk+M)V\text{Attention}(Q, K, V) = \text{softmax}\left( \frac{Q K^T}{\sqrt{d_k}} + M \right) V
Architecture Paradigm:
Domain Presets:
Active Tokens (NN):
1/8: Input Token Embeddings
Softmax Attention Matrix ARN×NA \in \mathbb{R}^{N \times N}
Click cell to inspect dot product arithmetic
Softmax Probability:
0%
100%
Attention Arithmetic X-Ray & Trace
qikj/dk\mathbf{q}_i \cdot \mathbf{k}_j / \sqrt{d_k}
🔀

Grouped-Query Attention (GQA) Head Topology Visualizer

Shows how HH Query heads share HKVH_{\text{KV}} Key-Value projection heads, reducing KV cache memory footprint by H/HKV×H / H_{\text{KV}} \times during autoregressive decoding.

Learnable ParametersWeights + Projections
--
Paramslayer=WQ+WK+WV+WO+FFN+2×Norm\text{Params}_{\text{layer}} = W_Q + W_K + W_V + W_O + \text{FFN} + 2 \times \text{Norm}
Computational ComplexityForward FLOPs
--
FLOPs=2Ndmodel(dQ+dK+dV+dO)+4N2dmodel+2Ndmodeldffn\text{FLOPs} = 2N d_{\text{model}} (d_Q + d_K + d_V + d_O) + 4N^2 d_{\text{model}} + 2N d_{\text{model}} d_{\text{ffn}}
KV Cache FootprintAutoregressive Decoding
--
VRAMKV=2×B×L×HKV×S×dhead×2 B\text{VRAM}_{\text{KV}} = 2 \times B \times L \times H_{\text{KV}} \times S \times d_{\text{head}} \times 2\text{ B}

Production-Ready PyTorch Transformer Layer Generator

Copy fully synchronized, production-grade PyTorch code implementing the currently configured Transformer layer, featuring RoPE rotary embeddings, RMSNorm Pre-LN residual paths, and SwiGLU gating with verification harness.

# Initializing PyTorch module generator...

Foundational Architectural Deep Dives

Rigorous mathematical proofs and systems engineering principles underpinning state-of-the-art Transformer architectures.

📐Mathematical Proof: Why Scale Dot-Product Attention by 1/dk1/\sqrt{d_k}?

In the seminal paper Attention Is All You Need (Vaswani et al. 2017), the authors note that for large values of dkd_k, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients. Here is the complete variance stabilization proof.

1. Statistical Formulation of the Raw Dot Product

Let q,kRdk\mathbf{q}, \mathbf{k} \in \mathbb{R}^{d_k} be independent random query and key vectors whose components are independent and identically distributed (i.i.d.) random variables with zero mean and unit variance:

E[qi]=0,Var(qi)=1,E[ki]=0,Var(ki)=1i{1,,dk}\mathbb{E}[q_i] = 0, \quad \text{Var}(q_i) = 1, \quad \mathbb{E}[k_i] = 0, \quad \text{Var}(k_i) = 1 \quad \forall i \in \{1, \dots, d_k\}

The unscaled dot product SS is given by the sum of pairwise products:

S=qk=i=1dkqikiS = \mathbf{q} \cdot \mathbf{k} = \sum_{i=1}^{d_k} q_i k_i

2. Expectation and Variance of Each Component Product

For each term Xi=qikiX_i = q_i k_i, using the independence of qiq_i and kik_i:

E[Xi]=E[qiki]=E[qi]E[ki]=00=0\mathbb{E}[X_i] = \mathbb{E}[q_i k_i] = \mathbb{E}[q_i] \cdot \mathbb{E}[k_i] = 0 \cdot 0 = 0

The variance of each individual product term is:

Var(Xi)=E[Xi2](E[Xi])2=E[qi2ki2]0=E[qi2]E[ki2]=11=1\text{Var}(X_i) = \mathbb{E}[X_i^2] - (\mathbb{E}[X_i])^2 = \mathbb{E}[q_i^2 k_i^2] - 0 = \mathbb{E}[q_i^2] \cdot \mathbb{E}[k_i^2] = 1 \cdot 1 = 1

3. Variance of the Total Sum

Because all dkd_k terms X1,,XdkX_1, \dots, X_{d_k} are mutually independent, the variance of the sum is the sum of the variances:

Var(S)=Var(i=1dkqiki)=i=1dkVar(qiki)=i=1dk1=dk\text{Var}(S) = \text{Var}\left(\sum_{i=1}^{d_k} q_i k_i\right) = \sum_{i=1}^{d_k} \text{Var}(q_i k_i) = \sum_{i=1}^{d_k} 1 = d_k

Consequently, the standard deviation is σS=dk\sigma_S = \sqrt{d_k}. In modern models where dk=128d_k = 128, the standard deviation of raw scores is 12811.31\sqrt{128} \approx 11.31.

4. Vanishing Softmax Gradients Under High Variance

Consider the softmax function pi=softmax(z)i=ezijezjp_i = \text{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j} e^{z_j}}. Its partial derivative with respect to any input logit zjz_j is:

pizj=pi(δijpj)\frac{\partial p_i}{\partial z_j} = p_i (\delta_{ij} - p_j)

When logits have large variance (σ11.3\sigma \approx 11.3), the maximum logit zmaxz_{\max} severely outstrips all others, causing the softmax probability distribution to saturate into a one-hot distribution:pmax1.0p_{\max} \approx 1.0 and pk0.0p_k \approx 0.0 for all kmaxk \neq \max. Substituting these saturated probabilities back into the derivative:

pmaxzmax=pmax(1pmax)1×(11)=0,pkzk0×(10)=0\frac{\partial p_{\max}}{\partial z_{\max}} = p_{\max}(1 - p_{\max}) \approx 1 \times (1 - 1) = 0, \quad \frac{\partial p_k}{\partial z_k} \approx 0 \times (1 - 0) = 0

Gradients vanish entirely, and backpropagation fails to update earlier layers.

5. Temperature Rescaling to Unit Variance

By dividing the raw dot product by dk\sqrt{d_k}, the variance of the scaled attention scores becomes:

Var(qkdk)=1(dk)2Var(qk)=1dkdk=1\text{Var}\left(\frac{\mathbf{q} \cdot \mathbf{k}}{\sqrt{d_k}}\right) = \frac{1}{(\sqrt{d_k})^2} \text{Var}(\mathbf{q} \cdot \mathbf{k}) = \frac{1}{d_k} \cdot d_k = 1

Key Takeaway: Scaling by 1/dk1/\sqrt{d_k} guarantees that the variance of the attention logits remains precisely 1.01.0 regardless of projection dimension, maintaining softmax sensitivity and preventing gradient collapse across arbitrarily deep networks.

🛣️Pre-LN vs Post-LN & The Gradient Highway (Enabling 70B+ Scale)

The placement of normalization layers represents one of the most critical architectural evolutions between the original 2017 Transformer and modern foundation LLMs (LLaMA, Mistral, Gemma, DeepSeek).

1. Classical Post-LN (Vaswani et al. 2017)

xl=LayerNorm(xl1+SubLayer(xl1))x_l = \text{LayerNorm}(x_{l-1} + \text{SubLayer}(x_{l-1}))

The residual stream passes directly through the normalization operator at every single layer. By the chain rule, gradients propagating backwards from layer LL to layer 00 are iteratively multiplied by the LayerNorm Jacobian:

xLx0=l=1L[JLN(zl)(I+JSubLayer(xl1))]\frac{\partial x_L}{\partial x_0} = \prod_{l=1}^{L} \left[ J_{\text{LN}}(z_l) \cdot \left( I + J_{\text{SubLayer}}(x_{l-1}) \right) \right]

Because LayerNorm rescales activations by 1/σ1/\sigma, gradient norms decay exponentially with depth as O(1/L)O(1/\sqrt{L}). Training Post-LN models requires an ultra-delicate learning rate warmup schedule, and training often destabilizes beyond 12 layers.

2. Modern Pre-LN (Radford et al. 2019 / LLaMA)

xl=xl1+SubLayer(Norm(xl1))x_l = x_{l-1} + \text{SubLayer}(\text{Norm}(x_{l-1}))

The residual connection is purely additive and completely bypasses the normalization step:

xL=x0+l=1LSubLayer(Norm(xl1))x_L = x_0 + \sum_{l=1}^{L} \text{SubLayer}(\text{Norm}(x_{l-1}))

Differentiating the final state xLx_L with respect to input embeddings x0x_0:

xLx0=I+l=1LSubLayer(Norm(xl1))x0\frac{\partial x_L}{\partial x_0} = I + \sum_{l=1}^{L} \frac{\partial \text{SubLayer}(\text{Norm}(x_{l-1}))}{\partial x_0}

The leading identity matrix II guarantees an unattenuated, clean "gradient highway" from the final loss directly to the input representations.

Why Modern LLMs Use Pre-RMSNorm: Pre-LN eliminates the need for delicate warmups and enables training networks with hundreds of layers (e.g. LLaMA 70B with 80 layers). Furthermore, replacing LayerNorm with RMSNorm (x/RMS(x)x / \text{RMS}(x)) discards mean centering, saving 10%\approx 10\% to 15%15\% of memory bandwidth without any degradation in perplexity.

FlashAttention-2, Tiling & Online Softmax (IO-Aware Exact Attention)

On modern GPU hardware (NVIDIA A100, H100, B200), compute throughput (Tensor Cores) has scaled dramatically faster than memory bandwidth (HBM). Consequently, standard self-attention is not compute-bound—it is strictly memory bandwidth (IO) bound.

1. The Memory Hierarchy Bottleneck in Standard Attention

Modern accelerators feature a multi-tier memory hierarchy:

  • High-Bandwidth Memory (HBM): Large capacity (80 GB), but relatively slow bandwidth (3.35 TB/s\approx 3.35\text{ TB/s} on H100 SXM).
  • On-Chip Static RAM (SRAM): Ultra-fast (33 TB/s\approx 33\text{ TB/s}, 10×10\times faster), but small capacity (228 KB\approx 228\text{ KB} per Streaming Multiprocessor, 50 MB\approx 50\text{ MB} total).

Standard attention materializes intermediate matrices in HBM at each step:

  1. Read Q,KQ, K from HBM \to compute S=QKTRN×NS = Q K^T \in \mathbb{R}^{N \times N} in SRAM \to write SS back to HBM (O(N2)O(N^2) memory access).
  2. Read SS from HBM \to compute A=softmax(S)A = \text{softmax}(S) in SRAM \to write AA back to HBM (O(N2)O(N^2) memory access).
  3. Read A,VA, V from HBM \to compute O=AVRN×dO = A V \in \mathbb{R}^{N \times d} \to write OO to HBM.
VRAMStandard(N=32k,H=32)=32×(32,768)2×2 bytes68.7 GB of intermediate storage!\text{VRAM}_{\text{Standard}}(N = 32\text{k}, H = 32) = 32 \times (32{,}768)^2 \times 2\text{ bytes} \approx 68.7\text{ GB of intermediate storage!}

2. FlashAttention Tiling & Online Softmax Algorithm

FlashAttention (Dao et al. 2022, 2023) completely avoids materializing the quadratic N×NN \times N attention matrix in HBM. It partitions inputs into blocks QiRBr×dQ_i \in \mathbb{R}^{B_r \times d} and Kj,VjRBc×dK_j, V_j \in \mathbb{R}^{B_c \times d} that fit entirely within fast on-chip SRAM. To compute softmax without seeing all tokens at once, it utilizes the Online Softmax recurrence (Milakov & Gimelshein 2018):

mnew=max(m(old),max(xj))m^{\text{new}} = \max\left(m^{(old)}, \max(x_j)\right)
dnew=d(old)em(old)mnew+kexj,kmnewd^{\text{new}} = d^{(old)} \cdot e^{m^{(old)} - m^{\text{new}}} + \sum_{k} e^{x_{j,k} - m^{\text{new}}}
Onew=O(old)(d(old)em(old)mnewdnew)+kexj,kmnewvj,kdnewO^{\text{new}} = O^{(old)} \cdot \left(\frac{d^{(old)} \cdot e^{m^{(old)} - m^{\text{new}}}}{d^{\text{new}}}\right) + \frac{\sum_k e^{x_{j,k} - m^{\text{new}}} v_{j,k}}{d^{\text{new}}}

Theoretical IO Complexity: FlashAttention reduces total HBM data transfers from O(N2)O(N^2) down to O(N)O(N) while computing mathematically exact (non-approximate) attention. This yields a 2×2\times to 4×4\times wall-clock speedup and enables context windows of 128k128\text{k} to 1M1\text{M} tokens.

🧠MHA vs MQA vs GQA & The KV Cache Decoding Bottleneck

In production LLM serving, generation takes place token-by-token in an autoregressive loop. While the initial prompt processing (prefill) is compute-heavy, autoregressive generation (decoding) is strictly limited by memory bandwidth.

1. Arithmetic Intensity of Autoregressive Decoding

To generate token t+1t+1, the query is a single vector qt+1R1×dmodel\mathbf{q}_{t+1} \in \mathbb{R}^{1 \times d_{\text{model}}}. However, to attend to all preceding context tokens, the GPU must fetch all previously computed Key and Value vectors for all layers from HBM:

Arithmetic Intensity=Floating Point Operations (FLOPs)Bytes Transferred (HBM)2×dmodel2×dmodel1 FLOP / byte\text{Arithmetic Intensity} = \frac{\text{Floating Point Operations (FLOPs)}}{\text{Bytes Transferred (HBM)}} \approx \frac{2 \times d_{\text{model}}}{2 \times d_{\text{model}}} \approx 1\text{ FLOP / byte}

Modern Tensor Cores operate at hundreds of teraflops, yet memory bus speeds are orders of magnitude lower. During generation, GPU compute cores idle for over 95% of execution time waiting for KV cache memory loads!

2. Memory Scaling Comparison: MHA vs MQA vs GQA

Consider serving a 70B parameter model (L=80L = 80 layers, H=64H = 64 heads, dhead=128d_{\text{head}} = 128) with sequence length S=4096S = 4096 and batch size B=16B = 16 in FP16 precision (2 bytes):

Multi-Head Attention (MHA)

Each Query head possesses its own Key and Value projection (HKV=H=64H_{\text{KV}} = H = 64):

VRAMMHA=2×B×L×H×S×dhead×2 B\text{VRAM}_{\text{MHA}} = 2 \times B \times L \times H \times S \times d_{\text{head}} \times 2\text{ B}
VRAM=2×16×80×64×4096×128×2171.8 GB\text{VRAM} = 2 \times 16 \times 80 \times 64 \times 4096 \times 128 \times 2 \approx \mathbf{171.8\text{ GB}}

Serving a single batch of 16 sequences exceeds the total capacity of two 80 GB GPUs purely for the KV cache!

Grouped-Query Attention (GQA)

Multiple Query heads share a single Key/Value head (HKV=8H_{\text{KV}} = 8, an 8:1 sharing ratio):

VRAMGQA=2×B×L×HKV×S×dhead×2 B\text{VRAM}_{\text{GQA}} = 2 \times B \times L \times H_{\text{KV}} \times S \times d_{\text{head}} \times 2\text{ B}
VRAM=2×16×80×8×4096×128×221.5 GB\text{VRAM} = 2 \times 16 \times 80 \times 8 \times 4096 \times 128 \times 2 \approx \mathbf{21.5\text{ GB}}

An 8×8\times reduction in memory bandwidth and storage with near-identical modeling performance.

ArchitectureQ HeadsKV HeadsSharing Ratio70B KV Cache (B=16, S=4k)Throughput Relative
MHA (Vaswani 2017)64641 : 1171.8 GB1.0× (Baseline)
GQA (Ainslie 2023 / LLaMA 3)6488 : 121.5 GB4.2×
MQA (Shazeer 2019)64164 : 12.7 GB5.8× (Quality Degrades)

The Architectural Verdict: While MQA achieves maximum bandwidth reduction, empirical research demonstrates quality degradation on complex reasoning and long-context retrieval tasks. GQA strikes the optimal Pareto frontier, achieving 95%95\% of MQA's speed with 100%100\% of MHA's quality.