transformer_util.py 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pickle
import warnings
from functools import partial
18

19 20 21
import numpy as np

import paddle
22
from paddle.dataset import wmt16
23 24


25
def get_input_descs(args, mode="train"):
26 27 28 29 30

    batch_size = args.batch_size  # TODO None(before)
    seq_len = None
    n_head = getattr(args, "n_head", 8)
    d_model = getattr(args, "d_model", 512)
31
    input_descs_train = {
32 33
        "src_word": [(batch_size, seq_len), "int64", 2],
        "src_pos": [(batch_size, seq_len), "int64"],
34 35 36 37
        "src_slf_attn_bias": [
            (batch_size, n_head, seq_len, seq_len),
            "float32",
        ],
38 39
        "trg_word": [(batch_size, seq_len), "int64", 2],
        "trg_pos": [(batch_size, seq_len), "int64"],
40 41 42 43 44 45 46 47
        "trg_slf_attn_bias": [
            (batch_size, n_head, seq_len, seq_len),
            "float32",
        ],
        "trg_src_attn_bias": [
            (batch_size, n_head, seq_len, seq_len),
            "float32",
        ],  # TODO: 1 for predict, seq_len for train
48 49 50 51
        "enc_output": [(batch_size, seq_len, d_model), "float32"],
        "lbl_word": [(None, 1), "int64"],
        "lbl_weight": [(None, 1), "float32"],
        "init_score": [(batch_size, 1), "float32", 2],
52
        "init_idx": [(batch_size,), "int32"],
53
    }
54 55 56
    input_descs_predict = {
        "src_word": [(batch_size, seq_len), "int64", 2],
        "src_pos": [(batch_size, seq_len), "int64"],
57 58 59 60
        "src_slf_attn_bias": [
            (batch_size, n_head, seq_len, seq_len),
            "float32",
        ],
61 62
        "trg_word": [(batch_size, seq_len), "int64", 2],
        "trg_pos": [(batch_size, seq_len), "int64"],
63 64 65 66
        "trg_slf_attn_bias": [
            (batch_size, n_head, seq_len, seq_len),
            "float32",
        ],
67 68 69 70 71
        "trg_src_attn_bias": [(batch_size, n_head, 1, seq_len), "float32"],
        "enc_output": [(batch_size, seq_len, d_model), "float32"],
        "lbl_word": [(None, 1), "int64"],
        "lbl_weight": [(None, 1), "float32"],
        "init_score": [(batch_size, 1), "float32", 2],
72
        "init_idx": [(batch_size,), "int32"],
73 74 75
    }

    return input_descs_train if mode == "train" else input_descs_predict
76 77 78 79 80


encoder_data_input_fields = (
    "src_word",
    "src_pos",
81 82
    "src_slf_attn_bias",
)
83 84 85 86 87
decoder_data_input_fields = (
    "trg_word",
    "trg_pos",
    "trg_slf_attn_bias",
    "trg_src_attn_bias",
88 89
    "enc_output",
)
90 91
label_data_input_fields = (
    "lbl_word",
92 93
    "lbl_weight",
)
94 95
fast_decoder_data_input_fields = (
    "trg_word",
96 97
    "trg_src_attn_bias",
)
98 99


100
class ModelHyperParams:
101
    print_step = 2
102 103
    save_dygraph_model_path = "dygraph_trained_models"
    save_static_model_path = "static_trained_models"
104 105 106 107 108 109 110 111 112 113 114
    inference_model_dir = "infer_model"
    output_file = "predict.txt"
    batch_size = 5
    epoch = 1
    learning_rate = 2.0
    beta1 = 0.9
    beta2 = 0.997
    eps = 1e-9
    warmup_steps = 8000
    label_smooth_eps = 0.1
    beam_size = 5
115
    max_out_len = 5  # small number to avoid the unittest timeout
116
    n_best = 1
117 118
    src_vocab_size = 36556
    trg_vocab_size = 36556
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    bos_idx = 0  # index for <bos> token
    eos_idx = 1  # index for <eos> token
    unk_idx = 2  # index for <unk> token
    max_length = 256
    d_model = 512
    d_inner_hid = 2048
    d_key = 64
    d_value = 64
    n_head = 8
    n_layer = 6
    prepostprocess_dropout = 0.1
    attention_dropout = 0.1
    relu_dropout = 0.1
    preprocess_cmd = "n"  # layer normalization
    postprocess_cmd = "da"  # dropout + residual connection
    weight_sharing = True


137 138 139 140 141 142 143 144 145 146
def pad_batch_data(
    insts,
    pad_idx,
    n_head,
    is_target=False,
    is_label=False,
    return_attn_bias=True,
    return_max_len=True,
    return_num_token=False,
):
147 148 149
    return_list = []
    max_len = max(len(inst) for inst in insts)
    inst_data = np.array(
150 151
        [inst + [pad_idx] * (max_len - len(inst)) for inst in insts]
    )
152 153
    return_list += [inst_data.astype("int64").reshape([-1, 1])]
    if is_label:  # label weight
154 155 156 157 158 159
        inst_weight = np.array(
            [
                [1.0] * len(inst) + [0.0] * (max_len - len(inst))
                for inst in insts
            ]
        )
160 161
        return_list += [inst_weight.astype("float32").reshape([-1, 1])]
    else:  # position data
162 163 164 165 166 167
        inst_pos = np.array(
            [
                list(range(0, len(inst))) + [0] * (max_len - len(inst))
                for inst in insts
            ]
        )
168 169 170 171
        return_list += [inst_pos.astype("int64").reshape([-1, 1])]
    if return_attn_bias:
        if is_target:
            slf_attn_bias_data = np.ones((inst_data.shape[0], max_len, max_len))
172 173 174 175 176 177
            slf_attn_bias_data = np.triu(slf_attn_bias_data, 1).reshape(
                [-1, 1, max_len, max_len]
            )
            slf_attn_bias_data = np.tile(
                slf_attn_bias_data, [1, n_head, 1, 1]
            ) * [-1e9]
178
        else:
179 180 181 182 183 184
            slf_attn_bias_data = np.array(
                [
                    [0] * len(inst) + [-1e9] * (max_len - len(inst))
                    for inst in insts
                ]
            )
185 186
            slf_attn_bias_data = np.tile(
                slf_attn_bias_data.reshape([-1, 1, 1, max_len]),
187 188
                [1, n_head, max_len, 1],
            )
189 190 191 192 193 194 195 196 197 198 199 200 201
        return_list += [slf_attn_bias_data.astype("float32")]
    if return_max_len:
        return_list += [max_len]
    if return_num_token:
        num_token = 0
        for inst in insts:
            num_token += len(inst)
        return_list += [num_token]
    return return_list if len(return_list) > 1 else return_list[0]


def prepare_train_input(insts, src_pad_idx, trg_pad_idx, n_head):
    src_word, src_pos, src_slf_attn_bias, src_max_len = pad_batch_data(
202 203
        [inst[0] for inst in insts], src_pad_idx, n_head, is_target=False
    )
204 205 206
    src_word = src_word.reshape(-1, src_max_len)
    src_pos = src_pos.reshape(-1, src_max_len)
    trg_word, trg_pos, trg_slf_attn_bias, trg_max_len = pad_batch_data(
207 208
        [inst[1] for inst in insts], trg_pad_idx, n_head, is_target=True
    )
209 210 211
    trg_word = trg_word.reshape(-1, trg_max_len)
    trg_pos = trg_pos.reshape(-1, trg_max_len)

212 213 214
    trg_src_attn_bias = np.tile(
        src_slf_attn_bias[:, :, ::src_max_len, :], [1, 1, trg_max_len, 1]
    ).astype("float32")
215 216 217 218 219 220 221 222 223

    lbl_word, lbl_weight, num_token = pad_batch_data(
        [inst[2] for inst in insts],
        trg_pad_idx,
        n_head,
        is_target=False,
        is_label=True,
        return_attn_bias=False,
        return_max_len=False,
224 225
        return_num_token=True,
    )
226 227 228 229
    lbl_word = lbl_word.reshape(-1, 1)
    lbl_weight = lbl_weight.reshape(-1, 1)

    data_inputs = [
230 231 232 233 234 235 236 237 238
        src_word,
        src_pos,
        src_slf_attn_bias,
        trg_word,
        trg_pos,
        trg_slf_attn_bias,
        trg_src_attn_bias,
        lbl_word,
        lbl_weight,
239 240 241 242 243 244 245
    ]

    return data_inputs


def prepare_infer_input(insts, src_pad_idx, bos_idx, n_head):
    src_word, src_pos, src_slf_attn_bias, src_max_len = pad_batch_data(
246 247
        [inst[0] for inst in insts], src_pad_idx, n_head, is_target=False
    )
248 249
    # start tokens
    trg_word = np.asarray([[bos_idx]] * len(insts), dtype="int64")
250 251 252
    trg_src_attn_bias = np.tile(
        src_slf_attn_bias[:, :, ::src_max_len, :], [1, 1, 1, 1]
    ).astype("float32")
253 254 255 256 257
    trg_word = trg_word.reshape(-1, 1)
    src_word = src_word.reshape(-1, src_max_len)
    src_pos = src_pos.reshape(-1, src_max_len)

    data_inputs = [
258 259 260 261 262
        src_word,
        src_pos,
        src_slf_attn_bias,
        trg_word,
        trg_src_attn_bias,
263 264 265 266 267 268
    ]
    return data_inputs


def get_feed_data_reader(args, mode='train'):
    def __for_train__():
269 270 271 272
        train_reader = paddle.batch(
            wmt16.train(args.src_vocab_size, args.trg_vocab_size),
            batch_size=args.batch_size,
        )
273
        for batch in train_reader():
274 275 276
            tensors = prepare_train_input(
                batch, args.eos_idx, args.eos_idx, args.n_head
            )
277 278 279
            yield tensors

    def __for_test__():
280 281 282 283
        test_reader = paddle.batch(
            wmt16.test(args.src_vocab_size, args.trg_vocab_size),
            batch_size=args.batch_size,
        )
284
        for batch in test_reader():
285 286 287
            tensors = prepare_infer_input(
                batch, args.eos_idx, args.eos_idx, args.n_head
            )
288 289 290 291 292
            yield tensors

    return __for_train__ if mode == 'train' else __for_test__


293
class InputField:
294 295 296 297
    def __init__(self, input_slots):
        self.feed_list = []
        for slot in input_slots:
            self.feed_list.append(
G
GGBond8488 已提交
298
                paddle.static.data(
299 300 301 302 303 304
                    name=slot['name'],
                    shape=slot['shape'],
                    dtype=slot['dtype'],
                    lod_level=slot.get('lod_level', 0),
                )
            )
305 306 307 308 309 310 311


def load(program, model_path, executor=None, var_list=None):
    """
    To load python2 saved models in python3.
    """
    try:
312
        paddle.static.load(program, model_path, executor, var_list)
313 314 315 316
    except UnicodeDecodeError:
        warnings.warn(
            "An UnicodeDecodeError is catched, which might be caused by loading "
            "a python2 saved model. Encoding of pickle.load would be set and "
317 318
            "load again automatically."
        )
319 320
        load_bak = pickle.load
        pickle.load = partial(load_bak, encoding="latin1")
321
        paddle.static.load(program, model_path, executor, var_list)
322
        pickle.load = load_bak
323 324 325 326 327 328 329


def load_dygraph(model_path, keep_name_table=False):
    """
    To load python2 saved models in python3.
    """
    try:
330 331 332 333 334
        para_dict = paddle.load(
            model_path + '.pdparams', keep_name_table=keep_name_table
        )
        opti_dict = paddle.load(
            model_path + '.pdopt', keep_name_table=keep_name_table
335
        )
336 337 338 339 340
        return para_dict, opti_dict
    except UnicodeDecodeError:
        warnings.warn(
            "An UnicodeDecodeError is catched, which might be caused by loading "
            "a python2 saved model. Encoding of pickle.load would be set and "
341 342
            "load again automatically."
        )
343 344
        load_bak = pickle.load
        pickle.load = partial(load_bak, encoding="latin1")
345 346 347 348 349
        para_dict = paddle.load(
            model_path + '.pdparams', keep_name_table=keep_name_table
        )
        opti_dict = paddle.load(
            model_path + '.pdopt', keep_name_table=keep_name_table
350
        )
351 352
        pickle.load = load_bak
        return para_dict, opti_dict