extract_vq.py 6.7 KB

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