Recursively traverse module and its children to replace all instances of ``torch.nn.modules.batchnorm._BatchNorm`` with `SplitBatchnorm2d`. Args: module (torch.nn.Module): input module num_splits: number of separate batchnorm layers to split input across Example::
(module, num_splits=2)
| 39 | |
| 40 | |
| 41 | def convert_splitbn_model(module, num_splits=2): |
| 42 | """ |
| 43 | Recursively traverse module and its children to replace all instances of |
| 44 | ``torch.nn.modules.batchnorm._BatchNorm`` with `SplitBatchnorm2d`. |
| 45 | Args: |
| 46 | module (torch.nn.Module): input module |
| 47 | num_splits: number of separate batchnorm layers to split input across |
| 48 | Example:: |
| 49 | >>> # model is an instance of torch.nn.Module |
| 50 | >>> model = timm.models.convert_splitbn_model(model, num_splits=2) |
| 51 | """ |
| 52 | mod = module |
| 53 | if isinstance(module, torch.nn.modules.instancenorm._InstanceNorm): |
| 54 | return module |
| 55 | if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): |
| 56 | mod = SplitBatchNorm2d( |
| 57 | module.num_features, module.eps, module.momentum, module.affine, |
| 58 | module.track_running_stats, num_splits=num_splits) |
| 59 | mod.running_mean = module.running_mean |
| 60 | mod.running_var = module.running_var |
| 61 | mod.num_batches_tracked = module.num_batches_tracked |
| 62 | if module.affine: |
| 63 | mod.weight.data = module.weight.data.clone().detach() |
| 64 | mod.bias.data = module.bias.data.clone().detach() |
| 65 | for aux in mod.aux_bn: |
| 66 | aux.running_mean = module.running_mean.clone() |
| 67 | aux.running_var = module.running_var.clone() |
| 68 | aux.num_batches_tracked = module.num_batches_tracked.clone() |
| 69 | if module.affine: |
| 70 | aux.weight.data = module.weight.data.clone().detach() |
| 71 | aux.bias.data = module.bias.data.clone().detach() |
| 72 | for name, child in module.named_children(): |
| 73 | mod.add_module(name, convert_splitbn_model(child, num_splits=num_splits)) |
| 74 | del module |
| 75 | return mod |
nothing calls this directly
no test coverage detected