utils.py 7.27 KB
Newer Older
1
# Copyright (c) Facebook, Inc. and its affiliates.
Myle Ott's avatar
Myle Ott committed
2
#
3
4
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
Myle Ott's avatar
Myle Ott committed
5

Myle Ott's avatar
Myle Ott committed
6
import argparse
Myle Ott's avatar
Myle Ott committed
7
8
import torch

alexeib's avatar
alexeib committed
9
from fairseq import utils
Myle Ott's avatar
Myle Ott committed
10
11
from fairseq.data import Dictionary
from fairseq.data.language_pair_dataset import collate
Myle Ott's avatar
Myle Ott committed
12
13
from fairseq.models import (
    FairseqEncoder,
Myle Ott's avatar
Myle Ott committed
14
    FairseqEncoderDecoderModel,
Myle Ott's avatar
Myle Ott committed
15
16
    FairseqIncrementalDecoder,
)
Myle Ott's avatar
Myle Ott committed
17
from fairseq.tasks import FairseqTask
Myle Ott's avatar
Myle Ott committed
18
19
20


def dummy_dictionary(vocab_size, prefix='token_'):
Myle Ott's avatar
Myle Ott committed
21
    d = Dictionary()
Myle Ott's avatar
Myle Ott committed
22
23
24
    for i in range(vocab_size):
        token = prefix + str(i)
        d.add_symbol(token)
Myle Ott's avatar
Myle Ott committed
25
    d.finalize(padding_factor=1)  # don't add extra padding symbols
Myle Ott's avatar
Myle Ott committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    return d


def dummy_dataloader(
    samples,
    padding_idx=1,
    eos_idx=2,
    batch_size=None,
):
    if batch_size is None:
        batch_size = len(samples)

    # add any missing data to samples
    for i, sample in enumerate(samples):
        if 'id' not in sample:
            sample['id'] = i

    # create dataloader
    dataset = TestDataset(samples)
    dataloader = torch.utils.data.DataLoader(
        dataset,
        batch_size=batch_size,
Myle Ott's avatar
Myle Ott committed
48
        collate_fn=(lambda samples: collate(samples, padding_idx, eos_idx)),
Myle Ott's avatar
Myle Ott committed
49
50
51
52
    )
    return iter(dataloader)


Myle Ott's avatar
Myle Ott committed
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
def sequence_generator_setup():
    # construct dummy dictionary
    d = dummy_dictionary(vocab_size=2)

    eos = d.eos()
    w1 = 4
    w2 = 5

    # construct source data
    src_tokens = torch.LongTensor([[w1, w2, eos], [w1, w2, eos]])
    src_lengths = torch.LongTensor([2, 2])

    args = argparse.Namespace()
    unk = 0.
    args.beam_probs = [
        # step 0:
        torch.FloatTensor([
            # eos      w1   w2
            # sentence 1:
            [0.0, unk, 0.9, 0.1],  # beam 1
            [0.0, unk, 0.9, 0.1],  # beam 2
            # sentence 2:
            [0.0, unk, 0.7, 0.3],
            [0.0, unk, 0.7, 0.3],
        ]),
        # step 1:
        torch.FloatTensor([
            # eos      w1   w2       prefix
            # sentence 1:
            [1.0, unk, 0.0, 0.0],  # w1: 0.9  (emit: w1 <eos>: 0.9*1.0)
            [0.0, unk, 0.9, 0.1],  # w2: 0.1
            # sentence 2:
            [0.25, unk, 0.35, 0.4],  # w1: 0.7  (don't emit: w1 <eos>: 0.7*0.25)
            [0.00, unk, 0.10, 0.9],  # w2: 0.3
        ]),
        # step 2:
        torch.FloatTensor([
            # eos      w1   w2       prefix
            # sentence 1:
            [0.0, unk, 0.1, 0.9],  # w2 w1: 0.1*0.9
            [0.6, unk, 0.2, 0.2],  # w2 w2: 0.1*0.1  (emit: w2 w2 <eos>: 0.1*0.1*0.6)
            # sentence 2:
            [0.60, unk, 0.4, 0.00],  # w1 w2: 0.7*0.4  (emit: w1 w2 <eos>: 0.7*0.4*0.6)
            [0.01, unk, 0.0, 0.99],  # w2 w2: 0.3*0.9
        ]),
        # step 3:
        torch.FloatTensor([
            # eos      w1   w2       prefix
            # sentence 1:
            [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)
            [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)
            # sentence 2:
            [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)
            [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)
        ]),
    ]

    task = TestTranslationTask.setup_task(args, d, d)
    model = task.build_model(args)
    tgt_dict = task.target_dictionary

    return tgt_dict, w1, w2, src_tokens, src_lengths, model


Myle Ott's avatar
Myle Ott committed
117
118
119
120
121
class TestDataset(torch.utils.data.Dataset):

    def __init__(self, data):
        super().__init__()
        self.data = data
122
        self.sizes = None
Myle Ott's avatar
Myle Ott committed
123
124
125
126
127
128
129
130

    def __getitem__(self, index):
        return self.data[index]

    def __len__(self):
        return len(self.data)


Myle Ott's avatar
Myle Ott committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
class TestTranslationTask(FairseqTask):

    def __init__(self, args, src_dict, tgt_dict, model):
        super().__init__(args)
        self.src_dict = src_dict
        self.tgt_dict = tgt_dict
        self.model = model

    @classmethod
    def setup_task(cls, args, src_dict=None, tgt_dict=None, model=None):
        return cls(args, src_dict, tgt_dict, model)

    def build_model(self, args):
        return TestModel.build_model(args, self)

    @property
    def source_dictionary(self):
        return self.src_dict

    @property
    def target_dictionary(self):
        return self.tgt_dict


Myle Ott's avatar
Myle Ott committed
155
class TestModel(FairseqEncoderDecoderModel):
Myle Ott's avatar
Myle Ott committed
156
157
158
159
    def __init__(self, encoder, decoder):
        super().__init__(encoder, decoder)

    @classmethod
Myle Ott's avatar
Myle Ott committed
160
161
162
    def build_model(cls, args, task):
        encoder = TestEncoder(args, task.source_dictionary)
        decoder = TestIncrementalDecoder(args, task.target_dictionary)
Myle Ott's avatar
Myle Ott committed
163
164
165
166
167
168
169
170
        return cls(encoder, decoder)


class TestEncoder(FairseqEncoder):
    def __init__(self, args, dictionary):
        super().__init__(dictionary)
        self.args = args

Myle Ott's avatar
Myle Ott committed
171
    def forward(self, src_tokens, src_lengths=None, **kwargs):
Myle Ott's avatar
Myle Ott committed
172
173
        return src_tokens

174
175
176
    def reorder_encoder_out(self, encoder_out, new_order):
        return encoder_out.index_select(0, new_order)

Myle Ott's avatar
Myle Ott committed
177
178
179
180

class TestIncrementalDecoder(FairseqIncrementalDecoder):
    def __init__(self, args, dictionary):
        super().__init__(dictionary)
181
        assert hasattr(args, 'beam_probs') or hasattr(args, 'probs')
Myle Ott's avatar
Myle Ott committed
182
183
184
        args.max_decoder_positions = getattr(args, 'max_decoder_positions', 100)
        self.args = args

Myle Ott's avatar
Myle Ott committed
185
    def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None):
186
        if incremental_state is not None:
Myle Ott's avatar
Myle Ott committed
187
188
189
190
191
192
193
            prev_output_tokens = prev_output_tokens[:, -1:]
        bbsz = prev_output_tokens.size(0)
        vocab = len(self.dictionary)
        src_len = encoder_out.size(1)
        tgt_len = prev_output_tokens.size(1)

        # determine number of steps
194
        if incremental_state is not None:
Myle Ott's avatar
Myle Ott committed
195
            # cache step number
196
            step = utils.get_incremental_state(self, incremental_state, 'step')
Myle Ott's avatar
Myle Ott committed
197
198
            if step is None:
                step = 0
199
            utils.set_incremental_state(self, incremental_state, 'step', step + 1)
Myle Ott's avatar
Myle Ott committed
200
201
202
203
204
            steps = [step]
        else:
            steps = list(range(tgt_len))

        # define output in terms of raw probs
205
206
207
208
209
210
211
212
213
214
215
216
217
        if hasattr(self.args, 'probs'):
            assert self.args.probs.dim() == 3, \
                'expected probs to have size bsz*steps*vocab'
            probs = self.args.probs.index_select(1, torch.LongTensor(steps))
        else:
            probs = torch.FloatTensor(bbsz, len(steps), vocab).zero_()
            for i, step in enumerate(steps):
                # args.beam_probs gives the probability for every vocab element,
                # starting with eos, then unknown, and then the rest of the vocab
                if step < len(self.args.beam_probs):
                    probs[:, i, self.dictionary.eos():] = self.args.beam_probs[step]
                else:
                    probs[:, i, self.dictionary.eos()] = 1.0
Myle Ott's avatar
Myle Ott committed
218
219

        # random attention
220
        attn = torch.rand(bbsz, tgt_len, src_len)
Myle Ott's avatar
Myle Ott committed
221

222
223
        dev = prev_output_tokens.device
        return probs.to(dev), attn.to(dev)
Myle Ott's avatar
Myle Ott committed
224

alexeib's avatar
alexeib committed
225
    def get_normalized_probs(self, net_output, log_probs, _):
Myle Ott's avatar
Myle Ott committed
226
        # the decoder returns probabilities directly
Myle Ott's avatar
Myle Ott committed
227
        probs = net_output[0]
Myle Ott's avatar
Myle Ott committed
228
        if log_probs:
Myle Ott's avatar
Myle Ott committed
229
            return probs.log()
Myle Ott's avatar
Myle Ott committed
230
        else:
Myle Ott's avatar
Myle Ott committed
231
            return probs
Myle Ott's avatar
Myle Ott committed
232
233
234

    def max_positions(self):
        return self.args.max_decoder_positions