extract_vq.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 = "modded_dac_vq",
  41. checkpoint_path: str = "checkpoints/openaudio-s1-mini/codec.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(wav.cuda(), sr, model.sample_rate)[0]
  81. total_time += len(wav) / model.sample_rate
  82. max_length = max(max_length, len(wav))
  83. wavs.append(wav)
  84. audio_lengths.append(len(wav))
  85. new_files.append(file)
  86. files = new_files
  87. # Pad to max length
  88. for i, wav in enumerate(wavs):
  89. wavs[i] = torch.nn.functional.pad(wav, (0, max_length - len(wav)), "constant")
  90. audios = torch.stack(wavs, dim=0)[:, None]
  91. audio_lengths = torch.tensor(audio_lengths, device=model.device, dtype=torch.long)
  92. # Calculate lengths
  93. indices, feature_lengths = model.encode(audios, audio_lengths)
  94. # Save to disk
  95. outputs = indices.cpu().numpy()
  96. for file, length, feature, audio_length in zip(
  97. files, feature_lengths, outputs, audio_lengths
  98. ):
  99. feature = feature[:, :length]
  100. # (T,)
  101. with open(file.with_suffix(".npy"), "wb") as f:
  102. np.save(f, feature)
  103. return total_time
  104. @click.command()
  105. @click.argument("folder")
  106. @click.option("--num-workers", default=1)
  107. @click.option("--config-name", default="modded_dac_vq")
  108. @click.option(
  109. "--checkpoint-path",
  110. default="checkpoints/s2-pro/codec.pth",
  111. )
  112. @click.option("--batch-size", default=64)
  113. @click.option("--filelist", default=None, type=Path)
  114. def main(
  115. folder: str,
  116. num_workers: int,
  117. config_name: str,
  118. checkpoint_path: str,
  119. batch_size: int,
  120. filelist: Path,
  121. ):
  122. if num_workers > 1 and WORLD_SIZE != num_workers:
  123. assert WORLD_SIZE == 1, "You should either use SLURM or this launcher, not both"
  124. logger.info(f"Spawning {num_workers} workers")
  125. if torch.cuda.is_available():
  126. visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None)
  127. if visible_devices is None:
  128. visible_devices = list(range(torch.cuda.device_count()))
  129. else:
  130. visible_devices = visible_devices.split(",")
  131. else:
  132. # Set to empty string to avoid using GPU
  133. visible_devices = [""]
  134. processes = []
  135. for i in range(num_workers):
  136. env = os.environ.copy()
  137. env["CUDA_VISIBLE_DEVICES"] = str(visible_devices[i % len(visible_devices)])
  138. env["SLURM_PROCID"] = str(i)
  139. env["SLURM_NTASKS"] = str(num_workers)
  140. processes.append(
  141. sp.Popen(
  142. [sys.executable] + sys.argv.copy(),
  143. env=env,
  144. )
  145. )
  146. for p in processes:
  147. p.wait()
  148. logger.info(f"All workers finished")
  149. return
  150. # This is a worker
  151. logger.info(f"Starting worker")
  152. if filelist:
  153. files = [i[0] for i in load_filelist(filelist)]
  154. else:
  155. files = list_files(folder, AUDIO_EXTENSIONS, recursive=True, sort=False)
  156. print(f"Found {len(files)} files")
  157. files = [Path(f) for f in files if not Path(f).with_suffix(".npy").exists()]
  158. total_files = len(files)
  159. files = files[RANK::WORLD_SIZE]
  160. logger.info(f"Processing {len(files)}/{total_files} files")
  161. # Batch processing
  162. total_time = 0
  163. begin_time = time.time()
  164. processed_files = 0
  165. model = get_model(config_name, checkpoint_path)
  166. for n_batch, idx in enumerate(range(0, len(files), batch_size)):
  167. batch = files[idx : idx + batch_size]
  168. batch_time = process_batch(batch, model)
  169. total_time += batch_time
  170. processed_files += len(batch)
  171. if (n_batch + 1) % 10 == 0:
  172. eta = (
  173. (time.time() - begin_time)
  174. / processed_files
  175. * (len(files) - processed_files)
  176. )
  177. logger.info(
  178. f"Processed {processed_files} files, {total_time / 3600:.2f} hours of audio, "
  179. + f"ETA: {timedelta(seconds=round(eta))}s"
  180. )
  181. logger.info(
  182. f"Finished processing {len(files)} files, {total_time / 3600:.2f} hours of audio"
  183. )
  184. if __name__ == "__main__":
  185. main()