inference.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. from pathlib import Path
  2. import click
  3. import hydra
  4. import numpy as np
  5. import pyrootutils
  6. import soundfile as sf
  7. import torch
  8. import torchaudio
  9. from hydra import compose, initialize
  10. from hydra.utils import instantiate
  11. from loguru import logger
  12. from omegaconf import OmegaConf
  13. pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
  14. from fish_speech.utils.file import AUDIO_EXTENSIONS
  15. # register eval resolver
  16. OmegaConf.register_new_resolver("eval", eval)
  17. def load_model(config_name, checkpoint_path, device="cuda"):
  18. hydra.core.global_hydra.GlobalHydra.instance().clear()
  19. with initialize(version_base="1.3", config_path="../../configs"):
  20. cfg = compose(config_name=config_name)
  21. model = instantiate(cfg)
  22. state_dict = torch.load(
  23. checkpoint_path, map_location=device, mmap=True, weights_only=True
  24. )
  25. if "state_dict" in state_dict:
  26. state_dict = state_dict["state_dict"]
  27. if any("generator" in k for k in state_dict):
  28. state_dict = {
  29. k.replace("generator.", ""): v
  30. for k, v in state_dict.items()
  31. if "generator." in k
  32. }
  33. result = model.load_state_dict(state_dict, strict=False, assign=True)
  34. model.eval()
  35. model.to(device)
  36. logger.info(f"Loaded model: {result}")
  37. return model
  38. @torch.no_grad()
  39. @click.command()
  40. @click.option(
  41. "--input-path",
  42. "-i",
  43. default="test.wav",
  44. type=click.Path(exists=True, path_type=Path),
  45. )
  46. @click.option(
  47. "--output-path", "-o", default="fake.wav", type=click.Path(path_type=Path)
  48. )
  49. @click.option("--config-name", default="firefly_gan_vq")
  50. @click.option(
  51. "--checkpoint-path",
  52. default="checkpoints/fish-speech-1.5/firefly-gan-vq-fsq-8x1024-21hz-generator.pth",
  53. )
  54. @click.option(
  55. "--device",
  56. "-d",
  57. default="cuda",
  58. )
  59. def main(input_path, output_path, config_name, checkpoint_path, device):
  60. model = load_model(config_name, checkpoint_path, device=device)
  61. if input_path.suffix in AUDIO_EXTENSIONS:
  62. logger.info(f"Processing in-place reconstruction of {input_path}")
  63. # Load audio
  64. audio, sr = torchaudio.load(str(input_path))
  65. if audio.shape[0] > 1:
  66. audio = audio.mean(0, keepdim=True)
  67. audio = torchaudio.functional.resample(audio, sr, model.sample_rate)
  68. audios = audio[None].to(device)
  69. logger.info(
  70. f"Loaded audio with {audios.shape[2] / model.sample_rate:.2f} seconds"
  71. )
  72. # VQ Encoder
  73. audio_lengths = torch.tensor([audios.shape[2]], device=device, dtype=torch.long)
  74. indices, indices_lens = model.encode(audios, audio_lengths)
  75. logger.info(f"Generated indices of shape {indices.shape}")
  76. # Save indices
  77. np.save(output_path.with_suffix(".npy"), indices.cpu().numpy())
  78. elif input_path.suffix == ".npy":
  79. logger.info(f"Processing precomputed indices from {input_path}")
  80. indices = np.load(input_path)
  81. indices = torch.from_numpy(indices).to(device).long()
  82. assert indices.ndim == 2, f"Expected 2D indices, got {indices.ndim}"
  83. indices_lens = torch.tensor([indices.shape[1]], device=device, dtype=torch.long)
  84. else:
  85. raise ValueError(f"Unknown input type: {input_path}")
  86. # Restore
  87. fake_audios, audio_lengths = model.decode(indices, indices_lens)
  88. audio_time = fake_audios.shape[-1] / model.sample_rate
  89. logger.info(
  90. f"Generated audio of shape {fake_audios.shape}, equivalent to {audio_time:.2f} seconds from {indices.shape[1]} features, features/second: {indices.shape[1] / audio_time:.2f}"
  91. )
  92. # Save audio
  93. fake_audio = fake_audios[0, 0].float().cpu().numpy()
  94. sf.write(output_path, fake_audio, model.sample_rate)
  95. logger.info(f"Saved audio to {output_path}")
  96. if __name__ == "__main__":
  97. main()