[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-Liuhong99--Sophia":3,"tool-Liuhong99--Sophia":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 真正成长为懂上",145895,2,"2026-04-08T11:32:59",[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 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108111,"2026-04-08T11:23:26",[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":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":74,"owner_location":77,"owner_email":74,"owner_twitter":74,"owner_website":74,"owner_url":78,"languages":79,"stars":84,"forks":85,"last_commit_at":86,"license":87,"difficulty_score":88,"env_os":89,"env_gpu":90,"env_ram":89,"env_deps":91,"category_tags":99,"github_topics":100,"view_count":10,"oss_zip_url":74,"oss_zip_packed_at":74,"status":17,"created_at":104,"updated_at":105,"faqs":106,"releases":140},5279,"Liuhong99\u002FSophia","Sophia","The official implementation of “Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training”","Sophia 是一款专为大型语言模型预训练设计的高效优化器，源自论文《Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training》的官方实现。它旨在解决传统一阶优化器（如 AdamW）在处理超大规模模型时收敛速度慢、计算资源消耗大的痛点。\n\n通过引入随机二阶优化技术，Sophia 能够利用海森矩阵（Hessian）的对角线估计来动态调整参数更新步长。其核心亮点在于独特的“梯度裁剪”机制：仅对曲率较大的参数方向进行限制，从而允许在其余方向使用更大的学习率。这种策略不仅显著提升了训练速度，还保持了极高的稳定性，实测表明在同等条件下比 Lion 等先进优化器更快收敛。\n\nSophia 主要面向 AI 研究人员和深度学习开发者，特别是那些从事大模型预训练、需要优化训练效率的专业团队。代码基于 nanoGPT 和 levanter 构建，提供了清晰的 PyTorch 接口和详细的超参数调优指南（如 $\\rho$ 值与学习率的设定），方便用户快速集成到现有的训练流程中。如果你正在寻求突破大","Sophia 是一款专为大型语言模型预训练设计的高效优化器，源自论文《Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training》的官方实现。它旨在解决传统一阶优化器（如 AdamW）在处理超大规模模型时收敛速度慢、计算资源消耗大的痛点。\n\n通过引入随机二阶优化技术，Sophia 能够利用海森矩阵（Hessian）的对角线估计来动态调整参数更新步长。其核心亮点在于独特的“梯度裁剪”机制：仅对曲率较大的参数方向进行限制，从而允许在其余方向使用更大的学习率。这种策略不仅显著提升了训练速度，还保持了极高的稳定性，实测表明在同等条件下比 Lion 等先进优化器更快收敛。\n\nSophia 主要面向 AI 研究人员和深度学习开发者，特别是那些从事大模型预训练、需要优化训练效率的专业团队。代码基于 nanoGPT 和 levanter 构建，提供了清晰的 PyTorch 接口和详细的超参数调优指南（如 $\\rho$ 值与学习率的设定），方便用户快速集成到现有的训练流程中。如果你正在寻求突破大模型训练瓶颈的方案，Sophia 提供了一个经过验证的高性能选择。","# Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training\n\n\nThis is an official implementation of the **Sophia-G** optimizer in the paper [https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.14342](https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.14342) and GPT-2 training scripts. The code is based on [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F) and [levanter](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002F). Please cite the paper and star this repo if you find Sophia useful. Thanks!\n\n\n```tex\n@article{liu2023sophia,\n title={Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training},\n author={Liu, Hong and Li, Zhiyuan and Hall, David and Liang, Percy and Ma, Tengyu},\n journal={arXiv preprint arXiv:2305.14342},\n year={2023}\n}\n```\n\n\n## News and Updates\n- Updated results with latest PyTorch version.\n\n\n\n## Dependencies\n\n\n- [PyTorch](https:\u002F\u002Fpytorch.org) 2.1.2\n- transformers 4.33.0\n- datasets\n- tiktoken\n- wandb\n\n## General Usage\n\nBelow is an example code snippet for training a general model with NLL loss with SophiaG. Please refer to the next section for guidelines on hyperparameter tuning.\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom sophia import SophiaG\n\n# init model loss function and input data\nmodel = Model()\ndata_loader = ...\n\n# init the optimizer\noptimizer = SophiaG(model.parameters(), lr=2e-4, betas=(0.965, 0.99), rho=0.01, weight_decay=1e-1)\n\ntotal_bs = len(data_loader)\nbs = total_bs * block_size\nk = 10\niter_num = -1\n\n# training loop\nfor epoch in range(epochs):\n    for X, Y in data_loader:\n        # standard training code\n        logits, loss = model(X, Y)\n        loss.backward()\n        optimizer.step(bs=bs)\n        optimizer.zero_grad(set_to_none=True)\n        iter_num += 1\n\n        if iter_num % k != k - 1:\n            continue\n        else:\n            # update hessian EMA\n            logits, _ = model(X, None)\n            samp_dist = torch.distributions.Categorical(logits=logits)\n            y_sample = samp_dist.sample()\n            loss_sampled = F.cross_entropy(logits.view(-1, logits.size(-1)), y_sample.view(-1), ignore_index=-1)\n            loss_sampled.backward()\n            optimizer.update_hessian()\n            optimizer.zero_grad(set_to_none=True)\n            model.zero_grad()\n```\n\n\n## Hyper-parameter Tuning\n\n### Definition of learning rate \n- The update in the code is written as $\\theta_{t+1} = \\theta_t - lr*\\textup{clip}(m_t \u002F (\\rho * h_t + \\epsilon), 1)$, which is equivalent to the update in the paper up to a re-parameterization. (the $lr$ here corresponds to $\\rho \\cdot \\eta_t$ in the paper). As a result, the learning rate of AdamW and Lion is not directly comparable. Empirically, Adam and Lion with learning rate ratio 5:1 has similar behaviour. The learning rate of SophiaG and Lion is directly comparable. Sophia allows to use much larger learning rate the Lion, and this is why Sophia is much faster. \n\n### Tuning the hyperparameter $\\rho$ \n- Tune $\\rho$ to make the proportion of the clipped coordinates stable and in a proper range. This is tracked as ```train\u002Fwin_rate``` in the [GPT-2 training example](https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fblob\u002F2443b03529ecdccf65699a5e55e68d69ede39509\u002Ftrain_sophiag.py#L398C21-L398C65). ```train\u002Fwin_rate``` should peak in the beginning and remain stable afterwards. ```train\u002Fwin_rate``` should stay in the range of 0.1 - 0.5. Typically a large $\\rho$ will lead to a large ```train\u002Fwin_rate```. An example of typical ```win_rate``` behavior in T5 model is provided below.\n\n### Tuning the learning rate and weight decay\n- Choose lr to be slightly smaller than the learning rate that you would use for AdamW or 3 - 5 times the learning rate that you would use for Lion. \n\u003Cp align=\"center\" width=\"100%\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_readme_5711b88729bf.png\" style=\"width: 60%; min-width: 200px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\n- If the loss blows up, slightly decrease the learning rate or increase $\\rho$.\n  \n- Always use about 2x larger weight decay than what you would use for AdamW.\n\n### Hyperparameters for GPT-2 models\n\n- Choose lr to be about the same as the learning rate that you would use for AdamW or 5 - 10 times the learning rate that you would use for Lion.\n- Tune $\\rho$ to make the proportion of the parameters where the update is not clipped stable and in a proper range. This is tracked as ```train\u002Fwin_rate``` in the [GPT-2 training example](https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fblob\u002F2443b03529ecdccf65699a5e55e68d69ede39509\u002Ftrain_sophiag.py#L398C21-L398C65). ```train\u002Fwin_rate``` should peak in the beginning and remain stable afterwards. ```train\u002Fwin_rate``` should stay in the range of 0.1 - 0.5. Typically a large $\\rho$ will lead to a large ```train\u002Fwin_rate```.\n- Use slightly larger weight decay than AdamW, e.g. 0.2.\n- Except learning rate, all other hyperparameters are transferable across different model sizes.\n- See the table below for the hyperparameters for different model sizes.\n\n| Model Size  | lr for Adam | lr for Lion | lr for Sophia | $\\rho$ for Sophia | weight decay for Sophia |\n| -------- | ------- | ------- | ------- | ------- | ------- |\n| 125M | 6e-4 | 1e-4 | 6e-4 | 0.05 | 0.2 |\n| 355M | 3e-4 | 1e-4 | 7e-4 | 0.08 | 0.2 |\n| 770M | 2e-4 | 8e-5 | 3e-4 | 0.05 | 0.2 |\n\n- Please feel free to let us know what you find out during hyper-parameters tuning. We appreciate your valuable feedback and comments!\n\n## Reproduce GPT-2 Results\n\nPrepare the [OpenWebText](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fopenwebtext) data following [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F):\n```\n$ python data\u002Fopenwebtext\u002Fprepare.py\n```\nStart pre-training GPT2 Small (125M):\n\nIf you have a machine with 10 A5000 (24GB) GPUs,\n```\n$ torchrun --standalone --nproc_per_node=10 \\\n      train_sophiag.py \\\n      config\u002Ftrain_gpt2_small_sophiag.py \\\n      --batch_size=8 \\\n      --gradient_accumulation_steps=6\n```\nIf you have a machine with 8 A100 (40GB) GPUs,\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      train_sophiag.py \\\n      config\u002Ftrain_gpt2_small_sophiag.py \\\n      --batch_size=12 \\\n      --gradient_accumulation_steps=5\n```\n\nTo reproduce the AdamW baseline following [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F):\n```\n$ torchrun --standalone --nproc_per_node=10 \\\n      train_adam.py \\\n      config\u002Ftrain_gpt2_small_adam.py \\\n      --batch_size=8 \\\n      --gradient_accumulation_steps=6\n```\n\nThis will lead to results in the figure below:\n\u003Cp align=\"center\" width=\"100%\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_readme_ce648c1f242d.png\" style=\"width: 60%; min-width: 200px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\nStart pre-training GPT2 Medium (355M):\n\nIf you have a machine with 8 A100 (40GB) GPUs,\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      train_sophiag.py \\\n      config\u002Ftrain_gpt2_medium_sophiag.py \\\n      --batch_size=6 \\\n      --gradient_accumulation_steps=10\n```\n\nTo reproduce the AdamW baseline:\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      train_adam.py \\\n      config\u002Ftrain_gpt2_medium_adam.py \\\n      --batch_size=6 \\\n      --gradient_accumulation_steps=10\n```\n\nPlease adjust ```nproc_per_node```, ```batch_size```, and ```gradient_accumulation_steps``` accordingly if you use other hardware setup. Make sure their product equals 480.\n\n\nThis will lead to results in the figure below:\n\u003Cp align=\"center\" width=\"100%\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_readme_3164cf087cd1.png\" style=\"width: 60%; min-width: 200px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\nStart pre-training GPT2 1.5B:\n\nWe use [the Pile](https:\u002F\u002Fgithub.com\u002FEleutherAI\u002Fthe-pile) and GPT NeoX tokenizer. First set up TPU instances and environment following [levanter](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002Fblob\u002Fe183ec80ec5971b12d4a3fb08a160268de342670\u002Fdocs\u002FGetting-Started-TPU-VM.md). Then change GAMMA_SOPHIA_G to 200 in [optim.py](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002Fblob\u002Fe183ec80ec5971b12d4a3fb08a160268de342670\u002Fsrc\u002Flevanter\u002Foptim.py). The training script for 1.5B model is \n```\ngcloud compute tpus tpu-vm ssh \u003Cinstance_name> \\\n      --zone \u003Czone_name> \\\n      --worker=all \\\n      --command 'WANDB_API_KEY=\u003Cwandb_api_key> levanter\u002Finfra\u002Flaunch.sh python levanter\u002Fexamples\u002Fgpt2_example.py --config_path levanter\u002Fconfig\u002Fgpt2_1536_pile.yaml --trainer.beta1 0.965 --trainer.beta2 0.99 --trainer.min_lr_ratio 0.020 --trainer.weight_decay 0.15 --trainer.learning_rate 2.5e-4 --trainer.warmup_ratio 0.01'\n\n```\n\n## Acknowledgement\n\nThe GPT-2 training code is based on [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F), which is elegant and super efficient.\n","# Sophia：用于语言模型预训练的可扩展随机二阶优化器\n\n\n这是论文[https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.14342](https:\u002F\u002Farxiv.org\u002Fabs\u002F2305.14342)中**Sophia-G**优化器以及GPT-2训练脚本的官方实现。代码基于[nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F)和[levanter](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002F)。如果您觉得Sophia有用，请引用该论文并给本仓库点个赞！谢谢！\n\n\n```tex\n@article{liu2023sophia,\n title={Sophia: A Scalable Stochastic Second-order Optimizer for Language Model Pre-training},\n author={Liu, Hong and Li, Zhiyuan and Hall, David and Liang, Percy and Ma, Tengyu},\n journal={arXiv preprint arXiv:2305.14342},\n year={2023}\n}\n```\n\n\n## 新闻与更新\n- 使用最新版PyTorch更新了实验结果。\n\n\n\n## 依赖项\n\n\n- [PyTorch](https:\u002F\u002Fpytorch.org) 2.1.2\n- transformers 4.33.0\n- datasets\n- tiktoken\n- wandb\n\n## 一般用法\n\n以下是使用SophiaG训练具有NLL损失的一般模型的示例代码片段。有关超参数调优的指导，请参阅下一节。\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom sophia import SophiaG\n\n# 初始化模型、损失函数和输入数据\nmodel = Model()\ndata_loader = ...\n\n# 初始化优化器\noptimizer = SophiaG(model.parameters(), lr=2e-4, betas=(0.965, 0.99), rho=0.01, weight_decay=1e-1)\n\ntotal_bs = len(data_loader)\nbs = total_bs * block_size\nk = 10\niter_num = -1\n\n# 训练循环\nfor epoch in range(epochs):\n    for X, Y in data_loader:\n        # 标准训练代码\n        logits, loss = model(X, Y)\n        loss.backward()\n        optimizer.step(bs=bs)\n        optimizer.zero_grad(set_to_none=True)\n        iter_num += 1\n\n        if iter_num % k != k - 1:\n            continue\n        else:\n            # 更新Hessian EMA\n            logits, _ = model(X, None)\n            samp_dist = torch.distributions.Categorical(logits=logits)\n            y_sample = samp_dist.sample()\n            loss_sampled = F.cross_entropy(logits.view(-1, logits.size(-1)), y_sample.view(-1), ignore_index=-1)\n            loss_sampled.backward()\n            optimizer.update_hessian()\n            optimizer.zero_grad(set_to_none=True)\n            model.zero_grad()\n```\n\n\n## 超参数调优\n\n### 学习率的定义 \n- 代码中的更新形式为$\\theta_{t+1} = \\theta_t - lr*\\textup{clip}(m_t \u002F (\\rho * h_t + \\epsilon), 1)$，这与论文中的更新形式在重新参数化后等价。（这里的$lr$对应于论文中的$\\rho \\cdot \\eta_t$）。因此，AdamW和Lion的学习率并不直接可比。经验上，Adam和Lion以5:1的学习率比例时行为相似。SophiaG和Lion的学习率则可以直接比较。Sophia允许使用比Lion大得多的学习率，这也是Sophia速度更快的原因。\n\n### 调整超参数$\\rho$ \n- 调整$\\rho$使被截断的坐标比例保持稳定且处于适当范围。这在[GPT-2训练示例](https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fblob\u002F2443b03529ecdccf65699a5e55e68d69ede39509\u002Ftrain_sophiag.py#L398C21-L398C65)中作为`train\u002Fwin_rate`进行跟踪。`train\u002Fwin_rate`应在训练初期达到峰值，并在之后保持稳定。其值应维持在0.1至0.5之间。通常，较大的$\\rho$会导致较高的`train\u002Fwin_rate`。下文提供了T5模型中典型`win_rate`行为的示例。\n\n### 调整学习率和权重衰减\n- 选择略小于您用于AdamW的学习率，或为用于Lion的学习率的3至5倍。\n\u003Cp align=\"center\" width=\"100%\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_readme_5711b88729bf.png\" style=\"width: 60%; min-width: 200px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\n- 如果损失发散，可适当降低学习率或增大$\\rho$。\n  \n- 始终使用约为AdamW两倍的权重衰减。\n\n### GPT-2模型的超参数\n\n- 选择与您用于AdamW的学习率相近，或为用于Lion的学习率的5至10倍。\n- 调整$\\rho$使未被截断的参数比例保持稳定且处于适当范围。这在[GPT-2训练示例](https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fblob\u002F2443b03529ecdccf65699a5e55e68d69ede39509\u002Ftrain_sophiag.py#L398C21-L398C65)中作为`train\u002Fwin_rate`进行跟踪。`train\u002Fwin_rate`应在训练初期达到峰值，并在之后保持稳定。其值应维持在0.1至0.5之间。通常，较大的$\\rho$会导致较高的`train\u002Fwin_rate`。\n- 使用略大于AdamW的权重衰减，例如0.2。\n- 除学习率外，其他超参数在不同模型规模间均可通用。\n- 下表列出了不同模型规模的超参数。\n\n| 模型规模  | Adam的学习率 | Lion的学习率 | Sophia的学习率 | Sophia的$\\rho$ | Sophia的权重衰减 |\n| -------- | ------- | ------- | ------- | ------- | ------- |\n| 125M | 6e-4 | 1e-4 | 6e-4 | 0.05 | 0.2 |\n| 355M | 3e-4 | 1e-4 | 7e-4 | 0.08 | 0.2 |\n| 770M | 2e-4 | 8e-5 | 3e-4 | 0.05 | 0.2 |\n\n- 欢迎您在超参数调优过程中分享您的发现。我们非常感谢您的宝贵反馈和建议！\n\n## 复现 GPT-2 结果\n\n按照 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F) 的说明准备 [OpenWebText](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fopenwebtext) 数据集：\n```\n$ python data\u002Fopenwebtext\u002Fprepare.py\n```\n开始预训练 GPT2 Small（1.25亿参数）：\n\n如果你的机器有 10 张 A5000（24GB 显存）显卡，\n```\n$ torchrun --standalone --nproc_per_node=10 \\\n      train_sophiag.py \\\n      config\u002Ftrain_gpt2_small_sophiag.py \\\n      --batch_size=8 \\\n      --gradient_accumulation_steps=6\n```\n如果你的机器有 8 张 A100（40GB 显存）显卡，\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      train_sophiag.py \\\n      config\u002Ftrain_gpt2_small_sophiag.py \\\n      --batch_size=12 \\\n      --gradient_accumulation_steps=5\n```\n\n要复现 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F) 中的 AdamW 基线，\n```\n$ torchrun --standalone --nproc_per_node=10 \\\n      train_adam.py \\\n      config\u002Ftrain_gpt2_small_adam.py \\\n      --batch_size=8 \\\n      --gradient_accumulation_steps=6\n```\n\n这将得到下图所示的结果：\n\u003Cp align=\"center\" width=\"100%\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_readme_ce648c1f242d.png\" style=\"width: 60%; min-width: 200px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\n开始预训练 GPT2 Medium（3.55亿参数）：\n\n如果你的机器有 8 张 A100（40GB 显存）显卡，\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      train_sophiag.py \\\n      config\u002Ftrain_gpt2_medium_sophiag.py \\\n      --batch_size=6 \\\n      --gradient_accumulation_steps=10\n```\n\n要复现 AdamW 基线：\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      train_adam.py \\\n      config\u002Ftrain_gpt2_medium_adam.py \\\n      --batch_size=6 \\\n      --gradient_accumulation_steps=10\n```\n\n请根据你使用的硬件配置相应调整 ```nproc_per_node```, ```batch_size``` 和 ```gradient_accumulation_steps```，确保三者的乘积等于 480。\n\n这将得到下图所示的结果：\n\u003Cp align=\"center\" width=\"100%\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_readme_3164cf087cd1.png\" style=\"width: 60%; min-width: 200px; display: block; margin: auto;\">\n\u003C\u002Fp>\n\n开始预训练 GPT2 15亿参数模型：\n\n我们使用 [The Pile](https:\u002F\u002Fgithub.com\u002FEleutherAI\u002Fthe-pile) 数据集和 GPT NeoX 分词器。首先按照 [levanter](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002Fblob\u002Fe183ec80ec5971b12d4a3fb08a160268de342670\u002Fdocs\u002FGetting-Started-TPU-VM.md) 的说明设置 TPU 实例及环境。然后在 [optim.py](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002Fblob\u002Fe183ec80ec5971b12d4a3fb08a160268de342670\u002Fsrc\u002Flevanter\u002Foptim.py) 中将 GAMMA_SOPHIA_G 修改为 200。15亿参数模型的训练脚本如下：\n```\ngcloud compute tpus tpu-vm ssh \u003Cinstance_name> \\\n      --zone \u003Czone_name> \\\n      --worker=all \\\n      --command 'WANDB_API_KEY=\u003Cwandb_api_key> levanter\u002Finfra\u002Flaunch.sh python levanter\u002Fexamples\u002Fgpt2_example.py --config_path levanter\u002Fconfig\u002Fgpt2_1536_pile.yaml --trainer.beta1 0.965 --trainer.beta2 0.99 --trainer.min_lr_ratio 0.020 --trainer.weight_decay 0.15 --trainer.learning_rate 2.5e-4 --trainer.warmup_ratio 0.01'\n```\n\n## 致谢\n\nGPT-2 的训练代码基于 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F)，其代码简洁高效，令人赞叹。","# Sophia 优化器快速上手指南\n\nSophia 是一种可扩展的随机二阶优化器，专为语言模型预训练设计。相比 AdamW 和 Lion，Sophia 允许使用更大的学习率，从而显著加速训练过程。本指南基于官方实现的 **Sophia-G** 版本。\n\n## 环境准备\n\n### 系统要求\n- **Python**: 建议 Python 3.8+\n- **GPU**: 支持 CUDA 的 NVIDIA GPU（推荐 A100\u002FA5000 或多卡环境）\n- **框架**: PyTorch 2.1.2\n\n### 前置依赖\n请确保安装以下核心依赖库：\n- `torch` (2.1.2)\n- `transformers` (4.33.0)\n- `datasets`\n- `tiktoken`\n- `wandb` (用于监控训练指标)\n\n> **国内加速建议**：安装时推荐使用清华或阿里镜像源以提升下载速度。\n\n## 安装步骤\n\n1. **创建虚拟环境（可选但推荐）**\n   ```bash\n   python -m venv sophia_env\n   source sophia_env\u002Fbin\u002Factivate  # Linux\u002FMac\n   # 或\n   sophia_env\\Scripts\\activate     # Windows\n   ```\n\n2. **安装 PyTorch (指定版本)**\n   ```bash\n   pip install torch==2.1.2 torchvision torchaudio --index-url https:\u002F\u002Fdownload.pytorch.org\u002Fwhl\u002Fcu118\n   # 国内用户可使用清华源：\n   # pip install torch==2.1.2 torchvision torchaudio --index-url https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n   ```\n\n3. **安装其他依赖**\n   ```bash\n   pip install transformers==4.33.0 datasets tiktoken wandb\n   ```\n\n4. **获取 Sophia 代码**\n   克隆官方仓库并将 `sophia` 模块放入你的项目目录：\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia.git\n   cp -r Sophia\u002Fsophia .\u002Fyour_project\u002F\n   ```\n\n## 基本使用\n\n以下是使用 SophiaG 训练通用模型的最小化代码示例。主要区别在于初始化优化器以及在训练循环中定期更新海森矩阵（Hessian EMA）。\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom sophia import SophiaG\n\n# 1. 初始化模型、损失函数和数据加载器\nmodel = Model()\ndata_loader = ... # 你的 DataLoader\n\n# 2. 初始化 SophiaG 优化器\n# 注意：lr 通常设为 AdamW 的同等大小，或 Lion 的 3-5 倍\n# rho 控制裁剪比例，建议初始设为 0.01 - 0.1 之间并根据 win_rate 调整\noptimizer = SophiaG(model.parameters(), lr=2e-4, betas=(0.965, 0.99), rho=0.01, weight_decay=1e-1)\n\ntotal_bs = len(data_loader)\nbs = total_bs * block_size\nk = 10  # 每 k 步更新一次海森矩阵估计\niter_num = -1\n\n# 3. 训练循环\nfor epoch in range(epochs):\n    for X, Y in data_loader:\n        # 标准前向传播与反向传播\n        logits, loss = model(X, Y)\n        loss.backward()\n        \n        # 执行优化器步进\n        optimizer.step(bs=bs)\n        optimizer.zero_grad(set_to_none=True)\n        iter_num += 1\n\n        # 每隔 k 步更新海森矩阵 EMA (关键步骤)\n        if iter_num % k != k - 1:\n            continue\n        else:\n            # 采样计算二阶信息\n            logits, _ = model(X, None)\n            samp_dist = torch.distributions.Categorical(logits=logits)\n            y_sample = samp_dist.sample()\n            loss_sampled = F.cross_entropy(logits.view(-1, logits.size(-1)), y_sample.view(-1), ignore_index=-1)\n            loss_sampled.backward()\n            \n            # 更新海森矩阵并清零梯度\n            optimizer.update_hessian()\n            optimizer.zero_grad(set_to_none=True)\n            model.zero_grad()\n```\n\n### 关键参数调优建议\n- **学习率 (`lr`)**: \n  - 对比 AdamW：使用相同或略小的值。\n  - 对比 Lion：使用 3-5 倍的值（GPT-2 场景下可达 5-10 倍）。\n- **Rho (`rho`)**: \n  - 目标是将 `train\u002Fwin_rate`（未裁剪参数的比例）稳定在 **0.1 - 0.5** 之间。\n  - 如果损失发散（blow up），尝试减小 `lr` 或增大 `rho`。\n- **权重衰减 (`weight_decay`)**: \n  - 建议使用 AdamW 默认值的 **2 倍**（例如 GPT-2 训练中常用 0.2）。","某大型 AI 实验室团队正在基于海量语料库从头预训练一个百亿参数级别的垂直领域大语言模型，面临巨大的算力成本与时间压力。\n\n### 没有 Sophia 时\n- **训练周期漫长**：使用传统的 AdamW 优化器时，受限于学习率上限，模型收敛速度缓慢，完成整个预训练任务预计需要数周甚至更久。\n- **超参调优困难**：为了维持训练稳定性，不得不保守地设置较小的学习率，导致在损失函数曲面平坦区域徘徊，难以快速跳出局部最优。\n- **算力资源浪费**：漫长的迭代过程意味着需要占用昂贵的 GPU 集群更长时间，显著推高了研发成本和碳排放。\n- **二阶信息缺失**：传统一阶优化器无法利用曲率信息（Hessian 矩阵），在面对病态条件数的问题时，梯度更新方向往往不是最优路径。\n\n### 使用 Sophia 后\n- **收敛速度倍增**：Sophia 通过引入随机二阶优化机制，允许使用比 Lion 或 AdamW 大得多的学习率，将整体预训练时间缩短了 50% 以上。\n- **智能梯度裁剪**：利用海森矩阵对角线估计动态调整更新步长，自动平衡不同参数的更新幅度，既加快了收敛又避免了损失函数爆炸。\n- **大幅降低成本**：在达到相同困惑度（Perplexity）指标的前提下，显著减少了所需的 GPU 运行小时数，直接节省了数十万美元的算力开支。\n- **稳定高效更新**：通过每隔 k 步更新一次海森指数移动平均（EMA），以极低的计算开销获得了二阶优化器的优势，确保了大规模分布式训练下的数值稳定性。\n\nSophia 通过巧妙融合随机二阶信息与自适应学习率，让大模型预训练在保持稳定的同时实现了“加速跑”，彻底改变了算力与时间的博弈格局。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FLiuhong99_Sophia_5711b887.png","Liuhong99",null,"https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FLiuhong99_32ac28c8.png","Cofounder of Voyage AI","Stanford","https:\u002F\u002Fgithub.com\u002FLiuhong99",[80],{"name":81,"color":82,"percentage":83},"Python","#3572A5",100,991,57,"2026-04-02T01:53:29","MIT",4,"未说明","需要 NVIDIA GPU。示例中使用了 10x A5000 (24GB) 或 8x A100 (40GB)。对于 1.5B 模型训练提到了 TPU 实例支持。",{"notes":92,"python":89,"dependencies":93},"该工具主要用于语言模型预训练。官方示例基于 nanoGPT 和 levanter 项目。训练不同规模模型（如 GPT-2 Small\u002FMedium\u002F1.5B）需根据硬件调整进程数、批次大小和梯度累积步数，确保三者乘积等于特定值（如 480）。超参数（如学习率、rho、权重衰减）需针对 Sophia 优化器专门调整，不能直接沿用 AdamW 的设置。若使用 TPU 训练大模型，需参考 levanter 文档配置环境。",[94,95,96,97,98],"PyTorch==2.1.2","transformers==4.33.0","datasets","tiktoken","wandb",[14,35],[101,102,103],"deep-learning","large-language-models","optimizer","2026-03-27T02:49:30.150509","2026-04-08T23:26:15.085688",[107,112,117,122,127,131,136],{"id":108,"question_zh":109,"answer_zh":110,"source_url":111},23919,"如何复现论文中 GPT-2 Small\u002FMedium 的结果？为什么我的 Sophia-G 表现不如 AdamW？","若无法复现结果，请检查以下关键配置：\n1. 确保将 `scale_attn_by_inverse_layer_idx` 设置为 `True`。\n2. 对于 GPT-2 Medium 模型，需要将学习率 (lr) 提升至 7e-4（Small 模型超参通常保持不变）。\n3. 检查配置文件是否已更新到最新版本。作者指出，之前的某些运行可能使用了过于保守的学习率和权重衰减。","https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fissues\u002F46",{"id":113,"question_zh":114,"answer_zh":115,"source_url":116},23920,"在图像分类任务中，Sophia 优化器的 \"bs\" (batch size) 参数应该如何设置？","`bs` 代表每个 minibatch 中的预测数量（number of predictions）。\n- 对于语言建模：如果批次中有 n 个序列，每个序列有 T 个 token，则 `bs` = T * n。\n- 对于图像分类：如果每个批次有 n 张图像，则 `bs` 直接等于 n（即图像数量），而不是像素总数。","https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fissues\u002F48",{"id":118,"question_zh":119,"answer_zh":120,"source_url":121},23921,"是否有 JAX 版本的 Sophia 实现？如何使用？","JAX 版本已经发布。您可以参考 Levanter 项目中的文档进行使用，具体地址为：https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002Fblob\u002Fe183ec80ec5971b12d4a3fb08a160268de342670\u002Fdocs\u002FGetting-Started-TPU-VM.md","https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fissues\u002F25",{"id":123,"question_zh":124,"answer_zh":125,"source_url":126},23922,"为什么我在复现时发现 Sophia-G 和 AdamW 的最终验证损失差不多，甚至 AdamW 更好？","这种情况通常由以下原因导致：\n1. 超参数未针对 Sophia 进行适当调整（例如学习率过小可能导致初期收敛快但最终结果差）。\n2. 实验脚本不一致：建议统一使用相同的训练脚本和配置（如 min_lr, beta 值等）来对比，消除脚本差异带来的偏差。\n3. 随机性噪声：结果可能存在较大噪声，建议多次运行取平均或观察更长时间步数的趋势。作者提到其提供的超参数并非最优，且不同硬件环境也可能导致细微差异。","https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fissues\u002F31",{"id":128,"question_zh":129,"answer_zh":130,"source_url":126},23923,"使用 float16 + scaling 训练 GPT-2 时损失发散（diverges）怎么办？","这是一个已知问题。在使用混合精度（float16）训练时，Sophia 可能会遇到数值不稳定导致损失发散。建议尝试以下方法：\n1. 暂时使用 float32 进行训练以验证流程。\n2. 检查梯度裁剪（gradient clipping）设置，虽然作者提到 clip rate 通常稳定，但在混合精度下可能需要调整。\n3. 确保使用了最新的代码和配置文件，作者曾更新过相关超参数以增强稳定性。",{"id":132,"question_zh":133,"answer_zh":134,"source_url":135},23924,"Sophia 相比 AdamW 的 2 倍加速是如何计算的？是否只是过拟合了验证集？","Sophia 的加速是指达到相同验证损失所需的训练步数更少（例如 Sophia 在 100k 步达到的效果，AdamW 需要 200k 步）。\n关于过拟合质疑：作者回应称并未对 Sophia 进行过度的超参数搜索（p-hacking），当前使用的超参数仅是第三次尝试的结果，甚至可能偏保守。除了学习率外，其他超参数可以直接迁移到更大规模的模型上，证明了其泛化能力而非单纯过拟合。","https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia\u002Fissues\u002F10",{"id":137,"question_zh":138,"answer_zh":139,"source_url":135},23925,"训练过程中出现 clip rate（裁剪率）、win rate 或 Hessian norm 突然飙升是否正常？","正常情况下，clip rate、win rate 和 Hessian norm 在整个训练过程中应保持稳定。如果出现飙升（例如在 50k 步后），通常意味着：\n1. 超参数设置不当（如学习率过大）。\n2. 硬件或环境差异导致的数值问题。\n建议检查并应用作者提供的最新超参数配置，并确保代码库是最新版本。",[]]