Skip to content

[transformers_modeling_backend] Populate rotary inv_freq in _init_weights - #4817

Closed
Jiarwang77 wants to merge 1 commit into
pytorch:mainfrom
Jiarwang77:fix-rope-inv-freq-init
Closed

Jiarwang77 wants to merge 1 commit into
pytorch:mainfrom
Jiarwang77:fix-rope-inv-freq-init

Conversation

@Jiarwang77

@Jiarwang77 Jiarwang77 commented Sep 21, 2026 •

Copy link
Copy Markdown

Fixes #4783.

Issue description

HFTransformerModel.init_states() did not write real values into inv_freq on HF rotary modules after meta init + to_empty(), so RoPE rotated by uninitialized memory. The compatibility loop added in #3772 reads module.rope_init_fn, which Transformers 5.0.0 changed from an instance attribute to a local variable inside __init__, so the loop has been a no-op since #2679 moved the pin to 5.x. Transformers' own RotaryEmbedding branch in PreTrainedModel._init_weights does not run either, because the backend replaces all of that method.

Nothing raises, and inv_freq is non-persistent, so loading a checkpoint does not write it either.

Fix

  • model.py -- reproduce the Transformers rotary initialization inside _init_weights_patched, so init_states() reaches it like any other submodule, and drop the loop that no longer does anything. The guard is original_inv_freq, the same one Transformers uses, so the layer-typed rotary modules handled by model-specific _init_weights overrides are also skipped here. Both buffers are written, because dynamic and longrope re-register inv_freq from original_inv_freq.
  • tests/test_rope_init.py (new) -- CPU unit tests over meta -> to_empty() -> init_states(). They compare against a rotary module built directly on CPU, so the expected values come from HF's own __init__ rather than from the code under test.
  • .github/workflows/unit_test_cpu_transformers_modeling_backend.yaml (new) -- unit_test_cpu.yaml has paths-ignore: torchtitan/experiments/** and runs pytest tests/unit_tests/cpu, and the 8-GPU workflow only runs integration_tests.py, so without this nothing would run the tests. Modelled on unit_test_cpu_torchft.yaml. It installs from .ci/docker/requirements-transformers-modeling-backend.txt and lists that file under paths, so a Transformers bump triggers this job and runs the tests against the new version -- which is how this regressed in the first place.

@meta-cla

meta-cla Bot commented Sep 21, 2026

Copy link
Copy Markdown

Hi @Jiarwang77!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

…ghts

HF rotary modules compute inv_freq in __init__, so meta init + to_empty()
leaves it as uninitialized memory and nothing ever writes real values into it.
The compatibility loop added in pytorch#3772 recomputed it from module.rope_init_fn,
but Transformers 5.0.0 changed that from an instance attribute to a local
variable, so the loop has been a no-op since the pin moved to 5.x in pytorch#2679.
Transformers' own RotaryEmbedding branch in _init_weights does not run either,
because the backend replaces all of that method. Nothing raises, inv_freq is
non-persistent so a checkpoint load does not write it either, and the only
symptom is loss starting at near-random.

Move the population into _init_weights_patched so init_states() reaches it like
any other submodule. The guard is original_inv_freq, the same one Transformers
uses, so the layer-typed rotary modules handled by model-specific _init_weights
overrides are also skipped here. Both buffers are written: dynamic and longrope
re-register inv_freq from original_inv_freq, so leaving that copy uninitialized
corrupts inv_freq a few forwards later.

Add CPU unit tests over meta -> to_empty() -> init_states() that compare
against a rotary module built directly on CPU, so the expected values are
independent of the code under test. unit_test_cpu.yaml skips
torchtitan/experiments, so add a workflow that runs them; it installs from the
pin file, which means the next Transformers bump runs these tests against the
new version instead of silently disabling RoPE again.

Co-authored-by: Cursor <[email protected]>
@Jiarwang77
Jiarwang77 force-pushed the fix-rope-inv-freq-init branch from bfe54ef to 69781a8 Compare September 21, 2026 09:38
@Jiarwang77 Jiarwang77 changed the title [transformers_modeling_backend] Reinitialize rotary inv_freq in _init_weights [transformers_modeling_backend] Populate rotary inv_freq in _init_weights Sep 21, 2026
@meta-cla

meta-cla Bot commented Sep 21, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 21, 2026
@meta-cla

meta-cla Bot commented Sep 21, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@Jiarwang77
Jiarwang77 marked this pull request as ready for review September 21, 2026 10:11
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 21, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

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

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR. Evaluate if this is the most proper fix.

@claude

claude Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

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


PR Review: Populate rotary inv_freq in _init_weights

I read model.py, the new test_rope_init.py, and the new workflow, and traced the init path (init_states -> self.model.apply(selective_init) -> patched _init_weights -> the new RotaryEmbedding branch). Note: transformers isn't installed in my sandbox and I couldn't fetch upstream source, so the version-specific claims below (marked verify) rest on the PR's description + the CI job you added, not on my own execution.

Verdict

The direction is correct and is more proper than the code it replaces. Routing the buffer population through _init_weights (which init_states() already walks over every submodule) unifies it with the existing init mechanism instead of bolting on a second post-hoc loop. Deleting the rope_init_fn loop is right: getattr(module, "rope_init_fn", None) returns None on transformers 5.x, so it was dead code. The tests and the new CI job are genuinely good and directly target the regression mode.

The one debatable choice is how the branch recomputes the buffers — see concern 1.

Concern 1 (main): reproducing HF internals is the same coupling that caused this bug

rope_init_fn = (
    module.compute_default_rope_parameters
    if module.rope_type == "default"
    else ROPE_INIT_FUNCTIONS[module.rope_type]
)
inv_freq, _ = rope_init_fn(module.config, module.inv_freq.device)

This hand-encodes HF's own dispatch — including the version-specific detail that "default" is a method on the rotary class rather than a ROPE_INIT_FUNCTIONS entry. That's precisely the kind of internal coupling that silently broke last time (rope_init_fn moving from attribute to local). A more robust "most proper" version is to delegate to the original, unpatched PreTrainedModel._init_weights for the RotaryEmbedding case rather than re-derive the dispatch:

  • Capture the original _init_weights before rebinding, and in the RotaryEmbedding branch call _original_init_weights(self, module).
  • Caveat that makes this non-trivial: _patch_hf_llama_like rebinds PreTrainedModel._init_weights globally and is called once per model, so a naive capture on the second model would grab the already-patched function and recurse. You'd need a sentinel (e.g. stash the original on the function object / a module-level _ORIGINAL_INIT_WEIGHTS set only if not already patched).

If that guard is judged too fiddly, keeping the inline reproduction is defensible because the new CI job re-runs these tests on every pin bump — that safety net is really what downgrades this from a blocker to a judgment call. Worth a one-line comment in the code saying "kept inline deliberately; the pin-triggered CI job is the guard against HF changing this dispatch."

Concern 2: compute_default_rope_parameters assumed present on every rotary class (verify)

module.compute_default_rope_parameters is only reached for rope_type == "default", but it assumes every supported model's rotary class exposes that method under that exact name. Per the repo's "audit all variants" rule, this branch is shared by llama3/llama4/qwen3/deepseek_v3/gpt_oss/gemma4/flux. If any of their rotary classes lacks the method (or names it differently), the default path raises AttributeError. Please confirm across variants, or fall back to ROPE_INIT_FUNCTIONS.get("default") when the method is absent.

Concern 3: test coverage doesn't exercise the paths the comments call out

The code comment justifies writing original_inv_freq because dynamic/longrope re-register inv_freq from it. But no test uses dynamic, longrope, or yarn:

  • test_original_inv_freq_is_materialized uses llama3, which (per the same comment) does not read original_inv_freq. So the exact behavior the second .copy_() exists to protect is never exercised end to end.
  • Coverage is Llama-only. The ROPE_INIT_FUNCTIONS[rope_type] dispatch and the original_inv_freq-guard skip for MLA / layer-typed rotary aren't hit for any non-Llama variant.

Suggest adding at least a dynamic (or longrope) case so the re-register path is real, and ideally one non-Llama rotary. LlamaConfig supports rope_type: "dynamic", so this can stay CPU/Llama-only and still cover the branch.

Concern 4: dropped attention_scaling — confirm intentional

The old loop also set module.attention_scaling = attention_scaling; the new branch discards the second return (inv_freq, _ = ...). This is correct — attention_scaling is a plain Python float attribute set in __init__, so it survives meta + to_empty() untouched, and HF's own _init_weights doesn't reset it either. Worth a sentence in the PR description so a reviewer doesn't read the drop as an oversight.

Nits

  • The in-code comment "the layer-typed rotary modules handled by model-specific _init_weights overrides are also skipped here" is a little confusing given the patch rebinds PreTrainedModel._init_weights wholesale. Since subclass-level _init_weights (if any) would shadow the base rebind, those overrides wouldn't route through this patched method at all — consider rewording to just "the original_inv_freq guard matches HF's own guard and skips rotary variants that don't register it."
  • Workflow runs only test_rope_init.py. Pointing it at the tests/ dir would auto-cover future experiment unit tests, but scoping to the file is a fine starting point.

What I could not verify

  • transformers 5.10.1 internals: that ROPE_INIT_FUNCTIONS truly lacks "default" and that compute_default_rope_parameters is a method on each rotary class. The added CI job will validate this at merge time — worth confirming it's green before landing.
  • I did not run pre-commit / pytest (transformers not installed here, network fetch not approved).

Summary

Solid fix with well-designed tests and a CI net that closes the specific regression loop. Not blocking, but I'd recommend: (a) either delegate to the original _init_weights for the rotary branch or add a code comment that the inline dispatch is deliberately guarded by the pin-triggered CI; (b) add a dynamic/longrope test so the original_inv_freq re-register path is actually exercised; (c) confirm compute_default_rope_parameters exists on all model variants' rotary classes.


  • Read changed files
  • Verify root-cause reasoning (dead loop, rope_init_fn change)
  • Evaluate whether reproducing HF's branch is the most proper fix
  • Check edge cases (rope_type dispatch, MLA/layer-typed skip, variants)
  • Review test + workflow
  • Post review
    | Branch: fix-rope-inv-freq-init

@tianyu-l

Copy link
Copy Markdown
Contributor

@Jiarwang77 do you agree with review claude gave? Seems that there could be some improvements.

@HosseinKaviani-H could you also help take a look?


# Install from the pin file rather than a literal version, so that a
# Transformers bump has to run these tests against the new version.
python -m pip install -r .ci/docker/requirements-transformers-modeling-backend.txt

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.

Pin-file install is right, but integration_test_8gpu_transformers_modeling_backend.yaml:87 still hardcodes transformers==5.9.0 vs 5.10.1 here. Two versions tested, you should unify.

else ROPE_INIT_FUNCTIONS[module.rope_type]
)
inv_freq, _ = rope_init_fn(module.config, module.inv_freq.device)
module.inv_freq.copy_(inv_freq)

@HosseinKaviani-H HosseinKaviani-H Sep 24, 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.

Under TP, is module.inv_freq a DTensor here? parallelize() runs before to_empty()/init_weights() and hf_sharding.py:437 declares these buffers replicated. Copying a plain tensor into a DTensor would raise an error then cc @tianyu-l

if module.rope_type == "default"
else ROPE_INIT_FUNCTIONS[module.rope_type]
)
inv_freq, _ = rope_init_fn(module.config, module.inv_freq.device)

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.

Your comment says this branch is reproduced from Transformers, but HF calls rope_fn(module.config) with no device arg and uses init.copy_ rather than Tensor.copy_. Is this intentional?

@tianyu-l tianyu-l closed this Oct 7, 2026
tianyu-l pushed a commit that referenced this pull request Oct 13, 2026
…'s _init_weights (#5214)

Fixes #4783.

HF rotary modules compute `inv_freq` and `original_inv_freq` in
`__init__`, so the backend's meta init + `to_empty()` leaves them
uninitialized and RoPE silently rotates by garbage. The recompute loop
in `init_states()` (from #3772) reads `module.rope_init_fn`, which
Transformers 5.x no longer sets, so it has been a no-op since the pin
moved to 5.x.

This adds a `RotaryEmbedding` branch to `_init_weights_patched` that
delegates to HF's own `PreTrainedModel._init_weights`, captured at
import before the backend patches it. HF's branch already handles every
`rope_type` and both buffers, so the backend no longer re-derives HF's
rope dispatch (the main point of the review on #4817). The dead loop is
removed. `attention_scaling` is a float set in `__init__` and survives
`to_empty()`, so nothing needs to reset it.

**Test:** `tests/test_rope_init.py` runs the real `Config -> build() on
meta -> to_empty() -> init_states()` path for Llama default / llama3 /
dynamic and Qwen3 yarn. It fills the rotary buffers with NaN before
`init_states()` and compares against the rotary module constructed
directly on CPU.
- fails 4/4 on main, passes with this change on transformers 5.9.0
(installed by the backend workflow), 5.10.1 (requirements pin) and
5.14.1
- `pre-commit` passes

The backend's unit tests aren't collected by any CI job (the CPU job
ignores `torchtitan/experiments/**`), so this test currently runs
locally.

**Numerics:** a tiny Llama (llama3 rope) built through `init_states()`,
with its weights loaded into a normally constructed `LlamaForCausalLM`,
gives bit-identical logits on the same batch with this change (max diff
0); on main they differ (max diff 5.6e-4 at init). #3775 has the
training-loss impact of this failure mode.

Diagnosis by @Jiarwang77 in #4783 / #4817. Drafted with AI assistance
(Claude); I reviewed and tested the change.
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 CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[transformers_modeling_backend]Regression of #3775: rotary inv_freq is left uninitialized after to_empty()

3 participants