-
Notifications
You must be signed in to change notification settings - Fork 31.2k
Much more efficient and clear weight initialization and tie weights #42191
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+3,341
−5,443
Merged
Changes from all commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
da26896
everything untilo informer
Cyrilvallez d561c6f
everything until perceiver
Cyrilvallez ceea305
all of them finally
Cyrilvallez 187bb8e
style
Cyrilvallez 2cd2add
replace by transformers init everywhere
Cyrilvallez 6bdffed
use relative import instead
Cyrilvallez d25fe72
deprecated models
Cyrilvallez 82899ac
style
Cyrilvallez a4ab598
start contexts
Cyrilvallez 192151e
small fixes
Cyrilvallez 5efa9a8
fix modular
Cyrilvallez c882d60
remove class switch
Cyrilvallez 22a55a3
do not initialize tied weights
Cyrilvallez 694440b
typo
Cyrilvallez 5a0174e
fix
Cyrilvallez 5423e06
improve
Cyrilvallez 9b7ace5
improve comments
Cyrilvallez 4acef54
improve
Cyrilvallez c58d243
improve
Cyrilvallez 2edc8c1
fix zamba
Cyrilvallez 2f40139
fix import
Cyrilvallez 2dd4e00
add the post_init
Cyrilvallez 3ede287
more post_init
Cyrilvallez 86f7169
fix
Cyrilvallez 706799e
protect
Cyrilvallez 1da2d27
more post_init
Cyrilvallez 83e0ada
fix
Cyrilvallez 50187a9
fixes
Cyrilvallez 16173f0
fix
Cyrilvallez bae372a
fix
Cyrilvallez 8500bcf
switch flag name
Cyrilvallez cdada86
more fixes
Cyrilvallez 99961fc
fixes
Cyrilvallez 557ef75
fixes
Cyrilvallez 2dd0817
Merge branch 'main' into better-init-2
Cyrilvallez 912440b
copies
Cyrilvallez acdaf9e
fix
Cyrilvallez cc10ea4
finally find the culprit
Cyrilvallez 627e77b
style
Cyrilvallez db42923
last small
Cyrilvallez 17115a2
big bird
Cyrilvallez bbdc5a5
better
Cyrilvallez 3a12aec
update init check
Cyrilvallez 9beb88c
final touch
Cyrilvallez 6092804
do it everywhere
Cyrilvallez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| # Copyright 2025 The HuggingFace Team. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| import sys | ||
| from collections import defaultdict | ||
| from contextlib import contextmanager | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| # Record all the torch primitives in advance, so that we can use them without them being modified when we patch torch | ||
| # in context managers | ||
| TORCH_INIT_FUNCTIONS = { | ||
| "uniform_": torch.nn.init.uniform_, | ||
| "normal_": torch.nn.init.normal_, | ||
| "constant_": torch.nn.init.constant_, | ||
| "ones_": torch.nn.init.ones_, | ||
| "zeros_": torch.nn.init.zeros_, | ||
| "eye_": torch.nn.init.eye_, | ||
| "dirac_": torch.nn.init.dirac_, | ||
| "xavier_uniform_": torch.nn.init.xavier_uniform_, | ||
| "xavier_normal_": torch.nn.init.xavier_normal_, | ||
| "kaiming_uniform_": torch.nn.init.kaiming_uniform_, | ||
| "kaiming_normal_": torch.nn.init.kaiming_normal_, | ||
| "trunc_normal_": torch.nn.init.trunc_normal_, | ||
| "orthogonal_": torch.nn.init.orthogonal_, | ||
| "sparse_": torch.nn.init.sparse_, | ||
| } | ||
|
|
||
|
|
||
| def uniform_( | ||
| tensor: torch.Tensor, a: float = 0.0, b: float = 1.0, generator: torch.Generator | None = None | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["uniform_"](tensor, a=a, b=b, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def normal_( | ||
| tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, generator: torch.Generator | None = None | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["normal_"](tensor, mean=mean, std=std, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def constant_(tensor: torch.Tensor, val: float) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["constant_"](tensor, val=val) | ||
| return tensor | ||
|
|
||
|
|
||
| def ones_(tensor: torch.Tensor) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["ones_"](tensor) | ||
| return tensor | ||
|
|
||
|
|
||
| def zeros_(tensor: torch.Tensor) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["zeros_"](tensor) | ||
| return tensor | ||
|
|
||
|
|
||
| def eye_(tensor: torch.Tensor) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["eye_"](tensor) | ||
| return tensor | ||
|
|
||
|
|
||
| def dirac_(tensor: torch.Tensor, groups: int = 1) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["dirac_"](tensor, groups=groups) | ||
| return tensor | ||
|
|
||
|
|
||
| def xavier_uniform_(tensor: torch.Tensor, gain: float = 1.0, generator: torch.Generator | None = None) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["xavier_uniform_"](tensor, gain=gain, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def xavier_normal_(tensor: torch.Tensor, gain: float = 1.0, generator: torch.Generator | None = None) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["xavier_normal_"](tensor, gain=gain, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def kaiming_uniform_( | ||
| tensor: torch.Tensor, | ||
| a: float = 0, | ||
| mode: str = "fan_in", | ||
| nonlinearity: str = "leaky_relu", | ||
| generator: torch.Generator | None = None, | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["kaiming_uniform_"]( | ||
| tensor, a=a, mode=mode, nonlinearity=nonlinearity, generator=generator | ||
| ) | ||
| return tensor | ||
|
|
||
|
|
||
| def kaiming_normal_( | ||
| tensor: torch.Tensor, | ||
| a: float = 0, | ||
| mode: str = "fan_in", | ||
| nonlinearity: str = "leaky_relu", | ||
| generator: torch.Generator | None = None, | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["kaiming_normal_"]( | ||
| tensor, a=a, mode=mode, nonlinearity=nonlinearity, generator=generator | ||
| ) | ||
| return tensor | ||
|
|
||
|
|
||
| def trunc_normal_( | ||
| tensor: torch.Tensor, | ||
| mean: float = 0.0, | ||
| std: float = 1.0, | ||
| a: float = -2.0, | ||
| b: float = 2.0, | ||
| generator: torch.Generator | None = None, | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["trunc_normal_"](tensor, mean=mean, std=std, a=a, b=b, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def orthogonal_( | ||
| tensor: torch.Tensor, | ||
| gain: float = 1, | ||
| generator: torch.Generator | None = None, | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["orthogonal_"](tensor, gain=gain, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def sparse_( | ||
| tensor: torch.Tensor, sparsity: float, std: float = 0.01, generator: torch.Generator | None = None | ||
| ) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| return TORCH_INIT_FUNCTIONS["sparse_"](tensor, sparsity=sparsity, std=std, generator=generator) | ||
| return tensor | ||
|
|
||
|
|
||
| def copy_(tensor: torch.Tensor, other: torch.Tensor) -> torch.Tensor: | ||
| if not getattr(tensor, "_is_hf_initialized", False): | ||
| with torch.no_grad(): | ||
| return tensor.copy_(other) | ||
| return tensor | ||
|
|
||
|
|
||
| @contextmanager | ||
| def guard_torch_init_functions(): | ||
| """ | ||
| Guard the `torch.nn.init` primitive functions to behave exactly like the functions in this file, i.e. be | ||
| protected against the `_is_hf_initialized` flag to avoid re-init if the param was already loaded. | ||
|
|
||
| Usually, all models are using the init from `transformers` which are already guarded, but just to make extra sure | ||
| and for remote code, we also use this context manager. | ||
| """ | ||
| originals = defaultdict(dict) | ||
| try: | ||
| # Replace all torch funcs by the ones in this file | ||
| for name in TORCH_INIT_FUNCTIONS.keys(): | ||
| # Here, we need to check all modules imported, and hot patch all of them, as usually torch does | ||
| # something like `from torch.nn.init import xavier_uniform_` in their internals (e.g in torch.nn.modules, | ||
| # where MultiHeadAttention lives), so the function name is binded at import time and just doing | ||
| # `setattr(torch.nn.init, name, gloabls()[name])` is thus not enough | ||
| for module in sys.modules.values(): | ||
| if module and hasattr(module, name): | ||
| originals[module][name] = getattr(module, name) | ||
| setattr(module, name, globals()[name]) | ||
| yield | ||
| finally: | ||
| # Set back the original functions on all modules | ||
| for module, functions in originals.items(): | ||
| for name, func in functions.items(): | ||
| setattr(module, name, func) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this won't work for any tensor manipulation for any remote code / code outside our scope, but its
fineThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes I know, this is very unfortunate but we cannot really make it work for remote code 🥲