Repository navigation
Make from_config respect _keep_in_fp32_modules / _keep_in_fp32_modules_strict - #50830
francesco-bertolotti wants to merge 2 commits into
Conversation
|
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 |
There was a problem hiding this comment.
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 = FalseThe 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.
There was a problem hiding this comment.
Thanks for weighing in. I should hopefully be able to have a look at it by the end of this week.
|
Humm, actually |
|
I'm taking care of it |
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_configonly instantiated the model underlocal_torch_dtype(dtype)and ignored the flags, so the same weights ended up in the requested low-precision dtype.After instantiating the model,
_from_confignow builds the same dtype plan and upcasts the matching floating-point parameters and buffers, matching names withbuild_glob_alternationexactly 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_initializedflag of the modules owning them is reset andinit_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_weightsof its own sub-model), and the weights are tied again. E.g. RWKV's deterministictime_decaybuilt withdtype=torch.float16is 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):Tests
Added
test_keep_in_fp32_modules_from_confignext totest_keep_in_fp32_modulesintests/test_modeling_common.py: for fp16 and bf16, every floating-point weight of_from_config(config, dtype=...)must have the same dtype asfrom_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):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);-k "dtype or from_config"over the same files andtests/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_pretrainedand 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 listsconv.norm, and BatchNorm'snum_batches_trackedloaded asfloat32instead ofint64. 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_keep_in_fp32_modules_from_confignow 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 andtests/utils/test_core_model_loading.pyshow no new failures.