Skip to content

Make from_config respect _keep_in_fp32_modules / _keep_in_fp32_modules_strict - #50830

Closed
francesco-bertolotti wants to merge 2 commits into
huggingface:mainfrom
francesco-bertolotti:fix/from-config-keep-in-fp32
Closed

francesco-bertolotti wants to merge 2 commits into
huggingface:mainfrom
francesco-bertolotti:fix/from-config-keep-in-fp32

Conversation

@francesco-bertolotti

@francesco-bertolotti francesco-bertolotti commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

from_pretrained(..., dtype=...) keeps the weights listed in _keep_in_fp32_modules (fp16) and _keep_in_fp32_modules_strict (fp16 and bf16) in fp32, through the plan built by _get_dtype_plan. from_config / _from_config only instantiated the model under local_torch_dtype(dtype) and ignored the flags, so the same weights ended up in the requested low-precision dtype.

After instantiating the model, _from_config now builds the same dtype plan and upcasts the matching floating-point parameters and buffers, matching names with build_glob_alternation exactly like the loading path does. Integer buffers are left alone, and under DeepSpeed ZeRO-3 (partitioned parameters) nothing changes.

Since the model was initialized under the low-precision default dtype, the upcast weights would otherwise hold bf16/fp16-rounded values. Once they are fp32, the _is_hf_initialized flag of the modules owning them is reset and init_weights() runs again: every other module is still flagged as initialized and is skipped, so only those modules are initialized again (each with the _init_weights of its own sub-model), and the weights are tied again. E.g. RWKV's deterministic time_decay built with dtype=torch.float16 is now bit-identical to an fp32 build.

Follow-up from #50722 (comment).

Fixes # (issue)

Reproducer

Beam declares _keep_in_fp32_modules_strict = ["e_score_correction_bias", "mlp.gate.weight"] (full script in the issue):

print("from_pretrained:", router_dtypes(AutoModelForCausalLM.from_pretrained(tmp, dtype=torch.bfloat16)))
print("from_config:    ", router_dtypes(AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16)))
# main
from_pretrained: (torch.float32, torch.float32)
from_config:     (torch.bfloat16, torch.bfloat16)
# this PR
from_pretrained: (torch.float32, torch.float32)
from_config:     (torch.float32, torch.float32)

Tests

Added test_keep_in_fp32_modules_from_config next to test_keep_in_fp32_modules in tests/test_modeling_common.py: for fp16 and bf16, every floating-point weight of _from_config(config, dtype=...) must have the same dtype as from_pretrained(..., dtype=...). It is skipped for models without the flags.

Run over the test files of all 52 model families that set either flag (-k test_keep_in_fp32_modules):

  • on main, the new test fails for 33 of them (e.g. Beam, DeepSeek-V3/V3.2/V4, GPT-OSS, T5/mT5/UMT5, MiMo-V2-Flash, Nemotron-H, Voxtral);
  • with this PR: 201 passed, 30 skipped.

-k "dtype or from_config" over the same files and tests/utils/test_modeling_utils.py -k "dtype or from_config or fp32" show no new failures.

Who can review?

@Cyrilvallez @ArthurZucker @vasqu

🤖 Generated with the help of Claude Code


Edits

  • from_pretrained and integer buffers (core_model_loading.py): loading applied the fp32 plan by key name only, so integer buffers matching it were cast too. E.g. Granite Speech 5 lists conv.norm, and BatchNorm's num_batches_tracked loaded as float32 instead of int64. The plan now only applies to floating-point weights. Thanks @14H034160212 for pointing this out in from_config does not honor _keep_in_fp32_modules #50827.
  • Test: test_keep_in_fp32_modules_from_config now compares the dtype of every tensor, integer buffers included, instead of only the floating-point ones. Without the loading change it fails for Granite Speech 5; with it, the 52 model families that set either flag pass (201 passed, 30 skipped). -k "dtype or from_config or init" on the same files and tests/utils/test_core_model_loading.py show no new failures.

@vasqu

vasqu commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

cc @Cyrilvallez just in case, feel like that's more up your ally 🫡

# The weights were initialized in the low-precision dtype: initialize them again now that they are upcast.
# All the other modules are flagged as initialized already, so they are skipped.
for module_name in upcast_modules:
model.get_submodule(module_name)._is_hf_initialized = False

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.

Thanks for picking up the integer-buffer case too. I ran the branch (61fe704) against all 61 model test files that use the flags: test_keep_in_fp32_modules* passes everywhere (116 passed).

The re-init here has one problem. Some _init_weights initialize a child's weight from the parent's branch. In T5, wo is set inside the T5DenseActDense / T5DenseGatedActDense branch with std factor * d_ff**-0.5. Resetting only wo's flag sends it through the generic nn.Linear path instead:

import torch
from transformers import T5Config, T5ForConditionalGeneration

config = T5Config(d_model=64, d_ff=256, num_layers=2, num_heads=4, d_kv=16, vocab_size=128)
for dtype in (torch.float32, torch.float16):
    torch.manual_seed(0)
    model = T5ForConditionalGeneration._from_config(config, dtype=dtype)
    wo = model.encoder.block[0].layer[1].DenseReluDense.wo.weight
    print(dtype, wo.dtype, f"std={wo.float().std().item():.5f}")
torch.float32 torch.float32 std=0.06272
torch.float16 torch.float32 std=0.99652   # expected ~0.0625 (d_ff**-0.5)

On main, the fp16 wo has the right std. The same thing happens in every model that reuses T5's FFN: MT5, UMT5, Udop, Pop2Piano, and Blip2 with a T5 language model.

To check every model at once, I built each class with _from_config(dtype=fp16/bf16) and with fp32 under the same seed, then compared the upcast tensors. Constant tensors had to match exactly; random ones had to have a std within 50%. Across 68 class/dtype combinations, those 6 families were the only mismatches.

Also resetting the direct parent's flag removes all of them (0 mismatches):

model.get_submodule(module_name)._is_hf_initialized = False
# Some `_init_weights` set a child's weight from the parent's branch (e.g. T5's `wo`)
model.get_submodule(module_name.rpartition(".")[0])._is_hf_initialized = False

The parent's other weights (e.g. wi) are re-drawn as well, which seems harmless for a freshly built model. A test that compares the std of the upcast weights against an fp32 build would catch this kind of regression. Without the re-init, the values are only bf16/fp16-rounded copies of a correct init, e.g. a layer-scale 0.01 becomes 0.01001.

Checked with Claude Code (Anthropic); I ran the scripts above.

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 weighing in. I should hopefully be able to have a look at it by the end of this week.

@Cyrilvallez

Copy link
Copy Markdown
Member

Humm, actually _keep_in_fp32_modules should NOT be respected with from_config, it's only there to avoid losing precision too much if switching dtype on-the-fly for a few precise combinations. As for _keep_in_fp32_modules_strict, it should already be handled correctly by having the hardcoded dtype=torch.float32 in all the params/buffers.
So TLDR, I don't think we have to do anything here, except maybe adding dtype=torch.float32 to a few missing places.
Feel free to reopen if you think otherwise though

@francesco-bertolotti

Copy link
Copy Markdown
Contributor Author

As for _keep_in_fp32_modules_strict, it should already be handled correctly by having the hardcoded dtype=torch.float32 in all the params/buffers.

Sounds good to me. Should I put the dtype back as in here: ea0cc8a @vasqu

@Cyrilvallez

Copy link
Copy Markdown
Member

I'm taking care of it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

from_config does not honor _keep_in_fp32_modules

4 participants