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

generate.py 6.9 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
  1. #!/usr/bin/env python3 -u
  2. # Copyright (c) 2017-present, Facebook, Inc.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the license found in the LICENSE file in
  6. # the root directory of this source tree. An additional grant of patent rights
  7. # can be found in the PATENTS file in the same directory.
  8. import torch
  9. from fairseq import bleu, data, options, progress_bar, tokenizer, utils
  10. from fairseq.meters import StopwatchMeter, TimeMeter
  11. from fairseq.sequence_generator import SequenceGenerator
  12. from fairseq.sequence_scorer import SequenceScorer
  13. def main(args):
  14. assert args.path is not None, '--path required for generation!'
  15. print(args)
  16. assert not args.sampling or args.nbest == args.beam, \
  17. '--sampling requires --nbest to be equal to --beam'
  18. use_cuda = torch.cuda.is_available() and not args.cpu
  19. # Load dataset
  20. if args.replace_unk is None:
  21. dataset = data.load_dataset(
  22. args.data,
  23. [args.gen_subset],
  24. args.source_lang,
  25. args.target_lang,
  26. )
  27. else:
  28. dataset = data.load_raw_text_dataset(
  29. args.data,
  30. [args.gen_subset],
  31. args.source_lang,
  32. args.target_lang,
  33. )
  34. if args.source_lang is None or args.target_lang is None:
  35. # record inferred languages in args
  36. args.source_lang, args.target_lang = dataset.src, dataset.dst
  37. # Load ensemble
  38. print('| loading model(s) from {}'.format(', '.join(args.path)))
  39. models, _ = utils.load_ensemble_for_inference(args.path, dataset.src_dict, dataset.dst_dict)
  40. print('| [{}] dictionary: {} types'.format(dataset.src, len(dataset.src_dict)))
  41. print('| [{}] dictionary: {} types'.format(dataset.dst, len(dataset.dst_dict)))
  42. print('| {} {} {} examples'.format(args.data, args.gen_subset, len(dataset.splits[args.gen_subset])))
  43. # Optimize ensemble for generation
  44. for model in models:
  45. model.make_generation_fast_(
  46. beamable_mm_beam_size=None if args.no_beamable_mm else args.beam,
  47. )
  48. # Load alignment dictionary for unknown word replacement
  49. # (None if no unknown word replacement, empty if no path to align dictionary)
  50. align_dict = utils.load_align_dict(args.replace_unk)
  51. # Load dataset (possibly sharded)
  52. max_positions = min(model.max_encoder_positions() for model in models)
  53. itr = dataset.eval_dataloader(
  54. args.gen_subset,
  55. max_sentences=args.max_sentences or 128,
  56. max_positions=max_positions,
  57. skip_invalid_size_inputs_valid_test=args.skip_invalid_size_inputs_valid_test,
  58. )
  59. if args.num_shards > 1:
  60. if args.shard_id < 0 or args.shard_id >= args.num_shards:
  61. raise ValueError('--shard-id must be between 0 and num_shards')
  62. itr = data.sharded_iterator(itr, args.num_shards, args.shard_id)
  63. # Initialize generator
  64. gen_timer = StopwatchMeter()
  65. if args.score_reference:
  66. translator = SequenceScorer(models)
  67. else:
  68. translator = SequenceGenerator(
  69. models, beam_size=args.beam, stop_early=(not args.no_early_stop),
  70. normalize_scores=(not args.unnormalized), len_penalty=args.lenpen,
  71. unk_penalty=args.unkpen, sampling=args.sampling)
  72. if use_cuda:
  73. translator.cuda()
  74. # Generate and compute BLEU score
  75. scorer = bleu.Scorer(dataset.dst_dict.pad(), dataset.dst_dict.eos(), dataset.dst_dict.unk())
  76. num_sentences = 0
  77. has_target = True
  78. with progress_bar.build_progress_bar(args, itr) as t:
  79. if args.score_reference:
  80. translations = translator.score_batched_itr(t, cuda=use_cuda, timer=gen_timer)
  81. else:
  82. translations = translator.generate_batched_itr(
  83. t, maxlen_a=args.max_len_a, maxlen_b=args.max_len_b,
  84. cuda=use_cuda, timer=gen_timer, prefix_size=args.prefix_size)
  85. wps_meter = TimeMeter()
  86. for sample_id, src_tokens, target_tokens, hypos in translations:
  87. # Process input and ground truth
  88. has_target = target_tokens is not None
  89. target_tokens = target_tokens.int().cpu() if has_target else None
  90. # Either retrieve the original sentences or regenerate them from tokens.
  91. if align_dict is not None:
  92. src_str = dataset.splits[args.gen_subset].src.get_original_text(sample_id)
  93. target_str = dataset.splits[args.gen_subset].dst.get_original_text(sample_id)
  94. else:
  95. src_str = dataset.src_dict.string(src_tokens, args.remove_bpe)
  96. target_str = dataset.dst_dict.string(target_tokens,
  97. args.remove_bpe,
  98. escape_unk=True) if has_target else ''
  99. if not args.quiet:
  100. print('S-{}\t{}'.format(sample_id, src_str))
  101. if has_target:
  102. print('T-{}\t{}'.format(sample_id, target_str))
  103. # Process top predictions
  104. for i, hypo in enumerate(hypos[:min(len(hypos), args.nbest)]):
  105. hypo_tokens, hypo_str, alignment = utils.post_process_prediction(
  106. hypo_tokens=hypo['tokens'].int().cpu(),
  107. src_str=src_str,
  108. alignment=hypo['alignment'].int().cpu(),
  109. align_dict=align_dict,
  110. dst_dict=dataset.dst_dict,
  111. remove_bpe=args.remove_bpe,
  112. )
  113. if not args.quiet:
  114. print('H-{}\t{}\t{}'.format(sample_id, hypo['score'], hypo_str))
  115. print('P-{}\t{}'.format(
  116. sample_id,
  117. ' '.join(map(
  118. lambda x: '{:.4f}'.format(x),
  119. hypo['positional_scores'].tolist(),
  120. ))
  121. ))
  122. print('A-{}\t{}'.format(
  123. sample_id,
  124. ' '.join(map(lambda x: str(utils.item(x)), alignment))
  125. ))
  126. # Score only the top hypothesis
  127. if has_target and i == 0:
  128. if align_dict is not None or args.remove_bpe is not None:
  129. # Convert back to tokens for evaluation with unk replacement and/or without BPE
  130. target_tokens = tokenizer.Tokenizer.tokenize(
  131. target_str, dataset.dst_dict, add_if_not_exist=True)
  132. scorer.add(target_tokens, hypo_tokens)
  133. wps_meter.update(src_tokens.size(0))
  134. t.log({'wps': round(wps_meter.avg)})
  135. num_sentences += 1
  136. print('| Translated {} sentences ({} tokens) in {:.1f}s ({:.2f} tokens/s)'.format(
  137. num_sentences, gen_timer.n, gen_timer.sum, 1. / gen_timer.avg))
  138. if has_target:
  139. print('| Generate {} with beam={}: {}'.format(args.gen_subset, args.beam, scorer.result_string()))
  140. if __name__ == '__main__':
  141. parser = options.get_generation_parser()
  142. args = parser.parse_args()
  143. main(args)
Tip!

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

Comments

Loading...