Spaces:
Build error
Build error
added loading/saving of voice latents by model hash, so no more needing to manually regenerate every time you change models
Browse files- src/utils.py +68 -39
src/utils.py
CHANGED
|
@@ -97,7 +97,11 @@ def generate(
|
|
| 97 |
voice_samples, conditioning_latents = None, tts.get_random_conditioning_latents()
|
| 98 |
else:
|
| 99 |
progress(0, desc="Loading voice...")
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
if voice_samples and len(voice_samples) > 0:
|
| 103 |
sample_voice = torch.cat(voice_samples, dim=-1).squeeze().cpu()
|
|
@@ -107,7 +111,10 @@ def generate(
|
|
| 107 |
conditioning_latents = (conditioning_latents[0], conditioning_latents[1], conditioning_latents[2], None)
|
| 108 |
|
| 109 |
if voice != "microphone":
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
| 111 |
voice_samples = None
|
| 112 |
else:
|
| 113 |
if conditioning_latents is not None:
|
|
@@ -413,6 +420,32 @@ def cancel_generate():
|
|
| 413 |
import tortoise.api
|
| 414 |
tortoise.api.STOP_SIGNAL = True
|
| 415 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
def compute_latents(voice, voice_latents_chunks, progress=gr.Progress(track_tqdm=True)):
|
| 417 |
global tts
|
| 418 |
global args
|
|
@@ -435,7 +468,10 @@ def compute_latents(voice, voice_latents_chunks, progress=gr.Progress(track_tqdm
|
|
| 435 |
if len(conditioning_latents) == 4:
|
| 436 |
conditioning_latents = (conditioning_latents[0], conditioning_latents[1], conditioning_latents[2], None)
|
| 437 |
|
| 438 |
-
|
|
|
|
|
|
|
|
|
|
| 439 |
|
| 440 |
return voice
|
| 441 |
|
|
@@ -487,6 +523,7 @@ class TrainingState():
|
|
| 487 |
self.eta = "?"
|
| 488 |
self.eta_hhmmss = "?"
|
| 489 |
|
|
|
|
| 490 |
self.losses = []
|
| 491 |
|
| 492 |
self.load_losses()
|
|
@@ -497,7 +534,7 @@ class TrainingState():
|
|
| 497 |
print("Spawning process: ", " ".join(self.cmd))
|
| 498 |
self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
|
| 499 |
|
| 500 |
-
def load_losses(self):
|
| 501 |
if not os.path.isdir(f'{self.dataset_dir}/tb_logger/'):
|
| 502 |
return
|
| 503 |
try:
|
|
@@ -506,18 +543,26 @@ class TrainingState():
|
|
| 506 |
except Exception as e:
|
| 507 |
use_tensorboard = False
|
| 508 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 509 |
if use_tensorboard:
|
| 510 |
logs = sorted([f'{self.dataset_dir}/tb_logger/{d}' for d in os.listdir(f'{self.dataset_dir}/tb_logger/') if d[:6] == "events" ])
|
| 511 |
-
|
|
|
|
|
|
|
| 512 |
for log in logs:
|
| 513 |
try:
|
| 514 |
ea = event_accumulator.EventAccumulator(log, size_guidance={event_accumulator.SCALARS: 0})
|
| 515 |
ea.Reload()
|
| 516 |
|
| 517 |
-
keys = ['loss_text_ce', 'loss_mel_ce', 'loss_gpt_total']
|
| 518 |
for key in keys:
|
| 519 |
scalar = ea.Scalars(key)
|
| 520 |
for s in scalar:
|
|
|
|
|
|
|
|
|
|
| 521 |
self.losses.append( { "step": s.step, "value": s.value, "type": key } )
|
| 522 |
except Exception as e:
|
| 523 |
print("Failed to parse event log:", log)
|
|
@@ -525,7 +570,9 @@ class TrainingState():
|
|
| 525 |
|
| 526 |
else:
|
| 527 |
logs = sorted([f'{self.dataset_dir}/{d}' for d in os.listdir(self.dataset_dir) if d[-4:] == ".log" ])
|
| 528 |
-
|
|
|
|
|
|
|
| 529 |
for log in logs:
|
| 530 |
with open(log, 'r', encoding="utf-8") as f:
|
| 531 |
lines = f.readlines()
|
|
@@ -546,9 +593,13 @@ class TrainingState():
|
|
| 546 |
|
| 547 |
for k in infos:
|
| 548 |
if 'loss_gpt_total' in infos[k]:
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
|
| 553 |
def cleanup_old(self, keep=2):
|
| 554 |
if keep <= 0:
|
|
@@ -581,7 +632,8 @@ class TrainingState():
|
|
| 581 |
if line.find('Start training from epoch') >= 0:
|
| 582 |
self.epoch_time_start = time.time()
|
| 583 |
self.training_started = True # could just leverage the above variable, but this is python, and there's no point in these aggressive microoptimizations
|
| 584 |
-
|
|
|
|
| 585 |
match = re.findall(r'epoch: ([\d,]+)', line)
|
| 586 |
if match and len(match) > 0:
|
| 587 |
self.epoch = int(match[0].replace(",", ""))
|
|
@@ -662,12 +714,15 @@ class TrainingState():
|
|
| 662 |
|
| 663 |
if 'loss_gpt_total' in self.info:
|
| 664 |
self.status = f"Total loss at epoch {self.epoch}: {self.info['loss_gpt_total']}"
|
| 665 |
-
|
| 666 |
self.losses.append({ "step": self.it, "value": self.info['loss_text_ce'], "type": "loss_text_ce" })
|
| 667 |
self.losses.append({ "step": self.it, "value": self.info['loss_mel_ce'], "type": "loss_mel_ce" })
|
| 668 |
self.losses.append({ "step": self.it, "value": self.info['loss_gpt_total'], "type": "loss_gpt_total" })
|
| 669 |
-
|
| 670 |
should_return = True
|
|
|
|
|
|
|
|
|
|
| 671 |
elif line.find('Saving models and training states') >= 0:
|
| 672 |
self.checkpoint = self.checkpoint + 1
|
| 673 |
|
|
@@ -1035,32 +1090,6 @@ def get_voice_list(dir=get_voice_dir(), append_defaults=False):
|
|
| 1035 |
res = res + ["random", "microphone"]
|
| 1036 |
return res
|
| 1037 |
|
| 1038 |
-
def hash_file(path, algo="md5", buffer_size=0):
|
| 1039 |
-
import hashlib
|
| 1040 |
-
|
| 1041 |
-
hash = None
|
| 1042 |
-
if algo == "md5":
|
| 1043 |
-
hash = hashlib.md5()
|
| 1044 |
-
elif algo == "sha1":
|
| 1045 |
-
hash = hashlib.sha1()
|
| 1046 |
-
else:
|
| 1047 |
-
raise Exception(f'Unknown hash algorithm specified: {algo}')
|
| 1048 |
-
|
| 1049 |
-
if not os.path.exists(path):
|
| 1050 |
-
raise Exception(f'Path not found: {path}')
|
| 1051 |
-
|
| 1052 |
-
with open(path, 'rb') as f:
|
| 1053 |
-
if buffer_size > 0:
|
| 1054 |
-
while True:
|
| 1055 |
-
data = f.read(buffer_size)
|
| 1056 |
-
if not data:
|
| 1057 |
-
break
|
| 1058 |
-
hash.update(data)
|
| 1059 |
-
else:
|
| 1060 |
-
hash.update(f.read())
|
| 1061 |
-
|
| 1062 |
-
return "{0}".format(hash.hexdigest())
|
| 1063 |
-
|
| 1064 |
def get_autoregressive_models(dir="./models/finetunes/", prefixed=False):
|
| 1065 |
os.makedirs(dir, exist_ok=True)
|
| 1066 |
base = [get_model_path('autoregressive.pth')]
|
|
|
|
| 97 |
voice_samples, conditioning_latents = None, tts.get_random_conditioning_latents()
|
| 98 |
else:
|
| 99 |
progress(0, desc="Loading voice...")
|
| 100 |
+
# nasty check for users that, for whatever reason, updated the web UI but not mrq/tortoise-tts
|
| 101 |
+
if hasattr(tts, 'autoregressive_model_hash'):
|
| 102 |
+
voice_samples, conditioning_latents = load_voice(voice, model_hash=tts.autoregressive_model_hash)
|
| 103 |
+
else:
|
| 104 |
+
voice_samples, conditioning_latents = load_voice(voice)
|
| 105 |
|
| 106 |
if voice_samples and len(voice_samples) > 0:
|
| 107 |
sample_voice = torch.cat(voice_samples, dim=-1).squeeze().cpu()
|
|
|
|
| 111 |
conditioning_latents = (conditioning_latents[0], conditioning_latents[1], conditioning_latents[2], None)
|
| 112 |
|
| 113 |
if voice != "microphone":
|
| 114 |
+
if hasattr(tts, 'autoregressive_model_hash'):
|
| 115 |
+
torch.save(conditioning_latents, f'{get_voice_dir()}/{voice}/cond_latents_{tts.autoregressive_model_hash[:8]}.pth')
|
| 116 |
+
else:
|
| 117 |
+
torch.save(conditioning_latents, f'{get_voice_dir()}/{voice}/cond_latents.pth')
|
| 118 |
voice_samples = None
|
| 119 |
else:
|
| 120 |
if conditioning_latents is not None:
|
|
|
|
| 420 |
import tortoise.api
|
| 421 |
tortoise.api.STOP_SIGNAL = True
|
| 422 |
|
| 423 |
+
def hash_file(path, algo="md5", buffer_size=0):
|
| 424 |
+
import hashlib
|
| 425 |
+
|
| 426 |
+
hash = None
|
| 427 |
+
if algo == "md5":
|
| 428 |
+
hash = hashlib.md5()
|
| 429 |
+
elif algo == "sha1":
|
| 430 |
+
hash = hashlib.sha1()
|
| 431 |
+
else:
|
| 432 |
+
raise Exception(f'Unknown hash algorithm specified: {algo}')
|
| 433 |
+
|
| 434 |
+
if not os.path.exists(path):
|
| 435 |
+
raise Exception(f'Path not found: {path}')
|
| 436 |
+
|
| 437 |
+
with open(path, 'rb') as f:
|
| 438 |
+
if buffer_size > 0:
|
| 439 |
+
while True:
|
| 440 |
+
data = f.read(buffer_size)
|
| 441 |
+
if not data:
|
| 442 |
+
break
|
| 443 |
+
hash.update(data)
|
| 444 |
+
else:
|
| 445 |
+
hash.update(f.read())
|
| 446 |
+
|
| 447 |
+
return "{0}".format(hash.hexdigest())
|
| 448 |
+
|
| 449 |
def compute_latents(voice, voice_latents_chunks, progress=gr.Progress(track_tqdm=True)):
|
| 450 |
global tts
|
| 451 |
global args
|
|
|
|
| 468 |
if len(conditioning_latents) == 4:
|
| 469 |
conditioning_latents = (conditioning_latents[0], conditioning_latents[1], conditioning_latents[2], None)
|
| 470 |
|
| 471 |
+
if hasattr(tts, 'autoregressive_model_hash'):
|
| 472 |
+
torch.save(conditioning_latents, f'{get_voice_dir()}/{voice}/cond_latents_{tts.autoregressive_model_hash[:8]}.pth')
|
| 473 |
+
else:
|
| 474 |
+
torch.save(conditioning_latents, f'{get_voice_dir()}/{voice}/cond_latents.pth')
|
| 475 |
|
| 476 |
return voice
|
| 477 |
|
|
|
|
| 523 |
self.eta = "?"
|
| 524 |
self.eta_hhmmss = "?"
|
| 525 |
|
| 526 |
+
self.last_info_check_at = 0
|
| 527 |
self.losses = []
|
| 528 |
|
| 529 |
self.load_losses()
|
|
|
|
| 534 |
print("Spawning process: ", " ".join(self.cmd))
|
| 535 |
self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
|
| 536 |
|
| 537 |
+
def load_losses(self, update=False):
|
| 538 |
if not os.path.isdir(f'{self.dataset_dir}/tb_logger/'):
|
| 539 |
return
|
| 540 |
try:
|
|
|
|
| 543 |
except Exception as e:
|
| 544 |
use_tensorboard = False
|
| 545 |
|
| 546 |
+
keys = ['loss_text_ce', 'loss_mel_ce', 'loss_gpt_total']
|
| 547 |
+
infos = {}
|
| 548 |
+
highest_step = self.last_info_check_at
|
| 549 |
+
|
| 550 |
if use_tensorboard:
|
| 551 |
logs = sorted([f'{self.dataset_dir}/tb_logger/{d}' for d in os.listdir(f'{self.dataset_dir}/tb_logger/') if d[:6] == "events" ])
|
| 552 |
+
if update:
|
| 553 |
+
logs = [logs[-1]]
|
| 554 |
+
|
| 555 |
for log in logs:
|
| 556 |
try:
|
| 557 |
ea = event_accumulator.EventAccumulator(log, size_guidance={event_accumulator.SCALARS: 0})
|
| 558 |
ea.Reload()
|
| 559 |
|
|
|
|
| 560 |
for key in keys:
|
| 561 |
scalar = ea.Scalars(key)
|
| 562 |
for s in scalar:
|
| 563 |
+
if update and s.step <= self.last_info_check_at:
|
| 564 |
+
continue
|
| 565 |
+
highest_step = max( highest_step, s.step )
|
| 566 |
self.losses.append( { "step": s.step, "value": s.value, "type": key } )
|
| 567 |
except Exception as e:
|
| 568 |
print("Failed to parse event log:", log)
|
|
|
|
| 570 |
|
| 571 |
else:
|
| 572 |
logs = sorted([f'{self.dataset_dir}/{d}' for d in os.listdir(self.dataset_dir) if d[-4:] == ".log" ])
|
| 573 |
+
if update:
|
| 574 |
+
logs = [logs[-1]]
|
| 575 |
+
|
| 576 |
for log in logs:
|
| 577 |
with open(log, 'r', encoding="utf-8") as f:
|
| 578 |
lines = f.readlines()
|
|
|
|
| 593 |
|
| 594 |
for k in infos:
|
| 595 |
if 'loss_gpt_total' in infos[k]:
|
| 596 |
+
for key in keys:
|
| 597 |
+
if update and int(k) <= self.last_info_check_at:
|
| 598 |
+
continue
|
| 599 |
+
highest_step = max( highest_step, s.step )
|
| 600 |
+
self.losses.append({ "step": int(k), "value": infos[k][key], "type": key })
|
| 601 |
+
|
| 602 |
+
self.last_info_check_at = highest_step
|
| 603 |
|
| 604 |
def cleanup_old(self, keep=2):
|
| 605 |
if keep <= 0:
|
|
|
|
| 632 |
if line.find('Start training from epoch') >= 0:
|
| 633 |
self.epoch_time_start = time.time()
|
| 634 |
self.training_started = True # could just leverage the above variable, but this is python, and there's no point in these aggressive microoptimizations
|
| 635 |
+
should_return = True
|
| 636 |
+
|
| 637 |
match = re.findall(r'epoch: ([\d,]+)', line)
|
| 638 |
if match and len(match) > 0:
|
| 639 |
self.epoch = int(match[0].replace(",", ""))
|
|
|
|
| 714 |
|
| 715 |
if 'loss_gpt_total' in self.info:
|
| 716 |
self.status = f"Total loss at epoch {self.epoch}: {self.info['loss_gpt_total']}"
|
| 717 |
+
"""
|
| 718 |
self.losses.append({ "step": self.it, "value": self.info['loss_text_ce'], "type": "loss_text_ce" })
|
| 719 |
self.losses.append({ "step": self.it, "value": self.info['loss_mel_ce'], "type": "loss_mel_ce" })
|
| 720 |
self.losses.append({ "step": self.it, "value": self.info['loss_gpt_total'], "type": "loss_gpt_total" })
|
| 721 |
+
"""
|
| 722 |
should_return = True
|
| 723 |
+
|
| 724 |
+
self.load_losses(update=True)
|
| 725 |
+
|
| 726 |
elif line.find('Saving models and training states') >= 0:
|
| 727 |
self.checkpoint = self.checkpoint + 1
|
| 728 |
|
|
|
|
| 1090 |
res = res + ["random", "microphone"]
|
| 1091 |
return res
|
| 1092 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1093 |
def get_autoregressive_models(dir="./models/finetunes/", prefixed=False):
|
| 1094 |
os.makedirs(dir, exist_ok=True)
|
| 1095 |
base = [get_model_path('autoregressive.pth')]
|