Upload ResNet10
Browse files- config.json +7 -1
- model.safetensors +3 -0
- modeling_resnet.py +285 -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.0"
|
| 23 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"_name_or_path": "helper2424/resnet10",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"ResNet10"
|
| 5 |
+
],
|
| 6 |
"auto_map": {
|
| 7 |
+
"AutoConfig": "helper2424/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.0"
|
| 29 |
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:10f7d125770aa256bd45ec9e4f586ca1157e29380fa1306d14a025664ae173d0
|
| 3 |
+
size 19626736
|
modeling_resnet.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, BaseModelOutputWithPoolingAndNoAttention
|
| 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 BasicBlock(nn.Module):
|
| 127 |
+
def __init__(self, in_channels, out_channels, activation, stride=1, norm_groups=4):
|
| 128 |
+
super().__init__()
|
| 129 |
+
|
| 130 |
+
self.conv1 = Conv2dJax(
|
| 131 |
+
in_channels,
|
| 132 |
+
out_channels,
|
| 133 |
+
kernel_size=3,
|
| 134 |
+
stride=stride,
|
| 135 |
+
bias=False,
|
| 136 |
+
)
|
| 137 |
+
self.norm1 = nn.GroupNorm(num_groups=norm_groups, num_channels=out_channels)
|
| 138 |
+
self.act1 = ACT2FN[activation]
|
| 139 |
+
self.act2 = ACT2FN[activation]
|
| 140 |
+
self.conv2 = Conv2dJax(out_channels, out_channels, kernel_size=3, stride=1, bias=False)
|
| 141 |
+
self.norm2 = nn.GroupNorm(num_groups=norm_groups, num_channels=out_channels)
|
| 142 |
+
|
| 143 |
+
self.shortcut = None
|
| 144 |
+
if in_channels != out_channels:
|
| 145 |
+
self.shortcut = nn.Sequential(
|
| 146 |
+
Conv2dJax(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
|
| 147 |
+
nn.GroupNorm(num_groups=norm_groups, num_channels=out_channels),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
def forward(self, x):
|
| 151 |
+
identity = x
|
| 152 |
+
|
| 153 |
+
out = self.conv1(x)
|
| 154 |
+
out = self.norm1(out)
|
| 155 |
+
out = self.act1(out)
|
| 156 |
+
|
| 157 |
+
out = self.conv2(out)
|
| 158 |
+
out = self.norm2(out)
|
| 159 |
+
|
| 160 |
+
if self.shortcut is not None:
|
| 161 |
+
identity = self.shortcut(identity)
|
| 162 |
+
|
| 163 |
+
out += identity
|
| 164 |
+
return self.act2(out)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class Encoder(nn.Module):
|
| 168 |
+
def __init__(self, config: ResNet10Config):
|
| 169 |
+
super().__init__()
|
| 170 |
+
self.config = config
|
| 171 |
+
self.stages = nn.ModuleList([])
|
| 172 |
+
|
| 173 |
+
for i, size in enumerate(self.config.hidden_sizes):
|
| 174 |
+
if i == 0:
|
| 175 |
+
self.stages.append(
|
| 176 |
+
BasicBlock(
|
| 177 |
+
self.config.embedding_size,
|
| 178 |
+
size,
|
| 179 |
+
activation=self.config.hidden_act,
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
self.stages.append(
|
| 184 |
+
BasicBlock(
|
| 185 |
+
self.config.hidden_sizes[i - 1],
|
| 186 |
+
size,
|
| 187 |
+
activation=self.config.hidden_act,
|
| 188 |
+
stride=2,
|
| 189 |
+
)
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
def forward(self, hidden_state: Tensor, output_hidden_states: bool = False) -> BaseModelOutputWithNoAttention:
|
| 193 |
+
hidden_states = () if output_hidden_states else None
|
| 194 |
+
|
| 195 |
+
for stage in self.stages:
|
| 196 |
+
if output_hidden_states:
|
| 197 |
+
hidden_states = hidden_states + (hidden_state,)
|
| 198 |
+
|
| 199 |
+
hidden_state = stage(hidden_state)
|
| 200 |
+
|
| 201 |
+
if output_hidden_states:
|
| 202 |
+
hidden_states = hidden_states + (hidden_state,)
|
| 203 |
+
|
| 204 |
+
return BaseModelOutputWithNoAttention(
|
| 205 |
+
last_hidden_state=hidden_state,
|
| 206 |
+
hidden_states=hidden_states,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
class ResNet10(PreTrainedModel):
|
| 211 |
+
config_class = ResNet10Config
|
| 212 |
+
|
| 213 |
+
def __init__(self, config):
|
| 214 |
+
super().__init__(config)
|
| 215 |
+
|
| 216 |
+
self.embedder = nn.Sequential(
|
| 217 |
+
nn.Conv2d(
|
| 218 |
+
self.config.num_channels,
|
| 219 |
+
self.config.embedding_size,
|
| 220 |
+
kernel_size=7,
|
| 221 |
+
stride=2,
|
| 222 |
+
padding=3,
|
| 223 |
+
bias=False,
|
| 224 |
+
),
|
| 225 |
+
# The original code has a small trick -
|
| 226 |
+
# https://github.com/rail-berkeley/hil-serl/blob/main/serl_launcher/serl_launcher/vision/resnet_v1.py#L119
|
| 227 |
+
# class MyGroupNorm(nn.GroupNorm):
|
| 228 |
+
# def __call__(self, x):
|
| 229 |
+
# if x.ndim == 3:
|
| 230 |
+
# x = x[jnp.newaxis]
|
| 231 |
+
# x = super().__call__(x)
|
| 232 |
+
# return x[0]
|
| 233 |
+
# else:
|
| 234 |
+
# return super().__call__(x)
|
| 235 |
+
nn.GroupNorm(num_groups=4, eps=1e-5, num_channels=self.config.embedding_size),
|
| 236 |
+
ACT2FN[self.config.hidden_act],
|
| 237 |
+
MaxPool2dJax(kernel_size=3, stride=2),
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
self.encoder = Encoder(self.config)
|
| 241 |
+
self.pooler = nn.AdaptiveAvgPool2d(output_size=1)
|
| 242 |
+
|
| 243 |
+
def _init_pooler(self):
|
| 244 |
+
if self.config.pooler == "avg":
|
| 245 |
+
self.pooler = nn.AdaptiveAvgPool2d(output_size=1)
|
| 246 |
+
elif self.config.pooler == "max":
|
| 247 |
+
self.pooler = nn.MaxPool2d(kernel_size=3, stride=2)
|
| 248 |
+
elif self.config.pooler == "spatial_learned_embeddings":
|
| 249 |
+
raise ValueError("Invalid pooler, it exist in the hil serl version, but weights are missing")
|
| 250 |
+
|
| 251 |
+
# In the original HIl-SERL code is used SpatialLearnedEmbeddings as pooliing method
|
| 252 |
+
# Check https://github.com/rail-berkeley/hil-serl/blob/7d17d13560d85abffbd45facec17c4f9189c29c0/serl_launcher/serl_launcher/agents/continuous/sac.py#L490
|
| 253 |
+
# But weights for this custom layer are missing
|
| 254 |
+
# Probably it means that pretrained weights used other way of pooling - probably it's AvgPool2d
|
| 255 |
+
# self.pooler = nn.Sequential(
|
| 256 |
+
# SpatialLearnedEmbeddings(
|
| 257 |
+
# height=height,
|
| 258 |
+
# width=width,
|
| 259 |
+
# channel=channel,
|
| 260 |
+
# num_features=self.num_spatial_blocks,
|
| 261 |
+
# ),
|
| 262 |
+
# nn.Dropout(0.1, deterministic=not train),
|
| 263 |
+
# )
|
| 264 |
+
else:
|
| 265 |
+
raise ValueError(f"Invalid pooler: {self.config.pooler}")
|
| 266 |
+
|
| 267 |
+
def forward(self, x: Tensor, output_hidden_states: Optional[bool] = None) -> BaseModelOutputWithNoAttention:
|
| 268 |
+
output_hidden_states = (
|
| 269 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 270 |
+
)
|
| 271 |
+
embedding_output = self.embedder(x)
|
| 272 |
+
encoder_outputs = self.encoder(embedding_output, output_hidden_states=output_hidden_states)
|
| 273 |
+
|
| 274 |
+
pooler_output = self.pooler(encoder_outputs.last_hidden_state)
|
| 275 |
+
|
| 276 |
+
return BaseModelOutputWithPoolingAndNoAttention(
|
| 277 |
+
last_hidden_state=encoder_outputs.last_hidden_state,
|
| 278 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 279 |
+
pooler_output=pooler_output,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
def print_model_hash(self):
|
| 283 |
+
print("Model parameters hashes:")
|
| 284 |
+
for name, param in self.named_parameters():
|
| 285 |
+
print(name, param.sum())
|