extract_vq.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import os
  2. import subprocess as sp
  3. import sys
  4. import time
  5. from datetime import timedelta
  6. from functools import lru_cache
  7. from pathlib import Path
  8. from random import Random
  9. import click
  10. import numpy as np
  11. import torch
  12. import torchaudio
  13. from hydra import compose, initialize
  14. from hydra.utils import instantiate
  15. from lightning import LightningModule
  16. from loguru import logger
  17. from omegaconf import OmegaConf
  18. from fish_speech.utils.file import AUDIO_EXTENSIONS, list_files, load_filelist
  19. # register eval resolver
  20. OmegaConf.register_new_resolver("eval", eval)
  21. # This file is used to convert the audio files to text files using the Whisper model.
  22. # It's mainly used to generate the training data for the VQ model.
  23. RANK = int(os.environ.get("SLURM_PROCID", 0))
  24. WORLD_SIZE = int(os.environ.get("SLURM_NTASKS", 1))
  25. logger_format = (
  26. "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
  27. "<level>{level: <8}</level> | "
  28. "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
  29. "{extra[rank]} - <level>{message}</level>"
  30. )
  31. logger.configure(extra={"rank": f"RANK: {RANK} / {WORLD_SIZE}"})
  32. logger.remove()
  33. logger.add(sys.stderr, format=logger_format)
  34. @lru_cache(maxsize=1)
  35. def get_model(
  36. config_name: str = "vqgan",
  37. checkpoint_path: str = "checkpoints/vqgan/step_000380000.ckpt",
  38. ):
  39. with initialize(version_base="1.3", config_path="../../fish_speech/configs"):
  40. cfg = compose(config_name=config_name)
  41. model: LightningModule = instantiate(cfg.model)
  42. state_dict = torch.load(
  43. checkpoint_path,
  44. map_location=model.device,
  45. )
  46. if "state_dict" in state_dict:
  47. state_dict = state_dict["state_dict"]
  48. model.load_state_dict(state_dict, strict=False)
  49. model.eval()
  50. model.cuda()
  51. logger.info(f"Loaded model")
  52. return model
  53. @torch.inference_mode()
  54. def process_batch(files: list[Path], model) -> float:
  55. wavs = []
  56. audio_lengths = []
  57. new_files = []
  58. max_length = total_time = 0
  59. for file in files:
  60. try:
  61. wav, sr = torchaudio.load(file)
  62. except Exception as e:
  63. logger.error(f"Error reading {file}: {e}")
  64. continue
  65. if wav.shape[0] > 1:
  66. wav = wav.mean(dim=0, keepdim=True)
  67. wav = torchaudio.functional.resample(wav.cuda(), sr, model.sampling_rate)[0]
  68. total_time += len(wav) / model.sampling_rate
  69. max_length = max(max_length, len(wav))
  70. wavs.append(wav)
  71. audio_lengths.append(len(wav))
  72. new_files.append(file)
  73. files = new_files
  74. # Pad to max length
  75. for i, wav in enumerate(wavs):
  76. wavs[i] = torch.nn.functional.pad(wav, (0, max_length - len(wav)), "constant")
  77. audios = torch.stack(wavs, dim=0)[:, None]
  78. audio_lengths = torch.tensor(audio_lengths, device=model.device, dtype=torch.long)
  79. # Calculate lengths
  80. indices, feature_lengths = model.encode(audios, audio_lengths)
  81. # Save to disk
  82. outputs = indices.cpu().numpy()
  83. for file, length, feature, audio_length in zip(
  84. files, feature_lengths, outputs, audio_lengths
  85. ):
  86. feature = feature[:, :length]
  87. # (T,)
  88. with open(file.with_suffix(".npy"), "wb") as f:
  89. np.save(f, feature)
  90. return total_time
  91. @click.command()
  92. @click.argument("folder")
  93. @click.option("--num-workers", default=1)
  94. @click.option("--config-name", default="vqgan_pretrain")
  95. @click.option(
  96. "--checkpoint-path",
  97. default="checkpoints/vq-gan-group-fsq-8x1024-wn-20x768-30kh.pth",
  98. )
  99. @click.option("--batch-size", default=64)
  100. @click.option("--filelist", default=None, type=Path)
  101. def main(
  102. folder: str,
  103. num_workers: int,
  104. config_name: str,
  105. checkpoint_path: str,
  106. batch_size: int,
  107. filelist: Path,
  108. ):
  109. if num_workers > 1 and WORLD_SIZE != num_workers:
  110. assert WORLD_SIZE == 1, "You should either use SLURM or this launcher, not both"
  111. logger.info(f"Spawning {num_workers} workers")
  112. visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
  113. if visible_devices is None:
  114. visible_devices = list(range(torch.cuda.device_count()))
  115. else:
  116. visible_devices = visible_devices.split(",")
  117. processes = []
  118. for i in range(num_workers):
  119. env = os.environ.copy()
  120. env["CUDA_VISIBLE_DEVICES"] = str(visible_devices[i % len(visible_devices)])
  121. env["SLURM_PROCID"] = str(i)
  122. env["SLURM_NTASKS"] = str(num_workers)
  123. processes.append(
  124. sp.Popen(
  125. [sys.executable] + sys.argv.copy(),
  126. env=env,
  127. )
  128. )
  129. for p in processes:
  130. p.wait()
  131. logger.info(f"All workers finished")
  132. return
  133. # This is a worker
  134. logger.info(f"Starting worker")
  135. if filelist:
  136. files = [i[0] for i in load_filelist(filelist)]
  137. else:
  138. files = list_files(folder, AUDIO_EXTENSIONS, recursive=True, sort=True)
  139. print(f"Found {len(files)} files")
  140. files = [Path(f) for f in files if not Path(f).with_suffix(".npy").exists()]
  141. Random(42).shuffle(files)
  142. total_files = len(files)
  143. files = files[RANK::WORLD_SIZE]
  144. logger.info(f"Processing {len(files)}/{total_files} files")
  145. # Batch processing
  146. total_time = 0
  147. begin_time = time.time()
  148. processed_files = 0
  149. model = get_model(config_name, checkpoint_path)
  150. for n_batch, idx in enumerate(range(0, len(files), batch_size)):
  151. batch = files[idx : idx + batch_size]
  152. batch_time = process_batch(batch, model)
  153. total_time += batch_time
  154. processed_files += len(batch)
  155. if (n_batch + 1) % 10 == 0:
  156. eta = (
  157. (time.time() - begin_time)
  158. / processed_files
  159. * (len(files) - processed_files)
  160. )
  161. logger.info(
  162. f"Processed {processed_files} files, {total_time / 3600:.2f} hours of audio, "
  163. + f"ETA: {timedelta(seconds=round(eta))}s"
  164. )
  165. logger.info(
  166. f"Finished processing {len(files)} files, {total_time / 3600:.2f} hours of audio"
  167. )
  168. if __name__ == "__main__":
  169. main()