[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-ConnorJL--GPT2":3,"tool-ConnorJL--GPT2":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 真正成长为懂上",142651,2,"2026-04-06T23:34:12",[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 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107888,"2026-04-06T11:32:50",[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},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":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":10,"last_commit_at":59,"category_tags":60,"status":17},4487,"LLMs-from-scratch","rasbt\u002FLLMs-from-scratch","LLMs-from-scratch 是一个基于 PyTorch 的开源教育项目，旨在引导用户从零开始一步步构建一个类似 ChatGPT 的大型语言模型（LLM）。它不仅是同名技术著作的官方代码库，更提供了一套完整的实践方案，涵盖模型开发、预训练及微调的全过程。\n\n该项目主要解决了大模型领域“黑盒化”的学习痛点。许多开发者虽能调用现成模型，却难以深入理解其内部架构与训练机制。通过亲手编写每一行核心代码，用户能够透彻掌握 Transformer 架构、注意力机制等关键原理，从而真正理解大模型是如何“思考”的。此外，项目还包含了加载大型预训练权重进行微调的代码，帮助用户将理论知识延伸至实际应用。\n\nLLMs-from-scratch 特别适合希望深入底层原理的 AI 开发者、研究人员以及计算机专业的学生。对于不满足于仅使用 API，而是渴望探究模型构建细节的技术人员而言，这是极佳的学习资源。其独特的技术亮点在于“循序渐进”的教学设计：将复杂的系统工程拆解为清晰的步骤，配合详细的图表与示例，让构建一个虽小但功能完备的大模型变得触手可及。无论你是想夯实理论基础，还是为未来研发更大规模的模型做准备",90106,"2026-04-06T11:19:32",[35,15,13,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":76,"owner_email":76,"owner_twitter":77,"owner_website":78,"owner_url":79,"languages":80,"stars":89,"forks":90,"last_commit_at":91,"license":92,"difficulty_score":93,"env_os":94,"env_gpu":95,"env_ram":94,"env_deps":96,"category_tags":109,"github_topics":76,"view_count":32,"oss_zip_url":76,"oss_zip_packed_at":76,"status":17,"created_at":110,"updated_at":111,"faqs":112,"releases":142},4838,"ConnorJL\u002FGPT2","GPT2","An implementation of training for GPT2, supports TPUs","GPT2 是一个开源的深度学习项目，旨在复现并训练 OpenAI 发布的 GPT-2 语言模型。它核心解决了开发者在本地或云端环境中从头训练大型文本生成模型的难题，支持基于 GPU 和 TPU（张量处理单元）的高效计算架构。\n\n该项目特别适合人工智能研究人员、算法工程师以及希望深入理解大模型训练机制的开发者使用。与普通用户直接调用 API 不同，GPT2 提供了完整的训练脚本、数据预处理工具及预训练模型下载功能，允许用户自定义数据集并进行模型微调。\n\n其独特的技术亮点在于对 TPU 集群的原生支持，这使得在大规模算力环境下加速训练成为可能。项目提供了从 1.17 亿到 15 亿参数不等的多种预训练模型版本，并包含详细的文本生成与数据集构建指南。需要注意的是，作者明确声明此为非官方实现，虽尽力遵循原模型规格，但在最终性能上可能与原版存在差距，且部分数据集脚本需要根据具体需求进行调整。对于想要探索大语言模型底层原理或进行实验性研究的团队来说，这是一个极具参考价值的实践框架。","# GPT2\n**Disclaimer: This is not the official GPT2 implementation! I've done my best to follow the specifications of the original GPT2 model as closely as possible, but be warned that I have not been able to replicate the full performance of the original model using this code. I don't know why this is, I haven't been able to track down any bug that could be causing this.**\n\nAn implementation of training for [GPT2](https:\u002F\u002Fopenai.com\u002Fblog\u002Fbetter-language-models\u002F) that supports both GPUs and TPUs. The dataset scripts are a bit hacky and will probably need to be adapted to your needs. \n## Requirements\nFor GPUs:\n\n`pip3 install tensorflow-gpu regex`\n\nFor TPUs:\n\n`pip3 install tensorflow regex google-api-python-client oauth2client`\n\nFor downloading the models:\n\n`pip3 install requests tqdm`\n\nFor generating the dataset (in addition to Tensorflow):\n\n`pip3 install ftfy tqdm newspaper3k`\n\n## Downloading Pretrained Models\nIf you want to use my models, I currently have \"117M\", \"PrettyBig\" and \"1.5B\" to offer. 117M was trained on a single v2 TPU for a week (probably less than the original OpenAI model), PrettyBig is slightly bigger than 345M and was trained on a v2-256 pod for a week. ~~I was originally also planning to release my version of the 1.5B model, but have decided against it. You can read about my reasoning [here](https:\u002F\u002Fmedium.com\u002F@NPCollapse\u002Fthe-hacker-learns-to-trust-62f3c1490f51).~~ Since OpenAI has released their model, I have now also released my (inferior) 1.5B model, which was trained on a v3-512 pod for a week.\n\n`python3 download_model.py PrettyBig`\n\nThis will create two directories, one named as the model and another named \"encoder\". Change the \"model_dir\" and \"encoder_path\" parameters in the .json corresponding to your model to point to these paths, respectively.\n\nIf you only want the encoder, use:\n\n`python3 download_model.py encoder`\n\n## Generating Text\nTo predict you can either pass the prompt directly in the command line, or have it read from a file. (This is useful for prompts that include newlines) Text is output to the console and the file specified in the \"predict_path\" parameter. You need a model checkpoint and a copy of the BPE encoder at an accessible location for this to work. (Change the \"model_dir\" and \"encoder_path\" parameters in the .json)\n\nFrom command line:\n\n`python3 main.py --model Your-Model.json [--top_k Top-K-Truncation] --predict_text \"Hello there! My name is\"`\n\nFrom file:\n\n`python3 main.py --model Your-Model.json [--top_k Top-K-Truncation] --predict_file input.txt`\n\nThe optional top_k parameter causes the model to only consider the top k most likely tokens at each step. Setting this around 40 tends to create better results, but with less variety. \n\nPrediction on TPUs is not supported.\n\n\n## Training\nTo train a model, define its parameters in a .json file (see examples) and then simply call\n\n`python3 main.py --model Your-Model.json [--tpu Your-TPU-Name]`\n\nUsing a TPU is optional, it runs fine on GPUs without modification. (Note: Evaluation doesn't work on TPU pods and must be commented out) \n\nThis assumes you have a version of the openwebtext corpus stored in an accessible location. If you don't, see below how to generate your own version.\n\n\n\n## Generating the Dataset\nGPT2 is trained on the webtext corpus, which is basically all websites linked to from Reddit with at least 3 Karma. Since the database is huge and contains a lot of copyrighted material, I can't provide a download here. Instead, I'll describe how I got it. Be aware it cost me around ~500€ in cloud compute resources to download and process the whole thing, but I'm not claiming I was optimally efficient. \n1. Use the download script from [here](https:\u002F\u002Fgithub.com\u002Fjcpeterson\u002Fopenwebtext) to download the archives (I used the prefiltered URLs file)\n2. Use *datasets\u002Fopenwebtext\u002F\nrun_newspaper_extract.py* to extract the text\n3. Once you have the raw .txt files use *datasets\u002Fopenwebtext\u002F\ncreate_tfrecords.py* to encode them into .tfrecords files (Requires a copy of the encoder, see Downloading Pretrained Models)\n4. Place the .tfrecords files into an accessible folder or Google Storage bucket (Placing in a Google Storage bucket is mandatory if you're using TPUs)\n5. Change the \"data_path\" parameter in your .json to point to where your .tfrecords files are located and, if necessary, adapt the functions in *inputs.py* to open the correct filenames, in case you changed them\n\n## Using Your Own Data\nYou can also use your own text files as training data, but you'll need to modify some code by hand.\n1. Modify the parameters in *datasets\u002Fopenwebtext\u002Fcreate_tfrecords.py*:\n\n```python\nbase_dir = \"\u002Fhome\u002Fconnor\u002Fmy_text_dir\" # Path to where your .txt files are located\nfiles_per = 175000 # How many txt files to put in one tfrecord, not too important\nname = \"my-custom-data\" # Name of output files will be name_i.tfrecords where i is the number of the file\noutput_dir = \"\u002Fhome\u002Fconnor\u002Foutput\" # Where to place the .tfrecords files\nlog_dir = \"logs\" # Some logs will be placed here to support restarting if the encoding is interrupted\nfiles = glob.glob(os.path.join(base_dir, \"**\u002F*.txt\")) # This needs to result in a list of paths to all of your txt files\nprocesses = 64 # Number of encoding processes to run\nencoder_path = \"\u002Fhome\u002Fconnor\u002Fencoder\" # Path to encoder files\nminimum_size = 128 # The minimum length (in BPE tokens) a file is allowed to have, otherwise it is discarded.\n```\n2. Run the script. This will result in a bunch of name_i.tfrecords files. Put these somewhere accessible (must be in a Google Storage bucket if you're using TPUs).\n3. Create a new input function in *inputs.py*. Any input function should have the signature *function_name(params, eval=False)*. The **stitch** value controls how many texts are concatenated so that you never end up with a sample that is too small. It should be: **ceil((n_ctx+1) \u002F minimum_size)** So for example, if my minimum size is 128 and my n_ctx is 1024, stitch should be 9.\n\n```python\ndef my_input(params, eval=False):\n    if not eval:\n        numbers = [0, 3, 4, 5, 6, 7, 8, 9] # A random subset of files for train\n    else:\n        numbers = [1, 2] # Random subset for eval\n    files = [os.path.join(params[\"data_path\"], \"my-custom-data_{}.tfrecords\".format(str(i))) for i in numbers] # Generates the list of files\n\n    return bpe_text(params[\"batch_size\"], files, amount=params[\"n_ctx\"], iterations=params[\"iterations\"], stitch=9, batch=True)\n```\n4. Register your new input in *main.py*.\n\n```python\ninputs = {\n    \"openwebtext\": openwebtext, # Standard OpenWebtext input\n    \"openwebtext_longbiased\": openwebtext_longbiased, # OpenWebtext with a bias towards showing more long (>512 tokens) examples\n    \"openwebtext_long\": openwebtext_long, # Openwebtext that only shows long examples\n    \"my_input\": my_input,\n}\n```\n5. Set your .json to use the new input.\n```python\n[...]\n    \"iterations\": 500,\n    \"n_embd\": 768,\n    \"input\": \"my_input\",\n    \"model\": \"GPT2\",\n[...]\n```\n6. You're done. The input described here should be as close to GPT2 as possible and run perfectly on TPUs.\n\n## Explanation of Parameters\nBecause passing two dozen parameters over the command line would be tedious, you pass all the model parameters in a .json file. Note that any paths also support Google Storage paths and *must* be gs:\u002F\u002F paths if you're running on TPUs.\n\nValues you'll definitely want to change:\n* **model_path**: Where to save and load checkpoints from\n* **data_path**: Where your .tfrecords files are located\n* **encoder_path**: Path to the BPE encoder files. To get this, use the download_model.py script to download any model (or just the encoder). You will get a folder called \"encoder\". This is what you want this to point to (only required for prediction)\n\nValues you'll probably want to change:\n* **train_batch_size**: Batch size during training phase\n* **eval_batch_size**: Batch size during evaluation\n* **predict_batch_size**: Batch size during prediction\n* **predict_path**: Where to save predictions (point this to a text file to append to)\n\nModel parameters:\n* **model**: A string that refers to which model to use. This should always just be \"GPT2\" (no other models are implemented here)\n* **n_ctx**: Number of tokens the model looks at (default: 1024)\n* **n_vocab**: Size of vocabulary (default: 50257)\n* **n_embd**: Dimension of embedding layers\n* **n_layer**: Number of layers in the model\n* **n_head**: Number of attention heads (default: n_embd \u002F 64)\n* **scale_by_depth**: Whether or not to scale init by the number of layers (Default: true)\n* **scale_by_in**: Whether to scale init by the number of input channels (Default: true)\n\nTraining parameters:\n* **precision**: Whether to use float32 or bfloat16 variables (use \"bfloat16\" when training very large models) (optional, defaults to float32)\n* **input**: Which input function to use (default: \"openwebtext\")\n* **lr**: Learning rate (default: 0.00025)\n* **warmup_steps**: Number of warmup steps. If this is set, a linear warmup + cosine decay schedule is used (default: 2000) (optional)\n* **opt_name**: Name of optimizer, currently there are \"adam\" and \"adafactor\" (default: \"adam\")\n* **weight_decay**: Weight decay parameter, if not present no weight decay is used (the weight decay fix for Adam is used) (default: 0.01) (optional)\n* **beta1**: Adam\u002FAdafactor beta1 parameter (adam default: 0.9, adafactor default: 0.0)\n* **beta2**: Adam\u002FAdafactor beta2 parameter (default: 0.98) (optional for adafactor with pow decay type)\n* **epsilon**: Adam epsilon parameter (default: 1e-9)\n* **decay_type**: Adafactor decay type, either \"pow\" or \"adam\" (default: \"pow\")\n* **decay_exponent**: Adafactor pow decay exponent (default: 0.8)\n* **train_steps**: Number of training steps to take between evaluations\n* **eval_steps**: Number of steps per evaluation\n* **max_steps**: The maximum number of training steps (important for declining lr)\n* **iterations**: Number of iterations to perform on TPUs (Default: 100) (Only required for TPUs)\n* **embed_dropout**: Dropout chance on the word embedding, set to 0 to disable (default: 0.1)\n* **attn_dropout**: Dropout chance on attention layers, set to 0 to disable (default: 0.1)\n* **res_dropout**: Dropout chance on residual connections, set to 0 to disable (default: 0.1)\n","# GPT2\n**免责声明：这不是官方的GPT2实现！我已尽最大努力尽可能贴近原始GPT2模型的规范，但请注意，我尚未能用这段代码复现原始模型的全部性能。至于原因，我也不清楚，目前未能找到可能导致此问题的任何 bug。**\n\n这是一个支持 GPU 和 TPU 的 [GPT2](https:\u002F\u002Fopenai.com\u002Fblog\u002Fbetter-language-models\u002F) 训练实现。数据集脚本略显粗糙，可能需要根据您的需求进行调整。\n## 需求\n对于 GPU：\n\n`pip3 install tensorflow-gpu regex`\n\n对于 TPU：\n\n`pip3 install tensorflow regex google-api-python-client oauth2client`\n\n下载模型所需：\n\n`pip3 install requests tqdm`\n\n生成数据集所需（除 TensorFlow 外）：\n\n`pip3 install ftfy tqdm newspaper3k`\n\n## 下载预训练模型\n如果您想使用我的模型，目前我提供了“117M”、“PrettyBig”和“1.5B”三种版本。“117M”是在单个 v2 TPU 上训练了一周（可能少于 OpenAI 原始模型的训练时间）；“PrettyBig”比 345M 略大，在 v2-256 Pod 上训练了一周。~~我原本还计划发布我的 1.5B 版本，但后来决定放弃。您可以阅读我的理由 [这里](https:\u002F\u002Fmedium.com\u002F@NPCollapse\u002Fthe-hacker-learns-to-trust-62f3c1490f51)。~~ 由于 OpenAI 已经发布了他们的模型，我现在也发布了我的（质量稍逊的）1.5B 模型，该模型是在 v3-512 Pod 上训练了一周。\n\n`python3 download_model.py PrettyBig`\n\n这将创建两个目录，一个以模型命名，另一个名为“encoder”。请修改与您的模型对应的 .json 文件中的 “model_dir” 和 “encoder_path” 参数，分别指向这两个路径。\n\n如果您只需要编码器，请使用：\n\n`python3 download_model.py encoder`\n\n## 文本生成\n进行预测时，您可以直接在命令行中输入提示词，也可以从文件中读取提示词。（这对于包含换行符的提示词非常有用）文本会输出到控制台以及 “predict_path” 参数指定的文件中。为此，您需要将模型检查点和 BPE 编码器副本放置在可访问的位置。（请修改 .json 文件中的 “model_dir” 和 “encoder_path” 参数）\n\n通过命令行：\n\n`python3 main.py --model Your-Model.json [--top_k Top-K-Truncation] --predict_text \"Hello there! My name is\"`\n\n从文件：\n\n`python3 main.py --model Your-Model.json [--top_k Top-K-Truncation] --predict_file input.txt`\n\n可选的 top_k 参数会使模型在每一步只考虑概率最高的前 k 个标记。将其设置为 40 左右通常会产生更好的结果，但多样性会降低。\n\n不支持在 TPU 上进行预测。\n\n## 训练\n要训练一个模型，首先在 .json 文件中定义其参数（参见示例），然后直接运行：\n\n`python3 main.py --model Your-Model.json [--tpu Your-TPU-Name]`\n\n使用 TPU 是可选的，无需修改即可在 GPU 上正常运行。（注意：评估功能在 TPU Pod 上无法使用，必须注释掉）\n\n此过程假定您已在可访问位置存储了 openwebtext 数据集。如果没有，请参阅下方如何生成您自己的版本。\n\n## 生成数据集\nGPT2 是基于 webtext 数据集训练的，该数据集基本上是 Reddit 上所有链接且至少有 3 个 Karma 的网站内容。由于数据库庞大且包含大量受版权保护的内容，我无法在此提供下载。相反，我将介绍我是如何获取它的。请注意，为了下载并处理整个数据集，我花费了大约 500 欧元的云资源费用，但我并不声称自己是最高效的。\n1. 使用 [此处](https:\u002F\u002Fgithub.com\u002Fjcpeterson\u002Fopenwebtext) 的下载脚本下载归档文件（我使用了预先过滤的 URL 文件）。\n2. 使用 *datasets\u002Fopenwebtext\u002Frun_newspaper_extract.py* 提取文本。\n3. 获取原始 .txt 文件后，使用 *datasets\u002Fopenwebtext\u002Fcreate_tfrecords.py* 将其编码为 .tfrecords 文件（需要编码器副本，详见“下载预训练模型”部分）。\n4. 将 .tfrecords 文件放入可访问的文件夹或 Google Storage 存储桶中（如果使用 TPU，则必须放入 Google Storage 存储桶）。\n5. 修改您的 .json 文件中的 “data_path” 参数，使其指向 .tfrecords 文件所在的位置；如有必要，还需调整 *inputs.py* 中的函数，以便在文件名更改时能够正确打开它们。\n\n## 使用您自己的数据\n您也可以使用自己的文本文件作为训练数据，但需要手动修改一些代码。\n1. 修改 *datasets\u002Fopenwebtext\u002Fcreate_tfrecords.py* 中的参数：\n\n```python\nbase_dir = \"\u002Fhome\u002Fconnor\u002Fmy_text_dir\" # 您的 .txt 文件所在路径\nfiles_per = 175000 # 每个 tfrecord 放入多少个 txt 文件，影响不大\nname = \"my-custom-data\" # 输出文件的名称格式为 name_i.tfrecords，其中 i 是文件编号\noutput_dir = \"\u002Fhome\u002Fconnor\u002Foutput\" # 保存 .tfrecords 文件的路径\nlog_dir = \"logs\" # 日志将存放于此，以便在编码中断时恢复\nfiles = glob.glob(os.path.join(base_dir, \"**\u002F*.txt\")) # 需要生成所有 txt 文件的路径列表\nprocesses = 64 # 并行编码进程数\nencoder_path = \"\u002Fhome\u002Fconnor\u002Fencoder\" # BPE 编码器文件路径\nminimum_size = 128 # 文件允许的最小长度（以 BPE 令牌计），否则会被丢弃。\n```\n2. 运行脚本。这将生成一系列 name_i.tfrecords 文件。请将这些文件放置在一个可访问的位置（如果您使用 TPU，则必须放在 Google Cloud Storage 存储桶中）。\n3. 在 *inputs.py* 中创建一个新的输入函数。任何输入函数都应具有签名 *function_name(params, eval=False)*。**stitch** 参数控制连接的文本数量，以避免样本过小。其值应为：**ceil((n_ctx+1) \u002F minimum_size)**。例如，如果我的 minimum_size 是 128，而 n_ctx 是 1024，则 stitch 应为 9。\n\n```python\ndef my_input(params, eval=False):\n    if not eval:\n        numbers = [0, 3, 4, 5, 6, 7, 8, 9] # 训练用随机文件子集\n    else:\n        numbers = [1, 2] # 评估用随机文件子集\n    files = [os.path.join(params[\"data_path\"], \"my-custom-data_{}.tfrecords\".format(str(i))) for i in numbers] # 生成文件列表\n\n    return bpe_text(params[\"batch_size\"], files, amount=params[\"n_ctx\"], iterations=params[\"iterations\"], stitch=9, batch=True)\n```\n4. 在 *main.py* 中注册您的新输入。\n\n```python\ninputs = {\n    \"openwebtext\": openwebtext, # 标准 OpenWebText 输入\n    \"openwebtext_longbiased\": openwebtext_longbiased, # 倾向于展示更多长文本（>512 个令牌）的 OpenWebText\n    \"openwebtext_long\": openwebtext_long, # 只展示长文本的 OpenWebText\n    \"my_input\": my_input,\n}\n```\n5. 将您的 .json 配置设置为使用新输入。\n```python\n[...]\n    \"iterations\": 500,\n    \"n_embd\": 768,\n    \"input\": \"my_input\",\n    \"model\": \"GPT2\",\n[...]\n```\n6. 完成！此处描述的输入应尽可能接近 GPT2，并且可在 TPU 上完美运行。\n\n## 参数说明\n由于通过命令行传递二十多个参数会非常繁琐，因此所有模型参数都通过 .json 文件传递。请注意，所有路径也支持 Google Cloud Storage 路径；如果您在 TPU 上运行，则路径必须是 gs:\u002F\u002F 格式。\n\n您可能需要更改的值：\n* **model_path**: 用于保存和加载检查点的路径\n* **data_path**: 您的 .tfrecords 文件所在路径\n* **encoder_path**: BPE 编码器文件的路径。您可以使用 download_model.py 脚本来下载任意模型（或仅下载编码器），得到一个名为“encoder”的文件夹，这就是您需要指向的路径（仅在预测时需要）。\n\n您可能希望调整的值：\n* **train_batch_size**: 训练阶段的批量大小\n* **eval_batch_size**: 评估阶段的批量大小\n* **predict_batch_size**: 预测阶段的批量大小\n* **predict_path**: 用于保存预测结果的路径（可指向一个文本文件以追加内容）\n\n模型参数：\n* **model**: 指定使用的模型名称。此处应始终为“GPT2”（未实现其他模型）\n* **n_ctx**: 模型一次处理的令牌数（默认：1024）\n* **n_vocab**: 词汇表大小（默认：50257）\n* **n_embd**: 嵌入层的维度\n* **n_layer**: 模型的层数\n* **n_head**: 注意力头的数量（默认：n_embd \u002F 64）\n* **scale_by_depth**: 是否根据层数缩放初始化权重（默认：是）\n* **scale_by_in**: 是否根据输入通道数缩放初始化权重（默认：是）\n\n训练参数：\n* **precision**: 使用 float32 还是 bfloat16 变量（训练超大规模模型时使用“bfloat16”）（可选，默认为 float32）\n* **input**: 使用哪个输入函数（默认：“openwebtext”）\n* **lr**: 学习率（默认：0.00025）\n* **warmup_steps**: 预热步数。若设置此参数，则采用线性预热 + 余弦退火调度（默认：2000）（可选）\n* **opt_name**: 优化器名称，目前有“adam”和“adafactor”两种（默认：“adam”）\n* **weight_decay**: 权重衰减参数，若未指定则不使用权重衰减（将应用 Adam 的权重衰减修正）（默认：0.01）（可选）\n* **beta1**: Adam\u002FAdafactor 的 beta1 参数（Adam 默认：0.9，Adafactor 默认：0.0）\n* **beta2**: Adam\u002FAdafactor 的 beta2 参数（默认：0.98）（对于采用幂次衰减类型的 Adafactor 可选）\n* **epsilon**: Adam 的 epsilon 参数（默认：1e-9）\n* **decay_type**: Adafactor 的衰减类型，可为“pow”或“adam”（默认：“pow”）\n* **decay_exponent**: Adafactor 幂次衰减的指数（默认：0.8）\n* **train_steps**: 两次评估之间的训练步数\n* **eval_steps**: 每次评估的步数\n* **max_steps**: 最大训练步数（对学习率衰减很重要）\n* **iterations**: 在 TPU 上执行的迭代次数（默认：100）（仅适用于 TPU）\n* **embed_dropout**: 词嵌入层的 dropout 率，设为 0 可禁用（默认：0.1）\n* **attn_dropout**: 注意力层的 dropout 率，设为 0 可禁用（默认：0.1）\n* **res_dropout**: 残差连接的 dropout 率，设为 0 可禁用（默认：0.1）","# GPT2 快速上手指南\n\n> **注意**：本仓库并非 OpenAI 官方实现的 GPT-2。作者尽力还原了原始模型规格，但性能可能无法完全复现原版效果。\n\n## 环境准备\n\n本项目基于 TensorFlow，支持 GPU 和 TPU 训练。请根据您的硬件环境安装相应依赖。\n\n### 系统要求\n- Python 3.x\n- TensorFlow (支持 GPU 或 TPU)\n\n### 前置依赖安装\n\n**GPU 用户：**\n```bash\npip3 install tensorflow-gpu regex\n```\n\n**TPU 用户：**\n```bash\npip3 install tensorflow regex google-api-python-client oauth2client\n```\n\n**通用工具（下载模型及生成数据集所需）：**\n```bash\npip3 install requests tqdm ftfy newspaper3k\n```\n\n> 💡 **国内加速建议**：如遇下载缓慢，可指定国内镜像源安装，例如：\n> `pip3 install -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple tensorflow-gpu regex`\n\n---\n\n## 安装与模型下载\n\n本工具不提供预训练模型文件托管，需通过脚本下载作者提供的模型（包含 \"117M\", \"PrettyBig\", \"1.5B\" 等版本）或仅下载编码器。\n\n### 下载预训练模型\n以下命令将下载 \"PrettyBig\" 模型，并自动生成模型目录和 `encoder` 目录：\n```bash\npython3 download_model.py PrettyBig\n```\n\n### 仅下载编码器\n如果您只需 BPE 编码器：\n```bash\npython3 download_model.py encoder\n```\n\n### 配置文件调整\n下载完成后，请找到对应模型的 `.json` 配置文件，修改以下参数以指向实际路径：\n- `model_dir`: 指向模型文件夹路径\n- `encoder_path`: 指向 `encoder` 文件夹路径\n\n---\n\n## 基本使用\n\n### 文本生成 (预测)\n\n您可以直接通过命令行输入提示词，或从文件读取提示词进行文本生成。生成的文本将输出到控制台及配置文件中指定的路径。\n\n**注意**：TPU 不支持预测功能，请在 GPU 环境下运行。\n\n#### 方式一：命令行直接输入\n```bash\npython3 main.py --model Your-Model.json [--top_k 40] --predict_text \"Hello there! My name is\"\n```\n*注：`--top_k` 为可选参数，设置为 40 左右通常能生成质量更高但多样性稍低的文本。*\n\n#### 方式二：从文件读取提示词\n适用于包含换行符的长提示词：\n```bash\npython3 main.py --model Your-Model.json [--top_k 40] --predict_file input.txt\n```\n\n### 模型训练\n\n训练前需准备好 `.tfrecords` 格式的数据集（默认使用 OpenWebText 或自定义数据），并在 `.json` 配置文件中设置好 `data_path`。\n\n#### 启动训练\n```bash\npython3 main.py --model Your-Model.json\n```\n\n#### 使用 TPU 训练（可选）\n```bash\npython3 main.py --model Your-Model.json --tpu Your-TPU-Name\n```\n*注：在 TPU Pod 上运行时，需在代码中注释掉评估（Evaluation）部分，因其暂不支持。*\n\n### 关键参数说明\n所有模型与训练参数均在 `.json` 文件中配置，主要参数包括：\n- `model_path`: 模型检查点保存\u002F加载路径\n- `data_path`: `.tfrecords` 数据集路径（TPU 用户必须使用 `gs:\u002F\u002F` Google Storage 路径）\n- `n_ctx`: 上下文窗口大小（默认 1024）\n- `lr`: 学习率（默认 0.00025）\n- `train_batch_size`: 训练批次大小","某独立游戏开发团队需要为 NPC 角色快速生成大量风格各异的对话文本，以丰富开放世界游戏的剧情互动。\n\n### 没有 GPT2 时\n- 开发人员需手动编写数千条对话脚本，耗时数周且创意容易枯竭，导致 NPC 台词重复单调。\n- 若尝试从头训练自定义语言模型，缺乏支持 TPU 加速的现成代码，本地 GPU 训练效率极低，难以在有限预算内完成。\n- 网络爬虫获取语料后，缺乏标准化的数据清洗与 TFRecord 转换流程，数据处理脚本报错频繁，工程落地困难。\n- 无法灵活调整生成文本的多样性，要么输出过于随机无逻辑，要么过于保守缺乏趣味，难以平衡游戏体验。\n\n### 使用 GPT2 后\n- 团队利用预训练的\"PrettyBig\"模型，通过命令行输入简短情境提示，瞬间批量生成数千条连贯且富有创意的 NPC 对话。\n- 借助原生支持的 TPU 训练功能，在云端高效微调模型以适应游戏特定文风，将原本数周的训练周期缩短至几天。\n- 直接复用项目提供的数据集生成脚本，快速将爬取的网页文本清洗并转换为模型可用的格式，大幅降低数据预处理门槛。\n- 通过调节 `top_k` 参数精准控制输出策略，既保证了对话的逻辑通顺，又保留了足够的随机性以增加探索乐趣。\n\nGPT2 让小型团队也能以低成本拥有高质量的内容生成能力，将开发者从繁琐的文案工作中解放出来专注于核心玩法设计。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FConnorJL_GPT2_bf714de8.png","ConnorJL","Connor Leahy","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FConnorJL_e71fde9c.jpg","Interested in A(G)I and Alignment",null,"NPCollapse","https:\u002F\u002Ftwitter.com\u002FNPCollapse","https:\u002F\u002Fgithub.com\u002FConnorJL",[81,85],{"name":82,"color":83,"percentage":84},"Python","#3572A5",99.8,{"name":86,"color":87,"percentage":88},"Shell","#89e051",0.2,1413,329,"2026-03-27T19:37:43","MIT",4,"未说明","可选（支持 GPU 和 TPU）。若使用 GPU，需安装 tensorflow-gpu。具体显卡型号、显存大小及 CUDA 版本未在文档中明确说明，但提及曾使用 v2\u002Fv3 TPU 集群训练大型模型。",{"notes":97,"python":98,"dependencies":99},"1. 此项目非 OpenAI 官方实现，性能可能不如原版。\n2. 支持 Google TPU，若使用 TPU，数据必须存储在 Google Storage Bucket (gs:\u002F\u002F路径) 中。\n3. 预测功能不支持在 TPU 上运行，仅支持 GPU 或 CPU。\n4. 评估功能在 TPU 集群上不工作，需在代码中注释掉。\n5. 训练数据默认为 OpenWebText 语料库，需自行下载和处理（过程昂贵且耗时），或按文档指引修改代码以使用自定义文本数据。\n6. 模型参数、数据路径等配置需通过 .json 文件传递。","3.x (通过 pip3 和 python3 命令推断)",[100,101,102,103,104,105,106,107,108],"tensorflow-gpu (GPU 环境)","tensorflow (TPU\u002FCPU 环境)","regex","requests","tqdm","google-api-python-client (TPU 环境)","oauth2client (TPU 环境)","ftfy (数据集生成)","newspaper3k (数据集生成)",[35,14],"2026-03-27T02:49:30.150509","2026-04-07T13:28:53.867667",[113,118,123,128,133,138],{"id":114,"question_zh":115,"answer_zh":116,"source_url":117},22003,"使用 PrettyBig 模型预测时出现 'InvalidArgumentError: indices... is not in [0, 1024)' 错误怎么办？","该错误通常是因为前缀令牌（prefix tokens）的长度未被正确处理，导致索引越界。解决方案是从最大长度中减去前缀令牌的长度，以防止超出范围（OOB）。维护者已实施此修复，如果问题再次出现，请确保应用了该逻辑。","https:\u002F\u002Fgithub.com\u002FConnorJL\u002FGPT2\u002Fissues\u002F4",{"id":119,"question_zh":120,"answer_zh":121,"source_url":122},22004,"如何使用原始文本文件创建类似 \"PrettyBig\" 的自定义数据集？","使用 `datasets\u002Fcreate_tfrecords.py` 脚本从 txt 文件生成 .tfrecords 文件。不需要手动添加 `\u003C|endoftext|>` 标记。如果在 `inputs.py` 中使用 `bpe_text` 函数作为输入，它会自动从数据集中采样 \"stitch\" 数量的文本，用 `\u003C|endoftext|>` 连接它们，然后从最终结果中采样 `n_ctx` 数量的令牌。请确保设置 \"stitch\" 参数，使得 `(最小文本长度 * stitch) >= n_ctx`。","https:\u002F\u002Fgithub.com\u002FConnorJL\u002FGPT2\u002Fissues\u002F2",{"id":124,"question_zh":125,"answer_zh":126,"source_url":127},22005,"运行 create_tfrecords.py 时遇到 'TypeError: unsupported operand type(s) for +: int and NoneType' 错误如何解决？","这通常是因为脚本无法覆盖之前的日志文件或处理进程冲突。尝试删除旧的日志文件夹（logs），或者将脚本顶部的 `processes` 参数改为 1，并将 `files_per` 改为较小的值（如 10）进行测试。同时请确认输出目录具有写入权限。","https:\u002F\u002Fgithub.com\u002FConnorJL\u002FGPT2\u002Fissues\u002F20",{"id":129,"question_zh":130,"answer_zh":131,"source_url":132},22006,"在哪里可以下载 1.5B (PrettyBig) 模型？","维护者已确认 1.5B 模型现已可供下载。您可以查看项目仓库或维护者的博客文章（如在 Medium 上发布的关于复制 GPT-2 1.5B 的文章）获取具体的下载链接和说明。","https:\u002F\u002Fgithub.com\u002FConnorJL\u002FGPT2\u002Fissues\u002F19",{"id":134,"question_zh":135,"answer_zh":136,"source_url":137},22007,"是否有该模型与 OpenAI 官方模型的性能对比数据？","是的，已有由 OpenAI 进行的正式评估数据。您可以参考相关博客文章（例如标题为 \"Addendum: Evaluation of my model\" 的文章）查看详细的性能对比结果。维护者也曾表示正在与 OpenAI 合作以产生准确的对比数据。","https:\u002F\u002Fgithub.com\u002FConnorJL\u002FGPT2\u002Fissues\u002F3",{"id":139,"question_zh":140,"answer_zh":141,"source_url":127},22008,"在 Google Colab 上使用 TPU 运行脚本时需要注意什么？","在 Google Colab 环境中，确保运行时设置为 Python 3 并启用了 TPU。如果遇到文件处理错误，检查文件路径是否正确（例如 `glob.glob` 的模式是否能找到文件），并确认挂载的 Google Drive 目录具有读写权限。如果并行处理出错，尝试减少 `processes` 数量。",[]]