[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-AGI-Arena--MARS":3,"tool-AGI-Arena--MARS":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 真正成长为懂上",140436,2,"2026-04-05T23:32:43",[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":75,"owner_avatar_url":76,"owner_bio":77,"owner_company":78,"owner_location":78,"owner_email":78,"owner_twitter":79,"owner_website":78,"owner_url":80,"languages":81,"stars":98,"forks":99,"last_commit_at":100,"license":101,"difficulty_score":10,"env_os":102,"env_gpu":103,"env_ram":102,"env_deps":104,"category_tags":109,"github_topics":110,"view_count":23,"oss_zip_url":78,"oss_zip_packed_at":78,"status":16,"created_at":116,"updated_at":117,"faqs":118,"releases":129},3490,"AGI-Arena\u002FMARS","MARS","The official implementation of MARS: Unleashing the Power of Variance Reduction for Training Large Models","MARS 是一个专为训练大型模型设计的统一优化框架，旨在释放“方差缩减”技术的潜力，解决传统自适应梯度方法（如 AdamW）在训练中随机梯度方差过高的问题。在大模型训练过程中，高方差往往导致收敛缓慢或不稳定，而现有的方差缩减技术又难以在实际深度学习场景中落地。MARS 巧妙地将“缩放随机递归动量”与“预条件更新”相结合：前者提供低方差的梯度估计以提升整体效率，后者近似二阶牛顿法以优化单步迭代效果，从而加速寻找最优解的过程。\n\n该工具特别适合从事大模型预训练、微调的研究人员以及需要高效优化算法的深度学习开发者。目前，MARS 已衍生出 MARS-AdamW、MARS-Lion 和 MARS-Shampoo 三种具体实现，其中 MARS-AdamW 还提供了高效的 CUDA 版本。其核心技术亮点在于引入了可调节的缩放梯度校正项，并支持多种海森矩阵近似策略，使其在视觉任务和语言模型（如 GPT-2 XL、FineWeb-Edu）上均展现出卓越的性能。对于希望突破现有优化器瓶颈、探索更高效训练方案的专业用户而言，MARS 提供了一个强大且灵活的开源选择。","# MARS: Unleashing the Power of Variance Reduction for Training Large Models\n\nThis repository contains the official code for the paper [MARS: Unleashing the Power of Variance Reduction for Training Large Models](https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438).\n\nAuthors: [Huizhuo Yuan](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=8foZzX4AAAAJ)\\*, [Yifeng Liu](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=mFvOVkMAAAAJ&hl=zh-CN)\\*, Shuang Wu, Xun Zhou, [Quanquan Gu](https:\u002F\u002Fweb.cs.ucla.edu\u002F~qgu\u002F)\n\n## 🔔 NEWS\n- **[03\u002F04\u002F2025]** MARS-AdamW CUDA implementation is available.\n- **[05\u002F01\u002F2025]** Our paper is accepted by **ICML 2025** 🎉🎉.\n- **[02\u002F10\u002F2025]** Our paper is updated on ArXiv: https:\u002F\u002Farxiv.org\u002Fpdf\u002F2411.10438v2.\n- **[01\u002F12\u002F2025]** Update scripts for reproducing GPT-2 XL results and FineWeb-Edu results.\n- **[01\u002F12\u002F2025]** Our pretraining results on FineWeb-Edu are available. GPT-2 XL reaches a Hellaswag accuracy of 56.52 in 50B tokens.\n- **[11\u002F26\u002F2024]** Vision tasks added.\n- **[11\u002F18\u002F2024]** Our code is open-sourced!\n- **[11\u002F15\u002F2024]** Our paper is released on arXiv: https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438.\n\n## About MARS\n\n**MARS** (**M**ake v**A**riance **R**eduction **S**hine) is a unified optimization framework designed to address the inherent challenges of training large models. Traditional adaptive gradient methods like Adam and AdamW often suffer from high stochastic gradient variance, while variance reduction techniques have struggled to gain practical impact in deep learning. At its core, **MARS** comprises two major components: (1) a scaled stochastic recursive momentum, which provides a variance-reduced estimator of the full gradient for better gradient complexity; and (2) the preconditioned update, which approximates the second-order Newton's method for better per-iteration complexity. By combining preconditioned gradient methods with variance reduction, **MARS** achieves the best of both worlds, accelerating the search for critical points in optimization.\n\nThe **MARS** framework is built on the following preconditioned variance-reduced updates\n\n$$\n\\mathbf{c}\\_t = \\nabla f(\\mathbf{x}\\_t, \\mathbf{\\xi}\\_t)+\\underbrace{{\\color{red}\\gamma_t} \\frac{\\beta_{1}}{1-\\beta_{1}} \\left(\\nabla f(\\mathbf{x}\\_t, \\mathbf{\\xi}\\_t)-\\nabla f(\\mathbf{x}\\_{t-1}, \\mathbf{\\xi}\\_t)\\right)}_{\\text{scaled gradient correction}}\n$$\n\n$$\n\\tilde{\\mathbf{c}}_t = \\text{Clip}(\\mathbf{c}_t,1) =  \\begin{cases}\n\\frac{\\mathbf{c}_t}{\\\\|\\mathbf{c}_t\\\\|_2} & \\text{if } \\\\|\\mathbf{c}_t\\\\|_2 > 1,\\\\\n\\mathbf{c}_t & \\text{otherwise}.\n\\end{cases}\n$$\n\n$$\n\\mathbf{m}\\_t = \\beta_1 \\mathbf{m}\\_{t-1} + (1-\\beta_{1})\\tilde{\\mathbf{c}}\\_t\n$$\n\n$$\n\\mathbf{x}\\_{t+1} = \\arg\\min_{\\mathbf{x} \\in \\mathbb{R}^d} \\left\\\\{\\eta_t \\left\\langle \\mathbf{m}_t, \\mathbf{x} \\right\\rangle + \\frac{1}{2} \\\\|\\mathbf{x} - \\mathbf{x}\\_t\n\\\\|\\_{\\mathbf{H}_t}^2\\right\\\\}\n$$\n\nHere ${\\color{red}\\gamma_t}$ is a scaling parameter that controls the strength of gradient correction.\n\n### Instantiations of **MARS**\n\nUnder the **MARS** framework, we provide three instantiations based on different Hessian matrix approximations: **MARS-AdamW**, **MARS-Lion**, and **MARS-Shampoo**. Please note that the hyperparameters in this framework are tuned on **MARS-AdamW**. When using other instantiations, it is essential to tune the hyperparameters—particularly the learning rates—for optimal performance.\n\n#### MARS-AdamW\n\n(Enable with `mars_type=\"mars-adamw\"` in `mars.py`)\n\nThe Hessian matrix approximation is defined as:\n\n$$\n\\mathbf{v}\\_t =\\beta_2 \\mathbf{v}\\_{t-1}+(1-\\beta_2) \\big(\\nabla f(\\mathbf{x}\\_t, \\mathbf{\\xi}\\_t)\\big)^2\n$$\n\n$$\n\\mathbf{H}_t := \\sqrt{\\text{diag}\\Big(\\mathbf{v}_t\\Big)}\\cdot \\frac{1 - \\beta_1^t}{\\sqrt{1 - \\beta_2^t}}.\n$$\n\n#### MARS-Lion\n\n(Enable with `mars_type=\"mars-lion\"` in `mars.py`)\n\nThe Hessian matrix approximation is defined as:\n\n$$\n\\mathbf{H}_t := \\sqrt{\\text{diag}(\\mathbf{m}_t^2)}.\n$$\n\n#### MARS-Shampoo\n\n(Enable with `mars_type=\"mars-shampoo\"` in `mars.py`)\n\nThe preconditioner can be seen as an [orthogonal mapping](https:\u002F\u002Farxiv.org\u002Fabs\u002F2409.20325) operator:\n\n$$\n\\mathbf{U}\\_t, \\mathbf{\\Sigma}\\_t, \\mathbf{V}\\_t = \\text{SVD}(\\mathbf{G}\\_t),\\qquad \n    \\mathbf{x}\\_{t+1} =\\mathbf{x}\\_t-\\eta_t\\mathbf{U}_t\\mathbf{V}\\_t^\\top.\n$$\n\nIn practice, we use the [Newton-Schulz iteration](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt) to accelerate and approximate the solution of SVD problem.\n\n### **Performance of MARS Compared to Baselines**\n\n#### Experiments on OpenWebText\n\nExperimental results for **MARS** are based on the **MARS-AdamW** instantiation, unless otherwise stated. In our experiments, gradients are calculated once per sample and per update (**MARS**-approx in our [paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438)). Performing exact gradient computation with two evaluations per update, as in the exact form of **MARS**, can slightly enhance performance but at the cost of doubling the computational expense. For more details, refer to our [paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438).\n\n**MARS** consistently outperforms AdamW and the [Muon]([https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt\u002Ftree\u002Fe01b457c7c52e1cd0c592920499a016f5289a69e)) optimizers across GPT-2 models:\n\n| **GPT-2 small**                            | **GPT-2 medium**                            | **GPT-2 large**                            |\n| ------------------------------------------------ | ------------------------------------------------- | ------------------------------------------------ |\n| \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1bc170c3e7f2.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_29a46b4aa169.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_a6f8679e86f9.png\" width=\"350\"> |\n\n| Best Val Loss         | GPT-2 Small (5B tokens) | GPT-2 Medium (5B tokens) | GPT-2 Large (5B tokens) | GPT-2 Small (20B tokens) | GPT-2 Medium (20B tokens) | GPT-2 Large (20B tokens) | GPT-2 Small (50B tokens) | GPT-2 Medium (50B tokens) | GPT-2 Large (50B tokens) |\n| --------------------- | ----------------------- | ------------------------ | ----------------------- | ------------------------ | ------------------------- | ------------------------ | ------------------------ | ------------------------- | ------------------------ |\n| AdamW                 | 3.193                   | 3.084                    | 3.013                   | 3.024                    | 2.821                     | 2.741                    | 2.885                    | 2.691                     | 2.561                    |\n| Muon                  | 3.165                   | 3.009                    | 2.915                   | 3.006                    | 2.813                     | 2.691                    | 2.901                    | 2.688                     | 2.573                    |\n| **MARS**-exact  | **3.107**         | -                      | -                     | 2.980                    | -                       | -                     | **2.847**          | -                       | -                      |\n| **MARS**-approx | 3.108                   | **2.969**          | **2.876**         | **2.981**          | **2.763**           | **2.647**          | **2.849**          | **2.636**           | **2.518**          |\n\n\n#### Efficiency of MARS\n\nThe **MARS** algorithm can achieve better performance not only within the same number of training steps, but also within the same training time:\n\n| **GPT-2 small**                             | **GPT-2 medium**                             | **GPT-2 large**                             |\n| ------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------- |\n| \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_dc6bc10a4bd7.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1b5023a675dd.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_ca6511782377.png\" width=\"350\"> |\n\n---\n\n#### Experiments on FineWeb-Edu\n\nBelow are the training and validation loss curves for both GPT‑2 Small and GPT‑2 XL when using our MARS approach versus AdamW. As you can see, MARS often yields faster convergence and consistently lower losses across different training steps.\n\n| Model                 | **GPT-2 small**                                       | **GPT-2 XL**                                       |\n| ----------------------- | -------------------------------------------------------- | --------------------------------------------------------- |\n| **Train Loss**     | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_88fbe365e9ab.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1c18bdbe35b9.png\" width=\"350\"> |\n| **Validation Loss** | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_adc36d8457e4.png\" width=\"350\">  | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_a290152bcfdf.png\" width=\"350\"> |\n\n##### Evaluation Metrics\nBelow, we present the evaluation metrics on the FineWeb-Edu dataset for both GPT‑2 Small and GPT‑2 XL, comparing OpenAI GPT2 baseline, AdamW, and our MARS-AdamW optimizer.\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_40fac08d9358.png\" width=\"350\">\n\n**Results on GPT-2 small**\n\nMARS-AdamW shows a clear improvement over AdamW and the OpenAI baseline across multiple tasks, with the **highest average score** of 45.93 on GPT‑2 Small.\n| Method\u002FTask       | ARC-E | ARC-C | BoolQ | HellaSwag | OBQA  | PIQA  | WG    | MMLU  | SciQ  | Avg.  |\n|--------------|-------|-------|-------|-----------|-------|-------|-------|-------|-------|-------|\n| OpenAI-Comm. | 39.48 | 22.70 | 48.72 | 31.14     | 27.20 | 62.51 | **51.62** | 22.92 | 64.40 | 41.19 |\n| AdamW        | 51.43 | 26.54 | 55.78 | 36.26     | 30.60 | 64.53 | 50.36 | **24.49** | **71.50** | 45.72 |\n| MARS-AdamW   | **52.23** | **27.39** | **55.84** | **36.91**    | **32.20** | **64.80** | 49.96 | 22.95 | 71.10 | **45.93** |\n\n**Results on GPT-2 XL**\n\nOn GPT‑2 XL, MARS-AdamW continues to outperform AdamW across most tasks, delivering an impressive **HellaSwag accuracy of 56.52**.\n\n| Method\u002FTask       | ARC-E | ARC-C | BoolQ | HellaSwag | OBQA  | PIQA  | WG    | MMLU  | SciQ  | Avg.  |\n|--------------|-------|-------|-------|-----------|-------|-------|-------|-------|-------|-------|\n| OpenAI-Comm. | 51.05 | 28.50 | 61.77 | 50.89     | 32.00 | 70.51 | **58.33** | 25.24 | 76.00 | 50.48 |\n| AdamW        | **68.22** | 38.40 | 61.13 | 53.93     | 39.00 | 72.69 | 54.78 | **25.47** | 85.30 | 55.43 |\n| MARS-AdamW   | 66.54 | **39.85** | **63.82** | **56.52**     | **41.20** | **73.34** | 56.59 | 23.86 | **86.00** | **56.41** |\n\n---\n\n#### Experiments on Vision Tasks\n\n**MARS** can achieve better test loss and accuracy than AdamW and the [Muon]([https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt\u002Ftree\u002Fe01b457c7c52e1cd0c592920499a016f5289a69e)) optimizers on CIFAR-10 and CIFAR-100 datasets with ResNet-18 and MultiStepLR(optimizer, milestones=[100, 150], gamma=0.1) scheduler (We display the best results for each optimizer with grid search of base learning rate within [1e-5, ..., 1e-1]):\n\n| Dataset                 | **CIFAR-10**                                       | **CIFAR-100**                                       |\n| ----------------------- | -------------------------------------------------------- | --------------------------------------------------------- |\n| **Test loss**     | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_4117d4d103dd.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_f1ad5aa4fe3a.png\" width=\"350\"> |\n| **Test Accuracy** | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1087d8678bb2.png\" width=\"350\">  | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_82b77986bb27.png\" width=\"350\"> |\n\n| Best Test loss        | CIFAR-10   | CIFAR-100  |\n| --------------------- | ---------- | ---------- |\n| AdamW                 | 0.306      | 2.608      |\n| Muon                  | 0.230      | 1.726      |\n| **MARS**-approx | **0.199** | **0.971** |\n\n| Best Test Accuracy (%) | CIFAR-10        | CIFAR-100       |\n| ---------------------- | --------------- | --------------- |\n| AdamW                  | 94.81            | 73.7           |\n| Muon                   | 95.08           | 74.64           |\n| **MARS**-approx  | **95.29** | **76.97** |\n\n\n## Training GPT-2 from Scratch:\n\n### Install Dependencies\n\n```\n$ pip install torch==2.1.2 transformers==4.33.0 datasets tiktoken numpy==1.26.4 wandb\n```\n\n### Data Preparation\n\nPrepare the [OpenWebText](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fopenwebtext) data following [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F):\n\n```\n$ python data\u002Fopenwebtext\u002Fprepare.py\n```\n\n### **Start Training**\n\nTo train a model using the **MARS** optimizer, run the following command:\n\n```bash\n$ torchrun --standalone --nproc_per_node=8 MARS\u002Ftrain_mars.py config\u002F${your_config_file}\n```\n\nThis command initiates the training of a GPT-2 model on the OpenWebText dataset using the **MARS** optimizer. All relevant hyperparameters—training, model, and optimizer—are specified in the configuration file (`${your_config_file}`). These parameters can be adjusted directly in the configuration file or through the bash script.\n\n### **Hyperparameter Details**\n\n#### **Model Hyperparameters**:\n\n- **n_layer**: Layers of networks, 12 for GPT2 Small, 24 for GPT2 Medium, 36 for GPT2 Large\n- **n_head**: Number of heads, 12 for GPT2 small, 16 for GPT2 Medium, 20 for GPT2 Large\n- **n_embd**: Embedding dimension, 768 for GPT2 small, 1024 for GPT2 Medium, 1280 for GPT2 Large\n\n#### **Optimizer Hyperparameters**:\n\n- **`learning_rate`**: Learning rate for the **MARS** optimizer.\n- **`weight_decay`**: Weight decay for the **MARS** optimizer.\n- **`beta1, beta2`**: Weights for exponential moving average.\n  - Default: `beta1=0.95, beta2=0.99`\n- **`mars_type`**: Type of optimizer to use:\n  - Options: `mars-adamw`, `mars-lion`, `mars-shampoo`\n  - Default: `mars-adamw`\n- **`optimize_1d`**: Whether **MARS** should optimize 1D parameters (e.g., layer norm parameters in GPT-2).\n  - If `False`, AdamW will be used for optimizing 1D parameters.\n  - Default: `False`\n- **`lr_1d`**: Learning rate for AdamW when **`optimize_1d`** is set to `False`.\n- **`betas_1d`**: Weights for exponential moving average in AdamW optimizer.\n  - Default: `(0.9, 0.95)`\n- **`is_approx`**: Whether to use approximate gradient calculation (**MARS**-approx).\n  - Default: `True`\n- **`gamma`**: The scaling parameter that controls the strength of gradient correction.\n  - Default: 0.025\n\n#### **Training Hyperparameters**:\n\n- **`batch_size`**: Mini-batch size per device. (for example GPT-2 Small on an A100 GPU typically uses a batch size of 15.)\n- **`gradient_accumulation_steps`**: Gradient accumulation steps to ensure the total effective batch size matches the desired scale. (for example, for a total batch size of 480: $15 \\times 4 \\times 8 \\, \\text{GPUs}$.)\n- **`schedule`**: learning rate schedule.\n  - Default: `cosine`\n\nFor more detailed hyperparameter examples, refer to:\n\n- `config\u002Ftrain_gpt2_small_mars.py`\n- `scripts\u002Frun_mars_small.sh`\n\n---\n\n### Reproducing Our Results\n\n#### **Reproducing GPT-2 Small (125M) Results**\n\nTraining with MARS using\n\n```\n$ bash scripts\u002Frun_mars_small.sh\n```\n\nor\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars.py \\\n      config\u002Ftrain_gpt2_small_mars.py \\\n      --batch_size=15 \\\n      --gradient_accumulation_steps=4\n```\n\n#### Reproducing GPT2 Medium (355M) Results\n\nTraining with MARS using\n\n```\n$ bash scripts\u002Frun_mars_medium.sh\n```\n\nor\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars.py \\\n      config\u002Ftrain_gpt2_medium_mars.py \\\n      --batch_size=15 \\\n      --gradient_accumulation_steps=4\n```\n\n#### Reproducing GPT2 Large (770M) Results\n\nTraining with MARS using\n\n```\n$ bash scripts\u002Frun_mars_large.sh\n```\n\nor\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars.py \\\n      config\u002Ftrain_gpt2_large_mars.py \\\n      --batch_size=5 \\\n      --gradient_accumulation_steps=12\n```\n\n#### **Reproducing GPT-2 XL (1.5B) Results on FineWeb-Edu**\n```\n$ bash scripts\u002Frun_mars_xl_fw.sh\n```\n\nor\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars_fw.py \\\n      config\u002Ftrain_gpt2_xl_mars.py \\\n      --batch_size=5 \\\n      --gradient_accumulation_steps=12\n```\n\n#### Reproducing Baseline Results\n\nTo reproduce the AdamW baseline:\n\n```\nbash scripts\u002Frun_adamw_{small\u002Fmedium\u002Flarge}.sh\n```\nTo reproduce the AdamW baseline on FineWeb-Edu:\n```\nbash scripts\u002Frun_adamw_{small\u002Fxl}_fw.sh\n```\n\nTo reproduce the Muon baseline following [modded-nanogpt](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt\u002Ftree\u002Fe01b457c7c52e1cd0c592920499a016f5289a69e):\n\n```\nbash scripts\u002Frun_muon_{small\u002Fmedium\u002Flarge}.sh\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#### Hyperparameters for GPT-2 models\n\n|  Model Name  | Model Size | lr for AdamW | lr for Muon | lr for MARS | lr_1d for MARS | wd for AdamW | wd for Muon | wd for MARS |\n| :----------: | :--------: | :----------: | :---------: | :---------: | :------------: | :----------: | :---------: | :---------: |\n| GPT-2 small |    125M    |     6e-4     |    2e-2    |    6e-3    |      3e-3      |     1e-1     |     0.0     |    1e-2    |\n| GPT-2 medium |    355M    |     3e-4     |    1e-2    |    3e-3    |     1.5e-3     |     1e-1     |     0.0     |    1e-2    |\n| GPT-2 large |    770M    |     2e-4     |   6.67e-3   |    2e-3    |      1e-3      |     1e-1     |     0.0     |    1e-2    |\n| GPT-2 xl |    1.5B    |     2e-4     |   -   |    2e-3    |      1e-3      |     1e-1     |     -     |    1e-2    |\n\n\n\n### Customized Training\n\nTo build your own training pipeline on other architectures and datasets, use the following template as an example:\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom mars import MARS\n\n# init model loss function and input data\nmodel = Model()\ndata_loader = ...\n\n# init the optimizer\noptimizer = MARS(model.parameters(), lr=1e-3, betas=(0.9, 0.95), gamma=0.025)\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        optimizer.update_last_grad()\n        iter_num += 1\n\n```\n\n## Star History\n\n[![Star History Chart](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_85267cd43922.png)](https:\u002F\u002Fwww.star-history.com\u002F#AGI-Arena\u002FMARS&Date)\n\n## Citation\n\nIf you find this repo useful for your research, please consider citing the paper\n\n```tex\n@article{yuan2024mars,\n  title={MARS: Unleashing the Power of Variance Reduction for Training Large Models},\n  author={Yuan, Huizhuo and Liu, Yifeng and Wu, Shuang and Zhou, Xun and Gu, Quanquan},\n  journal={arXiv preprint arXiv:2411.10438},\n  year={2024}\n}\n```\n\n## Acknowledgements\n\nThis repo is built upon [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F), [levanter](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002F) and [Sophia](https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia), we thank the authors for their great work!\n","# MARS：释放方差缩减的力量，用于训练大型模型\n\n本仓库包含论文《MARS：释放方差缩减的力量，用于训练大型模型》的官方代码，论文链接为：[https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438](https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438)。\n\n作者：[袁慧卓](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=8foZzX4AAAAJ)\\*、[刘一峰](https:\u002F\u002Fscholar.google.com\u002Fcitations?user=mFvOVkMAAAAJ&hl=zh-CN)\\*、吴爽、周勋、[顾全全](https:\u002F\u002Fweb.cs.ucla.edu\u002F~qgu\u002F)\n\n## 🔔 最新消息\n- **[2025年04月03日]** MARS-AdamW CUDA 实现已上线。\n- **[2025年01月05日]** 我们的论文已被 **ICML 2025** 接收 🎉🎉。\n- **[2025年10月02日]** 我们在 ArXiv 上更新了论文：https:\u002F\u002Farxiv.org\u002Fpdf\u002F2411.10438v2。\n- **[2025年12月01日]** 更新了复现 GPT-2 XL 和 FineWeb-Edu 结果的脚本。\n- **[2025年12月01日]** 我们在 FineWeb-Edu 上的预训练结果已公开。GPT-2 XL 在 500 亿 token 的训练下，Hellaswag 准确率达到 56.52%。\n- **[2024年11月26日]** 新增视觉任务支持。\n- **[2024年11月18日]** 我们的代码正式开源！\n- **[2024年11月15日]** 我们的论文已在 ArXiv 上发布：https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438。\n\n## 关于 MARS\n\n**MARS**（**M**ake v**A**riance **R**eduction **S**hine）是一个统一的优化框架，旨在解决训练大型模型时固有的挑战。传统的自适应梯度方法，如 Adam 和 AdamW，通常面临较高的随机梯度方差问题；而方差缩减技术在深度学习中却难以发挥实际作用。**MARS** 的核心由两个主要部分组成：(1) 缩放的随机递归动量，它提供了一种方差缩减的全梯度估计器，从而改善梯度复杂度；(2) 预条件更新，它近似二阶牛顿法，以降低每轮迭代的计算复杂度。通过将预条件梯度方法与方差缩减相结合，**MARS** 实现了两者的最佳结合，加速了优化过程中关键点的搜索。\n\n**MARS** 框架基于以下预条件方差缩减更新公式：\n\n$$\n\\mathbf{c}\\_t = \\nabla f(\\mathbf{x}\\_t, \\mathbf{\\xi}\\_t)+\\underbrace{{\\color{red}\\gamma_t} \\frac{\\beta_{1}}{1-\\beta_{1}} \\left(\\nabla f(\\mathbf{x}\\_t, \\mathbf{\\xi}\\_t)-\\nabla f(\\mathbf{x}\\_{t-1}, \\mathbf{\\xi}\\_t)\\right)}_{\\text{缩放梯度修正}}\n$$\n\n$$\n\\tilde{\\mathbf{c}}_t = \\text{Clip}(\\mathbf{c}_t,1) =  \\begin{cases}\n\\frac{\\mathbf{c}_t}{\\\\|\\mathbf{c}_t\\\\|_2} & \\text{若 } \\\\|\\mathbf{c}_t\\\\|_2 > 1,\\\\\n\\mathbf{c}_t & \\text{否则}.\n\\end{cases}\n$$\n\n$$\n\\mathbf{m}\\_t = \\beta_1 \\mathbf{m}\\_{t-1} + (1-\\beta_{1})\\tilde{\\mathbf{c}}\\_t\n$$\n\n$$\n\\mathbf{x}\\_{t+1} = \\arg\\min_{\\mathbf{x} \\in \\mathbb{R}^d} \\left\\\\{\\eta_t \\left\\langle \\mathbf{m}_t, \\mathbf{x} \\right\\rangle + \\frac{1}{2} \\\\|\\mathbf{x} - \\mathbf{x}\\_t\n\\\\|\\_{\\mathbf{H}_t}^2\\right\\\\}\n$$\n\n其中 ${\\color{red}\\gamma_t}$ 是控制梯度修正强度的缩放参数。\n\n### **MARS** 的具体实现\n\n在 **MARS** 框架下，我们提供了三种基于不同 Hessian 矩阵近似的实现：**MARS-AdamW**、**MARS-Lion** 和 **MARS-Shampoo**。请注意，该框架中的超参数是基于 **MARS-AdamW** 调优的。在使用其他实现时，务必对超参数（尤其是学习率）进行调优，以获得最佳性能。\n\n#### MARS-AdamW\n\n（在 `mars.py` 中通过设置 `mars_type=\"mars-adamw\"` 启用）\n\nHessian 矩阵的近似定义如下：\n\n$$\n\\mathbf{v}\\_t =\\beta_2 \\mathbf{v}\\_{t-1}+(1-\\beta_2) \\big(\\nabla f(\\mathbf{x}\\_t, \\mathbf{\\xi}\\_t)\\big)^2\n$$\n\n$$\n\\mathbf{H}_t := \\sqrt{\\text{diag}\\Big(\\mathbf{v}_t\\Big)}\\cdot \\frac{1 - \\beta_1^t}{\\sqrt{1 - \\beta_2^t}}.\n$$\n\n#### MARS-Lion\n\n（在 `mars.py` 中通过设置 `mars_type=\"mars-lion\"` 启用）\n\nHessian 矩阵的近似定义如下：\n\n$$\n\\mathbf{H}_t := \\sqrt{\\text{diag}(\\mathbf{m}_t^2)}.\n$$\n\n#### MARS-Shampoo\n\n（在 `mars.py` 中通过设置 `mars_type=\"mars-shampoo\"` 启用）\n\n预条件算子可以被视为一个 [正交映射](https:\u002F\u002Farxiv.org\u002Fabs\u002F2409.20325) 操作符：\n\n$$\n\\mathbf{U}\\_t, \\mathbf{\\Sigma}\\_t, \\mathbf{V}\\_t = \\text{SVD}(\\mathbf{G}\\_t),\\qquad \n    \\mathbf{x}\\_{t+1} =\\mathbf{x}\\_t-\\eta_t\\mathbf{U}_t\\mathbf{V}\\_t^\\top.\n$$\n\n在实践中，我们使用 [Newton-Schulz 迭代法](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt) 来加速并近似求解 SVD 问题。\n\n### **MARS 相比基线的表现**\n\n#### OpenWebText 数据集上的实验\n\n**MARS** 的实验结果基于 **MARS-AdamW** 实现，除非另有说明。在我们的实验中，梯度是在每个样本和每次更新时计算一次的（即 **MARS**-approx 形式，详见我们的论文 [https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438](https:\u002F\u002Farxiv.org\u002Fabs\u002F2411.10438)）。如果采用精确形式的 **MARS**，即每次更新进行两次梯度计算，则性能会略有提升，但计算开销也会翻倍。更多细节请参阅我们的论文。\n\n**MARS** 在 GPT-2 各个模型上均持续优于 AdamW 和 [Muon]([https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt\u002Ftree\u002Fe01b457c7c52e1cd0c592920499a016f5289a69e)) 优化器：\n\n| **GPT-2 small**                            | **GPT-2 medium**                            | **GPT-2 large**                            |\n| ------------------------------------------------ | ------------------------------------------------- | ------------------------------------------------ |\n| \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1bc170c3e7f2.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_29a46b4aa169.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_a6f8679e86f9.png\" width=\"350\"> |\n\n| 最佳验证损失         | GPT-2 Small (5B tokens) | GPT-2 Medium (5B tokens) | GPT-2 Large (5B tokens) | GPT-2 Small (20B tokens) | GPT-2 Medium (20B tokens) | GPT-2 Large (20B tokens) | GPT-2 Small (50B tokens) | GPT-2 Medium (50B tokens) | GPT-2 Large (50B tokens) |\n| --------------------- | ----------------------- | ------------------------ | ----------------------- | ------------------------ | ------------------------- | ------------------------ | ------------------------ | ------------------------- | ------------------------ |\n| AdamW                 | 3.193                   | 3.084                    | 3.013                   | 3.024                    | 2.821                     | 2.741                    | 2.885                    | 2.691                     | 2.561                    |\n| Muon                  | 3.165                   | 3.009                    | 2.915                   | 3.006                    | 2.813                     | 2.691                    | 2.901                    | 2.688                     | 2.573                    |\n| **MARS**-exact  | **3.107**         | -                      | -                     | 2.980                    | -                       | -                     | **2.847**          | -                       | -                      |\n| **MARS**-approx | 3.108                   | **2.969**          | **2.876**         | **2.981**          | **2.763**           | **2.647**          | **2.849**          | **2.636**           | **2.518**          |\n\n\n#### MARS 的效率\n\n**MARS** 算法不仅可以在相同的训练步数内取得更好的性能，还可以在相同的训练时间内实现更优的效果：\n\n| **GPT-2 small**                             | **GPT-2 medium**                             | **GPT-2 large**                             |\n| ------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------- |\n| \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_dc6bc10a4bd7.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1b5023a675dd.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_ca6511782377.png\" width=\"350\"> |\n\n---\n\n#### FineWeb-Edu 数据集上的实验\n\n以下是使用我们的 MARS 方法与 AdamW 相比时，GPT‑2 Small 和 GPT‑2 XL 的训练和验证损失曲线。可以看出，MARS 往往能带来更快的收敛速度，并且在不同训练步数下始终表现出更低的损失。\n\n| 模型                 | **GPT-2 small**                                       | **GPT-2 XL**                                       |\n| ----------------------- | -------------------------------------------------------- | --------------------------------------------------------- |\n| **训练损失**     | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_88fbe365e9ab.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1c18bdbe35b9.png\" width=\"350\"> |\n| **验证损失** | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_adc36d8457e4.png\" width=\"350\">  | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_a290152bcfdf.png\" width=\"350\"> |\n\n##### 评估指标\n下面我们展示了 GPT‑2 Small 和 GPT‑2 XL 在 FineWeb-Edu 数据集上的评估指标，对比了 OpenAI GPT2 基线、AdamW 以及我们的 MARS-AdamW 优化器。\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_40fac08d9358.png\" width=\"350\">\n\n**GPT-2 small 的结果**\n\nMARS-AdamW 在多个任务上均明显优于 AdamW 和 OpenAI 基线，在 GPT‑2 Small 上以 **45.93 的最高平均分**领先。\n| 方法\u002F任务       | ARC-E | ARC-C | BoolQ | HellaSwag | OBQA  | PIQA  | WG    | MMLU  | SciQ  | 平均  |\n|--------------|-------|-------|-------|-----------|-------|-------|-------|-------|-------|-------|\n| OpenAI-Comm. | 39.48 | 22.70 | 48.72 | 31.14     | 27.20 | 62.51 | **51.62** | 22.92 | 64.40 | 41.19 |\n| AdamW        | 51.43 | 26.54 | 55.78 | 36.26     | 30.60 | 64.53 | 50.36 | **24.49** | **71.50** | 45.72 |\n| MARS-AdamW   | **52.23** | **27.39** | **55.84** | **36.91**    | **32.20** | **64.80** | 49.96 | 22.95 | 71.10 | **45.93** |\n\n**GPT-2 XL 的结果**\n\n在 GPT‑2 XL 上，MARS-AdamW 继续在大多数任务上超越 AdamW，尤其在 **HellaSwag 任务中达到了 56.52% 的准确率**。\n\n| 方法\u002F任务       | ARC-E | ARC-C | BoolQ | HellaSwag | OBQA  | PIQA  | WG    | MMLU  | SciQ  | 平均  |\n|--------------|-------|-------|-------|-----------|-------|-------|-------|-------|-------|-------|\n| OpenAI-Comm. | 51.05 | 28.50 | 61.77 | 50.89     | 32.00 | 70.51 | **58.33** | 25.24 | 76.00 | 50.48 |\n| AdamW        | **68.22** | 38.40 | 61.13 | 53.93     | 39.00 | 72.69 | 54.78 | **25.47** | 85.30 | 55.43 |\n| MARS-AdamW   | 66.54 | **39.85** | **63.82** | **56.52**     | **41.20** | **73.34** | 56.59 | 23.86 | **86.00** | **56.41** |\n\n---\n\n#### 视觉任务上的实验\n\n在 CIFAR-10 和 CIFAR-100 数据集上，使用 ResNet-18 和 MultiStepLR(optimzer, milestones=[100, 150], gamma=0.1) 调度器时，**MARS** 能够获得比 AdamW 和 [Muon]([https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt\u002Ftree\u002Fe01b457c7c52e1cd0c592920499a016f5289a69e)) 更好的测试损失和准确率。（我们通过网格搜索基础学习率 [1e-5, ..., 1e-1] 来展示每个优化器的最佳结果）：\n\n| 数据集                 | **CIFAR-10**                                       | **CIFAR-100**                                       |\n| ----------------------- | -------------------------------------------------------- | --------------------------------------------------------- |\n| **测试损失**     | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_4117d4d103dd.png\" width=\"350\"> | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_f1ad5aa4fe3a.png\" width=\"350\"> |\n| **测试准确率** | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_1087d8678bb2.png\" width=\"350\">  | \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_82b77986bb27.png\" width=\"350\"> |\n\n| 最佳测试损失        | CIFAR-10   | CIFAR-100  |\n| --------------------- | ---------- | ---------- |\n| AdamW                 | 0.306      | 2.608      |\n| Muon                  | 0.230      | 1.726      |\n| **MARS**-approx | **0.199** | **0.971** |\n\n| 最佳测试准确率 (%) | CIFAR-10        | CIFAR-100       |\n| ---------------------- | --------------- | --------------- |\n| AdamW                  | 94.81            | 73.7           |\n| Muon                   | 95.08           | 74.64           |\n| **MARS**-approx  | **95.29** | **76.97** |\n\n\n\n\n## 从头开始训练 GPT-2：\n\n### 安装依赖\n\n```\n$ pip install torch==2.1.2 transformers==4.33.0 datasets tiktoken numpy==1.26.4 wandb\n```\n\n### 数据准备\n\n按照 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F) 的方式准备 [OpenWebText](https:\u002F\u002Fhuggingface.co\u002Fdatasets\u002Fopenwebtext) 数据：\n\n```\n$ python data\u002Fopenwebtext\u002Fprepare.py\n```\n\n### **开始训练**\n\n要使用 **MARS** 优化器训练模型，请运行以下命令：\n\n```bash\n$ torchrun --standalone --nproc_per_node=8 MARS\u002Ftrain_mars.py config\u002F${your_config_file}\n```\n\n该命令将使用 **MARS** 优化器在 OpenWebText 数据集上启动 GPT-2 模型的训练。所有相关超参数——包括训练、模型和优化器——均在配置文件（`${your_config_file}`）中指定。这些参数可以直接在配置文件中调整，也可以通过 Bash 脚本进行修改。\n\n### **超参数详情**\n\n#### **模型超参数**：\n\n- **n_layer**：网络层数，GPT2 Small 为 12 层，GPT2 Medium 为 24 层，GPT2 Large 为 36 层。\n- **n_head**：注意力头数，GPT2 small 为 12 个，GPT2 Medium 为 16 个，GPT2 Large 为 20 个。\n- **n_embd**：嵌入维度，GPT2 small 为 768，GPT2 Medium 为 1024，GPT2 Large 为 1280。\n\n#### **优化器超参数**：\n\n- **`learning_rate`**：**MARS** 优化器的学习率。\n- **`weight_decay`**：**MARS** 优化器的权重衰减。\n- **`beta1, beta2`**：指数移动平均的权重。\n  - 默认值：`beta1=0.95, beta2=0.99`\n- **`mars_type`**：使用的优化器类型：\n  - 选项：`mars-adamw`、`mars-lion`、`mars-shampoo`\n  - 默认值：`mars-adamw`\n- **`optimize_1d`**：是否让 **MARS** 优化一维参数（例如 GPT-2 中的层归一化参数）。\n  - 如果为 `False`，则使用 AdamW 来优化一维参数。\n  - 默认值：`False`\n- **`lr_1d`**：当 **`optimize_1d`** 设置为 `False` 时，AdamW 的学习率。\n- **`betas_1d`**：AdamW 优化器中指数移动平均的权重。\n  - 默认值：`(0.9, 0.95)`\n- **`is_approx`**：是否使用近似梯度计算（**MARS**-approx）。\n  - 默认值：`True`\n- **`gamma`**：控制梯度修正强度的缩放参数。\n  - 默认值：0.025\n\n#### **训练超参数**：\n\n- **`batch_size`**：每个设备上的小批量大小。（例如，在 A100 GPU 上训练 GPT-2 Small 时，通常使用 15 的批量大小。）\n- **`gradient_accumulation_steps`**：梯度累积步数，以确保总有效批量大小达到所需规模。（例如，对于总批量大小为 480 的情况：$15 \\times 4 \\times 8 \\, \\text{GPUs}$。）\n- **`schedule`**：学习率调度策略。\n  - 默认值：`cosine`\n\n更多详细的超参数示例，请参阅：\n\n- `config\u002Ftrain_gpt2_small_mars.py`\n- `scripts\u002Frun_mars_small.sh`\n\n---\n\n### 复现我们的结果\n\n#### **复现 GPT-2 Small (125M) 的结果**\n\n使用以下命令训练 MARS：\n\n```\n$ bash scripts\u002Frun_mars_small.sh\n```\n\n或者\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars.py \\\n      config\u002Ftrain_gpt2_small_mars.py \\\n      --batch_size=15 \\\n      --gradient_accumulation_steps=4\n```\n\n#### **复现 GPT2 Medium (355M) 的结果**\n\n使用以下命令训练 MARS：\n\n```\n$ bash scripts\u002Frun_mars_medium.sh\n```\n\n或者\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars.py \\\n      config\u002Ftrain_gpt2_medium_mars.py \\\n      --batch_size=15 \\\n      --gradient_accumulation_steps=4\n```\n\n#### **复现 GPT2 Large (770M) 的结果**\n\n使用以下命令训练 MARS：\n\n```\n$ bash scripts\u002Frun_mars_large.sh\n```\n\n或者\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars.py \\\n      config\u002Ftrain_gpt2_large_mars.py \\\n      --batch_size=5 \\\n      --gradient_accumulation_steps=12\n```\n\n#### **在 FineWeb-Edu 上复现 GPT-2 XL (1.5B) 的结果**\n\n```\n$ bash scripts\u002Frun_mars_xl_fw.sh\n```\n\n或者\n\n```\n$ torchrun --standalone --nproc_per_node=8 \\\n      MARS\u002Ftrain_mars_fw.py \\\n      config\u002Ftrain_gpt2_xl_mars.py \\\n      --batch_size=5 \\\n      --gradient_accumulation_steps=12\n```\n\n#### **复现基线结果**\n\n要复现 AdamW 基线：\n\n```\nbash scripts\u002Frun_adamw_{small\u002Fmedium\u002Flarge}.sh\n```\n\n要在 FineWeb-Edu 上复现 AdamW 基线：\n\n```\nbash scripts\u002Frun_adamw_{small\u002Fxl}_fw.sh\n```\n\n要复现 Muon 基线，遵循 [modded-nanogpt](https:\u002F\u002Fgithub.com\u002FKellerJordan\u002Fmodded-nanogpt\u002Ftree\u002Fe01b457c7c52e1cd0c592920499a016f5289a69e) 的方法：\n\n```\nbash scripts\u002Frun_muon_{small\u002Fmedium\u002Flarge}.sh\n```\n\n请根据您使用的硬件配置相应调整 ``nproc_per_node``、``batch_size`` 和 ``gradient_accumulation_steps``，确保它们的乘积等于 480。\n\n#### GPT-2 模型的超参数\n\n| 模型名称  | 模型大小 | AdamW 学习率 | Muon 学习率 | MARS 学习率 | MARS 一维学习率 | AdamW 权重衰减 | Muon 权重衰减 | MARS 权重衰减 |\n| :----------: | :--------: | :----------: | :---------: | :---------: | :------------: | :----------: | :---------: | :---------: |\n| GPT-2 small |    125M    |     6e-4     |    2e-2    |    6e-3    |      3e-3      |     1e-1     |     0.0     |    1e-2    |\n| GPT-2 medium |    355M    |     3e-4     |    1e-2    |    3e-3    |     1.5e-3     |     1e-1     |     0.0     |    1e-2    |\n| GPT-2 large |    770M    |     2e-4     |   6.67e-3   |    2e-3    |      1e-3      |     1e-1     |     0.0     |    1e-2    |\n| GPT-2 xl |    1.5B    |     2e-4     |   -   |    2e-3    |      1e-3      |     1e-1     |     -     |    1e-2    |\n\n\n\n### 自定义训练\n\n要构建针对其他架构和数据集的自定义训练流程，可以参考以下模板：\n\n```python\nimport torch\nimport torch.nn.functional as F\nfrom mars import MARS\n\n# 初始化模型损失函数和输入数据\nmodel = Model()\ndata_loader = ...\n\n# 初始化优化器\noptimizer = MARS(model.parameters(), lr=1e-3, betas=(0.9, 0.95), gamma=0.025)\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        optimizer.update_last_grad()\n        iter_num += 1\n\n```\n\n## 星标历史\n\n[![星标历史图](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_readme_85267cd43922.png)](https:\u002F\u002Fwww.star-history.com\u002F#AGI-Arena\u002FMARS&Date)\n\n## 引用\n\n如果您觉得本仓库对您的研究有所帮助，请考虑引用以下论文：\n\n```tex\n@article{yuan2024mars,\n  title={MARS: Unleashing the Power of Variance Reduction for Training Large Models},\n  author={Yuan, Huizhuo and Liu, Yifeng and Wu, Shuang and Zhou, Xun and Gu, Quanquan},\n  journal={arXiv preprint arXiv:2411.10438},\n  year={2024}\n}\n```\n\n## 致谢\n\n本仓库基于 [nanoGPT](https:\u002F\u002Fgithub.com\u002Fkarpathy\u002FnanoGPT\u002F)、[levanter](https:\u002F\u002Fgithub.com\u002Fstanford-crfm\u002Flevanter\u002F) 和 [Sophia](https:\u002F\u002Fgithub.com\u002FLiuhong99\u002FSophia) 构建，我们感谢这些作者的杰出工作！","# MARS 快速上手指南\n\nMARS (**M**ake v**A**riance **R**eduction **S**hine) 是一个统一的优化框架，旨在解决大模型训练中的挑战。它结合了方差缩减技术与预条件更新方法，在相同训练步数或时间内，相比 AdamW 和 Muon 等优化器能实现更快的收敛速度和更低的损失值。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**: Linux (推荐 Ubuntu 20.04+)\n*   **Python 版本**: 3.8 - 3.10\n*   **硬件要求**: NVIDIA GPU (支持 CUDA)，建议显存 16GB 以上以运行大模型实验\n*   **核心依赖**:\n    *   PyTorch >= 2.1.2\n    *   Transformers >= 4.33.0\n    *   CUDA Toolkit (需与 PyTorch 版本匹配)\n\n> **国内加速建议**：建议使用清华或阿里镜像源安装依赖，以提升下载速度。\n\n## 安装步骤\n\n### 1. 克隆项目代码\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fyour-repo\u002FMARS.git\ncd MARS\n```\n\n### 2. 创建虚拟环境并安装依赖\n\n推荐使用 `conda` 或 `venv` 隔离环境。以下命令使用国内镜像源安装指定版本的 PyTorch 和其他依赖：\n\n```bash\n# 创建虚拟环境\nconda create -n mars_env python=3.9 -y\nconda activate mars_env\n\n# 安装 PyTorch (使用清华镜像，根据实际 CUDA 版本调整，此处以 cu118 为例)\npip install torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --index-url https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n\n# 安装其他项目依赖\npip install transformers==4.33.0 datasets accelerate wandb matplotlib numpy scipy -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n```\n\n> **注意**：如果需要使用 **MARS-AdamW CUDA 加速版**（2025\u002F03\u002F04 更新），请确保已正确安装 CUDA 开发工具包，并按照仓库内的 `cuda_extension` 说明编译自定义算子（如有）。\n\n## 基本使用\n\nMARS 提供了三种实例化变体：**MARS-AdamW**（推荐默认）、**MARS-Lion** 和 **MARS-Shampoo**。大多数情况下，直接使用 `MARS-AdamW` 即可获得最佳效果。\n\n### 1. 在 Python 代码中调用\n\n将原有的优化器（如 `torch.optim.AdamW`）替换为 `MARS` 优化器。\n\n```python\nfrom mars import MARS\n\n# 假设 model 是你的神经网络模型\nmodel = ... \n\n# 初始化 MARS 优化器\n# mars_type 可选：\"mars-adamw\" (默认), \"mars-lion\", \"mars-shampoo\"\noptimizer = MARS(\n    model.parameters(), \n    lr=1e-3,              # 学习率可能需要重新调优，通常比 AdamW 稍大\n    betas=(0.9, 0.999),   # beta1, beta2\n    weight_decay=0.01,\n    mars_type=\"mars-adamw\" \n)\n\n# 标准训练循环\nfor batch in dataloader:\n    optimizer.zero_grad()\n    loss = compute_loss(model, batch)\n    loss.backward()\n    optimizer.step()\n```\n\n### 2. 关键参数说明\n\n*   **`mars_type`**: 选择变体。\n    *   `\"mars-adamw\"`: 基于对角海森矩阵近似，最稳定，适合大多数 NLP 和 Vision 任务。\n    *   `\"mars-lion\"`: 使用动量的平方作为近似，计算更轻量。\n    *   `\"mars-shampoo\"`: 使用 SVD 分解进行正交映射，适合特定大规模分布式场景（内部使用 Newton-Schulz 迭代加速）。\n*   **`lr` (学习率)**: MARS 的超参数敏感性与 AdamW 不同。官方建议在迁移使用时，针对新任务对学习率进行网格搜索（范围通常在 `1e-5` 到 `1e-1` 之间）。\n*   **`gamma_t`**: 梯度校正的缩放参数，已在内部实现动态调整，通常无需手动设置。\n\n### 3. 复现 GPT-2 训练结果\n\n项目提供了完整的脚本用于复现 OpenWebText 和 FineWeb-Edu 上的 GPT-2 训练结果。\n\n```bash\n# 示例：运行 GPT-2 Small 在 FineWeb-Edu 上的训练 (使用 MARS-AdamW)\npython train_gpt2.py \\\n    --dataset fineweb-edu \\\n    --model_size small \\\n    --optimizer mars-adamw \\\n    --total_tokens 50B \\\n    --batch_size 512\n```\n\n> **提示**：对于视觉任务（如 CIFAR-10\u002F100），请参考 `examples\u002Fvision\u002F` 目录下的脚本，配合 `MultiStepLR` 调度器使用可获得优于 AdamW 的准确率。","某大型 AI 实验室团队正在基于 FineWeb-Edu 数据集从头预训练一个类似 GPT-2 XL 的亿级参数语言模型，面临训练成本高昂与收敛缓慢的双重挑战。\n\n### 没有 MARS 时\n- **梯度噪声大导致收敛震荡**：传统 AdamW 优化器在处理大规模数据时，随机梯度方差过高，导致损失函数曲线剧烈波动，难以稳定下降。\n- **训练周期漫长**：为了达到理想的验证集准确率（如 Hellaswag 基准），需要消耗海量的 Token 和极长的 GPU 机时，研发迭代效率低下。\n- **超参数调优困难**：由于优化路径不平滑，学习率等关键超参数极其敏感，稍有不慎就会导致模型发散或陷入局部最优。\n- **算力资源浪费**：大量的计算资源被消耗在无效的震荡更新上，而非实质性的模型性能提升，增加了项目的资金压力。\n\n### 使用 MARS 后\n- **方差抑制显著平滑轨迹**：MARS 通过“缩放随机递归动量”机制有效降低了梯度估计方差，使训练曲线平稳快速下降，大幅减少了震荡。\n- **加速收敛节省算力**：在相同 Token 数量下，模型能更快达到高精度（例如在 500 亿 Token 内即可让 Hellaswag 准确率突破 56.5%），显著缩短训练周期。\n- **二阶近似提升鲁棒性**：利用预处理更新模拟牛顿法，MARS 对超参数的变化更具包容性，降低了调参门槛，让模型更容易找到全局最优解。\n- **单位算力产出最大化**：结合方差缩减与预处理优势，每一轮迭代都更高效地逼近临界点，同等预算下可训练更大规模或更高质量的模型。\n\nMARS 通过将方差缩减技术与自适应梯度方法深度融合，从根本上解决了大模型训练中的噪声与效率瓶颈，让昂贵的算力真正转化为模型智能。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FAGI-Arena_MARS_1bc170c3.png","AGI-Arena","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FAGI-Arena_05478e62.png","🤖 AGI Arena | Where innovation meets intelligence 🌌 | Exploring the frontier of Artificial General Intelligence | Ideas, insights, and breakthroughs",null,"agiarena","https:\u002F\u002Fgithub.com\u002FAGI-Arena",[82,86,90,94],{"name":83,"color":84,"percentage":85},"Python","#3572A5",92.2,{"name":87,"color":88,"percentage":89},"Cuda","#3A4E3A",4.2,{"name":91,"color":92,"percentage":93},"C++","#f34b7d",2.7,{"name":95,"color":96,"percentage":97},"Shell","#89e051",0.9,718,49,"2026-04-03T11:22:54","Apache-2.0","未说明","需要 NVIDIA GPU（提及了 MARS-AdamW CUDA 实现），具体型号和显存大小未说明，需支持 CUDA",{"notes":105,"python":102,"dependencies":106},"README 内容在依赖安装部分被截断，仅明确列出了 torch==2.1.2 和 transformers==4.33.0。该工具包含针对大模型训练的优化器实现（如 MARS-AdamW），并提供了 Vision 任务（ResNet-18）和 LLM（GPT-2）的实验脚本。由于涉及大规模预训练实验（如 50B tokens），实际运行可能需要较高的显存和计算资源。",[107,108],"torch==2.1.2","transformers==4.33.0",[13,26],[111,112,113,114,115],"fine-tuning","large-language-models","optimization-algorithms","optimizer","pretraining","2026-03-27T02:49:30.150509","2026-04-06T11:31:10.385811",[119,124],{"id":120,"question_zh":121,"answer_zh":122,"source_url":123},16014,"MARS 优化器运行时出现关于 `add_` 函数过载的警告，这是否有害？","该警告是因为使用了旧版本的 `add_` 函数调用方式，不会影响性能。为避免此警告，维护者已更新了优化器文件（optimizers\u002Fmars.py）。建议拉取最新代码以消除警告。","https:\u002F\u002Fgithub.com\u002FAGI-Arena\u002FMARS\u002Fissues\u002F1",{"id":125,"question_zh":126,"answer_zh":127,"source_url":128},16015,"是否有 8bit 量化版本以减少 GPU 显存占用？","目前尚未发布 8bit 版本，但维护者确认未来将发布量化变体（quantization variants）。请持续关注项目更新以获取低比特优化器支持。","https:\u002F\u002Fgithub.com\u002FAGI-Arena\u002FMARS\u002Fissues\u002F2",[]]