[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-karpathy--nanoGPT":3,"tool-karpathy--nanoGPT":64},[4,17,27,35,43,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,3,"2026-04-05T11:01:52",[13,14,15],"开发框架","图像","Agent","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":23,"last_commit_at":24,"category_tags":25,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",138956,2,"2026-04-05T11:33:21",[13,15,26],"语言模型",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":23,"last_commit_at":33,"category_tags":34,"status":16},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[13,14,15],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":23,"last_commit_at":41,"category_tags":42,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,26],{"id":44,"name":45,"github_repo":46,"description_zh":47,"stars":48,"difficulty_score":23,"last_commit_at":49,"category_tags":50,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[14,51,52,53,15,54,26,13,55],"数据工具","视频","插件","其他","音频",{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":10,"last_commit_at":62,"category_tags":63,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[15,14,13,26,54],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":79,"owner_location":80,"owner_email":81,"owner_twitter":79,"owner_website":82,"owner_url":83,"languages":84,"stars":89,"forks":90,"last_commit_at":91,"license":92,"difficulty_score":10,"env_os":93,"env_gpu":94,"env_ram":95,"env_deps":96,"category_tags":107,"github_topics":79,"view_count":108,"oss_zip_url":79,"oss_zip_packed_at":79,"status":16,"created_at":109,"updated_at":110,"faqs":111,"releases":141},3948,"karpathy\u002FnanoGPT","nanoGPT","The simplest, fastest repository for training\u002Ffinetuning medium-sized GPTs.","nanoGPT 是一个专注于训练和微调中等规模 GPT 模型的极简开源项目。它旨在解决大语言模型代码库通常过于复杂、难以快速上手的问题，通过高度精简的代码结构，让开发者能在单张显卡上短短几天甚至几分钟内复现经典模型（如 GPT-2）或完成自定义训练。\n\n该项目非常适合深度学习开发者、研究人员以及希望深入理解 Transformer 架构原理的技术爱好者。对于想要从零开始构建模型，或基于现有检查点进行微调的用户来说，nanoGPT 提供了极低的入门门槛。其核心亮点在于“重实践、轻理论”的设计理念：整个训练循环和模型定义分别仅由约 300 行代码构成，去除了冗余的抽象层，代码 plain 且易读。用户不仅可以轻松修改代码以适应特定需求，还能快速在莎士比亚文本等数据集上体验从数据预处理到模型生成的完整流程。尽管作者已推出更新的 nanochat 项目，nanoGPT 作为学习大模型底层实现的经典教材，依然具有极高的参考价值。","\n# nanoGPT\n\n![nanoGPT](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_nanoGPT_readme_92b8ffbb1e7e.jpg)\n\n\n---\n\n**Update Nov 2025** nanoGPT has a new and improved cousin called [nanochat](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002Fnanochat). It is very likely you meant to use\u002Ffind nanochat instead. nanoGPT (this repo) is now very old and deprecated but I will leave it up for posterity.\n\n---\n\nThe simplest, fastest repository for training\u002Ffinetuning medium-sized GPTs. It is a rewrite of [minGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT) that prioritizes teeth over education. Still under active development, but currently the file `train.py` reproduces GPT-2 (124M) on OpenWebText, running on a single 8XA100 40GB node in about 4 days of training. The code itself is plain and readable: `train.py` is a ~300-line boilerplate training loop and `model.py` a ~300-line GPT model definition, which can optionally load the GPT-2 weights from OpenAI. That's it.\n\n![repro124m](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_nanoGPT_readme_2c175d95c6e7.png)\n\nBecause the code is so simple, it is very easy to hack to your needs, train new models from scratch, or finetune pretrained checkpoints (e.g. biggest one currently available as a starting point would be the GPT-2 1.3B model from OpenAI).\n\n## install\n\n```\npip install torch numpy transformers datasets tiktoken wandb tqdm\n```\n\nDependencies:\n\n- [pytorch](https:\u002F\u002Fpytorch.org) \u003C3\n- [numpy](https:\u002F\u002Fnumpy.org\u002Finstall\u002F) \u003C3\n-  `transformers` for huggingface transformers \u003C3 (to load GPT-2 checkpoints)\n-  `datasets` for huggingface datasets \u003C3 (if you want to download + preprocess OpenWebText)\n-  `tiktoken` for OpenAI's fast BPE code \u003C3\n-  `wandb` for optional logging \u003C3\n-  `tqdm` for progress bars \u003C3\n\n## quick start\n\nIf you are not a deep learning professional and you just want to feel the magic and get your feet wet, the fastest way to get started is to train a character-level GPT on the works of Shakespeare. First, we download it as a single (1MB) file and turn it from raw text into one large stream of integers:\n\n```sh\npython data\u002Fshakespeare_char\u002Fprepare.py\n```\n\nThis creates a `train.bin` and `val.bin` in that data directory. Now it is time to train your GPT. The size of it very much depends on the computational resources of your system:\n\n**I have a GPU**. Great, we can quickly train a baby GPT with the settings provided in the [config\u002Ftrain_shakespeare_char.py](config\u002Ftrain_shakespeare_char.py) config file:\n\n```sh\npython train.py config\u002Ftrain_shakespeare_char.py\n```\n\nIf you peek inside it, you'll see that we're training a GPT with a context size of up to 256 characters, 384 feature channels, and it is a 6-layer Transformer with 6 heads in each layer. On one A100 GPU this training run takes about 3 minutes and the best validation loss is 1.4697. Based on the configuration, the model checkpoints are being written into the `--out_dir` directory `out-shakespeare-char`. So once the training finishes we can sample from the best model by pointing the sampling script at this directory:\n\n```sh\npython sample.py --out_dir=out-shakespeare-char\n```\n\nThis generates a few samples, for example:\n\n```\nANGELO:\nAnd cowards it be strawn to my bed,\nAnd thrust the gates of my threats,\nBecause he that ale away, and hang'd\nAn one with him.\n\nDUKE VINCENTIO:\nI thank your eyes against it.\n\nDUKE VINCENTIO:\nThen will answer him to save the malm:\nAnd what have you tyrannous shall do this?\n\nDUKE VINCENTIO:\nIf you have done evils of all disposition\nTo end his power, the day of thrust for a common men\nThat I leave, to fight with over-liking\nHasting in a roseman.\n```\n\nlol  `¯\\_(ツ)_\u002F¯`. Not bad for a character-level model after 3 minutes of training on a GPU. Better results are quite likely obtainable by instead finetuning a pretrained GPT-2 model on this dataset (see finetuning section later).\n\n**I only have a macbook** (or other cheap computer). No worries, we can still train a GPT but we want to dial things down a notch. I recommend getting the bleeding edge PyTorch nightly ([select it here](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Flocally\u002F) when installing) as it is currently quite likely to make your code more efficient. But even without it, a simple train run could look as follows:\n\n```sh\npython train.py config\u002Ftrain_shakespeare_char.py --device=cpu --compile=False --eval_iters=20 --log_interval=1 --block_size=64 --batch_size=12 --n_layer=4 --n_head=4 --n_embd=128 --max_iters=2000 --lr_decay_iters=2000 --dropout=0.0\n```\n\nHere, since we are running on CPU instead of GPU we must set both `--device=cpu` and also turn off PyTorch 2.0 compile with `--compile=False`. Then when we evaluate we get a bit more noisy but faster estimate (`--eval_iters=20`, down from 200), our context size is only 64 characters instead of 256, and the batch size only 12 examples per iteration, not 64. We'll also use a much smaller Transformer (4 layers, 4 heads, 128 embedding size), and decrease the number of iterations to 2000 (and correspondingly usually decay the learning rate to around max_iters with `--lr_decay_iters`). Because our network is so small we also ease down on regularization (`--dropout=0.0`). This still runs in about ~3 minutes, but gets us a loss of only 1.88 and therefore also worse samples, but it's still good fun:\n\n```sh\npython sample.py --out_dir=out-shakespeare-char --device=cpu\n```\nGenerates samples like this:\n\n```\nGLEORKEN VINGHARD III:\nWhell's the couse, the came light gacks,\nAnd the for mought you in Aut fries the not high shee\nbot thou the sought bechive in that to doth groan you,\nNo relving thee post mose the wear\n```\n\nNot bad for ~3 minutes on a CPU, for a hint of the right character gestalt. If you're willing to wait longer, feel free to tune the hyperparameters, increase the size of the network, the context length (`--block_size`), the length of training, etc.\n\nFinally, on Apple Silicon Macbooks and with a recent PyTorch version make sure to add `--device=mps` (short for \"Metal Performance Shaders\"); PyTorch then uses the on-chip GPU that can *significantly* accelerate training (2-3X) and allow you to use larger networks. See [Issue 28](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F28) for more.\n\n## reproducing GPT-2\n\nA more serious deep learning professional may be more interested in reproducing GPT-2 results. So here we go - we first tokenize the dataset, in this case the [OpenWebText](https:\u002F\u002Fopenwebtext2.readthedocs.io\u002Fen\u002Flatest\u002F), an open reproduction of OpenAI's (private) WebText:\n\n```sh\npython data\u002Fopenwebtext\u002Fprepare.py\n```\n\nThis downloads and tokenizes the [OpenWebText](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fopenwebtext) dataset. It will create a `train.bin` and `val.bin` which holds the GPT2 BPE token ids in one sequence, stored as raw uint16 bytes. Then we're ready to kick off training. To reproduce GPT-2 (124M) you'll want at least an 8X A100 40GB node and run:\n\n```sh\ntorchrun --standalone --nproc_per_node=8 train.py config\u002Ftrain_gpt2.py\n```\n\nThis will run for about 4 days using PyTorch Distributed Data Parallel (DDP) and go down to loss of ~2.85. Now, a GPT-2 model just evaluated on OWT gets a val loss of about 3.11, but if you finetune it it will come down to ~2.85 territory (due to an apparent domain gap), making the two models ~match.\n\nIf you're in a cluster environment and you are blessed with multiple GPU nodes you can make GPU go brrrr e.g. across 2 nodes like:\n\n```sh\n# Run on the first (master) node with example IP 123.456.123.456:\ntorchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train.py\n# Run on the worker node:\ntorchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train.py\n```\n\nIt is a good idea to benchmark your interconnect (e.g. iperf3). In particular, if you don't have Infiniband then also prepend `NCCL_IB_DISABLE=1` to the above launches. Your multinode training will work, but most likely _crawl_. By default checkpoints are periodically written to the `--out_dir`. We can sample from the model by simply `python sample.py`.\n\nFinally, to train on a single GPU simply run the `python train.py` script. Have a look at all of its args, the script tries to be very readable, hackable and transparent. You'll most likely want to tune a number of those variables depending on your needs.\n\n## baselines\n\nOpenAI GPT-2 checkpoints allow us to get some baselines in place for openwebtext. We can get the numbers as follows:\n\n```sh\n$ python train.py config\u002Feval_gpt2.py\n$ python train.py config\u002Feval_gpt2_medium.py\n$ python train.py config\u002Feval_gpt2_large.py\n$ python train.py config\u002Feval_gpt2_xl.py\n```\n\nand observe the following losses on train and val:\n\n| model | params | train loss | val loss |\n| ------| ------ | ---------- | -------- |\n| gpt2 | 124M         | 3.11  | 3.12     |\n| gpt2-medium | 350M  | 2.85  | 2.84     |\n| gpt2-large | 774M   | 2.66  | 2.67     |\n| gpt2-xl | 1558M     | 2.56  | 2.54     |\n\nHowever, we have to note that GPT-2 was trained on (closed, never released) WebText, while OpenWebText is just a best-effort open reproduction of this dataset. This means there is a dataset domain gap. Indeed, taking the GPT-2 (124M) checkpoint and finetuning on OWT directly for a while reaches loss down to ~2.85. This then becomes the more appropriate baseline w.r.t. reproduction.\n\n## finetuning\n\nFinetuning is no different than training, we just make sure to initialize from a pretrained model and train with a smaller learning rate. For an example of how to finetune a GPT on new text go to `data\u002Fshakespeare` and run `prepare.py` to download the tiny shakespeare dataset and render it into a `train.bin` and `val.bin`, using the OpenAI BPE tokenizer from GPT-2. Unlike OpenWebText this will run in seconds. Finetuning can take very little time, e.g. on a single GPU just a few minutes. Run an example finetuning like:\n\n```sh\npython train.py config\u002Ffinetune_shakespeare.py\n```\n\nThis will load the config parameter overrides in `config\u002Ffinetune_shakespeare.py` (I didn't tune them much though). Basically, we initialize from a GPT2 checkpoint with `init_from` and train as normal, except shorter and with a small learning rate. If you're running out of memory try decreasing the model size (they are `{'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}`) or possibly decreasing the `block_size` (context length). The best checkpoint (lowest validation loss) will be in the `out_dir` directory, e.g. in `out-shakespeare` by default, per the config file. You can then run the code in `sample.py --out_dir=out-shakespeare`:\n\n```\nTHEODORE:\nThou shalt sell me to the highest bidder: if I die,\nI sell thee to the first; if I go mad,\nI sell thee to the second; if I\nlie, I sell thee to the third; if I slay,\nI sell thee to the fourth: so buy or sell,\nI tell thee again, thou shalt not sell my\npossession.\n\nJULIET:\nAnd if thou steal, thou shalt not sell thyself.\n\nTHEODORE:\nI do not steal; I sell the stolen goods.\n\nTHEODORE:\nThou know'st not what thou sell'st; thou, a woman,\nThou art ever a victim, a thing of no worth:\nThou hast no right, no right, but to be sold.\n```\n\nWhoa there, GPT, entering some dark place over there. I didn't really tune the hyperparameters in the config too much, feel free to try!\n\n## sampling \u002F inference\n\nUse the script `sample.py` to sample either from pre-trained GPT-2 models released by OpenAI, or from a model you trained yourself. For example, here is a way to sample from the largest available `gpt2-xl` model:\n\n```sh\npython sample.py \\\n    --init_from=gpt2-xl \\\n    --start=\"What is the answer to life, the universe, and everything?\" \\\n    --num_samples=5 --max_new_tokens=100\n```\n\nIf you'd like to sample from a model you trained, use the `--out_dir` to point the code appropriately. You can also prompt the model with some text from a file, e.g. ```python sample.py --start=FILE:prompt.txt```.\n\n## efficiency notes\n\nFor simple model benchmarking and profiling, `bench.py` might be useful. It's identical to what happens in the meat of the training loop of `train.py`, but omits much of the other complexities.\n\nNote that the code by default uses [PyTorch 2.0](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Fpytorch-2.0\u002F). At the time of writing (Dec 29, 2022) this makes `torch.compile()` available in the nightly release. The improvement from the one line of code is noticeable, e.g. cutting down iteration time from ~250ms \u002F iter to 135ms \u002F iter. Nice work PyTorch team!\n\n## todos\n\n- Investigate and add FSDP instead of DDP\n- Eval zero-shot perplexities on standard evals (e.g. LAMBADA? HELM? etc.)\n- Finetune the finetuning script, I think the hyperparams are not great\n- Schedule for linear batch size increase during training\n- Incorporate other embeddings (rotary, alibi)\n- Separate out the optim buffers from model params in checkpoints I think\n- Additional logging around network health (e.g. gradient clip events, magnitudes)\n- Few more investigations around better init etc.\n\n## troubleshooting\n\nNote that by default this repo uses PyTorch 2.0 (i.e. `torch.compile`). This is fairly new and experimental, and not yet available on all platforms (e.g. Windows). If you're running into related error messages try to disable this by adding `--compile=False` flag. This will slow down the code but at least it will run.\n\nFor some context on this repository, GPT, and language modeling it might be helpful to watch my [Zero To Hero series](https:\u002F\u002Fkarpathy.ai\u002Fzero-to-hero.html). Specifically, the [GPT video](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=kCc8FmEb1nY) is popular if you have some prior language modeling context.\n\nFor more questions\u002Fdiscussions feel free to stop by **#nanoGPT** on Discord:\n\n[![](https:\u002F\u002Fdcbadge.vercel.app\u002Fapi\u002Fserver\u002F3zy8kqD9Cp?compact=true&style=flat)](https:\u002F\u002Fdiscord.gg\u002F3zy8kqD9Cp)\n\n## acknowledgements\n\nAll nanoGPT experiments are powered by GPUs on [Lambda labs](https:\u002F\u002Flambdalabs.com), my favorite Cloud GPU provider. Thank you Lambda labs for sponsoring nanoGPT!\n","# nanoGPT\n\n![nanoGPT](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_nanoGPT_readme_92b8ffbb1e7e.jpg)\n\n\n---\n\n**更新：2025年11月** nanoGPT 有一个全新且更优秀的“表亲”项目，名为 [nanochat](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002Fnanochat)。你很可能本来想使用或寻找的是 nanochat，而不是 nanoGPT。nanoGPT（即本仓库）如今已经非常老旧并被弃用，但我仍将其保留以供后人参考。\n\n---\n\n这是训练和微调中等规模 GPT 模型最简单、最快的代码库。它是对 [minGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT) 的重写版，更注重实用性而非教学性。目前仍在积极开发中，但 `train.py` 文件已能在单台配备 8 张 A100 显卡（每张 40GB）的机器上，在大约 4 天的训练时间内复现 GPT-2（1.24 亿参数）模型，并在 OpenWebText 数据集上进行训练。代码本身简洁易懂：`train.py` 是一个约 300 行的标准训练循环，而 `model.py` 则定义了一个约 300 行的 GPT 模型结构，还可以选择加载 OpenAI 提供的 GPT-2 权重。仅此而已。\n\n![repro124m](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_nanoGPT_readme_2c175d95c6e7.png)\n\n由于代码极其简单，因此非常容易根据需求进行修改，从头开始训练新模型，或者对预训练检查点进行微调（例如，目前可用的最大预训练模型是 OpenAI 的 GPT-2 13 亿参数版本）。\n\n## 安装\n\n```\npip install torch numpy transformers datasets tiktoken wandb tqdm\n```\n\n依赖项：\n\n- [PyTorch](https:\u002F\u002Fpytorch.org) \u003C3\n- [NumPy](https:\u002F\u002Fnumpy.org\u002Finstall\u002F) \u003C3\n- `transformers` 用于加载 Hugging Face 的 Transformer 模型 \u003C3（以便加载 GPT-2 检查点）\n- `datasets` 用于处理 Hugging Face 的数据集 \u003C3（如果你需要下载并预处理 OpenWebText 数据集）\n- `tiktoken` 提供 OpenAI 快速 BPE 编码实现 \u003C3\n- `wandb` 用于可选的日志记录 \u003C3\n- `tqdm` 用于显示进度条 \u003C3\n\n## 快速入门\n\n如果你不是深度学习专业人士，只是想体验一下 AI 的神奇之处并初步上手，最快的方式是在莎士比亚的作品上训练一个基于字符级别的 GPT 模型。首先，我们将莎士比亚的作品下载为一个 1MB 的文本文件，并将其转换成一个巨大的整数序列：\n\n```sh\npython data\u002Fshakespeare_char\u002Fprepare.py\n```\n\n这会在该数据目录下生成 `train.bin` 和 `val.bin` 文件。接下来就可以开始训练你的 GPT 了。训练规模很大程度上取决于你的计算资源：\n\n**我有一块 GPU**。太好了！我们可以使用 [config\u002Ftrain_shakespeare_char.py](config\u002Ftrain_shakespeare_char.py) 配置文件中的设置快速训练一个小型 GPT：\n\n```sh\npython train.py config\u002Ftrain_shakespeare_char.py\n```\n\n打开该配置文件可以看到，我们正在训练一个上下文长度最多 256 个字符、特征通道数为 384、包含 6 层 Transformer 且每层有 6 个注意力头的 GPT 模型。在一块 A100 GPU 上，整个训练过程大约需要 3 分钟，最佳验证损失为 1.4697。根据配置，模型检查点会被保存到 `--out_dir` 指定的 `out-shakespeare-char` 目录中。训练完成后，我们可以通过指向该目录来采样最佳模型：\n\n```sh\npython sample.py --out_dir=out-shakespeare-char\n```\n\n这会生成一些示例文本，例如：\n\n```\n安杰洛：\n懦夫竟敢闯入我的床榻，\n强行推开我的门扉，\n只因他曾与那人一同偷窃、一同受刑。\n\n维琴提奥公爵：\n我感谢你的眼睛没有看到这一切。\n\n维琴提奥公爵：\n那么我就回答他，以挽救那杯美酒：\n你这位暴君究竟为何要如此行事呢？\n\n维琴提奥公爵：\n若你曾犯下种种恶行，\n只为终结他的权势，那么这一天终将到来——\n普通百姓将奋起反抗，\n如同玫瑰般绽放出新的希望。\n```\n\n哈哈 `¯\\_(ツ)_\u002F¯`。对于一个在 GPU 上训练了 3 分钟的字符级模型来说，这样的效果已经不错了。如果在此数据集上对预训练的 GPT-2 模型进行微调，很可能会获得更好的结果（详见后续的微调部分）。\n\n**我只有一台 MacBook**（或其他廉价电脑）。别担心，我们仍然可以训练 GPT，不过需要适当降低一些参数。建议在安装 PyTorch 时选择最新的 nightly 版本（[点击此处获取](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Flocally\u002F)），因为最新版本通常能显著提升代码效率。即便不使用 nightly 版本，简单的训练命令也可以如下所示：\n\n```sh\npython train.py config\u002Ftrain_shakespeare_char.py --device=cpu --compile=False --eval_iters=20 --log_interval=1 --block_size=64 --batch_size=12 --n_layer=4 --n_head=4 --n_embd=128 --max_iters=2000 --lr_decay_iters=2000 --dropout=0.0\n```\n\n在这里，由于我们是在 CPU 上运行，必须同时设置 `--device=cpu`，并且关闭 PyTorch 2.0 的编译功能，即 `--compile=False`。此外，在评估时，我们采用了更少但更快的估计次数（`--eval_iters=20`，从之前的 200 减少），上下文长度也从 256 个字符缩减至 64 个字符，每次迭代的批量大小也从 64 个样本减少到 12 个样本。我们还使用了一个更小的 Transformer 模型（4 层、4 个注意力头、128 维嵌入），并将最大迭代次数降至 2000 次（相应地，学习率衰减步数也调整为与最大迭代次数一致）。由于网络规模较小，我们也减少了正则化强度（`--dropout=0.0`）。尽管如此，整个训练过程仍然只需约 3 分钟，但得到的损失值为 1.88，生成的样本质量自然也会稍差，不过依然趣味十足：\n\n```sh\npython sample.py --out_dir=out-shakespeare-char --device=cpu\n```\n\n生成的样本可能如下：\n\n```\n格勒肯·温哈德三世：\n唉，这究竟是怎么回事，那光芒万丈的光束，\n为何在秋日的清晨显得如此黯淡无光？\n你是否也曾渴望过那样的辉煌，\n却始终未能如愿以偿？\n如今，时光流逝，岁月无情，\n```\n\n对于在 CPU 上运行了约 3 分钟的模型来说，这已经相当不错了，至少能让你感受到一点正确的字符风格。如果你愿意花更多时间，也可以进一步调整超参数，增大网络规模、上下文长度（`--block_size`）、训练时长等。\n\n最后，在搭载 Apple Silicon 芯片的 MacBook 上，并且使用较新版本的 PyTorch 时，请务必添加 `--device=mps`（即“Metal Performance Shaders”的缩写）；这样 PyTorch 就会利用芯片内置的 GPU 来显著加速训练（提速 2–3 倍），从而支持更大规模的网络。更多信息请参阅 [Issue 28](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F28)。\n\n## 复现 GPT-2\n\n对于更专业的深度学习从业者来说，复现 GPT-2 的结果可能更具吸引力。那么我们现在就开始——首先对数据集进行分词处理，这里我们使用的是 [OpenWebText](https:\u002F\u002Fopenwebtext2.readthedocs.io\u002Fen\u002Flatest\u002F) 数据集，它是 OpenAI（私有）WebText 的开源复现版本：\n\n```sh\npython data\u002Fopenwebtext\u002Fprepare.py\n```\n\n这段代码会下载并分词 [OpenWebText](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fopenwebtext) 数据集，生成 `train.bin` 和 `val.bin` 文件，其中包含 GPT-2 BPE 分词的 token ID，以原始 uint16 字节的形式存储。接下来我们就可以开始训练了。要复现 GPT-2（1.24 亿参数），你需要至少一台配备 8 块 A100 40GB 显卡的节点，并运行以下命令：\n\n```sh\ntorchrun --standalone --nproc_per_node=8 train.py config\u002Ftrain_gpt2.py\n```\n\n使用 PyTorch 的分布式数据并行（DDP）训练大约需要 4 天时间，最终损失可以降到约 2.85。需要注意的是，在 OpenWebText 数据集上直接评估的 GPT-2 模型验证损失约为 3.11，但经过微调后，由于领域差异的存在，损失会降至约 2.85 左右，从而使两个模型的表现接近。\n\n如果你在一个多 GPU 节点的集群环境中，可以让 GPU 加速训练，例如在 2 个节点上并行运行：\n\n```sh\n# 在第一个（主）节点上运行，假设 IP 地址为 123.456.123.456：\ntorchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=123.456.123.456 --master_port=1234 train.py\n# 在工作节点上运行：\ntorchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr=123.456.123.456 --master_port=1234 train.py\n```\n\n建议先对你的网络互联性能进行基准测试（例如使用 iperf3）。特别是如果没有 Infiniband 网络时，还需要在上述命令前加上 `NCCL_IB_DISABLE=1`。这样多节点训练仍然可以运行，但速度可能会非常慢。默认情况下，检查点会定期保存到 `--out_dir` 指定的目录中。你可以通过运行 `python sample.py` 来从模型中采样。\n\n最后，如果你想在单个 GPU 上训练，只需直接运行 `python train.py` 脚本即可。仔细查看脚本的所有参数，它设计得非常易读、可修改且透明。根据你的需求，你可能需要调整其中的一些变量。\n\n## 基线对比\n\n借助 OpenAI 提供的 GPT-2 检查点，我们可以为 OpenWebText 数据集设定一些基线。具体操作如下：\n\n```sh\n$ python train.py config\u002Feval_gpt2.py\n$ python train.py config\u002Feval_gpt2_medium.py\n$ python train.py config\u002Feval_gpt2_large.py\n$ python train.py config\u002Feval_gpt2_xl.py\n```\n\n以下是训练和验证损失的结果：\n\n| 模型       | 参数量   | 训练损失 | 验证损失 |\n| ---------- | -------- | -------- | -------- |\n| gpt2       | 1.24 亿  | 3.11     | 3.12     |\n| gpt2-medium| 3.5 亿   | 2.85     | 2.84     |\n| gpt2-large | 7.74 亿  | 2.66     | 2.67     |\n| gpt2-xl    | 15.58 亿 | 2.56     | 2.54     |\n\n不过需要注意的是，GPT-2 是在封闭且未公开的 WebText 数据集上训练的，而 OpenWebText 只是该数据集的一个尽力还原的开源版本。这意味着两者之间存在数据分布上的差距。事实上，如果我们使用 GPT-2（1.24 亿参数）的检查点直接在 OpenWebText 数据集上进行一段时间的微调，验证损失可以降低到约 2.85，这将是一个更合适的复现基线。\n\n## 微调\n\n微调的过程与普通训练并无不同，只是我们需要从预训练模型初始化，并使用较小的学习率进行训练。以在新文本上微调 GPT 为例，进入 `data\u002Fshakespeare` 目录，运行 `prepare.py` 下载莎士比亚的小型数据集，并使用 GPT-2 的 OpenAI BPE 分词器将其转换为 `train.bin` 和 `val.bin` 文件。与 OpenWebText 不同的是，这个过程只需几秒钟即可完成。微调所需的时间也很短，例如在单个 GPU 上可能只需要几分钟。你可以运行以下命令进行微调：\n\n```sh\npython train.py config\u002Ffinetune_shakespeare.py\n```\n\n该命令会加载 `config\u002Ffinetune_shakespeare.py` 中的配置参数覆盖（尽管我并没有对这些参数做太多调整）。基本上，我们从 GPT-2 检查点初始化（`init_from`），然后按照常规方式训练，只是训练时间更短，学习率也更小。如果显存不足，可以尝试减小模型规模（选项包括 `{'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}`）或减少 `block_size`（上下文长度）。最佳检查点（验证损失最低的）会保存在 `out_dir` 目录下，默认为 `out-shakespeare`，具体路径由配置文件决定。之后你可以运行 `sample.py --out_dir=out-shakespeare`：\n\n```\nTHEODORE:\n你要把我卖给出价最高的人：如果我死了，\n你就把卖给我第一个买家；如果我疯了，\n你就把卖给我第二个买家；如果我说谎，\n你就把卖给我第三个买家；如果我杀人，\n你就把卖给我第四个买家：所以无论买还是卖，\n我再告诉你一次，你都不能卖掉我的财产。\n\nJULIET:\n如果你偷窃，你就不能卖掉自己。\n\nTHEODORE:\n我不偷窃，我只是贩卖赃物。\n\nTHEODORE:\n你根本不知道你在卖什么；你，一个女人，\n永远都是受害者，毫无价值：\n你没有任何权利，只有被出卖的权利。\n```\n\n哇哦，GPT 这次似乎进入了某种黑暗的境地。我在配置文件中并没有对超参数做太多调整，大家完全可以自行尝试！\n\n## 采样\u002F推理\n\n使用 `sample.py` 脚本可以从 OpenAI 发布的预训练 GPT-2 模型中采样，也可以从你自己训练的模型中采样。例如，以下是从最大的可用 `gpt2-xl` 模型中采样的方法：\n\n```sh\npython sample.py \\\n    --init_from=gpt2-xl \\\n    --start=\"生命、宇宙以及一切的终极答案是什么？\" \\\n    --num_samples=5 --max_new_tokens=100\n```\n\n如果你想从自己训练的模型中采样，只需正确设置 `--out_dir` 参数即可。你还可以从文件中读取提示文本，例如：\n\n```sh\npython sample.py --start=FILE:prompt.txt\n```\n\n## 效率相关说明\n\n对于简单的模型基准测试和性能分析，`bench.py` 可能会很有用。它与 `train.py` 训练循环的核心部分完全相同，但省略了其他复杂的逻辑。\n\n请注意，代码默认使用 [PyTorch 2.0](https:\u002F\u002Fpytorch.org\u002Fget-started\u002Fpytorch-2.0\u002F)。截至 2022 年 12 月 29 日，夜间构建版本已经支持 `torch.compile()`。启用这一功能后，性能提升非常明显，例如迭代时间可以从每轮约 250 毫秒缩短至 135 毫秒。PyTorch 团队做得很好！\n\n## 待办事项\n\n- 探索并引入 FSDP 替代 DDP\n- 在标准评测（如 LAMBADA、HELM 等）上评估零样本困惑度\n- 对微调脚本进行优化，我认为当前的超参数设置并不理想\n- 在训练过程中安排线性增加的批量大小\n- 引入其他嵌入方式（旋转位置编码、Alibi 注意力等）\n- 将检查点中的优化器缓冲区与模型参数分离\n- 增加对网络健康状况的监控日志记录（如梯度裁剪事件及幅度）\n- 进一步研究更好的初始化方法等\n\n## 故障排除\n\n请注意，默认情况下，此仓库使用 PyTorch 2.0（即 `torch.compile`）。这一功能相对较新且处于实验阶段，并非所有平台都支持（例如 Windows）。如果您遇到相关错误信息，可以尝试通过添加 `--compile=False` 标志来禁用该功能。这样做会降低代码运行速度，但至少可以让程序正常运行。\n\n为了更好地了解本仓库、GPT 以及语言建模的相关背景，您可以观看我的 [Zero To Hero 系列](https:\u002F\u002Fkarpathy.ai\u002Fzero-to-hero.html)。特别是其中的 [GPT 视频](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=kCc8FmEb1nY)，如果您已经具备一定的语言建模基础，将会非常有帮助。\n\n如需进一步交流或讨论，欢迎前往 Discord 的 **#nanoGPT** 频道：\n\n[![](https:\u002F\u002Fdcbadge.vercel.app\u002Fapi\u002Fserver\u002F3zy8kqD9Cp?compact=true&style=flat)](https:\u002F\u002Fdiscord.gg\u002F3zy8kqD9Cp)\n\n## 致谢\n\n所有 nanoGPT 实验均在 [Lambda Labs](https:\u002F\u002Flambdalabs.com) 提供的 GPU 上运行，Lambda Labs 是我最喜爱的云端 GPU 服务提供商。感谢 Lambda Labs 对 nanoGPT 的赞助！","# nanoGPT 快速上手指南\n\nnanoGPT 是一个用于训练和微调中型 GPT 模型的最简单、最快的代码库。它由 Andrej Karpathy 编写，代码简洁易懂（核心训练循环和模型定义各约 300 行），非常适合学习大语言模型原理或进行快速实验。\n\n> **注意**：截至 2025 年 11 月，作者已推出升级版项目 [nanochat](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002Fnanochat)。nanoGPT 目前处于维护模式，但仍适用于学习 GPT-2 架构及基础训练流程。\n\n## 环境准备\n\n### 系统要求\n- **操作系统**：Linux, macOS, Windows (WSL 推荐)\n- **Python**：3.8+\n- **硬件**：\n  - **GPU 用户**：推荐 NVIDIA GPU (支持 CUDA)，单卡即可运行小型模型；复现 GPT-2 (124M) 建议 8x A100。\n  - **CPU\u002FMac 用户**：可运行小型字符级模型。Apple Silicon (M1\u002FM2\u002FM3) 用户建议使用 `mps` 后端加速。\n\n### 前置依赖\n本项目依赖以下 Python 库：\n- `torch`: 深度学习框架\n- `numpy`: 数值计算\n- `transformers`: 用于加载 Hugging Face 的 GPT-2 预训练权重\n- `datasets`: 用于下载和处理数据集 (如 OpenWebText)\n- `tiktoken`: OpenAI 的高效 BPE 分词器\n- `wandb`: (可选) 实验日志记录\n- `tqdm`: 进度条显示\n\n## 安装步骤\n\n1. **创建虚拟环境** (推荐)\n   ```bash\n   python -m venv nanogpt-env\n   source nanogpt-env\u002Fbin\u002Factivate  # Windows: nanogpt-env\\Scripts\\activate\n   ```\n\n2. **安装依赖包**\n   国内用户建议使用清华或阿里镜像源以加速下载：\n   ```bash\n   pip install torch numpy transformers datasets tiktoken wandb tqdm -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n   ```\n   *注：若需特定版本的 PyTorch (如支持 MPS 的最新版)，请前往 [pytorch.org](https:\u002F\u002Fpytorch.org) 获取带镜像源的安装命令。*\n\n3. **克隆项目代码**\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT.git\n   cd nanoGPT\n   ```\n\n## 基本使用\n\n最快速的入门方式是训练一个**字符级 (Character-level)** 的 GPT 模型，数据集选用莎士比亚文集。整个过程在单张 GPU 上仅需约 3 分钟。\n\n### 第一步：准备数据\n下载莎士比亚数据集并将其转换为整数流格式：\n```bash\npython data\u002Fshakespeare_char\u002Fprepare.py\n```\n执行后将在 `data\u002Fshakespeare_char\u002F` 目录下生成 `train.bin` 和 `val.bin`。\n\n### 第二步：开始训练\n\n#### 场景 A：我有 GPU (NVIDIA 或 Apple Silicon)\n直接使用默认配置文件启动训练：\n```bash\npython train.py config\u002Ftrain_shakespeare_char.py\n```\n- **配置说明**：上下文长度 256，6 层 Transformer，6 个注意力头。\n- **预期结果**：A100 上约 3 分钟完成，最佳验证损失 (loss) 约为 1.47。\n- **Mac 用户提示**：确保使用较新的 PyTorch 版本，脚本会自动识别或使用 `--device=mps` 参数利用 Metal 加速。\n\n#### 场景 B：我只有 CPU (或配置较低的电脑)\n需要降低模型规模和训练强度以避免超时或内存溢出：\n```bash\npython train.py config\u002Ftrain_shakespeare_char.py --device=cpu --compile=False --eval_iters=20 --log_interval=1 --block_size=64 --batch_size=12 --n_layer=4 --n_head=4 --n_embd=128 --max_iters=2000 --lr_decay_iters=2000 --dropout=0.0\n```\n- **调整项**：关闭编译优化 (`--compile=False`)，减小上下文 (`--block_size=64`)，缩小模型维度，减少迭代次数。\n- **预期结果**：约 3 分钟完成，loss 约为 1.88，生成的文本质量尚可但较粗糙。\n\n### 第三步：采样与推理\n训练完成后，模型检查点将保存在 `out-shakespeare-char` 目录。运行以下命令生成文本：\n```bash\npython sample.py --out_dir=out-shakespeare-char\n```\n*(CPU 用户请添加 `--device=cpu`)*\n\n**生成示例**：\n```text\nANGELO:\nAnd cowards it be strawn to my bed,\nAnd thrust the gates of my threats,\nBecause he that ale away, and hang'd\nAn one with him.\n...\n```\n\n### 进阶：微调预训练模型 (可选)\n若想获得更好的效果，可以基于开源的 GPT-2 预训练权重进行微调：\n1. 准备数据 (使用 GPT-2 的分词器)：\n   ```bash\n   python data\u002Fshakespeare\u002Fprepare.py\n   ```\n2. 启动微调 (加载 GPT-2 小模型权重)：\n   ```bash\n   python train.py config\u002Ffinetune_shakespeare.py\n   ```\n3. 采样测试：\n   ```bash\n   python sample.py --out_dir=out-shakespeare\n   ```","某初创教育科技公司希望快速构建一个能模仿莎士比亚风格写作的小型语言模型，用于其创意写作辅助产品的原型验证。\n\n### 没有 nanoGPT 时\n- 团队需从零搭建复杂的 Transformer 训练框架，仅环境配置和基础代码编写就耗时数周。\n- 缺乏清晰的中等规模模型复现参考，难以在单卡 GPU 上高效运行，资源利用率极低。\n- 想要微调现有模型（如 GPT-2）时，因代码耦合度高，修改架构或加载权重极易引发报错。\n- 非深度学习专家的成员无法快速上手实验，只能依赖资深算法工程师排期支持。\n- 从想法到看到生成结果周期过长，导致产品迭代节奏严重滞后。\n\n### 使用 nanoGPT 后\n- 直接复用约 300 行的 `train.py` 和 `model.py`，半天内即可完成环境部署并启动训练。\n- 在单张 A100 GPU 上仅需 3 分钟即可训好一个字符级莎士比亚模型，快速验证可行性。\n- 代码结构极简且模块化，轻松加载 OpenAI 的 GPT-2 预训练权重进行微调，大幅提升生成质量。\n- 普通开发人员也能读懂核心逻辑，自主调整超参数或数据预处理流程，降低协作门槛。\n- 当天即可产出可演示的文本样本，加速内部评审与用户测试流程。\n\nnanoGPT 让中小团队能以最低成本、最快速度将大语言模型从理论转化为实际可用的原型。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_nanoGPT_81748cce.png","karpathy","Andrej","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fkarpathy_75f033eb.jpg","I like to train Deep Neural Nets on large datasets.",null,"Stanford","andrej.karpathy@gmail.com","https:\u002F\u002Ftwitter.com\u002Fkarpathy","https:\u002F\u002Fgithub.com\u002Fkarpathy",[85],{"name":86,"color":87,"percentage":88},"Python","#3572A5",100,56122,9568,"2026-04-05T16:04:34","MIT","Linux, macOS","可选但推荐。训练中等模型需 NVIDIA GPU (如 A100 40GB)；复现 GPT-2 (124M) 推荐 8x A100 40GB 节点。Mac 用户支持 MPS (Apple Silicon) 加速。CPU 亦可运行但需减小模型规模。未明确指定 CUDA 版本，需与 PyTorch 版本匹配。","未说明 (取决于模型大小，复现 GPT-2 需多卡大显存环境)",{"notes":97,"python":98,"dependencies":99},"1. macOS Apple Silicon 用户建议添加 '--device=mps' 参数以利用芯片 GPU 加速 (2-3 倍)。2. 仅 CPU 运行时需设置 '--device=cpu --compile=False' 并大幅减小模型参数。3. 多机多卡训练需配置网络互联 (推荐 InfiniBand)，否则需设置 'NCCL_IB_DISABLE=1'。4. 该仓库已被作者标记为过时 (deprecated)，建议查看其新项目 nanochat。","未说明 (需兼容 PyTorch)",[100,101,102,103,104,105,106],"torch","numpy","transformers","datasets","tiktoken","wandb","tqdm",[26,13],9,"2026-03-27T02:49:30.150509","2026-04-06T04:27:55.401362",[112,117,122,127,132,137],{"id":113,"question_zh":114,"answer_zh":115,"source_url":116},18020,"训练约 6000 次迭代后 Loss 变为 NaN，该如何解决？","这通常与数据类型（如 float16）或数值不稳定有关。建议使用 NaN 检测工具来定位问题来源。可以通过添加断言检查 Inf 和 NaN 来调试，例如使用类似 https:\u002F\u002Fgithub.com\u002FalbanD\u002Fsubclass_zoo\u002Fblob\u002Fmain\u002Fnan_detect.py 中的检测器。注意：这些断言会强制同步张量数据，可能会降低速度，但非常适合调试。此外，尝试降低学习率或检查配置中的 dtype 设置也可能有帮助。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F167",{"id":118,"question_zh":119,"answer_zh":120,"source_url":121},18021,"为什么使用 UNet 架构的 GPT 模型 Loss 很低但生成效果很差？","这是因为在压缩\u002F扩展阶段破坏了因果性（causality）。虽然自注意力部分有三角掩码防止网络“看到未来”，但 UNet 架构打破了这个限制，导致模型无法正确生成句子。这是一个已知的架构设计陷阱，不建议在需要自回归生成的任务中直接使用此类结构。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F81",{"id":123,"question_zh":124,"answer_zh":125,"source_url":126},18022,"编译模型时是否应该移除 @torch.jit.script 装饰器？","是的，如果使用 torch.compile 编译模型，建议移除 @torch.jit.script 装饰器。测试表明，移除后推理速度显著更快。此外，可以尝试使用 `torch.compile(model, mode=\"max-autotune\")` 以获得轻微的性能提升，这对长时间训练尤其有益。相关修复已在 commit 177d5f7dc5f44d6f373cd7767c2a9259d740436e 中应用。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F11",{"id":128,"question_zh":129,"answer_zh":130,"source_url":131},18023,"model.py 中的预测逻辑是如何工作的？为什么一次性能得到整个序列的 logits？","lm_head 是一个线性层，它独立地应用于每个 token 的嵌入向量。每个 token 的嵌入已经通过前面的 Transformer 层（特别是自注意力机制）包含了其之前所有 token 的信息。自注意力层通过查询（Query）和键（Key）的计算，使得每个位置都能聚合前面位置的信息（受因果掩码限制）。因此，虽然 lm_head 是并行处理的，但输入给它的每个 token 表示已经是“条件化”后的结果，无需逐步递归预测。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F200",{"id":133,"question_zh":134,"answer_zh":135,"source_url":136},18024,"如何在内存有限的情况下处理非常大的数据集（如 40GB）进行预处理和分词？","对于超大数据集，不要一次性加载到内存中。建议将数据集分割成多个小块（chunks），分别对每个块进行读取、分词和保存，最后再合并结果。可以在 prepare.py 中实现流式读取或分块处理逻辑，避免 MemoryError。这种策略类似于处理 OpenWebText 等大型数据集的标准做法。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002Fissues\u002F176",{"id":138,"question_zh":139,"answer_zh":140,"source_url":116},18025,"在 MPS (Mac) 设备上训练时遇到 NaN 问题怎么办？","在 MPS 设备上出现 NaN 问题时，可以尝试在代码中添加断言来检查 -Inf 和 NaN 值，这有时能阻止问题发生或帮助定位出错的具体算子。例如，在 forward 函数中的关键计算步骤后插入检查。虽然这会增加同步开销影响速度，但对于调试非常有效。同时，检查是否使用了不支持的精度（如 float16）或特定算子在 MPS 上的兼容性。",[]]