Skip to content

[module] Reject dtype changes to materialized buffers - #5153

Merged
tianyu-l merged 5 commits into
pytorch:mainfrom
alfredclwong:rope-keep-cache-dtype-on-cast
Nov 6, 2026
Merged

tianyu-l merged 5 commits into
pytorch:mainfrom
alfredclwong:rope-keep-cache-dtype-on-cast

Conversation

@alfredclwong

@alfredclwong alfredclwong commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

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._apply now 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 torchtitan Module child protects its own buffers. Plain nn.Module children 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_buffers declarations remain.

Meta placeholders can change dtype. The supported order is meta construction, then the dtype cast, then to_empty(), then init_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 two add_moe_model numerical 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 and tests/utils.py match 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.
  • Direct CPU checks of real ComplexRoPE and CosSinRoPE: rejected casts preserve cache identity and values.
  • Non-type-check pre-commit hooks: passed.
  • Pyrefly with the isolated Python environment: the same 75 diagnostics before and after the blanket change.
  • The broader RoPE suite and EMA export tests cannot complete locally because this PyTorch build lacks torch.distributed.pipelining.analyze_pipeline_activation_liveness.
  • Isolated execution of the Kimi and Qwen construction sequences passes with the real Module guard and small buffer-owning probe modules.
  • CUDA tests and full checkpoint-backed numerical comparisons were not run.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

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.

@alfredclwong
alfredclwong marked this pull request as draft October 8, 2026 15:06
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 8, 2026
@alfredclwong alfredclwong changed the title [rope] Keep the RoPE cache in its built dtype across module casts [module] Keep dtype-pinned buffers in their dtype across module casts Oct 8, 2026
@alfredclwong alfredclwong changed the title [module] Keep dtype-pinned buffers in their dtype across module casts [module] Keep Module buffers in their dtype across module casts Oct 8, 2026
@alfredclwong
alfredclwong force-pushed the rope-keep-cache-dtype-on-cast branch from 12d93d6 to f49507e Compare October 9, 2026 11:57
@alfredclwong
alfredclwong marked this pull request as ready for review October 9, 2026 14:16
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 9, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 30s —— View job


Review: Keep Module buffers in their dtype across module casts

  • Gather context (diff, Module._apply, callsites)
  • Review the core change in torchtitan/protocols/module.py
  • Review the tests
  • Run the affected CPU tests: not done. This job's sandbox needs approval for pytest, so I reviewed by reading the code only. The author reports 75 passed, 33 subtests passed locally.
  • Post review

Overall: The diagnosis is right and the fix is small. Every floating buffer in core is a fixed-dtype cache or accumulator that _init_self_buffers rebuilds in that dtype anyway, so pinning buffer dtype in Module._apply matches the init_states contract. I couldn't find a correctness bug in the override. The comments below are mostly about test coverage, semantics, and the PR description.


Core change: torchtitan/protocols/module.py:141-153

I checked these properties and they hold:

  • Children are handled. super()._apply(fn, recurse=True) processes children first, and each torchtitan Module child restores its own _buffers. Buffers on a plain nn.Module still get cast, and the zoo test is designed to catch those.
  • Same-device restores alias the original. old.to(buf.device) returns old itself when the device is unchanged, so SPMD annotations survive without a copy. When the device changes, _preserve_buffer_spmd_types re-applies the annotations to the new tensor. Buffers from spmd_distribute_tensor are plain local tensors, not DTensors, so .to(device) is safe.
  • The dtype gate is required. It is what makes to_empty() and device-only moves work, and the inline comment explains this well.
  • Integer and None buffers are untouched. That covers _sr_seed (int64), _rht_sign_vector (int8), tid2eid and the histograms. nn.Module._apply never casts them, and the buf is not None check handles empty slots.
  • Activations keep their dtype. ComplexRoPE and CosSinRoPE both compute with query.float() and cast back with type_as. The bf16 scores + fp32 expert_bias_E add at moe.py:212/368 promotes to fp32, which is what FSDP2 MP training already does and matches HF's fp32 e_score_correction_bias. The .double() tests (test_deepseek_v4_compressor.py, test_deepseek_v4_dsa.py) are unaffected because RoPE already downcasts fp64 queries to fp32.

Comments:

  1. (Semantics) This keeps the dtype the buffer had before the cast, which is not always its canonical dtype. After load_state_dict(..., assign=True) from a checkpoint that stores e_score_correction_bias / expert_bias_E in bf16, the buffer becomes bf16. A later model.float() / .to(torch.float32) now leaves it in bf16, where before it was upcast. This is an edge case, but the docstring should say "keeps the buffer's current dtype" so nobody reads it as "restores the canonical dtype". The real canonical-dtype guarantee comes from init_states.

  2. (Semantics) The change can silently override an explicit request. model._apply(lambda t: t.to(torch.bfloat16)) in test_graph_pp_passes.py:180 asks for every tensor, buffers included, in bf16, and the buffers now quietly stay fp32. CLAUDE.md asks for a warning "when a code path silently skips user configuration". A warning on every model.to(bf16) would be noisy, so I'd treat this as an intended contract rather than skipped config. It should still be stated in the Module class docstring, not only in _apply, because downstream subclasses inherit it. Agreed that an opt-out can wait until someone needs one.

  3. (Minor perf) .to(device, dtype) copies each buffer twice. For a cross-device cast like model.to("cuda", torch.bfloat16), nn.Module._apply first sends a cast copy to the target device, the override throws it away, and then copies old across again. non_blocking and memory_format from the original call are also dropped on the restore path. The buffers are small (RoPE cache up to max_seq_len x dim, per-expert vectors), so this is acceptable. A short comment would help.

  4. (Nit) Docstring wording. "keep each own buffer's dtype" reads awkwardly. Suggested: "...and to keep this module's own buffers in their current dtype across casts; parameters are still cast."


Tests

  1. test_model_buffer_dtypes.py silently skips Flux. It filters on flavor.startswith("debug"), but Flux's debug flavor is "flux-debug" (torchtitan/models/flux/flavors.py:555). So the claim "every debug* flavour of every package" doesn't cover Flux. The test would also pass vacuously if MODEL_FLAVORS were renamed, because of getattr(package, "MODEL_FLAVORS", {}). Suggestions:

    • match "debug" in flavor, or list the expected packages explicitly, and
    • assert that the number of tested (package, flavor) pairs is non-zero, or at least the expected count, so a rename can't turn the test into a no-op.

    Fix this →

  2. The zoo test checks dtypes only. That is enough to cover the regression, because values are already covered by test_cast_through_parent_keeps_buffer. One cheap extra check on a real model would close the loop on the complex case: assert torch.is_complex(rope.cache) after .to(torch.bfloat16) on a CPU-materialized llama3 debug model.

  3. The new tests/utils.py import is now global. The import of torchtitan.models.common.aux_loss used to be lazy inside the helper and is now at module level. Every test that imports tests.utils (the hashing helpers) will now import the model package. That's probably fine, but keeping the import inside the function would match the old lazy behavior.


Callsites / PR description

  1. Unverified GPU and script callers. The list in the description is honest about which callers weren't run. test_sac_peak_memory.py checks peak-memory bounds, and now holds an fp32 RoPE cache instead of a bf16 one; with debug sizes the difference should be a few hundred KB at most. It, test_graph_pp_passes.py, and test_trace_module.py need a GPU CI pass before merge.

  2. Kimi script (numerical_tests_kimi.py:169). Removing the comment is right. Since the order no longer matters, consider also moving model.to(dtype) after init_states, to match the other numerical scripts. Optional.

  3. Qwen3.5 script. After model.half() the MRoPE cache now stays fp32 and the numbers may shift, as the description says. Since this is the expected direction (closer to HF, which also keeps inv_freq in fp32), a before/after line in the PR would be useful evidence.


Verdict: The approach looks good. The changes I'd want before merge are #5 (the zoo test silently skipping Flux and possibly passing vacuously) and a GPU CI run of the graph_trainer tests in #8. The rest are docstring and nit-level.

Comment thread torchtitan/protocols/module.py Outdated
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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

with torch.device("meta"):
model = model_config.build()
model.to_empty(device="cpu")
# Cast before init_states so the complex64 ComplexRoPE cache survives.
model.to(dtype)
model.init_states(buffer_device=torch.device("cpu"))

if a downstream user instead calls init_states() first before to(), the buffers are corrupted and the model outputs garbage.

@tianyu-l tianyu-l Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we just put this logic together with _preserve_buffer_spmd_types, maybe renaming to _preserve_buffer_types

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

happy with claude's suggestion!

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my reviews

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 58s —— View job


Review of @tianyu-l's review comments

  • Read Module._apply / _preserve_buffer_spmd_types on this branch
  • Find every place on main that casts a whole model
  • Check what would happen if the dtype logic moved into _preserve_buffer_spmd_types
  • Post findings

Comment 1: "Does this happen on main today? If not, is it worth violating the nn.Module contract?"

I agree with this, and I think it should block the PR in its current form.

I searched torchtitan/ and scripts/ (excluding tests) for whole-model casts (.to(dtype), .half(), .bfloat16(), _apply(...)). No training or inference path casts a model that has floating buffers. The trainer leaves parameters in fp32 and gets bf16 compute from FSDP2's MixedPrecisionPolicy, which never touches buffers. The callers I found are all offline scripts or tests:

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.to behavior ("casts floating point parameters and buffers"). Every downstream Module subclass 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 upcasts expert_bias_E.

A lighter fix:

  1. In numerical_tests_qwen3_5.py, move model.half() before init_states. This is the only real instance, and it matches the Kimi scripts.
  2. Optionally, make numerical_tests_kimi_k3.py:224 re-run init_states after the cast, or keep the cast-then-init order.
  3. If you want a guardrail, a CPU test can assert the documented pattern: to_empty → .to(bf16) → init_states leaves every buffer in its canonical dtype. That would reuse most of test_model_buffer_dtypes.py without changing nn.Module semantics.

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.

Fix this →


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:

  1. _apply (module.py:145)
  2. 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 touches self._buffers (own buffers) and relies on each child Module doing its own. A merged version has to pick one scope. Recursive would also catch buffers on plain nn.Module children, which changes the behavior again.
  • The restore has to run before the SPMD re-annotation in finally, because that step checks not 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 main outside 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_states revert freshly built buffers to the stale tensor. Use a separate context manager in _apply only, or gate it with a flag.

I only read code for this; I didn't run any tests.

@fegin fegin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@alfredclwong alfredclwong changed the title [module] Keep Module buffers in their dtype across module casts [module] Reject casts that violate buffer dtype requirements Oct 14, 2026
@alfredclwong
alfredclwong force-pushed the rope-keep-cache-dtype-on-cast branch from cc638dc to e0fce54 Compare October 14, 2026 05:30
@alfredclwong alfredclwong changed the title [module] Reject casts that violate buffer dtype requirements [scripts] Set model precision before buffer initialization Oct 14, 2026
tianyu-l added a commit that referenced this pull request Oct 29, 2026
… 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.
@tianyu-l

tianyu-l commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 19s —— View job


Request changes: the guard breaks three add_moe_model skill scripts that weren't updated, the opt-in classvar has no current use, and the tests should be trimmed. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 complex64

Must fix

  1. Missed callsites. In torchtitan/experiments/transformers_modeling_backend/.claude/skills/add_moe_model/scripts/, numerical_equivalence.py:464,505 and numerical_equivalence_pretrained.py:116 all run to_empty, then init_states, then load weights, then titan_moe.to(dtype=torch.bfloat16). Every MoE built there has a router with the fp32 tokens_per_expert_E buffer, which is now pinned, so all three scripts raise. Move titan_moe.to(dtype=torch.bfloat16) to right after the meta build, before to_empty, as the PR does for the other scripts.
  2. 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).
  3. tests/unit_tests/cpu/test_numerical_script_construction.py -- drop it, together with the _build_tt_model extractions and the tests/utils.py move that exist only to support it (inline comment).
  4. tests/unit_tests/cpu/models/base/test_buffer_dtype_guard.py -- trim to 3 cases and fold into test_module.py (inline comment).

Should consider

  • torchtitan/quantization/nvfp4/linear.py:338 and 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/ and tests/ 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:259 calls .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 in checked_fn is sound. Every tensor passed to fn during one _apply was 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 before dcp.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.py and 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.

Comment thread torchtitan/models/base/module.py Outdated
Failed conversions may leave earlier parameters or children changed.
"""

_dtype_pinned_buffers: ClassVar[frozenset[str]] = frozenset()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/quantization/nvfp4/linear.py Outdated
module, sharding, and checkpoint protocols.
"""

_dtype_pinned_buffers = frozenset({"_sr_seed", "_rht_sign_vector"})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_model from two scripts (numerical_tests_kimi.py, numerical_tests_qwen3_5.py) only so the test can call it,
  • mocking torch._dynamo.config.disable because the Qwen script sets it at import time,
  • moving restore_aux_loss_registry into tests/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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. A dtype cast through a parent (nn.Sequential) raises and leaves the buffer object and its values unchanged.
  2. The supported path works: meta build, then .to(dtype), then to_empty, then init_states, ending with parameters in dtype and buffers in their init dtype.
  3. Device-only moves and to_empty on a materialized module still work.

The other tests check PyTorch or Python behavior, or document limitations rather than guard them:

  • the mock call count,
  • _buffers aliasing 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_types tests should already cover this; please confirm).

The complex-value case is already covered by the real ComplexRoPE test in test_rope.py.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

tianyu-l pushed a commit that referenced this pull request Nov 3, 2026
…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`.
@alfredclwong
alfredclwong force-pushed the rope-keep-cache-dtype-on-cast branch from 1567691 to be35989 Compare November 5, 2026 21:13
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.
@alfredclwong
alfredclwong force-pushed the rope-keep-cache-dtype-on-cast branch from be35989 to 00860a9 Compare November 5, 2026 22:06
@alfredclwong alfredclwong changed the title [module] Reject dtype changes to pinned buffers [module] Reject dtype changes to materialized buffers Nov 5, 2026
@alfredclwong

Copy link
Copy Markdown
Contributor Author

Addressed the three missed cast call sites from the latest review in 2d98661: both branches in numerical_equivalence.py and the pretrained path now cast immediately after meta construction, before to_empty() and init_states(). Weight loading remains after initialization, with .eval() after loading.

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 alfredclwong as author and committer.

The separate suggestion to remove script construction tests and their supporting refactors remains outstanding. This update does not claim to address that thread.

@tianyu-l

tianyu-l commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 3s —— View job


Approve, with three small items to fix before merging (PR description, docstring/error wording, a dead CUDA branch in a CPU test). See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 dtypes

Resolved since the last review

  • The add_moe_model scripts 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_model extractions, and the tests/utils.py move are reverted.
  • The guard tests are folded into test_module.py, and the navit test is dropped.

Must fix

  1. 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.
  2. torchtitan/models/base/module.py:46-51 and :205: trim the docstring to the contract. The error message still says "pinned", a term from the removed opt-in (inline comment).
  3. 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 the to_empty check (inline comment).
  • Script numerics change. In numerical_tests_qwen3_5.py the MRoPE cache is now fp32 instead of fp16. In numerical_tests_kimi.py the vision inv_freq stays fp32 instead of vision_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.Module convention. The guard now raises instead of silently changing to() semantics. Are you OK with this as the documented Module contract?
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:323 and test_deepseek_v4_compressor.py:25 cast models whose only floating buffer is the complex ComplexRoPE cache. .bfloat16() and .double() skip complex tensors.
    • test_linear.py:346, test_hi_mid_lo_linear.py, and the GPU muse_spark RMSNorm test cast modules that have no buffers.
    • numerical_tests_kimi_k3.py:239 casts 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 to fn is alive while its id is looked up. Children are processed first, and each torchtitan child checks its own buffers. Plain nn.Module children keep PyTorch behavior. Parameters are cast before buffers in nn.Module._apply, so a rejected cast leaves the module's parameters converted. The docstring says so.
  • test_trace_module.create_model now uses the trainer's meta -> to_empty -> init_states path. ref and test are synced through load_state_dict, and non-persistent buffers are rebuilt deterministically, so the bitwise tests should be unaffected.
  • remove_duplicate=False in named_buffers has 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.

Comment thread torchtitan/models/base/module.py Outdated
Comment on lines +46 to +51
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +527 to +528
if torch.cuda.is_available():
m.cuda().cpu()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
if torch.cuda.is_available():
m.cuda().cpu()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +541 to +544
self.assertTrue(spmd.has_local_type(m.buf))
with self.assertRaises(ValueError):
m.half()
self.assertTrue(spmd.has_local_type(m.buf))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_states goes through _preserve_buffer_spmd_types directly. It doesn't use _apply, and this PR doesn't change it.
  • After half() raises, the buffer was never replaced (checked_fn raises before nn.Module._apply assigns it), so the annotation is trivially intact.

Suggest keeping only the to_empty check.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 87dc20f. Kept the to_empty annotation check and removed the init_states and rejected-cast checks. All 35 module tests pass.

@tianyu-l

tianyu-l commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 45s —— View job


Approve, with one item to fix before merging: the PR description is still not restructured. The two code items from the last review are fixed. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the to_empty SPMD check remains.

Must fix (still open)

  1. 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_buffers declarations remain", "Removed the script construction tests...", "The three previously missed MoE casts...", "The EMA test helper and tests/utils.py match 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.py the MRoPE cache stays fp32 instead of fp16. In numerical_tests_kimi.py the vision inv_freq stays 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.003584 in scripts/rl/loss_compare.py, and training itself finished. The guard either raises or returns fn(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 whether main fails 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.

@tianyu-l
tianyu-l merged commit b54ff76 into pytorch:main Nov 6, 2026
@alfredclwong
alfredclwong deleted the rope-keep-cache-dtype-on-cast branch November 6, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants