Spaces:
Running
on
Zero
Running
on
Zero
File size: 7,521 Bytes
a7dedf9 |
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 |
from torch import nn, Tensor
import open_clip
from peft import get_peft_model, LoraConfig
from ..utils import ConvRefine, ConvUpsample, ConvAdapter
from ..utils import _get_norm_layer, _get_activation
resnet_names_and_weights = {
"RN50": ["openai", "yfcc15m", "cc12m"],
"RN101": ["openai", "yfcc15m", "cc12m"],
"RN50x4": ["openai", "yfcc15m", "cc12m"],
"RN50x16": ["openai", "yfcc15m", "cc12m"],
"RN50x64": ["openai", "yfcc15m", "cc12m"],
}
refiner_channels = {
"RN50": 2048,
"RN101": 2048,
"RN50x4": 2560,
"RN50x16": 3072,
"RN50x64": 4096,
}
refiner_groups = {
"RN50": refiner_channels["RN50"] // 512, # 4
"RN101": refiner_channels["RN101"] // 512, # 4
"RN50x4": refiner_channels["RN50x4"] // 512, # 5
"RN50x16": refiner_channels["RN50x16"] // 512, # 6
"RN50x64": refiner_channels["RN50x64"] // 512, # 8
}
class ResNet(nn.Module):
def __init__(
self,
model_name: str,
weight_name: str,
block_size: int = 16,
adapter: bool = False,
adapter_reduction: int = 4,
norm: str = "none",
act: str = "none"
) -> None:
super(ResNet, self).__init__()
assert model_name in resnet_names_and_weights, f"Model name should be one of {list(resnet_names_and_weights.keys())}, but got {model_name}."
assert weight_name in resnet_names_and_weights[model_name], f"Pretrained should be one of {resnet_names_and_weights[model_name]}, but got {weight_name}."
assert block_size in [32, 16, 8], f"block_size should be one of [32, 16, 8], got {block_size}"
self.model_name, self.weight_name = model_name, weight_name
self.block_size = block_size
model = open_clip.create_model_from_pretrained(model_name, weight_name, return_transform=False).visual
self.adapter = adapter
if adapter:
for param in model.parameters():
param.requires_grad = False
# Stem
self.conv1 = model.conv1
self.bn1 = model.bn1
self.act1 = model.act1
self.conv2 = model.conv2
self.bn2 = model.bn2
self.act2 = model.act2
self.conv3 = model.conv3
self.bn3 = model.bn3
self.act3 = model.act3
self.avgpool = model.avgpool
# Stem: reduction = 4
# Layers
for idx in range(1, 5):
setattr(self, f"layer{idx}", getattr(model, f"layer{idx}"))
if adapter:
setattr(self, f"adapter{idx}", ConvAdapter(
in_channels=getattr(model, f"layer{idx}")[-1].conv3.out_channels,
bottleneck_channels=getattr(model, f"layer{idx}")[-1].conv3.out_channels // adapter_reduction,
) if idx < 4 else nn.Identity()) # No adapter for the last layer
self.in_features = model.attnpool.c_proj.weight.shape[1]
self.out_features = model.attnpool.c_proj.weight.shape[0]
if norm == "bn":
norm_layer = nn.BatchNorm2d
elif norm == "ln":
norm_layer = nn.LayerNorm
else:
norm_layer = _get_norm_layer(model)
if act == "relu":
activation = nn.ReLU(inplace=True)
elif act == "gelu":
activation = nn.GELU()
else:
activation = _get_activation(model)
if block_size == 32:
self.refiner = ConvRefine(
in_channels=self.in_features,
out_channels=self.in_features,
norm_layer=norm_layer,
activation=activation,
groups=refiner_groups[self.model_name],
)
elif block_size == 16:
self.refiner = ConvUpsample(
in_channels=self.in_features,
out_channels=self.in_features,
norm_layer=norm_layer,
activation=activation,
groups=refiner_groups[self.model_name],
)
else: # block_size == 8
self.refiner = nn.Sequential(
ConvUpsample(
in_channels=self.in_features,
out_channels=self.in_features,
norm_layer=norm_layer,
activation=activation,
groups=refiner_groups[self.model_name],
),
ConvUpsample(
in_channels=self.in_features,
out_channels=self.in_features,
norm_layer=norm_layer,
activation=activation,
groups=refiner_groups[self.model_name],
),
)
def train(self, mode: bool = True):
if self.adapter and mode:
# training:
self.conv1.eval()
self.bn1.eval()
self.act1.eval()
self.conv2.eval()
self.bn2.eval()
self.act2.eval()
self.conv3.eval()
self.bn3.eval()
self.act3.eval()
self.avgpool.eval()
for idx in range(1, 5):
getattr(self, f"layer{idx}").eval()
getattr(self, f"adapter{idx}").train()
self.refiner.train()
else:
# evaluation:
for module in self.children():
module.train(mode)
def stem(self, x: Tensor) -> Tensor:
x = self.act1(self.bn1(self.conv1(x)))
x = self.act2(self.bn2(self.conv2(x)))
x = self.act3(self.bn3(self.conv3(x)))
x = self.avgpool(x)
return x
def forward(self, x: Tensor) -> Tensor:
x = self.stem(x)
x = self.layer1(x)
if self.adapter:
x = self.adapter1(x)
x = self.layer2(x)
if self.adapter:
x = self.adapter2(x)
x = self.layer3(x)
if self.adapter:
x = self.adapter3(x)
x = self.layer4(x)
if self.adapter:
x = self.adapter4(x)
x = self.refiner(x)
return x
def _resnet(
model_name: str,
weight_name: str,
block_size: int = 16,
adapter: bool = False,
adapter_reduction: int = 4,
lora: bool = False,
lora_rank: int = 16,
lora_alpha: float = 32.0,
lora_dropout: float = 0.1,
norm: str = "none",
act: str = "none"
) -> ResNet:
assert not (lora and adapter), "Lora and adapter cannot be used together."
model = ResNet(
model_name=model_name,
weight_name=weight_name,
block_size=block_size,
adapter=adapter,
adapter_reduction=adapter_reduction,
norm=norm,
act=act
)
if lora:
target_modules = []
for name, module in model.named_modules():
if isinstance(module, (nn.Linear, nn.Conv2d)):
target_modules.append(name)
lora_config = LoraConfig(
r=lora_rank,
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
bias="none",
target_modules=target_modules,
)
model = get_peft_model(model, lora_config)
# Unfreeze BN layers
for name, module in model.named_modules():
if isinstance(module, nn.BatchNorm2d) and "refiner" not in name:
module.requires_grad_(True)
# Unfreeze refiner
for name, module in model.named_modules():
if "refiner" in name:
module.requires_grad_(True)
return model
|