Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

module_utils.py 8.4 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
  1. from collections import OrderedDict
  2. import copy
  3. from typing import List, Union, Tuple
  4. from torch import nn
  5. class MultiOutputModule(nn.Module):
  6. """
  7. This module wraps around a container nn.Module (such as Module, Sequential and ModuleList) and allows to extract
  8. multiple output from its inner modules on each forward call() (as a list of output tensors)
  9. note: the default output of the wrapped module will not be added to the output list by default. To get
  10. the default output in the outputs list, explicitly include its path in the @output_paths parameter
  11. i.e.
  12. for module:
  13. Sequential(
  14. (0): Sequential(
  15. (0): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
  16. (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  17. (2): ReLU6(inplace=True)
  18. ) ===================================>>
  19. (1): InvertedResidual(
  20. (conv): Sequential(
  21. (0): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32, bias=False)
  22. (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  23. (2): ReLU6(inplace=True) ===================================>>
  24. (3): Conv2d(32, 16, kernel_size=(1, 1), stride=(1, 1), bias=False)
  25. (4): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  26. )
  27. )
  28. )
  29. and paths:
  30. [0, [1, 'conv', 2]]
  31. the output are marked with arrows
  32. """
  33. def __init__(self, module: nn.Module, output_paths: list, prune: bool = True):
  34. """
  35. :param module: The wrapped container module
  36. :param output_paths: a list of lists or keys containing the canonical paths to the outputs
  37. i.e. [3, [4, 'conv', 5], 7] will extract outputs of layers 3, 7 and 4->conv->5
  38. """
  39. super().__init__()
  40. self.output_paths = output_paths
  41. self._modules['0'] = module
  42. self._outputs_lists = {}
  43. for path in output_paths:
  44. child = self._get_recursive(module, path)
  45. child.register_forward_hook(hook=self.save_output_hook)
  46. # PRUNE THE MODULE TO SUPPORT ALL PROVIDED OUTPUT_PATHS BUT REMOVE ALL REDUNDANT LAYERS
  47. if prune:
  48. self._prune(module, output_paths)
  49. def save_output_hook(self, _, input, output):
  50. self._outputs_lists[input[0].device].append(output)
  51. def forward(self, x) -> list:
  52. self._outputs_lists[x.device] = []
  53. self._modules['0'](x)
  54. return self._outputs_lists[x.device]
  55. def _get_recursive(self, module: nn.Module, path) -> nn.Module:
  56. """recursively look for a module using a path"""
  57. if not isinstance(path, list):
  58. return module._modules[str(path)]
  59. elif len(path) == 1:
  60. return module._modules[str(path[0])]
  61. else:
  62. return self._get_recursive(module._modules[str(path[0])], path[1:])
  63. def _prune(self, module: nn.Module, output_paths: list):
  64. """
  65. Recursively prune the module to support all provided output_paths but remove all redundant layers
  66. """
  67. last_index = -1
  68. last_key = None
  69. # look for the last key from all paths
  70. for path in output_paths:
  71. key = path[0] if isinstance(path, list) else path
  72. index = list(module._modules).index(str(key))
  73. if index > last_index:
  74. last_index = index
  75. last_key = key
  76. module._modules = self._slice_odict(module._modules, 0, last_index + 1)
  77. next_level_paths = []
  78. for path in output_paths:
  79. if isinstance(path, list) and path[0] == last_key and len(path) > 1:
  80. next_level_paths.append(path[1:])
  81. if len(next_level_paths) > 0:
  82. self._prune(module._modules[str(last_key)], next_level_paths)
  83. def _slice_odict(self, odict: OrderedDict, start: int, end: int):
  84. """Slice an OrderedDict in the same logic list,tuple... are sliced"""
  85. return OrderedDict([
  86. (k, v) for (k, v) in odict.items()
  87. if k in list(odict.keys())[start:end]
  88. ])
  89. def _replace_activations_recursive(module: nn.Module, new_activation: nn.Module, activations_to_replace: List[type]):
  90. """
  91. A helper called in replace_activations(...)
  92. """
  93. for n, m in module.named_children():
  94. if type(m) in activations_to_replace:
  95. setattr(module, n, copy.deepcopy(new_activation))
  96. else:
  97. _replace_activations_recursive(m, new_activation, activations_to_replace)
  98. def replace_activations(module: nn.Module, new_activation: nn.Module, activations_to_replace: List[type]):
  99. """
  100. Recursively go through module and replaces each activation in activations_to_replace with a copy of new_activation
  101. :param module: a module that will be changed inplace
  102. :param new_activation: a sample of a new activation (will be copied)
  103. :param activations_to_replace: types of activations to replace, each must be a subclass of nn.Module
  104. """
  105. # check arguments once before the recursion
  106. assert isinstance(new_activation, nn.Module), 'new_activation should be nn.Module'
  107. assert all([isinstance(t, type) and issubclass(t, nn.Module) for t in activations_to_replace]), \
  108. 'activations_to_replace should be types that are subclasses of nn.Module'
  109. # do the replacement
  110. _replace_activations_recursive(module, new_activation, activations_to_replace)
  111. def fuse_repvgg_blocks_residual_branches(model: nn.Module):
  112. '''
  113. Call fuse_block_residual_branches for all repvgg blocks in the model
  114. :param model: torch.nn.Module with repvgg blocks. Doesn't have to be entirely consists of repvgg.
  115. :type model: torch.nn.Module
  116. '''
  117. assert not model.training, "To fuse RepVGG block residual branches, model must be on eval mode"
  118. for module in model.modules():
  119. if hasattr(module, 'fuse_block_residual_branches'):
  120. module.fuse_block_residual_branches()
  121. model.build_residual_branches = False
  122. class ConvBNReLU(nn.Module):
  123. """
  124. Class for Convolution2d-Batchnorm2d-Relu layer. Default behaviour is Conv-BN-Relu. To exclude Batchnorm module use
  125. `use_normalization=False`, to exclude Relu activation use `use_activation=False`.
  126. For convolution arguments documentation see `nn.Conv2d`.
  127. For batchnorm arguments documentation see `nn.BatchNorm2d`.
  128. For relu arguments documentation see `nn.Relu`.
  129. """
  130. def __init__(self,
  131. in_channels: int,
  132. out_channels: int,
  133. kernel_size: Union[int, Tuple[int, int]],
  134. stride: Union[int, Tuple[int, int]] = 1,
  135. padding: Union[int, Tuple[int, int]] = 0,
  136. dilation: Union[int, Tuple[int, int]] = 1,
  137. groups: int = 1,
  138. bias: bool = True,
  139. padding_mode: str = 'zeros',
  140. use_normalization: bool = True,
  141. eps: float = 1e-5,
  142. momentum: float = 0.1,
  143. affine: bool = True,
  144. track_running_stats: bool = True,
  145. device=None,
  146. dtype=None,
  147. use_activation: bool = True,
  148. inplace: bool = False):
  149. super(ConvBNReLU, self).__init__()
  150. self.seq = nn.Sequential()
  151. self.seq.add_module("conv", nn.Conv2d(in_channels,
  152. out_channels,
  153. kernel_size=kernel_size,
  154. stride=stride,
  155. padding=padding,
  156. dilation=dilation,
  157. groups=groups,
  158. bias=bias,
  159. padding_mode=padding_mode))
  160. if use_normalization:
  161. self.seq.add_module("bn", nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum, affine=affine,
  162. track_running_stats=track_running_stats, device=device,
  163. dtype=dtype))
  164. if use_activation:
  165. self.seq.add_module("relu", nn.ReLU(inplace=inplace))
  166. def forward(self, x):
  167. return self.seq(x)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...