|
| 1 | +from __future__ import absolute_import, division, print_function, unicode_literals |
| 2 | +import tensorflow_datasets as tfds |
| 3 | +import tensorflow as tf |
| 4 | +import time |
| 5 | +import numpy as np |
| 6 | +import matplotlib.pyplot as plt |
| 7 | +from tensorlayer.models.transformer import Transformer |
| 8 | +from tensorlayer.models.transformer.utils import metrics |
| 9 | +from tensorlayer.models.transformer.utils import attention_visualisation |
| 10 | +import tensorlayer as tl |
| 11 | + |
| 12 | + |
| 13 | +""" Translation from Portugese to English by Transformer model |
| 14 | +This tutorial provides basic instructions on how to define and train Transformer model on Tensorlayer for |
| 15 | +Translation task. You can also learn how to visualize the attention block via this tutorial. |
| 16 | +""" |
| 17 | + |
| 18 | +def set_up_dataset(): |
| 19 | + # Set up dataset for Portugese-English translation from the TED Talks Open Translation Project. |
| 20 | + # This dataset contains approximately 50000 training examples, 1100 validation examples, and 2000 test examples. |
| 21 | + # https://www.ted.com/participate/translate |
| 22 | + |
| 23 | + examples, metadata = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True, |
| 24 | + as_supervised=True) |
| 25 | + train_examples, val_examples = examples['train'], examples['validation'] |
| 26 | + |
| 27 | + # Set up tokenizer and save the tokenizer |
| 28 | + tokenizer = tfds.features.text.SubwordTextEncoder.build_from_corpus( |
| 29 | + (en.numpy() and pt.numpy() for pt, en in train_examples), target_vocab_size=2**14) |
| 30 | + |
| 31 | + tokenizer.save_to_file("tokenizer") |
| 32 | + tokenizer = tfds.features.text.SubwordTextEncoder.load_from_file("tokenizer") |
| 33 | + |
| 34 | + return tokenizer, train_examples |
| 35 | + |
| 36 | + |
| 37 | +def test_tokenizer_success(tokenizer): |
| 38 | + sample_string = 'TensorLayer is awesome.' |
| 39 | + |
| 40 | + tokenized_string = tokenizer.encode(sample_string) |
| 41 | + print ('Tokenized string is {}'.format(tokenized_string)) |
| 42 | + |
| 43 | + original_string = tokenizer.decode(tokenized_string) |
| 44 | + print ('The original string: {}'.format(original_string)) |
| 45 | + assert original_string == sample_string |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +def generate_training_dataset(train_examples, tokenizer): |
| 50 | + def encode(lang1, lang2): |
| 51 | + lang1 = tokenizer.encode( |
| 52 | + lang1.numpy()) + [tokenizer.vocab_size+1] |
| 53 | + |
| 54 | + lang2 = tokenizer.encode( |
| 55 | + lang2.numpy()) + [tokenizer.vocab_size+1] |
| 56 | + |
| 57 | + return lang1, lang2 |
| 58 | + MAX_LENGTH = 50 |
| 59 | + def filter_max_length(x, y, max_length=MAX_LENGTH): |
| 60 | + return tf.logical_and(tf.size(x) <= max_length, |
| 61 | + tf.size(y) <= max_length) |
| 62 | + def tf_encode(pt, en): |
| 63 | + return tf.py_function(encode, [pt, en], [tf.int64, tf.int64]) |
| 64 | + train_dataset = train_examples.map(tf_encode) |
| 65 | + train_dataset = train_dataset.filter(filter_max_length) |
| 66 | + # cache the dataset to memory to get a speedup while reading from it. |
| 67 | + train_dataset = train_dataset.cache() |
| 68 | + BUFFER_SIZE = 20000 |
| 69 | + BATCH_SIZE = 64 |
| 70 | + train_dataset = train_dataset.shuffle(BUFFER_SIZE).padded_batch( |
| 71 | + BATCH_SIZE, padded_shapes=([-1], [-1])) |
| 72 | + train_dataset = train_dataset.prefetch(tf.data.experimental.AUTOTUNE) |
| 73 | + |
| 74 | + return train_dataset |
| 75 | + |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | +def model_setup(tokenizer): |
| 80 | + # define Hyper parameters for transformer |
| 81 | + class HYPER_PARAMS(object): |
| 82 | + vocab_size = tokenizer.vocab_size + 10 |
| 83 | + encoder_num_layers = 4 |
| 84 | + decoder_num_layers = 4 |
| 85 | + hidden_size = 128 |
| 86 | + ff_size = 512 |
| 87 | + num_heads = 8 |
| 88 | + keep_prob = 0.9 |
| 89 | + |
| 90 | + # Default prediction params |
| 91 | + extra_decode_length = 50 |
| 92 | + beam_size = 5 |
| 93 | + alpha = 0.6 # used to calculate length normalization in beam search |
| 94 | + |
| 95 | + |
| 96 | + label_smoothing=0.1 |
| 97 | + learning_rate=2.0 |
| 98 | + learning_rate_decay_rate=1.0 |
| 99 | + learning_rate_warmup_steps=4000 |
| 100 | + |
| 101 | + sos_id = 0 |
| 102 | + eos_id = tokenizer.vocab_size+1 |
| 103 | + |
| 104 | + |
| 105 | + model = Transformer(HYPER_PARAMS) |
| 106 | + |
| 107 | + # Set the optimizer |
| 108 | + learning_rate = CustomSchedule(HYPER_PARAMS.hidden_size, warmup_steps=HYPER_PARAMS.learning_rate_warmup_steps) |
| 109 | + optimizer = tl.optimizers.LazyAdamOptimizer(learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9) |
| 110 | + return model, optimizer, HYPER_PARAMS |
| 111 | + |
| 112 | + |
| 113 | +# Use the Adam optimizer with a custom learning rate scheduler according to the formula in the Paper "Attention is All you need" |
| 114 | +class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): |
| 115 | + def __init__(self, d_model, warmup_steps=5): |
| 116 | + super(CustomSchedule, self).__init__() |
| 117 | + |
| 118 | + self.d_model = d_model |
| 119 | + self.d_model = tf.cast(self.d_model, tf.float32) |
| 120 | + |
| 121 | + self.warmup_steps = warmup_steps |
| 122 | + |
| 123 | + def __call__(self, step): |
| 124 | + arg1 = tf.math.rsqrt(step) |
| 125 | + arg2 = step * (self.warmup_steps ** -1.5) |
| 126 | + |
| 127 | + return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2) |
| 128 | + |
| 129 | + |
| 130 | + |
| 131 | +def tutorial_transformer(): |
| 132 | + tokenizer, train_examples = set_up_dataset() |
| 133 | + train_dataset = generate_training_dataset(train_examples, tokenizer) |
| 134 | + model, optimizer, HYPER_PARAMS = model_setup(tokenizer) |
| 135 | + |
| 136 | + num_epochs = 10 |
| 137 | + for epoch in range(num_epochs): |
| 138 | + model.train() |
| 139 | + for (batch, (inp, tar)) in enumerate(train_dataset): |
| 140 | + with tf.GradientTape() as tape: |
| 141 | + logits, weights_encoder, weights_decoder = model(inputs=inp, targets=tar) |
| 142 | + logits = metrics.MetricLayer(HYPER_PARAMS.vocab_size)([logits, tar]) |
| 143 | + logits, loss = metrics.LossLayer(HYPER_PARAMS.vocab_size, 0.1)([logits, tar]) |
| 144 | + grad = tape.gradient(loss, model.all_weights) |
| 145 | + optimizer.apply_gradients(zip(grad, model.all_weights)) |
| 146 | + if (batch % 50 == 0): |
| 147 | + print('Batch ID {} at Epoch [{}/{}]: loss {:.4f}'.format(batch, epoch + 1, num_epochs, loss)) |
| 148 | + |
| 149 | + |
| 150 | + |
| 151 | + model.eval() |
| 152 | + sentence_en = tokenizer.encode('TensorLayer is awesome.') |
| 153 | + [prediction, weights_decoder], weights_encoder = model(inputs=[sentence_en]) |
| 154 | + |
| 155 | + predicted_sentence = tokenizer.decode([i for i in prediction["outputs"][0] |
| 156 | + if i < tokenizer.vocab_size]) |
| 157 | + print("Translated: ", predicted_sentence) |
| 158 | + |
| 159 | + |
| 160 | + # visualize the self attention |
| 161 | + tokenizer_str = [tokenizer.decode([ts]) for ts in (sentence_en)] |
| 162 | + attention_visualisation.plot_attention_weights(weights_encoder["layer_0"], tokenizer_str, tokenizer_str) |
| 163 | + |
| 164 | + |
| 165 | + |
| 166 | + |
| 167 | +if __name__ == "__main__": |
| 168 | + tutorial_transformer() |
0 commit comments