Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
orchestra-research avatar

Nanogpt

  • 399 installs
  • 11.2k repo stars
  • Updated June 16, 2026
  • orchestra-research/ai-research-skills

nanogpt is an Orchestra Research Claude Code skill that guides developers to build and train a minimal GPT-2 transformer in roughly 300 lines of PyTorch for learning language model internals.

About

nanogpt is an Orchestra Research AI Research Skills package teaching Karpathy-style educational GPT implementation in approximately 300 lines of PyTorch (283 lines in model.py plus reference docs). The skill covers CausalSelfAttention with multi-head masked self-attention, token embeddings, feed-forward blocks, and a clean GPT-2 configuration suitable for training experiments. Developers reach for nanogpt when learning transformer architecture, prototyping small language models, or teaching LLM internals without navigating full frameworks like Hugging Face Transformers or distributed training stacks. It ships as part of the 86-skill ai-research-skills library installable via npx @orchestra-research/ai-research-skills and targets hands-on architecture comprehension over production-scale training.

  • Clean GPT-2 implementation in ~300 lines
  • Educational transformer architecture with multi-head attention
  • Minimal dependencies for learning language model internals

Nanogpt by the numbers

  • 399 all-time installs (skills.sh)
  • +38 installs in the week ending Jul 18, 2026 (Skillselion tracking)
  • Ranked #1,943 of 16,659 AI & Agent Building skills by installs in the Skillselion catalog
  • Security screen: MEDIUM risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/orchestra-research/ai-research-skills --skill nanogpt

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs399
repo stars11.2k
Security audit2 / 3 scanners passed
Last updatedJune 16, 2026
Repositoryorchestra-research/ai-research-skills

How do you implement a minimal GPT-2 in PyTorch?

Build and train minimal GPT-2 models to understand transformer architecture and language model internals.

Who is it for?

ML engineers and researchers learning transformer internals who want a compact PyTorch GPT-2 reference implementation before scaling to larger frameworks.

Skip if: Production LLM deployment teams needing vLLM serving, distributed training, or billion-parameter model infrastructure.

When should I use this skill?

A developer asks to implement NanoGPT, understand GPT-2 attention blocks, or train a minimal transformer from scratch in PyTorch.

What you get

Working NanoGPT model.py with CausalSelfAttention layers, training scripts, and a trainable small GPT-2 prototype.

  • NanoGPT model.py architecture
  • Training loop scripts
  • Transformer architecture reference docs

By the numbers

  • NanoGPT GPT-2 implementation is approximately 300 lines (283 lines in model.py plus 3 refs)
  • Part of Orchestra ai-research-skills library with 86 skills across 22 categories

Files

SKILL.mdMarkdownGitHub ↗

nanoGPT - Minimalist GPT Training

Quick start

nanoGPT is a simplified GPT implementation designed for learning and experimentation.

Installation:

pip install torch numpy transformers datasets tiktoken wandb tqdm

Train on Shakespeare (CPU-friendly):

# Prepare data
python data/shakespeare_char/prepare.py

# Train (5 minutes on CPU)
python train.py config/train_shakespeare_char.py

# Generate text
python sample.py --out_dir=out-shakespeare-char

Output:

ROMEO:
What say'st thou? Shall I speak, and be a man?

JULIET:
I am afeard, and yet I'll speak; for thou art
One that hath been a man, and yet I know not
What thou art.

Common workflows

Workflow 1: Character-level Shakespeare

Complete training pipeline:

# Step 1: Prepare data (creates train.bin, val.bin)
python data/shakespeare_char/prepare.py

# Step 2: Train small model
python train.py config/train_shakespeare_char.py

# Step 3: Generate text
python sample.py --out_dir=out-shakespeare-char

Config (config/train_shakespeare_char.py):

# Model config
n_layer = 6          # 6 transformer layers
n_head = 6           # 6 attention heads
n_embd = 384         # 384-dim embeddings
block_size = 256     # 256 char context

# Training config
batch_size = 64
learning_rate = 1e-3
max_iters = 5000
eval_interval = 500

# Hardware
device = 'cpu'  # Or 'cuda'
compile = False # Set True for PyTorch 2.0

Training time: ~5 minutes (CPU), ~1 minute (GPU)

Workflow 2: Reproduce GPT-2 (124M)

Multi-GPU training on OpenWebText:

# Step 1: Prepare OpenWebText (takes ~1 hour)
python data/openwebtext/prepare.py

# Step 2: Train GPT-2 124M with DDP (8 GPUs)
torchrun --standalone --nproc_per_node=8 \
  train.py config/train_gpt2.py

# Step 3: Sample from trained model
python sample.py --out_dir=out

Config (config/train_gpt2.py):

# GPT-2 (124M) architecture
n_layer = 12
n_head = 12
n_embd = 768
block_size = 1024
dropout = 0.0

# Training
batch_size = 12
gradient_accumulation_steps = 5 * 8  # Total batch ~0.5M tokens
learning_rate = 6e-4
max_iters = 600000
lr_decay_iters = 600000

# System
compile = True  # PyTorch 2.0

Training time: ~4 days (8× A100)

Workflow 3: Fine-tune pretrained GPT-2

Start from OpenAI checkpoint:

# In train.py or config
init_from = 'gpt2'  # Options: gpt2, gpt2-medium, gpt2-large, gpt2-xl

# Model loads OpenAI weights automatically
python train.py config/finetune_shakespeare.py

Example config (config/finetune_shakespeare.py):

# Start from GPT-2
init_from = 'gpt2'

# Dataset
dataset = 'shakespeare_char'
batch_size = 1
block_size = 1024

# Fine-tuning
learning_rate = 3e-5  # Lower LR for fine-tuning
max_iters = 2000
warmup_iters = 100

# Regularization
weight_decay = 1e-1

Workflow 4: Custom dataset

Train on your own text:

# data/custom/prepare.py
import numpy as np

# Load your data
with open('my_data.txt', 'r') as f:
    text = f.read()

# Create character mappings
chars = sorted(list(set(text)))
stoi = {ch: i for i, ch in enumerate(chars)}
itos = {i: ch for i, ch in enumerate(chars)}

# Tokenize
data = np.array([stoi[ch] for ch in text], dtype=np.uint16)

# Split train/val
n = len(data)
train_data = data[:int(n*0.9)]
val_data = data[int(n*0.9):]

# Save
train_data.tofile('data/custom/train.bin')
val_data.tofile('data/custom/val.bin')

Train:

python data/custom/prepare.py
python train.py --dataset=custom

When to use vs alternatives

Use nanoGPT when:

  • Learning how GPT works
  • Experimenting with transformer variants
  • Teaching/education purposes
  • Quick prototyping
  • Limited compute (can run on CPU)

Simplicity advantages:

  • ~300 lines: Entire model in model.py
  • ~300 lines: Training loop in train.py
  • Hackable: Easy to modify
  • No abstractions: Pure PyTorch

Use alternatives instead:

  • HuggingFace Transformers: Production use, many models
  • Megatron-LM: Large-scale distributed training
  • LitGPT: More architectures, production-ready
  • PyTorch Lightning: Need high-level framework

Common issues

Issue: CUDA out of memory

Reduce batch size or context length:

batch_size = 1  # Reduce from 12
block_size = 512  # Reduce from 1024
gradient_accumulation_steps = 40  # Increase to maintain effective batch

Issue: Training too slow

Enable compilation (PyTorch 2.0+):

compile = True  # 2× speedup

Use mixed precision:

dtype = 'bfloat16'  # Or 'float16'

Issue: Poor generation quality

Train longer:

max_iters = 10000  # Increase from 5000

Lower temperature:

# In sample.py
temperature = 0.7  # Lower from 1.0
top_k = 200       # Add top-k sampling

Issue: Can't load GPT-2 weights

Install transformers:

pip install transformers

Check model name:

init_from = 'gpt2'  # Valid: gpt2, gpt2-medium, gpt2-large, gpt2-xl

Advanced topics

Model architecture: See references/architecture.md for GPT block structure, multi-head attention, and MLP layers explained simply.

Training loop: See references/training.md for learning rate schedule, gradient accumulation, and distributed data parallel setup.

Data preparation: See references/data.md for tokenization strategies (character-level vs BPE) and binary format details.

Hardware requirements

  • Shakespeare (char-level):
  • CPU: 5 minutes
  • GPU (T4): 1 minute
  • VRAM: <1GB
  • GPT-2 (124M):
  • 1× A100: ~1 week
  • 8× A100: ~4 days
  • VRAM: ~16GB per GPU
  • GPT-2 Medium (350M):
  • 8× A100: ~2 weeks
  • VRAM: ~40GB per GPU

Performance:

  • With compile=True: 2× speedup
  • With dtype=bfloat16: 50% memory reduction

Resources

  • GitHub: https://github.com/karpathy/nanoGPT ⭐ 48,000+
  • Video: "Let's build GPT" by Andrej Karpathy
  • Paper: "Attention is All You Need" (Vaswani et al.)
  • OpenWebText: https://huggingface.co/datasets/Skylion007/openwebtext
  • Educational: Best for understanding transformers from scratch

Related skills

How it compares

Choose nanogpt over distributed training skills when the goal is learning GPT-2 internals in minimal PyTorch, not scaling to Llama-class models.

FAQ

How large is the NanoGPT implementation?

NanoGPT implements a clean GPT-2 architecture in roughly 300 lines of PyTorch code, with model.py at about 283 lines plus three reference documents. The skill targets educational understanding of transformer internals.

What architecture does nanogpt cover?

nanogpt covers a GPT-2 stack with CausalSelfAttention using batched key-query-value projections, feed-forward blocks, token embeddings, and configuration-driven head counts. Developers can train small prototypes to study language model behavior.

Is Nanogpt safe to install?

skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

AI & Agent Buildingllmresearchautomation

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.