|
| 1 | +# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import numpy as np |
| 16 | +import argparse |
| 17 | +import time |
| 18 | +import math |
| 19 | + |
| 20 | +import paddle |
| 21 | +import paddle.fluid as fluid |
| 22 | +from paddle.fluid import core |
| 23 | +import os |
| 24 | +import sys |
| 25 | +import transformer_model |
| 26 | +import paddle.dataset.wmt16 as wmt16 |
| 27 | + |
| 28 | +# Fix seed for test |
| 29 | +fluid.default_startup_program().random_seed = 1 |
| 30 | +fluid.default_main_program().random_seed = 1 |
| 31 | + |
| 32 | +WMT16_RECORDIO_FILE = "/tmp/wmt16.recordio" |
| 33 | + |
| 34 | + |
| 35 | +class ModelHyperParams(object): |
| 36 | + # Dictionary size for source and target language. This model directly uses |
| 37 | + # paddle.dataset.wmt16 in which <bos>, <eos> and <unk> token has |
| 38 | + # alreay been added, but the <pad> token is not added. Transformer requires |
| 39 | + # sequences in a mini-batch are padded to have the same length. A <pad> token is |
| 40 | + # added into the original dictionary in paddle.dateset.wmt16. |
| 41 | + |
| 42 | + # size of source word dictionary. |
| 43 | + src_vocab_size = 10000 |
| 44 | + # index for <pad> token in source language. |
| 45 | + src_pad_idx = src_vocab_size |
| 46 | + |
| 47 | + # size of target word dictionay |
| 48 | + trg_vocab_size = 10000 |
| 49 | + # index for <pad> token in target language. |
| 50 | + trg_pad_idx = trg_vocab_size |
| 51 | + |
| 52 | + # position value corresponding to the <pad> token. |
| 53 | + pos_pad_idx = 0 |
| 54 | + |
| 55 | + # max length of sequences. It should plus 1 to include position |
| 56 | + # padding token for position encoding. |
| 57 | + max_length = 50 |
| 58 | + |
| 59 | + # the dimension for word embeddings, which is also the last dimension of |
| 60 | + # the input and output of multi-head attention, position-wise feed-forward |
| 61 | + # networks, encoder and decoder. |
| 62 | + |
| 63 | + d_model = 512 |
| 64 | + # size of the hidden layer in position-wise feed-forward networks. |
| 65 | + d_inner_hid = 1024 |
| 66 | + # the dimension that keys are projected to for dot-product attention. |
| 67 | + d_key = 64 |
| 68 | + # the dimension that values are projected to for dot-product attention. |
| 69 | + d_value = 64 |
| 70 | + # number of head used in multi-head attention. |
| 71 | + n_head = 8 |
| 72 | + # number of sub-layers to be stacked in the encoder and decoder. |
| 73 | + n_layer = 6 |
| 74 | + # dropout rate used by all dropout layers. |
| 75 | + dropout = 0.1 |
| 76 | + |
| 77 | + |
| 78 | +def prepare_batch_input(insts, src_pad_idx, trg_pad_idx, n_head): |
| 79 | + """ |
| 80 | + Pad the instances to the max sequence length in batch, and generate the |
| 81 | + corresponding position data and attention bias. Then, convert the numpy |
| 82 | + data to tensors and return a dict mapping names to tensors. |
| 83 | + """ |
| 84 | + |
| 85 | + def __pad_batch_data(insts, |
| 86 | + pad_idx, |
| 87 | + is_target=False, |
| 88 | + return_pos=True, |
| 89 | + return_attn_bias=True, |
| 90 | + return_max_len=True): |
| 91 | + """ |
| 92 | + Pad the instances to the max sequence length in batch, and generate the |
| 93 | + corresponding position data and attention bias. |
| 94 | + """ |
| 95 | + return_list = [] |
| 96 | + max_len = max(len(inst) for inst in insts) |
| 97 | + inst_data = np.array( |
| 98 | + [inst + [pad_idx] * (max_len - len(inst)) for inst in insts]) |
| 99 | + return_list += [inst_data.astype("int64").reshape([-1, 1])] |
| 100 | + if return_pos: |
| 101 | + inst_pos = np.array([[ |
| 102 | + pos_i + 1 if w_i != pad_idx else 0 |
| 103 | + for pos_i, w_i in enumerate(inst) |
| 104 | + ] for inst in inst_data]) |
| 105 | + |
| 106 | + return_list += [inst_pos.astype("int64").reshape([-1, 1])] |
| 107 | + if return_attn_bias: |
| 108 | + if is_target: |
| 109 | + # This is used to avoid attention on paddings and subsequent |
| 110 | + # words. |
| 111 | + slf_attn_bias_data = np.ones((inst_data.shape[0], max_len, |
| 112 | + max_len)) |
| 113 | + slf_attn_bias_data = np.triu(slf_attn_bias_data, 1).reshape( |
| 114 | + [-1, 1, max_len, max_len]) |
| 115 | + slf_attn_bias_data = np.tile(slf_attn_bias_data, |
| 116 | + [1, n_head, 1, 1]) * [-1e9] |
| 117 | + else: |
| 118 | + # This is used to avoid attention on paddings. |
| 119 | + slf_attn_bias_data = np.array([[0] * len(inst) + [-1e9] * |
| 120 | + (max_len - len(inst)) |
| 121 | + for inst in insts]) |
| 122 | + slf_attn_bias_data = np.tile( |
| 123 | + slf_attn_bias_data.reshape([-1, 1, 1, max_len]), |
| 124 | + [1, n_head, max_len, 1]) |
| 125 | + return_list += [slf_attn_bias_data.astype("float32")] |
| 126 | + if return_max_len: |
| 127 | + return_list += [max_len] |
| 128 | + return return_list if len(return_list) > 1 else return_list[0] |
| 129 | + |
| 130 | + src_word, src_pos, src_slf_attn_bias, src_max_len = __pad_batch_data( |
| 131 | + [inst[0] for inst in insts], src_pad_idx, is_target=False) |
| 132 | + trg_word, trg_pos, trg_slf_attn_bias, trg_max_len = __pad_batch_data( |
| 133 | + [inst[1] for inst in insts], trg_pad_idx, is_target=True) |
| 134 | + trg_src_attn_bias = np.tile(src_slf_attn_bias[:, :, ::src_max_len, :], |
| 135 | + [1, 1, trg_max_len, 1]).astype("float32") |
| 136 | + lbl_word = __pad_batch_data([inst[2] for inst in insts], trg_pad_idx, False, |
| 137 | + False, False, False) |
| 138 | + lbl_weight = (lbl_word != trg_pad_idx).astype("float32").reshape([-1, 1]) |
| 139 | + |
| 140 | + return [ |
| 141 | + src_word, src_pos, trg_word, trg_pos, src_slf_attn_bias, |
| 142 | + trg_slf_attn_bias, trg_src_attn_bias, lbl_word, lbl_weight |
| 143 | + ] |
| 144 | + |
| 145 | + |
| 146 | +def transformer(use_feed): |
| 147 | + assert not use_feed, "transfomer doesn't support feed yet" |
| 148 | + return transformer_model.transformer( |
| 149 | + ModelHyperParams.src_vocab_size + 1, |
| 150 | + ModelHyperParams.trg_vocab_size + 1, ModelHyperParams.max_length + 1, |
| 151 | + ModelHyperParams.n_layer, ModelHyperParams.n_head, |
| 152 | + ModelHyperParams.d_key, ModelHyperParams.d_value, |
| 153 | + ModelHyperParams.d_model, ModelHyperParams.d_inner_hid, |
| 154 | + ModelHyperParams.dropout, ModelHyperParams.src_pad_idx, |
| 155 | + ModelHyperParams.trg_pad_idx, ModelHyperParams.pos_pad_idx) |
| 156 | + |
| 157 | + |
| 158 | +def get_model(): |
| 159 | + avg_cost = transformer(use_feed=False) |
| 160 | + optimizer = fluid.optimizer.Adam() |
| 161 | + optimizer.minimize(avg_cost) |
| 162 | + return avg_cost |
| 163 | + |
| 164 | + |
| 165 | +def get_transpiler(trainer_id, main_program, pserver_endpoints, trainers): |
| 166 | + t = fluid.DistributeTranspiler() |
| 167 | + t.transpile( |
| 168 | + trainer_id=trainer_id, |
| 169 | + program=main_program, |
| 170 | + pservers=pserver_endpoints, |
| 171 | + trainers=trainers) |
| 172 | + return t |
| 173 | + |
| 174 | + |
| 175 | +class DistTransformer2x2(object): |
| 176 | + def run_pserver(self, pserver_endpoints, trainers, current_endpoint, |
| 177 | + trainer_id): |
| 178 | + get_model() |
| 179 | + t = get_transpiler(trainer_id, |
| 180 | + fluid.default_main_program(), pserver_endpoints, |
| 181 | + trainers) |
| 182 | + pserver_prog = t.get_pserver_program(current_endpoint) |
| 183 | + startup_prog = t.get_startup_program(current_endpoint, pserver_prog) |
| 184 | + |
| 185 | + place = fluid.CPUPlace() |
| 186 | + exe = fluid.Executor(place) |
| 187 | + exe.run(startup_prog) |
| 188 | + exe.run(pserver_prog) |
| 189 | + |
| 190 | + def _wait_ps_ready(self, pid): |
| 191 | + retry_times = 20 |
| 192 | + while True: |
| 193 | + assert retry_times >= 0, "wait ps ready failed" |
| 194 | + time.sleep(3) |
| 195 | + print("waiting ps ready: ", pid) |
| 196 | + try: |
| 197 | + # the listen_and_serv_op would touch a file which contains the listen port |
| 198 | + # on the /tmp directory until it was ready to process all the RPC call. |
| 199 | + os.stat("/tmp/paddle.%d.port" % pid) |
| 200 | + return |
| 201 | + except os.error: |
| 202 | + retry_times -= 1 |
| 203 | + |
| 204 | + def run_trainer(self, place, endpoints, trainer_id, trainers, is_dist=True): |
| 205 | + avg_cost = get_model() |
| 206 | + if is_dist: |
| 207 | + t = get_transpiler(trainer_id, |
| 208 | + fluid.default_main_program(), endpoints, |
| 209 | + trainers) |
| 210 | + trainer_prog = t.get_trainer_program() |
| 211 | + else: |
| 212 | + trainer_prog = fluid.default_main_program() |
| 213 | + |
| 214 | + startup_exe = fluid.Executor(place) |
| 215 | + startup_exe.run(fluid.default_startup_program()) |
| 216 | + |
| 217 | + strategy = fluid.ExecutionStrategy() |
| 218 | + strategy.num_threads = 1 |
| 219 | + strategy.allow_op_delay = False |
| 220 | + exe = fluid.ParallelExecutor( |
| 221 | + True, loss_name=avg_cost.name, exec_strategy=strategy) |
| 222 | + |
| 223 | + first_loss, = exe.run(fetch_list=[avg_cost.name]) |
| 224 | + print(first_loss) |
| 225 | + for i in xrange(5): |
| 226 | + _ = exe.run(fetch_list=[avg_cost.name]) |
| 227 | + last_loss, = exe.run(fetch_list=[avg_cost.name]) |
| 228 | + print(last_loss) |
| 229 | + |
| 230 | + |
| 231 | +def main(role="pserver", |
| 232 | + endpoints="127.0.0.1:9123", |
| 233 | + trainer_id=0, |
| 234 | + current_endpoint="127.0.0.1:9123", |
| 235 | + trainers=1, |
| 236 | + is_dist=True): |
| 237 | + |
| 238 | + reader = paddle.batch( |
| 239 | + wmt16.train(ModelHyperParams.src_vocab_size, |
| 240 | + ModelHyperParams.trg_vocab_size), |
| 241 | + batch_size=transformer_model.batch_size) |
| 242 | + |
| 243 | + with fluid.recordio_writer.create_recordio_writer( |
| 244 | + WMT16_RECORDIO_FILE) as writer: |
| 245 | + for batch in reader(): |
| 246 | + for tensor in prepare_batch_input( |
| 247 | + batch, ModelHyperParams.src_pad_idx, |
| 248 | + ModelHyperParams.trg_pad_idx, ModelHyperParams.n_head): |
| 249 | + t = fluid.LoDTensor() |
| 250 | + t.set(tensor, fluid.CPUPlace()) |
| 251 | + writer.append_tensor(t) |
| 252 | + writer.complete_append_tensor() |
| 253 | + |
| 254 | + model = DistTransformer2x2() |
| 255 | + if role == "pserver": |
| 256 | + model.run_pserver(endpoints, trainers, current_endpoint, trainer_id) |
| 257 | + else: |
| 258 | + p = fluid.CUDAPlace(0) if core.is_compiled_with_cuda( |
| 259 | + ) else fluid.CPUPlace() |
| 260 | + model.run_trainer(p, endpoints, trainer_id, trainers, is_dist) |
| 261 | + |
| 262 | + |
| 263 | +if __name__ == "__main__": |
| 264 | + if len(sys.argv) != 7: |
| 265 | + print( |
| 266 | + "Usage: python dist_transformer.py [pserver/trainer] [endpoints] [trainer_id] [current_endpoint] [trainers] [is_dist]" |
| 267 | + ) |
| 268 | + role = sys.argv[1] |
| 269 | + endpoints = sys.argv[2] |
| 270 | + trainer_id = int(sys.argv[3]) |
| 271 | + current_endpoint = sys.argv[4] |
| 272 | + trainers = int(sys.argv[5]) |
| 273 | + is_dist = True if sys.argv[6] == "TRUE" else False |
| 274 | + main( |
| 275 | + role=role, |
| 276 | + endpoints=endpoints, |
| 277 | + trainer_id=trainer_id, |
| 278 | + current_endpoint=current_endpoint, |
| 279 | + trainers=trainers, |
| 280 | + is_dist=is_dist) |
0 commit comments