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

fairseq_model.py 10 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
  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. from typing import Dict, List, Optional
  8. import torch
  9. import torch.nn as nn
  10. import torch.nn.functional as F
  11. from . import FairseqDecoder, FairseqEncoder
  12. from fairseq.data import Dictionary
  13. class BaseFairseqModel(nn.Module):
  14. """Base class for fairseq models."""
  15. def __init__(self):
  16. super().__init__()
  17. self._is_generation_fast = False
  18. @staticmethod
  19. def add_args(parser):
  20. """Add model-specific arguments to the parser."""
  21. pass
  22. @classmethod
  23. def build_model(cls, args, task):
  24. """Build a new model instance."""
  25. raise NotImplementedError('FairseqModels must implement the build_model method')
  26. def get_targets(self, sample, net_output):
  27. """Get targets from either the sample or the net's output."""
  28. return sample['target']
  29. def get_normalized_probs(self, net_output, log_probs, sample=None):
  30. """Get normalized probabilities (or log probs) from a net's output."""
  31. if hasattr(self, 'decoder'):
  32. return self.decoder.get_normalized_probs(net_output, log_probs, sample)
  33. elif torch.is_tensor(net_output):
  34. logits = net_output.float()
  35. if log_probs:
  36. return F.log_softmax(logits, dim=-1)
  37. else:
  38. return F.softmax(logits, dim=-1)
  39. raise NotImplementedError
  40. def max_positions(self):
  41. """Maximum length supported by the model."""
  42. return None
  43. def max_decoder_positions(self):
  44. """Maximum length supported by the decoder."""
  45. return self.decoder.max_positions()
  46. def load_state_dict(self, state_dict, strict=True):
  47. """Copies parameters and buffers from *state_dict* into this module and
  48. its descendants.
  49. Overrides the method in :class:`nn.Module`. Compared with that method
  50. this additionally "upgrades" *state_dicts* from old checkpoints.
  51. """
  52. self.upgrade_state_dict(state_dict)
  53. super().load_state_dict(state_dict, strict)
  54. def upgrade_state_dict(self, state_dict):
  55. """Upgrade old state dicts to work with newer code."""
  56. self.upgrade_state_dict_named(state_dict, '')
  57. def upgrade_state_dict_named(self, state_dict, name):
  58. """Upgrade old state dicts to work with newer code.
  59. Args:
  60. state_dict (dict): state dictionary to upgrade, in place
  61. name (str): the state dict key corresponding to the current module
  62. """
  63. assert state_dict is not None
  64. def do_upgrade(m, prefix):
  65. if len(prefix) > 0:
  66. prefix += '.'
  67. for n, c in m.named_children():
  68. name = prefix + n
  69. if hasattr(c, 'upgrade_state_dict_named'):
  70. c.upgrade_state_dict_named(state_dict, name)
  71. elif hasattr(c, 'upgrade_state_dict'):
  72. c.upgrade_state_dict(state_dict)
  73. do_upgrade(c, name)
  74. do_upgrade(self, name)
  75. def make_generation_fast_(self, **kwargs):
  76. """Optimize model for faster generation."""
  77. if self._is_generation_fast:
  78. return # only apply once
  79. self._is_generation_fast = True
  80. # remove weight norm from all modules in the network
  81. def apply_remove_weight_norm(module):
  82. try:
  83. nn.utils.remove_weight_norm(module)
  84. except ValueError: # this module didn't have weight norm
  85. return
  86. self.apply(apply_remove_weight_norm)
  87. seen = set()
  88. def apply_make_generation_fast_(module):
  89. if module != self and hasattr(module, 'make_generation_fast_') \
  90. and module not in seen:
  91. seen.add(module)
  92. module.make_generation_fast_(**kwargs)
  93. self.apply(apply_make_generation_fast_)
  94. def train(mode=True):
  95. if mode:
  96. raise RuntimeError('cannot train after make_generation_fast')
  97. # this model should no longer be used for training
  98. self.eval()
  99. self.train = train
  100. def prepare_for_onnx_export_(self, **kwargs):
  101. """Make model exportable via ONNX trace."""
  102. seen = set()
  103. def apply_prepare_for_onnx_export_(module):
  104. if module != self and hasattr(module, 'prepare_for_onnx_export_') \
  105. and module not in seen:
  106. seen.add(module)
  107. module.prepare_for_onnx_export_(**kwargs)
  108. self.apply(apply_prepare_for_onnx_export_)
  109. class FairseqModel(BaseFairseqModel):
  110. """Base class for encoder-decoder models.
  111. Args:
  112. encoder (FairseqEncoder): the encoder
  113. decoder (FairseqDecoder): the decoder
  114. """
  115. def __init__(self, encoder, decoder):
  116. super().__init__()
  117. self.encoder = encoder
  118. self.decoder = decoder
  119. assert isinstance(self.encoder, FairseqEncoder)
  120. assert isinstance(self.decoder, FairseqDecoder)
  121. def forward(self, src_tokens, src_lengths, prev_output_tokens):
  122. """
  123. Run the forward pass for an encoder-decoder model.
  124. First feed a batch of source tokens through the encoder. Then, feed the
  125. encoder output and previous decoder outputs (i.e., input feeding/teacher
  126. forcing) to the decoder to produce the next outputs::
  127. encoder_out = self.encoder(src_tokens, src_lengths)
  128. return self.decoder(prev_output_tokens, encoder_out)
  129. Args:
  130. src_tokens (LongTensor): tokens in the source language of shape
  131. `(batch, src_len)`
  132. src_lengths (LongTensor): source sentence lengths of shape `(batch)`
  133. prev_output_tokens (LongTensor): previous decoder outputs of shape
  134. `(batch, tgt_len)`, for input feeding/teacher forcing
  135. Returns:
  136. the decoder's output, typically of shape `(batch, tgt_len, vocab)`
  137. """
  138. encoder_out = self.encoder(src_tokens, src_lengths)
  139. decoder_out = self.decoder(prev_output_tokens, encoder_out)
  140. return decoder_out
  141. def max_positions(self):
  142. """Maximum length supported by the model."""
  143. return (self.encoder.max_positions(), self.decoder.max_positions())
  144. class FairseqMultiModel(BaseFairseqModel):
  145. """Base class for combining multiple encoder-decoder models."""
  146. def __init__(self, encoders, decoders):
  147. super().__init__()
  148. assert encoders.keys() == decoders.keys()
  149. self.keys = list(encoders.keys())
  150. for key in self.keys:
  151. assert isinstance(encoders[key], FairseqEncoder)
  152. assert isinstance(decoders[key], FairseqDecoder)
  153. self.models = nn.ModuleDict({
  154. key: FairseqModel(encoders[key], decoders[key])
  155. for key in self.keys
  156. })
  157. @staticmethod
  158. def build_shared_embeddings(
  159. dicts: Dict[str, Dictionary],
  160. langs: List[str],
  161. embed_dim: int,
  162. build_embedding: callable,
  163. pretrained_embed_path: Optional[str] = None,
  164. ):
  165. """
  166. Helper function to build shared embeddings for a set of languages after
  167. checking that all dicts corresponding to those languages are equivalent.
  168. Args:
  169. dicts: Dict of lang_id to its corresponding Dictionary
  170. langs: languages that we want to share embeddings for
  171. embed_dim: embedding dimension
  172. build_embedding: callable function to actually build the embedding
  173. pretrained_embed_path: Optional path to load pretrained embeddings
  174. """
  175. shared_dict = dicts[langs[0]]
  176. if any(dicts[lang] != shared_dict for lang in langs):
  177. raise ValueError(
  178. '--share-*-embeddings requires a joined dictionary: '
  179. '--share-encoder-embeddings requires a joined source '
  180. 'dictionary, --share-decoder-embeddings requires a joined '
  181. 'target dictionary, and --share-all-embeddings requires a '
  182. 'joint source + target dictionary.'
  183. )
  184. return build_embedding(
  185. shared_dict, embed_dim, pretrained_embed_path
  186. )
  187. def forward(self, src_tokens, src_lengths, prev_output_tokens):
  188. decoder_outs = {}
  189. for key in self.keys:
  190. encoder_out = self.models[key].encoder(src_tokens, src_lengths)
  191. decoder_outs[key] = self.models[key].decoder(prev_output_tokens, encoder_out)
  192. return decoder_outs
  193. def max_positions(self):
  194. """Maximum length supported by the model."""
  195. return {
  196. key: (self.models[key].encoder.max_positions(), self.models[key].decoder.max_positions())
  197. for key in self.keys
  198. }
  199. def max_decoder_positions(self):
  200. """Maximum length supported by the decoder."""
  201. return min(model.decoder.max_positions() for model in self.models.values())
  202. @property
  203. def encoder(self):
  204. return self.models[self.keys[0]].encoder
  205. @property
  206. def decoder(self):
  207. return self.models[self.keys[0]].decoder
  208. class FairseqLanguageModel(BaseFairseqModel):
  209. """Base class for decoder-only models.
  210. Args:
  211. decoder (FairseqDecoder): the decoder
  212. """
  213. def __init__(self, decoder):
  214. super().__init__()
  215. self.decoder = decoder
  216. assert isinstance(self.decoder, FairseqDecoder)
  217. def forward(self, src_tokens, src_lengths):
  218. """
  219. Run the forward pass for a decoder-only model.
  220. Feeds a batch of tokens through the decoder to predict the next tokens.
  221. Args:
  222. src_tokens (LongTensor): tokens on which to condition the decoder,
  223. of shape `(batch, tgt_len)`
  224. src_lengths (LongTensor): source sentence lengths of shape `(batch)`
  225. Returns:
  226. the decoder's output, typically of shape `(batch, seq_len, vocab)`
  227. """
  228. return self.decoder(src_tokens)
  229. def max_positions(self):
  230. """Maximum length supported by the model."""
  231. return self.decoder.max_positions()
  232. @property
  233. def supported_targets(self):
  234. return {'future'}
  235. def remove_head(self):
  236. """Removes the head of the model (e.g. the softmax layer) to conserve space when it is not needed"""
  237. raise NotImplementedError()
Tip!

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

Comments

Loading...