nanogpt

作者: firecrawl

约300行代码实现的教育性GPT,可在OpenWebText上复现GPT-2(124M)。干净、可修改的代码,用于学习Transformer。作者:Andrej Karpathy。……

npx skills add https://github.com/firecrawl/ai-research-skills --skill nanogpt

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

来自 firecrawl 的更多技能

oracle
firecrawl
使用oracle CLI的最佳实践(提示词与文件打包、引擎、会话及文件附件模式)。
official
firecrawl-monitor
firecrawl
检测网站内容变化,并通过webhook或邮件接收通知——无需cron任务、爬虫或差异脚本。当用户想要追踪页面变化、监控竞争对手定价、在新职位或博客发布时接收提醒、监测文档/更新日志/状态页面,或说出“监控”、“关注”、“追踪”、“当……时提醒我”、“当X变化时通知我”、“如果……请通知我”、“当……时发邮件给我”或“当……时发送webhook”时,使用此技能。内置AI判断器会过滤掉格式、时间戳和……
officialweb-scrapingresearch
firecrawl-deep-research
firecrawl
使用 Firecrawl 进行多源深度研究。当用户要求研究某个主题、比较不同观点、生成带来源的简报、调查技术或市场问题,或综合多个来源的网络证据时使用。
officialresearchweb-scraping
firecrawl-research-papers
firecrawl
使用Firecrawl查找并综合研究论文、白皮书、PDF文件、技术报告及学术来源。适用于用户需要文献综述、论文摘要、研究现状分析,或从PDF及学术/行业出版物中获取有来源的综合内容时。
officialresearchweb-scraping
firecrawl-market-research
firecrawl
使用Firecrawl提取市场、财务、收益、行业和公司指标。当用户询问市场研究、行业趋势、上市公司数据、财务比较、收益研究或结构化市场报告时使用。
officialresearchweb-scraping
firecrawl-website-design-clone
firecrawl
使用 Firecrawl 抓取证据,将任意网站的设计系统提取为可供智能体使用的 DESIGN.md 文件。当用户需要从网站获取颜色、字体、间距、组件、布局模式或品牌/UI 指导,以便 AI 智能体创建新网站、克隆外观或受该设计启发构建页面时使用。
officialdesignweb-scraping
firecrawl-knowledge-base
firecrawl
使用Firecrawl从网页内容构建知识库。适用于本地参考文档、RAG就绪文本块、微调数据集、文档镜像、主题语料库,或从网页来源整理的LLM就绪Markdown。
officialweb-scrapingresearch
firecrawl-lead-research
firecrawl
使用Firecrawl生成会前潜在客户情报简报。适用于用户在销售通话、合作会议、投资者对话或客户访谈前需要公司调研、人物调研、最新动态、谈话要点、痛点分析或外联准备时。
officialresearchweb-scraping