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

utils.py 7.3 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
  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 argparse
  8. import torch
  9. from fairseq import utils
  10. from fairseq.data import Dictionary
  11. from fairseq.data.language_pair_dataset import collate
  12. from fairseq.models import (
  13. FairseqEncoder,
  14. FairseqIncrementalDecoder,
  15. FairseqModel,
  16. )
  17. from fairseq.tasks import FairseqTask
  18. def dummy_dictionary(vocab_size, prefix='token_'):
  19. d = Dictionary()
  20. for i in range(vocab_size):
  21. token = prefix + str(i)
  22. d.add_symbol(token)
  23. d.finalize(padding_factor=1) # don't add extra padding symbols
  24. return d
  25. def dummy_dataloader(
  26. samples,
  27. padding_idx=1,
  28. eos_idx=2,
  29. batch_size=None,
  30. ):
  31. if batch_size is None:
  32. batch_size = len(samples)
  33. # add any missing data to samples
  34. for i, sample in enumerate(samples):
  35. if 'id' not in sample:
  36. sample['id'] = i
  37. # create dataloader
  38. dataset = TestDataset(samples)
  39. dataloader = torch.utils.data.DataLoader(
  40. dataset,
  41. batch_size=batch_size,
  42. collate_fn=(lambda samples: collate(samples, padding_idx, eos_idx)),
  43. )
  44. return iter(dataloader)
  45. def sequence_generator_setup():
  46. # construct dummy dictionary
  47. d = dummy_dictionary(vocab_size=2)
  48. eos = d.eos()
  49. w1 = 4
  50. w2 = 5
  51. # construct source data
  52. src_tokens = torch.LongTensor([[w1, w2, eos], [w1, w2, eos]])
  53. src_lengths = torch.LongTensor([2, 2])
  54. args = argparse.Namespace()
  55. unk = 0.
  56. args.beam_probs = [
  57. # step 0:
  58. torch.FloatTensor([
  59. # eos w1 w2
  60. # sentence 1:
  61. [0.0, unk, 0.9, 0.1], # beam 1
  62. [0.0, unk, 0.9, 0.1], # beam 2
  63. # sentence 2:
  64. [0.0, unk, 0.7, 0.3],
  65. [0.0, unk, 0.7, 0.3],
  66. ]),
  67. # step 1:
  68. torch.FloatTensor([
  69. # eos w1 w2 prefix
  70. # sentence 1:
  71. [1.0, unk, 0.0, 0.0], # w1: 0.9 (emit: w1 <eos>: 0.9*1.0)
  72. [0.0, unk, 0.9, 0.1], # w2: 0.1
  73. # sentence 2:
  74. [0.25, unk, 0.35, 0.4], # w1: 0.7 (don't emit: w1 <eos>: 0.7*0.25)
  75. [0.00, unk, 0.10, 0.9], # w2: 0.3
  76. ]),
  77. # step 2:
  78. torch.FloatTensor([
  79. # eos w1 w2 prefix
  80. # sentence 1:
  81. [0.0, unk, 0.1, 0.9], # w2 w1: 0.1*0.9
  82. [0.6, unk, 0.2, 0.2], # w2 w2: 0.1*0.1 (emit: w2 w2 <eos>: 0.1*0.1*0.6)
  83. # sentence 2:
  84. [0.60, unk, 0.4, 0.00], # w1 w2: 0.7*0.4 (emit: w1 w2 <eos>: 0.7*0.4*0.6)
  85. [0.01, unk, 0.0, 0.99], # w2 w2: 0.3*0.9
  86. ]),
  87. # step 3:
  88. torch.FloatTensor([
  89. # eos w1 w2 prefix
  90. # sentence 1:
  91. [1.0, unk, 0.0, 0.0], # w2 w1 w2: 0.1*0.9*0.9 (emit: w2 w1 w2 <eos>: 0.1*0.9*0.9*1.0)
  92. [1.0, unk, 0.0, 0.0], # w2 w1 w1: 0.1*0.9*0.1 (emit: w2 w1 w1 <eos>: 0.1*0.9*0.1*1.0)
  93. # sentence 2:
  94. [0.1, unk, 0.5, 0.4], # w2 w2 w2: 0.3*0.9*0.99 (emit: w2 w2 w2 <eos>: 0.3*0.9*0.99*0.1)
  95. [1.0, unk, 0.0, 0.0], # w1 w2 w1: 0.7*0.4*0.4 (emit: w1 w2 w1 <eos>: 0.7*0.4*0.4*1.0)
  96. ]),
  97. ]
  98. task = TestTranslationTask.setup_task(args, d, d)
  99. model = task.build_model(args)
  100. tgt_dict = task.target_dictionary
  101. return tgt_dict, w1, w2, src_tokens, src_lengths, model
  102. class TestDataset(torch.utils.data.Dataset):
  103. def __init__(self, data):
  104. super().__init__()
  105. self.data = data
  106. self.sizes = None
  107. def __getitem__(self, index):
  108. return self.data[index]
  109. def __len__(self):
  110. return len(self.data)
  111. class TestTranslationTask(FairseqTask):
  112. def __init__(self, args, src_dict, tgt_dict, model):
  113. super().__init__(args)
  114. self.src_dict = src_dict
  115. self.tgt_dict = tgt_dict
  116. self.model = model
  117. @classmethod
  118. def setup_task(cls, args, src_dict=None, tgt_dict=None, model=None):
  119. return cls(args, src_dict, tgt_dict, model)
  120. def build_model(self, args):
  121. return TestModel.build_model(args, self)
  122. @property
  123. def source_dictionary(self):
  124. return self.src_dict
  125. @property
  126. def target_dictionary(self):
  127. return self.tgt_dict
  128. class TestModel(FairseqModel):
  129. def __init__(self, encoder, decoder):
  130. super().__init__(encoder, decoder)
  131. @classmethod
  132. def build_model(cls, args, task):
  133. encoder = TestEncoder(args, task.source_dictionary)
  134. decoder = TestIncrementalDecoder(args, task.target_dictionary)
  135. return cls(encoder, decoder)
  136. class TestEncoder(FairseqEncoder):
  137. def __init__(self, args, dictionary):
  138. super().__init__(dictionary)
  139. self.args = args
  140. def forward(self, src_tokens, src_lengths):
  141. return src_tokens
  142. def reorder_encoder_out(self, encoder_out, new_order):
  143. return encoder_out.index_select(0, new_order)
  144. class TestIncrementalDecoder(FairseqIncrementalDecoder):
  145. def __init__(self, args, dictionary):
  146. super().__init__(dictionary)
  147. assert hasattr(args, 'beam_probs') or hasattr(args, 'probs')
  148. args.max_decoder_positions = getattr(args, 'max_decoder_positions', 100)
  149. self.args = args
  150. def forward(self, prev_output_tokens, encoder_out, incremental_state=None):
  151. if incremental_state is not None:
  152. prev_output_tokens = prev_output_tokens[:, -1:]
  153. bbsz = prev_output_tokens.size(0)
  154. vocab = len(self.dictionary)
  155. src_len = encoder_out.size(1)
  156. tgt_len = prev_output_tokens.size(1)
  157. # determine number of steps
  158. if incremental_state is not None:
  159. # cache step number
  160. step = utils.get_incremental_state(self, incremental_state, 'step')
  161. if step is None:
  162. step = 0
  163. utils.set_incremental_state(self, incremental_state, 'step', step + 1)
  164. steps = [step]
  165. else:
  166. steps = list(range(tgt_len))
  167. # define output in terms of raw probs
  168. if hasattr(self.args, 'probs'):
  169. assert self.args.probs.dim() == 3, \
  170. 'expected probs to have size bsz*steps*vocab'
  171. probs = self.args.probs.index_select(1, torch.LongTensor(steps))
  172. else:
  173. probs = torch.FloatTensor(bbsz, len(steps), vocab).zero_()
  174. for i, step in enumerate(steps):
  175. # args.beam_probs gives the probability for every vocab element,
  176. # starting with eos, then unknown, and then the rest of the vocab
  177. if step < len(self.args.beam_probs):
  178. probs[:, i, self.dictionary.eos():] = self.args.beam_probs[step]
  179. else:
  180. probs[:, i, self.dictionary.eos()] = 1.0
  181. # random attention
  182. attn = torch.rand(bbsz, tgt_len, src_len)
  183. dev = prev_output_tokens.device
  184. return probs.to(dev), attn.to(dev)
  185. def get_normalized_probs(self, net_output, log_probs, _):
  186. # the decoder returns probabilities directly
  187. probs = net_output[0]
  188. if log_probs:
  189. return probs.log()
  190. else:
  191. return probs
  192. def max_positions(self):
  193. return self.args.max_decoder_positions
Tip!

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

Comments

Loading...