Plana-Archive commited on
Commit
b0f1341
·
verified ·
1 Parent(s): 301fc9d

Clean up previous raw files

Browse files
Files changed (1) hide show
  1. Zero-CPU/utils.py +0 -498
Zero-CPU/utils.py DELETED
@@ -1,498 +0,0 @@
1
- import argparse
2
- import glob
3
- import json
4
- import logging
5
- import os
6
- import re
7
- import subprocess
8
-
9
- import numpy as np
10
- import torch
11
- from huggingface_hub import hf_hub_download
12
- from safetensors import safe_open
13
- from safetensors.torch import save_file
14
- from scipy.io.wavfile import read
15
-
16
- from common.log import logger
17
-
18
- MATPLOTLIB_FLAG = False
19
-
20
-
21
- def download_checkpoint(
22
- dir_path, repo_config, token=None, regex="G_*.pth", mirror="openi"
23
- ):
24
- repo_id = repo_config["repo_id"]
25
- f_list = glob.glob(os.path.join(dir_path, regex))
26
- if f_list:
27
- print("Use existed model, skip downloading.")
28
- return
29
- for file in ["DUR_0.pth", "D_0.pth", "G_0.pth"]:
30
- hf_hub_download(repo_id, file, local_dir=dir_path, local_dir_use_symlinks=False)
31
-
32
-
33
- def load_checkpoint(
34
- checkpoint_path, model, optimizer=None, skip_optimizer=False, for_infer=False
35
- ):
36
- assert os.path.isfile(checkpoint_path)
37
- checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
38
- iteration = checkpoint_dict["iteration"]
39
- learning_rate = checkpoint_dict["learning_rate"]
40
- logger.info(
41
- f"Loading model and optimizer at iteration {iteration} from {checkpoint_path}"
42
- )
43
- if (
44
- optimizer is not None
45
- and not skip_optimizer
46
- and checkpoint_dict["optimizer"] is not None
47
- ):
48
- optimizer.load_state_dict(checkpoint_dict["optimizer"])
49
- elif optimizer is None and not skip_optimizer:
50
- # else: Disable this line if Infer and resume checkpoint,then enable the line upper
51
- new_opt_dict = optimizer.state_dict()
52
- new_opt_dict_params = new_opt_dict["param_groups"][0]["params"]
53
- new_opt_dict["param_groups"] = checkpoint_dict["optimizer"]["param_groups"]
54
- new_opt_dict["param_groups"][0]["params"] = new_opt_dict_params
55
- optimizer.load_state_dict(new_opt_dict)
56
-
57
- saved_state_dict = checkpoint_dict["model"]
58
- if hasattr(model, "module"):
59
- state_dict = model.module.state_dict()
60
- else:
61
- state_dict = model.state_dict()
62
-
63
- new_state_dict = {}
64
- for k, v in state_dict.items():
65
- try:
66
- # assert "emb_g" not in k
67
- new_state_dict[k] = saved_state_dict[k]
68
- assert saved_state_dict[k].shape == v.shape, (
69
- saved_state_dict[k].shape,
70
- v.shape,
71
- )
72
- except:
73
- # For upgrading from the old version
74
- if "ja_bert_proj" in k:
75
- v = torch.zeros_like(v)
76
- logger.warning(
77
- f"Seems you are using the old version of the model, the {k} is automatically set to zero for backward compatibility"
78
- )
79
- elif "enc_q" in k and for_infer:
80
- continue
81
- else:
82
- logger.error(f"{k} is not in the checkpoint {checkpoint_path}")
83
-
84
- new_state_dict[k] = v
85
-
86
- if hasattr(model, "module"):
87
- model.module.load_state_dict(new_state_dict, strict=False)
88
- else:
89
- model.load_state_dict(new_state_dict, strict=False)
90
-
91
- logger.info("Loaded '{}' (iteration {})".format(checkpoint_path, iteration))
92
-
93
- return model, optimizer, learning_rate, iteration
94
-
95
-
96
- def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
97
- logger.info(
98
- "Saving model and optimizer state at iteration {} to {}".format(
99
- iteration, checkpoint_path
100
- )
101
- )
102
- if hasattr(model, "module"):
103
- state_dict = model.module.state_dict()
104
- else:
105
- state_dict = model.state_dict()
106
- torch.save(
107
- {
108
- "model": state_dict,
109
- "iteration": iteration,
110
- "optimizer": optimizer.state_dict(),
111
- "learning_rate": learning_rate,
112
- },
113
- checkpoint_path,
114
- )
115
-
116
-
117
- def save_safetensors(model, iteration, checkpoint_path, is_half=False, for_infer=False):
118
- """
119
- Save model with safetensors.
120
- """
121
- if hasattr(model, "module"):
122
- state_dict = model.module.state_dict()
123
- else:
124
- state_dict = model.state_dict()
125
- keys = []
126
- for k in state_dict:
127
- if "enc_q" in k and for_infer:
128
- continue # noqa: E701
129
- keys.append(k)
130
-
131
- new_dict = (
132
- {k: state_dict[k].half() for k in keys}
133
- if is_half
134
- else {k: state_dict[k] for k in keys}
135
- )
136
- new_dict["iteration"] = torch.LongTensor([iteration])
137
- logger.info(f"Saved safetensors to {checkpoint_path}")
138
- save_file(new_dict, checkpoint_path)
139
-
140
-
141
- def load_safetensors(checkpoint_path, model, for_infer=False):
142
- """
143
- Load safetensors model.
144
- """
145
-
146
- tensors = {}
147
- iteration = None
148
- with safe_open(checkpoint_path, framework="pt", device="cpu") as f:
149
- for key in f.keys():
150
- if key == "iteration":
151
- iteration = f.get_tensor(key).item()
152
- tensors[key] = f.get_tensor(key)
153
- if hasattr(model, "module"):
154
- result = model.module.load_state_dict(tensors, strict=False)
155
- else:
156
- result = model.load_state_dict(tensors, strict=False)
157
- for key in result.missing_keys:
158
- if key.startswith("enc_q") and for_infer:
159
- continue
160
- logger.warning(f"Missing key: {key}")
161
- for key in result.unexpected_keys:
162
- if key == "iteration":
163
- continue
164
- logger.warning(f"Unexpected key: {key}")
165
- #logger.info(f"Swapped to model '{checkpoint_path}'")
166
- return model, iteration
167
-
168
-
169
- def summarize(
170
- writer,
171
- global_step,
172
- scalars={},
173
- histograms={},
174
- images={},
175
- audios={},
176
- audio_sampling_rate=22050,
177
- ):
178
- for k, v in scalars.items():
179
- writer.add_scalar(k, v, global_step)
180
- for k, v in histograms.items():
181
- writer.add_histogram(k, v, global_step)
182
- for k, v in images.items():
183
- writer.add_image(k, v, global_step, dataformats="HWC")
184
- for k, v in audios.items():
185
- writer.add_audio(k, v, global_step, audio_sampling_rate)
186
-
187
-
188
- def is_resuming(dir_path):
189
- # JP-ExtraバージョンではDURがなくWDがあったり変わるため、Gのみで判断する
190
- g_list = glob.glob(os.path.join(dir_path, "G_*.pth"))
191
- # d_list = glob.glob(os.path.join(dir_path, "D_*.pth"))
192
- # dur_list = glob.glob(os.path.join(dir_path, "DUR_*.pth"))
193
- return len(g_list) > 0
194
-
195
-
196
- def latest_checkpoint_path(dir_path, regex="G_*.pth"):
197
- f_list = glob.glob(os.path.join(dir_path, regex))
198
- f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
199
- try:
200
- x = f_list[-1]
201
- except IndexError:
202
- raise ValueError(f"No checkpoint found in {dir_path} with regex {regex}")
203
- return x
204
-
205
-
206
- def plot_spectrogram_to_numpy(spectrogram):
207
- global MATPLOTLIB_FLAG
208
- if not MATPLOTLIB_FLAG:
209
- import matplotlib
210
-
211
- matplotlib.use("Agg")
212
- MATPLOTLIB_FLAG = True
213
- mpl_logger = logging.getLogger("matplotlib")
214
- mpl_logger.setLevel(logging.WARNING)
215
- import matplotlib.pylab as plt
216
- import numpy as np
217
-
218
- fig, ax = plt.subplots(figsize=(10, 2))
219
- im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
220
- plt.colorbar(im, ax=ax)
221
- plt.xlabel("Frames")
222
- plt.ylabel("Channels")
223
- plt.tight_layout()
224
-
225
- fig.canvas.draw()
226
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
227
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
228
- plt.close()
229
- return data
230
-
231
-
232
- def plot_alignment_to_numpy(alignment, info=None):
233
- global MATPLOTLIB_FLAG
234
- if not MATPLOTLIB_FLAG:
235
- import matplotlib
236
-
237
- matplotlib.use("Agg")
238
- MATPLOTLIB_FLAG = True
239
- mpl_logger = logging.getLogger("matplotlib")
240
- mpl_logger.setLevel(logging.WARNING)
241
- import matplotlib.pylab as plt
242
- import numpy as np
243
-
244
- fig, ax = plt.subplots(figsize=(6, 4))
245
- im = ax.imshow(
246
- alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
247
- )
248
- fig.colorbar(im, ax=ax)
249
- xlabel = "Decoder timestep"
250
- if info is not None:
251
- xlabel += "\n\n" + info
252
- plt.xlabel(xlabel)
253
- plt.ylabel("Encoder timestep")
254
- plt.tight_layout()
255
-
256
- fig.canvas.draw()
257
- data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
258
- data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
259
- plt.close()
260
- return data
261
-
262
-
263
- def load_wav_to_torch(full_path):
264
- sampling_rate, data = read(full_path)
265
- return torch.FloatTensor(data.astype(np.float32)), sampling_rate
266
-
267
-
268
- def load_filepaths_and_text(filename, split="|"):
269
- with open(filename, encoding="utf-8") as f:
270
- filepaths_and_text = [line.strip().split(split) for line in f]
271
- return filepaths_and_text
272
-
273
-
274
- def get_hparams(init=True):
275
- parser = argparse.ArgumentParser()
276
- parser.add_argument(
277
- "-c",
278
- "--config",
279
- type=str,
280
- default="./configs/base.json",
281
- help="JSON file for configuration",
282
- )
283
- parser.add_argument("-m", "--model", type=str, required=True, help="Model name")
284
-
285
- args = parser.parse_args()
286
- model_dir = os.path.join("./logs", args.model)
287
-
288
- if not os.path.exists(model_dir):
289
- os.makedirs(model_dir)
290
-
291
- config_path = args.config
292
- config_save_path = os.path.join(model_dir, "config.json")
293
- if init:
294
- with open(config_path, "r", encoding="utf-8") as f:
295
- data = f.read()
296
- with open(config_save_path, "w", encoding="utf-8") as f:
297
- f.write(data)
298
- else:
299
- with open(config_save_path, "r", vencoding="utf-8") as f:
300
- data = f.read()
301
- config = json.loads(data)
302
- hparams = HParams(**config)
303
- hparams.model_dir = model_dir
304
- return hparams
305
-
306
-
307
- def clean_checkpoints(path_to_models="logs/44k/", n_ckpts_to_keep=2, sort_by_time=True):
308
- """Freeing up space by deleting saved ckpts
309
-
310
- Arguments:
311
- path_to_models -- Path to the model directory
312
- n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
313
- sort_by_time -- True -> chronologically delete ckpts
314
- False -> lexicographically delete ckpts
315
- """
316
- import re
317
-
318
- ckpts_files = [
319
- f
320
- for f in os.listdir(path_to_models)
321
- if os.path.isfile(os.path.join(path_to_models, f))
322
- ]
323
-
324
- def name_key(_f):
325
- return int(re.compile("._(\\d+)\\.pth").match(_f).group(1))
326
-
327
- def time_key(_f):
328
- return os.path.getmtime(os.path.join(path_to_models, _f))
329
-
330
- sort_key = time_key if sort_by_time else name_key
331
-
332
- def x_sorted(_x):
333
- return sorted(
334
- [f for f in ckpts_files if f.startswith(_x) and not f.endswith("_0.pth")],
335
- key=sort_key,
336
- )
337
-
338
- to_del = [
339
- os.path.join(path_to_models, fn)
340
- for fn in (
341
- x_sorted("G_")[:-n_ckpts_to_keep]
342
- + x_sorted("D_")[:-n_ckpts_to_keep]
343
- + x_sorted("WD_")[:-n_ckpts_to_keep]
344
- + x_sorted("DUR_")[:-n_ckpts_to_keep]
345
- )
346
- ]
347
-
348
- def del_info(fn):
349
- return logger.info(f"Free up space by deleting ckpt {fn}")
350
-
351
- def del_routine(x):
352
- return [os.remove(x), del_info(x)]
353
-
354
- [del_routine(fn) for fn in to_del]
355
-
356
-
357
- def get_hparams_from_dir(model_dir):
358
- config_save_path = os.path.join(model_dir, "config.json")
359
- with open(config_save_path, "r", encoding="utf-8") as f:
360
- data = f.read()
361
- config = json.loads(data)
362
-
363
- hparams = HParams(**config)
364
- hparams.model_dir = model_dir
365
- return hparams
366
-
367
-
368
- def get_hparams_from_file(config_path):
369
- # print("config_path: ", config_path)
370
- with open(config_path, "r", encoding="utf-8") as f:
371
- data = f.read()
372
- config = json.loads(data)
373
-
374
- hparams = HParams(**config)
375
- return hparams
376
-
377
-
378
- def check_git_hash(model_dir):
379
- source_dir = os.path.dirname(os.path.realpath(__file__))
380
- if not os.path.exists(os.path.join(source_dir, ".git")):
381
- logger.warning(
382
- "{} is not a git repository, therefore hash value comparison will be ignored.".format(
383
- source_dir
384
- )
385
- )
386
- return
387
-
388
- cur_hash = subprocess.getoutput("git rev-parse HEAD")
389
-
390
- path = os.path.join(model_dir, "githash")
391
- if os.path.exists(path):
392
- saved_hash = open(path).read()
393
- if saved_hash != cur_hash:
394
- logger.warning(
395
- "git hash values are different. {}(saved) != {}(current)".format(
396
- saved_hash[:8], cur_hash[:8]
397
- )
398
- )
399
- else:
400
- open(path, "w").write(cur_hash)
401
-
402
-
403
- def get_logger(model_dir, filename="train.log"):
404
- global logger
405
- logger = logging.getLogger(os.path.basename(model_dir))
406
- logger.setLevel(logging.DEBUG)
407
-
408
- formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
409
- if not os.path.exists(model_dir):
410
- os.makedirs(model_dir)
411
- h = logging.FileHandler(os.path.join(model_dir, filename))
412
- h.setLevel(logging.DEBUG)
413
- h.setFormatter(formatter)
414
- logger.addHandler(h)
415
- return logger
416
-
417
-
418
- class HParams:
419
- def __init__(self, **kwargs):
420
- for k, v in kwargs.items():
421
- if type(v) == dict:
422
- v = HParams(**v)
423
- self[k] = v
424
-
425
- def keys(self):
426
- return self.__dict__.keys()
427
-
428
- def items(self):
429
- return self.__dict__.items()
430
-
431
- def values(self):
432
- return self.__dict__.values()
433
-
434
- def __len__(self):
435
- return len(self.__dict__)
436
-
437
- def __getitem__(self, key):
438
- return getattr(self, key)
439
-
440
- def __setitem__(self, key, value):
441
- return setattr(self, key, value)
442
-
443
- def __contains__(self, key):
444
- return key in self.__dict__
445
-
446
- def __repr__(self):
447
- return self.__dict__.__repr__()
448
-
449
-
450
- def load_model(model_path, config_path):
451
- hps = get_hparams_from_file(config_path)
452
- net = SynthesizerTrn(
453
- # len(symbols),
454
- 108,
455
- hps.data.filter_length // 2 + 1,
456
- hps.train.segment_size // hps.data.hop_length,
457
- n_speakers=hps.data.n_speakers,
458
- **hps.model,
459
- ).to("cpu")
460
- _ = net.eval()
461
- _ = load_checkpoint(model_path, net, None, skip_optimizer=True)
462
- return net
463
-
464
-
465
- def mix_model(
466
- network1, network2, output_path, voice_ratio=(0.5, 0.5), tone_ratio=(0.5, 0.5)
467
- ):
468
- if hasattr(network1, "module"):
469
- state_dict1 = network1.module.state_dict()
470
- state_dict2 = network2.module.state_dict()
471
- else:
472
- state_dict1 = network1.state_dict()
473
- state_dict2 = network2.state_dict()
474
- for k in state_dict1.keys():
475
- if k not in state_dict2.keys():
476
- continue
477
- if "enc_p" in k:
478
- state_dict1[k] = (
479
- state_dict1[k].clone() * tone_ratio[0]
480
- + state_dict2[k].clone() * tone_ratio[1]
481
- )
482
- else:
483
- state_dict1[k] = (
484
- state_dict1[k].clone() * voice_ratio[0]
485
- + state_dict2[k].clone() * voice_ratio[1]
486
- )
487
- for k in state_dict2.keys():
488
- if k not in state_dict1.keys():
489
- state_dict1[k] = state_dict2[k].clone()
490
- torch.save(
491
- {"model": state_dict1, "iteration": 0, "optimizer": None, "learning_rate": 0},
492
- output_path,
493
- )
494
-
495
-
496
- def get_steps(model_path):
497
- matches = re.findall(r"\d+", model_path)
498
- return matches[-1] if matches else None