nanochat-llm-training▌
aradotso/trending-skills · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
Skill by ara.so — Daily 2026 Skills collection.
nanochat LLM Training
Skill by ara.so — Daily 2026 Skills collection.
nanochat is Karpathy's minimal, hackable harness for training LLMs end-to-end on a single GPU node. It covers tokenization, pretraining, SFT finetuning, RL, evaluation (DCLM CORE score), inference with KV cache, and a ChatGPT-like web UI. A single complexity dial (--depth) auto-configures all other hyperparameters (width, heads, LR, training horizon, weight decay) for compute-optimal training. You can reproduce GPT-2 capability (~$43,000 in 2019) for ~$48 on an 8×H100 node (~2 hours).
Installation
nanochat uses uv for dependency management:
git clone https://github.com/karpathy/nanochat.git
cd nanochat
# Install uv if needed
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create venv and install deps
uv sync
source .venv/bin/activate
Key Commands
Full GPT-2 Speedrun (8×H100 node, ~2–3 hours, ~$48)
# Run the reference pipeline: data download, pretraining, SFT, eval, chat
bash runs/speedrun.sh
Pretraining (distributed)
OMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \
--depth=26 \
--run="d26_run" \
--model-tag="d26"
Pretraining (single GPU)
python -m scripts.base_train -- \
--depth=26 \
--run="d26_single"
Quick Research Iteration (~5 min, GPT-1 scale)
OMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \
--depth=12 \
--run="d12_exp" \
--model-tag="d12" \
--core-metric-every=999999 \
--sample-every=-1 \
--save-every=-1
CPU / Apple Silicon (tiny model, ~minutes)
bash runs/runcpu.sh
Serve Chat UI
# After training completes
source .venv/bin/activate
python -m scripts.chat_web
# Visit http://<your-server-ip>:8000/
CLI Chat
python -m scripts.chat_cli -p "hello"
Scaling Laws / Miniseries
bash runs/scaling_laws.sh # sweep depths for scaling law data
bash runs/miniseries.sh # train full compute-optimal miniseries
The Depth Dial
The single most important parameter. Everything else is derived automatically:
--depth |
Approximate model scale | Notes |
|---|---|---|
| 6–8 | Tiny (toy) | CPU/MPS feasible |
| 12 | GPT-1 size | ~5 min on 8×H100, great for research iteration |
| 16 | Medium | ~15 min on 8×H100 |
| 24–26 | GPT-2 size | ~2 hrs on 8×H100, ~$48 |
# Smaller/faster experiments
python -m scripts.base_train -- --depth=12 --run="quick_test"
# Full GPT-2 grade
torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- --depth=26 --run="gpt2_repro"
Precision / dtype Configuration
nanochat uses explicit dtype management via COMPUTE_DTYPE in nanochat/common.py. No torch.amp.autocast.
| Hardware | Default | Override |
|---|---|---|
| CUDA SM 80+ (A100, H100) | bfloat16 |
NANOCHAT_DTYPE=float32 |
| CUDA SM < 80 (V100, T4) | float32 |
NANOCHAT_DTYPE=float16 |
| CPU / MPS | float32 |
— |
# Force fp32 for inference
NANOCHAT_DTYPE=float32 python -m scripts.chat_cli -p "hello"
# Force bf16 for training
NANOCHAT_DTYPE=bfloat16 torchrun --nproc_per_node=8 -m scripts.base_train
# float16 training (enables GradScaler automatically)
NANOCHAT_DTYPE=float16 torchrun --nproc_per_node=8 -m scripts.base_train
How it works: Weights stored in fp32 (optimizer precision), custom Linear casts to COMPUTE_DTYPE in forward pass, embeddings stored directly in COMPUTE_DTYPE to save memory.
Key Python Modules
nanochat/
├── gpt.py # GPT nn.Module Transformer
├── engine.py # Inference with KV Cache
├── dataloader.py # Tokenizing Distributed Data Loader
├── dataset.py # Download/read utils for pretraining data
├── optim.py # AdamW + Muon optimizer (1GPU and distributed)
├── core_eval.py # DCLM CORE score evaluation
├── loss_eval.py # Bits-per-byte evaluation
├── checkpoint_manager.py # Save/Load checkpoints
├── common.py # Utilities, COMPUTE_DTYPE
├── execution.py # Python code execution tool for LLM
└── engine.py # Efficient KV-cache inference
scripts/
├── base_train.py # Pretraining entry point
├── chat_web.py # Web chat UI server
└── chat_cli.py # CLI chat interface
runs/
├── speedrun.sh # Reference full pipeline (GPT-2 speedrun)
├── scaling_laws.sh # Scaling law sweeps
├── miniseries.sh # Full compute-optimal miniseries
└── runcpu.sh # CPU/MPS example
Real Code Examples
Load and Run Inference on a Trained Model
import torch
from nanochat.gpt import GPT
from nanochat.engine import InferenceEngine
from nanochat.checkpoint_manager import CheckpointManager
# Load checkpoint
ckpt_manager = CheckpointManager("checkpoints/d26")
model, config = ckpt_manager.load()
model.eval()
# Run inference with KV cache
engine = InferenceEngine(model)
output = engine.generate(
prompt="Once upon a time",
max_new_tokens=200,
temperature=0.8,
top_p=0.95,
)
print(output)
Custom Training Script with Depth Dial
import subprocess
def train_model(depth: int, run_name: str, nproc: int = 8):
"""Launch a compute-optimal training run for given depth."""
cmd = [
"torchrun",
"--standalone",
f"--nproc_per_node={nproc}",
"-m", "scripts.base_train",
"--",
f"--depth={depth}",
f"--run={run_name}",
f"--model-tag={run_name}",
]
subprocess.run(cmd, env={"OMP_NUM_THREADS": "1", **__import__("os").environ})
# Quick research iteration
train_model(depth=12, run_name="my_experiment_d12")
# Full GPT-2 grade
train_model(depth=26, run_name="my_gpt2_repro")
Adjust Device Batch Size for Lower VRAM
# Default device_batch_size=32 needs ~80GB VRAM per GPU
# Reduce for smaller GPUs (gradient accumulation handles the rest)
torchrun --standalone --nproc_per_node=4 -m scripts.base_train -- \
--depth=12 \
--device_batch_size=16 \
--run="low_vram_run"
# Even smaller
python -m scripts.base_train -- \
--depth=8 \
--device_batch_size=4 \
--run="single_gpu_small"
Monitoring Key Metrics in wandb
# nanochat logs to wandb automatically. Key metrics to watch:
# - val_bpb: validation loss in bits-per-byte (vocab-size-invariant)
# as a function of step, total_training_time, total_training_flops
# - core_metric: DCLM CORE score (target > 0.2565 to beat GPT-2)
# - train/mfu: Model FLOPS utilization
# - train/tok_per_sec: Training throughput
# Set wandb project via env var before training
import os
os.environHow to use nanochat-llm-training on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add nanochat-llm-training
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches nanochat-llm-training from GitHub repository aradotso/trending-skills and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate nanochat-llm-training. Access the skill through slash commands (e.g., /nanochat-llm-training) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
Task Automation & Efficiency
Automate repetitive workflows and reduce manual effort
Example
Generate reports, summarize documents, draft communications
Save 3-5 hours per week on routine tasks
Knowledge Enhancement
Learn new skills, understand complex topics, get expert guidance
Example
Explain concepts, provide examples, suggest learning resources
Accelerate learning and skill development by 2x
Quality Improvement
Enhance output quality through reviews, suggestions, and refinements
Example
Review drafts, suggest improvements, catch errors
Improve work quality by 30-40% with less effort
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client with skill support
- ›Clear understanding of task or problem to solve
- ›Willingness to iterate and refine outputs
Time Estimate
15-45 minutes depending on use case complexity
Installation Steps
- 1.Install skill using provided installation command
- 2.Test with simple use case relevant to your work
- 3.Evaluate output quality and relevance
- 4.Iterate on prompts to improve results
- 5.Integrate into regular workflow if valuable
Common Pitfalls
- ⚠Expecting perfect results without iteration
- ⚠Not providing enough context in prompts
- ⚠Using skill for tasks outside its intended scope
- ⚠Accepting outputs without review and validation
Best Practices▌
✓ Do
- +Start with clear, specific prompts
- +Provide relevant context and constraints
- +Review and refine all outputs before using
- +Iterate to improve output quality
- +Document successful prompt patterns
✗ Don't
- −Don't use without understanding skill limitations
- −Don't skip validation of outputs
- −Don't share sensitive information in prompts
- −Don't expect skill to replace human judgment
💡 Pro Tips
- ★Be specific about desired format and style
- ★Ask for multiple options to choose from
- ★Request explanations to understand reasoning
- ★Combine AI efficiency with human expertise
When to Use This▌
✓ Use When
Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.
✗ Avoid When
Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.
Learning Path▌
- 1Familiarize yourself with skill capabilities and limitations
- 2Start with low-risk, non-critical tasks
- 3Progress to more complex and valuable use cases
- 4Build expertise through regular use and experimentation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.5★★★★★34 reviews- ★★★★★James Harris· Dec 20, 2024
Useful defaults in nanochat-llm-training — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Daniel Mensah· Dec 20, 2024
Solid pick for teams standardizing on skills: nanochat-llm-training is focused, and the summary matches what you get after install.
- ★★★★★Chaitanya Patil· Dec 8, 2024
I recommend nanochat-llm-training for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Amina Nasser· Dec 8, 2024
nanochat-llm-training is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Piyush G· Nov 27, 2024
Useful defaults in nanochat-llm-training — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Amelia Ghosh· Nov 27, 2024
nanochat-llm-training reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★Amina Brown· Nov 23, 2024
Keeps context tight: nanochat-llm-training is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Aarav Choi· Nov 11, 2024
I recommend nanochat-llm-training for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Michael Menon· Nov 11, 2024
Registry listing for nanochat-llm-training matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Shikha Mishra· Oct 18, 2024
nanochat-llm-training is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
showing 1-10 of 34