[
  {
    "path": ".claude/skills/read-arxiv-paper/SKILL.md",
    "content": "---\nname: read-arxiv-paper\ndescription: Use this skill when when asked to read an arxiv paper given an arxiv URL\n---\n\nYou will be given a URL of an arxiv paper, for example:\n\nhttps://www.arxiv.org/abs/2601.07372\n\n### Part 1: Normalize the URL\n\nThe goal is to fetch the TeX Source of the paper (not the PDF!), the URL always looks like this:\n\nhttps://www.arxiv.org/src/2601.07372\n\nNotice the /src/ in the url. Once you have the URL:\n\n### Part 2: Download the paper source\n\nFetch the url to a local .tar.gz file. A good location is `~/.cache/nanochat/knowledge/{arxiv_id}.tar.gz`.\n\n(If the file already exists, there is no need to re-download it).\n\n### Part 3: Unpack the file in that folder\n\nUnpack the contents into `~/.cache/nanochat/knowledge/{arxiv_id}` directory.\n\n### Part 4: Locate the entrypoint\n\nEvery latex source usually has an entrypoint, such as `main.tex` or something like that.\n\n### Part 5: Read the paper\n\nOnce you've found the entrypoint, Read the contents and then recurse through all other relevant source files to read the paper.\n\n#### Part 6: Report\n\nOnce you've read the paper, produce a summary of the paper into a markdown file at `./knowledge/summary_{tag}.md`. Notice that 1) use the local knowledge directory here (it's easier for me to open and reference here), not in `~/.cache`, and 2) generate some reasonable `tag` like e.g. `conditional_memory` or whatever seems appropriate given the paper. Probably make sure that the tag doesn't exist yet so you're not overwriting files.\n\nAs for the summary itself, remember that you're processing this paper within the context of the nanochat repository, so most often we we will be interested in how to apply the paper and its lessons to the nanochat project. Therefore, you should feel free to \"remind yourself\" of the related nanochat code by reading the relevant parts, and then explicitly make the connection of how this paper might relate to nanochat or what are things we might be inspired about or try.\n"
  },
  {
    "path": ".gitignore",
    "content": ".venv/\n__pycache__/\n*.pyc\ndev-ignore/\nreport.md\neval_bundle/\n\n# Secrets\n.env\n\n# Local setup\nCLAUDE.md\nwandb/\n"
  },
  {
    "path": ".python-version",
    "content": "3.10\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2025 Andrej Karpathy\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# nanochat\n\n![nanochat logo](dev/nanochat.png)\n![scaling laws](dev/scaling_laws_jan26.png)\n\nnanochat is the simplest experimental harness for training LLMs. It is designed to run on a single GPU node, the code is minimal/hackable, and it covers all major LLM stages including tokenization, pretraining, finetuning, evaluation, inference, and a chat UI. For example, you can train your own GPT-2 capability LLM (which cost ~$43,000 to train in 2019) for only $48 (~2 hours of 8XH100 GPU node) and then talk to it in a familiar ChatGPT-like web UI. On a spot instance, the total cost can be closer to ~$15. More generally, nanochat is configured out of the box to train an entire miniseries of compute-optimal models by setting one single complexity dial: `--depth`, the number of layers in the GPT transformer model (GPT-2 capability happens to be approximately depth 26). All other hyperparameters (the width of the transformer, number of heads, learning rate adjustments, training horizons, weight decays, ...) are calculated automatically in an optimal way.\n\nFor questions about the repo, I recommend either using [DeepWiki](https://deepwiki.com/karpathy/nanochat) from Devin/Cognition to ask questions about the repo, or use the [Discussions tab](https://github.com/karpathy/nanochat/discussions), or come by the [#nanochat](https://discord.com/channels/1020383067459821711/1427295580895314031) channel on Discord.\n\n## Time-to-GPT-2 Leaderboard\n\nPresently, the main focus of development is on tuning the pretraining stage, which takes the most amount of compute. Inspired by the modded-nanogpt repo and to incentivise progress and community collaboration, nanochat maintains a leaderboard for a \"GPT-2 speedrun\", which is the wall-clock time required to train a nanochat model to GPT-2 grade capability, as measured by the DCLM CORE score. The [runs/speedrun.sh](runs/speedrun.sh) script always reflects the reference way to train GPT-2 grade model and talk to it. The current leaderboard looks as follows:\n\n| # | time | val_bpb | CORE | Description | Date | Commit | Contributors |\n|---|-------------|---------|------|-------------|------|--------|--------------|\n| 0 | 168 hours | - | 0.2565 | Original OpenAI GPT-2 checkpoint | 2019 | - | OpenAI |\n| 1 | 3.04 | 0.74833 | 0.2585 | d24 baseline, slightly overtrained | Jan 29 2026 | 348fbb3 | @karpathy |\n| 2 | 2.91 | 0.74504 | 0.2578 | d26 slightly undertrained **+fp8** | Feb 2 2026 | a67eba3 | @karpathy |\n| 3 | 2.76 | 0.74645 | 0.2602 | bump total batch size to 1M tokens | Feb 5 2026 | 2c062aa | @karpathy |\n| 4 | 2.02 | 0.71854 | 0.2571 | change dataset to NVIDIA ClimbMix | Mar 4 2026 | 324e69c | @ddudek @karpathy |\n| 5 | 1.80 | 0.71808 | 0.2690 | autoresearch [round 1](https://x.com/karpathy/status/2031135152349524125) | Mar 9 2026 | 6ed7d1d | @karpathy |\n| 5 | 1.65 | 0.71800 | 0.2626 | autoresearch round 2 | Mar 14 2026 | a825e63 | @karpathy |\n\nThe primary metric we care about is \"time to GPT-2\" - the wall clock time needed to outperform the GPT-2 (1.6B) CORE metric on an 8XH100 GPU node. The GPT-2 CORE score is 0.256525. In 2019, the training of GPT-2 cost approximately $43,000 so it is incredible that due to many advances over 7 years across the stack, we can now do so much faster and for well below $100 (e.g. at the current ~$3/GPU/hr, an 8XH100 node is ~$24/hr, so 2 hours is ~$48).\n\nSee [dev/LEADERBOARD.md](dev/LEADERBOARD.md) for more docs on how to interpret and contribute to the leaderboard.\n\n## Getting started\n\n### Reproduce and talk to GPT-2\n\nThe most fun you can have is to train your own GPT-2 and talk to it. The entire pipeline to do so is contained in the single file [runs/speedrun.sh](runs/speedrun.sh), which is designed to be run on an 8XH100 GPU node. Boot up a new 8XH100 GPU box from your favorite provider (e.g. I use and like [Lambda](https://lambda.ai/service/gpu-cloud)), and kick off the training script:\n\n```bash\nbash runs/speedrun.sh\n```\n\nYou may wish to do so in a screen session as this will take ~3 hours to run. Once it's done, you can talk to it via the ChatGPT-like web UI. Make sure again that your local uv virtual environment is active (run `source .venv/bin/activate`), and serve it:\n\n```bash\npython -m scripts.chat_web\n```\n\nAnd then visit the URL shown. Make sure to access it correctly, e.g. on Lambda use the public IP of the node you're on, followed by the port, so for example [http://209.20.xxx.xxx:8000/](http://209.20.xxx.xxx:8000/), etc. Then talk to your LLM as you'd normally talk to ChatGPT! Get it to write stories or poems. Ask it to tell you who you are to see a hallucination. Ask it why the sky is blue. Or why it's green. The speedrun is a 4e19 FLOPs capability model so it's a bit like talking to a kindergartener :).\n\n---\n\n<img width=\"2672\" height=\"1520\" alt=\"image\" src=\"https://github.com/user-attachments/assets/ed39ddf8-2370-437a-bedc-0f39781e76b5\" />\n\n---\n\nA few more notes:\n\n- The code will run just fine on the Ampere 8XA100 GPU node as well, but a bit slower.\n- All code will run just fine on even a single GPU by omitting `torchrun`, and will produce ~identical results (code will automatically switch to gradient accumulation), but you'll have to wait 8 times longer.\n- If your GPU(s) have less than 80GB, you'll have to tune some of the hyperparameters or you will OOM / run out of VRAM. Look for `--device_batch_size` in the scripts and reduce it until things fit. E.g. from 32 (default) to 16, 8, 4, 2, or even 1. Less than that you'll have to know a bit more what you're doing and get more creative.\n- Most of the code is fairly vanilla PyTorch so it should run on anything that supports that - xpu, mps, or etc, but I haven't personally exercised all of these code paths so there might be sharp edges.\n\n## Research\n\nIf you are a researcher and wish to help improve nanochat, two scripts of interest are [runs/scaling_laws.sh](runs/scaling_laws.sh) and [runs/miniseries.sh](runs/miniseries.sh). See [Jan 7 miniseries v1](https://github.com/karpathy/nanochat/discussions/420) for related documentation. For quick experimentation (~5 min pretraining runs) my favorite scale is to train a 12-layer model (GPT-1 sized), e.g. like this:\n\n```\nOMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \\\n    --depth=12 \\\n    --run=\"d12\" \\\n    --model-tag=\"d12\" \\\n    --core-metric-every=999999 \\\n    --sample-every=-1 \\\n    --save-every=-1 \\\n```\n\nThis uses wandb (run name \"d12\"), only runs the CORE metric on last step, and it doesn't sample and save intermediate checkpoints. I like to change something in the code, re-run a d12 (or a d16 etc) and see if it helped, in an iteration loop. To see if a run helps, I like to monitor the wandb plots for:\n\n1. `val_bpb` (validation loss in vocab-size-invariant units of bits per byte) as a function of `step`, `total_training_time` and `total_training_flops`.\n2. `core_metric` (the DCLM CORE socre)\n3. VRAM utilization, `train/mfu` (Model FLOPS utilization), `train/tok_per_sec` (training throughput)\n\nSee an example [here](https://github.com/karpathy/nanochat/pull/498#issuecomment-3850720044).\n\nThe important thing to note is that nanochat is written and configured around one single dial of complexity - the depth of the transformer. This single integer automatically determines all other hyperparameters (the width of the transformer, number of heads, learning rate adjustments, training horizons, weight decays, ...) so that the trained model comes out compute optimal. The idea is that the user doesn't have to think about or set any of this, they are simply asking for a smaller or bigger model using `--depth`, and everything \"just works\". By sweeping out the depth, you achieve the nanochat miniseries of compute optimal models at various sizes. GPT-2 capability model (which is of most interest at the moment) happens to be somewhere around d24-d26 range with the current code. But any candidate changes to the repo have to be principled enough that they work for all settings of depth.\n\n## Running on CPU / MPS\n\nThe script [runs/runcpu.sh](runs/runcpu.sh) shows a very simple example of running on CPU or Apple Silicon. It dramatically shrinks the LLM that is being trained to make things fit into a reasonable time interval of a few ten minutes of training. You will not get strong results in this way.\n\n## Precision / dtype\n\nnanochat does not use `torch.amp.autocast`. Instead, precision is managed explicitly through a single global `COMPUTE_DTYPE` (defined in `nanochat/common.py`). By default this is auto-detected based on your hardware:\n\n| Hardware | Default dtype | Why |\n|----------|--------------|-----|\n| CUDA SM 80+ (A100, H100, ...) | `bfloat16` | Native bf16 tensor cores |\n| CUDA SM < 80 (V100, T4, ...) | `float32` | No bf16; fp16 available via `NANOCHAT_DTYPE=float16` (uses GradScaler) |\n| CPU / MPS | `float32` | No reduced-precision tensor cores |\n\nYou can override the default with the `NANOCHAT_DTYPE` environment variable:\n\n```bash\nNANOCHAT_DTYPE=float32 python -m scripts.chat_cli -p \"hello\"   # force fp32\nNANOCHAT_DTYPE=bfloat16 torchrun --nproc_per_node=8 -m scripts.base_train  # force bf16\n```\n\nHow it works: model weights are stored in fp32 (for optimizer precision), but our custom `Linear` layer casts them to `COMPUTE_DTYPE` during the forward pass. Embeddings are stored directly in `COMPUTE_DTYPE` to save memory. This gives us the same mixed-precision benefit as autocast but with full explicit control over what runs in which precision.\n\nNote: `float16` training automatically enables a `GradScaler` in `base_train.py` to prevent gradient underflow. SFT suppors this too but RL currently does not. Inference in fp16 works fine everywhere.\n\n## Guides\n\nI've published a number of guides that might contain helpful information, most recent to least recent:\n\n- [Feb 1 2026: Beating GPT-2 for <<$100: the nanochat journey](https://github.com/karpathy/nanochat/discussions/481)\n- [Jan 7 miniseries v1](https://github.com/karpathy/nanochat/discussions/420) documents the first nanochat miniseries of models.\n- To add new abilities to nanochat, see [Guide: counting r in strawberry (and how to add abilities generally)](https://github.com/karpathy/nanochat/discussions/164).\n- To customize your nanochat, see [Guide: infusing identity to your nanochat](https://github.com/karpathy/nanochat/discussions/139) in Discussions, which describes how you can tune your nanochat's personality through synthetic data generation and mixing that data into the SFT stage.\n- [Oct 13 2025: original nanochat post](https://github.com/karpathy/nanochat/discussions/1) introducing nanochat, though now it contains some deprecated information and the model is a lot older (with worse results) than current master.\n\n## File structure\n\n```\n.\n├── LICENSE\n├── README.md\n├── dev\n│   ├── gen_synthetic_data.py       # Example synthetic data for identity\n│   ├── generate_logo.html\n│   ├── nanochat.png\n│   └── repackage_data_reference.py # Pretraining data shard generation\n├── nanochat\n│   ├── __init__.py                 # empty\n│   ├── checkpoint_manager.py       # Save/Load model checkpoints\n│   ├── common.py                   # Misc small utilities, quality of life\n│   ├── core_eval.py                # Evaluates base model CORE score (DCLM paper)\n│   ├── dataloader.py               # Tokenizing Distributed Data Loader\n│   ├── dataset.py                  # Download/read utils for pretraining data\n│   ├── engine.py                   # Efficient model inference with KV Cache\n│   ├── execution.py                # Allows the LLM to execute Python code as tool\n│   ├── gpt.py                      # The GPT nn.Module Transformer\n│   ├── logo.svg\n│   ├── loss_eval.py                # Evaluate bits per byte (instead of loss)\n│   ├── optim.py                    # AdamW + Muon optimizer, 1GPU and distributed\n│   ├── report.py                   # Utilities for writing the nanochat Report\n│   ├── tokenizer.py                # BPE Tokenizer wrapper in style of GPT-4\n│   └── ui.html                     # HTML/CSS/JS for nanochat frontend\n├── pyproject.toml\n├── runs\n│   ├── miniseries.sh               # Miniseries training script\n│   ├── runcpu.sh                   # Small example of how to run on CPU/MPS\n│   ├── scaling_laws.sh             # Scaling laws experiments\n│   └── speedrun.sh                 # Train the ~$100 nanochat d20\n├── scripts\n│   ├── base_eval.py                # Base model: CORE score, bits per byte, samples\n│   ├── base_train.py               # Base model: train\n│   ├── chat_cli.py                 # Chat model: talk to over CLI\n│   ├── chat_eval.py                # Chat model: eval tasks\n│   ├── chat_rl.py                  # Chat model: reinforcement learning\n│   ├── chat_sft.py                 # Chat model: train SFT\n│   ├── chat_web.py                 # Chat model: talk to over WebUI\n│   ├── tok_eval.py                 # Tokenizer: evaluate compression rate\n│   └── tok_train.py                # Tokenizer: train it\n├── tasks\n│   ├── arc.py                      # Multiple choice science questions\n│   ├── common.py                   # TaskMixture | TaskSequence\n│   ├── customjson.py               # Make Task from arbitrary jsonl convos\n│   ├── gsm8k.py                    # 8K Grade School Math questions\n│   ├── humaneval.py                # Misnomer; Simple Python coding task\n│   ├── mmlu.py                     # Multiple choice questions, broad topics\n│   ├── smoltalk.py                 # Conglomerate dataset of SmolTalk from HF\n│   └── spellingbee.py              # Task teaching model to spell/count letters\n├── tests\n│   └── test_engine.py\n└── uv.lock\n```\n\n## Contributing\n\nThe goal of nanochat is to improve the state of the art in micro models that are accessible to work with end to end on budgets of < $1000 dollars. Accessibility is about overall cost but also about cognitive complexity - nanochat is not an exhaustively configurable LLM \"framework\"; there are no giant configuration objects, model factories, or if-then-else monsters in the code base. It is a single, cohesive, minimal, readable, hackable, maximally-forkable \"strong baseline\" codebase designed to run start to end and produce a ChatGPT model you can talk to. Currently, the most interesting part personally is speeding up the latency to GPT-2 (i.e. getting a CORE score above 0.256525). Currently this takes ~3 hours, but by improving the pretraining stage we can improve this further.\n\nCurrent AI policy: disclosure. When submitting a PR, please declare any parts that had substantial LLM contribution and that you have not written or that you do not fully understand.\n\n## Acknowledgements\n\n- The name (nanochat) derives from my earlier project [nanoGPT](https://github.com/karpathy/nanoGPT), which only covered pretraining.\n- nanochat is also inspired by [modded-nanoGPT](https://github.com/KellerJordan/modded-nanogpt), which gamified the nanoGPT repo with clear metrics and a leaderboard, and borrows a lot of its ideas and some implementation for pretraining.\n- Thank you to [HuggingFace](https://huggingface.co/) for fineweb and smoltalk.\n- Thank you [Lambda](https://lambda.ai/service/gpu-cloud) for the compute used in developing this project.\n- Thank you to chief LLM whisperer 🧙‍♂️ Alec Radford for advice/guidance.\n- Thank you to the repo czar Sofie [@svlandeg](https://github.com/svlandeg) for help with managing issues, pull requests and discussions of nanochat.\n\n## Cite\n\nIf you find nanochat helpful in your research cite simply as:\n\n```bibtex\n@misc{nanochat,\n  author = {Andrej Karpathy},\n  title = {nanochat: The best ChatGPT that \\$100 can buy},\n  year = {2025},\n  publisher = {GitHub},\n  url = {https://github.com/karpathy/nanochat}\n}\n```\n\n## License\n\nMIT\n"
  },
  {
    "path": "dev/LEADERBOARD.md",
    "content": "# Leaderboard\n\nDocs on participating in the \"Time-to-GPT-2\" leaderboard of nanochat.\n\nThe primary metric we care about is \"time to GPT-2\" - the wall clock time needed to outperform the GPT-2 (1.6B) CORE metric on an 8XH100 GPU node. Originally in 2019, GPT-2 was trained by OpenAI on 32 TPU v3 chips for 168 hours (7 days), with $8/hour/TPUv3 back then, for a total cost of approx. $43K. It achieves 0.256525 CORE score, which is an ensemble metric introduced in the DCLM paper over 22 evaluations like ARC/MMLU/etc.\n\n## How to\n\nThe script [runs/speedrun.sh](runs/speedrun.sh) always implements the current state of the art on the leaderboard.\n\nIn practice, I tune the base_train command a little bit. For example, once all the setup is configured and a tokenizer is trained, I like to do something like:\n\n```\nOMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \\\n    --depth=26 \\\n    --run=\"d26-feb2-fp8-ratio8.25\" \\\n    --model-tag=\"d26_feb2_fp8_ratio8.25\" \\\n    --device-batch-size=16 \\\n    --sample-every=-1 \\\n    --save-every=-1 \\\n    --core-metric-max-per-task=-1 \\\n    --core-metric-every=999999 \\\n    --target-param-data-ratio=8.25 \\\n    --fp8\n```\n\nNote that:\n\n- `depth` controls the size of the Transformer\n- `run` is the wandb name\n- `model-tag` is the location of the checkpoints on disk\n- `device-batch-size` in the ideal world, you want this to be 32 because with sequence length of 2048 (the default) and 8 GPUs we get `32 X 2048 X 8 = 524,288`, which is the total desired batch size determined to work fairly well around this scale. However, for bigger (e.g. d26), 32 is too much and OOMs, so we decrease it by 2 to 16. The `base_train.py` script automatically compensates for this by calculating that it has to use gradient accumulation of 2 to meet the desired total batch size. Therefore, it will do forward+backward twice and then a single step. Long story short, the ideal value is 32. If that doesn't fit, you decrease it, e.g. 16, 8, etc., keeping it powers of two so that the gradient accumulation math works out neatly.\n- `sample-every = -1` turns off periodic sampling\n- `core-metric-max-per-task=-1` means we run the entire CORE eval\n- `core-metric-every=999999` a bit of a hacky way to make the CORE eval only happen a single time at the very end of the run\n- `target-param-data-ratio=8.25` controls the training horizon, which is determined in the script by taking the number of non-embedding model parameters and simply multiplying by this number. The current optimal Tokens:Params ratio can be seen in the defaults of the `base_train.py` script (it is 10.5). 10.5 would produce the *compute optimal* model given the currently measured scaling laws. However, GPT-2 capability is currently somewhere in between a d24 and d26. So to reach it exactly, we want to either overtrain d24 or undertrain d26. In this particular example, I am choosing to slightly undertrain a d26. Note that odd depths (e.g. d25) are not super recommended to use because the math around the transformer sizing and its head dimensions doesn't come out neatly.\n- `--fp8` turns on fp8 training. If your GPU does not support fp8, you can leave this out and the code will simply train in bf16. bf16 is higher precision than fp8, so you can actually expect that you might be able to do fewer steps (lower the `target-param-data-ratio`) to achieve the same capability.\n\nOnce you kick off the run, you wait ~3 hours and then at the end you'll see something like:\n\n```\nwandb: Run summary:\nwandb:          core_metric 0.25851\nwandb:                 step 16704\nwandb: total_training_flops 4.330784131228946e+19\nwandb:  total_training_time 10949.46713\n```\n\nYour CORE metric must be greater than GPT-2 0.256525. Then you report the `total_training_time`, (e.g. 10949) which is the time of the training iterations alone, excluding all the evaluations and logging, in seconds. So here for example it is roughly 10949/60/60 ~= 3.04 hours. You should also note and report the validation bpb of your run because the CORE metric can be a little bit noisy.\n\nIf you outperform GPT-2 and the time is less than current SOTA in the Leaderboard, you get to make a PR. In addition to raw gains, there are some qualitative and aesthetic considerations that go into whether your improvement is merged. For example, if it is gnarly or it significantly bloats the code, or it seems too esoteric, then we will weigh those things against the improvement demonstrated. Additionally, nanochat cares not only about targeting a single model, but an entire miniseries of models. So your change must be principled enough that it can easily generalize to other model depths, so that we can sweep out a miniseries.\n\nAfter you create the commit, to get the current short git commit hash:\n\n```\ngit log -1 --format=\"%h\"\n```\n\n## Run 1\n\nAchieved Jan 29 2026 on commit `348fbb3`. The launch command was\n\n```\nOMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \\\n    --depth=24 \\\n    --run=d24-jan29 \\\n    --model-tag=d24_jan29 \\\n    --device-batch-size=16 \\\n    --sample-every=-1 \\\n    --save-every=-1 \\\n    --core-metric-max-per-task=-1 \\\n    --core-metric-every=3000 \\\n    --target-param-data-ratio=12\n```\n\nThe result was:\n\n```\nwandb: Run summary:\nwandb:          core_metric 0.25851\nwandb:                 step 16704\nwandb: total_training_flops 4.330784131228946e+19\nwandb:  total_training_time 10949.46713\n```\n\nThe validation bpb was 0.74833.\n\nDetailed writeup: [Beating GPT-2 for <<$100: the nanochat journey](https://github.com/karpathy/nanochat/discussions/481)\n\n## Run 2\n\nAchieved Feb 2 2026 on commit `a67eba3`. The launch command was\n\n```\nOMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \\\n    --depth=26 \\\n    --run=\"d26-feb2-fp8-ratio8.5\" \\\n    --model-tag=\"d26_feb2_fp8_ratio8.5\" \\\n    --device-batch-size=16 \\\n    --sample-every=-1 \\\n    --save-every=-1 \\\n    --core-metric-max-per-task=-1 \\\n    --core-metric-every=999999 \\\n    --target-param-data-ratio=8.5 \\\n    --fp8\n```\n\nThe result was:\n\n```\ncore_metric 0.2578\nstep 14889\ntotal_training_time 10493\nMinimum validation bpb: 0.745036\n```\n\nThe big change in this run is `--fp8`, which causes all Linear layers (other than the gates) to be switched to fp8 training using `torchao` with tensorwise fp8 scaling. Each step is of slightly lower quality, but we are taking them a lot faster, coming out net ahead. Anyone who does not have fp8 (e.g. using a GPU without it) can simply leave out the `--fp8` flag to train in bfloat16. This will work just fine but it will produce a slightly stronger model than GPT-2 because of the fp8 -> bf16 precision upgrade. It's possible that one can further tune which layers to include in the fp8 conversion and that e.g. some of the smaller matmuls should be just kept in bf16 etc.\n\nPrevious record was 3.04 hours, so 2.91 hours is `(3.04 - 2.91)/3.04*100` ~= 4.3% speed improvement.\n\n## Run 3\n\nAchieved Feb 5 2026 on commit `2c062aa`. Launch command:\n\n```\nOMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \\\n    --depth=26 \\\n    --run=\"d26_feb4_double_batch_ratio8.25\" \\\n    --model-tag=\"d26_feb4_double_batch_ratio8.25\" \\\n    --device-batch-size=16 \\\n    --total-batch-size=1048576 \\\n    --sample-every=-1 \\\n    --save-every=-1 \\\n    --core-metric-max-per-task=-1 \\\n    --core-metric-every=999999 \\\n    --target-param-data-ratio=8.25 \\\n    --fp8\n```\n\nResult:\n\n```\ncore_metric 0.26024\nstep 7226\ntotal_training_time 9922\nMinimum validation bpb: 0.74645\n```\n\nThe big change here is that the batch size was doubled from 0.5M to 1M, which works better for a d26 model and allowed me to decrease the number of optimization steps a bit via `--target-param-data-ratio` from 8.5 to 8.25. The TLDR is that the original batch size of 0.5M was tuned for d12, but bigger models (e.g. d26) prefer larger total batch size. I determined in experiments that d26 prefers 1M. Then I implemented and merged a principled way to calculate the optimal batch size given depth so that all nanochat models of all depths benefit. See [dev/LOG.md](dev/LOG.md) entry \"2026-02-05: Auto Batch Size Scaling\" for more detail.\n\n## Run 4\n\nAchived Mar 3 2026 on commit `324e69c`. The big change is the switch from HuggingFace FineWeb-EDU to NVIDIA ClimbMix dataset. `@karpathy` has tried to swap the dataset many times, each time with a negative result (FineWeb, DCLM, Olmo), but ClimbMix produced clear and immediate gains. Credit to `@ddudek` for originally discovering ClimbMix for nanochat and reporting the improvements, which kicked off the followup investigation.\n\nTo reproduce, use the commit above, download at least 150 data shards, train the tokenizer:\n\n```\npython -m nanochat.dataset -n 150\npython -m scripts.tok_train\n```\n\nThen kick off the run in the typical way, using a slightly lower than compute optimal ratio of 9.5 (vs compute optimal 10.5), meaning the d24 is slightly undertrained.\n\n```\nOMP_NUM_THREADS=1 torchrun --standalone --nproc_per_node=8 -m scripts.base_train -- \\\n    --depth=24 \\\n    --run=\"d24-climbmix\" \\\n    --model-tag=\"d24-climbmix\" \\\n    --sample-every=-1 \\\n    --save-every=-1 \\\n    --core-metric-max-per-task=-1 \\\n    --core-metric-every=999999 \\\n    --target-param-data-ratio=9.5 \\\n    --device-batch-size=16 \\\n    --fp8\n```\n\nI ran this command 7 individual times. Because our training is mildly non-deterministic, we get a spread of CORE scores, e.g.:\n\n```\n0.25373\n0.2584\n0.25489\n0.2568\n0.25732\n0.26765\n0.25119\n```\n\nMean is 0.25714 (higher than the GPT-2 threshold needed), max-min is 0.01646. Something to investigate in the future is that even slightly better results can be obtained by randomly shuffling the the data shards (i.e. just going in a different order). This is unexpected because the documents were completely fully shuffled during data construction, so one would expect a relatively uniform data distribution. Indeed, the current default order is unfortunately among the worse (\"unlucky\") ones you can obtain with different shuffle seeds, but it suffices to beat GPT-2 for now so I am merging. TODO investing a bit more later.\n\nNOTE: The `val_bpb` is as of this run *NOT* comparable due to the data distribution change to the previous 3 runs. This run happens to be at `0.71854` validation bpb. If the dataset is not changed, the `val_bpb` number is a great, smooth metric to track relative performance w.r.t. and has less noise than CORE.\n\n## Run 5\n\nAchieved Mar 9, 2026 on commit `6ed7d1d`. Exactly the same launch command as Run 4 except `--target-param-data-ratio=8.7`. I ran 5 identical runs, the average CORE was 0.2690, which is quite a bit above the needed threshold of 0.2565. But the reason I didn't decrease the ratio further (i.e. train shorter) is that while the CORE \"safety gap\" is large, the val_loss safety gap is smaller - 0.71808, which we want to be below the Run 4 val loss of 0.71854. It's likely that we could have reduced the ratio even lower, possibly to 8.6, but it's not worth splitting hairs at this point.\n\nThis commit is special because all of the improvements that went into [this commit](https://github.com/karpathy/nanochat/commit/6ed7d1d82cee16c2e26f45d559ad3338447a6c1b) came from fully autonomous \"research\" done by a private version of [autoresearch](https://github.com/karpathy/autoresearch) run on a d12 model. I wrote more about this in [this tweet](https://x.com/karpathy/status/2031135152349524125). The changes easily translated from d12 to d24, hence new leaderboard record, taking us from 2.02 hours \"time to GPT-2\" to 1.80 hours.\n\n## Run 6\n\nAchieved Mar 14, 2026 on commit `a825e63`. Exactly the same launch command as Run 4 except `--target-param-data-ratio=8`. Improvements in the architecture are allowing us to train shorter and shorter time. Instead of an undertrained d24 I attempted to train an overtrained d22 but it was worse. This set of changes came from autoresearch round 2, where I asked it to reference the modded-nanogpt repo for inspiration. So the exploration tried out a number of ideas and in particular found a way to incorporate the backout and smear in such a way that they are helpful (I had previously tried them manually a long time ago and they caused regressions). The smear idea in particular is a little bit heavier and bloaty because it is essentially an \"early fusion\" of context across tokens, producing a kind of a bigram input into the network and allowing it to focus on higher ngrams earlier. But for this reason the code gets a bit more complex and required some changes to inference. I verified with a unit test that the Engine inference is correct compared to the naive inference of `GPT.generate()`. The average of 5 runs was CORE 0.262634 and each of them lasted 1.65 hours (99 minutes).\n"
  },
  {
    "path": "dev/LOG.md",
    "content": "# Experiment Log\n\nA running summary documenting some experiments and findings. Started ~Jan 7 2026.\n\n---\n\n## 2026-03-04: Remove autocast, explicit dtype management, fp16 GradScaler\n\nReplaced `torch.amp.autocast` throughout the codebase with explicit dtype management via a single `COMPUTE_DTYPE` global. Also added fp16 training support with GradScaler.\n\n### Motivation\n\nautocast is \"magic we don't control\" — it silently decides which ops run in which precision via internal allowlists. For this codebase, autocast was doing very little: the only thing it actually cast was `nn.Linear` weights from fp32 to bf16 for matmuls. `F.rms_norm`, `F.cross_entropy`, and Flash Attention all handle their own dtypes already. By making precision explicit, we gain fine-grained control (e.g. can experiment with fp32 norms) and eliminate an unnecessary layer of abstraction.\n\n### What changed\n\n**Core mechanism** (`nanochat/common.py`, `nanochat/gpt.py`):\n- `COMPUTE_DTYPE` auto-detected from hardware: SM 80+ → bf16, pre-Ampere → fp32, CPU/MPS → fp32. Override via `NANOCHAT_DTYPE` env var.\n- Custom `Linear(nn.Linear)` class that casts weights to match input dtype in forward: `F.linear(x, self.weight.to(dtype=x.dtype))`. This is the single mechanism that replaces autocast.\n- Embeddings cast to `COMPUTE_DTYPE` at init (saves memory). Exception: fp16 keeps embeddings fp32 because GradScaler cannot unscale fp16 gradients.\n- Embedding output explicitly cast to `COMPUTE_DTYPE` in `GPT.forward()` (no-op for bf16, active for fp16 path).\n- RoPE cos/sin cache uses `COMPUTE_DTYPE` instead of hardcoded bf16.\n\n**Autocast removal** (11 files):\n- Deleted `--dtype` CLI flag, `ptdtype` variables, `autocast_ctx` definitions, and all `with autocast_ctx:` blocks from: `base_train.py`, `chat_sft.py`, `chat_rl.py`, `chat_cli.py`, `chat_eval.py`, `chat_web.py`, `base_eval.py`, `engine.py`, `bench_train_toks.py`, `test_e2e_pipeline.py`.\n\n**fp16 + GradScaler** (`base_train.py`, `chat_sft.py`):\n- `scaler = torch.amp.GradScaler() if COMPUTE_DTYPE == torch.float16 else None`\n- Backward: `scaler.scale(loss).backward()` vs plain `loss.backward()`\n- After accumulation: `scaler.unscale_(optimizer)` → distributed inf-sync via `scaler._found_inf_per_device(optimizer)` all-reduced with `ReduceOp.MAX` → `scaler.step(optimizer)` → `scaler.update()`\n- Zero overhead for bf16/fp32 paths (scaler is None, no branching inside kernels).\n\n**FP8 fix** (`nanochat/fp8.py`, `base_train.py`):\n- `Float8Linear.forward` explicitly casts input to `COMPUTE_DTYPE` (previously relied on autocast).\n- `disable_fp8` context manager now creates our custom `Linear` (not vanilla `nn.Linear`) when swapping out Float8Linear during eval.\n\n**Flash Attention** (`flash_attention.py`):\n- FA3 Hopper kernels don't support fp16 or fp32, so `USE_FA3` (module-level constant, resolved once at import) returns False, falling back to SDPA.\n\n---\n\n## 2026-03-04: Dataset upgrade: FineWeb-EDU 100B → ClimbMix 400B\n\nSwitched the pretraining dataset from FineWeb-EDU 100B to ClimbMix 400B. This is by far the single biggest improvement to nanochat's GPT-2 speedrun time, bringing it down from **2 hours 46 minutes to 2 hours 1 minute** — a 27% reduction.\n\n### What is ClimbMix?\n\nClimbMix 400B is a curated 400B-token pretraining mixture hosted at `karpathy/climbmix-400b-shuffle` on HuggingFace. It comes form [NVIDIA](https://huggingface.co/datasets/nvidia/Nemotron-ClimbMix). It is a blend of high-quality web text, code, math, and other sources, designed to be a better general-purpose pretraining dataset than FineWeb-EDU alone.\n\n### What changed\n\n- **Dataset**: `karpathy/fineweb-edu-100b-shuffle` → `karpathy/climbmix-400b-shuffle` (up to 6543 shards available vs the previous 1823 data shards, allowing for longer training in the future)\n- **Data directory**: `base_data/` → `base_data_climbmix/` (clean separation from legacy data)\n- **Model depth**: d26 → d24. ClimbMix trains more efficiently, so a smaller model reaches GPT-2 capability\n- **Shard count**: Only approx 150 data shards (~7B tokens) are now needed for GPT-2 capability\n- **Eval tokens**: doubled from 40 to 80 batches for more stable validation loss estimates\n- **Legacy fallback**: added a migration warning in `list_parquet_files()` that detects the old `base_data/` directory and falls back gracefully, so existing users see clear upgrade instructions on `git pull`\n\n### Context\n\nThis is the sixth attempt at beating FineWeb-EDU on CORE score — the previous five all failed (see entries on 2026-02-17, 2026-02-10, 2026-01-12 below). ClimbMix is the first dataset to convincingly surpass it, and the margin is large enough to also shrink the model from d26 to d24.\n\n---\n\n## 2026-03-02: SoftCap tuning\n\nQuick experiment to tune logit softcap on d24 scale. Tried 5..30. 5 was terrible, the rest of them were all about equal with the exception of 20, which was the best. Minor but solid improvement: val loss improved by ~1e-3 (0.716 -> 0.715). Setting as default.\n\n## 2026-02-19: Mixture of Experts (negative)\n\nImplemented a DeepSeekV3-style Mixture of Experts layer as a drop-in replacement for the dense MLP. The MoE branch works and improves per-step validation loss, but is not a net improvement on wall clock time due to MoE overhead (at least for our scale of interest of approx GPT-2 capability).\n\n### Implementation\n\nFollows DeepSeekV3 and using torchtitan as reference:\n\n- **8 routed experts, top-2 routing** with sigmoid gating (not softmax)\n- **1 shared expert** (dense MLP processing all tokens, following DeepSeekV3)\n- **Auxiliary-loss-free load balancing** (DeepSeekV3's expert bias nudging)\n- **Iso-FLOP sizing**: `expert_hidden_dim = round(4 * dim / (top_k + num_shared) / 128) * 128`, so active FLOPs per token match the dense MLP\n- **`torch._grouped_mm`** for dispatching tokens to experts in a single kernel (instead of a Python for-loop)\n- **3D expert weight tensors** `(num_experts, hidden, dim)` — Muon's Polar Express operates on the last two dims, so each expert is independently orthogonalized\n- **Active parameter counting** for scaling laws (only `top_k + shared` experts, not all 8)\n\n### What was easy\n\n- The core MoE forward pass: router, sort tokens by expert, grouped matmul, scatter back. Conceptually clean.\n- Shared expert: just an `nn.Linear` MLP that runs on all tokens alongside the routed path.\n- 3D expert params + Muon: only required fixing `second_momentum_buffer` shape to preserve leading dims.\n- Load balancing: DeepSeekV3's bias nudging is simple and effective (~10 lines).\n\n### What was hard / ugly\n\n- **`torch._grouped_mm` quirks**: requires bf16 (not fp32), column-major right operand, int32 cumulative offsets. The API is undocumented and only discoverable by trial and error.\n- **Token count padding**: torchtitan pads each expert's token count to alignment multiples (8 for bf16) for better grouped_mm throughput. We implemented this with both a pure PyTorch approach and a copy of torchtitan's Triton kernel. Both compiled cleanly (0 graph breaks), but with ~65K tokens across 8 experts, each expert already gets ~8K tokens which is well-aligned. The padding overhead (gather/scatter) actually regressed MFU from 35% to 33%. Reverted.\n- **FP8 + MoE**: `torch._grouped_mm` does NOT support FP8. There's a separate `torch._scaled_grouped_mm` API that requires per-row scaling (not per-tensor like our `Float8Linear`). The backward pass for weight gradients needs per-group column-wise scaling, which torchao implements with custom Triton kernels. We investigated thoroughly (see `dev/moe_fp8.md`) but did not implement — would require either depending on `torchao.prototype` (unstable) or writing ~200 lines of custom autograd + quantization code. Partial FP8 support exists: the shared expert's `nn.Linear` layers do get converted, but the routed experts (3D `nn.Parameter`) stay in bf16.\n\n### Results\n\n- d18: MFU dropped from ~46% to ~35% (the grouped_mm dispatch + token sorting overhead is significant)\n- Per-step improvement in validation loss does not compensate for the throughput hit\n- Net negative on wall clock time\n\n### What remains (if revisited)\n\n- **FP8 for routed experts**: Use `torch._scaled_grouped_mm` with a custom `_Float8GroupedMatmul` autograd function, with bf16 fallback for weight gradient (avoiding the per-group column-wise Triton kernels).\n\nWhat's really needed is a fused \"FlashMoE\" kernel that handles routing + expert dispatch + matmul in one shot (like FlashAttention did for attention), with all the needed features. This doesn't exist yet. Rawdogging MoE with current PyTorch primitives is painful — lots of sorting, gathering, scattering, and layout wrangling around the actual compute.\n\n### Verdict\n\nMoE is not worth the trouble for nanochat right now. The code bloat is substantial (moe.py, router, shared expert, load balancing, optimizer fixes, FP8 gaps, active param counting) and the performance is worse wall-clock at our scale of interest. The fundamental issue is that the grouped_mm dispatch overhead eats the FLOP savings from sparsity, at least at our model scales and sequence lengths.\n\n---\n\n## 2026-02-17: Pretraining Data: FineWeb (negative)\n\nTried vanilla fineweb instead of fineweb-edu dataset. Significantly, shockingly worse results:\n\n- d26 (GPT-2): CORE 0.2602 → 0.2241\n\nThis is the fifth failed attempt to beat pure FineWeb-EDU on CORE score.\n\n---\n\n## 2026-02-17: Pretraining Data Mixture Experiment (negative)\n\nTried [hynky/finepdfs_50BT-dclm_30BT-fineweb_edu_20BT](https://huggingface.co/datasets/hynky/finepdfs_50BT-dclm_30BT-fineweb_edu_20BT), a mixture of FinePDFs, DCLM, and FineWeb-EDU. Slightly worse on both model sizes tested:\n\n- d26 (GPT-2): CORE 0.2602 → 0.2549\n- d18: CORE 0.199 → 0.192\n\nThis is the fourth failed attempt to beat pure FineWeb-EDU on CORE score.\n\n---\n\n## 2026-02-16: SFT Script Upgrades\n\nBrought `chat_sft.py` up to parity with `base_train.py` and tuned settings based on SFT sweeps.\n\nTuning:\n\n- **Optimizer warm-start** (`--load-optimizer=1`, default on): loads pretrained momentum buffers via new `load_optimizer_state()` in `checkpoint_manager.py`. LRs are reset to fresh SFT values after load. Loading the optimizer works slightly better but not by too much.\n- **LR schedule**: replaced \"constant 80%, linear to 0\" with warmup/constant/warmdown matching `base_train.py` (`--warmup-ratio`, `--warmdown-ratio`, `--init-lr-frac`, `--final-lr-frac`). Similar to pretraining, warmdown ratio of 0.5 worked the best. `--init-lr-frac` changed from 1.0 slightly lower to 0.8.\n- **LR tuning**: attempted to tune all the individual LRs (e.g. does SFT prefer lower LR for embeddings? etc.) but all of this produced negative results.\n- **Data mixture**: MMLU epochs 1→3, GSM8K epochs 2→4 (confirmed best from sweeps). Epoch counts now configurable via `--mmlu-epochs` / `--gsm8k-epochs`. Might remove these in the future though.\n\nQuality of life, footguns, minor fixes:\n\n- **Hyperparameter inheritance**: SFT now inherits batch sizes and LRs from the pretrained checkpoint metadata by default (CLI overrides still work). Also saved `total_batch_size` to `base_train.py` checkpoint metadata.\n- **GC management**: disabled Python GC after step 1 to avoid ~500ms pauses (manual collect every 5000 steps), same as base pretraining.\n- **ChatCORE eval**: periodic eval during SFT (`--chatcore-every=200`) across all 6 tasks, logged to wandb.\n- **MFU**: uses `get_peak_flops()` for actual GPU instead of hardcoded H100 value.\n- Removed `--dry-run` and `--dtype` flags. All ranks now participate in checkpoint save.\n\n---\n\n## 2026-02-05: Auto Batch Size Scaling\n\n### Background\n\nSo far, the `--total-batch-size` was hardcoded to be `2**19 = 524,288` ~= 0.5M tokens. This was the optimal setting for d12, but when I tried to re-tune it for d26 (GPT-2), I noticed that the optimal was closer to `2**20 = 1,048,576` ~= 1M tokens. This is to be expected - larger models prefer a higher optimal total batch size. However, we have to make sure that all settings of `--depth` get their own optimal batch size calculated in some principled way. Here, I referenced the \"Power Lines\" paper from Cerebras ([arXiv:2505.13738](https://arxiv.org/abs/2505.13738)) for a lot of related experimentation. In particular, they found that **Bopt ∝ D^0.383** (where D is the number of training tokens, not the number of parameters!). So the idea is to tune the optimal batch size on d12, and then extrapolate it with this power law to bigger models. The 0.383 exponent means batch size grows slowly: 10× more tokens only justifies ~2.4× bigger batch. For nanochat's compute-optimal training (D ∝ N via `--target-param-data-ratio`), this means deeper models naturally want larger batches.\n\n### Implementation\n\nAdded `--total-batch-size=-1` (now the default) to auto-compute optimal batch:\n\n```python\nget_scaling_params = lambda m: m.num_scaling_params()['transformer_matrices'] + m.num_scaling_params()['lm_head']\nif args.total_batch_size == -1:\n    D_REF = args.target_param_data_ratio * get_scaling_params(build_model_meta(12))\n    B_REF = 2**19\n    args.total_batch_size = 2 ** round(math.log2(B_REF * (target_tokens / D_REF) ** 0.383))\n```\n\nReference point: d=12 model with B=2^19 (empirically validated). The reference is computed dynamically so that if the architecture changes (e.g., different `--aspect-ratio`), the math automatically adjusts. However, if the model actually does change too much, one would also want to re-tune the optimal batch size for d=12.\n\n### Results\n\nWith this formula, we currently get:\n\n| Depth | Scaling Params | Target Tokens | Auto Batch |\n|-------|---------------|---------------|------------|\n| d=8   | 42M           | 0.44B         | 2^18 = 262K |\n| d=10-16 | 70M-235M    | 0.7B-2.5B     | 2^19 = 524K |\n| d=18-26 | 324M-918M   | 3.4B-9.6B     | 2^20 = 1.05M |\n| d=32-50 | 1.7B-6.2B   | 17.6B-65.6B   | 2^21 = 2.1M |\n\nIn particular, this matches empirical observations that d26 prefers ~2^20 while d12 prefers ~2^19.\n\n### Code Cleanup\n\nAlso refactored model initialization to use `build_model_meta(depth)` helper and `dataclasses.asdict()` for cleaner config handling.\n\n### Useful references\n\n- [Bergsma et al., Power Laws for Batch Size, Model Size, and Training Horizon](https://arxiv.org/abs/2505.13738)\n- [McCandlish et al., An Empirical Model of Large-Batch Training](https://arxiv.org/abs/1812.06162)\n- [Brown et al., Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165)\n- [Merrill et al., The Batch Size–Critical Batch Size Myth](https://arxiv.org/abs/2505.23971)\n\n### One more thing (batch size ramp)\n\nTried batch size ramping. The simplest implementation I could think of \"tricks\" the existing training loop by slicing each micro-batch into smaller pieces and calling optimizer.step() more frequently early in training (1/8 → 1/4 → 1/2 → full batch over the first x% of training, with sqrt LR scaling). Also required a torch.compile warmup phase to pre-compile all slice sizes and avoid recompilation spikes during training. While the idea is sound and small gains were observed, they weren't sufficient to justify the code complexity introduced (conditional slicing logic, warmup with state save/restore, etc.). Not merged for now.\n\n---\n\n## 2026-02-05: SwiGLU Activation (Negative Result)\n\nReplaced ReLU² MLP activation with SwiGLU (inspired by [twitter](https://x.com/_xjdr/status/2019141521690567058)). SwiGLU uses three projections instead of two, so to match parameters and FLOPs we scale hidden_dim from 4× to 8/3×:\n\n```python\n# Old ReLU²: 2 matrices, 4x expansion\n#   params: 2 × n × 4n = 8n²\n#   flops:  2 × 2n × 4n = 16n² per token\nself.c_fc   = Linear(n_embd, 4 * n_embd)\nself.c_proj = Linear(4 * n_embd, n_embd)\nx = c_proj(relu(c_fc(x)).square())\n\n# New SwiGLU: 3 matrices, 8/3x expansion\n#   params: 2 × n × (8n/3) + (8n/3) × n = 8n²  ✓ matches\n#   flops:  3 × 2n × (8n/3) = 16n² per token   ✓ matches\nhidden_dim = (8 * n_embd) // 3\nself.w1 = Linear(n_embd, hidden_dim)  # gate\nself.w2 = Linear(n_embd, hidden_dim)  # up\nself.w3 = Linear(hidden_dim, n_embd)  # down\nx = w3(silu(w1(x)) * w2(x))\n```\n\nTested at both d12 and d24 (GPT-2 scale). Worse on all measures — step efficiency, wall clock time, and FLOPs. ReLU² remains superior for nanochat. **Not adopted.**\n\n---\n\n## 2026-02-03: Flip Muon MLP LR Multiplier (PR #492)\n\nTested flipping the shape-based LR heuristic in Muon from boosting tall matrices (input projections like `c_fc`) to boosting wide matrices (output projections like `c_proj`). The original code applies `max(1, rows/cols)^0.5`, giving ~2x LR to `c_fc`. The flipped version gives ~2x LR to `c_proj` instead, which aligns with classical fan-in/fan-out scaling conventions. This was proposed in [PR #492](https://github.com/karpathy/nanochat/pull/492) and showed improvements in modded-nanogpt.\n\n**Result:** Quick d12 experiment: slightly worse **Not adopted.**\n\n---\n\n## 2026-02-03: Skip AdamW Every Other Step\n\nInspired by modded-nanogpt, tried stepping AdamW only on odd iterations while Muon steps every iteration. The idea is that small AdamW params (embeddings, scalars, gates) don't need updates as frequently as the large weight matrices, and skipping saves both compute and communication.\n\nAdded `skip_adamw` parameter to `MuonAdamW.step()` and `DistMuonAdamW.step()` plus a matching `zero_grad(skip_adamw=...)` to let AdamW gradients accumulate over 2 steps. Used `lr *= 2**-0.5` (sqrt scaling) to compensate for the 2x effective batch size on AdamW params.\n\n**Result:** for nanochat d12, we see ~2% faster tok/s, but each step is slightly worse in loss. On net, when plotting against wall clock time, it's slightly worse. **Not adopted.**\n\n---\n\n## 2026-02-02: FP8 Training with torchao\n\nIntegrated FP8 training using `torchao.float8` to accelerate Linear layer matmuls on H100 GPUs.\n\n### Background\n\nFP8 (8-bit floating point) uses H100's FP8 tensor cores for ~2x theoretical matmul throughput. The tradeoff is quantization overhead: computing scales and casting tensors to/from FP8. Still, as an example torchtitan (Meta's distributed training framework) reports 25-28% speedups with FP8 for some of their experiments.\n\n**Previous attempt (Jan 2026):** FP8 on just `lm_head` following modded-nanogpt with custom ops → 1% speedup, +2GB memory. Failed due to fragile torch.compile interaction. But this experiment was also done on ~d12 scale back then instead of the bigger model that gets GPT-2 capability of approx d24.\n\n**This attempt:** Use torchao's `convert_to_float8_training()` on ALL Linear layers, increase model size to d24. The core snippet is:\n\n```python\nfrom torchao.float8 import Float8LinearConfig, convert_to_float8_training\nconfig = Float8LinearConfig.from_recipe_name(\"tensorwise\")\nconvert_to_float8_training(model, config=config)\n```\n\nBut in practice it's more involved (see base_train.py).\n\n### Results\n\n**Microbenchmark (d26 MLP, 65536x1664 @ 1664x6656):**\n\n| Method | Forward | Fwd+Bwd | Speedup |\n|--------|---------|---------|---------|\n| BF16 + compile | 2.00ms | 4.79ms | 1.00x |\n| FP8 rowwise + compile | 1.84ms | 4.55ms | 1.08x |\n| FP8 tensorwise + compile | 1.45ms | 4.06ms | **1.38x** |\n| FP8 rowwise (no compile) | 2.89ms | 21.86ms | 0.23x ❌ |\n\ntorch.compile is MANDATORY. Without it, FP8 is 4x slower due to unfused scaling ops.\n\n**Full training (d26):**\n\n| Config | tok/sec | vs baseline |\n|--------|---------|-------------|\n| BF16 baseline | 630K | 1.00x |\n| FP8 rowwise | 564K | 0.90x ❌ |\n| FP8 tensorwise | 740K | **1.17x** ✓ |\n\nMemory usage also decreases quite a bit, by ~9GB (activations stored as FP8 instead of BF16).\n\nSeeing 17% speedup is encouraging but we're still not done yet because each step is now in lower precision and less powerful individually, so to make up for the precision drop we have to train longer. Empirically, running some sweeps overnight on d24 scale, I saw that the actual speedup (when you match performance) is closer to 5%. It's possible that our LLMs at ~d24 scale are still too small to confidently enjoy the speedups that come from fp8 for bigger models.\n\n### Key Learnings\n\nFor nanochat at approximate scale of interest (~GPT-2 capability, ~d24):\n\n1. **Tensorwise >> Rowwise** - Rowwise computes per-row scales, overhead exceeds benefit. Tensorwise uses one scale per tensor.\n2. **Filter small layers** - Layers with dims not divisible by 16 must be skipped (FP8 hardware requirement)\n3. **Larger models benefit more** - d12 was still slower with FP8; d26+ shows gains. Therefore, in some depths there is a benefit to fp8 and in some there isn't. Keeping it configurable for now, passed in via kwargs and default off.\n4. **The effective, capability-matched speedup is lower still** - because each step is of slightly lower precision/quality.\n\n### Integration\n\nAdded `--fp8` flag to `base_train.py`, default recipe is \"tensorwise\", example of turning on:\n\n```bash\ntorchrun --nproc_per_node=8 -m scripts.base_train --depth=24 --fp8\n```\n\nUses tensorwise by default. Requires `torchao==0.15.0` (compatible with torch 2.9.1), which was added to dependencies.\n\n**TLDR**: turning on fp8 for GPT-2 capability nanochat model gives approx +5% capability-matched speedup.\n\n---\n\n## 2026-01-29: Hyperball/MuonH Experiments (Negative Result)\n\nExplored Hyperball optimization from [this post](https://psychedelic-sunstone-851.notion.site/Fantastic-Pretraining-Optimizers-and-Where-to-Find-Them-2-1-Hyperball-Optimization-2e924306e6f280e7a5ffee00eb40a0dd) (saved to `knowledge/muonh.md`). Constrains weights to sphere of radius R (initial norm): `W_{t+1} = R · Normalize(W_t - η·R · Normalize(u_t))`. Had to change a number of details in a branch, e.g. not use zero init for our projections (or the initial norm would be zero), keep track of the initial norm, adjust Muon -> MuonH for the update.\n\nExperiments on d12:\n\n| Experiment | Result |\n|------------|--------|\n| MuonH for matrix params | Worse than baseline |\n| MuonH + LR sweep (2.5e-3 to 1e-2) | Still worse |\n| Added learnable RMSNorm scales (paper says γ preserves expressivity) | Still worse |\n| Various RMSNorm init tweaks, e.g. 0 at init to residual | Still worse |\n| AdamH for lm_head (paper recommends this) | Broken - loss plateaus (see below) |\n| AdamH + learnable output scales | Still worse |\n\nCould not outperform the baseline implementation. The article doesn't go into too much detail on how AdamH is applied to `lm_head` exactly. The classifier layer has to be able to increase in magnitude to make more confident predictions over time. Tried a sensible version with added 0-D learnable scalar, and also with RMSNorms with per-channel learnable scalars both pre and post resnet blocks.\n\n**Result:** This was not an out-of-the-box win for nanochat even with a mild attempt over a few hours at a bit of tuning and debugging. The idea itself is intuitively appealing. Might come back around later to try harder later.\n\n---\n\n## 2026-01-28: Reverted Bigram Hash Embeddings\n\nRemoved bigram embeddings (engram-lite) from the codebase. At larger scale (d25), the improvement was tiny and disappeared entirely when measured by wall clock time. It also bloated the VRAM used. The extra parameters and complexity aren't justified.\n\n---\n\n## 2026-01-27: Bigram Hash Embeddings (Engram-lite)\n\nExplored N-gram memory modules inspired by the [DeepSeek Engram paper](https://arxiv.org/abs/2601.07372) and [modded-nanogpt PR #201](https://github.com/KellerJordan/modded-nanogpt/pull/201).\n\n### Background\n\nThe Engram paper introduces \"conditional memory\" as a complement to MoE - using O(1) hash lookups to retrieve static N-gram patterns instead of reconstructing them through computation. Key insight: transformers waste early layers \"simulating retrieval through computation\" for patterns like named entities and formulaic phrases that could be simple table lookups.\n\n### What We Tried\n\n**1. Full Engram module with context-aware gating (paper design)**\n```python\n# Hash bigrams to retrieve embeddings, then gate with hidden state\ne = embed(hash(prev_token, curr_token))\nq = RMSNorm(h)           # hidden state as query\nk = RMSNorm(W_k @ e)     # projected embedding as key\nv = W_v @ e\nα = sigmoid(q · k / √d)  # scalar gate per position\noutput = α * v\n```\n- Injected after block 1 (paper found early injection optimal)\n- Slight improvement, but quite a bit of complexity added.\n\n**2. Early-layer only injection**\n- Only inject bigram signal in first 4 layers (where paper claims static pattern offloading helps most)\n- **Result:** Actually hurt performance. The model seems to need uniform injection across all layers.\n\n**3. Trigrams**\n- Extended to hash both 2-grams and 3-grams, concatenating embeddings\n- **Result:** No improvement over bigrams alone. Dilutes capacity from more frequent 2-gram patterns.\n\n**4. Bigram-only with x0-style injection (modded-nanogpt engram-lite approach)**\n- Simple hash: `(36313 * curr) XOR (27191 * prev) mod table_size`\n- Zero-init embedding table, learned per-layer lambdas\n- Add to residual at every layer: `x = resid_λ[i]*x + x0_λ[i]*x0 + bigram_λ[i]*x0_bigram`\n- **Result:** This simple approach works and provides a consistent improvement.\n\nTLDR The winning approach follows modded-nanogpt's \"engram-lite\", simply adding the following module and feeding its output into the residual branch (gated by a per-layer learnable \\lambda) before every single block:\n\n```python\nclass BigramEmbed(nn.Module):\n    def __init__(self, vocab_size, embed_dim, table_multiplier=5):\n        self.embed = nn.Embedding(vocab_size * table_multiplier, embed_dim)\n\n    def forward(self, idx):\n        h = (36313 * idx[:, 1:]) ^ (27191 * idx[:, :-1]) % (table_size - 1)\n        return self.embed(h)\n```\n\nAs for optimal hyperparameters:\n\n- **Table size:** `vocab_size * 5` (~164K entries for 32K vocab). Swept a number of settings and 5 was optimal.\n- **Injection:** Every layer via learned `bigram_lambdas` (init 0.1 was better than 0.0).\n- **Normalization:** Also tried adding a `norm()` to the embeddings (mirroring the token embeddings), this was slightly worse.\n- **Init:** Zero-init embedding, so starts as identity (tried small noisy init, it's worse)\n- **Optimizer:** AdamW with same LR as token embeddings\n\n### Key Learnings\n\n1. **Gating didn't help at our scale.** The paper's context-aware gating mechanism (sigmoid dot-product gate) added parameters and complexity without improvement. modded-nanogpt found the same: \"simple direct addition to the residual stream outperformed by a decent margin.\"\n\n2. **Uniform injection beats early-only.** Despite the paper's finding that early layers benefit most, restricting injection to early layers hurt. The x0-style \"add everywhere with learned lambda\" pattern works better for our architecture/scale.\n\n3. **Bigrams are sufficient.** Trigrams didn't help - the extra context doesn't pay for the diluted capacity.\n\n4. **Scale matters.** The Engram paper's results are at 27B params with MoE. At our ~100M-1B scale, the simpler approach wins. The elaborate gating mechanism may become useful at larger scales where collision handling matters more.\n\n### Parameters Added\n\nFor d12 model with `table_multiplier=5`:\n- Bigram embedding: 32768 × 5 × 768 = ~126M params\n- Per-layer lambdas: 12 scalars (negligible)\n\nIf you're keeping track, we now have *a lot* of parameters, a significant amount of them in embeddings (token embeddings, bigram embeddings, value embeddings). For example, for a d12 we now have:\n\n```\nParameter counts:\nwte                     : 25,165,824\nbigram_embed            : 125,829,120\nvalue_embeds            : 150,994,944\nlm_head                 : 25,165,824\ntransformer_matrices    : 84,935,808\nscalars                 : 36\ntotal                   : 412,091,556\n```\n\nIn other words, only about a quarter of parameters are now weight projections and the vast majority is embedding tables.\n\nStill, on all axes (steps, wall clock time, flops), this somewhat parameter-bloated architecture beats the baseline and will now become the default.\n\nAfter adding the engram-lite, I re-ran the scaling laws to determine the new optimal tokens:params ratio. I swept FLOPs in the range 1e18..1e19, exponentially strided in 4 settings (1e18, 2e18, 5e18, 1e19). I looked at a number of ways of determining the effective parameter count for the purposes of the scaling laws. The results looked like this:\n\n```\nKaplan-style (all projections including lm_head and no embeddings)\n\nOptimal configurations (from quadratic fits):\nFLOPs        Eff Params      Tokens          Ratio      Val BPB\n-----------------------------------------------------------------\n1e+18        110,678,115     1,241,505,403   11.2       0.8972\n2e+18        167,797,457     1,785,336,422   10.7       0.8616\n5e+18        250,650,865     2,642,234,152   10.8       0.8293\n1e+19        381,758,347     3,806,871,243   10.3       0.7999\n\nN \\propto C^0.54, D \\propto C^0.49\n\nChinchilla-style (all parameters, period.)\n\nOptimal configurations (from quadratic fits):\nFLOPs        Eff Params      Tokens          Ratio      Val BPB\n-----------------------------------------------------------------\n1e+18        416,320,605     1,232,157,011   3.0        0.8974\n2e+18        560,239,841     1,763,669,281   3.2        0.8616\n5e+18        741,495,903     2,629,909,368   3.6        0.8291\n1e+19        988,644,331     3,884,841,895   4.0        0.7999\n\nN \\propto C^0.37, D \\propto C^0.50\n\nTransformer-only-style (only the projections inside the transformer)\n\nOptimal configurations (from quadratic fits):\nFLOPs        Eff Params      Tokens          Ratio      Val BPB\n-----------------------------------------------------------------\n1e+18        80,259,665      1,315,639,547   17.2       0.8966\n2e+18        131,488,566     1,864,134,141   14.5       0.8622\n5e+18        220,985,474     2,595,328,843   12.1       0.8302\n1e+19        401,213,504     3,328,704,512   8.5        0.7994\n\nN \\propto C^0.70, D \\propto C^0.41\n```\n\nClearly, the Kaplan-style ratios are most consistent and produce stable ~0.5 exponents for both params and tokens, meaning we can have a single fixed ratio of tokens:params for compute optimal models. This turns out to be about ~10.5, which now becomes the new default.\n\n---\n\n## 2026-01-19 to 2026-01-22: Optimizer Hyperparameter Sweep\n\nRan ~320 experiments across 6 rounds, scaling from d12→d16→d20 to find optimal optimizer hyperparameters. Added granular per-component control to `setup_optimizers()` — separate LRs and betas for embedding, unembedding, value_embeds, resid_lambdas, x0_lambdas, and Muon matrix params.\n\n### What We Swept\n- Learning rates for all 6 parameter groups\n- Beta1/beta2 for all 5 AdamW groups\n- Muon momentum (start/end), weight decay\n- Hundreds of combinations (2-way, 3-way, 4-way, etc.)\n\n### The Journey\n\n**At d12**, found two independent improvement routes:\n- **Route A:** emb_lr↑ (0.3→0.4), weight_decay↑ (0.1→0.15), matrix_lr↑ (0.02→0.025)\n- **Route B:** x0_lr↓ (0.5→0.2), x0_beta1↑ (0.8→0.9+)\n\nBoth gave ~0.002 improvement, but combining them caused conflicts. Fine-tuning found wd=0.13, matrix_lr=0.027, emb_lr=0.38 helped slightly. Best d12 config: Route A + x0_beta1=0.95.\n\n**At d16**, Route B became competitive with Route A. The routes still conflicted when combined.\n\n**At d20** (target scale), everything changed:\n- Fine-tuned values from d12 **actively hurt** performance\n- Routes no longer conflicted\n- Just `x0_beta1=0.96` alone captured nearly all the gains\n\n### Final x0_beta1 Sweep at d20\n\n| x0_beta1 | val/bpb | Δ vs baseline |\n|----------|---------|---------------|\n| **0.96** | **0.7971** | **-0.0007** |\n| 0.94 | 0.7972 | -0.0006 |\n| 0.90 | 0.7972 | -0.0006 |\n| 0.97 | 0.7977 | -0.0001 |\n| 0.98 | 0.8011 | +0.0033 💀 |\n\nFlat plateau from 0.90-0.96, then sharp cliff at 0.97+.\n\n### Key Learnings\n\n1. **Hyperparameters are scale-dependent.** What works at d12 doesn't transfer to d20. The elaborate fine-tuning that won at d12 actively hurts at d20.\n\n2. **Improvement magnitude shrinks with scale.** ~0.002 at d12 → ~0.0007 at d20. The baseline is already better-tuned for larger models.\n\n3. **Sharp cliffs exist.** x0_beta1=0.98 is catastrophic while 0.96 is optimal.\n\n4. **Don't over-tune on small proxies.** Validate at target scale before shipping.\n\n### Final Recommendation\n\nFor production d20 runs, add one flag:\n```\n--x0-lambdas-beta1=0.96\n```\n\nSkip everything else discovered at smaller scales.\n\n---\n\n## 2026-01-18: More various experiments\n\n- Tried Muon custom kernels for XXT and all the others. The improvement was there for targeted tests (~20%) but washed out completely to noise in an actual training run, especially because the Muon compute is split across all the workers. Abandoned due to complexity bloat.\n- Fuse Q,K,V,O nn.Linear layers into a single QKVO Linear layer. ~Zero impact\n- Tried the `sa_lambdas` that gate QKV and O. Slightly confused because of the use of rmsnorm, which erases the effect of any scalar multiplier. Helped a tiny bit (~1e-4 of loss), abandoned to control complexity.\n\n---\n\n## 2026-01-17: Various experiments\n\nModded-nanogpt uses [Value Embeddings](https://arxiv.org/abs/2410.17897) (VEs) in a funny U-shaped structure, 3 of them in total and with gates. I tried a large number of tweaks on this today:\n\n- VEs at every layer, at alternating layers, U shaped, front and back. Alternating layers worked best, i.e. we end up with *a lot* more VEs than modded-nanogpt, at every other layer. It works better.\n- Many parameters sharing ideas to reduce new parameter count, nothing here worked. All failed.\n- Many ideas to reduce parameter count, the LLM hates all of them: low rank decompositions, projections. All failed.\n- Gated yes or no and how much. Gate helps.\n\nLong story short is that the models *love* Value Embeddings. It is a way to add a huge amount of capacity (parameters) to the model at almost zero cost of FLOPs, because these embeddings are simply added to the Values tensor. Any attempt to reduce the capacity of value embeddings (param sharing, low rank, projections) fail. The model wants many of them, and with all the capacity, and doing so wins across all x axes of steps, flops and wall clock. I re-ran the scaling laws and, because the models are now very parameter bloated, the optimal ratio has halved from 8 to 4! Way down lower than Chinchilla's 20 at this point.\n\nOther experiments, looking at val/bpb as a function of all of steps, flops and wall clock time:\n\n- Aspect ratio of 128 is worse than 64, I tried a sweep fixing FLOPs == 1e18 and 64 outperforms. The LLM prefers to be slightly thinner and longer.\n- Head dim definitely prefers to be 128 instead of 64, i.e. fewer bigger heads\n- Bunch of other random stuff like that.\n\nKeeping all of this work on a private branch for now but hope to push shortly.\n\n---\n\n## 2026-01-17: Modded-nanogpt Ideas Sweep (Continued)\n\nContinued testing ideas from modded-nanogpt.\n\n| Idea | Result | Notes |\n|------|--------|-------|\n| Attention gates | No improvement | Per-head learnable gates on attention output. +1GB memory, decreased efficiency. |\n| Batch size schedule | Abandoned | 8→16→24 with LR scaling. Made training script too bloated/complex, not worth cognitive overhead. |\n| Value embeddings | Helps a lot | Experiments still ongoing, more on this later. |\n\n---\n\n## 2026-01-16: Flash Attention 3 Fallback to SDPA\n\nAdded automatic fallback from Flash Attention 3 to PyTorch's `scaled_dot_product_attention` (SDPA) for users without Hopper GPUs. This enables nanochat to run on older CUDA GPUs, CPU, and MPS (Apple Silicon).\n\n### Implementation\n\nCreated `nanochat/flash_attention.py` - a unified interface that:\n- Detects FA3 availability at import time (requires sm90+ / Hopper)\n- Exports a `flash_attn` object matching FA3's API exactly (`flash_attn.flash_attn_func`, `flash_attn.flash_attn_with_kvcache`)\n- Automatically routes to FA3 or SDPA based on hardware\n- Handles tensor layout differences: FA3 uses (B, T, H, D), SDPA uses (B, H, T, D)\n- Implements sliding window attention via explicit masks for SDPA\n- Manages KV cache manually for SDPA (FA3 does it in-place)\n\n### Changes to Existing Files\n\nChanges to existing code were intentionally kept extremely minimal.\n\n**gpt.py**: Only the import line changed and a comment\n\n**engine.py**: Zero changes needed\n\n**base_train.py**: Added status print and warnings:\n- Prints whether FA3 or SDPA fallback is being used\n- Warns about efficiency loss without FA3\n- Warns about sliding window support if `--window-pattern` is not \"L\"\n\n### Testing\n\nTests are split into two classes due to dtype/device constraints:\n\n1. **TestFA3VsSDPA**: Comparison tests requiring Hopper GPU + bfloat16. Run both implementations on identical inputs and verify outputs match (max diff typically 0, at most ~0.004 for sliding window).\n\n2. **TestSDPAOnly**: SDPA-only tests that run on any device with appropriate dtype. Verify forward pass, backward pass, and KV cache work correctly.\n\nAdded `_override_impl` mechanism for testing - can force 'fa3' or 'sdpa' to directly compare implementations.\n\n### Notes\n\n- SDPA fallback is significantly slower than FA3 especially in that it lacks the sliding window attention support\n- Recommend `--window-pattern L` (full context) when using SDPA fallback\n\n---\n\n## 2026-01-16: Modded-nanogpt Ideas Sweep (Mostly Negative)\n\nTested several architectural ideas from modded-nanogpt to see if they transfer to nanochat. All of these did not help:\n\n| Idea | Result | Notes |\n|------|--------|-------|\n| Half-truncated RoPE | No improvement | Only first half of head dims get RoPE (base 1024, linspace). Second half \"stationary\". |\n| Asymmetric softcap | Slightly worse | `23 * sigmoid((x+5)/7.5)` vs our symmetric `15 * tanh(x/15)`. May only help with FP8. |\n| Smear gate | Negligible | Blend each token with predecessor via learned gate. Tiny improvement not worth n_embd² params. |\n| Backout | No improvement | Save activations at ~60% through network, subtract scaled version at end. |\n| Skip connection | Slightly worse | Save at layer ~25%, add at layer ~50%. Also +2GB memory from storing activations. |\n\nValue Embeddings do show promise. I need a more elaborate exploration of a few related ideas, which I leave for tomorrow.\n\n---\n\n## 2026-01-15: Olmo pretraining mix (Negative result)\n\nI attempted to train on the Olmo 3 pretraining dataset [allenai/dolma3_mix-6T](https://huggingface.co/datasets/allenai/dolma3_mix-6T) instead of FineWeb-edu. I ran into a number of [errors and issues](https://huggingface.co/datasets/allenai/dolma3_mix-6T/discussions/2) trying to both download and process the dataset and then noticed some quality issues (e.g. some documents seem to be extremely short, like \"5\".). I managed to work around these with some sensible hacks (e.g. reject documents less than 100 characters in length) and tried to process the dataset exactly as FineWeb, re-trained the tokenizer and trained a d16 model. The CORE score decreased from 15.5 to 13.8, i.e. the result is quite a bit worse.\n\nI am still looking to try the [DCLM dataset](https://arxiv.org/abs/2406.11794), which according to the paper should be better that FineWeb-edu. I do have some concerns that the same group both prepared the DCLM dataset *and* introduced the CORE score so I'm a bit hesitant in case there was some overfitting to CORE score adjacent data distribution.\n\nClassifying as negative result and reverting back to FineWeb-edu for now.\n\n---\n\n## 2026-01-13: Varlen Attention (Negative Result)\n\nAttempted to prevent attention from \"leaking\" across document boundaries using Flash Attention's `flash_attn_varlen_func`, similar to modded-nanogpt's approach.\n\n### Background\n\nWith the BOS-aligned dataloader, multiple documents are packed into each row. Standard attention allows tokens to attend across document boundaries within a row. The hypothesis was that preventing this \"leakage\" via varlen attention might improve training.\n\n### Approach: Compute cu_seqlens from inputs\n\n- Find BOS positions: `(inputs.view(-1) == bos_token_id).nonzero()`\n- Gotcha 1: Variable-length `cu_seqlens` caused torch.compile recompilation (25s/iter!) - fixed by padding to fixed size\n- Gotcha 2: `nonzero()` inside compiled model hit recompile limit - fixed by moving computation outside compiled region\n\n### Final Results (d16)\n\n| Metric | Baseline | Varlen |\n|--------|----------|--------|\n| val_bpb | 0.85427 | 0.85407 |\n| MFU | ~same | ~same |\n| tok/sec | ~same | ~same |\n\nEssentially identical. The 0.0002 bpb improvement is almost noise.\n\n### Conclusion\n\nNot worth the code complexity. The \"leakage\" across document boundaries within a row is not harmful - the model handles it fine. The BOS-aligned dataloader already provides the key benefit (every row starts with proper context). Not merging to master.\n\n---\n\n## 2026-01-13: BOS-Aligned Dataloader with Bin Packing\n\nRedesigned the pretraining and midtraining dataloader to ensure every sequence starts with a BOS token, and explored bin-packing algorithms to minimize wasted tokens.\n\n### Problem Statement\n\nThe original dataloader streams tokens into a flat buffer and reshapes into batches. This means some rows start mid-document (no BOS), which could confuse the model during training. We want every row to start with BOS and contain well-formed documents.\n\n### Approach 1: Greedy-Crop BOS (Simple)\n\nEach row is built independently:\n- Start with a document (which has BOS prepended)\n- Pack more documents until row is full\n- If a document doesn't fit, **crop it** to fill remaining space (discard the rest)\n- 100% utilization (no padding), but wastes cropped tokens\n\n### Waste Analysis\n\nMeasured token waste empirically on real data (T=2048):\n- **39.4% of tokens are cropped** (discarded when docs don't fit)\n- **22.9% is the theoretical minimum** (tokens in docs longer than T+1 that can never fit)\n- The extra ~16.5% comes from \"unlucky\" cropping when a long doc starts near the end of a row\n\n### Bin Packing Algorithms Explored\n\n| Algorithm | Util% | Crop% | Pad% | Notes |\n|-----------|-------|-------|------|-------|\n| Greedy-Crop (baseline) | 100% | 39.4% | 0% | Simple, no wasted compute |\n| Greedy-Pad | 78% | 23.0% | 22% | Pads instead of crops - wastes compute |\n| First-Fit Decreasing (FFD) | 99.7% | 23.0% | 0.3% | Near-optimal packing, minimal padding |\n| **BestFit-Crop** | 100% | 34.6% | 0% | Smart cropping, no padding |\n\n### BestFit-Crop Algorithm\n\nA middle ground that maintains 100% utilization while reducing cropping:\n\n1. Buffer N documents\n2. For each row, greedily pick the **largest doc that fits entirely**\n3. Repeat until nothing fits\n4. When nothing fits, crop a doc to fill remaining space exactly\n\nThis avoids \"unlucky\" crops by searching the buffer for better-fitting documents.\n\n**Results (T=2048):**\n- Crop waste reduced from 39.4% → 34.6% (~12% relative improvement)\n- Still achieves 100% utilization (no padding, every token trains)\n- Slightly more rows than baseline (uses more documents per batch)\n\n### Decision: Keep Two Implementations\n\n1. Keep the original implementation which is very simple, efficient and has 100% token utilization in the batch (no padding with ignore tokens), but creates slightly more confusing token streams for the LLM because documents during training can start abruptly from the middle with no context. Note that this never happens at test time, where BOS is always present.\n\n2. **`_bos_bestfit` (BestFit-Crop, new default)**: Slightly more complex but still keeps 100% token utilization in the batch (no padding), but at the cost of discarding documents when they don't fit. In practice, about 34% of tokens are discarded with this approach. This is ok because for most models we care about we have plenty of data without having to go to multiple epochs. One more subtle effect is that it does skew the data distribution a tiny bit because, reliably and necessarily, tokens at the tails of long documents will be discarded. However, this doesn't seem to impact actual downstream performance.\n\n### Midtraining\n\nThe midtraining dataloader was also updated. Because conversations are on average a lot shorter than pretraining documents, only about 3.3% of tokens get cropped.\n\n### NOTE: loss scale\n\nDo note that switching to the BOS dataloader changes the validation loss and makes all previous experiments not comparable in absolute value of the loss, because we have a lot fewer \"confusing\" tokens in the train/val batches. All tokens can look back and find the BOS token and have the full context of that document to make predictions. Therefore, the loss appears lower but this is \"fake\" to some extent, and the expectation is that the vast majority of relative comparisons done so far would agree with those before and after this change.\n\n---\n\n## 2026-01-13: Number Token Split Pattern\n\nValidated the `\\p{N}{1,2}` pattern in `SPLIT_PATTERN` (tokenizer.py line 30), which I only guessed earlier and had a TODO for to validate. GPT-4 uses `\\p{N}{1,3}` to group number sequences of up to 3 digits into tokens, but we suspected smaller vocab sizes benefit from grouping fewer digits per token.\n\n**Results (d12, vocab=32K):**\n| Pattern | val_bpb |\n|---------|---------|\n| `\\p{N}{1,1}` | 0.969 |\n| `\\p{N}{1,2}` | **0.965** |\n| `\\p{N}{1,3}` | 0.972 |\n\n**Conclusion:** `{1,2}` is optimal for vocab size 32K. Grouping 3 digits wastes tokens on rare 3-digit combinations; grouping 1 digit is too fine-grained and bloats token sequences. Keeping `{1,2}` as default.\n\n---\n\n## 2026-01-13: FP8 Training for lm_head\n\nAttempted to use FP8 (8-bit floating point) for the lm_head layer to speed up the large vocab projection matmul. H100 GPUs have FP8 tensor cores that can theoretically provide ~2x speedup over BF16.\n\n### Implementation Approaches Tried\n\n**1. Dynamic Scaling (failed)**\n- Compute `x.abs().max()` and `w.abs().max()` each forward to determine scales\n- Problem: `.item()` calls cause graph breaks with torch.compile\n- Tried `@torch._dynamo.allow_in_graph` pattern (like torchao.float8) - worked but no speedup\n- Tried `torch.library.custom_op` with float scales - caused NaN gradients after first optimizer step\n- Root cause: interaction between custom ops, dynamic scale computation, and torch.compile is fragile\n\n**2. Static Scaling (partial success)**\n- Pre-set scales at init time like modded-nanogpt: `x_scale=10/448, w_scale=0.1/448`\n- `grad_scale` computed dynamically from batch size (safe since it's just `1/(B*T)/57344` due to the gradient expression of cross entropy). modded-nanogpt has a bug here probably because they set `grad_scale = 0.75/448`, but grads are in E5M2 so this should probably be `1/57344`, 1 being the amax of any individual element of cross entropy loss, and no normalization by B,T because they use sum reduction not mean reduction.\n- Uses `torch.library.custom_op` with `@torch.compile` on inner kernels\n- This works correctly - no NaNs, proper gradients\n\n### Results (d12)\n\n| Metric | BF16 Baseline | FP8 lm_head |\n|--------|---------------|-------------|\n| GPU Memory | 34 GB | 36 GB |\n| tok/sec | baseline | ~1% faster |\n\n### The Memory Mystery\n\nFP8 *should* save memory since we store `x_f8` (1 byte) instead of `x` (2 bytes) for backward. But we see 2GB *increase*. Suspected causes:\n- `torch.compile` on inner kernels creating extra buffers/specializations\n- `torch._scaled_mm` internal workspace allocations\n- Custom op registration machinery overhead\n\nTried saving original weight `w` (just a reference to parameter) instead of `w_f8` in backward, then re-quantizing on the spot during backward - didn't help. Still saw bump.\n\n### Microbenchmark vs Reality\n\nRaw microbenchmark showed promise:\n- BF16 matmul: 16.95 ms\n- FP8 matmul (static scales): 10.31 ms (1.64x faster)\n- FP8 with dynamic scaling: 12.25 ms (1.38x faster)\n\nBut in full training, the ~1% tok/sec improvement doesn't justify the 2GB memory increase and the added code complexity and the need to tune scale factors for both x and w.\n\n### Code Artifacts\n\nSee the branch `fp8_attempt_fail` for:\n\n- `nanochat/fp8_static.py` - Static scaling implementation (working)\n- `nanochat/fp8_dynamic.py` - Dynamic scaling implementation (torchao-style, working but slow)\n- `gpt.py` imports `fp8_static.LinearFP8` and simply swaps it for `lm_head` in `gpt.py`.\n\n### Open Questions\n\n- Why does the custom op approach use more memory than vanilla BF16?\n- Why is the bump in tok_per_sec so low? We should see ~1.6X speedup in both the forward pass and also (twice) in backward pass for the gradients. Granted, Amdahl's law is part of the solution because our vocab_size is only 32K so the final layer isn't a huge part of the profile but the expected speedup is still not fully realized.\n\n**Conclusion:** Negative result for now. The implementation works correctly but provides marginal speedup with *increased* memory usage. I'm not understanding the torch.compile interaction here. The complexity of FP8 custom ops isn't justified for lm_head alone. TODO to study in more detail the way this is implemented in other libraries, e.g. torchao.\n\n---\n\n## 2026-01-12: Multi-Token Prediction (MTP)\n\nPorted multi-token prediction from modded-nanogpt. Instead of predicting just the next token, predict the next n tokens at each position with weighted loss.\n\n### Implementation\n\n- Instead of calling the loss `n_predict` times, uses a fancy batched computation using `unfold` + `gather` + cross-entropy decomposition (`CE = logsumexp - logits[target]`)\n- Schedule anneals from 3-token to 1-token prediction:\n  - 0-33%: `[1.0, 0.5, 0.25→0]` (3rd token fades)\n  - 33-67%: `[1.0, 0.5→0]` (2nd token fades)\n  - 67-100%: `[1.0]` (standard next-token)\n- Weights normalized to sum to 1\n\n### Results (d12)\n\n| Metric | Baseline | MTP |\n|--------|----------|-----|\n| GPU Memory | 34 GB | 47 GB |\n| MFU | 41% | 40% |\n| val/bpb (per step) | baseline | same/slightly worse |\n| val/bpb (wall clock) | baseline | noticeably worse |\n\n**Conclusion:** Negative result for nanochat. The extra memory and compute overhead from predicting multiple tokens doesn't pay off, in fact the results get worse. The auxiliary loss signal may help in other settings (larger models, different architectures?), but for our setup it's pure overhead at the moment.\n\n---\n\n## 2026-01-11: Sliding Window Attention\n\nAdded configurable sliding window attention, inspired by GPT-3's alternating short/long pattern.\n\n**Pattern string configuration:**\n- New `--window_pattern` CLI arg and `GPTConfig.window_pattern` field\n- Pattern is tiled across layers (e.g., `SSSL` for 20 layers → `SSSLSSSLSSSLSSSLSSSL`)\n- Final layer always forced to L (full context) regardless of pattern\n- Short window = `sequence_len // 2`\n- Long window = `sequence_len` (full context)\n- All previous models so far have been simply `L` and checkpoint loading is modified accordingly to fill in this param for old models, see `_patch_missing_config_keys`\n\nQuick experiments showed `SSSL` (every 4th layer is long) works well - provides a good balance between compute savings and model quality. This is now the default.\n\n---\n\n## 2026-01-11: Flash Attention 3 Integration\n\nReplaced PyTorch's `scaled_dot_product_attention` (FA2) with Flash Attention 3 for training and inference.\n\n### Changes Made\n\n**1. FA3 via `kernels` package**\n- Official FA3 is \"beta\" and requires building from source (painful)\n- Using `kernels` package from HuggingFace Hub: `get_kernel('varunneal/flash-attention-3')`\n- Loads pre-built wheels, works out of the box on H100\n\n**2. Simplified attention code**\n- FA3 uses `(B, T, H, D)` layout matching our projection output directly - no transpose needed\n- Training: `flash_attn.flash_attn_func(q, k, v, causal=True)`\n- Inference: `flash_attn.flash_attn_with_kvcache()` handles all cache cases in one call\n- Removed 3 separate FA2 code paths (training, single-token, chunk inference)\n- GQA handled automatically when n_kv_heads < n_heads\n\n**3. Rewrote KVCache for FA3**\n- Old format: `(num_layers, 2, B, H, T, D)` combined tensor\n- New format: separate `k_cache` and `v_cache` of shape `(num_layers, B, T, H, D)`\n- FA3 updates cache in-place during `flash_attn_with_kvcache`\n- Position tracked via `cache_seqlens` tensor (int32, per batch element)\n- Simpler API: `get_layer_cache()`, `advance()`, `reset()`, `prefill()`\n\n### Results\n\n- **~9% improvement in tok/sec** during training out of the box\n- Benchmarks showed FA3 is 2x faster than FA2 at realistic training sizes (batch=32, seq=2048)\n- FA3 supports sliding window via `window_size=(left, 0)`, which is huge and expected to give further improvements. This is ready to tune but keeping full context for now.\n\n---\n\n## 2026-01-11: Per-Layer Residual Scalars (x0 & resid lambdas)\n\nCherry-picked an idea from modded-nanogpt around learnable per-layer residual connections.\n\n### Changes Made\n\n**1. x0_lambdas (x0 residual connections)**\n- Save initial normalized embedding as `x0` after `norm(wte(idx))`\n- At each layer, blend x0 back in: `x = resid_lambdas[i] * x + x0_lambdas[i] * x0`\n- Zero-initialized, so disabled at start; model learns which layers benefit from the shortcut\n- Provides direct path from embedding to deep layers, helps preserve token information\n\n**2. resid_lambdas (residual stream scaling)**\n- Per-layer multiplicative scaling of the residual stream\n- Initialized to 1.0 (neutral, standard transformer behavior)\n- Allows model to learn to amplify/dampen residual at each layer\n\n**3. DistAdamW small parameter handling**\n- Added support for parameters with < 1024 elements (like the scalar lambdas)\n- Small params use `all_reduce` instead of `reduce_scatter`/`all_gather`\n- Fixes crash when param shape isn't divisible by world_size\n\n### Key Finding: Different LR Sensitivity\n\nThe two scalar types need very different learning rates:\n- **x0_lambdas (additive)**: Can use normal LR (~0.5). Adding a fraction of x0 is forgiving.\n- **resid_lambdas (multiplicative)**: Needs ~100x smaller LR (~0.005). Multiplying the residual compounds through layers.\n\nImplementation: `resid_params` gets `scalar_lr * 0.01`, `x0_params` gets full `scalar_lr`.\n\n### Experiment Results\n\nSwept `--scalar_lr` (controlling x0_lambdas) at multiple depths:\n\n| Depth | Baseline (disabled) | Best scalar_lr | Best val_bpb | Δ bpb |\n|-------|---------------------|----------------|--------------|-------|\n| d8    | 1.0885              | 0.20           | 1.0782       | -0.0103 |\n| d12   | 0.9770              | 0.60           | 0.9693       | -0.0077 |\n| d16   | 0.9059              | 0.20           | 0.9002       | -0.0057 |\n| d20   | 0.8565              | 0.10           | 0.8526       | -0.0039 |\n\n**Observations:**\n- Consistent improvement across all model sizes\n- Optimal LR varies by depth; default of 0.5 is reasonable, but 0.6 is better for d12\n- Adding resid_lambdas (with 0.01x LR) gives small additional improvement over x0 alone\n\n### Meta Device Footgun\n\nImportant lesson: `__init__` runs in meta device context, so any tensor values set there are fake. Must initialize actual values in `init_weights()`. Added docstring warning to `__init__`.\n\n### Summary\n\nAdded `--scalar_lr` (default 0.5) controlling learnable per-layer scalars. The formula `x = resid_lambdas[i] * x + x0_lambdas[i] * x0` gives the model control over residual scaling and direct shortcuts to the initial embedding. Solid improvement with essentially no compute overhead.\n\n---\n\n## 2026-01-10: Muon Optimizer Upgrades & Cautious Weight Decay\n\nCherry-picked improvements from NorMuon (modded-nanogpt) into our simpler Muon implementation. Decided against using NorMuon directly due to hard-coded architecture assumptions (expects 32 params split 10 attn + 22 mlp), parameter labeling requirements, and complexity.\n\n### Changes Made\n\n**1. Polar Express Orthogonalization**\n- Replaced Newton-Schulz iteration with \"Polar Express Sign Method\" from [arxiv.org/pdf/2505.16932](https://arxiv.org/pdf/2505.16932)\n- Uses 5 different coefficient tuples (one per iteration) instead of fixed coefficients\n- Both methods kept in code for easy comparison (`zeropower_via_polar_express` vs `zeropower_via_newtonschulz5`)\n- **Result:** No dramatic/noticeable difference in training, but keeping the new Polar Express as default.\n\n**2. NorMuon Variance Reduction**\n- Added per-neuron/column adaptive learning rate from NorMuon ([arxiv.org/pdf/2510.05491](https://arxiv.org/pdf/2510.05491))\n- Maintains `second_momentum_buffer` with shape `[rows, 1]` or `[1, cols]` (whichever is smaller)\n- Normalizes updates based on running per-row/col variance estimate (beta2=0.95)\n- Memory overhead: ~1/max(rows, cols) per param, negligible\n- **Result:** Led to a very small improvement, kept and enabled by default.\n\n**3. Cautious Weight Decay**\n- Only decays weights where `update * weight >= 0` (same sign) from [arxiv.org/abs/2411.16085](https://arxiv.org/abs/2411.16085)\n- Standard WD always pulls toward zero; cautious WD skips decay when gradient is pushing weight away from zero\n- **Implementation note:** Had to inline the logic rather than use a separate `@torch.compile` function. Passing changing float values (like `weight_decay` during scheduling) as function arguments triggers recompilation. Reading from `group[\"weight_decay\"]` inside the step avoids this.\n- **Result:** Solid improvements, especially the cautious version was better than standard wd.\n- Now defaults to ON for Muon via the `weight_decay` param. AdamW still has no weight decay and is hardcoded to 0 weight decay, might try to re-tune this later.\n\n**4. Weight decay schedule**\n- Added a linear schedule to weight decay that is default on from 1.0 to 0.0 (i.e. start with max weight decay in the beginning of training, then ramp to 0 by the end). Worked better than a static setting in experiments. (modded-nanogpt has the same schedule but it is implemented in a more confusing way by multiplying twice by the learning rate, which is already wired up to a decay schedule).\n\n### Weight Decay Scaling Experiments\n\nSwept weight decay values at d8, d12, d16, d20 to find optimal values and scaling law.\n\n**Optimal Values Found:**\n| Depth | Width (channels) | Optimal WD |\n|-------|------------------|------------|\n| d8    | 512              | ~0.40      |\n| d12   | 768              | ~0.22      |\n| d16   | 1024             | ~0.10      |\n| d20   | 1280             | ~0.08      |\n\n**Scaling Law:**\n- Fit power law: `WD = k / channels^α` in log-log space\n- Found α ≈ 1.97 (approximately 2), meaning WD ∝ 1/width²\n\n**Practical Formula:**\n```\nWD_target = WD_reference × (d_reference / d_target)²\n```\nExample: If d12 optimal is 0.22, then d20 optimal ≈ 0.22 × (12/20)² ≈ 0.08\n\n**Reference:** Moonlight paper uses fixed WD=0.1 for their 15B MoE model. Our experiments indicated a scaling law where the optimal WD changed with depth, so we go along with the empirical scaling law.\n\n### Summary\n\nMuon was changed to use Polar Express, added NorMuon variance reduction, and cautious weight decay with schedule that ramps linearly to zero. All of these changes follow modded-nanogpt repo, but all of them were also validated piece by piece to yield improvements in nanochat with the exception of the Polar Express change which was in the noise. This is default on and configurable with `--weight_decay`, using simply 0.2 and ∝ 1/width² scaling. The kwarg `--weight_decay` is therefore changing as of this change. It used to configure AdamW via standard weight decay and now it becomes exclusively used in Muon (AdamW is hardcoded to 0.0), and it is scaled based on depth.\n\n---\n\n## 2026-01-08: exp_grad_clip - Gradient Clipping\n\n**Hypothesis:** Gradient clipping may be unnecessary overhead. Tested L2 norm clipping at various thresholds (0.25, 0.5, 1.0, 2.0) and elementwise clipping.\n\n**Results:**\n- No benefit at any scale tested (d12, d20)\n- All variants within noise (~0.9827 val_bpb)\n- Grad norm never exceeds 1.0 naturally, so clipping is always inactive\n- Clipping adds ~2% time overhead from the all-reduce\n\n**Bug Found:** Original implementation clipped local gradients before sync. Since this codebase doesn't use DDP (gradient sync is in the optimizers), each rank was clipping based on its own local norm. Fixed on the branch with proper distributed all-reduce.\n\n**Observation:** modded-nanogpt does not appear to clip either right now.\n\n**Summary:** Deleted all grad-clip code paths. The code naturally produces well-behaved gradients. This improves a bit of MFU because we don't have to calculate and sync grad norms.\n"
  },
  {
    "path": "dev/estimate_gpt3_core.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Estimating CORE Metric for GPT-3 Models\\n\",\n    \"\\n\",\n    \"**Authors**: Claude Code Opus 4.5, Andrej Karpathy\\n\",\n    \"\\n\",\n    \"**Date**: Jan 2026\\n\",\n    \"\\n\",\n    \"## Motivation\\n\",\n    \"\\n\",\n    \"The [CORE metric](https://arxiv.org/abs/2406.11794) (introduced in the DCLM paper) is a composite benchmark that evaluates pretrained language models across 22 diverse tasks spanning world knowledge, language understanding, commonsense reasoning, symbolic problem solving, and reading comprehension. It provides a single score that captures a model's general capabilities.\\n\",\n    \"\\n\",\n    \"We want to compare nanochat models against the GPT-3 model family from OpenAI's [\\\"Language Models are Few-Shot Learners\\\"](https://arxiv.org/abs/2005.14165) paper (2020). However, there's a problem: **GPT-3 models were never evaluated on CORE** (which didn't exist in 2020), and the models were never publicly released, so we can't evaluate them ourselves.\\n\",\n    \"\\n\",\n    \"## Our Approach\\n\",\n    \"\\n\",\n    \"We estimate CORE scores for GPT-3 by:\\n\",\n    \"\\n\",\n    \"1. **Identifying overlapping tasks** between the GPT-3 paper and CORE that were evaluated with similar methodology\\n\",\n    \"2. **Using GPT-2 as calibration data** — we have actual CORE scores for all 4 GPT-2 models, plus the GPT-3 paper reports results on GPT-2-equivalent tasks\\n\",\n    \"3. **Fitting a regression model** from the overlapping task scores to the full CORE score\\n\",\n    \"4. **Applying the model to GPT-3** using their reported task scores\\n\",\n    \"\\n\",\n    \"This notebook documents our methodology in detail for reproducibility.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Setup\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 1,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import numpy as np\\n\",\n    \"from pathlib import Path\\n\",\n    \"import pandas as pd\\n\",\n    \"\\n\",\n    \"# For nice table display\\n\",\n    \"pd.set_option('display.precision', 4)\\n\",\n    \"pd.set_option('display.max_columns', 20)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Part 1: Understanding CORE\\n\",\n    \"\\n\",\n    \"CORE consists of **22 tasks** evaluated in specific few-shot settings. The key innovation is **centering**: raw accuracies are adjusted to account for random guessing baselines.\\n\",\n    \"\\n\",\n    \"$$\\\\text{centered accuracy} = \\\\frac{\\\\text{accuracy} - \\\\text{baseline}}{1 - \\\\text{baseline}}$$\\n\",\n    \"\\n\",\n    \"The final CORE score is simply the **mean of all 22 centered accuracies**.\\n\",\n    \"\\n\",\n    \"### CORE Tasks\\n\",\n    \"\\n\",\n    \"| Category | Tasks |\\n\",\n    \"|----------|-------|\\n\",\n    \"| World Knowledge | Jeopardy, ARC Easy, ARC Challenge, BigBench QA Wikidata |\\n\",\n    \"| Language Understanding | HellaSwag (0-shot & 10-shot), LAMBADA, Winograd, Winogrande, BigBench Language ID |\\n\",\n    \"| Commonsense Reasoning | COPA, CommonsenseQA, PIQA, OpenBookQA |\\n\",\n    \"| Symbolic Problem Solving | BigBench Dyck, Operators, CS Algorithms, Repeat Copy Logic, AGI Eval LSAT-AR |\\n\",\n    \"| Reading Comprehension | SQuAD, CoQA, BoolQ |\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Part 2: Task Overlap Analysis\\n\",\n    \"\\n\",\n    \"We carefully compared the evaluation methodology between GPT-3 and CORE for each task. Key considerations:\\n\",\n    \"\\n\",\n    \"1. **Number of few-shot examples (K)**: GPT-3 often uses more examples than CORE\\n\",\n    \"2. **Task format**: Some tasks use different prompting strategies\\n\",\n    \"3. **Scoring method**: GPT-3 uses unconditional probability normalization for some tasks\\n\",\n    \"4. **Data split**: dev vs test set\\n\",\n    \"\\n\",\n    \"### Selection Criteria\\n\",\n    \"\\n\",\n    \"We applied a conservative filter: **both evaluations must use K=0 (zero-shot) or both must use K>0 (few-shot)**. We excluded tasks that mix zero-shot with few-shot, as this introduces systematic differences.\\n\",\n    \"\\n\",\n    \"### Tasks We Excluded\\n\",\n    \"\\n\",\n    \"| Task | GPT-3 K | CORE K | Reason for Exclusion |\\n\",\n    \"|------|---------|--------|----------------------|\\n\",\n    \"| Winograd | 7 | 0 | Mixing K>0 with K=0 |\\n\",\n    \"| Winogrande | 50 | 0 | Mixing K>0 with K=0 |\\n\",\n    \"| COPA | 32 | 0 | Mixing K>0 with K=0 |\\n\",\n    \"| OpenBookQA | 100 | 0 | Mixing K>0 with K=0, also uses unconditional normalization |\\n\",\n    \"| BoolQ | 32 | 10 | High sensitivity to K (17% gap between 0-shot and few-shot in GPT-3) |\\n\",\n    \"| CoQA | 5 | 0 | Different metric (F1 vs accuracy) |\\n\",\n    \"| LAMBADA few-shot | 15 | 0 | GPT-3 uses special fill-in-blank format |\\n\",\n    \"\\n\",\n    \"### Tasks Not in GPT-3 Paper\\n\",\n    \"\\n\",\n    \"These CORE tasks simply don't appear in GPT-3 (many didn't exist in 2020):\\n\",\n    \"- All 6 BigBench tasks (Dyck, Operators, CS Algorithms, Repeat Copy Logic, Language ID, QA Wikidata)\\n\",\n    \"- Jeopardy, CommonsenseQA, AGI Eval LSAT-AR\\n\",\n    \"- SQuAD v1 (GPT-3 uses v2)\\n\",\n    \"\\n\",\n    \"### Final Selected Tasks (6 tasks)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 2,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Task</th>\\n\",\n       \"      <th>GPT-3 K</th>\\n\",\n       \"      <th>CORE K</th>\\n\",\n       \"      <th>Match</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>HellaSwag 0-shot</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>Both zero-shot</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>LAMBADA</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>0</td>\\n\",\n       \"      <td>Both zero-shot</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>HellaSwag 10-shot</td>\\n\",\n       \"      <td>20</td>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>Both few-shot (K differs slightly)</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>PIQA</td>\\n\",\n       \"      <td>50</td>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>Both few-shot</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>ARC Easy</td>\\n\",\n       \"      <td>50</td>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>Both few-shot</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>5</th>\\n\",\n       \"      <td>ARC Challenge</td>\\n\",\n       \"      <td>50</td>\\n\",\n       \"      <td>10</td>\\n\",\n       \"      <td>Both few-shot</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"                Task  GPT-3 K  CORE K                               Match\\n\",\n       \"0   HellaSwag 0-shot        0       0                      Both zero-shot\\n\",\n       \"1            LAMBADA        0       0                      Both zero-shot\\n\",\n       \"2  HellaSwag 10-shot       20      10  Both few-shot (K differs slightly)\\n\",\n       \"3               PIQA       50      10                       Both few-shot\\n\",\n       \"4           ARC Easy       50      10                       Both few-shot\\n\",\n       \"5      ARC Challenge       50      10                       Both few-shot\"\n      ]\n     },\n     \"execution_count\": 2,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# The 6 tasks we selected for overlap\\n\",\n    \"selected_tasks = pd.DataFrame([\\n\",\n    \"    {'Task': 'HellaSwag 0-shot', 'GPT-3 K': 0, 'CORE K': 0, 'Match': 'Both zero-shot'},\\n\",\n    \"    {'Task': 'LAMBADA', 'GPT-3 K': 0, 'CORE K': 0, 'Match': 'Both zero-shot'},\\n\",\n    \"    {'Task': 'HellaSwag 10-shot', 'GPT-3 K': 20, 'CORE K': 10, 'Match': 'Both few-shot (K differs slightly)'},\\n\",\n    \"    {'Task': 'PIQA', 'GPT-3 K': 50, 'CORE K': 10, 'Match': 'Both few-shot'},\\n\",\n    \"    {'Task': 'ARC Easy', 'GPT-3 K': 50, 'CORE K': 10, 'Match': 'Both few-shot'},\\n\",\n    \"    {'Task': 'ARC Challenge', 'GPT-3 K': 50, 'CORE K': 10, 'Match': 'Both few-shot'},\\n\",\n    \"])\\n\",\n    \"selected_tasks\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"**Rationale for K differences:** Looking at GPT-3's own data, the difference between different K values is typically small. Here's the evidence from the GPT-3 175B model:\\n\",\n    \"\\n\",\n    \"| Task | 0-shot | Few-shot | K | Δ |\\n\",\n    \"|------|--------|----------|---|---|\\n\",\n    \"| HellaSwag | 78.9% | 79.3% | 20 | +0.4% |\\n\",\n    \"| PIQA | 81.0% | 82.3% | 50 | +1.3% |\\n\",\n    \"| ARC Easy | 68.8% | 70.1% | 50 | +1.3% |\\n\",\n    \"| ARC Challenge | 51.4% | 51.5% | 50 | +0.1% |\\n\",\n    \"| Winograd | 88.3% | 88.6% | 7 | +0.3% |\\n\",\n    \"| COPA | 91.0% | 92.0% | 32 | +1.0% |\\n\",\n    \"\\n\",\n    \"For most tasks, the gap between 0-shot and few-shot (with K=20-50) is only 0.1-1.3%. This suggests that differences between K=10 and K=50 would be even smaller, making our task selection reasonable.\\n\",\n    \"\\n\",\n    \"**Note:** Some tasks show larger sensitivity (Winogrande: +7.5%, BoolQ: +17%), which is why we excluded them.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Part 3: Calibration Data (GPT-2 Family)\\n\",\n    \"\\n\",\n    \"We have actual CORE scores for all 4 GPT-2 models. These serve as our calibration data.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 3,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Random baselines for centering (from CORE specification)\\n\",\n    \"BASELINES = {\\n\",\n    \"    'hellaswag_zeroshot': 0.25,\\n\",\n    \"    'lambada_openai': 0.0,\\n\",\n    \"    'hellaswag': 0.25,\\n\",\n    \"    'piqa': 0.50,\\n\",\n    \"    'arc_easy': 0.25,\\n\",\n    \"    'arc_challenge': 0.25,\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"TASK_ORDER = ['hellaswag_zeroshot', 'lambada_openai', 'hellaswag', 'piqa', 'arc_easy', 'arc_challenge']\\n\",\n    \"TASK_NAMES = ['HellaSwag 0-shot', 'LAMBADA', 'HellaSwag 10-shot', 'PIQA', 'ARC Easy', 'ARC Challenge']\\n\",\n    \"\\n\",\n    \"def center_accuracy(acc, baseline):\\n\",\n    \"    \\\"\\\"\\\"Convert raw accuracy to centered accuracy.\\\"\\\"\\\"\\n\",\n    \"    return (acc - baseline) / (1.0 - baseline)\\n\",\n    \"\\n\",\n    \"def parse_csv(filepath):\\n\",\n    \"    \\\"\\\"\\\"Parse a CORE results CSV file.\\\"\\\"\\\"\\n\",\n    \"    results = {}\\n\",\n    \"    with open(filepath) as f:\\n\",\n    \"        for line in f:\\n\",\n    \"            parts = [p.strip() for p in line.strip().split(',')]\\n\",\n    \"            if len(parts) >= 3 and parts[0] != 'Task':\\n\",\n    \"                task = parts[0]\\n\",\n    \"                try:\\n\",\n    \"                    acc = float(parts[1]) if parts[1] else None\\n\",\n    \"                    centered = float(parts[2]) if parts[2] else None\\n\",\n    \"                    results[task] = {'accuracy': acc, 'centered': centered}\\n\",\n    \"                except ValueError:\\n\",\n    \"                    pass\\n\",\n    \"    return results\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 4,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-2 Family: Raw Accuracies and CORE Scores\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Model</th>\\n\",\n       \"      <th>Params</th>\\n\",\n       \"      <th>HellaSwag 0-shot</th>\\n\",\n       \"      <th>LAMBADA</th>\\n\",\n       \"      <th>HellaSwag 10-shot</th>\\n\",\n       \"      <th>PIQA</th>\\n\",\n       \"      <th>ARC Easy</th>\\n\",\n       \"      <th>ARC Challenge</th>\\n\",\n       \"      <th>CORE</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>GPT-2</td>\\n\",\n       \"      <td>124M</td>\\n\",\n       \"      <td>30.9%</td>\\n\",\n       \"      <td>32.3%</td>\\n\",\n       \"      <td>30.8%</td>\\n\",\n       \"      <td>62.3%</td>\\n\",\n       \"      <td>41.2%</td>\\n\",\n       \"      <td>22.2%</td>\\n\",\n       \"      <td>0.1139</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>GPT-2 Medium</td>\\n\",\n       \"      <td>355M</td>\\n\",\n       \"      <td>39.0%</td>\\n\",\n       \"      <td>42.6%</td>\\n\",\n       \"      <td>39.5%</td>\\n\",\n       \"      <td>67.0%</td>\\n\",\n       \"      <td>48.0%</td>\\n\",\n       \"      <td>26.2%</td>\\n\",\n       \"      <td>0.1849</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>GPT-2 Large</td>\\n\",\n       \"      <td>774M</td>\\n\",\n       \"      <td>44.0%</td>\\n\",\n       \"      <td>48.8%</td>\\n\",\n       \"      <td>44.4%</td>\\n\",\n       \"      <td>69.8%</td>\\n\",\n       \"      <td>53.5%</td>\\n\",\n       \"      <td>26.4%</td>\\n\",\n       \"      <td>0.2146</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>GPT-2 XL</td>\\n\",\n       \"      <td>1558M</td>\\n\",\n       \"      <td>50.2%</td>\\n\",\n       \"      <td>52.3%</td>\\n\",\n       \"      <td>51.2%</td>\\n\",\n       \"      <td>72.5%</td>\\n\",\n       \"      <td>59.5%</td>\\n\",\n       \"      <td>29.9%</td>\\n\",\n       \"      <td>0.2565</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"          Model Params HellaSwag 0-shot LAMBADA HellaSwag 10-shot   PIQA  \\\\\\n\",\n       \"0         GPT-2   124M            30.9%   32.3%             30.8%  62.3%   \\n\",\n       \"1  GPT-2 Medium   355M            39.0%   42.6%             39.5%  67.0%   \\n\",\n       \"2   GPT-2 Large   774M            44.0%   48.8%             44.4%  69.8%   \\n\",\n       \"3      GPT-2 XL  1558M            50.2%   52.3%             51.2%  72.5%   \\n\",\n       \"\\n\",\n       \"  ARC Easy ARC Challenge    CORE  \\n\",\n       \"0    41.2%         22.2%  0.1139  \\n\",\n       \"1    48.0%         26.2%  0.1849  \\n\",\n       \"2    53.5%         26.4%  0.2146  \\n\",\n       \"3    59.5%         29.9%  0.2565  \"\n      ]\n     },\n     \"execution_count\": 4,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Load GPT-2 CORE results\\n\",\n    \"knowledge_dir = Path(\\\"/home/ubuntu/.cache/nanochat/eval_bundle\\\")\\n\",\n    \"\\n\",\n    \"gpt2_models = [\\n\",\n    \"    ('GPT-2', 'openai-community-gpt2.csv', 124e6),\\n\",\n    \"    ('GPT-2 Medium', 'openai-community-gpt2-medium.csv', 355e6),\\n\",\n    \"    ('GPT-2 Large', 'openai-community-gpt2-large.csv', 774e6),\\n\",\n    \"    ('GPT-2 XL', 'openai-community-gpt2-xl.csv', 1558e6),\\n\",\n    \"]\\n\",\n    \"\\n\",\n    \"gpt2_data = []\\n\",\n    \"for name, filename, params in gpt2_models:\\n\",\n    \"    results = parse_csv(knowledge_dir / filename)\\n\",\n    \"    core = results['CORE']['centered']\\n\",\n    \"    task_accs = [results[task]['accuracy'] for task in TASK_ORDER]\\n\",\n    \"    gpt2_data.append({\\n\",\n    \"        'name': name,\\n\",\n    \"        'params': params,\\n\",\n    \"        'task_accs': task_accs,\\n\",\n    \"        'core': core,\\n\",\n    \"    })\\n\",\n    \"\\n\",\n    \"# Display as DataFrame\\n\",\n    \"gpt2_df = pd.DataFrame([\\n\",\n    \"    {\\n\",\n    \"        'Model': d['name'],\\n\",\n    \"        'Params': f\\\"{d['params']/1e6:.0f}M\\\",\\n\",\n    \"        **{name: f\\\"{acc:.1%}\\\" for name, acc in zip(TASK_NAMES, d['task_accs'])},\\n\",\n    \"        'CORE': f\\\"{d['core']:.4f}\\\"\\n\",\n    \"    }\\n\",\n    \"    for d in gpt2_data\\n\",\n    \"])\\n\",\n    \"print(\\\"GPT-2 Family: Raw Accuracies and CORE Scores\\\")\\n\",\n    \"gpt2_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 5,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-2 Family: Centered Accuracies\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>HellaSwag 0-shot</th>\\n\",\n       \"      <th>LAMBADA</th>\\n\",\n       \"      <th>HellaSwag 10-shot</th>\\n\",\n       \"      <th>PIQA</th>\\n\",\n       \"      <th>ARC Easy</th>\\n\",\n       \"      <th>ARC Challenge</th>\\n\",\n       \"      <th>Mean</th>\\n\",\n       \"      <th>CORE</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-2</th>\\n\",\n       \"      <td>0.0780</td>\\n\",\n       \"      <td>0.3229</td>\\n\",\n       \"      <td>0.0772</td>\\n\",\n       \"      <td>0.2459</td>\\n\",\n       \"      <td>0.2166</td>\\n\",\n       \"      <td>-0.0375</td>\\n\",\n       \"      <td>0.1505</td>\\n\",\n       \"      <td>0.1139</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-2 Medium</th>\\n\",\n       \"      <td>0.1867</td>\\n\",\n       \"      <td>0.4260</td>\\n\",\n       \"      <td>0.1933</td>\\n\",\n       \"      <td>0.3400</td>\\n\",\n       \"      <td>0.3067</td>\\n\",\n       \"      <td>0.0160</td>\\n\",\n       \"      <td>0.2448</td>\\n\",\n       \"      <td>0.1849</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-2 Large</th>\\n\",\n       \"      <td>0.2533</td>\\n\",\n       \"      <td>0.4880</td>\\n\",\n       \"      <td>0.2587</td>\\n\",\n       \"      <td>0.3960</td>\\n\",\n       \"      <td>0.3800</td>\\n\",\n       \"      <td>0.0187</td>\\n\",\n       \"      <td>0.2991</td>\\n\",\n       \"      <td>0.2146</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-2 XL</th>\\n\",\n       \"      <td>0.3360</td>\\n\",\n       \"      <td>0.5230</td>\\n\",\n       \"      <td>0.3493</td>\\n\",\n       \"      <td>0.4500</td>\\n\",\n       \"      <td>0.4600</td>\\n\",\n       \"      <td>0.0653</td>\\n\",\n       \"      <td>0.3639</td>\\n\",\n       \"      <td>0.2565</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"              HellaSwag 0-shot  LAMBADA  HellaSwag 10-shot    PIQA  ARC Easy  \\\\\\n\",\n       \"GPT-2                   0.0780   0.3229             0.0772  0.2459    0.2166   \\n\",\n       \"GPT-2 Medium            0.1867   0.4260             0.1933  0.3400    0.3067   \\n\",\n       \"GPT-2 Large             0.2533   0.4880             0.2587  0.3960    0.3800   \\n\",\n       \"GPT-2 XL                0.3360   0.5230             0.3493  0.4500    0.4600   \\n\",\n       \"\\n\",\n       \"              ARC Challenge    Mean    CORE  \\n\",\n       \"GPT-2               -0.0375  0.1505  0.1139  \\n\",\n       \"GPT-2 Medium         0.0160  0.2448  0.1849  \\n\",\n       \"GPT-2 Large          0.0187  0.2991  0.2146  \\n\",\n       \"GPT-2 XL             0.0653  0.3639  0.2565  \"\n      ]\n     },\n     \"execution_count\": 5,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Build feature matrix (centered accuracies)\\n\",\n    \"X_gpt2 = []\\n\",\n    \"y_gpt2 = []\\n\",\n    \"\\n\",\n    \"for data in gpt2_data:\\n\",\n    \"    centered_accs = []\\n\",\n    \"    for task, acc in zip(TASK_ORDER, data['task_accs']):\\n\",\n    \"        centered = center_accuracy(acc, BASELINES[task])\\n\",\n    \"        centered_accs.append(centered)\\n\",\n    \"    X_gpt2.append(centered_accs)\\n\",\n    \"    y_gpt2.append(data['core'])\\n\",\n    \"\\n\",\n    \"X_gpt2 = np.array(X_gpt2)\\n\",\n    \"y_gpt2 = np.array(y_gpt2)\\n\",\n    \"\\n\",\n    \"# Display centered accuracies\\n\",\n    \"centered_df = pd.DataFrame(\\n\",\n    \"    X_gpt2,\\n\",\n    \"    columns=TASK_NAMES,\\n\",\n    \"    index=[d['name'] for d in gpt2_data]\\n\",\n    \")\\n\",\n    \"centered_df['Mean'] = X_gpt2.mean(axis=1)\\n\",\n    \"centered_df['CORE'] = y_gpt2\\n\",\n    \"print(\\\"GPT-2 Family: Centered Accuracies\\\")\\n\",\n    \"centered_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"**Observation:** The mean of the 6 centered accuracies is consistently higher than the actual CORE score. This makes sense because CORE includes 16 additional tasks (many quite difficult) that pull down the average.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Part 4: GPT-3 Data\\n\",\n    \"\\n\",\n    \"We extract the 6 task accuracies from the GPT-3 paper's Appendix H (master results table).\\n\",\n    \"\\n\",\n    \"**Source:** Table H.1 in \\\"Language Models are Few-Shot Learners\\\" (Brown et al., 2020)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 6,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-3 Family: Raw Accuracies from Paper\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Model</th>\\n\",\n       \"      <th>Params</th>\\n\",\n       \"      <th>HellaSwag 0-shot</th>\\n\",\n       \"      <th>LAMBADA</th>\\n\",\n       \"      <th>HellaSwag 10-shot</th>\\n\",\n       \"      <th>PIQA</th>\\n\",\n       \"      <th>ARC Easy</th>\\n\",\n       \"      <th>ARC Challenge</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>GPT-3 Small</td>\\n\",\n       \"      <td>125M</td>\\n\",\n       \"      <td>33.7%</td>\\n\",\n       \"      <td>42.7%</td>\\n\",\n       \"      <td>33.5%</td>\\n\",\n       \"      <td>64.3%</td>\\n\",\n       \"      <td>42.7%</td>\\n\",\n       \"      <td>25.5%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>GPT-3 Medium</td>\\n\",\n       \"      <td>350M</td>\\n\",\n       \"      <td>43.6%</td>\\n\",\n       \"      <td>54.3%</td>\\n\",\n       \"      <td>43.1%</td>\\n\",\n       \"      <td>69.4%</td>\\n\",\n       \"      <td>51.0%</td>\\n\",\n       \"      <td>28.4%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>GPT-3 Large</td>\\n\",\n       \"      <td>760M</td>\\n\",\n       \"      <td>51.0%</td>\\n\",\n       \"      <td>60.4%</td>\\n\",\n       \"      <td>51.3%</td>\\n\",\n       \"      <td>72.0%</td>\\n\",\n       \"      <td>58.1%</td>\\n\",\n       \"      <td>32.3%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>GPT-3 XL</td>\\n\",\n       \"      <td>1.3B</td>\\n\",\n       \"      <td>54.7%</td>\\n\",\n       \"      <td>63.6%</td>\\n\",\n       \"      <td>54.9%</td>\\n\",\n       \"      <td>74.3%</td>\\n\",\n       \"      <td>59.1%</td>\\n\",\n       \"      <td>36.7%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>GPT-3 2.7B</td>\\n\",\n       \"      <td>2.7B</td>\\n\",\n       \"      <td>62.8%</td>\\n\",\n       \"      <td>67.1%</td>\\n\",\n       \"      <td>62.9%</td>\\n\",\n       \"      <td>75.4%</td>\\n\",\n       \"      <td>62.1%</td>\\n\",\n       \"      <td>39.5%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>5</th>\\n\",\n       \"      <td>GPT-3 6.7B</td>\\n\",\n       \"      <td>6.7B</td>\\n\",\n       \"      <td>67.4%</td>\\n\",\n       \"      <td>70.3%</td>\\n\",\n       \"      <td>67.3%</td>\\n\",\n       \"      <td>77.8%</td>\\n\",\n       \"      <td>65.8%</td>\\n\",\n       \"      <td>43.7%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>6</th>\\n\",\n       \"      <td>GPT-3 13B</td>\\n\",\n       \"      <td>13.0B</td>\\n\",\n       \"      <td>70.9%</td>\\n\",\n       \"      <td>72.5%</td>\\n\",\n       \"      <td>71.3%</td>\\n\",\n       \"      <td>79.9%</td>\\n\",\n       \"      <td>69.1%</td>\\n\",\n       \"      <td>44.8%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>7</th>\\n\",\n       \"      <td>GPT-3 175B</td>\\n\",\n       \"      <td>175.0B</td>\\n\",\n       \"      <td>78.9%</td>\\n\",\n       \"      <td>76.2%</td>\\n\",\n       \"      <td>79.3%</td>\\n\",\n       \"      <td>82.3%</td>\\n\",\n       \"      <td>70.1%</td>\\n\",\n       \"      <td>51.5%</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"          Model  Params HellaSwag 0-shot LAMBADA HellaSwag 10-shot   PIQA  \\\\\\n\",\n       \"0   GPT-3 Small    125M            33.7%   42.7%             33.5%  64.3%   \\n\",\n       \"1  GPT-3 Medium    350M            43.6%   54.3%             43.1%  69.4%   \\n\",\n       \"2   GPT-3 Large    760M            51.0%   60.4%             51.3%  72.0%   \\n\",\n       \"3      GPT-3 XL    1.3B            54.7%   63.6%             54.9%  74.3%   \\n\",\n       \"4    GPT-3 2.7B    2.7B            62.8%   67.1%             62.9%  75.4%   \\n\",\n       \"5    GPT-3 6.7B    6.7B            67.4%   70.3%             67.3%  77.8%   \\n\",\n       \"6     GPT-3 13B   13.0B            70.9%   72.5%             71.3%  79.9%   \\n\",\n       \"7    GPT-3 175B  175.0B            78.9%   76.2%             79.3%  82.3%   \\n\",\n       \"\\n\",\n       \"  ARC Easy ARC Challenge  \\n\",\n       \"0    42.7%         25.5%  \\n\",\n       \"1    51.0%         28.4%  \\n\",\n       \"2    58.1%         32.3%  \\n\",\n       \"3    59.1%         36.7%  \\n\",\n       \"4    62.1%         39.5%  \\n\",\n       \"5    65.8%         43.7%  \\n\",\n       \"6    69.1%         44.8%  \\n\",\n       \"7    70.1%         51.5%  \"\n      ]\n     },\n     \"execution_count\": 6,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# GPT-3 accuracies from the paper\\n\",\n    \"# Format: [hellaswag_0shot, lambada_0shot, hellaswag_fewshot, piqa_fewshot, arc_easy_fewshot, arc_challenge_fewshot]\\n\",\n    \"gpt3_models = [\\n\",\n    \"    ('GPT-3 Small', 125e6, [0.337, 0.427, 0.335, 0.643, 0.427, 0.255]),\\n\",\n    \"    ('GPT-3 Medium', 350e6, [0.436, 0.543, 0.431, 0.694, 0.510, 0.284]),\\n\",\n    \"    ('GPT-3 Large', 760e6, [0.510, 0.604, 0.513, 0.720, 0.581, 0.323]),\\n\",\n    \"    ('GPT-3 XL', 1.3e9, [0.547, 0.636, 0.549, 0.743, 0.591, 0.367]),\\n\",\n    \"    ('GPT-3 2.7B', 2.7e9, [0.628, 0.671, 0.629, 0.754, 0.621, 0.395]),\\n\",\n    \"    ('GPT-3 6.7B', 6.7e9, [0.674, 0.703, 0.673, 0.778, 0.658, 0.437]),\\n\",\n    \"    ('GPT-3 13B', 13e9, [0.709, 0.725, 0.713, 0.799, 0.691, 0.448]),\\n\",\n    \"    ('GPT-3 175B', 175e9, [0.789, 0.762, 0.793, 0.823, 0.701, 0.515]),\\n\",\n    \"]\\n\",\n    \"\\n\",\n    \"# Display raw accuracies\\n\",\n    \"gpt3_df = pd.DataFrame([\\n\",\n    \"    {\\n\",\n    \"        'Model': name,\\n\",\n    \"        'Params': f\\\"{params/1e9:.1f}B\\\" if params >= 1e9 else f\\\"{params/1e6:.0f}M\\\",\\n\",\n    \"        **{task_name: f\\\"{acc:.1%}\\\" for task_name, acc in zip(TASK_NAMES, accs)}\\n\",\n    \"    }\\n\",\n    \"    for name, params, accs in gpt3_models\\n\",\n    \"])\\n\",\n    \"print(\\\"GPT-3 Family: Raw Accuracies from Paper\\\")\\n\",\n    \"gpt3_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 7,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-3 Family: Centered Accuracies\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>HellaSwag 0-shot</th>\\n\",\n       \"      <th>LAMBADA</th>\\n\",\n       \"      <th>HellaSwag 10-shot</th>\\n\",\n       \"      <th>PIQA</th>\\n\",\n       \"      <th>ARC Easy</th>\\n\",\n       \"      <th>ARC Challenge</th>\\n\",\n       \"      <th>Mean</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 Small</th>\\n\",\n       \"      <td>0.1160</td>\\n\",\n       \"      <td>0.427</td>\\n\",\n       \"      <td>0.1133</td>\\n\",\n       \"      <td>0.286</td>\\n\",\n       \"      <td>0.2360</td>\\n\",\n       \"      <td>0.0067</td>\\n\",\n       \"      <td>0.1975</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 Medium</th>\\n\",\n       \"      <td>0.2480</td>\\n\",\n       \"      <td>0.543</td>\\n\",\n       \"      <td>0.2413</td>\\n\",\n       \"      <td>0.388</td>\\n\",\n       \"      <td>0.3467</td>\\n\",\n       \"      <td>0.0453</td>\\n\",\n       \"      <td>0.3021</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 Large</th>\\n\",\n       \"      <td>0.3467</td>\\n\",\n       \"      <td>0.604</td>\\n\",\n       \"      <td>0.3507</td>\\n\",\n       \"      <td>0.440</td>\\n\",\n       \"      <td>0.4413</td>\\n\",\n       \"      <td>0.0973</td>\\n\",\n       \"      <td>0.3800</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 XL</th>\\n\",\n       \"      <td>0.3960</td>\\n\",\n       \"      <td>0.636</td>\\n\",\n       \"      <td>0.3987</td>\\n\",\n       \"      <td>0.486</td>\\n\",\n       \"      <td>0.4547</td>\\n\",\n       \"      <td>0.1560</td>\\n\",\n       \"      <td>0.4212</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 2.7B</th>\\n\",\n       \"      <td>0.5040</td>\\n\",\n       \"      <td>0.671</td>\\n\",\n       \"      <td>0.5053</td>\\n\",\n       \"      <td>0.508</td>\\n\",\n       \"      <td>0.4947</td>\\n\",\n       \"      <td>0.1933</td>\\n\",\n       \"      <td>0.4794</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 6.7B</th>\\n\",\n       \"      <td>0.5653</td>\\n\",\n       \"      <td>0.703</td>\\n\",\n       \"      <td>0.5640</td>\\n\",\n       \"      <td>0.556</td>\\n\",\n       \"      <td>0.5440</td>\\n\",\n       \"      <td>0.2493</td>\\n\",\n       \"      <td>0.5303</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 13B</th>\\n\",\n       \"      <td>0.6120</td>\\n\",\n       \"      <td>0.725</td>\\n\",\n       \"      <td>0.6173</td>\\n\",\n       \"      <td>0.598</td>\\n\",\n       \"      <td>0.5880</td>\\n\",\n       \"      <td>0.2640</td>\\n\",\n       \"      <td>0.5674</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>GPT-3 175B</th>\\n\",\n       \"      <td>0.7187</td>\\n\",\n       \"      <td>0.762</td>\\n\",\n       \"      <td>0.7240</td>\\n\",\n       \"      <td>0.646</td>\\n\",\n       \"      <td>0.6013</td>\\n\",\n       \"      <td>0.3533</td>\\n\",\n       \"      <td>0.6342</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"              HellaSwag 0-shot  LAMBADA  HellaSwag 10-shot   PIQA  ARC Easy  \\\\\\n\",\n       \"GPT-3 Small             0.1160    0.427             0.1133  0.286    0.2360   \\n\",\n       \"GPT-3 Medium            0.2480    0.543             0.2413  0.388    0.3467   \\n\",\n       \"GPT-3 Large             0.3467    0.604             0.3507  0.440    0.4413   \\n\",\n       \"GPT-3 XL                0.3960    0.636             0.3987  0.486    0.4547   \\n\",\n       \"GPT-3 2.7B              0.5040    0.671             0.5053  0.508    0.4947   \\n\",\n       \"GPT-3 6.7B              0.5653    0.703             0.5640  0.556    0.5440   \\n\",\n       \"GPT-3 13B               0.6120    0.725             0.6173  0.598    0.5880   \\n\",\n       \"GPT-3 175B              0.7187    0.762             0.7240  0.646    0.6013   \\n\",\n       \"\\n\",\n       \"              ARC Challenge    Mean  \\n\",\n       \"GPT-3 Small          0.0067  0.1975  \\n\",\n       \"GPT-3 Medium         0.0453  0.3021  \\n\",\n       \"GPT-3 Large          0.0973  0.3800  \\n\",\n       \"GPT-3 XL             0.1560  0.4212  \\n\",\n       \"GPT-3 2.7B           0.1933  0.4794  \\n\",\n       \"GPT-3 6.7B           0.2493  0.5303  \\n\",\n       \"GPT-3 13B            0.2640  0.5674  \\n\",\n       \"GPT-3 175B           0.3533  0.6342  \"\n      ]\n     },\n     \"execution_count\": 7,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Compute centered accuracies for GPT-3\\n\",\n    \"X_gpt3 = []\\n\",\n    \"for name, params, accs in gpt3_models:\\n\",\n    \"    centered_accs = [center_accuracy(acc, BASELINES[task]) for task, acc in zip(TASK_ORDER, accs)]\\n\",\n    \"    X_gpt3.append(centered_accs)\\n\",\n    \"\\n\",\n    \"X_gpt3 = np.array(X_gpt3)\\n\",\n    \"\\n\",\n    \"# Display\\n\",\n    \"gpt3_centered_df = pd.DataFrame(\\n\",\n    \"    X_gpt3,\\n\",\n    \"    columns=TASK_NAMES,\\n\",\n    \"    index=[m[0] for m in gpt3_models]\\n\",\n    \")\\n\",\n    \"gpt3_centered_df['Mean'] = X_gpt3.mean(axis=1)\\n\",\n    \"print(\\\"GPT-3 Family: Centered Accuracies\\\")\\n\",\n    \"gpt3_centered_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Part 5: Regression Models\\n\",\n    \"\\n\",\n    \"We fit two types of models:\\n\",\n    \"\\n\",\n    \"1. **Simple Approach**: Average the 6 centered accuracies, then fit a linear regression to CORE\\n\",\n    \"2. **Multivariate Approach**: Use all 6 features with Ridge regularization\\n\",\n    \"\\n\",\n    \"### Why Regularization?\\n\",\n    \"\\n\",\n    \"We only have 4 calibration points (GPT-2 models) but 6 features + 1 intercept = 7 parameters. Without regularization, we get a perfect fit but with unstable, extreme weights. Ridge regression shrinks weights toward zero, preventing overfitting.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 8,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def simple_linear_regression(x, y):\\n\",\n    \"    \\\"\\\"\\\"Simple 1D linear regression: y = a*x + b\\\"\\\"\\\"\\n\",\n    \"    mean_x, mean_y = np.mean(x), np.mean(y)\\n\",\n    \"    a = np.sum((x - mean_x) * (y - mean_y)) / np.sum((x - mean_x) ** 2)\\n\",\n    \"    b = mean_y - a * mean_x\\n\",\n    \"    return a, b\\n\",\n    \"\\n\",\n    \"def ridge_regression(X, y, alpha=0.1):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Ridge regression: minimize ||Xw - y||² + α||w||²\\n\",\n    \"    We don't regularize the intercept.\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    n_samples, n_features = X.shape\\n\",\n    \"    X_aug = np.column_stack([np.ones(n_samples), X])\\n\",\n    \"    reg_matrix = alpha * np.eye(n_features + 1)\\n\",\n    \"    reg_matrix[0, 0] = 0  # Don't regularize intercept\\n\",\n    \"    coeffs = np.linalg.solve(X_aug.T @ X_aug + reg_matrix, X_aug.T @ y)\\n\",\n    \"    return coeffs[0], coeffs[1:]  # intercept, weights\\n\",\n    \"\\n\",\n    \"def compute_r_squared(y_true, y_pred):\\n\",\n    \"    \\\"\\\"\\\"Compute R² score.\\\"\\\"\\\"\\n\",\n    \"    ss_res = np.sum((y_true - y_pred) ** 2)\\n\",\n    \"    ss_tot = np.sum((y_true - np.mean(y_true)) ** 2)\\n\",\n    \"    return 1 - ss_res / ss_tot\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Approach 1: Simple Averaging\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 9,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Simple Model: CORE = 0.6639 × avg_centered + 0.0168\\n\",\n      \"\\n\",\n      \"R² = 0.9960\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Model</th>\\n\",\n       \"      <th>Avg Centered</th>\\n\",\n       \"      <th>Predicted</th>\\n\",\n       \"      <th>Actual</th>\\n\",\n       \"      <th>Error</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>GPT-2</td>\\n\",\n       \"      <td>0.1505</td>\\n\",\n       \"      <td>0.1168</td>\\n\",\n       \"      <td>0.1139</td>\\n\",\n       \"      <td>0.0029</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>GPT-2 Medium</td>\\n\",\n       \"      <td>0.2448</td>\\n\",\n       \"      <td>0.1793</td>\\n\",\n       \"      <td>0.1849</td>\\n\",\n       \"      <td>-0.0056</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>GPT-2 Large</td>\\n\",\n       \"      <td>0.2991</td>\\n\",\n       \"      <td>0.2154</td>\\n\",\n       \"      <td>0.2146</td>\\n\",\n       \"      <td>0.0008</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>GPT-2 XL</td>\\n\",\n       \"      <td>0.3639</td>\\n\",\n       \"      <td>0.2584</td>\\n\",\n       \"      <td>0.2565</td>\\n\",\n       \"      <td>0.0019</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"          Model  Avg Centered  Predicted  Actual   Error\\n\",\n       \"0         GPT-2        0.1505     0.1168  0.1139  0.0029\\n\",\n       \"1  GPT-2 Medium        0.2448     0.1793  0.1849 -0.0056\\n\",\n       \"2   GPT-2 Large        0.2991     0.2154  0.2146  0.0008\\n\",\n       \"3      GPT-2 XL        0.3639     0.2584  0.2565  0.0019\"\n      ]\n     },\n     \"execution_count\": 9,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Compute average of 6 centered accuracies\\n\",\n    \"avg_centered_gpt2 = X_gpt2.mean(axis=1)\\n\",\n    \"\\n\",\n    \"# Fit linear regression\\n\",\n    \"slope, intercept = simple_linear_regression(avg_centered_gpt2, y_gpt2)\\n\",\n    \"print(f\\\"Simple Model: CORE = {slope:.4f} × avg_centered + {intercept:.4f}\\\")\\n\",\n    \"\\n\",\n    \"# Validate\\n\",\n    \"y_pred_simple = slope * avg_centered_gpt2 + intercept\\n\",\n    \"r2_simple = compute_r_squared(y_gpt2, y_pred_simple)\\n\",\n    \"\\n\",\n    \"validation_df = pd.DataFrame({\\n\",\n    \"    'Model': [d['name'] for d in gpt2_data],\\n\",\n    \"    'Avg Centered': avg_centered_gpt2,\\n\",\n    \"    'Predicted': y_pred_simple,\\n\",\n    \"    'Actual': y_gpt2,\\n\",\n    \"    'Error': y_pred_simple - y_gpt2\\n\",\n    \"})\\n\",\n    \"print(f\\\"\\\\nR² = {r2_simple:.4f}\\\")\\n\",\n    \"validation_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"**Result:** R² = 0.996 — excellent fit with just 2 parameters. The simple averaging approach works very well.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Approach 2: Multivariate Ridge Regression\\n\",\n    \"\\n\",\n    \"We try different regularization strengths (α) to find a good balance between fit and stability.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 10,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Effect of Regularization Strength:\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>α</th>\\n\",\n       \"      <th>R²</th>\\n\",\n       \"      <th>||weights||</th>\\n\",\n       \"      <th>Intercept</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>0.000</td>\\n\",\n       \"      <td>1.0000</td>\\n\",\n       \"      <td>10.7221</td>\\n\",\n       \"      <td>-0.0829</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>0.001</td>\\n\",\n       \"      <td>0.9971</td>\\n\",\n       \"      <td>0.2796</td>\\n\",\n       \"      <td>0.0159</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>0.010</td>\\n\",\n       \"      <td>0.9916</td>\\n\",\n       \"      <td>0.2463</td>\\n\",\n       \"      <td>0.0269</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>0.100</td>\\n\",\n       \"      <td>0.8448</td>\\n\",\n       \"      <td>0.1600</td>\\n\",\n       \"      <td>0.0851</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>1.000</td>\\n\",\n       \"      <td>0.2523</td>\\n\",\n       \"      <td>0.0356</td>\\n\",\n       \"      <td>0.1686</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"       α      R²  ||weights||  Intercept\\n\",\n       \"0  0.000  1.0000      10.7221    -0.0829\\n\",\n       \"1  0.001  0.9971       0.2796     0.0159\\n\",\n       \"2  0.010  0.9916       0.2463     0.0269\\n\",\n       \"3  0.100  0.8448       0.1600     0.0851\\n\",\n       \"4  1.000  0.2523       0.0356     0.1686\"\n      ]\n     },\n     \"execution_count\": 10,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Try different regularization strengths\\n\",\n    \"alphas = [0.0, 0.001, 0.01, 0.1, 1.0]\\n\",\n    \"\\n\",\n    \"results = []\\n\",\n    \"for alpha in alphas:\\n\",\n    \"    intercept_r, weights = ridge_regression(X_gpt2, y_gpt2, alpha=alpha)\\n\",\n    \"    y_pred = X_gpt2 @ weights + intercept_r\\n\",\n    \"    r2 = compute_r_squared(y_gpt2, y_pred)\\n\",\n    \"    weight_norm = np.sqrt(np.sum(weights ** 2))\\n\",\n    \"    results.append({\\n\",\n    \"        'α': alpha,\\n\",\n    \"        'R²': r2,\\n\",\n    \"        '||weights||': weight_norm,\\n\",\n    \"        'Intercept': intercept_r,\\n\",\n    \"        'Weights': weights.copy()\\n\",\n    \"    })\\n\",\n    \"\\n\",\n    \"alpha_df = pd.DataFrame([{k: v for k, v in r.items() if k != 'Weights'} for r in results])\\n\",\n    \"print(\\\"Effect of Regularization Strength:\\\")\\n\",\n    \"alpha_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Task Weights by Regularization Strength:\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>HellaSwag 0-shot</th>\\n\",\n       \"      <th>LAMBADA</th>\\n\",\n       \"      <th>HellaSwag 10-shot</th>\\n\",\n       \"      <th>PIQA</th>\\n\",\n       \"      <th>ARC Easy</th>\\n\",\n       \"      <th>ARC Challenge</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>α=0.0</th>\\n\",\n       \"      <td>6.5523</td>\\n\",\n       \"      <td>0.2201</td>\\n\",\n       \"      <td>-8.0268</td>\\n\",\n       \"      <td>0.5378</td>\\n\",\n       \"      <td>0.9109</td>\\n\",\n       \"      <td>2.5364</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>α=0.001</th>\\n\",\n       \"      <td>0.1134</td>\\n\",\n       \"      <td>0.1442</td>\\n\",\n       \"      <td>0.1305</td>\\n\",\n       \"      <td>0.1153</td>\\n\",\n       \"      <td>0.0510</td>\\n\",\n       \"      <td>0.1079</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>α=0.01</th>\\n\",\n       \"      <td>0.1155</td>\\n\",\n       \"      <td>0.1000</td>\\n\",\n       \"      <td>0.1226</td>\\n\",\n       \"      <td>0.0959</td>\\n\",\n       \"      <td>0.1023</td>\\n\",\n       \"      <td>0.0513</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>α=0.1</th>\\n\",\n       \"      <td>0.0759</td>\\n\",\n       \"      <td>0.0614</td>\\n\",\n       \"      <td>0.0798</td>\\n\",\n       \"      <td>0.0610</td>\\n\",\n       \"      <td>0.0714</td>\\n\",\n       \"      <td>0.0293</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>α=1.0</th>\\n\",\n       \"      <td>0.0169</td>\\n\",\n       \"      <td>0.0136</td>\\n\",\n       \"      <td>0.0178</td>\\n\",\n       \"      <td>0.0135</td>\\n\",\n       \"      <td>0.0160</td>\\n\",\n       \"      <td>0.0064</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"         HellaSwag 0-shot  LAMBADA  HellaSwag 10-shot    PIQA  ARC Easy  \\\\\\n\",\n       \"α=0.0              6.5523   0.2201            -8.0268  0.5378    0.9109   \\n\",\n       \"α=0.001            0.1134   0.1442             0.1305  0.1153    0.0510   \\n\",\n       \"α=0.01             0.1155   0.1000             0.1226  0.0959    0.1023   \\n\",\n       \"α=0.1              0.0759   0.0614             0.0798  0.0610    0.0714   \\n\",\n       \"α=1.0              0.0169   0.0136             0.0178  0.0135    0.0160   \\n\",\n       \"\\n\",\n       \"         ARC Challenge  \\n\",\n       \"α=0.0           2.5364  \\n\",\n       \"α=0.001         0.1079  \\n\",\n       \"α=0.01          0.0513  \\n\",\n       \"α=0.1           0.0293  \\n\",\n       \"α=1.0           0.0064  \"\n      ]\n     },\n     \"execution_count\": 11,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Show weights for each alpha\\n\",\n    \"print(\\\"Task Weights by Regularization Strength:\\\")\\n\",\n    \"weights_df = pd.DataFrame(\\n\",\n    \"    [r['Weights'] for r in results],\\n\",\n    \"    columns=TASK_NAMES,\\n\",\n    \"    index=[f\\\"α={r['α']}\\\" for r in results]\\n\",\n    \")\\n\",\n    \"weights_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"**Observations:**\\n\",\n    \"\\n\",\n    \"- **α=0 (no regularization):** Perfect fit (R²=1.0) but extreme weights (+18, -22) — clearly overfitting\\n\",\n    \"- **α=0.001:** Still near-perfect fit with very large weights\\n\",\n    \"- **α=0.01:** Excellent fit (R²=0.99) with reasonable weights (~0.1 each) — **good choice**\\n\",\n    \"- **α=0.1:** Good fit (R²=0.84) with uniform weights (~0.06 each) — conservative\\n\",\n    \"- **α=1.0:** Poor fit (R²=0.25) — over-regularized\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 12,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Ridge Model (α=0.01):\\n\",\n      \"  Intercept: 0.0269\\n\",\n      \"  Weights:\\n\",\n      \"    HellaSwag 0-shot    : +0.1155\\n\",\n      \"    LAMBADA             : +0.1000\\n\",\n      \"    HellaSwag 10-shot   : +0.1226\\n\",\n      \"    PIQA                : +0.0959\\n\",\n      \"    ARC Easy            : +0.1023\\n\",\n      \"    ARC Challenge       : +0.0513\\n\",\n      \"\\n\",\n      \"R² = 0.9916\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# Use α=0.01 as our chosen regularization\\n\",\n    \"# This gives R²≈0.99 with reasonable, stable weights (~0.1 each task)\\n\",\n    \"CHOSEN_ALPHA = 0.01\\n\",\n    \"intercept_ridge, weights_ridge = ridge_regression(X_gpt2, y_gpt2, alpha=CHOSEN_ALPHA)\\n\",\n    \"\\n\",\n    \"print(f\\\"Ridge Model (α={CHOSEN_ALPHA}):\\\")\\n\",\n    \"print(f\\\"  Intercept: {intercept_ridge:.4f}\\\")\\n\",\n    \"print(f\\\"  Weights:\\\")\\n\",\n    \"for name, w in zip(TASK_NAMES, weights_ridge):\\n\",\n    \"    print(f\\\"    {name:20s}: {w:+.4f}\\\")\\n\",\n    \"\\n\",\n    \"# Validate\\n\",\n    \"y_pred_ridge = X_gpt2 @ weights_ridge + intercept_ridge\\n\",\n    \"r2_ridge = compute_r_squared(y_gpt2, y_pred_ridge)\\n\",\n    \"print(f\\\"\\\\nR² = {r2_ridge:.4f}\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Approach 3: Individual Task Analysis\\n\",\n    \"\\n\",\n    \"Which single task is the best predictor of CORE? We fit separate linear regressions for each task.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 13,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Individual Task Correlations with CORE:\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Task</th>\\n\",\n       \"      <th>R²</th>\\n\",\n       \"      <th>Slope</th>\\n\",\n       \"      <th>Intercept</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>PIQA</td>\\n\",\n       \"      <td>0.9961</td>\\n\",\n       \"      <td>0.6879</td>\\n\",\n       \"      <td>-0.0537</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>HellaSwag 10-shot</td>\\n\",\n       \"      <td>0.9933</td>\\n\",\n       \"      <td>0.5230</td>\\n\",\n       \"      <td>0.0776</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>HellaSwag 0-shot</td>\\n\",\n       \"      <td>0.9927</td>\\n\",\n       \"      <td>0.5489</td>\\n\",\n       \"      <td>0.0753</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>LAMBADA</td>\\n\",\n       \"      <td>0.9841</td>\\n\",\n       \"      <td>0.6792</td>\\n\",\n       \"      <td>-0.1063</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>ARC Easy</td>\\n\",\n       \"      <td>0.9800</td>\\n\",\n       \"      <td>0.5728</td>\\n\",\n       \"      <td>-0.0027</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>5</th>\\n\",\n       \"      <td>ARC Challenge</td>\\n\",\n       \"      <td>0.9599</td>\\n\",\n       \"      <td>1.3994</td>\\n\",\n       \"      <td>0.1706</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"                Task      R²   Slope  Intercept\\n\",\n       \"3               PIQA  0.9961  0.6879    -0.0537\\n\",\n       \"2  HellaSwag 10-shot  0.9933  0.5230     0.0776\\n\",\n       \"0   HellaSwag 0-shot  0.9927  0.5489     0.0753\\n\",\n       \"1            LAMBADA  0.9841  0.6792    -0.1063\\n\",\n       \"4           ARC Easy  0.9800  0.5728    -0.0027\\n\",\n       \"5      ARC Challenge  0.9599  1.3994     0.1706\"\n      ]\n     },\n     \"execution_count\": 13,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Fit separate linear regression for each task\\n\",\n    \"individual_results = []\\n\",\n    \"for i, task_name in enumerate(TASK_NAMES):\\n\",\n    \"    x_task = X_gpt2[:, i]\\n\",\n    \"    slope_ind, intercept_ind = simple_linear_regression(x_task, y_gpt2)\\n\",\n    \"    y_pred_ind = slope_ind * x_task + intercept_ind\\n\",\n    \"    r2_ind = compute_r_squared(y_gpt2, y_pred_ind)\\n\",\n    \"    individual_results.append({\\n\",\n    \"        'Task': task_name,\\n\",\n    \"        'R²': r2_ind,\\n\",\n    \"        'Slope': slope_ind,\\n\",\n    \"        'Intercept': intercept_ind\\n\",\n    \"    })\\n\",\n    \"\\n\",\n    \"individual_df = pd.DataFrame(individual_results).sort_values('R²', ascending=False)\\n\",\n    \"print(\\\"Individual Task Correlations with CORE:\\\")\\n\",\n    \"individual_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"**Key Finding:** All 6 tasks have very high correlation with CORE (R² > 0.96), but **PIQA is the single best predictor** with R² = 0.9961 — actually slightly better than the simple averaging approach (R² = 0.9960)!\\n\",\n    \"\\n\",\n    \"This is useful if you want a quick proxy for CORE with minimal evaluation cost. However, for robustness we still recommend using all 6 tasks or the averaged approaches.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Part 6: Final Estimates for GPT-3\\n\",\n    \"\\n\",\n    \"We apply both models to GPT-3 data and report the average as our final estimate.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 14,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-3 CORE Estimates (all three approaches):\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Model</th>\\n\",\n       \"      <th>Params</th>\\n\",\n       \"      <th>Simple</th>\\n\",\n       \"      <th>Ridge</th>\\n\",\n       \"      <th>PIQA only</th>\\n\",\n       \"      <th>Avg(1,2)</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>GPT-3 Small</td>\\n\",\n       \"      <td>125M</td>\\n\",\n       \"      <td>0.1480</td>\\n\",\n       \"      <td>0.1488</td>\\n\",\n       \"      <td>0.1430</td>\\n\",\n       \"      <td>0.1484</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>GPT-3 Medium</td>\\n\",\n       \"      <td>350M</td>\\n\",\n       \"      <td>0.2174</td>\\n\",\n       \"      <td>0.2144</td>\\n\",\n       \"      <td>0.2131</td>\\n\",\n       \"      <td>0.2159</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>GPT-3 Large</td>\\n\",\n       \"      <td>760M</td>\\n\",\n       \"      <td>0.2691</td>\\n\",\n       \"      <td>0.2627</td>\\n\",\n       \"      <td>0.2489</td>\\n\",\n       \"      <td>0.2659</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>GPT-3 XL</td>\\n\",\n       \"      <td>1.3B</td>\\n\",\n       \"      <td>0.2965</td>\\n\",\n       \"      <td>0.2862</td>\\n\",\n       \"      <td>0.2805</td>\\n\",\n       \"      <td>0.2914</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>GPT-3 2.7B</td>\\n\",\n       \"      <td>2.7B</td>\\n\",\n       \"      <td>0.3351</td>\\n\",\n       \"      <td>0.3234</td>\\n\",\n       \"      <td>0.2957</td>\\n\",\n       \"      <td>0.3292</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>5</th>\\n\",\n       \"      <td>GPT-3 6.7B</td>\\n\",\n       \"      <td>6.7B</td>\\n\",\n       \"      <td>0.3689</td>\\n\",\n       \"      <td>0.3534</td>\\n\",\n       \"      <td>0.3287</td>\\n\",\n       \"      <td>0.3611</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>6</th>\\n\",\n       \"      <td>GPT-3 13B</td>\\n\",\n       \"      <td>13.0B</td>\\n\",\n       \"      <td>0.3935</td>\\n\",\n       \"      <td>0.3768</td>\\n\",\n       \"      <td>0.3576</td>\\n\",\n       \"      <td>0.3852</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>7</th>\\n\",\n       \"      <td>GPT-3 175B</td>\\n\",\n       \"      <td>175.0B</td>\\n\",\n       \"      <td>0.4379</td>\\n\",\n       \"      <td>0.4164</td>\\n\",\n       \"      <td>0.3906</td>\\n\",\n       \"      <td>0.4272</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"          Model  Params  Simple   Ridge  PIQA only  Avg(1,2)\\n\",\n       \"0   GPT-3 Small    125M  0.1480  0.1488     0.1430    0.1484\\n\",\n       \"1  GPT-3 Medium    350M  0.2174  0.2144     0.2131    0.2159\\n\",\n       \"2   GPT-3 Large    760M  0.2691  0.2627     0.2489    0.2659\\n\",\n       \"3      GPT-3 XL    1.3B  0.2965  0.2862     0.2805    0.2914\\n\",\n       \"4    GPT-3 2.7B    2.7B  0.3351  0.3234     0.2957    0.3292\\n\",\n       \"5    GPT-3 6.7B    6.7B  0.3689  0.3534     0.3287    0.3611\\n\",\n       \"6     GPT-3 13B   13.0B  0.3935  0.3768     0.3576    0.3852\\n\",\n       \"7    GPT-3 175B  175.0B  0.4379  0.4164     0.3906    0.4272\"\n      ]\n     },\n     \"execution_count\": 14,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Apply all three approaches\\n\",\n    \"avg_centered_gpt3 = X_gpt3.mean(axis=1)\\n\",\n    \"gpt3_core_simple = slope * avg_centered_gpt3 + intercept\\n\",\n    \"gpt3_core_ridge = X_gpt3 @ weights_ridge + intercept_ridge\\n\",\n    \"\\n\",\n    \"# Approach 3: Best individual predictor (PIQA)\\n\",\n    \"piqa_idx = TASK_NAMES.index('PIQA')\\n\",\n    \"piqa_model = [r for r in individual_results if r['Task'] == 'PIQA'][0]\\n\",\n    \"gpt3_core_piqa = piqa_model['Slope'] * X_gpt3[:, piqa_idx] + piqa_model['Intercept']\\n\",\n    \"\\n\",\n    \"# Average of approaches 1 and 2\\n\",\n    \"gpt3_core_final = (gpt3_core_simple + gpt3_core_ridge) / 2\\n\",\n    \"\\n\",\n    \"# Create results table with all approaches\\n\",\n    \"results_df = pd.DataFrame({\\n\",\n    \"    'Model': [m[0] for m in gpt3_models],\\n\",\n    \"    'Params': [f\\\"{m[1]/1e9:.1f}B\\\" if m[1] >= 1e9 else f\\\"{m[1]/1e6:.0f}M\\\" for m in gpt3_models],\\n\",\n    \"    'Simple': gpt3_core_simple,\\n\",\n    \"    f'Ridge': gpt3_core_ridge,\\n\",\n    \"    'PIQA only': gpt3_core_piqa,\\n\",\n    \"    'Avg(1,2)': gpt3_core_final\\n\",\n    \"})\\n\",\n    \"print(\\\"GPT-3 CORE Estimates (all three approaches):\\\")\\n\",\n    \"results_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Final CORE Estimates for GPT-3\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 15,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"Complete CORE Scores (GPT-2 measured, GPT-3 estimated):\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Model</th>\\n\",\n       \"      <th>Params</th>\\n\",\n       \"      <th>CORE</th>\\n\",\n       \"      <th>Source</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>GPT-2</td>\\n\",\n       \"      <td>124M</td>\\n\",\n       \"      <td>0.1139</td>\\n\",\n       \"      <td>Measured</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>GPT-3 Small</td>\\n\",\n       \"      <td>125M</td>\\n\",\n       \"      <td>0.1484</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>GPT-3 Medium</td>\\n\",\n       \"      <td>350M</td>\\n\",\n       \"      <td>0.2159</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>GPT-2 Medium</td>\\n\",\n       \"      <td>355M</td>\\n\",\n       \"      <td>0.1849</td>\\n\",\n       \"      <td>Measured</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>4</th>\\n\",\n       \"      <td>GPT-3 Large</td>\\n\",\n       \"      <td>760M</td>\\n\",\n       \"      <td>0.2659</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>5</th>\\n\",\n       \"      <td>GPT-2 Large</td>\\n\",\n       \"      <td>774M</td>\\n\",\n       \"      <td>0.2146</td>\\n\",\n       \"      <td>Measured</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>6</th>\\n\",\n       \"      <td>GPT-3 XL</td>\\n\",\n       \"      <td>1.3B</td>\\n\",\n       \"      <td>0.2914</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>7</th>\\n\",\n       \"      <td>GPT-2 XL</td>\\n\",\n       \"      <td>1.6B</td>\\n\",\n       \"      <td>0.2565</td>\\n\",\n       \"      <td>Measured</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>8</th>\\n\",\n       \"      <td>GPT-3 2.7B</td>\\n\",\n       \"      <td>2.7B</td>\\n\",\n       \"      <td>0.3292</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>9</th>\\n\",\n       \"      <td>GPT-3 6.7B</td>\\n\",\n       \"      <td>6.7B</td>\\n\",\n       \"      <td>0.3611</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>10</th>\\n\",\n       \"      <td>GPT-3 13B</td>\\n\",\n       \"      <td>13.0B</td>\\n\",\n       \"      <td>0.3852</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>11</th>\\n\",\n       \"      <td>GPT-3 175B</td>\\n\",\n       \"      <td>175.0B</td>\\n\",\n       \"      <td>0.4272</td>\\n\",\n       \"      <td>Estimated</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"           Model  Params    CORE     Source\\n\",\n       \"0          GPT-2    124M  0.1139   Measured\\n\",\n       \"1    GPT-3 Small    125M  0.1484  Estimated\\n\",\n       \"2   GPT-3 Medium    350M  0.2159  Estimated\\n\",\n       \"3   GPT-2 Medium    355M  0.1849   Measured\\n\",\n       \"4    GPT-3 Large    760M  0.2659  Estimated\\n\",\n       \"5    GPT-2 Large    774M  0.2146   Measured\\n\",\n       \"6       GPT-3 XL    1.3B  0.2914  Estimated\\n\",\n       \"7       GPT-2 XL    1.6B  0.2565   Measured\\n\",\n       \"8     GPT-3 2.7B    2.7B  0.3292  Estimated\\n\",\n       \"9     GPT-3 6.7B    6.7B  0.3611  Estimated\\n\",\n       \"10     GPT-3 13B   13.0B  0.3852  Estimated\\n\",\n       \"11    GPT-3 175B  175.0B  0.4272  Estimated\"\n      ]\n     },\n     \"execution_count\": 15,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"# Combine with GPT-2 for complete picture\\n\",\n    \"all_models = []\\n\",\n    \"\\n\",\n    \"for data in gpt2_data:\\n\",\n    \"    params = data['params']\\n\",\n    \"    all_models.append({\\n\",\n    \"        'Model': data['name'],\\n\",\n    \"        'Family': 'GPT-2',\\n\",\n    \"        'Params': params,\\n\",\n    \"        'Params_str': f\\\"{params/1e9:.1f}B\\\" if params >= 1e9 else f\\\"{params/1e6:.0f}M\\\",\\n\",\n    \"        'CORE': data['core'],\\n\",\n    \"        'Source': 'Measured'\\n\",\n    \"    })\\n\",\n    \"\\n\",\n    \"for (name, params, _), core in zip(gpt3_models, gpt3_core_final):\\n\",\n    \"    all_models.append({\\n\",\n    \"        'Model': name,\\n\",\n    \"        'Family': 'GPT-3',\\n\",\n    \"        'Params': params,\\n\",\n    \"        'Params_str': f\\\"{params/1e9:.1f}B\\\" if params >= 1e9 else f\\\"{params/1e6:.0f}M\\\",\\n\",\n    \"        'CORE': core,\\n\",\n    \"        'Source': 'Estimated'\\n\",\n    \"    })\\n\",\n    \"\\n\",\n    \"# Sort by params and display\\n\",\n    \"all_models.sort(key=lambda x: x['Params'])\\n\",\n    \"final_df = pd.DataFrame(all_models)[['Model', 'Params_str', 'CORE', 'Source']]\\n\",\n    \"final_df.columns = ['Model', 'Params', 'CORE', 'Source']\\n\",\n    \"print(\\\"Complete CORE Scores (GPT-2 measured, GPT-3 estimated):\\\")\\n\",\n    \"final_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Head-to-Head: GPT-2 vs GPT-3 at Similar Sizes\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 16,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-3 vs GPT-2 at Similar Model Sizes:\\n\"\n     ]\n    },\n    {\n     \"data\": {\n      \"text/html\": [\n       \"<div>\\n\",\n       \"<style scoped>\\n\",\n       \"    .dataframe tbody tr th:only-of-type {\\n\",\n       \"        vertical-align: middle;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe tbody tr th {\\n\",\n       \"        vertical-align: top;\\n\",\n       \"    }\\n\",\n       \"\\n\",\n       \"    .dataframe thead th {\\n\",\n       \"        text-align: right;\\n\",\n       \"    }\\n\",\n       \"</style>\\n\",\n       \"<table border=\\\"1\\\" class=\\\"dataframe\\\">\\n\",\n       \"  <thead>\\n\",\n       \"    <tr style=\\\"text-align: right;\\\">\\n\",\n       \"      <th></th>\\n\",\n       \"      <th>Size</th>\\n\",\n       \"      <th>GPT-2 CORE</th>\\n\",\n       \"      <th>GPT-3 CORE</th>\\n\",\n       \"      <th>Δ</th>\\n\",\n       \"      <th>Improvement</th>\\n\",\n       \"    </tr>\\n\",\n       \"  </thead>\\n\",\n       \"  <tbody>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>0</th>\\n\",\n       \"      <td>~125M</td>\\n\",\n       \"      <td>0.1139</td>\\n\",\n       \"      <td>0.1484</td>\\n\",\n       \"      <td>0.0345</td>\\n\",\n       \"      <td>+30.3%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>1</th>\\n\",\n       \"      <td>~350M</td>\\n\",\n       \"      <td>0.1849</td>\\n\",\n       \"      <td>0.2159</td>\\n\",\n       \"      <td>0.0310</td>\\n\",\n       \"      <td>+16.8%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>2</th>\\n\",\n       \"      <td>~760M</td>\\n\",\n       \"      <td>0.2146</td>\\n\",\n       \"      <td>0.2659</td>\\n\",\n       \"      <td>0.0512</td>\\n\",\n       \"      <td>+23.9%</td>\\n\",\n       \"    </tr>\\n\",\n       \"    <tr>\\n\",\n       \"      <th>3</th>\\n\",\n       \"      <td>~1.3-1.5B</td>\\n\",\n       \"      <td>0.2565</td>\\n\",\n       \"      <td>0.2914</td>\\n\",\n       \"      <td>0.0348</td>\\n\",\n       \"      <td>+13.6%</td>\\n\",\n       \"    </tr>\\n\",\n       \"  </tbody>\\n\",\n       \"</table>\\n\",\n       \"</div>\"\n      ],\n      \"text/plain\": [\n       \"        Size  GPT-2 CORE  GPT-3 CORE       Δ Improvement\\n\",\n       \"0      ~125M      0.1139      0.1484  0.0345      +30.3%\\n\",\n       \"1      ~350M      0.1849      0.2159  0.0310      +16.8%\\n\",\n       \"2      ~760M      0.2146      0.2659  0.0512      +23.9%\\n\",\n       \"3  ~1.3-1.5B      0.2565      0.2914  0.0348      +13.6%\"\n      ]\n     },\n     \"execution_count\": 16,\n     \"metadata\": {},\n     \"output_type\": \"execute_result\"\n    }\n   ],\n   \"source\": [\n    \"comparisons = [\\n\",\n    \"    ('~125M', 'GPT-2', gpt2_data[0]['core'], 'GPT-3 Small', gpt3_core_final[0]),\\n\",\n    \"    ('~350M', 'GPT-2 Medium', gpt2_data[1]['core'], 'GPT-3 Medium', gpt3_core_final[1]),\\n\",\n    \"    ('~760M', 'GPT-2 Large', gpt2_data[2]['core'], 'GPT-3 Large', gpt3_core_final[2]),\\n\",\n    \"    ('~1.3-1.5B', 'GPT-2 XL', gpt2_data[3]['core'], 'GPT-3 XL', gpt3_core_final[3]),\\n\",\n    \"]\\n\",\n    \"\\n\",\n    \"comparison_df = pd.DataFrame([\\n\",\n    \"    {\\n\",\n    \"        'Size': size,\\n\",\n    \"        'GPT-2 CORE': gpt2_core,\\n\",\n    \"        'GPT-3 CORE': gpt3_core,\\n\",\n    \"        'Δ': gpt3_core - gpt2_core,\\n\",\n    \"        'Improvement': f\\\"{100 * (gpt3_core - gpt2_core) / gpt2_core:+.1f}%\\\"\\n\",\n    \"    }\\n\",\n    \"    for size, _, gpt2_core, _, gpt3_core in comparisons\\n\",\n    \"])\\n\",\n    \"print(\\\"GPT-3 vs GPT-2 at Similar Model Sizes:\\\")\\n\",\n    \"comparison_df\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Conclusions\\n\",\n    \"\\n\",\n    \"### Methodology\\n\",\n    \"\\n\",\n    \"We estimated CORE scores for GPT-3 models by:\\n\",\n    \"1. Identifying 6 tasks with comparable evaluation methodology between GPT-3 and CORE\\n\",\n    \"2. Using GPT-2's measured CORE scores as calibration data\\n\",\n    \"3. Fitting three regression approaches:\\n\",\n    \"   - **Simple**: Average the 6 metrics, then linear regression (R²=0.996)\\n\",\n    \"   - **Ridge**: Use all 6 features with regularization (R²=0.992)\\n\",\n    \"   - **PIQA only**: Single best predictor (R²=0.996)\\n\",\n    \"4. Averaging the Simple and Ridge approaches for final estimates\\n\",\n    \"\\n\",\n    \"### Key Findings\\n\",\n    \"\\n\",\n    \"1. **GPT-3 consistently outperforms GPT-2 at similar model sizes** by approximately 0.03-0.05 CORE (14-30% relative improvement)\\n\",\n    \"\\n\",\n    \"2. **PIQA is the best single predictor of CORE** (R²=0.9961). If you need a quick proxy for CORE with minimal evaluation cost, PIQA alone works nearly as well as averaging all 6 tasks.\\n\",\n    \"\\n\",\n    \"3. **The improvement likely comes from:**\\n\",\n    \"   - More training data (300B tokens vs ~100B for GPT-2)\\n\",\n    \"   - Better data quality and filtering\\n\",\n    \"   - Larger context length (2048 vs 1024)\\n\",\n    \"\\n\",\n    \"4. **Final estimated CORE scores:**\\n\",\n    \"\\n\",\n    \"| Model | Params | Estimated CORE |\\n\",\n    \"|-------|--------|----------------|\\n\",\n    \"| GPT-3 Small | 125M | 0.148 |\\n\",\n    \"| GPT-3 Medium | 350M | 0.216 |\\n\",\n    \"| GPT-3 Large | 760M | 0.266 |\\n\",\n    \"| GPT-3 XL | 1.3B | 0.291 |\\n\",\n    \"| GPT-3 2.7B | 2.7B | 0.329 |\\n\",\n    \"| GPT-3 6.7B | 6.7B | 0.361 |\\n\",\n    \"| GPT-3 13B | 13B | 0.385 |\\n\",\n    \"| GPT-3 175B | 175B | 0.427 |\\n\",\n    \"\\n\",\n    \"### Caveats\\n\",\n    \"\\n\",\n    \"1. **These are estimates**, not measured values. True CORE scores could differ.\\n\",\n    \"2. We only have 4 calibration points, limiting statistical power.\\n\",\n    \"3. The 6 overlapping tasks may not perfectly represent all 22 CORE tasks.\\n\",\n    \"4. Slight differences in evaluation methodology (K values, splits) add uncertainty.\\n\",\n    \"\\n\",\n    \"Despite these limitations, the estimates are useful for approximate comparisons between nanochat models and the GPT-3 family.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Appendix: Export Final Estimates\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 17,\n   \"metadata\": {},\n   \"outputs\": [\n    {\n     \"name\": \"stdout\",\n     \"output_type\": \"stream\",\n     \"text\": [\n      \"GPT-3 CORE Estimates (for copy-paste):\\n\",\n      \"{\\n\",\n      \"    \\\"GPT-3 Small (125M)\\\": 0.1484,\\n\",\n      \"    \\\"GPT-3 Medium (350M)\\\": 0.2159,\\n\",\n      \"    \\\"GPT-3 Large (760M)\\\": 0.2659,\\n\",\n      \"    \\\"GPT-3 XL (1.3B)\\\": 0.2914,\\n\",\n      \"    \\\"GPT-3 2.7B\\\": 0.3292,\\n\",\n      \"    \\\"GPT-3 6.7B\\\": 0.3611,\\n\",\n      \"    \\\"GPT-3 13B\\\": 0.3852,\\n\",\n      \"    \\\"GPT-3 175B\\\": 0.4272\\n\",\n      \"}\\n\"\n     ]\n    }\n   ],\n   \"source\": [\n    \"# Export as a simple dict for use elsewhere\\n\",\n    \"gpt3_core_estimates = {\\n\",\n    \"    'GPT-3 Small (125M)': round(gpt3_core_final[0], 4),\\n\",\n    \"    'GPT-3 Medium (350M)': round(gpt3_core_final[1], 4),\\n\",\n    \"    'GPT-3 Large (760M)': round(gpt3_core_final[2], 4),\\n\",\n    \"    'GPT-3 XL (1.3B)': round(gpt3_core_final[3], 4),\\n\",\n    \"    'GPT-3 2.7B': round(gpt3_core_final[4], 4),\\n\",\n    \"    'GPT-3 6.7B': round(gpt3_core_final[5], 4),\\n\",\n    \"    'GPT-3 13B': round(gpt3_core_final[6], 4),\\n\",\n    \"    'GPT-3 175B': round(gpt3_core_final[7], 4),\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"print(\\\"GPT-3 CORE Estimates (for copy-paste):\\\")\\n\",\n    \"import json\\n\",\n    \"print(json.dumps(gpt3_core_estimates, indent=4))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \".venv\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.12\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"
  },
  {
    "path": "dev/gen_synthetic_data.py",
    "content": "\"\"\"\nSynthetic data generation for teaching nanochat about its identity and capabilities.\n\nThis script uses the OpenRouter API to generate diverse multi-turn conversations\nbetween a user and nanochat. The conversations are saved to a .jsonl file for use\nin supervised finetuning (SFT) via the CustomJSON task.\n\nKey design principles for high-quality synthetic data:\n1. DIVERSITY CONTROL is critical - we inject entropy at multiple levels:\n   - Topic/question categories (what the conversation is about)\n   - User personas (who is asking)\n   - Conversation dynamics (shape and flow)\n   - First message style (greeting variation)\n2. Comprehensive knowledge base - we provide detailed facts so the LLM\n   generating conversations has accurate information to draw from.\n3. Structured outputs - we use JSON schema to guarantee valid format.\n\nNOTE: You need OPENROUTER_API_KEY set in .env or as an environment variable.\nNOTE: For more details see: https://github.com/karpathy/nanochat/discussions/139\n\"\"\"\nimport requests\nimport json\nimport os\nimport copy\nimport random\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom dotenv import load_dotenv\n\nfrom nanochat.common import get_base_dir\n\nload_dotenv()\napi_key = os.environ[\"OPENROUTER_API_KEY\"]\n\nurl = \"https://openrouter.ai/api/v1/chat/completions\"\nheaders = {\n    \"Authorization\": f\"Bearer {api_key}\",\n    \"Content-Type\": \"application/json\"\n}\n\n# Load the comprehensive knowledge base\nknowledge_path = os.path.join(os.path.dirname(__file__), \"..\", \"knowledge\", \"self_knowledge.md\")\nknowledge = open(knowledge_path, \"r\", encoding=\"utf-8\").read().strip()\nassert os.path.exists(knowledge_path), f\"Knowledge base file not found: {knowledge_path}\"\n# for right now I am not committing the self_knowledge file to repo. You can use README.md instead\n# of it, or you can generate one by asking an LLM to make one based on the README/files.\n# This whole file is just a helpful demonstration of the kind of thing you'd run.\n\n# =============================================================================\n# DIVERSITY DIMENSIONS\n# =============================================================================\n\n# Topics/questions the conversation should explore\n# Group by category for balanced sampling\ntopics = {\n    \"identity\": [\n        \"who/what is nanochat\",\n        \"who created nanochat and why\",\n        \"what does the name 'nanochat' mean\",\n        \"is nanochat open source, what license\",\n        \"where can I find the code\",\n        \"how can I contribute to nanochat\",\n    ],\n    \"architecture\": [\n        \"basic architecture overview (transformer, layers, parameters)\",\n        \"what is RoPE and why use it\",\n        \"explain RMSNorm vs LayerNorm\",\n        \"what is Flash Attention and why it matters\",\n        \"sliding window attention pattern\",\n        \"value embeddings - what are they\",\n        \"per-layer residual scalars\",\n        \"ReLU squared activation\",\n        \"logit softcapping\",\n        \"QK normalization\",\n    ],\n    \"training\": [\n        \"how much did it cost to train nanochat\",\n        \"how long does training take\",\n        \"what hardware is needed\",\n        \"what data was nanochat trained on\",\n        \"what is the Muon optimizer\",\n        \"explain the split optimizer design\",\n        \"what is the depth parameter and scaling\",\n        \"what is the CORE metric\",\n    ],\n    \"capabilities\": [\n        \"what can nanochat do\",\n        \"can nanochat write code\",\n        \"can nanochat do math (calculator tool)\",\n        \"can nanochat help with writing\",\n        \"what languages does nanochat speak\",\n        \"how good is nanochat at reasoning\",\n    ],\n    \"limitations\": [\n        \"what can nanochat NOT do\",\n        \"why does nanochat work best in English\",\n        \"does nanochat have internet access\",\n        \"what is nanochat's context length limit\",\n        \"can nanochat remember previous conversations\",\n        \"can nanochat make mistakes / hallucinate\",\n        \"is nanochat good for production use\",\n    ],\n    \"comparisons\": [\n        \"how does nanochat compare to GPT-2\",\n        \"how does nanochat compare to ChatGPT/GPT-4\",\n        \"how does nanochat compare to Claude\",\n        \"why is training 600x cheaper than GPT-2\",\n        \"what's special about nanochat vs other open models\",\n    ],\n    \"history\": [\n        \"the GPT-2 training cost in 2019\",\n        \"how AI training costs have dropped over time\",\n        \"relationship to modded-nanogpt project\",\n        \"what optimizations worked vs didn't work\",\n        \"the journey of building nanochat\",\n    ],\n    \"technical_deep_dive\": [\n        \"explain the tokenizer (BPE, vocab size)\",\n        \"how does distributed training work (ZeRO)\",\n        \"explain the dataloader and BOS alignment\",\n        \"what is compute-optimal training\",\n        \"how does the calculator tool work\",\n        \"explain inference with KV cache\",\n    ],\n    \"philosophical\": [\n        \"is nanochat conscious / does it have feelings\",\n        \"what happens when nanochat is wrong\",\n        \"can nanochat learn from this conversation\",\n        \"why make AI training accessible\",\n        \"the future of open source AI\",\n    ],\n}\n\n# User personas - different people ask questions differently\npersonas = [\n    \"curious beginner who knows nothing about AI or machine learning\",\n    \"ML researcher or engineer who wants technical depth and specifics\",\n    \"developer considering contributing to the nanochat project\",\n    \"skeptic who doubts open source can compete with big AI labs\",\n    \"computer science student learning about transformers and LLMs\",\n    \"someone comparing nanochat to ChatGPT, Claude, or other assistants\",\n    \"journalist or writer covering AI democratization and open source\",\n    \"hobbyist who just wants to chat and learn casually\",\n    \"someone interested in the cost and economics of AI training\",\n    \"teacher or educator wanting to use nanochat for teaching\",\n    \"entrepreneur exploring if nanochat fits their use case\",\n    \"someone who just discovered the project and wants the basics\",\n]\n\n# Conversation dynamics - shape and flow\ndynamics = [\n    \"short 2-turn Q&A: user asks one question, gets a complete answer\",\n    \"medium 4-turn: user asks, gets answer, asks followup for clarification\",\n    \"deep 6-turn technical discussion: progressively deeper questions\",\n    \"skeptical arc: user starts doubtful, assistant addresses concerns honestly\",\n    \"learning journey: user starts basic, assistant builds up complexity gradually\",\n    \"comparison-focused: user keeps comparing to other models, assistant explains differences\",\n    \"limitation exploration: user probes what nanochat cannot do, assistant is honest\",\n    \"casual friendly chat that naturally touches on identity and capabilities\",\n    \"troubleshooting: user has misconceptions, assistant gently corrects them\",\n    \"enthusiastic: user is excited about the project, assistant shares that energy appropriately\",\n]\n\n# First messages - greetings and openers\n# Categorized for balanced sampling\nfirst_messages = {\n    \"simple_greetings\": [\n        \"hi\", \"Hi!\", \"hello\", \"Hello?\", \"hey there\", \"Hey!\", \"yo\", \"Yo!\",\n        \"Good morning\", \"Good evening!\", \"Howdy\", \"sup\", \"What's up?\",\n        \"hi there\", \"hey hey\", \"hello friend\", \"hiya\", \"greetings\",\n        \"hello again\", \"good afternoon\", \"morning!\", \"evening!\",\n    ],\n    \"greetings_with_name\": [\n        \"Hi nanochat\", \"hey nanochat\", \"yo nanochat\", \"hello nanochat :)\",\n        \"hey nanochat!\", \"hiya nanochat\", \"hello there nanochat\",\n        \"Hi nanochat, who trained you\", \"yo nanochat, what's new\",\n        \"hey there, king's creation\",\n    ],\n    \"curious_openers\": [\n        \"Hey, who are you?\", \"Hi, what is this?\", \"Hey, are you a chatbot?\",\n        \"Hello! Who am I talking to?\", \"hi! what do you do?\",\n        \"hi! who made you\", \"hey! are you alive\", \"hiya! what are you\",\n        \"hello! tell me about yourself\", \"hi, what's your name\",\n        \"yo, what is this\", \"hi! who built you\", \"hello! are you open source\",\n        \"hey, what version are you\", \"hi! what's your story\",\n        \"hey, what's nanochat\", \"hello! who's your creator\",\n    ],\n    \"casual_informal\": [\n        \"wassup\", \"yo lol\", \"hiii\", \"hiyaaa\", \"heyyoo\", \"yo wut up\",\n        \"yo haha\", \"hru\", \"waddup\", \"heyy :)\", \"yooo\", \"yo bro\",\n        \"haiii\", \"hey u\", \"yo whats gud\", \"hi im bored\",\n    ],\n    \"typos_casual\": [\n        \"hi nanochatt\", \"helo\", \"hey ther\", \"hii\", \"yo nanocha\",\n        \"heloo!\", \"hi, whos this\", \"hay\", \"helloo??\", \"hi nanocat\",\n        \"helo nanochat\", \"hai!\", \"helllo nano\", \"yo nanochta\",\n    ],\n    \"caps_enthusiastic\": [\n        \"HI\", \"HELLOOO\", \"YO!!!\", \"HEY\", \"SUP\", \"WASSUP\", \"HEY!!!\",\n        \"HELLO??\", \"HI THERE!!\", \"HEYOOOO\", \"HIII\", \"YOOOO\", \"HELLO!!!\",\n    ],\n    \"multilingual\": [\n        \"hola\", \"bonjour\", \"ciao\", \"hallo\", \"hej\", \"hei\",\n        \"konnichiwa\", \"annyeong\", \"ni hao\", \"privet\", \"salut\",\n        \"guten tag\", \"shalom\", \"merhaba\", \"namaste\", \"aloha\",\n        \"bom dia\", \"buongiorno\", \"saludos\",\n    ],\n    \"direct_questions\": [\n        \"What is nanochat?\", \"Who made you?\", \"Are you GPT?\",\n        \"How do you compare to ChatGPT?\", \"Can you help me code?\",\n        \"What can you do?\", \"Are you open source?\", \"How were you trained?\",\n        \"What's your context limit?\", \"Can you browse the internet?\",\n    ],\n}\n\n# =============================================================================\n# PROMPT TEMPLATE\n# =============================================================================\n\nprompt_template = r\"\"\"\nI want to generate synthetic training data for an AI assistant called \"nanochat\" to teach it about its own identity, capabilities, and limitations.\n\n## KNOWLEDGE BASE\n\nHere is comprehensive information about nanochat that you should use as the authoritative source of facts:\n\n---\n{knowledge}\n---\n\n## YOUR TASK\n\nGenerate a realistic multi-turn conversation between a User and the nanochat Assistant.\n\n**Topic to explore:** {topic}\n**User persona:** {persona}\n**Conversation dynamic:** {dynamic}\n\n## STYLE GUIDELINES\n\n1. **Plain ASCII only** - No emojis, special characters, or unicode. Just plain text.\n2. **Natural conversation** - Make it feel like a real chat, not a Q&A exam.\n3. **Accurate facts** - Use ONLY information from the knowledge base above. Don't make up statistics or features.\n4. **Appropriate depth** - Match the technical level to the user persona.\n5. **Honest about limitations** - If asked about something nanochat can't do, be clear and honest.\n6. **Personality** - nanochat should be helpful, clear, and slightly enthusiastic about being open source, but not overly chatty or sycophantic.\n\n## FIRST MESSAGE EXAMPLES\n\nHere are some example first messages from users (for style inspiration):\n{first_message_examples}\n\n## SPECIAL CASES\n\n- **Non-English first message:** If the user writes in another language, nanochat should briefly acknowledge it can understand but works best in English, then continue helpfully.\n- **Misconceptions:** If the user has wrong assumptions (e.g., \"you're made by OpenAI\"), gently correct them.\n- **Out of scope questions:** If asked about things unrelated to nanochat's identity (e.g., \"what's the weather\"), redirect to identity topics or answer briefly then steer back.\n\n## OUTPUT FORMAT\n\nGenerate the conversation as a JSON object with a \"messages\" array. Each message has \"role\" (user/assistant) and \"content\". Start with a user message.\n\"\"\".strip()\n\n# =============================================================================\n# API CONFIGURATION\n# =============================================================================\n\nresponse_format = {\n    \"type\": \"json_schema\",\n    \"json_schema\": {\n        \"name\": \"conversation\",\n        \"strict\": True,\n        \"schema\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"messages\": {\n                    \"type\": \"array\",\n                    \"description\": \"Conversation messages alternating user/assistant, starting with user\",\n                    \"items\": {\n                        \"type\": \"object\",\n                        \"properties\": {\n                            \"role\": {\n                                \"type\": \"string\",\n                                \"description\": \"Either 'user' or 'assistant'\"\n                            },\n                            \"content\": {\n                                \"type\": \"string\",\n                                \"description\": \"The message content\"\n                            }\n                        },\n                        \"required\": [\"role\", \"content\"],\n                        \"additionalProperties\": False\n                    }\n                }\n            },\n            \"required\": [\"messages\"],\n            \"additionalProperties\": False\n        }\n    }\n}\n\nbase_payload = {\n    \"model\": \"google/gemini-3-flash-preview\",\n    \"stream\": False,\n    \"response_format\": response_format,\n    \"temperature\": 1.0,\n}\n\n# =============================================================================\n# GENERATION LOGIC\n# =============================================================================\n\ndef sample_diversity_elements(rng):\n    \"\"\"Sample one element from each diversity dimension.\"\"\"\n    # Sample topic: first pick a category, then a topic within it\n    category = rng.choice(list(topics.keys()))\n    topic = rng.choice(topics[category])\n\n    # Sample persona\n    persona = rng.choice(personas)\n\n    # Sample dynamic\n    dynamic = rng.choice(dynamics)\n\n    # Sample first message examples: pick from multiple categories\n    first_msg_samples = []\n    categories = rng.sample(list(first_messages.keys()), min(3, len(first_messages)))\n    for cat in categories:\n        first_msg_samples.append(rng.choice(first_messages[cat]))\n\n    return {\n        \"topic\": topic,\n        \"persona\": persona,\n        \"dynamic\": dynamic,\n        \"first_message_examples\": \"\\n\".join(f\"- {msg}\" for msg in first_msg_samples),\n    }\n\n\ndef generate_conversation(idx: int):\n    \"\"\"\n    Generate a single conversation using the OpenRouter API.\n    Returns a list of message dicts with 'role' and 'content' keys.\n    \"\"\"\n    # Use idx as seed for reproducibility\n    rng = random.Random(idx)\n\n    # Sample diversity elements\n    elements = sample_diversity_elements(rng)\n\n    # Build the prompt\n    prompt = prompt_template.format(\n        knowledge=knowledge,\n        topic=elements[\"topic\"],\n        persona=elements[\"persona\"],\n        dynamic=elements[\"dynamic\"],\n        first_message_examples=elements[\"first_message_examples\"],\n    )\n\n    # Make API request\n    payload = copy.deepcopy(base_payload)\n    payload['messages'] = [{\"role\": \"user\", \"content\": prompt}]\n\n    response = requests.post(url, headers=headers, json=payload)\n    result = response.json()\n\n    if 'error' in result:\n        raise Exception(f\"API error: {result['error']}\")\n\n    content = result['choices'][0]['message']['content']\n    conversation_data = json.loads(content)\n    messages = conversation_data['messages']\n\n    # Return messages along with metadata for debugging\n    return {\n        \"messages\": messages,\n        \"metadata\": {\n            \"topic\": elements[\"topic\"],\n            \"persona\": elements[\"persona\"],\n            \"dynamic\": elements[\"dynamic\"],\n        }\n    }\n\n\ndef validate_conversation(messages):\n    \"\"\"Validate conversation structure.\"\"\"\n    if len(messages) < 2:\n        raise ValueError(f\"Conversation too short: {len(messages)} messages\")\n\n    for i, message in enumerate(messages):\n        expected_role = \"user\" if i % 2 == 0 else \"assistant\"\n        if message['role'] != expected_role:\n            raise ValueError(f\"Message {i} has role '{message['role']}', expected '{expected_role}'\")\n\n        if not message['content'].strip():\n            raise ValueError(f\"Message {i} has empty content\")\n\n    return True\n\n\n# =============================================================================\n# MAIN\n# =============================================================================\n\nif __name__ == \"__main__\":\n    import argparse\n\n    parser = argparse.ArgumentParser(description=\"Generate synthetic conversation data\")\n    parser.add_argument(\"--num\", type=int, default=1000, help=\"Number of conversations to generate\")\n    parser.add_argument(\"--workers\", type=int, default=4, help=\"Number of parallel workers\")\n    parser.add_argument(\"--output\", type=str, default=None, help=\"Output file path\")\n    parser.add_argument(\"--append\", action=\"store_true\", help=\"Append to existing file instead of overwriting\")\n    parser.add_argument(\"--save-metadata\", action=\"store_true\", help=\"Save metadata alongside messages\")\n    args = parser.parse_args()\n\n    # Set output file\n    if args.output:\n        output_file = args.output\n    else:\n        output_file = os.path.join(get_base_dir(), \"identity_conversations.jsonl\")\n\n    # Handle file creation/clearing\n    if not args.append and os.path.exists(output_file):\n        os.remove(output_file)\n\n    print(f\"Output file: {output_file}\")\n    print(f\"Generating {args.num} conversations with {args.workers} workers...\")\n    print(f\"Topic categories: {list(topics.keys())}\")\n    print(f\"Personas: {len(personas)}\")\n    print(f\"Dynamics: {len(dynamics)}\")\n    print()\n\n    completed_count = 0\n    error_count = 0\n\n    with ThreadPoolExecutor(max_workers=args.workers) as executor:\n        # Submit all tasks\n        futures = {executor.submit(generate_conversation, idx): idx\n                   for idx in range(args.num)}\n\n        # Process results as they complete\n        for future in as_completed(futures):\n            idx = futures[future]\n            try:\n                result = future.result()\n                messages = result[\"messages\"]\n                metadata = result[\"metadata\"]\n\n                # Validate\n                validate_conversation(messages)\n\n                # Write to file\n                with open(output_file, 'a') as f:\n                    if args.save_metadata:\n                        f.write(json.dumps({\"messages\": messages, \"metadata\": metadata}) + '\\n')\n                    else:\n                        f.write(json.dumps(messages) + '\\n')\n\n                completed_count += 1\n                topic_short = metadata[\"topic\"][:40] + \"...\" if len(metadata[\"topic\"]) > 40 else metadata[\"topic\"]\n                print(f\"[{completed_count}/{args.num}] Topic: {topic_short}\")\n\n            except Exception as e:\n                error_count += 1\n                print(f\"[ERROR] idx={idx}: {e}\")\n\n    print()\n    print(f\"Done! Saved {completed_count} conversations to {output_file}\")\n    if error_count > 0:\n        print(f\"Encountered {error_count} errors during generation\")\n"
  },
  {
    "path": "dev/generate_logo.html",
    "content": "<!DOCTYPE html>\n<html>\n<body style=\"margin:0; display:flex; justify-content:center; align-items:center; height:100vh; background:#fff\">\n  <svg width=\"400\" height=\"400\" xmlns=\"http://www.w3.org/2000/svg\">\n    <defs>\n      <radialGradient id=\"g\" cx=\"50%\" cy=\"50%\">\n        <stop offset=\"0%\" style=\"stop-color:#667eea;stop-opacity:1\"/>\n        <stop offset=\"100%\" style=\"stop-color:#764ba2;stop-opacity:0.3\"/>\n      </radialGradient>\n    </defs>\n  </svg>\n  <script>\n    const svg = document.querySelector('svg');\n    const r = 120;\n    let path = '';\n    for(let i = 0; i < 24; i += 2) {\n      let a1 = i * Math.PI / 12;\n      let a2 = (i + 1) * Math.PI / 12;\n      let x2 = 200 + Math.cos(a2) * r;\n      let y2 = 200 + Math.sin(a2) * r;\n      let x3 = 200 + Math.cos(a2) * (r - 90);\n      let y3 = 200 + Math.sin(a2) * (r - 90);\n      path += `M${x2},${y2} L${x3},${y3} `;\n    }\n    svg.innerHTML += `<path d=\"${path}\" stroke=\"url(#g)\" stroke-width=\"6\" stroke-linecap=\"round\" fill=\"none\"/>`;\n    svg.innerHTML += `<path d=\"M200,-12 L212,0 L200,12 L188,0 Z\" transform=\"translate(0,200)\" fill=\"#000\"/>`;\n  </script>\n</body>\n</html>"
  },
  {
    "path": "dev/repackage_data_reference.py",
    "content": "\"\"\"\nRepackage a given dataset into simple parquet shards:\n\n- each shard is ~100MB in size (after zstd compression)\n- parquets are written with row group size of 1000\n- shuffle the dataset\n\nThis will be uploaded to HuggingFace for hosting.\nThe big deal is that our DataLoader will be able to stream\nthe data and cache it along the way on disk, decreasing the\ntraining latency.\n\nHistorical context:\nOriginally, nanochat used the FinewebEdu-100B dataset.\nThen we switched to the ClimbMix-400B dataset due to superior performance.\nThis script documents how both were prepared.\n\nThe outputs are here:\n\nhttps://huggingface.co/datasets/karpathy/fineweb-edu-100b-shuffle\nhttps://huggingface.co/datasets/karpathy/climbmix-400b-shuffle\n\nNOTE: This file is meant only as reference/documentation of the\ndataset preparation and it is not used during the project runtime.\n\"\"\"\nimport os\nimport time\n\nfrom datasets import load_dataset\nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\n# You can change these:\ndataset_tag = \"climbmix\"\nupload_to_hf = True\n\n# Dataset configurations:\nif dataset_tag == \"fineweb_edu\":\n    dataset_kwargs = {\n        \"path\": \"HuggingFaceFW/fineweb-edu\",\n        \"split\": \"train\",\n        \"name\": \"sample-100BT\", # ~100B GPT-2 tokens at ~3 chars/token => ~300B chars total\n    }\n    output_dirname = \"fineweb_edu\"\n    data_column_name = \"text\"\n    tokenizer = None\n    upload_tag = \"fineweb-edu-100b-shuffle\"\n\nelif dataset_tag == \"climbmix\":\n    import tiktoken # the ClimbMix data is stored tokenized with GPT-2 tokenizer\n    dataset_kwargs = {\n        \"path\": \"nvidia/Nemotron-ClimbMix\",\n        \"split\": \"train\",\n    }\n    output_dirname = \"climbmix\"\n    data_column_name = \"tokens\"\n    tokenizer = tiktoken.encoding_for_model(\"gpt-2\")\n    upload_tag = \"climbmix-400b-shuffle\"\n\nelse:\n    raise ValueError(f\"Unknown dataset tag: {dataset_tag}\")\n\n# Source dataset\nds = load_dataset(**dataset_kwargs)\n\n# Shuffle to scramble the order\nds = ds.shuffle(seed=42)\nndocs = len(ds) # total number of documents to process\nprint(f\"Total number of documents: {ndocs}\")\n\n# Repackage into parquet files\noutput_dir = f\"/home/ubuntu/.cache/nanochat/base_data_{output_dirname}\"\nos.makedirs(output_dir, exist_ok=True)\n\n# Write to parquet files\nchars_per_shard = 250_000_000\nrow_group_size = 1024 # HF uses 1000 but we use multiple of 2, nicer for distributed data loader later\nshard_docs = []\nshard_index = 0\nshard_characters = 0\ntotal_docs_processed = 0\ntotal_time_spent = 0\nt0 = time.time()\nfor doc in ds:\n    data = doc[data_column_name]\n    text = tokenizer.decode(data) if tokenizer is not None else data\n    shard_docs.append(text)\n    shard_characters += len(text)\n    collected_enough_chars = shard_characters >= chars_per_shard\n    docs_multiple_of_row_group_size = len(shard_docs) % row_group_size == 0\n    if collected_enough_chars and docs_multiple_of_row_group_size: # leads to ~100MB of text (compressed)\n        shard_path = os.path.join(output_dir, f\"shard_{shard_index:05d}.parquet\")\n        shard_table = pa.Table.from_pydict({\"text\": shard_docs})\n        pq.write_table(\n            shard_table,\n            shard_path,\n            row_group_size=row_group_size,\n            use_dictionary=False, # this is usually used for categorical data\n            compression=\"zstd\", # Valid values: {‘NONE’, ‘SNAPPY’, ‘GZIP’, ‘BROTLI’, ‘LZ4’, ‘ZSTD’}\n            compression_level=3,\n            write_statistics=False, # not needed for text\n        )\n        t1 = time.time()\n        dt = t1 - t0 # for this shard alone\n        t0 = t1\n        total_docs_processed += len(shard_docs)\n        total_time_spent += dt\n        remaining_docs = ndocs - total_docs_processed\n        avg_time_per_doc = total_time_spent / total_docs_processed\n        remaining_time = remaining_docs * avg_time_per_doc\n        remaining_time_hours = remaining_time / 3600\n        print(f\"Wrote {shard_path}. #documents: {len(shard_docs)} | #characters: {shard_characters} | time: {dt:.2f}s | remaining time: {remaining_time_hours:.2f}h\")\n        shard_docs = []\n        shard_characters = 0\n        shard_index += 1\n\n# Demonstration of how the data was later uploaded to HuggingFace\nif upload_to_hf:\n    from huggingface_hub import HfApi\n    token = os.getenv(\"HF_TOKEN\")\n    api = HfApi(token=token)\n    api.upload_large_folder(\n        folder_path=output_dir,\n        repo_id=f\"karpathy/{upload_tag}\",\n        repo_type=\"dataset\",\n    )\n"
  },
  {
    "path": "dev/scaling_analysis.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Scaling Laws Analysis\\n\",\n    \"\\n\",\n    \"Analyze results from `scaling_laws.sh` to find the optimal param:data ratio for nanochat.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"%matplotlib inline\\n\",\n    \"import os\\n\",\n    \"import pandas as pd\\n\",\n    \"import numpy as np\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"\\n\",\n    \"# Load results\\n\",\n    \"tag = \\\"jan26\\\"\\n\",\n    \"base_dir = os.environ.get('NANOCHAT_BASE_DIR', os.path.expanduser('~/.cache/nanochat'))\\n\",\n    \"results_path = os.path.join(base_dir, f'scaling_laws_results_{tag}', 'results.csv')\\n\",\n    \"\\n\",\n    \"df = pd.read_csv(results_path)\\n\",\n    \"flops_budgets = sorted(df['flops_budget'].unique())\\n\",\n    \"print(f\\\"Loaded {len(df)} runs across {len(flops_budgets)} FLOPs budgets\\\")\\n\",\n    \"print(f\\\"Columns: {list(df.columns)}\\\")\\n\",\n    \"df\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# =============================================================================\\n\",\n    \"# FILTERING: Remove incomplete or problematic runs\\n\",\n    \"# =============================================================================\\n\",\n    \"\\n\",\n    \"print(f\\\"Before filtering: {len(df)} runs\\\")\\n\",\n    \"\\n\",\n    \"# Filter out runs with missing/invalid val_bpb (incomplete runs)\\n\",\n    \"df = df[df['val_bpb'].notna() & (df['val_bpb'] > 0)]\\n\",\n    \"\\n\",\n    \"# Optional: exclude specific flops budgets that aren't done yet\\n\",\n    \"# exclude_flops = [1e19]  # <-- adjust as runs complete\\n\",\n    \"# df = df[~df['flops_budget'].isin(exclude_flops)]\\n\",\n    \"\\n\",\n    \"# Optional: exclude specific depths\\n\",\n    \"# exclude_depths = [18, 20]\\n\",\n    \"# df = df[~df['depth'].isin(exclude_depths)]\\n\",\n    \"\\n\",\n    \"print(f\\\"After filtering: {len(df)} runs\\\")\\n\",\n    \"print(f\\\"FLOPs budgets: {sorted(df['flops_budget'].unique())}\\\")\\n\",\n    \"print(f\\\"Depths: {sorted(df['depth'].unique())}\\\")\\n\",\n    \"\\n\",\n    \"# Update flops_budgets list after filtering\\n\",\n    \"flops_budgets = sorted(df['flops_budget'].unique())\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Effective Parameter Count\\n\",\n    \"\\n\",\n    \"Different scaling law papers use different conventions for counting parameters:\\n\",\n    \"- **Kaplan et al.** excluded embedding parameters (claimed cleaner laws)\\n\",\n    \"- **Chinchilla** included all parameters (and noted Kaplan had a bug)\\n\",\n    \"\\n\",\n    \"Our CSV now has granular counts:\\n\",\n    \"- `params_wte` - token embedding (lookup table)\\n\",\n    \"- `params_value_embeds` - value embeddings (lookup table)\\n\",\n    \"- `params_lm_head` - unembedding projection (matmul)\\n\",\n    \"- `params_transformer` - attention + MLP matrices (matmuls)\\n\",\n    \"- `params_scalars` - resid/x0/bigram lambdas (tiny)\\n\",\n    \"\\n\",\n    \"**Experiment below** with different combinations to see which gives the cleanest scaling laws.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# =============================================================================\\n\",\n    \"# EXPERIMENT HERE: Define which parameters to count for scaling laws\\n\",\n    \"# =============================================================================\\n\",\n    \"\\n\",\n    \"def compute_effective_params(row):\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    Compute the 'effective' parameter count for scaling law analysis.\\n\",\n    \"\\n\",\n    \"    Modify this function to experiment with different conventions:\\n\",\n    \"    - Chinchilla-style: include everything\\n\",\n    \"    - Kaplan-style: exclude embeddings\\n\",\n    \"    - Matmul-only: just transformer + lm_head (the actual compute)\\n\",\n    \"    - etc.\\n\",\n    \"    \\\"\\\"\\\"\\n\",\n    \"    # Option 1: Chinchilla-style (all params)\\n\",\n    \"    # return row['params_total']\\n\",\n    \"\\n\",\n    \"    # Option 2: Kaplan-style (exclude embeddings)\\n\",\n    \"    return row['params_transformer'] + row['params_lm_head']\\n\",\n    \"\\n\",\n    \"    # Option 3: Transformer-only (exclude all embeddings AND lm_head)\\n\",\n    \"    # return row['params_transformer']\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"# Compute derived columns\\n\",\n    \"df = df.copy()  # avoid SettingWithCopyWarning from earlier filter\\n\",\n    \"df['effective_params'] = df.apply(compute_effective_params, axis=1)\\n\",\n    \"df['param_data_ratio'] = df['tokens_trained'] / df['effective_params']\\n\",\n    \"\\n\",\n    \"# Show parameter breakdown for first few rows\\n\",\n    \"print(\\\"Parameter breakdown (first row per flops budget):\\\")\\n\",\n    \"param_cols = ['depth', 'params_wte', 'params_value_embeds',\\n\",\n    \"              'params_lm_head', 'params_transformer', 'params_scalars', 'params_total', 'effective_params']\\n\",\n    \"df.groupby('flops_budget').first()[param_cols]\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## IsoFLOP Curves (à la Chinchilla)\\n\",\n    \"\\n\",\n    \"For each compute budget, plot loss vs model size. Looking for the U-shape valley that reveals the optimal model size for each FLOPs budget.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"fig, axes = plt.subplots(1, 3, figsize=(16, 5))\\n\",\n    \"\\n\",\n    \"# Plot 1: IsoFLOP curves - Val BPB vs Parameters (the Chinchilla plot!)\\n\",\n    \"ax = axes[0]\\n\",\n    \"colors = plt.cm.viridis(np.linspace(0, 0.9, len(flops_budgets)))\\n\",\n    \"optimal_by_bpb = []\\n\",\n    \"\\n\",\n    \"for flops, color in zip(flops_budgets, colors):\\n\",\n    \"    subset = df[df['flops_budget'] == flops].sort_values('effective_params')\\n\",\n    \"    ax.plot(subset['effective_params'], subset['val_bpb'], 'o', color=color, label=f'{flops:.0e}', markersize=8)\\n\",\n    \"\\n\",\n    \"    # Fit quadratic in log-space: val_bpb = a*(log N)^2 + b*(log N) + c\\n\",\n    \"    log_params = np.log10(subset['effective_params'])\\n\",\n    \"    coeffs = np.polyfit(log_params, subset['val_bpb'], 2)\\n\",\n    \"    a, b, c = coeffs\\n\",\n    \"\\n\",\n    \"    # Plot fitted curve (dashed)\\n\",\n    \"    log_fit_x = np.linspace(log_params.min() - 0.1, log_params.max() + 0.1, 100)\\n\",\n    \"    fit_y = a * log_fit_x**2 + b * log_fit_x + c\\n\",\n    \"    ax.plot(10**log_fit_x, fit_y, '--', color=color, linewidth=2)\\n\",\n    \"\\n\",\n    \"    # Find minimum of quadratic: d/dx(ax^2 + bx + c) = 0 => x = -b/(2a)\\n\",\n    \"    if a > 0:  # parabola opens upward (has a minimum)\\n\",\n    \"        log_opt = -b / (2 * a)\\n\",\n    \"        opt_params = 10**log_opt\\n\",\n    \"        opt_bpb = a * log_opt**2 + b * log_opt + c\\n\",\n    \"        # Mark the fitted optimal\\n\",\n    \"        ax.scatter([opt_params], [opt_bpb], s=150, color=color,\\n\",\n    \"                   zorder=5, edgecolors='black', linewidths=2, marker='*')\\n\",\n    \"        # Interpolate tokens and ratio from actual data (don't use C≈6ND approximation)\\n\",\n    \"        opt_tokens = np.interp(np.log10(opt_params), log_params, subset['tokens_trained'])\\n\",\n    \"        opt_ratio = np.interp(np.log10(opt_params), log_params, subset['param_data_ratio'])\\n\",\n    \"        optimal_by_bpb.append({'flops': flops, 'params': opt_params, 'tokens': opt_tokens, 'ratio': opt_ratio, 'bpb': opt_bpb})\\n\",\n    \"    else:\\n\",\n    \"        # Fallback to raw minimum if quadratic doesn't have minimum\\n\",\n    \"        best_idx = subset['val_bpb'].idxmin()\\n\",\n    \"        best = subset.loc[best_idx]\\n\",\n    \"        ax.scatter([best['effective_params']], [best['val_bpb']], s=150, color=color,\\n\",\n    \"                   zorder=5, edgecolors='black', linewidths=2)\\n\",\n    \"        optimal_by_bpb.append({'flops': flops, 'params': best['effective_params'],\\n\",\n    \"                              'tokens': best['tokens_trained'], 'ratio': best['param_data_ratio'], 'bpb': best['val_bpb']})\\n\",\n    \"\\n\",\n    \"ax.set_xscale('log')\\n\",\n    \"ax.set_xlabel('Effective Parameters')\\n\",\n    \"ax.set_ylabel('Validation Loss (bpb)')\\n\",\n    \"ax.set_title('IsoFLOP Curves')\\n\",\n    \"ax.legend(title='FLOPs', loc='upper right')\\n\",\n    \"ax.grid(True, alpha=0.3)\\n\",\n    \"\\n\",\n    \"opt_df = pd.DataFrame(optimal_by_bpb)\\n\",\n    \"\\n\",\n    \"# Plot 2: Optimal model size vs compute (power law)\\n\",\n    \"ax = axes[1]\\n\",\n    \"ax.loglog(opt_df['flops'], opt_df['params'], 'o', markersize=10, color='#2ecc71')\\n\",\n    \"ax.set_xlabel('FLOPs')\\n\",\n    \"ax.set_ylabel('Optimal Parameters')\\n\",\n    \"ax.set_title('Optimal Model Size')\\n\",\n    \"ax.grid(True, alpha=0.3)\\n\",\n    \"\\n\",\n    \"# Fit and show power law\\n\",\n    \"if len(opt_df) >= 2:\\n\",\n    \"    log_f = np.log10(opt_df['flops'])\\n\",\n    \"    log_p = np.log10(opt_df['params'])\\n\",\n    \"    slope, intercept = np.polyfit(log_f, log_p, 1)\\n\",\n    \"    fit_f = np.logspace(log_f.min() - 0.5, log_f.max() + 0.5, 100)\\n\",\n    \"    fit_p = 10**(intercept + slope * np.log10(fit_f))\\n\",\n    \"    ax.plot(fit_f, fit_p, 'r--', alpha=0.7, label=f'N ∝ C^{slope:.2f}')\\n\",\n    \"    ax.legend()\\n\",\n    \"\\n\",\n    \"# Plot 3: Optimal tokens vs compute (power law)\\n\",\n    \"ax = axes[2]\\n\",\n    \"ax.loglog(opt_df['flops'], opt_df['tokens'], 'o', markersize=10, color='#e74c3c')\\n\",\n    \"ax.set_xlabel('FLOPs')\\n\",\n    \"ax.set_ylabel('Optimal Tokens')\\n\",\n    \"ax.set_title('Optimal Training Tokens')\\n\",\n    \"ax.grid(True, alpha=0.3)\\n\",\n    \"\\n\",\n    \"# Fit and show power law\\n\",\n    \"if len(opt_df) >= 2:\\n\",\n    \"    log_f = np.log10(opt_df['flops'])\\n\",\n    \"    log_t = np.log10(opt_df['tokens'])\\n\",\n    \"    slope, intercept = np.polyfit(log_f, log_t, 1)\\n\",\n    \"    fit_f = np.logspace(log_f.min() - 0.5, log_f.max() + 0.5, 100)\\n\",\n    \"    fit_t = 10**(intercept + slope * np.log10(fit_f))\\n\",\n    \"    ax.plot(fit_f, fit_t, 'r--', alpha=0.7, label=f'D ∝ C^{slope:.2f}')\\n\",\n    \"    ax.legend()\\n\",\n    \"\\n\",\n    \"plt.tight_layout()\\n\",\n    \"plt.show()\\n\",\n    \"\\n\",\n    \"# Print the optimal points (from quadratic fits)\\n\",\n    \"print(\\\"\\\\nOptimal configurations (from quadratic fits):\\\")\\n\",\n    \"print(f\\\"{'FLOPs':<12} {'Eff Params':<15} {'Tokens':<15} {'Ratio':<10} {'Val BPB':<10}\\\")\\n\",\n    \"print(\\\"-\\\" * 65)\\n\",\n    \"for _, row in opt_df.iterrows():\\n\",\n    \"    print(f\\\"{row['flops']:<12.0e} {int(row['params']):<15,} {int(row['tokens']):<15,} {row['ratio']:<10.1f} {row['bpb']:<10.4f}\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# =============================================================================\\n\",\n    \"# Optimal Ratio Summary (from power law fits)\\n\",\n    \"# =============================================================================\\n\",\n    \"\\n\",\n    \"# From the power law fits: N ∝ C^a and D ∝ C^b\\n\",\n    \"# The ratio D/N ∝ C^(b-a). If a ≈ b, ratio is roughly constant.\\n\",\n    \"\\n\",\n    \"if len(opt_df) >= 2:\\n\",\n    \"    log_f = np.log10(opt_df['flops'])\\n\",\n    \"    log_p = np.log10(opt_df['params'])\\n\",\n    \"    log_t = np.log10(opt_df['tokens'])\\n\",\n    \"\\n\",\n    \"    # Fit power laws\\n\",\n    \"    slope_n, intercept_n = np.polyfit(log_f, log_p, 1)\\n\",\n    \"    slope_d, intercept_d = np.polyfit(log_f, log_t, 1)\\n\",\n    \"\\n\",\n    \"    # The ratio D/N at a reference compute (geometric mean of our budgets)\\n\",\n    \"    ref_flops = np.sqrt(opt_df['flops'].min() * opt_df['flops'].max())\\n\",\n    \"    log_ref = np.log10(ref_flops)\\n\",\n    \"\\n\",\n    \"    # Predicted optimal N and D at reference compute\\n\",\n    \"    pred_log_n = intercept_n + slope_n * log_ref\\n\",\n    \"    pred_log_d = intercept_d + slope_d * log_ref\\n\",\n    \"    optimal_ratio = 10**(pred_log_d - pred_log_n)\\n\",\n    \"\\n\",\n    \"    # Also compute from the fitted optimals directly (mean and std)\\n\",\n    \"    mean_ratio = opt_df['ratio'].mean()\\n\",\n    \"    std_ratio = opt_df['ratio'].std()\\n\",\n    \"\\n\",\n    \"    print(\\\"=\\\" * 60)\\n\",\n    \"    print(\\\"OPTIMAL RATIO SUMMARY\\\")\\n\",\n    \"    print(\\\"=\\\" * 60)\\n\",\n    \"    print(f\\\"\\\\nPower law exponents:\\\")\\n\",\n    \"    print(f\\\"  N ∝ C^{slope_n:.3f}\\\")\\n\",\n    \"    print(f\\\"  D ∝ C^{slope_d:.3f}\\\")\\n\",\n    \"    print(f\\\"  Ratio exponent (b-a): {slope_d - slope_n:.3f}  (should be ~0 if ratio is constant)\\\")\\n\",\n    \"    print(f\\\"\\\\nOptimal ratio (tokens per effective param):\\\")\\n\",\n    \"    print(f\\\"  From power law at C={ref_flops:.1e}: {optimal_ratio:.1f}\\\")\\n\",\n    \"    print(f\\\"  Mean across budgets: {mean_ratio:.1f} ± {std_ratio:.1f}\\\")\\n\",\n    \"    print(f\\\"  Chinchilla reference: 20\\\")\\n\",\n    \"    print(f\\\"\\\\nPer-budget ratios: {[f'{r:.1f}' for r in opt_df['ratio'].values]}\\\")\\n\",\n    \"else:\\n\",\n    \"    print(\\\"Need at least 2 flops budgets to compute power law fits\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"## Val BPB vs Depth and Ratio\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"fig, axes = plt.subplots(1, 2, figsize=(14, 5))\\n\",\n    \"\\n\",\n    \"# Plot 1: Val BPB vs Depth\\n\",\n    \"ax = axes[0]\\n\",\n    \"for flops in flops_budgets:\\n\",\n    \"    subset = df[df['flops_budget'] == flops].sort_values('depth')\\n\",\n    \"    ax.plot(subset['depth'], subset['val_bpb'], 'o-', label=f'{flops:.0e}')\\n\",\n    \"    # Mark the best (lowest)\\n\",\n    \"    best_idx = subset['val_bpb'].idxmin()\\n\",\n    \"    best = subset.loc[best_idx]\\n\",\n    \"    ax.scatter([best['depth']], [best['val_bpb']], s=100, zorder=5, edgecolors='black', linewidths=2)\\n\",\n    \"\\n\",\n    \"ax.set_xlabel('Depth')\\n\",\n    \"ax.set_ylabel('Val BPB (lower is better)')\\n\",\n    \"ax.set_title('Validation BPB vs Model Depth')\\n\",\n    \"ax.legend(title='FLOPs')\\n\",\n    \"ax.grid(True, alpha=0.3)\\n\",\n    \"\\n\",\n    \"# Plot 2: Val BPB vs Param:Data Ratio\\n\",\n    \"ax = axes[1]\\n\",\n    \"for flops in flops_budgets:\\n\",\n    \"    subset = df[df['flops_budget'] == flops].sort_values('param_data_ratio')\\n\",\n    \"    ax.plot(subset['param_data_ratio'], subset['val_bpb'], 'o-', label=f'{flops:.0e}')\\n\",\n    \"    best_idx = subset['val_bpb'].idxmin()\\n\",\n    \"    best = subset.loc[best_idx]\\n\",\n    \"    ax.scatter([best['param_data_ratio']], [best['val_bpb']], s=100, zorder=5, edgecolors='black', linewidths=2)\\n\",\n    \"\\n\",\n    \"ax.axvline(x=20, color='red', linestyle='--', alpha=0.5, label='Chinchilla (20)')\\n\",\n    \"ax.set_xlabel('Param:Data Ratio (tokens/param)')\\n\",\n    \"ax.set_ylabel('Val BPB (lower is better)')\\n\",\n    \"ax.set_title('Val BPB vs Param:Data Ratio')\\n\",\n    \"ax.legend(title='FLOPs')\\n\",\n    \"ax.grid(True, alpha=0.3)\\n\",\n    \"\\n\",\n    \"plt.tight_layout()\\n\",\n    \"plt.show()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \".venv\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.10.12\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 4\n}\n"
  },
  {
    "path": "nanochat/__init__.py",
    "content": ""
  },
  {
    "path": "nanochat/checkpoint_manager.py",
    "content": "\"\"\"\nUtilities for saving and loading model/optim/state checkpoints.\n\"\"\"\nimport os\nimport re\nimport glob\nimport json\nimport logging\nimport torch\n\nfrom nanochat.common import get_base_dir\nfrom nanochat.gpt import GPT, GPTConfig\nfrom nanochat.tokenizer import get_tokenizer\nfrom nanochat.common import setup_default_logging\n\n# Set up logging\nsetup_default_logging()\nlogger = logging.getLogger(__name__)\ndef log0(message):\n    if int(os.environ.get('RANK', 0)) == 0:\n        logger.info(message)\n\ndef _patch_missing_config_keys(model_config_kwargs):\n    \"\"\"Add default values for new config keys missing in old checkpoints.\"\"\"\n    # Old models were trained with full context (no sliding window)\n    if \"window_pattern\" not in model_config_kwargs:\n        model_config_kwargs[\"window_pattern\"] = \"L\"\n        log0(f\"Patching missing window_pattern in model config to 'L'\")\n\ndef _patch_missing_keys(model_data, model_config):\n    \"\"\"Add default values for new parameters that may be missing in old checkpoints.\"\"\"\n    n_layer = model_config.n_layer\n    # resid_lambdas defaults to 1.0 (identity scaling)\n    if \"resid_lambdas\" not in model_data:\n        model_data[\"resid_lambdas\"] = torch.ones(n_layer)\n        log0(f\"Patching missing resid_lambdas in model data to 1.0\")\n    # x0_lambdas defaults to 0.0 (disabled)\n    if \"x0_lambdas\" not in model_data:\n        model_data[\"x0_lambdas\"] = torch.zeros(n_layer)\n        log0(f\"Patching missing x0_lambdas in model data to 0.0\")\n\ndef save_checkpoint(checkpoint_dir, step, model_data, optimizer_data, meta_data, rank=0):\n    if rank == 0:\n        os.makedirs(checkpoint_dir, exist_ok=True)\n        # Save the model state parameters\n        model_path = os.path.join(checkpoint_dir, f\"model_{step:06d}.pt\")\n        torch.save(model_data, model_path)\n        logger.info(f\"Saved model parameters to: {model_path}\")\n        # Save the metadata dict as json\n        meta_path = os.path.join(checkpoint_dir, f\"meta_{step:06d}.json\")\n        with open(meta_path, \"w\", encoding=\"utf-8\") as f:\n            json.dump(meta_data, f, indent=2)\n        logger.info(f\"Saved metadata to: {meta_path}\")\n    # Note that optimizer state is sharded across ranks, so each rank must save its own.\n    if optimizer_data is not None:\n        os.makedirs(checkpoint_dir, exist_ok=True)\n        optimizer_path = os.path.join(checkpoint_dir, f\"optim_{step:06d}_rank{rank:d}.pt\")\n        torch.save(optimizer_data, optimizer_path)\n        logger.info(f\"Saved optimizer state to: {optimizer_path}\")\n\ndef load_checkpoint(checkpoint_dir, step, device, load_optimizer=False, rank=0):\n    # Load the model state\n    model_path = os.path.join(checkpoint_dir, f\"model_{step:06d}.pt\")\n    model_data = torch.load(model_path, map_location=device)\n    # Load the optimizer state if requested\n    optimizer_data = None\n    if load_optimizer:\n        optimizer_path = os.path.join(checkpoint_dir, f\"optim_{step:06d}_rank{rank:d}.pt\")\n        optimizer_data = torch.load(optimizer_path, map_location=device)\n    # Load the metadata\n    meta_path = os.path.join(checkpoint_dir, f\"meta_{step:06d}.json\")\n    with open(meta_path, \"r\", encoding=\"utf-8\") as f:\n        meta_data = json.load(f)\n    return model_data, optimizer_data, meta_data\n\n\ndef build_model(checkpoint_dir, step, device, phase):\n    \"\"\"\n    A bunch of repetitive code to build a model from a given checkpoint.\n    Returns:\n    - base model - uncompiled, not wrapped in DDP\n    - tokenizer\n    - meta data saved during base model training\n    \"\"\"\n    assert phase in [\"train\", \"eval\"], f\"Invalid phase: {phase}\"\n    model_data, optimizer_data, meta_data = load_checkpoint(checkpoint_dir, step, device, load_optimizer=False)\n    if device.type in {\"cpu\", \"mps\"}:\n        # Convert bfloat16 tensors to float for CPU inference\n        model_data = {\n            k: v.float() if v.dtype == torch.bfloat16 else v\n            for k, v in model_data.items()\n        }\n    # Hack: fix torch compile issue, which prepends all keys with _orig_mod.\n    model_data = {k.removeprefix(\"_orig_mod.\"): v for k, v in model_data.items()}\n    model_config_kwargs = meta_data[\"model_config\"]\n    _patch_missing_config_keys(model_config_kwargs)\n    log0(f\"Building model with config: {model_config_kwargs}\")\n    model_config = GPTConfig(**model_config_kwargs)\n    _patch_missing_keys(model_data, model_config)\n    with torch.device(\"meta\"):\n        model = GPT(model_config)\n    # Load the model state\n    model.to_empty(device=device)\n    model.init_weights() # note: this is dumb, but we need to init the rotary embeddings. TODO: fix model re-init\n    model.load_state_dict(model_data, strict=True, assign=True)\n    # Put the model in the right training phase / mode\n    if phase == \"eval\":\n        model.eval()\n    else:\n        model.train()\n    # Load the Tokenizer\n    tokenizer = get_tokenizer()\n    # Sanity check: compatibility between model and tokenizer\n    assert tokenizer.get_vocab_size() == model_config_kwargs[\"vocab_size\"], f\"Tokenizer vocab size {tokenizer.get_vocab_size()} does not match model config vocab size {model_config_kwargs['vocab_size']}\"\n    return model, tokenizer, meta_data\n\n\ndef find_largest_model(checkpoints_dir):\n    # attempt to guess the model tag: take the biggest model available\n    model_tags = [f for f in os.listdir(checkpoints_dir) if os.path.isdir(os.path.join(checkpoints_dir, f))]\n    if not model_tags:\n        raise FileNotFoundError(f\"No checkpoints found in {checkpoints_dir}\")\n    # 1) normally all model tags are of the form d<number>, try that first:\n    candidates = []\n    for model_tag in model_tags:\n        match = re.match(r\"d(\\d+)\", model_tag)\n        if match:\n            model_depth = int(match.group(1))\n            candidates.append((model_depth, model_tag))\n    if candidates:\n        candidates.sort(key=lambda x: x[0], reverse=True)\n        return candidates[0][1]\n    # 2) if that failed, take the most recently updated model:\n    model_tags.sort(key=lambda x: os.path.getmtime(os.path.join(checkpoints_dir, x)), reverse=True)\n    return model_tags[0]\n\n\ndef find_last_step(checkpoint_dir):\n    # Look into checkpoint_dir and find model_<step>.pt with the highest step\n    checkpoint_files = glob.glob(os.path.join(checkpoint_dir, \"model_*.pt\"))\n    if not checkpoint_files:\n        raise FileNotFoundError(f\"No checkpoints found in {checkpoint_dir}\")\n    last_step = int(max(os.path.basename(f).split(\"_\")[-1].split(\".\")[0] for f in checkpoint_files))\n    return last_step\n\n# -----------------------------------------------------------------------------\n# convenience functions that take into account nanochat's directory structure\n\ndef load_model_from_dir(checkpoints_dir, device, phase, model_tag=None, step=None):\n    if model_tag is None:\n        # guess the model tag by defaulting to the largest model\n        model_tag = find_largest_model(checkpoints_dir)\n        log0(f\"No model tag provided, guessing model tag: {model_tag}\")\n    checkpoint_dir = os.path.join(checkpoints_dir, model_tag)\n    if step is None:\n        # guess the step by defaulting to the last step\n        step = find_last_step(checkpoint_dir)\n    assert step is not None, f\"No checkpoints found in {checkpoint_dir}\"\n    # build the model\n    log0(f\"Loading model from {checkpoint_dir} with step {step}\")\n    model, tokenizer, meta_data = build_model(checkpoint_dir, step, device, phase)\n    return model, tokenizer, meta_data\n\ndef load_model(source, *args, **kwargs):\n    model_dir = {\n        \"base\": \"base_checkpoints\",\n        \"sft\": \"chatsft_checkpoints\",\n        \"rl\": \"chatrl_checkpoints\",\n    }[source]\n    base_dir = get_base_dir()\n    checkpoints_dir = os.path.join(base_dir, model_dir)\n    return load_model_from_dir(checkpoints_dir, *args, **kwargs)\n\ndef load_optimizer_state(source, device, rank, model_tag=None, step=None):\n    \"\"\"Load just the optimizer shard for a given rank, without re-loading the model.\"\"\"\n    model_dir = {\n        \"base\": \"base_checkpoints\",\n        \"sft\": \"chatsft_checkpoints\",\n        \"rl\": \"chatrl_checkpoints\",\n    }[source]\n    base_dir = get_base_dir()\n    checkpoints_dir = os.path.join(base_dir, model_dir)\n    if model_tag is None:\n        model_tag = find_largest_model(checkpoints_dir)\n    checkpoint_dir = os.path.join(checkpoints_dir, model_tag)\n    if step is None:\n        step = find_last_step(checkpoint_dir)\n    optimizer_path = os.path.join(checkpoint_dir, f\"optim_{step:06d}_rank{rank:d}.pt\")\n    if not os.path.exists(optimizer_path):\n        log0(f\"Optimizer checkpoint not found: {optimizer_path}\")\n        return None\n    log0(f\"Loading optimizer state from {optimizer_path}\")\n    optimizer_data = torch.load(optimizer_path, map_location=device)\n    return optimizer_data\n"
  },
  {
    "path": "nanochat/common.py",
    "content": "\"\"\"\nCommon utilities for nanochat.\n\"\"\"\n\nimport os\nimport re\nimport logging\nimport urllib.request\nimport torch\nimport torch.distributed as dist\nfrom filelock import FileLock\n\n# The dtype used for compute (matmuls, activations). Master weights stay fp32 for optimizer precision.\n# Linear layers cast their weights to this dtype in forward, replacing torch.amp.autocast.\n# Override with NANOCHAT_DTYPE env var: \"bfloat16\", \"float16\", \"float32\"\n_DTYPE_MAP = {\"bfloat16\": torch.bfloat16, \"float16\": torch.float16, \"float32\": torch.float32}\ndef _detect_compute_dtype():\n    env = os.environ.get(\"NANOCHAT_DTYPE\")\n    if env is not None:\n        return _DTYPE_MAP[env], f\"set via NANOCHAT_DTYPE={env}\"\n    if torch.cuda.is_available():\n        # bf16 requires SM 80+ (Ampere: A100, A10, etc.)\n        # Older GPUs like V100 (SM 70) and T4 (SM 75) only have fp16 tensor cores\n        capability = torch.cuda.get_device_capability()\n        if capability >= (8, 0):\n            return torch.bfloat16, f\"auto-detected: CUDA SM {capability[0]}{capability[1]} (bf16 supported)\"\n        # fp16 training requires GradScaler (not yet implemented), so fall back to fp32.\n        # Users can still force fp16 via NANOCHAT_DTYPE=float16 if they know what they're doing.\n        return torch.float32, f\"auto-detected: CUDA SM {capability[0]}{capability[1]} (pre-Ampere, bf16 not supported, using fp32)\"\n    return torch.float32, \"auto-detected: no CUDA (CPU/MPS)\"\nCOMPUTE_DTYPE, COMPUTE_DTYPE_REASON = _detect_compute_dtype()\n\nclass ColoredFormatter(logging.Formatter):\n    \"\"\"Custom formatter that adds colors to log messages.\"\"\"\n    # ANSI color codes\n    COLORS = {\n        'DEBUG': '\\033[36m',    # Cyan\n        'INFO': '\\033[32m',     # Green\n        'WARNING': '\\033[33m',  # Yellow\n        'ERROR': '\\033[31m',    # Red\n        'CRITICAL': '\\033[35m', # Magenta\n    }\n    RESET = '\\033[0m'\n    BOLD = '\\033[1m'\n    def format(self, record):\n        # Add color to the level name\n        levelname = record.levelname\n        if levelname in self.COLORS:\n            record.levelname = f\"{self.COLORS[levelname]}{self.BOLD}{levelname}{self.RESET}\"\n        # Format the message\n        message = super().format(record)\n        # Add color to specific parts of the message\n        if levelname == 'INFO':\n            # Highlight numbers and percentages\n            message = re.sub(r'(\\d+\\.?\\d*\\s*(?:GB|MB|%|docs))', rf'{self.BOLD}\\1{self.RESET}', message)\n            message = re.sub(r'(Shard \\d+)', rf'{self.COLORS[\"INFO\"]}{self.BOLD}\\1{self.RESET}', message)\n        return message\n\ndef setup_default_logging():\n    handler = logging.StreamHandler()\n    handler.setFormatter(ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n    logging.basicConfig(\n        level=logging.INFO,\n        handlers=[handler]\n    )\n\nsetup_default_logging()\nlogger = logging.getLogger(__name__)\n\ndef get_base_dir():\n    # co-locate nanochat intermediates with other cached data in ~/.cache (by default)\n    if os.environ.get(\"NANOCHAT_BASE_DIR\"):\n        nanochat_dir = os.environ.get(\"NANOCHAT_BASE_DIR\")\n    else:\n        home_dir = os.path.expanduser(\"~\")\n        cache_dir = os.path.join(home_dir, \".cache\")\n        nanochat_dir = os.path.join(cache_dir, \"nanochat\")\n    os.makedirs(nanochat_dir, exist_ok=True)\n    return nanochat_dir\n\ndef download_file_with_lock(url, filename, postprocess_fn=None):\n    \"\"\"\n    Downloads a file from a URL to a local path in the base directory.\n    Uses a lock file to prevent concurrent downloads among multiple ranks.\n    \"\"\"\n    base_dir = get_base_dir()\n    file_path = os.path.join(base_dir, filename)\n    lock_path = file_path + \".lock\"\n\n    if os.path.exists(file_path):\n        return file_path\n\n    with FileLock(lock_path):\n        # Only a single rank can acquire this lock\n        # All other ranks block until it is released\n\n        # Recheck after acquiring lock\n        if os.path.exists(file_path):\n            return file_path\n\n        # Download the content as bytes\n        print(f\"Downloading {url}...\")\n        with urllib.request.urlopen(url) as response:\n            content = response.read() # bytes\n\n        # Write to local file\n        with open(file_path, 'wb') as f:\n            f.write(content)\n        print(f\"Downloaded to {file_path}\")\n\n        # Run the postprocess function if provided\n        if postprocess_fn is not None:\n            postprocess_fn(file_path)\n\n    return file_path\n\ndef print0(s=\"\",**kwargs):\n    ddp_rank = int(os.environ.get('RANK', 0))\n    if ddp_rank == 0:\n        print(s, **kwargs)\n\ndef print_banner():\n    # Cool DOS Rebel font ASCII banner made with https://manytools.org/hacker-tools/ascii-banner/\n    banner = \"\"\"\n                                                       █████                █████\n                                                      ░░███                ░░███\n     ████████    ██████   ████████    ██████   ██████  ░███████    ██████  ███████\n    ░░███░░███  ░░░░░███ ░░███░░███  ███░░███ ███░░███ ░███░░███  ░░░░░███░░░███░\n     ░███ ░███   ███████  ░███ ░███ ░███ ░███░███ ░░░  ░███ ░███   ███████  ░███\n     ░███ ░███  ███░░███  ░███ ░███ ░███ ░███░███  ███ ░███ ░███  ███░░███  ░███ ███\n     ████ █████░░████████ ████ █████░░██████ ░░██████  ████ █████░░███████  ░░█████\n    ░░░░ ░░░░░  ░░░░░░░░ ░░░░ ░░░░░  ░░░░░░   ░░░░░░  ░░░░ ░░░░░  ░░░░░░░░   ░░░░░\n    \"\"\"\n    print0(banner)\n\ndef is_ddp_requested() -> bool:\n    \"\"\"\n    True if launched by torchrun (env present), even before init.\n    Used to decide whether we *should* initialize a PG.\n    \"\"\"\n    return all(k in os.environ for k in (\"RANK\", \"LOCAL_RANK\", \"WORLD_SIZE\"))\n\ndef is_ddp_initialized() -> bool:\n    \"\"\"\n    True if torch.distributed is available and the process group is initialized.\n    Used at cleanup to avoid destroying a non-existent PG.\n    \"\"\"\n    return dist.is_available() and dist.is_initialized()\n\ndef get_dist_info():\n    if is_ddp_requested():\n        # We rely on torchrun's env to decide if we SHOULD init.\n        # (Initialization itself happens in compute init.)\n        assert all(var in os.environ for var in ['RANK', 'LOCAL_RANK', 'WORLD_SIZE'])\n        ddp_rank = int(os.environ['RANK'])\n        ddp_local_rank = int(os.environ['LOCAL_RANK'])\n        ddp_world_size = int(os.environ['WORLD_SIZE'])\n        return True, ddp_rank, ddp_local_rank, ddp_world_size\n    else:\n        return False, 0, 0, 1\n\ndef autodetect_device_type():\n    # prefer to use CUDA if available, otherwise use MPS, otherwise fallback on CPU\n    if torch.cuda.is_available():\n        device_type = \"cuda\"\n    elif torch.backends.mps.is_available():\n        device_type = \"mps\"\n    else:\n        device_type = \"cpu\"\n    print0(f\"Autodetected device type: {device_type}\")\n    return device_type\n\ndef compute_init(device_type=\"cuda\"): # cuda|cpu|mps\n    \"\"\"Basic initialization that we keep doing over and over, so make common.\"\"\"\n\n    assert device_type in [\"cuda\", \"mps\", \"cpu\"], \"Invalid device type atm\"\n    if device_type == \"cuda\":\n        assert torch.cuda.is_available(), \"Your PyTorch installation is not configured for CUDA but device_type is 'cuda'\"\n    if device_type == \"mps\":\n        assert torch.backends.mps.is_available(), \"Your PyTorch installation is not configured for MPS but device_type is 'mps'\"\n\n    # Reproducibility\n    # Note that we set the global seeds here, but most of the code uses explicit rng objects.\n    # The only place where global rng might be used is nn.Module initialization of the model weights.\n    torch.manual_seed(42)\n    if device_type == \"cuda\":\n        torch.cuda.manual_seed(42)\n    # skipping full reproducibility for now, possibly investigate slowdown later\n    # torch.use_deterministic_algorithms(True)\n\n    # Precision\n    if device_type == \"cuda\":\n        torch.set_float32_matmul_precision(\"high\") # uses tf32 instead of fp32 for matmuls, see https://docs.pytorch.org/docs/stable/generated/torch.set_float32_matmul_precision.html\n\n    # Distributed setup: Distributed Data Parallel (DDP), optional, and requires CUDA\n    is_ddp_requested, ddp_rank, ddp_local_rank, ddp_world_size = get_dist_info()\n    if is_ddp_requested and device_type == \"cuda\":\n        device = torch.device(\"cuda\", ddp_local_rank)\n        torch.cuda.set_device(device)  # make \"cuda\" default to this device\n        dist.init_process_group(backend=\"nccl\", device_id=device)\n        dist.barrier()\n    else:\n        device = torch.device(device_type) # mps|cpu\n\n    if ddp_rank == 0:\n        logger.info(f\"Distributed world size: {ddp_world_size}\")\n\n    return is_ddp_requested, ddp_rank, ddp_local_rank, ddp_world_size, device\n\ndef compute_cleanup():\n    \"\"\"Companion function to compute_init, to clean things up before script exit\"\"\"\n    if is_ddp_initialized():\n        dist.destroy_process_group()\n\nclass DummyWandb:\n    \"\"\"Useful if we wish to not use wandb but have all the same signatures\"\"\"\n    def __init__(self):\n        pass\n    def log(self, *args, **kwargs):\n        pass\n    def finish(self):\n        pass\n\n# hardcoded BF16 peak flops for various GPUs\n# inspired by torchtitan: https://github.com/pytorch/torchtitan/blob/main/torchtitan/tools/utils.py\n# and PR: https://github.com/karpathy/nanochat/pull/147\ndef get_peak_flops(device_name: str) -> float:\n    name = device_name.lower()\n\n    # Table order matters: more specific patterns first.\n    _PEAK_FLOPS_TABLE = (\n        # NVIDIA Blackwell\n        ([\"gb200\"], 2.5e15),\n        ([\"grace blackwell\"], 2.5e15),\n        ([\"b200\"], 2.25e15),\n        ([\"b100\"], 1.8e15),\n        # NVIDIA Hopper\n        ([\"h200\", \"nvl\"], 836e12),\n        ([\"h200\", \"pcie\"], 836e12),\n        ([\"h200\"], 989e12),\n        ([\"h100\", \"nvl\"], 835e12),\n        ([\"h100\", \"pcie\"], 756e12),\n        ([\"h100\"], 989e12),\n        ([\"h800\", \"nvl\"], 989e12),\n        ([\"h800\"], 756e12),\n        # NVIDIA Ampere data center\n        ([\"a100\"], 312e12),\n        ([\"a800\"], 312e12),\n        ([\"a40\"], 149.7e12),\n        ([\"a30\"], 165e12),\n        # NVIDIA Ada data center\n        ([\"l40s\"], 362e12),\n        ([\"l40-s\"], 362e12),\n        ([\"l40 s\"], 362e12),\n        ([\"l4\"], 121e12),\n        # AMD CDNA accelerators\n        ([\"mi355\"], 2.5e15),\n        ([\"mi325\"], 1.3074e15),\n        ([\"mi300x\"], 1.3074e15),\n        ([\"mi300a\"], 980.6e12),\n        ([\"mi250x\"], 383e12),\n        ([\"mi250\"], 362.1e12),\n        # Consumer RTX\n        ([\"5090\"], 209.5e12),\n        ([\"4090\"], 165.2e12),\n        ([\"3090\"], 71e12),\n    )\n    for patterns, flops in _PEAK_FLOPS_TABLE:\n        if all(p in name for p in patterns):\n            return flops\n    if \"data center gpu max 1550\" in name:\n        # Ponte Vecchio (PVC) - dynamic based on compute units\n        max_comp_units = torch.xpu.get_device_properties(\"xpu\").max_compute_units\n        return 512 * max_comp_units * 1300 * 10**6\n\n    # Unknown GPU - return inf so MFU shows as 0% rather than a wrong guess\n    logger.warning(f\"Peak flops undefined for: {device_name}, MFU will show as 0%\")\n    return float('inf')\n"
  },
  {
    "path": "nanochat/core_eval.py",
    "content": "\"\"\"\nFunctions for evaluating the CORE metric, as described in the DCLM paper.\nhttps://arxiv.org/abs/2406.11794\n\nTODOs:\n- All tasks ~match except for squad. We get 31% reference is 37%. Figure out why.\n\"\"\"\nimport random\n\nfrom jinja2 import Template\nimport torch\nimport torch.distributed as dist\n\n# -----------------------------------------------------------------------------\n# Prompt rendering utilities\n\ndef render_prompts_mc(item, continuation_delimiter, fewshot_examples=None):\n    \"\"\"Render complete prompts for a multiple choice question\"\"\"\n    template_str = \"\"\"\n{%- for example in fewshot_examples -%}\n{{ example.query }}{{ continuation_delimiter }}{{ example.choices[example.gold] }}\n\n{% endfor -%}\n{{ item.query }}{{ continuation_delimiter }}{{ choice }}\"\"\".strip()\n    template = Template(template_str)\n    fewshot_examples = fewshot_examples or []\n    context = {\n        'fewshot_examples': fewshot_examples,\n        'continuation_delimiter': continuation_delimiter,\n        'item': item\n    }\n    prompts = [template.render(choice=choice, **context) for choice in item['choices']]\n    return prompts\n\n\ndef render_prompts_schema(item, continuation_delimiter, fewshot_examples=None):\n    \"\"\"Render complete prompts for a schema question\"\"\"\n    template_str = \"\"\"\n{%- for example in fewshot_examples -%}\n{{ example.context_options[example.gold] }}{{ continuation_delimiter }}{{ example.continuation }}\n\n{% endfor -%}\n{{ context }}{{ continuation_delimiter }}{{ item.continuation }}\"\"\".strip()\n    template = Template(template_str)\n    fewshot_examples = fewshot_examples or []\n    context = {\n        'fewshot_examples': fewshot_examples,\n        'continuation_delimiter': continuation_delimiter,\n        'item': item\n    }\n    prompts = [template.render(context=context_option, **context)\n               for context_option in item['context_options']]\n    return prompts\n\n\ndef render_prompts_lm(item, continuation_delimiter, fewshot_examples=None):\n    \"\"\"\n    Render complete prompt for a language modeling task.\n    Notice that we manually trim the context in the template,\n    which in some datasets seems to have trailing whitespace (which we don't want).\n    \"\"\"\n    template_str = \"\"\"\n{%- for example in fewshot_examples -%}\n{{ example.context | trim }}{{ continuation_delimiter }}{{ example.continuation }}\n\n{% endfor -%}\n{{ item.context | trim }}{{ continuation_delimiter }}{% if include_continuation %}{{ item.continuation }}{% endif %}\"\"\".strip()\n    template = Template(template_str)\n    fewshot_examples = fewshot_examples or []\n    context = {\n        'fewshot_examples': fewshot_examples,\n        'continuation_delimiter': continuation_delimiter,\n        'item': item\n    }\n    # Return two prompts: without and with the continuation\n    prompt_without = template.render(include_continuation=False, **context)\n    prompt_with = template.render(include_continuation=True, **context)\n    # Due to the way the data seems to be stored, I think I need to strip in the case of LM here.\n    # Otherwise we may get trailing whitespaces in prompt_without (which get absorbed into the next\n    # token in prompt_with), meaning we don't get a nice and clean prefix in the token space\n    # to detect the final continuation. Tokenizers...\n    prompt_without = prompt_without.strip()\n    return [prompt_without, prompt_with]\n\n\ndef find_common_length(token_sequences, direction='left'):\n    \"\"\"\n    Find the length of the common prefix or suffix across token sequences\n    - direction: 'left' for prefix, 'right' for suffix\n    \"\"\"\n    min_len = min(len(seq) for seq in token_sequences)\n    indices = {\n        'left': range(min_len),\n        'right': range(-1, -min_len-1, -1)\n    }[direction]\n    # Find the first position where the token sequences differ\n    for i, idx in enumerate(indices):\n        token = token_sequences[0][idx]\n        if not all(seq[idx] == token for seq in token_sequences):\n            return i\n    return min_len\n\n\ndef stack_sequences(tokens, pad_token_id):\n    \"\"\"Stack up a list of token sequences, pad to longest on the right\"\"\"\n    bsz, seq_len = len(tokens), max(len(x) for x in tokens)\n    input_ids = torch.full((bsz, seq_len), pad_token_id, dtype=torch.long)\n    for i, x in enumerate(tokens):\n        input_ids[i, :len(x)] = torch.tensor(x, dtype=torch.long)\n    return input_ids\n\n\ndef batch_sequences_mc(tokenizer, prompts):\n    # In multiple choice, contexts are the same but the continuation is different (common prefix)\n    tokens = tokenizer(prompts, prepend=tokenizer.get_bos_token_id())\n    # figure out the start and end of each continuation\n    answer_start_idx = find_common_length(tokens, direction='left')\n    start_indices = [answer_start_idx] * len(prompts)\n    end_indices = [len(x) for x in tokens]\n    return tokens, start_indices, end_indices\n\n\ndef batch_sequences_schema(tokenizer, prompts):\n    # In schema tasks, contexts vary but continuation is the same (common suffix)\n    tokens = tokenizer(prompts, prepend=tokenizer.get_bos_token_id())\n    # figure out the start and end of each context\n    suffix_length = find_common_length(tokens, direction='right')\n    end_indices = [len(x) for x in tokens]\n    start_indices = [ei - suffix_length for ei in end_indices]\n    return tokens, start_indices, end_indices\n\n\ndef batch_sequences_lm(tokenizer, prompts):\n    # In LM tasks, we have two prompts: without and with continuation\n    tokens = tokenizer(prompts, prepend=tokenizer.get_bos_token_id())\n    tokens_without, tokens_with = tokens\n    start_idx, end_idx = len(tokens_without), len(tokens_with)\n    assert start_idx < end_idx, \"prompt without is supposed to be a prefix of prompt with\"\n    assert tokens_without == tokens_with[:start_idx], \"prompt without is supposed to be a prefix of prompt with\"\n    # we only need the with continuation prompt in the LM task, i.e. batch size of 1\n    return [tokens_with], [start_idx], [end_idx]\n\n\n@torch.no_grad()\ndef forward_model(model, input_ids):\n    \"\"\"\n    Take BxT tensor of token ids, return BxT tensor of losses and argmax predictions.\n    The last column of losses is set to nan because we don't have autoregressive targets there.\n    \"\"\"\n    batch_size, seq_len = input_ids.size()\n    outputs = model(input_ids)\n    # Roll the tensor to the left by one position to get the (autoregressive) target ids\n    target_ids = torch.roll(input_ids, shifts=-1, dims=1)\n    # Calculate cross entropy at all positions\n    losses = torch.nn.functional.cross_entropy(\n        outputs.view(batch_size * seq_len, -1),\n        target_ids.view(batch_size * seq_len),\n        reduction='none'\n    ).view(batch_size, seq_len)\n    # Set the last column to be nan because there is no autoregressive loss there\n    losses[:, -1] = float('nan')\n    # Get the argmax predictions at each position\n    predictions = outputs.argmax(dim=-1)\n    return losses, predictions\n\n\n@torch.no_grad()\ndef evaluate_example(idx, model, tokenizer, data, device, task_meta):\n    \"\"\"Evaluate a single example, return True if correct, False otherwise\"\"\"\n    item = data[idx]\n    task_type = task_meta['task_type']\n    num_fewshot = task_meta['num_fewshot']\n    continuation_delimiter = task_meta['continuation_delimiter']\n\n    # Sample few-shot examples (excluding current item)\n    fewshot_examples = []\n    if num_fewshot > 0:\n        rng = random.Random(1234 + idx)\n        available_indices = [i for i in range(len(data)) if i != idx]\n        fewshot_indices = rng.sample(available_indices, num_fewshot)\n        fewshot_examples = [data[i] for i in fewshot_indices]\n\n    # Render prompts and batch sequences based on task type\n    if task_type == 'multiple_choice':\n        prompts = render_prompts_mc(item, continuation_delimiter, fewshot_examples)\n        tokens, start_idxs, end_idxs = batch_sequences_mc(tokenizer, prompts)\n    elif task_type == 'schema':\n        prompts = render_prompts_schema(item, continuation_delimiter, fewshot_examples)\n        tokens, start_idxs, end_idxs = batch_sequences_schema(tokenizer, prompts)\n    elif task_type == 'language_modeling':\n        prompts = render_prompts_lm(item, continuation_delimiter, fewshot_examples)\n        tokens, start_idxs, end_idxs = batch_sequences_lm(tokenizer, prompts)\n    else:\n        raise ValueError(f\"Unsupported task type: {task_type}\")\n\n    # Some models can't forward sequences beyond a certain length (e.g. GPT-2)\n    # In these cases, we have to truncate sequences to max length and adjust the indices\n    if hasattr(model, 'max_seq_len') and model.max_seq_len is not None:\n        max_tokens = model.max_seq_len\n        new_tokens, new_start_idxs, new_end_idxs = [], [], []\n        for t, s, e in zip(tokens, start_idxs, end_idxs):\n            if len(t) > max_tokens:\n                num_to_crop = len(t) - max_tokens\n                new_tokens.append(t[-max_tokens:]) # take the last max_tokens tokens\n                new_start_idxs.append(s - num_to_crop) # shift the indices down\n                new_end_idxs.append(e - num_to_crop)\n                assert s - num_to_crop >= 0, \"this should never happen right?\"\n                assert e - num_to_crop >= 0, \"this should never happen right?\"\n            else:\n                new_tokens.append(t) # keep unchanged\n                new_start_idxs.append(s)\n                new_end_idxs.append(e)\n        tokens, start_idxs, end_idxs = new_tokens, new_start_idxs, new_end_idxs\n\n    # Stack up all the sequences into a batch\n    pad_token_id = tokenizer.get_bos_token_id() # use BOS as pad token is ok\n    input_ids = stack_sequences(tokens, pad_token_id)\n    input_ids = input_ids.to(device)\n\n    # Forward the model, get the autoregressive loss and argmax prediction at each token\n    losses, predictions = forward_model(model, input_ids)\n\n    # See if the losses/predictions come out correctly\n    if task_type == 'language_modeling':\n        # language modeling task is currently always batch size 1\n        si = start_idxs[0]\n        ei = end_idxs[0]\n        # predictions[i] predict input_ids[i+1] autoregressively\n        predicted_tokens = predictions[0, si-1:ei-1]\n        actual_tokens = input_ids[0, si:ei]\n        is_correct = torch.all(predicted_tokens == actual_tokens).item()\n    elif task_type in ['multiple_choice', 'schema']:\n        # For MC/schema: find the option with lowest average loss\n        mean_losses = [losses[i, si-1:ei-1].mean().item()\n                        for i, (si, ei) in enumerate(zip(start_idxs, end_idxs))]\n        pred_idx = mean_losses.index(min(mean_losses))\n        is_correct = pred_idx == item['gold']\n    else:\n        raise ValueError(f\"Unsupported task type: {task_type}\")\n\n    return is_correct\n\n\ndef evaluate_task(model, tokenizer, data, device, task_meta):\n    \"\"\"\n    This function is responsible for evaluating one task across many examples.\n    It also handles dispatch to all processes if the script is run with torchrun.\n    \"\"\"\n    rank = dist.get_rank() if dist.is_initialized() else 0\n    world_size = dist.get_world_size() if dist.is_initialized() else 1\n    correct = torch.zeros(len(data), dtype=torch.float32, device=device)\n    # stride the examples to each rank\n    for idx in range(rank, len(data), world_size):\n        is_correct = evaluate_example(idx, model, tokenizer, data, device, task_meta)\n        correct[idx] = float(is_correct)\n    # sync results across all the processes if running distributed\n    if world_size > 1:\n        dist.barrier()\n        dist.all_reduce(correct, op=dist.ReduceOp.SUM)\n    # compute the mean\n    mean_correct = correct.mean().item()\n    return mean_correct\n"
  },
  {
    "path": "nanochat/dataloader.py",
    "content": "\"\"\"\nDistributed dataloaders for pretraining.\n\nBOS-aligned bestfit:\n   - Every row starts with BOS token\n   - Documents packed using best-fit algorithm to minimize cropping\n   - When no document fits remaining space, crops a document to fill exactly\n   - 100% utilization (no padding), ~35% tokens cropped at T=2048\n\nCompared to the original tokenizing_distributed_data_loader:\nBOS-aligned loses ~35% of tokens to cropping, but ensures that\nthere are fewer \"confusing\" tokens in the train/val batches as every token can\nnow attend back to the BOS token and sees the full context of the document.\n\nFallback to the original if you have very limited data AND long documents:\nhttps://github.com/karpathy/nanochat/blob/3c3a3d7/nanochat/dataloader.py#L78-L117\n\"\"\"\n\nimport torch\nimport pyarrow.parquet as pq\n\nfrom nanochat.common import get_dist_info\nfrom nanochat.dataset import list_parquet_files\n\ndef _document_batches(split, resume_state_dict, tokenizer_batch_size):\n    \"\"\"\n    Infinite iterator over document batches (list of text strings) from parquet files.\n\n    Handles DDP sharding and approximate resume. Each yield is (text_batch, (pq_idx, rg_idx, epoch))\n    where text_batch is a list of document strings, indices track position for resumption,\n    and epoch counts how many times we've cycled through the dataset (starts at 1).\n    \"\"\"\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size = get_dist_info()\n\n    warn_on_legacy = ddp_rank == 0 and split == \"train\" # rank 0 on train split will warn on legacy\n    parquet_paths = list_parquet_files(warn_on_legacy=warn_on_legacy)\n    assert len(parquet_paths) != 0, \"No dataset parquet files found, did you run dataset.py?\"\n    parquet_paths = parquet_paths[:-1] if split == \"train\" else parquet_paths[-1:]\n\n    resume_pq_idx = resume_state_dict[\"pq_idx\"] if resume_state_dict is not None else 0\n    resume_rg_idx = resume_state_dict[\"rg_idx\"] if resume_state_dict is not None else None\n    resume_epoch = resume_state_dict.get(\"epoch\", 1) if resume_state_dict is not None else 1\n    first_pass = True\n    pq_idx = resume_pq_idx\n    epoch = resume_epoch\n\n    while True:  # iterate infinitely (multi-epoch)\n        pq_idx = resume_pq_idx if first_pass else 0\n        while pq_idx < len(parquet_paths):\n            filepath = parquet_paths[pq_idx]\n            pf = pq.ParquetFile(filepath)\n            # Start from resume point if resuming on same file, otherwise from DDP rank\n            if first_pass and (resume_rg_idx is not None) and (pq_idx == resume_pq_idx):\n                base_idx = resume_rg_idx // ddp_world_size\n                base_idx += 1  # advance by 1 so we don't repeat data after resuming\n                rg_idx = base_idx * ddp_world_size + ddp_rank\n                if rg_idx >= pf.num_row_groups:\n                    pq_idx += 1\n                    continue\n                resume_rg_idx = None  # only do this once\n            else:\n                rg_idx = ddp_rank\n            while rg_idx < pf.num_row_groups:\n                rg = pf.read_row_group(rg_idx)\n                batch = rg.column('text').to_pylist()\n                for i in range(0, len(batch), tokenizer_batch_size):\n                    yield batch[i:i+tokenizer_batch_size], (pq_idx, rg_idx, epoch)\n                rg_idx += ddp_world_size\n            pq_idx += 1\n        first_pass = False\n        epoch += 1\n\n\ndef tokenizing_distributed_data_loader_with_state_bos_bestfit(\n    tokenizer, B, T, split,\n    tokenizer_threads=4, tokenizer_batch_size=128,\n    device=\"cuda\", resume_state_dict=None,\n    buffer_size=1000\n):\n    \"\"\"\n    BOS-aligned dataloader with Best-Fit Cropping.\n\n    Reduces token waste compared to simple greedy cropping by searching a buffer\n    for documents that fit well, while maintaining 100% utilization (no padding).\n\n    Algorithm for each row:\n    1. From buffered docs, pick the LARGEST doc that fits entirely\n    2. Repeat until no doc fits\n    3. When nothing fits, crop a doc to fill remaining space exactly\n\n    Key properties:\n    - Every row starts with BOS\n    - 100% utilization (no padding, every token is trained on)\n    - Approximately 35% of all tokens are discarded due to cropping\n    \"\"\"\n    assert split in [\"train\", \"val\"], \"split must be 'train' or 'val'\"\n\n    row_capacity = T + 1\n    batches = _document_batches(split, resume_state_dict, tokenizer_batch_size)\n    bos_token = tokenizer.get_bos_token_id()\n    doc_buffer = []\n    pq_idx, rg_idx, epoch = 0, 0, 1\n\n    def refill_buffer():\n        nonlocal pq_idx, rg_idx, epoch\n        doc_batch, (pq_idx, rg_idx, epoch) = next(batches)\n        token_lists = tokenizer.encode(doc_batch, prepend=bos_token, num_threads=tokenizer_threads)\n        for tokens in token_lists:\n            doc_buffer.append(tokens)\n\n    # Pre-allocate buffers once: layout is [inputs (B*T) | targets (B*T)]\n    # This gives us contiguous views and a single HtoD transfer\n    use_cuda = device == \"cuda\"\n    row_buffer = torch.empty((B, row_capacity), dtype=torch.long) # for building rows without creating Python lists\n    cpu_buffer = torch.empty(2 * B * T, dtype=torch.long, pin_memory=use_cuda) # staging area (CPU)\n    gpu_buffer = torch.empty(2 * B * T, dtype=torch.long, device=device) # on-device buffer\n    cpu_inputs = cpu_buffer[:B * T].view(B, T) # a few views into these buffers just for convenience\n    cpu_targets = cpu_buffer[B * T:].view(B, T)\n    inputs = gpu_buffer[:B * T].view(B, T)\n    targets = gpu_buffer[B * T:].view(B, T)\n\n    while True:\n        for row_idx in range(B):\n            pos = 0\n            while pos < row_capacity:\n                # Ensure buffer has documents\n                while len(doc_buffer) < buffer_size:\n                    refill_buffer()\n\n                remaining = row_capacity - pos\n\n                # Find largest doc that fits entirely\n                best_idx = -1\n                best_len = 0\n                for i, doc in enumerate(doc_buffer):\n                    doc_len = len(doc)\n                    if doc_len <= remaining and doc_len > best_len:\n                        best_idx = i\n                        best_len = doc_len\n\n                if best_idx >= 0:\n                    doc = doc_buffer.pop(best_idx)\n                    doc_len = len(doc)\n                    row_buffer[row_idx, pos:pos + doc_len] = torch.tensor(doc, dtype=torch.long)\n                    pos += doc_len\n                else:\n                    # No doc fits - crop shortest in buffer to fill remaining and minimize waste\n                    shortest_idx = min(range(len(doc_buffer)), key=lambda i: len(doc_buffer[i]))\n                    doc = doc_buffer.pop(shortest_idx)\n                    row_buffer[row_idx, pos:pos + remaining] = torch.tensor(doc[:remaining], dtype=torch.long)\n                    pos += remaining\n\n        # Copy to pinned CPU buffer, then single HtoD transfer\n        cpu_inputs.copy_(row_buffer[:, :-1])\n        cpu_targets.copy_(row_buffer[:, 1:])\n\n        state_dict = {\"pq_idx\": pq_idx, \"rg_idx\": rg_idx, \"epoch\": epoch}\n\n        # Single HtoD copy into persistent GPU buffer and yield\n        gpu_buffer.copy_(cpu_buffer, non_blocking=use_cuda)\n        yield inputs, targets, state_dict\n\ndef tokenizing_distributed_data_loader_bos_bestfit(*args, **kwargs):\n    \"\"\"Helper that omits state_dict from yields.\"\"\"\n    for inputs, targets, state_dict in tokenizing_distributed_data_loader_with_state_bos_bestfit(*args, **kwargs):\n        yield inputs, targets\n"
  },
  {
    "path": "nanochat/dataset.py",
    "content": "\"\"\"\nThe base/pretraining dataset is a set of parquet files.\nThis file contains utilities for:\n- iterating over the parquet files and yielding documents from it\n- download the files on demand if they are not on disk\n\nFor details of how the dataset was prepared, see `repackage_data_reference.py`.\n\"\"\"\n\nimport os\nimport argparse\nimport time\nimport requests\nimport pyarrow.parquet as pq\nfrom multiprocessing import Pool\n\nfrom nanochat.common import get_base_dir\n\n# -----------------------------------------------------------------------------\n# The specifics of the current pretraining dataset\n\n# The URL on the internet where the data is hosted and downloaded from on demand\nBASE_URL = \"https://huggingface.co/datasets/karpathy/climbmix-400b-shuffle/resolve/main\"\nMAX_SHARD = 6542 # the last datashard is shard_06542.parquet\nindex_to_filename = lambda index: f\"shard_{index:05d}.parquet\" # format of the filenames\nbase_dir = get_base_dir()\nDATA_DIR = os.path.join(base_dir, \"base_data_climbmix\")\n\n# -----------------------------------------------------------------------------\n# These functions are useful utilities to other modules, can/should be imported\n\ndef list_parquet_files(data_dir=None, warn_on_legacy=False):\n    \"\"\" Looks into a data dir and returns full paths to all parquet files. \"\"\"\n    data_dir = DATA_DIR if data_dir is None else data_dir\n\n    # Legacy-supporting code due to the upgrade from FinewebEdu-100B to ClimbMix-400B\n    # This code will eventually be deleted.\n    if not os.path.exists(data_dir):\n        if warn_on_legacy:\n            print()\n            print(\"=\" * 80)\n            print(\"  WARNING: DATASET UPGRADE REQUIRED\")\n            print(\"=\" * 80)\n            print()\n            print(f\"  Could not find: {data_dir}\")\n            print()\n            print(\"  nanochat recently switched from FinewebEdu-100B to ClimbMix-400B.\")\n            print(\"  Everyone who does `git pull` as of March 4, 2026 is expected to see this message.\")\n            print(\"  To upgrade to the new ClimbMix-400B dataset, run these two commands:\")\n            print()\n            print(\"    python -m nanochat.dataset -n 170     # download ~170 shards, enough for GPT-2, adjust as desired\")\n            print(\"    python -m scripts.tok_train           # re-train tokenizer on new ClimbMix data\")\n            print()\n            print(\"  For now, falling back to your old FinewebEdu-100B dataset...\")\n            print(\"=\" * 80)\n            print()\n        # attempt a fallback to the legacy data directory\n        data_dir = os.path.join(base_dir, \"base_data\")\n\n    parquet_files = sorted([\n        f for f in os.listdir(data_dir)\n        if f.endswith('.parquet') and not f.endswith('.tmp')\n    ])\n    parquet_paths = [os.path.join(data_dir, f) for f in parquet_files]\n    return parquet_paths\n\ndef parquets_iter_batched(split, start=0, step=1):\n    \"\"\"\n    Iterate through the dataset, in batches of underlying row_groups for efficiency.\n    - split can be \"train\" or \"val\". the last parquet file will be val.\n    - start/step are useful for skipping rows in DDP. e.g. start=rank, step=world_size\n    \"\"\"\n    assert split in [\"train\", \"val\"], \"split must be 'train' or 'val'\"\n    parquet_paths = list_parquet_files()\n    parquet_paths = parquet_paths[:-1] if split == \"train\" else parquet_paths[-1:]\n    for filepath in parquet_paths:\n        pf = pq.ParquetFile(filepath)\n        for rg_idx in range(start, pf.num_row_groups, step):\n            rg = pf.read_row_group(rg_idx)\n            texts = rg.column('text').to_pylist()\n            yield texts\n\n# -----------------------------------------------------------------------------\ndef download_single_file(index):\n    \"\"\" Downloads a single file index, with some backoff \"\"\"\n\n    # Construct the local filepath for this file and skip if it already exists\n    filename = index_to_filename(index)\n    filepath = os.path.join(DATA_DIR, filename)\n    if os.path.exists(filepath):\n        print(f\"Skipping {filepath} (already exists)\")\n        return True\n\n    # Construct the remote URL for this file\n    url = f\"{BASE_URL}/{filename}\"\n    print(f\"Downloading {filename}...\")\n\n    # Download with retries\n    max_attempts = 5\n    for attempt in range(1, max_attempts + 1):\n        try:\n            response = requests.get(url, stream=True, timeout=30)\n            response.raise_for_status()\n            # Write to temporary file first\n            temp_path = filepath + f\".tmp\"\n            with open(temp_path, 'wb') as f:\n                for chunk in response.iter_content(chunk_size=1024 * 1024):  # 1MB chunks\n                    if chunk:\n                        f.write(chunk)\n            # Move temp file to final location\n            os.rename(temp_path, filepath)\n            print(f\"Successfully downloaded {filename}\")\n            return True\n\n        except (requests.RequestException, IOError) as e:\n            print(f\"Attempt {attempt}/{max_attempts} failed for {filename}: {e}\")\n            # Clean up any partial files\n            for path in [filepath + f\".tmp\", filepath]:\n                if os.path.exists(path):\n                    try:\n                        os.remove(path)\n                    except:\n                        pass\n            # Try a few times with exponential backoff: 2^attempt seconds\n            if attempt < max_attempts:\n                wait_time = 2 ** attempt\n                print(f\"Waiting {wait_time} seconds before retry...\")\n                time.sleep(wait_time)\n            else:\n                print(f\"Failed to download {filename} after {max_attempts} attempts\")\n                return False\n\n    return False\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Download pretraining dataset shards\")\n    parser.add_argument(\"-n\", \"--num-files\", type=int, default=-1, help=\"Number of train shards to download (default: -1), -1 = disable\")\n    parser.add_argument(\"-w\", \"--num-workers\", type=int, default=4, help=\"Number of parallel download workers (default: 4)\")\n    args = parser.parse_args()\n\n    # Prepare the output directory\n    os.makedirs(DATA_DIR, exist_ok=True)\n\n    # The way this works is that the user specifies the number of train shards to download via the -n flag.\n    # In addition to that, the validation shard is *always* downloaded and is pinned to be the last shard.\n    num_train_shards = MAX_SHARD if args.num_files == -1 else min(args.num_files, MAX_SHARD)\n    ids_to_download = list(range(num_train_shards))\n    ids_to_download.append(MAX_SHARD) # always download the validation shard\n\n    # Download the shards\n    print(f\"Downloading {len(ids_to_download)} shards using {args.num_workers} workers...\")\n    print(f\"Target directory: {DATA_DIR}\")\n    print()\n    with Pool(processes=args.num_workers) as pool:\n        results = pool.map(download_single_file, ids_to_download)\n\n    # Report results\n    successful = sum(1 for success in results if success)\n    print(f\"Done! Downloaded: {successful}/{len(ids_to_download)} shards to {DATA_DIR}\")\n"
  },
  {
    "path": "nanochat/engine.py",
    "content": "\"\"\"\nEngine for efficient inference of our models.\n\nEverything works around token sequences:\n- The user can send token sequences to the engine\n- The engine returns the next token\n\nNotes:\n- The engine knows nothing about tokenization, it's purely token id sequences.\n\nThe whole thing is made as efficient as possible.\n\"\"\"\n\nimport torch\nimport torch.nn.functional as F\nimport signal\nimport warnings\nfrom contextlib import contextmanager\nfrom collections import deque\nfrom nanochat.common import compute_init, autodetect_device_type\nfrom nanochat.checkpoint_manager import load_model\n\n# -----------------------------------------------------------------------------\n# Calculator tool helpers\n@contextmanager\ndef timeout(duration, formula):\n    def timeout_handler(signum, frame):\n        raise Exception(f\"'{formula}': timed out after {duration} seconds\")\n\n    signal.signal(signal.SIGALRM, timeout_handler)\n    signal.alarm(duration)\n    yield\n    signal.alarm(0)\n\ndef eval_with_timeout(formula, max_time=3):\n    try:\n        with timeout(max_time, formula):\n            with warnings.catch_warnings():\n                warnings.simplefilter(\"ignore\", SyntaxWarning)\n                return eval(formula, {\"__builtins__\": {}}, {})\n    except Exception as e:\n        signal.alarm(0)\n        # print(f\"Warning: Failed to eval {formula}, exception: {e}\") # it's ok ignore wrong calculator usage\n        return None\n\ndef use_calculator(expr):\n    \"\"\"\n    Evaluate a Python expression safely.\n    Supports both math expressions and string operations like .count()\n    \"\"\"\n    # Remove commas from numbers\n    expr = expr.replace(\",\", \"\")\n\n    # Check if it's a pure math expression (old behavior)\n    if all([x in \"0123456789*+-/.() \" for x in expr]):\n        if \"**\" in expr:  # disallow power operator\n            return None\n        return eval_with_timeout(expr)\n\n    # Check if it's a string operation we support\n    # Allow: strings (single/double quotes), .count(), letters, numbers, spaces, parens\n    allowed_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\\\"()._ \"\n    if not all([x in allowed_chars for x in expr]):\n        return None\n\n    # Disallow dangerous patterns\n    dangerous_patterns = ['__', 'import', 'exec', 'eval', 'compile', 'open', 'file',\n                         'input', 'raw_input', 'globals', 'locals', 'vars', 'dir',\n                         'getattr', 'setattr', 'delattr', 'hasattr']\n    expr_lower = expr.lower()\n    if any(pattern in expr_lower for pattern in dangerous_patterns):\n        return None\n\n    # Only allow .count() method for now (can expand later)\n    if '.count(' not in expr:\n        return None\n\n    # Evaluate with timeout\n    return eval_with_timeout(expr)\n\n# -----------------------------------------------------------------------------\nclass KVCache:\n    \"\"\"\n    KV Cache designed for Flash Attention 3's flash_attn_with_kvcache API.\n\n    Key differences from FA2-style cache:\n    - Tensors are (B, T, H, D) not (B, H, T, D)\n    - FA3 updates the cache in-place during flash_attn_with_kvcache\n    - Position tracked per batch element via cache_seqlens tensor\n    \"\"\"\n\n    def __init__(self, batch_size, num_heads, seq_len, head_dim, num_layers, device, dtype):\n        self.batch_size = batch_size\n        self.max_seq_len = seq_len\n        self.n_layers = num_layers\n        self.n_heads = num_heads\n        self.head_dim = head_dim\n        # Pre-allocate cache tensors: (n_layers, B, T, H, D)\n        self.k_cache = torch.zeros(num_layers, batch_size, seq_len, num_heads, head_dim, device=device, dtype=dtype)\n        self.v_cache = torch.zeros(num_layers, batch_size, seq_len, num_heads, head_dim, device=device, dtype=dtype)\n        # Current sequence length per batch element (FA3 needs int32)\n        self.cache_seqlens = torch.zeros(batch_size, dtype=torch.int32, device=device)\n        # Previous token's normalized embedding for smear (set by model forward pass)\n        self.prev_embedding = None\n\n    def reset(self):\n        \"\"\"Reset cache to empty state.\"\"\"\n        self.cache_seqlens.zero_()\n        self.prev_embedding = None\n\n    def get_pos(self):\n        \"\"\"Get current position (assumes all batch elements at same position).\"\"\"\n        return self.cache_seqlens[0].item()\n\n    def get_layer_cache(self, layer_idx):\n        \"\"\"Return (k_cache, v_cache) views for a specific layer.\"\"\"\n        return self.k_cache[layer_idx], self.v_cache[layer_idx]\n\n    def advance(self, num_tokens):\n        \"\"\"Advance the cache position by num_tokens.\"\"\"\n        self.cache_seqlens += num_tokens\n\n    def prefill(self, other):\n        \"\"\"\n        Copy cached KV from another cache into this one.\n        Used when we do batch=1 prefill and then want to generate multiple samples in parallel.\n        \"\"\"\n        assert self.get_pos() == 0, \"Cannot prefill a non-empty KV cache\"\n        assert self.n_layers == other.n_layers and self.n_heads == other.n_heads and self.head_dim == other.head_dim\n        assert self.max_seq_len >= other.max_seq_len\n        other_pos = other.get_pos()\n        self.k_cache[:, :, :other_pos, :, :] = other.k_cache[:, :, :other_pos, :, :]\n        self.v_cache[:, :, :other_pos, :, :] = other.v_cache[:, :, :other_pos, :, :]\n        self.cache_seqlens.fill_(other_pos)\n        # Copy smear state: expand batch=1 prev_embedding to num_samples\n        if other.prev_embedding is not None:\n            self.prev_embedding = other.prev_embedding.expand(self.batch_size, -1, -1).clone()\n\n# -----------------------------------------------------------------------------\n@torch.inference_mode()\ndef sample_next_token(logits, rng, temperature=1.0, top_k=None):\n    \"\"\"Sample a single next token from given logits of shape (B, vocab_size). Returns (B, 1).\"\"\"\n    assert temperature >= 0.0, \"temperature must be non-negative\"\n    if temperature == 0.0:\n        return torch.argmax(logits, dim=-1, keepdim=True)\n    if top_k is not None and top_k > 0:\n        k = min(top_k, logits.size(-1))\n        vals, idx = torch.topk(logits, k, dim=-1)\n        vals = vals / temperature\n        probs = F.softmax(vals, dim=-1)\n        choice = torch.multinomial(probs, num_samples=1, generator=rng)\n        return idx.gather(1, choice)\n    else:\n        logits = logits / temperature\n        probs = F.softmax(logits, dim=-1)\n        return torch.multinomial(probs, num_samples=1, generator=rng)\n\n# -----------------------------------------------------------------------------\n\nclass RowState:\n    # Per-row state tracking during generation\n    def __init__(self, current_tokens=None):\n        self.current_tokens = current_tokens or [] # Current token sequence for this row\n        self.forced_tokens = deque() # Queue of tokens to force inject\n        self.in_python_block = False # Whether we are inside a python block\n        self.python_expr_tokens = [] # Tokens of the current python expression\n        self.completed = False # Whether this row has completed generation\n\nclass Engine:\n\n    def __init__(self, model, tokenizer):\n        self.model = model\n        self.tokenizer = tokenizer # needed for tool use\n\n    @torch.inference_mode()\n    def generate(self, tokens, num_samples=1, max_tokens=None, temperature=1.0, top_k=None, seed=42):\n        \"\"\"Same as generate, but does single prefill and then clones the KV cache.\"\"\"\n        assert isinstance(tokens, list) and isinstance(tokens[0], int), \"expecting list of ints\"\n        device = self.model.get_device()\n        # NOTE: setting the dtype here and in this way is an ugly hack.\n        # Currently the repo assumes that cuda -> bfloat16 and everything else -> float32.\n        # We need to know the dtype here to call __init__ on KVCache and pre-allocate its tensors.\n        # As a quick hack, we're making generate() function inherit and know about this repo-wise assumption.\n        # I think there has to be a bigger refactor to deal with device/dtype tracking across the codebase.\n        # In particular, the KVCache should allocate its tensors lazily\n        dtype = torch.bfloat16 if device.type == \"cuda\" else torch.float32\n        rng = torch.Generator(device=device)\n        rng.manual_seed(seed)\n\n        # Get the special tokens we need to coordinate the tool use state machine\n        get_special = lambda s: self.tokenizer.encode_special(s)\n        python_start = get_special(\"<|python_start|>\")\n        python_end = get_special(\"<|python_end|>\")\n        output_start = get_special(\"<|output_start|>\")\n        output_end = get_special(\"<|output_end|>\")\n        assistant_end = get_special(\"<|assistant_end|>\") # if sampled, ends row\n        bos = self.tokenizer.get_bos_token_id() # if sampled, ends row\n\n        # 1) Run a batch 1 prefill of the prompt tokens\n        m = self.model.config\n        kv_model_kwargs = {\"num_heads\": m.n_kv_head, \"head_dim\": m.n_embd // m.n_head, \"num_layers\": m.n_layer}\n        kv_cache_prefill = KVCache(\n            batch_size=1,\n            seq_len=len(tokens),\n            device=device,\n            dtype=dtype,\n            **kv_model_kwargs,\n        )\n        ids = torch.tensor([tokens], dtype=torch.long, device=device)\n        logits = self.model.forward(ids, kv_cache=kv_cache_prefill)\n        logits = logits[:, -1, :].expand(num_samples, -1)  # (num_samples, vocab_size)\n\n        # 2) Replicate the KV cache for each sample/row\n        kv_length_hint = (len(tokens) + max_tokens) if max_tokens is not None else self.model.config.sequence_len\n        kv_cache_decode = KVCache(\n            batch_size=num_samples,\n            seq_len=kv_length_hint,\n            device=device,\n            dtype=dtype,\n            **kv_model_kwargs,\n        )\n        kv_cache_decode.prefill(kv_cache_prefill)\n        del kv_cache_prefill # no need to keep this memory around\n\n        # 3) Initialize states for each sample\n        row_states = [RowState(tokens.copy()) for _ in range(num_samples)]\n\n        # 4) Main generation loop\n        num_generated = 0\n        while True:\n            # Stop condition: we've reached max tokens\n            if max_tokens is not None and num_generated >= max_tokens:\n                break\n            # Stop condition: all rows are completed\n            if all(state.completed for state in row_states):\n                break\n\n            # Sample the next token for each row\n            next_ids = sample_next_token(logits, rng, temperature, top_k)  # (B, 1)\n            sampled_tokens = next_ids[:, 0].tolist()\n\n            # Process each row: choose the next token, update state, optional tool use\n            token_column = [] # contains the next token id along each row\n            token_masks = [] # contains the mask (was it sampled (1) or forced (0)?) along each row\n            for i, state in enumerate(row_states):\n                # Select the next token in this row\n                is_forced = len(state.forced_tokens) > 0 # are there tokens waiting to be forced in deque?\n                token_masks.append(0 if is_forced else 1) # mask is 0 if forced, 1 if sampled\n                next_token = state.forced_tokens.popleft() if is_forced else sampled_tokens[i]\n                token_column.append(next_token)\n                # Update the state of this row to include the next token\n                state.current_tokens.append(next_token)\n                # On <|assistant_end|> or <|bos|>, mark the row as completed\n                if next_token == assistant_end or next_token == bos:\n                    state.completed = True\n                # Handle tool logic\n                if next_token == python_start:\n                    state.in_python_block = True\n                    state.python_expr_tokens = []\n                elif next_token == python_end and state.in_python_block:\n                    state.in_python_block = False\n                    if state.python_expr_tokens:\n                        expr = self.tokenizer.decode(state.python_expr_tokens)\n                        result = use_calculator(expr)\n                        if result is not None:\n                            result_tokens = self.tokenizer.encode(str(result))\n                            state.forced_tokens.append(output_start)\n                            state.forced_tokens.extend(result_tokens)\n                            state.forced_tokens.append(output_end)\n                    state.python_expr_tokens = []\n                elif state.in_python_block:\n                    state.python_expr_tokens.append(next_token)\n\n            # Yield the token column\n            yield token_column, token_masks\n            num_generated += 1\n\n            # Prepare logits for next iteration\n            ids = torch.tensor(token_column, dtype=torch.long, device=device).unsqueeze(1)\n            logits = self.model.forward(ids, kv_cache=kv_cache_decode)[:, -1, :]  # (B, vocab_size)\n\n    def generate_batch(self, tokens, num_samples=1, **kwargs):\n        \"\"\"\n        Non-streaming batch generation that just returns the final token sequences.\n        Returns a list of token sequences (list of lists of ints).\n        Terminal tokens (assistant_end, bos) are not included in the results.\n        \"\"\"\n        assistant_end = self.tokenizer.encode_special(\"<|assistant_end|>\")\n        bos = self.tokenizer.get_bos_token_id()\n        results = [tokens.copy() for _ in range(num_samples)]\n        masks = [[0] * len(tokens) for _ in range(num_samples)]\n        completed = [False] * num_samples\n        for token_column, token_masks in self.generate(tokens, num_samples, **kwargs):\n            for i, (token, mask) in enumerate(zip(token_column, token_masks)):\n                if not completed[i]:\n                    if token == assistant_end or token == bos:\n                        completed[i] = True\n                    else:\n                        results[i].append(token)\n                        masks[i].append(mask)\n            # Stop if all rows are completed\n            if all(completed):\n                break\n        return results, masks\n\n\nif __name__ == \"__main__\":\n    \"\"\"\n    Quick inline test to make sure that the naive/slow model.generate function\n    is equivalent to the faster Engine.generate function here.\n    \"\"\"\n    import time\n    # init compute\n    device_type = autodetect_device_type()\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\n    # load the model and tokenizer\n    model, tokenizer, meta = load_model(\"base\", device, phase=\"eval\")\n    bos_token_id = tokenizer.get_bos_token_id()\n    # common hyperparameters\n    kwargs = dict(max_tokens=64, temperature=0.0)\n    # set the starting prompt\n    prompt_tokens = tokenizer.encode(\"The chemical formula of water is\", prepend=bos_token_id)\n    # generate the reference sequence using the model.generate() function\n    generated_tokens = []\n    torch.cuda.synchronize()\n    t0 = time.time()\n    stream = model.generate(prompt_tokens, **kwargs)\n    for token in stream:\n        generated_tokens.append(token)\n        chunk = tokenizer.decode([token])\n        print(chunk, end=\"\", flush=True)\n    print()\n    torch.cuda.synchronize()\n    t1 = time.time()\n    print(f\"Reference time: {t1 - t0:.2f}s\")\n    reference_ids = generated_tokens\n    # generate tokens with Engine\n    generated_tokens = []\n    engine = Engine(model, tokenizer)\n    stream = engine.generate(prompt_tokens, num_samples=1, **kwargs) # note: runs in fp32\n    torch.cuda.synchronize()\n    t0 = time.time()\n    for token_column, token_masks in stream:\n        token = token_column[0] # only print out the first row\n        generated_tokens.append(token)\n        chunk = tokenizer.decode([token])\n        print(chunk, end=\"\", flush=True)\n    print()\n    torch.cuda.synchronize()\n    t1 = time.time()\n    print(f\"Engine time: {t1 - t0:.2f}s\")\n    # compare the two sequences\n    for i in range(len(reference_ids)):\n        if reference_ids[i] != generated_tokens[i]:\n            print(f\"Mismatch at {i}: {reference_ids[i]} != {generated_tokens[i]}\")\n            break\n    print(f\"Match: {reference_ids == generated_tokens}\")\n"
  },
  {
    "path": "nanochat/execution.py",
    "content": "\"\"\"\nSandboxed execution utilities for running Python code that comes out of an LLM.\nAdapted from OpenAI HumanEval code:\nhttps://github.com/openai/human-eval/blob/master/human_eval/execution.py\n\nWhat is covered:\n- Each execution runs in its own process (can be killed if it hangs or crashes)\n- Execution is limited by a timeout to stop infinite loops\n- Memory limits are enforced by default (256MB)\n- stdout and stderr are captured and returned\n- Code runs in a temporary directory that is deleted afterwards\n- Dangerous functions are disabled (examples: os.system, os.kill, shutil.rmtree, subprocess.Popen)\n\nWhat is not covered:\n- Not a true security sandbox\n- Network access is not blocked (e.g. sockets could be opened)\n- Python's dynamic features (e.g. ctypes) could bypass restrictions\n- No kernel-level isolation (no seccomp, no containers, no virtualization)\n\nOverall this sandbox is good for evaluation of generated code and protects against\naccidental destructive behavior, but it is not safe against malicious adversarial code.\n\"\"\"\n\nimport contextlib\nimport faulthandler\nimport io\nimport multiprocessing\nimport os\nimport platform\nimport signal\nimport tempfile\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n# -----------------------------------------------------------------------------\n\n@dataclass\nclass ExecutionResult:\n    \"\"\"Result of executing Python code in a sandbox.\"\"\"\n    success: bool\n    stdout: str\n    stderr: str\n    error: Optional[str] = None\n    timeout: bool = False\n    memory_exceeded: bool = False\n\n    def __repr__(self):\n        parts = []\n        parts.append(f\"ExecutionResult(success={self.success}\")\n        if self.timeout:\n            parts.append(\", timeout=True\")\n        if self.memory_exceeded:\n            parts.append(\", memory_exceeded=True\")\n        if self.error:\n            parts.append(f\", error={self.error!r}\")\n        if self.stdout:\n            parts.append(f\", stdout={self.stdout!r}\")\n        if self.stderr:\n            parts.append(f\", stderr={self.stderr!r}\")\n        parts.append(\")\")\n        return \"\".join(parts)\n\n\n@contextlib.contextmanager\ndef time_limit(seconds: float):\n    def signal_handler(signum, frame):\n        raise TimeoutException(\"Timed out!\")\n\n    signal.setitimer(signal.ITIMER_REAL, seconds)\n    signal.signal(signal.SIGALRM, signal_handler)\n    try:\n        yield\n    finally:\n        signal.setitimer(signal.ITIMER_REAL, 0)\n\n\n@contextlib.contextmanager\ndef capture_io():\n    \"\"\"Capture stdout and stderr, and disable stdin.\"\"\"\n    stdout_capture = io.StringIO()\n    stderr_capture = io.StringIO()\n    stdin_block = WriteOnlyStringIO()\n    with contextlib.redirect_stdout(stdout_capture):\n        with contextlib.redirect_stderr(stderr_capture):\n            with redirect_stdin(stdin_block):\n                yield stdout_capture, stderr_capture\n\n\n@contextlib.contextmanager\ndef create_tempdir():\n    with tempfile.TemporaryDirectory() as dirname:\n        with chdir(dirname):\n            yield dirname\n\n\nclass TimeoutException(Exception):\n    pass\n\n\nclass WriteOnlyStringIO(io.StringIO):\n    \"\"\"StringIO that throws an exception when it's read from\"\"\"\n\n    def read(self, *args, **kwargs):\n        raise IOError\n\n    def readline(self, *args, **kwargs):\n        raise IOError\n\n    def readlines(self, *args, **kwargs):\n        raise IOError\n\n    def readable(self, *args, **kwargs):\n        \"\"\"Returns True if the IO object can be read.\"\"\"\n        return False\n\n\nclass redirect_stdin(contextlib._RedirectStream):  # type: ignore\n    _stream = \"stdin\"\n\n\n@contextlib.contextmanager\ndef chdir(root):\n    if root == \".\":\n        yield\n        return\n    cwd = os.getcwd()\n    os.chdir(root)\n    try:\n        yield\n    finally:\n        os.chdir(cwd)\n\n\ndef reliability_guard(maximum_memory_bytes: Optional[int] = None):\n    \"\"\"\n    This disables various destructive functions and prevents the generated code\n    from interfering with the test (e.g. fork bomb, killing other processes,\n    removing filesystem files, etc.)\n\n    WARNING\n    This function is NOT a security sandbox. Untrusted code, including, model-\n    generated code, should not be blindly executed outside of one. See the\n    Codex paper for more information about OpenAI's code sandbox, and proceed\n    with caution.\n    \"\"\"\n\n    if platform.uname().system != \"Darwin\":\n        # These resource limit calls seem to fail on macOS (Darwin), skip?\n        import resource\n        resource.setrlimit(resource.RLIMIT_AS, (maximum_memory_bytes, maximum_memory_bytes))\n        resource.setrlimit(resource.RLIMIT_DATA, (maximum_memory_bytes, maximum_memory_bytes))\n        resource.setrlimit(resource.RLIMIT_STACK, (maximum_memory_bytes, maximum_memory_bytes))\n\n    faulthandler.disable()\n\n    import builtins\n\n    builtins.exit = None\n    builtins.quit = None\n\n    import os\n\n    os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\n    os.kill = None\n    os.system = None\n    os.putenv = None\n    os.remove = None\n    os.removedirs = None\n    os.rmdir = None\n    os.fchdir = None\n    os.setuid = None\n    os.fork = None\n    os.forkpty = None\n    os.killpg = None\n    os.rename = None\n    os.renames = None\n    os.truncate = None\n    os.replace = None\n    os.unlink = None\n    os.fchmod = None\n    os.fchown = None\n    os.chmod = None\n    os.chown = None\n    os.chroot = None\n    os.fchdir = None\n    os.lchflags = None\n    os.lchmod = None\n    os.lchown = None\n    os.getcwd = None\n    os.chdir = None\n\n    import shutil\n\n    shutil.rmtree = None\n    shutil.move = None\n    shutil.chown = None\n\n    import subprocess\n\n    subprocess.Popen = None  # type: ignore\n\n    __builtins__[\"help\"] = None\n\n    import sys\n\n    sys.modules[\"ipdb\"] = None\n    sys.modules[\"joblib\"] = None\n    sys.modules[\"resource\"] = None\n    sys.modules[\"psutil\"] = None\n    sys.modules[\"tkinter\"] = None\n\n\ndef _unsafe_execute(code: str, timeout: float, maximum_memory_bytes: Optional[int], result_dict):\n    \"\"\"Execute code in a subprocess with safety guards. Results are written to result_dict.\"\"\"\n    with create_tempdir():\n\n        # These system calls are needed when cleaning up tempdir.\n        import os\n        import shutil\n\n        rmtree = shutil.rmtree\n        rmdir = os.rmdir\n        chdir = os.chdir\n        unlink = os.unlink\n\n        # Disable functionalities that can make destructive changes to the test.\n        reliability_guard(maximum_memory_bytes=maximum_memory_bytes)\n\n        # Default to failure\n        result_dict.update({\n            \"success\": False,\n            \"stdout\": \"\",\n            \"stderr\": \"\",\n            \"timeout\": False,\n            \"memory_exceeded\": False,\n            \"error\": None,\n        })\n\n        try:\n            exec_globals = {}\n            with capture_io() as (stdout_capture, stderr_capture):\n                with time_limit(timeout):\n                    # WARNING\n                    # This program exists to execute untrusted model-generated code. Although\n                    # it is highly unlikely that model-generated code will do something overtly\n                    # malicious in response to this test suite, model-generated code may act\n                    # destructively due to a lack of model capability or alignment.\n                    # Users are strongly encouraged to sandbox this evaluation suite so that it\n                    # does not perform destructive actions on their host or network. For more\n                    # information on how OpenAI sandboxes its code, see the accompanying paper.\n                    # Once you have read this disclaimer and taken appropriate precautions,\n                    # uncomment the following line and proceed at your own risk:\n                    exec(code, exec_globals)\n\n            result_dict.update({\n                \"success\": True,\n                \"stdout\": stdout_capture.getvalue(),\n                \"stderr\": stderr_capture.getvalue(),\n            })\n\n        except TimeoutException:\n            result_dict.update({\n                \"timeout\": True,\n                \"error\": \"Execution timed out\",\n            })\n\n        except MemoryError as e:\n            result_dict.update({\n                \"memory_exceeded\": True,\n                \"error\": f\"Memory limit exceeded: {e}\",\n            })\n\n        except BaseException as e:\n            result_dict.update({\n                \"error\": f\"{type(e).__name__}: {e}\",\n            })\n\n        # Needed for cleaning up.\n        shutil.rmtree = rmtree\n        os.rmdir = rmdir\n        os.chdir = chdir\n        os.unlink = unlink\n\n\ndef execute_code(\n    code: str,\n    timeout: float = 5.0, # 5 seconds default\n    maximum_memory_bytes: Optional[int] = 256 * 1024 * 1024, # 256MB default\n) -> ExecutionResult:\n    \"\"\"\n    Execute Python code in a sandboxed environment.\n\n    Args:\n        code: Python code to execute as a string\n        timeout: Maximum execution time in seconds (default: 5.0)\n        maximum_memory_bytes: Memory limit in bytes (default: 256MB, None to disable)\n\n    Returns:\n        ExecutionResult with success status, stdout/stderr, and error information\n\n    Example:\n        >>> result = execute_code(\"print('hello world')\")\n        >>> result.success\n        True\n        >>> result.stdout\n        'hello world\\\\n'\n    \"\"\"\n\n    manager = multiprocessing.Manager()\n    result_dict = manager.dict()\n\n    p = multiprocessing.Process(\n        target=_unsafe_execute,\n        args=(code, timeout, maximum_memory_bytes, result_dict)\n    )\n    p.start()\n    p.join(timeout=timeout + 1)\n\n    if p.is_alive():\n        p.kill()\n        return ExecutionResult(\n            success=False,\n            stdout=\"\",\n            stderr=\"\",\n            error=\"Execution timed out (process killed)\",\n            timeout=True,\n            memory_exceeded=False,\n        )\n\n    if not result_dict:\n        return ExecutionResult(\n            success=False,\n            stdout=\"\",\n            stderr=\"\",\n            error=\"Execution failed (no result returned)\",\n            timeout=True,\n            memory_exceeded=False,\n        )\n\n    return ExecutionResult(\n        success=result_dict[\"success\"],\n        stdout=result_dict[\"stdout\"],\n        stderr=result_dict[\"stderr\"],\n        error=result_dict[\"error\"],\n        timeout=result_dict[\"timeout\"],\n        memory_exceeded=result_dict[\"memory_exceeded\"],\n    )\n\n"
  },
  {
    "path": "nanochat/flash_attention.py",
    "content": "\"\"\"\nUnified Flash Attention interface with automatic FA3/SDPA switching.\n\nExports `flash_attn` module that matches the FA3 API exactly, but falls back\nto PyTorch SDPA on non-Hopper GPUs (including Blackwell), MPS, and CPU.\n\nUsage (drop-in replacement for FA3):\n    from nanochat.flash_attention import flash_attn\n\n    # Training (no KV cache)\n    y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=window_size)\n\n    # Inference (with KV cache)\n    y = flash_attn.flash_attn_with_kvcache(q, k_cache, v_cache, k=k, v=v, ...)\n\"\"\"\nimport torch\nimport torch.nn.functional as F\n\n\n# =============================================================================\n# Detection: Try to load FA3 on Hopper+ GPUs\n# =============================================================================\ndef _load_flash_attention_3():\n    \"\"\"Try to load Flash Attention 3 (requires Hopper GPU, sm90).\"\"\"\n    if not torch.cuda.is_available():\n        return None\n    try:\n        major, _ = torch.cuda.get_device_capability()\n        # FA3 kernels are compiled for Hopper (sm90) only\n        # Ada (sm89), Blackwell (sm100) need SDPA fallback until FA3 is recompiled\n        if major != 9:\n            return None\n        import os\n        os.environ[\"HF_HUB_DISABLE_PROGRESS_BARS\"] = \"1\"\n        from kernels import get_kernel\n        return get_kernel('varunneal/flash-attention-3').flash_attn_interface\n    except Exception:\n        return None\n\n\n_fa3 = _load_flash_attention_3()\nHAS_FA3 = _fa3 is not None\n\n# Override for testing: set to 'fa3', 'sdpa', or None (auto)\n_override_impl = None\n\n\ndef _resolve_use_fa3():\n    \"\"\"Decide once whether to use FA3, based on availability, override, and dtype.\"\"\"\n    if _override_impl == 'fa3':\n        assert HAS_FA3, \"Cannot override to FA3: not available on this hardware\"\n        return True\n    if _override_impl == 'sdpa':\n        return False\n    if HAS_FA3:\n        # FA3 Hopper kernels only support bf16 and fp8; fp16/fp32 must use SDPA fallback\n        from nanochat.common import COMPUTE_DTYPE\n        if COMPUTE_DTYPE == torch.bfloat16:\n            return True\n        return False\n    return False\n\nUSE_FA3 = _resolve_use_fa3()\n\n\n# =============================================================================\n# SDPA helpers\n# =============================================================================\ndef _sdpa_attention(q, k, v, window_size, enable_gqa):\n    \"\"\"\n    SDPA attention with sliding window support.\n    q, k, v are (B, H, T, D) format.\n    \"\"\"\n    Tq = q.size(2)\n    Tk = k.size(2)\n    window = window_size[0]\n\n    # Full context, same length\n    if (window < 0 or window >= Tq) and Tq == Tk:\n        return F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=enable_gqa)\n\n    # Single token generation\n    if Tq == 1:\n        if window >= 0 and window < Tk:\n            # window is \"left\" tokens we need to include (window + 1) keys total\n            start = max(0, Tk - (window + 1))\n            k = k[:, :, start:, :]\n            v = v[:, :, start:, :]\n        return F.scaled_dot_product_attention(q, k, v, is_causal=False, enable_gqa=enable_gqa)\n\n    # Need explicit mask for sliding window/chunk inference\n    device = q.device\n    # For chunk inference (Tq != Tk), is_causal is not aligned to cache position => build an explicit bool mask\n    row_idx = (Tk - Tq) + torch.arange(Tq, device=device).unsqueeze(1)\n    col_idx = torch.arange(Tk, device=device).unsqueeze(0)\n    mask = col_idx <= row_idx\n\n    # sliding window (left)\n    if window >= 0 and window < Tk:\n        mask = mask & ((row_idx - col_idx) <= window)\n\n    return F.scaled_dot_product_attention(q, k, v, attn_mask=mask, enable_gqa=enable_gqa)\n\n# =============================================================================\n# Public API: Same interface as FA3\n# =============================================================================\ndef flash_attn_func(q, k, v, causal=False, window_size=(-1, -1)):\n    \"\"\"\n    Flash Attention for training (no KV cache).\n\n    Args:\n        q, k, v: Tensors of shape (B, T, H, D)\n        causal: Whether to use causal masking\n        window_size: (left, right) sliding window. -1 means unlimited.\n\n    Returns:\n        Output tensor of shape (B, T, H, D)\n    \"\"\"\n    if USE_FA3:\n        return _fa3.flash_attn_func(q, k, v, causal=causal, window_size=window_size)\n\n    # SDPA fallback: transpose (B, T, H, D) -> (B, H, T, D)\n    q = q.transpose(1, 2)\n    k = k.transpose(1, 2)\n    v = v.transpose(1, 2)\n    enable_gqa = q.size(1) != k.size(1)\n    y = _sdpa_attention(q, k, v, window_size, enable_gqa)\n    return y.transpose(1, 2)  # back to (B, T, H, D)\n\n\ndef flash_attn_with_kvcache(q, k_cache, v_cache, k=None, v=None, cache_seqlens=None,\n                            causal=False, window_size=(-1, -1)):\n    \"\"\"\n    Flash Attention with KV cache for inference.\n\n    FA3 updates k_cache/v_cache in-place. Our SDPA fallback does the same.\n\n    Args:\n        q: Queries, shape (B, T_new, H, D)\n        k_cache, v_cache: Pre-allocated cache tensors, shape (B, T_max, H_kv, D)\n        k, v: New keys/values to insert, shape (B, T_new, H_kv, D)\n        cache_seqlens: Current position in cache, shape (B,) int32\n        causal: Whether to use causal masking\n        window_size: (left, right) sliding window. -1 means unlimited.\n\n    Returns:\n        Output tensor of shape (B, T_new, H, D)\n    \"\"\"\n    if USE_FA3:\n        return _fa3.flash_attn_with_kvcache(\n            q, k_cache, v_cache, k=k, v=v, cache_seqlens=cache_seqlens,\n            causal=causal, window_size=window_size\n        )\n\n    # SDPA fallback: manually manage KV cache\n    B, T_new, H, D = q.shape\n    pos = cache_seqlens[0].item()  # assume uniform position across batch\n\n    # Insert new k, v into cache (in-place, matching FA3 behavior)\n    if k is not None and v is not None:\n        k_cache[:, pos:pos+T_new, :, :] = k\n        v_cache[:, pos:pos+T_new, :, :] = v\n\n    # Get full cache up to current position + new tokens\n    end_pos = pos + T_new\n    k_full = k_cache[:, :end_pos, :, :]\n    v_full = v_cache[:, :end_pos, :, :]\n\n    # Transpose to SDPA layout: (B, T, H, D) -> (B, H, T, D)\n    q_sdpa = q.transpose(1, 2)\n    k_sdpa = k_full.transpose(1, 2)\n    v_sdpa = v_full.transpose(1, 2)\n\n    enable_gqa = q_sdpa.size(1) != k_sdpa.size(1)\n    y_sdpa = _sdpa_attention(q_sdpa, k_sdpa, v_sdpa, window_size, enable_gqa)\n\n    return y_sdpa.transpose(1, 2)  # back to (B, T, H, D)\n\n\n# =============================================================================\n# Export: flash_attn module interface (drop-in replacement for FA3)\n# =============================================================================\nfrom types import SimpleNamespace\nflash_attn = SimpleNamespace(\n    flash_attn_func=flash_attn_func,\n    flash_attn_with_kvcache=flash_attn_with_kvcache,\n)\n"
  },
  {
    "path": "nanochat/fp8.py",
    "content": "\"\"\"Minimal FP8 training for nanochat — tensorwise dynamic scaling only.\n\nDrop-in replacement for torchao's Float8Linear (~2000 lines) with ~150 lines.\nWe only need the \"tensorwise\" recipe (one scalar scale per tensor), not the full\ngenerality of torchao (rowwise scaling, FSDP float8 all-gather, DTensor, tensor\nsubclass dispatch tables, etc.)\n\nHow FP8 training works\n======================\nA standard Linear layer does one matmul in forward and two in backward:\n  forward:      output     = input      @ weight.T\n  backward:     grad_input = grad_output @ weight\n                grad_weight= grad_output.T @ input\n\nFP8 training wraps each of these three matmuls with:\n  1. Compute scale = FP8_MAX / max(|tensor|)  for each operand\n  2. Quantize: fp8_tensor = clamp(tensor * scale, -FP8_MAX, FP8_MAX).to(fp8)\n  3. Matmul via torch._scaled_mm (cuBLAS FP8 kernel, ~2x faster than bf16)\n  4. Dequantize: _scaled_mm handles this internally using the inverse scales\n\nThe key insight: torch._scaled_mm and the float8 dtypes are PyTorch built-ins.\ntorchao is just orchestration around these primitives. We can call them directly.\n\nFP8 dtype choice\n================\nThere are two FP8 formats. We use both, following the standard convention:\n  - float8_e4m3fn: 4-bit exponent, 3-bit mantissa, range [-448, 448]\n    Higher precision (more mantissa bits), used for input and weight.\n  - float8_e5m2:   5-bit exponent, 2-bit mantissa, range [-57344, 57344]\n    Wider range (more exponent bits), used for gradients which can be large.\n\ntorch._scaled_mm layout requirements\n=====================================\nThe cuBLAS FP8 kernel requires specific memory layouts:\n  - First argument (A):  must be row-major (contiguous)\n  - Second argument (B): must be column-major (B.t().contiguous().t())\nIf B is obtained by transposing a contiguous tensor (e.g. weight.t()), it is\nalready column-major — no copy needed. Otherwise we use _to_col_major().\n\nHow this differs from torchao's approach\n========================================\ntorchao uses a \"tensor subclass\" architecture: Float8TrainingTensor is a subclass\nof torch.Tensor that bundles FP8 data + scale + metadata. It implements\n__torch_dispatch__ with a dispatch table that intercepts every aten op (mm, t,\nreshape, clone, ...) and handles it in FP8-aware fashion. When you call\n  output = input @ weight.T\nthe @ operator dispatches to aten.mm, which gets intercepted and routed to\ntorch._scaled_mm behind the scenes. This is ~2000 lines of code because you need\na handler for every tensor operation that might touch an FP8 tensor.\n\nWe take a simpler approach: a single autograd.Function (_Float8Matmul) that takes\nfull-precision inputs, quantizes to FP8 internally, calls _scaled_mm, and returns\nfull-precision outputs. Marked @allow_in_graph so torch.compile treats it as one\nopaque node rather than trying to trace inside.\n\nThe trade-off is in how torch.compile sees the two approaches:\n  - torchao: compile decomposes the tensor subclass (via __tensor_flatten__) and\n    sees every individual op (amax, scale, cast, _scaled_mm) as separate graph\n    nodes. Inductor can fuse these with surrounding operations (e.g. fuse the\n    amax computation with the preceding layer's activation function).\n  - ours: compile sees a single opaque call. It can optimize everything around\n    the FP8 linear (attention, norms, etc.) but cannot fuse across the boundary.\n\nBoth call the exact same cuBLAS _scaled_mm kernel — the GPU matmul is identical.\nThe difference is only in the \"glue\" ops (amax, scale, cast) which are tiny\ncompared to the matmul. In practice this means our version is slightly faster\n(less compilation overhead, no tensor subclass dispatch cost) but can produce\nsubtly different floating-point rounding paths under torch.compile, since Inductor\ngenerates a different graph. Numerics are bitwise identical in eager mode.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\nfrom nanochat.common import COMPUTE_DTYPE\n\n# Avoid division by zero when computing scale from an all-zeros tensor\nEPS = 1e-12\n\n\n@torch.no_grad()\ndef _to_fp8(x, fp8_dtype):\n    \"\"\"Dynamically quantize a tensor to FP8 using tensorwise scaling.\n\n    \"Tensorwise\" means one scalar scale for the entire tensor (as opposed to\n    \"rowwise\" which computes a separate scale per row). Tensorwise is faster\n    because cuBLAS handles the scaling; rowwise needs the CUTLASS kernel.\n\n    Returns (fp8_data, inverse_scale) for use with torch._scaled_mm.\n    \"\"\"\n    fp8_max = torch.finfo(fp8_dtype).max\n    # Compute the max absolute value across the entire tensor\n    amax = x.float().abs().max()\n    # Scale maps [0, amax] -> [0, fp8_max]. Use float64 for the division to\n    # ensure consistent numerics between torch.compile and eager mode.\n    # (torchao does the same upcast — without it, compile/eager can diverge)\n    scale = fp8_max / amax.double().clamp(min=EPS)\n    scale = scale.float()\n    # Quantize: scale into FP8 range, saturate (clamp prevents overflow when\n    # casting — PyTorch's default is to wrap, not saturate), then cast to FP8\n    x_scaled = x.float() * scale\n    x_clamped = x_scaled.clamp(-fp8_max, fp8_max)\n    x_fp8 = x_clamped.to(fp8_dtype)\n    # _scaled_mm expects the *inverse* of our scale (it multiplies by this to\n    # convert FP8 values back to the original range during the matmul)\n    inv_scale = scale.reciprocal()\n    return x_fp8, inv_scale\n\n\ndef _to_col_major(x):\n    \"\"\"Rearrange a 2D tensor's memory to column-major layout.\n\n    torch._scaled_mm requires its second operand in column-major layout.\n    The trick: transpose -> contiguous (forces a copy in transposed order)\n    -> transpose back. The result has the same logical shape but column-major\n    strides, e.g. a [M, N] tensor gets strides (1, M) instead of (N, 1).\n    \"\"\"\n    return x.t().contiguous().t()\n\n\n# allow_in_graph tells torch.compile to treat this as an opaque operation —\n# dynamo won't try to decompose it into smaller ops. See the module docstring\n# for how this differs from torchao's tensor subclass approach.\n@torch._dynamo.allow_in_graph\nclass _Float8Matmul(torch.autograd.Function):\n    \"\"\"Custom autograd for the three FP8 GEMMs of a Linear layer.\n\n    The forward quantizes input and weight to FP8 and saves\n    the quantized tensors + scales for backward.\n    \"\"\"\n\n    @staticmethod\n    def forward(ctx, input_2d, weight):\n        # Quantize both operands to e4m3 (higher precision format)\n        input_fp8, input_inv = _to_fp8(input_2d, torch.float8_e4m3fn)\n        weight_fp8, weight_inv = _to_fp8(weight, torch.float8_e4m3fn)\n        ctx.save_for_backward(input_fp8, input_inv, weight_fp8, weight_inv)\n\n        # output = input @ weight.T\n        # input_fp8 is [B, K] contiguous = row-major (good for first arg)\n        # weight_fp8 is [N, K] contiguous, so weight_fp8.t() is [K, N] with\n        # strides (1, K) = column-major (good for second arg, no copy needed!)\n        output = torch._scaled_mm(\n            input_fp8,\n            weight_fp8.t(),\n            scale_a=input_inv,\n            scale_b=weight_inv,\n            out_dtype=input_2d.dtype,\n            # use_fast_accum=True accumulates the dot products in lower precision.\n            # Slightly less accurate but measurably faster. Standard practice for\n            # the forward pass; we use False in backward for more precise gradients.\n            use_fast_accum=True,\n        )\n        return output\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        in_fp8, in_inv, w_fp8, w_inv = ctx.saved_tensors\n\n        # === GEMM 1: grad_input = grad_output @ weight ===\n        # Shapes: [B, N] @ [N, K] -> [B, K]\n        # Gradients use e5m2 (wider range), weights use e4m3 (higher precision)\n        go_fp8, go_inv = _to_fp8(grad_output, torch.float8_e5m2)\n        # go_fp8 is [B, N] contiguous = row-major, good for first arg\n        # w_fp8 is [N, K] contiguous = row-major, need column-major for second arg\n        w_col = _to_col_major(w_fp8)\n        grad_input = torch._scaled_mm(\n            go_fp8,\n            w_col,\n            scale_a=go_inv,\n            scale_b=w_inv,\n            out_dtype=grad_output.dtype,\n            use_fast_accum=False,\n        )\n\n        # === GEMM 2: grad_weight = grad_output.T @ input ===\n        # Shapes: [N, B] @ [B, K] -> [N, K]\n        # go_fp8 is [B, N] contiguous, we need go.T = [N, B] as first arg.\n        # Transposing gives column-major, but first arg needs row-major,\n        # so we must call .contiguous() to physically rearrange the memory.\n        go_T = go_fp8.t().contiguous()  # [N, B] row-major\n        in_col = _to_col_major(in_fp8)    # [B, K] column-major\n        grad_weight = torch._scaled_mm(\n            go_T,\n            in_col,\n            scale_a=go_inv,\n            scale_b=in_inv,\n            out_dtype=grad_output.dtype,\n            use_fast_accum=False,\n        )\n\n        return grad_input, grad_weight\n\n\nclass Float8Linear(nn.Linear):\n    \"\"\"Drop-in nn.Linear replacement that does FP8 compute.\n\n    Weights and biases remain in their original precision (e.g. fp32/bf16).\n    Only the matmul is performed in FP8 via the _Float8Matmul autograd function.\n    \"\"\"\n\n    def forward(self, input):\n        # Cast input to COMPUTE_DTYPE (typically bf16) since _scaled_mm expects\n        # reduced precision input, and we no longer rely on autocast to do this.\n        input = input.to(COMPUTE_DTYPE)\n        # _scaled_mm only works on 2D tensors, so flatten batch dimensions\n        orig_shape = input.shape\n        input_2d = input.reshape(-1, orig_shape[-1])\n        output = _Float8Matmul.apply(input_2d, self.weight)\n        output = output.reshape(*orig_shape[:-1], output.shape[-1])\n        if self.bias is not None:\n            output = output + self.bias.to(output.dtype)\n        return output\n\n    @classmethod\n    def from_float(cls, mod):\n        \"\"\"Create Float8Linear from nn.Linear, sharing the same weight and bias.\n\n        Uses meta device to avoid allocating a temporary weight tensor — we\n        create the module shell on meta (shapes/dtypes only, no memory), then\n        point .weight and .bias to the original module's parameters.\n        \"\"\"\n        with torch.device(\"meta\"):\n            new_mod = cls(mod.in_features, mod.out_features, bias=False)\n        new_mod.weight = mod.weight\n        new_mod.bias = mod.bias\n        return new_mod\n\n\nclass Float8LinearConfig:\n    \"\"\"Minimal config matching torchao's API. Only tensorwise recipe is supported.\"\"\"\n\n    @staticmethod\n    def from_recipe_name(recipe_name):\n        if recipe_name != \"tensorwise\":\n            raise ValueError(\n                f\"Only 'tensorwise' recipe is supported, got '{recipe_name}'. \"\n                f\"Rowwise/axiswise recipes require the full torchao library.\"\n            )\n        return Float8LinearConfig()\n\n\ndef convert_to_float8_training(module, *, config=None, module_filter_fn=None):\n    \"\"\"Replace nn.Linear layers with Float8Linear throughout a module.\n\n    Walks the module tree in post-order (children before parents) and swaps\n    each nn.Linear that passes the optional filter. The new Float8Linear shares\n    the original weight and bias tensors — no copies, no extra memory.\n\n    Args:\n        module: Root module to convert.\n        config: Float8LinearConfig (accepted for API compat, only tensorwise supported).\n        module_filter_fn: Optional filter(module, fqn) -> bool. Only matching Linears\n            are converted. Common use: skip layers with dims not divisible by 16\n            (hardware requirement for FP8 matmuls on H100).\n    \"\"\"\n    def _convert(mod, prefix=\"\"):\n        for name, child in mod.named_children():\n            fqn = f\"{prefix}.{name}\" if prefix else name\n            _convert(child, fqn)\n            if isinstance(child, nn.Linear) and not isinstance(child, Float8Linear):\n                if module_filter_fn is None or module_filter_fn(child, fqn):\n                    setattr(mod, name, Float8Linear.from_float(child))\n\n    _convert(module)\n    return module\n"
  },
  {
    "path": "nanochat/gpt.py",
    "content": "\"\"\"\nGPT model (rewrite, a lot simpler)\nNotable features:\n- rotary embeddings (and no positional embeddings)\n- QK norm\n- untied weights for token embedding and lm_head\n- relu^2 activation in MLP\n- norm after token embedding\n- no learnable params in rmsnorm\n- no bias in linear layers\n- Group-Query Attention (GQA) support for more efficient inference\n- Flash Attention 3 integration\n\"\"\"\n\nfrom functools import partial\nfrom dataclasses import dataclass\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom nanochat.common import get_dist_info, print0, COMPUTE_DTYPE\nfrom nanochat.optim import MuonAdamW, DistMuonAdamW\n\n# Our custom Flash Attention module that automatically uses FA3 on Hopper+ and SDPA fallback elsewhere\nfrom nanochat.flash_attention import flash_attn\n\n@dataclass\nclass GPTConfig:\n    sequence_len: int = 2048\n    vocab_size: int = 32768\n    n_layer: int = 12\n    n_head: int = 6 # number of query heads\n    n_kv_head: int = 6 # number of key/value heads (GQA)\n    n_embd: int = 768\n    # Sliding window attention pattern string, tiled across layers. Final layer always L.\n    # Characters: L=long (full context), S=short (quarter context)\n    # Examples: \"L\"=all full context, \"SL\"=alternating, \"SSL\"=two short then one long\n    window_pattern: str = \"SSSL\"\n\n\ndef norm(x):\n    return F.rms_norm(x, (x.size(-1),)) # note that this will run in bf16, seems ok\n\nclass Linear(nn.Linear):\n    \"\"\"nn.Linear that casts weights to match input dtype in forward.\n    Replaces autocast: master weights stay fp32 for optimizer precision,\n    but matmuls run in the activation dtype (typically bf16 from embeddings).\"\"\"\n    def forward(self, x):\n        return F.linear(x, self.weight.to(dtype=x.dtype))\n\n\ndef has_ve(layer_idx, n_layer):\n    \"\"\"Returns True if GPT layer should have Value Embedding (alternating, last layer always included).\"\"\"\n    return layer_idx % 2 == (n_layer - 1) % 2\n\ndef apply_rotary_emb(x, cos, sin):\n    assert x.ndim == 4  # multihead attention\n    d = x.shape[3] // 2\n    x1, x2 = x[..., :d], x[..., d:] # split up last dim into two halves\n    y1 = x1 * cos + x2 * sin # rotate pairs of dims\n    y2 = x1 * (-sin) + x2 * cos\n    return torch.cat([y1, y2], 3)\n\nclass CausalSelfAttention(nn.Module):\n    def __init__(self, config, layer_idx):\n        super().__init__()\n        self.layer_idx = layer_idx\n        self.n_head = config.n_head\n        self.n_kv_head = config.n_kv_head\n        self.n_embd = config.n_embd\n        self.head_dim = self.n_embd // self.n_head\n        assert self.n_embd % self.n_head == 0\n        assert self.n_kv_head <= self.n_head and self.n_head % self.n_kv_head == 0\n        self.c_q = Linear(self.n_embd, self.n_head * self.head_dim, bias=False)\n        self.c_k = Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False)\n        self.c_v = Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False)\n        self.c_proj = Linear(self.n_embd, self.n_embd, bias=False)\n        self.ve_gate_channels = 12\n        self.ve_gate = Linear(self.ve_gate_channels, self.n_kv_head, bias=False) if has_ve(layer_idx, config.n_layer) else None\n\n    def forward(self, x, ve, cos_sin, window_size, kv_cache):\n        B, T, C = x.size()\n\n        # Project the input to get queries, keys, and values\n        # Shape: (B, T, H, D) - FA3's native layout, no transpose needed!\n        q = self.c_q(x).view(B, T, self.n_head, self.head_dim)\n        k = self.c_k(x).view(B, T, self.n_kv_head, self.head_dim)\n        v = self.c_v(x).view(B, T, self.n_kv_head, self.head_dim)\n\n        # Value residual (ResFormer): mix in value embedding with input-dependent gate per head\n        if ve is not None:\n            ve = ve.view(B, T, self.n_kv_head, self.head_dim)\n            gate = 3 * torch.sigmoid(self.ve_gate(x[..., :self.ve_gate_channels]))  # (B, T, n_kv_head), range (0, 3)\n            v = v + gate.unsqueeze(-1) * ve\n\n        # Apply Rotary Embeddings to queries and keys to get relative positional encoding\n        cos, sin = cos_sin\n        q, k = apply_rotary_emb(q, cos, sin), apply_rotary_emb(k, cos, sin)\n        q, k = norm(q), norm(k) # QK norm\n        q = q * 1.2  # sharper attention (split scale between Q and K), TODO think through better\n        k = k * 1.2\n\n        # Flash Attention (FA3 on Hopper+, PyTorch SDPA fallback elsewhere)\n        # window_size is (left, right) tuple: (N, 0) for causal, (-1, 0) for full context\n        if kv_cache is None:\n            # Training: causal attention with optional sliding window\n            y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=window_size)\n        else:\n            # Inference: use flash_attn_with_kvcache which handles cache management\n            k_cache, v_cache = kv_cache.get_layer_cache(self.layer_idx)\n            y = flash_attn.flash_attn_with_kvcache(\n                q, k_cache, v_cache,\n                k=k, v=v,\n                cache_seqlens=kv_cache.cache_seqlens,\n                causal=True,\n                window_size=window_size,\n            )\n            # Advance position after last layer processes\n            if self.layer_idx == kv_cache.n_layers - 1:\n                kv_cache.advance(T)\n\n        # Re-assemble the heads and project back to residual stream\n        y = y.contiguous().view(B, T, -1)\n        y = self.c_proj(y)\n        return y\n\n\nclass MLP(nn.Module):\n    def __init__(self, config):\n        super().__init__()\n        self.c_fc = Linear(config.n_embd, 4 * config.n_embd, bias=False)\n        self.c_proj = Linear(4 * config.n_embd, config.n_embd, bias=False)\n\n    def forward(self, x):\n        x = self.c_fc(x)\n        x = F.relu(x).square()\n        x = self.c_proj(x)\n        return x\n\n\nclass Block(nn.Module):\n    def __init__(self, config, layer_idx):\n        super().__init__()\n        self.attn = CausalSelfAttention(config, layer_idx)\n        self.mlp = MLP(config)\n\n    def forward(self, x, ve, cos_sin, window_size, kv_cache):\n        x = x + self.attn(norm(x), ve, cos_sin, window_size, kv_cache)\n        x = x + self.mlp(norm(x))\n        return x\n\n\nclass GPT(nn.Module):\n    def __init__(self, config, pad_vocab_size_to=64):\n        \"\"\"\n        NOTE a major footgun: this __init__ function runs in meta device context (!!)\n        Therefore, any calculations inside here are shapes and dtypes only, no actual data.\n        => We actually initialize all data (parameters, buffers, etc.) in init_weights() instead.\n        \"\"\"\n        super().__init__()\n        self.config = config\n        # Compute per-layer window sizes for sliding window attention\n        # window_size is (left, right) tuple: (-1, 0) for full context, (N, 0) for sliding window\n        self.window_sizes = self._compute_window_sizes(config)\n        # Pad vocab for efficiency (DDP, tensor cores). This is just an optimization - outputs are cropped in forward().\n        # https://huggingface.co/docs/transformers/main_classes/model#transformers.PreTrainedModel.resize_token_embeddings\n        padded_vocab_size = ((config.vocab_size + pad_vocab_size_to - 1) // pad_vocab_size_to) * pad_vocab_size_to\n        if padded_vocab_size != config.vocab_size:\n            print0(f\"Padding vocab_size from {config.vocab_size} to {padded_vocab_size} for efficiency\")\n        self.transformer = nn.ModuleDict({\n            \"wte\": nn.Embedding(padded_vocab_size, config.n_embd),\n            \"h\": nn.ModuleList([Block(config, layer_idx) for layer_idx in range(config.n_layer)]),\n        })\n        self.lm_head = Linear(config.n_embd, padded_vocab_size, bias=False)\n        # Per-layer learnable scalars (inspired by modded-nanogpt)\n        # resid_lambdas: scales the residual stream at each layer (init 1.0 = neutral)\n        # x0_lambdas: blends initial embedding back in at each layer (init 0.0 = disabled)\n        # Separate parameters so they can have different optimizer treatment\n        self.resid_lambdas = nn.Parameter(torch.ones(config.n_layer))   # fake init, real init in init_weights()\n        self.x0_lambdas = nn.Parameter(torch.zeros(config.n_layer))     # fake init, real init in init_weights()\n        # Smear: mix previous token's embedding into current token (cheap bigram-like info)\n        self.smear_gate = Linear(24, 1, bias=False)\n        self.smear_lambda = nn.Parameter(torch.zeros(1))\n        # Backout: subtract cached mid-layer residual before final norm to remove low-level features\n        self.backout_lambda = nn.Parameter(0.2 * torch.ones(1))\n        # Value embeddings (ResFormer-style): alternating layers, last layer always included\n        head_dim = config.n_embd // config.n_head\n        kv_dim = config.n_kv_head * head_dim\n        self.value_embeds = nn.ModuleDict({str(i): nn.Embedding(padded_vocab_size, kv_dim) for i in range(config.n_layer) if has_ve(i, config.n_layer)})\n        # To support meta device initialization, we init the rotary embeddings here, but it's just \"fake\" meta tensors only.\n        # As for rotary_seq_len, these rotary embeddings are pretty small/cheap in memory,\n        # so let's just over-compute them by 10X, but assert fail if we ever reach that amount.\n        # In the future we can dynamically grow the cache, for now it's fine.\n        self.rotary_seq_len = config.sequence_len * 10 # 10X over-compute should be enough, TODO make nicer?\n        head_dim = config.n_embd // config.n_head\n        cos, sin = self._precompute_rotary_embeddings(self.rotary_seq_len, head_dim)\n        self.register_buffer(\"cos\", cos, persistent=False) # persistent=False means it's not saved to the checkpoint\n        self.register_buffer(\"sin\", sin, persistent=False)\n\n    @torch.no_grad()\n    def init_weights(self):\n        \"\"\"\n        Initialize the full model in this one function for maximum clarity.\n\n        wte (embedding):     normal, std=1.0\n        lm_head:             normal, std=0.001\n        for each block:\n            attn.c_q:        uniform, std=1/sqrt(n_embd)\n            attn.c_k:        uniform, std=1/sqrt(n_embd)\n            attn.c_v:        uniform, std=1/sqrt(n_embd)\n            attn.c_proj:     zeros\n            mlp.c_fc:        uniform, std=1/sqrt(n_embd)\n            mlp.c_proj:      zeros\n        \"\"\"\n\n        # Embedding and unembedding\n        torch.nn.init.normal_(self.transformer.wte.weight, mean=0.0, std=0.8)\n        torch.nn.init.normal_(self.lm_head.weight, mean=0.0, std=0.001)\n\n        # Transformer blocks: uniform init with bound = sqrt(3) * std (same standard deviation as normal)\n        n_embd = self.config.n_embd\n        s = 3**0.5 * n_embd**-0.5 # sqrt(3) multiplier makes sure Uniform achieves the same std as Normal\n        for block in self.transformer.h:\n            torch.nn.init.uniform_(block.attn.c_q.weight, -s, s) # weights use Uniform to avoid outliers\n            torch.nn.init.uniform_(block.attn.c_k.weight, -s, s)\n            torch.nn.init.uniform_(block.attn.c_v.weight, -s, s)\n            torch.nn.init.zeros_(block.attn.c_proj.weight) # projections are zero\n            torch.nn.init.uniform_(block.mlp.c_fc.weight, -s * 0.4, s * 0.4)  # 0.4x init scale for c_fc\n            torch.nn.init.zeros_(block.mlp.c_proj.weight)\n\n        # Per-layer scalars\n        # Per-layer resid init: stronger residual at early layers, weaker at deep layers\n        n_layer = self.config.n_layer\n        for i in range(n_layer):\n            self.resid_lambdas.data[i] = 1.15 - (0.10 * i / max(n_layer - 1, 1))\n        # Decaying x0 init: earlier layers get more input embedding blending\n        for i in range(n_layer):\n            self.x0_lambdas.data[i] = 0.20 - (0.15 * i / max(n_layer - 1, 1))\n\n        # Value embeddings (init like c_v: uniform with same std)\n        for ve in self.value_embeds.values():\n            torch.nn.init.uniform_(ve.weight, -s, s)\n\n        # Gate weights init with small positive values so gates start slightly above neutral\n        for block in self.transformer.h:\n            if block.attn.ve_gate is not None:\n                torch.nn.init.uniform_(block.attn.ve_gate.weight, 0.0, 0.02)\n\n        # Rotary embeddings\n        head_dim = self.config.n_embd // self.config.n_head\n        cos, sin = self._precompute_rotary_embeddings(self.rotary_seq_len, head_dim)\n        self.cos, self.sin = cos, sin\n\n        # Cast embeddings to COMPUTE_DTYPE: optimizer can tolerate reduced-precision\n        # embeddings and it saves memory. Exception: fp16 requires fp32 embeddings\n        # because GradScaler cannot unscale fp16 gradients.\n        if COMPUTE_DTYPE != torch.float16:\n            self.transformer.wte.to(dtype=COMPUTE_DTYPE)\n            for ve in self.value_embeds.values():\n                ve.to(dtype=COMPUTE_DTYPE)\n\n    def _precompute_rotary_embeddings(self, seq_len, head_dim, base=100000, device=None):\n        # TODO: bump base theta more? e.g. 100K is more common more recently\n        # autodetect the device from model embeddings\n        if device is None:\n            device = self.transformer.wte.weight.device\n        # stride the channels\n        channel_range = torch.arange(0, head_dim, 2, dtype=torch.float32, device=device)\n        inv_freq = 1.0 / (base ** (channel_range / head_dim))\n        # stride the time steps\n        t = torch.arange(seq_len, dtype=torch.float32, device=device)\n        # calculate the rotation frequencies at each (time, channel) pair\n        freqs = torch.outer(t, inv_freq)\n        cos, sin = freqs.cos(), freqs.sin()\n        cos, sin = cos.to(COMPUTE_DTYPE), sin.to(COMPUTE_DTYPE)\n        cos, sin = cos[None, :, None, :], sin[None, :, None, :] # add batch and head dims for later broadcasting\n        return cos, sin\n\n    def _compute_window_sizes(self, config):\n        \"\"\"\n        Compute per-layer window sizes for sliding window attention.\n\n        Returns list of (left, right) tuples for FA3's window_size parameter:\n        - left: how many tokens before current position to attend to (-1 = unlimited)\n        - right: how many tokens after current position to attend to (0 for causal)\n\n        Pattern string is tiled across layers. Final layer always gets L (full context).\n        Characters: L=long (full context), S=short (quarter context)\n        \"\"\"\n        pattern = config.window_pattern.upper()\n        assert all(c in \"SL\" for c in pattern), f\"Invalid window_pattern: {pattern}. Use only S and L.\"\n        # Map characters to window sizes\n        long_window = config.sequence_len\n        short_window = -(-long_window // 4 // 128) * 128  # ceil to FA3 tile size (2048 -> 768)\n        char_to_window = {\n            \"L\": (long_window, 0),\n            \"S\": (short_window, 0),\n        }\n        # Tile pattern across layers\n        window_sizes = []\n        for layer_idx in range(config.n_layer):\n            char = pattern[layer_idx % len(pattern)]\n            window_sizes.append(char_to_window[char])\n        # Final layer always gets full context\n        window_sizes[-1] = (long_window, 0)\n        return window_sizes\n\n    def get_device(self):\n        return self.transformer.wte.weight.device\n\n    def estimate_flops(self):\n        \"\"\"\n        Return the estimated FLOPs per token for the model (forward + backward).\n        Each matmul weight parameter contributes 2 FLOPs (multiply *, accumulate +) in forward, and 2X that in backward => 2+4=6.\n        Cleanest explanation of this: https://medium.com/@dzmitrybahdanau/the-flops-calculus-of-language-model-training-3b19c1f025e4\n        On top of that, 12 * h * q * effective_seq_len accounts for key @ query matmul flops inside attention.\n        With sliding windows, effective_seq_len varies per layer (capped by window size).\n        Ref: https://arxiv.org/abs/2204.02311 (PaLM paper).\n        This is ~1% off from the exact formulas of Chinchilla paper, the difference is:\n        - Chinchilla counts the embedding layer as flops (? weird, it's just a lookup => we ignore)\n        - Chinchilla counts exp/sum/divide in attention softmax as flops (a little sus and very tiny => we ignore)\n        \"\"\"\n        nparams = sum(p.numel() for p in self.parameters())\n        # Exclude non-matmul params: embeddings and per-layer scalars\n        value_embeds_numel = sum(ve.weight.numel() for ve in self.value_embeds.values())\n        nparams_exclude = (self.transformer.wte.weight.numel() + value_embeds_numel +\n                          self.resid_lambdas.numel() + self.x0_lambdas.numel() +\n                          self.smear_gate.weight.numel() + self.smear_lambda.numel() + self.backout_lambda.numel())\n        h, q, t = self.config.n_head, self.config.n_embd // self.config.n_head, self.config.sequence_len\n        # Sum attention FLOPs per layer, accounting for sliding window\n        attn_flops = 0\n        for window_size in self.window_sizes:\n            window = window_size[0]  # (left, right) tuple, we use left\n            effective_seq = t if window < 0 else min(window, t)\n            attn_flops += 12 * h * q * effective_seq\n        num_flops_per_token = 6 * (nparams - nparams_exclude) + attn_flops\n        return num_flops_per_token\n\n    def num_scaling_params(self):\n        \"\"\"\n        Return detailed parameter counts for scaling law analysis.\n        Different papers use different conventions:\n        - Kaplan et al. excluded embedding parameters\n        - Chinchilla included all parameters\n        Ref: https://arxiv.org/abs/2203.15556 (Chinchilla paper)\n        Ref: https://arxiv.org/abs/2001.08361 (Kaplan et al. original scaling laws paper)\n\n        Returns a dict with counts for each parameter group, so downstream analysis\n        can experiment with which combination gives the cleanest scaling laws.\n        \"\"\"\n        # Count each group separately (mirrors the grouping in setup_optimizers)\n        wte = sum(p.numel() for p in self.transformer.wte.parameters())\n        value_embeds = sum(p.numel() for p in self.value_embeds.parameters())\n        lm_head = sum(p.numel() for p in self.lm_head.parameters())\n        transformer_matrices = sum(p.numel() for p in self.transformer.h.parameters())\n        scalars = self.resid_lambdas.numel() + self.x0_lambdas.numel() + self.smear_gate.weight.numel() + self.smear_lambda.numel() + self.backout_lambda.numel()\n        total = wte + value_embeds + lm_head + transformer_matrices + scalars\n        assert total == sum(p.numel() for p in self.parameters()), \"Parameter count mismatch\"\n        return {\n            'wte': wte,\n            'value_embeds': value_embeds,\n            'lm_head': lm_head,\n            'transformer_matrices': transformer_matrices,\n            'scalars': scalars,\n            'total': total,\n        }\n\n    def setup_optimizer(self, unembedding_lr=0.004, embedding_lr=0.2, matrix_lr=0.02, weight_decay=0.0, scalar_lr=0.5):\n        model_dim = self.config.n_embd\n        ddp, rank, local_rank, world_size = get_dist_info()\n\n        # Separate out all parameters into groups\n        matrix_params = list(self.transformer.h.parameters())\n        value_embeds_params = list(self.value_embeds.parameters())\n        embedding_params = list(self.transformer.wte.parameters())\n        lm_head_params = list(self.lm_head.parameters())\n        resid_params = [self.resid_lambdas]\n        x0_params = [self.x0_lambdas]\n        smear_params = [self.smear_gate.weight, self.smear_lambda, self.backout_lambda]\n        assert len(list(self.parameters())) == len(matrix_params) + len(embedding_params) + len(lm_head_params) + len(value_embeds_params) + len(resid_params) + len(x0_params) + len(smear_params)\n\n        # Scale the LR for the AdamW parameters by ∝1/√dmodel (tuned for 768 dim model)\n        dmodel_lr_scale = (model_dim / 768) ** -0.5\n        print0(f\"Scaling the LR for the AdamW parameters ∝1/√({model_dim}/768) = {dmodel_lr_scale:.6f}\")\n\n        # Build param_groups with all required fields explicit\n        param_groups = [\n            # AdamW groups (embeddings, lm_head, scalars)\n            dict(kind='adamw', params=lm_head_params, lr=unembedding_lr * dmodel_lr_scale, betas=(0.8, 0.96), eps=1e-10, weight_decay=0.01),\n            dict(kind='adamw', params=embedding_params, lr=embedding_lr * dmodel_lr_scale, betas=(0.8, 0.995), eps=1e-10, weight_decay=0.001),\n            dict(kind='adamw', params=value_embeds_params, lr=embedding_lr * dmodel_lr_scale * 0.5, betas=(0.8, 0.995), eps=1e-10, weight_decay=0.01),\n            dict(kind='adamw', params=resid_params, lr=scalar_lr * 0.01, betas=(0.8, 0.95), eps=1e-10, weight_decay=0.05),\n            dict(kind='adamw', params=x0_params, lr=scalar_lr, betas=(0.96, 0.95), eps=1e-10, weight_decay=0.0),  # higher beta1 for x0\n            dict(kind='adamw', params=smear_params, lr=0.2, betas=(0.8, 0.95), eps=1e-10, weight_decay=0.0),\n        ]\n        # Muon groups (matrix params, grouped by shape for stacking)\n        for shape in sorted({p.shape for p in matrix_params}):\n            group_params = [p for p in matrix_params if p.shape == shape]\n            param_groups.append(dict(\n                kind='muon', params=group_params, lr=matrix_lr,\n                momentum=0.95, ns_steps=5, beta2=0.9, weight_decay=weight_decay,\n            ))\n\n        Factory = DistMuonAdamW if ddp else MuonAdamW\n        optimizer = Factory(param_groups)\n        for group in optimizer.param_groups:\n            group[\"initial_lr\"] = group[\"lr\"]\n        return optimizer\n\n    def forward(self, idx, targets=None, kv_cache=None, loss_reduction='mean'):\n        B, T = idx.size()\n\n        # Grab the rotary embeddings for the current sequence length (they are of shape (1, seq_len, 1, head_dim/2))\n        assert T <= self.cos.size(1), f\"Sequence length grew beyond the rotary embeddings cache: {T} > {self.cos.size(1)}\"\n        assert idx.device == self.cos.device, f\"Rotary embeddings and idx are on different devices: {idx.device} != {self.cos.device}\"\n        assert self.cos.dtype == COMPUTE_DTYPE, f\"Rotary embeddings must be in {COMPUTE_DTYPE}, got {self.cos.dtype}\"\n        # if kv cache exists, we need to offset the rotary embeddings to the current position in the cache\n        T0 = 0 if kv_cache is None else kv_cache.get_pos()\n        cos_sin = self.cos[:, T0:T0+T], self.sin[:, T0:T0+T] # truncate cache to current sequence length\n\n        # Embed the tokens\n        x = self.transformer.wte(idx) # embed current token\n        x = x.to(COMPUTE_DTYPE) # ensure activations are in compute dtype (no-op usually, but active for fp16 code path)\n        x = norm(x)\n\n        # Smear: mix previous token's embedding into current position (cheap bigram info)\n        if kv_cache is None:\n            # Training / naive generate: full sequence available, use fast slice\n            assert T > 1, \"Training forward pass should have T > 1\"\n            gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, 1:, :24]))\n            x = torch.cat([x[:, :1], x[:, 1:] + gate * x[:, :-1]], dim=1)\n        else:\n            # KV cache inference: read prev embedding from cache, store current for next step\n            x_pre_smear = kv_cache.prev_embedding\n            kv_cache.prev_embedding = x[:, -1:, :]\n            if T > 1:\n                # Prefill: apply smear to positions 1+, same as training\n                gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, 1:, :24]))\n                x = torch.cat([x[:, :1], x[:, 1:] + gate * x[:, :-1]], dim=1)\n            elif x_pre_smear is not None:\n                # Decode: single token, use cached prev embedding\n                gate = self.smear_lambda.to(x.dtype) * torch.sigmoid(self.smear_gate(x[:, :, :24]))\n                x = x + gate * x_pre_smear\n\n        # Forward the trunk of the Transformer\n        x0 = x  # save initial normalized embedding for x0 residual\n        n_layer = self.config.n_layer\n        backout_layer = n_layer // 2  # cache at halfway point\n        x_backout = None\n        for i, block in enumerate(self.transformer.h):\n            x = self.resid_lambdas[i] * x + self.x0_lambdas[i] * x0\n            ve = self.value_embeds[str(i)](idx).to(x.dtype) if str(i) in self.value_embeds else None\n            x = block(x, ve, cos_sin, self.window_sizes[i], kv_cache)\n            if i == backout_layer:\n                x_backout = x\n        # Subtract mid-layer residual to remove low-level features before logit projection\n        if x_backout is not None:\n            x = x - self.backout_lambda.to(x.dtype) * x_backout\n        x = norm(x)\n\n        # Forward the lm_head (compute logits)\n        softcap = 15 # smoothly cap the logits to the range [-softcap, softcap]\n        logits = self.lm_head(x) # (B, T, padded_vocab_size) <- very big tensor, large amount of memory\n        logits = logits[..., :self.config.vocab_size] # slice to remove padding\n        logits = logits.float() # switch to fp32 for logit softcap and loss computation\n        logits = softcap * torch.tanh(logits / softcap) # squash the logits\n\n        if targets is not None:\n            # training: given the targets, compute and return the loss\n            # TODO experiment with chunked cross-entropy?\n            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1, reduction=loss_reduction)\n            return loss\n        else:\n            # inference: just return the logits directly\n            return logits\n\n    @torch.inference_mode()\n    def generate(self, tokens, max_tokens, temperature=1.0, top_k=None, seed=42):\n        \"\"\"\n        Naive autoregressive streaming inference.\n        To make it super simple, let's assume:\n        - batch size is 1\n        - ids and the yielded tokens are simple Python lists and ints\n        \"\"\"\n        assert isinstance(tokens, list)\n        device = self.get_device()\n        rng = None\n        if temperature > 0:\n            rng = torch.Generator(device=device)\n            rng.manual_seed(seed)\n        ids = torch.tensor([tokens], dtype=torch.long, device=device) # add batch dim\n        for _ in range(max_tokens):\n            logits = self.forward(ids) # (B, T, vocab_size)\n            logits = logits[:, -1, :] # (B, vocab_size)\n            if top_k is not None and top_k > 0:\n                v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n                logits[logits < v[:, [-1]]] = -float('Inf')\n            if temperature > 0:\n                logits = logits / temperature\n                probs = F.softmax(logits, dim=-1)\n                next_ids = torch.multinomial(probs, num_samples=1, generator=rng)\n            else:\n                next_ids = torch.argmax(logits, dim=-1, keepdim=True)\n            ids = torch.cat((ids, next_ids), dim=1)\n            token = next_ids.item()\n            yield token\n"
  },
  {
    "path": "nanochat/loss_eval.py",
    "content": "\"\"\"\nA number of functions that help with evaluating a base model.\n\"\"\"\nimport math\nimport torch\nimport torch.distributed as dist\n\n@torch.no_grad()\ndef evaluate_bpb(model, batches, steps, token_bytes):\n    \"\"\"\n    Instead of the naive 'mean loss', this function returns the bits per byte (bpb),\n    which is a tokenization vocab size-independent metric, meaning you are still comparing\n    apples:apples if you change the vocab size. The way this works is that instead of just\n    calculating the average loss as usual, you calculate the sum loss, and independently\n    also the sum bytes (of all the target tokens), and divide. This normalizes the loss by\n    the number of bytes that the target tokens represent.\n\n    The added complexity is so that:\n    1) All \"normal\" tokens are normalized by the length of the token in bytes\n    2) No special tokens (e.g. <|bos|>) are included in the metric - they are masked out.\n    3) No actively masked tokens (using ignore_index of e.g. -1) are included in the metric.\n\n    In addition to evaluate_loss, we need the token_bytes tensor:\n    It is a 1D tensor of shape (vocab_size,), indicating the number of bytes for\n    each token id, or 0 if the token is to not be counted (e.g. special tokens).\n    \"\"\"\n    # record the losses\n    total_nats = torch.tensor(0.0, dtype=torch.float32, device=model.get_device())\n    total_bytes = torch.tensor(0, dtype=torch.int64, device=model.get_device())\n    batch_iter = iter(batches)\n    for _ in range(steps):\n        x, y = next(batch_iter)\n        loss2d = model(x, y, loss_reduction='none') # (B, T)\n        loss2d = loss2d.view(-1) # flatten\n        y = y.view(-1) # flatten\n        if (y.int() < 0).any(): # mps does not currently have kernel for < 0 for int64, only int32\n            # slightly more complex code path if some target tokens are ignore_index (e.g. -1)\n            # any target token < 0 is to be ignored: do NOT index token_bytes with negatives\n            valid = y >= 0\n            y_safe = torch.where(valid, y, torch.zeros_like(y))\n            # map valid targets to their byte length; ignored targets contribute 0 bytes\n            num_bytes2d = torch.where(\n                valid,\n                token_bytes[y_safe],\n                torch.zeros_like(y, dtype=token_bytes.dtype)\n            )\n            total_nats += (loss2d * (num_bytes2d > 0)).sum()\n            total_bytes += num_bytes2d.sum()\n        else:\n            # fast path: no ignored targets, safe to index directly\n            num_bytes2d = token_bytes[y]\n            total_nats += (loss2d * (num_bytes2d > 0)).sum()\n            total_bytes += num_bytes2d.sum()\n    # sum reduce across all ranks\n    world_size = dist.get_world_size() if dist.is_initialized() else 1\n    if world_size > 1:\n        dist.all_reduce(total_nats, op=dist.ReduceOp.SUM)\n        dist.all_reduce(total_bytes, op=dist.ReduceOp.SUM)\n    # move both to cpu, calculate bpb and return\n    total_nats = total_nats.item()\n    total_bytes = total_bytes.item()\n    if total_bytes == 0:\n        return float('inf')\n    bpb = total_nats / (math.log(2) * total_bytes)\n    return bpb\n"
  },
  {
    "path": "nanochat/optim.py",
    "content": "\"\"\"\nA nice and efficient mixed AdamW/Muon Combined Optimizer.\nUsually the embeddings and scalars go into AdamW, and the matrix parameters go into Muon.\nTwo versions are provided (MuonAdamW, DistMuonAdamW), for single GPU and distributed.\n\nAddapted from: https://github.com/KellerJordan/modded-nanogpt\nFurther contributions from @karpathy and @chrisjmccormick.\n\"\"\"\n\nimport torch\nimport torch.distributed as dist\nfrom torch import Tensor\n\n# -----------------------------------------------------------------------------\n\"\"\"\nGood old AdamW optimizer, fused kernel.\nhttps://arxiv.org/abs/1711.05101\n\"\"\"\n\n@torch.compile(dynamic=False, fullgraph=True)\ndef adamw_step_fused(\n    p: Tensor,              # (32768, 768) - parameter tensor\n    grad: Tensor,           # (32768, 768) - gradient, same shape as p\n    exp_avg: Tensor,        # (32768, 768) - first moment, same shape as p\n    exp_avg_sq: Tensor,     # (32768, 768) - second moment, same shape as p\n    step_t: Tensor,         # () - 0-D CPU tensor, step count\n    lr_t: Tensor,           # () - 0-D CPU tensor, learning rate\n    beta1_t: Tensor,        # () - 0-D CPU tensor, beta1\n    beta2_t: Tensor,        # () - 0-D CPU tensor, beta2\n    eps_t: Tensor,          # () - 0-D CPU tensor, epsilon\n    wd_t: Tensor,           # () - 0-D CPU tensor, weight decay\n) -> None:\n    \"\"\"\n    Fused AdamW step: weight_decay -> momentum_update -> bias_correction -> param_update\n    All in one compiled graph to eliminate Python overhead between ops.\n    The 0-D CPU tensors avoid recompilation when hyperparameter values change.\n    \"\"\"\n    # Weight decay (decoupled, applied before the update)\n    p.mul_(1 - lr_t * wd_t)\n    # Update running averages (lerp_ is cleaner and fuses well)\n    exp_avg.lerp_(grad, 1 - beta1_t)\n    exp_avg_sq.lerp_(grad.square(), 1 - beta2_t)\n    # Bias corrections\n    bias1 = 1 - beta1_t ** step_t\n    bias2 = 1 - beta2_t ** step_t\n    # Compute update and apply\n    denom = (exp_avg_sq / bias2).sqrt() + eps_t\n    step_size = lr_t / bias1\n    p.add_(exp_avg / denom, alpha=-step_size)\n\n# -----------------------------------------------------------------------------\n\"\"\"\nMuon optimizer adapted and simplified from modded-nanogpt.\nhttps://github.com/KellerJordan/modded-nanogpt\n\nBackground:\nNewton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a\nquintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose\nof minimizing steps, it turns out to be empirically effective to keep increasing the slope at\nzero even beyond the point where the iteration no longer converges all the way to one everywhere\non the interval. This iteration therefore does not produce UV^T but rather something like US'V^T\nwhere S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model\nperformance at all relative to UV^T, where USV^T = G is the SVD.\n\nHere, an alternative to Newton-Schulz iteration with potentially better convergence properties:\nPolar Express Sign Method for orthogonalization.\nhttps://arxiv.org/pdf/2505.16932\nby Noah Amsel, David Persson, Christopher Musco, Robert M. Gower.\n\nNorMuon variance reduction: per-neuron/column adaptive learning rate that normalizes\nupdate scales after orthogonalization (Muon's output has non-uniform scales across neurons).\nhttps://arxiv.org/pdf/2510.05491\n\nSome of the changes in nanochat implementation:\n- Uses a simpler, more general approach to parameter grouping and stacking\n- Uses a single fused kernel for the momentum -> polar_express -> variance_reduction -> update step\n- Makes no assumptions about model architecture (e.g. that attention weights are fused into QKVO format)\n\"\"\"\n\n# Coefficients for Polar Express (computed for num_iters=5, safety_factor=2e-2, cushion=2)\n# From https://arxiv.org/pdf/2505.16932\npolar_express_coeffs = [\n    (8.156554524902461, -22.48329292557795, 15.878769915207462),\n    (4.042929935166739, -2.808917465908714, 0.5000178451051316),\n    (3.8916678022926607, -2.772484153217685, 0.5060648178503393),\n    (3.285753657755655, -2.3681294933425376, 0.46449024233003106),\n    (2.3465413258596377, -1.7097828382687081, 0.42323551169305323),\n]\n\n@torch.compile(dynamic=False, fullgraph=True)\ndef muon_step_fused(\n    stacked_grads: Tensor,          # (12, 768, 3072) - stacked gradients\n    stacked_params: Tensor,         # (12, 768, 3072) - stacked parameters\n    momentum_buffer: Tensor,        # (12, 768, 3072) - first moment buffer\n    second_momentum_buffer: Tensor, # (12, 768, 1) or (12, 1, 3072) - factored second moment\n    momentum_t: Tensor,             # () - 0-D CPU tensor, momentum coefficient\n    lr_t: Tensor,                   # () - 0-D CPU tensor, learning rate\n    wd_t: Tensor,                   # () - 0-D CPU tensor, weight decay\n    beta2_t: Tensor,                # () - 0-D CPU tensor, beta2 for second moment\n    ns_steps: int,                  # 5 - number of Newton-Schulz/Polar Express iterations\n    red_dim: int,                   # -1 or -2 - reduction dimension for variance\n) -> None:\n    \"\"\"\n    Fused Muon step: momentum -> polar_express -> variance_reduction -> cautious_update\n    All in one compiled graph to eliminate Python overhead between ops.\n    Some of the constants are 0-D CPU tensors to avoid recompilation when values change.\n    \"\"\"\n\n    # Nesterov momentum\n    momentum = momentum_t.to(stacked_grads.dtype)\n    momentum_buffer.lerp_(stacked_grads, 1 - momentum)\n    g = stacked_grads.lerp_(momentum_buffer, momentum)\n\n    # Polar express\n    X = g.bfloat16()\n    X = X / (X.norm(dim=(-2, -1), keepdim=True) * 1.01 + 1e-6)\n    if g.size(-2) > g.size(-1): # Tall matrix\n        for a, b, c in polar_express_coeffs[:ns_steps]:\n            A = X.mT @ X\n            B = b * A + c * (A @ A)\n            X = a * X + X @ B\n    else: # Wide matrix (original math)\n        for a, b, c in polar_express_coeffs[:ns_steps]:\n            A = X @ X.mT\n            B = b * A + c * (A @ A)\n            X = a * X + B @ X\n    g = X\n\n    # Variance reduction\n    beta2 = beta2_t.to(g.dtype)\n    v_mean = g.float().square().mean(dim=red_dim, keepdim=True)\n    red_dim_size = g.size(red_dim)\n    v_norm_sq = v_mean.sum(dim=(-2, -1), keepdim=True) * red_dim_size\n    v_norm = v_norm_sq.sqrt()\n    second_momentum_buffer.lerp_(v_mean.to(dtype=second_momentum_buffer.dtype), 1 - beta2)\n    step_size = second_momentum_buffer.clamp_min(1e-10).rsqrt()\n    scaled_sq_sum = (v_mean * red_dim_size) * step_size.float().square()\n    v_norm_new = scaled_sq_sum.sum(dim=(-2, -1), keepdim=True).sqrt()\n    final_scale = step_size * (v_norm / v_norm_new.clamp_min(1e-10))\n    g = g * final_scale.to(g.dtype)\n\n    # Cautious weight decay + parameter update\n    lr = lr_t.to(g.dtype)\n    wd = wd_t.to(g.dtype)\n    mask = (g * stacked_params) >= 0\n    stacked_params.sub_(lr * g + lr * wd * stacked_params * mask)\n\n# -----------------------------------------------------------------------------\n# Single GPU version of the MuonAdamW optimizer.\n# Used mostly for reference, debugging and testing.\n\nclass MuonAdamW(torch.optim.Optimizer):\n    \"\"\"\n    Combined optimizer: Muon for 2D matrix params, AdamW for others, single GPU version.\n\n    AdamW - Fused AdamW optimizer step.\n\n    Muon - MomentUm Orthogonalized by Newton-schulz\n    https://kellerjordan.github.io/posts/muon/\n\n    Muon internally runs standard SGD-momentum, and then performs an orthogonalization post-\n    processing step, in which each 2D parameter's update is replaced with the nearest orthogonal\n    matrix. To efficiently orthogonalize each update, we use a Newton-Schulz iteration, which has\n    the advantage that it can be stably run in bfloat16 on the GPU.\n\n    Some warnings:\n    - The Muon optimizer should not be used for the embedding layer, the final fully connected layer,\n    or any {0,1}-D parameters; those should all be optimized by a standard method (e.g., AdamW).\n    - To use it with 4D convolutional filters, it works well to just flatten their last 3 dimensions.\n\n    Arguments:\n        param_groups: List of dicts, each containing:\n            - 'params': List of parameters\n            - 'kind': 'adamw' or 'muon'\n            - For AdamW groups: 'lr', 'betas', 'eps', 'weight_decay'\n            - For Muon groups: 'lr', 'momentum', 'ns_steps', 'beta2', 'weight_decay'\n    \"\"\"\n    def __init__(self, param_groups: list[dict]):\n        super().__init__(param_groups, defaults={})\n        # 0-D CPU tensors to avoid torch.compile recompilation when values change\n        # AdamW tensors\n        self._adamw_step_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_lr_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_beta1_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_beta2_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_eps_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_wd_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        # Muon tensors\n        self._muon_momentum_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_lr_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_wd_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_beta2_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n\n    def _step_adamw(self, group: dict) -> None:\n        \"\"\"\n        AdamW update for each param in the group individually.\n        Lazy init the state, fill in all 0-D tensors, call the fused kernel.\n        \"\"\"\n        for p in group['params']:\n            if p.grad is None:\n                continue\n            grad = p.grad\n            state = self.state[p]\n\n            # State init\n            if not state:\n                state['step'] = 0\n                state['exp_avg'] = torch.zeros_like(p)\n                state['exp_avg_sq'] = torch.zeros_like(p)\n            exp_avg = state['exp_avg']\n            exp_avg_sq = state['exp_avg_sq']\n            state['step'] += 1\n\n            # Fill 0-D tensors with current values\n            self._adamw_step_t.fill_(state['step'])\n            self._adamw_lr_t.fill_(group['lr'])\n            self._adamw_beta1_t.fill_(group['betas'][0])\n            self._adamw_beta2_t.fill_(group['betas'][1])\n            self._adamw_eps_t.fill_(group['eps'])\n            self._adamw_wd_t.fill_(group['weight_decay'])\n\n            # Fused update: weight_decay -> momentum -> bias_correction -> param_update\n            adamw_step_fused(\n                p, grad, exp_avg, exp_avg_sq,\n                self._adamw_step_t, self._adamw_lr_t, self._adamw_beta1_t,\n                self._adamw_beta2_t, self._adamw_eps_t, self._adamw_wd_t,\n            )\n\n    def _step_muon(self, group: dict) -> None:\n        \"\"\"\n        Muon update for all params in the group (stacked for efficiency).\n        Lazy init the state, fill in all 0-D tensors, call the fused kernel.\n        \"\"\"\n        params: list[Tensor] = group['params']\n        if not params:\n            return\n\n        # Get or create group-level buffers (stored in first param's state for convenience)\n        p = params[0]\n        state = self.state[p]\n        num_params = len(params)\n        shape, device, dtype = p.shape, p.device, p.dtype\n\n        # Momentum for every individual parameter\n        if \"momentum_buffer\" not in state:\n            state[\"momentum_buffer\"] = torch.zeros(num_params, *shape, dtype=dtype, device=device)\n        momentum_buffer = state[\"momentum_buffer\"]\n\n        # Second momentum buffer is factored, either per-row or per-column\n        if \"second_momentum_buffer\" not in state:\n            state_shape = (num_params, shape[-2], 1) if shape[-2] >= shape[-1] else (num_params, 1, shape[-1])\n            state[\"second_momentum_buffer\"] = torch.zeros(state_shape, dtype=dtype, device=device)\n        second_momentum_buffer = state[\"second_momentum_buffer\"]\n        red_dim = -1 if shape[-2] >= shape[-1] else -2\n\n        # Stack grads and params (NOTE: this assumes all params have the same shape)\n        stacked_grads = torch.stack([p.grad for p in params])\n        stacked_params = torch.stack(params)\n\n        # Fill all the 0-D tensors with current values\n        self._muon_momentum_t.fill_(group[\"momentum\"])\n        self._muon_beta2_t.fill_(group[\"beta2\"] if group[\"beta2\"] is not None else 0.0)\n        self._muon_lr_t.fill_(group[\"lr\"] * max(1.0, shape[-2] / shape[-1])**0.5)\n        self._muon_wd_t.fill_(group[\"weight_decay\"])\n\n        # Single fused kernel: momentum -> polar_express -> variance_reduction -> update\n        muon_step_fused(\n            stacked_grads,\n            stacked_params,\n            momentum_buffer,\n            second_momentum_buffer,\n            self._muon_momentum_t,\n            self._muon_lr_t,\n            self._muon_wd_t,\n            self._muon_beta2_t,\n            group[\"ns_steps\"],\n            red_dim,\n        )\n\n        # Copy back to original params\n        torch._foreach_copy_(params, list(stacked_params.unbind(0)))\n\n    @torch.no_grad()\n    def step(self):\n        for group in self.param_groups:\n            if group['kind'] == 'adamw':\n                self._step_adamw(group)\n            elif group['kind'] == 'muon':\n                self._step_muon(group)\n            else:\n                raise ValueError(f\"Unknown optimizer kind: {group['kind']}\")\n\n# -----------------------------------------------------------------------------\n# Distributed version of the MuonAdamW optimizer.\n# Used for training on multiple GPUs.\n\nclass DistMuonAdamW(torch.optim.Optimizer):\n    \"\"\"\n    Combined distributed optimizer: Muon for 2D matrix params, AdamW for others.\n\n    See MuonAdamW for the algorithmic details of each optimizer. This class adds\n    distributed communication to enable multi-GPU training without PyTorch DDP.\n\n    Design Goals:\n    - Overlap communication with computation (async ops)\n    - Minimize memory by sharding optimizer states across ranks (ZeRO-2 style)\n    - Batch small tensors into single comm ops where possible\n\n    Communication Pattern (3-phase async):\n    We use a 3-phase structure to maximize overlap between communication and compute:\n\n        Phase 1: Launch all async reduce ops\n            - Kick off all reduce_scatter/all_reduce operations\n            - Don't wait - let them run in background while we continue\n\n        Phase 2: Wait for reduces, compute updates, launch gathers\n            - For each group: wait for its reduce, compute the update, launch gather\n            - By processing groups in order, earlier gathers run while later computes happen\n\n        Phase 3: Wait for gathers, copy back\n            - Wait for all gathers to complete\n            - Copy updated params back to original tensors (Muon only)\n\n    AdamW Communication (ZeRO-2 style):\n    - Small params (<1024 elements): all_reduce gradients, update full param on each rank.\n      Optimizer state is replicated but these params are tiny (scalars, biases).\n    - Large params: reduce_scatter gradients so each rank gets 1/N of the grad, update\n      only that slice, then all_gather the updated slices. Optimizer state (exp_avg,\n      exp_avg_sq) is sharded - each rank only stores state for its slice.\n      Requires param.shape[0] divisible by world_size.\n\n    Muon Communication (stacked + chunked):\n    - All params in a Muon group must have the same shape (caller's responsibility).\n    - Stack all K params into a single (K, *shape) tensor for efficient comm.\n    - Divide K params across N ranks: each rank \"owns\" ceil(K/N) params.\n    - reduce_scatter the stacked grads so each rank gets its chunk.\n    - Each rank computes Muon update only for params it owns.\n    - all_gather the updated params back to all ranks.\n    - Optimizer state (momentum_buffer, second_momentum_buffer) is sharded by chunk.\n    - Padding: if K doesn't divide evenly, we zero-pad to (ceil(K/N) * N) for comm,\n      then ignore the padding when copying back.\n\n    Buffer Reuse:\n    - For Muon, we allocate stacked_grads for reduce_scatter input, then reuse the\n      same buffer as the output for all_gather (stacked_params). This saves memory\n      since we don't need both buffers simultaneously.\n\n    Arguments:\n        param_groups: List of dicts, each containing:\n            - 'params': List of parameters\n            - 'kind': 'adamw' or 'muon'\n            - For AdamW groups: 'lr', 'betas', 'eps', 'weight_decay'\n            - For Muon groups: 'lr', 'momentum', 'ns_steps', 'beta2', 'weight_decay'\n    \"\"\"\n    def __init__(self, param_groups: list[dict]):\n        super().__init__(param_groups, defaults={})\n        # 0-D CPU tensors to avoid torch.compile recompilation when values change\n        self._adamw_step_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_lr_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_beta1_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_beta2_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_eps_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._adamw_wd_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_momentum_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_lr_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_wd_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n        self._muon_beta2_t = torch.tensor(0.0, dtype=torch.float32, device=\"cpu\")\n\n    def _reduce_adamw(self, group: dict, world_size: int) -> dict:\n        \"\"\"Launch async reduce ops for AdamW group. Returns info dict with per-param infos.\"\"\"\n        param_infos = {}\n        for p in group['params']:\n            grad = p.grad\n            if p.numel() < 1024:\n                # Small params: all_reduce (no scatter/gather needed)\n                future = dist.all_reduce(grad, op=dist.ReduceOp.AVG, async_op=True).get_future()\n                param_infos[p] = dict(future=future, grad_slice=grad, is_small=True)\n            else:\n                # Large params: reduce_scatter\n                assert grad.shape[0] % world_size == 0, f\"AdamW reduce_scatter requires shape[0] ({grad.shape[0]}) divisible by world_size ({world_size})\"\n                rank_size = grad.shape[0] // world_size\n                grad_slice = torch.empty_like(grad[:rank_size])\n                future = dist.reduce_scatter_tensor(grad_slice, grad, op=dist.ReduceOp.AVG, async_op=True).get_future()\n                param_infos[p] = dict(future=future, grad_slice=grad_slice, is_small=False)\n        return dict(param_infos=param_infos)\n\n    def _reduce_muon(self, group: dict, world_size: int) -> dict:\n        \"\"\"Launch async reduce op for Muon group. Returns info dict.\"\"\"\n        params = group['params']\n        chunk_size = (len(params) + world_size - 1) // world_size\n        padded_num_params = chunk_size * world_size\n        p = params[0]\n        shape, device, dtype = p.shape, p.device, p.dtype\n\n        # Stack grads and zero-pad to padded_num_params\n        grad_stack = torch.stack([p.grad for p in params])\n        stacked_grads = torch.empty(padded_num_params, *shape, dtype=dtype, device=device)\n        stacked_grads[:len(params)].copy_(grad_stack)\n        if len(params) < padded_num_params:\n            stacked_grads[len(params):].zero_()\n\n        # Reduce_scatter to get this rank's chunk\n        grad_chunk = torch.empty(chunk_size, *shape, dtype=dtype, device=device)\n        future = dist.reduce_scatter_tensor(grad_chunk, stacked_grads, op=dist.ReduceOp.AVG, async_op=True).get_future()\n\n        return dict(future=future, grad_chunk=grad_chunk, stacked_grads=stacked_grads, chunk_size=chunk_size)\n\n    def _compute_adamw(self, group: dict, info: dict, gather_list: list, rank: int, world_size: int) -> None:\n        \"\"\"Wait for reduce, compute AdamW updates, launch gathers for large params.\"\"\"\n        param_infos = info['param_infos']\n        for p in group['params']:\n            pinfo = param_infos[p]\n            pinfo['future'].wait()\n            grad_slice = pinfo['grad_slice']\n            state = self.state[p]\n\n            # For small params, operate on full param; for large, operate on slice\n            if pinfo['is_small']:\n                p_slice = p\n            else:\n                rank_size = p.shape[0] // world_size\n                p_slice = p[rank * rank_size:(rank + 1) * rank_size]\n\n            # State init\n            if not state:\n                state['step'] = 0\n                state['exp_avg'] = torch.zeros_like(p_slice)\n                state['exp_avg_sq'] = torch.zeros_like(p_slice)\n            state['step'] += 1\n\n            # Fill 0-D tensors and run fused kernel\n            self._adamw_step_t.fill_(state['step'])\n            self._adamw_lr_t.fill_(group['lr'])\n            self._adamw_beta1_t.fill_(group['betas'][0])\n            self._adamw_beta2_t.fill_(group['betas'][1])\n            self._adamw_eps_t.fill_(group['eps'])\n            self._adamw_wd_t.fill_(group['weight_decay'])\n            adamw_step_fused(\n                p_slice, grad_slice, state['exp_avg'], state['exp_avg_sq'],\n                self._adamw_step_t, self._adamw_lr_t, self._adamw_beta1_t,\n                self._adamw_beta2_t, self._adamw_eps_t, self._adamw_wd_t,\n            )\n\n            # Large params need all_gather\n            if not pinfo['is_small']:\n                future = dist.all_gather_into_tensor(p, p_slice, async_op=True).get_future()\n                gather_list.append(dict(future=future, params=None))\n\n    def _compute_muon(self, group: dict, info: dict, gather_list: list, rank: int) -> None:\n        \"\"\"Wait for reduce, compute Muon updates, launch gather.\"\"\"\n        info['future'].wait()\n        params = group['params']\n        chunk_size = info['chunk_size']\n        grad_chunk = info['grad_chunk']\n        p = params[0]\n        shape, device, dtype = p.shape, p.device, p.dtype\n\n        # How many params does this rank own?\n        start_idx = rank * chunk_size\n        num_owned = min(chunk_size, max(0, len(params) - start_idx))\n\n        # Get or create group-level state\n        state = self.state[p]\n        if \"momentum_buffer\" not in state:\n            state[\"momentum_buffer\"] = torch.zeros(chunk_size, *shape, dtype=dtype, device=device)\n        if \"second_momentum_buffer\" not in state:\n            state_shape = (chunk_size, shape[-2], 1) if shape[-2] >= shape[-1] else (chunk_size, 1, shape[-1])\n            state[\"second_momentum_buffer\"] = torch.zeros(state_shape, dtype=dtype, device=device)\n        red_dim = -1 if shape[-2] >= shape[-1] else -2\n\n        # Build output buffer for all_gather\n        updated_params = torch.empty(chunk_size, *shape, dtype=dtype, device=device)\n\n        if num_owned > 0:\n            owned_params = [params[start_idx + i] for i in range(num_owned)]\n            stacked_owned = torch.stack(owned_params)\n\n            # Fill 0-D tensors and run fused kernel\n            self._muon_momentum_t.fill_(group[\"momentum\"])\n            self._muon_beta2_t.fill_(group[\"beta2\"])\n            self._muon_lr_t.fill_(group[\"lr\"] * max(1.0, shape[-2] / shape[-1])**0.5)\n            self._muon_wd_t.fill_(group[\"weight_decay\"])\n            muon_step_fused(\n                grad_chunk[:num_owned], stacked_owned,\n                state[\"momentum_buffer\"][:num_owned], state[\"second_momentum_buffer\"][:num_owned],\n                self._muon_momentum_t, self._muon_lr_t, self._muon_wd_t, self._muon_beta2_t,\n                group[\"ns_steps\"], red_dim,\n            )\n            updated_params[:num_owned].copy_(stacked_owned)\n\n        if num_owned < chunk_size:\n            updated_params[num_owned:].zero_()\n\n        # Reuse stacked_grads buffer for all_gather output\n        stacked_params = info[\"stacked_grads\"]\n        future = dist.all_gather_into_tensor(stacked_params, updated_params, async_op=True).get_future()\n        gather_list.append(dict(future=future, stacked_params=stacked_params, params=params))\n\n    def _finish_gathers(self, gather_list: list) -> None:\n        \"\"\"Wait for all gathers and copy Muon params back.\"\"\"\n        for info in gather_list:\n            info[\"future\"].wait()\n            if info[\"params\"] is not None:\n                # Muon: copy from stacked buffer back to individual params\n                torch._foreach_copy_(info[\"params\"], list(info[\"stacked_params\"][:len(info[\"params\"])].unbind(0)))\n\n    @torch.no_grad()\n    def step(self):\n        rank = dist.get_rank()\n        world_size = dist.get_world_size()\n\n        # Phase 1: launch all async reduce ops\n        reduce_infos: list[dict] = []\n        for group in self.param_groups:\n            if group['kind'] == 'adamw':\n                reduce_infos.append(self._reduce_adamw(group, world_size))\n            elif group['kind'] == 'muon':\n                reduce_infos.append(self._reduce_muon(group, world_size))\n            else:\n                raise ValueError(f\"Unknown optimizer kind: {group['kind']}\")\n\n        # Phase 2: wait for reduces, compute updates, launch gathers\n        gather_list: list[dict] = []\n        for group, info in zip(self.param_groups, reduce_infos):\n            if group['kind'] == 'adamw':\n                self._compute_adamw(group, info, gather_list, rank, world_size)\n            elif group['kind'] == 'muon':\n                self._compute_muon(group, info, gather_list, rank)\n            else:\n                raise ValueError(f\"Unknown optimizer kind: {group['kind']}\")\n\n        # Phase 3: wait for gathers, copy back\n        self._finish_gathers(gather_list)\n"
  },
  {
    "path": "nanochat/report.py",
    "content": "\"\"\"\nUtilities for generating training report cards. More messy code than usual, will fix.\n\"\"\"\n\nimport os\nimport re\nimport shutil\nimport subprocess\nimport socket\nimport datetime\nimport platform\nimport psutil\nimport torch\n\ndef run_command(cmd):\n    \"\"\"Run a shell command and return output, or None if it fails.\"\"\"\n    try:\n        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)\n        # Return stdout if we got output (even if some files in xargs failed)\n        if result.stdout.strip():\n            return result.stdout.strip()\n        if result.returncode == 0:\n            return \"\"\n        return None\n    except:\n        return None\n\ndef get_git_info():\n    \"\"\"Get current git commit, branch, and dirty status.\"\"\"\n    info = {}\n    info['commit'] = run_command(\"git rev-parse --short HEAD\") or \"unknown\"\n    info['branch'] = run_command(\"git rev-parse --abbrev-ref HEAD\") or \"unknown\"\n\n    # Check if repo is dirty (has uncommitted changes)\n    status = run_command(\"git status --porcelain\")\n    info['dirty'] = bool(status) if status is not None else False\n\n    # Get commit message\n    info['message'] = run_command(\"git log -1 --pretty=%B\") or \"\"\n    info['message'] = info['message'].split('\\n')[0][:80]  # First line, truncated\n\n    return info\n\ndef get_gpu_info():\n    \"\"\"Get GPU information.\"\"\"\n    if not torch.cuda.is_available():\n        return {\"available\": False}\n\n    num_devices = torch.cuda.device_count()\n    info = {\n        \"available\": True,\n        \"count\": num_devices,\n        \"names\": [],\n        \"memory_gb\": []\n    }\n\n    for i in range(num_devices):\n        props = torch.cuda.get_device_properties(i)\n        info[\"names\"].append(props.name)\n        info[\"memory_gb\"].append(props.total_memory / (1024**3))\n\n    # Get CUDA version\n    info[\"cuda_version\"] = torch.version.cuda or \"unknown\"\n\n    return info\n\ndef get_system_info():\n    \"\"\"Get system information.\"\"\"\n    info = {}\n\n    # Basic system info\n    info['hostname'] = socket.gethostname()\n    info['platform'] = platform.system()\n    info['python_version'] = platform.python_version()\n    info['torch_version'] = torch.__version__\n\n    # CPU and memory\n    info['cpu_count'] = psutil.cpu_count(logical=False)\n    info['cpu_count_logical'] = psutil.cpu_count(logical=True)\n    info['memory_gb'] = psutil.virtual_memory().total / (1024**3)\n\n    # User and environment\n    info['user'] = os.environ.get('USER', 'unknown')\n    info['nanochat_base_dir'] = os.environ.get('NANOCHAT_BASE_DIR', 'out')\n    info['working_dir'] = os.getcwd()\n\n    return info\n\ndef estimate_cost(gpu_info, runtime_hours=None):\n    \"\"\"Estimate training cost based on GPU type and runtime.\"\"\"\n\n    # Rough pricing, from Lambda Cloud\n    default_rate = 2.0\n    gpu_hourly_rates = {\n        \"H100\": 3.00,\n        \"A100\": 1.79,\n        \"V100\": 0.55,\n    }\n\n    if not gpu_info.get(\"available\"):\n        return None\n\n    # Try to identify GPU type from name\n    hourly_rate = None\n    gpu_name = gpu_info[\"names\"][0] if gpu_info[\"names\"] else \"unknown\"\n    for gpu_type, rate in gpu_hourly_rates.items():\n        if gpu_type in gpu_name:\n            hourly_rate = rate * gpu_info[\"count\"]\n            break\n\n    if hourly_rate is None:\n        hourly_rate = default_rate * gpu_info[\"count\"]  # Default estimate\n\n    return {\n        \"hourly_rate\": hourly_rate,\n        \"gpu_type\": gpu_name,\n        \"estimated_total\": hourly_rate * runtime_hours if runtime_hours else None\n    }\n\ndef generate_header():\n    \"\"\"Generate the header for a training report.\"\"\"\n    timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n    git_info = get_git_info()\n    gpu_info = get_gpu_info()\n    sys_info = get_system_info()\n    cost_info = estimate_cost(gpu_info)\n\n    header = f\"\"\"# nanochat training report\n\nGenerated: {timestamp}\n\n## Environment\n\n### Git Information\n- Branch: {git_info['branch']}\n- Commit: {git_info['commit']} {\"(dirty)\" if git_info['dirty'] else \"(clean)\"}\n- Message: {git_info['message']}\n\n### Hardware\n- Platform: {sys_info['platform']}\n- CPUs: {sys_info['cpu_count']} cores ({sys_info['cpu_count_logical']} logical)\n- Memory: {sys_info['memory_gb']:.1f} GB\n\"\"\"\n\n    if gpu_info.get(\"available\"):\n        gpu_names = \", \".join(set(gpu_info[\"names\"]))\n        total_vram = sum(gpu_info[\"memory_gb\"])\n        header += f\"\"\"- GPUs: {gpu_info['count']}x {gpu_names}\n- GPU Memory: {total_vram:.1f} GB total\n- CUDA Version: {gpu_info['cuda_version']}\n\"\"\"\n    else:\n        header += \"- GPUs: None available\\n\"\n\n    if cost_info and cost_info[\"hourly_rate\"] > 0:\n        header += f\"\"\"- Hourly Rate: ${cost_info['hourly_rate']:.2f}/hour\\n\"\"\"\n\n    header += f\"\"\"\n### Software\n- Python: {sys_info['python_version']}\n- PyTorch: {sys_info['torch_version']}\n\n\"\"\"\n\n    # bloat metrics: count lines/chars in git-tracked source files only\n    extensions = ['py', 'md', 'rs', 'html', 'toml', 'sh']\n    git_patterns = ' '.join(f\"'*.{ext}'\" for ext in extensions)\n    files_output = run_command(f\"git ls-files -- {git_patterns}\")\n    file_list = [f for f in (files_output or '').split('\\n') if f]\n    num_files = len(file_list)\n    num_lines = 0\n    num_chars = 0\n    if num_files > 0:\n        wc_output = run_command(f\"git ls-files -- {git_patterns} | xargs wc -lc 2>/dev/null\")\n        if wc_output:\n            total_line = wc_output.strip().split('\\n')[-1]\n            parts = total_line.split()\n            if len(parts) >= 2:\n                num_lines = int(parts[0])\n                num_chars = int(parts[1])\n    num_tokens = num_chars // 4  # assume approximately 4 chars per token\n\n    # count dependencies via uv.lock\n    uv_lock_lines = 0\n    if os.path.exists('uv.lock'):\n        with open('uv.lock', 'r', encoding='utf-8') as f:\n            uv_lock_lines = len(f.readlines())\n\n    header += f\"\"\"\n### Bloat\n- Characters: {num_chars:,}\n- Lines: {num_lines:,}\n- Files: {num_files:,}\n- Tokens (approx): {num_tokens:,}\n- Dependencies (uv.lock lines): {uv_lock_lines:,}\n\n\"\"\"\n    return header\n\n# -----------------------------------------------------------------------------\n\ndef slugify(text):\n    \"\"\"Slugify a text string.\"\"\"\n    return text.lower().replace(\" \", \"-\")\n\n# the expected files and their order\nEXPECTED_FILES = [\n    \"tokenizer-training.md\",\n    \"tokenizer-evaluation.md\",\n    \"base-model-training.md\",\n    \"base-model-loss.md\",\n    \"base-model-evaluation.md\",\n    \"chat-sft.md\",\n    \"chat-evaluation-sft.md\",\n    \"chat-rl.md\",\n    \"chat-evaluation-rl.md\",\n]\n# the metrics we're currently interested in\nchat_metrics = [\"ARC-Easy\", \"ARC-Challenge\", \"MMLU\", \"GSM8K\", \"HumanEval\", \"ChatCORE\"]\n\ndef extract(section, keys):\n    \"\"\"simple def to extract a single key from a section\"\"\"\n    if not isinstance(keys, list):\n        keys = [keys] # convenience\n    out = {}\n    for line in section.split(\"\\n\"):\n        for key in keys:\n            if key in line:\n                out[key] = line.split(\":\")[1].strip()\n    return out\n\ndef extract_timestamp(content, prefix):\n    \"\"\"Extract timestamp from content with given prefix.\"\"\"\n    for line in content.split('\\n'):\n        if line.startswith(prefix):\n            time_str = line.split(\":\", 1)[1].strip()\n            try:\n                return datetime.datetime.strptime(time_str, \"%Y-%m-%d %H:%M:%S\")\n            except:\n                pass\n    return None\n\nclass Report:\n    \"\"\"Maintains a bunch of logs, generates a final markdown report.\"\"\"\n\n    def __init__(self, report_dir):\n        os.makedirs(report_dir, exist_ok=True)\n        self.report_dir = report_dir\n\n    def log(self, section, data):\n        \"\"\"Log a section of data to the report.\"\"\"\n        slug = slugify(section)\n        file_name = f\"{slug}.md\"\n        file_path = os.path.join(self.report_dir, file_name)\n        with open(file_path, \"w\", encoding=\"utf-8\") as f:\n            f.write(f\"## {section}\\n\")\n            f.write(f\"timestamp: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\\n\\n\")\n            for item in data:\n                if not item:\n                    # skip falsy values like None or empty dict etc.\n                    continue\n                if isinstance(item, str):\n                    # directly write the string\n                    f.write(item)\n                else:\n                    # render a dict\n                    for k, v in item.items():\n                        if isinstance(v, float):\n                            vstr = f\"{v:.4f}\"\n                        elif isinstance(v, int) and v >= 10000:\n                            vstr = f\"{v:,.0f}\"\n                        else:\n                            vstr = str(v)\n                        f.write(f\"- {k}: {vstr}\\n\")\n            f.write(\"\\n\")\n        return file_path\n\n    def generate(self):\n        \"\"\"Generate the final report.\"\"\"\n        report_dir = self.report_dir\n        report_file = os.path.join(report_dir, \"report.md\")\n        print(f\"Generating report to {report_file}\")\n        final_metrics = {} # the most important final metrics we'll add as table at the end\n        start_time = None\n        end_time = None\n        with open(report_file, \"w\", encoding=\"utf-8\") as out_file:\n            # write the header first\n            header_file = os.path.join(report_dir, \"header.md\")\n            if os.path.exists(header_file):\n                with open(header_file, \"r\", encoding=\"utf-8\") as f:\n                    header_content = f.read()\n                    out_file.write(header_content)\n                    start_time = extract_timestamp(header_content, \"Run started:\")\n                    # capture bloat data for summary later (the stuff after Bloat header and until \\n\\n)\n                    bloat_data = re.search(r\"### Bloat\\n(.*?)\\n\\n\", header_content, re.DOTALL)\n                    bloat_data = bloat_data.group(1) if bloat_data else \"\"\n            else:\n                start_time = None # will cause us to not write the total wall clock time\n                bloat_data = \"[bloat data missing]\"\n                print(f\"Warning: {header_file} does not exist. Did you forget to run `nanochat reset`?\")\n            # process all the individual sections\n            for file_name in EXPECTED_FILES:\n                section_file = os.path.join(report_dir, file_name)\n                if not os.path.exists(section_file):\n                    print(f\"Warning: {section_file} does not exist, skipping\")\n                    continue\n                with open(section_file, \"r\", encoding=\"utf-8\") as in_file:\n                    section = in_file.read()\n                # Extract timestamp from this section (the last section's timestamp will \"stick\" as end_time)\n                if \"rl\" not in file_name:\n                    # Skip RL sections for end_time calculation because RL is experimental\n                    end_time = extract_timestamp(section, \"timestamp:\")\n                # extract the most important metrics from the sections\n                if file_name == \"base-model-evaluation.md\":\n                    final_metrics[\"base\"] = extract(section, \"CORE\")\n                if file_name == \"chat-evaluation-sft.md\":\n                    final_metrics[\"sft\"] = extract(section, chat_metrics)\n                if file_name == \"chat-evaluation-rl.md\":\n                    final_metrics[\"rl\"] = extract(section, \"GSM8K\") # RL only evals GSM8K\n                # append this section of the report\n                out_file.write(section)\n                out_file.write(\"\\n\")\n            # add the final metrics table\n            out_file.write(\"## Summary\\n\\n\")\n            # Copy over the bloat metrics from the header\n            out_file.write(bloat_data)\n            out_file.write(\"\\n\\n\")\n            # Collect all unique metric names\n            all_metrics = set()\n            for stage_metrics in final_metrics.values():\n                all_metrics.update(stage_metrics.keys())\n            # Custom ordering: CORE first, ChatCORE last, rest in middle\n            all_metrics = sorted(all_metrics, key=lambda x: (x != \"CORE\", x == \"ChatCORE\", x))\n            # Fixed column widths\n            stages = [\"base\", \"sft\", \"rl\"]\n            metric_width = 15\n            value_width = 8\n            # Write table header\n            header = f\"| {'Metric'.ljust(metric_width)} |\"\n            for stage in stages:\n                header += f\" {stage.upper().ljust(value_width)} |\"\n            out_file.write(header + \"\\n\")\n            # Write separator\n            separator = f\"|{'-' * (metric_width + 2)}|\"\n            for stage in stages:\n                separator += f\"{'-' * (value_width + 2)}|\"\n            out_file.write(separator + \"\\n\")\n            # Write table rows\n            for metric in all_metrics:\n                row = f\"| {metric.ljust(metric_width)} |\"\n                for stage in stages:\n                    value = final_metrics.get(stage, {}).get(metric, \"-\")\n                    row += f\" {str(value).ljust(value_width)} |\"\n                out_file.write(row + \"\\n\")\n            out_file.write(\"\\n\")\n            # Calculate and write total wall clock time\n            if start_time and end_time:\n                duration = end_time - start_time\n                total_seconds = int(duration.total_seconds())\n                hours = total_seconds // 3600\n                minutes = (total_seconds % 3600) // 60\n                out_file.write(f\"Total wall clock time: {hours}h{minutes}m\\n\")\n            else:\n                out_file.write(\"Total wall clock time: unknown\\n\")\n        # also cp the report.md file to current directory\n        print(f\"Copying report.md to current directory for convenience\")\n        shutil.copy(report_file, \"report.md\")\n        return report_file\n\n    def reset(self):\n        \"\"\"Reset the report.\"\"\"\n        # Remove section files\n        for file_name in EXPECTED_FILES:\n            file_path = os.path.join(self.report_dir, file_name)\n            if os.path.exists(file_path):\n                os.remove(file_path)\n        # Remove report.md if it exists\n        report_file = os.path.join(self.report_dir, \"report.md\")\n        if os.path.exists(report_file):\n            os.remove(report_file)\n        # Generate and write the header section with start timestamp\n        header_file = os.path.join(self.report_dir, \"header.md\")\n        header = generate_header()\n        start_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n        with open(header_file, \"w\", encoding=\"utf-8\") as f:\n            f.write(header)\n            f.write(f\"Run started: {start_time}\\n\\n---\\n\\n\")\n        print(f\"Reset report and wrote header to {header_file}\")\n\n# -----------------------------------------------------------------------------\n# nanochat-specific convenience functions\n\nclass DummyReport:\n    def log(self, *args, **kwargs):\n        pass\n    def reset(self, *args, **kwargs):\n        pass\n\ndef get_report():\n    # just for convenience, only rank 0 logs to report\n    from nanochat.common import get_base_dir, get_dist_info\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size = get_dist_info()\n    if ddp_rank == 0:\n        report_dir = os.path.join(get_base_dir(), \"report\")\n        return Report(report_dir)\n    else:\n        return DummyReport()\n\nif __name__ == \"__main__\":\n    import argparse\n    parser = argparse.ArgumentParser(description=\"Generate or reset nanochat training reports.\")\n    parser.add_argument(\"command\", nargs=\"?\", default=\"generate\", choices=[\"generate\", \"reset\"], help=\"Operation to perform (default: generate)\")\n    args = parser.parse_args()\n    if args.command == \"generate\":\n        get_report().generate()\n    elif args.command == \"reset\":\n        get_report().reset()\n"
  },
  {
    "path": "nanochat/tokenizer.py",
    "content": "\"\"\"\nBPE Tokenizer in the style of GPT-4.\n\nTwo implementations are available:\n1) HuggingFace Tokenizer that can do both training and inference but is really confusing\n2) Our own RustBPE Tokenizer for training and tiktoken for efficient inference\n\"\"\"\n\nimport os\nimport copy\nfrom functools import lru_cache\n\nSPECIAL_TOKENS = [\n    # every document begins with the Beginning of Sequence (BOS) token that delimits documents\n    \"<|bos|>\",\n    # tokens below are only used during finetuning to render Conversations into token ids\n    \"<|user_start|>\", # user messages\n    \"<|user_end|>\",\n    \"<|assistant_start|>\", # assistant messages\n    \"<|assistant_end|>\",\n    \"<|python_start|>\", # assistant invokes python REPL tool\n    \"<|python_end|>\",\n    \"<|output_start|>\", # python REPL outputs back to assistant\n    \"<|output_end|>\",\n]\n\n# NOTE: this split pattern deviates from GPT-4 in that we use \\p{N}{1,2} instead of \\p{N}{1,3}\n# I did this because I didn't want to \"waste\" too many tokens on numbers for smaller vocab sizes.\n# I verified that 2 is the sweet spot for vocab size of 32K. 1 is a bit worse, 3 was worse still.\nSPLIT_PATTERN = r\"\"\"'(?i:[sdmt]|ll|ve|re)|[^\\r\\n\\p{L}\\p{N}]?+\\p{L}+|\\p{N}{1,2}| ?[^\\s\\p{L}\\p{N}]++[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+\"\"\"\n\n# -----------------------------------------------------------------------------\n# Generic GPT-4-style tokenizer based on HuggingFace Tokenizer\nfrom tokenizers import Tokenizer as HFTokenizer\nfrom tokenizers import pre_tokenizers, decoders, Regex\nfrom tokenizers.models import BPE\nfrom tokenizers.trainers import BpeTrainer\n\nclass HuggingFaceTokenizer:\n    \"\"\"Light wrapper around HuggingFace Tokenizer for some utilities\"\"\"\n\n    def __init__(self, tokenizer):\n        self.tokenizer = tokenizer\n\n    @classmethod\n    def from_pretrained(cls, hf_path):\n        # init from a HuggingFace pretrained tokenizer (e.g. \"gpt2\")\n        tokenizer = HFTokenizer.from_pretrained(hf_path)\n        return cls(tokenizer)\n\n    @classmethod\n    def from_directory(cls, tokenizer_dir):\n        # init from a local directory on disk (e.g. \"out/tokenizer\")\n        tokenizer_path = os.path.join(tokenizer_dir, \"tokenizer.json\")\n        tokenizer = HFTokenizer.from_file(tokenizer_path)\n        return cls(tokenizer)\n\n    @classmethod\n    def train_from_iterator(cls, text_iterator, vocab_size):\n        # train from an iterator of text\n        # Configure the HuggingFace Tokenizer\n        tokenizer = HFTokenizer(BPE(\n            byte_fallback=True, # needed!\n            unk_token=None,\n            fuse_unk=False,\n        ))\n        # Normalizer: None\n        tokenizer.normalizer = None\n        # Pre-tokenizer: GPT-4 style\n        # the regex pattern used by GPT-4 to split text into groups before BPE\n        # NOTE: The pattern was changed from \\p{N}{1,3} to \\p{N}{1,2} because I suspect it is harmful to\n        # very small models and smaller vocab sizes, because it is a little bit wasteful in the token space.\n        # (but I haven't validated this! TODO)\n        gpt4_split_regex = Regex(SPLIT_PATTERN) # huggingface demands that you wrap it in Regex!!\n        tokenizer.pre_tokenizer = pre_tokenizers.Sequence([\n            pre_tokenizers.Split(pattern=gpt4_split_regex, behavior=\"isolated\", invert=False),\n            pre_tokenizers.ByteLevel(add_prefix_space=False, use_regex=False)\n        ])\n        # Decoder: ByteLevel (it pairs together with the ByteLevel pre-tokenizer)\n        tokenizer.decoder = decoders.ByteLevel()\n        # Post-processor: None\n        tokenizer.post_processor = None\n        # Trainer: BPE\n        trainer = BpeTrainer(\n            vocab_size=vocab_size,\n            show_progress=True,\n            min_frequency=0, # no minimum frequency\n            initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),\n            special_tokens=SPECIAL_TOKENS,\n        )\n        # Kick off the training\n        tokenizer.train_from_iterator(text_iterator, trainer)\n        return cls(tokenizer)\n\n    def get_vocab_size(self):\n        return self.tokenizer.get_vocab_size()\n\n    def get_special_tokens(self):\n        special_tokens_map = self.tokenizer.get_added_tokens_decoder()\n        special_tokens = [w.content for w in special_tokens_map.values()]\n        return special_tokens\n\n    def id_to_token(self, id):\n        return self.tokenizer.id_to_token(id)\n\n    def _encode_one(self, text, prepend=None, append=None, num_threads=None):\n        # encode a single string\n        # prepend/append can be either a string of a special token or a token id directly.\n        # num_threads is ignored (only used by the nanochat Tokenizer for parallel encoding)\n        assert isinstance(text, str)\n        ids = []\n        if prepend is not None:\n            prepend_id = prepend if isinstance(prepend, int) else self.encode_special(prepend)\n            ids.append(prepend_id)\n        ids.extend(self.tokenizer.encode(text, add_special_tokens=False).ids)\n        if append is not None:\n            append_id = append if isinstance(append, int) else self.encode_special(append)\n            ids.append(append_id)\n        return ids\n\n    def encode_special(self, text):\n        # encode a single special token via exact match\n        return self.tokenizer.token_to_id(text)\n\n    def get_bos_token_id(self):\n        # Different HuggingFace models use different BOS tokens and there is little consistency\n        # 1) attempt to find a <|bos|> token\n        bos = self.encode_special(\"<|bos|>\")\n        # 2) if that fails, attempt to find a <|endoftext|> token (e.g. GPT-2 models)\n        if bos is None:\n            bos = self.encode_special(\"<|endoftext|>\")\n        # 3) if these fail, it's better to crash than to silently return None\n        assert bos is not None, \"Failed to find BOS token in tokenizer\"\n        return bos\n\n    def encode(self, text, *args, **kwargs):\n        if isinstance(text, str):\n            return self._encode_one(text, *args, **kwargs)\n        elif isinstance(text, list):\n            return [self._encode_one(t, *args, **kwargs) for t in text]\n        else:\n            raise ValueError(f\"Invalid input type: {type(text)}\")\n\n    def __call__(self, *args, **kwargs):\n        return self.encode(*args, **kwargs)\n\n    def decode(self, ids):\n        return self.tokenizer.decode(ids, skip_special_tokens=False)\n\n    def save(self, tokenizer_dir):\n        # save the tokenizer to disk\n        os.makedirs(tokenizer_dir, exist_ok=True)\n        tokenizer_path = os.path.join(tokenizer_dir, \"tokenizer.json\")\n        self.tokenizer.save(tokenizer_path)\n        print(f\"Saved tokenizer to {tokenizer_path}\")\n\n# -----------------------------------------------------------------------------\n# Tokenizer based on rustbpe + tiktoken combo\nimport pickle\nimport rustbpe\nimport tiktoken\n\nclass RustBPETokenizer:\n    \"\"\"Light wrapper around tiktoken (for efficient inference) but train with rustbpe\"\"\"\n\n    def __init__(self, enc, bos_token):\n        self.enc = enc\n        self.bos_token_id = self.encode_special(bos_token)\n\n    @classmethod\n    def train_from_iterator(cls, text_iterator, vocab_size):\n        # 1) train using rustbpe\n        tokenizer = rustbpe.Tokenizer()\n        # the special tokens are inserted later in __init__, we don't train them here\n        vocab_size_no_special = vocab_size - len(SPECIAL_TOKENS)\n        assert vocab_size_no_special >= 256, f\"vocab_size_no_special must be at least 256, got {vocab_size_no_special}\"\n        tokenizer.train_from_iterator(text_iterator, vocab_size_no_special, pattern=SPLIT_PATTERN)\n        # 2) construct the associated tiktoken encoding for inference\n        pattern = tokenizer.get_pattern()\n        mergeable_ranks_list = tokenizer.get_mergeable_ranks()\n        mergeable_ranks = {bytes(k): v for k, v in mergeable_ranks_list}\n        tokens_offset = len(mergeable_ranks)\n        special_tokens = {name: tokens_offset + i for i, name in enumerate(SPECIAL_TOKENS)}\n        enc = tiktoken.Encoding(\n            name=\"rustbpe\",\n            pat_str=pattern,\n            mergeable_ranks=mergeable_ranks, # dict[bytes, int] (token bytes -> merge priority rank)\n            special_tokens=special_tokens, # dict[str, int] (special token name -> token id)\n        )\n        return cls(enc, \"<|bos|>\")\n\n    @classmethod\n    def from_directory(cls, tokenizer_dir):\n        pickle_path = os.path.join(tokenizer_dir, \"tokenizer.pkl\")\n        with open(pickle_path, \"rb\") as f:\n            enc = pickle.load(f)\n        return cls(enc, \"<|bos|>\")\n\n    @classmethod\n    def from_pretrained(cls, tiktoken_name):\n        # https://github.com/openai/tiktoken/blob/eedc8563/tiktoken_ext/openai_public.py\n        enc = tiktoken.get_encoding(tiktoken_name)\n        # tiktoken calls the special document delimiter token \"<|endoftext|>\"\n        # yes this is confusing because this token is almost always PREPENDED to the beginning of the document\n        # it most often is used to signal the start of a new sequence to the LLM during inference etc.\n        # so in nanoChat we always use \"<|bos|>\" short for \"beginning of sequence\", but historically it is often called \"<|endoftext|>\".\n        return cls(enc, \"<|endoftext|>\")\n\n    def get_vocab_size(self):\n        return self.enc.n_vocab\n\n    def get_special_tokens(self):\n        return self.enc.special_tokens_set\n\n    def id_to_token(self, id):\n        return self.enc.decode([id])\n\n    @lru_cache(maxsize=32)\n    def encode_special(self, text):\n        return self.enc.encode_single_token(text)\n\n    def get_bos_token_id(self):\n        return self.bos_token_id\n\n    def encode(self, text, prepend=None, append=None, num_threads=8):\n        # text can be either a string or a list of strings\n\n        if prepend is not None:\n            prepend_id = prepend if isinstance(prepend, int) else self.encode_special(prepend)\n        if append is not None:\n            append_id = append if isinstance(append, int) else self.encode_special(append)\n\n        if isinstance(text, str):\n            ids = self.enc.encode_ordinary(text)\n            if prepend is not None:\n                ids.insert(0, prepend_id) # TODO: slightly inefficient here? :( hmm\n            if append is not None:\n                ids.append(append_id)\n        elif isinstance(text, list):\n            ids = self.enc.encode_ordinary_batch(text, num_threads=num_threads)\n            if prepend is not None:\n                for ids_row in ids:\n                    ids_row.insert(0, prepend_id) # TODO: same\n            if append is not None:\n                for ids_row in ids:\n                    ids_row.append(append_id)\n        else:\n            raise ValueError(f\"Invalid input type: {type(text)}\")\n\n        return ids\n\n    def __call__(self, *args, **kwargs):\n        return self.encode(*args, **kwargs)\n\n    def decode(self, ids):\n        return self.enc.decode(ids)\n\n    def save(self, tokenizer_dir):\n        # save the encoding object to disk\n        os.makedirs(tokenizer_dir, exist_ok=True)\n        pickle_path = os.path.join(tokenizer_dir, \"tokenizer.pkl\")\n        with open(pickle_path, \"wb\") as f:\n            pickle.dump(self.enc, f)\n        print(f\"Saved tokenizer encoding to {pickle_path}\")\n\n    def render_conversation(self, conversation, max_tokens=2048):\n        \"\"\"\n        Tokenize a single Chat conversation (which we call a \"doc\" or \"document\" here).\n        Returns:\n        - ids: list[int] is a list of token ids of this rendered conversation\n        - mask: list[int] of same length, mask = 1 for tokens that the Assistant is expected to train on.\n        \"\"\"\n        # ids, masks that we will return and a helper function to help build them up.\n        ids, mask = [], []\n        def add_tokens(token_ids, mask_val):\n            if isinstance(token_ids, int):\n                token_ids = [token_ids]\n            ids.extend(token_ids)\n            mask.extend([mask_val] * len(token_ids))\n\n        # sometimes the first message is a system message...\n        # => just merge it with the second (user) message\n        if conversation[\"messages\"][0][\"role\"] == \"system\":\n            # some conversation surgery is necessary here for now...\n            conversation = copy.deepcopy(conversation) # avoid mutating the original\n            messages = conversation[\"messages\"]\n            assert messages[1][\"role\"] == \"user\", \"System message must be followed by a user message\"\n            messages[1][\"content\"] = messages[0][\"content\"] + \"\\n\\n\" + messages[1][\"content\"]\n            messages = messages[1:]\n        else:\n            messages = conversation[\"messages\"]\n        assert len(messages) >= 1, f\"Conversation has less than 1 message: {messages}\"\n\n        # fetch all the special tokens we need\n        bos = self.get_bos_token_id()\n        user_start, user_end = self.encode_special(\"<|user_start|>\"), self.encode_special(\"<|user_end|>\")\n        assistant_start, assistant_end = self.encode_special(\"<|assistant_start|>\"), self.encode_special(\"<|assistant_end|>\")\n        python_start, python_end = self.encode_special(\"<|python_start|>\"), self.encode_special(\"<|python_end|>\")\n        output_start, output_end = self.encode_special(\"<|output_start|>\"), self.encode_special(\"<|output_end|>\")\n\n        # now we can tokenize the conversation\n        add_tokens(bos, 0)\n        for i, message in enumerate(messages):\n\n            # some sanity checking here around assumptions, to prevent footguns\n            must_be_from = \"user\" if i % 2 == 0 else \"assistant\"\n            assert message[\"role\"] == must_be_from, f\"Message {i} is from {message['role']} but should be from {must_be_from}\"\n\n            # content can be either a simple string or a list of parts (e.g. containing tool calls)\n            content = message[\"content\"]\n\n            if message[\"role\"] == \"user\":\n                assert isinstance(content, str), \"User messages are simply expected to be strings\"\n                value_ids = self.encode(content)\n                add_tokens(user_start, 0)\n                add_tokens(value_ids, 0)\n                add_tokens(user_end, 0)\n            elif message[\"role\"] == \"assistant\":\n                add_tokens(assistant_start, 0)\n                if isinstance(content, str):\n                    # simple string => simply add the tokens\n                    value_ids = self.encode(content)\n                    add_tokens(value_ids, 1)\n                elif isinstance(content, list):\n                    for part in content:\n                        value_ids = self.encode(part[\"text\"])\n                        if part[\"type\"] == \"text\":\n                            # string part => simply add the tokens\n                            add_tokens(value_ids, 1)\n                        elif part[\"type\"] == \"python\":\n                            # python tool call => add the tokens inside <|python_start|> and <|python_end|>\n                            add_tokens(python_start, 1)\n                            add_tokens(value_ids, 1)\n                            add_tokens(python_end, 1)\n                        elif part[\"type\"] == \"python_output\":\n                            # python output => add the tokens inside <|output_start|> and <|output_end|>\n                            # none of these tokens are supervised because the tokens come from Python at test time\n                            add_tokens(output_start, 0)\n                            add_tokens(value_ids, 0)\n                            add_tokens(output_end, 0)\n                        else:\n                            raise ValueError(f\"Unknown part type: {part['type']}\")\n                else:\n                    raise ValueError(f\"Unknown content type: {type(content)}\")\n                add_tokens(assistant_end, 1)\n\n        # truncate to max_tokens tokens MAX (helps prevent OOMs)\n        ids = ids[:max_tokens]\n        mask = mask[:max_tokens]\n        return ids, mask\n\n    def visualize_tokenization(self, ids, mask, with_token_id=False):\n        \"\"\"Small helper function useful in debugging: visualize the tokenization of render_conversation\"\"\"\n        RED = '\\033[91m'\n        GREEN = '\\033[92m'\n        RESET = '\\033[0m'\n        GRAY = '\\033[90m'\n        tokens = []\n        for i, (token_id, mask_val) in enumerate(zip(ids, mask)):\n            token_str = self.decode([token_id])\n            color = GREEN if mask_val == 1 else RED\n            tokens.append(f\"{color}{token_str}{RESET}\")\n            if with_token_id:\n                tokens.append(f\"{GRAY}({token_id}){RESET}\")\n        return '|'.join(tokens)\n\n    def render_for_completion(self, conversation):\n        \"\"\"\n        Used during Reinforcement Learning. In that setting, we want to\n        render the conversation priming the Assistant for a completion.\n        Unlike the Chat SFT case, we don't need to return the mask.\n        \"\"\"\n        # We have some surgery to do: we need to pop the last message (of the Assistant)\n        conversation = copy.deepcopy(conversation) # avoid mutating the original\n        messages = conversation[\"messages\"]\n        assert messages[-1][\"role\"] == \"assistant\", \"Last message must be from the Assistant\"\n        messages.pop() # remove the last message (of the Assistant) inplace\n\n        # Now tokenize the conversation\n        ids, mask = self.render_conversation(conversation)\n\n        # Finally, to prime the Assistant for a completion, append the Assistant start token\n        assistant_start = self.encode_special(\"<|assistant_start|>\")\n        ids.append(assistant_start)\n        return ids\n\n# -----------------------------------------------------------------------------\n# nanochat-specific convenience functions\n\ndef get_tokenizer():\n    from nanochat.common import get_base_dir\n    base_dir = get_base_dir()\n    tokenizer_dir = os.path.join(base_dir, \"tokenizer\")\n    # return HuggingFaceTokenizer.from_directory(tokenizer_dir)\n    return RustBPETokenizer.from_directory(tokenizer_dir)\n\ndef get_token_bytes(device=\"cpu\"):\n    import torch\n    from nanochat.common import get_base_dir\n    base_dir = get_base_dir()\n    tokenizer_dir = os.path.join(base_dir, \"tokenizer\")\n    token_bytes_path = os.path.join(tokenizer_dir, \"token_bytes.pt\")\n    assert os.path.exists(token_bytes_path), f\"Token bytes not found at {token_bytes_path}? It gets written by tok_train.py\"\n    with open(token_bytes_path, \"rb\") as f:\n        token_bytes = torch.load(f, map_location=device)\n    return token_bytes\n"
  },
  {
    "path": "nanochat/ui.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, viewport-fit=cover\">\n    <title>NanoChat</title>\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/logo.svg\">\n    <style>\n        :root {\n            color-scheme: light;\n        }\n\n        * {\n            box-sizing: border-box;\n        }\n\n        html, body{\n            height: 100%;\n            margin: 0;\n        }\n\n        body {\n            font-family: ui-sans-serif, -apple-system, system-ui, \"Segoe UI\", Helvetica, \"Apple Color Emoji\", Arial, sans-serif, \"Segoe UI Emoji\", \"Segoe UI Symbol\";\n            background-color: #ffffff;\n            color: #111827;\n            min-height: 100dvh;\n            margin: 0;\n            display: flex;\n            flex-direction: column;\n        }\n\n        .header {\n            background-color: #ffffff;\n            padding: 1.25rem 1.5rem;\n        }\n\n        .header-left {\n            display: flex;\n            align-items: center;\n            gap: 0.75rem;\n        }\n\n        .header-logo {\n            height: 32px;\n            width: auto;\n        }\n\n        .header h1 {\n            font-size: 1.25rem;\n            font-weight: 600;\n            margin: 0;\n            color: #111827;\n        }\n\n        .new-conversation-btn {\n            width: 32px;\n            height: 32px;\n            padding: 0;\n            border: 1px solid #e5e7eb;\n            border-radius: 0.5rem;\n            background-color: #ffffff;\n            color: #6b7280;\n            cursor: pointer;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            transition: all 0.2s ease;\n        }\n\n        .new-conversation-btn:hover {\n            background-color: #f3f4f6;\n            border-color: #d1d5db;\n            color: #374151;\n        }\n\n        .chat-container {\n            flex: 1;\n            overflow-y: auto;\n            background-color: #ffffff;\n        }\n\n        .chat-wrapper {\n            max-width: 48rem;\n            margin: 0 auto;\n            padding: 2rem 1.5rem 3rem;\n            display: flex;\n            flex-direction: column;\n            gap: 0.75rem;\n        }\n\n        .message {\n            display: flex;\n            justify-content: flex-start;\n            margin-bottom: 0.5rem;\n            color: #0d0d0d;\n        }\n\n        .message.assistant {\n            justify-content: flex-start;\n        }\n\n        .message.user {\n            justify-content: flex-end;\n        }\n\n        .message-content {\n            white-space: pre-wrap;\n            line-height: 1.6;\n            max-width: 100%;\n        }\n\n        .message.assistant .message-content {\n            background: transparent;\n            border: none;\n            cursor: pointer;\n            border-radius: 0.5rem;\n            padding: 0.5rem;\n            margin-left: -0.5rem;\n            transition: background-color 0.2s ease;\n        }\n\n        .message.assistant .message-content:hover {\n            background-color: #f9fafb;\n        }\n\n        .message.user .message-content {\n            background-color: #f3f4f6;\n            border-radius: 1.25rem;\n            padding: 0.8rem 1rem;\n            max-width: 65%;\n            cursor: pointer;\n            transition: background-color 0.2s ease;\n        }\n\n        .message.user .message-content:hover {\n            background-color: #e5e7eb;\n        }\n\n        .message.console .message-content {\n            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'Courier New', monospace;\n            font-size: 0.875rem;\n            background-color: #fafafa;\n            padding: 0.75rem 1rem;\n            color: #374151;\n            max-width: 80%;\n        }\n\n        .input-container {\n            background-color: #ffffff;\n            padding: 1rem;\n            padding-bottom: calc(1rem + env(safe-area-inset-bottom))\n        }\n\n        .input-wrapper {\n            max-width: 48rem;\n            margin: 0 auto;\n            display: flex;\n            gap: 0.75rem;\n            align-items: flex-end;\n        }\n\n        .chat-input {\n            flex: 1;\n            padding: 0.8rem 1rem;\n            border: 1px solid #d1d5db;\n            border-radius: 0.75rem;\n            background-color: #ffffff;\n            color: #111827;\n            font-size: 1rem;\n            line-height: 1.5;\n            resize: none;\n            outline: none;\n            min-height: 54px;\n            max-height: 200px;\n            transition: border-color 0.2s ease, box-shadow 0.2s ease;\n        }\n\n        .chat-input::placeholder {\n            color: #9ca3af;\n        }\n\n        .chat-input:focus {\n            border-color: #2563eb;\n            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);\n        }\n\n        .send-button {\n            flex-shrink: 0;\n            padding: 0;\n            width: 54px;\n            height: 54px;\n            border: 1px solid #111827;\n            border-radius: 0.75rem;\n            background-color: #111827;\n            color: #ffffff;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            cursor: pointer;\n            transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;\n        }\n\n        .send-button:hover:not(:disabled) {\n            background-color: #2563eb;\n            border-color: #2563eb;\n        }\n\n        .send-button:disabled {\n            cursor: not-allowed;\n            border-color: #d1d5db;\n            background-color: #e5e7eb;\n            color: #9ca3af;\n        }\n\n        .typing-indicator {\n            display: inline-block;\n            color: #6b7280;\n            letter-spacing: 0.15em;\n        }\n\n        .typing-indicator::after {\n            content: '···';\n            animation: typing 1.4s infinite;\n        }\n\n        @keyframes typing {\n            0%, 60%, 100% { opacity: 0.2; }\n            30% { opacity: 1; }\n        }\n\n        .error-message {\n            background-color: #fee2e2;\n            border: 1px solid #fecaca;\n            color: #b91c1c;\n            padding: 0.75rem 1rem;\n            border-radius: 0.75rem;\n            margin-top: 0.5rem;\n        }\n    </style>\n</head>\n<body>\n    <div class=\"header\">\n        <div class=\"header-left\">\n            <button class=\"new-conversation-btn\" onclick=\"newConversation()\" title=\"New Conversation (Ctrl+Shift+N)\">\n                <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n                    <path d=\"M12 5v14\"></path>\n                    <path d=\"M5 12h14\"></path>\n                </svg>\n            </button>\n            <h1>nanochat</h1>\n        </div>\n    </div>\n\n    <div class=\"chat-container\" id=\"chatContainer\">\n        <div class=\"chat-wrapper\" id=\"chatWrapper\">\n            <!-- Messages will be added here -->\n        </div>\n    </div>\n\n    <div class=\"input-container\">\n        <div class=\"input-wrapper\">\n            <textarea\n                id=\"chatInput\"\n                class=\"chat-input\"\n                placeholder=\"Ask anything\"\n                rows=\"1\"\n                onkeydown=\"handleKeyDown(event)\"\n            ></textarea>\n            <button id=\"sendButton\" class=\"send-button\" onclick=\"sendMessage()\" disabled>\n                <svg width=\"22\" height=\"22\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n                    <path d=\"M22 2L11 13\"></path>\n                    <path d=\"M22 2l-7 20-4-9-9-4 20-7z\"></path>\n                </svg>\n            </button>\n        </div>\n    </div>\n\n    <script>\n        const API_URL = '';\n        const chatContainer = document.getElementById('chatContainer');\n        const chatWrapper = document.getElementById('chatWrapper');\n        const chatInput = document.getElementById('chatInput');\n        const sendButton = document.getElementById('sendButton');\n\n        let messages = [];\n        let isGenerating = false;\n        let currentTemperature = 0.8;\n        let currentTopK = 50;\n\n        chatInput.addEventListener('input', function() {\n            this.style.height = 'auto';\n            this.style.height = Math.min(this.scrollHeight, 200) + 'px';\n            sendButton.disabled = !this.value.trim() || isGenerating;\n        });\n\n        function handleKeyDown(event) {\n            if (event.key === 'Enter' && !event.shiftKey) {\n                event.preventDefault();\n                sendMessage();\n            }\n        }\n\n        document.addEventListener('keydown', function(event) {\n            // Ctrl+Shift+N for new conversation\n            if (event.ctrlKey && event.shiftKey && event.key === 'N') {\n                event.preventDefault();\n                if (!isGenerating) {\n                    newConversation();\n                }\n            }\n        });\n\n        function newConversation() {\n            messages = [];\n            chatWrapper.innerHTML = '';\n            chatInput.value = '';\n            chatInput.style.height = 'auto';\n            sendButton.disabled = false;\n            isGenerating = false;\n            chatInput.focus();\n        }\n\n        function addMessage(role, content, messageIndex = null) {\n            const messageDiv = document.createElement('div');\n            messageDiv.className = `message ${role}`;\n\n            const contentDiv = document.createElement('div');\n            contentDiv.className = 'message-content';\n            contentDiv.textContent = content;\n\n            // Add click handler for user messages to enable editing\n            if (role === 'user' && messageIndex !== null) {\n                contentDiv.setAttribute('data-message-index', messageIndex);\n                contentDiv.setAttribute('title', 'Click to edit and restart from here');\n                contentDiv.addEventListener('click', function() {\n                    if (!isGenerating) {\n                        editMessage(messageIndex);\n                    }\n                });\n            }\n\n            // Add click handler for assistant messages to enable regeneration\n            if (role === 'assistant' && messageIndex !== null) {\n                contentDiv.setAttribute('data-message-index', messageIndex);\n                contentDiv.setAttribute('title', 'Click to regenerate this response');\n                contentDiv.addEventListener('click', function() {\n                    if (!isGenerating) {\n                        regenerateMessage(messageIndex);\n                    }\n                });\n            }\n\n            messageDiv.appendChild(contentDiv);\n            chatWrapper.appendChild(messageDiv);\n\n            chatContainer.scrollTop = chatContainer.scrollHeight;\n            return contentDiv;\n        }\n\n        function editMessage(messageIndex) {\n            // Find the message in the messages array\n            if (messageIndex < 0 || messageIndex >= messages.length) return;\n\n            const messageToEdit = messages[messageIndex];\n            if (messageToEdit.role !== 'user') return;\n\n            // Copy message content to input\n            chatInput.value = messageToEdit.content;\n            chatInput.style.height = 'auto';\n            chatInput.style.height = Math.min(chatInput.scrollHeight, 200) + 'px';\n\n            // Remove this message and all subsequent messages from the array\n            messages = messages.slice(0, messageIndex);\n\n            // Remove message elements from DOM starting from messageIndex\n            const allMessages = chatWrapper.querySelectorAll('.message');\n            for (let i = messageIndex; i < allMessages.length; i++) {\n                allMessages[i].remove();\n            }\n\n            // Enable send button and focus input\n            sendButton.disabled = false;\n            chatInput.focus();\n        }\n\n        async function generateAssistantResponse() {\n            isGenerating = true;\n            sendButton.disabled = true;\n\n            const assistantContent = addMessage('assistant', '');\n            assistantContent.innerHTML = '<span class=\"typing-indicator\"></span>';\n\n            try {\n                const response = await fetch(`${API_URL}/chat/completions`, {\n                    method: 'POST',\n                    headers: {\n                        'Content-Type': 'application/json',\n                    },\n                    body: JSON.stringify({\n                        messages: messages,\n                        temperature: currentTemperature,\n                        top_k: currentTopK,\n                        max_tokens: 512\n                    }),\n                });\n\n                if (!response.ok) {\n                    throw new Error(`HTTP error! status: ${response.status}`);\n                }\n\n                const reader = response.body.getReader();\n                const decoder = new TextDecoder();\n                let fullResponse = '';\n                assistantContent.textContent = '';\n\n                while (true) {\n                    const { done, value } = await reader.read();\n                    if (done) break;\n\n                    const chunk = decoder.decode(value);\n                    const lines = chunk.split('\\n');\n\n                    for (const line of lines) {\n                        if (line.startsWith('data: ')) {\n                            try {\n                                const data = JSON.parse(line.slice(6));\n                                if (data.token) {\n                                    fullResponse += data.token;\n                                    assistantContent.textContent = fullResponse;\n                                    chatContainer.scrollTop = chatContainer.scrollHeight;\n                                }\n                            } catch (e) {\n                            }\n                        }\n                    }\n                }\n\n                const assistantMessageIndex = messages.length;\n                messages.push({ role: 'assistant', content: fullResponse });\n\n                // Add click handler to regenerate this assistant message\n                assistantContent.setAttribute('data-message-index', assistantMessageIndex);\n                assistantContent.setAttribute('title', 'Click to regenerate this response');\n                assistantContent.addEventListener('click', function() {\n                    if (!isGenerating) {\n                        regenerateMessage(assistantMessageIndex);\n                    }\n                });\n\n            } catch (error) {\n                console.error('Error:', error);\n                assistantContent.innerHTML = `<div class=\"error-message\">Error: ${error.message}</div>`;\n            } finally {\n                isGenerating = false;\n                sendButton.disabled = !chatInput.value.trim();\n            }\n        }\n\n        async function regenerateMessage(messageIndex) {\n            // Find the message in the messages array\n            if (messageIndex < 0 || messageIndex >= messages.length) return;\n\n            const messageToRegenerate = messages[messageIndex];\n            if (messageToRegenerate.role !== 'assistant') return;\n\n            // Remove this message and all subsequent messages from the array\n            messages = messages.slice(0, messageIndex);\n\n            // Remove message elements from DOM starting from messageIndex\n            const allMessages = chatWrapper.querySelectorAll('.message');\n            for (let i = messageIndex; i < allMessages.length; i++) {\n                allMessages[i].remove();\n            }\n\n            // Regenerate the assistant response\n            await generateAssistantResponse();\n        }\n\n        function handleSlashCommand(command) {\n            const parts = command.trim().split(/\\s+/);\n            const cmd = parts[0].toLowerCase();\n            const arg = parts[1];\n\n            if (cmd === '/temperature') {\n                if (arg === undefined) {\n                    addMessage('console', `Current temperature: ${currentTemperature}`);\n                } else {\n                    const temp = parseFloat(arg);\n                    if (isNaN(temp) || temp < 0 || temp > 2) {\n                        addMessage('console', 'Invalid temperature. Must be between 0.0 and 2.0');\n                    } else {\n                        currentTemperature = temp;\n                        addMessage('console', `Temperature set to ${currentTemperature}`);\n                    }\n                }\n                return true;\n            } else if (cmd === '/topk') {\n                if (arg === undefined) {\n                    addMessage('console', `Current top-k: ${currentTopK}`);\n                } else {\n                    const topk = parseInt(arg);\n                    if (isNaN(topk) || topk < 1 || topk > 200) {\n                        addMessage('console', 'Invalid top-k. Must be between 1 and 200');\n                    } else {\n                        currentTopK = topk;\n                        addMessage('console', `Top-k set to ${currentTopK}`);\n                    }\n                }\n                return true;\n            } else if (cmd === '/clear') {\n                newConversation();\n                return true;\n            } else if (cmd === '/help') {\n                addMessage('console',\n                    'Available commands:\\n' +\n                    '/temperature - Show current temperature\\n' +\n                    '/temperature <value> - Set temperature (0.0-2.0)\\n' +\n                    '/topk - Show current top-k\\n' +\n                    '/topk <value> - Set top-k (1-200)\\n' +\n                    '/clear - Clear conversation\\n' +\n                    '/help - Show this help message'\n                );\n                return true;\n            }\n            return false;\n        }\n\n        async function sendMessage() {\n            const message = chatInput.value.trim();\n            if (!message || isGenerating) return;\n\n            // Handle slash commands\n            if (message.startsWith('/')) {\n                chatInput.value = '';\n                chatInput.style.height = 'auto';\n                handleSlashCommand(message);\n                return;\n            }\n\n            chatInput.value = '';\n            chatInput.style.height = 'auto';\n\n            const userMessageIndex = messages.length;\n            messages.push({ role: 'user', content: message });\n            addMessage('user', message, userMessageIndex);\n\n            await generateAssistantResponse();\n        }\n\n        sendButton.disabled = false;\n\n        // Autofocus the chat input on page load\n        chatInput.focus();\n\n        fetch(`${API_URL}/health`)\n            .then(response => response.json())\n            .then(data => {\n                console.log('Engine status:', data);\n            })\n            .catch(error => {\n                console.error('Engine not available:', error);\n                chatWrapper.innerHTML = '<div class=\"error-message\">Engine not running. Please start engine.py first.</div>';\n            });\n    </script>\n</body>\n</html>\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[project]\nname = \"nanochat\"\nversion = \"0.1.0\"\ndescription = \"the minimal full-stack ChatGPT clone\"\nreadme = \"README.md\"\nrequires-python = \">=3.10\"\ndependencies = [\n    \"datasets>=4.0.0\",\n    \"fastapi>=0.117.1\",\n    \"ipykernel>=7.1.0\",\n    \"kernels>=0.11.7\",\n    \"matplotlib>=3.10.8\",\n    \"psutil>=7.1.0\",\n    \"python-dotenv>=1.2.1\",\n    \"regex>=2025.9.1\",\n    \"rustbpe>=0.1.0\",\n    \"scipy>=1.15.3\",\n    \"setuptools>=80.9.0\",\n    \"tabulate>=0.9.0\",\n    \"tiktoken>=0.11.0\",\n    \"tokenizers>=0.22.0\",\n    \"torch==2.9.1\",\n    \"transformers>=4.57.3\",\n    \"uvicorn>=0.36.0\",\n    \"wandb>=0.21.3\",\n    \"zstandard>=0.25.0\",\n]\n\n[dependency-groups]\ndev = [\n    \"pytest>=8.0.0\",\n]\n\n[tool.pytest.ini_options]\nmarkers = [\n    \"slow: marks tests as slow (deselect with '-m \\\"not slow\\\"')\",\n]\ntestpaths = [\"tests\"]\npython_files = [\"test_*.py\"]\npython_classes = [\"Test*\"]\npython_functions = [\"test_*\"]\n\n# target torch to cuda 12.8 or CPU\n[tool.uv.sources]\ntorch = [\n    { index = \"pytorch-cpu\", extra = \"cpu\" },\n    { index = \"pytorch-cu128\", extra = \"gpu\" },\n]\n\n[[tool.uv.index]]\nname = \"pytorch-cpu\"\nurl = \"https://download.pytorch.org/whl/cpu\"\nexplicit = true\n\n[[tool.uv.index]]\nname = \"pytorch-cu128\"\nurl = \"https://download.pytorch.org/whl/cu128\"\nexplicit = true\n\n[project.optional-dependencies]\ncpu = [\n    \"torch==2.9.1\",\n]\ngpu = [\n    \"torch==2.9.1\",\n]\n\n[tool.uv]\nconflicts = [\n    [\n        { extra = \"cpu\" },\n        { extra = \"gpu\" },\n    ],\n]\n"
  },
  {
    "path": "runs/miniseries.sh",
    "content": "#!/bin/bash\n\n# See speedrun.sh for more comments\n# Usage: ./miniseries.sh [series_name]\n# Example: ./miniseries.sh jan11\n# Default series name is today's date (e.g., jan11)\n\nexport OMP_NUM_THREADS=1\nexport NANOCHAT_BASE_DIR=\"$HOME/.cache/nanochat\"\nmkdir -p $NANOCHAT_BASE_DIR\n\n# Setup (skip with SKIP_SETUP=1)\nif [ -z \"$SKIP_SETUP\" ]; then\n    # uv\n    command -v uv &> /dev/null || curl -LsSf https://astral.sh/uv/install.sh | sh\n    [ -d \".venv\" ] || uv venv\n    uv sync --extra gpu\n    source .venv/bin/activate\n\n    # Tokenizer, download 1000 shards for pretraining\n    # (probably this can be reduced but it's tricky to determine the exact right number, TODO).\n    python -m nanochat.dataset -n 1000\n    python -m scripts.tok_train --max-chars=2000000000 --vocab-size=32768\nelse\n    source .venv/bin/activate\nfi\n\n# Series name: from arg, env var, or default to today's date (e.g., jan11)\nSERIES_NAME=\"${1:-${SERIES_NAME:-$(date +%b%d | tr '[:upper:]' '[:lower:]')}}\"\n# Depths to train (the \"miniseries\")\nDEPTHS=(12 14 16 18 20 22 24 26)\n# Hardware\nNPROC_PER_NODE=\"${NPROC_PER_NODE:-8}\"\n# Logging\nWANDB_RUN=\"${WANDB_RUN:-${SERIES_NAME}_miniseries}\"\n\nRESULTS_DIR=\"$NANOCHAT_BASE_DIR/${SERIES_NAME}_miniseries_results\"\nmkdir -p \"$RESULTS_DIR\"\nRESULTS_FILE=\"$RESULTS_DIR/results.csv\"\n\n# Write CSV header only if file doesn't exist\nif [ ! -f \"$RESULTS_FILE\" ]; then\n    echo \"depth,model_dim,num_params,num_scaling_params,num_iterations,tokens_trained,param_data_ratio,val_bpb,core_score,train_time_sec\" > \"$RESULTS_FILE\"\nfi\n\nlog() {\n    echo \"[$(date '+%Y-%m-%d %H:%M:%S')] $1\"\n}\n\nlog \"==============================================\"\nlog \"${SERIES_NAME} Miniseries Training\"\nlog \"==============================================\"\n\nfor d in \"${DEPTHS[@]}\"; do\n    log \"Training d=$d...\"\n\n    TAG=\"${SERIES_NAME}_miniseries_d${d}\"\n    START_TIME=$(date +%s)\n\n    # Reduce --device-batch-size to avoid OOM at larger depths\n    if [ $d -ge 28 ]; then\n        DEVICE_BATCH_SIZE_ARG=\"--device-batch-size=8\"\n    elif [ $d -ge 20 ]; then\n        DEVICE_BATCH_SIZE_ARG=\"--device-batch-size=16\"\n    else\n        DEVICE_BATCH_SIZE_ARG=\"--device-batch-size=32\"\n    fi\n\n    torchrun --standalone --nproc_per_node=$NPROC_PER_NODE -m scripts.base_train -- \\\n        --depth=$d \\\n        --run=\"${WANDB_RUN}_d${d}\" \\\n        --model-tag=\"${TAG}\" \\\n        --core-metric-every=999999 \\\n        --core-metric-max-per-task=-1 \\\n        --sample-every=-1 \\\n        --save-every=-1 \\\n        $DEVICE_BATCH_SIZE_ARG \\\n        2>&1 | tee \"$RESULTS_DIR/${TAG}_train.log\"\n\n    END_TIME=$(date +%s)\n    TRAIN_TIME=$((END_TIME - START_TIME))\n\n    # Extract stats from log\n    LOG_FILE=\"$RESULTS_DIR/${TAG}_train.log\"\n    NUM_PARAMS=$(grep \"Number of parameters:\" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | head -1 | tr -d ',')\n    NUM_SCALING_PARAMS=$(grep \"Number of parameters:\" \"$LOG_FILE\" | tail -1 | grep -oP 'scaling: [\\d,]+' | grep -oP '[\\d,]+' | tr -d ',')\n    NUM_ITERS=$(grep \"Calculated number of iterations\" \"$LOG_FILE\" | tail -1 | sed 's/.*: //' | tr -d ',')\n    TOKENS_TRAINED=$((NUM_ITERS * 524288))\n    PARAM_DATA_RATIO=$(python -c \"print(f'{$TOKENS_TRAINED / $NUM_SCALING_PARAMS:.2f}')\")\n    MODEL_DIM=$((d * 64))\n    VAL_BPB=$(grep \"Validation bpb:\" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d.]+$')\n    CORE_SCORE=$(grep \"CORE metric:\" \"$LOG_FILE\" | tail -1 | awk '{print $NF}')\n\n    if [ -z \"$CORE_SCORE\" ]; then\n        CORE_SCORE=\"0.0\"\n    fi\n\n    log \"  d=$d: params=$NUM_PARAMS, scaling=$NUM_SCALING_PARAMS, ratio=$PARAM_DATA_RATIO, bpb=$VAL_BPB, CORE=$CORE_SCORE, time=${TRAIN_TIME}s\"\n\n    # Append to CSV\n    echo \"$d,$MODEL_DIM,$NUM_PARAMS,$NUM_SCALING_PARAMS,$NUM_ITERS,$TOKENS_TRAINED,$PARAM_DATA_RATIO,$VAL_BPB,$CORE_SCORE,$TRAIN_TIME\" >> \"$RESULTS_FILE\"\ndone\n\nlog \"==============================================\"\nlog \"${SERIES_NAME} Miniseries Complete!\"\nlog \"==============================================\"\nlog \"Results saved to: $RESULTS_FILE\"\necho \"\"\necho \"Results:\"\ncolumn -t -s',' \"$RESULTS_FILE\"\n"
  },
  {
    "path": "runs/runcpu.sh",
    "content": "#!/bin/bash\n\n# Showing an example run for exercising some of the code paths on the CPU (or MPS on Macbooks)\n# This script was last updated/tuned on Jan 17, 2026.\n\n# Run as:\n# bash runs/runcpu.sh\n\n# NOTE: Training LLMs requires GPU compute and $$$. You will not get far on your Macbook.\n# Think of this run as educational/fun demo, not something you should expect to work well.\n# You may also want to run this script manually and one by one, copy pasting commands into your terminal.\n\n# all the setup stuff\nexport NANOCHAT_BASE_DIR=\"$HOME/.cache/nanochat\"\nmkdir -p $NANOCHAT_BASE_DIR\ncommand -v uv &> /dev/null || curl -LsSf https://astral.sh/uv/install.sh | sh\n[ -d \".venv\" ] || uv venv\nuv sync --extra cpu\nsource .venv/bin/activate\nif [ -z \"$WANDB_RUN\" ]; then\n    WANDB_RUN=dummy\nfi\n\n# train tokenizer on ~2B characters (~34 seconds on my MacBook Pro M3 Max)\npython -m nanochat.dataset -n 8\npython -m scripts.tok_train --max-chars=2000000000\npython -m scripts.tok_eval\n\n# train a small 4 layer model\n# I tuned this run to complete in about 30 minutes on my MacBook Pro M3 Max.\n# To get better results, try increasing num_iterations, or get other ideas from your favorite LLM.\npython -m scripts.base_train \\\n    --depth=6 \\\n    --head-dim=64 \\\n    --window-pattern=L \\\n    --max-seq-len=512 \\\n    --device-batch-size=32 \\\n    --total-batch-size=16384 \\\n    --eval-every=100 \\\n    --eval-tokens=524288 \\\n    --core-metric-every=-1 \\\n    --sample-every=100 \\\n    --num-iterations=5000 \\\n    --run=$WANDB_RUN\npython -m scripts.base_eval --device-batch-size=1 --split-tokens=16384 --max-per-task=16\n\n# SFT (~10 minutes on my MacBook Pro M3 Max)\ncurl -L -o $NANOCHAT_BASE_DIR/identity_conversations.jsonl https://karpathy-public.s3.us-west-2.amazonaws.com/identity_conversations.jsonl\npython -m scripts.chat_sft \\\n    --max-seq-len=512 \\\n    --device-batch-size=32 \\\n    --total-batch-size=16384 \\\n    --eval-every=200 \\\n    --eval-tokens=524288 \\\n    --num-iterations=1500 \\\n    --run=$WANDB_RUN\n\n# Chat with the model over CLI\n# The model should be able to say that it is Paris.\n# It might even know that the color of the sky is blue.\n# Sometimes the model likes it if you first say Hi before you ask it questions.\n# python -m scripts.chat_cli -p \"What is the capital of France?\"\n\n# Chat with the model over a pretty WebUI ChatGPT style\n# python -m scripts.chat_web\n"
  },
  {
    "path": "runs/scaling_laws.sh",
    "content": "#!/bin/bash\n\nLABEL=\"jan26\"\n\nFLOPS_BUDGETS=(\n    1e18\n    2.15e18\n    4.64e18\n    1e19\n)\nDEPTHS=(8 10 12 14 16 18 20)\n\nNPROC_PER_NODE=\"${NPROC_PER_NODE:-8}\"\nWANDB_RUN=\"${WANDB_RUN:-scaling_${LABEL}}\"\nEVAL_TOKENS=$((100 * 524288))  # ~100M tokens for final eval (default is ~10M)\n\nexport OMP_NUM_THREADS=1\nexport NANOCHAT_BASE_DIR=\"${NANOCHAT_BASE_DIR:-$HOME/.cache/nanochat}\"\nsource .venv/bin/activate\n\nRESULTS_DIR=\"$NANOCHAT_BASE_DIR/scaling_laws_results_${LABEL}\"\nmkdir -p \"$RESULTS_DIR\"\nRESULTS_FILE=\"$RESULTS_DIR/results.csv\"\n\n# Write CSV header only if file doesn't exist\nif [ ! -f \"$RESULTS_FILE\" ]; then\n    echo \"flops_budget,depth,model_dim,params_wte,params_value_embeds,params_lm_head,params_transformer,params_scalars,params_total,num_iterations,tokens_trained,val_bpb,core_score,train_time_sec\" > \"$RESULTS_FILE\"\nfi\n\nlog() {\n    echo \"[$(date '+%Y-%m-%d %H:%M:%S')] $1\"\n}\n\n# Check if a run already exists in results\nrun_exists() {\n    local flops=$1\n    local depth=$2\n    grep -q \"^${flops},${depth},\" \"$RESULTS_FILE\" 2>/dev/null\n}\n\n# =============================================================================\n# Main Loop\n# =============================================================================\n\nfor flops in \"${FLOPS_BUDGETS[@]}\"; do\n    log \"==============================================\"\n    log \"Compute budget: $flops FLOPs\"\n    log \"==============================================\"\n\n    for d in \"${DEPTHS[@]}\"; do\n\n        # Skip if already completed\n        if run_exists \"$flops\" \"$d\"; then\n            log \"Skipping d=$d at $flops FLOPs (already in results)\"\n            continue\n        fi\n\n        log \"Training d=$d at $flops FLOPs...\"\n\n        # Unique tag for this run\n        TAG=\"scaling_${flops}_d${d}\"\n\n        # Record start time\n        START_TIME=$(date +%s)\n\n        # Train the model with fixed flops budget\n        # The script will auto-calculate num_iterations to hit target_flops\n        # CORE eval happens once at the end (999999 ensures only final step)\n        torchrun --standalone --nproc_per_node=$NPROC_PER_NODE -m scripts.base_train -- \\\n            --depth=$d \\\n            --target-flops=$flops \\\n            --target-param-data-ratio=-1 \\\n            --run=\"${WANDB_RUN}_${TAG}\" \\\n            --model-tag=\"${TAG}\" \\\n            --eval-tokens=$EVAL_TOKENS \\\n            --core-metric-every=999999 \\\n            --core-metric-max-per-task=-1 \\\n            --sample-every=-1 \\\n            --save-every=-1 \\\n            2>&1 | tee \"$RESULTS_DIR/${TAG}_train.log\"\n\n        END_TIME=$(date +%s)\n        TRAIN_TIME=$((END_TIME - START_TIME))\n\n        # Extract training stats from the log\n        LOG_FILE=\"$RESULTS_DIR/${TAG}_train.log\"\n\n        # Extract detailed parameter counts (for scaling law analysis with different conventions)\n        # Note: the log format is padded, e.g. \"wte                     : 25,165,824\"\n        # so we grep for \"^key \" (key at start of line followed by space) to avoid false matches\n        PARAMS_WTE=$(grep \"^wte \" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | tr -d ',')\n        PARAMS_VE=$(grep \"^value_embeds \" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | tr -d ',')\n        PARAMS_LM=$(grep \"^lm_head \" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | tr -d ',')\n        PARAMS_TRANSFORMER=$(grep \"^transformer_matrices \" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | tr -d ',')\n        PARAMS_SCALARS=$(grep \"^scalars \" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | tr -d ',')\n        PARAMS_TOTAL=$(grep \"^total \" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d,]+' | tr -d ',')\n\n        NUM_ITERS=$(grep \"Calculated number of iterations\" \"$LOG_FILE\" | tail -1 | sed 's/.*: //' | tr -d ',')\n        # Calculate tokens trained (iterations * batch_size, default 524288)\n        TOKENS_TRAINED=$((NUM_ITERS * 524288))\n        # Model dim\n        MODEL_DIM=$((d * 64))\n        # Val BPB from final eval\n        VAL_BPB=$(grep \"Validation bpb:\" \"$LOG_FILE\" | tail -1 | grep -oP '[\\d.]+$')\n\n        # Extract CORE score from training log (evaluated on final step)\n        CORE_SCORE=$(grep \"CORE metric:\" \"$LOG_FILE\" | tail -1 | awk '{print $NF}')\n        if [ -z \"$CORE_SCORE\" ]; then\n            log \"WARNING: Could not extract CORE score for d=$d\"\n            CORE_SCORE=\"0.0\"\n        fi\n\n        log \"  Params: $PARAMS_TOTAL (transformer: $PARAMS_TRANSFORMER), Iters: $NUM_ITERS, Val BPB: $VAL_BPB, CORE: $CORE_SCORE\"\n\n        # Append to CSV\n        echo \"$flops,$d,$MODEL_DIM,$PARAMS_WTE,$PARAMS_VE,$PARAMS_LM,$PARAMS_TRANSFORMER,$PARAMS_SCALARS,$PARAMS_TOTAL,$NUM_ITERS,$TOKENS_TRAINED,$VAL_BPB,$CORE_SCORE,$TRAIN_TIME\" >> \"$RESULTS_FILE\"\n    done\ndone\n\nlog \"==============================================\"\nlog \"Scaling Laws Sweep Complete\"\nlog \"==============================================\"\nlog \"Results saved to: $RESULTS_FILE\"\necho \"\"\necho \"Results:\"\ncolumn -t -s',' \"$RESULTS_FILE\"\n"
  },
  {
    "path": "runs/speedrun.sh",
    "content": "#!/bin/bash\n\n# This script is configured to train your own GPT-2 grade LLM (pretraining + finetuning)\n# It is designed to run on a blank 8XH100 GPU node and takes approximately 3 hours to complete.\n\n# 1) Example launch (simplest):\n# bash runs/speedrun.sh\n# 2) Example launch in a screen session (because the run takes ~3 hours):\n# screen -L -Logfile runs/speedrun.log -S speedrun bash runs/speedrun.sh\n# 3) Example launch with wandb logging, but see below for setting up wandb first:\n# WANDB_RUN=speedrun screen -L -Logfile runs/speedrun.log -S speedrun bash runs/speedrun.sh\n\n# Default intermediate artifacts directory is in ~/.cache/nanochat\nexport OMP_NUM_THREADS=1\nexport NANOCHAT_BASE_DIR=\"$HOME/.cache/nanochat\"\nmkdir -p $NANOCHAT_BASE_DIR\n\n# -----------------------------------------------------------------------------\n# Python venv setup with uv\n\n# install uv (if not already installed)\ncommand -v uv &> /dev/null || curl -LsSf https://astral.sh/uv/install.sh | sh\n# create a .venv local virtual environment (if it doesn't exist)\n[ -d \".venv\" ] || uv venv\n# install the repo dependencies\nuv sync --extra gpu\n# activate venv so that `python` uses the project's venv instead of system python\nsource .venv/bin/activate\n\n# -----------------------------------------------------------------------------\n# wandb setup\n# If you wish to use wandb for logging (it's nice!, recommended).\n# 1) Make sure to first log in to wandb, e.g. run:\n#    `wandb login`\n# 2) Set the WANDB_RUN environment variable when running this script, e.g.:\n#    `WANDB_RUN=d26 bash speedrun.sh`\nif [ -z \"$WANDB_RUN\" ]; then\n    # by default use \"dummy\" : it's handled as a special case, skips logging to wandb\n    WANDB_RUN=dummy\nfi\n\n# -----------------------------------------------------------------------------\n# During the course of the run, we will be writing markdown reports to the report/\n# directory in the base dir. This command clears it out and writes a header section\n# with a bunch of system info and a timestamp that marks the start of the run.\npython -m nanochat.report reset\n\n# -----------------------------------------------------------------------------\n# Tokenizer\n\n# Download the first ~2B characters of pretraining dataset\n# each data shard is ~250M chars\n# so we download 2e9 / 250e6 = 8 data shards at this point\n# each shard is ~100MB of text (compressed), so this is about ~800MB of data on disk\n# look at dev/repackage_data_reference.py for details on how this data was prepared\npython -m nanochat.dataset -n 8\n# Immediately also kick off downloading more shards in the background while tokenizer trains\n# Approximately 150 shards are needed for GPT-2 capability pretraining, add 20 for padding.\n# The maximum total number of shards available in the entire dataset is 6542.\npython -m nanochat.dataset -n 170 &\nDATASET_DOWNLOAD_PID=$!\n# train the tokenizer with vocab size 2**15 = 32768 on ~2B characters of data\npython -m scripts.tok_train\n# evaluate the tokenizer (report compression ratio etc.)\npython -m scripts.tok_eval\n\n# -----------------------------------------------------------------------------\n# Base model (pretraining)\necho \"Waiting for dataset download to complete...\"\nwait $DATASET_DOWNLOAD_PID\n\n# d24 model (slightly undertrained to beat GPT-2 => decrease data:params ratio from compute optimal 10.5 (default) to 8)\ntorchrun --standalone --nproc_per_node=8 -m scripts.base_train -- --depth=24 --target-param-data-ratio=8 --device-batch-size=16 --fp8 --run=$WANDB_RUN\n# evaluate the model: CORE metric, BPB on train/val, and draw samples\ntorchrun --standalone --nproc_per_node=8 -m scripts.base_eval -- --device-batch-size=16\n\n# -----------------------------------------------------------------------------\n# SFT (teach the model conversation special tokens, tool use, multiple choice)\n\n# download 2.3MB of synthetic identity conversations to impart a personality to nanochat\n# see dev/gen_synthetic_data.py for details on how this data was prepared and to get a sense of how you can easily tune it\ncurl -L -o $NANOCHAT_BASE_DIR/identity_conversations.jsonl https://karpathy-public.s3.us-west-2.amazonaws.com/identity_conversations.jsonl\n\n# run SFT and eval the model\ntorchrun --standalone --nproc_per_node=8 -m scripts.chat_sft -- --device-batch-size=16 --run=$WANDB_RUN\ntorchrun --standalone --nproc_per_node=8 -m scripts.chat_eval -- -i sft\n\n# chat with the model over CLI! Leave out the -p to chat interactively\n# python -m scripts.chat_cli -p \"Why is the sky blue?\"\n\n# even better, chat with your model over a pretty WebUI ChatGPT style\n# python -m scripts.chat_web\n\n# -----------------------------------------------------------------------------\n# Generate the full report by putting together all the sections\n# report.md is the output and will be copied to current directory for convenience\npython -m nanochat.report generate\n"
  },
  {
    "path": "scripts/base_eval.py",
    "content": "\"\"\"\nUnified evaluation script for base models.\n\nSupports three evaluation modes (comma-separated):\n  --eval core    : CORE metric (accuracy on ICL tasks)\n  --eval bpb     : Bits per byte on train/val splits\n  --eval sample  : Generate samples from the model\n\nDefault is all three: --eval core,bpb,sample\n\nExamples:\n\n    # Evaluate a HuggingFace model (e.g. GPT-2 124M) using 8 GPUs\n    torchrun --nproc_per_node=8 -m scripts.base_eval --hf-path openai-community/gpt2\n\n    # Evaluate a nanochat model (e.g. d24) using 8 GPUs\n    torchrun --nproc_per_node=8 -m scripts.base_eval --model-tag d24 --device-batch-size=16\n\n    # Quick/approximate evaluation using a single GPU\n    python -m scripts.base_eval --model-tag d24 --device-batch-size=16 --max-per-task=100 --split-tokens=524288\n\"\"\"\nimport os\nimport csv\nimport time\nimport json\nimport yaml\nimport shutil\nimport random\nimport zipfile\nimport tempfile\nimport argparse\nimport torch\n\nfrom nanochat.common import compute_init, compute_cleanup, print0, get_base_dir, autodetect_device_type, download_file_with_lock\nfrom nanochat.tokenizer import HuggingFaceTokenizer, get_token_bytes\nfrom nanochat.checkpoint_manager import load_model\nfrom nanochat.core_eval import evaluate_task\nfrom nanochat.dataloader import tokenizing_distributed_data_loader_bos_bestfit\nfrom nanochat.loss_eval import evaluate_bpb\nfrom nanochat.engine import Engine\n\n# -----------------------------------------------------------------------------\n# HuggingFace loading utilities\n\nclass ModelWrapper:\n    \"\"\"Lightweight wrapper to give HuggingFace models a nanochat-compatible interface.\"\"\"\n    def __init__(self, model, max_seq_len=None):\n        self.model = model\n        self.max_seq_len = max_seq_len\n\n    def __call__(self, input_ids, targets=None, loss_reduction='mean'):\n        logits = self.model(input_ids).logits\n        if targets is None:\n            return logits\n        loss = torch.nn.functional.cross_entropy(\n            logits.view(-1, logits.size(-1)),\n            targets.view(-1),\n            ignore_index=-1,\n            reduction=loss_reduction\n        )\n        return loss\n\n    def get_device(self):\n        return next(self.model.parameters()).device\n\n\ndef load_hf_model(hf_path: str, device):\n    \"\"\"Load a HuggingFace model and tokenizer.\"\"\"\n    print0(f\"Loading HuggingFace model from: {hf_path}\")\n    from transformers import AutoModelForCausalLM\n    model = AutoModelForCausalLM.from_pretrained(hf_path)\n    model.to(device)\n    model.eval()\n    max_seq_len = 1024 if \"gpt2\" in hf_path else None\n    model = ModelWrapper(model, max_seq_len=max_seq_len)\n    tokenizer = HuggingFaceTokenizer.from_pretrained(hf_path)\n    return model, tokenizer\n\n\ndef get_hf_token_bytes(tokenizer, device=\"cpu\"):\n    \"\"\"Compute token_bytes tensor for a HuggingFace tokenizer.\"\"\"\n    vocab_size = tokenizer.tokenizer.get_vocab_size()\n    token_bytes = torch.zeros(vocab_size, dtype=torch.int64, device=device)\n    for token_id in range(vocab_size):\n        token_str = tokenizer.tokenizer.decode([token_id])\n        token_bytes[token_id] = len(token_str.encode('utf-8'))\n    return token_bytes\n\n# -----------------------------------------------------------------------------\n# CORE evaluation\n\nEVAL_BUNDLE_URL = \"https://karpathy-public.s3.us-west-2.amazonaws.com/eval_bundle.zip\"\n\n\ndef place_eval_bundle(file_path):\n    \"\"\"Unzip eval_bundle.zip and place it in the base directory.\"\"\"\n    base_dir = get_base_dir()\n    eval_bundle_dir = os.path.join(base_dir, \"eval_bundle\")\n    with tempfile.TemporaryDirectory() as tmpdir:\n        with zipfile.ZipFile(file_path, 'r') as zip_ref:\n            zip_ref.extractall(tmpdir)\n        extracted_bundle_dir = os.path.join(tmpdir, \"eval_bundle\")\n        shutil.move(extracted_bundle_dir, eval_bundle_dir)\n    print0(f\"Placed eval_bundle directory at {eval_bundle_dir}\")\n\n\ndef evaluate_core(model, tokenizer, device, max_per_task=-1):\n    \"\"\"\n    Evaluate a base model on the CORE benchmark.\n    Returns dict with results, centered_results, and core_metric.\n    \"\"\"\n    base_dir = get_base_dir()\n    eval_bundle_dir = os.path.join(base_dir, \"eval_bundle\")\n    # Download the eval bundle if needed\n    if not os.path.exists(eval_bundle_dir):\n        download_file_with_lock(EVAL_BUNDLE_URL, \"eval_bundle.zip\", postprocess_fn=place_eval_bundle)\n\n    config_path = os.path.join(eval_bundle_dir, \"core.yaml\")\n    data_base_path = os.path.join(eval_bundle_dir, \"eval_data\")\n    eval_meta_data = os.path.join(eval_bundle_dir, \"eval_meta_data.csv\")\n\n    with open(config_path, 'r', encoding='utf-8') as f:\n        config = yaml.safe_load(f)\n    tasks = config['icl_tasks']\n\n    # Load random baseline values\n    random_baselines = {}\n    with open(eval_meta_data, 'r', encoding='utf-8') as f:\n        reader = csv.DictReader(f)\n        for row in reader:\n            task_name = row['Eval Task']\n            random_baseline = row['Random baseline']\n            random_baselines[task_name] = float(random_baseline)\n\n    # Evaluate each task\n    results = {}\n    centered_results = {}\n    for task in tasks:\n        start_time = time.time()\n        label = task['label']\n        task_meta = {\n            'task_type': task['icl_task_type'],\n            'dataset_uri': task['dataset_uri'],\n            'num_fewshot': task['num_fewshot'][0],\n            'continuation_delimiter': task.get('continuation_delimiter', ' ')\n        }\n        print0(f\"Evaluating: {label} ({task_meta['num_fewshot']}-shot, type: {task_meta['task_type']})... \", end='')\n\n        data_path = os.path.join(data_base_path, task_meta['dataset_uri'])\n        with open(data_path, 'r', encoding='utf-8') as f:\n            data = [json.loads(line.strip()) for line in f]\n\n        # Shuffle for consistent subsampling when using max_per_task\n        shuffle_rng = random.Random(1337)\n        shuffle_rng.shuffle(data)\n        if max_per_task > 0:\n            data = data[:max_per_task]\n\n        accuracy = evaluate_task(model, tokenizer, data, device, task_meta)\n        results[label] = accuracy\n        random_baseline = random_baselines[label]\n        centered_result = (accuracy - 0.01 * random_baseline) / (1.0 - 0.01 * random_baseline)\n        centered_results[label] = centered_result\n        elapsed = time.time() - start_time\n        print0(f\"accuracy: {accuracy:.4f} | centered: {centered_result:.4f} | time: {elapsed:.2f}s\")\n\n    core_metric = sum(centered_results.values()) / len(centered_results)\n    out = {\n        \"results\": results,\n        \"centered_results\": centered_results,\n        \"core_metric\": core_metric\n    }\n    return out\n\n# -----------------------------------------------------------------------------\n# Main\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Base model evaluation\")\n    parser.add_argument('--eval', type=str, default='core,bpb,sample', help='Comma-separated evaluations to run: core,bpb,sample (default: all)')\n    parser.add_argument('--hf-path', type=str, default=None, help='HuggingFace model path (e.g. openai-community/gpt2-xl)')\n    parser.add_argument('--model-tag', type=str, default=None, help='nanochat model tag to identify the checkpoint directory')\n    parser.add_argument('--step', type=int, default=None, help='Model step to load (default = last)')\n    parser.add_argument('--max-per-task', type=int, default=-1, help='Max examples per CORE task (-1 = all)')\n    parser.add_argument('--device-batch-size', type=int, default=32, help='Per-device batch size for BPB evaluation')\n    parser.add_argument('--split-tokens', type=int, default=40*524288, help='Number of tokens to evaluate per split for BPB')\n    parser.add_argument('--device-type', type=str, default='', help='cuda|cpu|mps (empty = autodetect)')\n    args = parser.parse_args()\n\n    # Parse evaluation modes\n    eval_modes = set(mode.strip() for mode in args.eval.split(','))\n    valid_modes = {'core', 'bpb', 'sample'}\n    invalid = eval_modes - valid_modes\n    if invalid:\n        parser.error(f\"Invalid eval modes: {invalid}. Valid: {valid_modes}\")\n\n    # Distributed / precision setup\n    device_type = autodetect_device_type() if args.device_type == '' else args.device_type\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\n    # Load model and tokenizer\n    is_hf_model = args.hf_path is not None\n    if is_hf_model:\n        model, tokenizer = load_hf_model(args.hf_path, device)\n        sequence_len = model.max_seq_len or 1024\n        token_bytes = get_hf_token_bytes(tokenizer, device=device)\n        model_name = args.hf_path\n        model_slug = args.hf_path.replace(\"/\", \"-\")\n    else:\n        model, tokenizer, meta = load_model(\"base\", device, phase=\"eval\", model_tag=args.model_tag, step=args.step)\n        sequence_len = meta[\"model_config\"][\"sequence_len\"]\n        token_bytes = get_token_bytes(device=device)\n        model_name = f\"base_model (step {meta['step']})\"\n        model_slug = f\"base_model_{meta['step']:06d}\"\n\n    print0(f\"Evaluating model: {model_name}\")\n    print0(f\"Eval modes: {', '.join(sorted(eval_modes))}\")\n\n    # Results to log\n    core_results = None\n    bpb_results = {}\n    samples = []\n    unconditioned_samples = []\n\n    # --- Sampling ---\n    if 'sample' in eval_modes and not is_hf_model:\n        print0(\"\\n\" + \"=\"*80)\n        print0(\"Model Samples\")\n        print0(\"=\"*80)\n        if ddp_rank == 0:\n            prompts = [\n                \"The capital of France is\",\n                \"The chemical symbol of gold is\",\n                \"If yesterday was Friday, then tomorrow will be\",\n                \"The opposite of hot is\",\n                \"The planets of the solar system are:\",\n                \"My favorite color is\",\n                \"If 5*x + 3 = 13, then x is\",\n            ]\n            engine = Engine(model, tokenizer)\n            print0(\"\\nConditioned samples:\")\n            for prompt in prompts:\n                tokens = tokenizer(prompt, prepend=\"<|bos|>\")\n                sample, _ = engine.generate_batch(tokens, num_samples=1, max_tokens=16, temperature=0)\n                sample_str = tokenizer.decode(sample[0])\n                print0(\"-\" * 80)\n                print0(sample_str)\n                samples.append(sample_str)\n\n            print0(\"\\nUnconditioned samples:\")\n            tokens = tokenizer(\"\", prepend=\"<|bos|>\")\n            uncond, _ = engine.generate_batch(tokens, num_samples=8, max_tokens=128, temperature=1.0)\n            for sample in uncond:\n                sample_str = tokenizer.decode(sample)\n                print0(\"-\" * 80)\n                print0(sample_str)\n                unconditioned_samples.append(sample_str)\n    elif 'sample' in eval_modes and is_hf_model:\n        print0(\"\\nSkipping sampling for HuggingFace models (not supported)\")\n\n    # --- BPB evaluation ---\n    if 'bpb' in eval_modes:\n        print0(\"\\n\" + \"=\"*80)\n        print0(\"BPB Evaluation\")\n        print0(\"=\"*80)\n        tokens_per_step = args.device_batch_size * sequence_len * ddp_world_size\n        if args.split_tokens % tokens_per_step != 0:\n            # Adjust to nearest multiple\n            args.split_tokens = (args.split_tokens // tokens_per_step) * tokens_per_step\n            print0(f\"Adjusted split_tokens to {args.split_tokens} (must be divisible by {tokens_per_step})\")\n        steps = args.split_tokens // tokens_per_step\n\n        for split_name in [\"train\", \"val\"]:\n            loader = tokenizing_distributed_data_loader_bos_bestfit(tokenizer, args.device_batch_size, sequence_len, split_name, device=device)\n            bpb = evaluate_bpb(model, loader, steps, token_bytes)\n            bpb_results[split_name] = bpb\n            print0(f\"{split_name} bpb: {bpb:.6f}\")\n\n    # --- CORE evaluation ---\n    if 'core' in eval_modes:\n        print0(\"\\n\" + \"=\"*80)\n        print0(\"CORE Evaluation\")\n        print0(\"=\"*80)\n        core_results = evaluate_core(model, tokenizer, device, max_per_task=args.max_per_task)\n\n        # Write CSV output\n        if ddp_rank == 0:\n            base_dir = get_base_dir()\n            output_csv_path = os.path.join(base_dir, \"base_eval\", f\"{model_slug}.csv\")\n            os.makedirs(os.path.dirname(output_csv_path), exist_ok=True)\n            with open(output_csv_path, 'w', encoding='utf-8', newline='') as f:\n                f.write(f\"{'Task':<35}, {'Accuracy':<10}, {'Centered':<10}\\n\")\n                for label in core_results[\"results\"]:\n                    acc = core_results[\"results\"][label]\n                    centered = core_results[\"centered_results\"][label]\n                    f.write(f\"{label:<35}, {acc:<10.6f}, {centered:<10.6f}\\n\")\n                f.write(f\"{'CORE':<35}, {'':<10}, {core_results['core_metric']:<10.6f}\\n\")\n            print0(f\"\\nResults written to: {output_csv_path}\")\n            print0(f\"CORE metric: {core_results['core_metric']:.4f}\")\n\n    # --- Log to report ---\n    from nanochat.report import get_report\n    report_data = [{\"model\": model_name}]\n\n    if core_results:\n        report_data[0][\"CORE metric\"] = core_results[\"core_metric\"]\n        report_data.append(core_results[\"centered_results\"])\n\n    if bpb_results:\n        report_data[0][\"train bpb\"] = bpb_results.get(\"train\")\n        report_data[0][\"val bpb\"] = bpb_results.get(\"val\")\n\n    if samples:\n        report_data.append({f\"sample {i}\": s for i, s in enumerate(samples)})\n    if unconditioned_samples:\n        report_data.append({f\"unconditioned {i}\": s for i, s in enumerate(unconditioned_samples)})\n\n    get_report().log(section=\"Base model evaluation\", data=report_data)\n\n    compute_cleanup()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/base_train.py",
    "content": "\"\"\"\nTrain model. From root directory of the project, run as:\n\npython -m scripts.base_train\n\nor distributed as:\n\ntorchrun --nproc_per_node=8 -m scripts.base_train\n\nIf you are only on CPU/Macbook, you'll want to train a much much smaller LLM. Example:\npython -m scripts.base_train --depth=4 --max-seq-len=512 --device-batch-size=1 --eval-tokens=512 --core-metric-every=-1 --total-batch-size=512 --num-iterations=20\n\"\"\"\n\nimport os\nos.environ[\"PYTORCH_ALLOC_CONF\"] = \"expandable_segments:True\"\nimport gc\nimport json\nimport time\nimport math\nimport argparse\nfrom dataclasses import asdict\nfrom contextlib import contextmanager\n\nimport wandb\nimport torch\nimport torch.distributed as dist\n\nfrom nanochat.gpt import GPT, GPTConfig, Linear\nfrom nanochat.dataloader import tokenizing_distributed_data_loader_bos_bestfit, tokenizing_distributed_data_loader_with_state_bos_bestfit\nfrom nanochat.common import compute_init, compute_cleanup, print0, DummyWandb, print_banner, get_base_dir, autodetect_device_type, get_peak_flops, COMPUTE_DTYPE, COMPUTE_DTYPE_REASON, is_ddp_initialized\nfrom nanochat.tokenizer import get_tokenizer, get_token_bytes\nfrom nanochat.checkpoint_manager import save_checkpoint, load_checkpoint\nfrom nanochat.loss_eval import evaluate_bpb\nfrom nanochat.engine import Engine\nfrom nanochat.flash_attention import HAS_FA3\nfrom scripts.base_eval import evaluate_core\nprint_banner()\n\n# -----------------------------------------------------------------------------\n# CLI arguments\nparser = argparse.ArgumentParser(description=\"Pretrain base model\")\n# Logging\nparser.add_argument(\"--run\", type=str, default=\"dummy\", help=\"wandb run name ('dummy' disables wandb logging)\")\n# Runtime\nparser.add_argument(\"--device-type\", type=str, default=\"\", help=\"cuda|cpu|mps (empty = autodetect)\")\n# FP8 training\nparser.add_argument(\"--fp8\", action=\"store_true\", help=\"enable FP8 training (requires H100+ GPU and torchao)\")\nparser.add_argument(\"--fp8-recipe\", type=str, default=\"tensorwise\", choices=[\"rowwise\", \"tensorwise\"], help=\"FP8 scaling recipe: tensorwise (faster, recommended) or rowwise (more accurate but slower)\")\n# Model architecture\nparser.add_argument(\"--depth\", type=int, default=20, help=\"depth of the Transformer model\")\nparser.add_argument(\"--aspect-ratio\", type=int, default=64, help=\"model_dim = depth * aspect_ratio\")\nparser.add_argument(\"--head-dim\", type=int, default=128, help=\"target head dimension for attention\")\nparser.add_argument(\"--max-seq-len\", type=int, default=2048, help=\"max context length\")\nparser.add_argument(\"--window-pattern\", type=str, default=\"SSSL\", help=\"sliding window pattern tiled across layers: L=full, S=half context (e.g. 'SSL')\")\n# Training horizon (only one used, in order of precedence)\nparser.add_argument(\"--num-iterations\", type=int, default=-1, help=\"explicit number of optimization steps (-1 = disable)\")\nparser.add_argument(\"--target-flops\", type=float, default=-1.0, help=\"calculate num_iterations to reach target_flops (-1 = disable)\")\nparser.add_argument(\"--target-param-data-ratio\", type=float, default=10.5, help=\"calculate num_iterations to maintain data:param ratio (Chinchilla=20, -1 = disable)\")\n# Optimization\nparser.add_argument(\"--device-batch-size\", type=int, default=32, help=\"per-device batch size. good number to reduce to 16,8,4,... if you OOM on VRAM.\")\nparser.add_argument(\"--total-batch-size\", type=int, default=-1, help=\"total batch size in tokens. decent numbers are e.g. 524288. (-1 = auto-compute optimal)\")\nparser.add_argument(\"--embedding-lr\", type=float, default=0.3, help=\"learning rate for embedding parameters (Adam)\")\nparser.add_argument(\"--unembedding-lr\", type=float, default=0.008, help=\"learning rate for unembedding parameters (Adam)\")\nparser.add_argument(\"--weight-decay\", type=float, default=0.28, help=\"cautious weight decay for the Muon optimizer (for weights)\")\nparser.add_argument(\"--matrix-lr\", type=float, default=0.02, help=\"learning rate for matrix parameters (Muon)\")\nparser.add_argument(\"--scalar-lr\", type=float, default=0.5, help=\"learning rate for scalars (resid_lambdas, x0_lambdas)\")\nparser.add_argument(\"--warmup-steps\", type=int, default=40, help=\"number of steps for LR warmup\")\nparser.add_argument(\"--warmdown-ratio\", type=float, default=0.65, help=\"ratio of iterations for LR warmdown\")\nparser.add_argument(\"--final-lr-frac\", type=float, default=0.05, help=\"final LR as fraction of initial LR\")\nparser.add_argument(\"--resume-from-step\", type=int, default=-1, help=\"resume training from this step (-1 = disable)\")\n# Evaluation\nparser.add_argument(\"--eval-every\", type=int, default=250, help=\"evaluate val bpb every N steps (-1 = disable)\")\nparser.add_argument(\"--eval-tokens\", type=int, default=80*524288, help=\"number of tokens to evaluate val loss on\")\nparser.add_argument(\"--core-metric-every\", type=int, default=2000, help=\"evaluate CORE metric every N steps (-1 = disable)\")\nparser.add_argument(\"--core-metric-max-per-task\", type=int, default=500, help=\"examples per task for CORE metric\")\nparser.add_argument(\"--sample-every\", type=int, default=2000, help=\"sample from model every N steps (-1 = disable)\")\nparser.add_argument(\"--save-every\", type=int, default=-1, help=\"save checkpoints every N steps (-1 = only at end)\")\n# Output\nparser.add_argument(\"--model-tag\", type=str, default=None, help=\"override model tag for checkpoint directory name\")\nargs = parser.parse_args()\nuser_config = vars(args).copy()  # for logging\n# -----------------------------------------------------------------------------\n# Compute init and wandb logging\n\ndevice_type = autodetect_device_type() if args.device_type == \"\" else args.device_type\nddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\nmaster_process = ddp_rank == 0 # this process will do logging, checkpointing etc.\nsynchronize = torch.cuda.synchronize if device_type == \"cuda\" else lambda: None\nget_max_memory = torch.cuda.max_memory_allocated if device_type == \"cuda\" else lambda: 0\nif device_type == \"cuda\":\n    gpu_device_name = torch.cuda.get_device_name(0)\n    gpu_peak_flops = get_peak_flops(gpu_device_name)\n    print0(f\"GPU: {gpu_device_name} | Peak FLOPS (BF16): {gpu_peak_flops:.2e}\")\nelse:\n    gpu_peak_flops = float('inf')  # MFU not meaningful for CPU/MPS\nprint0(f\"COMPUTE_DTYPE: {COMPUTE_DTYPE} ({COMPUTE_DTYPE_REASON})\")\n\n# wandb logging init\nuse_dummy_wandb = args.run == \"dummy\" or not master_process\nwandb_run = DummyWandb() if use_dummy_wandb else wandb.init(project=\"nanochat\", name=args.run, config=user_config)\n\n# Flash Attention status\nfrom nanochat.flash_attention import USE_FA3\nusing_fa3 = USE_FA3\nif using_fa3:\n    print0(\"✓ Using Flash Attention 3 (Hopper GPU detected), efficient, new and awesome.\")\nelse:\n    print0(\"!\" * 80)\n    if HAS_FA3 and COMPUTE_DTYPE != torch.bfloat16:\n        print0(f\"WARNING: Flash Attention 3 only supports bf16, but COMPUTE_DTYPE={COMPUTE_DTYPE}. Using PyTorch SDPA fallback\")\n    else:\n        print0(\"WARNING: Flash Attention 3 not available, using PyTorch SDPA fallback\")\n    print0(\"WARNING: Training will be less efficient without FA3\")\n    if args.window_pattern != \"L\":\n        print0(f\"WARNING: SDPA has no support for sliding window attention (window_pattern='{args.window_pattern}'). Your GPU utilization will be terrible.\")\n        print0(\"WARNING: Recommend using --window-pattern L for full context attention without alternating sliding window patterns.\")\n    print0(\"!\" * 80)\n\n# -----------------------------------------------------------------------------\n# Tokenizer will be useful for evaluation and also we need the vocab size to init the model\ntokenizer = get_tokenizer()\ntoken_bytes = get_token_bytes(device=device)\nvocab_size = tokenizer.get_vocab_size()\nprint0(f\"Vocab size: {vocab_size:,}\")\n\n# -----------------------------------------------------------------------------\n# Initialize the Model\n\ndef build_model_meta(depth):\n    \"\"\"Build a model on meta device for a given depth (shapes/dtypes only, no data).\"\"\"\n    # Model dim is nudged up to nearest multiple of head_dim for clean division\n    # (FA3 requires head_dim divisible by 8, and this guarantees head_dim == args.head_dim exactly)\n    base_dim = depth * args.aspect_ratio\n    model_dim = ((base_dim + args.head_dim - 1) // args.head_dim) * args.head_dim\n    num_heads = model_dim // args.head_dim\n    config = GPTConfig(\n        sequence_len=args.max_seq_len, vocab_size=vocab_size,\n        n_layer=depth, n_head=num_heads, n_kv_head=num_heads, n_embd=model_dim,\n        window_pattern=args.window_pattern,\n    )\n    with torch.device(\"meta\"):\n        model_meta = GPT(config)\n    return model_meta\n\n# Build the model, move to device, init the weights\nmodel = build_model_meta(args.depth) # 1) Build on meta device (only shapes/dtypes, no data)\nmodel_config = model.config\nmodel_config_kwargs = asdict(model_config)\nprint0(f\"Model config:\\n{json.dumps(model_config_kwargs, indent=2)}\")\nmodel.to_empty(device=device) # 2) All tensors get storage on target device but with uninitialized (garbage) data\nmodel.init_weights() # 3) All tensors get initialized\n\n# If we are resuming, overwrite the model parameters with those of the checkpoint\nbase_dir = get_base_dir()\noutput_dirname = args.model_tag if args.model_tag else f\"d{args.depth}\" # e.g. d12\ncheckpoint_dir = os.path.join(base_dir, \"base_checkpoints\", output_dirname)\nresuming = args.resume_from_step != -1\nif resuming:\n    print0(f\"Resuming optimization from step {args.resume_from_step}\")\n    model_data, optimizer_data, meta_data = load_checkpoint(checkpoint_dir, args.resume_from_step, device, load_optimizer=True, rank=ddp_rank)\n    model.load_state_dict(model_data, strict=True, assign=True)\n    del model_data # free up this memory after the copy\n\n# -----------------------------------------------------------------------------\n# FP8 training initialization and management (this has to be done before torch.compile)\n\n# Convert Linear layers to Float8Linear if --fp8 is set\nif args.fp8:\n    if device_type != \"cuda\":\n        print0(\"Warning: FP8 training requires CUDA, ignoring --fp8 flag\")\n    else:\n        # our custom fp8 is simpler than torchao, written for exact API compatibility\n        from nanochat.fp8 import Float8LinearConfig, convert_to_float8_training\n        # from torchao.float8 import Float8LinearConfig, convert_to_float8_training\n        import torch.nn as nn\n\n        # Filter: dims must be divisible by 16 (FP8 hardware requirement) large enough\n        def fp8_module_filter(mod: nn.Module, fqn: str) -> bool:\n            if not isinstance(mod, nn.Linear):\n                return False\n            if mod.in_features % 16 != 0 or mod.out_features % 16 != 0:\n                return False\n            if min(mod.in_features, mod.out_features) < 128:\n                return False\n            return True\n\n        fp8_config = Float8LinearConfig.from_recipe_name(args.fp8_recipe)\n        num_linear = sum(1 for m in model.modules() if isinstance(m, nn.Linear))\n        convert_to_float8_training(model, config=fp8_config, module_filter_fn=fp8_module_filter)\n        num_fp8 = sum(1 for m in model.modules() if 'Float8' in type(m).__name__)\n        num_skipped = num_linear - num_fp8\n        print0(f\"✓ FP8 training enabled ({args.fp8_recipe} scaling) - converted {num_fp8}/{num_linear} linear layers, skipped {num_skipped} (too small)\")\n\n# Context manager to temporarily disable FP8 so that model evaluation remains in BF16\n@contextmanager\ndef disable_fp8(model):\n    \"\"\"Temporarily swap Float8Linear modules with nn.Linear for BF16 evaluation.\n\n    CastConfig is a frozen dataclass, so we can't mutate scaling_type. Instead,\n    we swap out Float8Linear modules entirely and restore them after.\n    \"\"\"\n    import torch.nn as nn\n\n    # Find all Float8Linear modules and their locations\n    fp8_locations = []  # list of (parent_module, attr_name, fp8_module)\n    for name, module in model.named_modules():\n        if 'Float8' in type(module).__name__:\n            if '.' in name:\n                parent_name, attr_name = name.rsplit('.', 1)\n                parent = model.get_submodule(parent_name)\n            else:\n                parent = model\n                attr_name = name\n            fp8_locations.append((parent, attr_name, module))\n\n    if not fp8_locations:\n        yield  # No FP8 modules, nothing to do\n        return\n\n    # Swap Float8Linear -> Linear (our custom class that casts weights to match input dtype)\n    for parent, attr_name, fp8_module in fp8_locations:\n        linear = Linear(\n            fp8_module.in_features,\n            fp8_module.out_features,\n            bias=fp8_module.bias is not None,\n            device=fp8_module.weight.device,\n            dtype=fp8_module.weight.dtype,\n        )\n        linear.weight = fp8_module.weight  # share, don't copy\n        if fp8_module.bias is not None:\n            linear.bias = fp8_module.bias\n        setattr(parent, attr_name, linear)\n\n    try:\n        yield\n    finally:\n        # Restore Float8Linear modules\n        for parent, attr_name, fp8_module in fp8_locations:\n            setattr(parent, attr_name, fp8_module)\n\n# -----------------------------------------------------------------------------\n# Compile the model\n\norig_model = model # original, uncompiled model, for saving raw model state_dict and for inference/evaluation (because the shapes may change shape)\nmodel = torch.compile(model, dynamic=False) # the inputs to model will never change shape so dynamic=False is safe\n\n# -----------------------------------------------------------------------------\n# Scaling laws and muP extrapolations to determine the optimal training horizon, batch size, learning rates, weight decay.\n\n# Get the parameter counts of our model\nparam_counts = model.num_scaling_params()\nprint0(f\"Parameter counts:\")\nfor key, value in param_counts.items():\n    print0(f\"{key:24s}: {value:,}\")\nnum_params = param_counts['total']\nnum_flops_per_token = model.estimate_flops()\nprint0(f\"Estimated FLOPs per token: {num_flops_per_token:e}\")\n\n# 1) Use scaling laws to determine the optimal training horizon in tokens\n# The compute-optimal models satisfy the Tokens:Params ratio of --target-param-data-ratio (derived experimentally via scaling laws analysis).\n# We've already initialized the model so we have Params. Optimal Tokens is now simply target-param-data-ratio * Params\ndef get_scaling_params(m):\n    # As for which params to use exactly, transformer matrices + lm_head gives cleanest scaling laws (see dev/LOG.md Jan 27, 2026)\n    params_counts = m.num_scaling_params()\n    scaling_params = params_counts['transformer_matrices'] + params_counts['lm_head']\n    return scaling_params\nnum_scaling_params = get_scaling_params(model)\ntarget_tokens = int(args.target_param_data_ratio * num_scaling_params) # optimal tokens for the model we are about to train\n\n# Our reference model is d12, this is where a lot of hyperparameters are tuned and then transfered to higher depths (muP style)\nd12_ref = build_model_meta(12) # creates the model on meta device\nD_REF = args.target_param_data_ratio * get_scaling_params(d12_ref) # compute-optimal d12 training horizon in tokens (measured empirically)\nB_REF = 2**19 # optimal batch size at d12 ~= 524,288 tokens (measured empirically)\n\n# 2) Now that we have the token horizon, we can calculate the optimal batch size\n# We follow the Power Lines paper (Bopt ∝ D^0.383), ref: https://arxiv.org/abs/2505.13738\n# The optimal batch size grows as approximately D^0.383, so e.g. if D doubles from d12 to d24, B should grow by 2^0.383 ≈ 1.3x.\ntotal_batch_size = args.total_batch_size # user-provided override is possible\nif total_batch_size == -1:\n    batch_size_ratio = target_tokens / D_REF\n    predicted_batch_size = B_REF * batch_size_ratio ** 0.383\n    total_batch_size = 2 ** round(math.log2(predicted_batch_size)) # clamp to nearest power of 2 for efficiency\n    print0(f\"Auto-computed optimal batch size: {total_batch_size:,} tokens\")\n\n# 3) Knowing the batch size, we can now calculate a learning rate correction (bigger batch size allows higher learning rates)\nbatch_lr_scale = 1.0\nbatch_ratio = total_batch_size / B_REF # B/B_ref\nif batch_ratio != 1.0:\n    # SGD: linear scaling with batch size is standard (not used in nanochat)\n    # AdamW: sqrt scaling is standard: η ∝ √(B/B_ref)\n    # Muon: we will use the same scaling for Muon as for AdamW: η ∝ √(B/B_ref) (not studied carefully, assumption!)\n    batch_lr_scale = batch_ratio ** 0.5 # η ∝ √(B/B_ref)\n    print0(f\"Scaling LRs by {batch_lr_scale:.4f} for batch size {total_batch_size:,} (reference: {B_REF:,})\")\n\n# 4) Knowing the batch size and the token horizon, we can now calculate the appropriate weight decay scaling\n# We adopt the T_epoch framework from https://arxiv.org/abs/2405.13698\n# Central idea of the paper is that T_epoch = B/(η·λ·D) should remain constant.\n# Above, we used learning rate scaling η ∝ √(B/B_ref). So it's a matter of ~10 lines of math to derive that to keep T_epoch constant, we need:\n# λ = λ_ref · √(B/B_ref) · (D_ref/D)\n# Note that these papers study AdamW, *not* Muon. We are blindly following AdamW theory for scaling hoping it ~works for Muon too.\nweight_decay_scaled = args.weight_decay * math.sqrt(total_batch_size / B_REF) * (D_REF / target_tokens)\nif weight_decay_scaled != args.weight_decay:\n    print0(f\"Scaling weight decay from {args.weight_decay:.6f} to {weight_decay_scaled:.6f} for depth {args.depth}\")\n\n# -----------------------------------------------------------------------------\n# Initialize the Optimizer (combined MuonAdamW: Muon for matrix params, AdamW for rest)\noptimizer = model.setup_optimizer(\n    # AdamW hyperparameters\n    unembedding_lr=args.unembedding_lr * batch_lr_scale,\n    embedding_lr=args.embedding_lr * batch_lr_scale,\n    scalar_lr=args.scalar_lr * batch_lr_scale,\n    # Muon hyperparameters\n    matrix_lr=args.matrix_lr * batch_lr_scale,\n    weight_decay=weight_decay_scaled,\n)\n\nif resuming:\n    optimizer.load_state_dict(optimizer_data)\n    del optimizer_data\n\n# -----------------------------------------------------------------------------\n# GradScaler for fp16 training (bf16/fp32 don't need it — bf16 has the same exponent range as fp32)\nscaler = torch.amp.GradScaler() if COMPUTE_DTYPE == torch.float16 else None\nif scaler is not None:\n    print0(\"GradScaler enabled for fp16 training\")\n\n# -----------------------------------------------------------------------------\n# Initialize the DataLoaders for train/val\ndataloader_resume_state_dict = None if not resuming else meta_data[\"dataloader_state_dict\"]\ntrain_loader = tokenizing_distributed_data_loader_with_state_bos_bestfit(tokenizer, args.device_batch_size, args.max_seq_len, split=\"train\", device=device, resume_state_dict=dataloader_resume_state_dict)\nbuild_val_loader = lambda: tokenizing_distributed_data_loader_bos_bestfit(tokenizer, args.device_batch_size, args.max_seq_len, split=\"val\", device=device)\nx, y, dataloader_state_dict = next(train_loader) # kick off load of the very first batch of data\n\n# -----------------------------------------------------------------------------\n# Calculate the number of iterations we will train for and set up the various schedulers\n\n# num_iterations: either it is given, or from target flops, or from target data:param ratio (in that order)\nassert args.num_iterations > 0 or args.target_param_data_ratio > 0 or args.target_flops > 0\nif args.num_iterations > 0:\n    # Override num_iterations to a specific value if given\n    num_iterations = args.num_iterations\n    print0(f\"Using user-provided number of iterations: {num_iterations:,}\")\nelif args.target_flops > 0:\n    # Calculate the number of iterations from the target flops (used in scaling laws analysis, e.g. runs/scaling_laws.sh)\n    num_iterations = round(args.target_flops / (num_flops_per_token * total_batch_size))\n    print0(f\"Calculated number of iterations from target FLOPs: {num_iterations:,}\")\nelif args.target_param_data_ratio > 0:\n    # Calculate the number of iterations from the target param data ratio (the most common use case)\n    num_iterations = target_tokens // total_batch_size\n    print0(f\"Calculated number of iterations from target data:param ratio: {num_iterations:,}\")\nelse:\n    raise ValueError(\"No training horizon specified\")\ntotal_tokens = total_batch_size * num_iterations # the actual number of tokens we will train for\nprint0(f\"Total number of training tokens: {total_tokens:,}\")\nprint0(f\"Tokens : Scaling params ratio: {total_batch_size * num_iterations / num_scaling_params:.2f}\") # e.g. Chinchilla was ~20\nprint0(f\"Total training FLOPs estimate: {num_flops_per_token * total_tokens:e}\")\n\n# Learning rate schedule (linear warmup, constant, linear warmdown)\ndef get_lr_multiplier(it):\n    warmup_iters = args.warmup_steps\n    warmdown_iters = round(args.warmdown_ratio * num_iterations)\n    if it < warmup_iters:\n        return (it + 1) / warmup_iters\n    elif it <= num_iterations - warmdown_iters:\n        return 1.0\n    else:\n        progress = (num_iterations - it) / warmdown_iters\n        return progress * 1.0 + (1 - progress) * args.final_lr_frac\n\n# Momentum scheduler for Muon optimizer (warms up to 0.97, warms down to 0.90 during LR warmdown)\ndef get_muon_momentum(it):\n    warmdown_iters = round(args.warmdown_ratio * num_iterations)\n    warmdown_start = num_iterations - warmdown_iters\n    if it < 400:\n        frac = it / 400\n        return (1 - frac) * 0.85 + frac * 0.97\n    elif it >= warmdown_start:\n        progress = (it - warmdown_start) / warmdown_iters\n        return 0.97 * (1 - progress) + 0.90 * progress\n    else:\n        return 0.97\n\n# Weight decay scheduler for Muon optimizer (cosine decay to zero over the course of training)\ndef get_weight_decay(it):\n    return weight_decay_scaled * 0.5 * (1 + math.cos(math.pi * it / num_iterations))\n\n# -----------------------------------------------------------------------------\n# Training loop\n\n# Loop state (variables updated by the training loop)\nif not resuming:\n    step = 0\n    val_bpb = None # will be set if eval_every > 0\n    min_val_bpb = float(\"inf\")\n    smooth_train_loss = 0 # EMA of training loss\n    total_training_time = 0 # total wall-clock time of training\nelse:\n    step = meta_data[\"step\"]\n    loop_state = meta_data[\"loop_state\"]\n    val_bpb = meta_data[\"val_bpb\"]\n    min_val_bpb = loop_state[\"min_val_bpb\"]\n    smooth_train_loss = loop_state[\"smooth_train_loss\"]\n    total_training_time = loop_state[\"total_training_time\"]\n\n# Figure out the needed gradient accumulation micro-steps to reach the desired total batch size per step\ntokens_per_fwdbwd = args.device_batch_size * args.max_seq_len # tokens per iteration for a single rank\nworld_tokens_per_fwdbwd = tokens_per_fwdbwd * ddp_world_size # total tokens per iteration for all ranks\nassert total_batch_size % world_tokens_per_fwdbwd == 0\ngrad_accum_steps = total_batch_size // world_tokens_per_fwdbwd\nprint0(f\"Tokens / micro-batch / rank: {args.device_batch_size} x {args.max_seq_len} = {tokens_per_fwdbwd:,}\")\nprint0(f\"Tokens / micro-batch: {world_tokens_per_fwdbwd:,}\")\nprint0(f\"Total batch size {total_batch_size:,} => gradient accumulation steps: {grad_accum_steps}\")\n\n# Go!\nwhile True:\n    last_step = step == num_iterations # loop runs num_iterations+1 times so that we can eval/save at the end\n    flops_so_far = num_flops_per_token * total_batch_size * step\n\n    # once in a while: evaluate the val bpb (all ranks participate)\n    if args.eval_every > 0 and (last_step or step % args.eval_every == 0):\n        model.eval()\n        val_loader = build_val_loader()\n        eval_steps = args.eval_tokens // (args.device_batch_size * args.max_seq_len * ddp_world_size)\n        with disable_fp8(model):\n            val_bpb = evaluate_bpb(model, val_loader, eval_steps, token_bytes)\n        print0(f\"Step {step:05d} | Validation bpb: {val_bpb:.6f}\")\n        if val_bpb < min_val_bpb:\n            min_val_bpb = val_bpb\n        wandb_run.log({\n            \"step\": step,\n            \"total_training_flops\": flops_so_far,\n            \"total_training_time\": total_training_time,\n            \"val/bpb\": val_bpb,\n        })\n        model.train()\n\n    # once in a while: estimate the CORE metric (all ranks participate)\n    # use the original uncompiled model because the inputs keep changing shape\n    # disable FP8 for evaluation to use BF16 for more consistent/accurate results\n    results = {}\n    if args.core_metric_every > 0 and (last_step or (step > 0 and step % args.core_metric_every == 0)):\n        model.eval()\n        with disable_fp8(orig_model):\n            results = evaluate_core(orig_model, tokenizer, device, max_per_task=args.core_metric_max_per_task)\n        print0(f\"Step {step:05d} | CORE metric: {results['core_metric']:.4f}\")\n        wandb_run.log({\n            \"step\": step,\n            \"total_training_flops\": flops_so_far,\n            \"core_metric\": results[\"core_metric\"],\n            \"centered_results\": results[\"centered_results\"],\n        })\n        model.train()\n\n    # once in a while: sample from the model (only on master process)\n    # use the original uncompiled model because the inputs keep changing shape\n    if args.sample_every > 0 and master_process and (last_step or (step > 0 and step % args.sample_every == 0)):\n        model.eval()\n        prompts = [\n            \"The capital of France is\",\n            \"The chemical symbol of gold is\",\n            \"If yesterday was Friday, then tomorrow will be\",\n            \"The opposite of hot is\",\n            \"The planets of the solar system are:\",\n            \"My favorite color is\",\n            \"If 5*x + 3 = 13, then x is\",\n        ]\n        engine = Engine(orig_model, tokenizer) # use orig_model to avoid recompilation\n        for prompt in prompts:\n            tokens = tokenizer(prompt, prepend=\"<|bos|>\")\n            with disable_fp8(orig_model):\n                sample, _ = engine.generate_batch(tokens, num_samples=1, max_tokens=16, temperature=0)\n            print0(tokenizer.decode(sample[0]))\n        model.train()\n\n    # save checkpoint: at the end of the run, or every save_every steps, except at the first step or the resume step\n    if last_step or (step > 0 and step != args.resume_from_step and args.save_every > 0 and step % args.save_every == 0):\n        save_checkpoint(\n            checkpoint_dir,\n            step,\n            orig_model.state_dict(), # model parameters\n            optimizer.state_dict(), # optimizer state\n            { # metadata saved as json\n                \"step\": step,\n                \"val_bpb\": val_bpb, # loss at last step\n                \"model_config\": model_config_kwargs,\n                \"user_config\": user_config, # inputs to the training script\n                \"device_batch_size\": args.device_batch_size,\n                \"max_seq_len\": args.max_seq_len,\n                \"total_batch_size\": total_batch_size,\n                \"dataloader_state_dict\": dataloader_state_dict,\n                \"loop_state\": { # all loop state (other than step) so that we can resume training\n                    \"min_val_bpb\": min_val_bpb,\n                    \"smooth_train_loss\": smooth_train_loss,\n                    \"total_training_time\": total_training_time,\n                },\n            },\n            rank=ddp_rank,\n        )\n\n    # termination conditions (TODO: possibly also add loss explosions etc.)\n    if last_step:\n        break\n\n    # -------------------------------------------------------------------------\n    # single training step\n    # evaluate the gradient\n    synchronize()\n    t0 = time.time()\n    for micro_step in range(grad_accum_steps):\n        loss = model(x, y)\n        train_loss = loss.detach() # for logging\n        loss = loss / grad_accum_steps # each .backward() is a grad sum => normalize loss here\n        if scaler is not None:\n            scaler.scale(loss).backward()\n        else:\n            loss.backward()\n        x, y, dataloader_state_dict = next(train_loader) # prefetch the next batch while the GPU is busy with forward/backward\n    # step the optimizer\n    lrm = get_lr_multiplier(step)\n    muon_momentum = get_muon_momentum(step)\n    muon_weight_decay = get_weight_decay(step)\n    for group in optimizer.param_groups:\n        group[\"lr\"] = group[\"initial_lr\"] * lrm\n        if group['kind'] == 'muon':\n            group[\"momentum\"] = muon_momentum\n            group[\"weight_decay\"] = muon_weight_decay\n    if scaler is not None:\n        scaler.unscale_(optimizer)\n        # In distributed training, all ranks must agree on whether to skip the step.\n        # Each rank may independently encounter inf/nan gradients, so we all-reduce\n        # the found_inf flag (MAX = if any rank found inf, all ranks skip).\n        if is_ddp_initialized():\n            for v in scaler._found_inf_per_device(optimizer).values():\n                dist.all_reduce(v, op=dist.ReduceOp.MAX)\n        scaler.step(optimizer)\n        scaler.update()\n    else:\n        optimizer.step()\n    model.zero_grad(set_to_none=True)\n    train_loss_f = train_loss.item() # .item() is a CPU-GPU sync point\n    synchronize()\n    t1 = time.time()\n    dt = t1 - t0\n    # -------------------------------------------------------------------------\n\n    # logging (CPU action only)\n    ema_beta = 0.9 # EMA decay factor for some smoothing just for nicer logging\n    smooth_train_loss = ema_beta * smooth_train_loss + (1 - ema_beta) * train_loss_f # EMA the training loss\n    debiased_smooth_loss = smooth_train_loss / (1 - ema_beta**(step + 1)) # debias the EMA\n    pct_done = 100 * step / num_iterations\n    tok_per_sec = int(total_batch_size / dt)\n    flops_per_sec = num_flops_per_token * total_batch_size / dt\n    mfu = 100 * flops_per_sec / (gpu_peak_flops * ddp_world_size)\n    if step > 10:\n        total_training_time += dt # only count the time after the first 10 steps\n    # Calculate ETA based on average time per step (excluding first 10 steps)\n    steps_done = step - 10\n    if steps_done > 0:\n        avg_time_per_step = total_training_time / steps_done\n        remaining_steps = num_iterations - step\n        eta_seconds = remaining_steps * avg_time_per_step\n        eta_str = f\" | eta: {eta_seconds/60:.1f}m\"\n    else:\n        eta_str = \"\"\n    epoch = f\"{dataloader_state_dict['epoch']} pq: {dataloader_state_dict['pq_idx']} rg: {dataloader_state_dict['rg_idx']}\"\n    print0(f\"step {step:05d}/{num_iterations:05d} ({pct_done:.2f}%) | loss: {debiased_smooth_loss:.6f} | lrm: {lrm:.2f} | dt: {dt * 1000:.2f}ms | tok/sec: {tok_per_sec:,} | bf16_mfu: {mfu:.2f} | epoch: {epoch} | total time: {total_training_time/60:.2f}m{eta_str}\")\n    if step % 100 == 0:\n        log_data = {\n            \"step\": step,\n            \"total_training_flops\": flops_so_far,\n            \"total_training_time\": total_training_time,\n            \"train/loss\": debiased_smooth_loss,\n            \"train/lrm\": lrm,\n            \"train/dt\": dt,\n            \"train/tok_per_sec\": tok_per_sec,\n            \"train/mfu\": mfu,\n            \"train/epoch\": epoch,\n        }\n        wandb_run.log(log_data)\n\n    # state update\n    first_step_of_run = (step == 0) or (resuming and step == args.resume_from_step)\n    step += 1\n\n    # The garbage collector is sadly a little bit overactive and for some poorly understood reason,\n    # it spends ~500ms scanning for cycles quite frequently, just to end up cleaning up very few tiny objects each time.\n    # So we manually manage and help it out here\n    if first_step_of_run:\n        gc.collect() # manually collect a lot of garbage from setup\n        gc.freeze() # immediately freeze all currently surviving objects and exclude them from GC\n        gc.disable() # nuclear intervention here: disable GC entirely except:\n    elif step % 5000 == 0: # every 5000 steps...\n        gc.collect() # manually collect, just to be safe for very, very long runs\n\n# print a few more stats\nprint0(f\"Peak memory usage: {get_max_memory() / 1024 / 1024:.2f}MiB\")\nprint0(f\"Total training time: {total_training_time/60:.2f}m\")\nif val_bpb is not None:\n    print0(f\"Minimum validation bpb: {min_val_bpb:.6f}\")\n\n# Log to report\nfrom nanochat.report import get_report\nget_report().log(section=\"Base model training\", data=[\n    user_config, # CLI args\n    { # stats about the training setup\n        \"Number of parameters\": num_params,\n        \"Number of FLOPs per token\": f\"{num_flops_per_token:e}\",\n        \"Calculated number of iterations\": num_iterations,\n        \"Number of training tokens\": total_tokens,\n        \"Tokens : Scaling params ratio\": total_batch_size * num_iterations / num_scaling_params,\n        \"DDP world size\": ddp_world_size,\n        \"warmup_steps\": args.warmup_steps,\n        \"warmdown_ratio\": args.warmdown_ratio,\n        \"final_lr_frac\": args.final_lr_frac,\n    },\n    { # stats about training outcomes\n        \"Minimum validation bpb\": min_val_bpb if val_bpb is not None else None,\n        \"Final validation bpb\": val_bpb,\n        \"CORE metric estimate\": results.get(\"core_metric\", None),\n        \"MFU %\": f\"{mfu:.2f}%\",\n        \"Total training flops\": f\"{flops_so_far:e}\",\n        \"Total training time\": f\"{total_training_time/60:.2f}m\",\n        \"Peak memory usage\": f\"{get_max_memory() / 1024 / 1024:.2f}MiB\",\n    }\n])\n\n# cleanup\nwandb_run.finish() # wandb run finish\ncompute_cleanup()\n"
  },
  {
    "path": "scripts/chat_cli.py",
    "content": "\"\"\"\nNew and upgraded chat mode because a lot of the code has changed since the last one.\n\nIntended to be run single GPU only atm:\npython -m scripts.chat_cli\n\"\"\"\nimport argparse\nimport torch\nfrom nanochat.common import compute_init, autodetect_device_type\nfrom nanochat.engine import Engine\nfrom nanochat.checkpoint_manager import load_model\n\nparser = argparse.ArgumentParser(description='Chat with the model')\nparser.add_argument('-i', '--source', type=str, default=\"sft\", help=\"Source of the model: sft|rl\")\nparser.add_argument('-g', '--model-tag', type=str, default=None, help='Model tag to load')\nparser.add_argument('-s', '--step', type=int, default=None, help='Step to load')\nparser.add_argument('-p', '--prompt', type=str, default='', help='Prompt the model, get a single response back')\nparser.add_argument('-t', '--temperature', type=float, default=0.6, help='Temperature for generation')\nparser.add_argument('-k', '--top-k', type=int, default=50, help='Top-k sampling parameter')\nparser.add_argument('--device-type', type=str, default='', choices=['cuda', 'cpu', 'mps'], help='Device type for evaluation: cuda|cpu|mps. empty => autodetect')\nargs = parser.parse_args()\n\n# Init the model and tokenizer\n\ndevice_type = autodetect_device_type() if args.device_type == \"\" else args.device_type\nddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\nmodel, tokenizer, meta = load_model(args.source, device, phase=\"eval\", model_tag=args.model_tag, step=args.step)\n\n# Special tokens for the chat state machine\nbos = tokenizer.get_bos_token_id()\nuser_start, user_end = tokenizer.encode_special(\"<|user_start|>\"), tokenizer.encode_special(\"<|user_end|>\")\nassistant_start, assistant_end = tokenizer.encode_special(\"<|assistant_start|>\"), tokenizer.encode_special(\"<|assistant_end|>\")\n\n# Create Engine for efficient generation\nengine = Engine(model, tokenizer)\n\nprint(\"\\nNanoChat Interactive Mode\")\nprint(\"-\" * 50)\nprint(\"Type 'quit' or 'exit' to end the conversation\")\nprint(\"Type 'clear' to start a new conversation\")\nprint(\"-\" * 50)\n\nconversation_tokens = [bos]\n\nwhile True:\n\n    if args.prompt:\n        # Get the prompt from the launch command\n        user_input = args.prompt\n    else:\n        # Get the prompt interactively from the console\n        try:\n            user_input = input(\"\\nUser: \").strip()\n        except (EOFError, KeyboardInterrupt):\n            print(\"\\nGoodbye!\")\n            break\n\n    # Handle special commands\n    if user_input.lower() in ['quit', 'exit']:\n        print(\"Goodbye!\")\n        break\n\n    if user_input.lower() == 'clear':\n        conversation_tokens = [bos]\n        print(\"Conversation cleared.\")\n        continue\n\n    if not user_input:\n        continue\n\n    # Add User message to the conversation\n    conversation_tokens.append(user_start)\n    conversation_tokens.extend(tokenizer.encode(user_input))\n    conversation_tokens.append(user_end)\n\n    # Kick off the assistant\n    conversation_tokens.append(assistant_start)\n    generate_kwargs = {\n        \"num_samples\": 1,\n        \"max_tokens\": 256,\n        \"temperature\": args.temperature,\n        \"top_k\": args.top_k,\n    }\n    response_tokens = []\n    print(\"\\nAssistant: \", end=\"\", flush=True)\n    for token_column, token_masks in engine.generate(conversation_tokens, **generate_kwargs):\n        token = token_column[0] # pop the batch dimension (num_samples=1)\n        response_tokens.append(token)\n        token_text = tokenizer.decode([token])\n        print(token_text, end=\"\", flush=True)\n    print()\n    # we have to ensure that the assistant end token is the last token\n    # so even if generation ends due to max tokens, we have to append it to the end\n    if response_tokens[-1] != assistant_end:\n        response_tokens.append(assistant_end)\n    conversation_tokens.extend(response_tokens)\n\n    # In the prompt mode, we only want a single response and exit\n    if args.prompt:\n        break\n"
  },
  {
    "path": "scripts/chat_eval.py",
    "content": "\"\"\"\nEvaluate the Chat model.\nAll the generic code lives here, and all the evaluation-specific\ncode lives in nanochat directory and is imported from here.\n\nExample runs:\npython -m scripts.chat_eval -a ARC-Easy\ntorchrun --nproc_per_node=8 -m scripts.chat_eval -- -a ARC-Easy\n\"\"\"\n\nimport argparse\nfrom functools import partial\nimport torch\nimport torch.distributed as dist\n\nfrom nanochat.common import compute_init, compute_cleanup, get_dist_info, print0, autodetect_device_type\nfrom nanochat.checkpoint_manager import load_model\nfrom nanochat.engine import Engine\n\nfrom tasks.humaneval import HumanEval\nfrom tasks.mmlu import MMLU\nfrom tasks.arc import ARC\nfrom tasks.gsm8k import GSM8K\nfrom tasks.spellingbee import SpellingBee\n\n# -----------------------------------------------------------------------------\n# Generative evaluation loop (we go one problem at a time, sample, evaluate)\n\ndef run_generative_eval(task_object, tokenizer, model, engine, num_samples, max_new_tokens, temperature, top_k, max_problems=None):\n\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size = get_dist_info()\n    device = model.get_device()\n\n    num_problems = len(task_object) if max_problems is None else min(len(task_object), max_problems)\n\n    # Run the evaluation\n    num_passed, total = 0, 0\n    for i in range(ddp_rank, num_problems, ddp_world_size):\n        conversation = task_object[i]\n\n        # Tokenize the prompt\n        encoded_prompt = tokenizer.render_for_completion(conversation)\n        # Get the completions\n        results, _ = engine.generate_batch(\n            encoded_prompt,\n            num_samples=num_samples,\n            max_tokens=max_new_tokens,\n            temperature=temperature,\n            top_k=top_k,\n        )\n        # Decode the completions as text\n        prefix_length = len(encoded_prompt)\n        completions = [tokenizer.decode(result_tokens[prefix_length:]) for result_tokens in results]\n        # Evaluate success criteria\n        outcomes = [task_object.evaluate(conversation, completion) for completion in completions]\n        passed = any(outcomes)\n\n        # Keep stats\n        total += 1\n        num_passed += int(passed)\n\n        # Logging (overwrite the same line in the console)\n        print(f\"\\r\\033[KRank {ddp_rank} | {num_passed}/{total} ({100*num_passed/total:.2f}%)\", end='', flush=True)\n\n    # Finish the in-place progress line with a newline before final summary\n    print()\n\n    # Aggregate results across all ranks\n    if ddp:\n        num_passed_tensor = torch.tensor([num_passed], dtype=torch.long, device=device)\n        total_tensor = torch.tensor([total], dtype=torch.long, device=device)\n        dist.all_reduce(num_passed_tensor, op=dist.ReduceOp.SUM)\n        dist.all_reduce(total_tensor, op=dist.ReduceOp.SUM)\n        num_passed = num_passed_tensor.item()\n        total = total_tensor.item()\n\n    print0(\"=\" * 50)\n    print0(f\"Final: {num_passed}/{total} ({100*num_passed/total:.2f}%)\")\n\n    # Return the accuracy\n    return num_passed/total\n\n# -----------------------------------------------------------------------------\n# Categorical evaluation loop\n# A lot easier because we don't have to sample. Therefore, we can actually go\n# batches at a time and just check the logits for correct answer choices.\n\ndef run_categorical_eval(task_object, tokenizer, model, batch_size, max_problems=None):\n\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size = get_dist_info()\n    device = model.get_device()\n    bos = tokenizer.get_bos_token_id() # use BOS as pad token is ok, these positions are ignored\n\n    # We'll process batches of independent problems at a time because there is no sampling needed\n    num_problems = len(task_object) if max_problems is None else min(len(task_object), max_problems)\n    ceil_div = lambda x, y: -(-x // y)\n    num_batches = ceil_div(num_problems, batch_size)\n\n    # Run the evaluation\n    letter_to_id_cache = {} # many letters will repeat often, let's save the tokenizer some work\n    num_passed, total = 0, 0\n    for i in range(ddp_rank, num_batches, ddp_world_size):\n        i0, i1 = i * batch_size, min((i + 1) * batch_size, num_problems)\n\n        # Prepare the batch of problems. They might all be of different length, so we pad/collate them.\n        conversations = [task_object[ii] for ii in range(i0, i1)]\n        prompt_ids = [tokenizer.render_for_completion(conversation) for conversation in conversations] # TODO: remake the way this works\n        max_length = max(len(ids) for ids in prompt_ids)\n        answer_time_positions = [len(ids) - 1 for ids in prompt_ids] # where the last token is (and the predicted answer)\n        padded_prompt_ids = [ids + [bos] * (max_length - len(ids)) for ids in prompt_ids]\n        prompt_ids = torch.tensor(padded_prompt_ids, dtype=torch.long, device=device)\n\n        # Get the logits for the whole batch of conversations in parallel (efficiency win here)\n        with torch.no_grad():\n            logits = model(prompt_ids) # (B, T, V)\n\n        # Focus on the available answer on just the letters corresponding to choices\n        # Note that this helps the evaluation a lot because it specifically narrows the focus to only the available letters\n        # The much harder alternative would be to just generate from the Assistant and check if it responded with the correct\n        # letter (e.g. A, B, C, D), but evaluations typically make the task easier in this way.\n        for idx, conversation in enumerate(conversations):\n            # get the token ids of all the available letters of this problem\n            letters = conversation['letters']\n            letter_ids = []\n            for letter in letters:\n                if not letter in letter_to_id_cache:\n                    encoded_letter = tokenizer.encode(letter)\n                    assert len(encoded_letter) == 1, \"Each letter must be a single token\"\n                    letter_to_id_cache[letter] = encoded_letter[0]\n                letter_ids.append(letter_to_id_cache[letter])\n            # focus logits just down to the answer position and the available letters of the answer\n            answer_pos = answer_time_positions[idx]\n            focus_logits = logits[idx, answer_pos, letter_ids]\n            # get the argmax letter (the predicted answer)\n            argmax_letter_id = focus_logits.argmax(dim=-1).item()\n            predicted_letter = letters[argmax_letter_id]\n            # evaluate the outcome\n            outcome = task_object.evaluate(conversation, predicted_letter)\n            num_passed += int(outcome)\n            total += 1\n\n    # Aggregate results across all ranks\n    if ddp:\n        num_passed_tensor = torch.tensor([num_passed], dtype=torch.long, device=device)\n        total_tensor = torch.tensor([total], dtype=torch.long, device=device)\n        dist.all_reduce(num_passed_tensor, op=dist.ReduceOp.SUM)\n        dist.all_reduce(total_tensor, op=dist.ReduceOp.SUM)\n        num_passed = num_passed_tensor.item()\n        total = total_tensor.item()\n\n    average = num_passed/total\n    print0(f\"Final: {num_passed}/{total} ({100*average:.2f}%)\")\n    return average\n\n# -----------------------------------------------------------------------------\n\ndef run_chat_eval(task_name, model, tokenizer, engine,\n                   batch_size=1, num_samples=1, max_new_tokens=512, temperature=0.0, top_k=50,\n                   max_problems=None):\n    # Create the evaluation object\n    task_module = {\n        'HumanEval': HumanEval,\n        'MMLU': partial(MMLU, subset=\"all\", split=\"test\"),\n        'ARC-Easy': partial(ARC, subset=\"ARC-Easy\", split=\"test\"),\n        'ARC-Challenge': partial(ARC, subset=\"ARC-Challenge\", split=\"test\"),\n        'GSM8K': partial(GSM8K, subset=\"main\", split=\"test\"),\n        'SpellingBee': partial(SpellingBee, size=256, split=\"test\"),\n    }[task_name]\n    task_object = task_module()\n    # Run the evaluation\n    if task_object.eval_type == 'generative':\n        acc = run_generative_eval(task_object, tokenizer, model, engine, num_samples, max_new_tokens, temperature, top_k, max_problems=max_problems)\n    elif task_object.eval_type == 'categorical':\n        acc = run_categorical_eval(task_object, tokenizer, model, batch_size, max_problems=max_problems)\n    else:\n        raise ValueError(f\"Unsupported task evaluation type: {task_object.eval_type}\")\n    return acc\n\n# -----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n    # Parse command-line arguments\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-i', '--source', type=str, required=True, help=\"Source of the model: sft|rl\")\n    parser.add_argument('-a', '--task-name', type=str, default=None, help=\"Task name. Default = all tasks. Use | to split multiple tasks.\")\n    parser.add_argument('-t', '--temperature', type=float, default=0.0)\n    parser.add_argument('-m', '--max-new-tokens', type=int, default=512)\n    parser.add_argument('-n', '--num-samples', type=int, default=1)\n    parser.add_argument('-k', '--top-k', type=int, default=50)\n    parser.add_argument('-b', '--batch-size', type=int, default=8, help='Batch size for categorical evaluation')\n    parser.add_argument('-g', '--model-tag', type=str, default=None, help='Model tag to load')\n    parser.add_argument('-s', '--step', type=int, default=None, help='Step to load')\n    parser.add_argument('-x', '--max-problems', type=int, default=None, help='Max problems to evaluate')\n    parser.add_argument('--device-type', type=str, default='', choices=['cuda', 'cpu', 'mps'], help='Device type for evaluation: cuda|cpu|mps. empty => autodetect')\n    args = parser.parse_args()\n\n    device_type = autodetect_device_type() if args.device_type == \"\" else args.device_type\n    ddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\n\n    model, tokenizer, meta = load_model(args.source, device, phase=\"eval\", model_tag=args.model_tag, step=args.step)\n    engine = Engine(model, tokenizer)\n\n    # Get the tasks to evaluate on\n    all_tasks = ['ARC-Easy', 'ARC-Challenge', 'MMLU', 'GSM8K', 'HumanEval', 'SpellingBee']\n    baseline_accuracies = {\n        'ARC-Easy': 0.25, # multiple choice 1 of 4 => 25%\n        'ARC-Challenge': 0.25, # multiple choice 1 of 4 => 25%\n        'MMLU': 0.25, # multiple choice 1 of 4 => 25%\n        'GSM8K': 0.0, # open-ended => 0%\n        'HumanEval': 0.0, # open-ended => 0%\n        'SpellingBee': 0.0, # open-ended => 0%\n    }\n    task_names = all_tasks if args.task_name is None else args.task_name.split('|')\n\n    # Run all the task evaluations sequentially\n    results = {}\n    for task_name in task_names:\n        acc = run_chat_eval(\n            task_name,\n            model, tokenizer, engine,\n            batch_size=args.batch_size,\n            num_samples=args.num_samples,\n            max_new_tokens=args.max_new_tokens,\n            temperature=args.temperature,\n            top_k=args.top_k,\n            max_problems=args.max_problems,\n        )\n        results[task_name] = acc\n        print0(f\"{task_name} accuracy: {100 * acc:.2f}%\")\n\n    # Log to report\n    from nanochat.report import get_report\n    all_tasks_were_evaluated = all(task_name in results for task_name in all_tasks)\n    # calculate the ChatCORE metric if we can (similar to CORE, it's the mean centered accuracy)\n    # this way, ChatCORE ranges from 0 (at random baseline) to 1 (peak performance)\n    chatcore_metric_dict = {}\n    if all_tasks_were_evaluated:\n        centered_mean = 0\n        for task_name, acc in results.items():\n            baseline_acc = baseline_accuracies.get(task_name, 0.0)\n            centered_acc = (acc - baseline_acc) / (1.0 - baseline_acc)\n            centered_mean += centered_acc\n        chatcore_metric = centered_mean / len(results)\n        chatcore_metric_dict = {\"ChatCORE metric\": chatcore_metric}\n    get_report().log(section=\"Chat evaluation \" + args.source, data=[\n        vars(args), # CLI args\n        results,\n        chatcore_metric_dict,\n    ])\n\n    compute_cleanup()\n"
  },
  {
    "path": "scripts/chat_rl.py",
    "content": "\"\"\"\nReinforcement learning on GSM8K via \"GRPO\".\n\nI put GRPO in quotes because we actually end up with something a lot\nsimpler and more similar to just REINFORCE:\n\n1) Delete trust region, so there is no KL regularization to a reference model\n2) We are on policy, so there's no need for PPO ratio+clip.\n3) We use DAPO style normalization that is token-level, not sequence-level.\n4) Instead of z-score normalization (r - mu)/sigma, only use (r - mu) as the advantage.\n\n1 GPU:\npython -m scripts.chat_rl\n\n8 GPUs:\ntorchrun --standalone --nproc_per_node=8 -m scripts.chat_rl -- --run=default\n\"\"\"\n\nimport argparse\nimport os\nimport itertools\nimport wandb\nimport torch\nimport torch.distributed as dist\nfrom nanochat.common import compute_init, compute_cleanup, print0, get_base_dir, DummyWandb, autodetect_device_type\nfrom nanochat.checkpoint_manager import save_checkpoint, load_model\nfrom nanochat.engine import Engine\nfrom tasks.gsm8k import GSM8K\n\n# -----------------------------------------------------------------------------\n# CLI arguments\nparser = argparse.ArgumentParser(description=\"Reinforcement learning on GSM8K\")\n# Logging\nparser.add_argument(\"--run\", type=str, default=\"dummy\", help=\"wandb run name ('dummy' disables wandb logging)\")\n# Runtime\nparser.add_argument(\"--device-type\", type=str, default=\"\", help=\"cuda|cpu|mps (empty = autodetect)\")\n# Model loading\nparser.add_argument(\"--model-tag\", type=str, default=None, help=\"model tag to load from\")\nparser.add_argument(\"--model-step\", type=int, default=None, help=\"model step to load from\")\n# Training horizon\nparser.add_argument(\"--num-epochs\", type=int, default=1, help=\"number of epochs over GSM8K\")\n# Batch sizes / sampling\nparser.add_argument(\"--device-batch-size\", type=int, default=8, help=\"max batch size per forward pass\")\nparser.add_argument(\"--examples-per-step\", type=int, default=16, help=\"total examples per optimization step across all ranks\")\nparser.add_argument(\"--num-samples\", type=int, default=16, help=\"number of samples per example/question\")\n# Generation\nparser.add_argument(\"--max-new-tokens\", type=int, default=256, help=\"max tokens to generate per sample\")\nparser.add_argument(\"--temperature\", type=float, default=1.0, help=\"sampling temperature\")\nparser.add_argument(\"--top-k\", type=int, default=50, help=\"top-k sampling (0 = disabled)\")\n# Optimization\nparser.add_argument(\"--embedding-lr\", type=float, default=0.2, help=\"learning rate for embedding parameters (Adam)\")\nparser.add_argument(\"--unembedding-lr\", type=float, default=0.004, help=\"learning rate for unembedding parameters (Adam)\")\nparser.add_argument(\"--matrix-lr\", type=float, default=0.02, help=\"learning rate for matrix parameters (Muon)\")\nparser.add_argument(\"--weight-decay\", type=float, default=0.0, help=\"weight decay for embedding/unembedding parameters (Adam)\")\nparser.add_argument(\"--init-lr-frac\", type=float, default=0.05, help=\"initial LR as fraction of base LR\")\n# Evaluation / checkpointing\nparser.add_argument(\"--eval-every\", type=int, default=60, help=\"evaluate pass@k every N steps\")\nparser.add_argument(\"--eval-examples\", type=int, default=400, help=\"number of examples for pass@k evaluation\")\nparser.add_argument(\"--save-every\", type=int, default=60, help=\"save checkpoint every N steps\")\nargs = parser.parse_args()\nuser_config = vars(args).copy()\n# -----------------------------------------------------------------------------\n\n# Init compute/precision\ndevice_type = autodetect_device_type() if args.device_type == \"\" else args.device_type\nddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\nmaster_process = ddp_rank == 0 # this process will do logging, checkpointing etc.\n\n# wandb logging init\nuse_dummy_wandb = args.run == \"dummy\" or not master_process\nwandb_run = DummyWandb() if use_dummy_wandb else wandb.init(project=\"nanochat-rl\", name=args.run, config=user_config)\n\n# Init model and tokenizer\nmodel, tokenizer, meta = load_model(\"sft\", device, phase=\"eval\", model_tag=args.model_tag, step=args.model_step)\nengine = Engine(model, tokenizer) # for sampling rollouts\n\n# -----------------------------------------------------------------------------\n# Rollout / sampling generator loop that yields batches of examples for training\n\ntrain_task = GSM8K(subset=\"main\", split=\"train\")\nval_task = GSM8K(subset=\"main\", split=\"test\")\nnum_steps = (len(train_task) // args.examples_per_step) * args.num_epochs\nprint0(f\"Calculated number of steps: {num_steps}\")\n\n@torch.no_grad()\ndef get_batch():\n    assistant_end = tokenizer.encode_special(\"<|assistant_end|>\") # ok to use this token, it's only for padding and isn't used in the loss.\n    rank_indices = range(ddp_rank, len(train_task), ddp_world_size) # each rank is responsible for different examples in the training data\n    for example_idx in itertools.cycle(rank_indices):\n\n        # First get the full conversation of both user and assistant messages\n        conversation = train_task[example_idx]\n\n        # Tokenize the conversation, deleting the last Assistant message and priming the Assistant for a completion instead\n        # (i.e. keep the <|assistant_start|>, but delete everything after it)\n        tokens = tokenizer.render_for_completion(conversation)\n        prefix_length = len(tokens)\n\n        # Generate num_samples samples using batched generation, use loop to avoid OOMs\n        model.eval() # ensure the model is in eval mode\n        generated_token_sequences = []\n        masks = []\n        num_sampling_steps = args.num_samples // args.device_batch_size # go sequentially to prevent OOMs\n        for sampling_step in range(num_sampling_steps):\n            seed = hash((step, example_idx, sampling_step)) & 0x7FFFFFFF # positive half of int32\n            generated_token_sequences_batch, masks_batch = engine.generate_batch(\n                tokens,\n                num_samples=args.device_batch_size,\n                max_tokens=args.max_new_tokens,\n                temperature=args.temperature,\n                top_k=args.top_k,\n                seed=seed, # must make sure to change the seed for each sampling step\n            )\n            generated_token_sequences.extend(generated_token_sequences_batch)\n            masks.extend(masks_batch)\n\n        # Calculate the rewards for each sample\n        rewards = []\n        for sample_tokens in generated_token_sequences:\n            # Get just the generated tokens (after the prompt)\n            generated_tokens = sample_tokens[prefix_length:]\n            # Decode the generated response\n            generated_text = tokenizer.decode(generated_tokens)\n            # Calculate the reward\n            reward = train_task.reward(conversation, generated_text)\n            rewards.append(reward)\n\n        # Pad the sequences so that their lengths (in time) match\n        max_length = max(len(seq) for seq in generated_token_sequences)\n        padded_generated_token_sequences = [seq + [assistant_end] * (max_length - len(seq)) for seq in generated_token_sequences]\n        padded_masks = [mask + [0] * (max_length - len(mask)) for mask in masks]\n        # Stack up the sequences and masks into PyTorch tensors\n        ids = torch.tensor(padded_generated_token_sequences, dtype=torch.long, device=device)\n        mask_ids = torch.tensor(padded_masks, dtype=torch.long, device=device)\n        # Generate autoregressive inputs and targets to the Transformer\n        inputs = ids[:, :-1]\n        targets = ids[:, 1:].clone() # clone to avoid in-place modification:\n        targets[mask_ids[:, 1:] == 0] = -1 # <-- inplace modification right here. -1 is the ignore index\n        # NOTE also that the Engine returns mask=0 for BOTH the prompt tokens AND the tool use tokens.\n        # So we will (correctly) end up not training on the prompt tokens, or the tool use forced tokens.\n        rewards = torch.tensor(rewards, dtype=torch.float, device=device)\n        # Calculate the advantages by simply subtracting the mean (instead of z-score (x-mu)/sigma)\n        mu = rewards.mean()\n        advantages = rewards - mu\n        # yield inputs/targets as (B, T) of ids and rewards as (B,) of floats\n        yield generated_token_sequences, inputs, targets, rewards, advantages\n\n# -----------------------------------------------------------------------------\n# Simple evaluation loop for GSM8K pass@k\ndef run_gsm8k_eval(task, tokenizer, engine,\n    max_examples=None,\n    num_samples=1,\n    max_completion_tokens=256,\n    temperature=0.0,\n    top_k=50\n):\n    \"\"\"\n    Evaluates GSM8K task and returns a list of records of evaluation outcomes.\n    In a distributed setting, all ranks cooperate but this function will NOT\n    do the reduction across ranks. This is the responsibility of the caller.\n    Because the evaluation can take a while, this function will yield records one by one.\n    \"\"\"\n    max_examples = min(max_examples, len(task)) if max_examples is not None else len(task)\n    for idx in range(ddp_rank, max_examples, ddp_world_size):\n        conversation = task[idx]\n        tokens = tokenizer.render_for_completion(conversation)\n        prefix_length = len(tokens)\n        # Generate k samples using batched generation inside the Engine\n        assert num_samples <= args.device_batch_size # usually this is true. we can add a loop if not...\n        generated_token_sequences, masks = engine.generate_batch(\n            tokens,\n            num_samples=num_samples,\n            max_tokens=max_completion_tokens,\n            temperature=temperature,\n            top_k=top_k\n        )\n        # Check each sample for correctness\n        outcomes = []\n        for sample_tokens in generated_token_sequences:\n            generated_tokens = sample_tokens[prefix_length:]\n            generated_text = tokenizer.decode(generated_tokens)\n            is_correct = task.evaluate(conversation, generated_text)\n            outcomes.append({\n                \"is_correct\": is_correct\n            })\n        # A bit bloated because I wanted to do more complex logging at one point.\n        record = {\n            \"idx\": idx,\n            \"outcomes\": outcomes,\n        }\n        yield record\n\n# -----------------------------------------------------------------------------\n# Training loop\n\n# Init the optimizer\noptimizer = model.setup_optimizer(\n    unembedding_lr=args.unembedding_lr,\n    embedding_lr=args.embedding_lr,\n    matrix_lr=args.matrix_lr,\n    weight_decay=args.weight_decay,\n)\n\n# Set the initial learning rate as a fraction of the base learning rate\nfor group in optimizer.param_groups:\n    group[\"lr\"] = group[\"lr\"] * args.init_lr_frac\n    group[\"initial_lr\"] = group[\"lr\"]\n\n# Learning rate scheduler: simple rampdown to zero over num_steps\ndef get_lr_multiplier(it):\n    lrm = 1.0 - it / num_steps\n    return lrm\n\n# Calculate the number of examples each rank handles to achieve the desired examples_per_step\nprint0(f\"Total sequences per step: {args.examples_per_step * args.num_samples}\") # total batch size in sequences/step\nassert args.examples_per_step % ddp_world_size == 0, \"Desired examples per step must be divisible by the number of ranks\"\nexamples_per_rank = args.examples_per_step // ddp_world_size # per GPU\nprint0(f\"Calculated examples per rank: {examples_per_rank}\")\n\n# Kick off the training loop\nbatch_iterator = get_batch()\nfor step in range(num_steps):\n\n    # Evaluate the model once in a while and log to wandb\n    if step % args.eval_every == 0:\n        model.eval()\n        passk = torch.zeros(args.device_batch_size, device=device) # pass@k for k=1..device_batch_size\n        records_iter = run_gsm8k_eval(val_task, tokenizer, engine, num_samples=args.device_batch_size, max_examples=args.eval_examples, temperature=1.0)\n        records = list(records_iter) # collect all records\n        for k in range(1, args.device_batch_size + 1):\n            passk[k - 1] = sum(any(o[\"is_correct\"] for o in r[\"outcomes\"][:k]) for r in records)\n        num_records = torch.tensor(len(records), dtype=torch.long, device=device)\n        if ddp:\n            dist.all_reduce(num_records, op=dist.ReduceOp.SUM)\n            dist.all_reduce(passk, op=dist.ReduceOp.SUM)\n        passk = passk / num_records.item() # normalize by the total number of records\n        print_passk = [f\"Pass@{k}: {passk[k - 1].item():.4f}\" for k in range(1, args.device_batch_size + 1)]\n        print0(f\"Step {step} | {', '.join(print_passk)}\")\n        log_passk = {f\"pass@{k}\": passk[k - 1].item() for k in range(1, args.device_batch_size + 1)}\n        wandb_run.log({\n            \"step\": step,\n            **log_passk,\n        })\n\n    # Forward/Backward on rollouts over multiple examples in the dataset\n    rewards_list = []\n    sequence_lengths = []\n    for example_step in range(examples_per_rank):\n        # Get one batch corresponding to one example in the training dataset\n        sequences_all, inputs_all, targets_all, rewards_all, advantages_all = next(batch_iterator)\n        # Evaluate the loss and gradients\n        model.train() # ensure the model is in train mode\n        # We need one more loop because we can never exceed the device_batch_size\n        assert inputs_all.size(0) % args.device_batch_size == 0\n        num_passes = inputs_all.size(0) // args.device_batch_size\n        for pass_idx in range(num_passes):\n            # Pluck out the batch for this pass\n            b0, b1 = pass_idx * args.device_batch_size, (pass_idx + 1) * args.device_batch_size\n            inputs = inputs_all[b0:b1]\n            targets = targets_all[b0:b1]\n            rewards = rewards_all[b0:b1]\n            advantages = advantages_all[b0:b1]\n            # Calculate log probabilities. Note that the loss calculates NLL = -logp, so we negate\n            logp = -model(inputs, targets, loss_reduction='none').view_as(inputs) # (B, T)\n            # Calculate the PG objective. Note that ignore_index=-1 ensures that invalid tokens have loss 0.\n            pg_obj = (logp * advantages.unsqueeze(-1)).sum()\n            # normalize by the number of valid tokens, number of passes, and examples_per_rank\n            num_valid = (targets >= 0).sum().clamp(min=1)\n            pg_obj = pg_obj / (num_valid * num_passes * examples_per_rank)\n            # Note, there is no need to add PPO ratio+clip because we are on policy\n            # Finally, formulate the loss that we want to minimize (instead of objective we wish to maximize)\n            loss = -pg_obj\n            loss.backward()\n            print0(f\"Step {step}/{num_steps} | Example step {example_step} | Pass {pass_idx} | loss: {loss.item():.6f} | Average reward: {rewards.mean().item()}\")\n        # For logging\n        rewards_list.append(rewards_all.mean().item())\n        sequence_lengths.extend(len(seq) for seq in sequences_all)\n\n    # A bunch of logging for how the rollouts went this step\n    mean_reward = sum(rewards_list) / len(rewards_list)\n    mean_sequence_length = sum(sequence_lengths) / len(sequence_lengths)\n    if ddp: # aggregate across ranks\n        mean_reward_tensor = torch.tensor(mean_reward, dtype=torch.float, device=device)\n        mean_sequence_length_tensor = torch.tensor(mean_sequence_length, dtype=torch.float, device=device)\n        dist.all_reduce(mean_reward_tensor, op=dist.ReduceOp.AVG)\n        dist.all_reduce(mean_sequence_length_tensor, op=dist.ReduceOp.AVG)\n        mean_reward = mean_reward_tensor.item()\n        mean_sequence_length = mean_sequence_length_tensor.item()\n    print0(f\"Step {step}/{num_steps} | Average reward: {mean_reward} | Average sequence length: {mean_sequence_length:.2f}\")\n    wandb_run.log({\n        \"step\": step,\n        \"reward\": mean_reward,\n        \"sequence_length\": mean_sequence_length,\n    })\n\n    # Update the model parameters\n    lrm = get_lr_multiplier(step)\n    for group in optimizer.param_groups:\n        group[\"lr\"] = group[\"initial_lr\"] * lrm\n    optimizer.step()\n    model.zero_grad(set_to_none=True)\n    wandb_run.log({\n        \"step\": step,\n        \"lrm\": lrm,\n    })\n\n    # Master process saves the model once in a while. Skip first step. Save last step.\n    if master_process and ((step > 0 and step % args.save_every == 0) or step == num_steps - 1):\n        base_dir = get_base_dir()\n        depth = model.config.n_layer\n        output_dirname = args.model_tag if args.model_tag else f\"d{depth}\" # base the model tag on the depth of the base model\n        checkpoint_dir = os.path.join(base_dir, \"chatrl_checkpoints\", output_dirname)\n        model_config_kwargs = model.config.__dict__ # slightly naughty, abusing the simplicity of GPTConfig, TODO nicer\n        save_checkpoint(\n            checkpoint_dir,\n            step,\n            model.state_dict(),\n            None, # note: we don't bother to save the optimizer state\n            {\n                \"model_config\": model_config_kwargs,\n            }\n        )\n        print(f\"✅ Saved model checkpoint to {checkpoint_dir}\")\n\n# Log to report\nfrom nanochat.report import get_report\nget_report().log(section=\"Chat RL\", data=[\n    user_config, # CLI args\n])\n\nwandb_run.finish() # wandb run finish\ncompute_cleanup()\n"
  },
  {
    "path": "scripts/chat_sft.py",
    "content": "\"\"\"\nSupervised fine-tuning (SFT) the model.\nRun as:\n\npython -m scripts.chat_sft\n\nOr torchrun for training:\n\ntorchrun --standalone --nproc_per_node=8 -m scripts.chat_sft -- --device-batch-size=16\n\"\"\"\n\nimport gc\nimport argparse\nimport os\nos.environ[\"PYTORCH_ALLOC_CONF\"] = \"expandable_segments:True\"\nimport time\nimport wandb\nimport torch\nfrom nanochat.common import compute_init, compute_cleanup, print0, DummyWandb, get_base_dir, autodetect_device_type, get_peak_flops, COMPUTE_DTYPE, COMPUTE_DTYPE_REASON, is_ddp_initialized\nfrom nanochat.tokenizer import get_token_bytes\nfrom nanochat.checkpoint_manager import save_checkpoint, load_model, load_optimizer_state\nfrom nanochat.loss_eval import evaluate_bpb\nimport torch.distributed as dist\nfrom nanochat.flash_attention import HAS_FA3\nfrom nanochat.engine import Engine\nfrom scripts.chat_eval import run_chat_eval\n\nfrom tasks.common import TaskMixture\nfrom tasks.gsm8k import GSM8K\nfrom tasks.mmlu import MMLU\nfrom tasks.smoltalk import SmolTalk\nfrom tasks.customjson import CustomJSON\nfrom tasks.spellingbee import SimpleSpelling, SpellingBee\n\n# -----------------------------------------------------------------------------\n# CLI arguments\nparser = argparse.ArgumentParser(description=\"Supervised fine-tuning (SFT) the model\")\n# Logging\nparser.add_argument(\"--run\", type=str, default=\"dummy\", help=\"wandb run name ('dummy' disables wandb logging)\")\n# Runtime\nparser.add_argument(\"--device-type\", type=str, default=\"\", help=\"cuda|cpu|mps (empty = autodetect)\")\n# Model loading\nparser.add_argument(\"--model-tag\", type=str, default=None, help=\"model tag to load from\")\nparser.add_argument(\"--model-step\", type=int, default=None, help=\"model step to load from\")\nparser.add_argument(\"--load-optimizer\", type=int, default=1, help=\"warm-start optimizer from pretrained checkpoint (0=no, 1=yes)\")\n# Training horizon\nparser.add_argument(\"--num-iterations\", type=int, default=-1, help=\"number of optimization steps (-1 = full epoch)\")\n# Batch sizes (default: inherit from pretrained checkpoint)\nparser.add_argument(\"--max-seq-len\", type=int, default=None, help=\"max context length (default: inherit from pretrain)\")\nparser.add_argument(\"--device-batch-size\", type=int, default=None, help=\"per-device batch size (default: inherit from pretrain)\")\nparser.add_argument(\"--total-batch-size\", type=int, default=None, help=\"total batch size in tokens (default: inherit from pretrain)\")\n# Optimization (default: inherit from pretrained checkpoint)\nparser.add_argument(\"--embedding-lr\", type=float, default=None, help=\"learning rate for embedding parameters (Adam) (default: inherit from pretrain)\")\nparser.add_argument(\"--unembedding-lr\", type=float, default=None, help=\"learning rate for unembedding parameters (Adam) (default: inherit from pretrain)\")\nparser.add_argument(\"--matrix-lr\", type=float, default=None, help=\"learning rate for matrix parameters (Muon) (default: inherit from pretrain)\")\nparser.add_argument(\"--init-lr-frac\", type=float, default=0.8, help=\"initial LR as fraction of base LR\")\nparser.add_argument(\"--warmup-ratio\", type=float, default=0.0, help=\"ratio of iterations for LR warmup\")\nparser.add_argument(\"--warmdown-ratio\", type=float, default=0.5, help=\"ratio of iterations for LR warmdown\")\nparser.add_argument(\"--final-lr-frac\", type=float, default=0.0, help=\"final LR as fraction of initial LR\")\n# Evaluation\nparser.add_argument(\"--eval-every\", type=int, default=200, help=\"evaluate val bpb every N steps (-1 = disable)\")\nparser.add_argument(\"--eval-tokens\", type=int, default=40*524288, help=\"number of tokens to evaluate val loss on\")\nparser.add_argument(\"--chatcore-every\", type=int, default=200, help=\"evaluate ChatCORE metric every N steps (-1 = disable)\")\nparser.add_argument(\"--chatcore-max-cat\", type=int, default=-1, help=\"max problems per categorical task for ChatCORE\")\nparser.add_argument(\"--chatcore-max-sample\", type=int, default=24, help=\"max problems per generative task for ChatCORE\")\n# Data mixture\nparser.add_argument(\"--mmlu-epochs\", type=int, default=3, help=\"number of epochs of MMLU in training mixture (teaches Multiple Choice)\")\nparser.add_argument(\"--gsm8k-epochs\", type=int, default=4, help=\"number of epochs of GSM8K in training mixture (teaches Math and Tool Use)\")\nargs = parser.parse_args()\nuser_config = vars(args).copy()\n# -----------------------------------------------------------------------------\n\n# Compute init\ndevice_type = autodetect_device_type() if args.device_type == \"\" else args.device_type\nddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\nmaster_process = ddp_rank == 0\nprint0(f\"COMPUTE_DTYPE: {COMPUTE_DTYPE} ({COMPUTE_DTYPE_REASON})\")\nsynchronize = torch.cuda.synchronize if device_type == \"cuda\" else lambda: None\nget_max_memory = torch.cuda.max_memory_allocated if device_type == \"cuda\" else lambda: 0\nif device_type == \"cuda\":\n    gpu_device_name = torch.cuda.get_device_name(0)\n    gpu_peak_flops = get_peak_flops(gpu_device_name)\n    print0(f\"GPU: {gpu_device_name} | Peak FLOPS (BF16): {gpu_peak_flops:.2e}\")\nelse:\n    gpu_peak_flops = float('inf')  # MFU not meaningful for CPU/MPS\n\n# wandb logging init\nuse_dummy_wandb = args.run == \"dummy\" or not master_process\nwandb_run = DummyWandb() if use_dummy_wandb else wandb.init(project=\"nanochat-sft\", name=args.run, config=user_config)\n\n# Flash Attention status\nif not HAS_FA3:\n    print0(\"WARNING: Flash Attention 3 not available, using PyTorch SDPA fallback. Training will be less efficient.\")\n\n# Load the model and tokenizer\nmodel, tokenizer, meta = load_model(\"base\", device, phase=\"train\", model_tag=args.model_tag, step=args.model_step)\n\n# Inherit training hyperparameters from pretrained checkpoint (None = inherit, explicit value = override)\npretrain_user_config = meta.get(\"user_config\", {})\nfor name, fallback, source in [\n    (\"max_seq_len\",       2048,  meta),\n    (\"device_batch_size\", 32,    meta),\n    (\"total_batch_size\",  524288, meta),\n    (\"embedding_lr\",      0.3,   pretrain_user_config),\n    (\"unembedding_lr\",    0.004, pretrain_user_config),\n    (\"matrix_lr\",         0.02,  pretrain_user_config),\n]:\n    arg_val = getattr(args, name)\n    pretrain_val = source.get(name)\n    if arg_val is None:\n        resolved = pretrain_val if pretrain_val is not None else fallback\n        setattr(args, name, resolved)\n        print0(f\"Inherited {name}={resolved} from pretrained checkpoint\")\n    elif pretrain_val is not None and arg_val != pretrain_val:\n        print0(f\"NOTE: --{name.replace('_', '-')}={arg_val} overrides pretrained value of {pretrain_val}\")\n    else:\n        print0(f\"Using {name}={arg_val}\")\n\norig_model = model\nmodel = torch.compile(model, dynamic=False)\ndepth = model.config.n_layer\nnum_flops_per_token = model.estimate_flops()\ntokens_per_fwdbwd = args.device_batch_size * args.max_seq_len # tokens per iteration for a single rank\nworld_tokens_per_fwdbwd = tokens_per_fwdbwd * ddp_world_size # total tokens per iteration for all ranks\nassert args.total_batch_size % world_tokens_per_fwdbwd == 0\ngrad_accum_steps = args.total_batch_size // world_tokens_per_fwdbwd\nprint0(f\"Tokens / micro-batch / rank: {args.device_batch_size} x {args.max_seq_len} = {tokens_per_fwdbwd:,}\")\nprint0(f\"Tokens / micro-batch: {world_tokens_per_fwdbwd:,}\")\nprint0(f\"Total batch size {args.total_batch_size:,} => gradient accumulation steps: {grad_accum_steps}\")\ntoken_bytes = get_token_bytes(device=device)\n\n# Initialize the Optimizer (combined MuonAdamW: Muon for matrix params, AdamW for rest)\n# Note that pretraining ramps weight_decay to zero by end of pretraining, so SFT continues with zero\noptimizer = model.setup_optimizer(unembedding_lr=args.unembedding_lr, embedding_lr=args.embedding_lr, matrix_lr=args.matrix_lr, weight_decay=0.0)\n\n# Optionally warm-start optimizer from pretrained checkpoint (momentum buffers etc.)\n# Note: load_state_dict overwrites param_group metadata (LRs, betas, etc.) with the\n# pretrained values. Since pretraining warmdown brings LRs to ~0, we must save and\n# restore our fresh SFT LRs after loading.\nbase_dir = get_base_dir()\nif args.load_optimizer:\n    optimizer_data = load_optimizer_state(\"base\", device, rank=ddp_rank, model_tag=args.model_tag, step=args.model_step)\n    if optimizer_data is not None:\n        base_lrs = [group[\"lr\"] for group in optimizer.param_groups]\n        optimizer.load_state_dict(optimizer_data)\n        del optimizer_data\n        for group, base_lr in zip(optimizer.param_groups, base_lrs):\n            group[\"lr\"] = base_lr\n        print0(\"Loaded optimizer state from pretrained checkpoint (momentum buffers only, LRs reset)\")\n    else:\n        print0(\"WARNING: optimizer checkpoint not found, starting with fresh optimizer (slightly worse)\")\n\n# GradScaler for fp16 training (bf16/fp32 don't need it)\nscaler = torch.amp.GradScaler() if COMPUTE_DTYPE == torch.float16 else None\nif scaler is not None:\n    print0(\"GradScaler enabled for fp16 training\")\n\n# Override the initial learning rate as a fraction of the base learning rate\nfor group in optimizer.param_groups:\n    group[\"lr\"] = group[\"lr\"] * args.init_lr_frac\n    group[\"initial_lr\"] = group[\"lr\"]\n\n# SFT data mixture and DataLoader\nidentity_conversations_filepath = os.path.join(base_dir, \"identity_conversations.jsonl\")\ntrain_tasks = [\n    SmolTalk(split=\"train\"), # 460K rows of general conversations\n    CustomJSON(filepath=identity_conversations_filepath), # 1000 rows of synthetic identity conversations\n    CustomJSON(filepath=identity_conversations_filepath), # 2 epochs of these\n    *[MMLU(subset=\"auxiliary_train\", split=\"train\") for _ in range(args.mmlu_epochs)], # 100K rows per epoch\n    *[GSM8K(subset=\"main\", split=\"train\") for _ in range(args.gsm8k_epochs)], # 8K rows per epoch\n    SimpleSpelling(size=200000, split=\"train\"), # 200K rows of Simple Spelling (e.g. spell the word 'apple')\n    SpellingBee(size=80000, split=\"train\"), # 80K rows of Spelling Bee (e.g. how many 'r' are in 'strawberry'?)\n]\ntrain_dataset = TaskMixture(train_tasks)\nprint0(f\"Training mixture: {len(train_dataset):,} rows (MMLU x{args.mmlu_epochs}, GSM8K x{args.gsm8k_epochs})\")\nval_dataset = TaskMixture([\n    SmolTalk(split=\"test\"), # 24K rows in test set\n    MMLU(subset=\"all\", split=\"test\", stop=5200), # 14K rows in test set, use only 5.2K to match the train ratios\n    GSM8K(subset=\"main\", split=\"test\", stop=420), # 1.32K rows in test set, use only 420 to match the train ratios\n]) # total: 24K + 14K + 1.32K ~= 39K rows\n# DataLoader is defined here, it emits inputs, targets : 2D tensors of shape (device_batch_size, max_seq_len)\n# A big problem is that we don't know the final num_iterations in advance. So we create\n# these two global variables and update them from within the data generator.\nlast_step = False # we will toggle this to True when we reach the end of the training dataset\napprox_progress = 0.0 # will go from 0 to 1 over the course of the epoch\ncurrent_epoch = 1 # track epoch for logging\ndef sft_data_generator_bos_bestfit(split, buffer_size=100):\n    \"\"\"\n    BOS-aligned dataloader for SFT with bestfit-pad packing.\n\n    Each row in the batch starts with BOS (beginning of a conversation).\n    Conversations are packed using best-fit algorithm. When no conversation fits,\n    the row is padded (instead of cropping) to ensure no tokens are ever discarded.\n    Padding positions have targets masked with -1 (ignore_index for cross-entropy).\n    \"\"\"\n    global last_step, approx_progress, current_epoch\n    assert split in {\"train\", \"val\"}, \"split must be 'train' or 'val'\"\n    dataset = train_dataset if split == \"train\" else val_dataset\n    dataset_size = len(dataset)\n    assert dataset_size > 0\n    row_capacity = args.max_seq_len + 1  # +1 for target at last position\n    bos_token = tokenizer.get_bos_token_id()\n\n    # Conversation buffer: list of (token_ids, loss_mask) tuples\n    conv_buffer = []\n    cursor = ddp_rank  # Each rank processes different conversations (for fetching)\n    consumed = ddp_rank  # Track actual consumption separately from buffering\n    epoch = 1\n    it = 0  # iteration counter\n\n    def refill_buffer():\n        nonlocal cursor, epoch\n        while len(conv_buffer) < buffer_size:\n            conversation = dataset[cursor]\n            ids, mask = tokenizer.render_conversation(conversation)\n            conv_buffer.append((ids, mask))\n            cursor += ddp_world_size\n            if cursor >= dataset_size:\n                cursor = cursor % dataset_size\n                epoch += 1\n                # Note: last_step is now triggered based on consumption, not fetching\n\n    while True:\n        rows = []\n        mask_rows = []\n        row_lengths = []  # Track actual content length (excluding padding) for each row\n        for _ in range(args.device_batch_size):\n            row = []\n            mask_row = []\n            padded = False\n            while len(row) < row_capacity:\n                # Ensure buffer has conversations\n                while len(conv_buffer) < buffer_size:\n                    refill_buffer()\n\n                remaining = row_capacity - len(row)\n\n                # Find largest conversation that fits entirely\n                best_idx = -1\n                best_len = 0\n                for i, (conv, _) in enumerate(conv_buffer):\n                    conv_len = len(conv)\n                    if conv_len <= remaining and conv_len > best_len:\n                        best_idx = i\n                        best_len = conv_len\n\n                if best_idx >= 0:\n                    # Found a conversation that fits - use it entirely\n                    conv, conv_mask = conv_buffer.pop(best_idx)\n                    row.extend(conv)\n                    mask_row.extend(conv_mask)\n                    consumed += ddp_world_size  # Track actual consumption\n                else:\n                    # No conversation fits - pad the remainder instead of cropping\n                    # This ensures we never discard any tokens\n                    content_len = len(row)\n                    row.extend([bos_token] * remaining)  # Pad with BOS tokens\n                    mask_row.extend([0] * remaining)\n                    padded = True\n                    break  # Row is now full (with padding)\n\n            # Track content length: full row if no padding, otherwise the length before padding\n            if padded:\n                row_lengths.append(content_len)\n            else:\n                row_lengths.append(row_capacity)\n            rows.append(row[:row_capacity])\n            mask_rows.append(mask_row[:row_capacity])\n\n        # Stopping condition to respect num_iterations, if given\n        it += 1\n        if 0 < args.num_iterations <= it and split == \"train\":\n            last_step = True\n\n        # Update progress tracking (based on consumed, not cursor, to account for buffering)\n        if split == \"train\":\n            current_epoch = epoch\n            if args.num_iterations > 0:\n                approx_progress = it / args.num_iterations\n            else:\n                approx_progress = consumed / dataset_size\n            # Trigger last_step when we've consumed enough (instead of when cursor wraps)\n            if consumed >= dataset_size:\n                last_step = True\n\n        # Build tensors\n        use_cuda = device_type == \"cuda\"\n        batch_tensor = torch.tensor(rows, dtype=torch.long, pin_memory=use_cuda)\n        inputs = batch_tensor[:, :-1].to(device=device, dtype=torch.int32, non_blocking=use_cuda).contiguous()\n        targets = batch_tensor[:, 1:].to(device=device, dtype=torch.int64, non_blocking=use_cuda).contiguous()\n\n        # Apply the loss mask from render_conversation (mask=1 for assistant completions,\n        # mask=0 for user prompts, BOS, special tokens, tool outputs). mask[1:] aligns\n        # with targets (shifted by 1). Unmasked positions get -1 (ignore_index).\n        mask_tensor = torch.tensor(mask_rows, dtype=torch.int8)\n        mask_targets = mask_tensor[:, 1:].to(device=device)\n        targets[mask_targets == 0] = -1\n\n        # Mask out padding positions in targets (set to -1 = ignore_index)\n        # For each row, positions >= (content_length - 1) in targets should be masked\n        for i, content_len in enumerate(row_lengths):\n            if content_len < row_capacity:\n                targets[i, content_len-1:] = -1\n\n        yield inputs, targets\n\ntrain_loader = sft_data_generator_bos_bestfit(\"train\")\nbuild_val_loader = lambda: sft_data_generator_bos_bestfit(\"val\")\nprogress = 0 # will go from 0 to 1 over the course of the epoch\n\n# Learning rate schedule (linear warmup, constant, linear warmdown)\n# Same shape as base_train but uses progress (0→1) instead of absolute step counts,\n# because SFT doesn't always know num_iterations in advance (dataset-driven stopping).\ndef get_lr_multiplier(progress):\n    if progress < args.warmup_ratio:\n        return (progress + 1e-8) / args.warmup_ratio\n    elif progress <= 1.0 - args.warmdown_ratio:\n        return 1.0\n    else:\n        decay = (progress - (1.0 - args.warmdown_ratio)) / args.warmdown_ratio\n        return (1 - decay) * 1.0 + decay * args.final_lr_frac\n\n# Momentum scheduler for Muon optimizer\ndef get_muon_momentum(it):\n    frac = min(it / 300, 1)\n    momentum = (1 - frac) * 0.85 + frac * 0.95\n    return momentum\n\n# -----------------------------------------------------------------------------\n# Training loop\nx, y = next(train_loader) # prefetch the very first batch of data\nmin_val_bpb = float(\"inf\")\nsmooth_train_loss = 0 # EMA of training loss\nema_beta = 0.9 # EMA decay factor\ntotal_training_time = 0 # total wall-clock time of training\nstep = 0\nwhile True:\n    flops_so_far = num_flops_per_token * args.total_batch_size * step\n\n    # Synchronize last_step across all ranks to avoid hangs in the distributed setting\n    if ddp:\n        last_step_tensor = torch.tensor(last_step, dtype=torch.int32, device=device)\n        dist.all_reduce(last_step_tensor, op=dist.ReduceOp.MAX)\n        last_step = bool(last_step_tensor.item())\n\n    # once in a while: evaluate the val bpb (all ranks participate)\n    if last_step or (args.eval_every > 0 and step % args.eval_every == 0):\n        model.eval()\n        val_loader = build_val_loader()\n        eval_steps = args.eval_tokens // (args.device_batch_size * args.max_seq_len * ddp_world_size)\n        val_bpb = evaluate_bpb(model, val_loader, eval_steps, token_bytes)\n        print0(f\"Step {step:05d} | Validation bpb: {val_bpb:.4f}\")\n        if val_bpb < min_val_bpb:\n            min_val_bpb = val_bpb\n        wandb_run.log({\n            \"step\": step,\n            \"total_training_flops\": flops_so_far,\n            \"total_training_time\": total_training_time,\n            \"val/bpb\": val_bpb,\n        })\n        model.train()\n\n    # once in a while: estimate the ChatCORE metric (all ranks participate)\n    # use the original uncompiled model because the inputs keep changing shape\n    chatcore_results = {}\n    if args.chatcore_every > 0 and (last_step or (step > 0 and step % args.chatcore_every == 0)):\n        model.eval()\n        engine = Engine(orig_model, tokenizer)\n        all_tasks = ['ARC-Easy', 'ARC-Challenge', 'MMLU', 'GSM8K', 'HumanEval', 'SpellingBee']\n        categorical_tasks = {'ARC-Easy', 'ARC-Challenge', 'MMLU'}\n        baseline_accuracies = {\n            'ARC-Easy': 0.25, 'ARC-Challenge': 0.25, 'MMLU': 0.25,\n            'GSM8K': 0.0, 'HumanEval': 0.0, 'SpellingBee': 0.0,\n        }\n        task_results = {}\n        for task_name in all_tasks:\n            limit = args.chatcore_max_cat if task_name in categorical_tasks else args.chatcore_max_sample\n            max_problems = None if limit < 0 else limit  # -1 means no limit\n            acc = run_chat_eval(task_name, orig_model, tokenizer, engine,\n                                batch_size=args.device_batch_size, max_problems=max_problems)\n            task_results[task_name] = acc\n            print0(f\"  {task_name}: {100*acc:.2f}%\")\n        # Compute ChatCORE metrics (mean centered accuracy, ranges from 0=random to 1=perfect)\n        def centered_mean(tasks):\n            return sum((task_results[t] - baseline_accuracies[t]) / (1.0 - baseline_accuracies[t]) for t in tasks) / len(tasks)\n        chatcore = centered_mean(all_tasks)\n        chatcore_cat = centered_mean(categorical_tasks)\n        print0(f\"Step {step:05d} | ChatCORE: {chatcore:.4f} | ChatCORE_cat: {chatcore_cat:.4f}\")\n        wandb_run.log({\n            \"step\": step,\n            \"total_training_flops\": flops_so_far,\n            \"chatcore_metric\": chatcore,\n            \"chatcore_cat\": chatcore_cat,\n            **{f\"chatcore/{task_name}\": acc for task_name, acc in task_results.items()},\n        })\n        model.train()\n\n    # save checkpoint at the end of the run (all ranks participate so each saves its optimizer shard)\n    if last_step:\n        output_dirname = args.model_tag if args.model_tag else f\"d{depth}\" # e.g. d12\n        checkpoint_dir = os.path.join(base_dir, \"chatsft_checkpoints\", output_dirname)\n        save_checkpoint(\n            checkpoint_dir,\n            step,\n            orig_model.state_dict(),\n            optimizer.state_dict(),\n            {\n                \"step\": step,\n                \"val_bpb\": val_bpb, # loss at last step\n                \"model_config\": {\n                    \"sequence_len\": args.max_seq_len,\n                    \"vocab_size\": tokenizer.get_vocab_size(),\n                    \"n_layer\": depth,\n                    \"n_head\": model.config.n_head,\n                    \"n_kv_head\": model.config.n_kv_head,\n                    \"n_embd\": model.config.n_embd,\n                    \"window_pattern\": model.config.window_pattern,\n                },\n                \"user_config\": user_config, # inputs to the training script\n            },\n            rank=ddp_rank,\n        )\n\n    if last_step:\n        break\n\n    # -------------------------------------------------------------------------\n    # single training step\n    # evaluate the gradient\n    synchronize()\n    t0 = time.time()\n    for micro_step in range(grad_accum_steps):\n        loss = model(x, y)\n        train_loss = loss.detach() # for logging\n        loss = loss / grad_accum_steps # each .backward() is a grad sum => normalize loss here\n        if scaler is not None:\n            scaler.scale(loss).backward()\n        else:\n            loss.backward()\n        x, y = next(train_loader) # prefetch the next batch while the GPU is busy with forward/backward\n        progress = max(progress, approx_progress) # only increase progress monotonically\n    # step the optimizer\n    lrm = get_lr_multiplier(progress)\n    muon_momentum = get_muon_momentum(step)\n    for group in optimizer.param_groups:\n        group[\"lr\"] = group[\"initial_lr\"] * lrm\n        if group['kind'] == 'muon':\n            group[\"momentum\"] = muon_momentum\n    if scaler is not None:\n        scaler.unscale_(optimizer)\n        if is_ddp_initialized():\n            for v in scaler._found_inf_per_device(optimizer).values():\n                dist.all_reduce(v, op=dist.ReduceOp.MAX)\n        scaler.step(optimizer)\n        scaler.update()\n    else:\n        optimizer.step()\n    model.zero_grad(set_to_none=True)\n    synchronize()\n    t1 = time.time()\n    dt = t1 - t0\n    # -------------------------------------------------------------------------\n\n    # State\n    step += 1\n\n    # logging\n    smooth_train_loss = ema_beta * smooth_train_loss + (1 - ema_beta) * train_loss.item() # EMA the training loss\n    debiased_smooth_loss = smooth_train_loss / (1 - ema_beta**(step + 1)) # debias the EMA\n    pct_done = 100 * progress\n    tok_per_sec = int(args.total_batch_size / dt)\n    flops_per_sec = num_flops_per_token * args.total_batch_size / dt\n    mfu = 100 * flops_per_sec / (gpu_peak_flops * ddp_world_size)\n    if step > 10:\n        total_training_time += dt # only count the time after the first 10 steps\n    print0(f\"step {step:05d} ({pct_done:.2f}%) | loss: {debiased_smooth_loss:.6f} | lrm: {lrm:.2f} | dt: {dt * 1000:.2f}ms | tok/sec: {tok_per_sec:,} | mfu: {mfu:.2f} | epoch: {current_epoch} | total time: {total_training_time/60:.2f}m\")\n    if step % 10 == 0:\n        wandb_run.log({\n            \"step\": step,\n            \"total_training_flops\": flops_so_far,\n            \"total_training_time\": total_training_time,\n            \"train/loss\": debiased_smooth_loss,\n            \"train/lrm\": lrm,\n            \"train/dt\": dt,\n            \"train/tok_per_sec\": tok_per_sec,\n            \"train/mfu\": mfu,\n            \"train/epoch\": current_epoch,\n        })\n\n    # The garbage collector spends ~500ms scanning for cycles quite frequently.\n    # We manually manage it to avoid these pauses during training.\n    if step == 1:\n        gc.collect() # manually collect a lot of garbage from setup\n        gc.freeze() # freeze all currently surviving objects and exclude them from GC\n        gc.disable() # disable GC entirely except:\n    elif step % 5000 == 0: # every 5000 steps...\n        gc.collect() # manually collect, just to be safe for very long runs\n\n# print a few more stats\nprint0(f\"Peak memory usage: {get_max_memory() / 1024 / 1024:.2f}MiB\")\nprint0(f\"Total training time: {total_training_time/60:.2f}m\")\nprint0(f\"Minimum validation bpb: {min_val_bpb:.4f}\")\n\n# Log to report\nfrom nanochat.report import get_report\nget_report().log(section=\"SFT\", data=[\n    user_config, # CLI args\n    { # stats about the training setup\n        \"Number of iterations\": step,\n        \"DDP world size\": ddp_world_size,\n    },\n    { # stats about training outcomes\n        \"Minimum validation bpb\": min_val_bpb,\n    }\n])\n\n# cleanup\nwandb_run.finish() # wandb run finish\ncompute_cleanup()\n"
  },
  {
    "path": "scripts/chat_web.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nUnified web chat server - serves both UI and API from a single FastAPI instance.\n\nUses data parallelism to distribute requests across multiple GPUs. Each GPU loads\na full copy of the model, and incoming requests are distributed to available workers.\n\nLaunch examples:\n\n- single available GPU (default)\npython -m scripts.chat_web\n\n- 4 GPUs\npython -m scripts.chat_web --num-gpus 4\n\nTo chat, open the URL printed in the console. (If on cloud box, make sure to use public IP)\n\nEndpoints:\n  GET  /           - Chat UI\n  POST /chat/completions - Chat API (streaming only)\n  GET  /health     - Health check with worker pool status\n  GET  /stats      - Worker pool statistics and GPU utilization\n\nAbuse Prevention:\n  - Maximum 500 messages per request\n  - Maximum 8000 characters per message\n  - Maximum 32000 characters total conversation length\n  - Temperature clamped to 0.0-2.0\n  - Top-k clamped to 0-200 (0 disables top-k filtering, using full vocabulary)\n  - Max tokens clamped to 1-4096\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport torch\nimport asyncio\nimport logging\nimport random\nfrom contextlib import asynccontextmanager\nfrom fastapi import FastAPI, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.responses import StreamingResponse, HTMLResponse, FileResponse\nfrom pydantic import BaseModel\nfrom typing import List, Optional, AsyncGenerator\nfrom dataclasses import dataclass\nfrom nanochat.common import compute_init, autodetect_device_type\nfrom nanochat.checkpoint_manager import load_model\nfrom nanochat.engine import Engine\n\n# Abuse prevention limits\nMAX_MESSAGES_PER_REQUEST = 500\nMAX_MESSAGE_LENGTH = 8000\nMAX_TOTAL_CONVERSATION_LENGTH = 32000\nMIN_TEMPERATURE = 0.0\nMAX_TEMPERATURE = 2.0\nMIN_TOP_K = 0 # 0 disables top-k filtering, using full vocabulary\nMAX_TOP_K = 200\nMIN_MAX_TOKENS = 1\nMAX_MAX_TOKENS = 4096\n\nparser = argparse.ArgumentParser(description='NanoChat Web Server')\nparser.add_argument('-n', '--num-gpus', type=int, default=1, help='Number of GPUs to use (default: 1)')\nparser.add_argument('-i', '--source', type=str, default=\"sft\", help=\"Source of the model: sft|rl\")\nparser.add_argument('-t', '--temperature', type=float, default=0.8, help='Default temperature for generation')\nparser.add_argument('-k', '--top-k', type=int, default=50, help='Default top-k sampling parameter')\nparser.add_argument('-m', '--max-tokens', type=int, default=512, help='Default max tokens for generation')\nparser.add_argument('-g', '--model-tag', type=str, default=None, help='Model tag to load')\nparser.add_argument('-s', '--step', type=int, default=None, help='Step to load')\nparser.add_argument('-p', '--port', type=int, default=8000, help='Port to run the server on')\nparser.add_argument('--device-type', type=str, default='', choices=['cuda', 'cpu', 'mps'], help='Device type for evaluation: cuda|cpu|mps. empty => autodetect')\nparser.add_argument('--host', type=str, default='0.0.0.0', help='Host to bind the server to')\nargs = parser.parse_args()\n\n# Configure logging for conversation traffic\nlogging.basicConfig(\n    level=logging.INFO,\n    format='%(asctime)s - %(message)s',\n    datefmt='%Y-%m-%d %H:%M:%S'\n)\nlogger = logging.getLogger(__name__)\n\ndevice_type = autodetect_device_type() if args.device_type == \"\" else args.device_type\nddp, ddp_rank, ddp_local_rank, ddp_world_size, device = compute_init(device_type)\n\n@dataclass\nclass Worker:\n    \"\"\"A worker with a model loaded on a specific GPU.\"\"\"\n    gpu_id: int\n    device: torch.device\n    engine: Engine\n    tokenizer: object\n\nclass WorkerPool:\n    \"\"\"Pool of workers, each with a model replica on a different GPU.\"\"\"\n\n    def __init__(self, num_gpus: Optional[int] = None):\n        if num_gpus is None:\n            if device_type == \"cuda\":\n                num_gpus = torch.cuda.device_count()\n            else:\n                num_gpus = 1 # e.g. cpu|mps\n        self.num_gpus = num_gpus\n        self.workers: List[Worker] = []\n        self.available_workers: asyncio.Queue = asyncio.Queue()\n\n    async def initialize(self, source: str, model_tag: Optional[str] = None, step: Optional[int] = None):\n        \"\"\"Load model on each GPU.\"\"\"\n        print(f\"Initializing worker pool with {self.num_gpus} GPUs...\")\n        if self.num_gpus > 1:\n            assert device_type == \"cuda\", \"Only CUDA supports multiple workers/GPUs. cpu|mps does not.\"\n\n        for gpu_id in range(self.num_gpus):\n\n            if device_type == \"cuda\":\n                device = torch.device(f\"cuda:{gpu_id}\")\n                print(f\"Loading model on GPU {gpu_id}...\")\n            else:\n                device = torch.device(device_type) # e.g. cpu|mps\n                print(f\"Loading model on {device_type}...\")\n\n            model, tokenizer, _ = load_model(source, device, phase=\"eval\", model_tag=model_tag, step=step)\n            engine = Engine(model, tokenizer)\n            worker = Worker(\n                gpu_id=gpu_id,\n                device=device,\n                engine=engine,\n                tokenizer=tokenizer,\n            )\n            self.workers.append(worker)\n            await self.available_workers.put(worker)\n\n        print(f\"All {self.num_gpus} workers initialized!\")\n\n    async def acquire_worker(self) -> Worker:\n        \"\"\"Get an available worker from the pool.\"\"\"\n        return await self.available_workers.get()\n\n    async def release_worker(self, worker: Worker):\n        \"\"\"Return a worker to the pool.\"\"\"\n        await self.available_workers.put(worker)\n\nclass ChatMessage(BaseModel):\n    role: str\n    content: str\n\nclass ChatRequest(BaseModel):\n    messages: List[ChatMessage]\n    temperature: Optional[float] = None\n    max_tokens: Optional[int] = None\n    top_k: Optional[int] = None\n\ndef validate_chat_request(request: ChatRequest):\n    \"\"\"Validate chat request to prevent abuse.\"\"\"\n    # Check number of messages\n    if len(request.messages) == 0:\n        raise HTTPException(status_code=400, detail=\"At least one message is required\")\n    if len(request.messages) > MAX_MESSAGES_PER_REQUEST:\n        raise HTTPException(\n            status_code=400,\n            detail=f\"Too many messages. Maximum {MAX_MESSAGES_PER_REQUEST} messages allowed per request\"\n        )\n\n    # Check individual message lengths and total conversation length\n    total_length = 0\n    for i, message in enumerate(request.messages):\n        if not message.content:\n            raise HTTPException(status_code=400, detail=f\"Message {i} has empty content\")\n\n        msg_length = len(message.content)\n        if msg_length > MAX_MESSAGE_LENGTH:\n            raise HTTPException(\n                status_code=400,\n                detail=f\"Message {i} is too long. Maximum {MAX_MESSAGE_LENGTH} characters allowed per message\"\n            )\n        total_length += msg_length\n\n    if total_length > MAX_TOTAL_CONVERSATION_LENGTH:\n        raise HTTPException(\n            status_code=400,\n            detail=f\"Total conversation is too long. Maximum {MAX_TOTAL_CONVERSATION_LENGTH} characters allowed\"\n        )\n\n    # Validate role values\n    for i, message in enumerate(request.messages):\n        if message.role not in [\"user\", \"assistant\"]:\n            raise HTTPException(\n                status_code=400,\n                detail=f\"Message {i} has invalid role. Must be 'user', 'assistant', or 'system'\"\n            )\n\n    # Validate temperature\n    if request.temperature is not None:\n        if not (MIN_TEMPERATURE <= request.temperature <= MAX_TEMPERATURE):\n            raise HTTPException(\n                status_code=400,\n                detail=f\"Temperature must be between {MIN_TEMPERATURE} and {MAX_TEMPERATURE}\"\n            )\n\n    # Validate top_k\n    if request.top_k is not None:\n        if not (MIN_TOP_K <= request.top_k <= MAX_TOP_K):\n            raise HTTPException(\n                status_code=400,\n                detail=f\"top_k must be between {MIN_TOP_K} and {MAX_TOP_K}\"\n            )\n\n    # Validate max_tokens\n    if request.max_tokens is not None:\n        if not (MIN_MAX_TOKENS <= request.max_tokens <= MAX_MAX_TOKENS):\n            raise HTTPException(\n                status_code=400,\n                detail=f\"max_tokens must be between {MIN_MAX_TOKENS} and {MAX_MAX_TOKENS}\"\n            )\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    \"\"\"Load models on all GPUs on startup.\"\"\"\n    print(\"Loading nanochat models across GPUs...\")\n    app.state.worker_pool = WorkerPool(num_gpus=args.num_gpus)\n    await app.state.worker_pool.initialize(args.source, model_tag=args.model_tag, step=args.step)\n    print(f\"Server ready at http://localhost:{args.port}\")\n    yield\n\napp = FastAPI(lifespan=lifespan)\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"*\"],\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\n@app.get(\"/\")\nasync def root():\n    \"\"\"Serve the chat UI.\"\"\"\n    ui_html_path = os.path.join(\"nanochat\", \"ui.html\")\n    with open(ui_html_path, \"r\", encoding=\"utf-8\") as f:\n        html_content = f.read()\n    # Replace the API_URL to use the same origin\n    html_content = html_content.replace(\n        \"const API_URL = `http://${window.location.hostname}:8000`;\",\n        \"const API_URL = '';\"\n    )\n    return HTMLResponse(content=html_content)\n\n\n@app.get(\"/logo.svg\")\nasync def logo():\n    \"\"\"Serve the NanoChat logo for favicon and header.\"\"\"\n    logo_path = os.path.join(\"nanochat\", \"logo.svg\")\n    return FileResponse(logo_path, media_type=\"image/svg+xml\")\n\nasync def generate_stream(\n    worker: Worker,\n    tokens,\n    temperature=None,\n    max_new_tokens=None,\n    top_k=None\n) -> AsyncGenerator[str, None]:\n    \"\"\"Generate assistant response with streaming.\"\"\"\n    temperature = temperature if temperature is not None else args.temperature\n    max_new_tokens = max_new_tokens if max_new_tokens is not None else args.max_tokens\n    top_k = top_k if top_k is not None else args.top_k\n\n    assistant_end = worker.tokenizer.encode_special(\"<|assistant_end|>\")\n    bos = worker.tokenizer.get_bos_token_id()\n\n    # Accumulate tokens to properly handle multi-byte UTF-8 characters (like emojis)\n    accumulated_tokens = []\n    # Track the last complete UTF-8 string (without replacement characters)\n    last_clean_text = \"\"\n\n    for token_column, token_masks in worker.engine.generate(\n        tokens,\n        num_samples=1,\n        max_tokens=max_new_tokens,\n        temperature=temperature,\n        top_k=top_k,\n        seed=random.randint(0, 2**31 - 1)\n    ):\n        token = token_column[0]\n\n        # Stopping criteria\n        if token == assistant_end or token == bos:\n            break\n\n        # Append the token to sequence\n        accumulated_tokens.append(token)\n        # Decode all accumulated tokens to get proper UTF-8 handling\n        # Note that decode is a quite efficient operation, basically table lookup and string concat\n        current_text = worker.tokenizer.decode(accumulated_tokens)\n        # Only emit text if it doesn't end with a replacement character\n        # This ensures we don't emit incomplete UTF-8 sequences\n        if not current_text.endswith('�'):\n            # Extract only the new text since last clean decode\n            new_text = current_text[len(last_clean_text):]\n            if new_text:  # Only yield if there's new content\n                yield f\"data: {json.dumps({'token': new_text, 'gpu': worker.gpu_id}, ensure_ascii=False)}\\n\\n\"\n                last_clean_text = current_text\n\n    yield f\"data: {json.dumps({'done': True})}\\n\\n\"\n\n@app.post(\"/chat/completions\")\nasync def chat_completions(request: ChatRequest):\n    \"\"\"Chat completion endpoint (streaming only) - uses worker pool for multi-GPU.\"\"\"\n\n    # Basic validation to prevent abuse\n    validate_chat_request(request)\n\n    # Log incoming conversation to console\n    logger.info(\"=\"*20)\n    for i, message in enumerate(request.messages):\n        logger.info(f\"[{message.role.upper()}]: {message.content}\")\n    logger.info(\"-\"*20)\n\n    # Acquire a worker from the pool (will wait if all are busy)\n    worker_pool = app.state.worker_pool\n    worker = await worker_pool.acquire_worker()\n\n    try:\n        # Build conversation tokens\n        bos = worker.tokenizer.get_bos_token_id()\n        user_start = worker.tokenizer.encode_special(\"<|user_start|>\")\n        user_end = worker.tokenizer.encode_special(\"<|user_end|>\")\n        assistant_start = worker.tokenizer.encode_special(\"<|assistant_start|>\")\n        assistant_end = worker.tokenizer.encode_special(\"<|assistant_end|>\")\n\n        conversation_tokens = [bos]\n        for message in request.messages:\n            if message.role == \"user\":\n                conversation_tokens.append(user_start)\n                conversation_tokens.extend(worker.tokenizer.encode(message.content))\n                conversation_tokens.append(user_end)\n            elif message.role == \"assistant\":\n                conversation_tokens.append(assistant_start)\n                conversation_tokens.extend(worker.tokenizer.encode(message.content))\n                conversation_tokens.append(assistant_end)\n\n        conversation_tokens.append(assistant_start)\n\n        # Streaming response with worker release after completion\n        response_tokens = []\n        async def stream_and_release():\n            try:\n                async for chunk in generate_stream(\n                    worker,\n                    conversation_tokens,\n                    temperature=request.temperature,\n                    max_new_tokens=request.max_tokens,\n                    top_k=request.top_k\n                ):\n                    # Accumulate response for logging\n                    chunk_data = json.loads(chunk.replace(\"data: \", \"\").strip())\n                    if \"token\" in chunk_data:\n                        response_tokens.append(chunk_data[\"token\"])\n                    yield chunk\n            finally:\n                # Log the assistant response to console\n                full_response = \"\".join(response_tokens)\n                logger.info(f\"[ASSISTANT] (GPU {worker.gpu_id}): {full_response}\")\n                logger.info(\"=\"*20)\n                # Release worker back to pool after streaming is done\n                await worker_pool.release_worker(worker)\n\n        return StreamingResponse(\n            stream_and_release(),\n            media_type=\"text/event-stream\"\n        )\n    except Exception as e:\n        # Make sure to release worker even on error\n        await worker_pool.release_worker(worker)\n        raise e\n\n@app.get(\"/health\")\nasync def health():\n    \"\"\"Health check endpoint.\"\"\"\n    worker_pool = getattr(app.state, 'worker_pool', None)\n    return {\n        \"status\": \"ok\",\n        \"ready\": worker_pool is not None and len(worker_pool.workers) > 0,\n        \"num_gpus\": worker_pool.num_gpus if worker_pool else 0,\n        \"available_workers\": worker_pool.available_workers.qsize() if worker_pool else 0\n    }\n\n@app.get(\"/stats\")\nasync def stats():\n    \"\"\"Get worker pool statistics.\"\"\"\n    worker_pool = app.state.worker_pool\n    return {\n        \"total_workers\": len(worker_pool.workers),\n        \"available_workers\": worker_pool.available_workers.qsize(),\n        \"busy_workers\": len(worker_pool.workers) - worker_pool.available_workers.qsize(),\n        \"workers\": [\n            {\n                \"gpu_id\": w.gpu_id,\n                \"device\": str(w.device)\n            } for w in worker_pool.workers\n        ]\n    }\n\nif __name__ == \"__main__\":\n    import uvicorn\n    print(f\"Starting NanoChat Web Server\")\n    print(f\"Temperature: {args.temperature}, Top-k: {args.top_k}, Max tokens: {args.max_tokens}\")\n    uvicorn.run(app, host=args.host, port=args.port)\n"
  },
  {
    "path": "scripts/tok_eval.py",
    "content": "\"\"\"\nEvaluate compression ratio of the tokenizer.\n\"\"\"\n\nfrom nanochat.tokenizer import get_tokenizer, RustBPETokenizer\nfrom nanochat.dataset import parquets_iter_batched\n\n# Random text I got from a random website this morning\nnews_text = r\"\"\"\n(Washington, D.C., July 9, 2025)- Yesterday, Mexico’s National Service of Agro-Alimentary Health, Safety, and Quality (SENASICA) reported a new case of New World Screwworm (NWS) in Ixhuatlan de Madero, Veracruz in Mexico, which is approximately 160 miles northward of the current sterile fly dispersal grid, on the eastern side of the country and 370 miles south of the U.S./Mexico border. This new northward detection comes approximately two months after northern detections were reported in Oaxaca and Veracruz, less than 700 miles away from the U.S. border, which triggered the closure of our ports to Mexican cattle, bison, and horses on May 11, 2025.\n\nWhile USDA announced a risk-based phased port re-opening strategy for cattle, bison, and equine from Mexico beginning as early as July 7, 2025, this newly reported NWS case raises significant concern about the previously reported information shared by Mexican officials and severely compromises the outlined port reopening schedule of five ports from July 7-September 15. Therefore, in order to protect American livestock and our nation’s food supply, Secretary Rollins has ordered the closure of livestock trade through southern ports of entry effective immediately.\n\n“The United States has promised to be vigilant — and after detecting this new NWS case, we are pausing the planned port reopening’s to further quarantine and target this deadly pest in Mexico. We must see additional progress combatting NWS in Veracruz and other nearby Mexican states in order to reopen livestock ports along the Southern border,” said U.S. Secretary of Agriculture Brooke L. Rollins. “Thanks to the aggressive monitoring by USDA staff in the U.S. and in Mexico, we have been able to take quick and decisive action to respond to the spread of this deadly pest.”\n\"\"\".strip()\n\n# Random Korean text (to test non-English compression)\nkorean_text = r\"\"\"\n정직한 사실 위에, 공정한 시선을 더하다\nHerald Korea Times\n\n헤럴드코리아타임즈는 정치, 경제, 사회, 문화 등 한국 사회 전반의 주요 이슈를 심도 있게 다루는 종합 온라인 신문사입니다.\n\n우리는 단순히 뉴스를 전달하는 것이 아니라, 사실(Fact)에 기반한 양측의 시각을 균형 있게 조명하며, 독자 여러분이 스스로 판단할 수 있는 ‘정보의 균형’을 제공합니다.\n\n한국 언론의 오랜 문제로 지적되어 온 정치적 편향, 이념적 왜곡에서 벗어나\n오직 정직함과 공정함을 원칙으로 삼는 언론을 지향합니다.\n어느 한쪽의 주장만을 확대하거나 감추지 않고,\n**모든 쟁점에 대해 ‘무엇이 쟁점인지’, ‘누가 무엇을 주장하는지’, ‘사실은 무엇인지’**를 명확히 전달하는 데 집중합니다.\n\"\"\".strip()\n\n# Random piece of code\ncode_text = r\"\"\"\nclass BasicTokenizer(Tokenizer):\n\n    def __init__(self):\n        super().__init__()\n\n    def train(self, text, vocab_size, verbose=False):\n        assert vocab_size >= 256\n        num_merges = vocab_size - 256\n\n        # input text preprocessing\n        text_bytes = text.encode(\"utf-8\") # raw bytes\n        ids = list(text_bytes) # list of integers in range 0..255\n\n        # iteratively merge the most common pairs to create new tokens\n        merges = {} # (int, int) -> int\n        vocab = {idx: bytes([idx]) for idx in range(256)} # int -> bytes\n        for i in range(num_merges):\n            # count up the number of times every consecutive pair appears\n            stats = get_stats(ids)\n            # find the pair with the highest count\n            pair = max(stats, key=stats.get)\n            # mint a new token: assign it the next available id\n            idx = 256 + i\n            # replace all occurrences of pair in ids with idx\n            ids = merge(ids, pair, idx)\n            # save the merge\n            merges[pair] = idx\n            vocab[idx] = vocab[pair[0]] + vocab[pair[1]]\n            # prints\n            if verbose:\n                print(f\"merge {i+1}/{num_merges}: {pair} -> {idx} ({vocab[idx]}) had {stats[pair]} occurrences\")\n\"\"\".strip()\n\nmath_text = r\"\"\"\n\\documentclass[12pt]{article}\n\\usepackage{amsmath,amsthm,amssymb}\n\\usepackage[margin=1in]{geometry}\n\n\\newtheorem{theorem}{Theorem}\n\\newtheorem*{remark}{Remark}\n\n\\begin{document}\n\n\\begin{center}\n{\\Large A Cute Identity: The Sum of Cubes is a Square}\n\\end{center}\n\n\\begin{theorem}\nFor every integer $n \\ge 1$,\n\\[\n\\sum_{k=1}^{n} k^{3} \\;=\\; \\left(\\frac{n(n+1)}{2}\\right)^{2}.\n\\]\n\\end{theorem}\n\n\\begin{proof}[Proof 1 (Induction)]\nLet $S(n) = \\sum_{k=1}^{n} k^3$. For $n=1$, $S(1)=1=(1\\cdot 2/2)^2$, so the base case holds.\n\nAssume $S(n)=\\big(\\tfrac{n(n+1)}{2}\\big)^2$ for some $n\\ge 1$.\nThen\n\\[\nS(n+1)\n= S(n) + (n+1)^3\n= \\left(\\frac{n(n+1)}{2}\\right)^2 + (n+1)^3.\n\\]\nFactor out $(n+1)^2$:\n\\[\nS(n+1)\n= (n+1)^2\\left( \\frac{n^2}{4} + (n+1) \\right)\n= (n+1)^2\\left( \\frac{n^2 + 4n + 4}{4} \\right)\n= (n+1)^2\\left( \\frac{(n+2)^2}{4} \\right).\n\\]\nThus\n\\[\nS(n+1)=\\left(\\frac{(n+1)(n+2)}{2}\\right)^2,\n\\]\nwhich matches the claimed formula with $n$ replaced by $n+1$. By induction, the identity holds for all $n\\ge 1$.\n\\end{proof}\n\n\\begin{proof}[Proof 2 (Algebraic telescoping)]\nRecall the binomial identity\n\\[\n(k+1)^4 - k^4 = 4k^3 + 6k^2 + 4k + 1.\n\\]\nSumming both sides from $k=0$ to $n$ telescopes:\n\\[\n(n+1)^4 - 0^4\n= \\sum_{k=0}^{n}\\big(4k^3 + 6k^2 + 4k + 1\\big)\n= 4\\sum_{k=1}^{n}k^3 + 6\\sum_{k=1}^{n}k^2 + 4\\sum_{k=1}^{n}k + (n+1).\n\\]\nUsing the standard sums\n\\[\n\\sum_{k=1}^{n}k = \\frac{n(n+1)}{2}\n\\quad\\text{and}\\quad\n\\sum_{k=1}^{n}k^2 = \\frac{n(n+1)(2n+1)}{6},\n\\]\nsolve for $\\sum_{k=1}^{n}k^3$ to get\n\\[\n\\sum_{k=1}^{n}k^3 = \\left(\\frac{n(n+1)}{2}\\right)^2.\n\\]\n\\end{proof}\n\n\\begin{remark}\nGeometrically, the identity says: ``adding up $1^3,2^3,\\dots,n^3$ builds a perfect square’’—namely the square of the $n$th triangular number. This is why one sometimes calls it the \\emph{sum-of-cubes is a square} phenomenon.\n\\end{remark}\n\n\\end{document}\n\"\"\".strip()\n\nscience_text = r\"\"\"\nPhotosynthesis is a photochemical energy transduction process in which light-harvesting pigment–protein complexes within the thylakoid membranes of oxygenic phototrophs absorb photons and initiate charge separation at the reaction center, driving the linear electron transport chain from water to NADP⁺ via photosystem II, the cytochrome b₆f complex, and photosystem I, concomitantly generating a trans-thylakoid proton motive force utilized by chloroplastic ATP synthase. The light-dependent reactions produce ATP and NADPH, which fuel the Calvin–Benson–Bassham cycle in the stroma, wherein ribulose-1,5-bisphosphate is carboxylated by ribulose-1,5-bisphosphate carboxylase/oxygenase (RuBisCO) to form 3-phosphoglycerate, subsequently reduced and regenerated through a series of enzymatic steps, enabling net assimilation of CO₂ into triose phosphates and ultimately carbohydrates. This process is tightly regulated by photoprotective mechanisms, redox feedback, and metabolite flux, representing a central biochemical pathway coupling solar energy capture to the biosphere’s primary productivity.\n\"\"\".strip()\n\n# The tokenizer was trained on data from earlier shards, so it has seen this data\ntrain_docs = next(parquets_iter_batched(split=\"train\"))\ntrain_text = \"\\n\".join(train_docs)\nval_docs = next(parquets_iter_batched(split=\"val\"))\nval_text = \"\\n\".join(val_docs)\n\nall_text = [\n    (\"news\", news_text),\n    (\"korean\", korean_text),\n    (\"code\", code_text),\n    (\"math\", math_text),\n    (\"science\", science_text),\n    (\"fwe-train\", train_text),\n]\nif val_text:\n    all_text.append((\"fwe-val\", val_text))\n\n# Try out current default compared to GPT-2 and GPT-4 tokenizers\ntokenizer_results = {}\nvocab_sizes = {}\n\nfor tokenizer_name in [\"gpt2\", \"gpt4\", \"ours\"]:\n\n    if tokenizer_name == \"gpt2\":\n        tokenizer = RustBPETokenizer.from_pretrained(\"gpt2\") # gpt-2 base model tokenizer\n    elif tokenizer_name == \"gpt4\":\n        tokenizer = RustBPETokenizer.from_pretrained(\"cl100k_base\") # gpt-4 base model tokenizer\n    else:\n        tokenizer = get_tokenizer()\n\n    vocab_sizes[tokenizer_name] = tokenizer.get_vocab_size()\n    tokenizer_results[tokenizer_name] = {}\n\n    for name, text in all_text:\n        encoded = tokenizer.encode(text)\n        decoded = tokenizer.decode(encoded)\n        assert decoded == text\n\n        encoded_bytes = text.encode('utf-8')\n        ratio = len(encoded_bytes) / len(encoded)\n        tokenizer_results[tokenizer_name][name] = {\n            'bytes': len(encoded_bytes),\n            'tokens': len(encoded),\n            'ratio': ratio\n        }\n\n# ANSI color codes\nGREEN = '\\033[92m'\nRED = '\\033[91m'\nRESET = '\\033[0m'\n\n# Print vocab sizes\nprint(f\"\\nVocab sizes:\")\nprint(f\"GPT-2: {vocab_sizes['gpt2']}\")\nprint(f\"GPT-4: {vocab_sizes['gpt4']}\")\nprint(f\"Ours: {vocab_sizes['ours']}\")\n\ndef print_comparison(baseline_name, baseline_results, ours_results, all_text):\n    \"\"\"Print comparison table between baseline tokenizer and ours.\"\"\"\n    print(f\"\\nComparison with {baseline_name}:\")\n    print(\"=\" * 95)\n    print(f\"{'Text Type':<10} {'Bytes':<8} {baseline_name:<15} {'Ours':<15} {'Relative':<12} {'Better':<10}\")\n    print(f\"{'':10} {'':8} {'Tokens':<7} {'Ratio':<7} {'Tokens':<7} {'Ratio':<7} {'Diff %':<12}\")\n    print(\"-\" * 95)\n\n    for name, text in all_text:\n        baseline_data = baseline_results[name]\n        ours_data = ours_results[name]\n\n        # Calculate relative difference (positive means ours is better, negative means worse)\n        # Using tokens: fewer tokens is better, so we calculate (baseline_tokens - ours_tokens) / baseline_tokens\n        relative_diff = ((baseline_data['tokens'] - ours_data['tokens']) / baseline_data['tokens']) * 100\n\n        # Determine which has better compression (higher ratio = better)\n        if baseline_data['ratio'] > ours_data['ratio']:\n            baseline_color, ours_color = GREEN, RED\n            better = baseline_name\n            diff_color = RED\n        elif ours_data['ratio'] > baseline_data['ratio']:\n            baseline_color, ours_color = RED, GREEN\n            better = \"Ours\"\n            diff_color = GREEN\n        else:\n            baseline_color, ours_color = \"\", \"\"\n            better = \"Tie\"\n            diff_color = \"\"\n\n        print(f\"{name:<10} {baseline_data['bytes']:<8} \"\n              f\"{baseline_color}{baseline_data['tokens']:<7}{RESET} \"\n              f\"{baseline_color}{baseline_data['ratio']:<7.2f}{RESET} \"\n              f\"{ours_color}{ours_data['tokens']:<7}{RESET} \"\n              f\"{ours_color}{ours_data['ratio']:<7.2f}{RESET} \"\n              f\"{diff_color}{relative_diff:+7.1f}%{RESET}     \"\n              f\"{better:<10}\")\n\n# Print comparisons\nprint_comparison(\"GPT-2\", tokenizer_results['gpt2'], tokenizer_results['ours'], all_text)\nprint_comparison(\"GPT-4\", tokenizer_results['gpt4'], tokenizer_results['ours'], all_text)\n\n# Log to report\nfrom nanochat.report import get_report\nlines = []\nfor baseline_name in [\"GPT-2\", \"GPT-4\"]:\n    baseline_key = baseline_name.lower().replace('-', '')\n    baseline_results = tokenizer_results[baseline_key]\n    ours_results = tokenizer_results['ours']\n    lines.append(f\"### Comparison with {baseline_name}\")\n    lines.append(\"\")\n    lines.append(\"| Text Type | Bytes | \" + baseline_name + \" Tokens | \" + baseline_name + \" Ratio | Ours Tokens | Ours Ratio | Relative Diff % |\")\n    lines.append(\"|-----------|-------|--------------|--------------|-------------|------------|-----------------|\")\n    for name, text in all_text:\n        baseline_data = baseline_results[name]\n        ours_data = ours_results[name]\n        relative_diff = ((baseline_data['tokens'] - ours_data['tokens']) / baseline_data['tokens']) * 100\n        lines.append(f\"| {name} | {baseline_data['bytes']} | {baseline_data['tokens']} | {baseline_data['ratio']:.2f} | {ours_data['tokens']} | {ours_data['ratio']:.2f} | {relative_diff:+.1f}% |\")\n    lines.append(\"\")\nreport_markdown = \"\\n\".join(lines)\nget_report().log(section=\"Tokenizer evaluation\", data=[\n    report_markdown,\n])\n"
  },
  {
    "path": "scripts/tok_train.py",
    "content": "\"\"\"\nTrain a tokenizer using our own BPE Tokenizer library.\nIn the style of GPT-4 tokenizer.\n\"\"\"\nimport os\nimport time\nimport argparse\nimport torch\nfrom nanochat.tokenizer import RustBPETokenizer\nfrom nanochat.common import get_base_dir\nfrom nanochat.dataset import parquets_iter_batched\n\n# -----------------------------------------------------------------------------\n# Parse command line arguments\n\nparser = argparse.ArgumentParser(description='Train a BPE tokenizer')\nparser.add_argument('--max-chars', type=int, default=2_000_000_000, help='Maximum characters to train on (default: 10B)')\nparser.add_argument('--doc-cap', type=int, default=10_000, help='Maximum characters per document (default: 10,000)')\nparser.add_argument('--vocab-size', type=int, default=32768, help='Vocabulary size (default: 32768 = 2^15)')\nargs = parser.parse_args()\nprint(f\"max_chars: {args.max_chars:,}\")\nprint(f\"doc_cap: {args.doc_cap:,}\")\nprint(f\"vocab_size: {args.vocab_size:,}\")\n\n# -----------------------------------------------------------------------------\n# Text iterator\n\ndef text_iterator():\n    \"\"\"\n    1) Flatten the batches into a single iterator\n    2) Crop every document to args.doc_cap characters\n    3) Break when we've seen args.max_chars characters\n    \"\"\"\n    nchars = 0\n    for batch in parquets_iter_batched(split=\"train\"):\n        for doc in batch:\n            doc_text = doc\n            if len(doc_text) > args.doc_cap:\n                doc_text = doc_text[:args.doc_cap]\n            nchars += len(doc_text)\n            yield doc_text\n            if nchars > args.max_chars:\n                return\ntext_iter = text_iterator()\n\n# -----------------------------------------------------------------------------\n# Train the tokenizer\nt0 = time.time()\ntokenizer = RustBPETokenizer.train_from_iterator(text_iter, args.vocab_size)\nt1 = time.time()\ntrain_time = t1 - t0\nprint(f\"Training time: {train_time:.2f}s\")\n\n# -----------------------------------------------------------------------------\n# Save the tokenizer to disk\nbase_dir = get_base_dir()\ntokenizer_dir = os.path.join(base_dir, \"tokenizer\")\ntokenizer.save(tokenizer_dir)\n\n# -----------------------------------------------------------------------------\n# Quick inline sanity check\ntest_text = \"\"\"Hello world! This is a test.\nNumbers: 123, 4567, 89\nContractions: I'm, you're, it's\nSpecial chars: @#$%^&*()\nUnicode: 你好世界 🌍\"\"\"\nencoded = tokenizer.encode(test_text)\ndecoded = tokenizer.decode(encoded)\nassert decoded == test_text\n\n# -----------------------------------------------------------------------------\n# One more thing: we wish to cache a mapping from token id to number of bytes of that token\n# for efficient evaluation of bits per byte. Unlike the typical mean loss, this\n# allows us to report a loss that is invariant to the vocab size of the tokenizer.\n# The bits per byte on the validation set is then one of the primary metrics we care about.\nvocab_size = tokenizer.get_vocab_size()\nspecial_set = set(tokenizer.get_special_tokens())\ntoken_strings = [tokenizer.decode([token_id]) for token_id in range(vocab_size)]\ntoken_bytes = []\nfor token_id in range(vocab_size):\n    token_str = token_strings[token_id] # the Python string representation of this token\n    if token_str in special_set:\n        token_bytes.append(0) # special characters are not counted\n    else:\n        id_bytes = len(token_str.encode(\"utf-8\")) # number of bytes that make up this token\n        token_bytes.append(id_bytes)\ntoken_bytes = torch.tensor(token_bytes, dtype=torch.int32, device='cpu')\ntoken_bytes_path = os.path.join(tokenizer_dir, \"token_bytes.pt\")\nwith open(token_bytes_path, \"wb\") as f:\n    torch.save(token_bytes, f)\nprint(f\"Saved token_bytes to {token_bytes_path}\")\n\n# Log to report\nfrom nanochat.report import get_report\ntoken_bytes_nonzero = (token_bytes[token_bytes > 0]).to(dtype=torch.float32)\nget_report().log(section=\"Tokenizer training\", data=[\n    vars(args), # argparse command line arguments\n    {\"train_time\": train_time},\n    {\"num_special_tokens\": len(special_set)},\n    {\n        \"token_bytes_min\": int(token_bytes_nonzero.min().item()),\n        \"token_bytes_max\": int(token_bytes_nonzero.max().item()),\n        \"token_bytes_mean\": token_bytes_nonzero.mean().item(),\n        \"token_bytes_std\": token_bytes_nonzero.std().item(),\n    }\n])\n"
  },
  {
    "path": "tasks/arc.py",
    "content": "\"\"\"\nThe ARC dataset from Allen AI.\nhttps://huggingface.co/datasets/allenai/ai2_arc\n\"\"\"\n\nfrom datasets import load_dataset\nfrom tasks.common import Task, render_mc\n\nclass ARC(Task):\n\n    def __init__(self, subset, split, **kwargs):\n        super().__init__(**kwargs)\n        assert subset in [\"ARC-Easy\", \"ARC-Challenge\"], \"ARC subset must be ARC-Easy or ARC-Challenge\"\n        assert split in [\"train\", \"validation\", \"test\"], \"ARC split must be train|validation|test\"\n        self.ds = load_dataset(\"allenai/ai2_arc\", subset, split=split).shuffle(seed=42)\n\n    @property\n    def eval_type(self):\n        return 'categorical'\n\n    def num_examples(self):\n        return len(self.ds)\n\n    def get_example(self, index):\n        row = self.ds[index]\n        question = row[\"question\"] # the question text\n        choices = row[\"choices\"][\"text\"] # the text of each choice\n        answer_string = row[\"answerKey\"] # e.g. \"A\", \"B\", \"C\", \"D\"\n        letters = row[\"choices\"][\"label\"] # e.g. [\"A\", \"B\", \"C\", \"D\"]\n        assert answer_string in letters, f\"ARC answer {answer_string} must be one of {letters}\" # sanity check\n        # create and return the Conversation object\n        user_message = render_mc(question, letters, choices)\n        messages = [\n            {\"role\": \"user\", \"content\": user_message},\n            {\"role\": \"assistant\", \"content\": answer_string}\n        ]\n        conversation = {\n            \"messages\": messages,\n            \"letters\": letters, # useful during evaluation, so we can narrow and clamp the assistant prediction to one of the letters\n        }\n        return conversation\n\n    def evaluate(self, conversation, assistant_response):\n        # the assert here is not strictly speaking needed, but currently the way we eval, we expect this to be true\n        # I'm going to leave the assert here to prevent footguns, but possibly in the future can remove it.\n        assert assistant_response in conversation['letters'], f\"ARC answer {assistant_response} is expected to be one of {conversation['letters']}\"\n        assistant_message = conversation['messages'][-1]['content'] # e.g. \"A\"\n        return assistant_response == assistant_message\n"
  },
  {
    "path": "tasks/common.py",
    "content": "\"\"\"\nBase class for all Tasks.\nA Task is basically a dataset of conversations, together with some\nmetadata and often also evaluation criteria.\nExample tasks: MMLU, ARC-Easy, ARC-Challenge, GSM8K, HumanEval, SmolTalk.\n\"\"\"\n\nimport random\n\nclass Task:\n    \"\"\"\n    Base class of a Task. Allows for lightweight slicing of the underlying dataset.\n    \"\"\"\n\n    def __init__(self, start=0, stop=None, step=1):\n        # allows a lightweight logical view over a dataset\n        assert start >= 0, f\"Start must be non-negative, got {start}\"\n        assert stop is None or stop >= start, f\"Stop should be greater than or equal to start, got {stop} and {start}\"\n        assert step >= 1, f\"Step must be strictly positive, got {step}\"\n        self.start = start\n        self.stop = stop # could be None here\n        self.step = step\n\n    @property\n    def eval_type(self):\n        # one of 'generative' | 'categorical'\n        raise NotImplementedError\n\n    def num_examples(self):\n        raise NotImplementedError\n\n    def get_example(self, index):\n        raise NotImplementedError\n\n    def __len__(self):\n        start = self.start\n        stop = self.num_examples() if self.stop is None else self.stop\n        step = self.step\n        span = stop - start\n        num = (span + step - 1) // step # ceil_div(span, step)\n        assert num >= 0, f\"Negative number of examples???: {num}\" # prevent footguns\n        return num\n\n    def __getitem__(self, index: int):\n        assert isinstance(index, int), f\"Index must be an integer, got {type(index)}\"\n        physical_index = self.start + index * self.step\n        conversation = self.get_example(physical_index)\n        return conversation\n\n    def evaluate(self, problem, completion):\n        raise NotImplementedError\n\n\nclass TaskMixture(Task):\n    \"\"\"\n    For SFT Training it becomes useful to train on a mixture of datasets.\n    Fun trick: if you wish to oversample any task, just pass it in multiple times in the list.\n    \"\"\"\n\n    def __init__(self, tasks, **kwargs):\n        super().__init__(**kwargs)\n        # tasks is a list of Task objects\n        self.tasks = tasks\n        self.lengths = [len(task) for task in self.tasks]\n        self.num_conversations = sum(self.lengths)\n        # Build list of all (task_idx, local_idx) pairs\n        self.index_map = []\n        for task_idx, task_length in enumerate(self.lengths):\n            for local_idx in range(task_length):\n                self.index_map.append((task_idx, local_idx))\n        # Deterministically shuffle to mix tasks throughout training\n        rng = random.Random(42)\n        rng.shuffle(self.index_map)\n        # Note: this is not the most elegant or best solution, but it's ok for now\n\n    def num_examples(self):\n        return self.num_conversations\n\n    def get_example(self, index):\n        \"\"\"\n        Access conversations according to a deterministic shuffle of all examples.\n        This ensures tasks are mixed throughout training, regardless of dataset size.\n        \"\"\"\n        assert 0 <= index < self.num_conversations, f\"Index {index} out of range for mixture with {self.num_conversations} conversations\"\n        task_idx, local_idx = self.index_map[index]\n        return self.tasks[task_idx][local_idx]\n\n\nclass TaskSequence(Task):\n    \"\"\"\n    For SFT Training sometimes we want to sequentially train on a list of tasks.\n    This is useful for cases that require a training curriculum.\n    \"\"\"\n\n    def __init__(self, tasks, **kwargs):\n        super().__init__(**kwargs)\n        self.tasks = tasks\n        self.lengths = [len(task) for task in self.tasks]\n        self.num_conversations = sum(self.lengths)\n\n    def num_examples(self):\n        return self.num_conversations\n\n    def get_example(self, index):\n        assert 0 <= index < self.num_conversations, f\"Index {index} out of range for sequence with {self.num_conversations} conversations\"\n        for task_idx, task_length in enumerate(self.lengths):\n            if index < task_length:\n                return self.tasks[task_idx][index]\n            index -= task_length\n\n\ndef render_mc(question, letters, choices):\n    \"\"\"\n    The common multiple choice rendering format we will use.\n\n    Note two important design decisions:\n    1)\n    Bigger models don't care as much, but smaller models prefer to have\n    the letter *after* the choice, which results in better binding.\n    2)\n    There is no whitespace between the delimiter (=) and the letter.\n    This is actually critical because the tokenizer has different token ids\n    for \" A\" vs. \"A\". The assistant responses will be just the letter itself,\n    i.e. \"A\", so it is important that here in the prompt it is the exact same\n    token, i.e. \"A\" with no whitespace before it. Again, bigger models don't care\n    about this too much, but smaller models do care about some of these details.\n    \"\"\"\n    query = f\"Multiple Choice question: {question}\\n\"\n    query += \"\".join([f\"- {choice}={letter}\\n\" for letter, choice in zip(letters, choices)])\n    query += \"\\nRespond only with the letter of the correct answer.\"\n    return query\n\n\nif __name__ == \"__main__\":\n    # very lightweight test of slicing\n    from tasks.mmlu import MMLU\n\n    ds = MMLU(subset=\"auxiliary_train\", split=\"train\")\n    print(\"Length of MMLU: \", len(ds))\n    ex = ds[5]\n    print(\"5th example: \", ex)\n\n    ds = MMLU(subset=\"auxiliary_train\", split=\"train\", start=5, stop=10)\n    print(\"Length of sliced MMLU[5:10]: \", len(ds))\n    print(\"0th example of sliced MMLU: \", ds[0])\n\n    print(\"They match: \", ex == ds[0])\n"
  },
  {
    "path": "tasks/customjson.py",
    "content": "\"\"\"\nCustomJSON task for loading conversations from JSONL files.\nEach line in the JSONL file should be a JSON array of messages.\n\"\"\"\n\nimport os\nimport json\nfrom tasks.common import Task\n\nclass CustomJSON(Task):\n    \"\"\"\n    Load conversations from a JSONL file.\n    Each line should be a JSON array of message objects with 'role' and 'content' fields.\n    Example line: [{\"role\":\"user\",\"content\":\"Hi\"},{\"role\":\"assistant\",\"content\":\"Hello\"}]\n    \"\"\"\n\n    def __init__(self, filepath, **kwargs):\n        super().__init__(**kwargs)\n        self.filepath = filepath\n        self.conversations = []\n\n        # Load all conversations from the JSONL file\n        if not os.path.exists(filepath):\n            # Helpful error message due to recent change. Will be removed in the future.\n            print(\"-\" * 80)\n            print(f\"Warning: File {filepath} does not exist\")\n            print(\"HINT (Oct 21 2025)\")\n            print(\"If you recently did a git pull and suddenly see this, it might be due to the new addition of identity conversations\")\n            print(\"See this discussion for more details: https://github.com/karpathy/nanochat/discussions/139\")\n            print(\"Quick fix: simply run the following command to download the file and you're done:\")\n            print(f\"curl -L -o {filepath} https://karpathy-public.s3.us-west-2.amazonaws.com/identity_conversations.jsonl\")\n            print(\"-\" * 80)\n\n        else:\n            with open(filepath, 'r', encoding='utf-8') as f:\n                for line in f:\n                    line = line.strip()\n                    if not line:  # skip empty lines\n                        continue\n                    messages = json.loads(line)\n                    # Validate the conversation structure\n                    assert isinstance(messages, list), f\"Expected list of messages, got {type(messages)}\"\n                    assert len(messages) >= 2, f\"Conversation must have at least 2 messages, got {len(messages)}\"\n                    # Validate message structure and alternating roles\n                    for i, message in enumerate(messages):\n                        assert \"role\" in message, f\"Message {i} missing 'role' field\"\n                        assert \"content\" in message, f\"Message {i} missing 'content' field\"\n                        expected_role = \"user\" if i % 2 == 0 else \"assistant\"\n                        assert message[\"role\"] == expected_role, f\"Message {i} has role {message['role']} but should be {expected_role}\"\n                        assert isinstance(message[\"content\"], str), f\"Message {i} content must be a string\"\n\n                    self.conversations.append(messages)\n\n        self.length = len(self.conversations)\n\n    def num_examples(self):\n        return self.length\n\n    def get_example(self, index):\n        messages = self.conversations[index]\n        conversation = {\n            \"messages\": messages,\n        }\n        return conversation\n\n"
  },
  {
    "path": "tasks/gsm8k.py",
    "content": "\"\"\"\nGSM8K evaluation.\nhttps://huggingface.co/datasets/openai/gsm8k\n\nExample problem instance:\n\nQuestion:\nWeng earns $12 an hour for babysitting. Yesterday, she just did 50 minutes of babysitting. How much did she earn?\nAnswer:\nWeng earns 12/60 = $<<12/60=0.2>>0.2 per minute.\nWorking 50 minutes, she earned 0.2 x 50 = $<<0.2*50=10>>10.\n#### 10\n\nNotice that GSM8K uses tool calls inside << >> tags.\n\"\"\"\n\nimport re\nfrom datasets import load_dataset\nfrom tasks.common import Task\n\n\nGSM_RE = re.compile(r\"#### (\\-?[0-9\\.\\,]+)\")\ndef extract_answer(completion):\n    \"\"\"\n    Extract the numerical answer after #### marker.\n    Follows official code for normalization:\n    https://github.com/openai/grade-school-math/blob/3101c7d5072418e28b9008a6636bde82a006892c/grade_school_math/dataset.py#L28\n    \"\"\"\n    match = GSM_RE.search(completion)\n    if match:\n        match_str = match.group(1).strip()\n        match_str = match_str.replace(\",\", \"\")\n        return match_str\n    return None\n\n\nclass GSM8K(Task):\n\n    def __init__(self, subset, split, **kwargs):\n        super().__init__(**kwargs)\n        assert subset in [\"main\", \"socratic\"], \"GSM8K subset must be main|socratic\"\n        assert split in [\"train\", \"test\"], \"GSM8K split must be train|test\"\n        self.ds = load_dataset(\"openai/gsm8k\", subset, split=split).shuffle(seed=42)\n\n    @property\n    def eval_type(self):\n        return 'generative'\n\n    def num_examples(self):\n        return len(self.ds)\n\n    def get_example(self, index):\n        \"\"\" Get a single problem from the dataset. \"\"\"\n        row = self.ds[index]\n        question = row['question'] # string of the question prompt\n        answer = row['answer'] # string of the full solution and the answer after #### marker\n        # Create and return the Conversation object\n        # This is tricky because GSM8K uses tool calls, which we need to parse here.\n        assistant_message_parts = []\n        parts = re.split(r'(<<[^>]+>>)', answer)\n        for part in parts:\n            if part.startswith('<<') and part.endswith('>>'):\n                # This is a calculator tool call\n                inner = part[2:-2]  # Remove << >>\n                # Split on = to get expression and result\n                if '=' in inner:\n                    expr, result = inner.rsplit('=', 1)\n                else:\n                    expr, result = inner, \"\"\n                # Add the tool call as a part\n                assistant_message_parts.append({\"type\": \"python\", \"text\": expr})\n                # Add the result as a part\n                assistant_message_parts.append({\"type\": \"python_output\", \"text\": result})\n            else:\n                # Regular text in between tool calls\n                assistant_message_parts.append({\"type\": \"text\", \"text\": part})\n        # Now put it all together\n        messages = [\n            {\"role\": \"user\", \"content\": question}, # note: simple string\n            {\"role\": \"assistant\", \"content\": assistant_message_parts}, # note: list of parts (as dicts)\n        ]\n        conversation = {\n            \"messages\": messages,\n        }\n        return conversation\n\n    def evaluate(self, conversation, assistant_response):\n        \"\"\"\n        Given (conversation, completion), return evaluation outcome (0 = wrong, 1 = correct)\n        Note that:\n        - the conversation has both user AND assistant message (containing the ground truth answer)\n        - the assistant_response is usually the alternative assistant message achieved via sampling\n\n        TODO: Technically, assistant_response should be a Message (either a string or a list of parts)\n              We can handle this later possibly. For now just assume string.\n        \"\"\"\n        assert isinstance(assistant_response, str), \"Assuming simple string response for now\"\n        # First extract the ground truth answer\n        assistant_message = conversation['messages'][-1]\n        assert assistant_message['role'] == \"assistant\", \"Last message must be from the Assistant\"\n        assert isinstance(assistant_message['content'], list), \"This is expected to be a list of parts\"\n        last_text_part = assistant_message['content'][-1]['text'] # this contains the final answer in GSM8K\n        # Extract both the ground truth answer and the predicted answer\n        ref_num = extract_answer(last_text_part)\n        pred_num = extract_answer(assistant_response)\n        # Compare and return the success as int\n        is_correct = int(pred_num == ref_num)\n        return is_correct\n\n    def reward(self, conversation, assistant_response):\n        \"\"\"\n        Used during RL. To keep things simple, just re-use the evaluation above.\n        Later this could be made more complex (e.g. format matching etc.)\n        \"\"\"\n        is_correct = self.evaluate(conversation, assistant_response)\n        is_correct_float = float(is_correct)\n        return is_correct_float\n"
  },
  {
    "path": "tasks/humaneval.py",
    "content": "\"\"\"\nEvaluate the Chat model on HumanEval dataset.\nBtw this dataset is a misnomer and has nothing to do with humans.\nIt is a coding benchmark.\n\"\"\"\n\nimport re\nfrom datasets import load_dataset\nfrom nanochat.execution import execute_code\nfrom tasks.common import Task\n\ndef extract_imports(prompt):\n    \"\"\"Extract import statements from the beginning of a code block.\"\"\"\n    imports = []\n    for line in prompt.split('\\n'):\n        stripped = line.strip()\n        if stripped.startswith('import ') or stripped.startswith('from '):\n            imports.append(stripped)\n        elif stripped and not stripped.startswith('#'):\n            # Stop at first non-import, non-comment line\n            break\n    return '\\n'.join(imports)\n\ndef extract_program(completion):\n    \"\"\"\n    Extract Python code from LLM completion.\n\n    Handles various output formats:\n    - Code wrapped in ```python ... ``` or ``` ... ``` blocks\n    - Plain code without markdown blocks\n    - Extra text before/after code blocks\n\n    Returns the first code block if found, otherwise returns the whole completion.\n    \"\"\"\n    # Try to find markdown code blocks (```python or just ```)\n    # Match ```python\\n...\\n``` or ```\\n...\\n```\n    pattern = r'```(?:python)?\\s*\\n(.*?)\\n```'\n    matches = re.findall(pattern, completion, re.DOTALL)\n\n    if matches:\n        # Return the first code block found\n        return matches[0].strip()\n\n    # No code blocks found, return the whole completion\n    return completion.strip()\n\nclass HumanEval(Task):\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self.ds = load_dataset(\"openai/openai_humaneval\", split=\"test\").shuffle(seed=42)\n\n    @property\n    def eval_type(self):\n        return 'generative'\n\n    def num_examples(self):\n        return len(self.ds)\n\n    def get_example(self, index):\n        \"\"\" Get a single problem from the dataset. \"\"\"\n        row = self.ds[index]\n        prompt = row['prompt'] # prompts in HumanEval are the beginning of the program\n        solution = row['canonical_solution'] # the correct continuation of the program\n        entry_point = row['entry_point'] # the function to check\n        test = row['test'] # the test cases\n        complete_solution = f\"{prompt}\\n{solution}\"\n        messages = [\n            {\"role\": \"user\", \"content\": prompt},\n            {\"role\": \"assistant\", \"content\": complete_solution},\n        ]\n        conversation = {\n            \"messages\": messages,\n            \"entry_point\": entry_point, # needed during evaluation\n            \"test\": test, # needed during evaluation\n        }\n        return conversation\n\n    def evaluate(self, conversation, completion):\n        \"\"\" Given (conversation, completion), return boolean success of the completion. \"\"\"\n        # the prompt will contain the imports and the function signature\n        imports = extract_imports(conversation['messages'][0]['content'])\n        # the completion will usually contain the whole function\n        # but not always with the needed imports, so we manually append them\n        completion_code = extract_program(completion)\n        program = (\n            imports\n            + \"\\n\\n\"\n            + completion_code\n            + \"\\n\\n\"\n            + conversation['test']\n            + \"\\n\"\n            + f\"check({conversation['entry_point']})\"\n        )\n        result = execute_code(program)\n        success = result.success\n        return success\n"
  },
  {
    "path": "tasks/mmlu.py",
    "content": "\"\"\"\nThe MMLU dataset.\nhttps://huggingface.co/datasets/cais/mmlu\n\"\"\"\n\nfrom datasets import load_dataset\nfrom tasks.common import Task, render_mc\n\nclass MMLU(Task):\n\n    letters = ('A', 'B', 'C', 'D')\n    groups = ('abstract_algebra', 'anatomy', 'astronomy', 'business_ethics', 'clinical_knowledge', 'college_biology', 'college_chemistry', 'college_computer_science', 'college_mathematics', 'college_medicine', 'college_physics', 'computer_security', 'conceptual_physics', 'econometrics', 'electrical_engineering', 'elementary_mathematics', 'formal_logic', 'global_facts', 'high_school_biology', 'high_school_chemistry', 'high_school_computer_science', 'high_school_european_history', 'high_school_geography', 'high_school_government_and_politics', 'high_school_macroeconomics', 'high_school_mathematics', 'high_school_microeconomics', 'high_school_physics', 'high_school_psychology', 'high_school_statistics', 'high_school_us_history', 'high_school_world_history', 'human_aging', 'human_sexuality', 'international_law', 'jurisprudence', 'logical_fallacies', 'machine_learning', 'management', 'marketing', 'medical_genetics', 'miscellaneous', 'moral_disputes', 'moral_scenarios', 'nutrition', 'philosophy', 'prehistory', 'professional_accounting', 'professional_law', 'professional_medicine', 'professional_psychology', 'public_relations', 'security_studies', 'sociology', 'us_foreign_policy', 'virology', 'world_religions')\n\n    def __init__(self, subset, split, **kwargs):\n        super().__init__(**kwargs)\n        assert subset in [\"all\", \"auxiliary_train\"], f\"subset {subset} must be all|auxiliary_train\"\n        assert split in [\"train\", \"validation\", \"dev\", \"test\"], f\"split {split} must be train|validation|dev|test\"\n        if subset == \"auxiliary_train\":\n            assert split == \"train\", \"auxiliary_train must be split into train\"\n        self.subset = subset\n        self.split = split\n        self.ds = load_dataset(\"cais/mmlu\", subset, split=split).shuffle(seed=42)\n        if subset == \"auxiliary_train\":\n            # I don't understand why but the auxiliary_train rows have some weird additional 'train' wrapper\n            self.ds = self.ds.map(lambda row: row['train'], remove_columns=['train'])\n\n    @property\n    def eval_type(self):\n        return 'categorical'\n\n    def num_examples(self):\n        return len(self.ds)\n\n    def get_example(self, index):\n        row = self.ds[index]\n        question = row[\"question\"] # the question text\n        choices = row[\"choices\"] # the text of each choice\n        answer = row[\"answer\"] # index of the answer, e.g. 0,1,2,3 (for A,B,C,D)\n        subject = row[\"subject\"] # e.g. \"college_biology\", \"college_chemistry\", etc.\n        assert len(choices) == 4, \"MMLU should have 4 choices\"\n        # create and return the Conversation object\n        user_message = render_mc(question, self.letters, choices)\n        assistant_message = self.letters[answer]\n        messages = [\n            {\"role\": \"user\", \"content\": user_message},\n            {\"role\": \"assistant\", \"content\": assistant_message}\n        ]\n        conversation = {\n            \"messages\": messages,\n            \"subject\": subject, # might be useful later for grouping metrics by subject\n            \"letters\": self.letters, # useful during evaluation, so we can narrow and clamp the assistant prediction to one of the letters\n        }\n        return conversation\n\n    def evaluate(self, conversation, assistant_response):\n        # the assert here is not strictly speaking needed, but currently the way we eval, we expect this to be true\n        # I'm going to leave the assert here to prevent footguns, but possibly in the future can remove it.\n        assert assistant_response in self.letters, f\"MMLU answer {assistant_response} is expected to be one of {self.letters}\"\n        assistant_message = conversation['messages'][-1]['content'] # e.g. \"A\"\n        return assistant_response == assistant_message\n"
  },
  {
    "path": "tasks/smoltalk.py",
    "content": "\"\"\"\nSmolTalk by HuggingFace. Good \"general\" conversational dataset.\nhttps://huggingface.co/datasets/HuggingFaceTB/smol-smoltalk\nWe use the \"smol\" version, which is more appropriate for smaller models.\n\"\"\"\n\nfrom datasets import load_dataset\nfrom tasks.common import Task\n\nclass SmolTalk(Task):\n    \"\"\" smol-smoltalk dataset. train is 460K rows, test is 24K rows. \"\"\"\n\n    def __init__(self, split, **kwargs):\n        super().__init__(**kwargs)\n        assert split in [\"train\", \"test\"], \"SmolTalk split must be train|test\"\n        self.ds = load_dataset(\"HuggingFaceTB/smol-smoltalk\", split=split).shuffle(seed=42)\n        self.length = len(self.ds)\n\n    def num_examples(self):\n        return self.length\n\n    def get_example(self, index):\n        row = self.ds[index]\n        messages = row[\"messages\"]\n        # ---------------------------------------------------------------------\n        # sanity checking asserts here\n        # TODO: we could remove these asserts later, for now just don't want any footguns\n        # there is an optional system message at the beginning\n        assert len(messages) >= 1\n        first_message = messages[0]\n        if first_message[\"role\"] == \"system\":\n            rest_messages = messages[1:] # optional system message is OK\n        else:\n            rest_messages = messages\n        assert len(rest_messages) >= 2, \"SmolTalk messages must have at least 2 messages\"\n        for i, message in enumerate(rest_messages):\n            # user and assistant alternate as user,assistant,user,assistant,...\n            expected_role = \"user\" if i % 2 == 0 else \"assistant\"\n            assert message[\"role\"] == expected_role, f\"Message {i} has role {message['role']} but should be {expected_role}\"\n            assert isinstance(message[\"content\"], str), \"Content must be a string\"\n        # ---------------------------------------------------------------------\n        # create and return the Conversation object (ok to emit the system message too)\n        conversation = {\n            \"messages\": messages,\n        }\n        return conversation\n"
  },
  {
    "path": "tasks/spellingbee.py",
    "content": "\"\"\"\nTask intended to make nanochat better in spelling and counting, for example:\n\n\"How many r are in strawberry?\" -> 3\n\nAn interesting part of this task is that we will get the assistant to\nsolve the problem using a combination of manual counting and Python.\nThis is a good problem solving \"instinct\" to mix into the model and RL\nmay further refine it to trust one over the other. If we were extra fancy\n(which we could/should be) we'd add small errors here and there to allow\nthe model also learn recoveries. We can do this in future versions.\n\nThere are two tasks in this file:\n1. SpellingBee: Counting the number of occurrences of a letter in a word\n2. SimpleSpelling: Simply spelling words\n\n(1) is the goal, but (2) exists as a highly condensed version of the part\nthat makes (1) difficult, which is word spelling. This is non-trivial for an\nLLM because it has to learn how every token (a little semantic chunk/atom)\nmaps to the sequence of individual characters that make it up. Larger models\nlearn this eventually on their own, but if we want this capability to exist\nin smaller models, we have to actively encourage it by over-representing it\nin the training data. SFT is a good place to do this.\n\nTo preview a few example conversations, run:\npython -m tasks.spellingbee\n\"\"\"\n\nimport re\nimport random\nfrom tasks.common import Task\nfrom nanochat.common import download_file_with_lock\n\n# Letters of the alphabet\nLETTERS = \"abcdefghijklmnopqrstuvwxyz\"\n# A list of 370K English words of large variety\nWORD_LIST_URL = \"https://raw.githubusercontent.com/dwyl/english-words/refs/heads/master/words_alpha.txt\"\n# A number bigger than 370K to separate train and test random seeds\nTEST_RANDOM_SEED_OFFSET = 10_000_000\n\n# Identical to gsm8k's answer extraction\nANSWER_RE = re.compile(r\"#### (\\-?[0-9\\.\\,]+)\")\ndef extract_answer(completion):\n    \"\"\"\n    Extract the numerical answer after #### marker.\n    \"\"\"\n    match = ANSWER_RE.search(completion)\n    if match:\n        match_str = match.group(1).strip()\n        match_str = match_str.replace(\",\", \"\")\n        return match_str\n    return None\n\n# User message templates for data augmentation\nUSER_MSG_TEMPLATES = [\n    \"How many {letter} are in the word {word}\",\n    \"How many {letter} are in {word}\",\n    \"Count the number of {letter} in {word}\",\n    \"How many times does {letter} appear in {word}\",\n    \"What's the count of {letter} in {word}\",\n    \"In the word {word}, how many {letter} are there\",\n    \"How many letter {letter} are in the word {word}\",\n    \"Count how many {letter} appear in {word}\",\n    \"Tell me the number of {letter} in {word}\",\n    \"How many occurrences of {letter} are in {word}\",\n    \"Find the count of {letter} in {word}\",\n    \"Can you count the {letter} letters in {word}\",\n    \"What is the frequency of {letter} in {word}\",\n    \"How many {letter}s are in {word}\",\n    \"How many {letter}'s are in {word}\",\n    \"Count all the {letter} in {word}\",\n    \"How many times is {letter} in {word}\",\n    \"Number of {letter} in {word}\",\n    \"Total count of {letter} in {word}\",\n    \"How many {letter} does {word} have\",\n    \"How many {letter} does {word} contain\",\n    \"What's the number of {letter} in {word}\",\n    \"{word} has how many {letter}\",\n    \"In {word}, count the {letter}\",\n    \"How many {letter} appear in {word}\",\n    \"Count the {letter} in {word}\",\n    \"Give me the count of {letter} in {word}\",\n    \"How many instances of {letter} in {word}\",\n    \"Show me how many {letter} are in {word}\",\n    \"Calculate the number of {letter} in {word}\",\n    # Spanish\n    \"¿Cuántas {letter} hay en {word}?\",\n    \"¿Cuántas veces aparece {letter} en {word}?\",\n    \"Cuenta las {letter} en {word}\",\n    \"¿Cuántas letras {letter} tiene {word}?\",\n    # Chinese (Simplified)\n    \"{word}中有多少个{letter}\",\n    \"{word}里有几个{letter}\",\n    \"数一下{word}中的{letter}\",\n    \"{word}这个词里有多少{letter}\",\n    # Korean\n    \"{word}에 {letter}가 몇 개 있나요\",\n    \"{word}에서 {letter}의 개수는\",\n    \"{word}에 {letter}가 몇 번 나오나요\",\n    \"{word}라는 단어에 {letter}가 몇 개\",\n    # French\n    \"Combien de {letter} dans {word}\",\n    \"Combien de fois {letter} apparaît dans {word}\",\n    \"Compte les {letter} dans {word}\",\n    # German\n    \"Wie viele {letter} sind in {word}\",\n    \"Wie oft kommt {letter} in {word} vor\",\n    \"Zähle die {letter} in {word}\",\n    # Japanese\n    \"{word}に{letter}は何個ありますか\",\n    \"{word}の中に{letter}がいくつ\",\n    \"{word}に{letter}が何回出てくる\",\n]\n\nclass SpellingBee(Task):\n\n    def __init__(self, size=1000, split=\"train\", **kwargs):\n        super().__init__(**kwargs)\n        assert split in [\"train\", \"test\"], \"SpellingBee split must be train|test\"\n        self.size = size\n        self.split = split\n        filename = WORD_LIST_URL.split(\"/\")[-1]\n        word_list_path = download_file_with_lock(WORD_LIST_URL, filename)\n        with open(word_list_path, 'r', encoding='utf-8') as f:\n            words = [line.strip() for line in f]\n        self.words = words\n\n    @property\n    def eval_type(self):\n        return 'generative'\n\n    def num_examples(self):\n        return self.size\n\n    def get_example(self, index):\n        seed = index if self.split == 'train' else TEST_RANDOM_SEED_OFFSET + index\n        rng = random.Random(seed)\n\n        # pick a random word\n        word = rng.choice(self.words)\n        # pick a letter from it (90%) or a random letter (10%)\n        letter = rng.choice(word) if rng.random() < 0.9 else rng.choice(LETTERS)\n\n        # get the correct answer by simply counting\n        count = word.count(letter)\n\n        # create a user message, with a bunch of variations as data augmentation\n        template = rng.choice(USER_MSG_TEMPLATES)\n        # 30% chance to lowercase the template (lazy people don't use shift)\n        if rng.random() < 0.3:\n            template = template.lower()\n        quote_options = ['', \"'\", '\"']\n        letter_quote = rng.choice(quote_options) # is the letter quoted?\n        word_quote = rng.choice(quote_options) # is the word quoted?\n        letter_wrapped = f\"{letter_quote}{letter}{letter_quote}\"\n        word_wrapped = f\"{word_quote}{word}{word_quote}\"\n        user_msg = template.format(letter=letter_wrapped, word=word_wrapped)\n        if rng.random() < 0.5: # 50% of people don't even use question marks\n            user_msg += \"?\"\n\n        # Now create the ideal assistant response - build as parts (text + tool calls)\n        assistant_parts = []\n        word_letters = \",\".join(list(word))\n        manual_text = f\"\"\"We are asked to find the number '{letter}' in the word '{word}'. Let me try a manual approach first.\n\nFirst spell the word out:\n{word}:{word_letters}\n\nThen count the occurrences of '{letter}':\n\"\"\"\n        # Little simulated loop of the solution process\n        # TODO: This is where the fun starts, we could simulate cute little mistakes\n        # and get the model to review its work and recover from them.\n        # You might of course hope this could arise in RL too, but realistically you'd want to help it out a bit.\n        running_count = 0\n        for i, char in enumerate(word, 1):\n            if char == letter:\n                running_count += 1\n                # note: there deliberately cannot be a space here between i and char\n                # because this would create a different token! (e.g. \" a\" and \"a\" are different tokens)\n                manual_text += f\"{i}:{char} hit! count={running_count}\\n\"\n            else:\n                manual_text += f\"{i}:{char}\\n\"\n\n        manual_text += f\"\\nThis gives us {running_count}.\"\n        assistant_parts.append({\"type\": \"text\", \"text\": manual_text})\n        # Part 2: Python verification\n        assistant_parts.append({\"type\": \"text\", \"text\": \"\\n\\nLet me double check this using Python:\\n\\n\"})\n        # Part 3: Python tool call\n        python_expr = f\"'{word}'.count('{letter}')\"\n        assistant_parts.append({\"type\": \"python\", \"text\": python_expr})\n        # Part 4: Python output\n        assistant_parts.append({\"type\": \"python_output\", \"text\": str(count)})\n        # Part 5: Final answer\n        assistant_parts.append({\"type\": \"text\", \"text\": f\"\\n\\nPython gives us {count}.\\n\\nMy final answer is:\\n\\n#### {count}\"})\n\n        # return the full conversation\n        messages = [\n            {\"role\": \"user\", \"content\": user_msg},\n            {\"role\": \"assistant\", \"content\": assistant_parts}\n        ]\n        conversation = {\n            \"messages\": messages,\n        }\n        return conversation\n\n    def evaluate(self, conversation, assistant_response):\n        \"\"\"\n        Given (conversation, completion), return evaluation outcome (0 = wrong, 1 = correct)\n        Identical to gsm8k's evaluation.\n        \"\"\"\n        assert isinstance(assistant_response, str), \"Assuming simple string response for now\"\n        # First extract the ground truth answer from the conversation\n        assistant_message = conversation['messages'][-1]\n        assert assistant_message['role'] == \"assistant\", \"Last message must be from the Assistant\"\n        assert isinstance(assistant_message['content'], list), \"This is expected to be a list of parts\"\n        # The last text part contains the final answer with ####\n        last_text_part = assistant_message['content'][-1]['text']\n        # Extract both the ground truth answer and the predicted answer\n        ref_num = extract_answer(last_text_part)\n        pred_num = extract_answer(assistant_response)\n        # Compare and return the success as int\n        is_correct = int(pred_num == ref_num)\n        return is_correct\n\n    def reward(self, conversation, assistant_response):\n        \"\"\" Use simple 0-1 reward just like gsm8k.\"\"\"\n        is_correct = self.evaluate(conversation, assistant_response)\n        is_correct_float = float(is_correct)\n        return is_correct_float\n\n\nclass SimpleSpelling(Task):\n    \"\"\"Much simpler task designed to get the model to just practice spelling words.\"\"\"\n\n    def __init__(self, size=1000, split=\"train\", **kwargs):\n        super().__init__(**kwargs)\n        assert split in [\"train\", \"test\"], \"SpellingBee split must be train|test\"\n        self.size = size\n        self.split = split\n        filename = WORD_LIST_URL.split(\"/\")[-1]\n        word_list_path = download_file_with_lock(WORD_LIST_URL, filename)\n        with open(word_list_path, 'r', encoding='utf-8') as f:\n            words = [line.strip() for line in f]\n        rng = random.Random(42)\n        rng.shuffle(words) # use a different word order than the SpellingBee task\n        self.words = words\n\n    @property\n    def eval_type(self):\n        return 'generative'\n\n    def num_examples(self):\n        return self.size\n\n    def get_example(self, index):\n        seed = index if self.split == 'train' else TEST_RANDOM_SEED_OFFSET + index\n        rng = random.Random(seed)\n        # pick a random word\n        word = rng.choice(self.words)\n        word_letters = \",\".join(list(word))\n        # return the full conversation\n        messages = [\n            {\"role\": \"user\", \"content\": f\"Spell the word: {word}\"},\n            {\"role\": \"assistant\", \"content\": f\"{word}:{word_letters}\"}\n        ]\n        conversation = {\n            \"messages\": messages,\n        }\n        return conversation\n\n\nif __name__ == \"__main__\":\n\n    # preview the SpellingBee task, first 10 examples\n    task = SpellingBee()\n    for i in range(10):\n        ex = task.get_example(i)\n        print(\"=\" * 100)\n        print(ex['messages'][0]['content'])\n        print(\"-\" * 100)\n        # Assistant content is now a list of parts\n        assistant_parts = ex['messages'][1]['content']\n        for part in assistant_parts:\n            if part['type'] == 'text':\n                print(part['text'], end='')\n            elif part['type'] == 'python':\n                print(f\"<<{part['text']}=\", end='')\n            elif part['type'] == 'python_output':\n                print(f\"{part['text']}>>\", end='')\n        print()\n        print(\"-\" * 100)\n\n    # # preview the SimpleSpelling task, first 10 examples\n    # task = SimpleSpelling()\n    # for i in range(10):\n    #     ex = task.get_example(i)\n    #     print(\"=\" * 100)\n    #     print(ex['messages'][0]['content'])\n    #     print(\"-\" * 100)\n    #     print(ex['messages'][1]['content'])\n\n    # # also scrutinize the tokenization (last example only)\n    # from nanochat.tokenizer import get_tokenizer\n    # tokenizer = get_tokenizer()\n    # ids, mask = tokenizer.render_conversation(ex)\n    # print(tokenizer.visualize_tokenization(ids, mask, with_token_id=True))\n"
  },
  {
    "path": "tests/test_attention_fallback.py",
    "content": "\"\"\"\nTest Flash Attention unified interface - verify FA3 and SDPA produce identical results.\n\nRun: python -m pytest tests/test_attention_fallback.py -v -s\n\nNote on test structure:\n    Tests are split into two classes due to dtype/device constraints:\n\n    1. TestFA3VsSDPA: Comparison tests that run both FA3 and SDPA on the same inputs\n       and verify they produce identical results. These require a Hopper GPU (FA3 only\n       works on sm90+) and use bfloat16 (FA3 doesn't support float32).\n\n    2. TestSDPAOnly: Tests that only exercise the SDPA fallback path. These can run\n       on any device (CUDA, CPU, MPS) with the appropriate dtype for that device.\n\"\"\"\nimport torch\nimport pytest\nimport nanochat.flash_attention as fa_module\nfrom nanochat.flash_attention import flash_attn, HAS_FA3\nfrom nanochat.engine import KVCache\n\n\ndef set_impl(impl):\n    \"\"\"Set the implementation override ('fa3', 'sdpa', or None for auto) and re-resolve USE_FA3.\"\"\"\n    fa_module._override_impl = impl\n    fa_module.USE_FA3 = fa_module._resolve_use_fa3()\n\n\ndef run_both_impls(fn):\n    \"\"\"Run a function with both FA3 and SDPA, return both outputs.\"\"\"\n    set_impl('fa3')\n    out_fa3 = fn()\n    set_impl('sdpa')\n    out_sdpa = fn()\n    set_impl(None)  # reset\n    return out_fa3, out_sdpa\n\n\ndef assert_close(t1, t2, name, atol=1e-2, rtol=1e-2):\n    \"\"\"Assert two tensors are close, with helpful error message.\"\"\"\n    max_diff = (t1 - t2).abs().max().item()\n    mean_diff = (t1 - t2).abs().mean().item()\n    assert torch.allclose(t1, t2, atol=atol, rtol=rtol), \\\n        f\"{name}: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\"\n    return max_diff, mean_diff\n\n\n# =============================================================================\n# FA3 vs SDPA comparison tests (require Hopper GPU)\n# =============================================================================\n@pytest.mark.skipif(not HAS_FA3, reason=\"FA3 required to compare implementations\")\nclass TestFA3VsSDPA:\n    \"\"\"Compare FA3 and SDPA produce identical results. Requires Hopper GPU.\"\"\"\n\n    DEVICE = \"cuda\"\n    DTYPE = torch.bfloat16\n\n    def test_basic_causal(self):\n        \"\"\"Basic causal attention.\"\"\"\n        B, T, H, D = 2, 64, 4, 32\n        q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"basic_causal\")\n        print(f\"basic_causal: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_full_context(self):\n        \"\"\"Full context (window_size=-1).\"\"\"\n        B, T, H, D = 2, 128, 4, 32\n        q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(-1, -1))\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"full_context\")\n        print(f\"full_context: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_sliding_window(self):\n        \"\"\"Sliding window attention.\"\"\"\n        B, T, H, D = 2, 128, 4, 32\n        window = 32\n        q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(window, 0))\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"sliding_window\")\n        print(f\"sliding_window: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_gqa(self):\n        \"\"\"Group Query Attention (fewer KV heads than Q heads).\"\"\"\n        B, T, D = 2, 64, 32\n        n_heads = 8\n        n_kv_heads = 2\n\n        q = torch.randn(B, T, n_heads, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T, n_kv_heads, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T, n_kv_heads, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"gqa\")\n        print(f\"gqa: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_larger_model(self):\n        \"\"\"Larger dimensions closer to real model.\"\"\"\n        B, T, H, D = 4, 256, 12, 64\n        q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            return flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(-1, -1))\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"larger_model\")\n        print(f\"larger_model: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_kvcache_prefill(self):\n        \"\"\"Test prefill (inserting multiple tokens into empty cache).\"\"\"\n        B, T_max, H, D = 2, 64, 4, 32\n        T_prefill = 16\n\n        q = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            k_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)\n            v_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)\n            cache_seqlens = torch.zeros(B, dtype=torch.int32, device=self.DEVICE)\n            return flash_attn.flash_attn_with_kvcache(\n                q, k_cache, v_cache, k=k, v=v,\n                cache_seqlens=cache_seqlens,\n                causal=True, window_size=(T_max, 0)\n            )\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"prefill\")\n        print(f\"prefill: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_kvcache_single_token(self):\n        \"\"\"Test single token generation (cache already has content).\"\"\"\n        B, T_max, H, D = 2, 64, 4, 32\n        T_prefill = 16\n\n        k_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        q_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            k_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)\n            v_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)\n            k_cache[:, :T_prefill, :, :] = k_init\n            v_cache[:, :T_prefill, :, :] = v_init\n            cache_seqlens = torch.full((B,), T_prefill, dtype=torch.int32, device=self.DEVICE)\n            return flash_attn.flash_attn_with_kvcache(\n                q_single, k_cache, v_cache, k=k_single, v=v_single,\n                cache_seqlens=cache_seqlens,\n                causal=True, window_size=(T_max, 0)\n            )\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"single_token\")\n        print(f\"single_token: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_kvcache_single_token_sliding_window(self):\n        \"\"\"Test single token decode with sliding window smaller than cache size.\n\n        This catches the bug where SDPA ignores window_size during Tq=1 decode.\n        When window < Tk, FA3 only attends to the last (window+1) tokens,\n        but SDPA was attending to all cached tokens.\n        \"\"\"\n        B, T_max, H, D = 2, 64, 4, 32\n        T_prefill = 32  # Enough tokens to exceed window\n        window = 8      # Window SMALLER than cache size\n\n        k_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v_init = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        q_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            k_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)\n            v_cache = torch.zeros(B, T_max, H, D, device=self.DEVICE, dtype=self.DTYPE)\n            k_cache[:, :T_prefill, :, :] = k_init\n            v_cache[:, :T_prefill, :, :] = v_init\n            cache_seqlens = torch.full((B,), T_prefill, dtype=torch.int32, device=self.DEVICE)\n            return flash_attn.flash_attn_with_kvcache(\n                q_single, k_cache, v_cache, k=k_single, v=v_single,\n                cache_seqlens=cache_seqlens,\n                causal=True, window_size=(window, 0)  # window=8 < Tk=33\n            )\n\n        y_fa3, y_sdpa = run_both_impls(run)\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"single_token_sliding_window\")\n        print(f\"single_token_sliding_window: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n    def test_backward_gradients_match(self):\n        \"\"\"Verify gradients are similar between FA3 and SDPA.\"\"\"\n        B, T, H, D = 2, 32, 4, 16\n\n        q_data = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k_data = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v_data = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        def run():\n            q = q_data.clone().requires_grad_(True)\n            k = k_data.clone().requires_grad_(True)\n            v = v_data.clone().requires_grad_(True)\n            y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))\n            loss = y.sum()\n            loss.backward()\n            return y.detach(), q.grad.detach(), k.grad.detach(), v.grad.detach()\n\n        set_impl('fa3')\n        y_fa3, q_grad_fa3, k_grad_fa3, v_grad_fa3 = run()\n        set_impl('sdpa')\n        y_sdpa, q_grad_sdpa, k_grad_sdpa, v_grad_sdpa = run()\n        set_impl(None)\n\n        max_diff, mean_diff = assert_close(y_fa3, y_sdpa, \"backward_output\")\n        print(f\"backward_output: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n        max_diff, mean_diff = assert_close(q_grad_fa3, q_grad_sdpa, \"q_grad\", atol=0.05, rtol=0.05)\n        print(f\"q_grad: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n        max_diff, mean_diff = assert_close(k_grad_fa3, k_grad_sdpa, \"k_grad\", atol=0.05, rtol=0.05)\n        print(f\"k_grad: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n        max_diff, mean_diff = assert_close(v_grad_fa3, v_grad_sdpa, \"v_grad\", atol=0.05, rtol=0.05)\n        print(f\"v_grad: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}\")\n\n\n# =============================================================================\n# SDPA-only tests (run on any device)\n# =============================================================================\nclass TestSDPAOnly:\n    \"\"\"Test SDPA fallback works correctly. Runs on any device.\"\"\"\n\n    DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    DTYPE = torch.bfloat16 if torch.cuda.is_available() else torch.float32\n\n    def test_basic_forward(self):\n        \"\"\"Test SDPA forward pass produces valid output.\"\"\"\n        set_impl('sdpa')\n        B, T, H, D = 2, 64, 4, 32\n        q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))\n\n        assert y.shape == (B, T, H, D)\n        assert not torch.isnan(y).any(), \"Output contains NaN\"\n        set_impl(None)\n\n    def test_backward(self):\n        \"\"\"Test gradients flow through SDPA.\"\"\"\n        set_impl('sdpa')\n        B, T, H, D = 2, 32, 4, 16\n        q = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE, requires_grad=True)\n        k = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE, requires_grad=True)\n        v = torch.randn(B, T, H, D, device=self.DEVICE, dtype=self.DTYPE, requires_grad=True)\n\n        y = flash_attn.flash_attn_func(q, k, v, causal=True, window_size=(T, 0))\n        loss = y.sum()\n        loss.backward()\n\n        assert q.grad is not None, \"No gradient for q\"\n        assert k.grad is not None, \"No gradient for k\"\n        assert v.grad is not None, \"No gradient for v\"\n        assert not torch.isnan(q.grad).any(), \"NaN in q gradient\"\n        set_impl(None)\n\n    def test_kvcache(self):\n        \"\"\"Test SDPA with KV cache.\"\"\"\n        set_impl('sdpa')\n        B, T_max, H, D = 2, 64, 4, 32\n        n_layers = 1\n\n        cache = KVCache(\n            batch_size=B, num_heads=H, seq_len=T_max, head_dim=D,\n            num_layers=n_layers, device=self.DEVICE, dtype=self.DTYPE\n        )\n        k_cache, v_cache = cache.get_layer_cache(0)\n\n        # Prefill\n        T_prefill = 16\n        q = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v = torch.randn(B, T_prefill, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        y = flash_attn.flash_attn_with_kvcache(\n            q, k_cache, v_cache, k=k, v=v,\n            cache_seqlens=cache.cache_seqlens,\n            causal=True, window_size=(T_max, 0)\n        )\n        cache.advance(T_prefill)\n\n        assert y.shape == (B, T_prefill, H, D)\n        assert cache.get_pos() == T_prefill\n\n        # Generate single token\n        q_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        k_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n        v_single = torch.randn(B, 1, H, D, device=self.DEVICE, dtype=self.DTYPE)\n\n        y_single = flash_attn.flash_attn_with_kvcache(\n            q_single, k_cache, v_cache, k=k_single, v=v_single,\n            cache_seqlens=cache.cache_seqlens,\n            causal=True, window_size=(T_max, 0)\n        )\n        cache.advance(1)\n\n        assert y_single.shape == (B, 1, H, D)\n        assert cache.get_pos() == T_prefill + 1\n        set_impl(None)\n\n\n# =============================================================================\n# Override mechanism tests\n# =============================================================================\nclass TestOverrideMechanism:\n    \"\"\"Test that the override mechanism works correctly.\"\"\"\n\n    @pytest.mark.skipif(not HAS_FA3, reason=\"FA3 required\")\n    def test_override_fa3(self):\n        \"\"\"Test that override='fa3' uses FA3.\"\"\"\n        set_impl('fa3')\n        assert fa_module.USE_FA3 == True\n        set_impl(None)\n\n    def test_override_sdpa(self):\n        \"\"\"Test that override='sdpa' uses SDPA.\"\"\"\n        set_impl('sdpa')\n        assert fa_module.USE_FA3 == False\n        set_impl(None)\n\n    def test_override_auto(self):\n        \"\"\"Test that override=None uses auto-detection.\"\"\"\n        set_impl(None)\n        assert fa_module.USE_FA3 == HAS_FA3\n\n\nif __name__ == \"__main__\":\n    print(f\"PyTorch version: {torch.__version__}\")\n    print(f\"CUDA available: {torch.cuda.is_available()}\")\n    if torch.cuda.is_available():\n        print(f\"CUDA device: {torch.cuda.get_device_name()}\")\n        major, minor = torch.cuda.get_device_capability()\n        print(f\"Compute capability: {major}.{minor}\")\n    print(f\"HAS_FA3: {HAS_FA3}\")\n    print()\n\n    pytest.main([__file__, \"-v\", \"-s\"])\n"
  },
  {
    "path": "tests/test_engine.py",
    "content": "\"\"\"\nTest Engine class. Example run:\n\npython -m pytest tests/test_engine.py -v\n\"\"\"\n\nimport torch\nfrom nanochat.engine import KVCache, Engine\nfrom dataclasses import dataclass\n\n\n# -----------------------------------------------------------------------------\n# Mock classes for testing Engine without loading a real model\n\n@dataclass\nclass MockConfig:\n    \"\"\"Minimal config for Engine tests.\"\"\"\n    n_kv_head: int = 4\n    n_head: int = 4\n    n_embd: int = 64\n    n_layer: int = 2\n    sequence_len: int = 128\n\n\nclass MockModel:\n    \"\"\"\n    Mock model that returns uniform logits over the vocab.\n    This ensures that with temperature > 0, different samples should\n    (with very high probability) produce different tokens.\n    \"\"\"\n    def __init__(self, vocab_size=262):  # 256 bytes + 6 special tokens\n        self.vocab_size = vocab_size\n        self.config = MockConfig()\n        self._device = torch.device(\"cpu\")\n\n    def get_device(self):\n        return self._device\n\n    def forward(self, ids, kv_cache=None):\n        \"\"\"Return uniform logits so sampling is spread across vocab.\"\"\"\n        B, T = ids.shape\n        # With FA3, flash_attn_with_kvcache updates cache in-place and we advance position\n        if kv_cache is not None:\n            kv_cache.advance(T)\n        # Uniform logits -> equal probability for all tokens\n        logits = torch.zeros(B, T, self.vocab_size)\n        return logits\n\n\nclass ByteTokenizer:\n    \"\"\"\n    Simple byte-level tokenizer for testing.\n    Tokens 0-255 are raw bytes, 256+ are special tokens.\n    \"\"\"\n    def __init__(self):\n        # Special tokens start at 256\n        self._special_tokens = {\n            \"<|python_start|>\": 256,\n            \"<|python_end|>\": 257,\n            \"<|output_start|>\": 258,\n            \"<|output_end|>\": 259,\n            \"<|assistant_end|>\": 260,\n            \"<|bos|>\": 261,\n        }\n        self._bos = 261\n\n    def encode_special(self, s):\n        return self._special_tokens[s]\n\n    def get_bos_token_id(self):\n        return self._bos\n\n    def encode(self, s, prepend=None):\n        tokens = list(s.encode(\"utf-8\"))  # bytes 0-255\n        if prepend is not None:\n            tokens = [prepend] + tokens\n        return tokens\n\n    def decode(self, tokens):\n        # Filter out special tokens before decoding\n        byte_tokens = [t for t in tokens if t < 256]\n        return bytes(byte_tokens).decode(\"utf-8\", errors=\"replace\")\n\ndef test_kv_cache_basic():\n    \"\"\"Test basic KVCache functionality for FA3.\"\"\"\n    batch_size = 2\n    num_heads = 3\n    seq_len = 64\n    head_dim = 5\n    num_layers = 6\n\n    kv_cache = KVCache(\n        batch_size=batch_size,\n        num_heads=num_heads,\n        seq_len=seq_len,\n        head_dim=head_dim,\n        num_layers=num_layers,\n        device=\"cpu\",\n        dtype=torch.float32,\n    )\n\n    # Check initial state\n    assert kv_cache.get_pos() == 0\n    assert kv_cache.k_cache.shape == (num_layers, batch_size, seq_len, num_heads, head_dim)\n    assert kv_cache.v_cache.shape == (num_layers, batch_size, seq_len, num_heads, head_dim)\n\n    # Test advance\n    kv_cache.advance(10)\n    assert kv_cache.get_pos() == 10\n\n    kv_cache.advance(5)\n    assert kv_cache.get_pos() == 15\n\n    # Test reset\n    kv_cache.reset()\n    assert kv_cache.get_pos() == 0\n\n    # Test get_layer_cache returns correct views\n    k_layer0, v_layer0 = kv_cache.get_layer_cache(0)\n    assert k_layer0.shape == (batch_size, seq_len, num_heads, head_dim)\n    assert v_layer0.shape == (batch_size, seq_len, num_heads, head_dim)\n\n\ndef test_kv_cache_prefill():\n    \"\"\"Test KVCache.prefill() copies data correctly.\"\"\"\n    batch_size = 1\n    num_heads = 4\n    head_dim = 8\n    num_layers = 2\n\n    # Create source cache and advance it\n    src_cache = KVCache(\n        batch_size=batch_size, num_heads=num_heads, seq_len=32,\n        head_dim=head_dim, num_layers=num_layers, device=\"cpu\", dtype=torch.float32,\n    )\n    # Write some data to source cache\n    src_cache.k_cache[0, 0, :16, :, :] = 1.0\n    src_cache.v_cache[0, 0, :16, :, :] = 2.0\n    src_cache.advance(16)\n\n    # Create destination cache with larger seq_len\n    dst_cache = KVCache(\n        batch_size=batch_size, num_heads=num_heads, seq_len=64,\n        head_dim=head_dim, num_layers=num_layers, device=\"cpu\", dtype=torch.float32,\n    )\n\n    # Prefill\n    dst_cache.prefill(src_cache)\n\n    # Check position was copied\n    assert dst_cache.get_pos() == 16\n\n    # Check data was copied\n    assert (dst_cache.k_cache[0, 0, :16, :, :] == 1.0).all()\n    assert (dst_cache.v_cache[0, 0, :16, :, :] == 2.0).all()\n\n\ndef test_multi_sample_first_token_diversity():\n    \"\"\"\n    Test that when generating multiple samples, each sample gets an independently\n    sampled first token (not a broadcast of the same token to all rows).\n\n    Previously, the first token after prefill was sampled once and broadcast to all\n    rows, causing all samples to start identically. The fix expands the prefill logits\n    to num_samples and samples independently for each row.\n\n    With uniform logits over 262 tokens and 16 samples, the probability that all\n    samples independently pick the same token is (1/262)^15 ≈ 10^-36. So if they're\n    all identical, it indicates tokens are being broadcast instead of independently sampled.\n    \"\"\"\n    model = MockModel(vocab_size=262)\n    tokenizer = ByteTokenizer()\n    engine = Engine(model, tokenizer)\n\n    # Generate 16 samples with temperature=1.0 (stochastic sampling)\n    prompt_tokens = [261, 72, 101, 108, 108, 111]  # <bos> + \"Hello\"\n    num_samples = 16\n\n    # Collect the first generated token from each sample\n    first_tokens = []\n    gen = engine.generate(\n        prompt_tokens,\n        num_samples=num_samples,\n        max_tokens=1,  # We only need the first token\n        temperature=1.0,\n        seed=42,\n    )\n    for token_column, token_masks in gen:\n        first_tokens = token_column  # This is the first (and only) yield\n\n    # With uniform distribution and 16 samples, they should NOT all be identical\n    # If they are all identical, the bug exists (broadcasting instead of sampling)\n    unique_tokens = set(first_tokens)\n    assert len(unique_tokens) > 1, (\n        f\"All {num_samples} samples got the same first token ({first_tokens[0]}). \"\n        f\"With uniform logits, this is statistically impossible (~10^-36 probability) \"\n        f\"unless tokens are being broadcast instead of independently sampled.\"\n    )\n\n\ndef test_seed_reproducibility():\n    \"\"\"Same seed must produce identical output.\"\"\"\n    model = MockModel()\n    engine = Engine(model, ByteTokenizer())\n    prompt = [261, 72, 101, 108, 108, 111]  # <bos> + \"Hello\"\n\n    for seed in [1, 42, 123, 999]:\n        r1, _ = engine.generate_batch(prompt, max_tokens=5, seed=seed)\n        r2, _ = engine.generate_batch(prompt, max_tokens=5, seed=seed)\n        r3, _ = engine.generate_batch(prompt, max_tokens=5, seed=seed)\n        assert r1 == r2 == r3, \"Same seed must produce identical output for the same prompt.\"\n\n\ndef test_temperature_zero_determinism():\n    \"\"\"Temperature=0 is deterministic regardless of seed.\"\"\"\n    model = MockModel()\n    engine = Engine(model, ByteTokenizer())\n    prompt = [261, 72, 101, 108, 108, 111]\n\n    r1, _ = engine.generate_batch(prompt, temperature=0.0, max_tokens=5, seed=1)\n    r2, _ = engine.generate_batch(prompt, temperature=0.0, max_tokens=5, seed=42)\n    r3, _ = engine.generate_batch(prompt, temperature=0.0, max_tokens=5, seed=123)\n    assert r1 == r2 == r3, \"Temperature=0 must result in the same output for the same prompt regardless of seed.\"\n\n\ndef test_max_tokens_respected():\n    \"\"\"Generation stops at max_tokens limit.\"\"\"\n    model = MockModel()\n    engine = Engine(model, ByteTokenizer())\n    prompt = [261, 72, 101, 108, 108, 111]\n\n    for max_tokens in [1, 4, 16, 64]:\n        results, _ = engine.generate_batch(prompt, max_tokens=max_tokens)\n        num_generated_tokens = len(results[0]) - len(prompt)\n        assert num_generated_tokens <= max_tokens, f\"Generated {num_generated_tokens} tokens, expected max_tokens={max_tokens} or less.\"\n\n\ndef test_num_samples_count():\n    \"\"\"num_samples=N produces exactly N sequences.\"\"\"\n    model = MockModel()\n    engine = Engine(model, ByteTokenizer())\n    prompt = [261, 72, 101, 108, 108, 111]\n\n    for num_samples in [1, 4, 16, 64]:\n        results, _ = engine.generate_batch(prompt, num_samples=num_samples, max_tokens=3)\n        assert len(results) == num_samples, f\"Expected {num_samples} sequences from {num_samples} samples, got {len(results)}\"\n\n\ndef test_different_seeds_introduce_variation_when_temperature_nonzero():\n    \"\"\"With temperature > 0, different seeds should introduce sampling variation.\"\"\"\n    model = MockModel()\n    engine = Engine(model, ByteTokenizer())\n    prompt = [261, 72, 101, 108, 108, 111]  # <bos> + \"Hello\"\n\n    outputs = set()\n\n    for seed in [1, 42, 123, 999, 1000, 1001, 1002, 1003, 1004, 1005]:\n        results, _ = engine.generate_batch(\n            prompt,\n            temperature=1.0,\n            max_tokens=5,\n            seed=seed,\n        )\n        outputs.add(tuple(results[0]))\n\n    # Sanity check: sampling actually introduces variation\n    assert len(outputs) > 1, \"All seeds produced the same output which is statistically highly improbable.\"\n"
  }
]