Repository navigation
[module] Reject dtype changes to materialized buffers - #5153
Conversation
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
12d93d6 to
f49507e
Compare
|
@claude review this PR |
|
Claude finished @tianyu-l's task in 3m 30s —— View job Review: Keep Module buffers in their dtype across module casts
Overall: The diagnosis is right and the fix is small. Every floating buffer in core is a fixed-dtype cache or accumulator that Core change:
|
| old = before.get(name) | ||
| # Dtype-gated, not just a fast path: to_empty() keeps dtype, and | ||
| # restoring there would try to copy out of the meta original. | ||
| if old is not None and buf is not None and buf.dtype != old.dtype: |
There was a problem hiding this comment.
nn.Module.to(dtype), .half() and .bfloat16() convert floating buffers along with the parameters. Every floating buffer in torchtitan's models is a cache or an accumulator that is built in a fixed dtype on purpose (each _init_self_buffers rebuilds it in that dtype), so a module cast corrupts it:
Do such issues happen in torchtitan main branch today? If not I'm not sure if it's worth violating pytorch nn.Modules contract.
There was a problem hiding this comment.
thanks for your review and good q! it doesn't happen in training code on main today. i thought it was worth fixing because the current code requires an unnatural ordering of operations when casting models, as demonstrated in:
torchtitan/scripts/checkpoint_conversion/numerical_tests_kimi.py
Lines 195 to 200 in 3c36a77
if a downstream user instead calls init_states() first before to(), the buffers are corrupted and the model outputs garbage.
There was a problem hiding this comment.
I think my only concern is that it's violating pytorch nn.module convention so may cause other surprises to users. And for this reason, I recommend doing claude's recommendation for now.
In numerical_tests_qwen3_5.py, move model.half() before init_states. This is the only real instance, and it matches the Kimi scripts.
| """Override to preserve annotations across model.to_empty() in trainer.py""" | ||
| """Override to preserve annotations across model.to_empty() in trainer.py, | ||
| and to keep each own buffer's dtype across casts (parameters still cast).""" | ||
| before = dict(self._buffers) | ||
| with self._preserve_buffer_spmd_types(): |
There was a problem hiding this comment.
Could we just put this logic together with _preserve_buffer_spmd_types, maybe renaming to _preserve_buffer_types
There was a problem hiding this comment.
happy with claude's suggestion!
|
@claude review my reviews |
|
Claude finished @tianyu-l's task in 1m 58s —— View job Review of @tianyu-l's review comments
Comment 1: "Does this happen on main today? If not, is it worth violating the
|
| Callsite | Order | Affected on main? |
|---|---|---|
scripts/checkpoint_conversion/numerical_tests_kimi.py:169 |
cast, then init_states |
No. There is already a workaround comment: "Cast before init_states so the complex64 ComplexRoPE cache survives." |
scripts/checkpoint_conversion/numerical_tests_kimi_k3.py:169 |
cast, then init_states |
No |
scripts/checkpoint_conversion/numerical_tests_kimi_k3.py:224 |
cast, then load_state_dict |
Probably yes (cache rounded), but this is a script |
scripts/checkpoint_conversion/numerical_tests_qwen3_5.py:278 |
init_states, then .half() |
Yes. The MRoPE cache gets rounded to fp16 |
flux/model/autoencoder.py:455,471 |
ae.to(dtype) |
No. The AE has no buffers |
graph_trainer tests, add_moe_model skill script |
various | Test-only |
Casting before init_states is a complete fix wherever it applies. Every _init_self_buffers rebuilds its buffer in a hard-coded dtype: torch.polar gives complex64 in rope.py:236, .float() is used in rope.py:326, and dtype=torch.float32 is set for tokens_per_expert_E and expert_bias_E in moe.py. They don't follow the parameter dtype.
So on main this is a footgun in debug and numerics scripts, not a live production bug. The cost of the override is real, though:
- It contradicts the documented
nn.Module.tobehavior ("casts floating point parameters and buffers"). Every downstreamModulesubclass inherits this silently. - It overrides an explicit
fn.model._apply(lambda t: t.to(bf16))no longer does what it says. - It locks in whatever dtype the buffer currently has. After
load_state_dict(assign=True)from a bf16 checkpoint,model.float()no longer upcastsexpert_bias_E.
A lighter fix:
- In
numerical_tests_qwen3_5.py, movemodel.half()beforeinit_states. This is the only real instance, and it matches the Kimi scripts. - Optionally, make
numerical_tests_kimi_k3.py:224re-runinit_statesafter the cast, or keep the cast-then-init order. - If you want a guardrail, a CPU test can assert the documented pattern:
to_empty→.to(bf16)→init_statesleaves every buffer in its canonical dtype. That would reuse most oftest_model_buffer_dtypes.pywithout changingnn.Modulesemantics.
One addition to the comment: the PR's measurements (24.6 vs 2.3e-3 score spread) are correct for the scenario they test. But no main path reaches that scenario except the Qwen3.5 script, so the motivation in the description overstates the impact.
Comment 2: "Merge this into _preserve_buffer_spmd_types, renamed to _preserve_buffer_types?"
The readability goal makes sense, but merging as written would introduce a bug. _preserve_buffer_spmd_types is used in two places:
_apply(module.py:145)init_states, around_init_self_buffers(module.py:137-138)
The dtype logic restores the old tensor. It does self._buffers[name] = old.to(buf.device); it does not just cast the dtype back. Inside init_states, that means: whenever _init_self_buffers rebuilds a buffer in a different dtype from the stale one, the context manager would throw away the freshly computed buffer and put the stale one back. Today's workaround order (to_empty → .to(bf16) → init_states) triggers exactly this case, because the stale cache is bf16 and the fresh one is complex64/fp32. And init_states is the one place that is supposed to set the canonical dtype.
There are two smaller mismatches as well:
- The SPMD context manager walks
self.named_buffers()(recursive). The dtype logic only touchesself._buffers(own buffers) and relies on each childModuledoing its own. A merged version has to pick one scope. Recursive would also catch buffers on plainnn.Modulechildren, which changes the behavior again. - The restore has to run before the SPMD re-annotation in
finally, because that step checksnot spmd.has_local_type(buf)on the final tensor. The current nesting gets this right; a merged context manager has to keep that order.
If the dtype override stays (see comment 1), I'd suggest a separate _preserve_buffer_dtypes() context manager used only in _apply, nested inside the SPMD one:
def _apply(self, fn, recurse=True):
with self._preserve_buffer_spmd_types(), self._preserve_buffer_dtypes():
return super()._apply(fn, recurse=recurse)This keeps _apply as short as you were after, and leaves init_states free to set dtypes. If they must be merged, add a flag like _preserve_buffer_types(*, keep_dtype: bool) that is off in init_states. I find that harder to read than two context managers.
Summary
- Comment 1: Agree. Nothing on
mainoutside scripts and tests hits this, and the only live instance (numerical_tests_qwen3_5.py) is fixed by moving one line. I'd ask the author either to show a real production path that casts the model, or to switch to the script fix plus a guardrail test. - Comment 2: The goal is fine, but a straight merge would make
init_statesrevert freshly built buffers to the stale tensor. Use a separate context manager in_applyonly, or gate it with a flag.
I only read code for this; I didn't run any tests.
fegin
left a comment
There was a problem hiding this comment.
Enforcing a clear initialization order is not uncommon. I would prefer that over silently changing how the semantic of to().
I suggest adding a guard in _apply() that rejects casts which would violate the initialized buffer's dtype requirements. This requires some design, but overall it should solve the silently changing to() semantic and buffer becoming garbage issues.
cc638dc to
e0fce54
Compare
… 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.
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- The guard is the design @fegin asked for, but it breaks three in-repo callers that weren't updated. The opt-in classvar has no current use for leaving a buffer unpinned, and about half the added lines are tests that don't earn their cost.
What this PR does. Module._apply now wraps fn. If a materialized buffer whose name is in the class's _dtype_pinned_buffers would come back with a different dtype, it raises ValueError instead of silently casting it. Meta buffers are exempt, so the supported order is: meta build, then .to(dtype), then to_empty, then init_states, and init_states rebuilds the buffers in their fixed dtype. The scripts and graph_trainer tests that cast after init are reordered to match.
Example.
rope = ComplexRoPE.Config(dim=8, max_context_length=16).build() # cache: complex64
rope.to(torch.bfloat16)
# main: the cache silently becomes real bf16 and the imaginary part is lost
# PR: ValueError: Cannot convert ComplexRoPE.cache from complex64 to bfloat16; ...
with torch.device("meta"):
m = cfg.build()
m.to(torch.bfloat16); m.to_empty(device="cpu"); m.init_states()
# OK: parameters are bf16, cache is complex64Must fix
- Missed callsites. In
torchtitan/experiments/transformers_modeling_backend/.claude/skills/add_moe_model/scripts/,numerical_equivalence.py:464,505andnumerical_equivalence_pretrained.py:116all runto_empty, theninit_states, then load weights, thentitan_moe.to(dtype=torch.bfloat16). Every MoE built there has a router with the fp32tokens_per_expert_Ebuffer, which is now pinned, so all three scripts raise. Movetitan_moe.to(dtype=torch.bfloat16)to right after the meta build, beforeto_empty, as the PR does for the other scripts. torchtitan/models/base/module.py:52-- every materialized buffer in the repo is already pinned, so the opt-in set adds nothing. A new buffer that someone forgets to declare is silently cast again. Guard all own buffers instead (inline comment).tests/unit_tests/cpu/test_numerical_script_construction.py-- drop it, together with the_build_tt_modelextractions and thetests/utils.pymove that exist only to support it (inline comment).tests/unit_tests/cpu/models/base/test_buffer_dtype_guard.py-- trim to 3 cases and fold intotest_module.py(inline comment).
Should consider
torchtitan/quantization/nvfp4/linear.py:338and the other integer pins --.to(dtype)never casts integer buffers. If the opt-in set stays, remove these pins (inline comment).tests/unit_tests/cpu/models/muse_spark/test_navit_encoder.py:27-- this repeats the guard test for one more module; drop it (inline comment).
Questions
- @tianyu-l earlier preferred the script-only fix. @fegin requested this guard. Please confirm the guard is the direction, since it is now the documented contract of every torchtitan
Module.
Details
- Callsite audit. I checked
torchtitan/,scripts/andtests/for whole-module.to(dtype),.half(),.bfloat16(),.double(),.type()and_apply. RL and the trainer never cast a model. FSDP2 mixed precision does not touch buffers. The flux autoencoder has no buffers. In the GPU tests, the modules cast with.to(device=..., dtype=...)(QKVLinear, the deltanet test module, KDA,test_offset_rmsnorm) have no pinned buffers.test_varlen_attention.py:259calls.bfloat16()on a materialized llama3; that only passes if llama3's RoPE cache is complex, because.bfloat16()skips complex tensors. It would raise if the cache were a CosSin fp32 cache. id(tensor)keying inchecked_fnis sound. Every tensor passed tofnduring one_applywas alive when the snapshot was taken, so ids can't collide. Storing the tensor in the dict value would make that obvious at no cost.- Kimi script numerics.
vision_encoder.to(vision_dtype)now runs beforedcp.load. With an fp32 checkpoint, the ViT weights are rounded fp32 -> fp16 once instead of fp32 -> bf16 -> fp16. That is slightly more accurate. With a bf16 checkpoint the result is the same. - Size of the suggested version. The blanket guard keeps the same ~30 lines in
module.pyand drops 10 declarations (about -30 lines). Dropping the script test, its refactors and the utils move saves about -130 lines. Trimming the guard tests saves about -120 lines.
Not verified: I didn't run any tests (pytest needs approval in this job). The GPU graph_trainer tests that were reordered (test_trace_module.py now builds on meta and relies on init_states to initialize every parameter) still need a CI run. A maintainer still needs to review, because this touches core Module.
| Failed conversions may leave earlier parameters or children changed. | ||
| """ | ||
|
|
||
| _dtype_pinned_buffers: ClassVar[frozenset[str]] = frozenset() |
There was a problem hiding this comment.
This opt-in set doesn't do anything today. Every register_buffer under torchtitan/ is already listed in some module's _dtype_pinned_buffers: RoPE cache, three vision inv_freqs, instance_acc, tokens_per_expert_E, _cumulative_expert_counts_E, expert_bias_E (the Kimi K3 and Muse Spark subclasses inherit it), plus the integer ones. No in-repo module leaves a materialized buffer unpinned. The only unpinned buffer is ordinary in the new test.
The opt-in also fails in the wrong direction. The next RoPE or accumulator someone adds without the classvar gets silently cast again, which is the bug this PR is fixing.
Smaller option: delete the classvar. Have Module._apply reject any dtype change to a materialized buffer it owns (recurse=False, non-meta). That removes the ~10 declarations, the Parent._dtype_pinned_buffers | frozenset(...) boilerplate in three subclasses, the cast(type[Module], parent_cls) in nvfp4/experts.py, and test_subclass_extends_protected_names. If a buffer that should follow the parameter dtype shows up later, add the opt-out then.
There was a problem hiding this comment.
Addressed in 00860a9. Module._apply now rejects dtype changes to every materialized buffer it owns. Removed _dtype_pinned_buffers and all per-module declarations.
The failure modes favor blanket protection: a missing opt-in can silently corrupt state, whereas over-protection raises immediately and names the buffer. We can add a narrow exception when a concrete buffer needs to follow parameter precision. Meta buffers remain exempt.
| module, sharding, and checkpoint protocols. | ||
| """ | ||
|
|
||
| _dtype_pinned_buffers = frozenset({"_sr_seed", "_rht_sign_vector"}) |
There was a problem hiding this comment.
If the opt-in set stays, don't pin integer buffers. nn.Module.to(dtype), .half(), .bfloat16() and .double() only convert floating and complex tensors, so _sr_seed, _rht_sign_vector, tid2eid (deepseek_v4/moe.py:40) and required_bias_histogram_EB (common/moe/moe.py:409) are never touched by them. These pins only take effect for .type(torch.float16), and nothing in the repo calls that. Dropping them also removes the cast(type[Module], parent_cls) in nvfp4/experts.py:36-38 and test_integer_buffer_cast_semantics.
There was a problem hiding this comment.
Addressed in 00860a9 by removing all per-module pins, including the integer declarations and the classvar-related cast in nvfp4/experts.py. The blanket guard covers materialized buffers. Normal .to(dtype) calls still leave integer buffers unchanged. Removed the separate integer-cast test.
There was a problem hiding this comment.
I'd drop this test. With the guard in place, the cast order it checks can't regress silently: if a script casts after init_states, it now raises a ValueError naming the buffer and the fix the first time someone runs it. What the test costs:
- extracting
_build_tt_modelfrom two scripts (numerical_tests_kimi.py,numerical_tests_qwen3_5.py) only so the test can call it, - mocking
torch._dynamo.config.disablebecause the Qwen script sets it at import time, - moving
restore_aux_loss_registryintotests/utils.py, which has no other new consumer.
Keep the one-line reorders in the three scripts and revert the rest, roughly -130 lines. If it does stay, it belongs under tests/unit_tests/cpu/scripts/ next to test_convert_ema_to_hf.py.
There was a problem hiding this comment.
Addressed in 927b284. Removed test_numerical_script_construction.py and the _build_tt_model extractions from Kimi and Qwen. Restored the EMA test helper and tests/utils.py to upstream main. The cast reorders remain, including Kimi's separate vision precision before materialization.
Validation: 35 module tests pass, isolated Kimi and Qwen construction sequences pass, and all non-type-check hooks pass. Pyrefly reports the same 75 diagnostics as before this cleanup. The EMA tests fail during model import because the local PyTorch build lacks analyze_pipeline_activation_liveness.
There was a problem hiding this comment.
176 lines and 10 tests for a ~30-line guard. Please fold this into the existing tests/unit_tests/cpu/models/base/test_module.py and keep only the cases that protect the contract:
- A dtype cast through a parent (
nn.Sequential) raises and leaves the buffer object and its values unchanged. - The supported path works: meta build, then
.to(dtype), thento_empty, theninit_states, ending with parameters indtypeand buffers in their init dtype. - Device-only moves and
to_emptyon a materialized module still work.
The other tests check PyTorch or Python behavior, or document limitations rather than guard them:
- the mock call count,
_buffersaliasing done by poking internals,- frozenset union in subclasses,
recurse=False,- integer
.type(), - loading a checkpoint with
assign=True(documents a known limitation), - SPMD annotations (the existing
_preserve_buffer_spmd_typestests should already cover this; please confirm).
The complex-value case is already covered by the real ComplexRoPE test in test_rope.py.
There was a problem hiding this comment.
Consolidated in 00860a9. Removed test_buffer_dtype_guard.py and moved four focused cases into test_module.py: rejection through a parent, the supported meta construction sequence, device moves and materialized to_empty, and SPMD annotation preservation. Removed the declaration-specific and other extra cases.
I retained the SPMD case because I found no equivalent coverage in the existing test_module.py. The real RoPE test remains. All 35 tests in test_module.py pass locally.
| assert not freq.state_dict() | ||
|
|
||
|
|
||
| def test_rope_frequency_values_survive_rejected_cast(): |
There was a problem hiding this comment.
This repeats the guard test for one more module. The only module-specific part is the one-line classvar declaration, and if the classvar goes away (see the comment on module.py:52) there's nothing module-specific left. test_rope.py already covers one real buffer owner. Please drop this test.
There was a problem hiding this comment.
Addressed in 00860a9. Removed this duplicate test along with the module-specific declaration. The base guard tests and real RoPE test cover the blanket contract.
…5758) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why `scripts/checkpoint_conversion/numerical_tests_qwen3_5.py` builds MRoPE ids in `build_inputs` by calling `MultiModalCollator._build_mrope_positions` on a `types.SimpleNamespace(spatial_merge_size=merge_size)` and on `hf_in["input_ids"]`. The method reads `self.patch_order` first and raises `ValueError` unless it is `"block"`. The stand-in has no `patch_order`, so the call raises `AttributeError` before that check. The real collator default is `"block"`. The method docstring says `tokens` is `(num_tokens,)`. It does `tokens.unsqueeze(0)` and later returns `mrope_positions.squeeze(0)`, shape `(num_tokens, 3)`. `processor.apply_chat_template(..., return_tensors="pt")` yields `input_ids` of shape `(1, S)`. Unsqueeze makes that `(1, 1, S)`, and `batch_size, seq_len = tokens.shape` raises `ValueError: too many values to unpack (expected 2)`. `Qwen35Model.forward` does not index `positions` itself. It passes them to each layer. `MRoPE._reshape_cache` uses the 3-axis cache only when `positions.ndim == 2` and the last dimension is 3, i.e. `(num_tokens, 3)`. The collator already returns that rank after `squeeze(0)`, and `preprocess_inputs` forwards the same rank. A stored `(1, S, 3)` tensor would skip MRoPE and fall through to plain RoPE. The old script comment asked for `(1, S, 3)`; that comment does not match the index. The forward comment that still says `(batch, seq, 3)` is the same mismatch and is left alone. `vision_to_patches` returns `grid_thw` of shape `(3,)`. The collator indexes `grid_thw[image_index]` as one image's `(t, h, w)`, so `grid_thw.unsqueeze(0)` to `(num_images, 3)` stays. **Example.** ```python mrope_builder = types.SimpleNamespace(spatial_merge_size=2) MultiModalCollator._build_mrope_positions( mrope_builder, torch.zeros(1, 5, dtype=torch.long), # HF input_ids torch.zeros(1, 3), None, None, image_token_id=99, video_token_id=98, ) # AttributeError: 'types.SimpleNamespace' object has no attribute 'patch_order' ``` With `patch_order="block"` but the same `(1, 5)` tokens: ```text ValueError: too many values to unpack (expected 2) ``` `build_inputs` now squeezes the processor row to `(S,)` before the collator call, so positions come back `(S, 3)`. `tt_inputs` stores that row and `patches` of shape `(N, P)`. `run_tt` reads packed `(T, V)` logits. ## What changed - `build_inputs` sets `patch_order="block"`, squeezes `hf_in["input_ids"]` to `(S,)`, and calls `MultiModalCollator._build_mrope_positions` inline. The one-off helper is gone. - Stored tensors match the packed forward: tokens `(S,)`, patches `(N, P)`, `grid_thw` `(num_images, 3)`, positions `(S, 3)`. `patches.unsqueeze(0)` is gone. `grid_thw.unsqueeze(0)` stays. - `run_tt`'s reference SDPA takes packed `(T, H, K)` the way `FlexInnerAttention` does: `transpose(0, 1).unsqueeze(0)` to `(1, H, T, K)`, then the inverse. `transpose(1, 2)` was the old `(B, L, H, K)` layout. - Last-token logits are `logits[-1:].unsqueeze(0)`, shape `(1, 1, V)`, matching `run_hf`. - Deleted `tests/unit_tests/cpu/scripts/test_qwen35_numerical_mrope.py`. It grepped the script and skipped on import. `mm_collator.py` is unchanged. The `model.half()` / `to_empty` / `init_states` order in `run_tt` is unchanged. ## Alternatives considered - Keep a helper that accepts both `(S,)` and `(1, S)`. No. `build_inputs` is the only caller and it owns the processor row. - Leave `run_tt` on batched `(1, S)` tokens and `(1, N, P)` patches. No. The vision encoder checks `pixel_values.shape[0]` against the patch grid, and the text forward is packed `(num_tokens,)`. - Leave `_SDPA` on `transpose(1, 2)`. No. That swaps heads with `head_dim` once Q/K/V are `(T, H, K)`. GQA then sees different query and key embedding sizes. - Make `_build_mrope_positions` treat a missing `patch_order` as `"block"`. No. The method already requires `"block"`. #5728 owns `mm_collator.py`. - Unsqueeze positions to `(1, S, 3)`. No. Rank 3 is not the MRoPE path in `MRoPE._reshape_cache`. - Construct a real `MultiModalCollator`. No. That needs a dataset context and a tokenizer. ## User-facing changes | Before | After | | --- | --- | | `build_inputs` raises `AttributeError` because the MRoPE stand-in has no `patch_order` | The stand-in sets `patch_order="block"` | | Processor `input_ids` `(1, S)` make `_build_mrope_positions` raise `ValueError` on the shape unpack | The call gets a 1-D row. Stored positions are `(S, 3)` | | `run_tt` passes tokens `(1, S)` and patches `(1, N, P)` into a packed forward | tokens `(S,)`, patches `(N, P)` | | `logits[:, -1:, :]` assumes 3-D logits | `logits[-1:].unsqueeze(0)` matches HF `(1, 1, V)` | | No config or CLI flag | No config or CLI flag | ## Numerics Not run. The script needs a downloaded Qwen3.5 checkpoint and a GPU. This does not change a training step. It changes the script's forward shapes so that check can run. ## Testing `py_compile` of `scripts/checkpoint_conversion/numerical_tests_qwen3_5.py` succeeded with `/opt/homebrew/anaconda3/bin/python`. The script was not executed. There is no local checkpoint and no GPU. The CPU test file was removed. It AST-walked the source, asserted `AttributeError` for a missing attribute, and turned import errors into skips. An existing `tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_mrope_positions.py` already locks the `(num_tokens, 3)` contract. This machine still cannot collect that file (`spmd_types` has no `rules`). ## Known issues / follow-ups #5153 is open and edits this script only around model construction: it moves `model.half()` before `to_empty` / `init_states` and factors `_build_tt_model`. This PR does not touch those lines. The SDPA and logit-index edits are later in `run_tt`. #5728 edits `mm_collator.py`. This PR does not. `Qwen35Model.forward` still comments that multimodal `positions` are `(batch, seq, 3)`. `MRoPE._reshape_cache` and `preprocess_inputs` use `(num_tokens, 3)`. Not changed here. Open PRs already edit `model.py`.
1567691 to
be35989
Compare
Let buffer owners opt in with names-only _dtype_pinned_buffers sets. Reject conversions that change a materialized pinned buffer's current dtype before installing the result, while preserving standard behavior for unmarked buffers and meta placeholders. Set script and graph-test precision before materialization and buffer initialization. Cover guard semantics and script precision explicitly.
Protect each Module's own materialized buffers without opt-in declarations. A missing declaration can silently corrupt a new cache or accumulator. An unnecessary rejection fails immediately and identifies the affected buffer. Keep meta casts available before materialization and initialization. Remove per-module declarations and redundant declaration tests. Fold the core guard tests into test_module.py and retain SPMD annotation coverage.
be35989 to
00860a9
Compare
|
Addressed the three missed cast call sites from the latest review in 2d98661: both branches in Rebased onto upstream main and switched to blanket buffer protection in 00860a9. The rationale and current validation results are in the updated PR description. All PR commits now use The separate suggestion to remove script construction tests and their supporting refactors remains outstanding. This update does not claim to address that thread. |
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The blanket guard is the explicit-error design @fegin asked for, and all four must-fix items from the last automated review are resolved at HEAD. I found no remaining in-repo caller that casts a materialized torchtitan Module's buffers. A maintainer still needs to review, because this changes the contract of every core Module, and @fegin's change request is still open.
What this PR does. Module._apply wraps fn. If a non-meta buffer that the module owns comes back from fn with a different dtype, it raises ValueError before PyTorch installs the result. Meta buffers are exempt. The supported order is: build on meta, cast, to_empty, then init_states, which rebuilds buffers in their fixed dtypes. Scripts and tests that cast after init were reordered to match.
Example.
rope = CosSinRoPE.Config(dim=8, max_context_length=16).build() # cache: fp32
rope.to(torch.bfloat16)
# main: the cache silently becomes bf16
# PR: ValueError: Cannot convert CosSinRoPE.cache from float32 to bfloat16; ...
with torch.device("meta"):
m = cfg.build()
m.to(torch.bfloat16); m.to_empty(device="cpu"); m.init_states()
# OK: parameters are bf16, buffers are in their init dtypesResolved since the last review
- The
add_moe_modelscripts are reordered, in all three places. - The opt-in classvar and all per-module pins are removed; the guard is now blanket.
- The script construction test, the
_build_tt_modelextractions, and thetests/utils.pymove are reverted. - The guard tests are folded into
test_module.py, and the navit test is dropped.
Must fix
- PR description. It doesn't follow
.github/pull_request_template.md. There is no "Summary (human-written)" section. The "Why" has no before/after example (the one above would do). Half the body narrates review history ("Removed the script construction tests...", "No per-module declarations remain"), which reviewers of the final diff don't need. Please restructure it into Summary / Why / What changed / Numerics / Testing. torchtitan/models/base/module.py:46-51and:205: trim the docstring to the contract. The error message still says "pinned", a term from the removed opt-in (inline comment).tests/unit_tests/cpu/models/base/test_module.py:527-528: remove the dead CUDA branch from the CPU test (inline comment).
Should consider
tests/unit_tests/cpu/models/base/test_module.py:541-544: these assertions can't fail. Keep only theto_emptycheck (inline comment).- Script numerics change. In
numerical_tests_qwen3_5.pythe MRoPE cache is now fp32 instead of fp16. Innumerical_tests_kimi.pythe visioninv_freqstays fp32 instead ofvision_dtype, and the ViT weights are rounded once instead of twice. Both changes should move the results closer to HF. These scripts exist to compare against HF, so one before/after line from each in the description would show the reorder had the expected effect.
Questions
- @tianyu-l: you earlier preferred the script-only fix because of the
nn.Moduleconvention. The guard now raises instead of silently changingto()semantics. Are you OK with this as the documentedModulecontract?
Details
- Callsite audit (HEAD). I searched
torchtitan/,scripts/,tests/,torchtitan_recipes/and the hidden.claude/skills/scripts for whole-module.half(),.bfloat16(),.double(),.float(),.to(dtype),.type()and_apply. The remaining casts on materialized modules are safe:test_varlen_attention.py:436,test_rope.py:323andtest_deepseek_v4_compressor.py:25cast models whose only floating buffer is the complexComplexRoPEcache..bfloat16()and.double()skip complex tensors.test_linear.py:346,test_hi_mid_lo_linear.py, and the GPU muse_sparkRMSNormtest cast modules that have no buffers.numerical_tests_kimi_k3.py:239casts the HF model.- The trainer and RL never cast a model, and FSDP2 mixed precision doesn't go through
_apply.
- Guard mechanics. Keying on
id(tensor)is safe: each tensor passed tofnis alive while its id is looked up. Children are processed first, and each torchtitan child checks its own buffers. Plainnn.Modulechildren keep PyTorch behavior. Parameters are cast before buffers innn.Module._apply, so a rejected cast leaves the module's parameters converted. The docstring says so. test_trace_module.create_modelnow uses the trainer's meta ->to_empty->init_statespath.refandtestare synced throughload_state_dict, and non-persistent buffers are rebuilt deterministically, so the bitwise tests should be unaffected.remove_duplicate=Falseinnamed_buffershas no effect, because an aliased buffer maps to one id either way. It's harmless.
Not verified: I couldn't run pytest in this job. The reordered GPU graph_trainer tests and the RL generator path still need CI; ciflow/rl and ciflow/fake-pg are awaiting workflow approval. In the RL path, vLLM attention layers mixed into Module now guard _k_scale and W_UK_T/W_UV. I found no dtype cast on them, but this needs that CI run.
| All materialized buffers owned by this module reject dtype changes. | ||
| This default prevents silent corruption when a new buffer is added. | ||
| An unsupported cast fails immediately instead of silently changing state. | ||
| Cast meta models before ``to_empty`` and ``init_states``. The guard preserves | ||
| the current dtype, not a canonical dtype after direct assignment or loading. | ||
| Failed conversions may leave earlier parameters or children changed. |
There was a problem hiding this comment.
Lines 47-48 give the design rationale ("This default prevents silent corruption when a new buffer is added..."). That reasoning belongs in the PR, not in the class contract. The docstring should only say what a subclass author needs to know. Suggested wording:
| All materialized buffers owned by this module reject dtype changes. | |
| This default prevents silent corruption when a new buffer is added. | |
| An unsupported cast fails immediately instead of silently changing state. | |
| Cast meta models before ``to_empty`` and ``init_states``. The guard preserves | |
| the current dtype, not a canonical dtype after direct assignment or loading. | |
| Failed conversions may leave earlier parameters or children changed. | |
| Materialized buffers owned by this module reject dtype changes. Cast a | |
| meta-built model before ``to_empty`` and ``init_states``, which rebuild | |
| buffers in their intended dtypes. The guard keeps a buffer's current dtype; | |
| it does not restore a canonical dtype after direct assignment or loading. | |
| A failed cast may leave earlier parameters or children converted. |
The error message at line 205 still says "this buffer's dtype is pinned". That term comes from the removed _dtype_pinned_buffers opt-in, and no buffer is "pinned" anymore, so it now sends readers looking for a declaration that doesn't exist. Something like "torchtitan Module buffers keep their dtype" would be accurate.
There was a problem hiding this comment.
Addressed in 87dc20f. The class docstring now states the buffer contract and supported initialization order. Removed the design rationale and replaced the obsolete "pinned" wording in the error message with "torchtitan Module buffers keep their dtype." All 35 module tests pass.
| if torch.cuda.is_available(): | ||
| m.cuda().cpu() |
There was a problem hiding this comment.
This is in the CPU suite, which never has CUDA, so this branch never runs (.claude/rules/tests.md: no GPU-only code in CPU suites). It also adds a torch.cuda.* call. The guard's device-move behavior doesn't depend on the device type, and .cpu() / to("meta") already exercise it. Drop it:
| if torch.cuda.is_available(): | |
| m.cuda().cpu() |
There was a problem hiding this comment.
Addressed in 87dc20f. Removed the CUDA branch from the CPU suite. The test retains CPU moves, conversion to meta, and materialized to_empty coverage. All 35 module tests pass.
| self.assertTrue(spmd.has_local_type(m.buf)) | ||
| with self.assertRaises(ValueError): | ||
| m.half() | ||
| self.assertTrue(spmd.has_local_type(m.buf)) |
There was a problem hiding this comment.
The to_empty assertion earns its place, because this PR rewrote _apply and the with _preserve_buffer_spmd_types() wrapping has to survive. These last lines can't fail, though:
init_statesgoes through_preserve_buffer_spmd_typesdirectly. It doesn't use_apply, and this PR doesn't change it.- After
half()raises, the buffer was never replaced (checked_fnraises beforenn.Module._applyassigns it), so the annotation is trivially intact.
Suggest keeping only the to_empty check.
There was a problem hiding this comment.
Addressed in 87dc20f. Kept the to_empty annotation check and removed the init_states and rejected-cast checks. All 35 module tests pass.
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. 87dc20f fixes both code items from the last review, and it adds no new problems. The PR description is still the original one. @fegin has approved, which resolves the earlier change request. This PR changes the contract of every core Module, so a maintainer still needs to review it.
What this PR does. Module._apply raises ValueError when a non-meta buffer that the module owns would come back from fn with a different dtype. Meta buffers are exempt. The supported order is: build on meta, cast, to_empty, then init_states. Scripts and tests that cast after init are reordered to match.
Example.
rope = CosSinRoPE.Config(dim=8, max_context_length=16).build() # cache: fp32
rope.to(torch.bfloat16)
# main: the cache silently becomes bf16
# PR: ValueError: Cannot convert CosSinRoPE.cache from float32 to bfloat16. torchtitan Module buffers keep their dtype. ...Resolved since the last review
module.py:46-50: the docstring now states only the contract, and the error message no longer says "pinned".test_module.py: the dead CUDA branch is gone.test_module.py: the assertions that could not fail are gone; only theto_emptySPMD check remains.
Must fix (still open)
- PR description. It still doesn't follow
.github/pull_request_template.md. It has no "Summary (human-written)" section and no before/after example; the one above would do. Several paragraphs describe review history that someone reading the final diff doesn't need: "No per-module_dtype_pinned_buffersdeclarations remain", "Removed the script construction tests...", "The three previously missed MoE casts...", "The EMA test helper andtests/utils.pymatch upstream main". Please restructure it into Summary / Why / What changed / Numerics / Testing.
Should consider (still open)
- Script numerics. Two scripts now start from different values. In
numerical_tests_qwen3_5.pythe MRoPE cache stays fp32 instead of fp16. Innumerical_tests_kimi.pythe visioninv_freqstays fp32, and the ViT weights are rounded once instead of twice. One before/after line per script would show the reorder moved results closer to HF.
Details
- The failing "RL Integration Tests" job doesn't come from this PR. The failure is
Loss mismatch at step 1: actual=-0.003829, expected=-0.003584inscripts/rl/loss_compare.py, and training itself finished. The guard either raises or returnsfn(tensor)unchanged, so it cannot change numerics. The PR also touches no RL code. A raise would have stopped training, and the log says it finished. RL H100 Integration, RL GPU and CPU unit tests, GraphTrainer 8 GPU, the Transformers backend, and the GPU unit tests all pass. I couldn't check whethermainfails the same way. - No new callers of whole-module casts have appeared since the last callsite audit. The head is
87dc20f, which changes only the docstring, the error message and the tests.
Not verified: I couldn't confirm against recent main runs that the RL A10G loss mismatch is pre-existing. A maintainer should check it before merging.
Whole-model casts can discard complex RoPE components or reduce cache and MoE accumulator precision. Reject buffer dtype changes instead of silently overriding the requested cast.
Module._applynow protects every materialized buffer owned by that module (recurse=False, non-meta). It checks each conversion result before PyTorch installs it. The conversion runs once. Each torchtitanModulechild protects its own buffers. Plainnn.Modulechildren retain standard PyTorch behavior.Blanket protection avoids a silent failure when a new module omits an opt-in declaration. An unnecessary rejection fails immediately and identifies the buffer. We can add a narrow exception when a buffer that should follow parameter precision has a concrete use case. No per-module
_dtype_pinned_buffersdeclarations remain.Meta placeholders can change dtype. The supported order is meta construction, then the dtype cast, then
to_empty(), theninit_states(). Initialization rebuilds buffers in their intended dtypes. The numerical scripts and affected graph-trainer tests use this order. Kimi also sets its separate vision precision before materialization and checkpoint loading. The three previously missed MoE casts in the twoadd_moe_modelnumerical scripts now follow this order.Removed the script construction tests and the helper extractions that supported them. Kimi and Qwen build their models directly in
run_tt. The script cast reorders remain. The EMA test helper andtests/utils.pymatch upstream main.The guard preserves the current dtype, including after checkpoint assignment. It does not repair an incorrect dtype or validate initialization. Failed conversions can leave earlier parameters or children changed. Functions that mutate inputs in place are outside the guard's contract. Device moves and dtype-preserving conversions remain supported. SPMD annotation preservation remains separate.
Validation on the rebased branch:
tests/unit_tests/cpu/models/base/test_module.py: 35 passed, including four consolidated buffer guard tests.ComplexRoPEandCosSinRoPE: rejected casts preserve cache identity and values.torch.distributed.pipelining.analyze_pipeline_activation_liveness.Moduleguard and small buffer-owning probe modules.