extract_vq.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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_pretrain",
  37. checkpoint_path: str = "checkpoints/vq-gan-group-fsq-2x1024.pth",
  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(
  62. str(file), backend="sox" if sys.platform == "linux" else "soundfile"
  63. ) # Need to install libsox-dev
  64. except Exception as e:
  65. logger.error(f"Error reading {file}: {e}")
  66. continue
  67. if wav.shape[0] > 1:
  68. wav = wav.mean(dim=0, keepdim=True)
  69. wav = torchaudio.functional.resample(wav.cuda(), sr, model.sampling_rate)[0]
  70. total_time += len(wav) / model.sampling_rate
  71. max_length = max(max_length, len(wav))
  72. wavs.append(wav)
  73. audio_lengths.append(len(wav))
  74. new_files.append(file)
  75. files = new_files
  76. # Pad to max length
  77. for i, wav in enumerate(wavs):
  78. wavs[i] = torch.nn.functional.pad(wav, (0, max_length - len(wav)), "constant")
  79. audios = torch.stack(wavs, dim=0)[:, None]
  80. audio_lengths = torch.tensor(audio_lengths, device=model.device, dtype=torch.long)
  81. # Calculate lengths
  82. indices, feature_lengths = model.encode(audios, audio_lengths)
  83. # Save to disk
  84. outputs = indices.cpu().numpy()
  85. for file, length, feature, audio_length in zip(
  86. files, feature_lengths, outputs, audio_lengths
  87. ):
  88. feature = feature[:, :length]
  89. # (T,)
  90. with open(file.with_suffix(".npy"), "wb") as f:
  91. np.save(f, feature)
  92. return total_time
  93. @click.command()
  94. @click.argument("folder")
  95. @click.option("--num-workers", default=1)
  96. @click.option("--config-name", default="vqgan_pretrain")
  97. @click.option(
  98. "--checkpoint-path",
  99. default="checkpoints/vq-gan-group-fsq-2x1024.pth",
  100. )
  101. @click.option("--batch-size", default=64)
  102. @click.option("--filelist", default=None, type=Path)
  103. def main(
  104. folder: str,
  105. num_workers: int,
  106. config_name: str,
  107. checkpoint_path: str,
  108. batch_size: int,
  109. filelist: Path,
  110. ):
  111. if num_workers > 1 and WORLD_SIZE != num_workers:
  112. assert WORLD_SIZE == 1, "You should either use SLURM or this launcher, not both"
  113. logger.info(f"Spawning {num_workers} workers")
  114. visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
  115. if visible_devices is None:
  116. visible_devices = list(range(torch.cuda.device_count()))
  117. else:
  118. visible_devices = visible_devices.split(",")
  119. processes = []
  120. for i in range(num_workers):
  121. env = os.environ.copy()
  122. env["CUDA_VISIBLE_DEVICES"] = str(visible_devices[i % len(visible_devices)])
  123. env["SLURM_PROCID"] = str(i)
  124. env["SLURM_NTASKS"] = str(num_workers)
  125. processes.append(
  126. sp.Popen(
  127. [sys.executable] + sys.argv.copy(),
  128. env=env,
  129. )
  130. )
  131. for p in processes:
  132. p.wait()
  133. logger.info(f"All workers finished")
  134. return
  135. # This is a worker
  136. logger.info(f"Starting worker")
  137. if filelist:
  138. files = [i[0] for i in load_filelist(filelist)]
  139. else:
  140. files = list_files(folder, AUDIO_EXTENSIONS, recursive=True, sort=False)
  141. print(f"Found {len(files)} files")
  142. files = [Path(f) for f in files if not Path(f).with_suffix(".npy").exists()]
  143. total_files = len(files)
  144. files = files[RANK::WORLD_SIZE]
  145. logger.info(f"Processing {len(files)}/{total_files} files")
  146. # Batch processing
  147. total_time = 0
  148. begin_time = time.time()
  149. processed_files = 0
  150. model = get_model(config_name, checkpoint_path)
  151. for n_batch, idx in enumerate(range(0, len(files), batch_size)):
  152. batch = files[idx : idx + batch_size]
  153. batch_time = process_batch(batch, model)
  154. total_time += batch_time
  155. processed_files += len(batch)
  156. if (n_batch + 1) % 10 == 0:
  157. eta = (
  158. (time.time() - begin_time)
  159. / processed_files
  160. * (len(files) - processed_files)
  161. )
  162. logger.info(
  163. f"Processed {processed_files} files, {total_time / 3600:.2f} hours of audio, "
  164. + f"ETA: {timedelta(seconds=round(eta))}s"
  165. )
  166. logger.info(
  167. f"Finished processing {len(files)} files, {total_time / 3600:.2f} hours of audio"
  168. )
  169. if __name__ == "__main__":
  170. main()