predict.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. #
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import argparse
  6. import logging
  7. import torch
  8. import torchaudio
  9. from argparse import Namespace
  10. from fairseq2.generation import SequenceGeneratorOptions
  11. from seamless_communication.models.inference import (
  12. NGramRepeatBlockProcessor,
  13. Translator,
  14. )
  15. from typing import Tuple
  16. logging.basicConfig(
  17. level=logging.INFO,
  18. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  19. )
  20. logger = logging.getLogger(__name__)
  21. def add_inference_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
  22. parser.add_argument("task", type=str, help="Task type")
  23. parser.add_argument(
  24. "tgt_lang", type=str, help="Target language to translate/transcribe into."
  25. )
  26. parser.add_argument(
  27. "--src_lang",
  28. type=str,
  29. help="Source language, only required if input is text.",
  30. default=None,
  31. )
  32. parser.add_argument(
  33. "--output_path",
  34. type=str,
  35. help="Path to save the generated audio.",
  36. default=None,
  37. )
  38. parser.add_argument(
  39. "--model_name",
  40. type=str,
  41. help=(
  42. "Base model name (`seamlessM4T_medium`, "
  43. "`seamlessM4T_large`, `seamlessM4T_v2_large`)"
  44. ),
  45. default="seamlessM4T_v2_large",
  46. )
  47. parser.add_argument(
  48. "--vocoder_name",
  49. type=str,
  50. help="Vocoder model name",
  51. default="vocoder_commercial",
  52. )
  53. # Text generation args.
  54. parser.add_argument(
  55. "--text_generation_beam_size",
  56. type=int,
  57. help="Beam size for incremental text decoding.",
  58. default=5,
  59. )
  60. parser.add_argument(
  61. "--text_generation_max_len_a",
  62. type=int,
  63. help="`a` in `ax + b` for incremental text decoding.",
  64. default=1,
  65. )
  66. parser.add_argument(
  67. "--text_generation_max_len_b",
  68. type=int,
  69. help="`b` in `ax + b` for incremental text decoding.",
  70. default=200,
  71. )
  72. parser.add_argument(
  73. "--text_generation_ngram_blocking",
  74. type=bool,
  75. help=(
  76. "Enable ngram_repeat_block for incremental text decoding."
  77. "This blocks hypotheses with repeating ngram tokens."
  78. ),
  79. default=False,
  80. )
  81. parser.add_argument(
  82. "--no_repeat_ngram_size",
  83. type=int,
  84. help="Size of ngram repeat block for both text & unit decoding.",
  85. default=4,
  86. )
  87. # Unit generation args.
  88. parser.add_argument(
  89. "--unit_generation_beam_size",
  90. type=int,
  91. help=(
  92. "Beam size for incremental unit decoding"
  93. "not applicable for the NAR T2U decoder."
  94. ),
  95. default=5,
  96. )
  97. parser.add_argument(
  98. "--unit_generation_max_len_a",
  99. type=int,
  100. help=(
  101. "`a` in `ax + b` for incremental unit decoding"
  102. "not applicable for the NAR T2U decoder."
  103. ),
  104. default=25,
  105. )
  106. parser.add_argument(
  107. "--unit_generation_max_len_b",
  108. type=int,
  109. help=(
  110. "`b` in `ax + b` for incremental unit decoding"
  111. "not applicable for the NAR T2U decoder."
  112. ),
  113. default=50,
  114. )
  115. parser.add_argument(
  116. "--unit_generation_ngram_blocking",
  117. type=bool,
  118. help=(
  119. "Enable ngram_repeat_block for incremental unit decoding."
  120. "This blocks hypotheses with repeating ngram tokens."
  121. ),
  122. default=False,
  123. )
  124. parser.add_argument(
  125. "--unit_generation_ngram_filtering",
  126. type=bool,
  127. help=(
  128. "If True, removes consecutive repeated ngrams"
  129. "from the decoded unit output."
  130. ),
  131. default=False,
  132. )
  133. return parser
  134. def set_generation_opts(
  135. args: Namespace,
  136. ) -> Tuple[SequenceGeneratorOptions, SequenceGeneratorOptions]:
  137. # Set text, unit generation opts.
  138. text_generation_opts = SequenceGeneratorOptions(
  139. beam_size=args.text_generation_beam_size,
  140. soft_max_seq_len=(
  141. args.text_generation_max_len_a,
  142. args.text_generation_max_len_b,
  143. ),
  144. )
  145. if args.text_generation_ngram_blocking:
  146. text_generation_opts.logits_processor = NGramRepeatBlockProcessor(
  147. no_repeat_ngram_size=args.no_repeat_ngram_size
  148. )
  149. unit_generation_opts = SequenceGeneratorOptions(
  150. beam_size=args.unit_generation_beam_size,
  151. soft_max_seq_len=(
  152. args.unit_generation_max_len_a,
  153. args.unit_generation_max_len_b,
  154. ),
  155. )
  156. if args.unit_generation_ngram_blocking:
  157. unit_generation_opts.logits_processor = NGramRepeatBlockProcessor(
  158. no_repeat_ngram_size=args.no_repeat_ngram_size
  159. )
  160. return text_generation_opts, unit_generation_opts
  161. def main():
  162. parser = argparse.ArgumentParser(
  163. description="M4T inference on supported tasks using Translator."
  164. )
  165. parser.add_argument("input", type=str, help="Audio WAV file path or text input.")
  166. parser = add_inference_arguments(parser)
  167. args = parser.parse_args()
  168. if args.task.upper() in {"S2ST", "T2ST"} and args.output_path is None:
  169. raise ValueError("output_path must be provided to save the generated audio")
  170. if torch.cuda.is_available():
  171. device = torch.device("cuda:0")
  172. dtype = torch.float16
  173. else:
  174. device = torch.device("cpu")
  175. dtype = torch.float32
  176. logger.info(f"Running inference on {device=} with {dtype=}.")
  177. translator = Translator(args.model_name, args.vocoder_name, device, dtype=dtype)
  178. text_generation_opts, unit_generation_opts = set_generation_opts(args)
  179. logger.info(f"{text_generation_opts=}")
  180. logger.info(f"{unit_generation_opts=}")
  181. logger.info(
  182. f"unit_generation_ngram_filtering={args.unit_generation_ngram_filtering}"
  183. )
  184. text_output, speech_output = translator.predict(
  185. args.input,
  186. args.task,
  187. args.tgt_lang,
  188. src_lang=args.src_lang,
  189. text_generation_opts=text_generation_opts,
  190. unit_generation_opts=unit_generation_opts,
  191. unit_generation_ngram_filtering=args.unit_generation_ngram_filtering,
  192. )
  193. if speech_output is not None:
  194. logger.info(f"Saving translated audio in {args.tgt_lang}")
  195. torchaudio.save(
  196. args.output_path,
  197. speech_output.audio_wavs[0][0].to(torch.float32).cpu(),
  198. sample_rate=speech_output.sample_rate,
  199. )
  200. logger.info(f"Translated text in {args.tgt_lang}: {text_output[0]}")
  201. if __name__ == "__main__":
  202. main()