A03HCY commited on
Commit
060be7c
·
verified ·
1 Parent(s): 6fa070a

Upload 3 files

Browse files
mobile_net.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''MobileNetV3 feature extractors (Small / Large), refactored from
2
+ https://github.com/xiaolai-sqlai/mobilenetv3.
3
+
4
+ Changes vs. the original classification model:
5
+ - classification head (linear4) removed, backbone only;
6
+ - unified naming: bn1/bn2/bn3 -> norm1/norm2/norm3, linear3 -> proj,
7
+ Block.se.se.* -> Block.se.features.*;
8
+ - `MobileNetV3` takes a `backend` ('small' | 'large'); its classmethod
9
+ `from_pretrained` infers the backend from a checkpoint file automatically.
10
+ '''
11
+ import torch
12
+ import torch.nn as nn
13
+ from torch.nn import init
14
+
15
+ from safetensors.torch import load_file, save_file
16
+
17
+ # (kernel, in_ch, expand_ch, out_ch, is_relu, use_se, stride)
18
+ _BACKEND_BLOCKS = {
19
+ 'small': [
20
+ (3, 16, 16, 16, True, True, 2),
21
+ (3, 16, 72, 24, True, False, 2),
22
+ (3, 24, 88, 24, True, False, 1),
23
+ (5, 24, 96, 40, False, True, 2),
24
+ (5, 40, 240, 40, False, True, 1),
25
+ (5, 40, 240, 40, False, True, 1),
26
+ (5, 40, 120, 48, False, True, 1),
27
+ (5, 48, 144, 48, False, True, 1),
28
+ (5, 48, 288, 96, False, True, 2),
29
+ (5, 96, 576, 96, False, True, 1),
30
+ (5, 96, 576, 96, False, True, 1),
31
+ ],
32
+ 'large': [
33
+ (3, 16, 16, 16, True, False, 1),
34
+ (3, 16, 64, 24, True, False, 2),
35
+ (3, 24, 72, 24, True, False, 1),
36
+ (5, 24, 72, 40, True, True, 2),
37
+ (5, 40, 120, 40, True, True, 1),
38
+ (5, 40, 120, 40, True, True, 1),
39
+ (3, 40, 240, 80, False, False, 2),
40
+ (3, 80, 200, 80, False, False, 1),
41
+ (3, 80, 184, 80, False, False, 1),
42
+ (3, 80, 184, 80, False, False, 1),
43
+ (3, 80, 480, 112, False, True, 1),
44
+ (3, 112, 672, 112, False, True, 1),
45
+ (5, 112, 672, 160, False, True, 2),
46
+ (5, 160, 672, 160, False, True, 1),
47
+ (5, 160, 960, 160, False, True, 1),
48
+ ],
49
+ }
50
+
51
+ # (head_in_ch, head_out_ch) fed to conv2 / proj
52
+ _BACKEND_HEAD = {
53
+ 'small': (96, 576),
54
+ 'large': (160, 960),
55
+ }
56
+
57
+ # conv2.weight (out, in, 1, 1) used to tell Small from Large
58
+ _BACKEND_CONV2_SHAPE = {
59
+ 'small': (576, 96),
60
+ 'large': (960, 160),
61
+ }
62
+
63
+ # Number of bneck blocks per backend (fallback signature when conv2 is absent)
64
+ _BACKEND_NBLOCKS = {
65
+ 'small': 11,
66
+ 'large': 15,
67
+ }
68
+
69
+
70
+ class SEModule(nn.Module):
71
+ '''Squeeze-and-excitation block (same layout as upstream, feature extractor only).'''
72
+
73
+ def __init__(self, in_size, reduction=4):
74
+ super(SEModule, self).__init__()
75
+ expand_size = max(in_size // reduction, 8)
76
+
77
+ self.features = nn.Sequential(
78
+ nn.AdaptiveAvgPool2d(1),
79
+ nn.Conv2d(in_size, expand_size, kernel_size=1, bias=False),
80
+ nn.BatchNorm2d(expand_size),
81
+ nn.ReLU(inplace=True),
82
+ nn.Conv2d(expand_size, in_size, kernel_size=1, bias=False),
83
+ nn.Hardsigmoid(),
84
+ )
85
+
86
+ def forward(self, x):
87
+ return x * self.features(x)
88
+
89
+
90
+ class Block(nn.Module):
91
+ '''expand + depthwise + pointwise.'''
92
+
93
+ def __init__(self, kernel_size, in_size, expand_size, out_size, act, se, stride):
94
+ super(Block, self).__init__()
95
+ self.stride = stride
96
+
97
+ self.conv1 = nn.Conv2d(in_size, expand_size, kernel_size=1, bias=False)
98
+ self.norm1 = nn.BatchNorm2d(expand_size)
99
+ self.act1 = act(inplace=True)
100
+
101
+ self.conv2 = nn.Conv2d(
102
+ expand_size, expand_size, kernel_size=kernel_size, stride=stride,
103
+ padding=kernel_size // 2, groups=expand_size, bias=False,
104
+ )
105
+ self.norm2 = nn.BatchNorm2d(expand_size)
106
+ self.act2 = act(inplace=True)
107
+
108
+ self.se = SEModule(expand_size) if se else nn.Identity()
109
+
110
+ self.conv3 = nn.Conv2d(expand_size, out_size, kernel_size=1, bias=False)
111
+ self.norm3 = nn.BatchNorm2d(out_size)
112
+ self.act3 = act(inplace=True)
113
+
114
+ self.skip = None
115
+ if stride == 1 and in_size != out_size:
116
+ self.skip = nn.Sequential(
117
+ nn.Conv2d(in_size, out_size, kernel_size=1, bias=False),
118
+ nn.BatchNorm2d(out_size),
119
+ )
120
+ if stride == 2 and in_size != out_size:
121
+ self.skip = nn.Sequential(
122
+ nn.Conv2d(in_channels=in_size, out_channels=in_size, kernel_size=3,
123
+ groups=in_size, stride=2, padding=1, bias=False),
124
+ nn.BatchNorm2d(in_size),
125
+ nn.Conv2d(in_size, out_size, kernel_size=1, bias=True),
126
+ nn.BatchNorm2d(out_size),
127
+ )
128
+ if stride == 2 and in_size == out_size:
129
+ self.skip = nn.Sequential(
130
+ nn.Conv2d(in_channels=in_size, out_channels=out_size, kernel_size=3,
131
+ groups=in_size, stride=2, padding=1, bias=False),
132
+ nn.BatchNorm2d(out_size),
133
+ )
134
+
135
+ def forward(self, x):
136
+ skip = x
137
+
138
+ out = self.act1(self.norm1(self.conv1(x)))
139
+ out = self.act2(self.norm2(self.conv2(out)))
140
+ out = self.se(out)
141
+ out = self.norm3(self.conv3(out))
142
+
143
+ if self.skip is not None:
144
+ skip = self.skip(skip)
145
+ return self.act3(out + skip)
146
+
147
+
148
+ def _read_tensors(path: str):
149
+ '''Read a checkpoint into a {key: Tensor} dict (any tensors only).
150
+
151
+ Supports .safetensors and .pth/.pt. State-dict wrappers
152
+ ({'state_dict': ...} / {'model': ...}) and a DataParallel 'module.' prefix
153
+ are handled transparently. No strictness checks here.
154
+ '''
155
+ if path.endswith('.safetensors'):
156
+ raw = load_file(path, device='cpu')
157
+ elif path.endswith(('.pth', '.pt')):
158
+ raw = torch.load(path, map_location='cpu')
159
+ if isinstance(raw, dict):
160
+ for wrapper in ('state_dict', 'model'):
161
+ sub = raw.get(wrapper)
162
+ if isinstance(sub, dict):
163
+ raw = sub
164
+ break
165
+ if not isinstance(raw, dict):
166
+ raise RuntimeError(f'{path} is not a valid PyTorch weight file (expected a dict)')
167
+ else:
168
+ raise ValueError(
169
+ f'unsupported weight format (only .safetensors / .pth / .pt): {path!r}')
170
+
171
+ tensors = {}
172
+ for key, val in raw.items():
173
+ if not isinstance(val, torch.Tensor):
174
+ continue # skip non-weight entries such as epoch / optimizer
175
+ if key.startswith('module.'):
176
+ key = key[len('module.'):] # strip DataParallel prefix
177
+ tensors[key] = val
178
+ return tensors
179
+
180
+
181
+ def detect_backend(path: str) -> str:
182
+ '''Return 'small' or 'large' for the backend stored in a checkpoint file.'''
183
+ tensors = _read_tensors(path)
184
+
185
+ conv2 = tensors.get('conv2.weight')
186
+ if conv2 is not None:
187
+ shape = tuple(conv2.shape[:2])
188
+ for name, expected in _BACKEND_CONV2_SHAPE.items():
189
+ if shape == expected:
190
+ return name
191
+ raise ValueError(
192
+ f'cannot tell Small from Large: conv2.weight shape {shape} matches neither '
193
+ f'{_BACKEND_CONV2_SHAPE}')
194
+
195
+ n_blocks = max(
196
+ (int(key.split('.')[1]) for key in tensors if key.startswith('bneck.') and key.split('.')[1].isdigit()),
197
+ default=-1,
198
+ ) + 1
199
+ for name, expected in _BACKEND_NBLOCKS.items():
200
+ if n_blocks == expected:
201
+ return name
202
+ raise ValueError(
203
+ f'cannot tell Small from Large: {n_blocks} bneck blocks match neither '
204
+ f'{_BACKEND_NBLOCKS}')
205
+
206
+
207
+ class MobileNetV3(nn.Module):
208
+ '''MobileNetV3 feature extractor. Outputs a 1280-dim feature vector per image.
209
+
210
+ Args:
211
+ backend: 'small' or 'large'. Defaults to 'small' for a bare instance;
212
+ prefer `MobileNetV3.from_pretrained(path)` to pick it automatically.
213
+ act: activation used by the hard-swish blocks (default nn.Hardswish).
214
+ '''
215
+
216
+ backend = None
217
+
218
+ def __init__(self, backend: str | None = None, act=nn.Hardswish):
219
+ super(MobileNetV3, self).__init__()
220
+ if backend is None:
221
+ backend = 'small' if self.backend is None else self.backend
222
+ if backend not in _BACKEND_BLOCKS:
223
+ raise ValueError(f'unknown backend {backend!r}; choose from {list(_BACKEND_BLOCKS)}')
224
+ self.backend = backend
225
+
226
+ head_in, head_out = _BACKEND_HEAD[backend]
227
+
228
+ self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=2, padding=1, bias=False)
229
+ self.norm1 = nn.BatchNorm2d(16)
230
+ self.act1 = act(inplace=True)
231
+
232
+ def act_for(is_relu):
233
+ return nn.ReLU if is_relu else act
234
+
235
+ self.bneck = nn.Sequential(*[
236
+ Block(k, i, e, o, act_for(relu), se, s)
237
+ for (k, i, e, o, relu, se, s) in _BACKEND_BLOCKS[backend]
238
+ ])
239
+
240
+ self.conv2 = nn.Conv2d(head_in, head_out, kernel_size=1, stride=1, padding=0, bias=False)
241
+ self.norm2 = nn.BatchNorm2d(head_out)
242
+ self.act2 = act(inplace=True)
243
+ self.gap = nn.AdaptiveAvgPool2d(1)
244
+
245
+ self.proj = nn.Linear(head_out, 1280, bias=False)
246
+ self.norm3 = nn.BatchNorm1d(1280)
247
+ self.act3 = act(inplace=True)
248
+ self.drop = nn.Dropout(0.2)
249
+
250
+ self.init_params()
251
+
252
+ def init_params(self):
253
+ for m in self.modules():
254
+ if isinstance(m, nn.Conv2d):
255
+ init.kaiming_normal_(m.weight, mode='fan_out')
256
+ if m.bias is not None:
257
+ init.constant_(m.bias, 0)
258
+ elif isinstance(m, nn.BatchNorm2d):
259
+ init.constant_(m.weight, 1)
260
+ init.constant_(m.bias, 0)
261
+ elif isinstance(m, nn.Linear):
262
+ init.normal_(m.weight, std=0.001)
263
+ if m.bias is not None:
264
+ init.constant_(m.bias, 0)
265
+
266
+ def forward(self, x):
267
+ out = self.act1(self.norm1(self.conv1(x)))
268
+ out = self.bneck(out)
269
+
270
+ out = self.act2(self.norm2(self.conv2(out)))
271
+ out = self.gap(out).flatten(1)
272
+ out = self.drop(self.act3(self.norm3(self.proj(out))))
273
+
274
+ return out
275
+
276
+ def save_pretrained(self, path: str):
277
+ '''Save the current weights by extension: safetensors or torch .pth/.pt.'''
278
+ sd = self.state_dict()
279
+ if path.endswith('.safetensors'):
280
+ save_file(sd, path)
281
+ elif path.endswith(('.pth', '.pt')):
282
+ torch.save(sd, path)
283
+ else:
284
+ raise ValueError(
285
+ f'unsupported weight format (only .safetensors / .pth / .pt): {path!r}')
286
+ return self
287
+
288
+ def load_pretrained(self, path: str):
289
+ '''Load weights by extension (.safetensors / .pth / .pt).
290
+
291
+ Strictly requires the current naming: keys must match this model exactly
292
+ (no extra, none missing, per-tensor shapes equal). No legacy fallback.
293
+ '''
294
+ tensors = _read_tensors(path)
295
+
296
+ ref = self.state_dict()
297
+ extra = sorted(k for k in tensors if k not in ref)
298
+ missing = sorted(k for k in ref if k not in tensors)
299
+ if extra or missing:
300
+ raise RuntimeError(
301
+ f'weights do not match this model ({self.backend}): {len(extra)} extra / '
302
+ f'{len(missing)} missing -> extra {extra[:5]}..., missing {missing[:5]}...')
303
+
304
+ for k, v in tensors.items():
305
+ want = tuple(ref[k].shape)
306
+ if tuple(v.shape) != want:
307
+ raise RuntimeError(f'shape mismatch for {k}: weights {tuple(v.shape)} vs model {want}')
308
+ if v.dtype != ref[k].dtype:
309
+ tensors[k] = v.to(ref[k].dtype)
310
+ self.load_state_dict(tensors, strict=True)
311
+ return self
312
+
313
+ @classmethod
314
+ def from_pretrained(cls, path: str) -> 'MobileNetV3':
315
+ '''Infer the backend ('small'/'large') from the checkpoint and load it.
316
+
317
+ Calling it on a pinned subclass raises if that subclass disagrees with
318
+ the backend detected in the file.
319
+ '''
320
+ backend = detect_backend(path)
321
+ pinned = cls.backend
322
+ if pinned is not None and pinned != backend:
323
+ raise ValueError(
324
+ f'checkpoint at {path!r} is a {backend} model, but {cls.__name__} '
325
+ f'is pinned to {pinned!r}')
326
+ model = cls(backend=backend) if pinned is None else cls()
327
+ return model.load_pretrained(path)
328
+
329
+
330
+ class MobileNetV3_Small(MobileNetV3):
331
+ '''MobileNetV3-Small feature extractor (explicit backend, no auto-detection).'''
332
+
333
+ backend = 'small'
334
+
335
+ def __init__(self, act=nn.Hardswish):
336
+ super(MobileNetV3_Small, self).__init__(backend='small', act=act)
337
+
338
+
339
+ class MobileNetV3_Large(MobileNetV3):
340
+ '''MobileNetV3-Large feature extractor (explicit backend, no auto-detection).'''
341
+
342
+ backend = 'large'
343
+
344
+ def __init__(self, act=nn.Hardswish):
345
+ super(MobileNetV3_Large, self).__init__(backend='large', act=act)
mobilenetv3_large.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86adb5480e88d76e9631b25070a455beae6ec01d3eac41fed726ccbbf7fa92e4
3
+ size 15743184
mobilenetv3_small.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d9976a3bd3c1292b09c9ba34ee79a5c30b187a4b10a564b93d5360ff03c0638
3
+ size 6773776