Path: blob/master/examples/nlp/neural_machine_translation_with_keras_hub.py
8412 views
"""1Title: English-to-Spanish translation with KerasHub2Author: [Abheesht Sharma](https://github.com/abheesht17/)3Date created: 2022/05/264Last modified: 2024/04/305Description: Use KerasHub to train a sequence-to-sequence Transformer model on the machine translation task.6Accelerator: GPU7"""89"""10## Introduction1112KerasHub provides building blocks for NLP (model layers, tokenizers, metrics, etc.) and13makes it convenient to construct NLP pipelines.1415In this example, we'll use KerasHub layers to build an encoder-decoder Transformer16model, and train it on the English-to-Spanish machine translation task.1718This example is based on the19[English-to-Spanish NMT20example](https://keras.io/examples/nlp/neural_machine_translation_with_transformer/)21by [fchollet](https://twitter.com/fchollet). The original example is more low-level22and implements layers from scratch, whereas this example uses KerasHub to show23some more advanced approaches, such as subword tokenization and using metrics24to compute the quality of generated translations.2526You'll learn how to:2728- Tokenize text using `keras_hub.tokenizers.WordPieceTokenizer`.29- Implement a sequence-to-sequence Transformer model using KerasHub's30`keras_hub.layers.TransformerEncoder`, `keras_hub.layers.TransformerDecoder` and31`keras_hub.layers.TokenAndPositionEmbedding` layers, and train it.32- Use `keras_hub.samplers` to generate translations of unseen input sentences33using the top-p decoding strategy!3435Don't worry if you aren't familiar with KerasHub. This tutorial will start with36the basics. Let's dive right in!37"""3839"""40## Setup4142Before we start implementing the pipeline, let's import all the libraries we need.43"""4445"""shell46pip install -q --upgrade rouge-score47pip install -q --upgrade keras-hub48"""4950import keras_hub51import pathlib52import random5354import keras55from keras import ops5657import tensorflow.data as tf_data5859"""60Let's also define our parameters/hyperparameters.61"""6263BATCH_SIZE = 6464EPOCHS = 1 # This should be at least 10 for convergence65MAX_SEQUENCE_LENGTH = 4066ENG_VOCAB_SIZE = 1500067SPA_VOCAB_SIZE = 150006869EMBED_DIM = 25670INTERMEDIATE_DIM = 204871NUM_HEADS = 87273"""74## Downloading the data7576We'll be working with an English-to-Spanish translation dataset77provided by [Anki](https://www.manythings.org/anki/). Let's download it:78"""7980text_file = keras.utils.get_file(81fname="spa-eng.zip",82origin="http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip",83extract=True,84)85text_file = pathlib.Path(text_file) / "spa-eng" / "spa.txt"8687"""88## Parsing the data8990Each line contains an English sentence and its corresponding Spanish sentence.91The English sentence is the *source sequence* and Spanish one is the *target sequence*.92Before adding the text to a list, we convert it to lowercase.93"""9495with open(text_file) as f:96lines = f.read().split("\n")[:-1]97text_pairs = []98for line in lines:99eng, spa = line.split("\t")100eng = eng.lower()101spa = spa.lower()102text_pairs.append((eng, spa))103104"""105Here's what our sentence pairs look like:106"""107108for _ in range(5):109print(random.choice(text_pairs))110111"""112Now, let's split the sentence pairs into a training set, a validation set,113and a test set.114"""115116random.shuffle(text_pairs)117num_val_samples = int(0.15 * len(text_pairs))118num_train_samples = len(text_pairs) - 2 * num_val_samples119train_pairs = text_pairs[:num_train_samples]120val_pairs = text_pairs[num_train_samples : num_train_samples + num_val_samples]121test_pairs = text_pairs[num_train_samples + num_val_samples :]122123print(f"{len(text_pairs)} total pairs")124print(f"{len(train_pairs)} training pairs")125print(f"{len(val_pairs)} validation pairs")126print(f"{len(test_pairs)} test pairs")127128129"""130## Tokenizing the data131132We'll define two tokenizers - one for the source language (English), and the other133for the target language (Spanish). We'll be using134`keras_hub.tokenizers.WordPieceTokenizer` to tokenize the text.135`keras_hub.tokenizers.WordPieceTokenizer` takes a WordPiece vocabulary136and has functions for tokenizing the text, and detokenizing sequences of tokens.137138Before we define the two tokenizers, we first need to train them on the dataset139we have. The WordPiece tokenization algorithm is a subword tokenization algorithm;140training it on a corpus gives us a vocabulary of subwords. A subword tokenizer141is a compromise between word tokenizers (word tokenizers need very large142vocabularies for good coverage of input words), and character tokenizers143(characters don't really encode meaning like words do). Luckily, KerasHub144makes it very simple to train WordPiece on a corpus with the145`keras_hub.tokenizers.compute_word_piece_vocabulary` utility.146"""147148149def train_word_piece(text_samples, vocab_size, reserved_tokens):150word_piece_ds = tf_data.Dataset.from_tensor_slices(text_samples)151vocab = keras_hub.tokenizers.compute_word_piece_vocabulary(152word_piece_ds.batch(1000).prefetch(2),153vocabulary_size=vocab_size,154reserved_tokens=reserved_tokens,155)156return vocab157158159"""160Every vocabulary has a few special, reserved tokens. We have four such tokens:161162- `"[PAD]"` - Padding token. Padding tokens are appended to the input sequence163length when the input sequence length is shorter than the maximum sequence length.164- `"[UNK]"` - Unknown token.165- `"[START]"` - Token that marks the start of the input sequence.166- `"[END]"` - Token that marks the end of the input sequence.167"""168169reserved_tokens = ["[PAD]", "[UNK]", "[START]", "[END]"]170171eng_samples = [text_pair[0] for text_pair in train_pairs]172eng_vocab = train_word_piece(eng_samples, ENG_VOCAB_SIZE, reserved_tokens)173174spa_samples = [text_pair[1] for text_pair in train_pairs]175spa_vocab = train_word_piece(spa_samples, SPA_VOCAB_SIZE, reserved_tokens)176177"""178Let's see some tokens!179"""180181print("English Tokens: ", eng_vocab[100:110])182print("Spanish Tokens: ", spa_vocab[100:110])183184"""185Now, let's define the tokenizers. We will configure the tokenizers with the186the vocabularies trained above.187"""188189eng_tokenizer = keras_hub.tokenizers.WordPieceTokenizer(190vocabulary=eng_vocab, lowercase=False191)192spa_tokenizer = keras_hub.tokenizers.WordPieceTokenizer(193vocabulary=spa_vocab, lowercase=False194)195196"""197Let's try and tokenize a sample from our dataset! To verify whether the text has198been tokenized correctly, we can also detokenize the list of tokens back to the199original text.200"""201202eng_input_ex = text_pairs[0][0]203eng_tokens_ex = eng_tokenizer.tokenize(eng_input_ex)204print("English sentence: ", eng_input_ex)205print("Tokens: ", eng_tokens_ex)206print(207"Recovered text after detokenizing: ",208eng_tokenizer.detokenize(eng_tokens_ex),209)210211print()212213spa_input_ex = text_pairs[0][1]214spa_tokens_ex = spa_tokenizer.tokenize(spa_input_ex)215print("Spanish sentence: ", spa_input_ex)216print("Tokens: ", spa_tokens_ex)217print(218"Recovered text after detokenizing: ",219spa_tokenizer.detokenize(spa_tokens_ex),220)221222"""223## Format datasets224225Next, we'll format our datasets.226227At each training step, the model will seek to predict target words N+1 (and beyond)228using the source sentence and the target words 0 to N.229230As such, the training dataset will yield a tuple `(inputs, targets)`, where:231232- `inputs` is a dictionary with the keys `encoder_inputs` and `decoder_inputs`.233`encoder_inputs` is the tokenized source sentence and `decoder_inputs` is the target234sentence "so far",235that is to say, the words 0 to N used to predict word N+1 (and beyond) in the target236sentence.237- `target` is the target sentence offset by one step:238it provides the next words in the target sentence -- what the model will try to predict.239240We will add special tokens, `"[START]"` and `"[END]"`, to the input Spanish241sentence after tokenizing the text. We will also pad the input to a fixed length.242This can be easily done using `keras_hub.layers.StartEndPacker`.243"""244245246def preprocess_batch(eng, spa):247eng = eng_tokenizer(eng)248spa = spa_tokenizer(spa)249250# Pad `eng` to `MAX_SEQUENCE_LENGTH`.251eng_start_end_packer = keras_hub.layers.StartEndPacker(252sequence_length=MAX_SEQUENCE_LENGTH,253pad_value=eng_tokenizer.token_to_id("[PAD]"),254)255eng = eng_start_end_packer(eng)256257# Add special tokens (`"[START]"` and `"[END]"`) to `spa` and pad it as well.258spa_start_end_packer = keras_hub.layers.StartEndPacker(259sequence_length=MAX_SEQUENCE_LENGTH + 1,260start_value=spa_tokenizer.token_to_id("[START]"),261end_value=spa_tokenizer.token_to_id("[END]"),262pad_value=spa_tokenizer.token_to_id("[PAD]"),263)264spa = spa_start_end_packer(spa)265266return (267{268"encoder_inputs": eng,269"decoder_inputs": spa[:, :-1],270},271spa[:, 1:],272)273274275def make_dataset(pairs):276eng_texts, spa_texts = zip(*pairs)277eng_texts = list(eng_texts)278spa_texts = list(spa_texts)279dataset = tf_data.Dataset.from_tensor_slices((eng_texts, spa_texts))280dataset = dataset.batch(BATCH_SIZE)281dataset = dataset.map(preprocess_batch, num_parallel_calls=tf_data.AUTOTUNE)282return dataset.shuffle(2048).prefetch(16).cache()283284285train_ds = make_dataset(train_pairs)286val_ds = make_dataset(val_pairs)287288"""289Let's take a quick look at the sequence shapes290(we have batches of 64 pairs, and all sequences are 40 steps long):291"""292293for inputs, targets in train_ds.take(1):294print(f'inputs["encoder_inputs"].shape: {inputs["encoder_inputs"].shape}')295print(f'inputs["decoder_inputs"].shape: {inputs["decoder_inputs"].shape}')296print(f"targets.shape: {targets.shape}")297298299"""300## Building the model301302Now, let's move on to the exciting part - defining our model!303We first need an embedding layer, i.e., a vector for every token in our input sequence.304This embedding layer can be initialised randomly. We also need a positional305embedding layer which encodes the word order in the sequence. The convention is306to add these two embeddings. KerasHub has a `keras_hub.layers.TokenAndPositionEmbedding `307layer which does all of the above steps for us.308309Our sequence-to-sequence Transformer consists of a `keras_hub.layers.TransformerEncoder`310layer and a `keras_hub.layers.TransformerDecoder` layer chained together.311312The source sequence will be passed to `keras_hub.layers.TransformerEncoder`, which313will produce a new representation of it. This new representation will then be passed314to the `keras_hub.layers.TransformerDecoder`, together with the target sequence315so far (target words 0 to N). The `keras_hub.layers.TransformerDecoder` will316then seek to predict the next words in the target sequence (N+1 and beyond).317318A key detail that makes this possible is causal masking.319The `keras_hub.layers.TransformerDecoder` sees the entire sequence at once, and320thus we must make sure that it only uses information from target tokens 0 to N321when predicting token N+1 (otherwise, it could use information from the future,322which would result in a model that cannot be used at inference time). Causal masking323is enabled by default in `keras_hub.layers.TransformerDecoder`.324325We also need to mask the padding tokens (`"[PAD]"`). For this, we can set the326`mask_zero` argument of the `keras_hub.layers.TokenAndPositionEmbedding` layer327to True. This will then be propagated to all subsequent layers.328"""329330# Encoder331encoder_inputs = keras.Input(shape=(None,), name="encoder_inputs")332333x = keras_hub.layers.TokenAndPositionEmbedding(334vocabulary_size=ENG_VOCAB_SIZE,335sequence_length=MAX_SEQUENCE_LENGTH,336embedding_dim=EMBED_DIM,337)(encoder_inputs)338339encoder_outputs = keras_hub.layers.TransformerEncoder(340intermediate_dim=INTERMEDIATE_DIM, num_heads=NUM_HEADS341)(inputs=x)342encoder = keras.Model(encoder_inputs, encoder_outputs)343344345# Decoder346decoder_inputs = keras.Input(shape=(None,), name="decoder_inputs")347encoded_seq_inputs = keras.Input(shape=(None, EMBED_DIM), name="decoder_state_inputs")348349x = keras_hub.layers.TokenAndPositionEmbedding(350vocabulary_size=SPA_VOCAB_SIZE,351sequence_length=MAX_SEQUENCE_LENGTH,352embedding_dim=EMBED_DIM,353)(decoder_inputs)354355x = keras_hub.layers.TransformerDecoder(356intermediate_dim=INTERMEDIATE_DIM, num_heads=NUM_HEADS357)(decoder_sequence=x, encoder_sequence=encoded_seq_inputs)358x = keras.layers.Dropout(0.5)(x)359decoder_outputs = keras.layers.Dense(SPA_VOCAB_SIZE, activation="softmax")(x)360decoder = keras.Model(361[362decoder_inputs,363encoded_seq_inputs,364],365decoder_outputs,366)367decoder_outputs = decoder([decoder_inputs, encoder_outputs])368369transformer = keras.Model(370[encoder_inputs, decoder_inputs],371decoder_outputs,372name="transformer",373)374375"""376## Training our model377378We'll use accuracy as a quick way to monitor training progress on the validation data.379Note that machine translation typically uses BLEU scores as well as other metrics,380rather than accuracy. However, in order to use metrics like ROUGE, BLEU, etc. we381will have decode the probabilities and generate the text. Text generation is382computationally expensive, and performing this during training is not recommended.383384Here we only train for 1 epoch, but to get the model to actually converge385you should train for at least 10 epochs.386"""387388transformer.summary()389transformer.compile(390"rmsprop", loss="sparse_categorical_crossentropy", metrics=["accuracy"]391)392transformer.fit(train_ds, epochs=EPOCHS, validation_data=val_ds)393394"""395## Decoding test sentences (qualitative analysis)396397Finally, let's demonstrate how to translate brand new English sentences.398We simply feed into the model the tokenized English sentence399as well as the target token `"[START]"`. The model outputs probabilities of the400next token. We then we repeatedly generated the next token conditioned on the401tokens generated so far, until we hit the token `"[END]"`.402403For decoding, we will use the `keras_hub.samplers` module from404KerasHub. Greedy Decoding is a text decoding method which outputs the most405likely next token at each time step, i.e., the token with the highest probability.406"""407408409def decode_sequences(input_sentences):410batch_size = 1411412# Tokenize the encoder input.413encoder_input_tokens = ops.convert_to_tensor(414eng_tokenizer(input_sentences), sparse=False, ragged=False415)416if ops.shape(encoder_input_tokens)[1] < MAX_SEQUENCE_LENGTH:417pads = ops.zeros(418(1, MAX_SEQUENCE_LENGTH - ops.shape(encoder_input_tokens)[1]),419dtype=encoder_input_tokens.dtype,420)421encoder_input_tokens = ops.concatenate([encoder_input_tokens, pads], 1)422423# Define a function that outputs the next token's probability given the424# input sequence.425def next(prompt, cache, index):426logits = transformer([encoder_input_tokens, prompt])[:, index - 1, :]427# Ignore hidden states for now; only needed for contrastive search.428hidden_states = None429return logits, hidden_states, cache430431# Build a prompt of length 40 with a start token and padding tokens.432length = 40433start = ops.full((batch_size, 1), spa_tokenizer.token_to_id("[START]"))434pad = ops.full((batch_size, length - 1), spa_tokenizer.token_to_id("[PAD]"))435prompt = ops.concatenate((start, pad), axis=-1)436437generated_tokens = keras_hub.samplers.GreedySampler()(438next,439prompt,440stop_token_ids=[spa_tokenizer.token_to_id("[END]")],441index=1, # Start sampling after start token.442)443generated_sentences = spa_tokenizer.detokenize(generated_tokens)444return generated_sentences445446447test_eng_texts = [pair[0] for pair in test_pairs]448for i in range(2):449input_sentence = random.choice(test_eng_texts)450translated = decode_sequences([input_sentence])[0]451translated = (452translated.replace("[PAD]", "")453.replace("[START]", "")454.replace("[END]", "")455.strip()456)457print(f"** Example {i} **")458print(input_sentence)459print(translated)460print()461462"""463## Evaluating our model (quantitative analysis)464465There are many metrics which are used for text generation tasks. Here, to466evaluate translations generated by our model, let's compute the ROUGE-1 and467ROUGE-2 scores. Essentially, ROUGE-N is a score based on the number of common468n-grams between the reference text and the generated text. ROUGE-1 and ROUGE-2469use the number of common unigrams and bigrams, respectively.470471We will calculate the score over 30 test samples (since decoding is an472expensive process).473"""474475rouge_1 = keras_hub.metrics.RougeN(order=1)476rouge_2 = keras_hub.metrics.RougeN(order=2)477478for test_pair in test_pairs[:30]:479input_sentence = test_pair[0]480reference_sentence = test_pair[1]481482translated_sentence = decode_sequences([input_sentence])[0]483translated_sentence = (484translated_sentence.replace("[PAD]", "")485.replace("[START]", "")486.replace("[END]", "")487.strip()488)489490rouge_1(reference_sentence, translated_sentence)491rouge_2(reference_sentence, translated_sentence)492493print("ROUGE-1 Score: ", rouge_1.result())494print("ROUGE-2 Score: ", rouge_2.result())495496"""497After 10 epochs, the scores are as follows:498499| | **ROUGE-1** | **ROUGE-2** |500|:-------------:|:-----------:|:-----------:|501| **Precision** | 0.568 | 0.374 |502| **Recall** | 0.615 | 0.394 |503| **F1 Score** | 0.579 | 0.381 |504"""505506"""507## Relevant Chapters from Deep Learning with Python508- [Chapter 15: Language models and the Transformer](https://deeplearningwithpython.io/chapters/chapter15_language-models-and-the-transformer)509- [Chapter 16: Text generation](https://deeplearningwithpython.io/chapters/chapter16_text-generation)510"""511512513