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

search.py 8.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
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
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. import math
  8. import torch
  9. class Search(object):
  10. def __init__(self, tgt_dict):
  11. self.pad = tgt_dict.pad()
  12. self.unk = tgt_dict.unk()
  13. self.eos = tgt_dict.eos()
  14. self.vocab_size = len(tgt_dict)
  15. self.scores_buf = None
  16. self.indices_buf = None
  17. self.beams_buf = None
  18. def _init_buffers(self, t):
  19. if self.scores_buf is None:
  20. self.scores_buf = t.new()
  21. self.indices_buf = torch.LongTensor().to(device=t.device)
  22. self.beams_buf = torch.LongTensor().to(device=t.device)
  23. def step(self, step, lprobs, scores, beam_size):
  24. """Take a single search step.
  25. Args:
  26. step: the current search step, starting at 0
  27. lprobs: (bsz x input_beam_size x vocab_size)
  28. the model's log-probabilities over the vocabulary at the current step
  29. scores: (bsz x input_beam_size x step)
  30. the historical model scores of each hypothesis up to this point
  31. Return: A tuple of (scores, indices, beams) where:
  32. scores: (bsz x output_beam_size)
  33. the scores of the chosen elements; output_beam_size can be
  34. larger than input_beam_size, e.g., we may return
  35. 2*input_beam_size to account for EOS
  36. indices: (bsz x output_beam_size)
  37. the indices of the chosen elements
  38. beams: (bsz x output_beam_size)
  39. the hypothesis ids of the chosen elements, in the range [0, input_beam_size)
  40. """
  41. raise NotImplementedError
  42. def set_src_lengths(self, src_lengths):
  43. self.src_lengths = src_lengths
  44. class BeamSearch(Search):
  45. def __init__(self, tgt_dict):
  46. super().__init__(tgt_dict)
  47. def step(self, step, lprobs, scores):
  48. super()._init_buffers(lprobs)
  49. bsz, beam_size, vocab_size = lprobs.size()
  50. if step == 0:
  51. # at the first step all hypotheses are equally likely, so use
  52. # only the first beam
  53. lprobs = lprobs[:, ::beam_size, :].contiguous()
  54. else:
  55. # make probs contain cumulative scores for each hypothesis
  56. lprobs.add_(scores[:, :, step - 1].unsqueeze(-1))
  57. torch.topk(
  58. lprobs.view(bsz, -1),
  59. k=min(
  60. # Take the best 2 x beam_size predictions. We'll choose the first
  61. # beam_size of these which don't predict eos to continue with.
  62. beam_size * 2,
  63. lprobs.view(bsz, -1).size(1) - 1, # -1 so we never select pad
  64. ),
  65. out=(self.scores_buf, self.indices_buf),
  66. )
  67. torch.div(self.indices_buf, vocab_size, out=self.beams_buf)
  68. self.indices_buf.fmod_(vocab_size)
  69. return self.scores_buf, self.indices_buf, self.beams_buf
  70. class LengthConstrainedBeamSearch(Search):
  71. def __init__(self, tgt_dict, min_len_a, min_len_b, max_len_a, max_len_b):
  72. super().__init__(tgt_dict)
  73. self.min_len_a = min_len_a
  74. self.min_len_b = min_len_b
  75. self.max_len_a = max_len_a
  76. self.max_len_b = max_len_b
  77. self.beam = BeamSearch(tgt_dict)
  78. def step(self, step, lprobs, scores):
  79. min_lens = self.min_len_a * self.src_lengths + self.min_len_b
  80. max_lens = self.max_len_a * self.src_lengths + self.max_len_b
  81. lprobs[step < min_lens, :, self.eos] = -math.inf
  82. lprobs[step == max_lens, :, self.eos] = 0
  83. lprobs[step > max_lens, :, self.eos] = -math.inf
  84. return self.beam.step(step, lprobs, scores)
  85. class DiverseBeamSearch(Search):
  86. """Diverse Beam Search.
  87. See "Diverse Beam Search: Decoding Diverse Solutions from Neural Sequence
  88. Models" for details.
  89. We only implement the Hamming Diversity penalty here, which performed best
  90. in the original paper.
  91. """
  92. def __init__(self, tgt_dict, num_groups, diversity_strength):
  93. super().__init__(tgt_dict)
  94. self.num_groups = num_groups
  95. self.diversity_strength = -diversity_strength
  96. self.diversity_buf = None
  97. self.beam = BeamSearch(tgt_dict)
  98. def step(self, step, lprobs, scores):
  99. super()._init_buffers(lprobs)
  100. bsz, beam_size, vocab_size = lprobs.size()
  101. if beam_size % self.num_groups != 0:
  102. raise ValueError(
  103. 'DiverseBeamSearch requires --beam to be divisible by the number of groups'
  104. )
  105. # initialize diversity penalty
  106. if self.diversity_buf is None:
  107. self.diversity_buf = lprobs.new()
  108. torch.zeros(lprobs[:, 0, :].size(), out=self.diversity_buf)
  109. scores_G, indices_G, beams_G = [], [], []
  110. for g in range(self.num_groups):
  111. lprobs_g = lprobs[:, g::self.num_groups, :]
  112. scores_g = scores[:, g::self.num_groups, :] if step > 0 else None
  113. # apply diversity penalty
  114. if g > 0:
  115. lprobs_g = torch.add(lprobs_g, self.diversity_strength, self.diversity_buf.unsqueeze(1))
  116. else:
  117. lprobs_g = lprobs_g.contiguous()
  118. scores_buf, indices_buf, beams_buf = self.beam.step(step, lprobs_g, scores_g)
  119. beams_buf.mul_(self.num_groups).add_(g)
  120. scores_G.append(scores_buf.clone())
  121. indices_G.append(indices_buf.clone())
  122. beams_G.append(beams_buf.clone())
  123. # update diversity penalty
  124. self.diversity_buf.scatter_add_(
  125. 1,
  126. indices_buf,
  127. self.diversity_buf.new_ones(indices_buf.size())
  128. )
  129. # interleave results from different groups
  130. self.scores_buf = torch.stack(scores_G, dim=2, out=self.scores_buf).view(bsz, -1)
  131. self.indices_buf = torch.stack(indices_G, dim=2, out=self.indices_buf).view(bsz, -1)
  132. self.beams_buf = torch.stack(beams_G, dim=2, out=self.beams_buf).view(bsz, -1)
  133. return self.scores_buf, self.indices_buf, self.beams_buf
  134. class Sampling(Search):
  135. def __init__(self, tgt_dict, sampling_topk=-1, sampling_temperature=1.):
  136. super().__init__(tgt_dict)
  137. self.sampling_topk = sampling_topk
  138. self.sampling_temperature = sampling_temperature
  139. def step(self, step, lprobs, scores):
  140. super()._init_buffers(lprobs)
  141. bsz, beam_size, vocab_size = lprobs.size()
  142. if step == 0:
  143. # at the first step all hypotheses are equally likely, so use
  144. # only the first beam
  145. lprobs = lprobs[:, ::beam_size, :].contiguous()
  146. # we exclude the first two vocab items, one of which is pad
  147. assert self.pad == 1, 'sampling assumes the first two symbols can be ignored'
  148. lprobs_nopad = lprobs[:, :, 2:]
  149. # only sample from top-k candidates
  150. if self.sampling_topk > 0:
  151. lprobs_nopad, topk_indices = lprobs_nopad.topk(self.sampling_topk)
  152. # sampling temperature
  153. if self.sampling_temperature != 1.:
  154. lprobs_nopad = lprobs_nopad.div_(self.sampling_temperature)
  155. # sample
  156. probs_nopad = lprobs_nopad.exp_()
  157. if step == 0:
  158. self.indices_buf = torch.multinomial(
  159. probs_nopad.view(bsz, -1),
  160. beam_size,
  161. replacement=True,
  162. out=self.indices_buf,
  163. ).view(bsz, beam_size)
  164. else:
  165. self.indices_buf = torch.multinomial(
  166. probs_nopad.view(bsz * beam_size, -1),
  167. 1,
  168. replacement=True,
  169. out=self.indices_buf,
  170. ).view(bsz, beam_size)
  171. if step == 0:
  172. # expand to beam size
  173. probs_nopad = probs_nopad.expand(bsz, beam_size, -1)
  174. # gather scores
  175. torch.gather(
  176. probs_nopad,
  177. dim=2,
  178. index=self.indices_buf.unsqueeze(-1),
  179. out=self.scores_buf,
  180. )
  181. self.scores_buf = self.scores_buf.log_().view(bsz, -1)
  182. # remap indices if using top-k sampling
  183. if self.sampling_topk > 0:
  184. self.indices_buf = torch.gather(
  185. topk_indices.expand(bsz, beam_size, -1),
  186. dim=2,
  187. index=self.indices_buf.unsqueeze(-1),
  188. ).squeeze(2)
  189. # remap indices since we excluded the first two vocab items
  190. self.indices_buf.add_(2)
  191. if step == 0:
  192. self.beams_buf = self.indices_buf.new_zeros(bsz, beam_size)
  193. else:
  194. self.beams_buf = torch.arange(0, beam_size, out=self.beams_buf).repeat(bsz, 1)
  195. # make scores cumulative
  196. self.scores_buf.add_(
  197. torch.gather(
  198. scores[:, :, step - 1],
  199. dim=1,
  200. index=self.beams_buf,
  201. )
  202. )
  203. return self.scores_buf, self.indices_buf, self.beams_buf
Tip!

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

Comments

Loading...