MCPcopy Create free account
hub / github.com/MiniMax-AI/VTP / freeze_batch_norm_2d

Function freeze_batch_norm_2d

vtp/models/utils/text_utils.py:30–66  ·  view source on GitHub ↗

Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and returned. Otherwise, the module is walked recursively and submodu

(module, module_match={}, name='')

Source from the content-addressed store, hash-verified

28 return model.module if hasattr(model, 'module') else model
29
30def freeze_batch_norm_2d(module, module_match={}, name=''):
31 """
32 Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
33 itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
34 returned. Otherwise, the module is walked recursively and submodules are converted in place.
35
36 Args:
37 module (torch.nn.Module): Any PyTorch module.
38 module_match (dict): Dictionary of full module names to freeze (all if empty)
39 name (str): Full module name (prefix)
40
41 Returns:
42 torch.nn.Module: Resulting module
43
44 Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
45 """
46 res = module
47 is_match = True
48 if module_match:
49 is_match = name in module_match
50 if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)):
51 res = FrozenBatchNorm2d(module.num_features)
52 res.num_features = module.num_features
53 res.affine = module.affine
54 if module.affine:
55 res.weight.data = module.weight.data.clone().detach()
56 res.bias.data = module.bias.data.clone().detach()
57 res.running_mean.data = module.running_mean.data
58 res.running_var.data = module.running_var.data
59 res.eps = module.eps
60 else:
61 for child_name, child in module.named_children():
62 full_child_name = '.'.join([name, child_name]) if name else child_name
63 new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
64 if new_child is not child:
65 res.add_module(child_name, new_child)
66 return res
67
68
69# From PyTorch internals

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected