fsoft-ai-center commited on
Commit
79f6504
·
verified ·
1 Parent(s): 238b5d5

Upload 24 files

Browse files
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz 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
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ process.ipynb
2
+ clean_speech/
3
+ noise/
4
+ __pycache__/
5
+ test.py
README.md CHANGED
@@ -1,12 +1,12 @@
1
- ---
2
- title: Speech Enhancement
3
- emoji: 🏆
4
- colorFrom: pink
5
- colorTo: green
6
- sdk: streamlit
7
- sdk_version: 1.36.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Speech Denoising
3
+ emoji:
4
+ colorFrom: red
5
+ colorTo: red
6
+ sdk: streamlit
7
+ sdk_version: 1.36.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
aic-logo.png ADDED
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import base64
4
+ import librosa
5
+ import numpy as np
6
+ from io import BytesIO
7
+ import streamlit as st
8
+ from pydub import AudioSegment
9
+ import matplotlib.pyplot as plt
10
+ from scipy.io.wavfile import write
11
+ from src.denoise import denoise
12
+ from myrecorder import recorder
13
+
14
+
15
+ SR = 16000
16
+ CONTAINER_HEIGHT = 380
17
+
18
+
19
+ def np_audio_to_bytesio(np_audio, np_audio_sr):
20
+ _bytes = bytes()
21
+ byte_io = io.BytesIO(_bytes)
22
+ write(byte_io, np_audio_sr, np_audio)
23
+ bytes_audio = byte_io.read()
24
+ return bytes_audio
25
+
26
+
27
+ def autoplay_audio(audio: str):
28
+ audio_base64 = base64.b64encode(audio).decode('utf-8')
29
+ audio_tag = f'<audio autoplay="true" src="data:audio/wav;base64,{audio_base64}">'
30
+ st.markdown(audio_tag, unsafe_allow_html=True)
31
+
32
+
33
+ def load_noisy_speech(root=os.path.join(os.getcwd(), 'noisy_speech')):
34
+ noisy_speech_paths = {'EN':{}, 'JA': {}}
35
+ noisy_speech_names = os.listdir(root)
36
+ for name in noisy_speech_names:
37
+ splt = name.split('_')
38
+ lang, snr = splt[0].upper(), int(splt[1][:2])
39
+ noisy_speech_paths[lang][snr] = os.path.join(root, name)
40
+
41
+ en_keys = list(noisy_speech_paths['EN'].keys())
42
+ en_keys.sort()
43
+ en_keys.reverse()
44
+ noisy_speech_paths['EN'] = {f'{key}dB': noisy_speech_paths['EN'][key] for key in en_keys}
45
+
46
+ ja_keys = list(noisy_speech_paths['JA'].keys())
47
+ ja_keys.sort()
48
+ ja_keys.reverse()
49
+ noisy_speech_paths['JA'] = {f'{key}dB': noisy_speech_paths['JA'][key] for key in ja_keys}
50
+
51
+ return noisy_speech_paths
52
+
53
+
54
+ def load_wav(wav_path):
55
+ wav_22k, sr = librosa.load(wav_path)
56
+ wav_16k = librosa.resample(wav_22k, orig_sr=sr, target_sr=SR)
57
+ return wav_22k, wav_16k
58
+
59
+
60
+ def wav_to_spec(wav, sr):
61
+ if sr == 16000:
62
+ wav = librosa.resample(wav, orig_sr=sr, target_sr=22050)
63
+ spec = np.abs(librosa.stft(wav))
64
+ spec = librosa.amplitude_to_db(spec, ref=np.max)
65
+ return spec
66
+
67
+
68
+ def export_spec_to_buffer(spec):
69
+ plt.rcParams['figure.figsize'] = (16, 4.5)
70
+ plt.rc('axes', labelsize=15)
71
+ plt.rc('xtick', labelsize=15)
72
+ plt.rc('ytick', labelsize=15)
73
+ librosa.display.specshow(spec, y_axis='log', x_axis='time')
74
+ img_buffer = BytesIO()
75
+ plt.savefig(img_buffer, format='JPEG', bbox_inches='tight', pad_inches=0)
76
+ return img_buffer
77
+
78
+
79
+ def process_recorded_wav_bytes(wav_bytes, sr):
80
+ file = BytesIO(wav_bytes)
81
+ audio = AudioSegment.from_file(file=file, format='wav')
82
+ audio = audio.set_sample_width(2)
83
+ audio = audio.set_channels(1)
84
+ audio_22k = audio.set_frame_rate(sr)
85
+ audio_16k = audio.set_frame_rate(SR)
86
+ audio_22k = np.array(audio_22k.get_array_of_samples(), dtype=np.float32)
87
+ audio_16k = np.array(audio_16k.get_array_of_samples(), dtype=np.float32)
88
+ return audio_22k, audio_16k
89
+
90
+
91
+ def main():
92
+
93
+ st.set_page_config(
94
+ page_title="speech-denoising-app",
95
+ layout="wide"
96
+ )
97
+
98
+ logo_space, title_space, _ = st.columns([1, 5, 1], gap="small")
99
+
100
+ with logo_space:
101
+ st.write(
102
+ """
103
+ <div style="display: flex; justify-content: left;">
104
+ <b><span style="text-align: center; color: #101414; font-size: 14px">FPT Corporation</span></b>
105
+ </div>
106
+ """,
107
+ unsafe_allow_html=True
108
+ )
109
+ st.image('aic-logo.png')
110
+
111
+ with title_space:
112
+ st.image('logo.png')
113
+
114
+ noisy_speech_files = load_noisy_speech()
115
+
116
+ input_space, output_space = st.columns([1, 1], gap="medium")
117
+ _, record_space, _, compute_space= st.columns([0.7, 1, 1, 1], gap="small")
118
+
119
+ with record_space:
120
+ record = recorder(
121
+ start_prompt="Start Recording",
122
+ stop_prompt="Stop Recording",
123
+ just_once=False,
124
+ use_container_width=False,
125
+ format="wav",
126
+ callback=None,
127
+ args=(),
128
+ kwargs={},
129
+ key=None
130
+ )
131
+
132
+ with compute_space:
133
+ compute = st.button('Denoise')
134
+
135
+ with input_space.container(height=CONTAINER_HEIGHT, border=True):
136
+ lang_select_space, snr_select_space = st.columns([1, 1], gap="small")
137
+ with lang_select_space:
138
+ language_select = st.selectbox("Language", list(noisy_speech_files.keys()))
139
+ with snr_select_space:
140
+ if language_select:
141
+ snr_select = st.selectbox("SNR Level", list(noisy_speech_files[language_select].keys()))
142
+
143
+ if record:
144
+ wav_bytes_record = record['bytes']
145
+ sr = record['sample_rate']
146
+ noisy_wav_22k, noisy_wav = process_recorded_wav_bytes(wav_bytes_record, sr=22050)
147
+ noisy_spec = wav_to_spec(noisy_wav_22k, sr=22050)
148
+ noisy_spec_buff = export_spec_to_buffer(noisy_spec)
149
+
150
+ st.audio(wav_bytes_record, format="wav")
151
+ st.image(image=noisy_spec_buff)
152
+
153
+ elif language_select and snr_select:
154
+ audio_path = noisy_speech_files[language_select][snr_select]
155
+ noisy_wav_22k, noisy_wav = load_wav(audio_path)
156
+ noisy_spec = wav_to_spec(noisy_wav_22k, sr=22050)
157
+ noisy_spec_buff = export_spec_to_buffer(noisy_spec)
158
+
159
+ st.audio(audio_path, format="wav")
160
+ st.image(image=noisy_spec_buff)
161
+
162
+ with output_space.container(height=CONTAINER_HEIGHT, border=True):
163
+ st.write(
164
+ """
165
+ <div style="display: flex; justify-content: center;">
166
+ <b><span style="text-align: center; color: #808080; font-size: 51.5px">Output</span></b>
167
+ </div>
168
+ """,
169
+ unsafe_allow_html=True
170
+ )
171
+ if noisy_wav.any() and compute:
172
+ denoised_wav = denoise(noisy_wav)
173
+ st.audio(denoised_wav, sample_rate=SR, format="audio/wav")
174
+ denoised_spec = wav_to_spec(denoised_wav, sr=SR)
175
+ denoised_spec_buff = export_spec_to_buffer(denoised_spec)
176
+ st.image(image=denoised_spec_buff)
177
+ record = None
178
+
179
+
180
+ if __name__ == '__main__':
181
+ main()
ckpt/full.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:145c101eb5bbfa3ba52fb2b4ec7e5b64a361c102f89291f75e1dd42601d95dc9
3
+ size 184336765
ckpt/high.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:513d9e4f69483bf2bcc3059dd6b3644140763bf3f22df41d7ee366cc2cbd1829
3
+ size 184336765
configs/full.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "network_config": {
3
+ "channels_input": 1,
4
+ "channels_output": 1,
5
+ "channels_H": 64,
6
+ "max_H": 768,
7
+ "encoder_n_layers": 8,
8
+ "kernel_size": 4,
9
+ "stride": 2,
10
+ "tsfm_n_layers": 5,
11
+ "tsfm_n_head": 8,
12
+ "tsfm_d_model": 512,
13
+ "tsfm_d_inner": 2048
14
+ },
15
+ "train_config": {
16
+ "exp_path": "DNS-large-full",
17
+ "log":{
18
+ "directory": "./exp",
19
+ "ckpt_iter": "max",
20
+ "iters_per_ckpt": 10000,
21
+ "iters_per_valid": 500
22
+ },
23
+ "optimization":{
24
+ "n_iters": 250000,
25
+ "learning_rate": 2e-4,
26
+ "batch_size_per_gpu": 8
27
+ },
28
+ "loss_config":{
29
+ "ell_p": 1,
30
+ "ell_p_lambda": 1,
31
+ "stft_lambda": 1,
32
+ "stft_config":{
33
+ "sc_lambda": 0.5,
34
+ "mag_lambda": 0.5,
35
+ "band": "full",
36
+ "hop_sizes": [50, 120, 240],
37
+ "win_lengths": [240, 600, 1200],
38
+ "fft_sizes": [512, 1024, 2048]
39
+ }
40
+ }
41
+ },
42
+ "trainset_config": {
43
+ "root": "./dns",
44
+ "crop_length_sec": 10,
45
+ "sample_rate": 16000
46
+ },
47
+ "gen_config":{
48
+ "output_directory": "./exp"
49
+ },
50
+ "dist_config": {
51
+ "dist_backend": "nccl",
52
+ "dist_url": "tcp://localhost:54321"
53
+ }
54
+ }
configs/high.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "network_config": {
3
+ "channels_input": 1,
4
+ "channels_output": 1,
5
+ "channels_H": 64,
6
+ "max_H": 768,
7
+ "encoder_n_layers": 8,
8
+ "kernel_size": 4,
9
+ "stride": 2,
10
+ "tsfm_n_layers": 5,
11
+ "tsfm_n_head": 8,
12
+ "tsfm_d_model": 512,
13
+ "tsfm_d_inner": 2048
14
+ },
15
+ "train_config": {
16
+ "exp_path": "DNS-large-high",
17
+ "log":{
18
+ "directory": "./exp",
19
+ "ckpt_iter": "max",
20
+ "iters_per_ckpt": 10000,
21
+ "iters_per_valid": 500
22
+ },
23
+ "optimization":{
24
+ "n_iters": 250000,
25
+ "learning_rate": 2e-4,
26
+ "batch_size_per_gpu": 8
27
+ },
28
+ "loss_config":{
29
+ "ell_p": 1,
30
+ "ell_p_lambda": 1,
31
+ "stft_lambda": 1,
32
+ "stft_config":{
33
+ "sc_lambda": 0.5,
34
+ "mag_lambda": 0.5,
35
+ "band": "high",
36
+ "hop_sizes": [50, 120, 240],
37
+ "win_lengths": [240, 600, 1200],
38
+ "fft_sizes": [512, 1024, 2048]
39
+ }
40
+ }
41
+ },
42
+ "trainset_config": {
43
+ "root": "./dns",
44
+ "crop_length_sec": 10,
45
+ "sample_rate": 16000
46
+ },
47
+ "gen_config":{
48
+ "output_directory": "./exp"
49
+ },
50
+ "dist_config": {
51
+ "dist_backend": "nccl",
52
+ "dist_url": "tcp://localhost:54321"
53
+ }
54
+ }
logo.png ADDED
noisy_speech/EN_+0dB.wav ADDED
Binary file (618 kB). View file
 
noisy_speech/EN_+3dB.wav ADDED
Binary file (494 kB). View file
 
noisy_speech/EN_+6dB.wav ADDED
Binary file (444 kB). View file
 
noisy_speech/EN_-3dB.wav ADDED
Binary file (613 kB). View file
 
noisy_speech/EN_-6db.wav ADDED
Binary file (489 kB). View file
 
noisy_speech/JA_+0dB.wav ADDED
Binary file (693 kB). View file
 
noisy_speech/JA_+3dB.wav ADDED
Binary file (652 kB). View file
 
noisy_speech/JA_+6dB.wav ADDED
Binary file (530 kB). View file
 
noisy_speech/JA_-3dB.wav ADDED
Binary file (719 kB). View file
 
noisy_speech/JA_-6dB.wav ADDED
Binary file (833 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ numpy <= 1.25
2
+ streamlit
3
+ scipy
4
+ myrecorder
5
+ librosa
6
+ torch
src/denoise.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import torch
4
+ import random
5
+ random.seed(0)
6
+ torch.manual_seed(0)
7
+ import numpy as np
8
+ np.random.seed(0)
9
+ from src.model import DenoisingModel
10
+
11
+
12
+ def denoise(
13
+ wav: np.ndarray,
14
+ ckpt_path: str = os.path.join(os.getcwd(), 'ckpt', 'full.pkl'),
15
+ cfg_path: str = os.path.join(os.getcwd(), 'configs', 'full.json'),
16
+ ):
17
+
18
+ with open(cfg_path) as f:
19
+ data = f.read()
20
+ config = json.loads(data)
21
+
22
+ net = DenoisingModel(**config['network_config']).to('cpu')
23
+
24
+ # load checkpoint
25
+ checkpoint = torch.load(ckpt_path, map_location='cpu')
26
+ net.load_state_dict(checkpoint['model_state_dict'])
27
+ net.eval()
28
+
29
+ # inference
30
+ wav = torch.from_numpy(wav).unsqueeze(0)
31
+ wav_denoised = net(wav).squeeze(0).detach().numpy().reshape(-1)
32
+
33
+ return wav_denoised
src/model.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 NVIDIA CORPORATION.
2
+ # Licensed under the MIT license.
3
+
4
+ import numpy as np
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from src.utils import weight_scaling_init
11
+
12
+
13
+ # Transformer (encoder) https://github.com/jadore801120/attention-is-all-you-need-pytorch
14
+ # Original Copyright 2017 Victor Huang
15
+ # MIT License (https://opensource.org/licenses/MIT)
16
+
17
+ class ScaledDotProductAttention(nn.Module):
18
+ ''' Scaled Dot-Product Attention '''
19
+
20
+ def __init__(self, temperature, attn_dropout=0.1):
21
+ super().__init__()
22
+ self.temperature = temperature
23
+ self.dropout = nn.Dropout(attn_dropout)
24
+
25
+ def forward(self, q, k, v, mask=None):
26
+
27
+ attn = torch.matmul(q / self.temperature, k.transpose(2, 3))
28
+
29
+ if mask is not None:
30
+ attn = attn.masked_fill(mask == 0, -1e9)
31
+
32
+ attn = self.dropout(F.softmax(attn, dim=-1))
33
+ output = torch.matmul(attn, v)
34
+
35
+ return output, attn
36
+
37
+
38
+ class MultiHeadAttention(nn.Module):
39
+ ''' Multi-Head Attention module '''
40
+
41
+ def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
42
+ super().__init__()
43
+
44
+ self.n_head = n_head
45
+ self.d_k = d_k
46
+ self.d_v = d_v
47
+
48
+ self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
49
+ self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
50
+ self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
51
+ self.fc = nn.Linear(n_head * d_v, d_model, bias=False)
52
+
53
+ self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)
54
+
55
+ self.dropout = nn.Dropout(dropout)
56
+ self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
57
+
58
+
59
+ def forward(self, q, k, v, mask=None):
60
+
61
+ d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
62
+ sz_b, len_q, len_k, len_v = q.size(0), q.size(1), k.size(1), v.size(1)
63
+
64
+ residual = q
65
+
66
+ # Pass through the pre-attention projection: b x lq x (n*dv)
67
+ # Separate different heads: b x lq x n x dv
68
+ q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
69
+ k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
70
+ v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
71
+
72
+ # Transpose for attention dot product: b x n x lq x dv
73
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
74
+
75
+ if mask is not None:
76
+ mask = mask.unsqueeze(1) # For head axis broadcasting.
77
+
78
+ q, attn = self.attention(q, k, v, mask=mask)
79
+
80
+ # Transpose to move the head dimension back: b x lq x n x dv
81
+ # Combine the last two dimensions to concatenate all the heads together: b x lq x (n*dv)
82
+ q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1)
83
+ q = self.dropout(self.fc(q))
84
+ q += residual
85
+
86
+ q = self.layer_norm(q)
87
+
88
+ return q, attn
89
+
90
+
91
+ class PositionwiseFeedForward(nn.Module):
92
+ ''' A two-feed-forward-layer module '''
93
+
94
+ def __init__(self, d_in, d_hid, dropout=0.1):
95
+ super().__init__()
96
+ self.w_1 = nn.Linear(d_in, d_hid) # position-wise
97
+ self.w_2 = nn.Linear(d_hid, d_in) # position-wise
98
+ self.layer_norm = nn.LayerNorm(d_in, eps=1e-6)
99
+ self.dropout = nn.Dropout(dropout)
100
+
101
+ def forward(self, x):
102
+
103
+ residual = x
104
+
105
+ x = self.w_2(F.relu(self.w_1(x)))
106
+ x = self.dropout(x)
107
+ x += residual
108
+
109
+ x = self.layer_norm(x)
110
+
111
+ return x
112
+
113
+
114
+ def get_subsequent_mask(seq):
115
+ ''' For masking out the subsequent info. '''
116
+ sz_b, len_s = seq.size()
117
+ subsequent_mask = (1 - torch.triu(
118
+ torch.ones((1, len_s, len_s), device=seq.device), diagonal=1)).bool()
119
+ return subsequent_mask
120
+
121
+
122
+ class PositionalEncoding(nn.Module):
123
+
124
+ def __init__(self, d_hid, n_position=200):
125
+ super(PositionalEncoding, self).__init__()
126
+
127
+ # Not a parameter
128
+ self.register_buffer('pos_table', self._get_sinusoid_encoding_table(n_position, d_hid))
129
+
130
+ def _get_sinusoid_encoding_table(self, n_position, d_hid):
131
+ ''' Sinusoid position encoding table '''
132
+ # TODO: make it with torch instead of numpy
133
+
134
+ def get_position_angle_vec(position):
135
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
136
+
137
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
138
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
139
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
140
+
141
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
142
+
143
+ def forward(self, x):
144
+ return x + self.pos_table[:, :x.size(1)].clone().detach()
145
+
146
+
147
+ class EncoderLayer(nn.Module):
148
+ ''' Compose with two layers '''
149
+
150
+ def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.0):
151
+ super(EncoderLayer, self).__init__()
152
+ self.slf_attn = MultiHeadAttention(n_head, d_model, d_k, d_v, dropout=dropout)
153
+ self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout)
154
+
155
+ def forward(self, enc_input, slf_attn_mask=None):
156
+ enc_output, enc_slf_attn = self.slf_attn(
157
+ enc_input, enc_input, enc_input, mask=slf_attn_mask)
158
+ enc_output = self.pos_ffn(enc_output)
159
+ return enc_output, enc_slf_attn
160
+
161
+
162
+ class TransformerEncoder(nn.Module):
163
+ ''' A encoder model with self attention mechanism. '''
164
+
165
+ def __init__(
166
+ self, d_word_vec=512, n_layers=2, n_head=8, d_k=64, d_v=64,
167
+ d_model=512, d_inner=2048, dropout=0.1, n_position=624, scale_emb=False):
168
+
169
+ super().__init__()
170
+
171
+ # self.src_word_emb = nn.Embedding(n_src_vocab, d_word_vec, padding_idx=pad_idx)
172
+ if n_position > 0:
173
+ self.position_enc = PositionalEncoding(d_word_vec, n_position=n_position)
174
+ else:
175
+ self.position_enc = lambda x: x
176
+ self.dropout = nn.Dropout(p=dropout)
177
+ self.layer_stack = nn.ModuleList([
178
+ EncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout)
179
+ for _ in range(n_layers)])
180
+ self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
181
+ self.scale_emb = scale_emb
182
+ self.d_model = d_model
183
+
184
+ def forward(self, src_seq, src_mask, return_attns=False):
185
+
186
+ enc_slf_attn_list = []
187
+
188
+ # -- Forward
189
+ # enc_output = self.src_word_emb(src_seq)
190
+ enc_output = src_seq
191
+ if self.scale_emb:
192
+ enc_output *= self.d_model ** 0.5
193
+ enc_output = self.dropout(self.position_enc(enc_output))
194
+ enc_output = self.layer_norm(enc_output)
195
+
196
+ for enc_layer in self.layer_stack:
197
+ enc_output, enc_slf_attn = enc_layer(enc_output, slf_attn_mask=src_mask)
198
+ enc_slf_attn_list += [enc_slf_attn] if return_attns else []
199
+
200
+ if return_attns:
201
+ return enc_output, enc_slf_attn_list
202
+ return enc_output
203
+
204
+
205
+ # CleanUNet architecture
206
+
207
+
208
+ def padding(x, D, K, S):
209
+ """padding zeroes to x so that denoised audio has the same length"""
210
+
211
+ L = x.shape[-1]
212
+ for _ in range(D):
213
+ if L < K:
214
+ L = 1
215
+ else:
216
+ L = 1 + np.ceil((L - K) / S)
217
+
218
+ for _ in range(D):
219
+ L = (L - 1) * S + K
220
+
221
+ L = int(L)
222
+ x = F.pad(x, (0, L - x.shape[-1]))
223
+ return x
224
+
225
+
226
+ class DenoisingModel(nn.Module):
227
+ """ CleanUNet architecture. """
228
+
229
+ def __init__(self, channels_input=1, channels_output=1,
230
+ channels_H=64, max_H=768,
231
+ encoder_n_layers=8, kernel_size=4, stride=2,
232
+ tsfm_n_layers=3,
233
+ tsfm_n_head=8,
234
+ tsfm_d_model=512,
235
+ tsfm_d_inner=2048):
236
+
237
+ """
238
+ Parameters:
239
+ channels_input (int): input channels
240
+ channels_output (int): output channels
241
+ channels_H (int): middle channels H that controls capacity
242
+ max_H (int): maximum H
243
+ encoder_n_layers (int): number of encoder/decoder layers D
244
+ kernel_size (int): kernel size K
245
+ stride (int): stride S
246
+ tsfm_n_layers (int): number of self attention blocks N
247
+ tsfm_n_head (int): number of heads in each self attention block
248
+ tsfm_d_model (int): d_model of self attention
249
+ tsfm_d_inner (int): d_inner of self attention
250
+ """
251
+
252
+ super(DenoisingModel, self).__init__()
253
+
254
+ self.channels_input = channels_input
255
+ self.channels_output = channels_output
256
+ self.channels_H = channels_H
257
+ self.max_H = max_H
258
+ self.encoder_n_layers = encoder_n_layers
259
+ self.kernel_size = kernel_size
260
+ self.stride = stride
261
+
262
+ self.tsfm_n_layers = tsfm_n_layers
263
+ self.tsfm_n_head = tsfm_n_head
264
+ self.tsfm_d_model = tsfm_d_model
265
+ self.tsfm_d_inner = tsfm_d_inner
266
+
267
+ # encoder and decoder
268
+ self.encoder = nn.ModuleList()
269
+ self.decoder = nn.ModuleList()
270
+
271
+ for i in range(encoder_n_layers):
272
+ self.encoder.append(nn.Sequential(
273
+ nn.Conv1d(channels_input, channels_H, kernel_size, stride),
274
+ nn.ReLU(),
275
+ nn.Conv1d(channels_H, channels_H * 2, 1),
276
+ nn.GLU(dim=1)
277
+ ))
278
+ channels_input = channels_H
279
+
280
+ if i == 0:
281
+ # no relu at end
282
+ self.decoder.append(nn.Sequential(
283
+ nn.Conv1d(channels_H, channels_H * 2, 1),
284
+ nn.GLU(dim=1),
285
+ nn.ConvTranspose1d(channels_H, channels_output, kernel_size, stride)
286
+ ))
287
+ else:
288
+ self.decoder.insert(0, nn.Sequential(
289
+ nn.Conv1d(channels_H, channels_H * 2, 1),
290
+ nn.GLU(dim=1),
291
+ nn.ConvTranspose1d(channels_H, channels_output, kernel_size, stride),
292
+ nn.ReLU()
293
+ ))
294
+ channels_output = channels_H
295
+
296
+ # double H but keep below max_H
297
+ channels_H *= 2
298
+ channels_H = min(channels_H, max_H)
299
+
300
+ # self attention block
301
+ self.tsfm_conv1 = nn.Conv1d(channels_output, tsfm_d_model, kernel_size=1)
302
+ self.tsfm_encoder = TransformerEncoder(d_word_vec=tsfm_d_model,
303
+ n_layers=tsfm_n_layers,
304
+ n_head=tsfm_n_head,
305
+ d_k=tsfm_d_model // tsfm_n_head,
306
+ d_v=tsfm_d_model // tsfm_n_head,
307
+ d_model=tsfm_d_model,
308
+ d_inner=tsfm_d_inner,
309
+ dropout=0.0,
310
+ n_position=0,
311
+ scale_emb=False)
312
+ self.tsfm_conv2 = nn.Conv1d(tsfm_d_model, channels_output, kernel_size=1)
313
+
314
+ # weight scaling initialization
315
+ for layer in self.modules():
316
+ if isinstance(layer, (nn.Conv1d, nn.ConvTranspose1d)):
317
+ weight_scaling_init(layer)
318
+
319
+ def forward(self, noisy_audio):
320
+ # (B, L) -> (B, C, L)
321
+ if len(noisy_audio.shape) == 2:
322
+ noisy_audio = noisy_audio.unsqueeze(1)
323
+ B, C, L = noisy_audio.shape
324
+ assert C == 1
325
+
326
+ # normalization and padding
327
+ std = noisy_audio.std(dim=2, keepdim=True) + 1e-3
328
+ noisy_audio /= std
329
+ x = padding(noisy_audio, self.encoder_n_layers, self.kernel_size, self.stride)
330
+
331
+ # encoder
332
+ skip_connections = []
333
+ for downsampling_block in self.encoder:
334
+ x = downsampling_block(x)
335
+ skip_connections.append(x)
336
+ skip_connections = skip_connections[::-1]
337
+
338
+ # attention mask for causal inference; for non-causal, set attn_mask to None
339
+ len_s = x.shape[-1] # length at bottleneck
340
+ attn_mask = (1 - torch.triu(torch.ones((1, len_s, len_s), device=x.device), diagonal=1)).bool()
341
+
342
+ x = self.tsfm_conv1(x) # C 1024 -> 512
343
+ x = x.permute(0, 2, 1)
344
+ x = self.tsfm_encoder(x, src_mask=attn_mask)
345
+ x = x.permute(0, 2, 1)
346
+ x = self.tsfm_conv2(x) # C 512 -> 1024
347
+
348
+ # decoder
349
+ for i, upsampling_block in enumerate(self.decoder):
350
+ skip_i = skip_connections[i]
351
+ x += skip_i[:, :, :x.shape[-1]]
352
+ x = upsampling_block(x)
353
+
354
+ x = x[:, :, :L] * std
355
+ return x
356
+
357
+
358
+ if __name__ == '__main__':
359
+ import json
360
+ import argparse
361
+ import os
362
+
363
+ parser = argparse.ArgumentParser()
364
+ parser.add_argument('-c', '--config', type=str, default='configs/DNS-large-full.json',
365
+ help='JSON file for configuration')
366
+ args = parser.parse_args()
367
+
368
+ with open(args.config) as f:
369
+ data = f.read()
370
+ config = json.loads(data)
371
+ network_config = config["network_config"]
372
+
373
+ model = CleanUNet(**network_config).cuda()
374
+ from util import print_size
375
+ print_size(model, keyword="tsfm")
376
+
377
+ input_data = torch.ones([4,1,int(4.5*16000)]).cuda()
378
+ output = model(input_data)
379
+ print(output.shape)
380
+
381
+ y = torch.rand([4,1,int(4.5*16000)]).cuda()
382
+ loss = torch.nn.MSELoss()(y, output)
383
+ loss.backward()
384
+ print(loss.item())
385
+
src/utils.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import functools
4
+ import numpy as np
5
+ from math import cos, pi, floor, sin
6
+ from tqdm import tqdm
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+
12
+ # from stft_loss import MultiResolutionSTFTLoss
13
+
14
+
15
+ def flatten(v):
16
+ return [x for y in v for x in y]
17
+
18
+
19
+ def rescale(x):
20
+ return (x - x.min()) / (x.max() - x.min())
21
+
22
+
23
+ def find_max_epoch(path):
24
+ """
25
+ Find latest checkpoint
26
+
27
+ Returns:
28
+ maximum iteration, -1 if there is no (valid) checkpoint
29
+ """
30
+
31
+ files = os.listdir(path)
32
+ epoch = -1
33
+ for f in files:
34
+ if len(f) <= 4:
35
+ continue
36
+ if f[-4:] == '.pkl':
37
+ number = f[:-4]
38
+ try:
39
+ epoch = max(epoch, int(number))
40
+ except:
41
+ continue
42
+ return epoch
43
+
44
+
45
+ def print_size(net, keyword=None):
46
+ """
47
+ Print the number of parameters of a network
48
+ """
49
+
50
+ if net is not None and isinstance(net, torch.nn.Module):
51
+ module_parameters = filter(lambda p: p.requires_grad, net.parameters())
52
+ params = sum([np.prod(p.size()) for p in module_parameters])
53
+
54
+ print("{} Parameters: {:.6f}M".format(
55
+ net.__class__.__name__, params / 1e6), flush=True, end="; ")
56
+
57
+ if keyword is not None:
58
+ keyword_parameters = [p for name, p in net.named_parameters() if p.requires_grad and keyword in name]
59
+ params = sum([np.prod(p.size()) for p in keyword_parameters])
60
+ print("{} Parameters: {:.6f}M".format(
61
+ keyword, params / 1e6), flush=True, end="; ")
62
+
63
+ print(" ")
64
+
65
+
66
+ ####################### lr scheduler: Linear Warmup then Cosine Decay #############################
67
+
68
+ # Adapted from https://github.com/rosinality/vq-vae-2-pytorch
69
+
70
+ # Original Copyright 2019 Kim Seonghyeon
71
+ # MIT License (https://opensource.org/licenses/MIT)
72
+
73
+
74
+ def anneal_linear(start, end, proportion):
75
+ return start + proportion * (end - start)
76
+
77
+
78
+ def anneal_cosine(start, end, proportion):
79
+ cos_val = cos(pi * proportion) + 1
80
+ return end + (start - end) / 2 * cos_val
81
+
82
+
83
+ class Phase:
84
+ def __init__(self, start, end, n_iter, cur_iter, anneal_fn):
85
+ self.start, self.end = start, end
86
+ self.n_iter = n_iter
87
+ self.anneal_fn = anneal_fn
88
+ self.n = cur_iter
89
+
90
+ def step(self):
91
+ self.n += 1
92
+
93
+ return self.anneal_fn(self.start, self.end, self.n / self.n_iter)
94
+
95
+ def reset(self):
96
+ self.n = 0
97
+
98
+ @property
99
+ def is_done(self):
100
+ return self.n >= self.n_iter
101
+
102
+
103
+ class LinearWarmupCosineDecay:
104
+ def __init__(
105
+ self,
106
+ optimizer,
107
+ lr_max,
108
+ n_iter,
109
+ iteration=0,
110
+ divider=25,
111
+ warmup_proportion=0.3,
112
+ phase=('linear', 'cosine'),
113
+ ):
114
+ self.optimizer = optimizer
115
+
116
+ phase1 = int(n_iter * warmup_proportion)
117
+ phase2 = n_iter - phase1
118
+ lr_min = lr_max / divider
119
+
120
+ phase_map = {'linear': anneal_linear, 'cosine': anneal_cosine}
121
+
122
+ cur_iter_phase1 = iteration
123
+ cur_iter_phase2 = max(0, iteration - phase1)
124
+ self.lr_phase = [
125
+ Phase(lr_min, lr_max, phase1, cur_iter_phase1, phase_map[phase[0]]),
126
+ Phase(lr_max, lr_min / 1e4, phase2, cur_iter_phase2, phase_map[phase[1]]),
127
+ ]
128
+
129
+ if iteration < phase1:
130
+ self.phase = 0
131
+ else:
132
+ self.phase = 1
133
+
134
+ def step(self):
135
+ lr = self.lr_phase[self.phase].step()
136
+
137
+ for group in self.optimizer.param_groups:
138
+ group['lr'] = lr
139
+
140
+ if self.lr_phase[self.phase].is_done:
141
+ self.phase += 1
142
+
143
+ if self.phase >= len(self.lr_phase):
144
+ for phase in self.lr_phase:
145
+ phase.reset()
146
+
147
+ self.phase = 0
148
+
149
+ return lr
150
+
151
+
152
+ ####################### model util #############################
153
+
154
+ def std_normal(size):
155
+ """
156
+ Generate the standard Gaussian variable of a certain size
157
+ """
158
+
159
+ return torch.normal(0, 1, size=size).cuda()
160
+
161
+
162
+ def weight_scaling_init(layer):
163
+ """
164
+ weight rescaling initialization from https://arxiv.org/abs/1911.13254
165
+ """
166
+ w = layer.weight.detach()
167
+ alpha = 10.0 * w.std()
168
+ layer.weight.data /= torch.sqrt(alpha)
169
+ layer.bias.data /= torch.sqrt(alpha)
170
+
171
+
172
+ @torch.no_grad()
173
+ def sampling(net, noisy_audio):
174
+ """
175
+ Perform denoising (forward) step
176
+ """
177
+
178
+ return net(noisy_audio)
179
+
180
+
181
+ def loss_fn(net, X, ell_p, ell_p_lambda, stft_lambda, mrstftloss, **kwargs):
182
+ """
183
+ Loss function in CleanUNet
184
+
185
+ Parameters:
186
+ net: network
187
+ X: training data pair (clean audio, noisy_audio)
188
+ ell_p: \ell_p norm (1 or 2) of the AE loss
189
+ ell_p_lambda: factor of the AE loss
190
+ stft_lambda: factor of the STFT loss
191
+ mrstftloss: multi-resolution STFT loss function
192
+
193
+ Returns:
194
+ loss: value of objective function
195
+ output_dic: values of each component of loss
196
+ """
197
+
198
+ assert type(X) == tuple and len(X) == 2
199
+
200
+ clean_audio, noisy_audio = X
201
+ B, C, L = clean_audio.shape
202
+ output_dic = {}
203
+ loss = 0.0
204
+
205
+ # AE loss
206
+ denoised_audio = net(noisy_audio)
207
+
208
+ if ell_p == 2:
209
+ ae_loss = nn.MSELoss()(denoised_audio, clean_audio)
210
+ elif ell_p == 1:
211
+ ae_loss = F.l1_loss(denoised_audio, clean_audio)
212
+ else:
213
+ raise NotImplementedError
214
+ loss += ae_loss * ell_p_lambda
215
+ output_dic["reconstruct"] = ae_loss.data * ell_p_lambda
216
+
217
+ if stft_lambda > 0:
218
+ sc_loss, mag_loss = mrstftloss(denoised_audio.squeeze(1), clean_audio.squeeze(1))
219
+ loss += (sc_loss + mag_loss) * stft_lambda
220
+ output_dic["stft_sc"] = sc_loss.data * stft_lambda
221
+ output_dic["stft_mag"] = mag_loss.data * stft_lambda
222
+
223
+ return loss, output_dic