[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-116982":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":11,"openIssues":12,"contributorsCount":12,"subscribersCount":12,"size":12,"stars1d":12,"stars7d":12,"stars30d":12,"stars90d":12,"forks30d":12,"starsTrendScore":12,"compositeScore":12,"rankGlobal":9,"rankLanguage":9,"license":13,"archived":14,"fork":14,"defaultBranch":15,"hasWiki":14,"hasPages":14,"topics":16,"createdAt":9,"pushedAt":9,"updatedAt":27,"readmeContent":28,"aiSummary":9,"trendingCount":12,"starSnapshotCount":12,"syncStatus":29,"lastSyncTime":30,"discoverSource":31},116982,"microgpt","prabeakarve\u002Fmicrogpt","prabeakarve","A from-scratch, dependency-free GPT implementation in pure NumPy: byte-level tokenizer, multi-head self-attention, Adam trainer, and top-k sampler.",null,"Python",51,0,"MIT License",false,"main",[17,18,19,20,21,22,23,24,25,26],"attention","deep-learning","from-scratch","gpt","language-model","llm","machine-learning","numpy","python","transformer","2026-11-25 02:05:52","# MicroGPT\n\n**A GPT you can read end to end in one sitting â€?700 lines of NumPy, no framework, no autograd.**\n\nMicroGPT is a decoder-only Transformer language model implemented from first principles.\nEvery gradient is derived by hand, every shape is annotated, and the whole thing trains on a\nlaptop CPU in about a minute. It exists for one reason: to make the machinery of modern\nlanguage models legible instead of magical.\n\n```\n                      â”Œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?   token ids  â”€â”€â”€â”€â”€â”€â–?â”? tok_emb[idx] + pos_emb[:T]                  â”?                      â””â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?                                          â–?              â”Œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?              â”? Ã— n_layer                                    â”?              â”?  â”Œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?â”?              â”?  â”?x = x + Attention(LN(x))                â”?â”?              â”?  â”?x = x + MLP(LN(x))                      â”?â”?              â”?  â””â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?â”?              â””â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?                                  â–?                      â”Œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?                      â”? LN_f â†?logits = x @ Eáµ€   â”? (weight tying)\n                      â””â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”?```\n\n## Why another tiny GPT\n\nMost \"build GPT from scratch\" projects end up re-implementing an autograd engine, which hides\nthe interesting part behind a second abstraction. MicroGPT keeps the forward pass explicit and\nwrites the backward pass by hand, so the chain rule is visible in the code that uses it. The\ntest suite proves the backward pass correct with central finite differences against every\nparameter class â€?attention projections, both layer norms, the MLP, and the tied embeddings.\n\n## Features\n\n- **Pure NumPy.** One dependency (`numpy`). Runs anywhere Python runs, including CI containers.\n- **Hand-written backward pass.** No autograd, no `torch.autograd`, no graph object.\n- **Causal multi-head self-attention** with residual connections and pre-layer-norm.\n- **Weight tying** between the input embedding and the output projection.\n- **Byte-level tokenizer** â€?256 symbols, no training, exact UTF-8 round-trip.\n- **AdamW** with bias correction, linear warmup, and cosine decay.\n- **Sampling** with temperature, top-k, and a next-token distribution inspector.\n- **Checkpointing** to compressed `.npz` plus a JSON sidecar with the full config and metrics.\n- **14 tests**, including a gradient check with a `2e-4` relative-error bound.\n- **CLI** with `train`, `sample`, `eval`, `info`, and `next` subcommands.\n\n## Install\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fprabeakarve\u002Fmicrogpt.git\ncd microgpt\npython -m pip install -e .\n```\n\nPython 3.10+ and NumPy are the only requirements.\n\n## Quick start\n\nTrain on the bundled corpus (about 8 KB of text, ~60 seconds on a laptop):\n\n```bash\npython -m microgpt train \\\n  --corpus examples\u002Fcorpus.txt \\\n  --out checkpoints\u002Fmodel.npz \\\n  --block-size 96 --n-layer 3 --n-head 4 --n-embd 128 \\\n  --batch-size 16 --steps 1200 --lr 3e-3 --warmup 60\n```\n\nSample from the checkpoint:\n\n```bash\npython -m microgpt sample --ckpt checkpoints\u002Fmodel.npz \\\n  --prompt \"A language model is a probability distribution over\" \\\n  --tokens 200 --temperature 0.7 --top-k 40\n```\n\nInspect what the model thinks comes next:\n\n```bash\npython -m microgpt next --context \"Attention is a lookup that\"\n```\n\nScore a text:\n\n```bash\npython -m microgpt eval --text examples\u002Fcorpus.txt\n```\n\n## Library use\n\n```python\nimport numpy as np\nfrom microgpt import GPT, ByteTokenizer, TrainConfig, train, complete, perplexity\n\ncfg = TrainConfig(corpus=\"examples\u002Fcorpus.txt\", steps=400, n_embd=96, n_layer=2)\nmeta = train(cfg)                       # writes cfg.out and cfg.out + \".json\"\n\nmodel = GPT(vocab_size=256, block_size=64, n_layer=2, n_head=4, n_embd=96)\nloss, grads = model.loss_and_grads(idx, targets)   # idx, targets: int64 (B, T)\n\nprint(complete(model, \"The model learns\", max_new_tokens=120))\nprint(perplexity(model, open(\"examples\u002Fcorpus.txt\").read()))\n```\n\n## What the numbers mean\n\n| Symbol | Meaning |\n| --- | --- |\n| `B` | batch size |\n| `T` | sequence length (`\u003C= block_size`) |\n| `C` | embedding width (`n_embd`) |\n| `H` | number of heads, `head_dim = C \u002F H` |\n| `V` | vocabulary size (256, byte-level) |\n\nCross-entropy loss is reported in nats per token. `ln(256) â‰?5.545` is the loss of a model that\nguesses uniformly, so any loss below that is real signal. Perplexity is `exp(loss)`.\n\n## Design notes\n\n**Why pre-layer-norm.** Normalizing before each sub-block keeps the residual stream's scale\nstable, which is what makes deep stacks trainable without learning-rate tricks. The residual\npath is a clean identity from the embedding to the final norm.\n\n**Why scale the output projections.** `wo` and `w2` are multiplied by `1\u002Fsqrt(2 * n_layer)` at\ninitialization. Residual branches accumulate variance with depth; this keeps the stream's\nmagnitude roughly constant and prevents the first few dozen steps from diverging.\n\n**Why the mask is applied before the softmax.** Setting masked scores to `-inf` makes their\npost-softmax probability exactly zero, so no future token can influence the present. Applying a\nmask afterwards would break the normalization.\n\n**Why byte-level tokens.** A learned subword vocabulary is a second thing to train, version, and\nget wrong. Bytes cost sequence length but remove an entire class of bugs, and they let the model\nround-trip any UTF-8 text exactly â€?including text it has never seen.\n\n## Project layout\n\n```\nmicrogpt\u002F\n  model.py        # Transformer: forward pass, hand-written backward pass, sampling\n  optim.py        # AdamW and the warmup + cosine schedule\n  train.py        # batching, training loop, checkpoint save\u002Fload\n  generate.py     # completion, perplexity, next-token inspection\n  tokenizer.py    # byte-level tokenizer\n  __main__.py     # CLI\nexamples\u002F\n  corpus.txt      # ~8 KB training corpus\ntests\u002F\n  test_microgpt.py\n```\n\n## Testing\n\n```bash\npython -m unittest discover -s tests -v\n```\n\nThe gradient check compares analytic gradients against central differences for the token\nembedding, positional embedding, query projection, output projection, both MLP matrices, and\nboth layer norms. A relative error above `2e-4` fails the build.\n\n## ä¸­æ–‡è¯´æ˜Ž\n\nMicroGPT æ˜¯ä¸€ä¸?*åªç”¨ NumPy ä»Žé›¶å®žçŽ°**çš?GPT è¯­è¨€æ¨¡åž‹ï¼šæ‰‹å†™å‰å‘ä¸Žåå‘ä¼ æ’­ï¼Œä¸ä¾èµ–ä»»ä½•æ·±åº¦å­¦ä¹ æ¡†æž¶ã€?\n- **ç»“æž„**ï¼šå­—èŠ‚çº§åˆ†è¯ï¼?56 è¯è¡¨ï¼? å¤šå¤´å› æžœè‡ªæ³¨æ„åŠ› + æ®‹å·® + Pre-LayerNorm + 4 å€æ‰©å±?FFNï¼Œè¾“å…¥è¾“å‡ºåµŒå…¥æƒé‡å…±äº«ã€?- **è®­ç»ƒ**ï¼šäº¤å‰ç†µæŸå¤±ï¼ŒAdamW ä¼˜åŒ–å™¨ï¼Œçº¿æ€?warmup + ä½™å¼¦é€€ç«ï¼Œæ¢¯åº¦ç”¨ä¸­å¿ƒå·®åˆ†é€å‚æ•°æ ¡éªŒã€?- **æŽ¨ç†**ï¼šæ¸©åº¦é‡‡æ ·ã€top-k æˆªæ–­ã€å›°æƒ‘åº¦è¯„ä¼°ã€ä¸‹ä¸€ä¸?token æ¦‚çŽ‡åˆ†å¸ƒæŸ¥çœ‹ã€?- **ä¸Šæ‰‹**ï¼š`pip install -e .` åŽæ‰§è¡?`python -m microgpt train`ï¼Œä¸€åˆ†é’Ÿå†…å¯åœ¨ç¬”è®°æœ¬ CPU ä¸Šå®Œæˆè®­ç»ƒã€?\n```bash\npython -m microgpt train --steps 1200 --n-embd 128 --n-layer 3\npython -m microgpt sample --prompt \"A language model is\" --tokens 200\n```\n\né€‚åˆç”¨æ¥ç†è§£æ³¨æ„åŠ›ã€åå‘ä¼ æ’­ã€ä¼˜åŒ–å™¨å’Œé‡‡æ ·ç­–ç•¥åˆ°åº•åœ¨åšä»€ä¹ˆâ€”â€”ä»£ç é‡å°åˆ°å¯ä»¥ä¸€ä¸ªä¸‹åˆè¯»å®Œã€?\n## License\n\nMIT Â© 2026 prabeakarve\n",2,"2026-11-24 04:54:44","CREATED_QUERY"]