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

backtranslation_dataset.py 6.5 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
  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 fairseq import utils
  9. from . import FairseqDataset
  10. def backtranslate_samples(samples, collate_fn, generate_fn, cuda=True):
  11. """Backtranslate a list of samples.
  12. Given an input (*samples*) of the form:
  13. [{'id': 1, 'source': 'hallo welt'}]
  14. this will return:
  15. [{'id': 1, 'source': 'hello world', 'target': 'hallo welt'}]
  16. Args:
  17. samples (List[dict]): samples to backtranslate. Individual samples are
  18. expected to have a 'source' key, which will become the 'target'
  19. after backtranslation.
  20. collate_fn (callable): function to collate samples into a mini-batch
  21. generate_fn (callable): function to generate backtranslations
  22. cuda (bool): use GPU for generation (default: ``True``)
  23. Returns:
  24. List[dict]: an updated list of samples with a backtranslated source
  25. """
  26. collated_samples = collate_fn(samples)
  27. s = utils.move_to_cuda(collated_samples) if cuda else collated_samples
  28. generated_sources = generate_fn(s['net_input'])
  29. def update_sample(sample, generated_source):
  30. sample['target'] = sample['source'] # the original source becomes the target
  31. sample['source'] = generated_source
  32. return sample
  33. # Go through each tgt sentence in batch and its corresponding best
  34. # generated hypothesis and create a backtranslation data pair
  35. # {id: id, source: generated backtranslation, target: original tgt}
  36. return [
  37. update_sample(
  38. sample=input_sample,
  39. generated_source=hypos[0]['tokens'].cpu(), # highest scoring hypo is first
  40. )
  41. for input_sample, hypos in zip(samples, generated_sources)
  42. ]
  43. class BacktranslationDataset(FairseqDataset):
  44. """
  45. Sets up a backtranslation dataset which takes a tgt batch, generates
  46. a src using a tgt-src backtranslation function (*backtranslation_fn*),
  47. and returns the corresponding `{generated src, input tgt}` batch.
  48. Args:
  49. tgt_dataset (~fairseq.data.FairseqDataset): the dataset to be
  50. backtranslated. Only the source side of this dataset will be used.
  51. After backtranslation, the source sentences in this dataset will be
  52. returned as the targets.
  53. backtranslation_fn (callable): function to call to generate
  54. backtranslations. This is typically the `generate` method of a
  55. :class:`~fairseq.sequence_generator.SequenceGenerator` object.
  56. max_len_a, max_len_b (int, int): will be used to compute
  57. `maxlen = max_len_a * src_len + max_len_b`, which will be passed
  58. into *backtranslation_fn*.
  59. output_collater (callable, optional): function to call on the
  60. backtranslated samples to create the final batch
  61. (default: ``tgt_dataset.collater``).
  62. cuda: use GPU for generation
  63. """
  64. def __init__(
  65. self,
  66. tgt_dataset,
  67. backtranslation_fn,
  68. max_len_a,
  69. max_len_b,
  70. output_collater=None,
  71. cuda=True,
  72. **kwargs
  73. ):
  74. self.tgt_dataset = tgt_dataset
  75. self.backtranslation_fn = backtranslation_fn
  76. self.max_len_a = max_len_a
  77. self.max_len_b = max_len_b
  78. self.output_collater = output_collater if output_collater is not None \
  79. else tgt_dataset.collater
  80. self.cuda = cuda if torch.cuda.is_available() else False
  81. def __getitem__(self, index):
  82. """
  83. Returns a single sample from *tgt_dataset*. Note that backtranslation is
  84. not applied in this step; use :func:`collater` instead to backtranslate
  85. a batch of samples.
  86. """
  87. return self.tgt_dataset[index]
  88. def __len__(self):
  89. return len(self.tgt_dataset)
  90. def collater(self, samples):
  91. """Merge and backtranslate a list of samples to form a mini-batch.
  92. Using the samples from *tgt_dataset*, load a collated target sample to
  93. feed to the backtranslation model. Then take the backtranslation with
  94. the best score as the source and the original input as the target.
  95. Note: we expect *tgt_dataset* to provide a function `collater()` that
  96. will collate samples into the format expected by *backtranslation_fn*.
  97. After backtranslation, we will feed the new list of samples (i.e., the
  98. `(backtranslated source, original source)` pairs) to *output_collater*
  99. and return the result.
  100. Args:
  101. samples (List[dict]): samples to backtranslate and collate
  102. Returns:
  103. dict: a mini-batch with keys coming from *output_collater*
  104. """
  105. samples = backtranslate_samples(
  106. samples=samples,
  107. collate_fn=self.tgt_dataset.collater,
  108. generate_fn=(
  109. lambda net_input: self.backtranslation_fn(
  110. net_input,
  111. maxlen=int(
  112. self.max_len_a * net_input['src_tokens'].size(1) + self.max_len_b
  113. ),
  114. )
  115. ),
  116. cuda=self.cuda,
  117. )
  118. return self.output_collater(samples)
  119. def get_dummy_batch(self, num_tokens, max_positions):
  120. """Just use the tgt dataset get_dummy_batch"""
  121. return self.tgt_dataset.get_dummy_batch(num_tokens, max_positions)
  122. def num_tokens(self, index):
  123. """Just use the tgt dataset num_tokens"""
  124. return self.tgt_dataset.num_tokens(index)
  125. def ordered_indices(self):
  126. """Just use the tgt dataset ordered_indices"""
  127. return self.tgt_dataset.ordered_indices()
  128. def valid_size(self, index, max_positions):
  129. """Just use the tgt dataset size"""
  130. return self.tgt_dataset.valid_size(index, max_positions)
  131. def size(self, index):
  132. """Return an example's size as a float or tuple. This value is used
  133. when filtering a dataset with ``--max-positions``.
  134. Note: we use *tgt_dataset* to approximate the length of the source
  135. sentence, since we do not know the actual length until after
  136. backtranslation.
  137. """
  138. tgt_size = self.tgt_dataset.size(index)[0]
  139. return (tgt_size, tgt_size)
  140. @property
  141. def supports_prefetch(self):
  142. return getattr(self.tgt_dataset, 'supports_prefetch', False)
  143. def prefetch(self, indices):
  144. return self.tgt_dataset.prefetch(indices)
Tip!

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

Comments

Loading...