lilkm HF Staff commited on
Commit
300b2a6
·
verified ·
1 Parent(s): 8215eed

Upload ResNet10

Browse files
Files changed (3) hide show
  1. config.json +7 -1
  2. model.safetensors +3 -0
  3. modeling_resnet.py +262 -0
config.json CHANGED
@@ -1,6 +1,11 @@
1
  {
 
 
 
 
2
  "auto_map": {
3
- "AutoConfig": "configuration_resnet.ResNet10Config"
 
4
  },
5
  "depths": [
6
  1,
@@ -19,5 +24,6 @@
19
  "model_type": "resnet10",
20
  "num_channels": 3,
21
  "pooler": "avg",
 
22
  "transformers_version": "4.48.1"
23
  }
 
1
  {
2
+ "_name_or_path": "lilkm/resnet10",
3
+ "architectures": [
4
+ "ResNet10"
5
+ ],
6
  "auto_map": {
7
+ "AutoConfig": "lilkm/resnet10--configuration_resnet.ResNet10Config",
8
+ "AutoModel": "modeling_resnet.ResNet10"
9
  },
10
  "depths": [
11
  1,
 
24
  "model_type": "resnet10",
25
  "num_channels": 3,
26
  "pooler": "avg",
27
+ "torch_dtype": "float32",
28
  "transformers_version": "4.48.1"
29
  }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1be729cd30827ec597a7601d7b10ce1d6a50729b79119142761fbb9bba090d5f
3
+ size 19627000
modeling_resnet.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -----------------------------------------------------------------------------
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # -----------------------------------------------------------------------------
15
+
16
+ import math
17
+ from typing import Optional
18
+
19
+ import torch.nn as nn
20
+ from torch import Tensor
21
+ from transformers import PreTrainedModel
22
+ from transformers.activations import ACT2FN
23
+ from transformers.modeling_outputs import BaseModelOutputWithNoAttention
24
+
25
+ from .configuration_resnet import ResNet10Config
26
+
27
+
28
+ class MaxPool2dJax(nn.Module):
29
+ """Mimics JAX's MaxPool with padding='SAME' for exact parity."""
30
+
31
+ def __init__(self, kernel_size, stride=2):
32
+ super().__init__()
33
+
34
+ # Ensure kernel_size and stride are tuples
35
+ self.kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size, kernel_size)
36
+ self.stride = stride if isinstance(stride, tuple) else (stride, stride)
37
+
38
+ self.maxpool = nn.MaxPool2d(
39
+ kernel_size=self.kernel_size,
40
+ stride=self.stride,
41
+ padding=0, # No padding
42
+ )
43
+
44
+ def _compute_padding(self, input_height, input_width):
45
+ """Calculate asymmetric padding to match JAX's 'SAME' behavior."""
46
+
47
+ # Compute padding needed for height and width
48
+ pad_h = max(
49
+ 0, (math.ceil(input_height / self.stride[0]) - 1) * self.stride[0] + self.kernel_size[0] - input_height
50
+ )
51
+ pad_w = max(
52
+ 0, (math.ceil(input_width / self.stride[1]) - 1) * self.stride[1] + self.kernel_size[1] - input_width
53
+ )
54
+
55
+ # Asymmetric padding (JAX-style: more padding on the bottom/right if needed)
56
+ pad_top = pad_h // 2
57
+ pad_bottom = pad_h - pad_top
58
+ pad_left = pad_w // 2
59
+ pad_right = pad_w - pad_left
60
+
61
+ return (pad_left, pad_right, pad_top, pad_bottom)
62
+
63
+ def forward(self, x):
64
+ """Apply asymmetric padding before convolution."""
65
+ _, _, h, w = x.shape
66
+
67
+ # Compute asymmetric padding
68
+ pad_left, pad_right, pad_top, pad_bottom = self._compute_padding(h, w)
69
+ x = nn.functional.pad(
70
+ x, (pad_left, pad_right, pad_top, pad_bottom), value=-float("inf")
71
+ ) # Pad right/bottom by 1 to match JAX's maxpooling padding="SAME"
72
+
73
+ return nn.MaxPool2d(kernel_size=3, stride=2, padding=0)(x)
74
+
75
+
76
+ class Conv2dJax(nn.Module):
77
+ """Mimics JAX's Conv2D with padding='SAME' for exact parity."""
78
+
79
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=False):
80
+ super().__init__()
81
+
82
+ # Ensure kernel_size and stride are tuples
83
+ self.kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size, kernel_size)
84
+ self.stride = stride if isinstance(stride, tuple) else (stride, stride)
85
+
86
+ self.conv = nn.Conv2d(
87
+ in_channels,
88
+ out_channels,
89
+ kernel_size=self.kernel_size,
90
+ stride=self.stride,
91
+ padding=0, # No padding
92
+ bias=bias,
93
+ )
94
+
95
+ def _compute_padding(self, input_height, input_width):
96
+ """Calculate asym
97
+ metric padding to match JAX's 'SAME' behavior."""
98
+
99
+ # Compute padding needed for height and width
100
+ pad_h = max(
101
+ 0, (math.ceil(input_height / self.stride[0]) - 1) * self.stride[0] + self.kernel_size[0] - input_height
102
+ )
103
+ pad_w = max(
104
+ 0, (math.ceil(input_width / self.stride[1]) - 1) * self.stride[1] + self.kernel_size[1] - input_width
105
+ )
106
+
107
+ # Asymmetric padding (JAX-style: more padding on the bottom/right if needed)
108
+ pad_top = pad_h // 2
109
+ pad_bottom = pad_h - pad_top
110
+ pad_left = pad_w // 2
111
+ pad_right = pad_w - pad_left
112
+
113
+ return (pad_left, pad_right, pad_top, pad_bottom)
114
+
115
+ def forward(self, x):
116
+ """Apply asymmetric padding before convolution."""
117
+ _, _, h, w = x.shape
118
+
119
+ # Compute asymmetric padding
120
+ pad_left, pad_right, pad_top, pad_bottom = self._compute_padding(h, w)
121
+ x = nn.functional.pad(x, (pad_left, pad_right, pad_top, pad_bottom))
122
+
123
+ return self.conv(x)
124
+
125
+
126
+ class MyGroupNorm(nn.Module):
127
+ def __init__(self, num_groups, num_channels, eps=1e-5, affine=True):
128
+ super().__init__()
129
+ self.group_norm = nn.GroupNorm(num_groups, num_channels, eps, affine)
130
+
131
+ def forward(self, x):
132
+ if x.ndim == 3:
133
+ x = x.unsqueeze(0)
134
+ x = self.group_norm(x)
135
+ x = x.squeeze(0)
136
+ else:
137
+ x = self.group_norm(x)
138
+ return x
139
+
140
+
141
+ class BasicBlock(nn.Module):
142
+ def __init__(self, in_channels, out_channels, activation, stride=1, norm_groups=4):
143
+ super().__init__()
144
+
145
+ self.conv1 = Conv2dJax(
146
+ in_channels,
147
+ out_channels,
148
+ kernel_size=3,
149
+ stride=stride,
150
+ bias=False,
151
+ )
152
+ self.norm1 = MyGroupNorm(num_groups=norm_groups, num_channels=out_channels)
153
+ self.act1 = ACT2FN[activation]
154
+ self.act2 = ACT2FN[activation]
155
+ self.conv2 = Conv2dJax(out_channels, out_channels, kernel_size=3, stride=1, bias=False)
156
+ self.norm2 = MyGroupNorm(num_groups=norm_groups, num_channels=out_channels)
157
+
158
+ self.shortcut = None
159
+ if in_channels != out_channels:
160
+ self.shortcut = nn.Sequential(
161
+ Conv2dJax(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
162
+ MyGroupNorm(num_groups=norm_groups, num_channels=out_channels),
163
+ )
164
+
165
+ def forward(self, x):
166
+ identity = x
167
+
168
+ out = self.conv1(x)
169
+ out = self.norm1(out)
170
+ out = self.act1(out)
171
+
172
+ out = self.conv2(out)
173
+ out = self.norm2(out)
174
+
175
+ if self.shortcut is not None:
176
+ identity = self.shortcut(identity)
177
+
178
+ out += identity
179
+ return self.act2(out)
180
+
181
+
182
+ class Encoder(nn.Module):
183
+ def __init__(self, config: ResNet10Config):
184
+ super().__init__()
185
+ self.config = config
186
+ self.stages = nn.ModuleList([])
187
+
188
+ for i, size in enumerate(self.config.hidden_sizes):
189
+ if i == 0:
190
+ self.stages.append(
191
+ BasicBlock(
192
+ self.config.embedding_size,
193
+ size,
194
+ activation=self.config.hidden_act,
195
+ )
196
+ )
197
+ else:
198
+ self.stages.append(
199
+ BasicBlock(
200
+ self.config.hidden_sizes[i - 1],
201
+ size,
202
+ activation=self.config.hidden_act,
203
+ stride=2,
204
+ )
205
+ )
206
+
207
+ def forward(self, hidden_state: Tensor, output_hidden_states: bool = False) -> BaseModelOutputWithNoAttention:
208
+ hidden_states = () if output_hidden_states else None
209
+
210
+ for stage in self.stages:
211
+ if output_hidden_states:
212
+ hidden_states = hidden_states + (hidden_state,)
213
+
214
+ hidden_state = stage(hidden_state)
215
+
216
+ if output_hidden_states:
217
+ hidden_states = hidden_states + (hidden_state,)
218
+
219
+ return BaseModelOutputWithNoAttention(
220
+ last_hidden_state=hidden_state,
221
+ hidden_states=hidden_states,
222
+ )
223
+
224
+
225
+ class ResNet10(PreTrainedModel):
226
+ config_class = ResNet10Config
227
+
228
+ def __init__(self, config):
229
+ super().__init__(config)
230
+
231
+ self.embedder = nn.Sequential(
232
+ nn.Conv2d(
233
+ self.config.num_channels,
234
+ self.config.embedding_size,
235
+ kernel_size=7,
236
+ stride=2,
237
+ padding=3,
238
+ bias=False,
239
+ ),
240
+ MyGroupNorm(num_groups=4, eps=1e-5, num_channels=self.config.embedding_size),
241
+ ACT2FN[self.config.hidden_act],
242
+ MaxPool2dJax(kernel_size=3, stride=2),
243
+ )
244
+
245
+ self.encoder = Encoder(self.config)
246
+
247
+ def forward(self, x: Tensor, output_hidden_states: Optional[bool] = None) -> BaseModelOutputWithNoAttention:
248
+ output_hidden_states = (
249
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
250
+ )
251
+ embedding_output = self.embedder(x)
252
+ encoder_outputs = self.encoder(embedding_output, output_hidden_states=output_hidden_states)
253
+
254
+ return BaseModelOutputWithNoAttention(
255
+ last_hidden_state=encoder_outputs.last_hidden_state,
256
+ hidden_states=encoder_outputs.hidden_states,
257
+ )
258
+
259
+ def print_model_hash(self):
260
+ print("Model parameters hashes:")
261
+ for name, param in self.named_parameters():
262
+ print(name, param.sum())