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 4.4 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
  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 torch
  8. from torch.autograd import Variable
  9. from fairseq import data, dictionary, utils
  10. from fairseq.models import (
  11. FairseqEncoder,
  12. FairseqIncrementalDecoder,
  13. FairseqModel,
  14. )
  15. def dummy_dictionary(vocab_size, prefix='token_'):
  16. d = dictionary.Dictionary()
  17. for i in range(vocab_size):
  18. token = prefix + str(i)
  19. d.add_symbol(token)
  20. d.finalize(padding_factor=1) # don't add extra padding symbols
  21. return d
  22. def dummy_dataloader(
  23. samples,
  24. padding_idx=1,
  25. eos_idx=2,
  26. batch_size=None,
  27. ):
  28. if batch_size is None:
  29. batch_size = len(samples)
  30. # add any missing data to samples
  31. for i, sample in enumerate(samples):
  32. if 'id' not in sample:
  33. sample['id'] = i
  34. # create dataloader
  35. dataset = TestDataset(samples)
  36. dataloader = torch.utils.data.DataLoader(
  37. dataset,
  38. batch_size=batch_size,
  39. collate_fn=(
  40. lambda samples: data.LanguagePairDataset.collate(
  41. samples,
  42. padding_idx,
  43. eos_idx,
  44. )
  45. ),
  46. )
  47. return iter(dataloader)
  48. class TestDataset(torch.utils.data.Dataset):
  49. def __init__(self, data):
  50. super().__init__()
  51. self.data = data
  52. def __getitem__(self, index):
  53. return self.data[index]
  54. def __len__(self):
  55. return len(self.data)
  56. class TestModel(FairseqModel):
  57. def __init__(self, encoder, decoder):
  58. super().__init__(encoder, decoder)
  59. @classmethod
  60. def build_model(cls, args, src_dict, dst_dict):
  61. encoder = TestEncoder(args, src_dict)
  62. decoder = TestIncrementalDecoder(args, dst_dict)
  63. return cls(encoder, decoder)
  64. class TestEncoder(FairseqEncoder):
  65. def __init__(self, args, dictionary):
  66. super().__init__(dictionary)
  67. self.args = args
  68. def forward(self, src_tokens, src_lengths):
  69. return src_tokens
  70. class TestIncrementalDecoder(FairseqIncrementalDecoder):
  71. def __init__(self, args, dictionary):
  72. super().__init__(dictionary)
  73. assert hasattr(args, 'beam_probs') or hasattr(args, 'probs')
  74. args.max_decoder_positions = getattr(args, 'max_decoder_positions', 100)
  75. self.args = args
  76. def forward(self, prev_output_tokens, encoder_out, incremental_state=None):
  77. if incremental_state is not None:
  78. prev_output_tokens = prev_output_tokens[:, -1:]
  79. bbsz = prev_output_tokens.size(0)
  80. vocab = len(self.dictionary)
  81. src_len = encoder_out.size(1)
  82. tgt_len = prev_output_tokens.size(1)
  83. # determine number of steps
  84. if incremental_state is not None:
  85. # cache step number
  86. step = utils.get_incremental_state(self, incremental_state, 'step')
  87. if step is None:
  88. step = 0
  89. utils.set_incremental_state(self, incremental_state, 'step', step + 1)
  90. steps = [step]
  91. else:
  92. steps = list(range(tgt_len))
  93. # define output in terms of raw probs
  94. if hasattr(self.args, 'probs'):
  95. assert self.args.probs.dim() == 3, \
  96. 'expected probs to have size bsz*steps*vocab'
  97. probs = self.args.probs.index_select(1, torch.LongTensor(steps))
  98. else:
  99. probs = torch.FloatTensor(bbsz, len(steps), vocab).zero_()
  100. for i, step in enumerate(steps):
  101. # args.beam_probs gives the probability for every vocab element,
  102. # starting with eos, then unknown, and then the rest of the vocab
  103. if step < len(self.args.beam_probs):
  104. probs[:, i, self.dictionary.eos():] = self.args.beam_probs[step]
  105. else:
  106. probs[:, i, self.dictionary.eos()] = 1.0
  107. # random attention
  108. attn = torch.rand(bbsz, src_len, tgt_len)
  109. return Variable(probs), Variable(attn)
  110. def get_normalized_probs(self, net_output, log_probs):
  111. # the decoder returns probabilities directly
  112. probs = net_output[0]
  113. if log_probs:
  114. return probs.log()
  115. else:
  116. return probs
  117. def max_positions(self):
  118. 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...