Machine Translation and the Dataset

:label:sec_machine_translation

We have used RNNs to design language models, which are key to natural language processing. Another flagship benchmark is machine translation, a central problem domain for sequence transduction models that transform input sequences into output sequences. Playing a crucial role in various modern AI applications, sequence transduction models will form the focus of the remainder of this chapter and :numref:chap_attention. To this end, this section introduces the machine translation problem and its dataset that will be used later.

Machine translation refers to the automatic translation of a sequence from one language to another. In fact, this field may date back to 1940s soon after digital computers were invented, especially by considering the use of computers for cracking language codes in World War II. For decades, statistical approaches had been dominant in this field :cite:Brown.Cocke.Della-Pietra.ea.1988,Brown.Cocke.Della-Pietra.ea.1990 before the rise of end-to-end learning using neural networks. The latter is often called neural machine translation to distinguish itself from statistical machine translation that involves statistical analysis in components such as the translation model and the language model.

Emphasizing end-to-end learning, this book will focus on neural machine translation methods. Different from our language model problem in :numref:sec_language_model whose corpus is in one single language, machine translation datasets are composed of pairs of text sequences that are in the source language and the target language, respectively. Thus, instead of reusing the preprocessing routine for language modeling, we need a different way to preprocess machine translation datasets. In the following, we show how to load the preprocessed data into minibatches for training.

```{.python .input} from d2l import mxnet as d2l from mxnet import np, npx import os npx.set_np()

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import torch
  5. import os

```{.python .input}

@tab tensorflow

from d2l import tensorflow as d2l import tensorflow as tf import os

  1. ## Downloading and Preprocessing the Dataset
  2. To begin with,
  3. we download an English-French dataset
  4. that consists of [bilingual sentence pairs from the Tatoeba Project](http://www.manythings.org/anki/).
  5. Each line in the dataset
  6. is a tab-delimited pair
  7. of an English text sequence
  8. and the translated French text sequence.
  9. Note that each text sequence
  10. can be just one sentence or a paragraph of multiple sentences.
  11. In this machine translation problem
  12. where English is translated into French,
  13. English is the *source language*
  14. and French is the *target language*.
  15. ```{.python .input}
  16. #@tab all
  17. #@save
  18. d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
  19. '94646ad1522d915e7b0f9296181140edcf86a4f5')
  20. #@save
  21. def read_data_nmt():
  22. """Load the English-French dataset."""
  23. data_dir = d2l.download_extract('fra-eng')
  24. with open(os.path.join(data_dir, 'fra.txt'), 'r') as f:
  25. return f.read()
  26. raw_text = read_data_nmt()
  27. print(raw_text[:75])

After downloading the dataset, we proceed with several preprocessing steps for the raw text data. For instance, we replace non-breaking space with space, convert uppercase letters to lowercase ones, and insert space between words and punctuation marks.

```{.python .input}

@tab all

@save

def preprocess_nmt(text): “””Preprocess the English-French dataset.””” def no_space(char, prev_char): return char in set(‘,.!?’) and prev_char != ‘ ‘

  1. # Replace non-breaking space with space, and convert uppercase letters to
  2. # lowercase ones
  3. text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
  4. # Insert space between words and punctuation marks
  5. out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
  6. for i, char in enumerate(text)]
  7. return ''.join(out)

text = preprocess_nmt(raw_text) print(text[:80])

  1. ## Tokenization
  2. Different from character-level tokenization
  3. in :numref:`sec_language_model`,
  4. for machine translation
  5. we prefer word-level tokenization here
  6. (state-of-the-art models may use more advanced tokenization techniques).
  7. The following `tokenize_nmt` function
  8. tokenizes the the first `num_examples` text sequence pairs,
  9. where
  10. each token is either a word or a punctuation mark.
  11. This function returns
  12. two lists of token lists: `source` and `target`.
  13. Specifically,
  14. `source[i]` is a list of tokens from the
  15. $i^\mathrm{th}$ text sequence in the source language (English here) and `target[i]` is that in the target language (French here).
  16. ```{.python .input}
  17. #@tab all
  18. #@save
  19. def tokenize_nmt(text, num_examples=None):
  20. """Tokenize the English-French dataset."""
  21. source, target = [], []
  22. for i, line in enumerate(text.split('\n')):
  23. if num_examples and i > num_examples:
  24. break
  25. parts = line.split('\t')
  26. if len(parts) == 2:
  27. source.append(parts[0].split(' '))
  28. target.append(parts[1].split(' '))
  29. return source, target
  30. source, target = tokenize_nmt(text)
  31. source[:6], target[:6]

Let us plot the histogram of the number of tokens per text sequence. In this simple English-French dataset, most of the text sequences have fewer than 20 tokens.

```{.python .input}

@tab all

d2l.setfigsize() , _, patches = d2l.plt.hist( [[len(l) for l in source], [len(l) for l in target]], label=[‘source’, ‘target’]) for patch in patches[1].patches: patch.set_hatch(‘/‘) d2l.plt.legend(loc=’upper right’);

  1. ## Vocabulary
  2. Since the machine translation dataset
  3. consists of pairs of languages,
  4. we can build two vocabularies for
  5. both the source language and
  6. the target language separately.
  7. With word-level tokenization,
  8. the vocabulary size will be significantly larger
  9. than that using character-level tokenization.
  10. To alleviate this,
  11. here we treat infrequent tokens
  12. that appear less than 2 times
  13. as the same unknown ("<unk>") token.
  14. Besides that,
  15. we specify additional special tokens
  16. such as for padding ("<pad>") sequences to the same length in minibatches,
  17. and for marking the beginning ("<bos>") or end ("<eos>") of sequences.
  18. Such special tokens are commonly used in
  19. natural language processing tasks.
  20. ```{.python .input}
  21. #@tab all
  22. src_vocab = d2l.Vocab(source, min_freq=2,
  23. reserved_tokens=['<pad>', '<bos>', '<eos>'])
  24. len(src_vocab)

Loading the Dataset

:label:subsec_mt_data_loading

Recall that in language modeling each sequence example, either a segment of one sentence or a span over multiple sentences, has a fixed length. This was specified by the num_steps (number of time steps or tokens) argument in :numref:sec_language_model. In machine translation, each example is a pair of source and target text sequences, where each text sequence may have different lengths.

For computational efficiency, we can still process a minibatch of text sequences at one time by truncation and padding. Suppose that every sequence in the same minibatch should have the same length num_steps. If a text sequence has fewer than num_steps tokens, we will keep appending the special “<pad>” token to its end until its length reaches num_steps. Otherwise, we will truncate the text sequence by only taking its first num_steps tokens and discarding the remaining. In this way, every text sequence will have the same length to be loaded in minibatches of the same shape.

The following truncate_pad function truncates or pads text sequences as described before.

```{.python .input}

@tab all

@save

def truncate_pad(line, num_steps, padding_token): “””Truncate or pad sequences.””” if len(line) > num_steps: return line[:num_steps] # Truncate return line + [padding_token] * (num_steps - len(line)) # Pad

truncate_pad(src_vocab[source[0]], 10, src_vocab[‘‘])

  1. Now we define a function to transform
  2. text sequences into minibatches for training.
  3. We append the special “&lt;eos&gt;” token
  4. to the end of every sequence to indicate the
  5. end of the sequence.
  6. When a model is predicting
  7. by
  8. generating a sequence token after token,
  9. the generation
  10. of the “&lt;eos&gt;” token
  11. can suggest that
  12. the output sequence is complete.
  13. Besides,
  14. we also record the length
  15. of each text sequence excluding the padding tokens.
  16. This information will be needed by
  17. some models that
  18. we will cover later.
  19. ```{.python .input}
  20. #@tab all
  21. #@save
  22. def build_array_nmt(lines, vocab, num_steps):
  23. """Transform text sequences of machine translation into minibatches."""
  24. lines = [vocab[l] for l in lines]
  25. lines = [l + [vocab['<eos>']] for l in lines]
  26. array = d2l.tensor([truncate_pad(
  27. l, num_steps, vocab['<pad>']) for l in lines])
  28. valid_len = d2l.reduce_sum(
  29. d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
  30. return array, valid_len

Putting All Things Together

Finally, we define the load_data_nmt function to return the data iterator, together with the vocabularies for both the source language and the target language.

```{.python .input}

@tab all

@save

def load_data_nmt(batch_size, num_steps, num_examples=600): “””Return the iterator and the vocabularies of the translation dataset.””” text = preprocess_nmt(read_data_nmt()) source, target = tokenize_nmt(text, num_examples) src_vocab = d2l.Vocab(source, min_freq=2, reserved_tokens=[‘‘, ‘‘, ‘‘]) tgt_vocab = d2l.Vocab(target, min_freq=2, reserved_tokens=[‘‘, ‘‘, ‘‘]) src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps) tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps) data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len) data_iter = d2l.load_array(data_arrays, batch_size) return data_iter, src_vocab, tgt_vocab

  1. Let us read the first minibatch from the English-French dataset.
  2. ```{.python .input}
  3. #@tab all
  4. train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8)
  5. for X, X_valid_len, Y, Y_valid_len in train_iter:
  6. print('X:', d2l.astype(X, d2l.int32))
  7. print('valid lengths for X:', X_valid_len)
  8. print('Y:', d2l.astype(Y, d2l.int32))
  9. print('valid lengths for Y:', Y_valid_len)
  10. break

Summary

  • Machine translation refers to the automatic translation of a sequence from one language to another.
  • Using word-level tokenization, the vocabulary size will be significantly larger than that using character-level tokenization. To alleviate this, we can treat infrequent tokens as the same unknown token.
  • We can truncate and pad text sequences so that all of them will have the same length to be loaded in minibatches.

Exercises

  1. Try different values of the num_examples argument in the load_data_nmt function. How does this affect the vocabulary sizes of the source language and the target language?
  2. Text in some languages such as Chinese and Japanese does not have word boundary indicators (e.g., space). Is word-level tokenization still a good idea for such cases? Why or why not?

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: