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

eval_lm.py 6.8 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
  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. """
  9. Evaluate the perplexity of a trained language model.
  10. """
  11. import numpy as np
  12. import torch
  13. from fairseq import options, progress_bar, tasks, utils
  14. from fairseq.meters import StopwatchMeter, TimeMeter
  15. from fairseq.sequence_scorer import SequenceScorer
  16. from fairseq.utils import import_user_module
  17. class WordStat(object):
  18. def __init__(self, word, is_bpe):
  19. self.word = word
  20. self.is_bpe = is_bpe
  21. self.log_prob = 0
  22. self.next_word_prob = 0
  23. self.count = 0
  24. self.missing_next_words = 0
  25. def add(self, log_prob, next_word_prob):
  26. """ increments counters for the sum of log probs of current word and next
  27. word (given context ending at current word). Since the next word might be at the end of the example,
  28. or it might be not counted because it is not an ending subword unit,
  29. also keeps track of how many of those we have seen """
  30. if next_word_prob is not None:
  31. self.next_word_prob += next_word_prob
  32. else:
  33. self.missing_next_words += 1
  34. self.log_prob += log_prob
  35. self.count += 1
  36. def __str__(self):
  37. return '{}\t{}\t{}\t{}\t{}\t{}'.format(self.word, self.count, self.log_prob, self.is_bpe,
  38. self.next_word_prob, self.count - self.missing_next_words)
  39. def main(parsed_args):
  40. assert parsed_args.path is not None, '--path required for evaluation!'
  41. import_user_module(parsed_args)
  42. print(parsed_args)
  43. use_cuda = torch.cuda.is_available() and not parsed_args.cpu
  44. task = tasks.setup_task(parsed_args)
  45. # Load ensemble
  46. print('| loading model(s) from {}'.format(parsed_args.path))
  47. models, args = utils.load_ensemble_for_inference(
  48. parsed_args.path.split(':'), task, model_arg_overrides=eval(parsed_args.model_overrides),
  49. )
  50. for arg in vars(parsed_args).keys():
  51. if arg not in {'self_target', 'future_target', 'past_target', 'tokens_per_sample', 'output_size_dictionary'}:
  52. setattr(args, arg, getattr(parsed_args, arg))
  53. task = tasks.setup_task(args)
  54. # Load dataset splits
  55. task.load_dataset(args.gen_subset)
  56. print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset))))
  57. # Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer)
  58. for model in models:
  59. model.make_generation_fast_()
  60. if args.fp16:
  61. model.half()
  62. assert len(models) > 0
  63. print('num. model params: {}'.format(sum(p.numel() for p in models[0].parameters())))
  64. itr = task.get_batch_iterator(
  65. dataset=task.dataset(args.gen_subset),
  66. max_tokens=args.max_tokens or 36000,
  67. max_sentences=args.max_sentences,
  68. max_positions=utils.resolve_max_positions(*[
  69. model.max_positions() for model in models
  70. ]),
  71. ignore_invalid_inputs=True,
  72. num_shards=args.num_shards,
  73. shard_id=args.shard_id,
  74. num_workers=args.num_workers,
  75. ).next_epoch_itr(shuffle=False)
  76. gen_timer = StopwatchMeter()
  77. scorer = SequenceScorer(models, task.target_dictionary)
  78. if use_cuda:
  79. scorer.cuda()
  80. score_sum = 0.
  81. count = 0
  82. if args.remove_bpe is not None:
  83. bpe_cont = args.remove_bpe.rstrip()
  84. bpe_toks = set(i for i in range(len(task.dictionary)) if task.dictionary[i].endswith(bpe_cont))
  85. bpe_len = len(bpe_cont)
  86. else:
  87. bpe_toks = None
  88. bpe_len = 0
  89. word_stats = dict()
  90. with progress_bar.build_progress_bar(args, itr) as t:
  91. results = scorer.score_batched_itr(t, cuda=use_cuda, timer=gen_timer)
  92. wps_meter = TimeMeter()
  93. for _, src_tokens, __, hypos in results:
  94. for hypo in hypos:
  95. pos_scores = hypo['positional_scores']
  96. skipped_toks = 0
  97. if bpe_toks is not None:
  98. for i in range(len(hypo['tokens']) - 1):
  99. if hypo['tokens'][i].item() in bpe_toks:
  100. skipped_toks += 1
  101. pos_scores[i + 1] += pos_scores[i]
  102. pos_scores[i] = 0
  103. inf_scores = pos_scores.eq(float('inf')) | pos_scores.eq(float('-inf'))
  104. if inf_scores.any():
  105. print('| Skipping tokens with inf scores:',
  106. task.target_dictionary.string(hypo['tokens'][inf_scores.nonzero()]))
  107. pos_scores = pos_scores[(~inf_scores).nonzero()]
  108. score_sum += pos_scores.sum().cpu()
  109. count += pos_scores.numel() - skipped_toks
  110. if args.output_word_probs or args.output_word_stats:
  111. w = ''
  112. word_prob = []
  113. is_bpe = False
  114. for i in range(len(hypo['tokens'])):
  115. w_ind = hypo['tokens'][i].item()
  116. w += task.dictionary[w_ind]
  117. if bpe_toks is not None and w_ind in bpe_toks:
  118. w = w[:-bpe_len]
  119. is_bpe = True
  120. else:
  121. word_prob.append((w, pos_scores[i].item()))
  122. next_prob = None
  123. ind = i + 1
  124. while ind < len(hypo['tokens']):
  125. if pos_scores[ind].item() != 0:
  126. next_prob = pos_scores[ind]
  127. break
  128. ind += 1
  129. word_stats.setdefault(w, WordStat(w, is_bpe)).add(pos_scores[i].item(), next_prob)
  130. is_bpe = False
  131. w = ''
  132. if args.output_word_probs:
  133. print('\t'.join('{} [{:2f}]'.format(x[0], x[1]) for x in word_prob))
  134. wps_meter.update(src_tokens.size(0))
  135. t.log({'wps': round(wps_meter.avg)})
  136. avg_nll_loss = -score_sum / count
  137. print('| Evaluated {} tokens in {:.1f}s ({:.2f} tokens/s)'.format(gen_timer.n, gen_timer.sum, 1. / gen_timer.avg))
  138. print('| Loss: {:.4f}, Perplexity: {:.2f}'.format(avg_nll_loss, np.exp(avg_nll_loss)))
  139. if args.output_word_stats:
  140. for ws in sorted(word_stats.values(), key=lambda x: x.count, reverse=True):
  141. print(ws)
  142. def cli_main():
  143. parser = options.get_eval_lm_parser()
  144. args = options.parse_args_and_arch(parser)
  145. main(args)
  146. if __name__ == '__main__':
  147. cli_main()
Tip!

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

Comments

Loading...