Repository navigation
Fix checkpointing with partially initialized optimizer state - #4474
Conversation
If "parameters" do not receive gradients, they are not being trained. Why would they be parameters in the first place, why not persistent buffers? @claude review the PR -- focus on analyzing if this is the proper solution of the underlying problem |
|
Claude finished @tianyu-l's task in 8m 1s —— View job Review: Is this the proper solution to the underlying problem?
Short answerThere are two separate questions bundled here, and they have different answers:
On @tianyu-l's question (buffers vs. parameters)Your instinct is correct, with one refinement. If
The important consequence: freezing solves the reported So per CLAUDE.md principle #2 ("investigate root cause before patching"): the root cause of the DeepSeek-V4 reproducer is in the model, and the model should be fixed regardless of this PR. This PR's description should stop presenting DeepSeek-V4 as the justification. But the
|
|
@tianyu-l Thanks for raising this. To clarify the DeepSeek-V4 case, the indexer auxiliary loss has not yet been connected in the current TorchTitan implementation. The code notes that it will be re-added once the carrier-injected auxiliary-loss mechanism is available. |
|
@yu-chen-code Thanks, I think the improvement sounds legit, given claude's analysis around MoE experts or any similar dynamism / sparsity in model. But yeah, agreed that this is not a solution for DSv4, which we should work on the loss instead. |
Surveyed, not merged -- two 80B captures are mid-flight and folding in 64 commits would make any new failure ambiguous. This records the analysis so the merge is cheap later. Diverged at 6ee6d5d (2026-08-30), upstream tip 966befc. ZERO upstream commits touch experiments/ezpz, so there are no conflicts in our own code. The risk is entirely in core files we import from. Of those, components/loss.py matters most: we import BaseLoss, CrossEntropyLoss, ChunkedLossWrapper and IGNORE_INDEX, all four still present, with one method renamed (typecheck_forward -> spmd_typecheck). zloss.py overrides only __init__ and __call__, so it does not inherit that rename -- checked rather than assumed, since a preserved name with a changed contract is the dangerous case, not a deleted one. Corrects my earlier risk ranking. I called pytorch#4328 (refactor max_context_length) the highest risk; that was wrong. max_context_length is UNCHANGED upstream -- same field, same default, plus a validation guard. The PR changes seq_len in model specs and registries, not the --training.max-context-length flag we pass. The single seam is agpt/config_registry.py:291, where our own agpt(seq_len=...) assigns cfg.training.max_context_length. The real risks, ordered: pytorch#4398 (valid-token counts move into collation -- that is the gradient-accumulation path), then the checkpoint cluster (pytorch#4187/pytorch#4188/pytorch#4197/pytorch#4270/pytorch#4474, which we subclass and where pinned clones have already broken on optim-statedict changes), then pytorch#4382 (Adam first-step state). Includes a merge order: smoke at 2N, then a resume from a real checkpoint, a seeded loss/grad_norm comparison, and config_registry.py:291 by inspection.
… PR 4474 Co-authored-by: zhenyu10<[email protected]> # message auto-generated for no-merge-commit merge: !721 merge master-backport-pr4474-resume into master fix(checkpoint): backport partial optimizer state initialization from PR 4474 Created-by: zhenyu10 Commit-by: zhenyu10 Merged-by: cann-robot Description: ## 描述 固定的 TorchTitan 版本 2807d3f550fe27db18bd9395ba63176364eaed6d 在 optimizer 已有任意 state 时直接跳过初始化。部分可训练参数尚未收到梯度时,checkpoint 会缺少对应 AdamW state,恢复时可能出现 Missing key。 回补已合入上游的 [pytorch/torchtitan#4474](https://github.com/pytorch/torchtitan/pull/4474),在 torchtitan_npu/patches/torchtitan/components/optimizer.py 实现随包导入生效的临时 package patch,保留当前固定依赖版本。 - 仅物化缺失的可训练参数 state,保留已有 state、参数、梯度引用和学习率;新建 Adam/AdamW state 的 step、moments 重置为零。 - 同时替换 checkpoint_utils 和 optimizer consumer 的函数引用。 - 保留真实 DCP 保存、加载和恢复后更新的单元测试。 - 将原单卡功能用例合并为两卡 FSDP2/EP2 精度对齐用例 dsv4_checkpoint_resume_ep2_fsdp2,接入现有 models 门禁 suite。 - 连续训练 4 步并保存完整 step 2 checkpoint;新进程显式 load-step=2,再训练第 3、4 步。两阶段总步数均为 4,seed=42 且开启 deterministic,学习率调度保持一致。 - 独立 TensorBoard 目录严格检查步骤集合 (1,2,3,4) 和 (3,4),逐值精确比较 loss_metrics/global_avg_loss 与 grad_norm,不舍入、不使用容差。缺失、重复步骤或非有限值均失败。 本轮 f7cab35 仅补充测试、文档和统一文件头;生产实现 AST 与 970aade 一致。a06c4ee 将比较器自测的数据生成循环展平,修复服务端 CodeCheck 的函数嵌套深度问题;8 项比较器自测在本地和 121 容器均再次通过。 ## 类型 - [x] Bug 修复 - [ ] 新功能 - [ ] 重构(即不是新增功能,也不是修改bug的代码变动) - [ ] 构建过程或辅助工具的变动 - [ ] 文档内容更新 ## Checklist: - [x] 我的代码遵循这个项目的代码风格 - [x] 我已经自己测试过我的代码 - [x] 我已经更新了相应的文档 - [x] 我已经在标题中正确使用了类型标签(例如:feat, fix, refactor, docs, test) ## 如何测试 2026-09-07,在 zy 容器、Ascend 910B4 两卡验证。Python 3.12.13,torch 2.14.0.dev20260719+cpu,torch_npu 2.14.0.dev20260808,triton-ascend 3.2.1,CANN 9.2.0_weekly.20260819.01;使用未修改的固定 TorchTitan 源码。 运行命令: ~~~bash python -m tests.integration_tests.run_tests "$OUTPUT_DIR" --test_suite models --test_name dsv4_checkpoint_resume_ep2_fsdp2 --ngpu 2 ~~~ 结果:通过,退出状态 0。TensorBoard 原始标量精确比较结果: | step | 连续训练 loss | 续训 loss | 连续训练 grad_norm | 续训 grad_norm | |---|---|---|---|---| | 3 | 15.815855026245117 | 15.815855026245117 | 5.025174617767334 | 5.025174617767334 | | 4 | 15.762657165527344 | 15.762657165527344 | 4.744232177734375 | 4.744232177734375 | ~~~bash TORCH_DEVICE_BACKEND_AUTOLOAD=0 python -m pytest -v --tb=short tests/unit_tests/tooling/test_checkpoint_metrics.py tests/unit_tests/patches/torchtitan/components/test_optimizer_patch.py tests/unit_tests/override/checkpoint/test_checkpoint.py ~~~ 结果:17 passed。其中 9 项为 optimizer/checkpoint 测试,8 项为使用真实 TensorBoard 文件的比较器 tooling 自测;tooling 自测不计入产品 UT 覆盖。可检测 loss 单独不一致、grad_norm 单独不一致、少训一步、从头重训、重复步骤及非有限值。 改动范围 Ruff check、Ruff format、OAT、git diff --check 通过。OAT 检查 9 个文件,两项无效文件/许可证头计数均为 0。 完整 python -m pre_commit run --all-files --show-diff-on-failure 已执行,未全通过:候选版本与干净 970aade 基线有完全相同的 Ruff I001(experiments/torchao-npu/tests/test_wrapper_storage_delegation.py:17)及 41 项 Pyrefly 错误,其余执行的 hooks 通过。未将历史问题混入本次测试修改。提交 a06c4ee 已在页面回复 `compile`,触发[流水线 #317](https://gitcode.com/cann/torchtitan-npu/actions/runs/844e1e29a0ea46b4b46de3105280ab05)。CodeCheck 于 2026-09-07 15:27:28 完成,代码问题 0、敏感词问题 0、忽略问题 0;Codecheck_dt、CodeCheck_precommit 和 CodeCheck_staticcheck 均通过。[CodeCheck 报告](https://www.openlibing.com/apps/entryCheckDashCode/MR_6c96e2165f194048a9f6b0a4ead03bbe/a4e0a4333093b0cdf53deb330ee2b60a?projectId=300033&codeHostingPlatformFlag=gitcode)。 ## 其他信息 checkpoint 格式不变;该 patch 保证新保存 checkpoint 的 optimizer state 完整,不修复历史上已缺少 state 的 checkpoint。固定依赖升级包含上游 PR #4474 后,应删除临时 patch 和对应导入。未修改仓内 golden loss 文件,续训对照使用本次连续训练结果。 See merge request: cann/torchtitan-npu!721
… route PRs to area experts (#5667) ## Why PR volume has outgrown review capacity. Of the 1,429 PRs merged since April, one maintainer approved 1,066 (75%), and October alone had 351 merged PRs. Many PRs are agent-generated, and the agents (and `@claude`) follow `.claude/CLAUDE.md`, which in several places contradicts how PRs are actually reviewed: - Principle 5 says to flag BC breakage. The maintainers deliberately don't promise BC. - config.md says "emit a warning" when config is silently skipped. Review comments almost always say "just error out". - PR expectations say "new features need CPU unit tests at minimum". In ~1,000 reviews the maintainer almost never asked for a new unit test, and often asked for tests to be removed or folded into existing ones. The result: across 130 PRs, the current `@claude` cited CLAUDE.md at least 38 times, mostly to escalate. That produced 16+ BC concerns, 9+ "add a warning" suggestions and 23+ test requests. It also missed the most common real review question: should this change exist in this form at all? This PR rewrites the rules from what reviewers actually say. The source data: - 3,391 inline comments, 289 review bodies and 383 PR comments from Jul-Oct 2026. - 48 refactor PRs, used to extract structural preferences. - A comparison of 196 `@claude` runs against the human review on the same PRs. It then adds a torchtitan review skill, builds on PyTorch's `pr-review` skill, and routes PRs to area experts without making them blocking owners. **Example: one past PR, as reviewed by the new skill** (#5546, at the commit that was originally reviewed; blind, with no access to the real comments): ``` Verdict: Request changes -- The problem is real, but the fix swaps a hard error for a warn-and-continue fallback to FA2 ... It also adds a head-dim hook to 9 call sites, 7 of which can never fire. Must fix 1. torchtitan/tools/utils.py:95-104 -- a missing wheel on Hopper/Blackwell now means a warning plus a silent switch to a slower kernel with different numerics ... Smallest fix (~15 lines): ... raise a clear error that names the module to install. ``` The human review of that PR: "450 LoC PR for a safety check sounds insane" and "can we error out -- we don't want people to implicitly get bad perf". ## What changed **1. Rules** (`.claude/CLAUDE.md`, `.claude/rules/`): - Core principles rewritten: - start from the problem, not the patch; - minimal by default; - PyTorch-native and upstream first; - reuse, but don't bend shared code for one consumer; - keep core oblivious to features; - no BC promises, but protect numerics, HF loading, metric keys and main-path perf; - raise instead of warn; - hardware-agnostic. - Naming additions: overloaded terms, one name per concept, `_private`. - PR expectations: descriptions must convince a human; tests must earn their cost; one concern per PR. - `config.md` rewritten: - each component owns its `X.Config`; - select implementations by config type; - `X.Config | None` instead of `enable_*`; - no post-hoc config mutation; - few knobs; - validate in `__post_init__`. - `distributed.md`: spmd_types first, parallelism combinations, hidden D2H syncs, hardware. - New rules files: - `design.md`: structural rules distilled from past refactors. - `tests.md`: when to add tests, preferring extensions of existing coverage, placement, golden files. - `direction.md`: current migrations. This needs maintainers to keep it current. **2. `pr-review` skill** (`.claude/skills/pr-review/`): | Step | What it does | | --- | --- | | Context | Applicable rules, maintainer comments addressed or not, earlier bot findings, overlapping open PRs. | | Necessity/design gate | Is the problem real on main? Root cause vs symptom? Right layer, or upstream? Should torchtitan own this? Superseded? Smallest alternative? Value evidence? | | Deep review | A quick sweep of every hunk (scope, placement, new knobs and tests), then the checklist, split by lens for large PRs. | | Consolidate and fact-check | Dedupe by root cause and fix; drop BC, "add a warning", generic "add tests", lint and praise; verify must-fix items. | | Output | Verdict first, plain-words summary, a concrete before/after example, at most a few must-fix items, details collapsed, unverified claims labeled. | | Modes | Full review, "review again" (only the delta), "review my review", or answer a specific question first. | | Posting | Line-anchored findings as inline comments (with `suggestion` blocks for small fixes, at most ~10, posted only by the main agent after fact-check), then one formal review via `gh pr review` (`--approve` / `--request-changes` / `--comment`) with the verdict and one-line pointers. | **3. PR descriptions:** - `pr-description` skill and `.github/pull_request_template.md`: Why (with a simple example) -> What changed -> user-facing before/after -> numerics -> testing. - CONTRIBUTING.md updated to match. **4. `@claude` workflow** (`claude-code.yml`): - Always uses the skill. - Allows read-only `gh issue view` / `gh pr view` / `gh pr diff` / `gh pr list`, plus `gh pr review` and the action's inline-comment tool (it cannot approve). `gh api` stays blocked. - `effort=low|max` and `fable` comment keywords; default effort `high`. - 55-minute timeout. **5. Review routing:** - `CODEOWNERS`: - `*`: `tianyu-l` `fegin` `wwwjn` `shuhuayu` `acisseJZhong` `felipemello1`. - graph_trainer paths: core plus `SherlockNoMad` `aditvenk` `sanketpurandare`. - torchft paths: core plus `d4l3k`. - Every path has an owner, so a bot approval can never satisfy branch protection on its own. - `.github/area_reviewers.yml` and `workflows/area_reviewers.yml` request at most 3 area experts as non-blocking reviewers, based on which areas the changed files touch. The workflow runs on `pull_request_target`, reads only the file list through the API, and never checks out PR code. ## Alternatives considered - **Copy PyTorch's skill as-is.** Its "missing tests -> Request Changes" and BC section are exactly what produced noise here. - **PyTorch-style per-directory `REVIEW.md` files.** The existing glob-scoped `.claude/rules/` already do this, without more `.md` sprawl. - **Deterministic lint hooks** for `torch.cuda.*`, `isinstance(.., DTensor)` and `enable_*` fields. Every pattern already has hits on main (12, 15 and 7 files), so they would need allowlists. The skill checks them on the diff instead. - **Making area experts code owners.** That makes them blocking; auto-requesting reviews routes PRs without adding gates. ## Testing **Backtest.** The new skill reviewed 7 past PRs blind, each at the commit that was originally reviewed, and the output was compared with the real human review. The skill was then fixed for the misses, and the affected cases were re-run. | PR | Human review's main point | New skill | | --- | --- | --- | | #5546 | too big for a safety check; error out | Hit both | | #5153 | does this happen on main? don't violate the `nn.Module` contract | Hit; proposed the fix that eventually landed | | #4754 | workaround, not a fix; move the test | Hit the root cause (the same fix the author later proposed); missed the test move, now covered by the sweep | | #5463 | motivation first; `LocalCompileConfig` design | Hit the design and unused kwargs; motivation is a must-fix after the re-run | | #5183 | NCCL-specific knob in core; TODO; `<0` semantics | Hit | | #4474 | approve; DSv4 should fix the model/loss | Approve; partly raised the model point | | #4421 | approve; "how much e2e?" | Originally requested changes; approves with items after the re-run | None of the 10 reviews raised BC or asked for a warning. **Other checks:** - **Reviewer routing:** the area-reviewer logic was replayed on 1,429 merged PRs. Peak load is about 50 requests/month per person (graph trainer, PP, MoE). - **Workflow script:** dry-run with mocked GitHub objects on a real PR's file list. The author is excluded, existing reviewers are skipped, and a non-collaborator failure doesn't fail the run. - **YAML and lint:** all YAML parses, the inline JS passes `node --check`, and `pre-commit` passes. ## Known issues / follow-ups - Comment-triggered workflows run from `main`, so `claude-code.yml` and the skill only take effect after merge. Try `@claude review` on a real PR right after. - Not verified: whether the Claude GitHub App has write access. If it does, its approvals count toward the 1 required approval (but never as a code-owner approval), and its REQUEST_CHANGES blocks merging until it re-approves or someone dismisses it. If it doesn't, its reviews are advisory. The first real review will show which. - `direction.md` and `area_reviewers.yml` are only useful if they are kept current. - Not included: - PyTorch's time-budget hook (reviews that hit the 55-minute limit are lost); - auto-review on every push, which needs the PyTorch CI owners' hardened setup.
Summary
Fix optimizer checkpointing when only a subset of trainable parameters has initialized optimizer state.
init_optim_state()previously returned as soon asoptim.statewas non-empty. For optimizers that initialize state lazily, this left other trainable parameters without state and could produce an incomplete checkpoint.Motivation
A partially initialized optimizer state can occur when some trainable parameters have not received their first gradient at checkpoint time. Since
init_optim_state()is used before both saving and loading optimizer state, it needs to materialize missing entries consistently even when other entries already exist.Previously, checkpoint save could emit only the state that had already been initialized. During resume, a fresh optimizer could materialize a complete destination state, causing DCP to request keys that were absent from the checkpoint.
Observed case: DeepSeek-V4
This behavior was observed while checkpointing the current DeepSeek-V4 training path.
The upstream implementation has not connected the CSA indexer auxiliary loss yet. The code notes that it will be re-added as a carrier-injected auxiliary loss once the general auxiliary-loss mechanism is available. Without that loss, the indexer currently affects the language-modeling path only through discrete top-k indices, so its parameters do not receive gradients in this path.
Once the indexer loss is connected, the indexer parameters are expected to receive gradients and Adam/AdamW will create their optimizer state normally. The detached indexer inputs isolate its optimization from the main model; they do not prevent gradients from the auxiliary loss from reaching the indexer parameters.
The current DeepSeek-V4 path therefore serves as the case that exposed the partial-state save/load asymmetry, rather than as the reason for keeping permanently no-gradient parameters trainable.
The observed failure was:
Fix
This change only addresses optimizer-state materialization. It does not modify DeepSeek-V4 training behavior or add the indexer auxiliary loss.
Testing
Related: pytorch/pytorch#192202