Spaces:
Running
on
Zero
Running
on
Zero
File size: 8,695 Bytes
c3c908f |
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 238 |
import torch
import torch.nn as nn
class audiocnn(nn.Module):
def __init__(self, num_classes=2):
super(audiocnn, self).__init__()
self.conv_block = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d((4,4)) # 최종 -> (B,32,4,4)
)
self.fc_block = nn.Sequential(
nn.Linear(32*4*4, 128),
nn.ReLU(),
nn.Linear(128, num_classes)
)
def forward(self, x):
x = self.conv_block(x)
# x.shape: (B,32,new_freq,new_time)
# 1) Flatten
B, C, H, W = x.shape # 동적 shape
x = x.view(B, -1) # (B, 32*H*W)
# 2) FC
x = self.fc_block(x)
return x
class AudioCNN(nn.Module):
def __init__(self, embed_dim=512):
super(AudioCNN, self).__init__()
self.conv_block = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d((4, 4)) # 최종 -> (B, 32, 4, 4)
)
self.projection = nn.Linear(32 * 4 * 4, embed_dim)
def forward(self, x):
x = self.conv_block(x)
B, C, H, W = x.shape
x = x.view(B, -1) # Flatten (B, C * H * W)
x = self.projection(x) # Project to embed_dim
return x
class ViTDecoder(nn.Module):
def __init__(self, embed_dim=512, num_heads=8, num_layers=6, num_classes=2):
super(ViTDecoder, self).__init__()
# Transformer layers
encoder_layer = nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# Classification head
self.classifier = nn.Sequential(
nn.LayerNorm(embed_dim),
nn.Linear(embed_dim, num_classes)
)
def forward(self, x):
# Transformer expects input of shape (seq_len, batch, embed_dim)
x = x.unsqueeze(1).permute(1, 0, 2) # Add sequence dim (1, B, embed_dim)
x = self.transformer(x) # Pass through Transformer
x = x.mean(dim=0) # Take the mean over the sequence dimension (B, embed_dim)
x = self.classifier(x) # Classification head
return x
class AudioCNNWithViTDecoder(nn.Module):
def __init__(self, embed_dim=512, num_heads=8, num_layers=6, num_classes=2):
super(AudioCNNWithViTDecoder, self).__init__()
self.encoder = AudioCNN(embed_dim=embed_dim)
self.decoder = ViTDecoder(embed_dim=embed_dim, num_heads=num_heads, num_layers=num_layers, num_classes=num_classes)
def forward(self, x):
x = self.encoder(x) # Pass through AudioCNN encoder
x = self.decoder(x) # Pass through ViT decoder
return x
# class AudioCNN(nn.Module):
# def __init__(self, num_classes=2):
# super(AudioCNN, self).__init__()
# self.conv_block = nn.Sequential(
# nn.Conv2d(1, 16, kernel_size=3, padding=1),
# nn.ReLU(),
# nn.MaxPool2d(2),
# nn.Conv2d(16, 32, kernel_size=3, padding=1),
# nn.ReLU(),
# nn.MaxPool2d(2),
# nn.AdaptiveAvgPool2d((4,4)) # 최종 -> (B,32,4,4)
# )
# self.fc_block = nn.Sequential(
# nn.Linear(32*4*4, 128),
# nn.ReLU(),
# nn.Linear(128, num_classes)
# )
# def forward(self, x):
# x = self.conv_block(x)
# # x.shape: (B,32,new_freq,new_time)
# # 1) Flatten
# B, C, H, W = x.shape # 동적 shape
# x = x.view(B, -1) # (B, 32*H*W)
# # 2) FC
# x = self.fc_block(x)
# return x
class audio_crossattn(nn.Module):
def __init__(self, embed_dim=512):
super(audio_crossattn, self).__init__()
self.conv_block = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d((4, 4)) # 최종 출력 -> (B, 32, 4, 4)
)
self.projection = nn.Linear(32 * 4 * 4, embed_dim)
def forward(self, x):
x = self.conv_block(x) # Convolutional feature extraction
B, C, H, W = x.shape
x = x.view(B, -1) # Flatten (B, C * H * W)
x = self.projection(x) # Linear projection to embed_dim
return x
class CrossAttentionLayer(nn.Module):
def __init__(self, embed_dim, num_heads):
super(CrossAttentionLayer, self).__init__()
self.multihead_attn = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
self.layer_norm = nn.LayerNorm(embed_dim)
self.feed_forward = nn.Sequential(
nn.Linear(embed_dim, embed_dim * 4),
nn.ReLU(),
nn.Linear(embed_dim * 4, embed_dim)
)
def forward(self, x, cross_input):
# Cross-attention between x and cross_input
attn_output, _ = self.multihead_attn(query=x, key=cross_input, value=cross_input)
x = self.layer_norm(x + attn_output) # Add & Norm
feed_forward_output = self.feed_forward(x)
x = self.layer_norm(x + feed_forward_output) # Add & Norm
return x
class ViTDecoderWithCrossAttention(nn.Module):
def __init__(self, embed_dim=512, num_heads=8, num_layers=6, num_classes=2):
super(ViTDecoderWithCrossAttention, self).__init__()
# Cross-Attention layers
self.cross_attention_layers = nn.ModuleList([
CrossAttentionLayer(embed_dim, num_heads) for _ in range(num_layers)
])
# Transformer Encoder layers
encoder_layer = nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# Classification head
self.classifier = nn.Sequential(
nn.LayerNorm(embed_dim),
nn.Linear(embed_dim, num_classes)
)
def forward(self, x, cross_attention_input):
# Pass through Cross-Attention layers
for layer in self.cross_attention_layers:
x = layer(x, cross_attention_input)
# Transformer expects input of shape (seq_len, batch, embed_dim)
x = x.unsqueeze(1).permute(1, 0, 2) # Add sequence dim (1, B, embed_dim)
x = self.transformer(x) # Pass through Transformer
embedding = x.mean(dim=0) # Take the mean over the sequence dimension (B, embed_dim)
# Classification head
x = self.classifier(embedding)
return x, embedding
# class AudioCNNWithViTDecoderAndCrossAttention(nn.Module):
# def __init__(self, embed_dim=512, num_heads=8, num_layers=6, num_classes=2):
# super(AudioCNNWithViTDecoderAndCrossAttention, self).__init__()
# self.encoder = audio_crossattn(embed_dim=embed_dim)
# self.decoder = ViTDecoderWithCrossAttention(embed_dim=embed_dim, num_heads=num_heads, num_layers=num_layers, num_classes=num_classes)
# def forward(self, x, cross_attention_input):
# # Pass through AudioCNN encoder
# x = self.encoder(x)
# # Pass through ViTDecoder with Cross-Attention
# x = self.decoder(x, cross_attention_input)
# return x
class CCV(nn.Module):
def __init__(self, embed_dim=512, num_heads=8, num_layers=6, num_classes=2, freeze_feature_extractor=True):
super(CCV, self).__init__()
self.encoder = AudioCNN(embed_dim=embed_dim)
self.decoder = ViTDecoderWithCrossAttention(embed_dim=embed_dim, num_heads=num_heads, num_layers=num_layers, num_classes=num_classes)
if freeze_feature_extractor:
for param in self.encoder.parameters():
param.requires_grad = False
for param in self.decoder.parameters():
param.requires_grad = False
def forward(self, x, cross_attention_input=None):
# Pass through AudioCNN encoder
x = self.encoder(x)
# If cross_attention_input is not provided, use the encoder output
if cross_attention_input is None:
cross_attention_input = x
# Pass through ViTDecoder with Cross-Attention
x, embedding = self.decoder(x, cross_attention_input)
return x, embedding
#---------------------------------------------------------
'''
audiocnn weight frozen
crossatten decoder -lora tuning
'''
|