Spaces:
Build error
Build error
trying to make custom config
Browse files- app.py +22 -4
- model_utils/efficientnet_config.py +500 -0
app.py
CHANGED
|
@@ -11,9 +11,10 @@ from types import SimpleNamespace
|
|
| 11 |
from transformers import AutoModel, pipeline
|
| 12 |
import torch
|
| 13 |
|
| 14 |
-
|
| 15 |
# from utils import model_utils, train_utils, data_utils, run_utils
|
| 16 |
# from model_utils import jason_regnet_maker, jason_efficientnet_maker
|
|
|
|
| 17 |
|
| 18 |
model_path = 'chlab/'
|
| 19 |
# model_path = './models/'
|
|
@@ -28,7 +29,7 @@ lw = 3
|
|
| 28 |
ps = 200
|
| 29 |
cmap = 'magma'
|
| 30 |
|
| 31 |
-
|
| 32 |
"num_classes": 2,
|
| 33 |
"gamma": 0.032606396652426956,
|
| 34 |
"lr": 0.008692971067922545,
|
|
@@ -39,8 +40,8 @@ effnet_61_hparams = {
|
|
| 39 |
"dropout": 0.027804120950575217,
|
| 40 |
"width_mult": 1.060782511229692,
|
| 41 |
"depth_mult": 0.7752918857163054,
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
|
| 45 |
# which layers to look at
|
| 46 |
activation_indices = {'efficientnet': [0, 3]}
|
|
@@ -202,6 +203,23 @@ def predict_and_analyze(model_name, num_channels, dim, input_channel, image):
|
|
| 202 |
print("Loading model")
|
| 203 |
model_loading_name = model_path + "%s_%i_planet_detection" % (model_name, num_channels)
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
# pipeline = pipeline(task="image-classification", model=model_loading_name)
|
| 206 |
|
| 207 |
# model = load_model(model_name, activation=True)
|
|
|
|
| 11 |
from transformers import AutoModel, pipeline
|
| 12 |
import torch
|
| 13 |
|
| 14 |
+
sys.path.insert(1, "../")
|
| 15 |
# from utils import model_utils, train_utils, data_utils, run_utils
|
| 16 |
# from model_utils import jason_regnet_maker, jason_efficientnet_maker
|
| 17 |
+
from model_utils.efficientnet_config import EfficientNetConfig
|
| 18 |
|
| 19 |
model_path = 'chlab/'
|
| 20 |
# model_path = './models/'
|
|
|
|
| 29 |
ps = 200
|
| 30 |
cmap = 'magma'
|
| 31 |
|
| 32 |
+
effnet_hparams = {61: {
|
| 33 |
"num_classes": 2,
|
| 34 |
"gamma": 0.032606396652426956,
|
| 35 |
"lr": 0.008692971067922545,
|
|
|
|
| 40 |
"dropout": 0.027804120950575217,
|
| 41 |
"width_mult": 1.060782511229692,
|
| 42 |
"depth_mult": 0.7752918857163054,
|
| 43 |
+
}}
|
| 44 |
+
# effnet_config = SimpleNamespace(**effnet_hparams)
|
| 45 |
|
| 46 |
# which layers to look at
|
| 47 |
activation_indices = {'efficientnet': [0, 3]}
|
|
|
|
| 203 |
print("Loading model")
|
| 204 |
model_loading_name = model_path + "%s_%i_planet_detection" % (model_name, num_channels)
|
| 205 |
|
| 206 |
+
if 'eff' in model_name:
|
| 207 |
+
hparams = effnet_hparams[num_channels]
|
| 208 |
+
hparams = SimpleNamespace(**hparams)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
config = EfficientNetConfig(
|
| 212 |
+
hparams.dropout,
|
| 213 |
+
num_channels=hparams.num_channels,
|
| 214 |
+
num_classes=hparams.num_classes,
|
| 215 |
+
size=hparams.size,
|
| 216 |
+
stochastic_depth_prob=hparams.stochastic_depth_prob,
|
| 217 |
+
width_mult=hparams.width_mult,
|
| 218 |
+
depth_mult=hparams.depth_mult,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
config.save_pretrained(model_loading_name)
|
| 222 |
+
|
| 223 |
# pipeline = pipeline(task="image-classification", model=model_loading_name)
|
| 224 |
|
| 225 |
# model = load_model(model_name, activation=True)
|
model_utils/efficientnet_config.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from functools import partial
|
| 9 |
+
from typing import Any, Callable, List, Optional, Sequence, Tuple, Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import Tensor, nn
|
| 13 |
+
from torchvision.models._utils import _make_divisible
|
| 14 |
+
from torchvision.ops import StochasticDepth
|
| 15 |
+
from torchvision.ops.misc import Conv2dNormActivation, SqueezeExcitation
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class _MBConvConfig:
|
| 20 |
+
expand_ratio: float
|
| 21 |
+
kernel: int
|
| 22 |
+
stride: int
|
| 23 |
+
input_channels: int
|
| 24 |
+
out_channels: int
|
| 25 |
+
num_layers: int
|
| 26 |
+
block: Callable[..., nn.Module]
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def adjust_channels(
|
| 30 |
+
channels: int, width_mult: float, min_value: Optional[int] = None
|
| 31 |
+
) -> int:
|
| 32 |
+
return _make_divisible(channels * width_mult, 8, min_value)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class MBConvConfig(_MBConvConfig):
|
| 36 |
+
# Stores information listed at Table 1 of the EfficientNet paper & Table 4 of the EfficientNetV2 paper
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
expand_ratio: float,
|
| 40 |
+
kernel: int,
|
| 41 |
+
stride: int,
|
| 42 |
+
input_channels: int,
|
| 43 |
+
out_channels: int,
|
| 44 |
+
num_layers: int,
|
| 45 |
+
width_mult: float = 1.0,
|
| 46 |
+
depth_mult: float = 1.0,
|
| 47 |
+
block: Optional[Callable[..., nn.Module]] = None,
|
| 48 |
+
) -> None:
|
| 49 |
+
input_channels = self.adjust_channels(input_channels, width_mult)
|
| 50 |
+
out_channels = self.adjust_channels(out_channels, width_mult)
|
| 51 |
+
num_layers = self.adjust_depth(num_layers, depth_mult)
|
| 52 |
+
if block is None:
|
| 53 |
+
block = MBConv
|
| 54 |
+
super().__init__(
|
| 55 |
+
expand_ratio,
|
| 56 |
+
kernel,
|
| 57 |
+
stride,
|
| 58 |
+
input_channels,
|
| 59 |
+
out_channels,
|
| 60 |
+
num_layers,
|
| 61 |
+
block,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def adjust_depth(num_layers: int, depth_mult: float):
|
| 66 |
+
return int(math.ceil(num_layers * depth_mult))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class FusedMBConvConfig(_MBConvConfig):
|
| 70 |
+
# Stores information listed at Table 4 of the EfficientNetV2 paper
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
expand_ratio: float,
|
| 74 |
+
kernel: int,
|
| 75 |
+
stride: int,
|
| 76 |
+
input_channels: int,
|
| 77 |
+
out_channels: int,
|
| 78 |
+
num_layers: int,
|
| 79 |
+
block: Optional[Callable[..., nn.Module]] = None,
|
| 80 |
+
) -> None:
|
| 81 |
+
if block is None:
|
| 82 |
+
block = FusedMBConv
|
| 83 |
+
super().__init__(
|
| 84 |
+
expand_ratio,
|
| 85 |
+
kernel,
|
| 86 |
+
stride,
|
| 87 |
+
input_channels,
|
| 88 |
+
out_channels,
|
| 89 |
+
num_layers,
|
| 90 |
+
block,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class MBConv(nn.Module):
|
| 95 |
+
def __init__(
|
| 96 |
+
self,
|
| 97 |
+
cnf: MBConvConfig,
|
| 98 |
+
stochastic_depth_prob: float,
|
| 99 |
+
norm_layer: Callable[..., nn.Module],
|
| 100 |
+
se_layer: Callable[..., nn.Module] = SqueezeExcitation,
|
| 101 |
+
) -> None:
|
| 102 |
+
super().__init__()
|
| 103 |
+
|
| 104 |
+
if not (1 <= cnf.stride <= 2):
|
| 105 |
+
raise ValueError("illegal stride value")
|
| 106 |
+
|
| 107 |
+
self.use_res_connect = (
|
| 108 |
+
cnf.stride == 1 and cnf.input_channels == cnf.out_channels
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
layers: List[nn.Module] = []
|
| 112 |
+
activation_layer = nn.SiLU
|
| 113 |
+
|
| 114 |
+
# expand
|
| 115 |
+
expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio)
|
| 116 |
+
if expanded_channels != cnf.input_channels:
|
| 117 |
+
layers.append(
|
| 118 |
+
Conv2dNormActivation(
|
| 119 |
+
cnf.input_channels,
|
| 120 |
+
expanded_channels,
|
| 121 |
+
kernel_size=1,
|
| 122 |
+
norm_layer=norm_layer,
|
| 123 |
+
activation_layer=activation_layer,
|
| 124 |
+
)
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# depthwise
|
| 128 |
+
layers.append(
|
| 129 |
+
Conv2dNormActivation(
|
| 130 |
+
expanded_channels,
|
| 131 |
+
expanded_channels,
|
| 132 |
+
kernel_size=cnf.kernel,
|
| 133 |
+
stride=cnf.stride,
|
| 134 |
+
groups=expanded_channels,
|
| 135 |
+
norm_layer=norm_layer,
|
| 136 |
+
activation_layer=activation_layer,
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# squeeze and excitation
|
| 141 |
+
squeeze_channels = max(1, cnf.input_channels // 4)
|
| 142 |
+
layers.append(
|
| 143 |
+
se_layer(
|
| 144 |
+
expanded_channels,
|
| 145 |
+
squeeze_channels,
|
| 146 |
+
activation=partial(nn.SiLU, inplace=True),
|
| 147 |
+
)
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# project
|
| 151 |
+
layers.append(
|
| 152 |
+
Conv2dNormActivation(
|
| 153 |
+
expanded_channels,
|
| 154 |
+
cnf.out_channels,
|
| 155 |
+
kernel_size=1,
|
| 156 |
+
norm_layer=norm_layer,
|
| 157 |
+
activation_layer=None,
|
| 158 |
+
)
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
self.block = nn.Sequential(*layers)
|
| 162 |
+
self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row")
|
| 163 |
+
self.out_channels = cnf.out_channels
|
| 164 |
+
|
| 165 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 166 |
+
result = self.block(input)
|
| 167 |
+
if self.use_res_connect:
|
| 168 |
+
result = self.stochastic_depth(result)
|
| 169 |
+
result += input
|
| 170 |
+
return result
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class FusedMBConv(nn.Module):
|
| 174 |
+
def __init__(
|
| 175 |
+
self,
|
| 176 |
+
cnf: FusedMBConvConfig,
|
| 177 |
+
stochastic_depth_prob: float,
|
| 178 |
+
norm_layer: Callable[..., nn.Module],
|
| 179 |
+
) -> None:
|
| 180 |
+
super().__init__()
|
| 181 |
+
|
| 182 |
+
if not (1 <= cnf.stride <= 2):
|
| 183 |
+
raise ValueError("illegal stride value")
|
| 184 |
+
|
| 185 |
+
self.use_res_connect = (
|
| 186 |
+
cnf.stride == 1 and cnf.input_channels == cnf.out_channels
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
layers: List[nn.Module] = []
|
| 190 |
+
activation_layer = nn.SiLU
|
| 191 |
+
|
| 192 |
+
expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio)
|
| 193 |
+
if expanded_channels != cnf.input_channels:
|
| 194 |
+
# fused expand
|
| 195 |
+
layers.append(
|
| 196 |
+
Conv2dNormActivation(
|
| 197 |
+
cnf.input_channels,
|
| 198 |
+
expanded_channels,
|
| 199 |
+
kernel_size=cnf.kernel,
|
| 200 |
+
stride=cnf.stride,
|
| 201 |
+
norm_layer=norm_layer,
|
| 202 |
+
activation_layer=activation_layer,
|
| 203 |
+
)
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# project
|
| 207 |
+
layers.append(
|
| 208 |
+
Conv2dNormActivation(
|
| 209 |
+
expanded_channels,
|
| 210 |
+
cnf.out_channels,
|
| 211 |
+
kernel_size=1,
|
| 212 |
+
norm_layer=norm_layer,
|
| 213 |
+
activation_layer=None,
|
| 214 |
+
)
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
layers.append(
|
| 218 |
+
Conv2dNormActivation(
|
| 219 |
+
cnf.input_channels,
|
| 220 |
+
cnf.out_channels,
|
| 221 |
+
kernel_size=cnf.kernel,
|
| 222 |
+
stride=cnf.stride,
|
| 223 |
+
norm_layer=norm_layer,
|
| 224 |
+
activation_layer=activation_layer,
|
| 225 |
+
)
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
self.block = nn.Sequential(*layers)
|
| 229 |
+
self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row")
|
| 230 |
+
self.out_channels = cnf.out_channels
|
| 231 |
+
|
| 232 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 233 |
+
result = self.block(input)
|
| 234 |
+
if self.use_res_connect:
|
| 235 |
+
result = self.stochastic_depth(result)
|
| 236 |
+
result += input
|
| 237 |
+
return result
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class EfficientNetConfig(PretrainedConfig):
|
| 241 |
+
|
| 242 |
+
model_type = "efficientnet"
|
| 243 |
+
|
| 244 |
+
def __init__(
|
| 245 |
+
self,
|
| 246 |
+
# inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]],
|
| 247 |
+
dropout: float,
|
| 248 |
+
num_channels: int = 61,
|
| 249 |
+
stochastic_depth_prob: float = 0.2,
|
| 250 |
+
num_classes: int = 2,
|
| 251 |
+
norm_layer: Optional[Callable[..., nn.Module]] = None,
|
| 252 |
+
# last_channel: Optional[int] = None,
|
| 253 |
+
size: str='v2_s',
|
| 254 |
+
width_mult: float = 1.0,
|
| 255 |
+
depth_mult: float = 1.0,
|
| 256 |
+
**kwargs: Any,
|
| 257 |
+
) -> None:
|
| 258 |
+
"""
|
| 259 |
+
EfficientNet V1 and V2 main class
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
inverted_residual_setting (Sequence[Union[MBConvConfig, FusedMBConvConfig]]): Network structure
|
| 263 |
+
dropout (float): The droupout probability
|
| 264 |
+
stochastic_depth_prob (float): The stochastic depth probability
|
| 265 |
+
num_classes (int): Number of classes
|
| 266 |
+
norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use
|
| 267 |
+
last_channel (int): The number of channels on the penultimate layer
|
| 268 |
+
"""
|
| 269 |
+
super().__init__()
|
| 270 |
+
# _log_api_usage_once(self)
|
| 271 |
+
|
| 272 |
+
inverted_residual_setting, last_channel = _efficientnet_conf(
|
| 273 |
+
"efficientnet_%s" % (size), width_mult=width_mult, depth_mult=depth_mult
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
if not inverted_residual_setting:
|
| 277 |
+
raise ValueError("The inverted_residual_setting should not be empty")
|
| 278 |
+
elif not (
|
| 279 |
+
isinstance(inverted_residual_setting, Sequence)
|
| 280 |
+
and all([isinstance(s, _MBConvConfig) for s in inverted_residual_setting])
|
| 281 |
+
):
|
| 282 |
+
raise TypeError(
|
| 283 |
+
"The inverted_residual_setting should be List[MBConvConfig]"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
if "block" in kwargs:
|
| 287 |
+
warnings.warn(
|
| 288 |
+
"The parameter 'block' is deprecated since 0.13 and will be removed 0.15. "
|
| 289 |
+
"Please pass this information on 'MBConvConfig.block' instead."
|
| 290 |
+
)
|
| 291 |
+
if kwargs["block"] is not None:
|
| 292 |
+
for s in inverted_residual_setting:
|
| 293 |
+
if isinstance(s, MBConvConfig):
|
| 294 |
+
s.block = kwargs["block"]
|
| 295 |
+
|
| 296 |
+
if norm_layer is None:
|
| 297 |
+
norm_layer = nn.BatchNorm2d
|
| 298 |
+
|
| 299 |
+
layers: List[nn.Module] = []
|
| 300 |
+
|
| 301 |
+
# building first layer
|
| 302 |
+
firstconv_output_channels = inverted_residual_setting[0].input_channels
|
| 303 |
+
layers.append(
|
| 304 |
+
Conv2dNormActivation(
|
| 305 |
+
num_channels,
|
| 306 |
+
firstconv_output_channels,
|
| 307 |
+
kernel_size=3,
|
| 308 |
+
stride=2,
|
| 309 |
+
norm_layer=norm_layer,
|
| 310 |
+
activation_layer=nn.SiLU,
|
| 311 |
+
)
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
# building inverted residual blocks
|
| 315 |
+
total_stage_blocks = sum(cnf.num_layers for cnf in inverted_residual_setting)
|
| 316 |
+
stage_block_id = 0
|
| 317 |
+
for cnf in inverted_residual_setting:
|
| 318 |
+
stage: List[nn.Module] = []
|
| 319 |
+
for _ in range(cnf.num_layers):
|
| 320 |
+
# copy to avoid modifications. shallow copy is enough
|
| 321 |
+
block_cnf = copy.copy(cnf)
|
| 322 |
+
|
| 323 |
+
# overwrite info if not the first conv in the stage
|
| 324 |
+
if stage:
|
| 325 |
+
block_cnf.input_channels = block_cnf.out_channels
|
| 326 |
+
block_cnf.stride = 1
|
| 327 |
+
|
| 328 |
+
# adjust stochastic depth probability based on the depth of the stage block
|
| 329 |
+
sd_prob = (
|
| 330 |
+
stochastic_depth_prob * float(stage_block_id) / total_stage_blocks
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
stage.append(block_cnf.block(block_cnf, sd_prob, norm_layer))
|
| 334 |
+
stage_block_id += 1
|
| 335 |
+
|
| 336 |
+
layers.append(nn.Sequential(*stage))
|
| 337 |
+
|
| 338 |
+
# building last several layers
|
| 339 |
+
lastconv_input_channels = inverted_residual_setting[-1].out_channels
|
| 340 |
+
lastconv_output_channels = (
|
| 341 |
+
last_channel if last_channel is not None else 4 * lastconv_input_channels
|
| 342 |
+
)
|
| 343 |
+
layers.append(
|
| 344 |
+
Conv2dNormActivation(
|
| 345 |
+
lastconv_input_channels,
|
| 346 |
+
lastconv_output_channels,
|
| 347 |
+
kernel_size=1,
|
| 348 |
+
norm_layer=norm_layer,
|
| 349 |
+
activation_layer=nn.SiLU,
|
| 350 |
+
)
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
self.features = nn.Sequential(*layers)
|
| 354 |
+
self.avgpool = nn.AdaptiveAvgPool2d(1)
|
| 355 |
+
self.classifier = nn.Sequential(
|
| 356 |
+
nn.Dropout(p=dropout, inplace=True),
|
| 357 |
+
nn.Linear(lastconv_output_channels, num_classes),
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
for m in self.modules():
|
| 361 |
+
if isinstance(m, nn.Conv2d):
|
| 362 |
+
nn.init.kaiming_normal_(m.weight, mode="fan_out")
|
| 363 |
+
if m.bias is not None:
|
| 364 |
+
nn.init.zeros_(m.bias)
|
| 365 |
+
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
|
| 366 |
+
nn.init.ones_(m.weight)
|
| 367 |
+
nn.init.zeros_(m.bias)
|
| 368 |
+
elif isinstance(m, nn.Linear):
|
| 369 |
+
init_range = 1.0 / math.sqrt(m.out_features)
|
| 370 |
+
nn.init.uniform_(m.weight, -init_range, init_range)
|
| 371 |
+
nn.init.zeros_(m.bias)
|
| 372 |
+
|
| 373 |
+
def _forward_impl(self, x: Tensor) -> Tensor:
|
| 374 |
+
x = self.features(x)
|
| 375 |
+
|
| 376 |
+
x = self.avgpool(x)
|
| 377 |
+
x = torch.flatten(x, 1)
|
| 378 |
+
|
| 379 |
+
x = self.classifier(x)
|
| 380 |
+
|
| 381 |
+
return x
|
| 382 |
+
|
| 383 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 384 |
+
return self._forward_impl(x)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# def _efficientnet(
|
| 388 |
+
# inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]],
|
| 389 |
+
# dropout: float,
|
| 390 |
+
# last_channel: Optional[int],
|
| 391 |
+
# weights=None,
|
| 392 |
+
# num_channels: int = 61,
|
| 393 |
+
# stochastic_depth_prob: float = 0.2,
|
| 394 |
+
# progress: bool = True,
|
| 395 |
+
# num_classes: int = 2,
|
| 396 |
+
# **kwargs: Any,
|
| 397 |
+
# ) -> EfficientNetCongig:
|
| 398 |
+
|
| 399 |
+
# model = EfficientNetCongif(
|
| 400 |
+
# inverted_residual_setting,
|
| 401 |
+
# dropout,
|
| 402 |
+
# num_classes=num_classes,
|
| 403 |
+
# num_channels=num_channels,
|
| 404 |
+
# stochastic_depth_prob=stochastic_depth_prob,
|
| 405 |
+
# last_channel=last_channel,
|
| 406 |
+
# **kwargs,
|
| 407 |
+
# )
|
| 408 |
+
|
| 409 |
+
# return model
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _efficientnet_conf(
|
| 413 |
+
arch: str,
|
| 414 |
+
**kwargs: Any,
|
| 415 |
+
) -> Tuple[Sequence[Union[MBConvConfig, FusedMBConvConfig]], Optional[int]]:
|
| 416 |
+
inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]]
|
| 417 |
+
if arch.startswith("efficientnet_b"):
|
| 418 |
+
bneck_conf = partial(
|
| 419 |
+
MBConvConfig,
|
| 420 |
+
width_mult=kwargs.pop("width_mult"),
|
| 421 |
+
depth_mult=kwargs.pop("depth_mult"),
|
| 422 |
+
)
|
| 423 |
+
inverted_residual_setting = [
|
| 424 |
+
bneck_conf(1, 3, 1, 32, 16, 1),
|
| 425 |
+
bneck_conf(6, 3, 2, 16, 24, 2),
|
| 426 |
+
bneck_conf(6, 5, 2, 24, 40, 2),
|
| 427 |
+
bneck_conf(6, 3, 2, 40, 80, 3),
|
| 428 |
+
bneck_conf(6, 5, 1, 80, 112, 3),
|
| 429 |
+
bneck_conf(6, 5, 2, 112, 192, 4),
|
| 430 |
+
bneck_conf(6, 3, 1, 192, 320, 1),
|
| 431 |
+
]
|
| 432 |
+
last_channel = None
|
| 433 |
+
elif arch.startswith("efficientnet_v2_s"):
|
| 434 |
+
inverted_residual_setting = [
|
| 435 |
+
FusedMBConvConfig(1, 3, 1, 24, 24, 2),
|
| 436 |
+
FusedMBConvConfig(4, 3, 2, 24, 48, 4),
|
| 437 |
+
FusedMBConvConfig(4, 3, 2, 48, 64, 4),
|
| 438 |
+
MBConvConfig(4, 3, 2, 64, 128, 6),
|
| 439 |
+
MBConvConfig(6, 3, 1, 128, 160, 9),
|
| 440 |
+
MBConvConfig(6, 3, 2, 160, 256, 15),
|
| 441 |
+
]
|
| 442 |
+
last_channel = 1280
|
| 443 |
+
elif arch.startswith("efficientnet_v2_m"):
|
| 444 |
+
inverted_residual_setting = [
|
| 445 |
+
FusedMBConvConfig(1, 3, 1, 24, 24, 3),
|
| 446 |
+
FusedMBConvConfig(4, 3, 2, 24, 48, 5),
|
| 447 |
+
FusedMBConvConfig(4, 3, 2, 48, 80, 5),
|
| 448 |
+
MBConvConfig(4, 3, 2, 80, 160, 7),
|
| 449 |
+
MBConvConfig(6, 3, 1, 160, 176, 14),
|
| 450 |
+
MBConvConfig(6, 3, 2, 176, 304, 18),
|
| 451 |
+
MBConvConfig(6, 3, 1, 304, 512, 5),
|
| 452 |
+
]
|
| 453 |
+
last_channel = 1280
|
| 454 |
+
elif arch.startswith("efficientnet_v2_l"):
|
| 455 |
+
inverted_residual_setting = [
|
| 456 |
+
FusedMBConvConfig(1, 3, 1, 32, 32, 4),
|
| 457 |
+
FusedMBConvConfig(4, 3, 2, 32, 64, 7),
|
| 458 |
+
FusedMBConvConfig(4, 3, 2, 64, 96, 7),
|
| 459 |
+
MBConvConfig(4, 3, 2, 96, 192, 10),
|
| 460 |
+
MBConvConfig(6, 3, 1, 192, 224, 19),
|
| 461 |
+
MBConvConfig(6, 3, 2, 224, 384, 25),
|
| 462 |
+
MBConvConfig(6, 3, 1, 384, 640, 7),
|
| 463 |
+
]
|
| 464 |
+
last_channel = 1280
|
| 465 |
+
else:
|
| 466 |
+
raise ValueError(f"Unsupported model type {arch}")
|
| 467 |
+
|
| 468 |
+
return inverted_residual_setting, last_channel
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
# def create_an_efficientnet(
|
| 472 |
+
# num_channels: int = 61,
|
| 473 |
+
# size: str = "v2_s",
|
| 474 |
+
# width_mult: float = 1.0,
|
| 475 |
+
# depth_mult: float = 1.0,
|
| 476 |
+
# dropout: float = 0.25,
|
| 477 |
+
# stochastic_depth_prob: float = 0.2,
|
| 478 |
+
# num_classes: int = 2,
|
| 479 |
+
# **kwargs,
|
| 480 |
+
# ):
|
| 481 |
+
|
| 482 |
+
# """Makes an EfficientNet of a given size and set of parameters"""
|
| 483 |
+
|
| 484 |
+
# inverted_residual_setting, last_channel = _efficientnet_conf(
|
| 485 |
+
# "efficientnet_%s" % (size), width_mult=width_mult, depth_mult=depth_mult
|
| 486 |
+
# )
|
| 487 |
+
|
| 488 |
+
# model = _efficientnet(
|
| 489 |
+
# inverted_residual_setting,
|
| 490 |
+
# dropout,
|
| 491 |
+
# last_channel,
|
| 492 |
+
# weights=None,
|
| 493 |
+
# num_classes=num_classes,
|
| 494 |
+
# num_channels=num_channels,
|
| 495 |
+
# stochastic_depth_prob=stochastic_depth_prob,
|
| 496 |
+
# progress=True,
|
| 497 |
+
# **kwargs,
|
| 498 |
+
# )
|
| 499 |
+
|
| 500 |
+
# return model
|