Skip to content

Fix transformers_modeling_backend for pretrained dense models - #3772

Merged
acisseJZhong merged 6 commits into
pytorch:mainfrom
HosseinKaviani-H:hf-backend-rope-fix
Jun 29, 2026
Merged

acisseJZhong merged 6 commits into
pytorch:mainfrom
HosseinKaviani-H:hf-backend-rope-fix

Conversation

@HosseinKaviani-H

@HosseinKaviani-H HosseinKaviani-H commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Fix for #3775

Problem

Loading a real pretrained dense model (e.g. Qwen3-0.6B) into the HF backend produced near-random loss, and on recent PyTorch the backend crashed before training. The HF safetensors load correctly (verified byte-for-byte): the bugs are in how the backend builds/initializes the model, not in loading.

With the same Qwen3-0.6B checkpoint + data, step-1 loss was 11.08 (≈ ln(vocab), i.e. random) vs native TorchTitan qwen3's 3.63.

Root causes fixed

  1. RoPE inv_freq left uninitialized after meta-device init. HF rotary modules compute inv_freq in init; meta init + to_empty()
    zeros it and init_weights only re-inits parameters, silently disabling RoPE. Recompute it from each rotary module's rope_init_fn in
    init_states.
  2. TitanDenseModelConfig overrode the HF config. Non-None defaults (dim=4096, n_layers=32, n_heads=32, norm_eps=1e-5,
    rope_theta=10000) were injected over AutoConfig values, forcing the wrong architecture (e.g. rope_theta 1e6 → 10000 for Qwen3).
    Default these to None; set explicitly only to intentionally override (e.g. debugmodel).
  3. Tied embeddings crashed FSDP2. tok_embeddings/lm_head share a parameter under tie_word_embeddings but were in separate fully_shard
    groups (forbidden by recent FSDP2). Group tied tok_embeddings/norm/lm_head into one unit.
  4. head_dim/intermediate_size derived instead of read from the HF config. update_from_config set head_dim = hidden_size // num_heads,
    overriding Qwen3's explicit head_dim=128 with 64 and mismatching checkpoint shapes. Only derive when dim is explicitly overridden;
    otherwise keep the HF config's values.
  5. No state-dict adapter. model_registry set state_dict_adapter=None, so HF weight names were never mapped and initial_load_in_hf
    loaded nothing. Add HFTransformerStateDictAdapter (model. prefix + tied-embedding handling).

Verification

Loading Qwen3-0.6B into the full config, same checkpoint/data/seed as native (--debug.seed 42 --debug.deterministic):

  • Forward parity (step 1, on loaded weights): native 3.631 vs HF 3.623 — identical within bf16 tolerance (was 11.08 before).
  • Training parity (matched LR 3e-4): the curves track step-for-step with no instability:
step native HF
1 3.63 3.62
2 4.06 4.14
5 4.08 4.28
  • (Residual drift is expected — two different model implementations diverge as updates accumulate.)
  • The backend previously crashed at the FSDP tied-param check on any tied model (incl. debugmodel); it now trains.

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

pytorch-bot Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

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

@acisseJZhong

Copy link
Copy Markdown
Contributor

Forward parity (step 1, on loaded weights): native 3.631 vs HF 3.623 — identical within bf16 tolerance (was 11.08 before).

can you also compare the kl divergence between titan logits and HF logits after the first step? previously @shuhuayu compared titan model vs HF model and the logits difference is within 1e-7.

@shuhuayu

Copy link
Copy Markdown
Contributor

Forward parity (step 1, on loaded weights): native 3.631 vs HF 3.623 — identical within bf16 tolerance (was 11.08 before).

can you also compare the kl divergence between titan logits and HF logits after the first step? previously @shuhuayu compared titan model vs HF model and the logits difference is within 1e-7.

yeah, you can try a numerical test similar to scripts/checkpoint_conversion/numerical_tests_qwen3_5.py to check the logits divergence to have more confidence in the numerics.

@HosseinKaviani-H

Copy link
Copy Markdown
Contributor Author

@acisseJZhong @shuhuayu Ran a logit-divergence test (let me know if you want me to push the script as well) -backend vs plain HF from_pretrained on Qwen3-0.6B:

  • Full sequence: KL ≈ 9e-7, cosine = 1.0, top-1 = 100%
  • Last token: KL ≈ 9e-8, max_diff ≈ 2.6e-5

So the backend logits match HF within ~1e-7, in line with @shuhuayu's earlier result.

@shuhuayu

Copy link
Copy Markdown
Contributor

@acisseJZhong @shuhuayu Ran a logit-divergence test (let me know if you want me to push the script as well) -backend vs plain HF from_pretrained on Qwen3-0.6B:

  • Full sequence: KL ≈ 9e-7, cosine = 1.0, top-1 = 100%
  • Last token: KL ≈ 9e-8, max_diff ≈ 2.6e-5

So the backend logits match HF within ~1e-7, in line with @shuhuayu's earlier result.

thanks. i think the script will be very similar to the existing example so it's fine to not include it.

@acisseJZhong acisseJZhong 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.

LGTM, please fix the linter before landing and make sure failing tests are not caused by this PR

@HosseinKaviani-H

Copy link
Copy Markdown
Contributor Author

LGTM, please fix the linter before landing and make sure failing tests are not caused by this PR

@acisseJZhong The lint failure is Pyrefly, not this PR:
1- Pyrefly excludes torchtitan/experiments/ (all my changes are there), so my files aren't even checked.
2- The 5 errors are in core files I didn't touch (distributed/utils.py, token_dispatcher.py), caused by the CI env missing its ../pytorch search path (WARN .../pytorch does not exist) therefore can't resolve batch_invariant_ops/torchcomms/all_to_all_single types.

# A self-mapped name (e.g. vocab_size -> vocab_size) is already
# stored under the correct name; creating an alias property would
# make its setter call setattr() on itself and recurse forever.
if titan_name == hf_name:

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.

@acisseJZhong Fixed the RecursionError in the integration test: the vocab_size -> vocab_size self-mapping built a self-referential alias property that recursed on first set. Now skip alias creation when TT and HF names match. Other CI failures (pyrefly, ROCm loss-parity) are pre-existing/environmental.

Hossein Kavianihamedani added 6 commits June 29, 2026 10:10
Three base-backend bugs that make the HF backend produce near-random loss /
crash when building or loading real pretrained models (independent of SFT):

1. RoPE inv_freq left uninitialized after meta-init: HF rotary modules compute
   inv_freq in __init__, but meta-device init + to_empty() zeros it and
   _init_weights does not recompute it, silently disabling RoPE. Recompute it
   from each rotary module's rope_init_fn in init_states.

2. TitanDenseModelConfig overrides the HF config: non-None defaults (dim=4096,
   n_layers=32, n_heads=32, norm_eps=1e-5, rope_theta=10000) were injected over
   AutoConfig values, forcing the wrong architecture/hyperparameters (e.g.
   rope_theta 1e6 -> 10000 for Qwen3). Default these to None so the HF config
   wins; set explicitly only to intentionally override (e.g. debugmodel).

3. Tied embeddings crash FSDP2: tok_embeddings and lm_head share a parameter
   when tie_word_embeddings is set, but were placed in separate fully_shard
   groups (FSDP2 forbids this on recent PyTorch). Group tied
   tok_embeddings/norm/lm_head into one FSDP unit.
…add state-dict adapter

Completes loaded-weight support for pretrained HF dense models:

4. head_dim/intermediate_size were unconditionally derived from
   hidden_size/num_heads in update_from_config, overriding the HF config.
   Models like Qwen3 decouple head_dim (128) from hidden_size/num_heads (64),
   so loading mismatched the projection shapes. Only derive these when dim is
   explicitly overridden (e.g. debugmodel); otherwise keep the HF config values.

5. model_registry set state_dict_adapter=None, so HF safetensors keys were never
   mapped to TorchTitan FQNs and initial_load_in_hf loaded nothing. Add
   HFTransformerStateDictAdapter (model. prefix mapping + tied-embedding handling).

Verified: loading Qwen3-0.6B into the 'full' config now gives step-1 loss 3.62,
matching native qwen3 (3.63) on the same checkpoint + data.
Group fields into HF-mapped (default None so AutoConfig's value is kept) vs
TorchTitan-only (concrete defaults, no HF equivalent so nothing is overridden),
with comments explaining why -- addresses review question on multiple_of.
…nfig alias

The dynamic getter/setter mechanism installs an alias property for each
TorchTitan->HuggingFace name pair. The 'vocab_size' -> 'vocab_size'
self-mapping produced a property whose setter calls setattr() on its own
name, recursing forever the first time vocab_size is set (during
Config construction). This crashed the integration test with
RecursionError under current transformers, where PretrainedConfig no
longer exposes vocab_size as a class attribute (so the existing
hasattr guard no longer skipped it).

Skip alias creation when the TorchTitan and HuggingFace names are
identical: no redirect is needed and the value is already stored under
the correct name. Genuine aliases (dim->hidden_size, etc.) are
unaffected, and vocab_size stays in the mapping so it is still copied
to/from the HF config.
@meta-codesync

meta-codesync Bot commented Jun 29, 2026

Copy link
Copy Markdown

@HosseinKaviani-H has imported this pull request. If you are a Meta employee, you can view this in D110075539.

@acisseJZhong
acisseJZhong merged commit ac240f9 into pytorch:main Jun 29, 2026
14 of 17 checks passed
mreso added a commit to mreso/torchtitan that referenced this pull request Jun 29, 2026
Absorbs pytorch#3772 "Fix transformers_modeling_backend for pretrained dense models",
which actively develops the same experiment, so this merge has real conflicts.

Resolutions:
- __init__.py: keep our class hierarchy (TitanModelConfig base + TitanMoeModelConfig)
  but adopt main's None defaults for HF-mapped fields (dim/n_layers/n_heads/norm_eps/
  rope_theta) so AutoConfig values win for pretrained models; keep our intermediate_size
  (None default) and MoE config. Registry: keep our register_moe_load_balancing_hook
  AND wire main's state_dict_adapter=HFTransformerStateDictAdapter.
- state_dict_adapter.py (add/add): keep BOTH -- our MoE key-conversion functions
  (hf_to_titan_moe_state_dict / titan_to_hf_moe_state_dict, used by the equivalence/
  roundtrip tests) AND main's HFTransformerStateDictAdapter class (model. prefix +
  tied-embedding handling, wired into the ModelSpec).
- model.py: the identity-mapping recursion guard was added by both sides (same fix);
  kept one. update_from_config: integrate main's dim_overridden gating (don't clobber
  HF head_dim/intermediate_size for pretrained models like Qwen3) WITH our MLA handling
  (qk_rope_head_dim for DeepSeek-V3/GLM-5) and DeepSeek expert-group consistency.
- parallelize.py: auto-merged -- main's tied-embedding FSDP grouping composes with our
  flat-FSDP EP (shard_placement_fn) code.

Validated: experiment unit tests (15) pass; full 8-GPU integration suite (6 flavors)
all rc=0.
mreso added a commit to mreso/torchtitan that referenced this pull request Jul 2, 2026
Mirror the dense-config fix (pytorch#3772) for the routed-expert fields that map to an
HF config key: num_experts, num_experts_per_tok, moe_intermediate_size,
decoder_sparse_step, norm_topk_prob now default to None so AutoConfig's value is
used for pretrained models and an explicit set is always detectable as an
override. TorchTitan-only knobs (experts_implementation, load_balance_coeff,
comm_backend) keep concrete defaults. Behavior-preserving: debugmodel_moe
FSDP+EP=2 loss is bitwise-identical, unit tests pass.
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Jul 15, 2026
…h#3772)

Fix for pytorch#3775 

***Problem***

Loading a real pretrained dense model (e.g. Qwen3-0.6B) into the HF
backend produced near-random loss, and on recent PyTorch the backend
crashed before training. The HF safetensors load correctly (verified
byte-for-byte): the bugs are in how the backend builds/initializes the
model, not in loading.

With the same Qwen3-0.6B checkpoint + data, step-1 loss was 11.08 (≈
ln(vocab), i.e. random) vs native TorchTitan qwen3's 3.63.

***Root causes fixed***

1. RoPE inv_freq left uninitialized after meta-device init. HF rotary
modules compute inv_freq in __init__; meta init + to_empty()
zeros it and init_weights only re-inits parameters, silently disabling
RoPE. Recompute it from each rotary module's rope_init_fn in
  init_states.
2. TitanDenseModelConfig overrode the HF config. Non-None defaults
(dim=4096, n_layers=32, n_heads=32, norm_eps=1e-5,
rope_theta=10000) were injected over AutoConfig values, forcing the
wrong architecture (e.g. rope_theta 1e6 → 10000 for Qwen3).
Default these to None; set explicitly only to intentionally override
(e.g. debugmodel).
3. Tied embeddings crashed FSDP2. tok_embeddings/lm_head share a
parameter under tie_word_embeddings but were in separate fully_shard
groups (forbidden by recent FSDP2). Group tied
tok_embeddings/norm/lm_head into one unit.
4. head_dim/intermediate_size derived instead of read from the HF
config. update_from_config set head_dim = hidden_size // num_heads,
overriding Qwen3's explicit head_dim=128 with 64 and mismatching
checkpoint shapes. Only derive when dim is explicitly overridden;
  otherwise keep the HF config's values.
5. No state-dict adapter. model_registry set state_dict_adapter=None, so
HF weight names were never mapped and initial_load_in_hf
loaded nothing. Add HFTransformerStateDictAdapter (model. prefix +
tied-embedding handling).

***Verification***

Loading Qwen3-0.6B into the full config, same checkpoint/data/seed as
native (--debug.seed 42 --debug.deterministic):

- Forward parity (step 1, on loaded weights): native 3.631 vs HF 3.623 —
identical within bf16 tolerance (was 11.08 before).
- Training parity (matched LR 3e-4): the curves track step-for-step with
no instability:

  | step | native | HF   |
  |------|--------|------|
  | 1    | 3.63   | 3.62 |
  | 2    | 4.06   | 4.14 |
  | 5    | 4.08   | 4.28 |

- (Residual drift is expected — two different model implementations
diverge as updates accumulate.)
- The backend previously crashed at the FSDP tied-param check on any
tied model (incl. debugmodel); it now trains.

---------

Co-authored-by: Hossein Kavianihamedani <[email protected]>
Jiarwang77 added a commit to Jiarwang77/torchtitan that referenced this pull request Sep 21, 2026
…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]>
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/8gpu 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