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

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
  1. from collections import OrderedDict
  2. import copy
  3. from typing import List, Union, Optional
  4. import torch
  5. from torch import nn
  6. from omegaconf.listconfig import ListConfig
  7. from super_gradients.common import UpsampleMode
  8. class MultiOutputModule(nn.Module):
  9. """
  10. This module wraps around a container nn.Module (such as Module, Sequential and ModuleList) and allows to extract
  11. multiple output from its inner modules on each forward call() (as a list of output tensors)
  12. note: the default output of the wrapped module will not be added to the output list by default. To get
  13. the default output in the outputs list, explicitly include its path in the @output_paths parameter
  14. i.e.
  15. for module:
  16. Sequential(
  17. (0): Sequential(
  18. (0): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
  19. (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  20. (2): ReLU6(inplace=True)
  21. ) ===================================>>
  22. (1): InvertedResidual(
  23. (conv): Sequential(
  24. (0): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32, bias=False)
  25. (1): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  26. (2): ReLU6(inplace=True) ===================================>>
  27. (3): Conv2d(32, 16, kernel_size=(1, 1), stride=(1, 1), bias=False)
  28. (4): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  29. )
  30. )
  31. )
  32. and paths:
  33. [0, [1, 'conv', 2]]
  34. the output are marked with arrows
  35. """
  36. def __init__(self, module: nn.Module, output_paths: list, prune: bool = True):
  37. """
  38. :param module: The wrapped container module
  39. :param output_paths: a list of lists or keys containing the canonical paths to the outputs
  40. i.e. [3, [4, 'conv', 5], 7] will extract outputs of layers 3, 7 and 4->conv->5
  41. """
  42. super().__init__()
  43. self.output_paths = output_paths
  44. self._modules["0"] = module
  45. self._outputs_lists = {}
  46. for path in output_paths:
  47. child = self._get_recursive(module, path)
  48. child.register_forward_hook(hook=self.save_output_hook)
  49. # PRUNE THE MODULE TO SUPPORT ALL PROVIDED OUTPUT_PATHS BUT REMOVE ALL REDUNDANT LAYERS
  50. if prune:
  51. self._prune(module, output_paths)
  52. def save_output_hook(self, _, input, output):
  53. self._outputs_lists[input[0].device].append(output)
  54. def forward(self, x) -> list:
  55. self._outputs_lists[x.device] = []
  56. self._modules["0"](x)
  57. outputs = self._outputs_lists[x.device]
  58. self._outputs_lists = {}
  59. return outputs
  60. def _get_recursive(self, module: nn.Module, path) -> nn.Module:
  61. """recursively look for a module using a path"""
  62. if not isinstance(path, (list, ListConfig)):
  63. return module._modules[str(path)]
  64. elif len(path) == 1:
  65. return module._modules[str(path[0])]
  66. else:
  67. return self._get_recursive(module._modules[str(path[0])], path[1:])
  68. def _prune(self, module: nn.Module, output_paths: list):
  69. """
  70. Recursively prune the module to support all provided output_paths but remove all redundant layers
  71. """
  72. last_index = -1
  73. last_key = None
  74. # look for the last key from all paths
  75. for path in output_paths:
  76. key = path[0] if isinstance(path, (list, ListConfig)) else path
  77. index = list(module._modules).index(str(key))
  78. if index > last_index:
  79. last_index = index
  80. last_key = key
  81. module._modules = self._slice_odict(module._modules, 0, last_index + 1)
  82. next_level_paths = []
  83. for path in output_paths:
  84. if isinstance(path, (list, ListConfig)) and path[0] == last_key and len(path) > 1:
  85. next_level_paths.append(path[1:])
  86. if len(next_level_paths) > 0:
  87. self._prune(module._modules[str(last_key)], next_level_paths)
  88. def _slice_odict(self, odict: OrderedDict, start: int, end: int):
  89. """Slice an OrderedDict in the same logic list,tuple... are sliced"""
  90. return OrderedDict([(k, v) for (k, v) in odict.items() if k in list(odict.keys())[start:end]])
  91. def _replace_activations_recursive(module: nn.Module, new_activation: nn.Module, activations_to_replace: List[type]):
  92. """
  93. A helper called in replace_activations(...)
  94. """
  95. for n, m in module.named_children():
  96. if type(m) in activations_to_replace:
  97. setattr(module, n, copy.deepcopy(new_activation))
  98. else:
  99. _replace_activations_recursive(m, new_activation, activations_to_replace)
  100. def replace_activations(module: nn.Module, new_activation: nn.Module, activations_to_replace: List[type]):
  101. """
  102. Recursively go through module and replaces each activation in activations_to_replace with a copy of new_activation
  103. :param module: a module that will be changed inplace
  104. :param new_activation: a sample of a new activation (will be copied)
  105. :param activations_to_replace: types of activations to replace, each must be a subclass of nn.Module
  106. """
  107. # check arguments once before the recursion
  108. assert isinstance(new_activation, nn.Module), "new_activation should be nn.Module"
  109. assert all(
  110. [isinstance(t, type) and issubclass(t, nn.Module) for t in activations_to_replace]
  111. ), "activations_to_replace should be types that are subclasses of nn.Module"
  112. # do the replacement
  113. _replace_activations_recursive(module, new_activation, activations_to_replace)
  114. def fuse_repvgg_blocks_residual_branches(model: nn.Module):
  115. """
  116. Call fuse_block_residual_branches for all repvgg blocks in the model
  117. :param model: torch.nn.Module with repvgg blocks. Doesn't have to be entirely consists of repvgg.
  118. :type model: torch.nn.Module
  119. """
  120. assert not model.training, "To fuse RepVGG block residual branches, model must be on eval mode"
  121. for module in model.modules():
  122. if hasattr(module, "fuse_block_residual_branches"):
  123. module.fuse_block_residual_branches()
  124. model.build_residual_branches = False
  125. class NormalizationAdapter(torch.nn.Module):
  126. """
  127. Denormalizes input by mean_original, std_original, then normalizes by mean_required, std_required.
  128. Used in KD training where teacher expects data normalized by mean_required, std_required.
  129. mean_original, std_original, mean_required, std_required are all list-like objects of length that's equal to the
  130. number of input channels.
  131. """
  132. def __init__(self, mean_original, std_original, mean_required, std_required):
  133. super(NormalizationAdapter, self).__init__()
  134. mean_original = torch.tensor(mean_original).unsqueeze(-1).unsqueeze(-1)
  135. std_original = torch.tensor(std_original).unsqueeze(-1).unsqueeze(-1)
  136. mean_required = torch.tensor(mean_required).unsqueeze(-1).unsqueeze(-1)
  137. std_required = torch.tensor(std_required).unsqueeze(-1).unsqueeze(-1)
  138. self.additive = torch.nn.Parameter((mean_original - mean_required) / std_original)
  139. self.multiplier = torch.nn.Parameter(std_original / std_required)
  140. def forward(self, x):
  141. x = (x + self.additive) * self.multiplier
  142. return x
  143. def make_upsample_module(scale_factor: int, upsample_mode: Union[str, UpsampleMode], align_corners: Optional[bool] = None):
  144. """
  145. Factory method for creating upsampling modules.
  146. :param scale_factor: upsample scale factor
  147. :param upsample_mode: see UpsampleMode for supported options.
  148. :return: nn.Module
  149. """
  150. upsample_mode = upsample_mode.value if isinstance(upsample_mode, UpsampleMode) else upsample_mode
  151. if upsample_mode == UpsampleMode.NEAREST.value:
  152. # Prevent ValueError when passing align_corners with nearest mode.
  153. module = nn.Upsample(scale_factor=scale_factor, mode=upsample_mode)
  154. elif upsample_mode in [UpsampleMode.BILINEAR.value, UpsampleMode.BICUBIC.value]:
  155. module = nn.Upsample(scale_factor=scale_factor, mode=upsample_mode, align_corners=align_corners)
  156. else:
  157. raise NotImplementedError(f"Upsample mode: `{upsample_mode}` is not supported.")
  158. return module
Discard
Tip!

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