Spaces:
Running
Running
Vansh Chugh commited on
Commit ·
a4688bc
1
Parent(s): 5aa5bc8
cleanup: remove pann/timm/bert/bart dead branches from model.py
Browse files- models/CLAP/open_clip/model.py +6 -45
- models/CLAP/open_clip/pann_model.py +0 -704
- models/CLAP/open_clip/timm_model.py +0 -112
models/CLAP/open_clip/model.py
CHANGED
|
@@ -14,13 +14,11 @@ import torch
|
|
| 14 |
import torch.nn.functional as F
|
| 15 |
from torch import nn
|
| 16 |
|
| 17 |
-
from .timm_model import TimmModel
|
| 18 |
import logging
|
| 19 |
from .utils import freeze_batch_norm_2d
|
| 20 |
-
|
| 21 |
-
from .pann_model import create_pann_model
|
| 22 |
from .htsat import create_htsat_model
|
| 23 |
-
from transformers import
|
|
|
|
| 24 |
from transformers.tokenization_utils_base import BatchEncoding
|
| 25 |
|
| 26 |
|
|
@@ -458,17 +456,8 @@ class CLAP(nn.Module):
|
|
| 458 |
else:
|
| 459 |
raise NotImplementedError
|
| 460 |
|
| 461 |
-
# audio branch
|
| 462 |
-
|
| 463 |
-
if audio_cfg.model_type == "PANN":
|
| 464 |
-
self.audio_branch = create_pann_model(audio_cfg, enable_fusion, fusion_type)
|
| 465 |
-
elif audio_cfg.model_type == "HTSAT":
|
| 466 |
-
self.audio_branch = create_htsat_model(
|
| 467 |
-
audio_cfg, enable_fusion, fusion_type
|
| 468 |
-
)
|
| 469 |
-
else:
|
| 470 |
-
logging.error(f"Model config for {audio_cfg.model_type} not found")
|
| 471 |
-
raise RuntimeError(f"Model config for {audio_cfg.model_type} not found.")
|
| 472 |
|
| 473 |
# text branch
|
| 474 |
# text branch parameters
|
|
@@ -498,21 +487,7 @@ class CLAP(nn.Module):
|
|
| 498 |
mlp_act_layer,
|
| 499 |
nn.Linear(self.joint_embed_shape, self.joint_embed_shape),
|
| 500 |
)
|
| 501 |
-
|
| 502 |
-
self.text_branch = BertModel.from_pretrained("bert-base-uncased")
|
| 503 |
-
self.text_transform = MLPLayers(
|
| 504 |
-
units=[
|
| 505 |
-
self.joint_embed_shape,
|
| 506 |
-
self.joint_embed_shape,
|
| 507 |
-
self.joint_embed_shape,
|
| 508 |
-
],
|
| 509 |
-
dropout=0.1,
|
| 510 |
-
)
|
| 511 |
-
self.text_projection = nn.Sequential(
|
| 512 |
-
nn.Linear(768, self.joint_embed_shape),
|
| 513 |
-
mlp_act_layer,
|
| 514 |
-
nn.Linear(self.joint_embed_shape, self.joint_embed_shape),
|
| 515 |
-
)
|
| 516 |
elif text_cfg.model_type == "roberta":
|
| 517 |
self.text_branch = RobertaModel.from_pretrained("roberta-base")
|
| 518 |
|
|
@@ -529,21 +504,7 @@ class CLAP(nn.Module):
|
|
| 529 |
mlp_act_layer,
|
| 530 |
nn.Linear(self.joint_embed_shape, self.joint_embed_shape),
|
| 531 |
)
|
| 532 |
-
|
| 533 |
-
self.text_branch = BartModel.from_pretrained("facebook/bart-base")
|
| 534 |
-
self.text_transform = MLPLayers(
|
| 535 |
-
units=[
|
| 536 |
-
self.joint_embed_shape,
|
| 537 |
-
self.joint_embed_shape,
|
| 538 |
-
self.joint_embed_shape,
|
| 539 |
-
],
|
| 540 |
-
dropout=0.1,
|
| 541 |
-
)
|
| 542 |
-
self.text_projection = nn.Sequential(
|
| 543 |
-
nn.Linear(768, self.joint_embed_shape),
|
| 544 |
-
mlp_act_layer,
|
| 545 |
-
nn.Linear(self.joint_embed_shape, self.joint_embed_shape),
|
| 546 |
-
)
|
| 547 |
else:
|
| 548 |
logging.error(f"Model config for {text_cfg.model_type} not found")
|
| 549 |
raise RuntimeError(f"Model config for {text_cfg.model_type} not found.")
|
|
|
|
| 14 |
import torch.nn.functional as F
|
| 15 |
from torch import nn
|
| 16 |
|
|
|
|
| 17 |
import logging
|
| 18 |
from .utils import freeze_batch_norm_2d
|
|
|
|
|
|
|
| 19 |
from .htsat import create_htsat_model
|
| 20 |
+
from transformers import RobertaModel, RobertaConfig
|
| 21 |
+
# removed: TimmModel, create_pann_model, BertModel, BartModel — only HTSAT audio + roberta text used in inference
|
| 22 |
from transformers.tokenization_utils_base import BatchEncoding
|
| 23 |
|
| 24 |
|
|
|
|
| 456 |
else:
|
| 457 |
raise NotImplementedError
|
| 458 |
|
| 459 |
+
# audio branch — removed: PANN branch, only HTSAT used
|
| 460 |
+
self.audio_branch = create_htsat_model(audio_cfg, enable_fusion, fusion_type)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
|
| 462 |
# text branch
|
| 463 |
# text branch parameters
|
|
|
|
| 487 |
mlp_act_layer,
|
| 488 |
nn.Linear(self.joint_embed_shape, self.joint_embed_shape),
|
| 489 |
)
|
| 490 |
+
# removed: bert branch — only roberta used
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
elif text_cfg.model_type == "roberta":
|
| 492 |
self.text_branch = RobertaModel.from_pretrained("roberta-base")
|
| 493 |
|
|
|
|
| 504 |
mlp_act_layer,
|
| 505 |
nn.Linear(self.joint_embed_shape, self.joint_embed_shape),
|
| 506 |
)
|
| 507 |
+
# removed: bart branch — only roberta used
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
else:
|
| 509 |
logging.error(f"Model config for {text_cfg.model_type} not found")
|
| 510 |
raise RuntimeError(f"Model config for {text_cfg.model_type} not found.")
|
models/CLAP/open_clip/pann_model.py
DELETED
|
@@ -1,704 +0,0 @@
|
|
| 1 |
-
# PANNs: Large-Scale Pretrained Audio Neural Networks for Audio Pattern Recognition
|
| 2 |
-
# Reference from https://github.com/qiuqiangkong/audioset_tagging_cnn
|
| 3 |
-
# Some layers are re-designed for CLAP
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
os.environ["NUMBA_CACHE_DIR"] = "/tmp/"
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
import torch.nn as nn
|
| 10 |
-
import torch.nn.functional as F
|
| 11 |
-
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
|
| 12 |
-
from torchlibrosa.augmentation import SpecAugmentation
|
| 13 |
-
|
| 14 |
-
from .utils import do_mixup, interpolate, pad_framewise_output
|
| 15 |
-
from .feature_fusion import iAFF, AFF, DAF
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def init_layer(layer):
|
| 19 |
-
"""Initialize a Linear or Convolutional layer."""
|
| 20 |
-
nn.init.xavier_uniform_(layer.weight)
|
| 21 |
-
|
| 22 |
-
if hasattr(layer, "bias"):
|
| 23 |
-
if layer.bias is not None:
|
| 24 |
-
layer.bias.data.fill_(0.0)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def init_bn(bn):
|
| 28 |
-
"""Initialize a Batchnorm layer."""
|
| 29 |
-
bn.bias.data.fill_(0.0)
|
| 30 |
-
bn.weight.data.fill_(1.0)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
class ConvBlock(nn.Module):
|
| 34 |
-
def __init__(self, in_channels, out_channels):
|
| 35 |
-
|
| 36 |
-
super(ConvBlock, self).__init__()
|
| 37 |
-
|
| 38 |
-
self.conv1 = nn.Conv2d(
|
| 39 |
-
in_channels=in_channels,
|
| 40 |
-
out_channels=out_channels,
|
| 41 |
-
kernel_size=(3, 3),
|
| 42 |
-
stride=(1, 1),
|
| 43 |
-
padding=(1, 1),
|
| 44 |
-
bias=False,
|
| 45 |
-
)
|
| 46 |
-
|
| 47 |
-
self.conv2 = nn.Conv2d(
|
| 48 |
-
in_channels=out_channels,
|
| 49 |
-
out_channels=out_channels,
|
| 50 |
-
kernel_size=(3, 3),
|
| 51 |
-
stride=(1, 1),
|
| 52 |
-
padding=(1, 1),
|
| 53 |
-
bias=False,
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
self.bn1 = nn.BatchNorm2d(out_channels)
|
| 57 |
-
self.bn2 = nn.BatchNorm2d(out_channels)
|
| 58 |
-
|
| 59 |
-
self.init_weight()
|
| 60 |
-
|
| 61 |
-
def init_weight(self):
|
| 62 |
-
init_layer(self.conv1)
|
| 63 |
-
init_layer(self.conv2)
|
| 64 |
-
init_bn(self.bn1)
|
| 65 |
-
init_bn(self.bn2)
|
| 66 |
-
|
| 67 |
-
def forward(self, input, pool_size=(2, 2), pool_type="avg"):
|
| 68 |
-
|
| 69 |
-
x = input
|
| 70 |
-
x = F.relu_(self.bn1(self.conv1(x)))
|
| 71 |
-
x = F.relu_(self.bn2(self.conv2(x)))
|
| 72 |
-
if pool_type == "max":
|
| 73 |
-
x = F.max_pool2d(x, kernel_size=pool_size)
|
| 74 |
-
elif pool_type == "avg":
|
| 75 |
-
x = F.avg_pool2d(x, kernel_size=pool_size)
|
| 76 |
-
elif pool_type == "avg+max":
|
| 77 |
-
x1 = F.avg_pool2d(x, kernel_size=pool_size)
|
| 78 |
-
x2 = F.max_pool2d(x, kernel_size=pool_size)
|
| 79 |
-
x = x1 + x2
|
| 80 |
-
else:
|
| 81 |
-
raise Exception("Incorrect argument!")
|
| 82 |
-
|
| 83 |
-
return x
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
class ConvBlock5x5(nn.Module):
|
| 87 |
-
def __init__(self, in_channels, out_channels):
|
| 88 |
-
|
| 89 |
-
super(ConvBlock5x5, self).__init__()
|
| 90 |
-
|
| 91 |
-
self.conv1 = nn.Conv2d(
|
| 92 |
-
in_channels=in_channels,
|
| 93 |
-
out_channels=out_channels,
|
| 94 |
-
kernel_size=(5, 5),
|
| 95 |
-
stride=(1, 1),
|
| 96 |
-
padding=(2, 2),
|
| 97 |
-
bias=False,
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
self.bn1 = nn.BatchNorm2d(out_channels)
|
| 101 |
-
|
| 102 |
-
self.init_weight()
|
| 103 |
-
|
| 104 |
-
def init_weight(self):
|
| 105 |
-
init_layer(self.conv1)
|
| 106 |
-
init_bn(self.bn1)
|
| 107 |
-
|
| 108 |
-
def forward(self, input, pool_size=(2, 2), pool_type="avg"):
|
| 109 |
-
|
| 110 |
-
x = input
|
| 111 |
-
x = F.relu_(self.bn1(self.conv1(x)))
|
| 112 |
-
if pool_type == "max":
|
| 113 |
-
x = F.max_pool2d(x, kernel_size=pool_size)
|
| 114 |
-
elif pool_type == "avg":
|
| 115 |
-
x = F.avg_pool2d(x, kernel_size=pool_size)
|
| 116 |
-
elif pool_type == "avg+max":
|
| 117 |
-
x1 = F.avg_pool2d(x, kernel_size=pool_size)
|
| 118 |
-
x2 = F.max_pool2d(x, kernel_size=pool_size)
|
| 119 |
-
x = x1 + x2
|
| 120 |
-
else:
|
| 121 |
-
raise Exception("Incorrect argument!")
|
| 122 |
-
|
| 123 |
-
return x
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
class AttBlock(nn.Module):
|
| 127 |
-
def __init__(self, n_in, n_out, activation="linear", temperature=1.0):
|
| 128 |
-
super(AttBlock, self).__init__()
|
| 129 |
-
|
| 130 |
-
self.activation = activation
|
| 131 |
-
self.temperature = temperature
|
| 132 |
-
self.att = nn.Conv1d(
|
| 133 |
-
in_channels=n_in,
|
| 134 |
-
out_channels=n_out,
|
| 135 |
-
kernel_size=1,
|
| 136 |
-
stride=1,
|
| 137 |
-
padding=0,
|
| 138 |
-
bias=True,
|
| 139 |
-
)
|
| 140 |
-
self.cla = nn.Conv1d(
|
| 141 |
-
in_channels=n_in,
|
| 142 |
-
out_channels=n_out,
|
| 143 |
-
kernel_size=1,
|
| 144 |
-
stride=1,
|
| 145 |
-
padding=0,
|
| 146 |
-
bias=True,
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
self.bn_att = nn.BatchNorm1d(n_out)
|
| 150 |
-
self.init_weights()
|
| 151 |
-
|
| 152 |
-
def init_weights(self):
|
| 153 |
-
init_layer(self.att)
|
| 154 |
-
init_layer(self.cla)
|
| 155 |
-
init_bn(self.bn_att)
|
| 156 |
-
|
| 157 |
-
def forward(self, x):
|
| 158 |
-
# x: (n_samples, n_in, n_time)
|
| 159 |
-
norm_att = torch.softmax(torch.clamp(self.att(x), -10, 10), dim=-1)
|
| 160 |
-
cla = self.nonlinear_transform(self.cla(x))
|
| 161 |
-
x = torch.sum(norm_att * cla, dim=2)
|
| 162 |
-
return x, norm_att, cla
|
| 163 |
-
|
| 164 |
-
def nonlinear_transform(self, x):
|
| 165 |
-
if self.activation == "linear":
|
| 166 |
-
return x
|
| 167 |
-
elif self.activation == "sigmoid":
|
| 168 |
-
return torch.sigmoid(x)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
class Cnn14(nn.Module):
|
| 172 |
-
def __init__(
|
| 173 |
-
self,
|
| 174 |
-
sample_rate,
|
| 175 |
-
window_size,
|
| 176 |
-
hop_size,
|
| 177 |
-
mel_bins,
|
| 178 |
-
fmin,
|
| 179 |
-
fmax,
|
| 180 |
-
classes_num,
|
| 181 |
-
enable_fusion=False,
|
| 182 |
-
fusion_type="None",
|
| 183 |
-
):
|
| 184 |
-
|
| 185 |
-
super(Cnn14, self).__init__()
|
| 186 |
-
|
| 187 |
-
window = "hann"
|
| 188 |
-
center = True
|
| 189 |
-
pad_mode = "reflect"
|
| 190 |
-
ref = 1.0
|
| 191 |
-
amin = 1e-10
|
| 192 |
-
top_db = None
|
| 193 |
-
|
| 194 |
-
self.enable_fusion = enable_fusion
|
| 195 |
-
self.fusion_type = fusion_type
|
| 196 |
-
|
| 197 |
-
# Spectrogram extractor
|
| 198 |
-
self.spectrogram_extractor = Spectrogram(
|
| 199 |
-
n_fft=window_size,
|
| 200 |
-
hop_length=hop_size,
|
| 201 |
-
win_length=window_size,
|
| 202 |
-
window=window,
|
| 203 |
-
center=center,
|
| 204 |
-
pad_mode=pad_mode,
|
| 205 |
-
freeze_parameters=True,
|
| 206 |
-
)
|
| 207 |
-
|
| 208 |
-
# Logmel feature extractor
|
| 209 |
-
self.logmel_extractor = LogmelFilterBank(
|
| 210 |
-
sr=sample_rate,
|
| 211 |
-
n_fft=window_size,
|
| 212 |
-
n_mels=mel_bins,
|
| 213 |
-
fmin=fmin,
|
| 214 |
-
fmax=fmax,
|
| 215 |
-
ref=ref,
|
| 216 |
-
amin=amin,
|
| 217 |
-
top_db=top_db,
|
| 218 |
-
freeze_parameters=True,
|
| 219 |
-
)
|
| 220 |
-
|
| 221 |
-
# Spec augmenter
|
| 222 |
-
self.spec_augmenter = SpecAugmentation(
|
| 223 |
-
time_drop_width=64,
|
| 224 |
-
time_stripes_num=2,
|
| 225 |
-
freq_drop_width=8,
|
| 226 |
-
freq_stripes_num=2,
|
| 227 |
-
)
|
| 228 |
-
|
| 229 |
-
self.bn0 = nn.BatchNorm2d(64)
|
| 230 |
-
|
| 231 |
-
if (self.enable_fusion) and (self.fusion_type == "channel_map"):
|
| 232 |
-
self.conv_block1 = ConvBlock(in_channels=4, out_channels=64)
|
| 233 |
-
else:
|
| 234 |
-
self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)
|
| 235 |
-
self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)
|
| 236 |
-
self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)
|
| 237 |
-
self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)
|
| 238 |
-
self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)
|
| 239 |
-
self.conv_block6 = ConvBlock(in_channels=1024, out_channels=2048)
|
| 240 |
-
|
| 241 |
-
self.fc1 = nn.Linear(2048, 2048, bias=True)
|
| 242 |
-
self.fc_audioset = nn.Linear(2048, classes_num, bias=True)
|
| 243 |
-
|
| 244 |
-
if (self.enable_fusion) and (
|
| 245 |
-
self.fusion_type in ["daf_1d", "aff_1d", "iaff_1d"]
|
| 246 |
-
):
|
| 247 |
-
self.mel_conv1d = nn.Sequential(
|
| 248 |
-
nn.Conv1d(64, 64, kernel_size=5, stride=3, padding=2),
|
| 249 |
-
nn.BatchNorm1d(64), # No Relu
|
| 250 |
-
)
|
| 251 |
-
if self.fusion_type == "daf_1d":
|
| 252 |
-
self.fusion_model = DAF()
|
| 253 |
-
elif self.fusion_type == "aff_1d":
|
| 254 |
-
self.fusion_model = AFF(channels=64, type="1D")
|
| 255 |
-
elif self.fusion_type == "iaff_1d":
|
| 256 |
-
self.fusion_model = iAFF(channels=64, type="1D")
|
| 257 |
-
|
| 258 |
-
if (self.enable_fusion) and (
|
| 259 |
-
self.fusion_type in ["daf_2d", "aff_2d", "iaff_2d"]
|
| 260 |
-
):
|
| 261 |
-
self.mel_conv2d = nn.Sequential(
|
| 262 |
-
nn.Conv2d(1, 64, kernel_size=(5, 5), stride=(6, 2), padding=(2, 2)),
|
| 263 |
-
nn.BatchNorm2d(64),
|
| 264 |
-
nn.ReLU(inplace=True),
|
| 265 |
-
)
|
| 266 |
-
|
| 267 |
-
if self.fusion_type == "daf_2d":
|
| 268 |
-
self.fusion_model = DAF()
|
| 269 |
-
elif self.fusion_type == "aff_2d":
|
| 270 |
-
self.fusion_model = AFF(channels=64, type="2D")
|
| 271 |
-
elif self.fusion_type == "iaff_2d":
|
| 272 |
-
self.fusion_model = iAFF(channels=64, type="2D")
|
| 273 |
-
self.init_weight()
|
| 274 |
-
|
| 275 |
-
def init_weight(self):
|
| 276 |
-
init_bn(self.bn0)
|
| 277 |
-
init_layer(self.fc1)
|
| 278 |
-
init_layer(self.fc_audioset)
|
| 279 |
-
|
| 280 |
-
def forward(self, input, mixup_lambda=None, device=None):
|
| 281 |
-
"""
|
| 282 |
-
Input: (batch_size, data_length)"""
|
| 283 |
-
|
| 284 |
-
if self.enable_fusion and input["longer"].sum() == 0:
|
| 285 |
-
# if no audio is longer than 10s, then randomly select one audio to be longer
|
| 286 |
-
input["longer"][torch.randint(0, input["longer"].shape[0], (1,))] = True
|
| 287 |
-
|
| 288 |
-
if not self.enable_fusion:
|
| 289 |
-
x = self.spectrogram_extractor(
|
| 290 |
-
input["waveform"].to(device=device, non_blocking=True)
|
| 291 |
-
) # (batch_size, 1, time_steps, freq_bins)
|
| 292 |
-
x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)
|
| 293 |
-
|
| 294 |
-
x = x.transpose(1, 3)
|
| 295 |
-
x = self.bn0(x)
|
| 296 |
-
x = x.transpose(1, 3)
|
| 297 |
-
else:
|
| 298 |
-
longer_list = input["longer"].to(device=device, non_blocking=True)
|
| 299 |
-
x = input["mel_fusion"].to(device=device, non_blocking=True)
|
| 300 |
-
longer_list_idx = torch.where(longer_list)[0]
|
| 301 |
-
x = x.transpose(1, 3)
|
| 302 |
-
x = self.bn0(x)
|
| 303 |
-
x = x.transpose(1, 3)
|
| 304 |
-
if self.fusion_type in ["daf_1d", "aff_1d", "iaff_1d"]:
|
| 305 |
-
new_x = x[:, 0:1, :, :].clone().contiguous()
|
| 306 |
-
# local processing
|
| 307 |
-
if len(longer_list_idx) > 0:
|
| 308 |
-
fusion_x_local = x[longer_list_idx, 1:, :, :].clone().contiguous()
|
| 309 |
-
FB, FC, FT, FF = fusion_x_local.size()
|
| 310 |
-
fusion_x_local = fusion_x_local.view(FB * FC, FT, FF)
|
| 311 |
-
fusion_x_local = torch.permute(
|
| 312 |
-
fusion_x_local, (0, 2, 1)
|
| 313 |
-
).contiguous()
|
| 314 |
-
fusion_x_local = self.mel_conv1d(fusion_x_local)
|
| 315 |
-
fusion_x_local = fusion_x_local.view(
|
| 316 |
-
FB, FC, FF, fusion_x_local.size(-1)
|
| 317 |
-
)
|
| 318 |
-
fusion_x_local = (
|
| 319 |
-
torch.permute(fusion_x_local, (0, 2, 1, 3))
|
| 320 |
-
.contiguous()
|
| 321 |
-
.flatten(2)
|
| 322 |
-
)
|
| 323 |
-
if fusion_x_local.size(-1) < FT:
|
| 324 |
-
fusion_x_local = torch.cat(
|
| 325 |
-
[
|
| 326 |
-
fusion_x_local,
|
| 327 |
-
torch.zeros(
|
| 328 |
-
(FB, FF, FT - fusion_x_local.size(-1)),
|
| 329 |
-
device=device,
|
| 330 |
-
),
|
| 331 |
-
],
|
| 332 |
-
dim=-1,
|
| 333 |
-
)
|
| 334 |
-
else:
|
| 335 |
-
fusion_x_local = fusion_x_local[:, :, :FT]
|
| 336 |
-
# 1D fusion
|
| 337 |
-
new_x = new_x.squeeze(1).permute((0, 2, 1)).contiguous()
|
| 338 |
-
new_x[longer_list_idx] = self.fusion_model(
|
| 339 |
-
new_x[longer_list_idx], fusion_x_local
|
| 340 |
-
)
|
| 341 |
-
x = new_x.permute((0, 2, 1)).contiguous()[:, None, :, :]
|
| 342 |
-
else:
|
| 343 |
-
x = new_x
|
| 344 |
-
elif self.fusion_type in ["daf_2d", "aff_2d", "iaff_2d", "channel_map"]:
|
| 345 |
-
x = x # no change
|
| 346 |
-
|
| 347 |
-
if self.training:
|
| 348 |
-
x = self.spec_augmenter(x)
|
| 349 |
-
# Mixup on spectrogram
|
| 350 |
-
if self.training and mixup_lambda is not None:
|
| 351 |
-
x = do_mixup(x, mixup_lambda)
|
| 352 |
-
if (self.enable_fusion) and (
|
| 353 |
-
self.fusion_type in ["daf_2d", "aff_2d", "iaff_2d"]
|
| 354 |
-
):
|
| 355 |
-
global_x = x[:, 0:1, :, :]
|
| 356 |
-
|
| 357 |
-
# global processing
|
| 358 |
-
B, C, H, W = global_x.shape
|
| 359 |
-
global_x = self.conv_block1(global_x, pool_size=(2, 2), pool_type="avg")
|
| 360 |
-
if len(longer_list_idx) > 0:
|
| 361 |
-
local_x = x[longer_list_idx, 1:, :, :].contiguous()
|
| 362 |
-
TH = global_x.size(-2)
|
| 363 |
-
# local processing
|
| 364 |
-
B, C, H, W = local_x.shape
|
| 365 |
-
local_x = local_x.view(B * C, 1, H, W)
|
| 366 |
-
local_x = self.mel_conv2d(local_x)
|
| 367 |
-
local_x = local_x.view(
|
| 368 |
-
B, C, local_x.size(1), local_x.size(2), local_x.size(3)
|
| 369 |
-
)
|
| 370 |
-
local_x = local_x.permute((0, 2, 1, 3, 4)).contiguous().flatten(2, 3)
|
| 371 |
-
TB, TC, _, TW = local_x.size()
|
| 372 |
-
if local_x.size(-2) < TH:
|
| 373 |
-
local_x = torch.cat(
|
| 374 |
-
[
|
| 375 |
-
local_x,
|
| 376 |
-
torch.zeros(
|
| 377 |
-
(TB, TC, TH - local_x.size(-2), TW),
|
| 378 |
-
device=global_x.device,
|
| 379 |
-
),
|
| 380 |
-
],
|
| 381 |
-
dim=-2,
|
| 382 |
-
)
|
| 383 |
-
else:
|
| 384 |
-
local_x = local_x[:, :, :TH, :]
|
| 385 |
-
|
| 386 |
-
global_x[longer_list_idx] = self.fusion_model(
|
| 387 |
-
global_x[longer_list_idx], local_x
|
| 388 |
-
)
|
| 389 |
-
x = global_x
|
| 390 |
-
else:
|
| 391 |
-
x = self.conv_block1(x, pool_size=(2, 2), pool_type="avg")
|
| 392 |
-
|
| 393 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 394 |
-
x = self.conv_block2(x, pool_size=(2, 2), pool_type="avg")
|
| 395 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 396 |
-
x = self.conv_block3(x, pool_size=(2, 2), pool_type="avg")
|
| 397 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 398 |
-
x = self.conv_block4(x, pool_size=(2, 2), pool_type="avg")
|
| 399 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 400 |
-
x = self.conv_block5(x, pool_size=(2, 2), pool_type="avg")
|
| 401 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 402 |
-
x = self.conv_block6(x, pool_size=(1, 1), pool_type="avg")
|
| 403 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 404 |
-
x = torch.mean(x, dim=3)
|
| 405 |
-
|
| 406 |
-
latent_x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)
|
| 407 |
-
latent_x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)
|
| 408 |
-
latent_x = latent_x1 + latent_x2
|
| 409 |
-
latent_x = latent_x.transpose(1, 2)
|
| 410 |
-
latent_x = F.relu_(self.fc1(latent_x))
|
| 411 |
-
latent_output = interpolate(latent_x, 32)
|
| 412 |
-
|
| 413 |
-
(x1, _) = torch.max(x, dim=2)
|
| 414 |
-
x2 = torch.mean(x, dim=2)
|
| 415 |
-
x = x1 + x2
|
| 416 |
-
x = F.dropout(x, p=0.5, training=self.training)
|
| 417 |
-
x = F.relu_(self.fc1(x))
|
| 418 |
-
embedding = F.dropout(x, p=0.5, training=self.training)
|
| 419 |
-
clipwise_output = torch.sigmoid(self.fc_audioset(x))
|
| 420 |
-
|
| 421 |
-
output_dict = {
|
| 422 |
-
"clipwise_output": clipwise_output,
|
| 423 |
-
"embedding": embedding,
|
| 424 |
-
"fine_grained_embedding": latent_output,
|
| 425 |
-
}
|
| 426 |
-
return output_dict
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
class Cnn6(nn.Module):
|
| 430 |
-
def __init__(
|
| 431 |
-
self,
|
| 432 |
-
sample_rate,
|
| 433 |
-
window_size,
|
| 434 |
-
hop_size,
|
| 435 |
-
mel_bins,
|
| 436 |
-
fmin,
|
| 437 |
-
fmax,
|
| 438 |
-
classes_num,
|
| 439 |
-
enable_fusion=False,
|
| 440 |
-
fusion_type="None",
|
| 441 |
-
):
|
| 442 |
-
|
| 443 |
-
super(Cnn6, self).__init__()
|
| 444 |
-
|
| 445 |
-
window = "hann"
|
| 446 |
-
center = True
|
| 447 |
-
pad_mode = "reflect"
|
| 448 |
-
ref = 1.0
|
| 449 |
-
amin = 1e-10
|
| 450 |
-
top_db = None
|
| 451 |
-
|
| 452 |
-
self.enable_fusion = enable_fusion
|
| 453 |
-
self.fusion_type = fusion_type
|
| 454 |
-
|
| 455 |
-
# Spectrogram extractor
|
| 456 |
-
self.spectrogram_extractor = Spectrogram(
|
| 457 |
-
n_fft=window_size,
|
| 458 |
-
hop_length=hop_size,
|
| 459 |
-
win_length=window_size,
|
| 460 |
-
window=window,
|
| 461 |
-
center=center,
|
| 462 |
-
pad_mode=pad_mode,
|
| 463 |
-
freeze_parameters=True,
|
| 464 |
-
)
|
| 465 |
-
|
| 466 |
-
# Logmel feature extractor
|
| 467 |
-
self.logmel_extractor = LogmelFilterBank(
|
| 468 |
-
sr=sample_rate,
|
| 469 |
-
n_fft=window_size,
|
| 470 |
-
n_mels=mel_bins,
|
| 471 |
-
fmin=fmin,
|
| 472 |
-
fmax=fmax,
|
| 473 |
-
ref=ref,
|
| 474 |
-
amin=amin,
|
| 475 |
-
top_db=top_db,
|
| 476 |
-
freeze_parameters=True,
|
| 477 |
-
)
|
| 478 |
-
|
| 479 |
-
# Spec augmenter
|
| 480 |
-
self.spec_augmenter = SpecAugmentation(
|
| 481 |
-
time_drop_width=64,
|
| 482 |
-
time_stripes_num=2,
|
| 483 |
-
freq_drop_width=8,
|
| 484 |
-
freq_stripes_num=2,
|
| 485 |
-
)
|
| 486 |
-
|
| 487 |
-
self.bn0 = nn.BatchNorm2d(64)
|
| 488 |
-
|
| 489 |
-
self.conv_block1 = ConvBlock5x5(in_channels=1, out_channels=64)
|
| 490 |
-
self.conv_block2 = ConvBlock5x5(in_channels=64, out_channels=128)
|
| 491 |
-
self.conv_block3 = ConvBlock5x5(in_channels=128, out_channels=256)
|
| 492 |
-
self.conv_block4 = ConvBlock5x5(in_channels=256, out_channels=512)
|
| 493 |
-
|
| 494 |
-
self.fc1 = nn.Linear(512, 512, bias=True)
|
| 495 |
-
self.fc_audioset = nn.Linear(512, classes_num, bias=True)
|
| 496 |
-
|
| 497 |
-
self.init_weight()
|
| 498 |
-
|
| 499 |
-
def init_weight(self):
|
| 500 |
-
init_bn(self.bn0)
|
| 501 |
-
init_layer(self.fc1)
|
| 502 |
-
init_layer(self.fc_audioset)
|
| 503 |
-
|
| 504 |
-
def forward(self, input, mixup_lambda=None, device=None):
|
| 505 |
-
"""
|
| 506 |
-
Input: (batch_size, data_length)"""
|
| 507 |
-
|
| 508 |
-
x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)
|
| 509 |
-
x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)
|
| 510 |
-
|
| 511 |
-
x = x.transpose(1, 3)
|
| 512 |
-
x = self.bn0(x)
|
| 513 |
-
x = x.transpose(1, 3)
|
| 514 |
-
|
| 515 |
-
if self.training:
|
| 516 |
-
x = self.spec_augmenter(x)
|
| 517 |
-
|
| 518 |
-
# Mixup on spectrogram
|
| 519 |
-
if self.training and mixup_lambda is not None:
|
| 520 |
-
x = do_mixup(x, mixup_lambda)
|
| 521 |
-
|
| 522 |
-
x = self.conv_block1(x, pool_size=(2, 2), pool_type="avg")
|
| 523 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 524 |
-
x = self.conv_block2(x, pool_size=(2, 2), pool_type="avg")
|
| 525 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 526 |
-
x = self.conv_block3(x, pool_size=(2, 2), pool_type="avg")
|
| 527 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 528 |
-
x = self.conv_block4(x, pool_size=(2, 2), pool_type="avg")
|
| 529 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 530 |
-
x = torch.mean(x, dim=3)
|
| 531 |
-
|
| 532 |
-
latent_x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)
|
| 533 |
-
latent_x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)
|
| 534 |
-
latent_x = latent_x1 + latent_x2
|
| 535 |
-
latent_x = latent_x.transpose(1, 2)
|
| 536 |
-
latent_x = F.relu_(self.fc1(latent_x))
|
| 537 |
-
latent_output = interpolate(latent_x, 16)
|
| 538 |
-
|
| 539 |
-
(x1, _) = torch.max(x, dim=2)
|
| 540 |
-
x2 = torch.mean(x, dim=2)
|
| 541 |
-
x = x1 + x2
|
| 542 |
-
x = F.dropout(x, p=0.5, training=self.training)
|
| 543 |
-
x = F.relu_(self.fc1(x))
|
| 544 |
-
embedding = F.dropout(x, p=0.5, training=self.training)
|
| 545 |
-
clipwise_output = torch.sigmoid(self.fc_audioset(x))
|
| 546 |
-
|
| 547 |
-
output_dict = {
|
| 548 |
-
"clipwise_output": clipwise_output,
|
| 549 |
-
"embedding": embedding,
|
| 550 |
-
"fine_grained_embedding": latent_output,
|
| 551 |
-
}
|
| 552 |
-
|
| 553 |
-
return output_dict
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
class Cnn10(nn.Module):
|
| 557 |
-
def __init__(
|
| 558 |
-
self,
|
| 559 |
-
sample_rate,
|
| 560 |
-
window_size,
|
| 561 |
-
hop_size,
|
| 562 |
-
mel_bins,
|
| 563 |
-
fmin,
|
| 564 |
-
fmax,
|
| 565 |
-
classes_num,
|
| 566 |
-
enable_fusion=False,
|
| 567 |
-
fusion_type="None",
|
| 568 |
-
):
|
| 569 |
-
|
| 570 |
-
super(Cnn10, self).__init__()
|
| 571 |
-
|
| 572 |
-
window = "hann"
|
| 573 |
-
center = True
|
| 574 |
-
pad_mode = "reflect"
|
| 575 |
-
ref = 1.0
|
| 576 |
-
amin = 1e-10
|
| 577 |
-
top_db = None
|
| 578 |
-
|
| 579 |
-
self.enable_fusion = enable_fusion
|
| 580 |
-
self.fusion_type = fusion_type
|
| 581 |
-
|
| 582 |
-
# Spectrogram extractor
|
| 583 |
-
self.spectrogram_extractor = Spectrogram(
|
| 584 |
-
n_fft=window_size,
|
| 585 |
-
hop_length=hop_size,
|
| 586 |
-
win_length=window_size,
|
| 587 |
-
window=window,
|
| 588 |
-
center=center,
|
| 589 |
-
pad_mode=pad_mode,
|
| 590 |
-
freeze_parameters=True,
|
| 591 |
-
)
|
| 592 |
-
|
| 593 |
-
# Logmel feature extractor
|
| 594 |
-
self.logmel_extractor = LogmelFilterBank(
|
| 595 |
-
sr=sample_rate,
|
| 596 |
-
n_fft=window_size,
|
| 597 |
-
n_mels=mel_bins,
|
| 598 |
-
fmin=fmin,
|
| 599 |
-
fmax=fmax,
|
| 600 |
-
ref=ref,
|
| 601 |
-
amin=amin,
|
| 602 |
-
top_db=top_db,
|
| 603 |
-
freeze_parameters=True,
|
| 604 |
-
)
|
| 605 |
-
|
| 606 |
-
# Spec augmenter
|
| 607 |
-
self.spec_augmenter = SpecAugmentation(
|
| 608 |
-
time_drop_width=64,
|
| 609 |
-
time_stripes_num=2,
|
| 610 |
-
freq_drop_width=8,
|
| 611 |
-
freq_stripes_num=2,
|
| 612 |
-
)
|
| 613 |
-
|
| 614 |
-
self.bn0 = nn.BatchNorm2d(64)
|
| 615 |
-
|
| 616 |
-
self.conv_block1 = ConvBlock(in_channels=1, out_channels=64)
|
| 617 |
-
self.conv_block2 = ConvBlock(in_channels=64, out_channels=128)
|
| 618 |
-
self.conv_block3 = ConvBlock(in_channels=128, out_channels=256)
|
| 619 |
-
self.conv_block4 = ConvBlock(in_channels=256, out_channels=512)
|
| 620 |
-
self.conv_block5 = ConvBlock(in_channels=512, out_channels=1024)
|
| 621 |
-
|
| 622 |
-
self.fc1 = nn.Linear(1024, 1024, bias=True)
|
| 623 |
-
self.fc_audioset = nn.Linear(1024, classes_num, bias=True)
|
| 624 |
-
|
| 625 |
-
self.init_weight()
|
| 626 |
-
|
| 627 |
-
def init_weight(self):
|
| 628 |
-
init_bn(self.bn0)
|
| 629 |
-
init_layer(self.fc1)
|
| 630 |
-
init_layer(self.fc_audioset)
|
| 631 |
-
|
| 632 |
-
def forward(self, input, mixup_lambda=None, device=None):
|
| 633 |
-
"""
|
| 634 |
-
Input: (batch_size, data_length)"""
|
| 635 |
-
|
| 636 |
-
x = self.spectrogram_extractor(input) # (batch_size, 1, time_steps, freq_bins)
|
| 637 |
-
x = self.logmel_extractor(x) # (batch_size, 1, time_steps, mel_bins)
|
| 638 |
-
|
| 639 |
-
x = x.transpose(1, 3)
|
| 640 |
-
x = self.bn0(x)
|
| 641 |
-
x = x.transpose(1, 3)
|
| 642 |
-
|
| 643 |
-
if self.training:
|
| 644 |
-
x = self.spec_augmenter(x)
|
| 645 |
-
|
| 646 |
-
# Mixup on spectrogram
|
| 647 |
-
if self.training and mixup_lambda is not None:
|
| 648 |
-
x = do_mixup(x, mixup_lambda)
|
| 649 |
-
|
| 650 |
-
x = self.conv_block1(x, pool_size=(2, 2), pool_type="avg")
|
| 651 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 652 |
-
x = self.conv_block2(x, pool_size=(2, 2), pool_type="avg")
|
| 653 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 654 |
-
x = self.conv_block3(x, pool_size=(2, 2), pool_type="avg")
|
| 655 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 656 |
-
x = self.conv_block4(x, pool_size=(2, 2), pool_type="avg")
|
| 657 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 658 |
-
x = self.conv_block5(x, pool_size=(2, 2), pool_type="avg")
|
| 659 |
-
x = F.dropout(x, p=0.2, training=self.training)
|
| 660 |
-
x = torch.mean(x, dim=3)
|
| 661 |
-
|
| 662 |
-
latent_x1 = F.max_pool1d(x, kernel_size=3, stride=1, padding=1)
|
| 663 |
-
latent_x2 = F.avg_pool1d(x, kernel_size=3, stride=1, padding=1)
|
| 664 |
-
latent_x = latent_x1 + latent_x2
|
| 665 |
-
latent_x = latent_x.transpose(1, 2)
|
| 666 |
-
latent_x = F.relu_(self.fc1(latent_x))
|
| 667 |
-
latent_output = interpolate(latent_x, 32)
|
| 668 |
-
|
| 669 |
-
(x1, _) = torch.max(x, dim=2)
|
| 670 |
-
x2 = torch.mean(x, dim=2)
|
| 671 |
-
x = x1 + x2
|
| 672 |
-
x = F.dropout(x, p=0.5, training=self.training)
|
| 673 |
-
x = F.relu_(self.fc1(x))
|
| 674 |
-
embedding = F.dropout(x, p=0.5, training=self.training)
|
| 675 |
-
clipwise_output = torch.sigmoid(self.fc_audioset(x))
|
| 676 |
-
|
| 677 |
-
output_dict = {
|
| 678 |
-
"clipwise_output": clipwise_output,
|
| 679 |
-
"embedding": embedding,
|
| 680 |
-
"fine_grained_embedding": latent_output,
|
| 681 |
-
}
|
| 682 |
-
|
| 683 |
-
return output_dict
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
def create_pann_model(audio_cfg, enable_fusion=False, fusion_type="None"):
|
| 687 |
-
try:
|
| 688 |
-
ModelProto = eval(audio_cfg.model_name)
|
| 689 |
-
model = ModelProto(
|
| 690 |
-
sample_rate=audio_cfg.sample_rate,
|
| 691 |
-
window_size=audio_cfg.window_size,
|
| 692 |
-
hop_size=audio_cfg.hop_size,
|
| 693 |
-
mel_bins=audio_cfg.mel_bins,
|
| 694 |
-
fmin=audio_cfg.fmin,
|
| 695 |
-
fmax=audio_cfg.fmax,
|
| 696 |
-
classes_num=audio_cfg.class_num,
|
| 697 |
-
enable_fusion=enable_fusion,
|
| 698 |
-
fusion_type=fusion_type,
|
| 699 |
-
)
|
| 700 |
-
return model
|
| 701 |
-
except:
|
| 702 |
-
raise RuntimeError(
|
| 703 |
-
f"Import Model for {audio_cfg.model_name} not found, or the audio cfg parameters are not enough."
|
| 704 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
models/CLAP/open_clip/timm_model.py
DELETED
|
@@ -1,112 +0,0 @@
|
|
| 1 |
-
""" timm model adapter
|
| 2 |
-
|
| 3 |
-
Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
|
| 4 |
-
"""
|
| 5 |
-
from collections import OrderedDict
|
| 6 |
-
|
| 7 |
-
import torch.nn as nn
|
| 8 |
-
|
| 9 |
-
try:
|
| 10 |
-
import timm
|
| 11 |
-
from timm.models.layers import Mlp, to_2tuple
|
| 12 |
-
from timm.models.layers.attention_pool2d import RotAttentionPool2d
|
| 13 |
-
from timm.models.layers.attention_pool2d import (
|
| 14 |
-
AttentionPool2d as AbsAttentionPool2d,
|
| 15 |
-
)
|
| 16 |
-
except ImportError as e:
|
| 17 |
-
timm = None
|
| 18 |
-
|
| 19 |
-
from .utils import freeze_batch_norm_2d
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
class TimmModel(nn.Module):
|
| 23 |
-
"""timm model adapter
|
| 24 |
-
# FIXME this adapter is a work in progress, may change in ways that break weight compat
|
| 25 |
-
"""
|
| 26 |
-
|
| 27 |
-
def __init__(
|
| 28 |
-
self,
|
| 29 |
-
model_name,
|
| 30 |
-
embed_dim,
|
| 31 |
-
image_size=224,
|
| 32 |
-
pool="avg",
|
| 33 |
-
proj="linear",
|
| 34 |
-
drop=0.0,
|
| 35 |
-
pretrained=False,
|
| 36 |
-
):
|
| 37 |
-
super().__init__()
|
| 38 |
-
if timm is None:
|
| 39 |
-
raise RuntimeError("Please `pip install timm` to use timm models.")
|
| 40 |
-
|
| 41 |
-
self.image_size = to_2tuple(image_size)
|
| 42 |
-
self.trunk = timm.create_model(model_name, pretrained=pretrained)
|
| 43 |
-
feat_size = self.trunk.default_cfg.get("pool_size", None)
|
| 44 |
-
feature_ndim = 1 if not feat_size else 2
|
| 45 |
-
if pool in ("abs_attn", "rot_attn"):
|
| 46 |
-
assert feature_ndim == 2
|
| 47 |
-
# if attn pooling used, remove both classifier and default pool
|
| 48 |
-
self.trunk.reset_classifier(0, global_pool="")
|
| 49 |
-
else:
|
| 50 |
-
# reset global pool if pool config set, otherwise leave as network default
|
| 51 |
-
reset_kwargs = dict(global_pool=pool) if pool else {}
|
| 52 |
-
self.trunk.reset_classifier(0, **reset_kwargs)
|
| 53 |
-
prev_chs = self.trunk.num_features
|
| 54 |
-
|
| 55 |
-
head_layers = OrderedDict()
|
| 56 |
-
if pool == "abs_attn":
|
| 57 |
-
head_layers["pool"] = AbsAttentionPool2d(
|
| 58 |
-
prev_chs, feat_size=feat_size, out_features=embed_dim
|
| 59 |
-
)
|
| 60 |
-
prev_chs = embed_dim
|
| 61 |
-
elif pool == "rot_attn":
|
| 62 |
-
head_layers["pool"] = RotAttentionPool2d(prev_chs, out_features=embed_dim)
|
| 63 |
-
prev_chs = embed_dim
|
| 64 |
-
else:
|
| 65 |
-
assert proj, "projection layer needed if non-attention pooling is used."
|
| 66 |
-
|
| 67 |
-
# NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used
|
| 68 |
-
if proj == "linear":
|
| 69 |
-
head_layers["drop"] = nn.Dropout(drop)
|
| 70 |
-
head_layers["proj"] = nn.Linear(prev_chs, embed_dim)
|
| 71 |
-
elif proj == "mlp":
|
| 72 |
-
head_layers["mlp"] = Mlp(prev_chs, 2 * embed_dim, embed_dim, drop=drop)
|
| 73 |
-
|
| 74 |
-
self.head = nn.Sequential(head_layers)
|
| 75 |
-
|
| 76 |
-
def lock(self, unlocked_groups=0, freeze_bn_stats=False):
|
| 77 |
-
"""lock modules
|
| 78 |
-
Args:
|
| 79 |
-
unlocked_groups (int): leave last n layer groups unlocked (default: 0)
|
| 80 |
-
"""
|
| 81 |
-
if not unlocked_groups:
|
| 82 |
-
# lock full model
|
| 83 |
-
for param in self.trunk.parameters():
|
| 84 |
-
param.requires_grad = False
|
| 85 |
-
if freeze_bn_stats:
|
| 86 |
-
freeze_batch_norm_2d(self.trunk)
|
| 87 |
-
else:
|
| 88 |
-
# NOTE: partial freeze requires latest timm (master) branch and is subject to change
|
| 89 |
-
try:
|
| 90 |
-
# FIXME import here until API stable and in an official release
|
| 91 |
-
from timm.models.helpers import group_parameters, group_modules
|
| 92 |
-
except ImportError:
|
| 93 |
-
raise RuntimeError(
|
| 94 |
-
"Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`"
|
| 95 |
-
)
|
| 96 |
-
matcher = self.trunk.group_matcher()
|
| 97 |
-
gparams = group_parameters(self.trunk, matcher)
|
| 98 |
-
max_layer_id = max(gparams.keys())
|
| 99 |
-
max_layer_id = max_layer_id - unlocked_groups
|
| 100 |
-
for group_idx in range(max_layer_id + 1):
|
| 101 |
-
group = gparams[group_idx]
|
| 102 |
-
for param in group:
|
| 103 |
-
self.trunk.get_parameter(param).requires_grad = False
|
| 104 |
-
if freeze_bn_stats:
|
| 105 |
-
gmodules = group_modules(self.trunk, matcher, reverse=True)
|
| 106 |
-
gmodules = {k for k, v in gmodules.items() if v <= max_layer_id}
|
| 107 |
-
freeze_batch_norm_2d(self.trunk, gmodules)
|
| 108 |
-
|
| 109 |
-
def forward(self, x):
|
| 110 |
-
x = self.trunk(x)
|
| 111 |
-
x = self.head(x)
|
| 112 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|