Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

evaluate.py 18 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
  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. # MIT_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 json
  12. from argparse import Namespace
  13. from dataclasses import dataclass
  14. from pathlib import Path
  15. from typing import Any, Dict, List, Optional, Tuple
  16. import torch
  17. import torchaudio
  18. from fairseq2.data import Collater, DataPipeline, FileMapper
  19. from fairseq2.data.audio import AudioDecoder, WaveformToFbankConverter
  20. from fairseq2.data.text import StrSplitter, TextTokenizer, read_text
  21. from fairseq2.data.typing import StringLike
  22. from fairseq2.typing import DataType, Device
  23. from torch import Tensor
  24. from tqdm import tqdm
  25. from seamless_communication.cli.eval_utils import (
  26. compute_quality_metrics,
  27. )
  28. from seamless_communication.cli.m4t.predict import (
  29. add_inference_arguments,
  30. set_generation_opts,
  31. )
  32. from seamless_communication.models.unity import UnitYModel
  33. from seamless_communication.inference import (
  34. BatchedSpeechOutput,
  35. Modality,
  36. SequenceGeneratorOptions,
  37. Translator,
  38. )
  39. logging.basicConfig(
  40. level=logging.INFO,
  41. format="%(asctime)s %(levelname)s -- %(name)s: %(message)s",
  42. )
  43. logger = logging.getLogger(__name__)
  44. @dataclass
  45. class EvalContext:
  46. task: str
  47. """String representing the task. Valid choices are
  48. "S2ST", "S2TT", "T2ST", "T2TT", "ASR"."""
  49. input_modality: Modality
  50. """The input modality of the task."""
  51. output_modality: Modality
  52. """The output modality of the task."""
  53. model_name: str
  54. """The name of the S2T UnitY model."""
  55. data_file: Path
  56. """The pathname of the test data file, TSV or manifest JSON."""
  57. data_file_type: str
  58. """Type of data file, TSV or manifest JSON."""
  59. audio_root_dir: Optional[Path]
  60. """The pathname of the directory under which
  61. audio files are stored."""
  62. target_lang: str
  63. """The target translation language."""
  64. source_lang: Optional[str]
  65. """The source language."""
  66. batch_size: int
  67. """The batch size for model input."""
  68. device: Device
  69. """The device on which to run inference."""
  70. dtype: DataType
  71. """The data type with which to run inference."""
  72. output_path: Path
  73. """The pathname of the output directory to save
  74. the evaluation results."""
  75. ref_field: str
  76. """The reference target text field to compute
  77. the BLEU score against."""
  78. text_generation_opts: SequenceGeneratorOptions
  79. """Text generation hyperparameters."""
  80. unit_generation_opts: Optional[SequenceGeneratorOptions]
  81. """Unit generation hyperparameters, not applicable
  82. for the NAR T2U decoder."""
  83. unit_generation_ngram_filtering: bool
  84. """If True, removes consecutive repeating ngrams
  85. from the decoded unit output."""
  86. def count_lines(filename: Path) -> int:
  87. result = subprocess.run(["wc", "-l", filename], stdout=subprocess.PIPE)
  88. return int(result.stdout.decode().split()[0])
  89. def build_data_pipeline(
  90. ctx: EvalContext,
  91. text_tokenizer: TextTokenizer,
  92. ) -> DataPipeline:
  93. if ctx.data_file_type == "TSV":
  94. with open(ctx.data_file, "r") as f:
  95. header = f.readline().strip("\n").split("\t")
  96. first_example = f.readline().strip("\n").split("\t")
  97. format_tsv = StrSplitter(names=header)
  98. pipeline_builder = read_text(ctx.data_file, rtrim=True).skip(1).map(format_tsv)
  99. elif ctx.data_file_type == "JSON":
  100. def format_json(line: str):
  101. example = json.loads(str(line))
  102. return {
  103. "src_text": example["source"]["text"],
  104. "src_lang": example["source"]["lang"],
  105. "audio": example["source"]["audio_local_path"],
  106. "tgt_text": example["target"]["text"],
  107. }
  108. with open(ctx.data_file, "r") as f:
  109. header = list(format_json(f.readline()).keys())
  110. first_example = list(format_json(f.readline()).values())
  111. pipeline_builder = read_text(ctx.data_file, rtrim=True).map(format_json)
  112. else:
  113. raise NotImplementedError
  114. # TODO: This will be soon auto-tuned. Right now hand-tuned for devfair.
  115. n_parallel = 4
  116. if ctx.input_modality == Modality.SPEECH:
  117. assert ctx.audio_root_dir is not None
  118. map_file = FileMapper(root_dir=ctx.audio_root_dir, cached_fd_count=10)
  119. pipeline_builder.map(map_file, selector="audio", num_parallel_calls=n_parallel)
  120. decode_audio = AudioDecoder(dtype=torch.float32, device=ctx.device)
  121. convert_to_fbank = WaveformToFbankConverter(
  122. num_mel_bins=80,
  123. waveform_scale=2**15,
  124. channel_last=True,
  125. standardize=True,
  126. device=ctx.device,
  127. dtype=ctx.dtype,
  128. )
  129. pipeline_builder.map(
  130. [decode_audio, convert_to_fbank],
  131. selector="audio.data",
  132. num_parallel_calls=n_parallel,
  133. )
  134. else:
  135. if "src_lang" in header:
  136. source_lang = first_example[header.index("src_lang")]
  137. ctx.source_lang = source_lang
  138. elif ctx.source_lang is None:
  139. raise ValueError(
  140. (
  141. "'src_lang' is missing in the data_file"
  142. "header and in the arguments."
  143. )
  144. )
  145. token_encoder = text_tokenizer.create_encoder(
  146. task="translation", lang=source_lang, mode="source", device=ctx.device
  147. )
  148. pipeline_builder.map(
  149. [token_encoder],
  150. selector="src_text",
  151. num_parallel_calls=n_parallel,
  152. )
  153. pipeline_builder.bucket(bucket_size=ctx.batch_size)
  154. collate = Collater(pad_value=0, pad_to_multiple=1)
  155. pipeline_builder.map(collate, num_parallel_calls=n_parallel)
  156. pipeline_builder.prefetch(4)
  157. return pipeline_builder.and_return()
  158. def adjust_output_for_corrupted_inputs(
  159. valid_sequences: Tensor,
  160. text_output: List[StringLike],
  161. speech_output: Optional[BatchedSpeechOutput],
  162. ) -> Tuple[List[StringLike], Optional[BatchedSpeechOutput]]:
  163. adjusted_text_output: List[StringLike] = []
  164. adjusted_speech_output: Optional[BatchedSpeechOutput] = None
  165. if speech_output is not None:
  166. assert (
  167. len(text_output)
  168. == len(speech_output.units)
  169. == len(speech_output.audio_wavs)
  170. )
  171. adjusted_speech_output = BatchedSpeechOutput(units=[], audio_wavs=[])
  172. batch_counter = 0
  173. for is_valid in valid_sequences:
  174. if is_valid:
  175. adjusted_text_output.append(text_output[batch_counter])
  176. if speech_output is not None:
  177. assert adjusted_speech_output is not None
  178. adjusted_speech_output.units.append(speech_output.units[batch_counter])
  179. adjusted_speech_output.audio_wavs.append(
  180. speech_output.audio_wavs[batch_counter]
  181. )
  182. batch_counter += 1
  183. else:
  184. # For the corrupted inputs, we save the following dummy outputs:
  185. # empty string for text, empty list for units, 1 second of silence for audio.
  186. adjusted_text_output.append("")
  187. if adjusted_speech_output is not None:
  188. sample_rate = adjusted_speech_output.sample_rate
  189. adjusted_speech_output.units.append([])
  190. adjusted_speech_output.audio_wavs.append(
  191. torch.zeros(sample_rate).unsqueeze(0).unsqueeze(0)
  192. )
  193. return (
  194. adjusted_text_output,
  195. adjusted_speech_output,
  196. )
  197. def run_eval(
  198. translator: Translator,
  199. ctx: EvalContext,
  200. whisper_model_name: str,
  201. n_samples = None
  202. ) -> None:
  203. pipeline = build_data_pipeline(ctx, translator.text_tokenizer)
  204. total_steps = count_lines(ctx.data_file) - 1
  205. progress_bar = tqdm(total=n_samples or total_steps)
  206. output_path = ctx.output_path / ctx.data_file.stem
  207. output_path.mkdir(parents=True, exist_ok=True)
  208. if ctx.output_modality == Modality.SPEECH:
  209. waveforms_dir = output_path / f"waveform_{ctx.data_file.stem}"
  210. waveforms_dir.mkdir(parents=True, exist_ok=True)
  211. model_outputs_tsv = output_path / f"model-outputs-{ctx.data_file.stem}.txt"
  212. unit_outputs_tsv = output_path / f"unit_output-{ctx.data_file.stem}.txt"
  213. with open(model_outputs_tsv, "w") as hyp_file, open(
  214. unit_outputs_tsv, "w"
  215. ) if ctx.output_modality == Modality.SPEECH else contextlib.nullcontext(
  216. itertools.repeat(None)
  217. ) as unit_file:
  218. sample_id = 0
  219. if ctx.output_modality == Modality.SPEECH:
  220. hyp_file.write("ref_tgt_text\tpred_tgt_text\tpred_tgt_audio\n")
  221. else:
  222. hyp_file.write("ref_tgt_text\tpred_tgt_text\n")
  223. for example in pipeline:
  224. valid_sequences: Optional[Tensor] = None
  225. if ctx.input_modality == Modality.SPEECH:
  226. src = example["audio"]["data"]["fbank"]
  227. # Skip corrupted audio tensors.
  228. valid_sequences = ~torch.any(
  229. torch.any(torch.isnan(src["seqs"]), dim=1), dim=1
  230. )
  231. if not valid_sequences.all():
  232. logger.warning(
  233. f"Sample IDs {sample_id} to {sample_id + ctx.batch_size} has some corrupted input."
  234. )
  235. src["seqs"] = src["seqs"][valid_sequences]
  236. src["seq_lens"] = src["seq_lens"][valid_sequences]
  237. else:
  238. src = example["src_text"]
  239. # Skip performing inference when the input is entirely corrupted.
  240. if src["seqs"].numel() > 0:
  241. # HACK:: Fix this bad handling
  242. # RuntimeError: The sequence generator returned no hypothesis at index 2. Please file a bug report.
  243. try:
  244. (text_output, speech_output,) = translator.predict(
  245. src,
  246. ctx.task,
  247. ctx.target_lang,
  248. src_lang=ctx.source_lang,
  249. text_generation_opts=ctx.text_generation_opts,
  250. unit_generation_opts=ctx.unit_generation_opts,
  251. unit_generation_ngram_filtering=ctx.unit_generation_ngram_filtering,
  252. )
  253. except RuntimeError as e:
  254. logger.exception(f"Caught RuntimeError: {e}")
  255. continue
  256. else:
  257. text_output = []
  258. if ctx.output_modality == Modality.SPEECH:
  259. speech_output = BatchedSpeechOutput(units=[], audio_wavs=[])
  260. else:
  261. speech_output = None
  262. if valid_sequences is not None and not valid_sequences.all():
  263. (text_output, speech_output,) = adjust_output_for_corrupted_inputs(
  264. valid_sequences,
  265. text_output,
  266. speech_output,
  267. )
  268. hyps = [str(s) for s in text_output]
  269. refs = [str(s) for s in example[ctx.ref_field]]
  270. for i in range(len(text_output)):
  271. if ctx.output_modality == Modality.SPEECH:
  272. assert speech_output is not None
  273. u = speech_output.units[i]
  274. str_units = [str(i) for i in u]
  275. unit_file.write(" ".join(str_units) + "\n")
  276. wav_fp = str(waveforms_dir / f"{sample_id}_pred.wav")
  277. torchaudio.save(
  278. wav_fp,
  279. speech_output.audio_wavs[i][0].to(torch.float32).cpu(),
  280. sample_rate=speech_output.sample_rate,
  281. )
  282. hyp_file.write(f"{refs[i]}\t{hyps[i]}\t{wav_fp}\n")
  283. else:
  284. hyp_file.write(f"{refs[i]}\t{hyps[i]}\n")
  285. sample_id += 1
  286. progress_bar.update(1)
  287. if n_samples and progress_bar.n == n_samples:
  288. break
  289. if n_samples and progress_bar.n == n_samples:
  290. break
  291. progress_bar.close()
  292. logger.info(f"Processed {sample_id} samples")
  293. compute_quality_metrics(
  294. output_manifest_tsv_path=model_outputs_tsv,
  295. output_path=output_path,
  296. tgt_lang=ctx.target_lang,
  297. task=ctx.task,
  298. device=ctx.device,
  299. whisper_model_name=whisper_model_name,
  300. )
  301. def load_checkpoint(model: UnitYModel, path: str, device = torch.device("cpu")) -> None:
  302. saved_model = torch.load(path, map_location=device)["model"]
  303. saved_model = { k.replace("model.", ""): v for k, v in saved_model.items() }
  304. def _select_keys(state_dict: Dict[str, Any], prefix: str) -> Dict[str, Any]:
  305. return {key.replace(prefix, ""): value for key, value in state_dict.items() if key.startswith(prefix)}
  306. model.speech_encoder_frontend.load_state_dict(_select_keys(saved_model, "model.speech_encoder_frontend."))
  307. model.speech_encoder.load_state_dict(_select_keys(saved_model, "model.speech_encoder."))
  308. assert model.text_decoder_frontend is not None
  309. model.text_decoder_frontend.load_state_dict(_select_keys(saved_model, "model.text_decoder_frontend."))
  310. assert model.text_decoder is not None
  311. model.text_decoder.load_state_dict(_select_keys(saved_model, "model.text_decoder."))
  312. assert model.final_proj is not None
  313. model.final_proj.load_state_dict(_select_keys(saved_model, "model.final_proj."))
  314. def main(optional_args: Optional[Dict[str, Any]] = None) -> None:
  315. parser = argparse.ArgumentParser(
  316. description="M4T evaluation for tasks supported by Translator."
  317. )
  318. parser.add_argument(
  319. "--data_file",
  320. type=str,
  321. help="Data file to be evaluated, either TSV file or manifest JSON file."
  322. "Format of the manifest JSON file should be that as produced by `m4t_prepare_dataset`"
  323. )
  324. parser.add_argument(
  325. "--load_checkpoint",
  326. type=str,
  327. help="Load a local Checkpoint",
  328. default=None
  329. )
  330. parser = add_inference_arguments(parser)
  331. parser.add_argument(
  332. "--device",
  333. type=str,
  334. help="Device",
  335. default="cuda" if torch.cuda.is_available() else "cpu",
  336. )
  337. parser.add_argument(
  338. "--batch_size",
  339. type=int,
  340. help="Inference batch size.",
  341. default=4,
  342. )
  343. parser.add_argument(
  344. "--audio_root_dir",
  345. type=str,
  346. help="Root directory for the audio filenames in the data file.",
  347. default="",
  348. )
  349. parser.add_argument(
  350. "--ref_field",
  351. type=str,
  352. help="Reference target text field to compute the BLEU score against.",
  353. default="tgt_text",
  354. )
  355. parser.add_argument(
  356. "--whisper_model_name",
  357. type=str,
  358. help="Whisper model to be used for ASR-BLEU scoring",
  359. default="large",
  360. )
  361. parser.add_argument(
  362. "--n_samples",
  363. type=int,
  364. help="Number of Samples to run eval on. All if None.",
  365. default=None,
  366. )
  367. args, _ = parser.parse_known_args()
  368. default_args = vars(args)
  369. default_args.update(optional_args) if optional_args else default_args
  370. args = Namespace(**default_args)
  371. assert args.data_file and args.task and args.tgt_lang and args.output_path, \
  372. "Please provide required arguments for evaluation - data_file, task, tgt_lang"
  373. assert Path(args.data_file).exists(), \
  374. f"Invalid `data_file`: {args.data_file} does not exist"
  375. if Path(args.data_file).suffix == ".tsv":
  376. data_type = "TSV"
  377. elif Path(args.data_file).suffix == ".json":
  378. data_type = "JSON"
  379. else:
  380. raise ValueError("Unable to recognize file type! Please use a data_file with either .tsv or .json extension.")
  381. input_modality, output_modality = Translator.get_modalities_from_task_str(args.task)
  382. if input_modality == Modality.SPEECH and not Path(args.audio_root_dir).exists():
  383. raise ValueError(
  384. f"Invalid audio_root_dir: {args.audio_root_dir} for speech input."
  385. )
  386. device = torch.device(args.device)
  387. dtype = torch.float16 if device.type == "cuda" else torch.float32
  388. # TODO: Avoid loading the T2U model, vocoder when the output
  389. # modality is text.
  390. translator = Translator(
  391. args.model_name,
  392. args.vocoder_name,
  393. device,
  394. dtype=dtype,
  395. input_modality=input_modality,
  396. output_modality=output_modality,
  397. )
  398. if args.load_checkpoint:
  399. load_checkpoint(translator.model, path=args.load_checkpoint, device=device)
  400. text_generation_opts, unit_generation_opts = set_generation_opts(args)
  401. logger.info(f"{text_generation_opts=}")
  402. logger.info(f"{unit_generation_opts=}")
  403. logger.info(
  404. f"unit_generation_ngram_filtering={args.unit_generation_ngram_filtering}"
  405. )
  406. # fmt: off
  407. ctx = EvalContext(
  408. task=args.task,
  409. input_modality=input_modality,
  410. output_modality=output_modality,
  411. model_name=args.model_name,
  412. data_file=Path(args.data_file),
  413. data_file_type=data_type,
  414. audio_root_dir=Path(args.audio_root_dir),
  415. target_lang=args.tgt_lang,
  416. source_lang=args.src_lang,
  417. batch_size=args.batch_size,
  418. device=device,
  419. dtype=dtype,
  420. ref_field=args.ref_field,
  421. text_generation_opts=text_generation_opts,
  422. unit_generation_opts=unit_generation_opts,
  423. unit_generation_ngram_filtering=args.unit_generation_ngram_filtering,
  424. output_path=args.output_path,
  425. )
  426. # fmt: on
  427. logger.info(f"Running inference on {device=} with {dtype=}, {ctx.batch_size=}.")
  428. run_eval(translator, ctx, args.whisper_model_name, n_samples=args.n_samples)
  429. if __name__ == "__main__":
  430. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...