Metadata-Version: 2.5
Name: buildMyGPT
Version: 1.20261129.1151348
Summary: Build your own small GPT: swap in your data, pretrain, fine-tune it for a task (e.g. article → title), evaluate against classic baselines — on a Mac or a Colab A100, with a bundled Claude Code skill.
Project-URL: Homepage, https://github.com/changyy/py-buildMyGPT
Project-URL: Repository, https://github.com/changyy/py-buildMyGPT
Project-URL: Issues, https://github.com/changyy/py-buildMyGPT/issues
Project-URL: Changelog, https://github.com/changyy/py-buildMyGPT/blob/main/CHANGELOG.md
Author: Yuan-Yi Chang
License: MIT
License-File: LICENSE
Keywords: claude-code,colab,education,fine-tuning,gpt,llm,micrograd,nanogpt,transformer
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: numpy>=1.26
Requires-Dist: requests>=2.31
Requires-Dist: tiktoken>=0.7
Requires-Dist: torch>=2.2
Description-Content-Type: text/markdown

# buildMyGPT

![PyPI](https://img.shields.io/pypi/v/buildmygpt.svg)
[![PyPI Downloads](https://static.pepy.tech/badge/buildmygpt)](https://pepy.tech/projects/buildmygpt)
[![Tests](https://github.com/changyy/py-buildMyGPT/actions/workflows/ci.yml/badge.svg)](https://github.com/changyy/py-buildMyGPT/actions/workflows/ci.yml)

Build your own small GPT: swap in your data, pretrain, fine-tune it for a task and measure it — on a Mac for quick
runs, on a Colab GPU (L4 / A100) for real ones, all from the terminal. The model and training loop follow
[nanoGPT](https://github.com/karpathy/nanoGPT); this project is not affiliated with it.

```bash
buildmygpt init mineGPT && cd mineGPT
scripts/title_demo.sh                                    # public data: a poem goes in, its title comes out
buildmygpt compose runs/tang_char_mac --title 夜雨思歸 --form 五言絕句
```

## Features

- 🧪 **Learn by building** — micrograd, an annotated GPT, hand-written attention checked against PyTorch, ablation switches, tokenizer experiments
- 📚 **Public, reproducible data** — 全唐詩 (Complete Tang Poems) at a pinned commit, with a sha256 fingerprint so everyone trains on byte-identical data
- 🎯 **Task models** — pretrain, then fine-tune on input → output pairs (poem → title), evaluated against TF-IDF keyword extraction
- ✍️ **Compose** — generate candidate poems from a title and rank them like search results (form, imagery, originality, fluency)
- ☁️ **Cloud GPU from the terminal** — Google's official Colab CLI: preflight check, automatic retry when no GPU is free, early stopping, guaranteed shutdown, compute units recorded
- 📦 **Export / import** — trained models as one `.tar.xz` with a sha256 manifest (30M parameters → 54 MB)
- 🤖 **Workspace + Claude Code skill** — `buildmygpt init` creates plan, journal, configs and scripts, and teaches an AI assistant the workflow

## Installation

```bash
pip install buildMyGPT        # or: uv tool install buildMyGPT
buildmygpt doctor             # python / torch / cuda | mps check
```

## Quick start

```bash
buildmygpt init mineGPT && cd mineGPT
scripts/quickstart.sh --quick     # the whole pipeline once: 16 s on a MacBook M1 Pro
scripts/title_demo.sh             # 全唐詩: prepare → pretrain → fine-tune poem → title → evaluate (~6 min on a MacBook M1 Pro)
```

`quickstart.sh` runs every stage once — `doctor`, micrograd and attention checks against PyTorch, tiny shakespeare, a
short training run — and files the log under `notes/` with a `JOURNAL.md` draft built from the real numbers.

## Mac or cloud GPU?

The same 唐詩GPT (30.05M parameters, 8 layers × 512 dims, 全唐詩, batch 64 × 256 characters, early stopping),
trained from scratch on three machines:

![Training time of the same Tang-poetry GPT on a MacBook M1 Pro, a Colab L4 and a Colab A100](https://raw.githubusercontent.com/changyy/py-buildMyGPT/main/docs/images/benchmark.png)

| | MacBook M1 Pro (32GB) | Colab L4 | Colab A100 (40GB) |
|---|---:|---:|---:|
| Precision | float32 (MPS) | bf16 + `torch.compile` | bf16 + `torch.compile` |
| Time per step | 1,146 ms | 133 ms | 27 ms |
| Throughput | ~14k tokens/s | ~123k tokens/s | ~607k tokens/s |
| **Training time** | **96.9 min** | **12.1 min** | **3.2 min** |
| **Best val loss** | **3.8572** | **3.8618** | **3.8527** |
| MFU | — | 17–22% | 29–39% |
| Cost | electricity | 0.33 compute units | 0.40 compute units |
| Waiting for a GPU (not billed) | — | 0–17 min | 19 min |

- **The cloud buys time, not quality.** All three reach the same val loss (within run-to-run noise) at step 2,500 and early-stop at 4,500.
- **The data is the ceiling.** 4.15M characters carry a 30M-parameter model for ~10 passes; after that it memorises. Without early stopping, the first L4 run took 24.9 min and 0.85 units for the same best model.
- **Train in the cloud, use on the Mac.** The model comes back as 70 MB of fp16 weights; sampling and `compose` run locally.
- **Availability is the hidden cost.** A100 requests returned "Service Unavailable" several times; `--retry-for` got one on the second round the next morning.

Full write-up (in Traditional Chinese): [同一個唐詩GPT，MacBook M1 Pro、Colab L4 與 A100 實測比較](https://blog.changyy.app/2026/11/tang-gpt-macbook-m1-pro-vs-colab-l4.html)

## Colab GPU from the terminal

Uses Google's official [Colab CLI](https://github.com/googlecolab/google-colab-cli) (macOS / Linux) and your own Colab compute units.

```bash
uv tool install google-colab-cli
colab usage                                          # one-time sign-in (paste the code from the browser)
buildmygpt colab check tang_char_a100                # preflight: CLI, sign-in + remaining units, data, package
buildmygpt colab run tang_char_a100                  # default GPU: L4 (cheaper, easier to get)
buildmygpt colab run tang_char_a100 --gpu A100,L4    # ask for an A100, fall back to L4
buildmygpt colab run tang_char_a100 --retry-for 2h   # no free GPU? keep trying every 5 min (waiting is free)
buildmygpt colab usage                               # remaining compute units
buildmygpt colab watch --until-idle                  # balance and running VMs every 5 min; warns about long-running VMs
```

`colab run` records your compute units, starts a GPU, runs a self-contained job on it (installs buildMyGPT, builds
public data on the VM, trains with early stopping), downloads the log, sample and model (fp16 weights + vocabulary) to
`runs/<run>/`, and always stops the VM — even on errors or Ctrl+C. The `*_a100` configs only set model size, bf16 and
`torch.compile`; they run on any recent CUDA GPU. `--wheel auto` ships this source checkout instead of the PyPI release,
`--upload-data` sends a small private dataset, `--dry-run` only writes the job.

## Use and keep your models

```bash
buildmygpt sample runs/tang_char_a100 --start $'春望\n'
buildmygpt compose runs/tang_char_a100 --title 夜雨思歸 --imagery 夜雨,孤燈,故園 --form 五言絕句 -n 40
buildmygpt export runs/tang_char_mac_full --pack     # → one .tar.xz: fp16 weights + vocabulary + log + sha256 manifest
buildmygpt import tang_char_mac_full.tar.xz          # → models/tang_char_mac_full/ (checksums verified)
```

Back up the exported model — it cannot be regenerated. The data does not need a backup: `buildmygpt prepare poetry`
rebuilds it in about a minute and checks the fingerprint (`--no-cache` deletes the downloaded JSON afterwards).

## Your own data

- **Corpus**: write a small script in the workspace's `scripts/` that produces `train.bin` / `val.bin` / `meta.pkl`
  (format in `scripts/README.md`), then `buildmygpt train <config> data_dir=data/<name>`.
- **Task**: write `{"input": ..., "output": ...}` lines to a JSONL file, `buildmygpt prepare pairs` it with your corpus's
  `meta.pkl`, fine-tune with `task="pairs"` + `init_from="finetune"`, and check it with `buildmygpt evaluate`.

## Workspace layout (`buildmygpt init`)

```text
mineGPT/
├── PLAN.md / JOURNAL.md / CLAUDE.md
├── .claude/skills/build-my-gpt/SKILL.md   # Claude Code skill
├── configs/                                # copies of the builtin configs, edit freely
├── colab/train_on_a100.ipynb               # browser alternative to `colab run`
├── notes/                                  # per-stage notes and small results
├── data/  runs/                            # git-ignored
└── scripts/                                # quickstart.sh, title_demo.sh, keep_run.sh, a100_roundtrip.sh + your own
```

## Commands

| command | what it does |
|---|---|
| `init [dir] [--name]` | create a workspace |
| `skill install [--user]` | install the Claude Code skill into `./.claude/skills` or `~/.claude/skills` |
| `eject [workspace]` | copy the whole package into `lab/buildmygpt`; `python -m buildmygpt ...` run from `lab/` uses that copy |
| `where` | print the package source path (read `nanogpt/model.py`) |
| `micrograd gradcheck\|moons` | autograd experiments |
| `attention check` | hand-written attention vs `scaled_dot_product_attention` and the model, causal-mask leak test |
| `attention show <run> --text T` | top attended positions per token (`--layer`, `--head`, `--topk`) |
| `prepare shakespeare` | download tiny shakespeare → `train.bin` / `val.bin` / `meta.pkl` |
| `prepare poetry [--collection tang\|song] [--author 蘇軾]` | chinese-poetry (pinned commit) → LM corpus + content → title pairs; `--no-cache`, `--expect` |
| `prepare pairs --jsonl F --meta M --out D` | your `{"input","output"}` JSONL → pairs reusing an existing vocabulary |
| `tokenizers <corpus.txt>` | char unigram/bigram vs GPT-2 / cl100k / o200k BPE |
| `train <config> [k=v ...]` | train; `--help-keys` lists keys and builtin configs; ablations `use_pos_emb=False`, `causal=False`; fine-tune `task=pairs init_from=finetune init_ckpt=...`; `early_stop_patience` |
| `sample <run> [--seed N]` | generate text from a checkpoint; the same seed gives the same text (default 42) |
| `compose <run> --title T [--imagery a,b] [--form 五言絕句] [-n 20]` | poems from a title, ranked by form / imagery / originality / fluency |
| `complete <run> --text T` | task model: input → output (e.g. poem → title) |
| `evaluate <run> [-n 300]` | task model on val pairs vs TF-IDF keywords and the most common title |
| `export <run> [--pack\|--zip]` | fp16 weights + vocabulary + log in one folder; `--pack` `.tar.xz` / `--zip` with a sha256 manifest |
| `import <archive>` | unpack an exported model into `models/<name>/` and verify every sha256 |
| `summary <run>` | `JOURNAL.md` entry draft from `log.jsonl` |
| `colab check\|run <config> [k=v ...]` | Colab GPU from the terminal: preflight / run (`--gpu`, `--retry-for`, `--wheel auto`, `--upload-data`, `--dry-run`) |
| `colab usage` / `colab watch` | remaining compute units / periodic balance and running-VM check |
| `colab notebook [-o path]` | (re)generate the browser notebook (not yet run on a real Colab; `colab run` is the tested path) |
| `drive push <dataset>` / `drive pull <run>` | Google Drive sync via rclone (not yet run against a real Drive) |

## Credits

Model and training loop follow Andrej Karpathy's [nanoGPT](https://github.com/karpathy/nanoGPT) and
[micrograd](https://github.com/karpathy/micrograd) (MIT), rewritten with explanatory comments.
全唐詩 comes from [chinese-poetry](https://github.com/chinese-poetry/chinese-poetry) (MIT), downloaded at run time.

## License

MIT — see `LICENSE`, which also carries the MIT notices of nanoGPT and micrograd.
