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

composite_encoder.py 1.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
  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 . import FairseqEncoder
  8. class CompositeEncoder(FairseqEncoder):
  9. """
  10. A wrapper around a dictionary of :class:`FairseqEncoder` objects.
  11. We run forward on each encoder and return a dictionary of outputs. The first
  12. encoder's dictionary is used for initialization.
  13. Args:
  14. encoders (dict): a dictionary of :class:`FairseqEncoder` objects.
  15. """
  16. def __init__(self, encoders):
  17. super().__init__(next(iter(encoders.values())).dictionary)
  18. self.encoders = encoders
  19. for key in self.encoders:
  20. self.add_module(key, self.encoders[key])
  21. def forward(self, src_tokens, src_lengths):
  22. """
  23. Args:
  24. src_tokens (LongTensor): tokens in the source language of shape
  25. `(batch, src_len)`
  26. src_lengths (LongTensor): lengths of each source sentence of shape
  27. `(batch)`
  28. Returns:
  29. dict:
  30. the outputs from each Encoder
  31. """
  32. encoder_out = {}
  33. for key in self.encoders:
  34. encoder_out[key] = self.encoders[key](src_tokens, src_lengths)
  35. return encoder_out
  36. def reorder_encoder_out(self, encoder_out, new_order):
  37. """Reorder encoder output according to new_order."""
  38. for key in self.encoders:
  39. encoder_out[key] = self.encoders[key].reorder_encoder_out(encoder_out[key], new_order)
  40. return encoder_out
  41. def max_positions(self):
  42. return min([self.encoders[key].max_positions() for key in self.encoders])
  43. def upgrade_state_dict(self, state_dict):
  44. for key in self.encoders:
  45. self.encoders[key].upgrade_state_dict(state_dict)
  46. return state_dict
Tip!

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

Comments

Loading...