Refactor initialization tests to check init from from_pretrained
#30451
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.
What does this PR do?
Adds a new test which checks that all model weights are correctly initialized when creating a model using
from_pretrained
. This was done by:test_initialization_from_pretrained
testtest_initialization_from_pretrained
andtest_initialization
into_test_models_weight_initialization
Motivation
A weight init bug in CLIP was highlighted in #30374.
When a model is created via a config, the layer weights are initialized with their default torch initialization i.e. with
parameter.reset_parameters()
.When a model is created with a checkpoint using
from_pretrained
, the model weights are not initialized, and are insteadtorch.empty
arrays. This is to speed up model creation: there's no need to initialize if we're going to use the checkpoint's weight.However, if the weight isn't in the checkpoint and doesn't have init behaviour specified in the model's
_init_weight
method, then the weight will remain empty.This can be tricky to catch if only part of the layer's weights are initialized. For example, in CLIP, the bias initialization is specified but not the
weight
. This means the Linear module will be marked as initialized even if this is partly True.The initialization bug wasn't caught in our test suite, despite test_initialization, because this test creates the model from the config, not from a checkpoint.
As this is difficult to correctly handle within the code itself, I propose adding a test which will at least catch when weights aren't properly covered in the
from_pretrained
scenarioBefore submitting
Pull Request section?
to it if that's the case.
documentation guidelines, and
here are tips on formatting docstrings.