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

repvgg.py 13 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
  1. '''
  2. Repvgg Pytorch Implementation. This model trains a vgg with residual blocks
  3. but during inference (in deployment mode) will convert the model to vgg model.
  4. Pretrained models: https://drive.google.com/drive/folders/1Avome4KvNp0Lqh2QwhXO6L5URQjzCjUq
  5. Refrerences:
  6. [1] https://github.com/DingXiaoH/RepVGG
  7. [2] https://arxiv.org/pdf/2101.03697.pdf
  8. Based on https://github.com/DingXiaoH/RepVGG
  9. '''
  10. from typing import Union
  11. import torch.nn as nn
  12. import numpy as np
  13. import torch
  14. import torch.nn.parallel
  15. import torch.optim
  16. import torch.utils.data
  17. import torch.utils.data.distributed
  18. from super_gradients.training.models import SgModule
  19. import torch.nn.functional as F
  20. from super_gradients.training.utils.module_utils import fuse_repvgg_blocks_residual_branches
  21. from super_gradients.training.utils.utils import get_param
  22. class SEBlock(nn.Module):
  23. def __init__(self, input_channels, internal_neurons):
  24. super(SEBlock, self).__init__()
  25. self.down = nn.Conv2d(in_channels=input_channels, out_channels=internal_neurons, kernel_size=1, stride=1, bias=True)
  26. self.up = nn.Conv2d(in_channels=internal_neurons, out_channels=input_channels, kernel_size=1, stride=1, bias=True)
  27. self.input_channels = input_channels
  28. def forward(self, inputs):
  29. x = F.avg_pool2d(inputs, kernel_size=inputs.size(3))
  30. x = self.down(x)
  31. x = F.relu(x)
  32. x = self.up(x)
  33. x = torch.sigmoid(x)
  34. x = x.view(-1, self.input_channels, 1, 1)
  35. return inputs * x
  36. def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1, dilation=1):
  37. result = nn.Sequential()
  38. result.add_module('conv', nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
  39. kernel_size=kernel_size, stride=stride, padding=padding, groups=groups,
  40. bias=False, dilation=dilation))
  41. result.add_module('bn', nn.BatchNorm2d(num_features=out_channels))
  42. return result
  43. class RepVGGBlock(nn.Module):
  44. '''
  45. Repvgg block consists of three branches
  46. 3x3: a branch of a 3x3 convolution + batchnorm + relu
  47. 1x1: a branch of a 1x1 convolution + batchnorm + relu
  48. no_conv_branch: a branch with only batchnorm which will only be used if input channel == output channel
  49. (usually in all but the first block of each stage)
  50. '''
  51. def __init__(self, in_channels, out_channels, kernel_size,
  52. stride=1, padding=0, dilation=1, groups=1, build_residual_branches=True, use_relu=True,
  53. use_se=False):
  54. super(RepVGGBlock, self).__init__()
  55. self.groups = groups
  56. self.in_channels = in_channels
  57. assert kernel_size == 3
  58. assert padding == dilation
  59. self.nonlinearity = nn.ReLU() if use_relu else nn.Identity()
  60. self.se = nn.Identity() if not use_se else SEBlock(out_channels, internal_neurons=out_channels // 16)
  61. self.no_conv_branch = nn.BatchNorm2d(
  62. num_features=in_channels) if out_channels == in_channels and stride == 1 else None
  63. self.branch_3x3 = conv_bn(in_channels=in_channels, out_channels=out_channels, dilation=dilation,
  64. kernel_size=kernel_size, stride=stride, padding=padding, groups=groups)
  65. self.branch_1x1 = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride,
  66. padding=0, groups=groups)
  67. if not build_residual_branches:
  68. self.fuse_block_residual_branches()
  69. else:
  70. self.build_residual_branches = True
  71. def forward(self, inputs):
  72. if not self.build_residual_branches:
  73. return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
  74. if self.no_conv_branch is None:
  75. id_out = 0
  76. else:
  77. id_out = self.no_conv_branch(inputs)
  78. return self.nonlinearity(self.se(self.branch_3x3(inputs) + self.branch_1x1(inputs) + id_out))
  79. def _get_equivalent_kernel_bias(self):
  80. """
  81. Fuses the 3x3, 1x1 and identity branches into a single 3x3 conv layer
  82. """
  83. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.branch_3x3)
  84. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.branch_1x1)
  85. kernelid, biasid = self._fuse_bn_tensor(self.no_conv_branch)
  86. return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
  87. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  88. """
  89. padding the 1x1 convolution weights with zeros to be able to fuse the 3x3 conv layer with the 1x1
  90. :param kernel1x1: weights of the 1x1 convolution
  91. :type kernel1x1:
  92. :return: padded 1x1 weights
  93. :rtype:
  94. """
  95. if kernel1x1 is None:
  96. return 0
  97. else:
  98. return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  99. def _fuse_bn_tensor(self, branch):
  100. """
  101. Fusing of the batchnorm into the conv layer.
  102. If the branch is the identity branch (no conv) the kernel will simply be eye.
  103. :param branch:
  104. :type branch:
  105. :return:
  106. :rtype:
  107. """
  108. if branch is None:
  109. return 0, 0
  110. if isinstance(branch, nn.Sequential):
  111. kernel = branch.conv.weight
  112. running_mean = branch.bn.running_mean
  113. running_var = branch.bn.running_var
  114. gamma = branch.bn.weight
  115. beta = branch.bn.bias
  116. eps = branch.bn.eps
  117. else:
  118. assert isinstance(branch, nn.BatchNorm2d)
  119. if not hasattr(self, 'id_tensor'):
  120. input_dim = self.in_channels // self.groups
  121. kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
  122. for i in range(self.in_channels):
  123. kernel_value[i, i % input_dim, 1, 1] = 1
  124. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  125. kernel = self.id_tensor
  126. running_mean = branch.running_mean
  127. running_var = branch.running_var
  128. gamma = branch.weight
  129. beta = branch.bias
  130. eps = branch.eps
  131. std = (running_var + eps).sqrt()
  132. t = (gamma / std).reshape(-1, 1, 1, 1)
  133. return kernel * t, beta - running_mean * gamma / std
  134. def fuse_block_residual_branches(self):
  135. """
  136. converts a repvgg block from training model (with branches) to deployment mode (vgg like model)
  137. :return:
  138. :rtype:
  139. """
  140. if hasattr(self, "build_residual_branches") and not self.build_residual_branches:
  141. return
  142. kernel, bias = self._get_equivalent_kernel_bias()
  143. self.rbr_reparam = nn.Conv2d(in_channels=self.branch_3x3.conv.in_channels, out_channels=self.branch_3x3.conv.out_channels,
  144. kernel_size=self.branch_3x3.conv.kernel_size, stride=self.branch_3x3.conv.stride,
  145. padding=self.branch_3x3.conv.padding, dilation=self.branch_3x3.conv.dilation, groups=self.branch_3x3.conv.groups, bias=True)
  146. self.rbr_reparam.weight.data = kernel
  147. self.rbr_reparam.bias.data = bias
  148. for para in self.parameters():
  149. para.detach_()
  150. self.__delattr__('branch_3x3')
  151. self.__delattr__('branch_1x1')
  152. if hasattr(self, 'no_conv_branch'):
  153. self.__delattr__('no_conv_branch')
  154. self.build_residual_branches = False
  155. class RepVGG(SgModule):
  156. def __init__(self, struct, num_classes=1000, width_multiplier=None,
  157. build_residual_branches=True, use_se=False, backbone_mode=False, in_channels=3):
  158. """
  159. :param struct: list containing number of blocks per repvgg stage
  160. :param num_classes: number of classes if nut in backbone mode
  161. :param width_multiplier: list of per stage width multiplier or float if using single value for all stages
  162. :param build_residual_branches: whether to add residual connections or not
  163. :param use_se: use squeeze and excitation layers
  164. :param backbone_mode: if true, dropping the final linear layer
  165. :param in_channels: input channels
  166. """
  167. super(RepVGG, self).__init__()
  168. if isinstance(width_multiplier, float):
  169. width_multiplier = [width_multiplier] * 4
  170. else:
  171. assert len(width_multiplier) == 4
  172. self.build_residual_branches = build_residual_branches
  173. self.use_se = use_se
  174. self.backbone_mode = backbone_mode
  175. self.in_planes = int(64 * width_multiplier[0])
  176. self.stem = RepVGGBlock(in_channels=in_channels, out_channels=self.in_planes, kernel_size=3, stride=2, padding=1,
  177. build_residual_branches=build_residual_branches, use_se=self.use_se)
  178. self.cur_layer_idx = 1
  179. self.stage1 = self._make_stage(int(64 * width_multiplier[0]), struct[0], stride=2)
  180. self.stage2 = self._make_stage(int(128 * width_multiplier[1]), struct[1], stride=2)
  181. self.stage3 = self._make_stage(int(256 * width_multiplier[2]), struct[2], stride=2)
  182. self.stage4 = self._make_stage(int(512 * width_multiplier[3]), struct[3], stride=2)
  183. if not self.backbone_mode:
  184. self.avgpool = nn.AdaptiveAvgPool2d(output_size=1)
  185. self.linear = nn.Linear(int(512 * width_multiplier[3]), num_classes)
  186. if not build_residual_branches:
  187. self.eval() # fusing has to be made in eval mode. When called in init, model will be built in eval mode
  188. fuse_repvgg_blocks_residual_branches(self)
  189. self.final_width_mult = width_multiplier[3]
  190. def _make_stage(self, planes, struct, stride):
  191. strides = [stride] + [1] * (struct - 1)
  192. blocks = []
  193. for stride in strides:
  194. blocks.append(RepVGGBlock(in_channels=self.in_planes, out_channels=planes, kernel_size=3,
  195. stride=stride, padding=1, groups=1, build_residual_branches=self.build_residual_branches,
  196. use_se=self.use_se))
  197. self.in_planes = planes
  198. self.cur_layer_idx += 1
  199. return nn.Sequential(*blocks)
  200. def forward(self, x):
  201. out = self.stem(x)
  202. out = self.stage1(out)
  203. out = self.stage2(out)
  204. out = self.stage3(out)
  205. out = self.stage4(out)
  206. if not self.backbone_mode:
  207. out = self.avgpool(out)
  208. out = out.view(out.size(0), -1)
  209. out = self.linear(out)
  210. return out
  211. def prep_model_for_conversion(self, input_size: Union[tuple, list] = None, **kwargs):
  212. if self.build_residual_branches:
  213. fuse_repvgg_blocks_residual_branches(self)
  214. def train(self, mode: bool = True):
  215. assert not mode or self.build_residual_branches, "Trying to train a model without residual branches, " \
  216. "set arch_params.build_residual_branches to True and retrain the model"
  217. super(RepVGG, self).train(mode=mode)
  218. def replace_head(self, new_num_classes=None, new_head=None):
  219. if new_num_classes is None and new_head is None:
  220. raise ValueError("At least one of new_num_classes, new_head must be given to replace output layer.")
  221. if new_head is not None:
  222. self.linear = new_head
  223. else:
  224. self.linear = nn.Linear(int(512 * self.final_width_mult), new_num_classes)
  225. class RepVggCustom(RepVGG):
  226. def __init__(self, arch_params):
  227. super().__init__(struct=arch_params.struct, num_classes=arch_params.num_classes,
  228. width_multiplier=arch_params.width_multiplier,
  229. build_residual_branches=arch_params.build_residual_branches,
  230. use_se=get_param(arch_params, 'use_se', False),
  231. backbone_mode=get_param(arch_params, 'backbone_mode', False),
  232. in_channels=get_param(arch_params, 'in_channels', 3))
  233. class RepVggA0(RepVggCustom):
  234. def __init__(self, arch_params):
  235. arch_params.override(struct=[2, 4, 14, 1], width_multiplier=[0.75, 0.75, 0.75, 2.5])
  236. super().__init__(arch_params=arch_params)
  237. class RepVggA1(RepVggCustom):
  238. def __init__(self, arch_params):
  239. arch_params.override(struct=[2, 4, 14, 1], width_multiplier=[1, 1, 1, 2.5])
  240. super().__init__(arch_params=arch_params)
  241. class RepVggA2(RepVggCustom):
  242. def __init__(self, arch_params):
  243. arch_params.override(struct=[2, 4, 14, 1], width_multiplier=[1.5, 1.5, 1.5, 2.75])
  244. super().__init__(arch_params=arch_params)
  245. class RepVggB0(RepVggCustom):
  246. def __init__(self, arch_params):
  247. arch_params.override(struct=[4, 6, 16, 1], width_multiplier=[1, 1, 1, 2.5])
  248. super().__init__(arch_params=arch_params)
  249. class RepVggB1(RepVggCustom):
  250. def __init__(self, arch_params):
  251. arch_params.override(struct=[4, 6, 16, 1], width_multiplier=[2, 2, 2, 4])
  252. super().__init__(arch_params=arch_params)
  253. class RepVggB2(RepVggCustom):
  254. def __init__(self, arch_params):
  255. arch_params.override(struct=[4, 6, 16, 1], width_multiplier=[2.5, 2.5, 2.5, 5])
  256. super().__init__(arch_params=arch_params)
  257. class RepVggB3(RepVggCustom):
  258. def __init__(self, arch_params):
  259. arch_params.override(struct=[4, 6, 16, 1], width_multiplier=[3, 3, 3, 5])
  260. super().__init__(arch_params=arch_params)
  261. class RepVggD2SE(RepVggCustom):
  262. def __init__(self, arch_params):
  263. arch_params.override(struct=[8, 14, 24, 1], width_multiplier=[2.5, 2.5, 2.5, 5])
  264. super().__init__(arch_params=arch_params)
Tip!

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

Comments

Loading...