extract_vq.py 6.7 KB

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