Kangarroar commited on
Commit
d5e0750
·
1 Parent(s): dcf7507

Delete utils

Browse files
utils/__init__.py DELETED
@@ -1,250 +0,0 @@
1
- import glob
2
- import logging
3
- import re
4
- import time
5
- from collections import defaultdict
6
- import os
7
- import sys
8
- import shutil
9
- import types
10
- import numpy as np
11
- import torch
12
- import torch.nn.functional as F
13
- import torch.distributed as dist
14
- from torch import nn
15
-
16
-
17
- def tensors_to_scalars(metrics):
18
- new_metrics = {}
19
- for k, v in metrics.items():
20
- if isinstance(v, torch.Tensor):
21
- v = v.item()
22
- if type(v) is dict:
23
- v = tensors_to_scalars(v)
24
- new_metrics[k] = v
25
- return new_metrics
26
-
27
-
28
- class AvgrageMeter(object):
29
-
30
- def __init__(self):
31
- self.reset()
32
-
33
- def reset(self):
34
- self.avg = 0
35
- self.sum = 0
36
- self.cnt = 0
37
-
38
- def update(self, val, n=1):
39
- self.sum += val * n
40
- self.cnt += n
41
- self.avg = self.sum / self.cnt
42
-
43
-
44
- def collate_1d(values, pad_idx=0, left_pad=False, shift_right=False, max_len=None, shift_id=1):
45
- """Convert a list of 1d tensors into a padded 2d tensor."""
46
- size = max(v.size(0) for v in values) if max_len is None else max_len
47
- res = values[0].new(len(values), size).fill_(pad_idx)
48
-
49
- def copy_tensor(src, dst):
50
- assert dst.numel() == src.numel()
51
- if shift_right:
52
- dst[1:] = src[:-1]
53
- dst[0] = shift_id
54
- else:
55
- dst.copy_(src)
56
-
57
- for i, v in enumerate(values):
58
- copy_tensor(v, res[i][size - len(v):] if left_pad else res[i][:len(v)])
59
- return res
60
-
61
-
62
- def collate_2d(values, pad_idx=0, left_pad=False, shift_right=False, max_len=None):
63
- """Convert a list of 2d tensors into a padded 3d tensor."""
64
- size = max(v.size(0) for v in values) if max_len is None else max_len
65
- res = values[0].new(len(values), size, values[0].shape[1]).fill_(pad_idx)
66
-
67
- def copy_tensor(src, dst):
68
- assert dst.numel() == src.numel()
69
- if shift_right:
70
- dst[1:] = src[:-1]
71
- else:
72
- dst.copy_(src)
73
-
74
- for i, v in enumerate(values):
75
- copy_tensor(v, res[i][size - len(v):] if left_pad else res[i][:len(v)])
76
- return res
77
-
78
-
79
- def _is_batch_full(batch, num_tokens, max_tokens, max_sentences):
80
- if len(batch) == 0:
81
- return 0
82
- if len(batch) == max_sentences:
83
- return 1
84
- if num_tokens > max_tokens:
85
- return 1
86
- return 0
87
-
88
-
89
- def batch_by_size(
90
- indices, num_tokens_fn, max_tokens=None, max_sentences=None,
91
- required_batch_size_multiple=1, distributed=False
92
- ):
93
- """
94
- Yield mini-batches of indices bucketed by size. Batches may contain
95
- sequences of different lengths.
96
-
97
- Args:
98
- indices (List[int]): ordered list of dataset indices
99
- num_tokens_fn (callable): function that returns the number of tokens at
100
- a given index
101
- max_tokens (int, optional): max number of tokens in each batch
102
- (default: None).
103
- max_sentences (int, optional): max number of sentences in each
104
- batch (default: None).
105
- required_batch_size_multiple (int, optional): require batch size to
106
- be a multiple of N (default: 1).
107
- """
108
- max_tokens = max_tokens if max_tokens is not None else sys.maxsize
109
- max_sentences = max_sentences if max_sentences is not None else sys.maxsize
110
- bsz_mult = required_batch_size_multiple
111
-
112
- if isinstance(indices, types.GeneratorType):
113
- indices = np.fromiter(indices, dtype=np.int64, count=-1)
114
-
115
- sample_len = 0
116
- sample_lens = []
117
- batch = []
118
- batches = []
119
- for i in range(len(indices)):
120
- idx = indices[i]
121
- num_tokens = num_tokens_fn(idx)
122
- sample_lens.append(num_tokens)
123
- sample_len = max(sample_len, num_tokens)
124
- assert sample_len <= max_tokens, (
125
- "sentence at index {} of size {} exceeds max_tokens "
126
- "limit of {}!".format(idx, sample_len, max_tokens)
127
- )
128
- num_tokens = (len(batch) + 1) * sample_len
129
-
130
- if _is_batch_full(batch, num_tokens, max_tokens, max_sentences):
131
- mod_len = max(
132
- bsz_mult * (len(batch) // bsz_mult),
133
- len(batch) % bsz_mult,
134
- )
135
- batches.append(batch[:mod_len])
136
- batch = batch[mod_len:]
137
- sample_lens = sample_lens[mod_len:]
138
- sample_len = max(sample_lens) if len(sample_lens) > 0 else 0
139
- batch.append(idx)
140
- if len(batch) > 0:
141
- batches.append(batch)
142
- return batches
143
-
144
-
145
- def make_positions(tensor, padding_idx):
146
- """Replace non-padding symbols with their position numbers.
147
-
148
- Position numbers begin at padding_idx+1. Padding symbols are ignored.
149
- """
150
- # The series of casts and type-conversions here are carefully
151
- # balanced to both work with ONNX export and XLA. In particular XLA
152
- # prefers ints, cumsum defaults to output longs, and ONNX doesn't know
153
- # how to handle the dtype kwarg in cumsum.
154
- mask = tensor.ne(padding_idx).int()
155
- return (
156
- torch.cumsum(mask, dim=1).type_as(mask) * mask
157
- ).long() + padding_idx
158
-
159
-
160
- def softmax(x, dim):
161
- return F.softmax(x, dim=dim, dtype=torch.float32)
162
-
163
-
164
- def unpack_dict_to_list(samples):
165
- samples_ = []
166
- bsz = samples.get('outputs').size(0)
167
- for i in range(bsz):
168
- res = {}
169
- for k, v in samples.items():
170
- try:
171
- res[k] = v[i]
172
- except:
173
- pass
174
- samples_.append(res)
175
- return samples_
176
-
177
-
178
- def load_ckpt(cur_model, ckpt_base_dir, prefix_in_ckpt='model', force=True, strict=True):
179
- if os.path.isfile(ckpt_base_dir):
180
- base_dir = os.path.dirname(ckpt_base_dir)
181
- checkpoint_path = [ckpt_base_dir]
182
- else:
183
- base_dir = ckpt_base_dir
184
- checkpoint_path = sorted(glob.glob(f'{base_dir}/model_ckpt_steps_*.ckpt'), key=
185
- lambda x: int(re.findall(f'{base_dir}/model_ckpt_steps_(\d+).ckpt', x.replace('\\','/'))[0]))
186
- if len(checkpoint_path) > 0:
187
- checkpoint_path = checkpoint_path[-1]
188
- state_dict = torch.load(checkpoint_path, map_location="cpu")["state_dict"]
189
- state_dict = {k[len(prefix_in_ckpt) + 1:]: v for k, v in state_dict.items()
190
- if k.startswith(f'{prefix_in_ckpt}.')}
191
- if not strict:
192
- cur_model_state_dict = cur_model.state_dict()
193
- unmatched_keys = []
194
- for key, param in state_dict.items():
195
- if key in cur_model_state_dict:
196
- new_param = cur_model_state_dict[key]
197
- if new_param.shape != param.shape:
198
- unmatched_keys.append(key)
199
- print("| Unmatched keys: ", key, new_param.shape, param.shape)
200
- for key in unmatched_keys:
201
- del state_dict[key]
202
- cur_model.load_state_dict(state_dict, strict=strict)
203
- print(f"| load '{prefix_in_ckpt}' from '{checkpoint_path}'.")
204
- else:
205
- e_msg = f"| ckpt not found in {base_dir}."
206
- if force:
207
- assert False, e_msg
208
- else:
209
- print(e_msg)
210
-
211
-
212
- def remove_padding(x, padding_idx=0):
213
- if x is None:
214
- return None
215
- assert len(x.shape) in [1, 2]
216
- if len(x.shape) == 2: # [T, H]
217
- return x[np.abs(x).sum(-1) != padding_idx]
218
- elif len(x.shape) == 1: # [T]
219
- return x[x != padding_idx]
220
-
221
-
222
- class Timer:
223
- timer_map = {}
224
-
225
- def __init__(self, name, print_time=False):
226
- if name not in Timer.timer_map:
227
- Timer.timer_map[name] = 0
228
- self.name = name
229
- self.print_time = print_time
230
-
231
- def __enter__(self):
232
- self.t = time.time()
233
-
234
- def __exit__(self, exc_type, exc_val, exc_tb):
235
- Timer.timer_map[self.name] += time.time() - self.t
236
- if self.print_time:
237
- print(self.name, Timer.timer_map[self.name])
238
-
239
-
240
- def print_arch(model, model_name='model'):
241
- #print(f"| {model_name} Arch: ", model)
242
- num_params(model, model_name=model_name)
243
-
244
-
245
- def num_params(model, print_out=True, model_name="model"):
246
- parameters = filter(lambda p: p.requires_grad, model.parameters())
247
- parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000
248
- if print_out:
249
- print(f'| {model_name} Trainable Parameters: %.3fM' % parameters)
250
- return parameters
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (8.59 kB)
 
utils/__pycache__/audio.cpython-38.pyc DELETED
Binary file (1.89 kB)
 
utils/__pycache__/cwt.cpython-38.pyc DELETED
Binary file (3.92 kB)
 
utils/__pycache__/hparams.cpython-38.pyc DELETED
Binary file (3.77 kB)
 
utils/__pycache__/indexed_datasets.cpython-38.pyc DELETED
Binary file (3.11 kB)
 
utils/__pycache__/multiprocess_utils.cpython-38.pyc DELETED
Binary file (1.42 kB)
 
utils/__pycache__/pitch_utils.cpython-38.pyc DELETED
Binary file (1.97 kB)
 
utils/__pycache__/pl_utils.cpython-38.pyc DELETED
Binary file (33.9 kB)
 
utils/__pycache__/plot.cpython-38.pyc DELETED
Binary file (2.2 kB)
 
utils/__pycache__/text_encoder.cpython-38.pyc DELETED
Binary file (12.2 kB)
 
utils/__pycache__/training_utils.cpython-38.pyc DELETED
Binary file (1.27 kB)
 
utils/audio.py DELETED
@@ -1,56 +0,0 @@
1
- import subprocess
2
- import matplotlib
3
-
4
- matplotlib.use('Agg')
5
- import librosa
6
- import librosa.filters
7
- import numpy as np
8
- from scipy import signal
9
- from scipy.io import wavfile
10
-
11
-
12
- def save_wav(wav, path, sr, norm=False):
13
- if norm:
14
- wav = wav / np.abs(wav).max()
15
- wav *= 32767
16
- # proposed by @dsmiller
17
- wavfile.write(path, sr, wav.astype(np.int16))
18
-
19
-
20
- def get_hop_size(hparams):
21
- hop_size = hparams['hop_size']
22
- if hop_size is None:
23
- assert hparams['frame_shift_ms'] is not None
24
- hop_size = int(hparams['frame_shift_ms'] / 1000 * hparams['audio_sample_rate'])
25
- return hop_size
26
-
27
-
28
- ###########################################################################################
29
- def _stft(y, hparams):
30
- return librosa.stft(y=y, n_fft=hparams['fft_size'], hop_length=get_hop_size(hparams),
31
- win_length=hparams['win_size'], pad_mode='constant')
32
-
33
-
34
- def _istft(y, hparams):
35
- return librosa.istft(y, hop_length=get_hop_size(hparams), win_length=hparams['win_size'])
36
-
37
-
38
- def librosa_pad_lr(x, fsize, fshift, pad_sides=1):
39
- '''compute right padding (final frame) or both sides padding (first and final frames)
40
- '''
41
- assert pad_sides in (1, 2)
42
- # return int(fsize // 2)
43
- pad = (x.shape[0] // fshift + 1) * fshift - x.shape[0]
44
- if pad_sides == 1:
45
- return 0, pad
46
- else:
47
- return pad // 2, pad // 2 + pad % 2
48
-
49
-
50
- # Conversions
51
- def amp_to_db(x):
52
- return 20 * np.log10(np.maximum(1e-5, x))
53
-
54
-
55
- def normalize(S, hparams):
56
- return (S - hparams['min_level_db']) / -hparams['min_level_db']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/cwt.py DELETED
@@ -1,146 +0,0 @@
1
- import librosa
2
- import numpy as np
3
- from pycwt import wavelet
4
- from scipy.interpolate import interp1d
5
-
6
-
7
- def load_wav(wav_file, sr):
8
- wav, _ = librosa.load(wav_file, sr=sr, mono=True)
9
- return wav
10
-
11
-
12
- def convert_continuos_f0(f0):
13
- '''CONVERT F0 TO CONTINUOUS F0
14
- Args:
15
- f0 (ndarray): original f0 sequence with the shape (T)
16
- Return:
17
- (ndarray): continuous f0 with the shape (T)
18
- '''
19
- # get uv information as binary
20
- f0 = np.copy(f0)
21
- uv = np.float32(f0 != 0)
22
-
23
- # get start and end of f0
24
- if (f0 == 0).all():
25
- print("| all of the f0 values are 0.")
26
- return uv, f0
27
- start_f0 = f0[f0 != 0][0]
28
- end_f0 = f0[f0 != 0][-1]
29
-
30
- # padding start and end of f0 sequence
31
- start_idx = np.where(f0 == start_f0)[0][0]
32
- end_idx = np.where(f0 == end_f0)[0][-1]
33
- f0[:start_idx] = start_f0
34
- f0[end_idx:] = end_f0
35
-
36
- # get non-zero frame index
37
- nz_frames = np.where(f0 != 0)[0]
38
-
39
- # perform linear interpolation
40
- f = interp1d(nz_frames, f0[nz_frames])
41
- cont_f0 = f(np.arange(0, f0.shape[0]))
42
-
43
- return uv, cont_f0
44
-
45
-
46
- def get_cont_lf0(f0, frame_period=5.0):
47
- uv, cont_f0_lpf = convert_continuos_f0(f0)
48
- # cont_f0_lpf = low_pass_filter(cont_f0_lpf, int(1.0 / (frame_period * 0.001)), cutoff=20)
49
- cont_lf0_lpf = np.log(cont_f0_lpf)
50
- return uv, cont_lf0_lpf
51
-
52
-
53
- def get_lf0_cwt(lf0):
54
- '''
55
- input:
56
- signal of shape (N)
57
- output:
58
- Wavelet_lf0 of shape(10, N), scales of shape(10)
59
- '''
60
- mother = wavelet.MexicanHat()
61
- dt = 0.005
62
- dj = 1
63
- s0 = dt * 2
64
- J = 9
65
-
66
- Wavelet_lf0, scales, _, _, _, _ = wavelet.cwt(np.squeeze(lf0), dt, dj, s0, J, mother)
67
- # Wavelet.shape => (J + 1, len(lf0))
68
- Wavelet_lf0 = np.real(Wavelet_lf0).T
69
- return Wavelet_lf0, scales
70
-
71
-
72
- def norm_scale(Wavelet_lf0):
73
- Wavelet_lf0_norm = np.zeros((Wavelet_lf0.shape[0], Wavelet_lf0.shape[1]))
74
- mean = Wavelet_lf0.mean(0)[None, :]
75
- std = Wavelet_lf0.std(0)[None, :]
76
- Wavelet_lf0_norm = (Wavelet_lf0 - mean) / std
77
- return Wavelet_lf0_norm, mean, std
78
-
79
-
80
- def normalize_cwt_lf0(f0, mean, std):
81
- uv, cont_lf0_lpf = get_cont_lf0(f0)
82
- cont_lf0_norm = (cont_lf0_lpf - mean) / std
83
- Wavelet_lf0, scales = get_lf0_cwt(cont_lf0_norm)
84
- Wavelet_lf0_norm, _, _ = norm_scale(Wavelet_lf0)
85
-
86
- return Wavelet_lf0_norm
87
-
88
-
89
- def get_lf0_cwt_norm(f0s, mean, std):
90
- uvs = list()
91
- cont_lf0_lpfs = list()
92
- cont_lf0_lpf_norms = list()
93
- Wavelet_lf0s = list()
94
- Wavelet_lf0s_norm = list()
95
- scaless = list()
96
-
97
- means = list()
98
- stds = list()
99
- for f0 in f0s:
100
- uv, cont_lf0_lpf = get_cont_lf0(f0)
101
- cont_lf0_lpf_norm = (cont_lf0_lpf - mean) / std
102
-
103
- Wavelet_lf0, scales = get_lf0_cwt(cont_lf0_lpf_norm) # [560,10]
104
- Wavelet_lf0_norm, mean_scale, std_scale = norm_scale(Wavelet_lf0) # [560,10],[1,10],[1,10]
105
-
106
- Wavelet_lf0s_norm.append(Wavelet_lf0_norm)
107
- uvs.append(uv)
108
- cont_lf0_lpfs.append(cont_lf0_lpf)
109
- cont_lf0_lpf_norms.append(cont_lf0_lpf_norm)
110
- Wavelet_lf0s.append(Wavelet_lf0)
111
- scaless.append(scales)
112
- means.append(mean_scale)
113
- stds.append(std_scale)
114
-
115
- return Wavelet_lf0s_norm, scaless, means, stds
116
-
117
-
118
- def inverse_cwt_torch(Wavelet_lf0, scales):
119
- import torch
120
- b = ((torch.arange(0, len(scales)).float().to(Wavelet_lf0.device)[None, None, :] + 1 + 2.5) ** (-2.5))
121
- lf0_rec = Wavelet_lf0 * b
122
- lf0_rec_sum = lf0_rec.sum(-1)
123
- lf0_rec_sum = (lf0_rec_sum - lf0_rec_sum.mean(-1, keepdim=True)) / lf0_rec_sum.std(-1, keepdim=True)
124
- return lf0_rec_sum
125
-
126
-
127
- def inverse_cwt(Wavelet_lf0, scales):
128
- b = ((np.arange(0, len(scales))[None, None, :] + 1 + 2.5) ** (-2.5))
129
- lf0_rec = Wavelet_lf0 * b
130
- lf0_rec_sum = lf0_rec.sum(-1)
131
- lf0_rec_sum = (lf0_rec_sum - lf0_rec_sum.mean(-1, keepdims=True)) / lf0_rec_sum.std(-1, keepdims=True)
132
- return lf0_rec_sum
133
-
134
-
135
- def cwt2f0(cwt_spec, mean, std, cwt_scales):
136
- assert len(mean.shape) == 1 and len(std.shape) == 1 and len(cwt_spec.shape) == 3
137
- import torch
138
- if isinstance(cwt_spec, torch.Tensor):
139
- f0 = inverse_cwt_torch(cwt_spec, cwt_scales)
140
- f0 = f0 * std[:, None] + mean[:, None]
141
- f0 = f0.exp() # [B, T]
142
- else:
143
- f0 = inverse_cwt(cwt_spec, cwt_scales)
144
- f0 = f0 * std[:, None] + mean[:, None]
145
- f0 = np.exp(f0) # [B, T]
146
- return f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/hparams.py DELETED
@@ -1,131 +0,0 @@
1
- import argparse
2
- import os
3
- import yaml
4
-
5
- global_print_hparams = True
6
- hparams = {}
7
-
8
-
9
- class Args:
10
- def __init__(self, **kwargs):
11
- for k, v in kwargs.items():
12
- self.__setattr__(k, v)
13
-
14
-
15
- def override_config(old_config: dict, new_config: dict):
16
- for k, v in new_config.items():
17
- if isinstance(v, dict) and k in old_config:
18
- override_config(old_config[k], new_config[k])
19
- else:
20
- old_config[k] = v
21
-
22
-
23
- def set_hparams(config='', exp_name='', hparams_str='', print_hparams=True, global_hparams=True,reset=True,infer=True):
24
- '''
25
- Load hparams from multiple sources:
26
- 1. config chain (i.e. first load base_config, then load config);
27
- 2. if reset == True, load from the (auto-saved) complete config file ('config.yaml')
28
- which contains all settings and do not rely on base_config;
29
- 3. load from argument --hparams or hparams_str, as temporary modification.
30
- '''
31
- if config == '':
32
- parser = argparse.ArgumentParser(description='neural music')
33
- parser.add_argument('--config', type=str, default='',
34
- help='location of the data corpus')
35
- parser.add_argument('--exp_name', type=str, default='', help='exp_name')
36
- parser.add_argument('--hparams', type=str, default='',
37
- help='location of the data corpus')
38
- parser.add_argument('--infer', action='store_true', help='infer')
39
- parser.add_argument('--validate', action='store_true', help='validate')
40
- parser.add_argument('--reset', action='store_true', help='reset hparams')
41
- parser.add_argument('--debug', action='store_true', help='debug')
42
- args, unknown = parser.parse_known_args()
43
- else:
44
- args = Args(config=config, exp_name=exp_name, hparams=hparams_str,
45
- infer=infer, validate=False, reset=reset, debug=False)
46
- args_work_dir = ''
47
- if args.exp_name != '':
48
- args.work_dir = args.exp_name
49
- args_work_dir = f'checkpoints/{args.work_dir}'
50
-
51
- config_chains = []
52
- loaded_config = set()
53
-
54
- def load_config(config_fn): # deep first
55
- with open(config_fn, encoding='utf-8') as f:
56
- hparams_ = yaml.safe_load(f)
57
- loaded_config.add(config_fn)
58
- if 'base_config' in hparams_:
59
- ret_hparams = {}
60
- if not isinstance(hparams_['base_config'], list):
61
- hparams_['base_config'] = [hparams_['base_config']]
62
- for c in hparams_['base_config']:
63
- if c not in loaded_config:
64
- if c.startswith('.'):
65
- c = f'{os.path.dirname(config_fn)}/{c}'
66
- c = os.path.normpath(c)
67
- override_config(ret_hparams, load_config(c))
68
- override_config(ret_hparams, hparams_)
69
- else:
70
- ret_hparams = hparams_
71
- config_chains.append(config_fn)
72
- return ret_hparams
73
-
74
- global hparams
75
- assert args.config != '' or args_work_dir != ''
76
- saved_hparams = {}
77
- if args_work_dir != 'checkpoints/':
78
- ckpt_config_path = f'{args_work_dir}/config.yaml'
79
- if os.path.exists(ckpt_config_path):
80
- try:
81
- with open(ckpt_config_path, encoding='utf-8') as f:
82
- saved_hparams.update(yaml.safe_load(f))
83
- except:
84
- pass
85
- if args.config == '':
86
- args.config = ckpt_config_path
87
-
88
- hparams_ = {}
89
-
90
- hparams_.update(load_config(args.config))
91
-
92
- if not args.reset:
93
- hparams_.update(saved_hparams)
94
- hparams_['work_dir'] = args_work_dir
95
-
96
- if args.hparams != "":
97
- for new_hparam in args.hparams.split(","):
98
- k, v = new_hparam.split("=")
99
- if k not in hparams_:
100
- hparams_[k] = eval(v)
101
- if v in ['True', 'False'] or type(hparams_[k]) == bool:
102
- hparams_[k] = eval(v)
103
- else:
104
- hparams_[k] = type(hparams_[k])(v)
105
-
106
- if args_work_dir != '' and (not os.path.exists(ckpt_config_path) or args.reset) and not args.infer:
107
- os.makedirs(hparams_['work_dir'], exist_ok=True)
108
- with open(ckpt_config_path, 'w', encoding='utf-8') as f:
109
- yaml.safe_dump(hparams_, f)
110
-
111
- hparams_['infer'] = args.infer
112
- hparams_['debug'] = args.debug
113
- hparams_['validate'] = args.validate
114
- global global_print_hparams
115
- if global_hparams:
116
- hparams.clear()
117
- hparams.update(hparams_)
118
-
119
- if print_hparams and global_print_hparams and global_hparams:
120
- print('| Hparams chains: ', config_chains)
121
- print('| Hparams: ')
122
- for i, (k, v) in enumerate(sorted(hparams_.items())):
123
- print(f"\033[;33;m{k}\033[0m: {v}, ", end="\n" if i % 5 == 4 else "")
124
- print("")
125
- global_print_hparams = False
126
- # print(hparams_.keys())
127
- if hparams.get('exp_name') is None:
128
- hparams['exp_name'] = args.exp_name
129
- if hparams_.get('exp_name') is None:
130
- hparams_['exp_name'] = args.exp_name
131
- return hparams_
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/indexed_datasets.py DELETED
@@ -1,71 +0,0 @@
1
- import pickle
2
- from copy import deepcopy
3
-
4
- import numpy as np
5
-
6
-
7
- class IndexedDataset:
8
- def __init__(self, path, num_cache=1):
9
- super().__init__()
10
- self.path = path
11
- self.data_file = None
12
- self.data_offsets = np.load(f"{path}.idx", allow_pickle=True).item()['offsets']
13
- self.data_file = open(f"{path}.data", 'rb', buffering=-1)
14
- self.cache = []
15
- self.num_cache = num_cache
16
-
17
- def check_index(self, i):
18
- if i < 0 or i >= len(self.data_offsets) - 1:
19
- raise IndexError('index out of range')
20
-
21
- def __del__(self):
22
- if self.data_file:
23
- self.data_file.close()
24
-
25
- def __getitem__(self, i):
26
- self.check_index(i)
27
- if self.num_cache > 0:
28
- for c in self.cache:
29
- if c[0] == i:
30
- return c[1]
31
- self.data_file.seek(self.data_offsets[i])
32
- b = self.data_file.read(self.data_offsets[i + 1] - self.data_offsets[i])
33
- item = pickle.loads(b)
34
- if self.num_cache > 0:
35
- self.cache = [(i, deepcopy(item))] + self.cache[:-1]
36
- return item
37
-
38
- def __len__(self):
39
- return len(self.data_offsets) - 1
40
-
41
- class IndexedDatasetBuilder:
42
- def __init__(self, path):
43
- self.path = path
44
- self.out_file = open(f"{path}.data", 'wb')
45
- self.byte_offsets = [0]
46
-
47
- def add_item(self, item):
48
- s = pickle.dumps(item)
49
- bytes = self.out_file.write(s)
50
- self.byte_offsets.append(self.byte_offsets[-1] + bytes)
51
-
52
- def finalize(self):
53
- self.out_file.close()
54
- np.save(open(f"{self.path}.idx", 'wb'), {'offsets': self.byte_offsets})
55
-
56
-
57
- if __name__ == "__main__":
58
- import random
59
- from tqdm import tqdm
60
- ds_path = '/tmp/indexed_ds_example'
61
- size = 100
62
- items = [{"a": np.random.normal(size=[10000, 10]),
63
- "b": np.random.normal(size=[10000, 10])} for i in range(size)]
64
- builder = IndexedDatasetBuilder(ds_path)
65
- for i in tqdm(range(size)):
66
- builder.add_item(items[i])
67
- builder.finalize()
68
- ds = IndexedDataset(ds_path)
69
- for i in tqdm(range(10000)):
70
- idx = random.randint(0, size - 1)
71
- assert (ds[idx]['a'] == items[idx]['a']).all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/multiprocess_utils.py DELETED
@@ -1,47 +0,0 @@
1
- import os
2
- import traceback
3
- from multiprocessing import Queue, Process
4
-
5
-
6
- def chunked_worker(worker_id, map_func, args, results_queue=None, init_ctx_func=None):
7
- ctx = init_ctx_func(worker_id) if init_ctx_func is not None else None
8
- for job_idx, arg in args:
9
- try:
10
- if ctx is not None:
11
- res = map_func(*arg, ctx=ctx)
12
- else:
13
- res = map_func(*arg)
14
- results_queue.put((job_idx, res))
15
- except:
16
- traceback.print_exc()
17
- results_queue.put((job_idx, None))
18
-
19
- def chunked_multiprocess_run(map_func, args, num_workers=None, ordered=True, init_ctx_func=None, q_max_size=1000):
20
- args = zip(range(len(args)), args)
21
- args = list(args)
22
- n_jobs = len(args)
23
- if num_workers is None:
24
- num_workers = int(os.getenv('N_PROC', os.cpu_count()))
25
- results_queues = []
26
- if ordered:
27
- for i in range(num_workers):
28
- results_queues.append(Queue(maxsize=q_max_size // num_workers))
29
- else:
30
- results_queue = Queue(maxsize=q_max_size)
31
- for i in range(num_workers):
32
- results_queues.append(results_queue)
33
- workers = []
34
- for i in range(num_workers):
35
- args_worker = args[i::num_workers]
36
- p = Process(target=chunked_worker, args=(
37
- i, map_func, args_worker, results_queues[i], init_ctx_func), daemon=True)
38
- workers.append(p)
39
- p.start()
40
- for n_finished in range(n_jobs):
41
- results_queue = results_queues[n_finished % num_workers]
42
- job_idx, res = results_queue.get()
43
- assert job_idx == n_finished or not ordered, (job_idx, n_finished)
44
- yield res
45
- for w in workers:
46
- w.join()
47
- w.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/pitch_utils.py DELETED
@@ -1,76 +0,0 @@
1
- #########
2
- # world
3
- ##########
4
- import librosa
5
- import numpy as np
6
- import torch
7
-
8
- # gamma = 0
9
- # mcepInput = 3 # 0 for dB, 3 for magnitude
10
- # alpha = 0.45
11
- # en_floor = 10 ** (-80 / 20)
12
- # FFT_SIZE = 2048
13
-
14
-
15
-
16
-
17
- def f0_to_coarse(f0,hparams):
18
- f0_bin = hparams['f0_bin']
19
- f0_max = hparams['f0_max']
20
- f0_min = hparams['f0_min']
21
- is_torch = isinstance(f0, torch.Tensor)
22
- f0_mel_min = 1127 * np.log(1 + f0_min / 700)
23
- f0_mel_max = 1127 * np.log(1 + f0_max / 700)
24
- f0_mel = 1127 * (1 + f0 / 700).log() if is_torch else 1127 * np.log(1 + f0 / 700)
25
- f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * (f0_bin - 2) / (f0_mel_max - f0_mel_min) + 1
26
-
27
- f0_mel[f0_mel <= 1] = 1
28
- f0_mel[f0_mel > f0_bin - 1] = f0_bin - 1
29
- f0_coarse = (f0_mel + 0.5).long() if is_torch else np.rint(f0_mel).astype(int)
30
- assert f0_coarse.max() <= 255 and f0_coarse.min() >= 1, (f0_coarse.max(), f0_coarse.min())
31
- return f0_coarse
32
-
33
-
34
- def norm_f0(f0, uv, hparams):
35
- is_torch = isinstance(f0, torch.Tensor)
36
- if hparams['pitch_norm'] == 'standard':
37
- f0 = (f0 - hparams['f0_mean']) / hparams['f0_std']
38
- if hparams['pitch_norm'] == 'log':
39
- f0 = torch.log2(f0) if is_torch else np.log2(f0)
40
- if uv is not None and hparams['use_uv']:
41
- f0[uv > 0] = 0
42
- return f0
43
-
44
-
45
- def norm_interp_f0(f0, hparams):
46
- is_torch = isinstance(f0, torch.Tensor)
47
- if is_torch:
48
- device = f0.device
49
- f0 = f0.data.cpu().numpy()
50
- uv = f0 == 0
51
- f0 = norm_f0(f0, uv, hparams)
52
- if sum(uv) == len(f0):
53
- f0[uv] = 0
54
- elif sum(uv) > 0:
55
- f0[uv] = np.interp(np.where(uv)[0], np.where(~uv)[0], f0[~uv])
56
- uv = torch.FloatTensor(uv)
57
- f0 = torch.FloatTensor(f0)
58
- if is_torch:
59
- f0 = f0.to(device)
60
- return f0, uv
61
-
62
-
63
- def denorm_f0(f0, uv, hparams, pitch_padding=None, min=None, max=None):
64
- if hparams['pitch_norm'] == 'standard':
65
- f0 = f0 * hparams['f0_std'] + hparams['f0_mean']
66
- if hparams['pitch_norm'] == 'log':
67
- f0 = 2 ** f0
68
- if min is not None:
69
- f0 = f0.clamp(min=min)
70
- if max is not None:
71
- f0 = f0.clamp(max=max)
72
- if uv is not None and hparams['use_uv']:
73
- f0[uv > 0] = 0
74
- if pitch_padding is not None:
75
- f0[pitch_padding] = 0
76
- return f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/pl_utils.py DELETED
@@ -1,1625 +0,0 @@
1
- import matplotlib
2
- from torch.nn import DataParallel
3
- from torch.nn.parallel import DistributedDataParallel
4
-
5
- matplotlib.use('Agg')
6
- import glob
7
- import itertools
8
- import subprocess
9
- import threading
10
- import traceback
11
-
12
- from pytorch_lightning.callbacks import GradientAccumulationScheduler
13
- from pytorch_lightning.callbacks import ModelCheckpoint
14
-
15
- from functools import wraps
16
- from torch.cuda._utils import _get_device_index
17
- import numpy as np
18
- import torch.optim
19
- import torch.utils.data
20
- import copy
21
- import logging
22
- import os
23
- import re
24
- import sys
25
- import torch
26
- import torch.distributed as dist
27
- import torch.multiprocessing as mp
28
- import tqdm
29
- from torch.optim.optimizer import Optimizer
30
-
31
-
32
- def get_a_var(obj): # pragma: no cover
33
- if isinstance(obj, torch.Tensor):
34
- return obj
35
-
36
- if isinstance(obj, list) or isinstance(obj, tuple):
37
- for result in map(get_a_var, obj):
38
- if isinstance(result, torch.Tensor):
39
- return result
40
- if isinstance(obj, dict):
41
- for result in map(get_a_var, obj.items()):
42
- if isinstance(result, torch.Tensor):
43
- return result
44
- return None
45
-
46
-
47
- def data_loader(fn):
48
- """
49
- Decorator to make any fx with this use the lazy property
50
- :param fn:
51
- :return:
52
- """
53
-
54
- wraps(fn)
55
- attr_name = '_lazy_' + fn.__name__
56
-
57
- def _get_data_loader(self):
58
- try:
59
- value = getattr(self, attr_name)
60
- except AttributeError:
61
- try:
62
- value = fn(self) # Lazy evaluation, done only once.
63
- if (
64
- value is not None and
65
- not isinstance(value, list) and
66
- fn.__name__ in ['test_dataloader', 'val_dataloader']
67
- ):
68
- value = [value]
69
- except AttributeError as e:
70
- # Guard against AttributeError suppression. (Issue #142)
71
- traceback.print_exc()
72
- error = f'{fn.__name__}: An AttributeError was encountered: ' + str(e)
73
- raise RuntimeError(error) from e
74
- setattr(self, attr_name, value) # Memoize evaluation.
75
- return value
76
-
77
- return _get_data_loader
78
-
79
-
80
- def parallel_apply(modules, inputs, kwargs_tup=None, devices=None): # pragma: no cover
81
- r"""Applies each `module` in :attr:`modules` in parallel on arguments
82
- contained in :attr:`inputs` (positional) and :attr:`kwargs_tup` (keyword)
83
- on each of :attr:`devices`.
84
-
85
- Args:
86
- modules (Module): modules to be parallelized
87
- inputs (tensor): inputs to the modules
88
- devices (list of int or torch.device): CUDA devices
89
-
90
- :attr:`modules`, :attr:`inputs`, :attr:`kwargs_tup` (if given), and
91
- :attr:`devices` (if given) should all have same length. Moreover, each
92
- element of :attr:`inputs` can either be a single object as the only argument
93
- to a module, or a collection of positional arguments.
94
- """
95
- assert len(modules) == len(inputs)
96
- if kwargs_tup is not None:
97
- assert len(modules) == len(kwargs_tup)
98
- else:
99
- kwargs_tup = ({},) * len(modules)
100
- if devices is not None:
101
- assert len(modules) == len(devices)
102
- else:
103
- devices = [None] * len(modules)
104
- devices = list(map(lambda x: _get_device_index(x, True), devices))
105
- lock = threading.Lock()
106
- results = {}
107
- grad_enabled = torch.is_grad_enabled()
108
-
109
- def _worker(i, module, input, kwargs, device=None):
110
- torch.set_grad_enabled(grad_enabled)
111
- if device is None:
112
- device = get_a_var(input).get_device()
113
- try:
114
- with torch.cuda.device(device):
115
- # this also avoids accidental slicing of `input` if it is a Tensor
116
- if not isinstance(input, (list, tuple)):
117
- input = (input,)
118
-
119
- # ---------------
120
- # CHANGE
121
- if module.training:
122
- output = module.training_step(*input, **kwargs)
123
-
124
- elif module.testing:
125
- output = module.test_step(*input, **kwargs)
126
-
127
- else:
128
- output = module.validation_step(*input, **kwargs)
129
- # ---------------
130
-
131
- with lock:
132
- results[i] = output
133
- except Exception as e:
134
- with lock:
135
- results[i] = e
136
-
137
- # make sure each module knows what training state it's in...
138
- # fixes weird bug where copies are out of sync
139
- root_m = modules[0]
140
- for m in modules[1:]:
141
- m.training = root_m.training
142
- m.testing = root_m.testing
143
-
144
- if len(modules) > 1:
145
- threads = [threading.Thread(target=_worker,
146
- args=(i, module, input, kwargs, device))
147
- for i, (module, input, kwargs, device) in
148
- enumerate(zip(modules, inputs, kwargs_tup, devices))]
149
-
150
- for thread in threads:
151
- thread.start()
152
- for thread in threads:
153
- thread.join()
154
- else:
155
- _worker(0, modules[0], inputs[0], kwargs_tup[0], devices[0])
156
-
157
- outputs = []
158
- for i in range(len(inputs)):
159
- output = results[i]
160
- if isinstance(output, Exception):
161
- raise output
162
- outputs.append(output)
163
- return outputs
164
-
165
-
166
- def _find_tensors(obj): # pragma: no cover
167
- r"""
168
- Recursively find all tensors contained in the specified object.
169
- """
170
- if isinstance(obj, torch.Tensor):
171
- return [obj]
172
- if isinstance(obj, (list, tuple)):
173
- return itertools.chain(*map(_find_tensors, obj))
174
- if isinstance(obj, dict):
175
- return itertools.chain(*map(_find_tensors, obj.values()))
176
- return []
177
-
178
-
179
- class DDP(DistributedDataParallel):
180
- """
181
- Override the forward call in lightning so it goes to training and validation step respectively
182
- """
183
-
184
- def parallel_apply(self, replicas, inputs, kwargs):
185
- return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)])
186
-
187
- def forward(self, *inputs, **kwargs): # pragma: no cover
188
- self._sync_params()
189
- if self.device_ids:
190
- inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
191
- if len(self.device_ids) == 1:
192
- # --------------
193
- # LIGHTNING MOD
194
- # --------------
195
- # normal
196
- # output = self.module(*inputs[0], **kwargs[0])
197
- # lightning
198
- if self.module.training:
199
- output = self.module.training_step(*inputs[0], **kwargs[0])
200
- elif self.module.testing:
201
- output = self.module.test_step(*inputs[0], **kwargs[0])
202
- else:
203
- output = self.module.validation_step(*inputs[0], **kwargs[0])
204
- else:
205
- outputs = self.parallel_apply(self._module_copies[:len(inputs)], inputs, kwargs)
206
- output = self.gather(outputs, self.output_device)
207
- else:
208
- # normal
209
- output = self.module(*inputs, **kwargs)
210
-
211
- if torch.is_grad_enabled():
212
- # We'll return the output object verbatim since it is a freeform
213
- # object. We need to find any tensors in this object, though,
214
- # because we need to figure out which parameters were used during
215
- # this forward pass, to ensure we short circuit reduction for any
216
- # unused parameters. Only if `find_unused_parameters` is set.
217
- if self.find_unused_parameters:
218
- self.reducer.prepare_for_backward(list(_find_tensors(output)))
219
- else:
220
- self.reducer.prepare_for_backward([])
221
- return output
222
-
223
-
224
- class DP(DataParallel):
225
- """
226
- Override the forward call in lightning so it goes to training and validation step respectively
227
- """
228
-
229
- def forward(self, *inputs, **kwargs):
230
- if not self.device_ids:
231
- return self.module(*inputs, **kwargs)
232
-
233
- for t in itertools.chain(self.module.parameters(), self.module.buffers()):
234
- if t.device != self.src_device_obj:
235
- raise RuntimeError("module must have its parameters and buffers "
236
- "on device {} (device_ids[0]) but found one of "
237
- "them on device: {}".format(self.src_device_obj, t.device))
238
-
239
- inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
240
- if len(self.device_ids) == 1:
241
- # lightning
242
- if self.module.training:
243
- return self.module.training_step(*inputs[0], **kwargs[0])
244
- elif self.module.testing:
245
- return self.module.test_step(*inputs[0], **kwargs[0])
246
- else:
247
- return self.module.validation_step(*inputs[0], **kwargs[0])
248
-
249
- replicas = self.replicate(self.module, self.device_ids[:len(inputs)])
250
- outputs = self.parallel_apply(replicas, inputs, kwargs)
251
- return self.gather(outputs, self.output_device)
252
-
253
- def parallel_apply(self, replicas, inputs, kwargs):
254
- return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)])
255
-
256
-
257
- class GradientAccumulationScheduler:
258
- def __init__(self, scheduling: dict):
259
- if scheduling == {}: # empty dict error
260
- raise TypeError("Empty dict cannot be interpreted correct")
261
-
262
- for key in scheduling.keys():
263
- if not isinstance(key, int) or not isinstance(scheduling[key], int):
264
- raise TypeError("All epoches and accumulation factor must be integers")
265
-
266
- minimal_epoch = min(scheduling.keys())
267
- if minimal_epoch < 1:
268
- msg = f"Epochs indexing from 1, epoch {minimal_epoch} cannot be interpreted correct"
269
- raise IndexError(msg)
270
- elif minimal_epoch != 1: # if user didnt define first epoch accumulation factor
271
- scheduling.update({1: 1})
272
-
273
- self.scheduling = scheduling
274
- self.epochs = sorted(scheduling.keys())
275
-
276
- def on_epoch_begin(self, epoch, trainer):
277
- epoch += 1 # indexing epochs from 1
278
- for i in reversed(range(len(self.epochs))):
279
- if epoch >= self.epochs[i]:
280
- trainer.accumulate_grad_batches = self.scheduling.get(self.epochs[i])
281
- break
282
-
283
-
284
- class LatestModelCheckpoint(ModelCheckpoint):
285
- def __init__(self, filepath, monitor='val_loss', verbose=0, num_ckpt_keep=5,
286
- save_weights_only=False, mode='auto', period=1, prefix='model', save_best=True):
287
- super(ModelCheckpoint, self).__init__()
288
- self.monitor = monitor
289
- self.verbose = verbose
290
- self.filepath = filepath
291
- os.makedirs(filepath, exist_ok=True)
292
- self.num_ckpt_keep = num_ckpt_keep
293
- self.save_best = save_best
294
- self.save_weights_only = save_weights_only
295
- self.period = period
296
- self.epochs_since_last_check = 0
297
- self.prefix = prefix
298
- self.best_k_models = {}
299
- # {filename: monitor}
300
- self.kth_best_model = ''
301
- self.save_top_k = 1
302
- self.task = None
303
- if mode == 'min':
304
- self.monitor_op = np.less
305
- self.best = np.Inf
306
- self.mode = 'min'
307
- elif mode == 'max':
308
- self.monitor_op = np.greater
309
- self.best = -np.Inf
310
- self.mode = 'max'
311
- else:
312
- if 'acc' in self.monitor or self.monitor.startswith('fmeasure'):
313
- self.monitor_op = np.greater
314
- self.best = -np.Inf
315
- self.mode = 'max'
316
- else:
317
- self.monitor_op = np.less
318
- self.best = np.Inf
319
- self.mode = 'min'
320
- if os.path.exists(f'{self.filepath}/best_valid.npy'):
321
- self.best = np.load(f'{self.filepath}/best_valid.npy')[0]
322
-
323
- def get_all_ckpts(self):
324
- return sorted(glob.glob(f'{self.filepath}/{self.prefix}_ckpt_steps_*.ckpt'),
325
- key=lambda x: -int(re.findall('.*steps\_(\d+)\.ckpt', x)[0]))
326
-
327
- def on_epoch_end(self, epoch, logs=None):
328
- logs = logs or {}
329
- self.epochs_since_last_check += 1
330
- best_filepath = f'{self.filepath}/{self.prefix}_ckpt_best.pt'
331
- if self.epochs_since_last_check >= self.period:
332
- self.epochs_since_last_check = 0
333
- filepath = f'{self.filepath}/{self.prefix}_ckpt_steps_{self.task.global_step}.ckpt'
334
- if self.verbose > 0:
335
- logging.info(f'Epoch {epoch:05d}@{self.task.global_step}: saving model to {filepath}')
336
- self._save_model(filepath)
337
- for old_ckpt in self.get_all_ckpts()[self.num_ckpt_keep:]:
338
- # TODO: test filesystem calls
339
- os.remove(old_ckpt)
340
- # subprocess.check_call(f'del "{old_ckpt}"', shell=True)
341
- if self.verbose > 0:
342
- logging.info(f'Delete ckpt: {os.path.basename(old_ckpt)}')
343
- current = logs.get(self.monitor)
344
- if current is not None and self.save_best:
345
- if self.monitor_op(current, self.best):
346
- self.best = current
347
- if self.verbose > 0:
348
- logging.info(
349
- f'Epoch {epoch:05d}@{self.task.global_step}: {self.monitor} reached'
350
- f' {current:0.5f} (best {self.best:0.5f}), saving model to'
351
- f' {best_filepath} as top 1')
352
- self._save_model(best_filepath)
353
- np.save(f'{self.filepath}/best_valid.npy', [self.best])
354
-
355
- def _save_model(self,path):
356
- return self.save_function(path)
357
-
358
-
359
-
360
- class BaseTrainer:
361
- def __init__(
362
- self,
363
- logger=True,
364
- checkpoint_callback=True,
365
- default_save_path=None,
366
- gradient_clip_val=0,
367
- process_position=0,
368
- gpus=-1,
369
- log_gpu_memory=None,
370
- show_progress_bar=True,
371
- track_grad_norm=-1,
372
- check_val_every_n_epoch=1,
373
- accumulate_grad_batches=1,
374
- max_updates=1000,
375
- min_epochs=1,
376
- val_check_interval=1.0,
377
- log_save_interval=100,
378
- row_log_interval=10,
379
- print_nan_grads=False,
380
- weights_summary='full',
381
- num_sanity_val_steps=5,
382
- resume_from_checkpoint=None,
383
- ):
384
- self.log_gpu_memory = log_gpu_memory
385
- self.gradient_clip_val = gradient_clip_val
386
- self.check_val_every_n_epoch = check_val_every_n_epoch
387
- self.track_grad_norm = track_grad_norm
388
- self.on_gpu = True if (gpus and torch.cuda.is_available()) else False
389
- self.process_position = process_position
390
- self.weights_summary = weights_summary
391
- self.max_updates = max_updates
392
- self.min_epochs = min_epochs
393
- self.num_sanity_val_steps = num_sanity_val_steps
394
- self.print_nan_grads = print_nan_grads
395
- self.resume_from_checkpoint = resume_from_checkpoint
396
- self.default_save_path = default_save_path
397
-
398
- # training bookeeping
399
- self.total_batch_idx = 0
400
- self.running_loss = []
401
- self.avg_loss = 0
402
- self.batch_idx = 0
403
- self.tqdm_metrics = {}
404
- self.callback_metrics = {}
405
- self.num_val_batches = 0
406
- self.num_training_batches = 0
407
- self.num_test_batches = 0
408
- self.get_train_dataloader = None
409
- self.get_test_dataloaders = None
410
- self.get_val_dataloaders = None
411
- self.is_iterable_train_dataloader = False
412
-
413
- # training state
414
- self.model = None
415
- self.testing = False
416
- self.disable_validation = False
417
- self.lr_schedulers = []
418
- self.optimizers = None
419
- self.global_step = 0
420
- self.current_epoch = 0
421
- self.total_batches = 0
422
-
423
- # configure checkpoint callback
424
- self.checkpoint_callback = checkpoint_callback
425
- self.checkpoint_callback.save_function = self.save_checkpoint
426
- self.weights_save_path = self.checkpoint_callback.filepath
427
-
428
- # accumulated grads
429
- self.configure_accumulated_gradients(accumulate_grad_batches)
430
-
431
- # allow int, string and gpu list
432
- self.data_parallel_device_ids = [
433
- int(x) for x in os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",") if x != '']
434
- if len(self.data_parallel_device_ids) == 0:
435
- self.root_gpu = None
436
- self.on_gpu = False
437
- else:
438
- self.root_gpu = self.data_parallel_device_ids[0]
439
- self.on_gpu = True
440
-
441
- # distributed backend choice
442
- self.use_ddp = False
443
- self.use_dp = False
444
- self.single_gpu = False
445
- self.distributed_backend = 'ddp' if self.num_gpus > 0 else 'dp'
446
- self.set_distributed_mode(self.distributed_backend)
447
-
448
- self.proc_rank = 0
449
- self.world_size = 1
450
- self.node_rank = 0
451
-
452
- # can't init progress bar here because starting a new process
453
- # means the progress_bar won't survive pickling
454
- self.show_progress_bar = show_progress_bar
455
-
456
- # logging
457
- self.log_save_interval = log_save_interval
458
- self.val_check_interval = val_check_interval
459
- self.logger = logger
460
- self.logger.rank = 0
461
- self.row_log_interval = row_log_interval
462
-
463
- @property
464
- def num_gpus(self):
465
- gpus = self.data_parallel_device_ids
466
- if gpus is None:
467
- return 0
468
- else:
469
- return len(gpus)
470
-
471
- @property
472
- def data_parallel(self):
473
- return self.use_dp or self.use_ddp
474
-
475
- def get_model(self):
476
- is_dp_module = isinstance(self.model, (DDP, DP))
477
- model = self.model.module if is_dp_module else self.model
478
- return model
479
-
480
- # -----------------------------
481
- # MODEL TRAINING
482
- # -----------------------------
483
- def fit(self, model):
484
- if self.use_ddp:
485
- mp.spawn(self.ddp_train, nprocs=self.num_gpus, args=(model,))
486
- else:
487
- model.model = model.build_model()
488
- if not self.testing:
489
- self.optimizers, self.lr_schedulers = self.init_optimizers(model.configure_optimizers())
490
- if self.use_dp:
491
- model.cuda(self.root_gpu)
492
- model = DP(model, device_ids=self.data_parallel_device_ids)
493
- elif self.single_gpu:
494
- model.cuda(self.root_gpu)
495
- self.run_pretrain_routine(model)
496
- return 1
497
-
498
- def init_optimizers(self, optimizers):
499
-
500
- # single optimizer
501
- if isinstance(optimizers, Optimizer):
502
- return [optimizers], []
503
-
504
- # two lists
505
- elif len(optimizers) == 2 and isinstance(optimizers[0], list):
506
- optimizers, lr_schedulers = optimizers
507
- return optimizers, lr_schedulers
508
-
509
- # single list or tuple
510
- elif isinstance(optimizers, list) or isinstance(optimizers, tuple):
511
- return optimizers, []
512
-
513
- def run_pretrain_routine(self, model):
514
- """Sanity check a few things before starting actual training.
515
-
516
- :param model:
517
- """
518
- ref_model = model
519
- if self.data_parallel:
520
- ref_model = model.module
521
-
522
- # give model convenience properties
523
- ref_model.trainer = self
524
-
525
- # set local properties on the model
526
- self.copy_trainer_model_properties(ref_model)
527
-
528
- # link up experiment object
529
- if self.logger is not None:
530
- ref_model.logger = self.logger
531
- self.logger.save()
532
-
533
- if self.use_ddp:
534
- dist.barrier()
535
-
536
- # set up checkpoint callback
537
- # self.configure_checkpoint_callback()
538
-
539
- # transfer data loaders from model
540
- self.get_dataloaders(ref_model)
541
-
542
- # track model now.
543
- # if cluster resets state, the model will update with the saved weights
544
- self.model = model
545
-
546
- # restore training and model before hpc call
547
- self.restore_weights(model)
548
-
549
- # when testing requested only run test and return
550
- if self.testing:
551
- self.run_evaluation(test=True)
552
- return
553
-
554
- # check if we should run validation during training
555
- self.disable_validation = self.num_val_batches == 0
556
-
557
- # run tiny validation (if validation defined)
558
- # to make sure program won't crash during val
559
- ref_model.on_sanity_check_start()
560
- ref_model.on_train_start()
561
- if not self.disable_validation and self.num_sanity_val_steps > 0:
562
- # init progress bars for validation sanity check
563
- pbar = tqdm.tqdm(desc='Validation sanity check',
564
- total=self.num_sanity_val_steps * len(self.get_val_dataloaders()),
565
- leave=False, position=2 * self.process_position,
566
- disable=not self.show_progress_bar, dynamic_ncols=True, unit='batch')
567
- self.main_progress_bar = pbar
568
- # dummy validation progress bar
569
- self.val_progress_bar = tqdm.tqdm(disable=True)
570
-
571
- self.evaluate(model, self.get_val_dataloaders(), self.num_sanity_val_steps, self.testing)
572
-
573
- # close progress bars
574
- self.main_progress_bar.close()
575
- self.val_progress_bar.close()
576
-
577
- # init progress bar
578
- pbar = tqdm.tqdm(leave=True, position=2 * self.process_position,
579
- disable=not self.show_progress_bar, dynamic_ncols=True, unit='batch',
580
- file=sys.stdout)
581
- self.main_progress_bar = pbar
582
-
583
- # clear cache before training
584
- if self.on_gpu:
585
- torch.cuda.empty_cache()
586
-
587
- # CORE TRAINING LOOP
588
- self.train()
589
-
590
- def test(self, model):
591
- self.testing = True
592
- self.fit(model)
593
-
594
- @property
595
- def training_tqdm_dict(self):
596
- tqdm_dict = {
597
- 'step': '{}'.format(self.global_step),
598
- }
599
- tqdm_dict.update(self.tqdm_metrics)
600
- return tqdm_dict
601
-
602
- # --------------------
603
- # restore ckpt
604
- # --------------------
605
- def restore_weights(self, model):
606
- """
607
- To restore weights we have two cases.
608
- First, attempt to restore hpc weights. If successful, don't restore
609
- other weights.
610
-
611
- Otherwise, try to restore actual weights
612
- :param model:
613
- :return:
614
- """
615
- # clear cache before restore
616
- if self.on_gpu:
617
- torch.cuda.empty_cache()
618
-
619
- if self.resume_from_checkpoint is not None:
620
- self.restore(self.resume_from_checkpoint, on_gpu=self.on_gpu)
621
- else:
622
- # restore weights if same exp version
623
- self.restore_state_if_checkpoint_exists(model)
624
-
625
- # wait for all models to restore weights
626
- if self.use_ddp:
627
- # wait for all processes to catch up
628
- dist.barrier()
629
-
630
- # clear cache after restore
631
- if self.on_gpu:
632
- torch.cuda.empty_cache()
633
-
634
- def restore_state_if_checkpoint_exists(self, model):
635
- did_restore = False
636
-
637
- # do nothing if there's not dir or callback
638
- no_ckpt_callback = (self.checkpoint_callback is None) or (not self.checkpoint_callback)
639
- if no_ckpt_callback or not os.path.exists(self.checkpoint_callback.filepath):
640
- return did_restore
641
-
642
- # restore trainer state and model if there is a weight for this experiment
643
- last_steps = -1
644
- last_ckpt_name = None
645
-
646
- # find last epoch
647
- checkpoints = os.listdir(self.checkpoint_callback.filepath)
648
- for name in checkpoints:
649
- if '.ckpt' in name and not name.endswith('part'):
650
- if 'steps_' in name:
651
- steps = name.split('steps_')[1]
652
- steps = int(re.sub('[^0-9]', '', steps))
653
-
654
- if steps > last_steps:
655
- last_steps = steps
656
- last_ckpt_name = name
657
-
658
- # restore last checkpoint
659
- if last_ckpt_name is not None:
660
- last_ckpt_path = os.path.join(self.checkpoint_callback.filepath, last_ckpt_name)
661
- self.restore(last_ckpt_path, self.on_gpu)
662
- logging.info(f'model and trainer restored from checkpoint: {last_ckpt_path}')
663
- did_restore = True
664
-
665
- return did_restore
666
-
667
- def restore(self, checkpoint_path, on_gpu):
668
- checkpoint = torch.load(checkpoint_path, map_location='cpu')
669
-
670
- # load model state
671
- model = self.get_model()
672
-
673
- # load the state_dict on the model automatically
674
- model.load_state_dict(checkpoint['state_dict'], strict=False)
675
- if on_gpu:
676
- model.cuda(self.root_gpu)
677
- # load training state (affects trainer only)
678
- self.restore_training_state(checkpoint)
679
- model.global_step = self.global_step
680
- del checkpoint
681
-
682
- try:
683
- if dist.is_initialized() and dist.get_rank() > 0:
684
- return
685
- except Exception as e:
686
- print(e)
687
- return
688
-
689
- def restore_training_state(self, checkpoint):
690
- """
691
- Restore trainer state.
692
- Model will get its change to update
693
- :param checkpoint:
694
- :return:
695
- """
696
- if self.checkpoint_callback is not None and self.checkpoint_callback is not False:
697
- # return allowing checkpoints with meta information (global_step, etc)
698
- self.checkpoint_callback.best = checkpoint['checkpoint_callback_best']
699
-
700
- self.global_step = checkpoint['global_step']
701
- self.current_epoch = checkpoint['epoch']
702
-
703
- if self.testing:
704
- return
705
-
706
- # restore the optimizers
707
- optimizer_states = checkpoint['optimizer_states']
708
- for optimizer, opt_state in zip(self.optimizers, optimizer_states):
709
- if optimizer is None:
710
- return
711
- optimizer.load_state_dict(opt_state)
712
-
713
- # move optimizer to GPU 1 weight at a time
714
- # avoids OOM
715
- if self.root_gpu is not None:
716
- for state in optimizer.state.values():
717
- for k, v in state.items():
718
- if isinstance(v, torch.Tensor):
719
- state[k] = v.cuda(self.root_gpu)
720
-
721
- # restore the lr schedulers
722
- lr_schedulers = checkpoint['lr_schedulers']
723
- for scheduler, lrs_state in zip(self.lr_schedulers, lr_schedulers):
724
- scheduler.load_state_dict(lrs_state)
725
-
726
- # --------------------
727
- # MODEL SAVE CHECKPOINT
728
- # --------------------
729
- def _atomic_save(self, checkpoint, filepath):
730
- """Saves a checkpoint atomically, avoiding the creation of incomplete checkpoints.
731
-
732
- This will create a temporary checkpoint with a suffix of ``.part``, then copy it to the final location once
733
- saving is finished.
734
-
735
- Args:
736
- checkpoint (object): The object to save.
737
- Built to be used with the ``dump_checkpoint`` method, but can deal with anything which ``torch.save``
738
- accepts.
739
- filepath (str|pathlib.Path): The path to which the checkpoint will be saved.
740
- This points to the file that the checkpoint will be stored in.
741
- """
742
- tmp_path = str(filepath) + ".part"
743
- torch.save(checkpoint, tmp_path)
744
- os.replace(tmp_path, filepath)
745
-
746
- def save_checkpoint(self, filepath):
747
- checkpoint = self.dump_checkpoint()
748
- self._atomic_save(checkpoint, filepath)
749
-
750
- def dump_checkpoint(self):
751
-
752
- checkpoint = {
753
- 'epoch': self.current_epoch,
754
- 'global_step': self.global_step
755
- }
756
-
757
- if self.checkpoint_callback is not None and self.checkpoint_callback is not False:
758
- checkpoint['checkpoint_callback_best'] = self.checkpoint_callback.best
759
-
760
- # save optimizers
761
- optimizer_states = []
762
- for i, optimizer in enumerate(self.optimizers):
763
- if optimizer is not None:
764
- optimizer_states.append(optimizer.state_dict())
765
-
766
- checkpoint['optimizer_states'] = optimizer_states
767
-
768
- # save lr schedulers
769
- lr_schedulers = []
770
- for i, scheduler in enumerate(self.lr_schedulers):
771
- lr_schedulers.append(scheduler.state_dict())
772
-
773
- checkpoint['lr_schedulers'] = lr_schedulers
774
-
775
- # add the hparams and state_dict from the model
776
- model = self.get_model()
777
- checkpoint['state_dict'] = model.state_dict()
778
- # give the model a chance to add a few things
779
- model.on_save_checkpoint(checkpoint)
780
-
781
- return checkpoint
782
-
783
- def copy_trainer_model_properties(self, model):
784
- if isinstance(model, DP):
785
- ref_model = model.module
786
- elif isinstance(model, DDP):
787
- ref_model = model.module
788
- else:
789
- ref_model = model
790
-
791
- for m in [model, ref_model]:
792
- m.trainer = self
793
- m.on_gpu = self.on_gpu
794
- m.use_dp = self.use_dp
795
- m.use_ddp = self.use_ddp
796
- m.testing = self.testing
797
- m.single_gpu = self.single_gpu
798
-
799
- def transfer_batch_to_gpu(self, batch, gpu_id):
800
- # base case: object can be directly moved using `cuda` or `to`
801
- if callable(getattr(batch, 'cuda', None)):
802
- return batch.cuda(gpu_id, non_blocking=True)
803
-
804
- elif callable(getattr(batch, 'to', None)):
805
- return batch.to(torch.device('cuda', gpu_id), non_blocking=True)
806
-
807
- # when list
808
- elif isinstance(batch, list):
809
- for i, x in enumerate(batch):
810
- batch[i] = self.transfer_batch_to_gpu(x, gpu_id)
811
- return batch
812
-
813
- # when tuple
814
- elif isinstance(batch, tuple):
815
- batch = list(batch)
816
- for i, x in enumerate(batch):
817
- batch[i] = self.transfer_batch_to_gpu(x, gpu_id)
818
- return tuple(batch)
819
-
820
- # when dict
821
- elif isinstance(batch, dict):
822
- for k, v in batch.items():
823
- batch[k] = self.transfer_batch_to_gpu(v, gpu_id)
824
-
825
- return batch
826
-
827
- # nothing matches, return the value as is without transform
828
- return batch
829
-
830
- def set_distributed_mode(self, distributed_backend):
831
- # skip for CPU
832
- if self.num_gpus == 0:
833
- return
834
-
835
- # single GPU case
836
- # in single gpu case we allow ddp so we can train on multiple
837
- # nodes, 1 gpu per node
838
- elif self.num_gpus == 1:
839
- self.single_gpu = True
840
- self.use_dp = False
841
- self.use_ddp = False
842
- self.root_gpu = 0
843
- self.data_parallel_device_ids = [0]
844
- else:
845
- if distributed_backend is not None:
846
- self.use_dp = distributed_backend == 'dp'
847
- self.use_ddp = distributed_backend == 'ddp'
848
- elif distributed_backend is None:
849
- self.use_dp = True
850
- self.use_ddp = False
851
-
852
- logging.info(f'gpu available: {torch.cuda.is_available()}, used: {self.on_gpu}')
853
-
854
- def ddp_train(self, gpu_idx, model):
855
- """
856
- Entry point into a DP thread
857
- :param gpu_idx:
858
- :param model:
859
- :param cluster_obj:
860
- :return:
861
- """
862
- # otherwise default to node rank 0
863
- self.node_rank = 0
864
-
865
- # show progressbar only on progress_rank 0
866
- self.show_progress_bar = self.show_progress_bar and self.node_rank == 0 and gpu_idx == 0
867
-
868
- # determine which process we are and world size
869
- if self.use_ddp:
870
- self.proc_rank = self.node_rank * self.num_gpus + gpu_idx
871
- self.world_size = self.num_gpus
872
-
873
- # let the exp know the rank to avoid overwriting logs
874
- if self.logger is not None:
875
- self.logger.rank = self.proc_rank
876
-
877
- # set up server using proc 0's ip address
878
- # try to init for 20 times at max in case ports are taken
879
- # where to store ip_table
880
- model.trainer = self
881
- model.init_ddp_connection(self.proc_rank, self.world_size)
882
-
883
- # CHOOSE OPTIMIZER
884
- # allow for lr schedulers as well
885
- model.model = model.build_model()
886
- if not self.testing:
887
- self.optimizers, self.lr_schedulers = self.init_optimizers(model.configure_optimizers())
888
-
889
- # MODEL
890
- # copy model to each gpu
891
- if self.distributed_backend == 'ddp':
892
- torch.cuda.set_device(gpu_idx)
893
- model.cuda(gpu_idx)
894
-
895
- # set model properties before going into wrapper
896
- self.copy_trainer_model_properties(model)
897
-
898
- # override root GPU
899
- self.root_gpu = gpu_idx
900
-
901
- if self.distributed_backend == 'ddp':
902
- device_ids = [gpu_idx]
903
- else:
904
- device_ids = None
905
-
906
- # allow user to configure ddp
907
- model = model.configure_ddp(model, device_ids)
908
-
909
- # continue training routine
910
- self.run_pretrain_routine(model)
911
-
912
- def resolve_root_node_address(self, root_node):
913
- if '[' in root_node:
914
- name = root_node.split('[')[0]
915
- number = root_node.split(',')[0]
916
- if '-' in number:
917
- number = number.split('-')[0]
918
-
919
- number = re.sub('[^0-9]', '', number)
920
- root_node = name + number
921
-
922
- return root_node
923
-
924
- def log_metrics(self, metrics, grad_norm_dic, step=None):
925
- """Logs the metric dict passed in.
926
-
927
- :param metrics:
928
- :param grad_norm_dic:
929
- """
930
- # added metrics by Lightning for convenience
931
- metrics['epoch'] = self.current_epoch
932
-
933
- # add norms
934
- metrics.update(grad_norm_dic)
935
-
936
- # turn all tensors to scalars
937
- scalar_metrics = self.metrics_to_scalars(metrics)
938
-
939
- step = step if step is not None else self.global_step
940
- # log actual metrics
941
- if self.proc_rank == 0 and self.logger is not None:
942
- self.logger.log_metrics(scalar_metrics, step=step)
943
- self.logger.save()
944
-
945
- def add_tqdm_metrics(self, metrics):
946
- for k, v in metrics.items():
947
- if type(v) is torch.Tensor:
948
- v = v.item()
949
-
950
- self.tqdm_metrics[k] = v
951
-
952
- def metrics_to_scalars(self, metrics):
953
- new_metrics = {}
954
- for k, v in metrics.items():
955
- if isinstance(v, torch.Tensor):
956
- v = v.item()
957
-
958
- if type(v) is dict:
959
- v = self.metrics_to_scalars(v)
960
-
961
- new_metrics[k] = v
962
-
963
- return new_metrics
964
-
965
- def process_output(self, output, train=False):
966
- """Reduces output according to the training mode.
967
-
968
- Separates loss from logging and tqdm metrics
969
- :param output:
970
- :return:
971
- """
972
- # ---------------
973
- # EXTRACT CALLBACK KEYS
974
- # ---------------
975
- # all keys not progress_bar or log are candidates for callbacks
976
- callback_metrics = {}
977
- for k, v in output.items():
978
- if k not in ['progress_bar', 'log', 'hiddens']:
979
- callback_metrics[k] = v
980
-
981
- if train and self.use_dp:
982
- num_gpus = self.num_gpus
983
- callback_metrics = self.reduce_distributed_output(callback_metrics, num_gpus)
984
-
985
- for k, v in callback_metrics.items():
986
- if isinstance(v, torch.Tensor):
987
- callback_metrics[k] = v.item()
988
-
989
- # ---------------
990
- # EXTRACT PROGRESS BAR KEYS
991
- # ---------------
992
- try:
993
- progress_output = output['progress_bar']
994
-
995
- # reduce progress metrics for tqdm when using dp
996
- if train and self.use_dp:
997
- num_gpus = self.num_gpus
998
- progress_output = self.reduce_distributed_output(progress_output, num_gpus)
999
-
1000
- progress_bar_metrics = progress_output
1001
- except Exception:
1002
- progress_bar_metrics = {}
1003
-
1004
- # ---------------
1005
- # EXTRACT LOGGING KEYS
1006
- # ---------------
1007
- # extract metrics to log to experiment
1008
- try:
1009
- log_output = output['log']
1010
-
1011
- # reduce progress metrics for tqdm when using dp
1012
- if train and self.use_dp:
1013
- num_gpus = self.num_gpus
1014
- log_output = self.reduce_distributed_output(log_output, num_gpus)
1015
-
1016
- log_metrics = log_output
1017
- except Exception:
1018
- log_metrics = {}
1019
-
1020
- # ---------------
1021
- # EXTRACT LOSS
1022
- # ---------------
1023
- # if output dict doesn't have the keyword loss
1024
- # then assume the output=loss if scalar
1025
- loss = None
1026
- if train:
1027
- try:
1028
- loss = output['loss']
1029
- except Exception:
1030
- if type(output) is torch.Tensor:
1031
- loss = output
1032
- else:
1033
- raise RuntimeError(
1034
- 'No `loss` value in the dictionary returned from `model.training_step()`.'
1035
- )
1036
-
1037
- # when using dp need to reduce the loss
1038
- if self.use_dp:
1039
- loss = self.reduce_distributed_output(loss, self.num_gpus)
1040
-
1041
- # ---------------
1042
- # EXTRACT HIDDEN
1043
- # ---------------
1044
- hiddens = output.get('hiddens')
1045
-
1046
- # use every metric passed in as a candidate for callback
1047
- callback_metrics.update(progress_bar_metrics)
1048
- callback_metrics.update(log_metrics)
1049
-
1050
- # convert tensors to numpy
1051
- for k, v in callback_metrics.items():
1052
- if isinstance(v, torch.Tensor):
1053
- callback_metrics[k] = v.item()
1054
-
1055
- return loss, progress_bar_metrics, log_metrics, callback_metrics, hiddens
1056
-
1057
- def reduce_distributed_output(self, output, num_gpus):
1058
- if num_gpus <= 1:
1059
- return output
1060
-
1061
- # when using DP, we get one output per gpu
1062
- # average outputs and return
1063
- if type(output) is torch.Tensor:
1064
- return output.mean()
1065
-
1066
- for k, v in output.items():
1067
- # recurse on nested dics
1068
- if isinstance(output[k], dict):
1069
- output[k] = self.reduce_distributed_output(output[k], num_gpus)
1070
-
1071
- # do nothing when there's a scalar
1072
- elif isinstance(output[k], torch.Tensor) and output[k].dim() == 0:
1073
- pass
1074
-
1075
- # reduce only metrics that have the same number of gpus
1076
- elif output[k].size(0) == num_gpus:
1077
- reduced = torch.mean(output[k])
1078
- output[k] = reduced
1079
- return output
1080
-
1081
- def clip_gradients(self):
1082
- if self.gradient_clip_val > 0:
1083
- model = self.get_model()
1084
- torch.nn.utils.clip_grad_norm_(model.parameters(), self.gradient_clip_val)
1085
-
1086
- def print_nan_gradients(self):
1087
- model = self.get_model()
1088
- for param in model.parameters():
1089
- if (param.grad is not None) and torch.isnan(param.grad.float()).any():
1090
- logging.info(param, param.grad)
1091
-
1092
- def configure_accumulated_gradients(self, accumulate_grad_batches):
1093
- self.accumulate_grad_batches = None
1094
-
1095
- if isinstance(accumulate_grad_batches, dict):
1096
- self.accumulation_scheduler = GradientAccumulationScheduler(accumulate_grad_batches)
1097
- elif isinstance(accumulate_grad_batches, int):
1098
- schedule = {1: accumulate_grad_batches}
1099
- self.accumulation_scheduler = GradientAccumulationScheduler(schedule)
1100
- else:
1101
- raise TypeError("Gradient accumulation supports only int and dict types")
1102
-
1103
- def get_dataloaders(self, model):
1104
- if not self.testing:
1105
- self.init_train_dataloader(model)
1106
- self.init_val_dataloader(model)
1107
- else:
1108
- self.init_test_dataloader(model)
1109
-
1110
- if self.use_ddp:
1111
- dist.barrier()
1112
- if not self.testing:
1113
- self.get_train_dataloader()
1114
- self.get_val_dataloaders()
1115
- else:
1116
- self.get_test_dataloaders()
1117
-
1118
- def init_train_dataloader(self, model):
1119
- self.fisrt_epoch = True
1120
- self.get_train_dataloader = model.train_dataloader
1121
- if isinstance(self.get_train_dataloader(), torch.utils.data.DataLoader):
1122
- self.num_training_batches = len(self.get_train_dataloader())
1123
- self.num_training_batches = int(self.num_training_batches)
1124
- else:
1125
- self.num_training_batches = float('inf')
1126
- self.is_iterable_train_dataloader = True
1127
- if isinstance(self.val_check_interval, int):
1128
- self.val_check_batch = self.val_check_interval
1129
- else:
1130
- self._percent_range_check('val_check_interval')
1131
- self.val_check_batch = int(self.num_training_batches * self.val_check_interval)
1132
- self.val_check_batch = max(1, self.val_check_batch)
1133
-
1134
- def init_val_dataloader(self, model):
1135
- self.get_val_dataloaders = model.val_dataloader
1136
- self.num_val_batches = 0
1137
- if self.get_val_dataloaders() is not None:
1138
- if isinstance(self.get_val_dataloaders()[0], torch.utils.data.DataLoader):
1139
- self.num_val_batches = sum(len(dataloader) for dataloader in self.get_val_dataloaders())
1140
- self.num_val_batches = int(self.num_val_batches)
1141
- else:
1142
- self.num_val_batches = float('inf')
1143
-
1144
- def init_test_dataloader(self, model):
1145
- self.get_test_dataloaders = model.test_dataloader
1146
- if self.get_test_dataloaders() is not None:
1147
- if isinstance(self.get_test_dataloaders()[0], torch.utils.data.DataLoader):
1148
- self.num_test_batches = sum(len(dataloader) for dataloader in self.get_test_dataloaders())
1149
- self.num_test_batches = int(self.num_test_batches)
1150
- else:
1151
- self.num_test_batches = float('inf')
1152
-
1153
- def evaluate(self, model, dataloaders, max_batches, test=False):
1154
- """Run evaluation code.
1155
-
1156
- :param model: PT model
1157
- :param dataloaders: list of PT dataloaders
1158
- :param max_batches: Scalar
1159
- :param test: boolean
1160
- :return:
1161
- """
1162
- # enable eval mode
1163
- model.zero_grad()
1164
- model.eval()
1165
-
1166
- # copy properties for forward overrides
1167
- self.copy_trainer_model_properties(model)
1168
-
1169
- # disable gradients to save memory
1170
- torch.set_grad_enabled(False)
1171
-
1172
- if test:
1173
- self.get_model().test_start()
1174
- # bookkeeping
1175
- outputs = []
1176
-
1177
- # run training
1178
- for dataloader_idx, dataloader in enumerate(dataloaders):
1179
- dl_outputs = []
1180
- for batch_idx, batch in enumerate(dataloader):
1181
-
1182
- if batch is None: # pragma: no cover
1183
- continue
1184
-
1185
- # stop short when on fast_dev_run (sets max_batch=1)
1186
- if batch_idx >= max_batches:
1187
- break
1188
-
1189
- # -----------------
1190
- # RUN EVALUATION STEP
1191
- # -----------------
1192
- output = self.evaluation_forward(model,
1193
- batch,
1194
- batch_idx,
1195
- dataloader_idx,
1196
- test)
1197
-
1198
- # track outputs for collation
1199
- dl_outputs.append(output)
1200
-
1201
- # batch done
1202
- if test:
1203
- self.test_progress_bar.update(1)
1204
- else:
1205
- self.val_progress_bar.update(1)
1206
- outputs.append(dl_outputs)
1207
-
1208
- # with a single dataloader don't pass an array
1209
- if len(dataloaders) == 1:
1210
- outputs = outputs[0]
1211
-
1212
- # give model a chance to do something with the outputs (and method defined)
1213
- model = self.get_model()
1214
- if test:
1215
- eval_results_ = model.test_end(outputs)
1216
- else:
1217
- eval_results_ = model.validation_end(outputs)
1218
- eval_results = eval_results_
1219
-
1220
- # enable train mode again
1221
- model.train()
1222
-
1223
- # enable gradients to save memory
1224
- torch.set_grad_enabled(True)
1225
-
1226
- return eval_results
1227
-
1228
- def run_evaluation(self, test=False):
1229
- # when testing make sure user defined a test step
1230
- model = self.get_model()
1231
- model.on_pre_performance_check()
1232
-
1233
- # select dataloaders
1234
- if test:
1235
- dataloaders = self.get_test_dataloaders()
1236
- max_batches = self.num_test_batches
1237
- else:
1238
- # val
1239
- dataloaders = self.get_val_dataloaders()
1240
- max_batches = self.num_val_batches
1241
-
1242
- # init validation or test progress bar
1243
- # main progress bar will already be closed when testing so initial position is free
1244
- position = 2 * self.process_position + (not test)
1245
- desc = 'Testing' if test else 'Validating'
1246
- pbar = tqdm.tqdm(desc=desc, total=max_batches, leave=test, position=position,
1247
- disable=not self.show_progress_bar, dynamic_ncols=True,
1248
- unit='batch', file=sys.stdout)
1249
- setattr(self, f'{"test" if test else "val"}_progress_bar', pbar)
1250
-
1251
- # run evaluation
1252
- eval_results = self.evaluate(self.model,
1253
- dataloaders,
1254
- max_batches,
1255
- test)
1256
- if eval_results is not None:
1257
- _, prog_bar_metrics, log_metrics, callback_metrics, _ = self.process_output(
1258
- eval_results)
1259
-
1260
- # add metrics to prog bar
1261
- self.add_tqdm_metrics(prog_bar_metrics)
1262
-
1263
- # log metrics
1264
- self.log_metrics(log_metrics, {})
1265
-
1266
- # track metrics for callbacks
1267
- self.callback_metrics.update(callback_metrics)
1268
-
1269
- # hook
1270
- model.on_post_performance_check()
1271
-
1272
- # add model specific metrics
1273
- tqdm_metrics = self.training_tqdm_dict
1274
- if not test:
1275
- self.main_progress_bar.set_postfix(**tqdm_metrics)
1276
-
1277
- # close progress bar
1278
- if test:
1279
- self.test_progress_bar.close()
1280
- else:
1281
- self.val_progress_bar.close()
1282
-
1283
- # model checkpointing
1284
- if self.proc_rank == 0 and self.checkpoint_callback is not None and not test:
1285
- self.checkpoint_callback.on_epoch_end(epoch=self.current_epoch,
1286
- logs=self.callback_metrics)
1287
-
1288
- def evaluation_forward(self, model, batch, batch_idx, dataloader_idx, test=False):
1289
- # make dataloader_idx arg in validation_step optional
1290
- args = [batch, batch_idx]
1291
- # print(batch)
1292
- if test and len(self.get_test_dataloaders()) > 1:
1293
- args.append(dataloader_idx)
1294
-
1295
- elif not test and len(self.get_val_dataloaders()) > 1:
1296
- args.append(dataloader_idx)
1297
-
1298
- # handle DP, DDP forward
1299
- if self.use_ddp or self.use_dp:
1300
- output = model(*args)
1301
- return output
1302
-
1303
- # single GPU
1304
- if self.single_gpu:
1305
- # for single GPU put inputs on gpu manually
1306
- root_gpu = 0
1307
- if isinstance(self.data_parallel_device_ids, list):
1308
- root_gpu = self.data_parallel_device_ids[0]
1309
- batch = self.transfer_batch_to_gpu(batch, root_gpu)
1310
- args[0] = batch
1311
-
1312
- # CPU
1313
- if test:
1314
- output = model.test_step(*args)
1315
- else:
1316
- output = model.validation_step(*args)
1317
-
1318
- return output
1319
-
1320
- def train(self):
1321
- model = self.get_model()
1322
- # run all epochs
1323
- for epoch in range(self.current_epoch, 1000000):
1324
- # set seed for distributed sampler (enables shuffling for each epoch)
1325
- if self.use_ddp and hasattr(self.get_train_dataloader().sampler, 'set_epoch'):
1326
- self.get_train_dataloader().sampler.set_epoch(epoch)
1327
-
1328
- # get model
1329
- model = self.get_model()
1330
-
1331
- # update training progress in trainer and model
1332
- model.current_epoch = epoch
1333
- self.current_epoch = epoch
1334
-
1335
- total_val_batches = 0
1336
- if not self.disable_validation:
1337
- # val can be checked multiple times in epoch
1338
- is_val_epoch = (self.current_epoch + 1) % self.check_val_every_n_epoch == 0
1339
- val_checks_per_epoch = self.num_training_batches // self.val_check_batch
1340
- val_checks_per_epoch = val_checks_per_epoch if is_val_epoch else 0
1341
- total_val_batches = self.num_val_batches * val_checks_per_epoch
1342
-
1343
- # total batches includes multiple val checks
1344
- self.total_batches = self.num_training_batches + total_val_batches
1345
- self.batch_loss_value = 0 # accumulated grads
1346
-
1347
- if self.is_iterable_train_dataloader:
1348
- # for iterable train loader, the progress bar never ends
1349
- num_iterations = None
1350
- else:
1351
- num_iterations = self.total_batches
1352
-
1353
- # reset progress bar
1354
- # .reset() doesn't work on disabled progress bar so we should check
1355
- desc = f'Epoch {epoch + 1}' if not self.is_iterable_train_dataloader else ''
1356
- self.main_progress_bar.set_description(desc)
1357
-
1358
- # changing gradient according accumulation_scheduler
1359
- self.accumulation_scheduler.on_epoch_begin(epoch, self)
1360
-
1361
- # -----------------
1362
- # RUN TNG EPOCH
1363
- # -----------------
1364
- self.run_training_epoch()
1365
-
1366
- # update LR schedulers
1367
- if self.lr_schedulers is not None:
1368
- for lr_scheduler in self.lr_schedulers:
1369
- lr_scheduler.step(epoch=self.current_epoch)
1370
-
1371
- self.main_progress_bar.close()
1372
-
1373
- model.on_train_end()
1374
-
1375
- if self.logger is not None:
1376
- self.logger.finalize("success")
1377
-
1378
- def run_training_epoch(self):
1379
- # before epoch hook
1380
- if self.is_function_implemented('on_epoch_start'):
1381
- model = self.get_model()
1382
- model.on_epoch_start()
1383
-
1384
- # run epoch
1385
- for batch_idx, batch in enumerate(self.get_train_dataloader()):
1386
- # stop epoch if we limited the number of training batches
1387
- if batch_idx >= self.num_training_batches:
1388
- break
1389
-
1390
- self.batch_idx = batch_idx
1391
-
1392
- model = self.get_model()
1393
- model.global_step = self.global_step
1394
-
1395
- # ---------------
1396
- # RUN TRAIN STEP
1397
- # ---------------
1398
- output = self.run_training_batch(batch, batch_idx)
1399
- batch_result, grad_norm_dic, batch_step_metrics = output
1400
-
1401
- # when returning -1 from train_step, we end epoch early
1402
- early_stop_epoch = batch_result == -1
1403
-
1404
- # ---------------
1405
- # RUN VAL STEP
1406
- # ---------------
1407
- should_check_val = (
1408
- not self.disable_validation and self.global_step % self.val_check_batch == 0 and not self.fisrt_epoch)
1409
- self.fisrt_epoch = False
1410
-
1411
- if should_check_val:
1412
- self.run_evaluation(test=self.testing)
1413
-
1414
- # when logs should be saved
1415
- should_save_log = (batch_idx + 1) % self.log_save_interval == 0 or early_stop_epoch
1416
- if should_save_log:
1417
- if self.proc_rank == 0 and self.logger is not None:
1418
- self.logger.save()
1419
-
1420
- # when metrics should be logged
1421
- should_log_metrics = batch_idx % self.row_log_interval == 0 or early_stop_epoch
1422
- if should_log_metrics:
1423
- # logs user requested information to logger
1424
- self.log_metrics(batch_step_metrics, grad_norm_dic)
1425
-
1426
- self.global_step += 1
1427
- self.total_batch_idx += 1
1428
-
1429
- # end epoch early
1430
- # stop when the flag is changed or we've gone past the amount
1431
- # requested in the batches
1432
- if early_stop_epoch:
1433
- break
1434
- if self.global_step > self.max_updates:
1435
- print("| Training end..")
1436
- exit()
1437
-
1438
- # epoch end hook
1439
- if self.is_function_implemented('on_epoch_end'):
1440
- model = self.get_model()
1441
- model.on_epoch_end()
1442
-
1443
- def run_training_batch(self, batch, batch_idx):
1444
- # track grad norms
1445
- grad_norm_dic = {}
1446
-
1447
- # track all metrics for callbacks
1448
- all_callback_metrics = []
1449
-
1450
- # track metrics to log
1451
- all_log_metrics = []
1452
-
1453
- if batch is None:
1454
- return 0, grad_norm_dic, {}
1455
-
1456
- # hook
1457
- if self.is_function_implemented('on_batch_start'):
1458
- model_ref = self.get_model()
1459
- response = model_ref.on_batch_start(batch)
1460
-
1461
- if response == -1:
1462
- return -1, grad_norm_dic, {}
1463
-
1464
- splits = [batch]
1465
- self.hiddens = None
1466
- for split_idx, split_batch in enumerate(splits):
1467
- self.split_idx = split_idx
1468
-
1469
- # call training_step once per optimizer
1470
- for opt_idx, optimizer in enumerate(self.optimizers):
1471
- if optimizer is None:
1472
- continue
1473
- # make sure only the gradients of the current optimizer's paramaters are calculated
1474
- # in the training step to prevent dangling gradients in multiple-optimizer setup.
1475
- if len(self.optimizers) > 1:
1476
- for param in self.get_model().parameters():
1477
- param.requires_grad = False
1478
- for group in optimizer.param_groups:
1479
- for param in group['params']:
1480
- param.requires_grad = True
1481
-
1482
- # wrap the forward step in a closure so second order methods work
1483
- def optimizer_closure():
1484
- # forward pass
1485
- output = self.training_forward(
1486
- split_batch, batch_idx, opt_idx, self.hiddens)
1487
-
1488
- closure_loss = output[0]
1489
- progress_bar_metrics = output[1]
1490
- log_metrics = output[2]
1491
- callback_metrics = output[3]
1492
- self.hiddens = output[4]
1493
- if closure_loss is None:
1494
- return None
1495
-
1496
- # accumulate loss
1497
- # (if accumulate_grad_batches = 1 no effect)
1498
- closure_loss = closure_loss / self.accumulate_grad_batches
1499
-
1500
- # backward pass
1501
- model_ref = self.get_model()
1502
- if closure_loss.requires_grad:
1503
- model_ref.backward(closure_loss, optimizer)
1504
-
1505
- # track metrics for callbacks
1506
- all_callback_metrics.append(callback_metrics)
1507
-
1508
- # track progress bar metrics
1509
- self.add_tqdm_metrics(progress_bar_metrics)
1510
- all_log_metrics.append(log_metrics)
1511
-
1512
- # insert after step hook
1513
- if self.is_function_implemented('on_after_backward'):
1514
- model_ref = self.get_model()
1515
- model_ref.on_after_backward()
1516
-
1517
- return closure_loss
1518
-
1519
- # calculate loss
1520
- loss = optimizer_closure()
1521
- if loss is None:
1522
- continue
1523
-
1524
- # nan grads
1525
- if self.print_nan_grads:
1526
- self.print_nan_gradients()
1527
-
1528
- # track total loss for logging (avoid mem leaks)
1529
- self.batch_loss_value += loss.item()
1530
-
1531
- # gradient update with accumulated gradients
1532
- if (self.batch_idx + 1) % self.accumulate_grad_batches == 0:
1533
-
1534
- # track gradient norms when requested
1535
- if batch_idx % self.row_log_interval == 0:
1536
- if self.track_grad_norm > 0:
1537
- model = self.get_model()
1538
- grad_norm_dic = model.grad_norm(
1539
- self.track_grad_norm)
1540
-
1541
- # clip gradients
1542
- self.clip_gradients()
1543
-
1544
- # calls .step(), .zero_grad()
1545
- # override function to modify this behavior
1546
- model = self.get_model()
1547
- model.optimizer_step(self.current_epoch, batch_idx, optimizer, opt_idx)
1548
-
1549
- # calculate running loss for display
1550
- self.running_loss.append(self.batch_loss_value)
1551
- self.batch_loss_value = 0
1552
- self.avg_loss = np.mean(self.running_loss[-100:])
1553
-
1554
- # activate batch end hook
1555
- if self.is_function_implemented('on_batch_end'):
1556
- model = self.get_model()
1557
- model.on_batch_end()
1558
-
1559
- # update progress bar
1560
- self.main_progress_bar.update(1)
1561
- self.main_progress_bar.set_postfix(**self.training_tqdm_dict)
1562
-
1563
- # collapse all metrics into one dict
1564
- all_log_metrics = {k: v for d in all_log_metrics for k, v in d.items()}
1565
-
1566
- # track all metrics for callbacks
1567
- self.callback_metrics.update({k: v for d in all_callback_metrics for k, v in d.items()})
1568
-
1569
- return 0, grad_norm_dic, all_log_metrics
1570
-
1571
- def training_forward(self, batch, batch_idx, opt_idx, hiddens):
1572
- """
1573
- Handle forward for each training case (distributed, single gpu, etc...)
1574
- :param batch:
1575
- :param batch_idx:
1576
- :return:
1577
- """
1578
- # ---------------
1579
- # FORWARD
1580
- # ---------------
1581
- # enable not needing to add opt_idx to training_step
1582
- args = [batch, batch_idx, opt_idx]
1583
-
1584
- # distributed forward
1585
- if self.use_ddp or self.use_dp:
1586
- output = self.model(*args)
1587
- # single GPU forward
1588
- elif self.single_gpu:
1589
- gpu_id = 0
1590
- if isinstance(self.data_parallel_device_ids, list):
1591
- gpu_id = self.data_parallel_device_ids[0]
1592
- batch = self.transfer_batch_to_gpu(copy.copy(batch), gpu_id)
1593
- args[0] = batch
1594
- output = self.model.training_step(*args)
1595
- # CPU forward
1596
- else:
1597
- output = self.model.training_step(*args)
1598
-
1599
- # allow any mode to define training_end
1600
- model_ref = self.get_model()
1601
- output_ = model_ref.training_end(output)
1602
- if output_ is not None:
1603
- output = output_
1604
-
1605
- # format and reduce outputs accordingly
1606
- output = self.process_output(output, train=True)
1607
-
1608
- return output
1609
-
1610
- # ---------------
1611
- # Utils
1612
- # ---------------
1613
- def is_function_implemented(self, f_name):
1614
- model = self.get_model()
1615
- f_op = getattr(model, f_name, None)
1616
- return callable(f_op)
1617
-
1618
- def _percent_range_check(self, name):
1619
- value = getattr(self, name)
1620
- msg = f"`{name}` must lie in the range [0.0, 1.0], but got {value:.3f}."
1621
- if name == "val_check_interval":
1622
- msg += " If you want to disable validation set `val_percent_check` to 0.0 instead."
1623
-
1624
- if not 0. <= value <= 1.:
1625
- raise ValueError(msg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/plot.py DELETED
@@ -1,56 +0,0 @@
1
- import matplotlib.pyplot as plt
2
- import numpy as np
3
- import torch
4
-
5
- LINE_COLORS = ['w', 'r', 'y', 'cyan', 'm', 'b', 'lime']
6
-
7
-
8
- def spec_to_figure(spec, vmin=None, vmax=None):
9
- if isinstance(spec, torch.Tensor):
10
- spec = spec.cpu().numpy()
11
- fig = plt.figure(figsize=(12, 6))
12
- plt.pcolor(spec.T, vmin=vmin, vmax=vmax)
13
- return fig
14
-
15
-
16
- def spec_f0_to_figure(spec, f0s, figsize=None):
17
- max_y = spec.shape[1]
18
- if isinstance(spec, torch.Tensor):
19
- spec = spec.detach().cpu().numpy()
20
- f0s = {k: f0.detach().cpu().numpy() for k, f0 in f0s.items()}
21
- f0s = {k: f0 / 10 for k, f0 in f0s.items()}
22
- fig = plt.figure(figsize=(12, 6) if figsize is None else figsize)
23
- plt.pcolor(spec.T)
24
- for i, (k, f0) in enumerate(f0s.items()):
25
- plt.plot(f0.clip(0, max_y), label=k, c=LINE_COLORS[i], linewidth=1, alpha=0.8)
26
- plt.legend()
27
- return fig
28
-
29
-
30
- def dur_to_figure(dur_gt, dur_pred, txt):
31
- dur_gt = dur_gt.long().cpu().numpy()
32
- dur_pred = dur_pred.long().cpu().numpy()
33
- dur_gt = np.cumsum(dur_gt)
34
- dur_pred = np.cumsum(dur_pred)
35
- fig = plt.figure(figsize=(12, 6))
36
- for i in range(len(dur_gt)):
37
- shift = (i % 8) + 1
38
- plt.text(dur_gt[i], shift, txt[i])
39
- plt.text(dur_pred[i], 10 + shift, txt[i])
40
- plt.vlines(dur_gt[i], 0, 10, colors='b') # blue is gt
41
- plt.vlines(dur_pred[i], 10, 20, colors='r') # red is pred
42
- return fig
43
-
44
-
45
- def f0_to_figure(f0_gt, f0_cwt=None, f0_pred=None):
46
- fig = plt.figure()
47
- f0_gt = f0_gt.cpu().numpy()
48
- plt.plot(f0_gt, color='r', label='gt')
49
- if f0_cwt is not None:
50
- f0_cwt = f0_cwt.cpu().numpy()
51
- plt.plot(f0_cwt, color='b', label='cwt')
52
- if f0_pred is not None:
53
- f0_pred = f0_pred.cpu().numpy()
54
- plt.plot(f0_pred, color='green', label='pred')
55
- plt.legend()
56
- return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/text_encoder.py DELETED
@@ -1,304 +0,0 @@
1
- import re
2
- import six
3
- from six.moves import range # pylint: disable=redefined-builtin
4
-
5
- PAD = "<pad>"
6
- EOS = "<EOS>"
7
- UNK = "<UNK>"
8
- SEG = "|"
9
- RESERVED_TOKENS = [PAD, EOS, UNK]
10
- NUM_RESERVED_TOKENS = len(RESERVED_TOKENS)
11
- PAD_ID = RESERVED_TOKENS.index(PAD) # Normally 0
12
- EOS_ID = RESERVED_TOKENS.index(EOS) # Normally 1
13
- UNK_ID = RESERVED_TOKENS.index(UNK) # Normally 2
14
-
15
- if six.PY2:
16
- RESERVED_TOKENS_BYTES = RESERVED_TOKENS
17
- else:
18
- RESERVED_TOKENS_BYTES = [bytes(PAD, "ascii"), bytes(EOS, "ascii")]
19
-
20
- # Regular expression for unescaping token strings.
21
- # '\u' is converted to '_'
22
- # '\\' is converted to '\'
23
- # '\213;' is converted to unichr(213)
24
- _UNESCAPE_REGEX = re.compile(r"\\u|\\\\|\\([0-9]+);")
25
- _ESCAPE_CHARS = set(u"\\_u;0123456789")
26
-
27
-
28
- def strip_ids(ids, ids_to_strip):
29
- """Strip ids_to_strip from the end ids."""
30
- ids = list(ids)
31
- while ids and ids[-1] in ids_to_strip:
32
- ids.pop()
33
- return ids
34
-
35
-
36
- class TextEncoder(object):
37
- """Base class for converting from ints to/from human readable strings."""
38
-
39
- def __init__(self, num_reserved_ids=NUM_RESERVED_TOKENS):
40
- self._num_reserved_ids = num_reserved_ids
41
-
42
- @property
43
- def num_reserved_ids(self):
44
- return self._num_reserved_ids
45
-
46
- def encode(self, s):
47
- """Transform a human-readable string into a sequence of int ids.
48
-
49
- The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
50
- num_reserved_ids) are reserved.
51
-
52
- EOS is not appended.
53
-
54
- Args:
55
- s: human-readable string to be converted.
56
-
57
- Returns:
58
- ids: list of integers
59
- """
60
- return [int(w) + self._num_reserved_ids for w in s.split()]
61
-
62
- def decode(self, ids, strip_extraneous=False):
63
- """Transform a sequence of int ids into a human-readable string.
64
-
65
- EOS is not expected in ids.
66
-
67
- Args:
68
- ids: list of integers to be converted.
69
- strip_extraneous: bool, whether to strip off extraneous tokens
70
- (EOS and PAD).
71
-
72
- Returns:
73
- s: human-readable string.
74
- """
75
- if strip_extraneous:
76
- ids = strip_ids(ids, list(range(self._num_reserved_ids or 0)))
77
- return " ".join(self.decode_list(ids))
78
-
79
- def decode_list(self, ids):
80
- """Transform a sequence of int ids into a their string versions.
81
-
82
- This method supports transforming individual input/output ids to their
83
- string versions so that sequence to/from text conversions can be visualized
84
- in a human readable format.
85
-
86
- Args:
87
- ids: list of integers to be converted.
88
-
89
- Returns:
90
- strs: list of human-readable string.
91
- """
92
- decoded_ids = []
93
- for id_ in ids:
94
- if 0 <= id_ < self._num_reserved_ids:
95
- decoded_ids.append(RESERVED_TOKENS[int(id_)])
96
- else:
97
- decoded_ids.append(id_ - self._num_reserved_ids)
98
- return [str(d) for d in decoded_ids]
99
-
100
- @property
101
- def vocab_size(self):
102
- raise NotImplementedError()
103
-
104
-
105
- class ByteTextEncoder(TextEncoder):
106
- """Encodes each byte to an id. For 8-bit strings only."""
107
-
108
- def encode(self, s):
109
- numres = self._num_reserved_ids
110
- if six.PY2:
111
- if isinstance(s, unicode):
112
- s = s.encode("utf-8")
113
- return [ord(c) + numres for c in s]
114
- # Python3: explicitly convert to UTF-8
115
- return [c + numres for c in s.encode("utf-8")]
116
-
117
- def decode(self, ids, strip_extraneous=False):
118
- if strip_extraneous:
119
- ids = strip_ids(ids, list(range(self._num_reserved_ids or 0)))
120
- numres = self._num_reserved_ids
121
- decoded_ids = []
122
- int2byte = six.int2byte
123
- for id_ in ids:
124
- if 0 <= id_ < numres:
125
- decoded_ids.append(RESERVED_TOKENS_BYTES[int(id_)])
126
- else:
127
- decoded_ids.append(int2byte(id_ - numres))
128
- if six.PY2:
129
- return "".join(decoded_ids)
130
- # Python3: join byte arrays and then decode string
131
- return b"".join(decoded_ids).decode("utf-8", "replace")
132
-
133
- def decode_list(self, ids):
134
- numres = self._num_reserved_ids
135
- decoded_ids = []
136
- int2byte = six.int2byte
137
- for id_ in ids:
138
- if 0 <= id_ < numres:
139
- decoded_ids.append(RESERVED_TOKENS_BYTES[int(id_)])
140
- else:
141
- decoded_ids.append(int2byte(id_ - numres))
142
- # Python3: join byte arrays and then decode string
143
- return decoded_ids
144
-
145
- @property
146
- def vocab_size(self):
147
- return 2**8 + self._num_reserved_ids
148
-
149
-
150
- class ByteTextEncoderWithEos(ByteTextEncoder):
151
- """Encodes each byte to an id and appends the EOS token."""
152
-
153
- def encode(self, s):
154
- return super(ByteTextEncoderWithEos, self).encode(s) + [EOS_ID]
155
-
156
-
157
- class TokenTextEncoder(TextEncoder):
158
- """Encoder based on a user-supplied vocabulary (file or list)."""
159
-
160
- def __init__(self,
161
- vocab_filename,
162
- reverse=False,
163
- vocab_list=None,
164
- replace_oov=None,
165
- num_reserved_ids=NUM_RESERVED_TOKENS):
166
- """Initialize from a file or list, one token per line.
167
-
168
- Handling of reserved tokens works as follows:
169
- - When initializing from a list, we add reserved tokens to the vocab.
170
- - When initializing from a file, we do not add reserved tokens to the vocab.
171
- - When saving vocab files, we save reserved tokens to the file.
172
-
173
- Args:
174
- vocab_filename: If not None, the full filename to read vocab from. If this
175
- is not None, then vocab_list should be None.
176
- reverse: Boolean indicating if tokens should be reversed during encoding
177
- and decoding.
178
- vocab_list: If not None, a list of elements of the vocabulary. If this is
179
- not None, then vocab_filename should be None.
180
- replace_oov: If not None, every out-of-vocabulary token seen when
181
- encoding will be replaced by this string (which must be in vocab).
182
- num_reserved_ids: Number of IDs to save for reserved tokens like <EOS>.
183
- """
184
- super(TokenTextEncoder, self).__init__(num_reserved_ids=num_reserved_ids)
185
- self._reverse = reverse
186
- self._replace_oov = replace_oov
187
- if vocab_filename:
188
- self._init_vocab_from_file(vocab_filename)
189
- else:
190
- assert vocab_list is not None
191
- self._init_vocab_from_list(vocab_list)
192
- self.pad_index = self._token_to_id[PAD]
193
- self.eos_index = self._token_to_id[EOS]
194
- self.unk_index = self._token_to_id[UNK]
195
- self.seg_index = self._token_to_id[SEG] if SEG in self._token_to_id else self.eos_index
196
-
197
- def encode(self, s):
198
- """Converts a space-separated string of tokens to a list of ids."""
199
- sentence = s
200
- tokens = sentence.strip().split()
201
- if self._replace_oov is not None:
202
- tokens = [t if t in self._token_to_id else self._replace_oov
203
- for t in tokens]
204
- ret = [self._token_to_id[tok] for tok in tokens]
205
- return ret[::-1] if self._reverse else ret
206
-
207
- def decode(self, ids, strip_eos=False, strip_padding=False):
208
- if strip_padding and self.pad() in list(ids):
209
- pad_pos = list(ids).index(self.pad())
210
- ids = ids[:pad_pos]
211
- if strip_eos and self.eos() in list(ids):
212
- eos_pos = list(ids).index(self.eos())
213
- ids = ids[:eos_pos]
214
- return " ".join(self.decode_list(ids))
215
-
216
- def decode_list(self, ids):
217
- seq = reversed(ids) if self._reverse else ids
218
- return [self._safe_id_to_token(i) for i in seq]
219
-
220
- @property
221
- def vocab_size(self):
222
- return len(self._id_to_token)
223
-
224
- def __len__(self):
225
- return self.vocab_size
226
-
227
- def _safe_id_to_token(self, idx):
228
- return self._id_to_token.get(idx, "ID_%d" % idx)
229
-
230
- def _init_vocab_from_file(self, filename):
231
- """Load vocab from a file.
232
-
233
- Args:
234
- filename: The file to load vocabulary from.
235
- """
236
- with open(filename) as f:
237
- tokens = [token.strip() for token in f.readlines()]
238
-
239
- def token_gen():
240
- for token in tokens:
241
- yield token
242
-
243
- self._init_vocab(token_gen(), add_reserved_tokens=False)
244
-
245
- def _init_vocab_from_list(self, vocab_list):
246
- """Initialize tokens from a list of tokens.
247
-
248
- It is ok if reserved tokens appear in the vocab list. They will be
249
- removed. The set of tokens in vocab_list should be unique.
250
-
251
- Args:
252
- vocab_list: A list of tokens.
253
- """
254
- def token_gen():
255
- for token in vocab_list:
256
- if token not in RESERVED_TOKENS:
257
- yield token
258
-
259
- self._init_vocab(token_gen())
260
-
261
- def _init_vocab(self, token_generator, add_reserved_tokens=True):
262
- """Initialize vocabulary with tokens from token_generator."""
263
-
264
- self._id_to_token = {}
265
- non_reserved_start_index = 0
266
-
267
- if add_reserved_tokens:
268
- self._id_to_token.update(enumerate(RESERVED_TOKENS))
269
- non_reserved_start_index = len(RESERVED_TOKENS)
270
-
271
- self._id_to_token.update(
272
- enumerate(token_generator, start=non_reserved_start_index))
273
-
274
- # _token_to_id is the reverse of _id_to_token
275
- self._token_to_id = dict((v, k)
276
- for k, v in six.iteritems(self._id_to_token))
277
-
278
- def pad(self):
279
- return self.pad_index
280
-
281
- def eos(self):
282
- return self.eos_index
283
-
284
- def unk(self):
285
- return self.unk_index
286
-
287
- def seg(self):
288
- return self.seg_index
289
-
290
- def store_to_file(self, filename):
291
- """Write vocab file to disk.
292
-
293
- Vocab files have one token per line. The file ends in a newline. Reserved
294
- tokens are written to the vocab file as well.
295
-
296
- Args:
297
- filename: Full path of the file to store the vocab to.
298
- """
299
- with open(filename, "w") as f:
300
- for i in range(len(self._id_to_token)):
301
- f.write(self._id_to_token[i] + "\n")
302
-
303
- def sil_phonemes(self):
304
- return [p for p in self._id_to_token.values() if not p[0].isalpha()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/text_norm.py DELETED
@@ -1,790 +0,0 @@
1
- # coding=utf-8
2
- # Authors:
3
- # 2019.5 Zhiyang Zhou (https://github.com/Joee1995/chn_text_norm.git)
4
- # 2019.9 Jiayu DU
5
- #
6
- # requirements:
7
- # - python 3.X
8
- # notes: python 2.X WILL fail or produce misleading results
9
-
10
- import sys, os, argparse, codecs, string, re
11
-
12
- # ================================================================================ #
13
- # basic constant
14
- # ================================================================================ #
15
- CHINESE_DIGIS = u'零一二三四五六七八九'
16
- BIG_CHINESE_DIGIS_SIMPLIFIED = u'零壹贰叁肆伍陆柒捌玖'
17
- BIG_CHINESE_DIGIS_TRADITIONAL = u'零壹貳參肆伍陸柒捌玖'
18
- SMALLER_BIG_CHINESE_UNITS_SIMPLIFIED = u'十百千万'
19
- SMALLER_BIG_CHINESE_UNITS_TRADITIONAL = u'拾佰仟萬'
20
- LARGER_CHINESE_NUMERING_UNITS_SIMPLIFIED = u'亿兆京垓秭穰沟涧正载'
21
- LARGER_CHINESE_NUMERING_UNITS_TRADITIONAL = u'億兆京垓秭穰溝澗正載'
22
- SMALLER_CHINESE_NUMERING_UNITS_SIMPLIFIED = u'十百千万'
23
- SMALLER_CHINESE_NUMERING_UNITS_TRADITIONAL = u'拾佰仟萬'
24
-
25
- ZERO_ALT = u'〇'
26
- ONE_ALT = u'幺'
27
- TWO_ALTS = [u'两', u'兩']
28
-
29
- POSITIVE = [u'正', u'正']
30
- NEGATIVE = [u'负', u'負']
31
- POINT = [u'点', u'點']
32
- # PLUS = [u'加', u'加']
33
- # SIL = [u'杠', u'槓']
34
-
35
- # 中文数字系统类型
36
- NUMBERING_TYPES = ['low', 'mid', 'high']
37
-
38
- CURRENCY_NAMES = '(人民币|美元|日元|英镑|欧元|马克|法郎|加拿大元|澳元|港币|先令|芬兰马克|爱尔兰镑|' \
39
- '里拉|荷兰盾|埃斯库多|比塞塔|印尼盾|林吉特|新西兰元|比索|卢布|新加坡元|韩元|泰铢)'
40
- CURRENCY_UNITS = '((亿|千万|百万|万|千|百)|(亿|千万|百万|万|千|百|)元|(亿|千万|百万|万|千|百|)块|角|毛|分)'
41
- COM_QUANTIFIERS = '(匹|张|座|回|场|尾|条|个|首|阙|阵|网|炮|顶|丘|棵|只|支|袭|辆|挑|担|颗|壳|窠|曲|墙|群|腔|' \
42
- '砣|座|客|贯|扎|捆|刀|令|打|手|罗|坡|山|岭|江|溪|钟|队|单|双|对|出|口|头|脚|板|跳|枝|件|贴|' \
43
- '针|线|管|名|位|身|堂|课|本|页|家|户|层|丝|毫|厘|分|钱|两|斤|担|铢|石|钧|锱|忽|(千|毫|微)克|' \
44
- '毫|厘|分|寸|尺|丈|里|寻|常|铺|程|(千|分|厘|毫|微)米|撮|勺|合|升|斗|石|盘|碗|碟|叠|桶|笼|盆|' \
45
- '盒|杯|钟|斛|锅|簋|篮|盘|桶|罐|瓶|壶|卮|盏|箩|箱|煲|啖|袋|钵|年|月|日|季|刻|时|周|天|秒|分|旬|' \
46
- '纪|岁|世|更|夜|春|夏|秋|冬|代|伏|辈|丸|泡|粒|颗|幢|堆|条|根|支|道|面|片|张|颗|块)'
47
-
48
- # punctuation information are based on Zhon project (https://github.com/tsroten/zhon.git)
49
- CHINESE_PUNC_STOP = '!?。。'
50
- CHINESE_PUNC_NON_STOP = '"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃《》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏'
51
- CHINESE_PUNC_LIST = CHINESE_PUNC_STOP + CHINESE_PUNC_NON_STOP
52
-
53
-
54
- # ================================================================================ #
55
- # basic class
56
- # ================================================================================ #
57
- class ChineseChar(object):
58
- """
59
- 中文字符
60
- 每个字符对应简体和繁体,
61
- e.g. 简体 = '负', 繁体 = '負'
62
- 转换时可转换为简体或繁体
63
- """
64
-
65
- def __init__(self, simplified, traditional):
66
- self.simplified = simplified
67
- self.traditional = traditional
68
- # self.__repr__ = self.__str__
69
-
70
- def __str__(self):
71
- return self.simplified or self.traditional or None
72
-
73
- def __repr__(self):
74
- return self.__str__()
75
-
76
-
77
- class ChineseNumberUnit(ChineseChar):
78
- """
79
- 中文数字/数位字符
80
- 每个字符除繁简体外还有一个额外的大写字符
81
- e.g. '陆' 和 '陸'
82
- """
83
-
84
- def __init__(self, power, simplified, traditional, big_s, big_t):
85
- super(ChineseNumberUnit, self).__init__(simplified, traditional)
86
- self.power = power
87
- self.big_s = big_s
88
- self.big_t = big_t
89
-
90
- def __str__(self):
91
- return '10^{}'.format(self.power)
92
-
93
- @classmethod
94
- def create(cls, index, value, numbering_type=NUMBERING_TYPES[1], small_unit=False):
95
-
96
- if small_unit:
97
- return ChineseNumberUnit(power=index + 1,
98
- simplified=value[0], traditional=value[1], big_s=value[1], big_t=value[1])
99
- elif numbering_type == NUMBERING_TYPES[0]:
100
- return ChineseNumberUnit(power=index + 8,
101
- simplified=value[0], traditional=value[1], big_s=value[0], big_t=value[1])
102
- elif numbering_type == NUMBERING_TYPES[1]:
103
- return ChineseNumberUnit(power=(index + 2) * 4,
104
- simplified=value[0], traditional=value[1], big_s=value[0], big_t=value[1])
105
- elif numbering_type == NUMBERING_TYPES[2]:
106
- return ChineseNumberUnit(power=pow(2, index + 3),
107
- simplified=value[0], traditional=value[1], big_s=value[0], big_t=value[1])
108
- else:
109
- raise ValueError(
110
- 'Counting type should be in {0} ({1} provided).'.format(NUMBERING_TYPES, numbering_type))
111
-
112
-
113
- class ChineseNumberDigit(ChineseChar):
114
- """
115
- 中文数字字符
116
- """
117
-
118
- def __init__(self, value, simplified, traditional, big_s, big_t, alt_s=None, alt_t=None):
119
- super(ChineseNumberDigit, self).__init__(simplified, traditional)
120
- self.value = value
121
- self.big_s = big_s
122
- self.big_t = big_t
123
- self.alt_s = alt_s
124
- self.alt_t = alt_t
125
-
126
- def __str__(self):
127
- return str(self.value)
128
-
129
- @classmethod
130
- def create(cls, i, v):
131
- return ChineseNumberDigit(i, v[0], v[1], v[2], v[3])
132
-
133
-
134
- class ChineseMath(ChineseChar):
135
- """
136
- 中文数位字符
137
- """
138
-
139
- def __init__(self, simplified, traditional, symbol, expression=None):
140
- super(ChineseMath, self).__init__(simplified, traditional)
141
- self.symbol = symbol
142
- self.expression = expression
143
- self.big_s = simplified
144
- self.big_t = traditional
145
-
146
-
147
- CC, CNU, CND, CM = ChineseChar, ChineseNumberUnit, ChineseNumberDigit, ChineseMath
148
-
149
-
150
- class NumberSystem(object):
151
- """
152
- 中文数字系统
153
- """
154
- pass
155
-
156
-
157
- class MathSymbol(object):
158
- """
159
- 用于中文数字系统的数学符号 (繁/简体), e.g.
160
- positive = ['正', '正']
161
- negative = ['负', '負']
162
- point = ['点', '點']
163
- """
164
-
165
- def __init__(self, positive, negative, point):
166
- self.positive = positive
167
- self.negative = negative
168
- self.point = point
169
-
170
- def __iter__(self):
171
- for v in self.__dict__.values():
172
- yield v
173
-
174
-
175
- # class OtherSymbol(object):
176
- # """
177
- # 其他符号
178
- # """
179
- #
180
- # def __init__(self, sil):
181
- # self.sil = sil
182
- #
183
- # def __iter__(self):
184
- # for v in self.__dict__.values():
185
- # yield v
186
-
187
-
188
- # ================================================================================ #
189
- # basic utils
190
- # ================================================================================ #
191
- def create_system(numbering_type=NUMBERING_TYPES[1]):
192
- """
193
- 根据数字系统类型返回创建相应的数字系统,默认为 mid
194
- NUMBERING_TYPES = ['low', 'mid', 'high']: 中文数字系统类型
195
- low: '兆' = '亿' * '十' = $10^{9}$, '京' = '兆' * '十', etc.
196
- mid: '兆' = '亿' * '万' = $10^{12}$, '京' = '兆' * '万', etc.
197
- high: '兆' = '亿' * '亿' = $10^{16}$, '京' = '兆' * '兆', etc.
198
- 返回对应的数字系统
199
- """
200
-
201
- # chinese number units of '亿' and larger
202
- all_larger_units = zip(
203
- LARGER_CHINESE_NUMERING_UNITS_SIMPLIFIED, LARGER_CHINESE_NUMERING_UNITS_TRADITIONAL)
204
- larger_units = [CNU.create(i, v, numbering_type, False)
205
- for i, v in enumerate(all_larger_units)]
206
- # chinese number units of '十, 百, 千, 万'
207
- all_smaller_units = zip(
208
- SMALLER_CHINESE_NUMERING_UNITS_SIMPLIFIED, SMALLER_CHINESE_NUMERING_UNITS_TRADITIONAL)
209
- smaller_units = [CNU.create(i, v, small_unit=True)
210
- for i, v in enumerate(all_smaller_units)]
211
- # digis
212
- chinese_digis = zip(CHINESE_DIGIS, CHINESE_DIGIS,
213
- BIG_CHINESE_DIGIS_SIMPLIFIED, BIG_CHINESE_DIGIS_TRADITIONAL)
214
- digits = [CND.create(i, v) for i, v in enumerate(chinese_digis)]
215
- digits[0].alt_s, digits[0].alt_t = ZERO_ALT, ZERO_ALT
216
- digits[1].alt_s, digits[1].alt_t = ONE_ALT, ONE_ALT
217
- digits[2].alt_s, digits[2].alt_t = TWO_ALTS[0], TWO_ALTS[1]
218
-
219
- # symbols
220
- positive_cn = CM(POSITIVE[0], POSITIVE[1], '+', lambda x: x)
221
- negative_cn = CM(NEGATIVE[0], NEGATIVE[1], '-', lambda x: -x)
222
- point_cn = CM(POINT[0], POINT[1], '.', lambda x,
223
- y: float(str(x) + '.' + str(y)))
224
- # sil_cn = CM(SIL[0], SIL[1], '-', lambda x, y: float(str(x) + '-' + str(y)))
225
- system = NumberSystem()
226
- system.units = smaller_units + larger_units
227
- system.digits = digits
228
- system.math = MathSymbol(positive_cn, negative_cn, point_cn)
229
- # system.symbols = OtherSymbol(sil_cn)
230
- return system
231
-
232
-
233
- def chn2num(chinese_string, numbering_type=NUMBERING_TYPES[1]):
234
- def get_symbol(char, system):
235
- for u in system.units:
236
- if char in [u.traditional, u.simplified, u.big_s, u.big_t]:
237
- return u
238
- for d in system.digits:
239
- if char in [d.traditional, d.simplified, d.big_s, d.big_t, d.alt_s, d.alt_t]:
240
- return d
241
- for m in system.math:
242
- if char in [m.traditional, m.simplified]:
243
- return m
244
-
245
- def string2symbols(chinese_string, system):
246
- int_string, dec_string = chinese_string, ''
247
- for p in [system.math.point.simplified, system.math.point.traditional]:
248
- if p in chinese_string:
249
- int_string, dec_string = chinese_string.split(p)
250
- break
251
- return [get_symbol(c, system) for c in int_string], \
252
- [get_symbol(c, system) for c in dec_string]
253
-
254
- def correct_symbols(integer_symbols, system):
255
- """
256
- 一百八 to 一百八十
257
- 一亿一千三百万 to 一亿 一千万 三百万
258
- """
259
-
260
- if integer_symbols and isinstance(integer_symbols[0], CNU):
261
- if integer_symbols[0].power == 1:
262
- integer_symbols = [system.digits[1]] + integer_symbols
263
-
264
- if len(integer_symbols) > 1:
265
- if isinstance(integer_symbols[-1], CND) and isinstance(integer_symbols[-2], CNU):
266
- integer_symbols.append(
267
- CNU(integer_symbols[-2].power - 1, None, None, None, None))
268
-
269
- result = []
270
- unit_count = 0
271
- for s in integer_symbols:
272
- if isinstance(s, CND):
273
- result.append(s)
274
- unit_count = 0
275
- elif isinstance(s, CNU):
276
- current_unit = CNU(s.power, None, None, None, None)
277
- unit_count += 1
278
-
279
- if unit_count == 1:
280
- result.append(current_unit)
281
- elif unit_count > 1:
282
- for i in range(len(result)):
283
- if isinstance(result[-i - 1], CNU) and result[-i - 1].power < current_unit.power:
284
- result[-i - 1] = CNU(result[-i - 1].power +
285
- current_unit.power, None, None, None, None)
286
- return result
287
-
288
- def compute_value(integer_symbols):
289
- """
290
- Compute the value.
291
- When current unit is larger than previous unit, current unit * all previous units will be used as all previous units.
292
- e.g. '两千万' = 2000 * 10000 not 2000 + 10000
293
- """
294
- value = [0]
295
- last_power = 0
296
- for s in integer_symbols:
297
- if isinstance(s, CND):
298
- value[-1] = s.value
299
- elif isinstance(s, CNU):
300
- value[-1] *= pow(10, s.power)
301
- if s.power > last_power:
302
- value[:-1] = list(map(lambda v: v *
303
- pow(10, s.power), value[:-1]))
304
- last_power = s.power
305
- value.append(0)
306
- return sum(value)
307
-
308
- system = create_system(numbering_type)
309
- int_part, dec_part = string2symbols(chinese_string, system)
310
- int_part = correct_symbols(int_part, system)
311
- int_str = str(compute_value(int_part))
312
- dec_str = ''.join([str(d.value) for d in dec_part])
313
- if dec_part:
314
- return '{0}.{1}'.format(int_str, dec_str)
315
- else:
316
- return int_str
317
-
318
-
319
- def num2chn(number_string, numbering_type=NUMBERING_TYPES[1], big=False,
320
- traditional=False, alt_zero=False, alt_one=False, alt_two=True,
321
- use_zeros=True, use_units=True):
322
- def get_value(value_string, use_zeros=True):
323
-
324
- striped_string = value_string.lstrip('0')
325
-
326
- # record nothing if all zeros
327
- if not striped_string:
328
- return []
329
-
330
- # record one digits
331
- elif len(striped_string) == 1:
332
- if use_zeros and len(value_string) != len(striped_string):
333
- return [system.digits[0], system.digits[int(striped_string)]]
334
- else:
335
- return [system.digits[int(striped_string)]]
336
-
337
- # recursively record multiple digits
338
- else:
339
- result_unit = next(u for u in reversed(
340
- system.units) if u.power < len(striped_string))
341
- result_string = value_string[:-result_unit.power]
342
- return get_value(result_string) + [result_unit] + get_value(striped_string[-result_unit.power:])
343
-
344
- system = create_system(numbering_type)
345
-
346
- int_dec = number_string.split('.')
347
- if len(int_dec) == 1:
348
- int_string = int_dec[0]
349
- dec_string = ""
350
- elif len(int_dec) == 2:
351
- int_string = int_dec[0]
352
- dec_string = int_dec[1]
353
- else:
354
- raise ValueError(
355
- "invalid input num string with more than one dot: {}".format(number_string))
356
-
357
- if use_units and len(int_string) > 1:
358
- result_symbols = get_value(int_string)
359
- else:
360
- result_symbols = [system.digits[int(c)] for c in int_string]
361
- dec_symbols = [system.digits[int(c)] for c in dec_string]
362
- if dec_string:
363
- result_symbols += [system.math.point] + dec_symbols
364
-
365
- if alt_two:
366
- liang = CND(2, system.digits[2].alt_s, system.digits[2].alt_t,
367
- system.digits[2].big_s, system.digits[2].big_t)
368
- for i, v in enumerate(result_symbols):
369
- if isinstance(v, CND) and v.value == 2:
370
- next_symbol = result_symbols[i +
371
- 1] if i < len(result_symbols) - 1 else None
372
- previous_symbol = result_symbols[i - 1] if i > 0 else None
373
- if isinstance(next_symbol, CNU) and isinstance(previous_symbol, (CNU, type(None))):
374
- if next_symbol.power != 1 and ((previous_symbol is None) or (previous_symbol.power != 1)):
375
- result_symbols[i] = liang
376
-
377
- # if big is True, '两' will not be used and `alt_two` has no impact on output
378
- if big:
379
- attr_name = 'big_'
380
- if traditional:
381
- attr_name += 't'
382
- else:
383
- attr_name += 's'
384
- else:
385
- if traditional:
386
- attr_name = 'traditional'
387
- else:
388
- attr_name = 'simplified'
389
-
390
- result = ''.join([getattr(s, attr_name) for s in result_symbols])
391
-
392
- # if not use_zeros:
393
- # result = result.strip(getattr(system.digits[0], attr_name))
394
-
395
- if alt_zero:
396
- result = result.replace(
397
- getattr(system.digits[0], attr_name), system.digits[0].alt_s)
398
-
399
- if alt_one:
400
- result = result.replace(
401
- getattr(system.digits[1], attr_name), system.digits[1].alt_s)
402
-
403
- for i, p in enumerate(POINT):
404
- if result.startswith(p):
405
- return CHINESE_DIGIS[0] + result
406
-
407
- # ^10, 11, .., 19
408
- if len(result) >= 2 and result[1] in [SMALLER_CHINESE_NUMERING_UNITS_SIMPLIFIED[0],
409
- SMALLER_CHINESE_NUMERING_UNITS_TRADITIONAL[0]] and \
410
- result[0] in [CHINESE_DIGIS[1], BIG_CHINESE_DIGIS_SIMPLIFIED[1], BIG_CHINESE_DIGIS_TRADITIONAL[1]]:
411
- result = result[1:]
412
-
413
- return result
414
-
415
-
416
- # ================================================================================ #
417
- # different types of rewriters
418
- # ================================================================================ #
419
- class Cardinal:
420
- """
421
- CARDINAL类
422
- """
423
-
424
- def __init__(self, cardinal=None, chntext=None):
425
- self.cardinal = cardinal
426
- self.chntext = chntext
427
-
428
- def chntext2cardinal(self):
429
- return chn2num(self.chntext)
430
-
431
- def cardinal2chntext(self):
432
- return num2chn(self.cardinal)
433
-
434
-
435
- class Digit:
436
- """
437
- DIGIT类
438
- """
439
-
440
- def __init__(self, digit=None, chntext=None):
441
- self.digit = digit
442
- self.chntext = chntext
443
-
444
- # def chntext2digit(self):
445
- # return chn2num(self.chntext)
446
-
447
- def digit2chntext(self):
448
- return num2chn(self.digit, alt_two=False, use_units=False)
449
-
450
-
451
- class TelePhone:
452
- """
453
- TELEPHONE类
454
- """
455
-
456
- def __init__(self, telephone=None, raw_chntext=None, chntext=None):
457
- self.telephone = telephone
458
- self.raw_chntext = raw_chntext
459
- self.chntext = chntext
460
-
461
- # def chntext2telephone(self):
462
- # sil_parts = self.raw_chntext.split('<SIL>')
463
- # self.telephone = '-'.join([
464
- # str(chn2num(p)) for p in sil_parts
465
- # ])
466
- # return self.telephone
467
-
468
- def telephone2chntext(self, fixed=False):
469
-
470
- if fixed:
471
- sil_parts = self.telephone.split('-')
472
- self.raw_chntext = '<SIL>'.join([
473
- num2chn(part, alt_two=False, use_units=False) for part in sil_parts
474
- ])
475
- self.chntext = self.raw_chntext.replace('<SIL>', '')
476
- else:
477
- sp_parts = self.telephone.strip('+').split()
478
- self.raw_chntext = '<SP>'.join([
479
- num2chn(part, alt_two=False, use_units=False) for part in sp_parts
480
- ])
481
- self.chntext = self.raw_chntext.replace('<SP>', '')
482
- return self.chntext
483
-
484
-
485
- class Fraction:
486
- """
487
- FRACTION类
488
- """
489
-
490
- def __init__(self, fraction=None, chntext=None):
491
- self.fraction = fraction
492
- self.chntext = chntext
493
-
494
- def chntext2fraction(self):
495
- denominator, numerator = self.chntext.split('分之')
496
- return chn2num(numerator) + '/' + chn2num(denominator)
497
-
498
- def fraction2chntext(self):
499
- numerator, denominator = self.fraction.split('/')
500
- return num2chn(denominator) + '分之' + num2chn(numerator)
501
-
502
-
503
- class Date:
504
- """
505
- DATE类
506
- """
507
-
508
- def __init__(self, date=None, chntext=None):
509
- self.date = date
510
- self.chntext = chntext
511
-
512
- # def chntext2date(self):
513
- # chntext = self.chntext
514
- # try:
515
- # year, other = chntext.strip().split('年', maxsplit=1)
516
- # year = Digit(chntext=year).digit2chntext() + '年'
517
- # except ValueError:
518
- # other = chntext
519
- # year = ''
520
- # if other:
521
- # try:
522
- # month, day = other.strip().split('月', maxsplit=1)
523
- # month = Cardinal(chntext=month).chntext2cardinal() + '月'
524
- # except ValueError:
525
- # day = chntext
526
- # month = ''
527
- # if day:
528
- # day = Cardinal(chntext=day[:-1]).chntext2cardinal() + day[-1]
529
- # else:
530
- # month = ''
531
- # day = ''
532
- # date = year + month + day
533
- # self.date = date
534
- # return self.date
535
-
536
- def date2chntext(self):
537
- date = self.date
538
- try:
539
- year, other = date.strip().split('年', 1)
540
- year = Digit(digit=year).digit2chntext() + '年'
541
- except ValueError:
542
- other = date
543
- year = ''
544
- if other:
545
- try:
546
- month, day = other.strip().split('月', 1)
547
- month = Cardinal(cardinal=month).cardinal2chntext() + '月'
548
- except ValueError:
549
- day = date
550
- month = ''
551
- if day:
552
- day = Cardinal(cardinal=day[:-1]).cardinal2chntext() + day[-1]
553
- else:
554
- month = ''
555
- day = ''
556
- chntext = year + month + day
557
- self.chntext = chntext
558
- return self.chntext
559
-
560
-
561
- class Money:
562
- """
563
- MONEY类
564
- """
565
-
566
- def __init__(self, money=None, chntext=None):
567
- self.money = money
568
- self.chntext = chntext
569
-
570
- # def chntext2money(self):
571
- # return self.money
572
-
573
- def money2chntext(self):
574
- money = self.money
575
- pattern = re.compile(r'(\d+(\.\d+)?)')
576
- matchers = pattern.findall(money)
577
- if matchers:
578
- for matcher in matchers:
579
- money = money.replace(matcher[0], Cardinal(cardinal=matcher[0]).cardinal2chntext())
580
- self.chntext = money
581
- return self.chntext
582
-
583
-
584
- class Percentage:
585
- """
586
- PERCENTAGE类
587
- """
588
-
589
- def __init__(self, percentage=None, chntext=None):
590
- self.percentage = percentage
591
- self.chntext = chntext
592
-
593
- def chntext2percentage(self):
594
- return chn2num(self.chntext.strip().strip('百分之')) + '%'
595
-
596
- def percentage2chntext(self):
597
- return '百分之' + num2chn(self.percentage.strip().strip('%'))
598
-
599
-
600
- # ================================================================================ #
601
- # NSW Normalizer
602
- # ================================================================================ #
603
- class NSWNormalizer:
604
- def __init__(self, raw_text):
605
- self.raw_text = '^' + raw_text + '$'
606
- self.norm_text = ''
607
-
608
- def _particular(self):
609
- text = self.norm_text
610
- pattern = re.compile(r"(([a-zA-Z]+)二([a-zA-Z]+))")
611
- matchers = pattern.findall(text)
612
- if matchers:
613
- # print('particular')
614
- for matcher in matchers:
615
- text = text.replace(matcher[0], matcher[1] + '2' + matcher[2], 1)
616
- self.norm_text = text
617
- return self.norm_text
618
-
619
- def normalize(self, remove_punc=True):
620
- text = self.raw_text
621
-
622
- # 规范化日期
623
- pattern = re.compile(r"\D+((([089]\d|(19|20)\d{2})年)?(\d{1,2}月(\d{1,2}[日号])?)?)")
624
- matchers = pattern.findall(text)
625
- if matchers:
626
- # print('date')
627
- for matcher in matchers:
628
- text = text.replace(matcher[0], Date(date=matcher[0]).date2chntext(), 1)
629
-
630
- # 规范化金钱
631
- pattern = re.compile(r"\D+((\d+(\.\d+)?)[多余几]?" + CURRENCY_UNITS + r"(\d" + CURRENCY_UNITS + r"?)?)")
632
- matchers = pattern.findall(text)
633
- if matchers:
634
- # print('money')
635
- for matcher in matchers:
636
- text = text.replace(matcher[0], Money(money=matcher[0]).money2chntext(), 1)
637
-
638
- # 规范化固话/手机号码
639
- # 手机
640
- # http://www.jihaoba.com/news/show/13680
641
- # 移动:139、138、137、136、135、134、159、158、157、150、151、152、188、187、182、183、184、178、198
642
- # 联通:130、131、132、156、155、186、185、176
643
- # 电信:133、153、189、180、181、177
644
- pattern = re.compile(r"\D((\+?86 ?)?1([38]\d|5[0-35-9]|7[678]|9[89])\d{8})\D")
645
- matchers = pattern.findall(text)
646
- if matchers:
647
- # print('telephone')
648
- for matcher in matchers:
649
- text = text.replace(matcher[0], TelePhone(telephone=matcher[0]).telephone2chntext(), 1)
650
- # 固话
651
- pattern = re.compile(r"\D((0(10|2[1-3]|[3-9]\d{2})-?)?[1-9]\d{6,7})\D")
652
- matchers = pattern.findall(text)
653
- if matchers:
654
- # print('fixed telephone')
655
- for matcher in matchers:
656
- text = text.replace(matcher[0], TelePhone(telephone=matcher[0]).telephone2chntext(fixed=True), 1)
657
-
658
- # 规范化分数
659
- pattern = re.compile(r"(\d+/\d+)")
660
- matchers = pattern.findall(text)
661
- if matchers:
662
- # print('fraction')
663
- for matcher in matchers:
664
- text = text.replace(matcher, Fraction(fraction=matcher).fraction2chntext(), 1)
665
-
666
- # 规范化百分数
667
- text = text.replace('%', '%')
668
- pattern = re.compile(r"(\d+(\.\d+)?%)")
669
- matchers = pattern.findall(text)
670
- if matchers:
671
- # print('percentage')
672
- for matcher in matchers:
673
- text = text.replace(matcher[0], Percentage(percentage=matcher[0]).percentage2chntext(), 1)
674
-
675
- # 规范化纯数+量词
676
- pattern = re.compile(r"(\d+(\.\d+)?)[多余几]?" + COM_QUANTIFIERS)
677
- matchers = pattern.findall(text)
678
- if matchers:
679
- # print('cardinal+quantifier')
680
- for matcher in matchers:
681
- text = text.replace(matcher[0], Cardinal(cardinal=matcher[0]).cardinal2chntext(), 1)
682
-
683
- # 规范化数字编号
684
- pattern = re.compile(r"(\d{4,32})")
685
- matchers = pattern.findall(text)
686
- if matchers:
687
- # print('digit')
688
- for matcher in matchers:
689
- text = text.replace(matcher, Digit(digit=matcher).digit2chntext(), 1)
690
-
691
- # 规范化纯数
692
- pattern = re.compile(r"(\d+(\.\d+)?)")
693
- matchers = pattern.findall(text)
694
- if matchers:
695
- # print('cardinal')
696
- for matcher in matchers:
697
- text = text.replace(matcher[0], Cardinal(cardinal=matcher[0]).cardinal2chntext(), 1)
698
-
699
- self.norm_text = text
700
- self._particular()
701
-
702
- text = self.norm_text.lstrip('^').rstrip('$')
703
- if remove_punc:
704
- # Punctuations removal
705
- old_chars = CHINESE_PUNC_LIST + string.punctuation # includes all CN and EN punctuations
706
- new_chars = ' ' * len(old_chars)
707
- del_chars = ''
708
- text = text.translate(str.maketrans(old_chars, new_chars, del_chars))
709
- return text
710
-
711
-
712
- def nsw_test_case(raw_text):
713
- print('I:' + raw_text)
714
- print('O:' + NSWNormalizer(raw_text).normalize())
715
- print('')
716
-
717
-
718
- def nsw_test():
719
- nsw_test_case('固话:0595-23865596或23880880。')
720
- nsw_test_case('固话:0595-23865596或23880880。')
721
- nsw_test_case('手机:+86 19859213959或15659451527。')
722
- nsw_test_case('分数:32477/76391。')
723
- nsw_test_case('百分数:80.03%。')
724
- nsw_test_case('编号:31520181154418。')
725
- nsw_test_case('纯数:2983.07克或12345.60米。')
726
- nsw_test_case('日期:1999年2月20日或09年3月15号。')
727
- nsw_test_case('金钱:12块5,34.5元,20.1万')
728
- nsw_test_case('特殊:O2O或B2C。')
729
- nsw_test_case('3456万吨')
730
- nsw_test_case('2938个')
731
- nsw_test_case('938')
732
- nsw_test_case('今天吃了115个小笼包231个馒头')
733
- nsw_test_case('有62%的概率')
734
-
735
-
736
- if __name__ == '__main__':
737
- # nsw_test()
738
-
739
- p = argparse.ArgumentParser()
740
- p.add_argument('ifile', help='input filename, assume utf-8 encoding')
741
- p.add_argument('ofile', help='output filename')
742
- p.add_argument('--to_upper', action='store_true', help='convert to upper case')
743
- p.add_argument('--to_lower', action='store_true', help='convert to lower case')
744
- p.add_argument('--has_key', action='store_true', help="input text has Kaldi's key as first field.")
745
- p.add_argument('--log_interval', type=int, default=10000, help='log interval in number of processed lines')
746
- args = p.parse_args()
747
-
748
- ifile = codecs.open(args.ifile, 'r', 'utf8')
749
- ofile = codecs.open(args.ofile, 'w+', 'utf8')
750
-
751
- n = 0
752
- for l in ifile:
753
- key = ''
754
- text = ''
755
- if args.has_key:
756
- cols = l.split(maxsplit=1)
757
- key = cols[0]
758
- if len(cols) == 2:
759
- text = cols[1]
760
- else:
761
- text = ''
762
- else:
763
- text = l
764
-
765
- # cases
766
- if args.to_upper and args.to_lower:
767
- sys.stderr.write('text norm: to_upper OR to_lower?')
768
- exit(1)
769
- if args.to_upper:
770
- text = text.upper()
771
- if args.to_lower:
772
- text = text.lower()
773
-
774
- # NSW(Non-Standard-Word) normalization
775
- text = NSWNormalizer(text).normalize()
776
-
777
- #
778
- if args.has_key:
779
- ofile.write(key + '\t' + text)
780
- else:
781
- ofile.write(text)
782
-
783
- n += 1
784
- if n % args.log_interval == 0:
785
- sys.stderr.write("text norm: {} lines done.\n".format(n))
786
-
787
- sys.stderr.write("text norm: {} lines done in total.\n".format(n))
788
-
789
- ifile.close()
790
- ofile.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
utils/training_utils.py DELETED
@@ -1,27 +0,0 @@
1
- from utils.hparams import hparams
2
-
3
-
4
- class RSQRTSchedule(object):
5
- def __init__(self, optimizer):
6
- super().__init__()
7
- self.optimizer = optimizer
8
- self.constant_lr = hparams['lr']
9
- self.warmup_updates = hparams['warmup_updates']
10
- self.hidden_size = hparams['hidden_size']
11
- self.lr = hparams['lr']
12
- for param_group in optimizer.param_groups:
13
- param_group['lr'] = self.lr
14
- self.step(0)
15
-
16
- def step(self, num_updates):
17
- constant_lr = self.constant_lr
18
- warmup = min(num_updates / self.warmup_updates, 1.0)
19
- rsqrt_decay = max(self.warmup_updates, num_updates) ** -0.5
20
- rsqrt_hidden = self.hidden_size ** -0.5
21
- self.lr = max(constant_lr * warmup * rsqrt_decay * rsqrt_hidden, 1e-7)
22
- for param_group in self.optimizer.param_groups:
23
- param_group['lr'] = self.lr
24
- return self.lr
25
-
26
- def get_lr(self):
27
- return self.optimizer.param_groups[0]['lr']