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

#438 Feature/sg 344 refactor modules

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-344-refactor-modules
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
  1. from typing import Union, Tuple
  2. from torch import nn
  3. from .conv_bn_act_block import ConvBNAct
  4. from .repvgg_block import RepVGGBlock
  5. from .se_blocks import SEBlock
  6. def ConvBNReLU(
  7. in_channels: int,
  8. out_channels: int,
  9. kernel_size: Union[int, Tuple[int, int]],
  10. stride: Union[int, Tuple[int, int]] = 1,
  11. padding: Union[int, Tuple[int, int]] = 0,
  12. dilation: Union[int, Tuple[int, int]] = 1,
  13. groups: int = 1,
  14. bias: bool = True,
  15. padding_mode: str = "zeros",
  16. use_normalization: bool = True,
  17. eps: float = 1e-5,
  18. momentum: float = 0.1,
  19. affine: bool = True,
  20. track_running_stats: bool = True,
  21. device=None,
  22. dtype=None,
  23. use_activation: bool = True,
  24. inplace: bool = False,
  25. ):
  26. """
  27. Class for Convolution2d-Batchnorm2d-Relu layer. Default behaviour is Conv-BN-Relu. To exclude Batchnorm module use
  28. `use_normalization=False`, to exclude Relu activation use `use_activation=False`.
  29. It exists to keep backward compatibility and will be superseeded by ConvBNAct in future releases.
  30. For new classes please use ConvBNAct instead.
  31. For convolution arguments documentation see `nn.Conv2d`.
  32. For batchnorm arguments documentation see `nn.BatchNorm2d`.
  33. For relu arguments documentation see `nn.Relu`.
  34. """
  35. return ConvBNAct(
  36. in_channels=in_channels,
  37. out_channels=out_channels,
  38. kernel_size=kernel_size,
  39. stride=stride,
  40. padding=padding,
  41. dilation=dilation,
  42. groups=groups,
  43. bias=bias,
  44. padding_mode=padding_mode,
  45. use_normalization=use_normalization,
  46. eps=eps,
  47. momentum=momentum,
  48. affine=affine,
  49. track_running_stats=track_running_stats,
  50. device=device,
  51. dtype=dtype,
  52. activation_type=nn.ReLU if use_activation else None,
  53. activation_kwargs=dict(inplace=inplace),
  54. )
  55. __all__ = ["ConvBNAct", "RepVGGBlock", "SEBlock", "ConvBNReLU"]
Discard
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
  1. from typing import Union, Tuple, Type
  2. from torch import nn
  3. class ConvBNAct(nn.Module):
  4. """
  5. Class for Convolution2d-Batchnorm2d-Activation layer.
  6. Default behaviour is Conv-BN-Act. To exclude Batchnorm module use
  7. `use_normalization=False`, to exclude activation use `activation_type=None`.
  8. For convolution arguments documentation see `nn.Conv2d`.
  9. For batchnorm arguments documentation see `nn.BatchNorm2d`.
  10. """
  11. def __init__(
  12. self,
  13. in_channels: int,
  14. out_channels: int,
  15. kernel_size: Union[int, Tuple[int, int]],
  16. padding: Union[int, Tuple[int, int]],
  17. activation_type: Type[nn.Module],
  18. stride: Union[int, Tuple[int, int]] = 1,
  19. dilation: Union[int, Tuple[int, int]] = 1,
  20. groups: int = 1,
  21. bias: bool = True,
  22. padding_mode: str = "zeros",
  23. use_normalization: bool = True,
  24. eps: float = 1e-5,
  25. momentum: float = 0.1,
  26. affine: bool = True,
  27. track_running_stats: bool = True,
  28. device=None,
  29. dtype=None,
  30. activation_kwargs=None,
  31. ):
  32. super().__init__()
  33. if activation_kwargs is None:
  34. activation_kwargs = {}
  35. self.seq = nn.Sequential()
  36. self.seq.add_module(
  37. "conv",
  38. nn.Conv2d(
  39. in_channels,
  40. out_channels,
  41. kernel_size=kernel_size,
  42. stride=stride,
  43. padding=padding,
  44. dilation=dilation,
  45. groups=groups,
  46. bias=bias,
  47. padding_mode=padding_mode,
  48. ),
  49. )
  50. if use_normalization:
  51. self.seq.add_module(
  52. "bn",
  53. nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_running_stats, device=device, dtype=dtype),
  54. )
  55. if activation_type is not None:
  56. self.seq.add_module("act", activation_type(**activation_kwargs))
  57. def forward(self, x):
  58. return self.seq(x)
Discard
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
197
198
199
200
201
202
203
204
  1. from typing import Type, Union, Mapping, Any
  2. import numpy as np
  3. import torch
  4. from torch import nn
  5. class RepVGGBlock(nn.Module):
  6. """
  7. Repvgg block consists of three branches
  8. 3x3: a branch of a 3x3 Convolution + BatchNorm + Activation
  9. 1x1: a branch of a 1x1 Convolution + BatchNorm + Activation
  10. no_conv_branch: a branch with only BatchNorm which will only be used if
  11. input channel == output channel and use_residual_connection is True
  12. (usually in all but the first block of each stage)
  13. """
  14. def __init__(
  15. self,
  16. in_channels,
  17. out_channels,
  18. activation_type: Type[nn.Module],
  19. se_type: Type[nn.Module],
  20. stride=1,
  21. dilation=1,
  22. groups=1,
  23. activation_kwargs: Union[Mapping[str, Any], None] = None,
  24. se_kwargs: Union[Mapping[str, Any], None] = None,
  25. build_residual_branches: bool = True,
  26. use_residual_connection: bool = True,
  27. use_alpha: bool = False,
  28. ):
  29. """
  30. :param in_channels: Number of input channels
  31. :param out_channels: Number of output channels
  32. :param activation_type: Type of the nonlinearity
  33. :param se_type: Type of the se block (Use nn.Identity to disable SE)
  34. :param stride: Output stride
  35. :param dilation: Dilation factor for 3x3 conv
  36. :param groups: Number of groups used in convolutions
  37. :param activation_kwargs: Additional arguments for instantiating activation module.
  38. :param se_kwargs: Additional arguments for instantiating SE module.
  39. :param build_residual_branches: Whether to initialize block with already fused paramters (for deployment)
  40. :param use_residual_connection: Whether to add input x to the output (Enabled in RepVGG, disabled in PP-Yolo)
  41. :param use_alpha: If True, enables additional learnable weighting parameter for 1x1 branch (PP-Yolo-E Plus)
  42. """
  43. super().__init__()
  44. if activation_kwargs is None:
  45. activation_kwargs = {}
  46. if se_kwargs is None:
  47. se_kwargs = {}
  48. self.groups = groups
  49. self.in_channels = in_channels
  50. self.nonlinearity = activation_type(**activation_kwargs)
  51. self.se = se_type(**se_kwargs)
  52. if use_residual_connection and out_channels == in_channels and stride == 1:
  53. self.no_conv_branch = nn.BatchNorm2d(num_features=in_channels)
  54. else:
  55. self.no_conv_branch = None
  56. self.branch_3x3 = self._conv_bn(
  57. in_channels=in_channels,
  58. out_channels=out_channels,
  59. dilation=dilation,
  60. kernel_size=3,
  61. stride=stride,
  62. padding=1,
  63. groups=groups,
  64. )
  65. self.branch_1x1 = self._conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, groups=groups)
  66. if use_alpha:
  67. self.alpha = torch.nn.Parameter(torch.tensor([1.0]), requires_grad=True)
  68. else:
  69. self.alpha = 1
  70. if not build_residual_branches:
  71. self.fuse_block_residual_branches()
  72. else:
  73. self.build_residual_branches = True
  74. def forward(self, inputs):
  75. if not self.build_residual_branches:
  76. return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
  77. if self.no_conv_branch is None:
  78. id_out = 0
  79. else:
  80. id_out = self.no_conv_branch(inputs)
  81. return self.nonlinearity(self.se(self.branch_3x3(inputs) + self.alpha * self.branch_1x1(inputs) + id_out))
  82. def _get_equivalent_kernel_bias(self):
  83. """
  84. Fuses the 3x3, 1x1 and identity branches into a single 3x3 conv layer
  85. """
  86. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.branch_3x3)
  87. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.branch_1x1)
  88. kernelid, biasid = self._fuse_bn_tensor(self.no_conv_branch)
  89. return kernel3x3 + self.alpha * self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + self.alpha * bias1x1 + biasid
  90. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  91. """
  92. padding the 1x1 convolution weights with zeros to be able to fuse the 3x3 conv layer with the 1x1
  93. :param kernel1x1: weights of the 1x1 convolution
  94. :type kernel1x1:
  95. :return: padded 1x1 weights
  96. :rtype:
  97. """
  98. if kernel1x1 is None:
  99. return 0
  100. else:
  101. return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  102. def _fuse_bn_tensor(self, branch):
  103. """
  104. Fusing of the batchnorm into the conv layer.
  105. If the branch is the identity branch (no conv) the kernel will simply be eye.
  106. :param branch:
  107. :type branch:
  108. :return:
  109. :rtype:
  110. """
  111. if branch is None:
  112. return 0, 0
  113. if isinstance(branch, nn.Sequential):
  114. kernel = branch.conv.weight
  115. running_mean = branch.bn.running_mean
  116. running_var = branch.bn.running_var
  117. gamma = branch.bn.weight
  118. beta = branch.bn.bias
  119. eps = branch.bn.eps
  120. else:
  121. assert isinstance(branch, nn.BatchNorm2d)
  122. if not hasattr(self, "id_tensor"):
  123. input_dim = self.in_channels // self.groups
  124. kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
  125. for i in range(self.in_channels):
  126. kernel_value[i, i % input_dim, 1, 1] = 1
  127. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  128. kernel = self.id_tensor
  129. running_mean = branch.running_mean
  130. running_var = branch.running_var
  131. gamma = branch.weight
  132. beta = branch.bias
  133. eps = branch.eps
  134. std = (running_var + eps).sqrt()
  135. t = (gamma / std).reshape(-1, 1, 1, 1)
  136. return kernel * t, beta - running_mean * gamma / std
  137. def fuse_block_residual_branches(self):
  138. """
  139. converts a repvgg block from training model (with branches) to deployment mode (vgg like model)
  140. :return:
  141. :rtype:
  142. """
  143. if hasattr(self, "build_residual_branches") and not self.build_residual_branches:
  144. return
  145. kernel, bias = self._get_equivalent_kernel_bias()
  146. self.rbr_reparam = nn.Conv2d(
  147. in_channels=self.branch_3x3.conv.in_channels,
  148. out_channels=self.branch_3x3.conv.out_channels,
  149. kernel_size=self.branch_3x3.conv.kernel_size,
  150. stride=self.branch_3x3.conv.stride,
  151. padding=self.branch_3x3.conv.padding,
  152. dilation=self.branch_3x3.conv.dilation,
  153. groups=self.branch_3x3.conv.groups,
  154. bias=True,
  155. )
  156. self.rbr_reparam.weight.data = kernel
  157. self.rbr_reparam.bias.data = bias
  158. for para in self.parameters():
  159. para.detach_()
  160. self.__delattr__("branch_3x3")
  161. self.__delattr__("branch_1x1")
  162. if hasattr(self, "no_conv_branch"):
  163. self.__delattr__("no_conv_branch")
  164. if hasattr(self, "alpha"):
  165. self.__delattr__("alpha")
  166. self.build_residual_branches = False
  167. @staticmethod
  168. def _conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1, dilation=1):
  169. result = nn.Sequential()
  170. result.add_module(
  171. "conv",
  172. nn.Conv2d(
  173. in_channels=in_channels,
  174. out_channels=out_channels,
  175. kernel_size=kernel_size,
  176. stride=stride,
  177. padding=padding,
  178. groups=groups,
  179. bias=False,
  180. dilation=dilation,
  181. ),
  182. )
  183. result.add_module("bn", nn.BatchNorm2d(num_features=out_channels))
  184. return result
Discard
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
  1. import torch
  2. from torch import nn, Tensor
  3. import torch.nn.functional as F
  4. class SEBlock(nn.Module):
  5. """
  6. Spatial Squeeze and Channel Excitation Block (cSE).
  7. Figure 1, Variant a from https://arxiv.org/abs/1808.08127v1
  8. """
  9. def __init__(self, in_channels: int, internal_neurons: int):
  10. super(SEBlock, self).__init__()
  11. self.down = nn.Conv2d(in_channels=in_channels, out_channels=internal_neurons, kernel_size=1, stride=1, bias=True)
  12. self.up = nn.Conv2d(in_channels=internal_neurons, out_channels=in_channels, kernel_size=1, stride=1, bias=True)
  13. self.input_channels = in_channels
  14. def forward(self, inputs: Tensor) -> Tensor:
  15. x = F.avg_pool2d(inputs, kernel_size=inputs.size(3))
  16. x = self.down(x)
  17. x = F.relu(x)
  18. x = self.up(x)
  19. x = torch.sigmoid(x)
  20. x = x.view(-1, self.input_channels, 1, 1)
  21. return inputs * x
Discard
@@ -11,212 +11,13 @@ Based on https://github.com/DingXiaoH/RepVGG
 from typing import Union
 from typing import Union
 
 
 import torch.nn as nn
 import torch.nn as nn
-import numpy as np
-import torch
-import torch.nn.parallel
-import torch.optim
-import torch.utils.data
-import torch.utils.data.distributed
+
+from super_gradients.modules import RepVGGBlock, SEBlock
 from super_gradients.training.models.sg_module import SgModule
 from super_gradients.training.models.sg_module import SgModule
-import torch.nn.functional as F
 from super_gradients.training.utils.module_utils import fuse_repvgg_blocks_residual_branches
 from super_gradients.training.utils.module_utils import fuse_repvgg_blocks_residual_branches
 from super_gradients.training.utils.utils import get_param
 from super_gradients.training.utils.utils import get_param
 
 
 
 
-class SEBlock(nn.Module):
-    def __init__(self, input_channels, internal_neurons):
-        super(SEBlock, self).__init__()
-        self.down = nn.Conv2d(
-            in_channels=input_channels, out_channels=internal_neurons, kernel_size=1, stride=1, bias=True
-        )
-        self.up = nn.Conv2d(
-            in_channels=internal_neurons, out_channels=input_channels, kernel_size=1, stride=1, bias=True
-        )
-        self.input_channels = input_channels
-
-    def forward(self, inputs):
-        x = F.avg_pool2d(inputs, kernel_size=inputs.size(3))
-        x = self.down(x)
-        x = F.relu(x)
-        x = self.up(x)
-        x = torch.sigmoid(x)
-        x = x.view(-1, self.input_channels, 1, 1)
-        return inputs * x
-
-
-def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1, dilation=1):
-    result = nn.Sequential()
-    result.add_module(
-        "conv",
-        nn.Conv2d(
-            in_channels=in_channels,
-            out_channels=out_channels,
-            kernel_size=kernel_size,
-            stride=stride,
-            padding=padding,
-            groups=groups,
-            bias=False,
-            dilation=dilation,
-        ),
-    )
-    result.add_module("bn", nn.BatchNorm2d(num_features=out_channels))
-    return result
-
-
-class RepVGGBlock(nn.Module):
-    """
-    Repvgg block consists of three branches
-    3x3: a branch of a 3x3 convolution + batchnorm + relu
-    1x1: a branch of a 1x1 convolution + batchnorm + relu
-    no_conv_branch: a branch with only batchnorm which will only be used if input channel == output channel
-    (usually in all but the first block of each stage)
-    """
-
-    def __init__(
-        self,
-        in_channels,
-        out_channels,
-        kernel_size,
-        stride=1,
-        padding=0,
-        dilation=1,
-        groups=1,
-        build_residual_branches=True,
-        use_relu=True,
-        use_se=False,
-    ):
-
-        super(RepVGGBlock, self).__init__()
-
-        self.groups = groups
-        self.in_channels = in_channels
-
-        assert kernel_size == 3
-        assert padding == dilation
-
-        self.nonlinearity = nn.ReLU() if use_relu else nn.Identity()
-        self.se = nn.Identity() if not use_se else SEBlock(out_channels, internal_neurons=out_channels // 16)
-
-        self.no_conv_branch = (
-            nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
-        )
-        self.branch_3x3 = conv_bn(
-            in_channels=in_channels,
-            out_channels=out_channels,
-            dilation=dilation,
-            kernel_size=kernel_size,
-            stride=stride,
-            padding=padding,
-            groups=groups,
-        )
-        self.branch_1x1 = conv_bn(
-            in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, groups=groups
-        )
-
-        if not build_residual_branches:
-            self.fuse_block_residual_branches()
-        else:
-            self.build_residual_branches = True
-
-    def forward(self, inputs):
-        if not self.build_residual_branches:
-            return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
-
-        if self.no_conv_branch is None:
-            id_out = 0
-        else:
-            id_out = self.no_conv_branch(inputs)
-
-        return self.nonlinearity(self.se(self.branch_3x3(inputs) + self.branch_1x1(inputs) + id_out))
-
-    def _get_equivalent_kernel_bias(self):
-        """
-        Fuses the 3x3, 1x1 and identity branches into a single 3x3 conv layer
-        """
-        kernel3x3, bias3x3 = self._fuse_bn_tensor(self.branch_3x3)
-        kernel1x1, bias1x1 = self._fuse_bn_tensor(self.branch_1x1)
-        kernelid, biasid = self._fuse_bn_tensor(self.no_conv_branch)
-        return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
-
-    def _pad_1x1_to_3x3_tensor(self, kernel1x1):
-        """
-        padding the 1x1 convolution weights with zeros to be able to fuse the 3x3 conv layer with the 1x1
-        :param kernel1x1: weights of the 1x1 convolution
-        :type kernel1x1:
-        :return: padded 1x1 weights
-        :rtype:
-        """
-        if kernel1x1 is None:
-            return 0
-        else:
-            return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
-
-    def _fuse_bn_tensor(self, branch):
-        """
-        Fusing of the batchnorm into the conv layer.
-        If the branch is the identity branch (no conv) the kernel will simply be eye.
-        :param branch:
-        :type branch:
-        :return:
-        :rtype:
-        """
-        if branch is None:
-            return 0, 0
-        if isinstance(branch, nn.Sequential):
-            kernel = branch.conv.weight
-            running_mean = branch.bn.running_mean
-            running_var = branch.bn.running_var
-            gamma = branch.bn.weight
-            beta = branch.bn.bias
-            eps = branch.bn.eps
-        else:
-            assert isinstance(branch, nn.BatchNorm2d)
-            if not hasattr(self, "id_tensor"):
-                input_dim = self.in_channels // self.groups
-                kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
-                for i in range(self.in_channels):
-                    kernel_value[i, i % input_dim, 1, 1] = 1
-                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
-            kernel = self.id_tensor
-            running_mean = branch.running_mean
-            running_var = branch.running_var
-            gamma = branch.weight
-            beta = branch.bias
-            eps = branch.eps
-        std = (running_var + eps).sqrt()
-        t = (gamma / std).reshape(-1, 1, 1, 1)
-        return kernel * t, beta - running_mean * gamma / std
-
-    def fuse_block_residual_branches(self):
-        """
-        converts a repvgg block from training model (with branches) to deployment mode (vgg like model)
-        :return:
-        :rtype:
-        """
-        if hasattr(self, "build_residual_branches") and not self.build_residual_branches:
-            return
-        kernel, bias = self._get_equivalent_kernel_bias()
-        self.rbr_reparam = nn.Conv2d(
-            in_channels=self.branch_3x3.conv.in_channels,
-            out_channels=self.branch_3x3.conv.out_channels,
-            kernel_size=self.branch_3x3.conv.kernel_size,
-            stride=self.branch_3x3.conv.stride,
-            padding=self.branch_3x3.conv.padding,
-            dilation=self.branch_3x3.conv.dilation,
-            groups=self.branch_3x3.conv.groups,
-            bias=True,
-        )
-        self.rbr_reparam.weight.data = kernel
-        self.rbr_reparam.bias.data = bias
-        for para in self.parameters():
-            para.detach_()
-        self.__delattr__("branch_3x3")
-        self.__delattr__("branch_1x1")
-        if hasattr(self, "no_conv_branch"):
-            self.__delattr__("no_conv_branch")
-        self.build_residual_branches = False
-
-
 class RepVGG(SgModule):
 class RepVGG(SgModule):
     def __init__(
     def __init__(
         self,
         self,
@@ -253,11 +54,12 @@ class RepVGG(SgModule):
         self.stem = RepVGGBlock(
         self.stem = RepVGGBlock(
             in_channels=in_channels,
             in_channels=in_channels,
             out_channels=self.in_planes,
             out_channels=self.in_planes,
-            kernel_size=3,
             stride=2,
             stride=2,
-            padding=1,
             build_residual_branches=build_residual_branches,
             build_residual_branches=build_residual_branches,
-            use_se=self.use_se,
+            activation_type=nn.ReLU,
+            activation_kwargs=dict(inplace=True),
+            se_type=SEBlock if self.use_se else nn.Identity,
+            se_kwargs=dict(in_channels=self.in_planes, internal_neurons=self.in_planes // 16) if self.use_se else None,
         )
         )
         self.cur_layer_idx = 1
         self.cur_layer_idx = 1
         self.stage1 = self._make_stage(int(64 * width_multiplier[0]), struct[0], stride=2)
         self.stage1 = self._make_stage(int(64 * width_multiplier[0]), struct[0], stride=2)
@@ -282,12 +84,13 @@ class RepVGG(SgModule):
                 RepVGGBlock(
                 RepVGGBlock(
                     in_channels=self.in_planes,
                     in_channels=self.in_planes,
                     out_channels=planes,
                     out_channels=planes,
-                    kernel_size=3,
                     stride=stride,
                     stride=stride,
-                    padding=1,
                     groups=1,
                     groups=1,
                     build_residual_branches=self.build_residual_branches,
                     build_residual_branches=self.build_residual_branches,
-                    use_se=self.use_se,
+                    activation_type=nn.ReLU,
+                    activation_kwargs=dict(inplace=True),
+                    se_type=SEBlock if self.use_se else nn.Identity,
+                    se_kwargs=dict(in_channels=self.in_planes, internal_neurons=self.in_planes // 16) if self.use_se else None,
                 )
                 )
             )
             )
             self.in_planes = planes
             self.in_planes = planes
@@ -312,10 +115,9 @@ class RepVGG(SgModule):
 
 
     def train(self, mode: bool = True):
     def train(self, mode: bool = True):
 
 
-        assert not mode or self.build_residual_branches, (
-            "Trying to train a model without residual branches, "
-            "set arch_params.build_residual_branches to True and retrain the model"
-        )
+        assert (
+            not mode or self.build_residual_branches
+        ), "Trying to train a model without residual branches, set arch_params.build_residual_branches to True and retrain the model"
         super(RepVGG, self).train(mode=mode)
         super(RepVGG, self).train(mode=mode)
 
 
     def replace_head(self, new_num_classes=None, new_head=None):
     def replace_head(self, new_num_classes=None, new_head=None):
Discard
@@ -3,7 +3,8 @@ import torch.nn as nn
 import torch.nn.functional as F
 import torch.nn.functional as F
 from typing import Union, List, Tuple
 from typing import Union, List, Tuple
 
 
-from super_gradients.training.utils.module_utils import ConvBNReLU, make_upsample_module
+from super_gradients.modules import ConvBNReLU
+from super_gradients.training.utils.module_utils import make_upsample_module
 from super_gradients.common import UpsampleMode
 from super_gradients.common import UpsampleMode
 from super_gradients.training.models.segmentation_models.stdc import SegmentationHead, AbstractSTDCBackbone,\
 from super_gradients.training.models.segmentation_models.stdc import SegmentationHead, AbstractSTDCBackbone,\
     STDC1Backbone, STDC2Backbone
     STDC1Backbone, STDC2Backbone
Discard
@@ -8,7 +8,7 @@ import torch
 import torch.nn as nn
 import torch.nn as nn
 from super_gradients.training.models import SgModule
 from super_gradients.training.models import SgModule
 from super_gradients.training.utils import HpmStruct, get_param
 from super_gradients.training.utils import HpmStruct, get_param
-from super_gradients.training.utils.module_utils import ConvBNReLU
+from super_gradients.modules import ConvBNReLU
 
 
 DEFAULT_REGSEG48_BACKBONE_PARAMS = {
 DEFAULT_REGSEG48_BACKBONE_PARAMS = {
     "stages": [
     "stages": [
Discard
@@ -11,7 +11,7 @@ from super_gradients.common.decorators.factory_decorator import resolve_param
 from super_gradients.common.factories.base_factory import BaseFactory
 from super_gradients.common.factories.base_factory import BaseFactory
 from super_gradients.training.models import SgModule
 from super_gradients.training.models import SgModule
 from super_gradients.training.utils import get_param, HpmStruct
 from super_gradients.training.utils import get_param, HpmStruct
-from super_gradients.training.utils.module_utils import ConvBNReLU
+from super_gradients.modules import ConvBNReLU
 from typing import Union, List
 from typing import Union, List
 from abc import ABC, abstractmethod
 from abc import ABC, abstractmethod
 
 
Discard
@@ -1,6 +1,6 @@
 from collections import OrderedDict
 from collections import OrderedDict
 import copy
 import copy
-from typing import List, Union, Tuple, Optional
+from typing import List, Union, Optional
 import torch
 import torch
 from torch import nn
 from torch import nn
 
 
@@ -45,7 +45,7 @@ class MultiOutputModule(nn.Module):
         """
         """
         super().__init__()
         super().__init__()
         self.output_paths = output_paths
         self.output_paths = output_paths
-        self._modules['0'] = module
+        self._modules["0"] = module
         self._outputs_lists = {}
         self._outputs_lists = {}
 
 
         for path in output_paths:
         for path in output_paths:
@@ -61,7 +61,7 @@ class MultiOutputModule(nn.Module):
 
 
     def forward(self, x) -> list:
     def forward(self, x) -> list:
         self._outputs_lists[x.device] = []
         self._outputs_lists[x.device] = []
-        self._modules['0'](x)
+        self._modules["0"](x)
         return self._outputs_lists[x.device]
         return self._outputs_lists[x.device]
 
 
     def _get_recursive(self, module: nn.Module, path) -> nn.Module:
     def _get_recursive(self, module: nn.Module, path) -> nn.Module:
@@ -100,10 +100,7 @@ class MultiOutputModule(nn.Module):
 
 
     def _slice_odict(self, odict: OrderedDict, start: int, end: int):
     def _slice_odict(self, odict: OrderedDict, start: int, end: int):
         """Slice an OrderedDict in the same logic list,tuple... are sliced"""
         """Slice an OrderedDict in the same logic list,tuple... are sliced"""
-        return OrderedDict([
-            (k, v) for (k, v) in odict.items()
-            if k in list(odict.keys())[start:end]
-        ])
+        return OrderedDict([(k, v) for (k, v) in odict.items() if k in list(odict.keys())[start:end]])
 
 
 
 
 def _replace_activations_recursive(module: nn.Module, new_activation: nn.Module, activations_to_replace: List[type]):
 def _replace_activations_recursive(module: nn.Module, new_activation: nn.Module, activations_to_replace: List[type]):
@@ -125,79 +122,28 @@ def replace_activations(module: nn.Module, new_activation: nn.Module, activation
     :param activations_to_replace:  types of activations to replace, each must be a subclass of nn.Module
     :param activations_to_replace:  types of activations to replace, each must be a subclass of nn.Module
     """
     """
     # check arguments once before the recursion
     # check arguments once before the recursion
-    assert isinstance(new_activation, nn.Module), 'new_activation should be nn.Module'
-    assert all([isinstance(t, type) and issubclass(t, nn.Module) for t in activations_to_replace]), \
-        'activations_to_replace should be types that are subclasses of nn.Module'
+    assert isinstance(new_activation, nn.Module), "new_activation should be nn.Module"
+    assert all(
+        [isinstance(t, type) and issubclass(t, nn.Module) for t in activations_to_replace]
+    ), "activations_to_replace should be types that are subclasses of nn.Module"
 
 
     # do the replacement
     # do the replacement
     _replace_activations_recursive(module, new_activation, activations_to_replace)
     _replace_activations_recursive(module, new_activation, activations_to_replace)
 
 
 
 
 def fuse_repvgg_blocks_residual_branches(model: nn.Module):
 def fuse_repvgg_blocks_residual_branches(model: nn.Module):
-    '''
+    """
     Call fuse_block_residual_branches for all repvgg blocks in the model
     Call fuse_block_residual_branches for all repvgg blocks in the model
     :param model: torch.nn.Module with repvgg blocks. Doesn't have to be entirely consists of repvgg.
     :param model: torch.nn.Module with repvgg blocks. Doesn't have to be entirely consists of repvgg.
     :type model: torch.nn.Module
     :type model: torch.nn.Module
-    '''
+    """
     assert not model.training, "To fuse RepVGG block residual branches, model must be on eval mode"
     assert not model.training, "To fuse RepVGG block residual branches, model must be on eval mode"
     for module in model.modules():
     for module in model.modules():
-        if hasattr(module, 'fuse_block_residual_branches'):
+        if hasattr(module, "fuse_block_residual_branches"):
             module.fuse_block_residual_branches()
             module.fuse_block_residual_branches()
     model.build_residual_branches = False
     model.build_residual_branches = False
 
 
 
 
-class ConvBNReLU(nn.Module):
-    """
-    Class for Convolution2d-Batchnorm2d-Relu layer. Default behaviour is Conv-BN-Relu. To exclude Batchnorm module use
-        `use_normalization=False`, to exclude Relu activation use `use_activation=False`.
-    For convolution arguments documentation see `nn.Conv2d`.
-    For batchnorm arguments documentation see `nn.BatchNorm2d`.
-    For relu arguments documentation see `nn.Relu`.
-    """
-
-    def __init__(self,
-                 in_channels: int,
-                 out_channels: int,
-                 kernel_size: Union[int, Tuple[int, int]],
-                 stride: Union[int, Tuple[int, int]] = 1,
-                 padding: Union[int, Tuple[int, int]] = 0,
-                 dilation: Union[int, Tuple[int, int]] = 1,
-                 groups: int = 1,
-                 bias: bool = True,
-                 padding_mode: str = 'zeros',
-                 use_normalization: bool = True,
-                 eps: float = 1e-5,
-                 momentum: float = 0.1,
-                 affine: bool = True,
-                 track_running_stats: bool = True,
-                 device=None,
-                 dtype=None,
-                 use_activation: bool = True,
-                 inplace: bool = False):
-
-        super(ConvBNReLU, self).__init__()
-        self.seq = nn.Sequential()
-        self.seq.add_module("conv", nn.Conv2d(in_channels,
-                                              out_channels,
-                                              kernel_size=kernel_size,
-                                              stride=stride,
-                                              padding=padding,
-                                              dilation=dilation,
-                                              groups=groups,
-                                              bias=bias,
-                                              padding_mode=padding_mode))
-
-        if use_normalization:
-            self.seq.add_module("bn", nn.BatchNorm2d(out_channels, eps=eps, momentum=momentum, affine=affine,
-                                                     track_running_stats=track_running_stats, device=device,
-                                                     dtype=dtype))
-        if use_activation:
-            self.seq.add_module("relu", nn.ReLU(inplace=inplace))
-
-    def forward(self, x):
-        return self.seq(x)
-
-
 class NormalizationAdapter(torch.nn.Module):
 class NormalizationAdapter(torch.nn.Module):
     """
     """
     Denormalizes input by mean_original, std_original, then normalizes by mean_required, std_required.
     Denormalizes input by mean_original, std_original, then normalizes by mean_required, std_required.
@@ -208,6 +154,7 @@ class NormalizationAdapter(torch.nn.Module):
      number of input channels.
      number of input channels.
 
 
     """
     """
+
     def __init__(self, mean_original, std_original, mean_required, std_required):
     def __init__(self, mean_original, std_original, mean_required, std_required):
         super(NormalizationAdapter, self).__init__()
         super(NormalizationAdapter, self).__init__()
         mean_original = torch.tensor(mean_original).unsqueeze(-1).unsqueeze(-1)
         mean_original = torch.tensor(mean_original).unsqueeze(-1).unsqueeze(-1)
@@ -223,9 +170,7 @@ class NormalizationAdapter(torch.nn.Module):
         return x
         return x
 
 
 
 
-def make_upsample_module(scale_factor: int,
-                         upsample_mode: Union[str, UpsampleMode],
-                         align_corners: Optional[bool] = None):
+def make_upsample_module(scale_factor: int, upsample_mode: Union[str, UpsampleMode], align_corners: Optional[bool] = None):
     """
     """
     Factory method for creating upsampling modules.
     Factory method for creating upsampling modules.
     :param scale_factor: upsample scale factor
     :param scale_factor: upsample scale factor
Discard
@@ -1,7 +1,7 @@
 import torch
 import torch
 import unittest
 import unittest
 import torch.nn as nn
 import torch.nn as nn
-from super_gradients.training.utils.module_utils import ConvBNReLU
+from super_gradients.modules import ConvBNReLU
 
 
 
 
 class TestConvBnRelu(unittest.TestCase):
 class TestConvBnRelu(unittest.TestCase):
Discard