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

(Idea, To Be Verified) feature: apply BN update for SWA model #299

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
24 changes: 23 additions & 1 deletion scripts/aux_swa.py → scripts/make_swa_model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

# Usage: python3 script/aux_swa.py [FINAL_EPOCH] [EPOCHS] [EPOCH_STEP]
# Usage: python3 script/make_swa_model.py [FINAL_EPOCH] [EPOCHS] [EPOCH_STEP]

import os
import sys
Expand Down Expand Up @@ -44,6 +44,28 @@ def _avg_fn(averaged_model_parameter, model_parameter, num_averaged):
model.load_state_dict(torch.load(os.path.join(model_dir, model_id)), strict=True)
swa_model.update_parameters(model)

# Update BN
# get averaged running stats from SWA model
averaged_running_stats = {}
for model_id in model_ids:
model.load_state_dict(torch.load(os.path.join(model_dir, model_id)), strict=True)
for name, module in dict(model.named_modules()).items():
if not issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm):
continue
if name not in averaged_running_stats:
averaged_running_stats[name] = {
'running_mean': torch.zeros_like(module.running_mean),
'running_var': torch.zeros_like(module.running_var),}
averaged_running_stats[name]['running_mean'] += module.running_mean / len(model_ids)
averaged_running_stats[name]['running_var'] += module.running_var / len(model_ids)

# set averaged running stats into SWA model
for name, module in dict(swa_model.module.named_modules()).items():
if issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm):
module.running_mean.copy_(averaged_running_stats[name]['running_mean'])
module.running_var.copy_(averaged_running_stats[name]['running_var'])

# Save SWA model
torch.save(swa_model.module.state_dict(), saved_model_path)

print('Saved %s' % saved_model_path)
Expand Down