Tianhao Wang commited on
Commit
dbbd709
·
1 Parent(s): ec45755

first commit

Browse files
Files changed (47) hide show
  1. .gitattributes +2 -0
  2. .gitignore +5 -0
  3. README.md +1 -0
  4. data_engine_processing/calc_resdr.py +104 -0
  5. data_engine_processing/filter_threshold.py +35 -0
  6. dataset.py +288 -0
  7. eval.py +161 -0
  8. eval.sh +14 -0
  9. experiments/ClearSep_audioset_32k/config.json +3 -0
  10. helpers/__init__.py +0 -0
  11. helpers/utils.py +205 -0
  12. infer_data_engine.sh +15 -0
  13. infer_data_engine_json.py +143 -0
  14. metadata/audioset/audioset_label.csv +3 -0
  15. metadata/audioset/class_labels_indices.csv +3 -0
  16. metadata/audioset/eval_lst.csv +3 -0
  17. metadata/audioset/ontology.json +3 -0
  18. metadata/audioset/train_lst.csv +3 -0
  19. metadata/data_engine_json/audioset_iter2_train_data_engine_th10.json +3 -0
  20. metadata/data_engine_json/audioset_iter2_train_data_engine_th15.json +3 -0
  21. metadata/data_engine_meta/child_label/bal_train_segments.json +3 -0
  22. metadata/data_engine_meta/child_label/bal_train_segments_multi_label.json +3 -0
  23. metadata/data_engine_meta/child_label/eval_segments.json +3 -0
  24. metadata/data_engine_meta/child_label/unbal_train_segments.json +3 -0
  25. metadata/data_engine_meta/child_label/unbal_train_segments_multi_label.json +3 -0
  26. metadata/evaluation/audiocaps_caption_eval.csv +3 -0
  27. metadata/evaluation/audiocaps_label_eval.csv +3 -0
  28. metadata/evaluation/audiocaps_label_eval_sep_silence_test.csv +3 -0
  29. metadata/evaluation/audioset_eval.csv +3 -0
  30. metadata/evaluation/audioset_single_eval.csv +3 -0
  31. metadata/evaluation/esc_eval.csv +3 -0
  32. metadata/evaluation/esc_eval_samples.csv +3 -0
  33. metadata/training/audiocaps_caption_32k_train.csv +3 -0
  34. metadata/training/audiocaps_caption_32k_val.csv +3 -0
  35. metadata/training/audiocaps_label_32k_train_sep.csv +3 -0
  36. metadata/training/audiocaps_label_32k_val_sep.csv +3 -0
  37. metadata/training/audioset_32k_train_sep.csv +3 -0
  38. metadata/training/audioset_32k_train_sep_th10_iter2.csv +3 -0
  39. metadata/training/audioset_32k_train_sep_th15_iter2.csv +3 -0
  40. metadata/training/audioset_32k_val_sep.csv +3 -0
  41. model/CLAPSep.py +229 -0
  42. model/CLAPSep_decoder.py +605 -0
  43. model/CLAPSep_infer.py +233 -0
  44. model/__init__.py +0 -0
  45. requirements.txt +13 -0
  46. run.sh +11 -0
  47. train.py +118 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.csv filter=lfs diff=lfs merge=lfs -text
37
+ *.json filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __pycache__
2
+
3
+ checkpoints
4
+ lightning_logs
5
+ music_audioset_epoch_15_esc_90.14.pt
README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # ClearSep
data_engine_processing/calc_resdr.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import glob
4
+ from tqdm import tqdm
5
+ import torch
6
+ import torchaudio
7
+ from torchmetrics.audio import ScaleInvariantSignalDistortionRatio, SignalDistortionRatio
8
+
9
+
10
+ def calculate_sdr_and_sisdr(original_audio_path, separated_audio_paths):
11
+ """
12
+ 计算叠加的音频与原始音频之间的 SDR 和 SI-SDR。
13
+
14
+ 参数:
15
+ - original_audio_path: str, 原始音频文件路径。
16
+ - separated_audio_paths: List[str], 分割后的音频片段文件路径列表。
17
+
18
+ 返回:
19
+ - sdr: float, SDR 值。
20
+ - sisdr: float, SI-SDR 值。
21
+ """
22
+ # 加载原始音频
23
+ original_waveform, sample_rate = torchaudio.load(original_audio_path)
24
+
25
+ # 初始化叠加的音频波形
26
+ combined_waveform = None
27
+
28
+ # 加载并叠加分割的音频片段
29
+ for path in separated_audio_paths:
30
+ separated_waveform, _ = torchaudio.load(path)
31
+
32
+ # 对齐片段长度
33
+ min_length = min(original_waveform.size(1), separated_waveform.size(1))
34
+ separated_waveform = separated_waveform[:, :min_length]
35
+
36
+ # 初始化或叠加音频
37
+ if combined_waveform is None:
38
+ combined_waveform = separated_waveform
39
+ else:
40
+ combined_waveform = combined_waveform[:, :min_length] + separated_waveform
41
+
42
+ # 确保合并后的音频和原始音频的长度一致
43
+ min_length = min(original_waveform.size(1), combined_waveform.size(1))
44
+ original_waveform = original_waveform[:, :min_length]
45
+ combined_waveform = combined_waveform[:, :min_length]
46
+
47
+ # 计算 SI-SDR
48
+ sisdr_metric = ScaleInvariantSignalDistortionRatio()
49
+ sisdr = sisdr_metric(combined_waveform, original_waveform).item()
50
+
51
+ # 计算 SDR
52
+ sdr_metric = SignalDistortionRatio()
53
+ sdr = sdr_metric(combined_waveform, original_waveform).item()
54
+
55
+ # print(f"SI-SDR between original and combined audio: {sisdr} dB")
56
+ # print(f"SDR between original and combined audio: {sdr} dB")
57
+
58
+ return sdr, sisdr
59
+
60
+
61
+ if __name__ == "__main__":
62
+ # 示例: 指定原始音频和分割后的音频片段路径
63
+ # original_audio_path = "path_to_original_audio.wav"
64
+ # separated_audio_paths = [
65
+ # "path_to_segment_1.wav",
66
+ # "path_to_segment_2.wav",
67
+ # "path_to_segment_3.wav",
68
+ # ]
69
+
70
+ # # 计算 SDR 和 SI-SDR
71
+ # sdr, sisdr = calculate_sdr_and_sisdr(original_audio_path, separated_audio_paths)
72
+
73
+
74
+ dset = 'balanced_train_segments'
75
+ # dset = 'eval_segments'
76
+
77
+ src_data_root = r'/data/sound/audioset/audios_32k'
78
+ sep_data_root = r'data_engine_infer/audioset_separation_child_label'
79
+
80
+ writer = csv.writer(open(os.path.join(sep_data_root, dset + '.csv'), 'w'))
81
+ writer.writerow(['video', 'sdr', 'sisdr'])
82
+ for video_path in tqdm(glob.glob(os.path.join(sep_data_root, dset, '*'))):
83
+ video = video_path.split('/')[-1]
84
+ original_audio_path = os.path.join(src_data_root, dset, video + '.wav')
85
+ separated_audio_paths = glob.glob(video_path + '/*')
86
+ sdr, sisdr = calculate_sdr_and_sisdr(original_audio_path, separated_audio_paths)
87
+ writer.writerow([video, f'{sdr:.3f}', f'{sisdr:.3f}'])
88
+
89
+
90
+ # dset = 'unbalanced_train_segments'
91
+
92
+ # src_data_root = r'/data/sound/audioset/audios_32k'
93
+ # sep_data_root = r'data_engine_infer/audioset_separation_child_label'
94
+
95
+ # writer = csv.writer(open(os.path.join(sep_data_root, dset + '.csv'), 'w'))
96
+ # writer.writerow(['video', 'sdr', 'sisdr'])
97
+ # for video_path in tqdm(glob.glob(os.path.join(sep_data_root, dset, '*', '*'))):
98
+ # part = video_path.split('/')[-2]
99
+ # video = video_path.split('/')[-1]
100
+ # original_audio_path = os.path.join(src_data_root, dset, part, video + '.wav')
101
+ # separated_audio_paths = glob.glob(video_path + '/*')
102
+ # sdr, sisdr = calculate_sdr_and_sisdr(original_audio_path, separated_audio_paths)
103
+ # writer.writerow([video, f'{sdr:.3f}', f'{sisdr:.3f}'])
104
+
data_engine_processing/filter_threshold.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import glob
4
+ from tqdm import tqdm
5
+
6
+
7
+ audioset_labels = set()
8
+ reader = csv.reader(open('metadata/audioset/class_labels_indices.csv', 'r'))
9
+ next(reader)
10
+ for item in reader:
11
+ assert len(item) == 3
12
+ audioset_labels.add(item[-1])
13
+
14
+ sdr_dict = dict()
15
+ reader = csv.reader(open('data_engine_infer/audioset_separation_child_label/balanced_train_segments.csv', 'r'))
16
+ next(reader)
17
+ for item in reader:
18
+ sdr_dict[item[0]] = min(float(item[1]), float(item[2]))
19
+
20
+
21
+ writer_10 = csv.writer(open('data_engine_infer/audioset_separation_child_label/audioset_bal_data_engine_th10.csv', 'w'))
22
+ writer_15 = csv.writer(open('data_engine_infer/audioset_separation_child_label/audioset_bal_data_engine_th15.csv', 'w'))
23
+
24
+ for video_path in tqdm(glob.glob('data_engine_infer/audioset_separation_child_label/balanced_train_segments/*')):
25
+ video = video_path.split('/')[-1]
26
+ assert video in sdr_dict
27
+ if sdr_dict[video] < 10.0:
28
+ continue
29
+ for wav_path in glob.glob(video_path + '/*.wav'):
30
+ label = wav_path.split('/')[-1][:-4]
31
+ assert label in audioset_labels, f"label: {label}, wav_path: {wav_path}"
32
+ writer_10.writerow([wav_path, label])
33
+ if sdr_dict[video] >= 15.0:
34
+ writer_15.writerow([wav_path, label])
35
+
dataset.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: UTF-8 -*-
3
+ '''
4
+ @Project :Waveformer-main
5
+ @File :dataset_online.py
6
+ @IDE :PyCharm
7
+ @Author :Aisaka/Hao Ma @SDU
8
+ @Date :2023/11/1 下午6:47
9
+ '''
10
+ import os
11
+ import random
12
+
13
+ import torch
14
+ import torchaudio
15
+ import torchaudio.transforms as AT
16
+ import csv
17
+ import json
18
+ import numpy as np
19
+ import librosa
20
+
21
+
22
+ def labels2caption(labels):
23
+ prefix = "The sound of " if len(labels) == 1 else "The sounds of "
24
+ caption = prefix + ', '.join(labels)
25
+ return caption
26
+
27
+
28
+ class CLAPSepDataSet(torch.utils.data.Dataset): # type: ignore
29
+
30
+ def __init__(self, data_list, dset='', silence_rate=0.05, chunk_dur=10, sr=None, resample_rate=None):
31
+ assert dset in ['train', 'val'], \
32
+ "`dset` must be one of ['train', 'val']"
33
+ self.dset = dset
34
+ self.silence_rate = silence_rate
35
+ self.chunk_dur = chunk_dur
36
+ self.data_meta = dict()
37
+ self.text_dict = dict()
38
+ with open(data_list, 'r', encoding='utf-8') as d:
39
+ reader = csv.reader(d, skipinitialspace=True)
40
+ for row in reader:
41
+ assert os.path.exists(row[0])
42
+ self.data_meta[row[0]] = row[1:]
43
+ label = ', '.join(row[1:])
44
+ if label not in self.text_dict:
45
+ self.text_dict[label] = []
46
+ self.text_dict[label].append(row[0])
47
+ # self.data_meta.pop('file_name')
48
+ self.augmentation = torchaudio.transforms.SpeedPerturbation(48000, [0.9, 1.1])
49
+
50
+ self.data_names = list(self.data_meta.keys())
51
+ if dset == 'val':
52
+ self.noise_names = []
53
+ for name in self.data_names:
54
+ noise_name = self.choose_other_samples(', '.join(self.data_meta[name]), 1)[0]
55
+ self.noise_names.append(noise_name)
56
+
57
+ if resample_rate is not None:
58
+ self.resampler = AT.Resample(sr, resample_rate)
59
+ self.sr = sr
60
+ self.resample_rate = resample_rate
61
+ else:
62
+ self.sr = sr
63
+
64
+ def __len__(self):
65
+ return len(self.data_names)
66
+
67
+ def choose_other_samples(self, target_text, num):
68
+ candidates = list(self.text_dict.keys())
69
+ candidates.remove(target_text)
70
+ chosen_text = random.sample(candidates, num)
71
+ chosen_samples = [random.choice(self.text_dict[text]) for text in chosen_text]
72
+ return chosen_samples
73
+
74
+ def load_wav(self, path):
75
+ max_length = self.sr * self.chunk_dur
76
+ wav = librosa.core.load(path, sr=self.sr)[0]
77
+ if len(wav) > max_length:
78
+ wav = wav[0:max_length]
79
+
80
+ # pad audio to max length, 10s for AudioCaps
81
+ if len(wav) < max_length:
82
+ wav = np.pad(wav, (0, max_length - len(wav)), 'constant')
83
+ return wav
84
+
85
+ def __getitem__(self, idx):
86
+ tgt_name = self.data_names[idx]
87
+ if self.dset =='train':
88
+ noise_name = tgt_name
89
+ while set(self.data_meta[noise_name]) & set(self.data_meta[tgt_name]):
90
+ noise_name = random.choice(self.data_names)
91
+ else:
92
+ noise_name = self.noise_names[idx]
93
+
94
+ snr = torch.zeros((1,))
95
+ # snr = (torch.rand((1,)) * 10 - 5) if self.dset == 'train' else torch.zeros((1,))
96
+ tgt = torch.tensor(self.load_wav(tgt_name)).unsqueeze(0)
97
+ noise = torch.tensor(self.load_wav(noise_name)).unsqueeze(0)
98
+ # assert not torch.isnan(tgt).any()
99
+ # assert not torch.isnan(noise).any()
100
+ mixed = torchaudio.functional.add_noise(tgt, noise, snr=snr)
101
+ assert not torch.isnan(mixed).any(), f"tgt: {tgt_name}, noise: {noise_name}"
102
+ pos_sample, _ = self.augmentation(self.resampler(tgt.squeeze()))
103
+ neg_sample, _ = self.augmentation(self.resampler(noise.squeeze()))
104
+
105
+ max_value = torch.max(torch.abs(mixed))
106
+ if max_value > 1:
107
+ tgt *= 0.9 / max_value
108
+ mixed *= 0.9 / max_value
109
+
110
+ tgt = tgt.squeeze()
111
+ mixed = mixed.squeeze()
112
+ tgt_cap = labels2caption(self.data_meta[tgt_name])
113
+ neg_cap = labels2caption(self.data_meta[noise_name])
114
+ mixed_resample = self.resampler(mixed)
115
+
116
+ # silence query
117
+ if self.dset =='train' and random.random() < self.silence_rate:
118
+ other_name = tgt_name
119
+ while set(self.data_meta[other_name]) & (set(self.data_meta[tgt_name]) | set(self.data_meta[noise_name])):
120
+ other_name = random.choice(self.data_names)
121
+ tgt = torch.zeros_like(mixed)
122
+ neg_cap = labels2caption(self.data_meta[tgt_name] + self.data_meta[noise_name])
123
+ tgt_cap = labels2caption(self.data_meta[other_name])
124
+ pos_sample, _ = self.augmentation(self.resampler(torch.tensor(self.load_wav(other_name))))
125
+ neg_sample, _ = self.augmentation(mixed_resample)
126
+
127
+ return mixed, mixed_resample, tgt_cap, neg_cap, tgt, self.pad_or_trim(pos_sample), self.pad_or_trim(neg_sample)
128
+
129
+ def pad_or_trim(self, wav_in):
130
+ target_len = 48000 * self.chunk_dur
131
+ if wav_in.size(0) < target_len:
132
+ wav_in = torch.nn.functional.pad(wav_in, (0, target_len - wav_in.size(0)))
133
+ elif wav_in.size(0) > target_len:
134
+ wav_in = wav_in[:target_len]
135
+ max_value = torch.max(torch.abs(wav_in))
136
+ if max_value > 1:
137
+ wav_in *= 0.9 / max_value
138
+ return wav_in
139
+
140
+
141
+ class CLAPSepDataEngineDataSet(torch.utils.data.Dataset): # type: ignore
142
+
143
+ def __init__(self, data_list, dset='', data_engine_json='', silence_rate=0.05, chunk_dur=10, sr=None, resample_rate=None):
144
+ assert dset in ['train', 'val'], \
145
+ "`dset` must be one of ['train', 'val']"
146
+ self.dset = dset
147
+ self.silence_rate = silence_rate
148
+ self.chunk_dur = chunk_dur
149
+ self.data_meta = dict()
150
+ with open(data_list, 'r', encoding='utf-8') as d:
151
+ reader = csv.reader(d, skipinitialspace=True)
152
+ for row in reader:
153
+ assert os.path.exists(row[0]), row[0]
154
+ self.data_meta[row[0]] = row[1:]
155
+ # self.data_meta.pop('file_name')
156
+ self.augmentation = torchaudio.transforms.SpeedPerturbation(48000, [0.9, 1.1])
157
+
158
+ self.data_names = list(self.data_meta.keys())
159
+ if dset == 'val':
160
+ self.noise_names = []
161
+ for name in self.data_names:
162
+ noise_name = name
163
+ while set(self.data_meta[noise_name]) & set(self.data_meta[name]):
164
+ noise_name = random.choice(self.data_names)
165
+ self.noise_names.append(noise_name)
166
+
167
+ self.data_engine_dict = {}
168
+ if os.path.exists(data_engine_json):
169
+ self.data_engine_dict = json.load(open(data_engine_json, 'r'))
170
+
171
+ if resample_rate is not None:
172
+ self.resampler = AT.Resample(sr, resample_rate)
173
+ self.sr = sr
174
+ self.resample_rate = resample_rate
175
+ else:
176
+ self.sr = sr
177
+
178
+ def __len__(self):
179
+ return len(self.data_names)
180
+
181
+ def load_wav(self, path):
182
+ max_length = self.sr * self.chunk_dur
183
+ wav = librosa.core.load(path, sr=self.sr)[0]
184
+ if len(wav) > max_length:
185
+ wav = wav[0:max_length]
186
+
187
+ # pad audio to max length, 10s for AudioCaps
188
+ if len(wav) < max_length:
189
+ wav = np.pad(wav, (0, max_length - len(wav)), 'constant')
190
+ return wav
191
+
192
+ def __getitem__(self, idx):
193
+ tgt_name = self.data_names[idx]
194
+ if self.dset =='train':
195
+ noise_name = tgt_name
196
+ while set(self.data_meta[noise_name]) & set(self.data_meta[tgt_name]):
197
+ noise_name = random.choice(self.data_names)
198
+ else:
199
+ noise_name = self.noise_names[idx]
200
+
201
+ snr = torch.zeros((1,))
202
+ # snr = (torch.rand((1,)) * 10 - 5) if self.dset == 'train' else torch.zeros((1,))
203
+ tgt = torch.tensor(self.load_wav(tgt_name)).unsqueeze(0)
204
+ noise = torch.tensor(self.load_wav(noise_name)).unsqueeze(0)
205
+ # assert not torch.isnan(tgt).any()
206
+ # assert not torch.isnan(noise).any()
207
+ mixed = torchaudio.functional.add_noise(tgt, noise, snr=snr)
208
+ # assert not torch.isnan(mixed).any(), f"tgt: {tgt_name}, noise: {noise_name}"
209
+
210
+ pos_sample, _ = self.augmentation(self.resampler(tgt.squeeze()))
211
+ noise = noise.squeeze()
212
+
213
+ max_value = torch.max(torch.abs(mixed))
214
+ if max_value > 1:
215
+ tgt *= 0.9 / max_value
216
+ mixed *= 0.9 / max_value
217
+
218
+ tgt = tgt.squeeze()
219
+ mixed = mixed.squeeze()
220
+ tgt_cap = labels2caption(self.data_meta[tgt_name])
221
+ neg_cap = labels2caption(self.data_meta[noise_name])
222
+ mixed_resample = self.resampler(mixed)
223
+
224
+ # A(A1, A2) + B, A1 as target, A2 + B as noise
225
+ # video = tgt_name.split('/')[-1][:-4]
226
+ # if self.dset =='train' and video in self.data_engine_dict and random.random() > 0.5:
227
+ # items = self.data_engine_dict[video]
228
+ # tgt_idx = random.choice(range(0, len(items)))
229
+ # tgt_item = items[tgt_idx]
230
+ # items.pop(tgt_idx)
231
+ # tgt = torch.tensor(self.load_wav(tgt_item[0]))
232
+ # max_value = torch.max(torch.abs(tgt))
233
+ # if max_value > 1:
234
+ # tgt *= 0.9 / max_value
235
+ # tgt_cap = tgt_item[1]
236
+ # if len(items) > 0:
237
+ # noises = [torch.tensor(self.load_wav(x[0])) for x in items]
238
+ # noises.append(noise)
239
+ # noise_caps = [neg_cap.replace('sound', 'sounds')] + [x[1] for x in items]
240
+ # noise = torch.mean(torch.stack(noises, dim=0), dim=0)
241
+ # neg_cap = ', '.join(noise_caps)
242
+
243
+ # A(A1, A2), A1 as target, others as noise
244
+ video = tgt_name.split('/')[-1][:-4]
245
+ if self.dset =='train' and video in self.data_engine_dict and random.random() > 0.5:
246
+ mixed = tgt
247
+ mixed_resample = self.resampler(mixed)
248
+ items = self.data_engine_dict[video]
249
+ tgt_idx = random.choice(range(0, len(items)))
250
+ tgt_item = items[tgt_idx]
251
+ items.pop(tgt_idx)
252
+ tgt = torch.tensor(self.load_wav(tgt_item[0]))
253
+ max_value = torch.max(torch.abs(tgt))
254
+ if max_value > 1:
255
+ tgt *= 0.9 / max_value
256
+ tgt_cap = tgt_item[1]
257
+ if len(items) > 0:
258
+ noises = [torch.tensor(self.load_wav(x[0])) for x in items]
259
+ noise_caps = [x[1] for x in items]
260
+ noise = torch.mean(torch.stack(noises, dim=0), dim=0)
261
+ neg_cap = labels2caption(noise_caps)
262
+
263
+ # silence query
264
+ elif self.dset =='train' and random.random() < self.silence_rate:
265
+ other_name = tgt_name
266
+ while set(self.data_meta[other_name]) & (set(self.data_meta[tgt_name]) | set(self.data_meta[noise_name])):
267
+ other_name = random.choice(self.data_names)
268
+ tgt = torch.zeros_like(mixed)
269
+ neg_cap = labels2caption(self.data_meta[tgt_name] + self.data_meta[noise_name])
270
+ tgt_cap = labels2caption(self.data_meta[other_name])
271
+ pos_sample, _ = self.augmentation(self.resampler(torch.tensor(self.load_wav(other_name))))
272
+ noise = mixed
273
+
274
+ neg_sample, _ = self.augmentation(self.resampler(noise))
275
+
276
+ return mixed, mixed_resample, tgt_cap, neg_cap, tgt, self.pad_or_trim(pos_sample), self.pad_or_trim(neg_sample)
277
+
278
+ def pad_or_trim(self, wav_in):
279
+ target_len = 48000 * self.chunk_dur
280
+ if wav_in.size(0) < target_len:
281
+ wav_in = torch.nn.functional.pad(wav_in, (0, target_len - wav_in.size(0)))
282
+ elif wav_in.size(0) > target_len:
283
+ wav_in = wav_in[:target_len]
284
+ max_value = torch.max(torch.abs(wav_in))
285
+ if max_value > 1:
286
+ wav_in *= 0.9 / max_value
287
+ return wav_in
288
+
eval.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+
4
+ import torch
5
+ import torchaudio
6
+ import torchaudio.transforms as AT
7
+ import csv
8
+ import numpy as np
9
+ import librosa
10
+ import pandas as pd
11
+ import laion_clap
12
+ import soundfile as sf
13
+ from model.CLAPSep import LightningModule
14
+ from model.CLAPSep_decoder import HTSAT_Decoder
15
+ import argparse
16
+ import pytorch_lightning as pl
17
+ from helpers import utils as local_utils
18
+
19
+
20
+ class AudioCapsTest(torch.utils.data.Dataset): # type: ignore
21
+
22
+ def __init__(self, eval_csv, input_dir, sr=32000,
23
+ resample_rate=48000):
24
+ self.data_path = input_dir
25
+
26
+ self.data_names = []
27
+ self.data_caps = []
28
+ self.noise_names = []
29
+ self.noise_caps = []
30
+ with open(eval_csv, 'r') as d:
31
+ reader = csv.reader(d, skipinitialspace=True)
32
+ next(reader)
33
+ for row in reader:
34
+ self.data_names.append(row[0])
35
+ self.data_caps.append(row[1])
36
+ self.noise_names.append(row[2])
37
+ self.noise_caps.append(row[3])
38
+
39
+ if resample_rate is not None:
40
+ self.resampler = AT.Resample(sr, resample_rate)
41
+ self.sr = sr
42
+ self.resample_rate = resample_rate
43
+ else:
44
+ self.sr = sr
45
+
46
+ def __len__(self):
47
+ return len(self.data_names)
48
+
49
+ def load_wav(self, path):
50
+ max_length = self.sr * 10
51
+ wav = librosa.core.load(path, sr=self.sr)[0]
52
+ if len(wav) > max_length:
53
+ wav = wav[0:max_length]
54
+
55
+ # pad audio to max length, 10s for AudioCaps
56
+ if len(wav) < max_length:
57
+ # audio = torch.nn.functional.pad(audio, (0, self.max_length - audio.size(1)), 'constant')
58
+ wav = np.pad(wav, (0, max_length - len(wav)), 'constant')
59
+ return wav
60
+
61
+ def __getitem__(self, idx):
62
+
63
+ tgt_name = self.data_names[idx]
64
+ noise_name = self.noise_names[idx]
65
+ tgt_cap = self.data_caps[idx]
66
+ neg_cap = self.noise_caps[idx]
67
+
68
+ assert noise_name != tgt_name
69
+ snr = torch.ones((1,)) * 0
70
+ tgt = torch.tensor(self.load_wav(os.path.join(self.data_path, tgt_name))).unsqueeze(0)
71
+ noise = torch.tensor(self.load_wav(os.path.join(self.data_path, noise_name))).unsqueeze(0)
72
+ mixed = torchaudio.functional.add_noise(tgt, noise, snr=snr)
73
+
74
+ max_value = torch.max(torch.abs(mixed))
75
+ if max_value > 1:
76
+ tgt *= 0.9 / max_value
77
+ mixed *= 0.9 / max_value
78
+
79
+ tgt = tgt.squeeze()
80
+ mixed = mixed.squeeze()
81
+
82
+ return mixed, self.resampler(mixed), tgt_cap, neg_cap, tgt
83
+
84
+
85
+
86
+ def main(args):
87
+ torch.set_float32_matmul_precision('highest')
88
+ # Load dataset
89
+
90
+ data_test = AudioCapsTest(eval_csv=args.eval_csv,
91
+ input_dir=args.input_dir,
92
+ sr=args.sample_rate,
93
+ resample_rate=48000)
94
+
95
+ test_loader = torch.utils.data.DataLoader(data_test,
96
+ batch_size=1,
97
+ num_workers=1,
98
+ pin_memory=True,
99
+ shuffle=False)
100
+
101
+ clap_model = laion_clap.CLAP_Module(enable_fusion=False, amodel='HTSAT-base', device='cpu')
102
+ clap_model.load_ckpt(args.clap_path)
103
+ decoder = HTSAT_Decoder(**args.model)
104
+ lightning_module = LightningModule(clap_model, decoder, lr=args.optim['lr'],
105
+ use_lora=args.lora,
106
+ rank=args.lora_rank,
107
+ nfft=args.nfft)
108
+ distributed_backend = "ddp"
109
+ trainer = pl.Trainer(
110
+ default_root_dir=os.path.join(args.exp_dir, 'checkpoint'),
111
+ devices=args.gpu_ids if args.use_cuda else "auto",
112
+ accelerator="gpu" if args.use_cuda else "cpu",
113
+ benchmark=False,
114
+ gradient_clip_val=5.0,
115
+ precision='bf16-mixed',
116
+ limit_train_batches=1.0,
117
+ max_epochs=args.epochs,
118
+ strategy=distributed_backend,
119
+ logger=False
120
+ )
121
+
122
+ # weight = torch.load(args.ckpt_path, map_location="cpu")
123
+ # lightning_module.load_state_dict(weight, strict=False)
124
+
125
+ # trainer.test(model=lightning_module, dataloaders=test_loader)
126
+
127
+ trainer.test(model=lightning_module, dataloaders=test_loader, ckpt_path=args.ckpt_path)
128
+
129
+
130
+
131
+ if __name__ == '__main__':
132
+ parser = argparse.ArgumentParser()
133
+ # Data Params
134
+ parser.add_argument('exp_dir', type=str,
135
+ default='experiments',
136
+ help="Path to save checkpoints and logs.")
137
+
138
+ parser.add_argument('--sample_rate', type=int, default=32000)
139
+ parser.add_argument('--ckpt_path', type=str, default='')
140
+ parser.add_argument('--eval_csv', type=str, default='')
141
+ parser.add_argument('--input_dir', type=str, default='')
142
+
143
+ parser.add_argument('--use_cuda', dest='use_cuda', action='store_true',
144
+ help="Whether to use cuda")
145
+ parser.add_argument('--gpu_ids', nargs='+', type=int, default=None,
146
+ help="List of GPU ids used for training. "
147
+ "Eg., --gpu_ids 2 4. All GPUs are used by default.")
148
+
149
+ args = parser.parse_args()
150
+
151
+ # Set the random seed for reproducible experiments
152
+ pl.seed_everything(114514)
153
+ # Set up checkpoints
154
+ if not os.path.exists(args.exp_dir):
155
+ os.makedirs(args.exp_dir)
156
+
157
+ # Load model and training params
158
+ params = local_utils.Params(os.path.join(args.exp_dir, 'config.json'))
159
+ for k, v in params.__dict__.items():
160
+ vars(args)[k] = v
161
+ main(args)
eval.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ ckpt_path="experiments/ClearSep_audioset_32k/checkpoints/epoch=100-step=868000-val_loss=10.33.ckpt"
4
+
5
+
6
+ python eval.py \
7
+ ./experiments/ClearSep_audioset_32k \
8
+ --sample_rate 32000 \
9
+ --ckpt_path $ckpt_path \
10
+ --eval_csv metadata/evaluation/audiocaps_label_eval.csv \
11
+ --input_dir /home/wangtianhao/data/sound/audiocaps/dataset/audios_32k/test \
12
+ --use_cuda \
13
+ --gpu_ids 0
14
+
experiments/ClearSep_audioset_32k/config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e375acdc54da7338b97f80035f272c6e019377363c60df0f107f9a00dd8a5267
3
+ size 1104
helpers/__init__.py ADDED
File without changes
helpers/utils.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A collection of useful helper functions"""
2
+
3
+ import os
4
+ import logging
5
+ import json
6
+
7
+ import torch
8
+ from torch.profiler import profile, record_function, ProfilerActivity
9
+ import pandas as pd
10
+ from torchmetrics.functional import(
11
+ scale_invariant_signal_noise_ratio as si_snr,
12
+ signal_noise_ratio as snr,
13
+ signal_distortion_ratio as sdr,
14
+ scale_invariant_signal_distortion_ratio as si_sdr)
15
+ import matplotlib.pyplot as plt
16
+
17
+ class Params():
18
+ """Class that loads hyperparameters from a json file.
19
+ Example:
20
+ ```
21
+ params = Params(json_path)
22
+ print(params.learning_rate)
23
+ params.learning_rate = 0.5 # change the value of learning_rate in params
24
+ ```
25
+ """
26
+
27
+ def __init__(self, json_path):
28
+ with open(json_path) as f:
29
+ params = json.load(f)
30
+ self.__dict__.update(params)
31
+
32
+ def save(self, json_path):
33
+ with open(json_path, 'w') as f:
34
+ json.dump(self.__dict__, f, indent=4)
35
+
36
+ def update(self, json_path):
37
+ """Loads parameters from json file"""
38
+ with open(json_path) as f:
39
+ params = json.load(f)
40
+ self.__dict__.update(params)
41
+
42
+ @property
43
+ def dict(self):
44
+ """Gives dict-like access to Params instance by `params.dict['learning_rate']"""
45
+ return self.__dict__
46
+
47
+ def save_graph(train_metrics, test_metrics, save_dir):
48
+ metrics = [snr, si_snr]
49
+ results = {'train_loss': train_metrics['loss'],
50
+ 'test_loss' : test_metrics['loss']}
51
+
52
+ for m_fn in metrics:
53
+ results["train_"+m_fn.__name__] = train_metrics[m_fn.__name__]
54
+ results["test_"+m_fn.__name__] = test_metrics[m_fn.__name__]
55
+
56
+ results_pd = pd.DataFrame(results)
57
+
58
+ results_pd.to_csv(os.path.join(save_dir, 'results.csv'))
59
+
60
+ fig, temp_ax = plt.subplots(2, 3, figsize=(15,10))
61
+ axs=[]
62
+ for i in temp_ax:
63
+ for j in i:
64
+ axs.append(j)
65
+
66
+ x = range(len(train_metrics['loss']))
67
+ axs[0].plot(x, train_metrics['loss'], label='train')
68
+ axs[0].plot(x, test_metrics['loss'], label='test')
69
+ axs[0].set(ylabel='Loss')
70
+ axs[0].set(xlabel='Epoch')
71
+ axs[0].set_title('loss',fontweight='bold')
72
+ axs[0].legend()
73
+
74
+ for i in range(len(metrics)):
75
+ axs[i+1].plot(x, train_metrics[metrics[i].__name__], label='train')
76
+ axs[i+1].plot(x, test_metrics[metrics[i].__name__], label='test')
77
+ axs[i+1].set(xlabel='Epoch')
78
+ axs[i+1].set_title(metrics[i].__name__,fontweight='bold')
79
+ axs[i+1].legend()
80
+
81
+ plt.tight_layout()
82
+ plt.savefig(os.path.join(save_dir, 'results.png'))
83
+ plt.close(fig)
84
+
85
+ def set_logger(log_path):
86
+ """Set the logger to log info in terminal and file `log_path`.
87
+ In general, it is useful to have a logger so that every output to the terminal is saved
88
+ in a permanent file. Here we save it to `model_dir/train.log`.
89
+ Example:
90
+ ```
91
+ logging.info("Starting training...")
92
+ ```
93
+ Args:
94
+ log_path: (string) where to log
95
+ """
96
+ logger = logging.getLogger()
97
+ logger.setLevel(logging.INFO)
98
+ logger.handlers.clear()
99
+
100
+ # Logging to a file
101
+ file_handler = logging.FileHandler(log_path)
102
+ file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))
103
+ logger.addHandler(file_handler)
104
+
105
+ # Logging to console
106
+ stream_handler = logging.StreamHandler()
107
+ stream_handler.setFormatter(logging.Formatter('%(message)s'))
108
+ logger.addHandler(stream_handler)
109
+
110
+ def load_checkpoint(checkpoint, model, optim=None, lr_sched=None, data_parallel=False):
111
+ """Loads model parameters (state_dict) from file_path.
112
+
113
+ Args:
114
+ checkpoint: (string) filename which needs to be loaded
115
+ model: (torch.nn.Module) model for which the parameters are loaded
116
+ data_parallel: (bool) if the model is a data parallel model
117
+ """
118
+ if not os.path.exists(checkpoint):
119
+ raise("File doesn't exist {}".format(checkpoint))
120
+
121
+ state_dict = torch.load(checkpoint)
122
+
123
+ if data_parallel:
124
+ state_dict['model_state_dict'] = {
125
+ 'module.' + k: state_dict['model_state_dict'][k]
126
+ for k in state_dict['model_state_dict'].keys()}
127
+ model.load_state_dict(state_dict['model_state_dict'])
128
+
129
+ if optim is not None:
130
+ optim.load_state_dict(state_dict['optim_state_dict'])
131
+
132
+ if lr_sched is not None:
133
+ lr_sched.load_state_dict(state_dict['lr_sched_state_dict'])
134
+
135
+ return state_dict['epoch'], state_dict['train_metrics'], \
136
+ state_dict['val_metrics']
137
+
138
+ def save_checkpoint(checkpoint, epoch, model, optim=None, lr_sched=None,
139
+ train_metrics=None, val_metrics=None, data_parallel=False):
140
+ """Saves model parameters (state_dict) to file_path.
141
+
142
+ Args:
143
+ checkpoint: (string) filename which needs to be loaded
144
+ model: (torch.nn.Module) model for which the parameters are loaded
145
+ data_parallel: (bool) if the model is a data parallel model
146
+ """
147
+ if os.path.exists(checkpoint):
148
+ raise("File already exists {}".format(checkpoint))
149
+
150
+ model_state_dict = model.state_dict()
151
+ if data_parallel:
152
+ model_state_dict = {
153
+ k.partition('module.')[2]:
154
+ model_state_dict[k] for k in model_state_dict.keys()}
155
+
156
+ optim_state_dict = None if not optim else optim.state_dict()
157
+ lr_sched_state_dict = None if not lr_sched else lr_sched.state_dict()
158
+
159
+ state_dict = {
160
+ 'epoch': epoch,
161
+ 'model_state_dict': model_state_dict,
162
+ 'optim_state_dict': optim_state_dict,
163
+ 'lr_sched_state_dict': lr_sched_state_dict,
164
+ 'train_metrics': train_metrics,
165
+ 'val_metrics': val_metrics
166
+ }
167
+
168
+ torch.save(state_dict, checkpoint)
169
+
170
+ def model_size(model):
171
+ """
172
+ Returns size of the `model` in millions of parameters.
173
+ """
174
+ num_train_params = sum(
175
+ p.numel() for p in model.parameters() if p.requires_grad)
176
+ return num_train_params / 1e6
177
+
178
+ def run_time(model, inputs, profiling=False):
179
+ """
180
+ Returns runtime of a model in ms.
181
+ """
182
+ # Warmup
183
+ for _ in range(100):
184
+ output = model(*inputs)
185
+
186
+ with profile(activities=[ProfilerActivity.CPU],
187
+ record_shapes=True) as prof:
188
+ with record_function("model_inference"):
189
+ output = model(*inputs)
190
+
191
+ # Print profiling results
192
+ if profiling:
193
+ print(prof.key_averages().table(sort_by="self_cpu_time_total",
194
+ row_limit=20))
195
+
196
+ # Return runtime in ms
197
+ return prof.profiler.self_cpu_time_total / 1000
198
+
199
+ def format_lr_info(optimizer):
200
+ lr_info = ""
201
+ for i, pg in enumerate(optimizer.param_groups):
202
+ lr_info += " {group %d: params=%.5fM lr=%.1E}" % (
203
+ i, sum([p.numel() for p in pg['params']]) / (1024 ** 2), pg['lr'])
204
+ return lr_info
205
+
infer_data_engine.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ ckpt_path="experiments/ClearSep_audioset_32k/checkpoints/epoch=100-step=868000-val_loss=10.33.ckpt"
4
+
5
+ # output audio save path: ClearSep/model/CLAPSep_infer.py:153~154
6
+
7
+ python infer_data_engine_json.py \
8
+ ./experiments/ClearSep_audioset_32k \
9
+ --sample_rate 32000 \
10
+ --ckpt_path $ckpt_path \
11
+ --audioset_json metadata/data_engine_meta/child_label/bal_train_segments_multi_label.json \
12
+ --video2path_map_csv metadata/audioset/train_lst.csv \
13
+ --use_cuda \
14
+ --gpu_ids 0
15
+
infer_data_engine_json.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+
5
+ import torch
6
+ import torchaudio
7
+ import torchaudio.transforms as AT
8
+ import csv
9
+ import numpy as np
10
+ import librosa
11
+ import pandas as pd
12
+ import laion_clap
13
+ from model.CLAPSep_infer import LightningModule
14
+ from model.CLAPSep_decoder import HTSAT_Decoder
15
+ import argparse
16
+ import pytorch_lightning as pl
17
+ from helpers import utils as local_utils
18
+
19
+
20
+ class AudioCapsTest(torch.utils.data.Dataset): # type: ignore
21
+
22
+ def __init__(self, audioset_json, video2path_map_csv, sr=32000, resample_rate=48000):
23
+ self.data_names = []
24
+ self.data_labels = []
25
+ video2path = {}
26
+ for item in csv.reader(open(video2path_map_csv, 'r')):
27
+ video2path[item[0]] = item[-1]
28
+
29
+ video2labels = json.load(open(audioset_json, 'r'))
30
+ for video, labels in video2labels.items():
31
+ if video in video2path:
32
+ video_path = video2path[video]
33
+ self.data_names.append(video_path)
34
+ self.data_labels.append(labels)
35
+
36
+ if resample_rate is not None:
37
+ self.resampler = AT.Resample(sr, resample_rate)
38
+ self.sr = sr
39
+ self.resample_rate = resample_rate
40
+ else:
41
+ self.sr = sr
42
+
43
+ def __len__(self):
44
+ return len(self.data_names)
45
+
46
+ def load_wav(self, path):
47
+ max_length = self.sr * 10
48
+ wav = librosa.core.load(path, sr=self.sr)[0]
49
+ if len(wav) > max_length:
50
+ wav = wav[0:max_length]
51
+
52
+ # pad audio to max length, 10s for AudioCaps
53
+ if len(wav) < max_length:
54
+ # audio = torch.nn.functional.pad(audio, (0, self.max_length - audio.size(1)), 'constant')
55
+ wav = np.pad(wav, (0, max_length - len(wav)), 'constant')
56
+ return wav
57
+
58
+ def __getitem__(self, idx):
59
+ tgt_name = self.data_names[idx]
60
+ tgt_labels = self.data_labels[idx]
61
+
62
+ mixed = torch.tensor(self.load_wav(tgt_name))
63
+
64
+ return mixed, self.resampler(mixed), '|'.join(tgt_labels), tgt_name
65
+
66
+
67
+
68
+ def main(args):
69
+ torch.set_float32_matmul_precision('highest')
70
+ # Load dataset
71
+
72
+ data_test = AudioCapsTest(audioset_json=args.audioset_json,
73
+ video2path_map_csv=args.video2path_map_csv,
74
+ sr=args.sample_rate,
75
+ resample_rate=48000)
76
+
77
+ test_loader = torch.utils.data.DataLoader(data_test,
78
+ batch_size=1,
79
+ num_workers=1,
80
+ pin_memory=True,
81
+ shuffle=False)
82
+
83
+ clap_model = laion_clap.CLAP_Module(enable_fusion=False, amodel='HTSAT-base', device='cpu')
84
+ clap_model.load_ckpt(args.clap_path)
85
+ decoder = HTSAT_Decoder(**args.model)
86
+ lightning_module = LightningModule(clap_model, decoder, lr=args.optim['lr'],
87
+ use_lora=args.lora,
88
+ rank=args.lora_rank,
89
+ nfft=args.nfft)
90
+ distributed_backend = "ddp"
91
+ trainer = pl.Trainer(
92
+ default_root_dir=os.path.join(args.exp_dir, 'checkpoint'),
93
+ devices=args.gpu_ids if args.use_cuda else "auto",
94
+ accelerator="gpu" if args.use_cuda else "cpu",
95
+ benchmark=False,
96
+ gradient_clip_val=5.0,
97
+ precision='bf16-mixed',
98
+ limit_train_batches=1.0,
99
+ max_epochs=args.epochs,
100
+ strategy=distributed_backend,
101
+ logger=False
102
+ )
103
+
104
+ weights = torch.load(args.ckpt_path, map_location='cpu')
105
+ lightning_module.load_state_dict(weights, strict=False)
106
+
107
+ trainer.test(model=lightning_module, dataloaders=test_loader)
108
+
109
+ # trainer.test(model=lightning_module, dataloaders=test_loader, ckpt_path=args.ckpt_path)
110
+
111
+
112
+
113
+ if __name__ == '__main__':
114
+ parser = argparse.ArgumentParser()
115
+ # Data Params
116
+ parser.add_argument('exp_dir', type=str,
117
+ default='experiments',
118
+ help="Path to save checkpoints and logs.")
119
+
120
+ parser.add_argument('--sample_rate', type=int, default=16000)
121
+ parser.add_argument('--ckpt_path', type=str, default='')
122
+ parser.add_argument('--audioset_json', type=str, default='')
123
+ parser.add_argument('--video2path_map_csv', type=str, default='')
124
+
125
+ parser.add_argument('--use_cuda', dest='use_cuda', action='store_true',
126
+ help="Whether to use cuda")
127
+ parser.add_argument('--gpu_ids', nargs='+', type=int, default=None,
128
+ help="List of GPU ids used for training. "
129
+ "Eg., --gpu_ids 2 4. All GPUs are used by default.")
130
+
131
+ args = parser.parse_args()
132
+
133
+ # Set the random seed for reproducible experiments
134
+ pl.seed_everything(114514)
135
+ # Set up checkpoints
136
+ if not os.path.exists(args.exp_dir):
137
+ os.makedirs(args.exp_dir)
138
+
139
+ # Load model and training params
140
+ params = local_utils.Params(os.path.join(args.exp_dir, 'config.json'))
141
+ for k, v in params.__dict__.items():
142
+ vars(args)[k] = v
143
+ main(args)
metadata/audioset/audioset_label.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e340235d4af6b34442d948bc41e2b2fadf90d7e4109702fb8520c4cc6c4b8f62
3
+ size 69661293
metadata/audioset/class_labels_indices.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdd1049833c4b86127c2773ac0d14a2754b6a6d0d1798002ed5c66e699708429
3
+ size 14675
metadata/audioset/eval_lst.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8efd7d12ad5d6658b0027ec11fe084aa6e5790d0b8a41da0292ab0dce348daf7
3
+ size 2019754
metadata/audioset/ontology.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c685f4403eecc3ca9be37fd7285cf212feaaea6ff7229d3e7ca89e0d1f2d15d
3
+ size 342780
metadata/audioset/train_lst.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:230032344363fe8f23ac9e3d96ed54efd4a8f2477cd658efa4cbf78d13e5253f
3
+ size 225874340
metadata/data_engine_json/audioset_iter2_train_data_engine_th10.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cd5db4da07f7755e4c318aba538e87040c701e463883ce9e860652684c48da1
3
+ size 329874536
metadata/data_engine_json/audioset_iter2_train_data_engine_th15.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bab017fe44d4964848a6a1ca67a1dc5fe0966b7ef4fa72c01336238a7c4dbb42
3
+ size 242464513
metadata/data_engine_meta/child_label/bal_train_segments.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bf9959d7830a2e3122e6aec07e6d65c3282c9067b95700ebc79285324dbfb68
3
+ size 1501593
metadata/data_engine_meta/child_label/bal_train_segments_multi_label.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e7cf8eb7237a8f156f963e0d39376d8e5f87b4b0fe386de64c1d527b9b0c20a
3
+ size 1063491
metadata/data_engine_meta/child_label/eval_segments.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:503a99a3902e94f2569fecb801ca14da4526d525dbdee4cef08a4ec3ded77d26
3
+ size 1449092
metadata/data_engine_meta/child_label/unbal_train_segments.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76ea2171235b11ce8803390b0b430a28f8c5ddaf70c9ee1bb3d3ceb0d6ced27a
3
+ size 119776930
metadata/data_engine_meta/child_label/unbal_train_segments_multi_label.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf64f07ed2e96e67db83314bb4c29e98c117f12c95b3c7de431243f3d99aaec6
3
+ size 66899715
metadata/evaluation/audiocaps_caption_eval.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b96a57ab8800d88cab2ecff108ca8e1cc5309b5505a83b04eb8fd956fcd4ef65
3
+ size 741741
metadata/evaluation/audiocaps_label_eval.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8c2534f2f4c51d293d16a7116e5f8036601ec43adba2e7fd6682d8c5956c19b
3
+ size 497487
metadata/evaluation/audiocaps_label_eval_sep_silence_test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1463d450becd35d9dd1dd2769030da69de3e0c56cd4f78c67886228d04593c6b
3
+ size 592858
metadata/evaluation/audioset_eval.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74e77cc633789d8d798efffd8183d557b948f31426cb1a450f49aa6b43ec9378
3
+ size 2411901
metadata/evaluation/audioset_single_eval.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8faf73e0b84db5d49383f67dfacdd8aba491bb6faa580e4070a44c69c411646
3
+ size 794337
metadata/evaluation/esc_eval.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1241a955f700332888bf40e80bc51cdaa6c9376edca09e5bdd05d5a7c25e32f0
3
+ size 608128
metadata/evaluation/esc_eval_samples.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fe79e1aa7b60266379fd02556be36aa5e8aecaa9f6e6000e53e6c8d41f12c00
3
+ size 11564
metadata/training/audiocaps_caption_32k_train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fd4db95b685e9b747b842290e35c83301ed47db9be146a05d15a21de4d84709
3
+ size 5660553
metadata/training/audiocaps_caption_32k_val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2c1535eb967d344299013dc8d9e31cb657faf419f6924adf000ca6ebc3c32ac
3
+ size 145573
metadata/training/audiocaps_label_32k_train_sep.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc819bf9bf9e100c5f2553e5e8c49e4b9ef2e973c4b54bc4815a1f8fdbf7b9eb
3
+ size 4869583
metadata/training/audiocaps_label_32k_val_sep.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:113de99477ccd9e2217e490ef2861f1f9197e6edcfc94ca451beabb36c824a16
3
+ size 47563
metadata/training/audioset_32k_train_sep.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c713ab96a393ee913146ffe8cf2e4be77502868718ee2ac0d7feb23f0a636df6
3
+ size 220302378
metadata/training/audioset_32k_train_sep_th10_iter2.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ede407a78b9d5e98157ca9a57e84aed887543affefa86c55642636b7f77ada52
3
+ size 451618397
metadata/training/audioset_32k_train_sep_th15_iter2.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90df3df917d46b67c990fa506f26f97f8081b0e3879d460225f6438c2e65dada
3
+ size 389681938
metadata/training/audioset_32k_val_sep.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66086b740b273f47b9248de8f94d9dd3fe94c6f790b9962f8c8e0ddd9ed5459f
3
+ size 1473876
model/CLAPSep.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: UTF-8 -*-
3
+ '''
4
+ @Project :Waveformer-main
5
+ @File :CLAPSep.py
6
+ @IDE :PyCharm
7
+ @Author :Aisaka/Hao Ma @SDU
8
+ @Date :2024/2/28 下午1:12
9
+ '''
10
+
11
+ import torch
12
+ import laion_clap
13
+ from torchmetrics.audio.snr import(
14
+ scale_invariant_signal_noise_ratio as si_snr,
15
+ signal_noise_ratio as snr)
16
+ from torchmetrics.audio.sdr import(
17
+ signal_distortion_ratio as sdr,
18
+ scale_invariant_signal_distortion_ratio as si_sdr)
19
+ import copy
20
+ import loralib as lora
21
+ from torchlibrosa import ISTFT, STFT, SpecAugmentation
22
+ from torchlibrosa.stft import magphase
23
+ import librosa
24
+ import pytorch_lightning as pl
25
+
26
+
27
+ def loss_fn(pred, tgt):
28
+ return -0.9 * snr(pred, tgt).mean() - 0.1 * si_snr(pred, tgt).mean()
29
+
30
+
31
+ def set_module(model, submodule_key, module):
32
+ tokens = submodule_key.split('.')
33
+ sub_tokens = tokens[:-1]
34
+ cur_mod = model
35
+ for s in sub_tokens:
36
+ cur_mod = getattr(cur_mod, s)
37
+ setattr(cur_mod, tokens[-1], module)
38
+
39
+
40
+ def process_model(model, rank):
41
+ for n, module in model.named_modules():
42
+ if 'WindowAttention' in str(type(module)):
43
+ for n_, layer in module.named_modules():
44
+ if isinstance(layer, torch.nn.Linear):
45
+ lora_layer = lora.Linear(layer.in_features, layer.out_features, r=rank,
46
+ bias=hasattr(layer, 'bias'), merge_weights=False)
47
+ lora_layer.weight = layer.weight
48
+ if hasattr(layer, 'bias'):
49
+ lora_layer.bias = layer.bias
50
+ set_module(model, n+'.'+n_, lora_layer)
51
+ return model
52
+
53
+
54
+ class LightningModule(pl.LightningModule):
55
+ def __init__(self, clap_model, decoder_model, lr, use_lora=False, rank=8, nfft=1024):
56
+ super().__init__()
57
+ self.phase = decoder_model.phase
58
+ self.lr = lr
59
+ self.clap_model = clap_model
60
+ for p in self.clap_model.parameters():
61
+ p.requires_grad = False
62
+ self.audio_branch = copy.deepcopy(self.clap_model.model.audio_branch)
63
+ if use_lora:
64
+ process_model(self.audio_branch, rank)
65
+ lora.mark_only_lora_as_trainable(self.audio_branch, bias='lora_only')
66
+
67
+ self.decoder_model = decoder_model
68
+ self.stft = STFT(n_fft=nfft, hop_length=320,
69
+ win_length=nfft, window='hann', center=True, pad_mode='reflect',
70
+ freeze_parameters=True)
71
+ self.istft = ISTFT(n_fft=nfft, hop_length=320,
72
+ win_length=nfft, window='hann', center=True, pad_mode='reflect',
73
+ freeze_parameters=True)
74
+ self.features = self.install_forward_hooks()
75
+
76
+ def training_step(self, batch, batch_idx):
77
+ self.clap_model.eval()
78
+ self.audio_branch.eval()
79
+ # print([len(x) for x in batch])
80
+ mixed, mixed_resample, pos_cap, neg_cap, gt, pos_sample, neg_sample = batch
81
+ real, imag = self.stft(mixed)
82
+ mag, cos, sin = magphase(real, imag)
83
+ with torch.no_grad():
84
+ a = torch.rand((1,)).type_as(gt)
85
+ embed_pos_a, embed_neg_a = torch.chunk(
86
+ self.clap_model.get_audio_embedding_from_data(torch.concat([pos_sample, neg_sample], dim=0),
87
+ use_tensor=True), dim=0, chunks=2)
88
+ embed_pos_t, embed_neg_t = torch.chunk(
89
+ self.clap_model.get_text_embedding(pos_cap + neg_cap, use_tensor=True), dim=0, chunks=2)
90
+ embed_pos = a * embed_pos_a + (1 - a) * embed_pos_t
91
+ embed_neg = a * embed_neg_a + (1 - a) * embed_neg_t
92
+ del self.features[:]
93
+ self.features.append(mag)
94
+ self.audio_branch({"waveform": mixed_resample})
95
+ a = torch.rand((1,))
96
+ if a < 0.25:
97
+ loss = self.cal_loss(embed_pos, torch.zeros_like(embed_pos), mag, cos, sin, length=mixed.size(-1), gt=gt)
98
+ elif a < 0.5:
99
+ loss = self.cal_loss(torch.zeros_like(embed_neg), embed_neg, mag, cos, sin, length=mixed.size(-1), gt=gt)
100
+ else:
101
+ loss = self.cal_loss(embed_pos, embed_neg, mag, cos, sin, length=mixed.size(-1), gt=gt)
102
+ self.log("train_loss", loss.item(), on_epoch=True, prog_bar=True, sync_dist=True, batch_size=len(mixed))
103
+ del self.features[:]
104
+ return loss
105
+
106
+ def cal_loss(self, embed_p, embed_n, mag, cos, sin, length, gt):
107
+ embed = torch.nn.functional.normalize(torch.concat([embed_p, embed_n], dim=-1), dim=-1)
108
+ mask = self.decoder_model(hidden_state=self.features[-1], skip_features=self.features[:-1], embed=embed)
109
+ pred = self.wav_reconstruct(mask, mag, cos, sin, length=length)
110
+ return loss_fn(pred, gt)
111
+
112
+ def wav_reconstruct(self, mask, mag_x, cos_x, sin_x, length):
113
+ # ref: https://github.com/Audio-AGI/AudioSep/blob/main/models/resunet.py
114
+ # Y = |Y|cos∠Y + j|Y|sin∠Y
115
+ # = |Y|cos(∠X + ∠M) + j|Y|sin(∠X + ∠M)
116
+ # = |Y|(cos∠X cos∠M - sin∠X sin∠M) + j|Y|(sin∠X cos∠M + cos∠X sin∠M)
117
+ if self.phase:
118
+ mag_y = torch.nn.functional.relu_(mag_x * mask[0])
119
+ _, mask_cos, mask_sin = magphase(mask[1], mask[2])
120
+ cos_y = cos_x * mask_cos - sin_x * mask_sin
121
+ sin_y = sin_x * mask_cos + cos_x * mask_sin
122
+ else:
123
+ mag_y = torch.nn.functional.relu_(mag_x * mask)
124
+ cos_y = cos_x
125
+ sin_y = sin_x
126
+ pred = self.istft(mag_y * cos_y, mag_y * sin_y, length=length)
127
+ return pred
128
+
129
+ def validation_step(self, batch, batch_idx):
130
+ mixed, mixed_resample, label, neg_label, gt, _, _ = batch
131
+ real, imag = self.stft(mixed)
132
+ mag, cos, sin = magphase(real, imag)
133
+ self.features.append(mag)
134
+ with torch.no_grad():
135
+ embed_pos = self.clap_model.get_text_embedding(label, use_tensor=True)
136
+ embed_neg = self.clap_model.get_text_embedding(neg_label, use_tensor=True)
137
+ embed = torch.concat([embed_pos, embed_neg], dim=-1)
138
+ self.audio_branch({"waveform": mixed_resample})
139
+ mask = self.decoder_model(hidden_state=self.features[-1], skip_features=self.features[:-1], embed=embed)
140
+ pred = self.wav_reconstruct(mask, mag, cos, sin, length=mixed.size(-1))
141
+ loss = si_snr(pred, gt).mean() - si_snr(mixed, gt).mean()
142
+ del self.features[:]
143
+ self.log("val_loss", loss, on_epoch=True, prog_bar=True, sync_dist=True, batch_size=len(mixed))
144
+ return {"val_loss": loss}
145
+
146
+ def on_test_start(self) -> None:
147
+ self.sdr_vals = torch.tensor([])
148
+ self.sdri_vals = torch.tensor([])
149
+ self.sisdr_vals = torch.tensor([])
150
+ self.sisdri_vals = torch.tensor([])
151
+
152
+ def test_step(self, batch, batch_idx):
153
+ mixed, mixed_resample, label, neg_label, gt = batch
154
+ real, imag = self.stft(mixed)
155
+ mag, cos, sin = magphase(real, imag)
156
+ with torch.no_grad():
157
+ embed_pos_bached, embed_neg_bached = torch.chunk(self.clap_model.get_text_embedding(label + neg_label, use_tensor=True), chunks=2, dim=0)
158
+ del self.features[:]
159
+ # only positive
160
+ # embed = torch.concat([embed_pos_bached, torch.zeros_like(embed_neg_bached)], dim=1)
161
+ # only negative
162
+ # embed = torch.concat([torch.zeros_like(embed_pos_bached), embed_neg_bached], dim=1)
163
+ # positive and negative
164
+ embed = torch.concat([embed_pos_bached, embed_neg_bached], dim=1)
165
+ self.features.append(mag)
166
+ self.audio_branch({"waveform": mixed_resample})
167
+ mask = self.decoder_model(hidden_state=self.features[-1], skip_features=self.features[:-1], embed=embed)
168
+ pred = self.wav_reconstruct(mask, mag, cos, sin, length=mixed.size(-1))
169
+ sisdr = si_sdr(pred, gt).cpu()
170
+ self.sisdr_vals = torch.concat([self.sisdr_vals, sisdr])
171
+ self.sisdri_vals = torch.concat([self.sisdri_vals, sisdr - si_sdr(mixed, gt).cpu()])
172
+ sdr_ = sdr(pred, gt).cpu()
173
+ self.sdr_vals = torch.concat([self.sdr_vals, sdr_])
174
+ self.sdri_vals = torch.concat([self.sdri_vals, sdr_ - sdr(mixed, gt).cpu()])
175
+ del self.features[:]
176
+
177
+ def on_test_end(self) -> None:
178
+ print(f"SDR-mean: {torch.mean(self.sdr_vals).cpu().numpy():.4f}, SDR-std: {torch.std(self.sdr_vals).cpu().numpy():.4f}")
179
+ print(f"SDRi-mean: {torch.mean(self.sdri_vals).cpu().numpy():.4f}, SDRi-std: {torch.std(self.sdri_vals).cpu().numpy():.4f}")
180
+ print(f"SISDR-mean: {torch.mean(self.sisdr_vals).cpu().numpy():.4f}, SISDR-std: {torch.std(self.sisdr_vals).cpu().numpy():.4f}")
181
+ print(f"SISDRi-mean: {torch.mean(self.sisdri_vals).cpu().numpy():.4f}, SISDRi-std: {torch.std(self.sisdri_vals).cpu().numpy():.4f}")
182
+
183
+ def configure_optimizers(self):
184
+ optimizer = torch.optim.AdamW(self.parameters(), lr=self.lr)
185
+ schedular = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.3, patience=5,
186
+ verbose=True, min_lr=5e-6)
187
+ return {
188
+ "optimizer": optimizer,
189
+ "lr_scheduler": {
190
+ "scheduler": schedular,
191
+ "interval": "epoch",
192
+ "monitor": "val_loss"
193
+ },
194
+ }
195
+
196
+ def install_forward_hooks(self):
197
+ features = []
198
+ spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2,
199
+ freq_drop_width=8, freq_stripes_num=2)
200
+
201
+ def get_features_list(_, __, output):
202
+ features.append(output)
203
+
204
+ def get_features_list_basic_layer(_, __, output):
205
+ features.append(output[0])
206
+
207
+ def spec_augmentation_hook(_, __, out):
208
+ out = out.transpose(1, 3)
209
+ out = spec_augmenter(out)
210
+ return out.transpose(1, 3)
211
+
212
+ def spectrogram_padding(_, __, out):
213
+ return torch.nn.functional.pad(out, (0, 0, 0, 1024 - out.size(2)))
214
+
215
+ self.clap_model.model.audio_branch.bn0.register_forward_hook(spec_augmentation_hook)
216
+ self.audio_branch.spectrogram_extractor.register_forward_hook(spectrogram_padding)
217
+ self.audio_branch.patch_embed.register_forward_hook(get_features_list)
218
+ for module in self.audio_branch.layers:
219
+ module.register_forward_hook(get_features_list_basic_layer)
220
+ return features
221
+
222
+ # # this will only save tuned parameters during training
223
+ # def on_save_checkpoint(self, checkpoint):
224
+ # weights = checkpoint['state_dict']
225
+ # new_dict = {}
226
+ # for k, v in weights.items():
227
+ # if any(e in k for e in ['lora', 'attn.qkv.bias', 'attn.proj.bias', 'decoder_model']):
228
+ # new_dict[k] = v
229
+ # checkpoint['state_dict'] = new_dict
model/CLAPSep_decoder.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: UTF-8 -*-
3
+ '''
4
+ @Project :Waveformer-main
5
+ @File :CLAPsep_decoder.py
6
+ @IDE :PyCharm
7
+ @Author :Aisaka/Hao Ma @SDU
8
+ @Date :2023/10/31 下午8:34
9
+ '''
10
+
11
+ from laion_clap.clap_module.htsat import *
12
+ from einops import rearrange
13
+ import numpy as np
14
+
15
+ class Transpose(nn.Module):
16
+
17
+ def __init__(self, dim0, dim1):
18
+ super(Transpose, self).__init__()
19
+ self.dim0 = dim0
20
+ self.dim1 = dim1
21
+
22
+ def forward(self, x):
23
+ return x.transpose(self.dim0, self.dim1)
24
+
25
+
26
+ class Swish(nn.Module):
27
+
28
+ def __init__(self):
29
+ super(Swish, self).__init__()
30
+
31
+ def forward(self, x):
32
+ return x * x.sigmoid()
33
+
34
+
35
+ class Glu(nn.Module):
36
+
37
+ def __init__(self, dim):
38
+ super(Glu, self).__init__()
39
+ self.dim = dim
40
+
41
+ def forward(self, x):
42
+ x_in, x_gate = x.chunk(2, dim=self.dim)
43
+ return x_in * x_gate.sigmoid()
44
+
45
+
46
+ class FiLM(nn.Module):
47
+ def __init__(self, dim_in=1024, hidden_dim=768):
48
+ super(FiLM, self).__init__()
49
+ self.beta = nn.Linear(dim_in, hidden_dim)
50
+ self.gamma = nn.Linear(dim_in, hidden_dim)
51
+
52
+ def forward(self, hidden_state, embed):
53
+ embed = embed.unsqueeze(1)
54
+ return self.gamma(embed) * hidden_state + self.beta(embed)
55
+
56
+
57
+ class SkipTrans(nn.Module):
58
+ def __init__(self, in_features, out_features, embed_dim=512, film=True):
59
+ super(SkipTrans, self).__init__()
60
+ self.film = film
61
+ if film:
62
+ self.skip_conv = FiLM(embed_dim, out_features)
63
+ self.feature_proj = nn.Linear(in_features, out_features)
64
+ self.norm = nn.LayerNorm(out_features)
65
+
66
+ def forward(self, skip, embed, x=None):
67
+ out = self.feature_proj(skip)
68
+ if self.film:
69
+ out = self.skip_conv(out, embed)
70
+ return self.norm(out) if x is None else self.norm(out + x)
71
+
72
+ class Conv1d(nn.Conv1d):
73
+
74
+ def __init__(
75
+ self,
76
+ in_channels,
77
+ out_channels,
78
+ kernel_size,
79
+ stride = 1,
80
+ padding = "same",
81
+ dilation = 1,
82
+ groups = 1,
83
+ bias = True
84
+ ):
85
+ super(Conv1d, self).__init__(
86
+ in_channels=in_channels,
87
+ out_channels=out_channels,
88
+ kernel_size=kernel_size,
89
+ stride=stride,
90
+ padding=0,
91
+ dilation=dilation,
92
+ groups=groups,
93
+ bias=bias,
94
+ padding_mode="zeros")
95
+
96
+ # Assert
97
+ assert padding in ["valid", "same", "causal"]
98
+
99
+ # Padding
100
+ if padding == "valid":
101
+ self.pre_padding = None
102
+ elif padding == "same":
103
+ self.pre_padding = nn.ConstantPad1d(padding=((kernel_size - 1) // 2, (kernel_size - 1) // 2), value=0)
104
+ elif padding == "causal":
105
+ self.pre_padding = nn.ConstantPad1d(padding=(kernel_size - 1, 0), value=0)
106
+
107
+ # Variational Noise
108
+ self.noise = None
109
+ self.vn_std = None
110
+
111
+ def init_vn(self, vn_std):
112
+
113
+ # Variational Noise
114
+ self.vn_std = vn_std
115
+
116
+ def sample_synaptic_noise(self, distributed):
117
+
118
+ # Sample Noise
119
+ self.noise = torch.normal(mean=0.0, std=1.0, size=self.weight.size(), device=self.weight.device, dtype=self.weight.dtype)
120
+
121
+ # Broadcast Noise
122
+ if distributed:
123
+ torch.distributed.broadcast(self.noise, 0)
124
+
125
+ def forward(self, input):
126
+
127
+ # Weight
128
+ weight = self.weight
129
+
130
+ # Add Noise
131
+ if self.noise is not None and self.training:
132
+ weight = weight + self.vn_std * self.noise
133
+
134
+ # Padding
135
+ if self.pre_padding is not None:
136
+ input = self.pre_padding(input)
137
+
138
+ # Apply Weight
139
+ return F.conv1d(input, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)
140
+
141
+
142
+ class ConvolutionModule(nn.Module):
143
+ """Conformer Convolution Module
144
+
145
+ Args:
146
+ dim_model: input feature dimension
147
+ dim_expand: output feature dimension
148
+ kernel_size: 1D depthwise convolution kernel size
149
+ Pdrop: residual dropout probability
150
+ stride: 1D depthwise convolution stride
151
+ padding: "valid", "same" or "causal"
152
+
153
+ Input: (batch size, input length, dim_model)
154
+ Output: (batch size, output length, dim_expand)
155
+
156
+ """
157
+
158
+ def __init__(self, dim_model, dim_expand, kernel_size, Pdrop, stride, padding):
159
+ super(ConvolutionModule, self).__init__()
160
+
161
+ # Layers
162
+ self.layers = nn.Sequential(
163
+ nn.LayerNorm(dim_model, eps=1e-6),
164
+ Transpose(1, 2),
165
+ Conv1d(dim_model, 2 * dim_expand, kernel_size=1),
166
+ Glu(dim=1),
167
+ Conv1d(dim_expand, dim_expand, kernel_size, stride=stride, padding=padding, groups=dim_expand),
168
+ nn.BatchNorm1d(dim_expand),
169
+ Swish(),
170
+ Conv1d(dim_expand, dim_expand, kernel_size=1),
171
+ Transpose(1, 2),
172
+ nn.Dropout(p=Pdrop)
173
+ )
174
+ self.ln = nn.LayerNorm(dim_expand)
175
+
176
+ def forward(self, x):
177
+ return self.ln(self.layers(x)+x)
178
+
179
+
180
+ class BasicLayerDec(nn.Module):
181
+ """ A basic Swin Transformer layer for one stage.
182
+ Args:
183
+ dim (int): Number of input channels.
184
+ input_resolution (tuple[int]): Input resolution.
185
+ depth (int): Number of blocks.
186
+ num_heads (int): Number of attention heads.
187
+ window_size (int): Local window size.
188
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
189
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
190
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
191
+ drop (float, optional): Dropout rate. Default: 0.0
192
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
193
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
194
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
195
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
196
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
197
+ """
198
+
199
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
200
+ mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
201
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
202
+ norm_before_mlp='ln'):
203
+
204
+ super().__init__()
205
+ self.dim = dim
206
+ self.input_resolution = input_resolution
207
+ self.depth = depth
208
+ self.use_checkpoint = use_checkpoint
209
+
210
+ # build blocks
211
+ self.blocks = nn.ModuleList([
212
+ SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
213
+ num_heads=num_heads, window_size=window_size,
214
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
215
+ mlp_ratio=mlp_ratio,
216
+ qkv_bias=qkv_bias, qk_scale=qk_scale,
217
+ drop=drop, attn_drop=attn_drop,
218
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
219
+ norm_layer=norm_layer, norm_before_mlp=norm_before_mlp)
220
+ for i in range(depth)])
221
+
222
+ # patch merging layer
223
+ if downsample is not None:
224
+ self.downsample = downsample((input_resolution[0]//2, input_resolution[1]//2), dim=dim * 2, norm_layer=norm_layer)
225
+ else:
226
+ self.downsample = None
227
+
228
+ def forward(self, x):
229
+ attns = []
230
+ if self.downsample is not None:
231
+ x = self.downsample(x)
232
+ for blk in self.blocks:
233
+ if self.use_checkpoint:
234
+ x = checkpoint.checkpoint(blk, x)
235
+ else:
236
+ x, attn = blk(x)
237
+ if not self.training:
238
+ attns.append(attn.unsqueeze(0))
239
+ if not self.training:
240
+ attn = torch.cat(attns, dim = 0)
241
+ attn = torch.mean(attn, dim = 0)
242
+ return x, attn
243
+
244
+ def extra_repr(self):
245
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
246
+
247
+
248
+ class PatchExpand(nn.Module):
249
+ def __init__(self, input_resolution, dim, dim_scale=2, norm_layer=nn.LayerNorm):
250
+ super().__init__()
251
+ self.input_resolution = input_resolution
252
+ self.dim = dim
253
+ self.expand = nn.Linear(dim, 2 * dim, bias=False) if dim_scale == 2 else nn.Identity()
254
+ self.norm = norm_layer(dim // dim_scale)
255
+
256
+ def forward(self, x):
257
+ """
258
+ x: B, H*W, C
259
+ """
260
+ H, W = self.input_resolution
261
+ x = self.expand(x)
262
+ B, L, C = x.shape
263
+ assert L == H * W, "input feature has wrong size"
264
+
265
+ x = x.view(B, H, W, C)
266
+ # This is the original implementation in SwinUnet
267
+ # x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=2, p2=2, c=C // 4)
268
+
269
+ # here is our implementation
270
+ # can reverse patch-merging in Swin-Transformer encoder, seems helpful
271
+ x0, x2, x1, x3 = x.chunk(4, dim=-1)
272
+ x = torch.stack((x0, x1, x2, x3), dim=-1)
273
+ x = torch.chunk(x, C // 4, dim=-2)
274
+ x = torch.concat(x, dim=-1).squeeze(-2)
275
+ x = rearrange(x, 'b h w c -> b c h w')
276
+ x = torch.nn.functional.pixel_shuffle(x, 2)
277
+ x = rearrange(x, 'b c h w -> b h w c')
278
+ x = x.view(B, -1, C // 4)
279
+ x = self.norm(x)
280
+
281
+ return x
282
+
283
+
284
+ class InversePatchEmbed(nn.Module):
285
+ """
286
+ Patch Embedding to 2D Image.
287
+ """
288
+
289
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True,
290
+ patch_stride=16):
291
+ super().__init__()
292
+ img_size = to_2tuple(img_size)
293
+ patch_size = to_2tuple(patch_size)
294
+ patch_stride = to_2tuple(patch_stride)
295
+ self.img_size = img_size
296
+ self.patch_size = patch_size
297
+ self.patch_stride = patch_stride
298
+ self.grid_size = (img_size[0] // patch_stride[0], img_size[1] // patch_stride[1])
299
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
300
+ self.flatten = flatten
301
+ self.in_chans = in_chans
302
+ self.embed_dim = embed_dim
303
+
304
+ padding = ((patch_size[0] - patch_stride[0]) // 2, (patch_size[1] - patch_stride[1]) // 2)
305
+
306
+ self.proj = nn.ConvTranspose2d(embed_dim, in_chans, kernel_size=patch_size, stride=patch_stride, padding=padding)
307
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
308
+
309
+ def forward(self, x):
310
+ # B, C, H, W = x.shape
311
+ # assert H == self.img_size[0] and W == self.img_size[1], \
312
+ # f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
313
+ x = self.norm(x)
314
+ if self.flatten:
315
+ # x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
316
+ x = x.transpose(1, 2).unflatten(2, self.grid_size).contiguous() # BNC -> BCHW
317
+ x = self.proj(x)
318
+
319
+ return x
320
+
321
+
322
+ class HTSAT_Decoder(nn.Module):
323
+ r"""HTSAT_decoder based on the Swin Transformer
324
+ Args:
325
+ spec_size (int | tuple(int)): Input Spectrogram size. Default 256
326
+ patch_size (int | tuple(int)): Patch size. Default: 4
327
+ path_stride (iot | tuple(int)): Patch Stride for Frequency and Time Axis. Default: 4
328
+ in_chans (int): Number of input image channels. Default: 1 (mono)
329
+ num_classes (int): Number of classes for classification head. Default: 527
330
+ embed_dim (int): Patch embedding dimension. Default: 96
331
+ depths (tuple(int)): Depth of each HTSAT-Swin Transformer layer.
332
+ num_heads (tuple(int)): Number of attention heads in different layers.
333
+ window_size (int): Window size. Default: 8
334
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
335
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
336
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
337
+ drop_rate (float): Dropout rate. Default: 0
338
+ attn_drop_rate (float): Attention dropout rate. Default: 0
339
+ drop_path_rate (float): Stochastic depth rate. Default: 0.1
340
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
341
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
342
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True
343
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
344
+ """
345
+
346
+ def __init__(self, lan_embed_dim=512, spec_size=256, patch_size=4, patch_stride=(4, 4),
347
+ in_chans=1, num_classes=527,
348
+ embed_dim=48, depths=[1, 1, 1, 1], num_heads=[4, 8, 16, 32],
349
+ window_size=8, mlp_ratio=4., qkv_bias=True, qk_scale=None,
350
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
351
+ norm_layer=nn.LayerNorm,
352
+ ape=False, patch_norm=True,
353
+ use_checkpoint=False, norm_before_mlp='ln', encoder_embed_dim=96, phase=False,
354
+ spec_factor=8, d_attn=640, n_masker_layer=4, conv=False):
355
+ super(HTSAT_Decoder, self).__init__()
356
+ self.mel_bins = 64
357
+ self.spec_size = spec_size
358
+ self.phase = phase
359
+ self.patch_stride = patch_stride
360
+ self.patch_size = patch_size
361
+ self.window_size = window_size
362
+ self.embed_dim = embed_dim
363
+ self.depths = depths
364
+ self.ape = ape
365
+ self.in_chans = in_chans
366
+ self.num_classes = num_classes
367
+ self.num_heads = num_heads
368
+ self.num_layers = len(self.depths)
369
+ self.num_features = int(self.embed_dim * 2 ** (self.num_layers - 1))
370
+
371
+ self.drop_rate = drop_rate
372
+ self.attn_drop_rate = attn_drop_rate
373
+ self.drop_path_rate = drop_path_rate
374
+
375
+ self.qkv_bias = qkv_bias
376
+ self.qk_scale = None
377
+
378
+ self.patch_norm = patch_norm
379
+ self.norm_layer = norm_layer if self.patch_norm else None
380
+ self.norm_before_mlp = norm_before_mlp
381
+ self.mlp_ratio = mlp_ratio
382
+
383
+ self.use_checkpoint = use_checkpoint
384
+
385
+ # process mel-spec ; used only once
386
+ self.freq_ratio = self.spec_size // self.mel_bins
387
+
388
+
389
+ # split spctrogram into non-overlapping patches
390
+ self.inverse_patch_embed = InversePatchEmbed(
391
+ img_size=self.spec_size, patch_size=self.patch_size, in_chans=self.in_chans,
392
+ embed_dim=self.embed_dim, norm_layer=self.norm_layer, patch_stride=patch_stride)
393
+
394
+ patches_resolution = self.inverse_patch_embed.grid_size
395
+ self.patches_resolution = patches_resolution
396
+
397
+
398
+ # stochastic depth
399
+ dpr = [x.item() for x in
400
+ torch.linspace(0, self.drop_path_rate, sum(self.depths))] # stochastic depth decay rule
401
+
402
+ # build layers
403
+ self.layers = nn.ModuleList()
404
+ self.skip = nn.ModuleList()
405
+ for i_layer in range(self.num_layers):
406
+ layer = BasicLayerDec(dim=int(self.embed_dim * 2 ** i_layer),
407
+ input_resolution=(patches_resolution[0] // (2 ** i_layer),
408
+ patches_resolution[1] // (2 ** i_layer)),
409
+ depth=self.depths[i_layer],
410
+ num_heads=self.num_heads[i_layer],
411
+ window_size=self.window_size,
412
+ mlp_ratio=self.mlp_ratio,
413
+ qkv_bias=self.qkv_bias, qk_scale=self.qk_scale,
414
+ drop=self.drop_rate, attn_drop=self.attn_drop_rate,
415
+ drop_path=dpr[sum(self.depths[:i_layer]):sum(self.depths[:i_layer + 1])],
416
+ norm_layer=self.norm_layer,
417
+ downsample=PatchExpand if (i_layer < self.num_layers - 1) else None,
418
+ use_checkpoint=use_checkpoint,
419
+ norm_before_mlp=self.norm_before_mlp)
420
+ self.layers.append(layer)
421
+ self.skip.append(
422
+ SkipTrans(embed_dim=lan_embed_dim, in_features=int(encoder_embed_dim * 2 ** i_layer), out_features=int(self.embed_dim * 2 ** i_layer)),
423
+ )
424
+ self.layers = self.layers[::-1]
425
+ self.skip = self.skip[::-1]
426
+ # self.skip.append(
427
+ # SkipTrans(embed_dim=lan_embed_dim, in_features=self.mel_bins, out_features=self.mel_bins),
428
+ # )
429
+
430
+ d_spec = self.mel_bins * spec_factor + 1
431
+
432
+ self.spec_norm = nn.BatchNorm2d(d_spec, momentum=0.01)
433
+ self.conv = conv
434
+ if not conv:
435
+ encoder_layer = nn.TransformerEncoderLayer(d_model=d_attn, nhead=8,
436
+ dim_feedforward=int(d_attn * self.mlp_ratio),
437
+ batch_first=True, dropout=0)
438
+ transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=n_masker_layer)
439
+
440
+ self.mask_net = nn.Sequential(
441
+ nn.Linear(self.mel_bins + d_spec, d_attn),
442
+ nn.LayerNorm(d_attn),
443
+ transformer_encoder,
444
+ nn.Linear(d_attn, d_spec)
445
+ )
446
+ else:
447
+ self.mask_net = nn.Sequential(
448
+ nn.Linear(self.mel_bins + d_spec, d_spec),
449
+ nn.LayerNorm(d_spec),
450
+ *[ConvolutionModule(dim_model=d_spec, dim_expand=d_spec, kernel_size=9, padding='same',
451
+ Pdrop=0, stride=1) for i in range(n_masker_layer)]
452
+ )
453
+ if self.phase:
454
+ self.phase_net = nn.Sequential(
455
+ nn.Linear(self.mel_bins + d_spec, d_spec * 2),
456
+ nn.LayerNorm(d_spec * 2),
457
+ *[ConvolutionModule(dim_model=d_spec * 2, dim_expand=d_spec * 2, kernel_size=9, padding='same',
458
+ Pdrop=0, stride=1) for i in range(n_masker_layer)]
459
+ )
460
+
461
+ self.film = SkipTrans(embed_dim=lan_embed_dim, in_features=encoder_embed_dim * 8, out_features=self.num_features)
462
+
463
+ self.apply(self._init_weights)
464
+
465
+ def _init_weights(self, m):
466
+ if isinstance(m, nn.Linear):
467
+ trunc_normal_(m.weight, std=.02)
468
+ if isinstance(m, nn.Linear) and m.bias is not None:
469
+ nn.init.constant_(m.bias, 0)
470
+ elif isinstance(m, nn.LayerNorm):
471
+ nn.init.constant_(m.bias, 0)
472
+ nn.init.constant_(m.weight, 1.0)
473
+
474
+ # @torch.jit.ignore
475
+ # def no_weight_decay(self):
476
+ # return {'absolute_pos_embed'}
477
+ #
478
+ # @torch.jit.ignore
479
+ # def no_weight_decay_keywords(self):
480
+ # return {'relative_position_bias_table'}
481
+
482
+ def forward(self, hidden_state, skip_features, embed):
483
+ skip_features = skip_features[::-1]
484
+ # hidden_state = torch.randn(hidden_state.shape).type_as(hidden_state)
485
+
486
+ spec = skip_features[-1]
487
+
488
+ h = self.film(hidden_state, embed)
489
+
490
+ for i, (layer, f, skip) in enumerate(zip(self.layers, skip_features, self.skip)):
491
+ h = layer(h)[0]
492
+ h = skip(skip=f, embed=embed, x=h)
493
+
494
+ h = self.reshape_img2wav(self.inverse_patch_embed(h)).squeeze(1)
495
+
496
+ h = h[:, :spec.size(2), :]
497
+
498
+ spec = spec.transpose(1, 3)
499
+
500
+ spec = self.spec_norm(spec).transpose(1, 3).squeeze(1)
501
+
502
+ h = torch.concat([spec, h], dim=-1)
503
+
504
+ mask = self.mask_net(h).unsqueeze(1)
505
+
506
+ if self.phase:
507
+ mask_r, mask_i = torch.chunk(self.phase_net(h).unsqueeze(1), chunks=2, dim=-1)
508
+ return torch.sigmoid(mask), torch.tanh(mask_r), torch.tanh(mask_i)
509
+ else:
510
+ return torch.sigmoid(mask)
511
+
512
+ def reshape_img2wav(self, x):
513
+ # (B, 1, 256, 256)
514
+ x = x.reshape(x.shape[0], x.shape[1], self.freq_ratio, x.shape[2]//self.freq_ratio, x.shape[3]) # (B, 1, 4, 64, 256)
515
+ x = x.permute(0, 1, 3, 2, 4).contiguous()
516
+ x = x.reshape(x.shape[0], x.shape[1], x.shape[2], x.shape[3] * x.shape[4])
517
+ x = x.permute(0, 1, 3, 2).contiguous()
518
+ return x
519
+
520
+
521
+ # if __name__ == "__main__":
522
+ # import torch
523
+ # from msclap import CLAP
524
+ # import os
525
+ # import torchaudio
526
+ # import torchaudio.transforms as T
527
+ # import numpy as np
528
+ # import random
529
+ # from torchlibrosa import Spectrogram, LogmelFilterBank
530
+ # clap_model = CLAP(model_fp="/home/user/202212661/clapsep/Waveformer-main/checkpoint_path/CLAP_weights_2023.pth",
531
+ # version='2023', use_cuda=True)
532
+ # text_data = [
533
+ # "Acoustic_guitar", "Applause", "Bark", "Bass_drum", "Burping_or_eructation",
534
+ # "Bus", "Cello", "Chime", "Clarinet", "Computer_keyboard",
535
+ # "Cough", "Cowbell", "Double_bass", "Drawer_open_or_close", "Electric_piano",
536
+ # "Fart", "Finger_snapping", "Fireworks", "Flute", "Glockenspiel",
537
+ # "Gong", "Gunshot_or_gunfire", "Harmonica", "Hi-hat", "Keys_jangling",
538
+ # "Knock", "Laughter", "Meow", "Microwave_oven", "Oboe",
539
+ # "Saxophone", "Scissors", "Shatter", "Snare_drum", "Squeak",
540
+ # "Tambourine", "Tearing", "Telephone", "Trumpet", "Violin_or_fiddle",
541
+ # "Writing"]
542
+ # # Extract text embeddings
543
+ # text_embeddings = clap_model.get_text_embeddings(text_data)
544
+ # path = "/home/user/202212661/clapsep/Waveformer-main/data/FSDSoundScapes/FSDKaggle2018/train/Tearing/2232ce13.wav"
545
+ # # Extract audio embeddings
546
+ # audio_embeddings_ = clap_model.get_audio_embeddings([path])
547
+ #
548
+ # window = 'hann'
549
+ # center = True
550
+ # pad_mode = 'reflect'
551
+ # ref = 1.0
552
+ # amin = 1e-10
553
+ # top_db = None
554
+ #
555
+ # spectrogram_extractor = Spectrogram(n_fft=512, hop_length=160,
556
+ # win_length=512, window=window, center=center, pad_mode=pad_mode,
557
+ # freeze_parameters=True).cuda()
558
+ # # Logmel feature extractor
559
+ # logmel_extractor = LogmelFilterBank(sr=16000, n_fft=512,
560
+ # n_mels=64, fmin=0, fmax=8000, ref=ref, amin=amin,
561
+ # top_db=top_db,
562
+ # freeze_parameters=True).cuda()
563
+ #
564
+ # clap_model.clap.audio_encoder.base.htsat.spectrogram_extractor = spectrogram_extractor
565
+ # clap_model.clap.audio_encoder.base.htsat.logmel_extractor = logmel_extractor
566
+ #
567
+ # features = []
568
+ #
569
+ #
570
+ # def get_features_list(module, input, output):
571
+ # features.append(output)
572
+ #
573
+ #
574
+ # def get_features_list_basic_layer(module, input, output):
575
+ # features.append(output[0])
576
+ #
577
+ #
578
+ # clap_model.clap.audio_encoder.base.htsat.patch_embed.register_forward_hook(get_features_list)
579
+ # for module in clap_model.clap.audio_encoder.base.htsat.layers:
580
+ # module.register_forward_hook(get_features_list_basic_layer)
581
+ #
582
+ # audio_time_series, sample_rate = torchaudio.load(path)
583
+ # resample_rate = 16000
584
+ # if resample_rate != sample_rate:
585
+ # resampler = T.Resample(sample_rate, resample_rate)
586
+ # audio_time_series = resampler(audio_time_series)
587
+ #
588
+ # sample_rate = resample_rate
589
+ # audio_duration = 10
590
+ # audio_time_series = audio_time_series.reshape(-1)
591
+ # if audio_duration * sample_rate >= audio_time_series.shape[0]:
592
+ # repeat_factor = int(np.ceil((audio_duration * sample_rate) /
593
+ # audio_time_series.shape[0]))
594
+ # # Repeat audio_time_series by repeat_factor to match audio_duration
595
+ # audio_time_series = audio_time_series.repeat(repeat_factor)
596
+ # # remove excess part of audio_time_series
597
+ # audio_time_series = audio_time_series[0:audio_duration * sample_rate]
598
+ # else:
599
+ # # audio_time_series is longer than predefined audio duration,
600
+ # # so audio_time_series is trimmed
601
+ # start_index = random.randrange(
602
+ # audio_time_series.shape[0] - audio_duration * sample_rate)
603
+ # audio_time_series = audio_time_series[start_index:start_index +
604
+ # audio_duration * sample_rate]
605
+ #
model/CLAPSep_infer.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: UTF-8 -*-
3
+ '''
4
+ @Project :Waveformer-main
5
+ @File :CLAPSep.py
6
+ @IDE :PyCharm
7
+ @Author :Aisaka/Hao Ma @SDU
8
+ @Date :2024/2/28 下午1:12
9
+ '''
10
+
11
+ import os
12
+ import torch
13
+ import laion_clap
14
+ from torchmetrics.audio.snr import(
15
+ scale_invariant_signal_noise_ratio as si_snr,
16
+ signal_noise_ratio as snr)
17
+ from torchmetrics.audio.sdr import(
18
+ signal_distortion_ratio as sdr,
19
+ scale_invariant_signal_distortion_ratio as si_sdr)
20
+ import copy
21
+ import loralib as lora
22
+ from torchlibrosa import ISTFT, STFT, SpecAugmentation
23
+ from torchlibrosa.stft import magphase
24
+ import librosa
25
+ import pytorch_lightning as pl
26
+ import soundfile as sf
27
+
28
+
29
+ def loss_fn(pred, tgt):
30
+ return -0.9 * snr(pred, tgt).mean() - 0.1 * si_snr(pred, tgt).mean()
31
+
32
+
33
+ def set_module(model, submodule_key, module):
34
+ tokens = submodule_key.split('.')
35
+ sub_tokens = tokens[:-1]
36
+ cur_mod = model
37
+ for s in sub_tokens:
38
+ cur_mod = getattr(cur_mod, s)
39
+ setattr(cur_mod, tokens[-1], module)
40
+
41
+
42
+ def process_model(model, rank):
43
+ for n, module in model.named_modules():
44
+ if 'WindowAttention' in str(type(module)):
45
+ for n_, layer in module.named_modules():
46
+ if isinstance(layer, torch.nn.Linear):
47
+ lora_layer = lora.Linear(layer.in_features, layer.out_features, r=rank,
48
+ bias=hasattr(layer, 'bias'), merge_weights=False)
49
+ lora_layer.weight = layer.weight
50
+ if hasattr(layer, 'bias'):
51
+ lora_layer.bias = layer.bias
52
+ set_module(model, n+'.'+n_, lora_layer)
53
+ return model
54
+
55
+
56
+ class LightningModule(pl.LightningModule):
57
+ def __init__(self, clap_model, decoder_model, lr, use_lora=False, rank=8, nfft=1024):
58
+ super().__init__()
59
+ self.phase = decoder_model.phase
60
+ self.lr = lr
61
+ self.clap_model = clap_model
62
+ for p in self.clap_model.parameters():
63
+ p.requires_grad = False
64
+ self.audio_branch = copy.deepcopy(self.clap_model.model.audio_branch)
65
+ if use_lora:
66
+ process_model(self.audio_branch, rank)
67
+ lora.mark_only_lora_as_trainable(self.audio_branch, bias='lora_only')
68
+
69
+ self.decoder_model = decoder_model
70
+ self.stft = STFT(n_fft=nfft, hop_length=320,
71
+ win_length=nfft, window='hann', center=True, pad_mode='reflect',
72
+ freeze_parameters=True)
73
+ self.istft = ISTFT(n_fft=nfft, hop_length=320,
74
+ win_length=nfft, window='hann', center=True, pad_mode='reflect',
75
+ freeze_parameters=True)
76
+ self.features = self.install_forward_hooks()
77
+
78
+ def training_step(self, batch, batch_idx):
79
+ self.clap_model.eval()
80
+ self.audio_branch.eval()
81
+ # print([len(x) for x in batch])
82
+ mixed, mixed_resample, pos_cap, neg_cap, gt, pos_sample, neg_sample = batch
83
+ real, imag = self.stft(mixed)
84
+ mag, cos, sin = magphase(real, imag)
85
+ with torch.no_grad():
86
+ a = torch.rand((1,)).type_as(gt)
87
+ embed_pos_a, embed_neg_a = torch.chunk(
88
+ self.clap_model.get_audio_embedding_from_data(torch.concat([pos_sample, neg_sample], dim=0),
89
+ use_tensor=True), dim=0, chunks=2)
90
+ embed_pos_t, embed_neg_t = torch.chunk(
91
+ self.clap_model.get_text_embedding(pos_cap + neg_cap, use_tensor=True), dim=0, chunks=2)
92
+ embed_pos = a * embed_pos_a + (1 - a) * embed_pos_t
93
+ embed_neg = a * embed_neg_a + (1 - a) * embed_neg_t
94
+ del self.features[:]
95
+ self.features.append(mag)
96
+ self.audio_branch({"waveform": mixed_resample})
97
+ a = torch.rand((1,))
98
+ if a < 0.25:
99
+ loss = self.cal_loss(embed_pos, torch.zeros_like(embed_pos), mag, cos, sin, length=mixed.size(-1), gt=gt)
100
+ elif a < 0.5:
101
+ loss = self.cal_loss(torch.zeros_like(embed_neg), embed_neg, mag, cos, sin, length=mixed.size(-1), gt=gt)
102
+ else:
103
+ loss = self.cal_loss(embed_pos, embed_neg, mag, cos, sin, length=mixed.size(-1), gt=gt)
104
+ self.log("train_loss", loss.item(), on_epoch=True, prog_bar=True, sync_dist=True, batch_size=len(mixed))
105
+ del self.features[:]
106
+ return loss
107
+
108
+ def cal_loss(self, embed_p, embed_n, mag, cos, sin, length, gt):
109
+ embed = torch.nn.functional.normalize(torch.concat([embed_p, embed_n], dim=-1), dim=-1)
110
+ mask = self.decoder_model(hidden_state=self.features[-1], skip_features=self.features[:-1], embed=embed)
111
+ pred = self.wav_reconstruct(mask, mag, cos, sin, length=length)
112
+ return loss_fn(pred, gt)
113
+
114
+ def wav_reconstruct(self, mask, mag_x, cos_x, sin_x, length):
115
+ # ref: https://github.com/Audio-AGI/AudioSep/blob/main/models/resunet.py
116
+ # Y = |Y|cos∠Y + j|Y|sin∠Y
117
+ # = |Y|cos(∠X + ∠M) + j|Y|sin(∠X + ∠M)
118
+ # = |Y|(cos∠X cos∠M - sin∠X sin∠M) + j|Y|(sin∠X cos∠M + cos∠X sin∠M)
119
+ if self.phase:
120
+ mag_y = torch.nn.functional.relu_(mag_x * mask[0])
121
+ _, mask_cos, mask_sin = magphase(mask[1], mask[2])
122
+ cos_y = cos_x * mask_cos - sin_x * mask_sin
123
+ sin_y = sin_x * mask_cos + cos_x * mask_sin
124
+ else:
125
+ mag_y = torch.nn.functional.relu_(mag_x * mask)
126
+ cos_y = cos_x
127
+ sin_y = sin_x
128
+ pred = self.istft(mag_y * cos_y, mag_y * sin_y, length=length)
129
+ return pred
130
+
131
+ def validation_step(self, batch, batch_idx):
132
+ mixed, mixed_resample, label, neg_label, gt, _, _ = batch
133
+ real, imag = self.stft(mixed)
134
+ mag, cos, sin = magphase(real, imag)
135
+ self.features.append(mag)
136
+ with torch.no_grad():
137
+ embed_pos = self.clap_model.get_text_embedding(label, use_tensor=True)
138
+ embed_neg = self.clap_model.get_text_embedding(neg_label, use_tensor=True)
139
+ embed = torch.concat([embed_pos, embed_neg], dim=-1)
140
+ self.audio_branch({"waveform": mixed_resample})
141
+ mask = self.decoder_model(hidden_state=self.features[-1], skip_features=self.features[:-1], embed=embed)
142
+ pred = self.wav_reconstruct(mask, mag, cos, sin, length=mixed.size(-1))
143
+ loss = si_snr(pred, gt).mean() - si_snr(mixed, gt).mean()
144
+ del self.features[:]
145
+ self.log("val_loss", loss, on_epoch=True, prog_bar=True, sync_dist=True, batch_size=len(mixed))
146
+ return {"val_loss": loss}
147
+
148
+
149
+ def test_step(self, batch, batch_idx):
150
+ mixed, mixed_resample, labels, src_path = batch
151
+ assert len(labels) == 1
152
+ src_path = src_path[0]
153
+ save_path = src_path.replace('/data/sound/audioset/audios_32k',
154
+ 'data_engine_infer/audioset_separation_child_label')[:-4]
155
+ os.makedirs(save_path, exist_ok=True)
156
+ real, imag = self.stft(mixed)
157
+ mag, cos, sin = magphase(real, imag)
158
+ with torch.no_grad():
159
+ labels = labels[0].split('|')
160
+ for pos_label in labels:
161
+ embed_pos = self.clap_model.get_text_embedding(pos_label, use_tensor=True)
162
+
163
+ neg_labels = copy.deepcopy(labels)
164
+ neg_labels.remove(pos_label)
165
+ if neg_labels:
166
+ neg_label = ', '.join(neg_labels)
167
+ embed_neg = self.clap_model.get_text_embedding(neg_label, use_tensor=True)
168
+ else:
169
+ embed_neg = torch.zeros_like(embed_pos)
170
+ # only positive
171
+ # embed = torch.concat([embed_pos, torch.zeros_like(embed_pos)], dim=1)
172
+ # positive and negative
173
+ embed = torch.concat([embed_pos, embed_neg], dim=1)
174
+ del self.features[:]
175
+ self.features.append(mag)
176
+ self.audio_branch({"waveform": mixed_resample})
177
+ mask = self.decoder_model(hidden_state=self.features[-1], skip_features=self.features[:-1], embed=embed)
178
+ pred = self.wav_reconstruct(mask, mag, cos, sin, length=mixed.size(-1))
179
+ del self.features[:]
180
+ sf.write(os.path.join(save_path, pos_label + '.wav'), pred.squeeze().cpu().numpy(), samplerate=32000)
181
+
182
+
183
+
184
+ def configure_optimizers(self):
185
+ optimizer = torch.optim.AdamW(self.parameters(), lr=self.lr)
186
+ schedular = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.3, patience=5,
187
+ verbose=True, min_lr=5e-6)
188
+ return {
189
+ "optimizer": optimizer,
190
+ "lr_scheduler": {
191
+ "scheduler": schedular,
192
+ "interval": "epoch",
193
+ "monitor": "val_loss"
194
+ },
195
+ }
196
+
197
+ def install_forward_hooks(self):
198
+ features = []
199
+ spec_augmenter = SpecAugmentation(time_drop_width=64, time_stripes_num=2,
200
+ freq_drop_width=8, freq_stripes_num=2)
201
+
202
+ def get_features_list(_, __, output):
203
+ features.append(output)
204
+
205
+ def get_features_list_basic_layer(_, __, output):
206
+ features.append(output[0])
207
+
208
+ def spec_augmentation_hook(_, __, out):
209
+ out = out.transpose(1, 3)
210
+ out = spec_augmenter(out)
211
+ return out.transpose(1, 3)
212
+
213
+ def spectrogram_padding(_, __, out):
214
+ return torch.nn.functional.pad(out, (0, 0, 0, 1024 - out.size(2)))
215
+
216
+ self.clap_model.model.audio_branch.bn0.register_forward_hook(spec_augmentation_hook)
217
+ self.audio_branch.spectrogram_extractor.register_forward_hook(spectrogram_padding)
218
+ self.audio_branch.patch_embed.register_forward_hook(get_features_list)
219
+ for module in self.audio_branch.layers:
220
+ module.register_forward_hook(get_features_list_basic_layer)
221
+ return features
222
+
223
+ # # this will only save tuned parameters during training
224
+ # def on_save_checkpoint(self, checkpoint):
225
+ # weights = checkpoint['state_dict']
226
+ # new_dict = {}
227
+ # for k, v in weights.items():
228
+ # if any(e in k for e in ['lora', 'attn.qkv.bias', 'attn.proj.bias', 'decoder_model']):
229
+ # new_dict[k] = v
230
+ # checkpoint['state_dict'] = new_dict
231
+
232
+
233
+
model/__init__.py ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # torch
2
+ librosa
3
+ # torchaudio
4
+ # torchvision
5
+ pytorch-lightning==2.4.0
6
+ tensorboard==2.18.0
7
+ torchlibrosa
8
+ numpy==1.26.4
9
+ einops
10
+ loralib
11
+ transformers==4.30.2
12
+ laion-clap
13
+ matplotlib
run.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ exp_dir=experiments/ClearSep_audioset_32k
4
+
5
+ resume_ckpt="${exp_dir}/checkpoints/last.ckpt"
6
+
7
+ python train.py $exp_dir \
8
+ --resume_ckpt $resume_ckpt \
9
+ --use_cuda \
10
+ --gpu_ids 0 1 2 3
11
+
train.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import torch
4
+ import torch.utils.data
5
+ import pytorch_lightning as pl
6
+ import laion_clap
7
+ from pytorch_lightning.loggers import TensorBoardLogger
8
+ from pytorch_lightning.callbacks import ModelCheckpoint
9
+ from model.CLAPSep_decoder import HTSAT_Decoder
10
+ from model.CLAPSep import LightningModule
11
+ import argparse
12
+ from helpers import utils as local_utils
13
+ from dataset import CLAPSepDataSet, CLAPSepDataEngineDataSet
14
+
15
+ import wandb
16
+ from pytorch_lightning.loggers import WandbLogger
17
+
18
+
19
+ def main(args):
20
+ torch.set_float32_matmul_precision('medium')
21
+ # Load dataset
22
+ data_train = CLAPSepDataEngineDataSet(**args.train_data)
23
+ # data_train = CLAPSepDataSet(**args.train_data)
24
+ logging.info("Loaded train dataset at %s containing %d elements" %
25
+ (args.train_data['data_list'], len(data_train)))
26
+ data_val = CLAPSepDataSet(**args.val_data)
27
+ logging.info("Loaded test dataset at %s containing %d elements" %
28
+ (args.val_data['data_list'], len(data_val)))
29
+ train_loader = torch.utils.data.DataLoader(data_train,
30
+ batch_size=args.batch_size,
31
+ shuffle=True,
32
+ num_workers=args.n_workers,
33
+ pin_memory=True)
34
+ val_loader = torch.utils.data.DataLoader(data_val,
35
+ batch_size=args.eval_batch_size,
36
+ shuffle=False,
37
+ num_workers=args.n_workers,
38
+ pin_memory=True)
39
+
40
+ clap_model = laion_clap.CLAP_Module(enable_fusion=False, amodel='HTSAT-base', device='cpu')
41
+ clap_model.load_ckpt(args.clap_path)
42
+ decoder = HTSAT_Decoder(**args.model)
43
+ lightning_module = LightningModule(clap_model, decoder, lr=args.optim['lr'],
44
+ use_lora=args.lora,
45
+ rank=args.lora_rank,
46
+ nfft=args.nfft,)
47
+
48
+ checkpoint_callback = ModelCheckpoint(dirpath=os.path.join(args.exp_dir, 'checkpoints'),
49
+ filename="{epoch:02d}-{step}-{val_loss:.2f}",
50
+ monitor="val_loss",
51
+ mode="max",
52
+ save_top_k=3,
53
+ every_n_train_steps=args.save_ckpt_every_steps,
54
+ save_last=True)
55
+ logger = TensorBoardLogger(args.exp_dir)
56
+ # wandb_logger = WandbLogger(project='clapsep')
57
+ # wandb_logger = WandbLogger(project='clapsep', id='', resume='must')
58
+ # distributed_backend = "ddp_find_unused_parameters_true"
59
+ distributed_backend = "ddp"
60
+ trainer = pl.Trainer(
61
+ default_root_dir=args.exp_dir,
62
+ devices=args.gpu_ids if args.use_cuda else "auto",
63
+ accelerator="gpu" if args.use_cuda else "cpu",
64
+ benchmark=True,
65
+ gradient_clip_val=5.0,
66
+ precision='bf16-mixed',
67
+ limit_train_batches=1.0,
68
+ max_epochs=args.epochs,
69
+ strategy=distributed_backend,
70
+ logger=logger,
71
+ callbacks=[checkpoint_callback],
72
+ )
73
+
74
+ if os.path.exists(args.resume_ckpt):
75
+ print('Load resume ckpt:', args.resume_ckpt)
76
+ trainer.fit(model=lightning_module, train_dataloaders=train_loader, val_dataloaders=val_loader,
77
+ ckpt_path=args.resume_ckpt)
78
+ elif os.path.exists(args.init_ckpt):
79
+ print('Load init ckpt:', args.init_ckpt)
80
+ weights = torch.load(args.init_ckpt, map_location='cpu')['state_dict']
81
+ lightning_module.load_state_dict(weights, strict=False)
82
+ trainer.fit(model=lightning_module, train_dataloaders=train_loader, val_dataloaders=val_loader)
83
+ else:
84
+ print('Training from scratch')
85
+ trainer.fit(model=lightning_module, train_dataloaders=train_loader, val_dataloaders=val_loader)
86
+
87
+
88
+ if __name__ == '__main__':
89
+ parser = argparse.ArgumentParser()
90
+ # Data Params
91
+ parser.add_argument('exp_dir', type=str,
92
+ default='./experiments/CLAPSep_base',
93
+ help="Path to save checkpoints and logs.")
94
+ parser.add_argument('--init_ckpt', type=str, default='')
95
+ parser.add_argument('--resume_ckpt', type=str, default='')
96
+
97
+ parser.add_argument('--multi_label_training', dest='multi_label_training', action='store_true',
98
+ help="Whether to multi label training")
99
+
100
+ parser.add_argument('--use_cuda', dest='use_cuda', action='store_true',
101
+ help="Whether to use cuda")
102
+ parser.add_argument('--gpu_ids', nargs='+', type=int, default=None,
103
+ help="List of GPU ids used for training. "
104
+ "Eg., --gpu_ids 2 4. All GPUs are used by default.")
105
+
106
+ args = parser.parse_args()
107
+
108
+ # Set the random seed for reproducible experiments
109
+ pl.seed_everything(114514)
110
+ # Set up checkpoints
111
+ if not os.path.exists(args.exp_dir):
112
+ os.makedirs(args.exp_dir)
113
+
114
+ # Load model and training params
115
+ params = local_utils.Params(os.path.join(args.exp_dir, 'config.json'))
116
+ for k, v in params.__dict__.items():
117
+ vars(args)[k] = v
118
+ main(args)