Audio Classification
autrainer
audio
ecoacoustic-tagging
HearTheSpecies
ecoacoustics
AlexanderGbd commited on
Commit
5374684
·
verified ·
1 Parent(s): dce20d3

Upload clap.py

Browse files
Files changed (1) hide show
  1. clap.py +130 -0
clap.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import torch
4
+ from transformers import ClapAudioModel, ClapAudioModelWithProjection, ClapFeatureExtractor, ClapProcessor
5
+
6
+ from autrainer.models.abstract_model import AbstractModel
7
+ from autrainer.models.ffnn import FFNN
8
+
9
+
10
+ class CLAPBackbone(AbstractModel):
11
+ def __init__(
12
+ self,
13
+ model_name,
14
+ freeze_extractor: bool = True,
15
+ time_pooling: bool = True,
16
+ ) -> None:
17
+ self.model_name = model_name
18
+ self.freeze_extractor = freeze_extractor
19
+ self.time_pooling = time_pooling
20
+
21
+ model = ClapAudioModelWithProjection.from_pretrained(self.model_name)
22
+ super().__init__(output_dim=model.config.hidden_size)
23
+
24
+ self.model = model.audio_model.audio_encoder
25
+ # self.model = model
26
+ # print(self.model)
27
+
28
+ if self.freeze_extractor:
29
+ for param in self.model.parameters():
30
+ param.requires_grad = False
31
+
32
+ def embeddings(self, x: torch.Tensor) -> torch.Tensor:
33
+ inputs = x
34
+ is_longer = torch.tensor([False])
35
+
36
+ x = self.model(input_features=inputs, is_longer=is_longer).last_hidden_state
37
+
38
+ # Flatten and transpose for the embeddings
39
+ x = x.flatten(2).transpose(1, 2)
40
+
41
+ if self.time_pooling:
42
+ x = x.mean(1)
43
+
44
+ return x
45
+
46
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
47
+ return self.embeddings(features)
48
+
49
+
50
+ class CLAPFFNN(AbstractModel):
51
+ def __init__(
52
+ self,
53
+ output_dim: int,
54
+ model_name: str,
55
+ freeze_extractor: bool,
56
+ hidden_size: int,
57
+ num_layers: int = 2,
58
+ dropout: float = 0.5,
59
+ ) -> None:
60
+ """CLAP model with FFNN frontend adapted for audio classification.
61
+ For more information, see: https://huggingface.co/docs/transformers/en/model_doc/clap#clap
62
+
63
+ Args:
64
+ output_dim: Output dimension of the FFNN.
65
+ model_name: Name of the model loaded from Huggingface.
66
+ freeze_extractor: Whether to freeze the feature extractor.
67
+ hidden_size: Hidden size of the FFNN.
68
+ num_layers: Number of layers of the FFNN. Defaults to 2.
69
+ dropout: Dropout rate. Defaults to 0.5.
70
+ """
71
+ super().__init__(output_dim)
72
+ self.model_name = model_name
73
+ self.freeze_extractor = freeze_extractor
74
+ self.hidden_size = hidden_size
75
+ self.num_layers = num_layers
76
+ self.dropout = dropout
77
+ self.backbone = CLAPBackbone(
78
+ model_name=model_name,
79
+ freeze_extractor=freeze_extractor,
80
+ time_pooling=True,
81
+ )
82
+ self.frontend = FFNN(
83
+ input_size=self.backbone.output_dim,
84
+ hidden_size=hidden_size,
85
+ output_dim=output_dim,
86
+ num_layers=num_layers,
87
+ dropout=dropout,
88
+ )
89
+
90
+ def embeddings(self, x: torch.Tensor) -> torch.Tensor:
91
+ return self.backbone(x)
92
+
93
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
94
+ return self.frontend(self.embeddings(features))
95
+
96
+
97
+ if __name__=='__main__':
98
+ output_dim = 4
99
+ model_name = "laion/clap-htsat-fused"
100
+ freeze_extractor = True
101
+ time_pooling = True
102
+ hidden_size = 512
103
+
104
+ model = CLAPFFNN(
105
+ output_dim=output_dim,
106
+ model_name = model_name,
107
+ freeze_extractor = freeze_extractor,
108
+ hidden_size=hidden_size
109
+ )
110
+
111
+ feature_extractor = ClapFeatureExtractor.from_pretrained('laion/clap-htsat-unfused')
112
+ # processor = ClapProcessor.from_pretrained('laion/clap-htsat-unfused')
113
+
114
+ import librosa
115
+ a, sr = librosa.load("/path/to/example.wav", sr=48000)
116
+ print(a.shape, sr)
117
+ audio = torch.tensor(a)
118
+
119
+ # inputs = processor(audios=audio, sampling_rate=48000, return_tensors="pt")
120
+ # print("Inputs:", inputs['input_features'].shape)
121
+ extracted = feature_extractor(audio, sampling_rate=48000, return_tensors='pt')
122
+ print("Extracted: ", extracted['input_features'].shape)
123
+ extracted = extracted['input_features']
124
+ # print(type(inputs))
125
+ print(type(extracted))
126
+
127
+ # features = extracted[list(extracted.keys())[0]][0].unsqueeze(0)
128
+ out = model(extracted)
129
+ print(out)
130
+ print(out.shape)