rerank_generate.py 12.9 KB
Newer Older
Nathan Ng's avatar
Nathan Ng committed
1
#!/usr/bin/env python3 -u
Myle Ott's avatar
Myle Ott committed
2
# Copyright (c) Facebook, Inc. and its affiliates.
Nathan Ng's avatar
Nathan Ng committed
3
#
Myle Ott's avatar
Myle Ott committed
4
5
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
Nathan Ng's avatar
Nathan Ng committed
6

Myle Ott's avatar
Myle Ott committed
7
8
9
10
11
"""
Generate n-best translations using a trained model.
"""

from contextlib import redirect_stdout
Nathan Ng's avatar
Nathan Ng committed
12
13
import os
import subprocess
Myle Ott's avatar
Myle Ott committed
14
15

import rerank_utils
Nathan Ng's avatar
Nathan Ng committed
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
from examples.noisychannel import rerank_options
from fairseq import options
import generate
import preprocess


def gen_and_reprocess_nbest(args):
    if args.score_dict_dir is None:
        args.score_dict_dir = args.data
    if args.prefix_len is not None:
        assert args.right_to_left1 is False, "prefix length not compatible with right to left models"
        assert args.right_to_left2 is False, "prefix length not compatible with right to left models"

    if args.nbest_list is not None:
        assert args.score_model2 is None

    if args.backwards1:
        scorer1_src = args.target_lang
        scorer1_tgt = args.source_lang
    else:
        scorer1_src = args.source_lang
        scorer1_tgt = args.target_lang

    store_data = os.path.join(os.path.dirname(__file__))+"/rerank_data/"+args.data_dir_name
    if not os.path.exists(store_data):
        os.makedirs(store_data)

    pre_gen, left_to_right_preprocessed_dir, right_to_left_preprocessed_dir, \
        backwards_preprocessed_dir, lm_preprocessed_dir = \
        rerank_utils.get_directories(args.data_dir_name, args.num_rescore, args.gen_subset,
                                     args.gen_model_name, args.shard_id, args.num_shards,
                                     args.sampling, args.prefix_len, args.target_prefix_frac,
                                     args.source_prefix_frac)
    assert not (args.right_to_left1 and args.backwards1), "backwards right to left not supported"
    assert not (args.right_to_left2 and args.backwards2), "backwards right to left not supported"
    assert not (args.prefix_len is not None and args.target_prefix_frac is not None), \
        "target prefix frac and target prefix len incompatible"

    # make directory to store generation results
    if not os.path.exists(pre_gen):
        os.makedirs(pre_gen)

    rerank1_is_gen = args.gen_model == args.score_model1 and args.source_prefix_frac is None
    rerank2_is_gen = args.gen_model == args.score_model2 and args.source_prefix_frac is None

    if args.nbest_list is not None:
        rerank2_is_gen = True

    # make directories to store preprossed nbest list for reranking
    if not os.path.exists(left_to_right_preprocessed_dir):
        os.makedirs(left_to_right_preprocessed_dir)
    if not os.path.exists(right_to_left_preprocessed_dir):
        os.makedirs(right_to_left_preprocessed_dir)
    if not os.path.exists(lm_preprocessed_dir):
        os.makedirs(lm_preprocessed_dir)
    if not os.path.exists(backwards_preprocessed_dir):
        os.makedirs(backwards_preprocessed_dir)

    score1_file = rerank_utils.rescore_file_name(pre_gen, args.prefix_len, args.model1_name,
                                                 target_prefix_frac=args.target_prefix_frac,
                                                 source_prefix_frac=args.source_prefix_frac,
                                                 backwards=args.backwards1)
    if args.score_model2 is not None:
        score2_file = rerank_utils.rescore_file_name(pre_gen, args.prefix_len, args.model2_name,
                                                     target_prefix_frac=args.target_prefix_frac,
                                                     source_prefix_frac=args.source_prefix_frac,
                                                     backwards=args.backwards2)

    predictions_bpe_file = pre_gen+"/generate_output_bpe.txt"

    using_nbest = args.nbest_list is not None

    if using_nbest:
        print("Using predefined n-best list from interactive.py")
        predictions_bpe_file = args.nbest_list

    else:
        if not os.path.isfile(predictions_bpe_file):
            print("STEP 1: generate predictions using the p(T|S) model with bpe")
            print(args.data)
            param1 = [args.data,
                      "--path", args.gen_model,
                      "--shard-id", str(args.shard_id),
                      "--num-shards", str(args.num_shards),
                      "--nbest", str(args.num_rescore),
                      "--batch-size", str(args.batch_size),
                      "--beam", str(args.num_rescore),
                      "--max-sentences", str(args.num_rescore),
                      "--gen-subset", args.gen_subset,
                      "--source-lang", args.source_lang,
                      "--target-lang", args.target_lang]
            if args.sampling:
                param1 += ["--sampling"]

            gen_parser = options.get_generation_parser()
            input_args = options.parse_args_and_arch(gen_parser, param1)

            print(input_args)
            with open(predictions_bpe_file, 'w') as f:
                with redirect_stdout(f):
                    generate.main(input_args)

    gen_output = rerank_utils.BitextOutputFromGen(predictions_bpe_file, bpe_symbol=args.remove_bpe,
                                                  nbest=using_nbest, prefix_len=args.prefix_len,
                                                  target_prefix_frac=args.target_prefix_frac)

    if args.diff_bpe:
        rerank_utils.write_reprocessed(gen_output.no_bpe_source, gen_output.no_bpe_hypo,
                                       gen_output.no_bpe_target, pre_gen+"/source_gen_bpe."+args.source_lang,
                                       pre_gen+"/target_gen_bpe."+args.target_lang,
                                       pre_gen+"/reference_gen_bpe."+args.target_lang)
        bitext_bpe = args.rescore_bpe_code
        bpe_src_param = ["-c", bitext_bpe,
                         "--input", pre_gen+"/source_gen_bpe."+args.source_lang,
                         "--output", pre_gen+"/rescore_data."+args.source_lang]
        bpe_tgt_param = ["-c", bitext_bpe,
                         "--input", pre_gen+"/target_gen_bpe."+args.target_lang,
                         "--output", pre_gen+"/rescore_data."+args.target_lang]

        subprocess.call(["python",
                         os.path.join(os.path.dirname(__file__),
                                      "subword-nmt/subword_nmt/apply_bpe.py")] + bpe_src_param,
                        shell=False)

        subprocess.call(["python",
                         os.path.join(os.path.dirname(__file__),
                                      "subword-nmt/subword_nmt/apply_bpe.py")] + bpe_tgt_param,
                        shell=False)

    if (not os.path.isfile(score1_file) and not rerank1_is_gen) or \
            (args.score_model2 is not None and not os.path.isfile(score2_file) and not rerank2_is_gen):
        print("STEP 2: process the output of generate.py so we have clean text files with the translations")

        rescore_file = "/rescore_data"
        if args.prefix_len is not None:
            prefix_len_rescore_file = rescore_file + "prefix"+str(args.prefix_len)
        if args.target_prefix_frac is not None:
            target_prefix_frac_rescore_file = rescore_file + "target_prefix_frac"+str(args.target_prefix_frac)
        if args.source_prefix_frac is not None:
            source_prefix_frac_rescore_file = rescore_file + "source_prefix_frac"+str(args.source_prefix_frac)

        if not args.right_to_left1 or not args.right_to_left2:
            if not args.diff_bpe:
                rerank_utils.write_reprocessed(gen_output.source, gen_output.hypo, gen_output.target,
                                               pre_gen+rescore_file+"."+args.source_lang,
                                               pre_gen+rescore_file+"."+args.target_lang,
                                               pre_gen+"/reference_file", bpe_symbol=args.remove_bpe)
                if args.prefix_len is not None:
                    bw_rescore_file = prefix_len_rescore_file
                    rerank_utils.write_reprocessed(gen_output.source, gen_output.hypo, gen_output.target,
                                                   pre_gen+prefix_len_rescore_file+"."+args.source_lang,
                                                   pre_gen+prefix_len_rescore_file+"."+args.target_lang,
                                                   pre_gen+"/reference_file", prefix_len=args.prefix_len,
                                                   bpe_symbol=args.remove_bpe)
                elif args.target_prefix_frac is not None:
                    bw_rescore_file = target_prefix_frac_rescore_file
                    rerank_utils.write_reprocessed(gen_output.source, gen_output.hypo, gen_output.target,
                                                   pre_gen+target_prefix_frac_rescore_file+"."+args.source_lang,
                                                   pre_gen+target_prefix_frac_rescore_file+"."+args.target_lang,
                                                   pre_gen+"/reference_file", bpe_symbol=args.remove_bpe,
                                                   target_prefix_frac=args.target_prefix_frac)
                else:
                    bw_rescore_file = rescore_file

                if args.source_prefix_frac is not None:
                    fw_rescore_file = source_prefix_frac_rescore_file
                    rerank_utils.write_reprocessed(gen_output.source, gen_output.hypo, gen_output.target,
                                                   pre_gen+source_prefix_frac_rescore_file+"."+args.source_lang,
                                                   pre_gen+source_prefix_frac_rescore_file+"."+args.target_lang,
                                                   pre_gen+"/reference_file", bpe_symbol=args.remove_bpe,
                                                   source_prefix_frac=args.source_prefix_frac)
                else:
                    fw_rescore_file = rescore_file

        if args.right_to_left1 or args.right_to_left2:
            rerank_utils.write_reprocessed(gen_output.source, gen_output.hypo, gen_output.target,
                                           pre_gen+"/right_to_left_rescore_data."+args.source_lang,
                                           pre_gen+"/right_to_left_rescore_data."+args.target_lang,
                                           pre_gen+"/right_to_left_reference_file",
                                           right_to_left=True, bpe_symbol=args.remove_bpe)

        print("STEP 3: binarize the translations")
        if not args.right_to_left1 or args.score_model2 is not None and not args.right_to_left2 or not rerank1_is_gen:

            if args.backwards1 or args.backwards2:
                if args.backwards_score_dict_dir is not None:
                    bw_dict = args.backwards_score_dict_dir
                else:
                    bw_dict = args.score_dict_dir
                bw_preprocess_param = ["--source-lang", scorer1_src,
                                       "--target-lang", scorer1_tgt,
                                       "--trainpref", pre_gen+bw_rescore_file,
                                       "--srcdict", bw_dict + "/dict." + scorer1_src + ".txt",
                                       "--tgtdict", bw_dict + "/dict." + scorer1_tgt + ".txt",
                                       "--destdir", backwards_preprocessed_dir]
                preprocess_parser = options.get_preprocessing_parser()
                input_args = preprocess_parser.parse_args(bw_preprocess_param)
                preprocess.main(input_args)

            preprocess_param = ["--source-lang", scorer1_src,
                                "--target-lang", scorer1_tgt,
                                "--trainpref", pre_gen+fw_rescore_file,
                                "--srcdict", args.score_dict_dir+"/dict."+scorer1_src+".txt",
                                "--tgtdict", args.score_dict_dir+"/dict."+scorer1_tgt+".txt",
                                "--destdir", left_to_right_preprocessed_dir]
            preprocess_parser = options.get_preprocessing_parser()
            input_args = preprocess_parser.parse_args(preprocess_param)
            preprocess.main(input_args)

        if args.right_to_left1 or args.right_to_left2:
            preprocess_param = ["--source-lang", scorer1_src,
                                "--target-lang", scorer1_tgt,
                                "--trainpref", pre_gen+"/right_to_left_rescore_data",
                                "--srcdict", args.score_dict_dir+"/dict."+scorer1_src+".txt",
                                "--tgtdict", args.score_dict_dir+"/dict."+scorer1_tgt+".txt",
                                "--destdir", right_to_left_preprocessed_dir]
            preprocess_parser = options.get_preprocessing_parser()
            input_args = preprocess_parser.parse_args(preprocess_param)
            preprocess.main(input_args)

    return gen_output


def cli_main():
    parser = rerank_options.get_reranking_parser()
    args = options.parse_args_and_arch(parser)
    gen_and_reprocess_nbest(args)


if __name__ == '__main__':
    cli_main()