evaluate.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. # Copyright (c) Meta Platforms, Inc. and affiliates
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. import argparse
  7. import contextlib
  8. import itertools
  9. import logging
  10. import subprocess
  11. import torch
  12. import torchaudio
  13. from argparse import Namespace
  14. from dataclasses import dataclass
  15. from pathlib import Path
  16. from torch import Tensor
  17. from tqdm import tqdm
  18. from typing import List, Optional, Tuple, Dict
  19. from fairseq2.data import Collater, DataPipeline, FileMapper
  20. from fairseq2.data.audio import AudioDecoder, WaveformToFbankConverter
  21. from fairseq2.data.text import StrSplitter, TextTokenizer, read_text
  22. from fairseq2.data.typing import StringLike
  23. from fairseq2.generation import SequenceGeneratorOptions
  24. from fairseq2.typing import Device, DataType
  25. from m4t_scripts.predict import add_inference_arguments, set_generation_opts
  26. from seamless_communication.models.inference import (
  27. BatchedSpeechOutput,
  28. Modality,
  29. Translator,
  30. )
  31. from seamless_communication.models.unity import load_unity_text_tokenizer
  32. from scripts.eval_utils.compute_metrics import (
  33. compute_quality_metrics,
  34. )
  35. logging.basicConfig(
  36. level=logging.INFO,
  37. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  38. )
  39. logger = logging.getLogger(__name__)
  40. @dataclass
  41. class EvalContext:
  42. task: str
  43. """String representing the task. Valid choices are
  44. "S2ST", "S2TT", "T2ST", "T2TT", "ASR"."""
  45. input_modality: Modality
  46. """The input modality of the task."""
  47. output_modality: Modality
  48. """The output modality of the task."""
  49. model_name: str
  50. """The name of the S2T UnitY model."""
  51. data_file: Path
  52. """The pathname of the test TSV data file."""
  53. audio_root_dir: Optional[Path]
  54. """The pathname of the directory under which
  55. audio files are stored."""
  56. target_lang: str
  57. """The target translation language."""
  58. source_lang: Optional[str]
  59. """The source language."""
  60. batch_size: int
  61. """The batch size for model input."""
  62. device: Device
  63. """The device on which to run inference."""
  64. dtype: DataType
  65. """The data type with which to run inference."""
  66. output_path: Path
  67. """The pathname of the output directory to save
  68. the evaluation results."""
  69. ref_field: str
  70. """The reference target text field to compute
  71. the BLEU score against."""
  72. text_generation_opts: SequenceGeneratorOptions
  73. """Text generation hyperparameters."""
  74. unit_generation_opts: Optional[SequenceGeneratorOptions]
  75. """Unit generation hyperparameters, not applicable
  76. for the NAR T2U decoder."""
  77. unit_generation_ngram_filtering: bool
  78. """If True, removes consecutive repeating ngrams
  79. from the decoded unit output."""
  80. def count_lines(filename: Path) -> int:
  81. result = subprocess.run(["wc", "-l", filename], stdout=subprocess.PIPE)
  82. return int(result.stdout.decode().split()[0])
  83. def build_data_pipeline(
  84. ctx: EvalContext,
  85. text_tokenizer: TextTokenizer,
  86. ) -> DataPipeline:
  87. with open(ctx.data_file, "r") as f:
  88. header = f.readline().strip("\n").split("\t")
  89. first_example = f.readline().strip("\n").split("\t")
  90. # TODO: This will be soon auto-tuned. Right now hand-tuned for devfair.
  91. n_parallel = 4
  92. split_tsv = StrSplitter(names=header)
  93. pipeline_builder = read_text(ctx.data_file, rtrim=True).skip(1).map(split_tsv)
  94. if ctx.input_modality == Modality.SPEECH:
  95. assert ctx.audio_root_dir is not None
  96. map_file = FileMapper(root_dir=ctx.audio_root_dir, cached_fd_count=10)
  97. pipeline_builder.map(map_file, selector="audio", num_parallel_calls=n_parallel)
  98. decode_audio = AudioDecoder(dtype=torch.float32, device=ctx.device)
  99. convert_to_fbank = WaveformToFbankConverter(
  100. num_mel_bins=80,
  101. waveform_scale=2**15,
  102. channel_last=True,
  103. standardize=True,
  104. device=ctx.device,
  105. dtype=ctx.dtype,
  106. )
  107. pipeline_builder.map(
  108. [decode_audio, convert_to_fbank],
  109. selector="audio.data",
  110. num_parallel_calls=n_parallel,
  111. )
  112. else:
  113. if "src_lang" in header:
  114. source_lang = first_example[header.index("src_lang")]
  115. ctx.source_lang = source_lang
  116. elif ctx.source_lang is None:
  117. raise ValueError(
  118. (
  119. "'src_lang' is missing in the data_file"
  120. "header and in the arguments."
  121. )
  122. )
  123. token_encoder = text_tokenizer.create_encoder(
  124. task="translation", lang=source_lang, mode="source", device=ctx.device
  125. )
  126. pipeline_builder.map(
  127. [token_encoder],
  128. selector="src_text",
  129. num_parallel_calls=n_parallel,
  130. )
  131. pipeline_builder.bucket(bucket_size=ctx.batch_size)
  132. collate = Collater(pad_value=0, pad_to_multiple=1)
  133. pipeline_builder.map(collate, num_parallel_calls=n_parallel)
  134. pipeline_builder.prefetch(4)
  135. return pipeline_builder.and_return()
  136. def adjust_output_for_corrupted_inputs(
  137. valid_sequences: Tensor,
  138. text_output: List[StringLike],
  139. speech_output: Optional[BatchedSpeechOutput],
  140. ) -> Tuple[List[StringLike], Optional[BatchedSpeechOutput]]:
  141. adjusted_text_output: List[StringLike] = []
  142. adjusted_speech_output: Optional[BatchedSpeechOutput] = None
  143. if speech_output is not None:
  144. assert (
  145. len(text_output)
  146. == len(speech_output.units)
  147. == len(speech_output.audio_wavs)
  148. )
  149. adjusted_speech_output = BatchedSpeechOutput(units=[], audio_wavs=[])
  150. batch_counter = 0
  151. for is_valid in valid_sequences:
  152. if is_valid:
  153. adjusted_text_output.append(text_output[batch_counter])
  154. if speech_output is not None:
  155. assert adjusted_speech_output is not None
  156. adjusted_speech_output.units.append(speech_output.units[batch_counter])
  157. adjusted_speech_output.audio_wavs.append(
  158. speech_output.audio_wavs[batch_counter]
  159. )
  160. batch_counter += 1
  161. else:
  162. # For the corrupted inputs, we save the following dummy outputs:
  163. # empty string for text, empty list for units, 1 second of silence for audio.
  164. adjusted_text_output.append("")
  165. if adjusted_speech_output is not None:
  166. sample_rate = adjusted_speech_output.sample_rate
  167. adjusted_speech_output.units.append([])
  168. adjusted_speech_output.audio_wavs.append(
  169. torch.zeros(sample_rate).unsqueeze(0).unsqueeze(0)
  170. )
  171. return (
  172. adjusted_text_output,
  173. adjusted_speech_output,
  174. )
  175. def run_eval(
  176. translator: Translator,
  177. text_tokenizer: TextTokenizer,
  178. ctx: EvalContext,
  179. whisper_model_name: Optional[str] = None,
  180. ) -> None:
  181. pipeline = build_data_pipeline(ctx, text_tokenizer)
  182. total_steps = count_lines(ctx.data_file) - 1
  183. progress_bar = tqdm(total=total_steps)
  184. output_path = ctx.output_path / ctx.data_file.stem
  185. output_path.mkdir(parents=True, exist_ok=True)
  186. if ctx.output_modality == Modality.SPEECH:
  187. waveforms_dir = output_path / f"waveform_{ctx.data_file.stem}"
  188. waveforms_dir.mkdir(parents=True, exist_ok=True)
  189. model_outputs_tsv = output_path / f"model-outputs-{ctx.data_file.stem}.txt"
  190. unit_outputs_tsv = output_path / f"unit_output-{ctx.data_file.stem}.txt"
  191. with open(model_outputs_tsv, "w") as hyp_file, open(
  192. unit_outputs_tsv, "w"
  193. ) if ctx.output_modality == Modality.SPEECH else contextlib.nullcontext(
  194. itertools.repeat(None)
  195. ) as unit_file:
  196. sample_id = 0
  197. if ctx.output_modality == Modality.SPEECH:
  198. hyp_file.write(f"ref_tgt_text\tpred_tgt_text\tpred_tgt_audio\n")
  199. else:
  200. hyp_file.write(f"ref_tgt_text\tpred_tgt_text\n")
  201. for example in pipeline:
  202. valid_sequences: Optional[Tensor] = None
  203. if ctx.input_modality == Modality.SPEECH:
  204. src = example["audio"]["data"]["fbank"]
  205. # Skip corrupted audio tensors.
  206. valid_sequences = ~torch.any(
  207. torch.any(torch.isnan(src["seqs"]), dim=1), dim=1
  208. )
  209. if not valid_sequences.all():
  210. logger.warning(
  211. f"Sample IDs {sample_id} to {sample_id + ctx.batch_size} has some corrupted input."
  212. )
  213. src["seqs"] = src["seqs"][valid_sequences]
  214. src["seq_lens"] = src["seq_lens"][valid_sequences]
  215. else:
  216. src = example["src_text"]
  217. # Skip performing inference when the input is entirely corrupted.
  218. if src["seqs"].numel() > 0:
  219. (
  220. text_output,
  221. speech_output,
  222. ) = translator.predict(
  223. src,
  224. ctx.task,
  225. ctx.target_lang,
  226. src_lang=ctx.source_lang,
  227. text_generation_opts=ctx.text_generation_opts,
  228. unit_generation_opts=ctx.unit_generation_opts,
  229. unit_generation_ngram_filtering=ctx.unit_generation_ngram_filtering,
  230. )
  231. else:
  232. text_output = []
  233. if ctx.output_modality == Modality.SPEECH:
  234. speech_output = BatchedSpeechOutput(units=[], audio_wavs=[])
  235. else:
  236. speech_output = None
  237. if valid_sequences is not None and not valid_sequences.all():
  238. (
  239. text_output,
  240. speech_output,
  241. ) = adjust_output_for_corrupted_inputs(
  242. valid_sequences,
  243. text_output,
  244. speech_output,
  245. )
  246. hyps = [str(s) for s in text_output]
  247. refs = [str(s) for s in example[ctx.ref_field]]
  248. for i in range(len(text_output)):
  249. t = text_output[i]
  250. if ctx.output_modality == Modality.SPEECH:
  251. assert speech_output is not None
  252. u = speech_output.units[i]
  253. str_units = [str(i) for i in u]
  254. unit_file.write(" ".join(str_units) + "\n")
  255. wav_fp = str(waveforms_dir / f"{sample_id}_pred.wav")
  256. torchaudio.save(
  257. wav_fp,
  258. speech_output.audio_wavs[i][0].to(torch.float32).cpu(),
  259. sample_rate=speech_output.sample_rate,
  260. )
  261. hyp_file.write(f"{refs[i]}\t{hyps[i]}\t{wav_fp}\n")
  262. else:
  263. hyp_file.write(f"{refs[i]}\t{hyps[i]}\n")
  264. sample_id += 1
  265. progress_bar.update(1)
  266. progress_bar.close()
  267. logger.info(f"Processed {sample_id} samples")
  268. compute_quality_metrics(
  269. output_manifest_tsv_path=model_outputs_tsv,
  270. output_dir=output_path,
  271. tgt_lang=ctx.target_lang,
  272. task=ctx.task,
  273. device=ctx.device,
  274. whisper_model_name=whisper_model_name,
  275. )
  276. def main(optional_args: Optional[Dict] = None):
  277. parser = argparse.ArgumentParser(
  278. description="M4T evaluation for tasks supported by Translator."
  279. )
  280. parser.add_argument(
  281. "--data_file", type=str, help="Data file (.tsv) to be evaluated."
  282. )
  283. parser = add_inference_arguments(parser)
  284. parser.add_argument(
  285. "--batch_size",
  286. type=int,
  287. help="Inference batch size.",
  288. default=4,
  289. )
  290. parser.add_argument(
  291. "--audio_root_dir",
  292. type=str,
  293. help="Root directory for the audio filenames in the data file.",
  294. default="",
  295. )
  296. parser.add_argument(
  297. "--ref_field",
  298. type=str,
  299. help="Reference target text field to compute the BLEU score against.",
  300. default="tgt_text",
  301. )
  302. parser.add_argument(
  303. "--whisper_model_name",
  304. type=str,
  305. help="Whisper model to be used for ASR-BLEU scoring",
  306. default="large",
  307. )
  308. args, unknown = parser.parse_known_args()
  309. default_args = vars(args)
  310. default_args.update(optional_args) if optional_args else default_args
  311. args = Namespace(**default_args)
  312. if not args.data_file or not args.task or not args.tgt_lang:
  313. raise Exception(
  314. "Please provide required arguments for evaluation - data_file, task, tgt_lang"
  315. )
  316. input_modality, output_modality = Translator.get_modalities_from_task_str(args.task)
  317. if input_modality == Modality.SPEECH and not Path(args.audio_root_dir).exists():
  318. raise ValueError(
  319. f"Invalid audio_root_dir: {args.audio_root_dir} for speech input."
  320. )
  321. if torch.cuda.is_available():
  322. device = torch.device("cuda:0")
  323. dtype = torch.float16
  324. else:
  325. device = torch.device("cpu")
  326. dtype = torch.float32
  327. text_tokenizer = load_unity_text_tokenizer(args.model_name)
  328. # TODO: Avoid loading the T2U model, vocoder when the output
  329. # modality is text.
  330. translator = Translator(
  331. args.model_name,
  332. args.vocoder_name,
  333. device,
  334. text_tokenizer=text_tokenizer,
  335. dtype=dtype,
  336. )
  337. text_generation_opts, unit_generation_opts = set_generation_opts(args)
  338. logger.info(f"{text_generation_opts=}")
  339. logger.info(f"{unit_generation_opts=}")
  340. logger.info(
  341. f"unit_generation_ngram_filtering={args.unit_generation_ngram_filtering}"
  342. )
  343. # fmt: off
  344. ctx = EvalContext(
  345. task=args.task,
  346. input_modality=input_modality,
  347. output_modality=output_modality,
  348. model_name=args.model_name,
  349. data_file=Path(args.data_file),
  350. audio_root_dir=Path(args.audio_root_dir),
  351. target_lang=args.tgt_lang,
  352. source_lang=args.src_lang,
  353. batch_size=args.batch_size,
  354. device=device,
  355. dtype=dtype,
  356. ref_field=args.ref_field,
  357. text_generation_opts=text_generation_opts,
  358. unit_generation_opts=unit_generation_opts,
  359. unit_generation_ngram_filtering=args.unit_generation_ngram_filtering,
  360. output_path=Path(args.output_path),
  361. )
  362. # fmt: on
  363. logger.info(f"Running inference on {device=} with {dtype=}, {ctx.batch_size=}.")
  364. run_eval(translator, text_tokenizer, ctx, args.whisper_model_name)
  365. if __name__ == "__main__":
  366. main()