Repository navigation
[transformers_modeling_backend] Populate rotary inv_freq in _init_weights - #4817
Jiarwang77 wants to merge 1 commit into
Conversation
|
Hi @Jiarwang77! Thank you for your pull request and welcome to our community. Action RequiredIn 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. ProcessIn 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 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]>
bfe54ef to
69781a8
Compare
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
|
|
@claude review this PR. Evaluate if this is the most proper fix. |
|
Claude finished @tianyu-l's task in 4m 53s —— View job PR Review: Populate rotary
|
|
@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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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?
…'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.
Fixes #4783.
Issue description
HFTransformerModel.init_states()did not write real values intoinv_freqon HF rotary modules aftermetainit +to_empty(), so RoPE rotated by uninitialized memory. The compatibility loop added in #3772 readsmodule.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' ownRotaryEmbeddingbranch inPreTrainedModel._init_weightsdoes not run either, because the backend replaces all of that method.Nothing raises, and
inv_freqis non-persistent, so loading a checkpoint does not write it either.Fix
model.py-- reproduce the Transformers rotary initialization inside_init_weights_patched, soinit_states()reaches it like any other submodule, and drop the loop that no longer does anything. The guard isoriginal_inv_freq, the same one Transformers uses, so the layer-typed rotary modules handled by model-specific_init_weightsoverrides are also skipped here. Both buffers are written, becausedynamicandlongropere-registerinv_freqfromoriginal_inv_freq.tests/test_rope_init.py(new) -- CPU unit tests overmeta->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.yamlhaspaths-ignore: torchtitan/experiments/**and runspytest tests/unit_tests/cpu, and the 8-GPU workflow only runsintegration_tests.py, so without this nothing would run the tests. Modelled onunit_test_cpu_torchft.yaml. It installs from.ci/docker/requirements-transformers-modeling-backend.txtand lists that file underpaths, so a Transformers bump triggers this job and runs the tests against the new version -- which is how this regressed in the first place.