[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-karpathy--minGPT":3,"tool-karpathy--minGPT":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},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,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},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 真正成长为懂上",156804,2,"2026-04-15T11:34:33",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},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 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":76,"owner_location":77,"owner_email":78,"owner_twitter":76,"owner_website":79,"owner_url":80,"languages":81,"stars":90,"forks":91,"last_commit_at":92,"license":93,"difficulty_score":32,"env_os":94,"env_gpu":95,"env_ram":94,"env_deps":96,"category_tags":101,"github_topics":76,"view_count":32,"oss_zip_url":76,"oss_zip_packed_at":76,"status":17,"created_at":102,"updated_at":103,"faqs":104,"releases":133},7769,"karpathy\u002FminGPT","minGPT","A minimal PyTorch re-implementation of the OpenAI GPT (Generative Pretrained Transformer) training","minGPT 是 OpenAI GPT 模型的一个极简版 PyTorch 复现项目，由知名开发者 Andrej Karpathy 创建。它旨在剥离复杂工程外壳，用约 300 行核心代码清晰展示 Transformer 架构的训练与推理全过程，将原本庞大的代码库浓缩为易于理解的教育范本。\n\nminGPT 主要解决了现有 GPT 实现代码过于冗长、难以入门的问题。它让学习者不再迷失在复杂的工程细节中，而是专注于理解“输入索引序列，输出下一个索引概率分布”这一核心逻辑。项目结构极其精简，仅包含模型定义、字节对编码（BPE）和训练器三个核心文件，并提供了数字加法、字符级语言模型等直观示例。\n\n这款工具非常适合希望深入理解大语言模型底层原理的开发者、学生及研究人员。对于想要从零开始手写 Transformer 或进行教学演示的用户来说，minGPT 是理想的起点。其独特的技术亮点在于极致的代码可读性与模块化设计，虽然作者已推出性能更强的后续项目 nanoGPT，但 minGPT 凭借其纯粹的教育价值，依然是社区中广受推崇的经典学习资料。","\n# minGPT\n\n![mingpt](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_minGPT_readme_127202529a47.jpg)\n\nA PyTorch re-implementation of [GPT](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fgpt-2), both training and inference. minGPT tries to be small, clean, interpretable and educational, as most of the currently available GPT model implementations can a bit sprawling. GPT is not a complicated model and this implementation is appropriately about 300 lines of code (see [mingpt\u002Fmodel.py](mingpt\u002Fmodel.py)). All that's going on is that a sequence of indices feeds into a [Transformer](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03762), and a probability distribution over the next index in the sequence comes out. The majority of the complexity is just being clever with batching (both across examples and over sequence length) for efficiency.\n\n**note (Jan 2023)**: though I may continue to accept and change some details, minGPT is in a semi-archived state. For more recent developments see my rewrite [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT). Basically, minGPT became referenced across a wide variety of places (notebooks, blogs, courses, books, etc.) which made me less willing to make the bigger changes I wanted to make to move the code forward. I also wanted to change the direction a bit, from a sole focus on education to something that is still simple and hackable but has teeth (reproduces medium-sized industry benchmarks, accepts some tradeoffs to gain runtime efficiency, etc).\n\nThe minGPT library is three files: [mingpt\u002Fmodel.py](mingpt\u002Fmodel.py) contains the actual Transformer model definition, [mingpt\u002Fbpe.py](mingpt\u002Fbpe.py) contains a mildly refactored Byte Pair Encoder that translates between text and sequences of integers exactly like OpenAI did in GPT, [mingpt\u002Ftrainer.py](mingpt\u002Ftrainer.py) is (GPT-independent) PyTorch boilerplate code that trains the model. Then there are a number of demos and projects that use the library in the `projects` folder:\n\n- `projects\u002Fadder` trains a GPT from scratch to add numbers (inspired by the addition section in the GPT-3 paper)\n- `projects\u002Fchargpt` trains a GPT to be a character-level language model on some input text file\n- `demo.ipynb` shows a minimal usage of the `GPT` and `Trainer` in a notebook format on a simple sorting example\n- `generate.ipynb` shows how one can load a pretrained GPT2 and generate text given some prompt\n\n### Library Installation\n\nIf you want to `import mingpt` into your project:\n\n```\ngit clone https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT.git\ncd minGPT\npip install -e .\n```\n\n### Usage\n\nHere's how you'd instantiate a GPT-2 (124M param version):\n\n```python\nfrom mingpt.model import GPT\nmodel_config = GPT.get_default_config()\nmodel_config.model_type = 'gpt2'\nmodel_config.vocab_size = 50257 # openai's model vocabulary\nmodel_config.block_size = 1024  # openai's model block_size (i.e. input context length)\nmodel = GPT(model_config)\n```\n\nAnd here's how you'd train it:\n\n```python\n# your subclass of torch.utils.data.Dataset that emits example\n# torch LongTensor of lengths up to 1024, with integers from [0,50257)\ntrain_dataset = YourDataset()\n\nfrom mingpt.trainer import Trainer\ntrain_config = Trainer.get_default_config()\ntrain_config.learning_rate = 5e-4 # many possible options, see the file\ntrain_config.max_iters = 1000\ntrain_config.batch_size = 32\ntrainer = Trainer(train_config, model, train_dataset)\ntrainer.run()\n```\n\nSee `demo.ipynb` for a more concrete example.\n\n### Unit tests\n\nCoverage is not super amazing just yet but:\n\n```\npython -m unittest discover tests\n```\n\n### todos\n\n- add gpt-2 finetuning demo on arbitrary given text file\n- add dialog agent demo\n- better docs of outcomes for existing projects (adder, chargpt)\n- add mixed precision and related training scaling goodies\n- distributed training support\n- reproduce some benchmarks in projects\u002F, e.g. text8 or other language modeling\n- proper logging instead of print statement amateur hour haha\n- i probably should have a requirements.txt file...\n- it should be possible to load in many other model weights other than just gpt2-\\*\n\n### References\n\nCode:\n\n- [openai\u002Fgpt-2](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fgpt-2) has the model definition in TensorFlow, but not the training code\n- [openai\u002Fimage-gpt](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fimage-gpt) has some more modern gpt-3 like modification in its code, good reference as well\n- [huggingface\u002Ftransformers](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftransformers) has a [language-modeling example](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftransformers\u002Ftree\u002Fmaster\u002Fexamples\u002Fpytorch\u002Flanguage-modeling). It is full-featured but as a result also somewhat challenging to trace. E.g. some large functions have as much as 90% unused code behind various branching statements that is unused in the default setting of simple language modeling\n\nPapers + some implementation notes:\n\n#### Improving Language Understanding by Generative Pre-Training (GPT-1)\n\n- Our model largely follows the original transformer work\n- We trained a 12-layer decoder-only transformer with masked self-attention heads (768 dimensional states and 12 attention heads). For the position-wise feed-forward networks, we used 3072 dimensional inner states.\n- Adam max learning rate of 2.5e-4. (later GPT-3 for this model size uses 6e-4)\n- LR decay: increased linearly from zero over the first 2000 updates and annealed to 0 using a cosine schedule\n- We train for 100 epochs on minibatches of 64 randomly sampled, contiguous sequences of 512 tokens.\n- Since layernorm is used extensively throughout the model, a simple weight initialization of N(0, 0.02) was sufficient\n- bytepair encoding (BPE) vocabulary with 40,000 merges\n- residual, embedding, and attention dropouts with a rate of 0.1 for regularization.\n- modified version of L2 regularization proposed in (37), with w = 0.01 on all non bias or gain weights\n- For the activation function, we used the Gaussian Error Linear Unit (GELU).\n- We used learned position embeddings instead of the sinusoidal version proposed in the original work\n- For finetuning: We add dropout to the classifier with a rate of 0.1. learning rate of 6.25e-5 and a batchsize of 32. 3 epochs. We use a linear learning rate decay schedule with warmup over 0.2% of training. λ was set to 0.5.\n- GPT-1 model is 12 layers and d_model 768, ~117M params\n\n#### Language Models are Unsupervised Multitask Learners (GPT-2)\n\n- LayerNorm was moved to the input of each sub-block, similar to a pre-activation residual network\n- an additional layer normalization was added after the final self-attention block.\n- modified initialization which accounts for the accumulation on the residual path with model depth is used. We scale the weights of residual layers at initialization by a factor of 1\u002F√N where N is the number of residual layers. (weird because in their released code i can only find a simple use of the old 0.02... in their release of image-gpt I found it used for c_proj, and even then only for attn, not for mlp. huh. https:\u002F\u002Fgithub.com\u002Fopenai\u002Fimage-gpt\u002Fblob\u002Fmaster\u002Fsrc\u002Fmodel.py)\n- the vocabulary is expanded to 50,257\n- increase the context size from 512 to 1024 tokens\n- larger batchsize of 512 is used\n- GPT-2 used 48 layers and d_model 1600 (vs. original 12 layers and d_model 768). ~1.542B params\n\n#### Language Models are Few-Shot Learners (GPT-3)\n\n- GPT-3: 96 layers, 96 heads, with d_model of 12,288 (175B parameters).\n- GPT-1-like: 12 layers, 12 heads, d_model 768 (125M)\n- We use the same model and architecture as GPT-2, including the modified initialization, pre-normalization, and reversible tokenization described therein\n- we use alternating dense and locally banded sparse attention patterns in the layers of the transformer, similar to the Sparse Transformer\n- we always have the feedforward layer four times the size of the bottleneck layer, dff = 4 ∗ dmodel\n- all models use a context window of nctx = 2048 tokens.\n- Adam with β1 = 0.9, β2 = 0.95, and eps = 10−8\n- All models use weight decay of 0.1 to provide a small amount of regularization. (NOTE: GPT-1 used 0.01 I believe, see above)\n- clip the global norm of the gradient at 1.0\n- Linear LR warmup over the first 375 million tokens. Then use cosine decay for learning rate down to 10% of its value, over 260 billion tokens.\n- gradually increase the batch size linearly from a small value (32k tokens) to the full value over the first 4-12 billion tokens of training, depending on the model size.\n- full 2048-sized time context window is always used, with a special END OF DOCUMENT token delimiter\n\n#### Generative Pretraining from Pixels (Image GPT)\n\n- When working with images, we pick the identity permutation πi = i for 1 ≤ i ≤ n, also known as raster order.\n- we create our own 9-bit color palette by clustering (R, G, B) pixel values using k-means with k = 512.\n- Our largest model, iGPT-XL, contains L = 60 layers and uses an embedding size of d = 3072 for a total of 6.8B parameters.\n- Our next largest model, iGPT-L, is essentially identical to GPT-2 with L = 48 layers, but contains a slightly smaller embedding size of d = 1536 (vs 1600) for a total of 1.4B parameters.\n- We use the same model code as GPT-2, except that we initialize weights in the layerdependent fashion as in Sparse Transformer (Child et al., 2019) and zero-initialize all projections producing logits.\n- We also train iGPT-M, a 455M parameter model with L = 36 and d = 1024\n- iGPT-S, a 76M parameter model with L = 24 and d = 512 (okay, and how many heads? looks like the Github code claims 8)\n- When pre-training iGPT-XL, we use a batch size of 64 and train for 2M iterations, and for all other models we use a batch size of 128 and train for 1M iterations.\n- Adam with β1 = 0.9 and β2 = 0.95\n- The learning rate is warmed up for one epoch, and then decays to 0\n- We did not use weight decay because applying a small weight decay of 0.01 did not change representation quality.\n- iGPT-S lr 0.003\n- No dropout is used.\n\n### License\n\nMIT\n","# minGPT\n\n![mingpt](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_minGPT_readme_127202529a47.jpg)\n\n一个基于 PyTorch 的 [GPT](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fgpt-2) 重新实现，支持训练和推理。minGPT 致力于保持代码简洁、易懂且具有教育意义，因为目前大多数可用的 GPT 模型实现往往过于冗长。实际上，GPT 并不是一个复杂的模型，而这个实现也恰如其分地控制在约 300 行代码内（参见 [mingpt\u002Fmodel.py](mingpt\u002Fmodel.py)）。其核心逻辑非常简单：将一串索引序列输入到一个 [Transformer](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03762) 中，然后输出下一个序列索引的概率分布。大部分复杂性其实都集中在如何通过巧妙地进行批处理（包括跨样本和跨序列长度的批处理）来提升效率。\n\n**注（2023年1月）**：尽管我可能还会接受一些小的改动，但 minGPT 已经处于半存档状态。如需了解更近的发展，请参阅我的重写版本 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT)。基本上，minGPT 在许多地方（例如笔记本、博客、课程、书籍等）被广泛引用，这让我不太愿意再对其做出较大的改动以推动代码向前发展。此外，我也希望稍微调整方向，不再仅仅专注于教育用途，而是让代码在保持简单易用的同时，具备一定的实用性（例如能够复现中等规模的工业基准、在运行效率上做出适当权衡等）。\n\nminGPT 库由三个文件组成：[mingpt\u002Fmodel.py](mingpt\u002Fmodel.py) 包含实际的 Transformer 模型定义；[mingpt\u002Fbpe.py](mingpt\u002Fbpe.py) 包含一个经过轻微重构的字节对编码器，它与 OpenAI 在 GPT 中使用的完全一致，用于在文本和整数序列之间进行转换；[mingpt\u002Ftrainer.py](mingpt\u002Ftrainer.py) 是与 GPT 无关的 PyTorch 样板代码，用于训练模型。此外，在 `projects` 文件夹中还包含多个使用该库的示例和项目：\n\n- `projects\u002Fadder` 训练一个从零开始的 GPT 模型来执行加法运算（灵感来自 GPT-3 论文中的加法部分）。\n- `projects\u002Fchargpt` 训练一个基于字符级别的语言模型，用于处理指定的输入文本文件。\n- `demo.ipynb` 展示了如何在笔记本中以最简方式使用 `GPT` 和 `Trainer` 类，并以一个简单的排序任务为例。\n- `generate.ipynb` 则演示了如何加载预训练好的 GPT-2 模型，并根据给定的提示生成文本。\n\n### 库的安装\n\n若要在你的项目中引入 `mingpt`：\n\n```\ngit clone https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT.git\ncd minGPT\npip install -e .\n```\n\n### 使用方法\n\n以下是如何实例化一个 GPT-2（1.24亿参数版本）的示例：\n\n```python\nfrom mingpt.model import GPT\nmodel_config = GPT.get_default_config()\nmodel_config.model_type = 'gpt2'\nmodel_config.vocab_size = 50257 # OpenAI 模型的词汇表大小\nmodel_config.block_size = 1024  # OpenAI 模型的块大小（即输入上下文长度）\nmodel = GPT(model_config)\n```\n\n以下是训练该模型的方法：\n\n```python\n# 你的 torch.utils.data.Dataset 子类，输出长度不超过 1024 的 torch LongTensor，\n# 其中包含 [0,50257) 范围内的整数。\ntrain_dataset = YourDataset()\n\nfrom mingpt.trainer import Trainer\ntrain_config = Trainer.get_default_config()\ntrain_config.learning_rate = 5e-4 # 还有许多可配置的选项，详见文档\ntrain_config.max_iters = 1000\ntrain_config.batch_size = 32\ntrainer = Trainer(train_config, model, train_dataset)\ntrainer.run()\n```\n\n更多具体的示例请参考 `demo.ipynb`。\n\n### 单元测试\n\n目前覆盖率还不是很高，但可以通过以下命令运行测试：\n\n```\npython -m unittest discover tests\n```\n\n### 待办事项\n\n- 添加针对任意文本文件的 GPT-2 微调示例。\n- 添加对话代理示例。\n- 改进现有项目（adder、chargpt）的结果文档。\n- 引入混合精度训练及相关扩展功能。\n- 实现分布式训练支持。\n- 在 projects\u002F 目录下复现一些基准数据集，例如 text8 或其他语言建模任务。\n- 替换掉当前的 print 语句，改为更专业的日志记录。\n- 增加 requirements.txt 文件。\n- 应该能够加载除 gpt2-* 之外的其他模型权重。\n\n### 参考资料\n\n代码：\n\n- [openai\u002Fgpt-2](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fgpt-2) 提供了 TensorFlow 中的模型定义，但没有训练代码。\n- [openai\u002Fimage-gpt](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fimage-gpt) 的代码中包含了一些更现代、类似 GPT-3 的改进，也是一个很好的参考。\n- [huggingface\u002Ftransformers](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftransformers) 提供了一个 [语言建模示例](https:\u002F\u002Fgithub.com\u002Fhuggingface\u002Ftransformers\u002Ftree\u002Fmaster\u002Fexamples\u002Fpytorch\u002Flanguage-modeling)。这个示例功能齐全，但也因此相对难以追踪。例如，一些大型函数中有高达 90% 的代码在默认的简单语言建模设置下是未被使用的。\n\n论文 + 一些实现说明：\n\n#### 通过生成式预训练提升语言理解能力（GPT-1）\n\n- 我们的模型基本遵循原始的 Transformer 工作。\n- 我们训练了一个 12 层的仅解码器架构的 Transformer，使用掩码自注意力头（状态维度为 768，注意力头数为 12）。对于位置前馈网络，我们使用了 3072 维的内部状态。\n- Adam 优化器的最大学习率为 2.5e-4。 （后来 GPT-3 对于该模型规模使用的是 6e-4）\n- 学习率衰减：在前 2000 次更新中从零线性增加，并使用余弦退火调度将其衰减至零。\n- 我们在 64 个随机采样的连续 512 个标记的 mini-batch 上训练 100 个 epoch。\n- 由于模型中广泛使用层归一化，简单的权重初始化方法 N(0, 0.02) 就足够了。\n- 使用字节对编码（BPE）词汇表，包含 40,000 次合并。\n- 为了正则化，我们在残差连接、嵌入和注意力机制中分别使用了 0.1 的 dropout 率。\n- 使用了 (37) 中提出的修改版 L2 正则化，对所有非偏置或增益权重设置 w = 0.01。\n- 激活函数我们使用了高斯误差线性单元（GELU）。\n- 我们使用了可学习的位置嵌入，而不是原始工作中提出的正弦形式。\n- 微调时：我们在分类器上添加了 0.1 的 dropout 率，学习率为 6.25e-5，批量大小为 32。训练 3 个 epoch。我们使用带有 0.2% 预热期的线性学习率衰减调度。λ 设置为 0.5。\n- GPT-1 模型有 12 层，d_model 为 768，参数量约为 1.17 亿。\n\n#### 语言模型是无监督的多任务学习者（GPT-2）\n\n- LayerNorm 被移到每个子模块的输入端，类似于预激活残差网络。\n- 在最后一个自注意力块之后，又增加了一层归一化。\n- 使用了考虑了随着模型深度增加而累积在残差路径上的改进初始化方法。我们在初始化时将残差层的权重按 1\u002F√N 的因子缩放，其中 N 是残差层的数量。（奇怪的是，在他们发布的代码中，我只看到简单地使用了旧的 0.02 初始化方式……而在他们发布的 image-gpt 代码中，我发现它只用于 c_proj，而且还是仅限于注意力机制，而非前馈网络。嗯。https:\u002F\u002Fgithub.com\u002Fopenai\u002Fimage-gpt\u002Fblob\u002Fmaster\u002Fsrc\u002Fmodel.py）\n- 词汇表扩展到 50,257 个词。\n- 上下文长度由 512 增加到 1024 个标记。\n- 使用更大的批量大小 512。\n- GPT-2 使用了 48 层，d_model 为 1600（相比之下，原始的 GPT-1 是 12 层，d_model 为 768）。参数量约为 15.42 亿。\n\n#### 语言模型是少样本学习者（GPT-3）\n\n- GPT-3：96 层，96 个注意力头，d_model 为 12,288（1750 亿参数）。\n- 类似 GPT-1 的版本：12 层，12 个注意力头，d_model 为 768（1.25 亿参数）。\n- 我们使用与 GPT-2 相同的模型和架构，包括其中描述的改进初始化、预归一化和可逆分词。\n- 我们在 Transformer 的各层中交替使用密集和局部带状稀疏注意力模式，类似于稀疏 Transformer。\n- 前馈层的大小始终是瓶颈层的四倍，即 dff = 4 ∗ dmodel。\n- 所有模型都使用 nctx = 2048 个标记的上下文窗口。\n- Adam 优化器设置为 β1 = 0.9，β2 = 0.95，eps = 10−8。\n- 所有模型都使用 0.1 的权重衰减来提供少量正则化。（注：GPT-1 使用的是 0.01，见上文）\n- 将梯度的全局范数限制在 1.0。\n- 在前 3.75 亿个标记处进行线性学习率预热。随后在接下来的 2600 亿个标记内，使用余弦衰减将学习率降至其初始值的 10%。\n- 根据模型规模的不同，在训练的前 40 亿到 120 亿个标记期间，逐步线性地将批量大小从较小值（3.2 万标记）增加到最大值。\n- 始终使用完整的 2048 标记时间上下文窗口，并使用特殊的“文档结束”标记作为分隔符。\n\n#### 从像素进行生成式预训练（Image GPT）\n\n- 处理图像时，我们选择恒等排列 πi = i，其中 1 ≤ i ≤ n，也称为光栅顺序。\n- 我们通过 k-means 聚类算法，以 k = 512 的聚类数，对 (R, G, B) 像素值进行聚类，从而创建了自己的 9 位颜色 palette。\n- 我们的最大模型 iGPT-XL 包含 L = 60 层，使用 d = 3072 的嵌入大小，总参数量为 68 亿。\n- 我们的次大模型 iGPT-L 本质上与 GPT-2 相同，都是 L = 48 层，但嵌入大小稍小，为 d = 1536（相比 GPT-2 的 1600），总参数量为 14 亿。\n- 我们使用与 GPT-2 相同的模型代码，只是按照稀疏 Transformer（Child 等，2019）中的逐层初始化方式来初始化权重，并将所有产生 logits 的投影层初始化为零。\n- 我们还训练了 iGPT-M，一个 4.55 亿参数的模型，具有 L = 36 层和 d = 1024。\n- iGPT-S 是一个 7600 万参数的模型，拥有 L = 24 层和 d = 512。（那么它的注意力头数是多少呢？看起来 GitHub 代码声称是 8 个。）\n- 在预训练 iGPT-XL 时，我们使用 64 的批量大小并训练 200 万次迭代；而对于其他模型，则使用 128 的批量大小并训练 100 万次迭代。\n- Adam 优化器设置为 β1 = 0.9 和 β2 = 0.95。\n- 学习率会先预热一个 epoch，然后逐渐衰减至零。\n- 我们没有使用权重衰减，因为即使应用了 0.01 的小权重衰减，也并未改善表示质量。\n- iGPT-S 的学习率设为 0.003。\n- 不使用 dropout。\n\n### 许可证\n\nMIT","# minGPT 快速上手指南\n\nminGPT 是一个基于 PyTorch 的 GPT 模型精简实现，旨在保持代码小巧（约 300 行）、清晰且易于教学。它涵盖了从训练到推理的完整流程，适合希望深入理解 Transformer 架构原理的开发者。\n\n> **注意**：该项目目前处于半归档状态。如需关注更近期的优化和工业级基准复现，建议参考作者的重写版本 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT)。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**：Linux, macOS 或 Windows\n*   **Python 版本**：推荐 Python 3.8 及以上\n*   **核心依赖**：\n    *   PyTorch (最新稳定版)\n    *   NumPy\n    *   tqdm (用于进度条显示)\n    *   torchdata (可选，视具体数据集加载方式而定)\n\n建议使用 `conda` 或 `venv` 创建独立的虚拟环境以避免依赖冲突。\n\n## 安装步骤\n\n通过克隆仓库并以可编辑模式安装，以便您可以直接修改源码或运行示例项目。\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT.git\ncd minGPT\npip install -e .\n```\n\n*国内用户提示：如果下载速度较慢，可在 `pip install` 命令后添加 `-i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple` 使用清华镜像源加速安装依赖。*\n\n## 基本使用\n\nminGPT 的核心用法分为模型实例化和训练两个步骤。以下是最小化的使用示例。\n\n### 1. 实例化模型\n\n您可以轻松配置并实例化一个 GPT-2 (124M 参数) 版本的模型：\n\n```python\nfrom mingpt.model import GPT\n\n# 获取默认配置\nmodel_config = GPT.get_default_config()\n\n# 设置模型类型为 gpt2\nmodel_config.model_type = 'gpt2'\n\n# 设置词汇表大小 (OpenAI 官方模型的词汇量)\nmodel_config.vocab_size = 50257 \n\n# 设置上下文长度 (block_size)\nmodel_config.block_size = 1024  \n\n# 初始化模型\nmodel = GPT(model_config)\n```\n\n### 2. 配置并启动训练\n\n训练过程由 `Trainer` 类管理。您需要准备一个继承自 `torch.utils.data.Dataset` 的数据集，该数据集应返回长度不超过 `block_size` 的整数序列（LongTensor）。\n\n```python\n# 假设您已经定义好了数据集类 YourDataset\n# 该数据集输出形状为 [block_size] 的 LongTensor，数值范围在 [0, vocab_size)\ntrain_dataset = YourDataset()\n\nfrom mingpt.trainer import Trainer\n\n# 获取训练默认配置\ntrain_config = Trainer.get_default_config()\n\n# 配置超参数\ntrain_config.learning_rate = 5e-4  # 学习率\ntrain_config.max_iters = 1000      # 最大迭代次数\ntrain_config.batch_size = 32       # 批次大小\n\n# 初始化训练器\ntrainer = Trainer(train_config, model, train_dataset)\n\n# 开始训练\ntrainer.run()\n```\n\n更多具体的实战案例（如字符级语言模型、数学加法训练等），请参阅项目根目录下的 `projects` 文件夹及 `demo.ipynb` Notebook 文件。","某高校深度学习课程的教学团队希望带领学生从零开始理解 GPT 架构，但受限于现有代码库的复杂性，难以开展有效的原理教学。\n\n### 没有 minGPT 时\n- 主流开源实现代码量庞大且结构 sprawling，学生需花费数周梳理工程细节而非关注核心算法。\n- 缺乏清晰的模块化设计，模型定义、分词器与训练循环耦合严重，导致调试和修改极其困难。\n- 难以通过阅读代码直观理解\"输入索引序列到输出概率分布”这一核心变换过程，学习曲线陡峭。\n- 缺少轻量级的示例项目（如字符级语言模型或数字加法），学生无法快速验证理论并建立信心。\n\n### 使用 minGPT 后\n- 核心模型代码仅约 300 行，结构极简清晰，学生可在一天内通读并掌握 Transformer 在 GPT 中的具体应用。\n- 库文件严格分离为模型定义、BPE 分词器和通用训练器，支持学生独立修改任一模块以进行对照实验。\n- 数据流向高度透明，直观展示了序列索引如何经过注意力机制转化为下一个 token 的概率分布。\n- 内置 `chargpt` 和 `adder` 等微型项目，让学生能立即动手训练一个微型 GPT，快速闭环理论与实践。\n\nminGPT 通过将工业级模型剥离至最简形态，成功将 GPT 的学习门槛从“工程考古”降低为“原理研读”。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fkarpathy_minGPT_b7586255.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",[82,86],{"name":83,"color":84,"percentage":85},"Python","#3572A5",74.8,{"name":87,"color":88,"percentage":89},"Jupyter Notebook","#DA5B0B",25.2,24150,3211,"2026-04-15T08:28:52","MIT","未说明","未说明 (基于 PyTorch，训练大型模型通常建议配备 NVIDIA GPU)",{"notes":97,"python":94,"dependencies":98},"该工具是一个极简的 GPT PyTorch 实现，主要用于教育和代码解读。README 中未提供具体的 requirements.txt 文件，仅明确依赖 PyTorch。由于代码简洁（约 300 行），它不依赖庞大的生态系统（如 transformers 库）。具体硬件需求取决于所训练的模型大小（如 GPT-2 124M 或更大版本）和批次大小。作者提示该项目处于半归档状态，建议有新需求的用户参考其后续项目 nanoGPT。",[99,100],"torch","numpy",[35,14],"2026-03-27T02:49:30.150509","2026-04-16T01:44:50.618710",[105,110,115,119,124,129],{"id":106,"question_zh":107,"answer_zh":108,"source_url":109},34790,"如何正确地在 PyTorch 中分离需要和不需要权重衰减的参数？","推荐在模型内部实现参数分组逻辑。具体步骤如下：\n1. 定义白名单模块（如 torch.nn.Linear）和黑名单模块（如 torch.nn.LayerNorm, torch.nn.Embedding）。\n2. 遍历 model.named_modules() 和 named_parameters()。\n3. 构造完整参数名 fpn。\n4. 规则：\n   - 如果参数名以 'bias' 结尾 -> 不衰减。\n   - 如果参数名以 'weight' 结尾且模块在白名单中 -> 衰减。\n   - 如果参数名以 'weight' 结尾且模块在黑名单中 -> 不衰减。\n这种方法比在训练循环中硬编码更灵活，也更容易迁移到其他框架（如 Lightning）。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT\u002Fissues\u002F23",{"id":111,"question_zh":112,"answer_zh":113,"source_url":114},34785,"为什么 CharDataset 在训练时会导致数据重复和过拟合？","这是因为 CharDataset 与多进程（multiprocessing）不兼容。当 DataLoader 的 num_workers 大于 1 时，随机数生成器的状态会被复制到多个工作进程中，导致每个进程生成相同的“随机”索引序列，从而重复返回相同的数据批次。\n解决方案：\n1. 临时方案：将 num_workers 设置为 1。\n2. 根本修复：修改 CharDataset，移除 __getitem__ 中的随机逻辑，改为使用顺序索引（i = idx），并在 DataLoader 中设置 shuffle=True。这样既避免了多进程问题，又保持了数据的随机性。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT\u002Fissues\u002F28",{"id":116,"question_zh":117,"answer_zh":118,"source_url":109},34786,"LayerNorm 的权重是否应该应用权重衰减（Weight Decay）？","不应该。LayerNorm 和 Embedding 层的权重通常不应应用权重衰减，只有 Linear 层的权重和偏置项需要特殊处理（偏置通常也不衰减）。\n最佳实践是将此逻辑耦合在模型代码内部，而不是放在训练器中。可以通过遍历模块，将 LayerNorm 和 Embedding 加入黑名单（blacklist），Linear 加入白名单（whitelist），或者简单地判断：如果参数属于黑名单模块或以 'bias' 结尾，则不衰减；如果是 'weight' 且不属于黑名单，则进行衰减。",{"id":120,"question_zh":121,"answer_zh":122,"source_url":123},34787,"在构建训练数据时，为什么目标序列 y 是输入序列 x 向后偏移一位，而不是只取最后一个字符？","这是为了在序列长度维度上进行批处理优化（amortizing the forward pass）。虽然推理时可能只需要预测下一个 token，但在训练时，让模型对序列中的每一个位置都进行预测（即输入 [0, 1, ..., N-1]，目标 [1, 2, ..., N]），可以充分利用计算资源，提高训练效率。\n这种做法还使模型能够适应不同长度的上下文窗口，即使测试时的提示词长度小于训练的 block_size，模型也能正常工作。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT\u002Fissues\u002F5",{"id":125,"question_zh":126,"answer_zh":127,"source_url":128},34788,"简化权重衰减筛选逻辑时，为什么会出现参数重复或分类错误的问题？","在使用简化的 if-else 逻辑筛选参数时，容易忽略对参数类型的精确判断。原始代码通过显式检查模块类型（如 Linear, LayerNorm）和参数名后缀（bias, weight）来分类。\n如果在简化代码中使用 `else` 直接归类为需衰减，可能会错误地将非 weight 参数包含进去。正确的简化逻辑应该是：\nif pn.endswith(\"bias\") or isinstance(m, blacklist_weight_modules):\n    no_decay.add(fpn)\nelif pn.endswith(\"weight\"):\n    decay.add(fpn)\n必须显式检查 `pn.endswith(\"weight\")`，以确保只有权重参数被加入衰减集合，避免逻辑漏洞。","https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FminGPT\u002Fissues\u002F112",{"id":130,"question_zh":131,"answer_zh":132,"source_url":114},34789,"如何解决 play_char 训练中因多进程导致的随机种子同步问题？","问题的根源在于多进程环境下随机状态被复制。除了将 num_workers 设为 1 外，更推荐的架构调整是：\n1. 修改 CharDataset 的 __len__ 返回有效序列长度。\n2. 修改 __getitem__ 使其不再随机采样，而是直接返回索引对应的切片（确定性输出）。\n3. 在 DataLoader 初始化时启用 shuffle=True。\n4. 移除训练器中对 epoch 的强依赖，改为基于迭代次数（iterations）进行日志记录和训练控制。这样既解决了多进程问题，又符合“基于原始迭代次数思考”的训练理念。",[]]