inference.py 3.7 KB

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