azamat commited on
Commit
33e3a91
1 Parent(s): 367349b
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 NVIDIA CORPORATION.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,4 +1,3 @@
1
- ---
2
  title: Nvidia Denoiser
3
  emoji: 🔥
4
  colorFrom: blue
@@ -7,7 +6,4 @@ sdk: gradio
7
  sdk_version: 3.23.0
8
  app_file: app.py
9
  pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
  title: Nvidia Denoiser
2
  emoji: 🔥
3
  colorFrom: blue
 
6
  sdk_version: 3.23.0
7
  app_file: app.py
8
  pinned: false
9
+ license: apache-2.0
 
 
 
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from tqdm import tqdm
4
+ from copy import deepcopy
5
+
6
+ import numpy as np
7
+ import gradio as gr
8
+ import torch
9
+
10
+ import random
11
+ random.seed(0)
12
+ torch.manual_seed(0)
13
+ np.random.seed(0)
14
+
15
+ from scipy.io.wavfile import write as wavwrite
16
+
17
+ from util import print_size, sampling
18
+ from network import CleanUNet
19
+ import torchaudio
20
+
21
+ def load_simple(filename):
22
+ audio, _ = torchaudio.load(filename)
23
+ return audio
24
+
25
+ CONFIG = "configs/DNS-large-full.json"
26
+ CHECKPOINT = "./exp/DNS-large-high/checkpoint/pretrained.pkl"
27
+
28
+ # Parse configs. Globals nicer in this case
29
+ with open(CONFIG) as f:
30
+ data = f.read()
31
+ config = json.loads(data)
32
+ gen_config = config["gen_config"]
33
+ global network_config
34
+ network_config = config["network_config"] # to define wavenet
35
+ global train_config
36
+ train_config = config["train_config"] # train config
37
+ global trainset_config
38
+ trainset_config = config["trainset_config"] # to read trainset configurations
39
+
40
+ def denoise(files, ckpt_path):
41
+ """
42
+ Denoise audio
43
+ Parameters:
44
+ output_directory (str): save generated speeches to this path
45
+ ckpt_iter (int or 'max'): the pretrained checkpoint to be loaded;
46
+ automitically selects the maximum iteration if 'max' is selected
47
+ subset (str): training, testing, validation
48
+ dump (bool): whether save enhanced (denoised) audio
49
+ """
50
+
51
+ # setup local experiment path
52
+ exp_path = train_config["exp_path"]
53
+ print('exp_path:', exp_path)
54
+
55
+ # load data
56
+ loader_config = deepcopy(trainset_config)
57
+ loader_config["crop_length_sec"] = 0
58
+
59
+ # predefine model
60
+ net = CleanUNet(**network_config)
61
+ print_size(net)
62
+
63
+ # load checkpoint
64
+ checkpoint = torch.load(ckpt_path, map_location='cpu')
65
+ net.load_state_dict(checkpoint['model_state_dict'])
66
+ net.eval()
67
+
68
+ # inference
69
+ batch_size = 1000000
70
+ for file_path in tqdm(files):
71
+ file_name = os.path.basename(file_path)
72
+ file_dir = os.path.dirname(file_name)
73
+ new_file_name = file_name + "_denoised.wav"
74
+ noisy_audio = load_simple(file_path)
75
+ LENGTH = len(noisy_audio[0].squeeze())
76
+ noisy_audio = torch.chunk(noisy_audio, LENGTH // batch_size + 1, dim=1)
77
+ all_audio = []
78
+
79
+ for batch in tqdm(noisy_audio):
80
+ with torch.no_grad():
81
+ generated_audio = sampling(net, batch)
82
+ generated_audio = generated_audio.cpu().numpy().squeeze()
83
+ all_audio.append(generated_audio)
84
+
85
+ all_audio = np.concatenate(all_audio, axis=0)
86
+ save_file = os.path.join(file_dir, new_file_name)
87
+ print("saved to:", save_file)
88
+ wavwrite(save_file, 32000, all_audio.squeeze())
89
+
90
+
91
+ audio = gr.inputs.Audio(label = "Audio to denoise", type = 'filepath')
92
+ inputs = [audio, CHECKPOINT]
93
+ outputs = gr.outputs.Audio(label = "Denoised audio", type = 'filepath')
94
+
95
+ title = "Speech Denoising in the Waveform Domain with Self-Attention from Nvidia"
96
+
97
+ gr.Interface(denoise, inputs, outputs, title=title, enable_queue=True).launch()
configs/DNS-large-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/DNS-large-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
+ }
dataset.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2022 NVIDIA CORPORATION.
2
+ # Licensed under the MIT license.
3
+
4
+ import os
5
+ import numpy as np
6
+
7
+ from scipy.io.wavfile import read as wavread
8
+ import warnings
9
+ warnings.filterwarnings("ignore")
10
+
11
+ import torch
12
+ from torch.utils.data import Dataset
13
+ from torch.utils.data.distributed import DistributedSampler
14
+
15
+ import random
16
+ random.seed(0)
17
+ torch.manual_seed(0)
18
+ np.random.seed(0)
19
+
20
+ from torchvision import datasets, models, transforms
21
+ import torchaudio
22
+
23
+
24
+ class CleanNoisyPairDataset(Dataset):
25
+ """
26
+ Create a Dataset of clean and noisy audio pairs.
27
+ Each element is a tuple of the form (clean waveform, noisy waveform, file_id)
28
+ """
29
+
30
+ def __init__(self, root='./', subset='training', crop_length_sec=0):
31
+ super(CleanNoisyPairDataset).__init__()
32
+
33
+ assert subset is None or subset in ["training", "testing"]
34
+ self.crop_length_sec = crop_length_sec
35
+ self.subset = subset
36
+
37
+ N_clean = len(os.listdir(os.path.join(root, 'training_set/clean')))
38
+ N_noisy = len(os.listdir(os.path.join(root, 'training_set/noisy')))
39
+ assert N_clean == N_noisy
40
+
41
+ if subset == "training":
42
+ self.files = [(os.path.join(root, 'training_set/clean', 'fileid_{}.wav'.format(i)),
43
+ os.path.join(root, 'training_set/noisy', 'fileid_{}.wav'.format(i))) for i in range(N_clean)]
44
+
45
+ elif subset == "testing":
46
+ sortkey = lambda name: '_'.join(name.split('_')[-2:]) # specific for dns due to test sample names
47
+ _p = os.path.join(root, 'datasets/test_set/synthetic/no_reverb') # path for DNS
48
+
49
+ clean_files = os.listdir(os.path.join(_p, 'clean'))
50
+ noisy_files = os.listdir(os.path.join(_p, 'noisy'))
51
+
52
+ clean_files.sort(key=sortkey)
53
+ noisy_files.sort(key=sortkey)
54
+
55
+ self.files = []
56
+ for _c, _n in zip(clean_files, noisy_files):
57
+ assert sortkey(_c) == sortkey(_n)
58
+ self.files.append((os.path.join(_p, 'clean', _c),
59
+ os.path.join(_p, 'noisy', _n)))
60
+ self.crop_length_sec = 0
61
+
62
+ else:
63
+ raise NotImplementedError
64
+
65
+ def __getitem__(self, n):
66
+ fileid = self.files[n]
67
+ clean_audio, sample_rate = torchaudio.load(fileid[0])
68
+ noisy_audio, sample_rate = torchaudio.load(fileid[1])
69
+ clean_audio, noisy_audio = clean_audio.squeeze(0), noisy_audio.squeeze(0)
70
+ assert len(clean_audio) == len(noisy_audio)
71
+
72
+ crop_length = int(self.crop_length_sec * sample_rate)
73
+ assert crop_length < len(clean_audio)
74
+
75
+ # random crop
76
+ if self.subset != 'testing' and crop_length > 0:
77
+ start = np.random.randint(low=0, high=len(clean_audio) - crop_length + 1)
78
+ clean_audio = clean_audio[start:(start + crop_length)]
79
+ noisy_audio = noisy_audio[start:(start + crop_length)]
80
+
81
+ clean_audio, noisy_audio = clean_audio.unsqueeze(0), noisy_audio.unsqueeze(0)
82
+ return (clean_audio, noisy_audio, fileid)
83
+
84
+ def __len__(self):
85
+ return len(self.files)
86
+
87
+
88
+ def load_CleanNoisyPairDataset(root, subset, crop_length_sec, batch_size, sample_rate, num_gpus=1):
89
+ """
90
+ Get dataloader with distributed sampling
91
+ """
92
+ dataset = CleanNoisyPairDataset(root=root, subset=subset, crop_length_sec=crop_length_sec)
93
+ kwargs = {"batch_size": batch_size, "num_workers": 4, "pin_memory": False, "drop_last": False}
94
+
95
+ if num_gpus > 1:
96
+ train_sampler = DistributedSampler(dataset)
97
+ dataloader = torch.utils.data.DataLoader(dataset, sampler=train_sampler, **kwargs)
98
+ else:
99
+ dataloader = torch.utils.data.DataLoader(dataset, sampler=None, shuffle=True, **kwargs)
100
+
101
+ return dataloader
102
+
103
+
104
+ if __name__ == '__main__':
105
+ import json
106
+ with open('./configs/DNS-large-full.json') as f:
107
+ data = f.read()
108
+ config = json.loads(data)
109
+ trainset_config = config["trainset_config"]
110
+
111
+ trainloader = load_CleanNoisyPairDataset(**trainset_config, subset='training', batch_size=2, num_gpus=1)
112
+ testloader = load_CleanNoisyPairDataset(**trainset_config, subset='testing', batch_size=2, num_gpus=1)
113
+ print(len(trainloader), len(testloader))
114
+
115
+ for clean_audio, noisy_audio, fileid in trainloader:
116
+ clean_audio = clean_audio.cuda()
117
+ noisy_audio = noisy_audio.cuda()
118
+ print(clean_audio.shape, noisy_audio.shape, fileid)
119
+ break
120
+
denoise.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import json
4
+ from tqdm import tqdm
5
+ from copy import deepcopy
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ import random
11
+ random.seed(0)
12
+ torch.manual_seed(0)
13
+ np.random.seed(0)
14
+
15
+ from scipy.io.wavfile import write as wavwrite
16
+
17
+ from dataset import load_CleanNoisyPairDataset
18
+ from util import find_max_epoch, print_size, sampling
19
+ from network import CleanUNet
20
+
21
+
22
+ def denoise(output_directory, ckpt_iter, subset, dump=False):
23
+ """
24
+ Denoise audio
25
+
26
+ Parameters:
27
+ output_directory (str): save generated speeches to this path
28
+ ckpt_iter (int or 'max'): the pretrained checkpoint to be loaded;
29
+ automitically selects the maximum iteration if 'max' is selected
30
+ subset (str): training, testing, validation
31
+ dump (bool): whether save enhanced (denoised) audio
32
+ """
33
+
34
+ # setup local experiment path
35
+ exp_path = train_config["exp_path"]
36
+ print('exp_path:', exp_path)
37
+
38
+ # load data
39
+ loader_config = deepcopy(trainset_config)
40
+ loader_config["crop_length_sec"] = 0
41
+ dataloader = load_CleanNoisyPairDataset(
42
+ **loader_config,
43
+ subset=subset,
44
+ batch_size=1,
45
+ num_gpus=1
46
+ )
47
+
48
+ # predefine model
49
+ net = CleanUNet(**network_config).cuda()
50
+ print_size(net)
51
+
52
+ # load checkpoint
53
+ ckpt_directory = os.path.join(train_config["log"]["directory"], exp_path, 'checkpoint')
54
+ if ckpt_iter == 'max':
55
+ ckpt_iter = find_max_epoch(ckpt_directory)
56
+ if ckpt_iter != 'pretrained':
57
+ ckpt_iter = int(ckpt_iter)
58
+ model_path = os.path.join(ckpt_directory, '{}.pkl'.format(ckpt_iter))
59
+ checkpoint = torch.load(model_path, map_location='cpu')
60
+ net.load_state_dict(checkpoint['model_state_dict'])
61
+ net.eval()
62
+
63
+ # get output directory ready
64
+ if ckpt_iter == "pretrained":
65
+ speech_directory = os.path.join(output_directory, exp_path, 'speech', ckpt_iter)
66
+ else:
67
+ speech_directory = os.path.join(output_directory, exp_path, 'speech', '{}k'.format(ckpt_iter//1000))
68
+ if dump and not os.path.isdir(speech_directory):
69
+ os.makedirs(speech_directory)
70
+ os.chmod(speech_directory, 0o775)
71
+ print("speech_directory: ", speech_directory, flush=True)
72
+
73
+ # inference
74
+ all_generated_audio = []
75
+ all_clean_audio = []
76
+ sortkey = lambda name: '_'.join(name.split('/')[-1].split('_')[1:])
77
+ for clean_audio, noisy_audio, fileid in tqdm(dataloader):
78
+ filename = sortkey(fileid[0][0])
79
+
80
+ noisy_audio = noisy_audio.cuda()
81
+ LENGTH = len(noisy_audio[0].squeeze())
82
+ generated_audio = sampling(net, noisy_audio)
83
+
84
+ if dump:
85
+ wavwrite(os.path.join(speech_directory, 'enhanced_{}'.format(filename)),
86
+ trainset_config["sample_rate"],
87
+ generated_audio[0].squeeze().cpu().numpy())
88
+ else:
89
+ all_clean_audio.append(clean_audio[0].squeeze().cpu().numpy())
90
+ all_generated_audio.append(generated_audio[0].squeeze().cpu().numpy())
91
+
92
+ return all_clean_audio, all_generated_audio
93
+
94
+
95
+ if __name__ == "__main__":
96
+ parser = argparse.ArgumentParser()
97
+ parser.add_argument('-c', '--config', type=str, default='config.json',
98
+ help='JSON file for configuration')
99
+ parser.add_argument('-ckpt_iter', '--ckpt_iter', default='max',
100
+ help='Which checkpoint to use; assign a number or "max" or "pretrained"')
101
+ parser.add_argument('-subset', '--subset', type=str, choices=['training', 'testing', 'validation'],
102
+ default='testing', help='subset for denoising')
103
+ args = parser.parse_args()
104
+
105
+ # Parse configs. Globals nicer in this case
106
+ with open(args.config) as f:
107
+ data = f.read()
108
+ config = json.loads(data)
109
+ gen_config = config["gen_config"]
110
+ global network_config
111
+ network_config = config["network_config"] # to define wavenet
112
+ global train_config
113
+ train_config = config["train_config"] # train config
114
+ global trainset_config
115
+ trainset_config = config["trainset_config"] # to read trainset configurations
116
+
117
+ torch.backends.cudnn.enabled = True
118
+ torch.backends.cudnn.benchmark = True
119
+
120
+ if args.subset == "testing":
121
+ denoise(gen_config["output_directory"],
122
+ subset=args.subset,
123
+ ckpt_iter=args.ckpt_iter,
124
+ dump=True)
exp/DNS-large-full/checkpoint/pretrained.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:145c101eb5bbfa3ba52fb2b4ec7e5b64a361c102f89291f75e1dd42601d95dc9
3
+ size 184336765
exp/DNS-large-high/checkpoint/pretrained.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:513d9e4f69483bf2bcc3059dd6b3644140763bf3f22df41d7ee366cc2cbd1829
3
+ size 184336765
network.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 util 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
+ _MASKING_VALUE = -1e9 if attn.dtype == torch.float32 else -1e4
31
+ attn = attn.masked_fill(mask == 0, _MASKING_VALUE)
32
+
33
+ attn = self.dropout(F.softmax(attn, dim=-1))
34
+ output = torch.matmul(attn, v)
35
+
36
+ return output, attn
37
+
38
+
39
+ class MultiHeadAttention(nn.Module):
40
+ ''' Multi-Head Attention module '''
41
+
42
+ def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
43
+ super().__init__()
44
+
45
+ self.n_head = n_head
46
+ self.d_k = d_k
47
+ self.d_v = d_v
48
+
49
+ self.w_qs = nn.Linear(d_model, n_head * d_k, bias=False)
50
+ self.w_ks = nn.Linear(d_model, n_head * d_k, bias=False)
51
+ self.w_vs = nn.Linear(d_model, n_head * d_v, bias=False)
52
+ self.fc = nn.Linear(n_head * d_v, d_model, bias=False)
53
+
54
+ self.attention = ScaledDotProductAttention(temperature=d_k ** 0.5)
55
+
56
+ self.dropout = nn.Dropout(dropout)
57
+ self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
58
+
59
+
60
+ def forward(self, q, k, v, mask=None):
61
+
62
+ d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
63
+ sz_b, len_q, len_k, len_v = q.size(0), q.size(1), k.size(1), v.size(1)
64
+
65
+ residual = q
66
+
67
+ # Pass through the pre-attention projection: b x lq x (n*dv)
68
+ # Separate different heads: b x lq x n x dv
69
+ q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
70
+ k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
71
+ v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
72
+
73
+ # Transpose for attention dot product: b x n x lq x dv
74
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
75
+
76
+ if mask is not None:
77
+ mask = mask.unsqueeze(1) # For head axis broadcasting.
78
+
79
+ q, attn = self.attention(q, k, v, mask=mask)
80
+
81
+ # Transpose to move the head dimension back: b x lq x n x dv
82
+ # Combine the last two dimensions to concatenate all the heads together: b x lq x (n*dv)
83
+ q = q.transpose(1, 2).contiguous().view(sz_b, len_q, -1)
84
+ q = self.dropout(self.fc(q))
85
+ q += residual
86
+
87
+ q = self.layer_norm(q)
88
+
89
+ return q, attn
90
+
91
+
92
+ class PositionwiseFeedForward(nn.Module):
93
+ ''' A two-feed-forward-layer module '''
94
+
95
+ def __init__(self, d_in, d_hid, dropout=0.1):
96
+ super().__init__()
97
+ self.w_1 = nn.Linear(d_in, d_hid) # position-wise
98
+ self.w_2 = nn.Linear(d_hid, d_in) # position-wise
99
+ self.layer_norm = nn.LayerNorm(d_in, eps=1e-6)
100
+ self.dropout = nn.Dropout(dropout)
101
+
102
+ def forward(self, x):
103
+
104
+ residual = x
105
+
106
+ x = self.w_2(F.relu(self.w_1(x)))
107
+ x = self.dropout(x)
108
+ x += residual
109
+
110
+ x = self.layer_norm(x)
111
+
112
+ return x
113
+
114
+
115
+ def get_subsequent_mask(seq):
116
+ ''' For masking out the subsequent info. '''
117
+ sz_b, len_s = seq.size()
118
+ subsequent_mask = (1 - torch.triu(
119
+ torch.ones((1, len_s, len_s), device=seq.device), diagonal=1)).bool()
120
+ return subsequent_mask
121
+
122
+
123
+ class PositionalEncoding(nn.Module):
124
+
125
+ def __init__(self, d_hid, n_position=200):
126
+ super(PositionalEncoding, self).__init__()
127
+
128
+ # Not a parameter
129
+ self.register_buffer('pos_table', self._get_sinusoid_encoding_table(n_position, d_hid))
130
+
131
+ def _get_sinusoid_encoding_table(self, n_position, d_hid):
132
+ ''' Sinusoid position encoding table '''
133
+ # TODO: make it with torch instead of numpy
134
+
135
+ def get_position_angle_vec(position):
136
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
137
+
138
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
139
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
140
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
141
+
142
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
143
+
144
+ def forward(self, x):
145
+ return x + self.pos_table[:, :x.size(1)].clone().detach()
146
+
147
+
148
+ class EncoderLayer(nn.Module):
149
+ ''' Compose with two layers '''
150
+
151
+ def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.0):
152
+ super(EncoderLayer, self).__init__()
153
+ self.slf_attn = MultiHeadAttention(n_head, d_model, d_k, d_v, dropout=dropout)
154
+ self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout)
155
+
156
+ def forward(self, enc_input, slf_attn_mask=None):
157
+ enc_output, enc_slf_attn = self.slf_attn(
158
+ enc_input, enc_input, enc_input, mask=slf_attn_mask)
159
+ enc_output = self.pos_ffn(enc_output)
160
+ return enc_output, enc_slf_attn
161
+
162
+
163
+ class TransformerEncoder(nn.Module):
164
+ ''' A encoder model with self attention mechanism. '''
165
+
166
+ def __init__(
167
+ self, d_word_vec=512, n_layers=2, n_head=8, d_k=64, d_v=64,
168
+ d_model=512, d_inner=2048, dropout=0.1, n_position=624, scale_emb=False):
169
+
170
+ super().__init__()
171
+
172
+ # self.src_word_emb = nn.Embedding(n_src_vocab, d_word_vec, padding_idx=pad_idx)
173
+ if n_position > 0:
174
+ self.position_enc = PositionalEncoding(d_word_vec, n_position=n_position)
175
+ else:
176
+ self.position_enc = lambda x: x
177
+ self.dropout = nn.Dropout(p=dropout)
178
+ self.layer_stack = nn.ModuleList([
179
+ EncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout)
180
+ for _ in range(n_layers)])
181
+ self.layer_norm = nn.LayerNorm(d_model, eps=1e-6)
182
+ self.scale_emb = scale_emb
183
+ self.d_model = d_model
184
+
185
+ def forward(self, src_seq, src_mask, return_attns=False):
186
+
187
+ enc_slf_attn_list = []
188
+
189
+ # -- Forward
190
+ # enc_output = self.src_word_emb(src_seq)
191
+ enc_output = src_seq
192
+ if self.scale_emb:
193
+ enc_output *= self.d_model ** 0.5
194
+ enc_output = self.dropout(self.position_enc(enc_output))
195
+ enc_output = self.layer_norm(enc_output)
196
+
197
+ for enc_layer in self.layer_stack:
198
+ enc_output, enc_slf_attn = enc_layer(enc_output, slf_attn_mask=src_mask)
199
+ enc_slf_attn_list += [enc_slf_attn] if return_attns else []
200
+
201
+ if return_attns:
202
+ return enc_output, enc_slf_attn_list
203
+ return enc_output
204
+
205
+
206
+ # CleanUNet architecture
207
+
208
+
209
+ def padding(x, D, K, S):
210
+ """padding zeroes to x so that denoised audio has the same length"""
211
+
212
+ L = x.shape[-1]
213
+ for _ in range(D):
214
+ if L < K:
215
+ L = 1
216
+ else:
217
+ L = 1 + np.ceil((L - K) / S)
218
+
219
+ for _ in range(D):
220
+ L = (L - 1) * S + K
221
+
222
+ L = int(L)
223
+ x = F.pad(x, (0, L - x.shape[-1]))
224
+ return x
225
+
226
+
227
+ class CleanUNet(nn.Module):
228
+ """ CleanUNet architecture. """
229
+
230
+ def __init__(self, channels_input=1, channels_output=1,
231
+ channels_H=64, max_H=768,
232
+ encoder_n_layers=8, kernel_size=4, stride=2,
233
+ tsfm_n_layers=3,
234
+ tsfm_n_head=8,
235
+ tsfm_d_model=512,
236
+ tsfm_d_inner=2048):
237
+
238
+ """
239
+ Parameters:
240
+ channels_input (int): input channels
241
+ channels_output (int): output channels
242
+ channels_H (int): middle channels H that controls capacity
243
+ max_H (int): maximum H
244
+ encoder_n_layers (int): number of encoder/decoder layers D
245
+ kernel_size (int): kernel size K
246
+ stride (int): stride S
247
+ tsfm_n_layers (int): number of self attention blocks N
248
+ tsfm_n_head (int): number of heads in each self attention block
249
+ tsfm_d_model (int): d_model of self attention
250
+ tsfm_d_inner (int): d_inner of self attention
251
+ """
252
+
253
+ super(CleanUNet, self).__init__()
254
+
255
+ self.channels_input = channels_input
256
+ self.channels_output = channels_output
257
+ self.channels_H = channels_H
258
+ self.max_H = max_H
259
+ self.encoder_n_layers = encoder_n_layers
260
+ self.kernel_size = kernel_size
261
+ self.stride = stride
262
+
263
+ self.tsfm_n_layers = tsfm_n_layers
264
+ self.tsfm_n_head = tsfm_n_head
265
+ self.tsfm_d_model = tsfm_d_model
266
+ self.tsfm_d_inner = tsfm_d_inner
267
+
268
+ # encoder and decoder
269
+ self.encoder = nn.ModuleList()
270
+ self.decoder = nn.ModuleList()
271
+
272
+ for i in range(encoder_n_layers):
273
+ self.encoder.append(nn.Sequential(
274
+ nn.Conv1d(channels_input, channels_H, kernel_size, stride),
275
+ nn.ReLU(),
276
+ nn.Conv1d(channels_H, channels_H * 2, 1),
277
+ nn.GLU(dim=1)
278
+ ))
279
+ channels_input = channels_H
280
+
281
+ if i == 0:
282
+ # no relu at end
283
+ self.decoder.append(nn.Sequential(
284
+ nn.Conv1d(channels_H, channels_H * 2, 1),
285
+ nn.GLU(dim=1),
286
+ nn.ConvTranspose1d(channels_H, channels_output, kernel_size, stride)
287
+ ))
288
+ else:
289
+ self.decoder.insert(0, nn.Sequential(
290
+ nn.Conv1d(channels_H, channels_H * 2, 1),
291
+ nn.GLU(dim=1),
292
+ nn.ConvTranspose1d(channels_H, channels_output, kernel_size, stride),
293
+ nn.ReLU()
294
+ ))
295
+ channels_output = channels_H
296
+
297
+ # double H but keep below max_H
298
+ channels_H *= 2
299
+ channels_H = min(channels_H, max_H)
300
+
301
+ # self attention block
302
+ self.tsfm_conv1 = nn.Conv1d(channels_output, tsfm_d_model, kernel_size=1)
303
+ self.tsfm_encoder = TransformerEncoder(d_word_vec=tsfm_d_model,
304
+ n_layers=tsfm_n_layers,
305
+ n_head=tsfm_n_head,
306
+ d_k=tsfm_d_model // tsfm_n_head,
307
+ d_v=tsfm_d_model // tsfm_n_head,
308
+ d_model=tsfm_d_model,
309
+ d_inner=tsfm_d_inner,
310
+ dropout=0.0,
311
+ n_position=0,
312
+ scale_emb=False)
313
+ self.tsfm_conv2 = nn.Conv1d(tsfm_d_model, channels_output, kernel_size=1)
314
+
315
+ # weight scaling initialization
316
+ for layer in self.modules():
317
+ if isinstance(layer, (nn.Conv1d, nn.ConvTranspose1d)):
318
+ weight_scaling_init(layer)
319
+
320
+ def forward(self, noisy_audio):
321
+ # (B, L) -> (B, C, L)
322
+ if len(noisy_audio.shape) == 2:
323
+ noisy_audio = noisy_audio.unsqueeze(1)
324
+ B, C, L = noisy_audio.shape
325
+ assert C == 1
326
+
327
+ # normalization and padding
328
+ std = noisy_audio.std(dim=2, keepdim=True) + 1e-3
329
+ noisy_audio /= std
330
+ x = padding(noisy_audio, self.encoder_n_layers, self.kernel_size, self.stride)
331
+
332
+ # encoder
333
+ skip_connections = []
334
+ for downsampling_block in self.encoder:
335
+ x = downsampling_block(x)
336
+ skip_connections.append(x)
337
+ skip_connections = skip_connections[::-1]
338
+
339
+ # attention mask for causal inference; for non-causal, set attn_mask to None
340
+ len_s = x.shape[-1] # length at bottleneck
341
+ attn_mask = (1 - torch.triu(torch.ones((1, len_s, len_s), device=x.device), diagonal=1)).bool()
342
+
343
+ x = self.tsfm_conv1(x) # C 1024 -> 512
344
+ x = x.permute(0, 2, 1)
345
+ x = self.tsfm_encoder(x, src_mask=attn_mask)
346
+ x = x.permute(0, 2, 1)
347
+ x = self.tsfm_conv2(x) # C 512 -> 1024
348
+
349
+ # decoder
350
+ for i, upsampling_block in enumerate(self.decoder):
351
+ skip_i = skip_connections[i]
352
+ x += skip_i[:, :, :x.shape[-1]]
353
+ x = upsampling_block(x)
354
+
355
+ x = x[:, :, :L] * std
356
+ return x
357
+
358
+
359
+ if __name__ == '__main__':
360
+ import json
361
+ import argparse
362
+ import os
363
+
364
+ parser = argparse.ArgumentParser()
365
+ parser.add_argument('-c', '--config', type=str, default='configs/DNS-large-full.json',
366
+ help='JSON file for configuration')
367
+ args = parser.parse_args()
368
+
369
+ with open(args.config) as f:
370
+ data = f.read()
371
+ config = json.loads(data)
372
+ network_config = config["network_config"]
373
+
374
+ model = CleanUNet(**network_config).cuda()
375
+ from util import print_size
376
+ print_size(model, keyword="tsfm")
377
+
378
+ input_data = torch.ones([4,1,int(4.5*16000)]).cuda()
379
+ output = model(input_data)
380
+ print(output.shape)
381
+
382
+ y = torch.rand([4,1,int(4.5*16000)]).cuda()
383
+ loss = torch.nn.MSELoss()(y, output)
384
+ loss.backward()
385
+ print(loss.item())
386
+
requirements.txt ADDED
File without changes
util.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
224
+