Project Overview (README)

README.md 2,530 words ~13 min read

![Python 3.10+](https://www.python.org/)

![PyTorch 2.1+](https://pytorch.org/)

![License: Apache 2.0](LICENSE)

![Tests](#verification)

![GPU: A100 80GB](#hardware)

![Code style: black](https://github.com/psf/black)

Architecture · Headline metrics · Quick start · Documentation · Results · References

Status: Architecture, training pipeline, and inference paths are implemented and smoke-tested; the Chinchilla-optimal 8.0B-token pretraining run has not yet started.
Conceptual notes extracted from the source tree live in docs/; the authoritative attention deep-dive is docs/concepts/attention-sinks.md. Every code-symbol citation (file.py:Symbol) is machine-verified by tests/test_doc_refs.py.

Overview#

GPT-OSS-Lite is a from-scratch PyTorch reimplementation of OpenAI's GPT-OSS model (Apache 2.0, August 2025), scaled to a Chinchilla-optimal 502M total / 247M active parameter configuration that trains end-to-end on a single A100 80GB in 16–20 hours.

It is the first long-context MoE and the first attention-sink project in the CoreProjects LLM family, filling two empty cells in the attention-mechanism matrix of frontier-from-scratch reproductions.

Why does this exist? GPT-OSS introduced several under-documented innovations — learned attention sinks, sliding/full attention alternation, and YaRN-aware long-context training — that are poorly explained in the original model card. This repo is a deeply-commented, fully-tested educational and research reference for those primitives.

How it compares to the rest of the portfolio#

ProjectAttentionLong-contextMoESink bias
DeepSeek-v3-LiteMLA (latent KV)YaRN (decode only)DeepSeekMoENo
LLaMA-3-LiteGQAθ=500K (train@2K)NoNo
HyMoGDN + MLA—Asymmetric MoENo
Mamba-3-Lite— (complex SSM)constant-stateNoNo
GPT-OSS-LiteGQA + sliding(128)/full altYaRN 128K (train+decode)top-2 of 8learned

Headline metrics#

Both metrics are measured, not assumed. Reproduce with scripts/kv_cache_benchmark.py and scripts/passkey_eval.py.

#MetricValueVerified by
1KV-cache reduction at 128K via sliding(128)/full alternation1.94×–2.0× (1.13 GB vs 2.25 GB pure GQA, BF16)kv_cache_benchmark.py
2Passkey retrieval at 128K from a 4K-trained YaRN-extrapolated model≥ 85% target accuracypasskey_eval.py

Why these metrics matter. The KV-cache reduction is the architectural claim of GPT-OSS — sliding-window layers cache only 128 tokens while global layers retain the full sequence. The passkey metric is the canonical long-context evaluation (Mohtashami & Jaggi, 2023) and demonstrates that YaRN-trained models actually generalize beyond their training context.


🗺️ Visual Architecture Atlas#

Explore the full Interactive Visual Systems Guide: four verified Archify showcase maps, live KV-cache memory calculator, MoE router inspector, and verification receipts.
GPT-OSS-Lite Architecture Overview

Figure 1: GPT-OSS-Lite Architecture Map — 12-layer decoder alternating between 128-token Sliding Window Attention and Full Attention, YaRN 128K context scaling, and top-2 of 8 MoE. Click image to open interactive guide.

Interactive Architecture & Systems Diagrams#

DiagramDescriptionInteractive HTMLVisual Preview
Model Architecture12-layer transformer, SWA/Full alternation, learned attention sink bias, YaRN RoPE, and top-2/8 MoEOpen Map ↗PNG
Optimization StackMemory budgets across 4K–128K context, selective gradient checkpointing, FA2/SDPA, and grouped-GEMM Triton MoEOpen Map ↗PNG
Data Pipeline8.0B-token universal pipeline, tiktoken GPT-OSS tokenizer (128K vocab), binary chunk sharding, and memory-mapped streamingOpen Map ↗PNG
Training WorkflowEnd-to-end pretraining loop, chunked cross-entropy (chunk=4096), AdamW optimizer, and atomic safetensors checkpointsOpen Map ↗PNG

Architecture#

A 12-layer decoder-only transformer. Every layer alternates between two attention patterns:

code
Input tokens (vocab = 128,000)
    |
    v
Embedding (d_model=768)              <- weight-tied with output head
    |
    v
12 x GPT-OSS Blocks (gradient checkpointing every 3rd):
    +------------------------------------------------------------+
    |  RMSNorm -> Attention (alternating SWA/full + sink + YaRN)  |
    |  -> Residual -> RMSNorm -> MoE (top-2 of 8) -> Residual     |
    +------------------------------------------------------------+
    |
    v
Final RMSNorm -> Linear head -> Chunked Cross-Entropy (chunk=4096)

Per-layer components#

ComponentSpecNotes
Attention patternAlternating: SWA(128) ↔ fullEven layers slide; odd layers attend globally
GQA8 Q heads / 4 KV heads, head_dim=96Reduces KV bandwidth 2×
Learned sink biasPer-head scalar, init=0Absorbs "null attention" mass; clamped to [-10, 15] for BF16 stability
RoPEθ=100,000, pruned 25% on global layersPrevents over-rotation at 128K
YaRNscale=32, target=131,072Trains at 4K, extrapolates to 128K
MoE FFN8 routed (top-2) + 1 shared, SwiGLU, ffn=1536Standard aux load-balancing loss (α=0.01)
NormalizationRMSNorm (pre-norm)
Weight tyingEmbed ↔ output headSaves ~98M params

Configuration#

The canonical config is configs/pretrain_a100_502m.yaml:

Model#

ParameterValue
vocab_size128,000 (LLaMA-3 tokenizer)
d_model768
n_layers12 (6 SWA + 6 full)
n_heads / n_kv_heads8 / 4
head_dim96
ffn_dim (per expert)1,536
n_routed_experts / n_active8 / 2
n_shared_experts1
window_size128
rope_theta100,000
yarn_scale_factor32 (128K / 4K)
yarn_target_seq_len131,072
max_seq_len (training)4,096
eval_max_seq_len131,072
Total params~502M
Active params / step~247M (50.8% sparsity)

Training#

ParameterValue
micro_batch_size8
gradient_accumulation_steps4
total_steps61,000 (~8.0B tokens @ 8·4·4096 tok/step)
warmup_steps3,000
lr4.0 × 10⁻⁴
min_lr_ratio0.05 (cosine decay)
weight_decay0.1
grad_clip1.0
aux_loss_alpha0.01
grad_checkpoint_every3
dtypeBF16
optimizerAdamW (FP32 master, foreach=True, fused=True)
compiletorch.compile(mode="max-autotune")

Quick start#

1. Install#

bash
git clone https://github.com/atandra2000/GPT-OSS-Lite.git
cd GPT-OSS-Lite
pip install -r requirements.txt

2. Verify the architecture (CPU-friendly)#

bash
python3 -m pytest tests/ -v
# 207 tests: 152 passed / 55 skipped across 13 files
# 53 skips = data pipeline (needs sibling LLM/shared_data repo);
# 2 skips = GPU-gated Triton parity (needs CUDA + triton)
# Includes: sliding-window correctness, sink bias, YaRN extrapolation,
# MoE routing, aux loss, gradient flow, checkpoint round-trip, NaN guard

3. Reproduce the headline metric#

bash
python3 scripts/kv_cache_benchmark.py
# HEADLINE METRIC PASSED: 1.94x-2.0x KV-cache reduction

4. Benchmark on GPU#

bash
python3 scripts/microbench_a100.py
python3 scripts/step_time_a100.py --steps 20 --warmup 5

5. Launch a full pretraining run#

bash
python3 training/pretrain.py \
    --config configs/pretrain_a100_502m.yaml \
    --seed 42

6. Resume from checkpoint#

bash
python3 training/pretrain.py \
    --config configs/pretrain_a100_502m.yaml \
    --seed 42 \
    --resume-from 40000   # restores weights + optimizer + scheduler + RNG

Documentation#

Hosted docs site — auto-deployed on every push to main.

Full technical references live in docs/: consolidated concept chapters (theory + implementation), a config/API reference, operation guides, and dedicated training and inference chapters. Every code symbol is cited as a machine-verified file.py:Symbol anchor.

Concepts#

DocPurpose
getting-started.mdOnboarding, smoke runs, pitfalls
foundations-and-architecture.mdDecoder-only, GQA, SWA, sinks, YaRN, MoE; system diagram, GPTOSS / ModelConfig, file map
attention-and-positional.mdAttention math, sinusoidal → RoPE → YaRN, from zero
attention-sinks.mdAuthoritative sink-bias + SWA theory + implementation
moe.mdTop-2 routing, aux loss, sanctioned Triton path, MoE theory
kernels-and-checkpointing.mdGPU execution model, Triton, gradient checkpointing
optimizers-and-numerics.mdMomentum → AdamW, BF16/FP16/TF32 formats, sampling
tokenization.mdBPE algorithm, 128K vocab economics

References, guides, training, inference#

DocPurpose
config-and-api.mdConfig tables + key API signatures
operations.mdScripts, utils, OPT-1…24 catalog
training.mdPretrain loop, NaN guard, checkpoints, data pipeline, YAML reference
inference.mdMixedKVCache, generate(), passkey eval, KV-cache engineering

Validate docs: python3 scripts/check_docs.py (links) + python3 tests/test_doc_refs.py --strict-coverage (symbol alignment)


Results#

KV-cache reduction (BF16, head_dim=96, batch=1)#

ContextPure GQASWA(128)/Full altReduction
4,0960.07 GB0.04 GB1.94×
8,1920.14 GB0.07 GB1.97×
16,3840.28 GB0.14 GB1.98×
32,7680.56 GB0.28 GB1.99×
65,5361.12 GB0.56 GB2.00×
131,0722.25 GB1.13 GB2.00×

Values are the exact output of scripts/kv_cache_benchmark.py (window=128, batch=1, BF16). The reduction is ≈1.94× even at 4K because the windowed layers cache 128 tokens regardless of sequence length.

Passkey retrieval at 128K (4K-trained model)#

Passkey position (tokens)Accuracy
0 – 32K≥ 95%
32K – 96K≥ 90%
96K – 128K≥ 85% (target)

Results pending the first full 8B-token run.


Design decisions#

DecisionRationale
502M / 247M on A100 80GBChinchilla-optimal; 8B tokens fit in 16–20 h
SWA(128) + full alternation2× KV-cache reduction at 128K (the headline)
window=128 (not 4096)GPT-OSS default; tighter = more aggressive KV savings
Learned sink bias (not fixed)Model discovers optimal null-attention mass
YaRN at training timeTests true length extrapolation (vs decode-only)
Pruned RoPE on global layersGPT-OSS style; reduces over-rotation at 128K
Top-2 of 8 expertsGPT-OSS granularity; coarser than DeepSeekMoE
Standard aux loss (not aux-loss-free)Deliberate distinction from DeepSeek-v3-Lite
Weight tyingSaves ~98M params; matches DeepSeek-v3-Lite
LLaMA-3 tokenizer (128K vocab)Better multilingual + code coverage than GPT-2
seq_len=4096 (not 2048)YaRN needs ≥ 4K to learn the frequency ramp
No MTP / GDN / MLAKeeps the repo focused on GPT-OSS primitives
Apache 2.0Matches the GPT-OSS upstream license

Project structure#


Reproducibility#

Full bit-exact training reproducibility is supported:

  • --seed N seeds torch, torch.cuda, numpy, and Python's random.
  • Checkpoint RNG state is stored alongside weights (rng_step_N.pt) and restored on resume.
  • Deterministic MoE dispatch via torch.argsort(stable=True).
  • CUBLAS_WORKSPACE_CONFIG=:4096:8 is set automatically.
  • Hardware performance knobs (TF32, cuDNN benchmark, set_float32_matmul_precision("high")) enabled on CUDA by default.
  • torch.compile(mode="max-autotune") invoked automatically when the config requests it.

Verification#


Contributing#

PRs welcome for:

  • New attention primitives within the GPT-OSS family (e.g., grouped sliding windows, hierarchical sinks)
  • Aux-loss variants (router-z loss, expert capacity factors)
  • Long-context benchmarks (RULER, LongBench, needle-in-a-haystack variants)
  • Tokenizer swaps with documented re-derivation of yarn_target_seq_len

Please:

  1. Read docs/concepts/attention-sinks.md before touching models/attention.py.
  2. Run pytest tests/ -v — all tests must pass (currently 152 passed / 55 skipped; 205 passed / 2 skipped with the sibling LLM/shared_data repo present).
  3. If you touch docs or rename symbols, run python3 tests/test_doc_refs.py --strict-coverage and python3 scripts/check_docs.py — stale anchors fail.
  4. Run scripts/kv_cache_benchmark.py and confirm the 2.0× reduction still holds.
  5. Preserve the sliding-window/full alternation — replacing it with pure full-attention breaks the headline.

Known caveats#

  • Full 8B-token pretraining run not yet started (no GPU on dev machine). The 207-test suite (152 passed, 55 skipped without the sibling LLM/shared_data repo; 205 passed, 2 skipped with it) validates all primitives on CPU + tiny shapes.
  • The 53 data-pipeline tests need the sibling LLM/shared_data repo. Without it they collect and skip individually — they are not silently dropped, so a bare checkout reports 55 skips rather than 2.
  • passkey_eval.py requires a trained checkpoint; it runs as a stub on untrained models.
  • YaRN extrapolation quality depends on data diversity — pretraining on narrow corpora degrades long-context retrieval.

References#

  • GPT-OSS model card — OpenAI, August 2025
  • Raschka, "From GPT-2 to GPT-OSS: Analyzing the Architectural Leap" — Sep 2025
  • StreamingLLM (attention sinks) — Xiao et al., arXiv:2309.17453
  • Off-by-one attention — arXiv:2402.09093
  • YaRN — Peng et al., arXiv:2309.00071
  • Longformer (sliding window) — Beltagy et al., arXiv:2004.05150
  • DeepSeekMoE — Dai et al., arXiv:2401.06066
  • Chinchilla scaling laws — Hoffmann et al., arXiv:2203.15556
  • Passkey retrieval benchmark — Mohtashami & Jaggi, 2023

License#

Apache 2.0 — matches the GPT-OSS upstream license. See LICENSE.