Skip to content

About

Research framework for training GPT-2 with interchangeable attention mechanisms — MHA, MQA, GQA, sliding-window, linear, sparse (BigBird) and MLA (DeepSeek-V2) — compared under identical conditions.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

104 Commits

Folders and files

Repository files navigation

variantGPT

A research framework for training GPT-2 with interchangeable attention mechanisms. The goal is to make it easy to swap in a different attention variant — from standard multi-head to DeepSeek-V2's MLA — and compare them under identical training conditions.

Attention variants

Key Name Description
mha Multi-Head Attention Standard scaled dot-product attention
mqa Multi-Query Attention Single shared K/V head across all query heads
gqa Grouped-Query Attention n_kv_head groups of K/V heads; generalises MHA and MQA
local Local (Sliding Window) Causal attention within a fixed window_size
linear Linear Attention Kernel-feature-map attention, O(T) compute via chunked parallel form
sparse Sparse Attention BigBird-style: global tokens + sliding window + random connections
mla Multi-Head Latent Attention DeepSeek-V2: low-rank KV compression + decoupled RoPE

Setup

Requires Python ≥ 3.11 and PyTorch 2.10.

pip install -e .

Architecture

src/variant_gpt/
├── attention/          # all attention variants + registry
│   ├── config.py       # AttentionConfig — single dataclass covering all variants
│   ├── base.py         # CausalSelfAttention abstract base class
│   ├── mha.py, mqa.py, gqa.py, local.py, linear.py, sparse.py, mla.py
│   └── __init__.py     # _REGISTRY, build_attention(), register_attention()
├── models/gpt2/
│   ├── configuration.py  # GPT2Config (includes all attention params)
│   └── modeling.py       # GPT2Model, GPT2Block, GPT2MLP
└── activations.py      # activation registry (gelu_new, silu, relu, …)

pretrain/
├── config.py   # TrainConfig — all training hyperparameters as a dataclass
├── train.py    # training loop: single-GPU or multi-GPU via DDP
└── data.py     # PretrainDataset (memory-mapped .bin files) + DataLoaders

notebooks/      # step-by-step pipeline: data cleaning → BPE → pretraining → fine-tuning
minbpe/         # Karpathy's RegexTokenizer (vendored)

Attention registry. Variants are registered with @register_attention("name") and instantiated through build_attention(name, config). Adding a new variant means subclassing CausalSelfAttention, decorating it, and adding the relevant config fields to AttentionConfig — no changes to the model or training code needed.

Model. GPT2Block constructs an AttentionConfig from GPT2Config and calls build_attention to wire in the chosen variant. The rest of the block is standard pre-norm transformer (LayerNorm → attn → residual → MLP → residual). GPT2Model supports torch.compile, Flash Attention (flash=True), fused AdamW, weight tying, and MFU estimation.

Training. TrainConfig drives everything. All fields are CLI-overridable. The loop supports gradient accumulation, bfloat16/float16 mixed precision, DDP, rotating checkpoints, early stopping, and MLflow tracking. Data is memory-mapped flat binary (train.bin / val.bin) of concatenated token IDs.

Running experiments

# Single GPU
python pretrain/train.py --attention_type mha

# Multi-GPU
torchrun --standalone --nproc_per_node=8 pretrain/train.py --attention_type gqa --n_kv_head 4

# Resume (auto-detects latest checkpoint)
python pretrain/train.py --run_name my_run

# MLA example (requires explicit dim config)
python pretrain/train.py \
  --attention_type mla \
  --kv_lora_rank 192 \
  --qk_nope_head_dim 64 \
  --qk_rope_head_dim 32 \
  --v_head_dim 64

MLflow credentials go in pretrain/.env. Training logs per variant (mha.log, mla.log, …) are written to pretrain/.

Tests

pytest                                      # all tests
pytest tests/test_gpt2_numeric.py          # model correctness

Experimental results

All seven variants were trained from scratch on the same dataset for ~10,500 steps under identical hyperparameters.

Full training run

Train loss — full run Validation loss — full run

The most striking feature of the full-run view is how cleanly the variants split into two groups:

  • Tight cluster (MHA, MQA, GQA, Local, Sparse, MLA): all converge along nearly identical trajectories.
  • Linear: starts from a higher initial loss, converges noticeably more slowly, and exhibits a period of training instability (loss spikes around steps 2,400–2,600) — a known symptom of the kernel feature-map approximation being sensitive to the learning rate schedule during the warmup phase.

MLA begins with a significantly higher initial loss (~11 vs ~5.5 for the rest). This cold-start cost reflects the extra parameters introduced by the low-rank KV compression and decoupled RoPE heads needing more gradient steps to stabilize — not a long-term weakness.

Late-training zoom (steps 8,000–10,500)

Train loss — steps 8k–10.5k Validation loss — steps 8k–10.5k

Once the initial transient is gone the validation-loss ranking becomes clear:

Rank Variant Final val loss (≈)
1 MLA 3.338
1 MHA 3.338
3 GQA 3.382
3 Sparse 3.382
5 Local 3.395
6 MQA 3.410
7 Linear 3.490

MHA vs MLA. Despite its slow start, MLA converges to the same validation loss as full MHA. This is the most notable result: MLA's low-rank KV compression yields no quality degradation at this scale, while its inference-time KV cache is substantially smaller.

GQA vs MQA. The gap between them (~0.03) shows that grouping K/V heads (GQA) recovers most of MHA's quality, while collapsing to a single shared K/V head (MQA) introduces a small but consistent deficit.

Sparse ≈ GQA. BigBird-style attention (global tokens + sliding window + random blocks) is competitive with grouped-query full attention. The global tokens appear sufficient to capture the long-range dependencies that would otherwise be missed by the local window alone.

Local vs Sparse. Without global tokens or random connections, local attention trails sparse by ~0.013 — confirming that even a small number of global tokens meaningfully helps.

Linear is the clear outlier. The kernel-based O(T) variant ends ~0.15 behind the leading group on validation loss, with higher training-loss variance throughout. At this context length and model size, the approximation error of the feature map is not amortized away.

About

Research framework for training GPT-2 with interchangeable attention mechanisms — MHA, MQA, GQA, sliding-window, linear, sparse (BigBird) and MLA (DeepSeek-V2) — compared under identical conditions.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages