Skip to content
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

[Refactoring] Revise init_weight in BaseModule #905

Merged
merged 5 commits into from
Apr 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions mmcv/runner/base_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ def init_weight(self):
if not self._is_init:
if hasattr(self, 'init_cfg'):
initialize(self, self.init_cfg)
for module in self.children():
if 'init_weight' in dir(module):
module.init_weight()
for m in self.children():
if hasattr(m, 'init_weight'):
m.init_weight()
self._is_init = True
else:
warnings.warn(f'init_weight of {self.__class__.__name__} has '
Expand Down
8 changes: 7 additions & 1 deletion tests/test_runner/test_basemodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,10 +336,12 @@ def test_sequential_model_weight_init():
assert torch.equal(seq_model[1].conv2d.bias,
torch.full(seq_model[1].conv2d.bias.shape, 3.))
# inner init_cfg has highter priority
layers = [build_from_cfg(cfg, COMPONENTS) for cfg in seq_model_cfg]
seq_model = Sequential(
*layers,
init_cfg=dict(
type='Constant', layer=['Conv1d', 'Conv2d'], val=4., bias=5.))
seq_model.init_weight()
assert torch.equal(seq_model[0].conv1d.weight,
torch.full(seq_model[0].conv1d.weight.shape, 0.))
assert torch.equal(seq_model[0].conv1d.bias,
Expand Down Expand Up @@ -371,8 +373,12 @@ def test_modulelist_weight_init():
assert torch.equal(modellist[1].conv2d.bias,
torch.full(modellist[1].conv2d.bias.shape, 3.))
# inner init_cfg has highter priority
layers = [build_from_cfg(cfg, COMPONENTS) for cfg in models_cfg]
modellist = ModuleList(
layers, init_cfg=dict(type='Constant', val=4., bias=5.))
layers,
init_cfg=dict(
type='Constant', layer=['Conv1d', 'Conv2d'], val=4., bias=5.))
modellist.init_weight()
assert torch.equal(modellist[0].conv1d.weight,
torch.full(modellist[0].conv1d.weight.shape, 0.))
assert torch.equal(modellist[0].conv1d.bias,
Expand Down