Downloads · 30 days
275
21% of all-time downloads
HarleyCooper/nanochat561
nanochat561 is a text generation model from HarleyCooper. Use it when you need the model to write or continue text. It is set up for nanochat. The card lists the license as mit.
Status (Oct 22, 2025 @ 11:30 PM MT): Oops again! The tokenizer files on the Hub got out of sync with the weights, so HarleyCooper/nanochat561 currently produces gibberish at inference and I am unsure of the fix. That…
Downloads · 30 days
275
21% of all-time downloads
All-time downloads
1.3K
Public
Parameters
561M
8.2 GB on disk
Likes
6
Public
Click a slice to open those files.
.safetensors2.2 GB · 60%
From the Hugging Face model README
Status (Oct 22, 2025 @ 11:30 PM MT): Oops again! The tokenizer files on the Hub got out of sync with the weights, so
HarleyCooper/nanochat561currently produces gibberish at inference and I am unsure of the fix. That package was meant to be used alongside Karpathy’s custom tokenizer/model modules (trust_remote_code=True). During the dozen tweaks I attempted, I also changed the tokenizer metadata several times, so the pickled tokenizer and the model weights went out of sync. Also, I can’t find my original.ptcheckpoints.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "HarleyCooper/nanochat561"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=True, trust_remote_code=False)
model = AutoModelForCausalLM.from_pretrained(
model_id,
trust_remote_code=False,
use_safetensors=True,
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
).to(device)
model.eval()
“Oops I thought I had a custom-model-to-HF inference converter but it's not working. You can run locally, or in HF Spaces I will put up, Gradio, or the inference Karpathy built right out of the box. – christian”

nanochat’s published checkpoint is a 20-layer Transformer with 560,988,160 learnable parameters. The count comes from:
| Component | Calculation | Params |
|---|---|---|
| Token embedding | 65,536 vocab × 1,280 dim | 83,886,080 |
| 20 × Attention projections | 20 × (4 × 1,280 × 1,280) | 131,072,000 |
| 20 × MLP projections | 20 × [1,280 × (4 × 1,280) + (4 × 1,280) × 1,280] | 262,144,000 |
| Output head | 1,280 dim × 65,536 vocab | 83,886,080 |
| Total | 560,988,160 |
Param share
Embedding ███████▋ 14.9%
Attention ███████████ 23.4%
MLP ████████████████████ 46.7%
Output head ███████▋ 14.9%
The embeddings are untied, so the input lookup and output head each contribute the same ~84M parameters, while each of the 20 decoder blocks supplies ~19.7M parameters split between attention (6.6M) and MLP (13.1M) weights.
nanochat is a full-stack implementation of a ChatGPT-like language model trained from scratch in a single, clean, minimal, and hackable codebase. This model demonstrates that powerful conversational AI capabilities can be achieved with modest computational budgets, making advanced language modeling accessible to researchers, educators, and practitioners.
This live model card documents the 561M-parameter (depth=20, sequence_len=2048) run that is currently training on 8x NVIDIA H100 80GB GPUs via Lambda Labs. Once the run finishes we will post the resulting checkpoints, evaluation artifacts, and chat-ready weights here.
This implementation represents a complete pipeline from raw text to a deployable chat interface, including:
Key Innovation: nanochat proves that with careful architectural choices and efficient training procedures, a capable ChatGPT clone can be trained for approximately $100 in compute costs, making it an invaluable educational resource and research baseline.
nanochat implements a modern Transformer architecture with several key improvements over the original GPT design:
Core Specifications:
--depth parameter)Architectural Innovations:
Rotary Position Embeddings (RoPE): Unlike traditional learned positional embeddings, RoPE provides better length generalization and more efficient position encoding.
RMSNorm: Replaces LayerNorm for improved training stability and efficiency, reducing computational overhead while maintaining performance.
Multi-Query Attention (MQA): Enables efficient inference by sharing key-value projections across heads, reducing memory bandwidth requirements.
Untied Embeddings: Separate input and output embedding matrices provide additional model capacity without significantly increasing parameters.
ReLU² Activation: Uses squared ReLU (ReLU²) in the feedforward network for improved expressiveness compared to standard activations.
QK Normalization: Normalizes query and key vectors before attention computation for training stability.
nanochat achieves remarkable training efficiency through:
Optimizer Design:
Computational Profile:
Primary Configuration (current run):
Alternative Configurations:
depth, device_batch_size, and max_seq_lennanochat employs a four-stage training pipeline optimized for performance and capability development:
Duration: ~1 minute
Training Data: 2 billion characters from FineWeb-EDU
Algorithm: Byte-Pair Encoding (BPE) with regex splitting
Vocabulary Size: 65,536 tokens
Compression Ratio: 4.8 characters/token
The custom Rust-based tokenizer (rustbpe) provides training performance critical for rapid iteration while maintaining compatibility with OpenAI's tiktoken for efficient inference.
Tokenizer Performance vs Baselines:
Duration: ~10.5 hours (projected; 21,400 steps at ~1.9 s/step)
Iterations: 21,400 steps
Training Tokens: 11.2 billion (following Chinchilla optimal scaling)
Batch Size: 524,288 tokens per step (32 sequences x 2048 tokens x 8 GPUs)
Dataset: FineWeb-EDU (240 shards, ~24GB)
Final Validation Loss: 0.81 bits per byte
CORE Score: 0.2219
Chinchilla Scaling Adherence: Following Hoffmann et al. (2022), nanochat trains with a 20:1 token-to-parameter ratio:
This optimization ensures maximal performance for the allocated compute budget, avoiding both undertrained and overtrained regimes.
Training Data Composition: FineWeb-EDU is a high-quality subset of CommonCrawl filtered for educational content, providing:
Duration: ~8 minutes
Dataset Mixture:
Purpose: Midtraining bridges the gap between document completion (pretraining) and conversational interaction:
Chat Format: nanochat uses OpenAI's Harmony-style formatting:
<|bos|>
<|user_start|>User message here<|user_end|>
<|assistant_start|>Assistant response here<|assistant_end|>
<|user_start|>Follow-up message<|user_end|>
<|assistant_start|>...
Evaluation Results:
Duration: ~7 minutes
Focus: High-quality conversation refinement
Key Adaptation: Padding to match inference-time format
SFT performs final refinement on carefully curated conversational data, eliminating the domain shift between packed training sequences and padded inference sequences.
Final Evaluation Results:
Duration: ~1.5 hours (when enabled)
Algorithm: Simplified GRPO (Group Relative Policy Optimization)
Focus: GSM8K mathematical reasoning
Improvement: GSM8K accuracy increases from 4.55% to 7.58%
The RL stage demonstrates that even simple reinforcement learning can yield measurable improvements on domains with clear reward signals, though it remains optional in the default pipeline.
Pretraining:
Instruction Tuning:
Evaluation:
| Metric | Score | Comparison |
|---|---|---|
| CORE | 0.2219 | Between GPT-2 Large (0.21) and GPT-2 XL (0.26) |
| Validation BPB | 0.81 | Bits per byte on held-out data |
| Benchmark | Score | Baseline (Random) | Description |
|---|---|---|---|
| ARC-Easy | 38.76% | 25% | Elementary science questions |
| ARC-Challenge | 28.07% | 25% | Middle school science questions |
| MMLU | 31.51% | 25% | Multitask language understanding |
| GSM8K | 4.55% | 0% | Grade-school math problems |
| HumanEval | 8.54% | 0% | Python code generation |
| ChatCORE | 0.0884 | 0.0 | Aggregate chat performance |
For reference, GPT-2 (1.5B parameters, 2019) achieved:
nanochat achieves comparable base capabilities with:
The recommended way to interact with nanochat is through its web interface:
# Activate virtual environment
source .venv/bin/activate
# Start web server
python -m scripts.chat_web
# Access at http://localhost:8000
# Or on cloud: http://YOUR_IP:8000
For terminal-based interaction:
python -m scripts.chat_cli
from nanochat.checkpoint_manager import load_model
from nanochat.common import compute_init
# Initialize
ddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init()
# Load model (sft = supervised fine-tuned, mid = midtrained, base = pretrained)
model, tokenizer, meta = load_model("sft", device, phase="eval")
# Generate response
prompt = "<|bos|><|user_start|>What is the capital of France?<|user_end|><|assistant_start|>"
tokens = tokenizer.encode(prompt)
# Generate with sampling
response_tokens = list(model.generate(
tokens,
max_tokens=100,
temperature=0.8,
top_k=50
))
# Decode response
response = tokenizer.decode(response_tokens)
print(response)
nanochat models can be exported to HuggingFace format for deployment on Inference Endpoints:
# Export model
python scripts/export_to_huggingface.py --source sft --output-dir ./hf_model
# Upload to HuggingFace
huggingface-cli login
huggingface-cli upload your-username/nanochat-model ./hf_model
The fastest way to train nanochat is using the speedrun script:
git clone https://github.com/karpathy/nanochat.git
cd nanochat
bash speedrun.sh
This will:
Total Cost: ~$250 on Lambda Labs (8xH100 @ $24/hr)
For those without access to cloud GPU infrastructure, we provide a complete Colab notebook:
Interactive Training Notebook: notebooks/train_on_colab.ipynb
Direct Link: Open in Colab
Colab Options:
The Colab notebook provides:
nanochat easily scales to larger models by adjusting the --depth parameter:
# GPT-2 capability model (~41.6 hours, ~$1000)
torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \
--depth=26 --device_batch_size=16
# Intermediate model (~12 hours, ~$300)
torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \
--depth=30 --device_batch_size=8
The codebase automatically adjusts:
nanochat prioritizes:
Codebase Statistics:
Core Implementation (nanochat/):
gpt.py: Transformer model implementationengine.py: Inference engine with KV cachingtokenizer.py: Tokenizer interface and special tokensdataloader.py: Efficient data loading and batchingcheckpoint_manager.py: Model checkpointing and loadingadamw.py / muon.py: Optimizer implementationsconfigurator.py: Hyperparameter configurationTraining Scripts (scripts/):
tok_train.py: Tokenizer trainingbase_train.py: Pretrainingmid_train.py: Midtrainingchat_sft.py: Supervised fine-tuningchat_rl.py: Reinforcement learning (optional)chat_eval.py: Comprehensive evaluationchat_web.py: Web interface serverexport_to_huggingface.py: HuggingFace exportTokenizer (rustbpe/):
nanochat builds upon decades of research in neural language modeling and represents a practical synthesis of modern best practices:
Transformer Architecture:
GPT Models and Scaling:
Radford et al. (2018). "Improving Language Understanding by Generative Pre-Training." OpenAI.
Radford et al. (2019). "Language Models are Unsupervised Multitask Learners." OpenAI.
Brown et al. (2020). "Language Models are Few-Shot Learners." NeurIPS. arXiv:2005.14165
Scaling Laws:
Kaplan et al. (2020). "Scaling Laws for Neural Language Models." arXiv:2001.08361
Hoffmann et al. (2022). "Training Compute-Optimal Large Language Models." NeurIPS. arXiv:2203.15556
Architectural Innovations:
Su et al. (2021). "RoFormer: Enhanced Transformer with Rotary Position Embedding." arXiv:2104.09864
Shazeer (2019). "Fast Transformer Decoding: One Write-Head is All You Need." arXiv:1911.02150
Zhang & Sennrich (2019). "Root Mean Square Layer Normalization." NeurIPS. arXiv:1910.07467
Instruction Tuning and Alignment:
Wei et al. (2022). "Finetuned Language Models are Zero-Shot Learners." ICLR. arXiv:2109.01652
Ouyang et al. (2022). "Training language models to follow instructions with human feedback." NeurIPS. arXiv:2203.02155
Evaluation and Benchmarking:
Optimization:
nanochat is designed as the capstone project for LLM101n, a course on large language models developed by Eureka Labs (founded by Andrej Karpathy). The implementation philosophy emphasizes:
Related educational resources by Andrej Karpathy:
As a model trained on a $100 budget with 560M parameters, nanochat has inherent limitations:
Knowledge and Reasoning:
Language and Coverage:
Context and Memory:
Important: nanochat has not undergone extensive safety testing or alignment:
nanochat is intended for:
nanochat should NOT be used for:
Environmental Impact: Training nanochat consumes approximately:
Data and Bias:
Transparency: nanochat prioritizes transparency by:
Author: Andrej Karpathy
Organization: Eureka Labs
Repository: github.com/karpathy/nanochat
License: MIT
For questions, issues, or contributions:
If you use nanochat in your research or projects, please cite:
@misc{nanochat2025,
author = {Andrej Karpathy},
title = {nanochat: The best ChatGPT that \$100 can buy},
year = {2025},
publisher = {GitHub},
journal = {GitHub repository},
howpublished = {\url{https://github.com/karpathy/nanochat}},
note = {Educational implementation of full-stack ChatGPT clone}
}
nanochat builds upon and is inspired by:
Special thanks to the open-source ML community for making projects like this possible.
Documentation:
Related Projects:
Educational Materials:
Note: This model card will be automatically updated with actual training metrics, costs, and performance numbers when the model completes training. Placeholder values should be replaced with real measurements from your training run.