HoneyTian commited on
Commit
c5cffc6
·
1 Parent(s): 7ec71f8
examples/spectrum_dfnet_aishell/run.sh ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ : <<'END'
4
+
5
+
6
+ sh run.sh --stage 2 --stop_stage 2 --system_version windows --file_folder_name file_dir \
7
+ --noise_dir "E:/Users/tianx/HuggingDatasets/nx_noise/data/noise" \
8
+ --speech_dir "E:/programmer/asr_datasets/aishell/data_aishell/wav/train"
9
+
10
+
11
+ sh run.sh --stage 1 --stop_stage 3 --system_version centos --file_folder_name file_dir \
12
+ --noise_dir "/data/tianxing/HuggingDatasets/nx_noise/data/noise" \
13
+ --speech_dir "/data/tianxing/HuggingDatasets/aishell/data_aishell/wav/train"
14
+
15
+ sh run.sh --stage 3 --stop_stage 3 --system_version centos --file_folder_name file_dir \
16
+ --noise_dir "/data/tianxing/HuggingDatasets/nx_noise/data/noise" \
17
+ --speech_dir "/data/tianxing/HuggingDatasets/aishell/data_aishell/wav/train"
18
+
19
+
20
+ END
21
+
22
+
23
+ # params
24
+ system_version="windows";
25
+ verbose=true;
26
+ stage=0 # start from 0 if you need to start from data preparation
27
+ stop_stage=9
28
+
29
+ work_dir="$(pwd)"
30
+ file_folder_name=file_folder_name
31
+ final_model_name=final_model_name
32
+ config_file="yaml/config.yaml"
33
+ limit=10
34
+
35
+ noise_dir=/data/tianxing/HuggingDatasets/nx_noise/data/noise
36
+ speech_dir=/data/tianxing/HuggingDatasets/aishell/data_aishell/wav/train
37
+
38
+ nohup_name=nohup.out
39
+
40
+ # model params
41
+ batch_size=64
42
+ max_epochs=200
43
+ save_top_k=10
44
+ patience=5
45
+
46
+
47
+ # parse options
48
+ while true; do
49
+ [ -z "${1:-}" ] && break; # break if there are no arguments
50
+ case "$1" in
51
+ --*) name=$(echo "$1" | sed s/^--// | sed s/-/_/g);
52
+ eval '[ -z "${'"$name"'+xxx}" ]' && echo "$0: invalid option $1" 1>&2 && exit 1;
53
+ old_value="(eval echo \\$$name)";
54
+ if [ "${old_value}" == "true" ] || [ "${old_value}" == "false" ]; then
55
+ was_bool=true;
56
+ else
57
+ was_bool=false;
58
+ fi
59
+
60
+ # Set the variable to the right value-- the escaped quotes make it work if
61
+ # the option had spaces, like --cmd "queue.pl -sync y"
62
+ eval "${name}=\"$2\"";
63
+
64
+ # Check that Boolean-valued arguments are really Boolean.
65
+ if $was_bool && [[ "$2" != "true" && "$2" != "false" ]]; then
66
+ echo "$0: expected \"true\" or \"false\": $1 $2" 1>&2
67
+ exit 1;
68
+ fi
69
+ shift 2;
70
+ ;;
71
+
72
+ *) break;
73
+ esac
74
+ done
75
+
76
+ file_dir="${work_dir}/${file_folder_name}"
77
+ final_model_dir="${work_dir}/../../trained_models/${final_model_name}";
78
+ evaluation_audio_dir="${file_dir}/evaluation_audio"
79
+
80
+ dataset="${file_dir}/dataset.xlsx"
81
+ train_dataset="${file_dir}/train.xlsx"
82
+ valid_dataset="${file_dir}/valid.xlsx"
83
+
84
+ $verbose && echo "system_version: ${system_version}"
85
+ $verbose && echo "file_folder_name: ${file_folder_name}"
86
+
87
+ if [ $system_version == "windows" ]; then
88
+ alias python3='D:/Users/tianx/PycharmProjects/virtualenv/nx_denoise/Scripts/python.exe'
89
+ elif [ $system_version == "centos" ] || [ $system_version == "ubuntu" ]; then
90
+ #source /data/local/bin/nx_denoise/bin/activate
91
+ alias python3='/data/local/bin/nx_denoise/bin/python3'
92
+ fi
93
+
94
+
95
+ if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then
96
+ $verbose && echo "stage 1: prepare data"
97
+ cd "${work_dir}" || exit 1
98
+ python3 step_1_prepare_data.py \
99
+ --file_dir "${file_dir}" \
100
+ --noise_dir "${noise_dir}" \
101
+ --speech_dir "${speech_dir}" \
102
+ --train_dataset "${train_dataset}" \
103
+ --valid_dataset "${valid_dataset}" \
104
+
105
+ fi
106
+
107
+
108
+ if [ ${stage} -le 2 ] && [ ${stop_stage} -ge 2 ]; then
109
+ $verbose && echo "stage 2: train model"
110
+ cd "${work_dir}" || exit 1
111
+ python3 step_2_train_model.py \
112
+ --train_dataset "${train_dataset}" \
113
+ --valid_dataset "${valid_dataset}" \
114
+ --serialization_dir "${file_dir}" \
115
+ --config_file "${config_file}" \
116
+
117
+ fi
118
+
119
+
120
+ if [ ${stage} -le 3 ] && [ ${stop_stage} -ge 3 ]; then
121
+ $verbose && echo "stage 3: test model"
122
+ cd "${work_dir}" || exit 1
123
+ python3 step_3_evaluation.py \
124
+ --valid_dataset "${valid_dataset}" \
125
+ --model_dir "${file_dir}/best" \
126
+ --evaluation_audio_dir "${evaluation_audio_dir}" \
127
+ --limit "${limit}" \
128
+
129
+ fi
130
+
131
+
132
+ if [ ${stage} -le 4 ] && [ ${stop_stage} -ge 4 ]; then
133
+ $verbose && echo "stage 4: export model"
134
+ cd "${work_dir}" || exit 1
135
+ python3 step_5_export_models.py \
136
+ --vocabulary_dir "${vocabulary_dir}" \
137
+ --model_dir "${file_dir}/best" \
138
+ --serialization_dir "${file_dir}" \
139
+
140
+ fi
141
+
142
+
143
+ if [ ${stage} -le 5 ] && [ ${stop_stage} -ge 5 ]; then
144
+ $verbose && echo "stage 5: collect files"
145
+ cd "${work_dir}" || exit 1
146
+
147
+ mkdir -p ${final_model_dir}
148
+
149
+ cp "${file_dir}/best"/* "${final_model_dir}"
150
+ cp -r "${file_dir}/vocabulary" "${final_model_dir}"
151
+
152
+ cp "${file_dir}/evaluation.xlsx" "${final_model_dir}/evaluation.xlsx"
153
+
154
+ cp "${file_dir}/trace_model.zip" "${final_model_dir}/trace_model.zip"
155
+ cp "${file_dir}/trace_quant_model.zip" "${final_model_dir}/trace_quant_model.zip"
156
+ cp "${file_dir}/script_model.zip" "${final_model_dir}/script_model.zip"
157
+ cp "${file_dir}/script_quant_model.zip" "${final_model_dir}/script_quant_model.zip"
158
+
159
+ cd "${final_model_dir}/.." || exit 1;
160
+
161
+ if [ -e "${final_model_name}.zip" ]; then
162
+ rm -rf "${final_model_name}_backup.zip"
163
+ mv "${final_model_name}.zip" "${final_model_name}_backup.zip"
164
+ fi
165
+
166
+ zip -r "${final_model_name}.zip" "${final_model_name}"
167
+ rm -rf "${final_model_name}"
168
+
169
+ fi
170
+
171
+
172
+ if [ ${stage} -le 6 ] && [ ${stop_stage} -ge 6 ]; then
173
+ $verbose && echo "stage 6: clear file_dir"
174
+ cd "${work_dir}" || exit 1
175
+
176
+ rm -rf "${file_dir}";
177
+
178
+ fi
examples/spectrum_dfnet_aishell/step_1_prepare_data.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+ import random
7
+ import sys
8
+ import shutil
9
+
10
+ pwd = os.path.abspath(os.path.dirname(__file__))
11
+ sys.path.append(os.path.join(pwd, "../../"))
12
+
13
+ import pandas as pd
14
+ from scipy.io import wavfile
15
+ from tqdm import tqdm
16
+ import librosa
17
+
18
+ from project_settings import project_path
19
+
20
+
21
+ def get_args():
22
+ parser = argparse.ArgumentParser()
23
+ parser.add_argument("--file_dir", default="./", type=str)
24
+
25
+ parser.add_argument(
26
+ "--noise_dir",
27
+ default=r"E:\Users\tianx\HuggingDatasets\nx_noise\data\noise",
28
+ type=str
29
+ )
30
+ parser.add_argument(
31
+ "--speech_dir",
32
+ default=r"E:\programmer\asr_datasets\aishell\data_aishell\wav\train",
33
+ type=str
34
+ )
35
+
36
+ parser.add_argument("--train_dataset", default="train.xlsx", type=str)
37
+ parser.add_argument("--valid_dataset", default="valid.xlsx", type=str)
38
+
39
+ parser.add_argument("--duration", default=2.0, type=float)
40
+ parser.add_argument("--min_snr_db", default=-10, type=float)
41
+ parser.add_argument("--max_snr_db", default=20, type=float)
42
+
43
+ parser.add_argument("--target_sample_rate", default=8000, type=int)
44
+
45
+ args = parser.parse_args()
46
+ return args
47
+
48
+
49
+ def filename_generator(data_dir: str):
50
+ data_dir = Path(data_dir)
51
+ for filename in data_dir.glob("**/*.wav"):
52
+ yield filename.as_posix()
53
+
54
+
55
+ def target_second_signal_generator(data_dir: str, duration: int = 2, sample_rate: int = 8000):
56
+ data_dir = Path(data_dir)
57
+ for filename in data_dir.glob("**/*.wav"):
58
+ signal, _ = librosa.load(filename.as_posix(), sr=sample_rate)
59
+ raw_duration = librosa.get_duration(y=signal, sr=sample_rate)
60
+
61
+ if raw_duration < duration:
62
+ # print(f"duration less than {duration} s. skip filename: {filename.as_posix()}")
63
+ continue
64
+ if signal.ndim != 1:
65
+ raise AssertionError(f"expected ndim 1, instead of {signal.ndim}")
66
+
67
+ signal_length = len(signal)
68
+ win_size = int(duration * sample_rate)
69
+ for begin in range(0, signal_length - win_size, win_size):
70
+ row = {
71
+ "filename": filename.as_posix(),
72
+ "raw_duration": round(raw_duration, 4),
73
+ "offset": round(begin / sample_rate, 4),
74
+ "duration": round(duration, 4),
75
+ }
76
+ yield row
77
+
78
+
79
+ def get_dataset(args):
80
+ file_dir = Path(args.file_dir)
81
+ file_dir.mkdir(exist_ok=True)
82
+
83
+ noise_dir = Path(args.noise_dir)
84
+ speech_dir = Path(args.speech_dir)
85
+
86
+ noise_generator = target_second_signal_generator(
87
+ noise_dir.as_posix(),
88
+ duration=args.duration,
89
+ sample_rate=args.target_sample_rate
90
+ )
91
+ speech_generator = target_second_signal_generator(
92
+ speech_dir.as_posix(),
93
+ duration=args.duration,
94
+ sample_rate=args.target_sample_rate
95
+ )
96
+
97
+ dataset = list()
98
+
99
+ count = 0
100
+ process_bar = tqdm(desc="build dataset excel")
101
+ for noise, speech in zip(noise_generator, speech_generator):
102
+
103
+ noise_filename = noise["filename"]
104
+ noise_raw_duration = noise["raw_duration"]
105
+ noise_offset = noise["offset"]
106
+ noise_duration = noise["duration"]
107
+
108
+ speech_filename = speech["filename"]
109
+ speech_raw_duration = speech["raw_duration"]
110
+ speech_offset = speech["offset"]
111
+ speech_duration = speech["duration"]
112
+
113
+ random1 = random.random()
114
+ random2 = random.random()
115
+
116
+ row = {
117
+ "noise_filename": noise_filename,
118
+ "noise_raw_duration": noise_raw_duration,
119
+ "noise_offset": noise_offset,
120
+ "noise_duration": noise_duration,
121
+
122
+ "speech_filename": speech_filename,
123
+ "speech_raw_duration": speech_raw_duration,
124
+ "speech_offset": speech_offset,
125
+ "speech_duration": speech_duration,
126
+
127
+ "snr_db": random.uniform(args.min_snr_db, args.max_snr_db),
128
+
129
+ "random1": random1,
130
+ "random2": random2,
131
+ "flag": "TRAIN" if random2 < 0.8 else "TEST",
132
+ }
133
+ dataset.append(row)
134
+ count += 1
135
+ duration_seconds = count * args.duration
136
+ duration_hours = duration_seconds / 3600
137
+
138
+ process_bar.update(n=1)
139
+ process_bar.set_postfix({
140
+ # "duration_seconds": round(duration_seconds, 4),
141
+ "duration_hours": round(duration_hours, 4),
142
+
143
+ })
144
+
145
+ dataset = pd.DataFrame(dataset)
146
+ dataset = dataset.sort_values(by=["random1"], ascending=False)
147
+ dataset.to_excel(
148
+ file_dir / "dataset.xlsx",
149
+ index=False,
150
+ )
151
+ return
152
+
153
+
154
+
155
+ def split_dataset(args):
156
+ """分割训练集, 测试集"""
157
+ file_dir = Path(args.file_dir)
158
+ file_dir.mkdir(exist_ok=True)
159
+
160
+ df = pd.read_excel(file_dir / "dataset.xlsx")
161
+
162
+ train = list()
163
+ test = list()
164
+
165
+ for i, row in df.iterrows():
166
+ flag = row["flag"]
167
+ if flag == "TRAIN":
168
+ train.append(row)
169
+ else:
170
+ test.append(row)
171
+
172
+ train = pd.DataFrame(train)
173
+ train.to_excel(
174
+ args.train_dataset,
175
+ index=False,
176
+ # encoding="utf_8_sig"
177
+ )
178
+ test = pd.DataFrame(test)
179
+ test.to_excel(
180
+ args.valid_dataset,
181
+ index=False,
182
+ # encoding="utf_8_sig"
183
+ )
184
+
185
+ return
186
+
187
+
188
+ def main():
189
+ args = get_args()
190
+
191
+ get_dataset(args)
192
+ split_dataset(args)
193
+ return
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()
examples/spectrum_dfnet_aishell/step_2_train_model.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ https://github.com/WenzheLiu-Speech/awesome-speech-enhancement
5
+ """
6
+ import argparse
7
+ import json
8
+ import logging
9
+ from logging.handlers import TimedRotatingFileHandler
10
+ import os
11
+ import platform
12
+ from pathlib import Path
13
+ import random
14
+ import sys
15
+ import shutil
16
+ from typing import List
17
+
18
+ pwd = os.path.abspath(os.path.dirname(__file__))
19
+ sys.path.append(os.path.join(pwd, "../../"))
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn as nn
24
+ from torch.nn import functional as F
25
+ from torch.utils.data.dataloader import DataLoader
26
+ import torchaudio
27
+ from tqdm import tqdm
28
+
29
+ from toolbox.torch.utils.data.dataset.denoise_excel_dataset import DenoiseExcelDataset
30
+ from toolbox.torchaudio.models.spectrum_dfnet.configuration_spectrum_dfnet import SpectrumDfNetConfig
31
+ from toolbox.torchaudio.models.spectrum_dfnet.modeling_spectrum_dfnet import SpectrumDfNetPretrainedModel
32
+
33
+
34
+ def get_args():
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument("--train_dataset", default="train.xlsx", type=str)
37
+ parser.add_argument("--valid_dataset", default="valid.xlsx", type=str)
38
+
39
+ parser.add_argument("--max_epochs", default=100, type=int)
40
+
41
+ parser.add_argument("--batch_size", default=64, type=int)
42
+ parser.add_argument("--learning_rate", default=1e-4, type=float)
43
+ parser.add_argument("--num_serialized_models_to_keep", default=10, type=int)
44
+ parser.add_argument("--patience", default=5, type=int)
45
+ parser.add_argument("--serialization_dir", default="serialization_dir", type=str)
46
+ parser.add_argument("--seed", default=0, type=int)
47
+
48
+ parser.add_argument("--config_file", default="config.yaml", type=str)
49
+
50
+ args = parser.parse_args()
51
+ return args
52
+
53
+
54
+ def logging_config(file_dir: str):
55
+ fmt = "%(asctime)s - %(name)s - %(levelname)s %(filename)s:%(lineno)d > %(message)s"
56
+
57
+ logging.basicConfig(format=fmt,
58
+ datefmt="%m/%d/%Y %H:%M:%S",
59
+ level=logging.INFO)
60
+ file_handler = TimedRotatingFileHandler(
61
+ filename=os.path.join(file_dir, "main.log"),
62
+ encoding="utf-8",
63
+ when="D",
64
+ interval=1,
65
+ backupCount=7
66
+ )
67
+ file_handler.setLevel(logging.INFO)
68
+ file_handler.setFormatter(logging.Formatter(fmt))
69
+ logger = logging.getLogger(__name__)
70
+ logger.addHandler(file_handler)
71
+
72
+ return logger
73
+
74
+
75
+ class CollateFunction(object):
76
+ def __init__(self,
77
+ n_fft: int = 512,
78
+ win_length: int = 200,
79
+ hop_length: int = 80,
80
+ window_fn: str = "hamming",
81
+ irm_beta: float = 1.0,
82
+ epsilon: float = 1e-8,
83
+ ):
84
+ self.n_fft = n_fft
85
+ self.win_length = win_length
86
+ self.hop_length = hop_length
87
+ self.window_fn = window_fn
88
+ self.irm_beta = irm_beta
89
+ self.epsilon = epsilon
90
+
91
+ self.complex_transform = torchaudio.transforms.Spectrogram(
92
+ n_fft=self.n_fft,
93
+ win_length=self.win_length,
94
+ hop_length=self.hop_length,
95
+ power=None,
96
+ window_fn=torch.hamming_window if window_fn == "hamming" else torch.hann_window,
97
+ )
98
+ self.transform = torchaudio.transforms.Spectrogram(
99
+ n_fft=self.n_fft,
100
+ win_length=self.win_length,
101
+ hop_length=self.hop_length,
102
+ power=2.0,
103
+ window_fn=torch.hamming_window if window_fn == "hamming" else torch.hann_window,
104
+ )
105
+
106
+ @staticmethod
107
+ def make_unfold_snr_db(x: torch.Tensor, n_time_steps: int = 3):
108
+ batch_size, channels, freq_dim, time_steps = x.shape
109
+
110
+ # kernel: [freq_dim, n_time_step]
111
+ kernel_size = (freq_dim, n_time_steps)
112
+
113
+ # pad
114
+ pad = n_time_steps // 2
115
+ x = torch.concat(tensors=[
116
+ x[:, :, :, :pad],
117
+ x,
118
+ x[:, :, :, -pad:],
119
+ ], dim=-1)
120
+
121
+ x = F.unfold(
122
+ input=x,
123
+ kernel_size=kernel_size,
124
+ )
125
+ # x shape: [batch_size, fold, time_steps]
126
+ return x
127
+
128
+ def __call__(self, batch: List[dict]):
129
+ speech_complex_spec_list = list()
130
+ mix_complex_spec_list = list()
131
+ speech_irm_list = list()
132
+ snr_db_list = list()
133
+ for sample in batch:
134
+ noise_wave: torch.Tensor = sample["noise_wave"]
135
+ speech_wave: torch.Tensor = sample["speech_wave"]
136
+ mix_wave: torch.Tensor = sample["mix_wave"]
137
+ # snr_db: float = sample["snr_db"]
138
+
139
+ noise_spec = self.transform.forward(noise_wave)
140
+ speech_spec = self.transform.forward(speech_wave)
141
+
142
+ speech_complex_spec = self.complex_transform.forward(speech_wave)
143
+ mix_complex_spec = self.complex_transform.forward(mix_wave)
144
+
145
+ # noise_irm = noise_spec / (noise_spec + speech_spec)
146
+ speech_irm = speech_spec / (noise_spec + speech_spec + self.epsilon)
147
+ speech_irm = torch.pow(speech_irm, self.irm_beta)
148
+
149
+ # noise_spec, speech_spec, mix_spec, speech_irm
150
+ # shape: [freq_dim, time_steps]
151
+
152
+ snr_db: torch.Tensor = 10 * torch.log10(
153
+ speech_spec / (noise_spec + self.epsilon)
154
+ )
155
+ snr_db = torch.clamp(snr_db, min=self.epsilon)
156
+
157
+ snr_db_ = torch.unsqueeze(snr_db, dim=0)
158
+ snr_db_ = torch.unsqueeze(snr_db_, dim=0)
159
+ snr_db_ = self.make_unfold_snr_db(snr_db_, n_time_steps=3)
160
+ snr_db_ = torch.squeeze(snr_db_, dim=0)
161
+ # snr_db_ shape: [fold, time_steps]
162
+
163
+ snr_db = torch.mean(snr_db_, dim=0, keepdim=True)
164
+ # snr_db shape: [1, time_steps]
165
+
166
+ speech_complex_spec_list.append(speech_complex_spec)
167
+ mix_complex_spec_list.append(mix_complex_spec)
168
+ speech_irm_list.append(speech_irm)
169
+ snr_db_list.append(snr_db)
170
+
171
+ speech_complex_spec_list = torch.stack(speech_complex_spec_list)
172
+ mix_complex_spec_list = torch.stack(mix_complex_spec_list)
173
+ speech_irm_list = torch.stack(speech_irm_list)
174
+ snr_db_list = torch.stack(snr_db_list) # shape: (batch_size, time_steps, 1)
175
+
176
+ speech_complex_spec_list = speech_complex_spec_list[:, :-1, :]
177
+ mix_complex_spec_list = mix_complex_spec_list[:, :-1, :]
178
+ speech_irm_list = speech_irm_list[:, :-1, :]
179
+
180
+ # speech_complex_spec_list shape: [batch_size, freq_dim, time_steps]
181
+ # mix_complex_spec_list shape: [batch_size, freq_dim, time_steps]
182
+ # speech_irm_list shape: [batch_size, freq_dim, time_steps]
183
+ # snr_db shape: [batch_size, 1, time_steps]
184
+
185
+ # assert
186
+ if torch.any(torch.isnan(speech_complex_spec_list)) or torch.any(torch.isinf(speech_complex_spec_list)):
187
+ raise AssertionError("nan or inf in speech_complex_spec_list")
188
+ if torch.any(torch.isnan(mix_complex_spec_list)) or torch.any(torch.isinf(mix_complex_spec_list)):
189
+ raise AssertionError("nan or inf in mix_complex_spec_list")
190
+ if torch.any(torch.isnan(speech_irm_list)) or torch.any(torch.isinf(speech_irm_list)):
191
+ raise AssertionError("nan or inf in speech_irm_list")
192
+ if torch.any(torch.isnan(snr_db_list)) or torch.any(torch.isinf(snr_db_list)):
193
+ raise AssertionError("nan or inf in snr_db_list")
194
+
195
+ return speech_complex_spec_list, mix_complex_spec_list, speech_irm_list, snr_db_list
196
+
197
+
198
+ collate_fn = CollateFunction()
199
+
200
+
201
+ def main():
202
+ args = get_args()
203
+
204
+ serialization_dir = Path(args.serialization_dir)
205
+ serialization_dir.mkdir(parents=True, exist_ok=True)
206
+
207
+ logger = logging_config(serialization_dir)
208
+
209
+ random.seed(args.seed)
210
+ np.random.seed(args.seed)
211
+ torch.manual_seed(args.seed)
212
+ logger.info("set seed: {}".format(args.seed))
213
+
214
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
215
+ n_gpu = torch.cuda.device_count()
216
+ logger.info("GPU available count: {}; device: {}".format(n_gpu, device))
217
+
218
+ # datasets
219
+ logger.info("prepare datasets")
220
+ train_dataset = DenoiseExcelDataset(
221
+ excel_file=args.train_dataset,
222
+ expected_sample_rate=8000,
223
+ max_wave_value=32768.0,
224
+ )
225
+ valid_dataset = DenoiseExcelDataset(
226
+ excel_file=args.valid_dataset,
227
+ expected_sample_rate=8000,
228
+ max_wave_value=32768.0,
229
+ )
230
+ train_data_loader = DataLoader(
231
+ dataset=train_dataset,
232
+ batch_size=args.batch_size,
233
+ shuffle=True,
234
+ # Linux 系统中可以使用多个子进程加载数据, 而在 Windows 系统中不能.
235
+ num_workers=0 if platform.system() == "Windows" else os.cpu_count() // 2,
236
+ collate_fn=collate_fn,
237
+ pin_memory=False,
238
+ # prefetch_factor=64,
239
+ )
240
+ valid_data_loader = DataLoader(
241
+ dataset=valid_dataset,
242
+ batch_size=args.batch_size,
243
+ shuffle=True,
244
+ # Linux 系统中可以使用多个子进程加载数据, 而在 Windows 系统中不能.
245
+ num_workers=0 if platform.system() == "Windows" else os.cpu_count() // 2,
246
+ collate_fn=collate_fn,
247
+ pin_memory=False,
248
+ # prefetch_factor=64,
249
+ )
250
+
251
+ # models
252
+ logger.info(f"prepare models. config_file: {args.config_file}")
253
+ config = SpectrumDfNetConfig.from_pretrained(
254
+ pretrained_model_name_or_path=args.config_file,
255
+ # num_labels=vocabulary.get_vocab_size(namespace="labels")
256
+ )
257
+ model = SpectrumDfNetPretrainedModel(
258
+ config=config,
259
+ )
260
+ model.to(device)
261
+ model.train()
262
+
263
+ # optimizer
264
+ logger.info("prepare optimizer, lr_scheduler, loss_fn, categorical_accuracy")
265
+ param_optimizer = model.parameters()
266
+ optimizer = torch.optim.Adam(
267
+ param_optimizer,
268
+ lr=args.learning_rate,
269
+ )
270
+ # lr_scheduler = torch.optim.lr_scheduler.StepLR(
271
+ # optimizer,
272
+ # step_size=2000
273
+ # )
274
+ lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
275
+ optimizer,
276
+ milestones=[10000, 20000, 30000, 40000, 50000], gamma=0.5
277
+ )
278
+
279
+ speech_mse_loss = nn.MSELoss(
280
+ reduction="mean",
281
+ )
282
+ irm_mse_loss = nn.MSELoss(
283
+ reduction="mean",
284
+ )
285
+ snr_mse_loss = nn.MSELoss(
286
+ reduction="mean",
287
+ )
288
+
289
+ # training loop
290
+ logger.info("training")
291
+
292
+ training_loss = 10000000000
293
+ evaluation_loss = 10000000000
294
+
295
+ model_list = list()
296
+ best_idx_epoch = None
297
+ best_metric = None
298
+ patience_count = 0
299
+
300
+ for idx_epoch in range(args.max_epochs):
301
+ total_loss = 0.
302
+ total_examples = 0.
303
+ progress_bar = tqdm(
304
+ total=len(train_data_loader),
305
+ desc="Training; epoch: {}".format(idx_epoch),
306
+ )
307
+
308
+ for batch in train_data_loader:
309
+ speech_complex_spec, mix_complex_spec, speech_irm, snr_db = batch
310
+ speech_complex_spec = speech_complex_spec.to(device)
311
+ mix_complex_spec = mix_complex_spec.to(device)
312
+ speech_irm_target = speech_irm.to(device)
313
+ snr_db_target = snr_db.to(device)
314
+
315
+ speech_spec_prediction, speech_irm_prediction, lsnr_prediction = model.forward(mix_complex_spec)
316
+ if torch.any(torch.isnan(speech_spec_prediction)) or torch.any(torch.isinf(speech_spec_prediction)):
317
+ raise AssertionError("nan or inf in speech_spec_prediction")
318
+ if torch.any(torch.isnan(speech_irm_prediction)) or torch.any(torch.isinf(speech_irm_prediction)):
319
+ raise AssertionError("nan or inf in speech_irm_prediction")
320
+ if torch.any(torch.isnan(lsnr_prediction)) or torch.any(torch.isinf(lsnr_prediction)):
321
+ raise AssertionError("nan or inf in lsnr_prediction")
322
+
323
+ speech_loss = speech_mse_loss.forward(speech_spec_prediction, speech_complex_spec)
324
+ irm_loss = irm_mse_loss.forward(speech_irm_prediction, speech_irm_target)
325
+
326
+ lsnr_prediction = (lsnr_prediction - config.lsnr_min) / (config.lsnr_max - config.lsnr_min)
327
+ snr_db_target = (snr_db_target - config.lsnr_min) / (config.lsnr_max - config.lsnr_min)
328
+ if torch.max(lsnr_prediction) > 1 or torch.min(lsnr_prediction) < 0:
329
+ raise AssertionError(f"expected lsnr_prediction between 0 and 1.")
330
+ if torch.max(snr_db_target) > 1 or torch.min(snr_db_target) < 0:
331
+ raise AssertionError(f"expected snr_db_target between 0 and 1.")
332
+
333
+ snr_loss = snr_mse_loss.forward(lsnr_prediction, snr_db_target)
334
+
335
+ if torch.any(torch.isnan(snr_loss)) or torch.any(torch.isinf(snr_loss)):
336
+ raise AssertionError("nan or inf in snr_loss")
337
+
338
+ loss = speech_loss + irm_loss + snr_loss
339
+
340
+ total_loss += loss.item()
341
+ total_examples += mix_complex_spec.size(0)
342
+
343
+ optimizer.zero_grad()
344
+ loss.backward()
345
+ optimizer.step()
346
+ lr_scheduler.step()
347
+
348
+ training_loss = total_loss / total_examples
349
+ training_loss = round(training_loss, 4)
350
+
351
+ progress_bar.update(1)
352
+ progress_bar.set_postfix({
353
+ "training_loss": training_loss,
354
+ })
355
+
356
+ total_loss = 0.
357
+ total_examples = 0.
358
+ progress_bar = tqdm(
359
+ total=len(valid_data_loader),
360
+ desc="Evaluation; epoch: {}".format(idx_epoch),
361
+ )
362
+ for batch in valid_data_loader:
363
+ speech_complex_spec, mix_complex_spec, speech_irm, snr_db = batch
364
+ speech_complex_spec = speech_complex_spec.to(device)
365
+ mix_complex_spec = mix_complex_spec.to(device)
366
+ speech_irm_target = speech_irm.to(device)
367
+ snr_db_target = snr_db.to(device)
368
+
369
+ with torch.no_grad():
370
+ speech_spec_prediction, speech_irm_prediction, lsnr_prediction = model.forward(mix_complex_spec)
371
+ if torch.any(torch.isnan(speech_spec_prediction)) or torch.any(torch.isinf(speech_spec_prediction)):
372
+ raise AssertionError("nan or inf in speech_spec_prediction")
373
+ if torch.any(torch.isnan(speech_irm_prediction)) or torch.any(torch.isinf(speech_irm_prediction)):
374
+ raise AssertionError("nan or inf in speech_irm_prediction")
375
+ if torch.any(torch.isnan(lsnr_prediction)) or torch.any(torch.isinf(lsnr_prediction)):
376
+ raise AssertionError("nan or inf in lsnr_prediction")
377
+
378
+ speech_loss = speech_mse_loss.forward(speech_spec_prediction, speech_complex_spec)
379
+ irm_loss = irm_mse_loss.forward(speech_irm_prediction, speech_irm_target)
380
+
381
+ lsnr_prediction = (lsnr_prediction - config.lsnr_min) / (config.lsnr_max - config.lsnr_min)
382
+ snr_db_target = (snr_db_target - config.lsnr_min) / (config.lsnr_max - config.lsnr_min)
383
+ if torch.max(lsnr_prediction) > 1 or torch.min(lsnr_prediction) < 0:
384
+ raise AssertionError(f"expected lsnr_prediction between 0 and 1.")
385
+ if torch.max(snr_db_target) > 1 or torch.min(snr_db_target) < 0:
386
+ raise AssertionError(f"expected snr_db_target between 0 and 1.")
387
+
388
+ snr_loss = snr_mse_loss.forward(lsnr_prediction, snr_db_target)
389
+
390
+ loss = speech_loss + irm_loss + snr_loss
391
+
392
+ total_loss += loss.item()
393
+ total_examples += mix_complex_spec.size(0)
394
+
395
+ evaluation_loss = total_loss / total_examples
396
+ evaluation_loss = round(evaluation_loss, 4)
397
+
398
+ progress_bar.update(1)
399
+ progress_bar.set_postfix({
400
+ "evaluation_loss": evaluation_loss,
401
+ })
402
+
403
+ # save path
404
+ epoch_dir = serialization_dir / "epoch-{}".format(idx_epoch)
405
+ epoch_dir.mkdir(parents=True, exist_ok=False)
406
+
407
+ # save models
408
+ model.save_pretrained(epoch_dir.as_posix())
409
+
410
+ model_list.append(epoch_dir)
411
+ if len(model_list) >= args.num_serialized_models_to_keep:
412
+ model_to_delete: Path = model_list.pop(0)
413
+ shutil.rmtree(model_to_delete.as_posix())
414
+
415
+ # save metric
416
+ if best_metric is None:
417
+ best_idx_epoch = idx_epoch
418
+ best_metric = evaluation_loss
419
+ elif evaluation_loss < best_metric:
420
+ best_idx_epoch = idx_epoch
421
+ best_metric = evaluation_loss
422
+ else:
423
+ pass
424
+
425
+ metrics = {
426
+ "idx_epoch": idx_epoch,
427
+ "best_idx_epoch": best_idx_epoch,
428
+ "training_loss": training_loss,
429
+ "evaluation_loss": evaluation_loss,
430
+ "learning_rate": optimizer.param_groups[0]["lr"],
431
+ }
432
+ metrics_filename = epoch_dir / "metrics_epoch.json"
433
+ with open(metrics_filename, "w", encoding="utf-8") as f:
434
+ json.dump(metrics, f, indent=4, ensure_ascii=False)
435
+
436
+ # save best
437
+ best_dir = serialization_dir / "best"
438
+ if best_idx_epoch == idx_epoch:
439
+ if best_dir.exists():
440
+ shutil.rmtree(best_dir)
441
+ shutil.copytree(epoch_dir, best_dir)
442
+
443
+ # early stop
444
+ early_stop_flag = False
445
+ if best_idx_epoch == idx_epoch:
446
+ patience_count = 0
447
+ else:
448
+ patience_count += 1
449
+ if patience_count >= args.patience:
450
+ early_stop_flag = True
451
+
452
+ # early stop
453
+ if early_stop_flag:
454
+ break
455
+ return
456
+
457
+
458
+ if __name__ == '__main__':
459
+ main()
examples/spectrum_dfnet_aishell/step_3_evaluation.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import argparse
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+ import sys
8
+ import uuid
9
+
10
+ pwd = os.path.abspath(os.path.dirname(__file__))
11
+ sys.path.append(os.path.join(pwd, "../../"))
12
+
13
+ import librosa
14
+ import numpy as np
15
+ import pandas as pd
16
+ from scipy.io import wavfile
17
+ import torch
18
+ import torch.nn as nn
19
+ import torchaudio
20
+ from tqdm import tqdm
21
+
22
+ from toolbox.torchaudio.models.spectrum_unet_irm.modeling_spectrum_unet_irm import SpectrumUnetIRMPretrainedModel
23
+
24
+
25
+ def get_args():
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--valid_dataset", default="valid.xlsx", type=str)
28
+ parser.add_argument("--model_dir", default="serialization_dir/best", type=str)
29
+ parser.add_argument("--evaluation_audio_dir", default="evaluation_audio_dir", type=str)
30
+
31
+ parser.add_argument("--limit", default=10, type=int)
32
+
33
+ args = parser.parse_args()
34
+ return args
35
+
36
+
37
+ def logging_config():
38
+ fmt = "%(asctime)s - %(name)s - %(levelname)s %(filename)s:%(lineno)d > %(message)s"
39
+
40
+ logging.basicConfig(format=fmt,
41
+ datefmt="%m/%d/%Y %H:%M:%S",
42
+ level=logging.INFO)
43
+ stream_handler = logging.StreamHandler()
44
+ stream_handler.setLevel(logging.INFO)
45
+ stream_handler.setFormatter(logging.Formatter(fmt))
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ return logger
50
+
51
+
52
+ def mix_speech_and_noise(speech: np.ndarray, noise: np.ndarray, snr_db: float):
53
+ l1 = len(speech)
54
+ l2 = len(noise)
55
+ l = min(l1, l2)
56
+ speech = speech[:l]
57
+ noise = noise[:l]
58
+
59
+ # np.float32, value between (-1, 1).
60
+
61
+ speech_power = np.mean(np.square(speech))
62
+ noise_power = speech_power / (10 ** (snr_db / 10))
63
+
64
+ noise_adjusted = np.sqrt(noise_power) * noise / np.sqrt(np.mean(noise ** 2))
65
+
66
+ noisy_signal = speech + noise_adjusted
67
+
68
+ return noisy_signal
69
+
70
+
71
+ stft_power = torchaudio.transforms.Spectrogram(
72
+ n_fft=512,
73
+ win_length=200,
74
+ hop_length=80,
75
+ power=2.0,
76
+ window_fn=torch.hamming_window,
77
+ )
78
+
79
+
80
+ stft_complex = torchaudio.transforms.Spectrogram(
81
+ n_fft=512,
82
+ win_length=200,
83
+ hop_length=80,
84
+ power=None,
85
+ window_fn=torch.hamming_window,
86
+ )
87
+
88
+
89
+ istft = torchaudio.transforms.InverseSpectrogram(
90
+ n_fft=512,
91
+ win_length=200,
92
+ hop_length=80,
93
+ window_fn=torch.hamming_window,
94
+ )
95
+
96
+
97
+ def enhance(mix_spec_complex: torch.Tensor, speech_irm_prediction: torch.Tensor):
98
+ mix_spec_complex = mix_spec_complex.detach().cpu()
99
+ speech_irm_prediction = speech_irm_prediction.detach().cpu()
100
+
101
+ mask_speech = speech_irm_prediction
102
+ mask_noise = 1.0 - speech_irm_prediction
103
+
104
+ speech_spec = mix_spec_complex * mask_speech
105
+ noise_spec = mix_spec_complex * mask_noise
106
+
107
+ speech_wave = istft.forward(speech_spec)
108
+ noise_wave = istft.forward(noise_spec)
109
+
110
+ return speech_wave, noise_wave
111
+
112
+
113
+ def save_audios(noise_wave: torch.Tensor,
114
+ speech_wave: torch.Tensor,
115
+ mix_wave: torch.Tensor,
116
+ speech_wave_enhanced: torch.Tensor,
117
+ noise_wave_enhanced: torch.Tensor,
118
+ output_dir: str,
119
+ sample_rate: int = 8000,
120
+ ):
121
+ basename = uuid.uuid4().__str__()
122
+ output_dir = Path(output_dir) / basename
123
+ output_dir.mkdir(parents=True, exist_ok=True)
124
+
125
+ filename = output_dir / "noise_wave.wav"
126
+ torchaudio.save(filename, noise_wave, sample_rate)
127
+ filename = output_dir / "speech_wave.wav"
128
+ torchaudio.save(filename, speech_wave, sample_rate)
129
+ filename = output_dir / "mix_wave.wav"
130
+ torchaudio.save(filename, mix_wave, sample_rate)
131
+
132
+ filename = output_dir / "speech_wave_enhanced.wav"
133
+ torchaudio.save(filename, speech_wave_enhanced, sample_rate)
134
+ filename = output_dir / "noise_wave_enhanced.wav"
135
+ torchaudio.save(filename, noise_wave_enhanced, sample_rate)
136
+
137
+ return output_dir.as_posix()
138
+
139
+
140
+ def main():
141
+ args = get_args()
142
+
143
+ logger = logging_config()
144
+
145
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
146
+ n_gpu = torch.cuda.device_count()
147
+ logger.info("GPU available count: {}; device: {}".format(n_gpu, device))
148
+
149
+ logger.info("prepare model")
150
+ model = SpectrumUnetIRMPretrainedModel.from_pretrained(
151
+ pretrained_model_name_or_path=args.model_dir,
152
+ )
153
+ model.to(device)
154
+ model.eval()
155
+
156
+ # optimizer
157
+ logger.info("prepare loss_fn")
158
+ irm_mse_loss = nn.MSELoss(
159
+ reduction="mean",
160
+ )
161
+ snr_mse_loss = nn.MSELoss(
162
+ reduction="mean",
163
+ )
164
+
165
+ logger.info("read excel")
166
+ df = pd.read_excel(args.valid_dataset)
167
+
168
+ total_loss = 0.
169
+ total_examples = 0.
170
+ progress_bar = tqdm(total=len(df), desc="Evaluation")
171
+ for idx, row in df.iterrows():
172
+ noise_filename = row["noise_filename"]
173
+ noise_offset = row["noise_offset"]
174
+ noise_duration = row["noise_duration"]
175
+
176
+ speech_filename = row["speech_filename"]
177
+ speech_offset = row["speech_offset"]
178
+ speech_duration = row["speech_duration"]
179
+
180
+ snr_db = row["snr_db"]
181
+
182
+ noise_wave, _ = librosa.load(
183
+ noise_filename,
184
+ sr=8000,
185
+ offset=noise_offset,
186
+ duration=noise_duration,
187
+ )
188
+ speech_wave, _ = librosa.load(
189
+ speech_filename,
190
+ sr=8000,
191
+ offset=speech_offset,
192
+ duration=speech_duration,
193
+ )
194
+ mix_wave: np.ndarray = mix_speech_and_noise(
195
+ speech=speech_wave,
196
+ noise=noise_wave,
197
+ snr_db=snr_db,
198
+ )
199
+ noise_wave = torch.tensor(noise_wave, dtype=torch.float32)
200
+ speech_wave = torch.tensor(speech_wave, dtype=torch.float32)
201
+ mix_wave: torch.Tensor = torch.tensor(mix_wave, dtype=torch.float32)
202
+
203
+ noise_wave = noise_wave.unsqueeze(dim=0)
204
+ speech_wave = speech_wave.unsqueeze(dim=0)
205
+ mix_wave = mix_wave.unsqueeze(dim=0)
206
+
207
+ noise_spec: torch.Tensor = stft_power.forward(noise_wave)
208
+ speech_spec: torch.Tensor = stft_power.forward(speech_wave)
209
+ mix_spec: torch.Tensor = stft_power.forward(mix_wave)
210
+
211
+ noise_spec = noise_spec[:, :-1, :]
212
+ speech_spec = speech_spec[:, :-1, :]
213
+ mix_spec = mix_spec[:, :-1, :]
214
+
215
+ mix_spec_complex: torch.Tensor = stft_complex.forward(mix_wave)
216
+ # mix_spec_complex shape: [batch_size, freq_dim (257), time_steps, 2]
217
+
218
+ speech_irm = speech_spec / (noise_spec + speech_spec)
219
+ speech_irm = torch.pow(speech_irm, 1.0)
220
+
221
+ snr_db: torch.Tensor = 10 * torch.log10(
222
+ speech_spec / (noise_spec + 1e-8)
223
+ )
224
+ snr_db = torch.mean(snr_db, dim=1, keepdim=True)
225
+ # snr_db shape: [batch_size, 1, time_steps]
226
+
227
+ mix_spec = mix_spec.to(device)
228
+ speech_irm_target = speech_irm.to(device)
229
+ snr_db_target = snr_db.to(device)
230
+
231
+ with torch.no_grad():
232
+ speech_irm_prediction, lsnr_prediction = model.forward(mix_spec)
233
+ irm_loss = irm_mse_loss.forward(speech_irm_prediction, speech_irm_target)
234
+ # snr_loss = snr_mse_loss.forward(lsnr_prediction, snr_db_target)
235
+ # loss = irm_loss + 0.1 * snr_loss
236
+ loss = irm_loss
237
+
238
+ # mix_spec_complex shape: [batch_size, freq_dim (257), time_steps, 2]
239
+ # speech_irm_prediction shape: [batch_size, freq_dim (256), time_steps]
240
+ batch_size, _, time_steps = speech_irm_prediction.shape
241
+ speech_irm_prediction = torch.concat(
242
+ [
243
+ speech_irm_prediction,
244
+ 0.5*torch.ones(size=(batch_size, 1, time_steps), dtype=speech_irm_prediction.dtype).to(device)
245
+ ],
246
+ dim=1,
247
+ )
248
+ # speech_irm_prediction shape: [batch_size, freq_dim (257), time_steps]
249
+ speech_wave_enhanced, noise_wave_enhanced = enhance(mix_spec_complex, speech_irm_prediction)
250
+ save_audios(noise_wave, speech_wave, mix_wave, speech_wave_enhanced, noise_wave_enhanced, args.evaluation_audio_dir)
251
+
252
+ total_loss += loss.item()
253
+ total_examples += mix_spec.size(0)
254
+
255
+ evaluation_loss = total_loss / total_examples
256
+ evaluation_loss = round(evaluation_loss, 4)
257
+
258
+ progress_bar.update(1)
259
+ progress_bar.set_postfix({
260
+ "evaluation_loss": evaluation_loss,
261
+ })
262
+
263
+ if idx > args.limit:
264
+ break
265
+
266
+ return
267
+
268
+
269
+ if __name__ == '__main__':
270
+ main()
examples/spectrum_dfnet_aishell/yaml/config.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model_name: "spectrum_unet_irm"
2
+
3
+ # spec
4
+ sample_rate: 8000
5
+ n_fft: 512
6
+ win_length: 200
7
+ hop_length: 80
8
+
9
+ spec_bins: 256
10
+
11
+ # model
12
+ conv_channels: 64
13
+ conv_kernel_size_input:
14
+ - 3
15
+ - 3
16
+ conv_kernel_size_inner:
17
+ - 1
18
+ - 3
19
+ conv_lookahead: 0
20
+
21
+ convt_kernel_size_inner:
22
+ - 1
23
+ - 3
24
+
25
+ encoder_emb_skip_op: "none"
26
+ encoder_emb_linear_groups: 16
27
+ encoder_emb_hidden_size: 256
28
+
29
+ lsnr_max: 30
30
+ lsnr_min: -15
31
+
32
+ decoder_emb_num_layers: 3
33
+ decoder_emb_skip_op: "none"
34
+ decoder_emb_linear_groups: 16
35
+ decoder_emb_hidden_size: 256
36
+
37
+ # runtime
38
+ use_post_filter: true
toolbox/torchaudio/models/mpnet/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+
5
+ if __name__ == '__main__':
6
+ pass
toolbox/torchaudio/models/mpnet/modeling_mpnet.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ https://huggingface.co/spaces/LeeSangHoon/HierSpeech_TTS/blob/main/denoiser/generator.py
5
+ """
6
+
7
+
8
+ if __name__ == '__main__':
9
+ pass
toolbox/torchaudio/models/spectrum_dfnet/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+
5
+ if __name__ == '__main__':
6
+ pass
toolbox/torchaudio/models/spectrum_dfnet/configuration_spectrum_dfnet.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ from typing import Tuple
4
+
5
+ from toolbox.torchaudio.configuration_utils import PretrainedConfig
6
+
7
+
8
+ class SpectrumDfNetConfig(PretrainedConfig):
9
+ def __init__(self,
10
+ sample_rate: int = 8000,
11
+ n_fft: int = 512,
12
+ win_length: int = 200,
13
+ hop_length: int = 80,
14
+
15
+ spec_bins: int = 256,
16
+
17
+ conv_channels: int = 64,
18
+ conv_kernel_size_input: Tuple[int, int] = (3, 3),
19
+ conv_kernel_size_inner: Tuple[int, int] = (1, 3),
20
+ conv_lookahead: int = 0,
21
+
22
+ convt_kernel_size_inner: Tuple[int, int] = (1, 3),
23
+
24
+ embedding_hidden_size: int = 256,
25
+ encoder_combine_op: str = "concat",
26
+
27
+ encoder_emb_skip_op: str = "none",
28
+ encoder_emb_linear_groups: int = 16,
29
+ encoder_emb_hidden_size: int = 256,
30
+
31
+ encoder_linear_groups: int = 32,
32
+
33
+ lsnr_max: int = 30,
34
+ lsnr_min: int = -15,
35
+ norm_tau: float = 1.,
36
+
37
+ decoder_emb_num_layers: int = 3,
38
+ decoder_emb_skip_op: str = "none",
39
+ decoder_emb_linear_groups: int = 16,
40
+ decoder_emb_hidden_size: int = 256,
41
+
42
+ df_decoder_hidden_size: int = 256,
43
+ df_num_layers: int = 2,
44
+ df_order: int = 5,
45
+ df_bins: int = 96,
46
+ df_gru_skip: str = "grouped_linear",
47
+ df_decoder_linear_groups: int = 16,
48
+ df_pathway_kernel_size_t: int = 5,
49
+ df_lookahead: int = 2,
50
+
51
+ use_post_filter: bool = False,
52
+ **kwargs
53
+ ):
54
+ super(SpectrumDfNetConfig, self).__init__(**kwargs)
55
+ # transform
56
+ self.sample_rate = sample_rate
57
+ self.n_fft = n_fft
58
+ self.win_length = win_length
59
+ self.hop_length = hop_length
60
+
61
+ # spectrum
62
+ self.spec_bins = spec_bins
63
+
64
+ # conv
65
+ self.conv_channels = conv_channels
66
+ self.conv_kernel_size_input = conv_kernel_size_input
67
+ self.conv_kernel_size_inner = conv_kernel_size_inner
68
+ self.conv_lookahead = conv_lookahead
69
+
70
+ self.convt_kernel_size_inner = convt_kernel_size_inner
71
+
72
+ self.embedding_hidden_size = embedding_hidden_size
73
+
74
+ # encoder
75
+ self.encoder_emb_skip_op = encoder_emb_skip_op
76
+ self.encoder_emb_linear_groups = encoder_emb_linear_groups
77
+ self.encoder_emb_hidden_size = encoder_emb_hidden_size
78
+
79
+ self.encoder_linear_groups = encoder_linear_groups
80
+ self.encoder_combine_op = encoder_combine_op
81
+
82
+ self.lsnr_max = lsnr_max
83
+ self.lsnr_min = lsnr_min
84
+ self.norm_tau = norm_tau
85
+
86
+ # decoder
87
+ self.decoder_emb_num_layers = decoder_emb_num_layers
88
+ self.decoder_emb_skip_op = decoder_emb_skip_op
89
+ self.decoder_emb_linear_groups = decoder_emb_linear_groups
90
+ self.decoder_emb_hidden_size = decoder_emb_hidden_size
91
+
92
+ # df decoder
93
+ self.df_decoder_hidden_size = df_decoder_hidden_size
94
+ self.df_num_layers = df_num_layers
95
+ self.df_order = df_order
96
+ self.df_bins = df_bins
97
+ self.df_gru_skip = df_gru_skip
98
+ self.df_decoder_linear_groups = df_decoder_linear_groups
99
+ self.df_pathway_kernel_size_t = df_pathway_kernel_size_t
100
+ self.df_lookahead = df_lookahead
101
+
102
+ # runtime
103
+ self.use_post_filter = use_post_filter
104
+
105
+
106
+ if __name__ == "__main__":
107
+ pass
toolbox/torchaudio/models/spectrum_dfnet/modeling_spectrum_dfnet.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+ import os
4
+ import math
5
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ import torchaudio
11
+
12
+ from toolbox.torchaudio.models.spectrum_dfnet.configuration_spectrum_dfnet import SpectrumDfNetConfig
13
+ from toolbox.torchaudio.configuration_utils import CONFIG_FILE
14
+
15
+
16
+ MODEL_FILE = "model.pt"
17
+
18
+
19
+ norm_layer_dict = {
20
+ "batch_norm_2d": torch.nn.BatchNorm2d
21
+ }
22
+
23
+
24
+ activation_layer_dict = {
25
+ "relu": torch.nn.ReLU,
26
+ "identity": torch.nn.Identity,
27
+ "sigmoid": torch.nn.Sigmoid,
28
+ }
29
+
30
+
31
+ class CausalConv2d(nn.Sequential):
32
+ def __init__(self,
33
+ in_channels: int,
34
+ out_channels: int,
35
+ kernel_size: Union[int, Iterable[int]],
36
+ fstride: int = 1,
37
+ dilation: int = 1,
38
+ fpad: bool = True,
39
+ bias: bool = True,
40
+ separable: bool = False,
41
+ norm_layer: str = "batch_norm_2d",
42
+ activation_layer: str = "relu",
43
+ lookahead: int = 0
44
+ ):
45
+ """
46
+ Causal Conv2d by delaying the signal for any lookahead.
47
+
48
+ Expected input format: [batch_size, channels, time_steps, spec_dim]
49
+
50
+ :param in_channels:
51
+ :param out_channels:
52
+ :param kernel_size:
53
+ :param fstride:
54
+ :param dilation:
55
+ :param fpad:
56
+ """
57
+ super(CausalConv2d, self).__init__()
58
+ kernel_size = (kernel_size, kernel_size) if isinstance(kernel_size, int) else tuple(kernel_size)
59
+
60
+ if fpad:
61
+ fpad_ = kernel_size[1] // 2 + dilation - 1
62
+ else:
63
+ fpad_ = 0
64
+
65
+ # for last 2 dim, pad (left, right, top, bottom).
66
+ pad = (0, 0, kernel_size[0] - 1 - lookahead, lookahead)
67
+
68
+ layers = list()
69
+ if any(x > 0 for x in pad):
70
+ layers.append(nn.ConstantPad2d(pad, 0.0))
71
+
72
+ groups = math.gcd(in_channels, out_channels) if separable else 1
73
+ if groups == 1:
74
+ separable = False
75
+ if max(kernel_size) == 1:
76
+ separable = False
77
+
78
+ layers.append(
79
+ nn.Conv2d(
80
+ in_channels,
81
+ out_channels,
82
+ kernel_size=kernel_size,
83
+ padding=(0, fpad_),
84
+ stride=(1, fstride), # stride over time is always 1
85
+ dilation=(1, dilation), # dilation over time is always 1
86
+ groups=groups,
87
+ bias=bias,
88
+ )
89
+ )
90
+
91
+ if separable:
92
+ layers.append(
93
+ nn.Conv2d(
94
+ out_channels,
95
+ out_channels,
96
+ kernel_size=1,
97
+ bias=False,
98
+ )
99
+ )
100
+
101
+ if norm_layer is not None:
102
+ norm_layer = norm_layer_dict[norm_layer]
103
+ layers.append(norm_layer(out_channels))
104
+
105
+ if activation_layer is not None:
106
+ activation_layer = activation_layer_dict[activation_layer]
107
+ layers.append(activation_layer())
108
+
109
+ super().__init__(*layers)
110
+
111
+ def forward(self, inputs):
112
+ for module in self:
113
+ inputs = module(inputs)
114
+ return inputs
115
+
116
+
117
+ class CausalConvTranspose2d(nn.Sequential):
118
+ def __init__(self,
119
+ in_channels: int,
120
+ out_channels: int,
121
+ kernel_size: Union[int, Iterable[int]],
122
+ fstride: int = 1,
123
+ dilation: int = 1,
124
+ fpad: bool = True,
125
+ bias: bool = True,
126
+ separable: bool = False,
127
+ norm_layer: str = "batch_norm_2d",
128
+ activation_layer: str = "relu",
129
+ lookahead: int = 0
130
+ ):
131
+ """
132
+ Causal ConvTranspose2d.
133
+
134
+ Expected input format: [batch_size, channels, time_steps, spec_dim]
135
+ """
136
+ super(CausalConvTranspose2d, self).__init__()
137
+
138
+ kernel_size = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
139
+
140
+ if fpad:
141
+ fpad_ = kernel_size[1] // 2
142
+ else:
143
+ fpad_ = 0
144
+
145
+ # for last 2 dim, pad (left, right, top, bottom).
146
+ pad = (0, 0, kernel_size[0] - 1 - lookahead, lookahead)
147
+
148
+ layers = []
149
+ if any(x > 0 for x in pad):
150
+ layers.append(nn.ConstantPad2d(pad, 0.0))
151
+
152
+ groups = math.gcd(in_channels, out_channels) if separable else 1
153
+ if groups == 1:
154
+ separable = False
155
+
156
+ layers.append(
157
+ nn.ConvTranspose2d(
158
+ in_channels,
159
+ out_channels,
160
+ kernel_size=kernel_size,
161
+ padding=(kernel_size[0] - 1, fpad_ + dilation - 1),
162
+ output_padding=(0, fpad_),
163
+ stride=(1, fstride), # stride over time is always 1
164
+ dilation=(1, dilation), # dilation over time is always 1
165
+ groups=groups,
166
+ bias=bias,
167
+ )
168
+ )
169
+
170
+ if separable:
171
+ layers.append(
172
+ nn.Conv2d(
173
+ out_channels,
174
+ out_channels,
175
+ kernel_size=1,
176
+ bias=False,
177
+ )
178
+ )
179
+
180
+ if norm_layer is not None:
181
+ norm_layer = norm_layer_dict[norm_layer]
182
+ layers.append(norm_layer(out_channels))
183
+
184
+ if activation_layer is not None:
185
+ activation_layer = activation_layer_dict[activation_layer]
186
+ layers.append(activation_layer())
187
+
188
+ super().__init__(*layers)
189
+
190
+
191
+ class GroupedLinear(nn.Module):
192
+
193
+ def __init__(self, input_size: int, hidden_size: int, groups: int = 1):
194
+ super().__init__()
195
+ # self.weight: Tensor
196
+ self.input_size = input_size
197
+ self.hidden_size = hidden_size
198
+ self.groups = groups
199
+ assert input_size % groups == 0, f"Input size {input_size} not divisible by {groups}"
200
+ assert hidden_size % groups == 0, f"Hidden size {hidden_size} not divisible by {groups}"
201
+ self.ws = input_size // groups
202
+ self.register_parameter(
203
+ "weight",
204
+ torch.nn.Parameter(
205
+ torch.zeros(groups, input_size // groups, hidden_size // groups), requires_grad=True
206
+ ),
207
+ )
208
+ self.reset_parameters()
209
+
210
+ def reset_parameters(self):
211
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5)) # type: ignore
212
+
213
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
214
+ # x: [..., I]
215
+ b, t, _ = x.shape
216
+ # new_shape = list(x.shape)[:-1] + [self.groups, self.ws]
217
+ new_shape = (b, t, self.groups, self.ws)
218
+ x = x.view(new_shape)
219
+ # The better way, but not supported by torchscript
220
+ # x = x.unflatten(-1, (self.groups, self.ws)) # [..., G, I/G]
221
+ x = torch.einsum("btgi,gih->btgh", x, self.weight) # [..., G, H/G]
222
+ x = x.flatten(2, 3) # [B, T, H]
223
+ return x
224
+
225
+ def __repr__(self):
226
+ cls = self.__class__.__name__
227
+ return f"{cls}(input_size: {self.input_size}, hidden_size: {self.hidden_size}, groups: {self.groups})"
228
+
229
+
230
+ class SqueezedGRU_S(nn.Module):
231
+ """
232
+ SGE net: Video object detection with squeezed GRU and information entropy map
233
+ https://arxiv.org/abs/2106.07224
234
+ """
235
+
236
+ def __init__(
237
+ self,
238
+ input_size: int,
239
+ hidden_size: int,
240
+ output_size: Optional[int] = None,
241
+ num_layers: int = 1,
242
+ linear_groups: int = 8,
243
+ batch_first: bool = True,
244
+ skip_op: str = "none",
245
+ activation_layer: str = "identity",
246
+ ):
247
+ super().__init__()
248
+ self.input_size = input_size
249
+ self.hidden_size = hidden_size
250
+
251
+ self.linear_in = nn.Sequential(
252
+ GroupedLinear(
253
+ input_size=input_size,
254
+ hidden_size=hidden_size,
255
+ groups=linear_groups,
256
+ ),
257
+ activation_layer_dict[activation_layer](),
258
+ )
259
+
260
+ # gru skip operator
261
+ self.gru_skip_op = None
262
+
263
+ if skip_op == "none":
264
+ self.gru_skip_op = None
265
+ elif skip_op == "identity":
266
+ if not input_size != output_size:
267
+ raise AssertionError("Dimensions do not match")
268
+ self.gru_skip_op = nn.Identity()
269
+ elif skip_op == "grouped_linear":
270
+ self.gru_skip_op = GroupedLinear(
271
+ input_size=hidden_size,
272
+ hidden_size=hidden_size,
273
+ groups=linear_groups,
274
+ )
275
+ else:
276
+ raise NotImplementedError()
277
+
278
+ self.gru = nn.GRU(
279
+ input_size=hidden_size,
280
+ hidden_size=hidden_size,
281
+ num_layers=num_layers,
282
+ batch_first=batch_first,
283
+ bidirectional=False,
284
+ )
285
+
286
+ if output_size is not None:
287
+ self.linear_out = nn.Sequential(
288
+ GroupedLinear(
289
+ input_size=hidden_size,
290
+ hidden_size=output_size,
291
+ groups=linear_groups,
292
+ ),
293
+ activation_layer_dict[activation_layer](),
294
+ )
295
+ else:
296
+ self.linear_out = nn.Identity()
297
+
298
+ def forward(self, inputs: torch.Tensor, h=None) -> Tuple[torch.Tensor, torch.Tensor]:
299
+ x = self.linear_in(inputs)
300
+
301
+ x, h = self.gru.forward(x, h)
302
+
303
+ x = self.linear_out(x)
304
+
305
+ if self.gru_skip_op is not None:
306
+ x = x + self.gru_skip_op(inputs)
307
+
308
+ return x, h
309
+
310
+
311
+ class Add(nn.Module):
312
+ def forward(self, a, b):
313
+ return a + b
314
+
315
+
316
+ class Concat(nn.Module):
317
+ def forward(self, a, b):
318
+ return torch.cat((a, b), dim=-1)
319
+
320
+
321
+ class Encoder(nn.Module):
322
+ def __init__(self, config: SpectrumDfNetConfig):
323
+ super(Encoder, self).__init__()
324
+ self.embedding_input_size = config.conv_channels * config.spec_bins // 4
325
+ self.embedding_output_size = config.conv_channels * config.spec_bins // 4
326
+ self.embedding_hidden_size = config.embedding_hidden_size
327
+
328
+ self.spec_conv0 = CausalConv2d(
329
+ in_channels=1,
330
+ out_channels=config.conv_channels,
331
+ kernel_size=config.conv_kernel_size_input,
332
+ bias=False,
333
+ separable=True,
334
+ fstride=1,
335
+ lookahead=config.conv_lookahead,
336
+ )
337
+ self.spec_conv1 = CausalConv2d(
338
+ in_channels=config.conv_channels,
339
+ out_channels=config.conv_channels,
340
+ kernel_size=config.conv_kernel_size_inner,
341
+ bias=False,
342
+ separable=True,
343
+ fstride=2,
344
+ lookahead=config.conv_lookahead,
345
+ )
346
+ self.spec_conv2 = CausalConv2d(
347
+ in_channels=config.conv_channels,
348
+ out_channels=config.conv_channels,
349
+ kernel_size=config.conv_kernel_size_inner,
350
+ bias=False,
351
+ separable=True,
352
+ fstride=2,
353
+ lookahead=config.conv_lookahead,
354
+ )
355
+ self.spec_conv3 = CausalConv2d(
356
+ in_channels=config.conv_channels,
357
+ out_channels=config.conv_channels,
358
+ kernel_size=config.conv_kernel_size_inner,
359
+ bias=False,
360
+ separable=True,
361
+ fstride=1,
362
+ lookahead=config.conv_lookahead,
363
+ )
364
+
365
+ self.df_conv0 = CausalConv2d(
366
+ in_channels=2,
367
+ out_channels=config.conv_channels,
368
+ kernel_size=config.conv_kernel_size_input,
369
+ bias=False,
370
+ separable=True,
371
+ )
372
+ self.df_conv1 = CausalConv2d(
373
+ in_channels=config.conv_channels,
374
+ out_channels=config.conv_channels,
375
+ kernel_size=config.conv_kernel_size_inner,
376
+ bias=False,
377
+ separable=True,
378
+ fstride=2,
379
+ )
380
+ self.df_fc_emb = nn.Sequential(
381
+ GroupedLinear(
382
+ config.conv_channels * config.df_bins // 2,
383
+ self.embedding_input_size,
384
+ groups=config.encoder_linear_groups
385
+ ),
386
+ nn.ReLU(inplace=True)
387
+ )
388
+
389
+ if config.encoder_combine_op == "concat":
390
+ self.embedding_input_size *= 2
391
+ self.combine = Concat()
392
+ else:
393
+ self.combine = Add()
394
+
395
+ # emb_gru
396
+ if config.spec_bins % 8 != 0:
397
+ raise AssertionError("spec_bins should be divisible by 8")
398
+
399
+ self.emb_gru = SqueezedGRU_S(
400
+ self.embedding_input_size,
401
+ self.embedding_hidden_size,
402
+ output_size=self.embedding_output_size,
403
+ num_layers=1,
404
+ batch_first=True,
405
+ skip_op=config.encoder_emb_skip_op,
406
+ linear_groups=config.encoder_emb_linear_groups,
407
+ activation_layer="relu",
408
+ )
409
+
410
+ # lsnr
411
+ self.lsnr_fc = nn.Sequential(
412
+ nn.Linear(self.embedding_output_size, 1),
413
+ nn.Sigmoid()
414
+ )
415
+ self.lsnr_scale = config.lsnr_max - config.lsnr_min
416
+ self.lsnr_offset = config.lsnr_min
417
+
418
+ def forward(self,
419
+ feat_power: torch.Tensor,
420
+ feat_spec: torch.Tensor,
421
+ hidden_state: torch.Tensor = None,
422
+ ):
423
+ # feat_power shape: (batch_size, 1, time_steps, spec_dim)
424
+ e0 = self.spec_conv0.forward(feat_power)
425
+ e1 = self.spec_conv1.forward(e0)
426
+ e2 = self.spec_conv2.forward(e1)
427
+ e3 = self.spec_conv3.forward(e2)
428
+ # e0 shape: [batch_size, channels, time_steps, spec_dim]
429
+ # e1 shape: [batch_size, channels, time_steps, spec_dim // 2]
430
+ # e2 shape: [batch_size, channels, time_steps, spec_dim // 4]
431
+ # e3 shape: [batch_size, channels, time_steps, spec_dim // 4]
432
+
433
+ # feat_spec, shape: (batch_size, 2, time_steps, df_bins)
434
+ c0 = self.df_conv0(feat_spec)
435
+ c1 = self.df_conv1(c0)
436
+ # c0 shape: [batch_size, channels, time_steps, df_bins]
437
+ # c1 shape: [batch_size, channels, time_steps, df_bins // 2]
438
+
439
+ cemb = c1.permute(0, 2, 3, 1)
440
+ # cemb shape: [batch_size, time_steps, df_bins // 2, channels]
441
+ cemb = cemb.flatten(2)
442
+ # cemb shape: [batch_size, time_steps, df_bins // 2 * channels]
443
+ cemb = self.df_fc_emb(cemb)
444
+ # cemb shape: [batch_size, time_steps, spec_dim // 4 * channels]
445
+
446
+ # e3 shape: [batch_size, channels, time_steps, spec_dim // 4]
447
+ emb = e3.permute(0, 2, 3, 1)
448
+ # emb shape: [batch_size, time_steps, spec_dim // 4, channels]
449
+ emb = emb.flatten(2)
450
+ # emb shape: [batch_size, time_steps, spec_dim // 4 * channels]
451
+
452
+ emb = self.combine(emb, cemb)
453
+ # if concat; emb shape: [batch_size, time_steps, spec_dim // 4 * channels * 2]
454
+ # if add; emb shape: [batch_size, time_steps, spec_dim // 4 * channels]
455
+
456
+ emb, h = self.emb_gru.forward(emb, hidden_state)
457
+ # emb shape: [batch_size, time_steps, spec_dim // 4 * channels]
458
+ # h shape: [batch_size, 1, spec_dim]
459
+
460
+ lsnr = self.lsnr_fc(emb) * self.lsnr_scale + self.lsnr_offset
461
+ # lsnr shape: [batch_size, time_steps, 1]
462
+
463
+ return e0, e1, e2, e3, emb, c0, lsnr, h
464
+
465
+
466
+ class Decoder(nn.Module):
467
+ def __init__(self, config: SpectrumDfNetConfig):
468
+ super(Decoder, self).__init__()
469
+
470
+ if config.spec_bins % 8 != 0:
471
+ raise AssertionError("spec_bins should be divisible by 8")
472
+
473
+ self.emb_in_dim = config.conv_channels * config.spec_bins // 4
474
+ self.emb_out_dim = config.conv_channels * config.spec_bins // 4
475
+ self.emb_hidden_dim = config.decoder_emb_hidden_size
476
+
477
+ self.emb_gru = SqueezedGRU_S(
478
+ self.emb_in_dim,
479
+ self.emb_hidden_dim,
480
+ output_size=self.emb_out_dim,
481
+ num_layers=config.decoder_emb_num_layers - 1,
482
+ batch_first=True,
483
+ skip_op=config.decoder_emb_skip_op,
484
+ linear_groups=config.decoder_emb_linear_groups,
485
+ activation_layer="relu",
486
+ )
487
+ self.conv3p = CausalConv2d(
488
+ in_channels=config.conv_channels,
489
+ out_channels=config.conv_channels,
490
+ kernel_size=1,
491
+ bias=False,
492
+ separable=True,
493
+ fstride=1,
494
+ lookahead=config.conv_lookahead,
495
+ )
496
+ self.convt3 = CausalConv2d(
497
+ in_channels=config.conv_channels,
498
+ out_channels=config.conv_channels,
499
+ kernel_size=config.conv_kernel_size_inner,
500
+ bias=False,
501
+ separable=True,
502
+ fstride=1,
503
+ lookahead=config.conv_lookahead,
504
+ )
505
+ self.conv2p = CausalConv2d(
506
+ in_channels=config.conv_channels,
507
+ out_channels=config.conv_channels,
508
+ kernel_size=1,
509
+ bias=False,
510
+ separable=True,
511
+ fstride=1,
512
+ lookahead=config.conv_lookahead,
513
+ )
514
+ self.convt2 = CausalConvTranspose2d(
515
+ in_channels=config.conv_channels,
516
+ out_channels=config.conv_channels,
517
+ kernel_size=config.convt_kernel_size_inner,
518
+ bias=False,
519
+ separable=True,
520
+ fstride=2,
521
+ lookahead=config.conv_lookahead,
522
+ )
523
+ self.conv1p = CausalConv2d(
524
+ in_channels=config.conv_channels,
525
+ out_channels=config.conv_channels,
526
+ kernel_size=1,
527
+ bias=False,
528
+ separable=True,
529
+ fstride=1,
530
+ lookahead=config.conv_lookahead,
531
+ )
532
+ self.convt1 = CausalConvTranspose2d(
533
+ in_channels=config.conv_channels,
534
+ out_channels=config.conv_channels,
535
+ kernel_size=config.convt_kernel_size_inner,
536
+ bias=False,
537
+ separable=True,
538
+ fstride=2,
539
+ lookahead=config.conv_lookahead,
540
+ )
541
+ self.conv0p = CausalConv2d(
542
+ in_channels=config.conv_channels,
543
+ out_channels=config.conv_channels,
544
+ kernel_size=1,
545
+ bias=False,
546
+ separable=True,
547
+ fstride=1,
548
+ lookahead=config.conv_lookahead,
549
+ )
550
+ self.conv0_out = CausalConv2d(
551
+ in_channels=config.conv_channels,
552
+ out_channels=1,
553
+ kernel_size=config.conv_kernel_size_inner,
554
+ activation_layer="sigmoid",
555
+ bias=False,
556
+ separable=True,
557
+ fstride=1,
558
+ lookahead=config.conv_lookahead,
559
+ )
560
+
561
+ def forward(self, emb, e3, e2, e1, e0) -> torch.Tensor:
562
+ # Estimates erb mask
563
+ b, _, t, f8 = e3.shape
564
+
565
+ # emb shape: [batch_size, time_steps, (freq_dim // 4) * conv_channels]
566
+ emb, _ = self.emb_gru(emb)
567
+ # emb shape: [batch_size, conv_channels, time_steps, freq_dim // 4]
568
+ emb = emb.view(b, t, f8, -1).permute(0, 3, 1, 2)
569
+ e3 = self.convt3(self.conv3p(e3) + emb)
570
+ # e3 shape: [batch_size, conv_channels, time_steps, freq_dim // 4]
571
+ e2 = self.convt2(self.conv2p(e2) + e3)
572
+ # e2 shape: [batch_size, conv_channels, time_steps, freq_dim // 2]
573
+ e1 = self.convt1(self.conv1p(e1) + e2)
574
+ # e1 shape: [batch_size, conv_channels, time_steps, freq_dim]
575
+ mask = self.conv0_out(self.conv0p(e0) + e1)
576
+ # mask shape: [batch_size, 1, time_steps, freq_dim]
577
+ return mask
578
+
579
+
580
+ class DfDecoder(nn.Module):
581
+ def __init__(self, config: SpectrumDfNetConfig):
582
+ super(DfDecoder, self).__init__()
583
+
584
+ self.embedding_input_size = config.conv_channels * config.spec_bins // 4
585
+ self.df_decoder_hidden_size = config.df_decoder_hidden_size
586
+ self.df_num_layers = config.df_num_layers
587
+
588
+ self.df_order = config.df_order
589
+
590
+ self.df_bins = config.df_bins
591
+ self.df_out_ch = config.df_order * 2
592
+
593
+ self.df_convp = CausalConv2d(
594
+ config.conv_channels,
595
+ self.df_out_ch,
596
+ fstride=1,
597
+ kernel_size=(config.df_pathway_kernel_size_t, 1),
598
+ separable=True,
599
+ bias=False,
600
+ )
601
+ self.df_gru = SqueezedGRU_S(
602
+ self.embedding_input_size,
603
+ self.df_decoder_hidden_size,
604
+ num_layers=self.df_num_layers,
605
+ batch_first=True,
606
+ skip_op="none",
607
+ activation_layer="relu",
608
+ )
609
+
610
+ if config.df_gru_skip == "none":
611
+ self.df_skip = None
612
+ elif config.df_gru_skip == "identity":
613
+ if config.embedding_hidden_size != config.df_decoder_hidden_size:
614
+ raise AssertionError("Dimensions do not match")
615
+ self.df_skip = nn.Identity()
616
+ elif config.df_gru_skip == "grouped_linear":
617
+ self.df_skip = GroupedLinear(
618
+ self.embedding_input_size,
619
+ self.df_decoder_hidden_size,
620
+ groups=config.df_decoder_linear_groups
621
+ )
622
+ else:
623
+ raise NotImplementedError()
624
+
625
+ self.df_out: nn.Module
626
+ out_dim = self.df_bins * self.df_out_ch
627
+
628
+ self.df_out = nn.Sequential(
629
+ GroupedLinear(
630
+ input_size=self.df_decoder_hidden_size,
631
+ hidden_size=out_dim,
632
+ groups=config.df_decoder_linear_groups
633
+ ),
634
+ nn.Tanh()
635
+ )
636
+ self.df_fc_a = nn.Sequential(
637
+ nn.Linear(self.df_decoder_hidden_size, 1),
638
+ nn.Sigmoid()
639
+ )
640
+
641
+ def forward(self, emb: torch.Tensor, c0: torch.Tensor) -> torch.Tensor:
642
+ # emb shape: [batch_size, time_steps, df_bins // 4 * channels]
643
+ b, t, _ = emb.shape
644
+ df_coefs, _ = self.df_gru(emb)
645
+ if self.df_skip is not None:
646
+ df_coefs = df_coefs + self.df_skip(emb)
647
+ # df_coefs shape: [batch_size, time_steps, df_decoder_hidden_size]
648
+
649
+ # c0 shape: [batch_size, channels, time_steps, df_bins]
650
+ c0 = self.df_convp(c0)
651
+ # c0 shape: [batch_size, df_order * 2, time_steps, df_bins]
652
+ c0 = c0.permute(0, 2, 3, 1)
653
+ # c0 shape: [batch_size, time_steps, df_bins, df_order * 2]
654
+
655
+ df_coefs = self.df_out(df_coefs) # [B, T, F*O*2], O: df_order
656
+ # df_coefs shape: [batch_size, time_steps, df_bins * df_order * 2]
657
+ df_coefs = df_coefs.view(b, t, self.df_bins, self.df_out_ch)
658
+ # df_coefs shape: [batch_size, time_steps, df_bins, df_order * 2]
659
+ df_coefs = df_coefs + c0
660
+ # df_coefs shape: [batch_size, time_steps, df_bins, df_order * 2]
661
+ return df_coefs
662
+
663
+
664
+ class DfOutputReshapeMF(nn.Module):
665
+ """Coefficients output reshape for multiframe/MultiFrameModule
666
+
667
+ Requires input of shape B, C, T, F, 2.
668
+ """
669
+
670
+ def __init__(self, df_order: int, df_bins: int):
671
+ super().__init__()
672
+ self.df_order = df_order
673
+ self.df_bins = df_bins
674
+
675
+ def forward(self, coefs: torch.Tensor) -> torch.Tensor:
676
+ # [B, T, F, O*2] -> [B, O, T, F, 2]
677
+ new_shape = list(coefs.shape)
678
+ new_shape[-1] = -1
679
+ new_shape.append(2)
680
+ coefs = coefs.view(new_shape)
681
+ coefs = coefs.permute(0, 3, 1, 2, 4)
682
+ return coefs
683
+
684
+
685
+ class Mask(nn.Module):
686
+ def __init__(self, use_post_filter: bool = False, eps: float = 1e-12):
687
+ super().__init__()
688
+ self.use_post_filter = use_post_filter
689
+ self.eps = eps
690
+
691
+ def post_filter(self, mask: torch.Tensor, beta: float = 0.02) -> torch.Tensor:
692
+ """
693
+ Post-Filter
694
+
695
+ A Perceptually-Motivated Approach for Low-Complexity, Real-Time Enhancement of Fullband Speech.
696
+ https://arxiv.org/abs/2008.04259
697
+
698
+ :param mask: Real valued mask, typically of shape [B, C, T, F].
699
+ :param beta: Global gain factor.
700
+ :return:
701
+ """
702
+ mask_sin = mask * torch.sin(np.pi * mask / 2)
703
+ mask_pf = (1 + beta) * mask / (1 + beta * mask.div(mask_sin.clamp_min(self.eps)).pow(2))
704
+ return mask_pf
705
+
706
+ def forward(self, spec: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
707
+ # spec shape: [batch_size, 1, time_steps, spec_bins, 2]
708
+
709
+ if not self.training and self.use_post_filter:
710
+ mask = self.post_filter(mask)
711
+
712
+ # mask shape: [batch_size, 1, time_steps, spec_bins]
713
+ mask = mask.unsqueeze(4)
714
+ # mask shape: [batch_size, 1, time_steps, spec_bins, 1]
715
+ return spec * mask
716
+
717
+
718
+ class DeepFiltering(nn.Module):
719
+ def __init__(self,
720
+ df_bins: int,
721
+ df_order: int,
722
+ lookahead: int = 0,
723
+ ):
724
+ super(DeepFiltering, self).__init__()
725
+ self.df_bins = df_bins
726
+ self.df_order = df_order
727
+ self.need_unfold = df_order > 1
728
+ self.lookahead = lookahead
729
+
730
+ self.pad = nn.ConstantPad2d((0, 0, df_order - 1 - lookahead, lookahead), 0.0)
731
+
732
+ def spec_unfold(self, spec: torch.Tensor):
733
+ """
734
+ Pads and unfolds the spectrogram according to frame_size.
735
+ :param spec: complex Tensor, Spectrogram of shape [B, C, T, F].
736
+ :return: Tensor, Unfolded spectrogram of shape [B, C, T, F, N], where N: frame_size.
737
+ """
738
+ if self.need_unfold:
739
+ # spec shape: [batch_size, spec_bins, time_steps]
740
+ spec_pad = self.pad(spec)
741
+ # spec_pad shape: [batch_size, 1, time_steps_pad, spec_bins]
742
+ spec_unfold = spec_pad.unfold(2, self.df_order, 1)
743
+ # spec_unfold shape: [batch_size, 1, time_steps, spec_bins, df_order]
744
+ return spec_unfold
745
+ else:
746
+ return spec.unsqueeze(-1)
747
+
748
+ def forward(self,
749
+ spec: torch.Tensor,
750
+ coefs: torch.Tensor,
751
+ ):
752
+ # spec shape: [batch_size, 1, time_steps, spec_bins, 2]
753
+ spec_u = self.spec_unfold(torch.view_as_complex(spec))
754
+ # spec_u shape: [batch_size, 1, time_steps, spec_bins, df_order]
755
+
756
+ # coefs shape: [batch_size, df_order, time_steps, df_bins, 2]
757
+ coefs = torch.view_as_complex(coefs)
758
+ # coefs shape: [batch_size, df_order, time_steps, df_bins]
759
+ spec_f = spec_u.narrow(-2, 0, self.df_bins)
760
+ # spec_f shape: [batch_size, 1, time_steps, df_bins, df_order]
761
+
762
+ coefs = coefs.view(coefs.shape[0], -1, self.df_order, *coefs.shape[2:])
763
+ # coefs shape: [batch_size, 1, df_order, time_steps, df_bins]
764
+
765
+ spec_f = self.df(spec_f, coefs)
766
+ # spec_f shape: [batch_size, 1, time_steps, df_bins]
767
+
768
+ if self.training:
769
+ spec = spec.clone()
770
+ spec[..., :self.df_bins, :] = torch.view_as_real(spec_f)
771
+ # spec shape: [batch_size, 1, time_steps, spec_bins, 2]
772
+ return spec
773
+
774
+ @staticmethod
775
+ def df(spec: torch.Tensor, coefs: torch.Tensor) -> torch.Tensor:
776
+ """
777
+ Deep filter implementation using `torch.einsum`. Requires unfolded spectrogram.
778
+ :param spec: (complex Tensor). Spectrogram of shape [B, C, T, F, N].
779
+ :param coefs: (complex Tensor). Coefficients of shape [B, C, N, T, F].
780
+ :return: (complex Tensor). Spectrogram of shape [B, C, T, F].
781
+ """
782
+ return torch.einsum("...tfn,...ntf->...tf", spec, coefs)
783
+
784
+
785
+ class SpectrumDfNet(nn.Module):
786
+ def __init__(self, config: SpectrumDfNetConfig):
787
+ super(SpectrumDfNet, self).__init__()
788
+ self.config = config
789
+ self.encoder = Encoder(config)
790
+ self.decoder = Decoder(config)
791
+
792
+ self.df_decoder = DfDecoder(config)
793
+ self.df_out_transform = DfOutputReshapeMF(config.df_order, config.df_bins)
794
+ self.df_op = DeepFiltering(
795
+ df_bins=config.df_bins,
796
+ df_order=config.df_order,
797
+ lookahead=config.df_lookahead,
798
+ )
799
+
800
+ self.mask = Mask(use_post_filter=config.use_post_filter)
801
+
802
+ def forward(self,
803
+ spec_complex: torch.Tensor,
804
+ ):
805
+ feat_power = torch.square(torch.abs(spec_complex))
806
+ feat_power = feat_power.unsqueeze(1).permute(0, 1, 3, 2)
807
+ # feat_power shape: [batch_size, spec_bins, time_steps]
808
+ # feat_power shape: [batch_size, 1, spec_bins, time_steps]
809
+ # feat_power shape: [batch_size, 1, time_steps, spec_bins]
810
+
811
+ # spec shape: [batch_size, spec_bins, time_steps]
812
+ feat_spec = torch.view_as_real(spec_complex)
813
+ # spec shape: [batch_size, spec_bins, time_steps, 2]
814
+ feat_spec = feat_spec.permute(0, 3, 2, 1)
815
+ # feat_spec shape: [batch_size, 2, time_steps, spec_bins]
816
+ feat_spec = feat_spec[..., :self.df_decoder.df_bins]
817
+ # feat_spec shape: [batch_size, 2, time_steps, df_bins]
818
+
819
+ # spec shape: [batch_size, spec_bins, time_steps]
820
+ spec = torch.unsqueeze(spec_complex, dim=1)
821
+ # spec shape: [batch_size, 1, spec_bins, time_steps]
822
+ spec = spec.permute(0, 1, 3, 2)
823
+ # spec shape: [batch_size, 1, time_steps, spec_bins]
824
+ spec = torch.view_as_real(spec)
825
+ # spec shape: [batch_size, 1, time_steps, spec_bins, 2]
826
+
827
+ e0, e1, e2, e3, emb, c0, lsnr, h = self.encoder.forward(feat_power, feat_spec)
828
+
829
+ mask = self.decoder.forward(emb, e3, e2, e1, e0)
830
+ # mask shape: [batch_size, 1, time_steps, spec_bins]
831
+ if torch.any(mask > 1) or torch.any(mask < 0):
832
+ raise AssertionError
833
+
834
+ spec_m = self.mask.forward(spec, mask)
835
+
836
+ # lsnr shape: [batch_size, time_steps, 1]
837
+ lsnr = torch.transpose(lsnr, dim0=2, dim1=1)
838
+ # lsnr shape: [batch_size, 1, time_steps]
839
+
840
+ df_coefs = self.df_decoder.forward(emb, c0)
841
+ df_coefs = self.df_out_transform(df_coefs)
842
+ # df_coefs shape: [batch_size, df_order, time_steps, df_bins, 2]
843
+
844
+ spec_e = self.df_op.forward(spec.clone(), df_coefs)
845
+ # spec_e shape: [batch_size, 1, time_steps, spec_bins, 2]
846
+
847
+ spec_e[..., self.df_decoder.df_bins:, :] = spec_m[..., self.df_decoder.df_bins:, :]
848
+ return spec_e, mask, lsnr
849
+
850
+
851
+ class SpectrumDfNetPretrainedModel(SpectrumDfNet):
852
+ def __init__(self,
853
+ config: SpectrumDfNetConfig,
854
+ ):
855
+ super(SpectrumDfNetPretrainedModel, self).__init__(
856
+ config=config,
857
+ )
858
+
859
+ @classmethod
860
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
861
+ config = SpectrumDfNetConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
862
+
863
+ model = cls(config)
864
+
865
+ if os.path.isdir(pretrained_model_name_or_path):
866
+ ckpt_file = os.path.join(pretrained_model_name_or_path, MODEL_FILE)
867
+ else:
868
+ ckpt_file = pretrained_model_name_or_path
869
+
870
+ with open(ckpt_file, "rb") as f:
871
+ state_dict = torch.load(f, map_location="cpu", weights_only=True)
872
+ model.load_state_dict(state_dict, strict=True)
873
+ return model
874
+
875
+ def save_pretrained(self,
876
+ save_directory: Union[str, os.PathLike],
877
+ state_dict: Optional[dict] = None,
878
+ ):
879
+
880
+ model = self
881
+
882
+ if state_dict is None:
883
+ state_dict = model.state_dict()
884
+
885
+ os.makedirs(save_directory, exist_ok=True)
886
+
887
+ # save state dict
888
+ model_file = os.path.join(save_directory, MODEL_FILE)
889
+ torch.save(state_dict, model_file)
890
+
891
+ # save config
892
+ config_file = os.path.join(save_directory, CONFIG_FILE)
893
+ self.config.to_yaml_file(config_file)
894
+ return save_directory
895
+
896
+
897
+ def main():
898
+
899
+ transformer = torchaudio.transforms.Spectrogram(
900
+ n_fft=512,
901
+ win_length=200,
902
+ hop_length=80,
903
+ window_fn=torch.hamming_window,
904
+ power=None,
905
+ )
906
+
907
+ config = SpectrumDfNetConfig()
908
+ model = SpectrumDfNet(config=config)
909
+
910
+ inputs = torch.randn(size=(1, 16000), dtype=torch.float32)
911
+ spec_complex = transformer.forward(inputs)
912
+ spec_complex = spec_complex[:, :-1, :]
913
+
914
+ output = model.forward(spec_complex)
915
+ print(output[0].shape)
916
+ return
917
+
918
+
919
+ if __name__ == '__main__':
920
+ main()