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

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

Comments

Loading...