Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix missing initializations for models created in 2022#39772

Open
bvantuan wants to merge 33 commits into
huggingface:mainfrom
bvantuan:fix-missing-initializations-2022
Open

Fix missing initializations for models created in 2022#39772
bvantuan wants to merge 33 commits into
huggingface:mainfrom
bvantuan:fix-missing-initializations-2022

Conversation

@bvantuan

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes missing weight initializations for models created in 2022.

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.
@Cyrilvallez

@bvantuan bvantuan marked this pull request as draft July 30, 2025 04:38
Comment on lines +557 to +558
nn.init.trunc_normal_(module.cls_token, std=std)
nn.init.trunc_normal_(module.position_embeddings, std=std)

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.

Comment on lines +540 to +541
nn.init.trunc_normal_(module.cls_token, std=std)
nn.init.trunc_normal_(module.position_embeddings, std=std)

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.

if isinstance(module, YolosEmbeddings):
nn.init.trunc_normal_(module.cls_token, std=std)
nn.init.trunc_normal_(module.position_embeddings, std=std)
nn.init.trunc_normal_(module.detection_tokens, std=std)

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.

nn.init.trunc_normal_(module.position_embeddings, std=std)
nn.init.trunc_normal_(module.detection_tokens, std=std)
elif isinstance(module, YolosEncoder):
nn.init.trunc_normal_(module.mid_position_embeddings, std=std)

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.

Comment on lines +764 to +765
elif isinstance(module, GroupViTVisionEmbeddings):
nn.init.trunc_normal_(module.position_embeddings, std=factor * 0.02)

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.

Comment on lines +778 to +784
elif isinstance(module, GroupViTStage):
if module.num_group_token > 0:
# only zero init group token if we have a projection
if module.group_projector is not None:
module.group_token.data.zero_()
else:
nn.init.trunc_normal_(module.group_token, std=factor * 0.02)

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.

Comment on lines -553 to +550
nn.init.normal_(module.position_embedding, std=self.config.initializer_factor)
nn.init.normal_(module.position_embedding, std=factor * 0.02)

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.

Comment on lines -559 to +558
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
module.weight.data.normal_(mean=0.0, std=factor * 0.02)

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.

Comment on lines +487 to +488
elif isinstance(module, VideoMAEForPreTraining):
module.mask_token.data.normal_(mean=0.0, std=std)

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.

@bvantuan

bvantuan commented Aug 8, 2025

Copy link
Copy Markdown
Contributor Author

Hi @Cyrilvallez ! I'm encountering a blocker while trying to fix the missing initializations for the Data2VecAudio model. Below is the updated initialization for this model:

def _init_weights(self, module: nn.Module):
        """Initialize the weights"""
        if isinstance(module, Data2VecAudioFeatureProjection):
            k = math.sqrt(1 / module.projection.in_features)
            nn.init.uniform_(module.projection.weight, a=-k, b=k)
            nn.init.uniform_(module.projection.bias, a=-k, b=k)
        elif isinstance(module, Data2VecAudioForXVector):
            nn.init.normal_(module.objective.weight)
        elif isinstance(module, Data2VecAudioPositionalConvLayer):
            nn.init.constant_(module.conv.bias, 0)
        elif isinstance(module, Data2VecAudioModel):
            # model only needs masking vector if mask prob is > 0.0
            if self.config.mask_time_prob > 0.0 or self.config.mask_feature_prob > 0.0:
                nn.init.uniform_(module.masked_spec_embed)
        elif isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.LayerNorm):
            if module.bias is not None:
                module.bias.data.zero_()
            if module.weight is not None:
                module.weight.data.fill_(1.0)
        elif isinstance(module, nn.Conv1d):
            nn.init.kaiming_normal_(module.weight)
            if module.bias is not None:
                k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
                nn.init.uniform_(module.bias, a=-k, b=k)

When generating the modeling file from the modular file, I run into a code verification error during the make fixup process.

src/transformers/models/data2vec/modeling_data2vec_audio.py:797:35: F821 Undefined name `Data2VecAudioPreTrainedModel`
    |
795 |     """
796 | )
797 | class Data2VecAudioForPreTraining(Data2VecAudioPreTrainedModel):
    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ F821
798 |     def __init__(self, config: Data2VecAudioConfig):
799 |         super().__init__(config)
    |

Found 1 error.

The error occurs because Data2VecAudioPreTrainedModel is declared after Data2VecAudioForPreTraining, and I don't know how to skip the creation of Data2VecAudioForPreTraining during the modular_model_converter.py process.

@Cyrilvallez

Cyrilvallez commented Aug 13, 2025

Copy link
Copy Markdown
Member

Hey @bvantuan! Sorry for the delay! The issue comes from the fact that Data2VecAudioModeland Data2VecAudioForXVector are now referenced before their redefinition inside the modular file, so modular imports them and their dependencies before it sees how they should be redefined... 🥲 We should indeed add forward checks, not only backward ones for such cases.

I'll try to look into it, for now we can just skip this model, or perform the checks in a way which does not use those module name (e.g. if the actual module name is unique, we can simply use if hasattr(module, "module_name")

@Cyrilvallez Cyrilvallez left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @bvantuan! Sorry for being late on this! Very happy to see this new batch! 🤗 Still some points to fix though, especially I'm not sure why you added 0.02 factors (apparently) randomly at some places? Did I miss something?

Comment on lines -855 to +851
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
module.weight.data.normal_(mean=0.0, std=factor * 0.02)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why add a random 0.02 here???

Comment on lines -859 to +855
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
module.weight.data.normal_(mean=0.0, std=factor * 0.02)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here??

fc_std = (2 * self.config.hidden_size) ** -0.5
for block in module.transformer.resblocks:
nn.init.normal_(block.attn.in_proj_weight, std=attn_std * std)
nn.init.normal_(block.attn.in_proj_weight, std=attn_std * factor)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not change files only to rename a variable, which had a perfectly fine name before 🙂

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.

By convention, it is better to use factor = self.config.initializer_factor

Comment on lines -473 to +474
if isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
if isinstance(module, (nn.Linear, nn.ConvTranspose2d)):
module.weight.data.normal_(mean=0.0, std=factor * 0.02)
if module.bias is not None:
module.bias.data.zero_()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would overwrite most of the others, so need to make it coherent here

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.

I didn’t see the nn.ConvTranspose2d initialization code in the original implementation, so I applied the same initialization approach as used for Linear.

Comment on lines -1991 to +2002
class EsmForProteinFolding(EsmPreTrainedModel):
class EsmForProteinFolding(EsmFoldPreTrainedModel):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤯🤯

Comment on lines +1443 to +1444
nn.init.xavier_uniform_(module.get_submodule("0").weight, gain=xavier_std)
nn.init.constant_(module.get_submodule("0").bias, 0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's initialize the correct module directly instead of that

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.

Does that mean keeping the original code?

module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=factor)
module.weight.data.normal_(mean=0.0, std=factor * 0.02)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why??

module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=factor)
module.weight.data.normal_(mean=0.0, std=factor * 0.02)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and here?

Comment on lines -553 to +550
nn.init.normal_(module.position_embedding, std=self.config.initializer_factor)
nn.init.normal_(module.position_embedding, std=factor * 0.02)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why 0.02 again here?

Comment on lines -559 to +558
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
module.weight.data.normal_(mean=0.0, std=factor * 0.02)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again, no 0.02!

@bvantuan

Copy link
Copy Markdown
Contributor Author

Hi @Cyrilvallez ! Thank you so much for reviewing and responding to my issue, as always😊. Yes, indeed, when using f hasattr(module, "module_name") for those two modules Data2VecAudioModel and Data2VecAudioForXVector, it worked.

For the term factor * 0.02, first we need to clarify the difference between config.initializer_factor and config.initializer_range. As far as I know, config.initializer_factor typically defaults to 1.0 and serves as a scaling factor for the initialization of all weight matrices within a model. config.initializer_range defines the standard deviation used for initializing the weights of a model (a common default value is 0.02). It is unusual to initialize the weights using config.initializer_factor as the standard deviation, because that value is excessively large for this purpose. Also, the term factor * 0.02 is sometimes used in the repository, for example in CLVP.

if isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=factor * 0.02)
elif isinstance(module, (nn.Linear, Conv1D, nn.Conv1d)):
module.weight.data.normal_(mean=0.0, std=factor * 0.02)
if module.bias is not None:
module.bias.data.zero_()

The original implementation of X-CLIP also hardcodes 0.02 for the Linear module:
https://github.com/microsoft/VideoX/blob/1744b2159c3d11694f94dab4fcde8660c685e79a/X-CLIP/models/mit.py#L40-L49

@bvantuan bvantuan marked this pull request as ready for review August 14, 2025 09:38
@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: altclip, bert, blip, bridgetower, camembert, chinese_clip, clip, clipseg, conditional_detr, cvt, data2vec, deformable_detr, detr, ernie, esm, groupvit

@Cyrilvallez

Copy link
Copy Markdown
Member

Yeah but unfortunately, once again if those old models were badly implemented at the time, it's hard to change it now. So this would be another PR, which would be quite breaking, so need to be separate. Happy to review such a PR in the future if you are open to it! In the meantime, this PR should keep its focus on adding missing initializations only, i.e. modules that are not taken into account - it should not change the default std of existing inits 🤗

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.

2 participants