: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.
%load ../utils/djl-imports
%load ../utils/plot-utils
%load ../utils/Functions.java
%load ../utils/timemachine/Vocab.java
%load ../utils/timemachine/RNNModel.java
%load ../utils/timemachine/RNNModelScratch.java
%load ../utils/timemachine/TimeMachine.java
%load ../utils/timemachine/TimeMachineDataset.java
import java.nio.charset.*;
import java.util.zip.*;
import java.util.stream.*;
NDManager manager = NDManager.newBaseManager();
To begin with, we download an English-French dataset that consists of bilingual sentence pairs from the Tatoeba Project. Each line in the dataset is a tab-delimited pair of an English text sequence and the translated French text sequence. Note that each text sequence can be just one sentence or a paragraph of multiple sentences. In this machine translation problem where English is translated into French, English is the source language and French is the target language.
public static String readDataNMT() throws IOException {
DownloadUtils.download(
"http://d2l-data.s3-accelerate.amazonaws.com/fra-eng.zip", "fra-eng.zip");
ZipFile zipFile = new ZipFile(new File("fra-eng.zip"));
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.getName().contains("fra.txt")) {
InputStream stream = zipFile.getInputStream(entry);
return new String(stream.readAllBytes(), StandardCharsets.UTF_8);
}
}
return null;
}
String rawText = readDataNMT();
System.out.println(rawText.substring(0, 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.
public static String preprocessNMT(String text) {
// Replace non-breaking space with space, and convert uppercase letters to
// lowercase ones
text = text.replace('\u202f', ' ').replaceAll("\\xa0", " ").toLowerCase();
// Insert space between words and punctuation marks
StringBuilder out = new StringBuilder();
Character currChar;
for (int i = 0; i < text.length(); i++) {
currChar = text.charAt(i);
if (i > 0 && noSpace(currChar, text.charAt(i - 1))) {
out.append(' ');
}
out.append(currChar);
}
return out.toString();
}
public static boolean noSpace(Character currChar, Character prevChar) {
/* Preprocess the English-French dataset. */
return new HashSet<>(Arrays.asList(',', '.', '!', '?')).contains(currChar)
&& prevChar != ' ';
}
String text = preprocessNMT(rawText);
System.out.println(text.substring(0, 80));
Different from character-level tokenization
in :numref:sec_language_model
,
for machine translation
we prefer word-level tokenization here
(state-of-the-art models may use more advanced tokenization techniques).
The following tokenizeNMT
function
tokenizes the the first numExamples
text sequence pairs,
where
each token is either a word or a punctuation mark.
This function returns
two lists of token lists: source
and target
.
Specifically,
source.get(i)
is a list of tokens from the
$i^\mathrm{th}$ text sequence in the source language (English here) and target.get(i)
is that in the target language (French here).
public static Pair<ArrayList<String[]>, ArrayList<String[]>> tokenizeNMT(
String text, Integer numExamples) {
ArrayList<String[]> source = new ArrayList<>();
ArrayList<String[]> target = new ArrayList<>();
int i = 0;
for (String line : text.split("\n")) {
if (numExamples != null && i > numExamples) {
break;
}
String[] parts = line.split("\t");
if (parts.length == 2) {
source.add(parts[0].split(" "));
target.add(parts[1].split(" "));
}
i += 1;
}
return new Pair<>(source, target);
}
Pair<ArrayList<String[]>, ArrayList<String[]>> pair = tokenizeNMT(text.toString(), null);
ArrayList<String[]> source = pair.getKey();
ArrayList<String[]> target = pair.getValue();
for (String[] subArr : source.subList(0, 6)) {
System.out.println(Arrays.toString(subArr));
}
for (String[] subArr : target.subList(0, 6)) {
System.out.println(Arrays.toString(subArr));
}
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.
double[] y1 = new double[source.size()];
for (int i = 0; i < source.size(); i++) y1[i] = source.get(i).length;
double[] y2 = new double[target.size()];
for (int i = 0; i < target.size(); i++) y2[i] = target.get(i).length;
HistogramTrace trace1 =
HistogramTrace.builder(y1).opacity(.75).name("source").nBinsX(20).build();
HistogramTrace trace2 =
HistogramTrace.builder(y2).opacity(.75).name("target").nBinsX(20).build();
Layout layout = Layout.builder().barMode(Layout.BarMode.GROUP).build();
new Figure(layout, trace1, trace2);
Since the machine translation dataset consists of pairs of languages, we can build two vocabularies for both the source language and the target language separately. With word-level tokenization, the vocabulary size will be significantly larger than that using character-level tokenization. To alleviate this, here we treat infrequent tokens that appear less than 2 times as the same unknown ("<unk>") token. Besides that, we specify additional special tokens such as for padding ("<pad>") sequences to the same length in minibatches, and for marking the beginning ("<bos>") or end ("<eos>") of sequences. Such special tokens are commonly used in natural language processing tasks.
Vocab srcVocab =
new Vocab(
source.stream().toArray(String[][]::new),
2,
new String[] {"<pad>", "<bos>", "<eos>"});
System.out.println(srcVocab.length());
: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 numSteps
(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 numSteps
.
If a text sequence has fewer than numSteps
tokens,
we will keep appending the special "<pad>" token
to its end until its length reaches numSteps
.
Otherwise,
we will truncate the text sequence
by only taking its first numSteps
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 truncatePad
function
truncates or pads text sequences as described before.
public static int[] truncatePad(Integer[] integerLine, int numSteps, int paddingToken) {
/* Truncate or pad sequences */
int[] line = Arrays.stream(integerLine).mapToInt(i -> i).toArray();
if (line.length > numSteps) {
return Arrays.copyOfRange(line, 0, numSteps);
}
int[] paddingTokenArr = new int[numSteps - line.length]; // Pad
Arrays.fill(paddingTokenArr, paddingToken);
return IntStream.concat(Arrays.stream(line), Arrays.stream(paddingTokenArr)).toArray();
}
int[] result = truncatePad(srcVocab.getIdxs(source.get(0)), 10, srcVocab.getIdx("<pad>"));
System.out.println(Arrays.toString(result));
Now we define a function to transform text sequences into minibatches for training. We append the special “<eos>” token to the end of every sequence to indicate the end of the sequence. When a model is predicting by generating a sequence token after token, the generation of the “<eos>” token can suggest that the output sequence is complete. Besides, we also record the length of each text sequence excluding the padding tokens. This information will be needed by some models that we will cover later.
public static Pair<NDArray, NDArray> buildArrayNMT(
List<String[]> lines, Vocab vocab, int numSteps) {
/* Transform text sequences of machine translation into minibatches. */
List<Integer[]> linesIntArr = new ArrayList<>();
for (String[] strings : lines) {
linesIntArr.add(vocab.getIdxs(strings));
}
for (int i = 0; i < linesIntArr.size(); i++) {
List<Integer> temp = new ArrayList<>(Arrays.asList(linesIntArr.get(i)));
temp.add(vocab.getIdx("<eos>"));
linesIntArr.set(i, temp.toArray(new Integer[0]));
}
NDManager manager = NDManager.newBaseManager();
NDArray arr = manager.create(new Shape(linesIntArr.size(), numSteps), DataType.INT32);
int row = 0;
for (Integer[] line : linesIntArr) {
NDArray rowArr = manager.create(truncatePad(line, numSteps, vocab.getIdx("<pad>")));
arr.set(new NDIndex("{}:", row), rowArr);
row += 1;
}
NDArray validLen = arr.neq(vocab.getIdx("<pad>")).sum(new int[] {1});
return new Pair<>(arr, validLen);
}
Finally, we define the loadDataNMT
function
to return the data iterator, together with
the vocabularies for both the source language and the target language.
public static Pair<ArrayDataset, Pair<Vocab, Vocab>> loadDataNMT(
int batchSize, int numSteps, int numExamples) throws IOException {
/* Return the iterator and the vocabularies of the translation dataset. */
String text = preprocessNMT(readDataNMT());
Pair<ArrayList<String[]>, ArrayList<String[]>> pair = tokenizeNMT(text, numExamples);
ArrayList<String[]> source = pair.getKey();
ArrayList<String[]> target = pair.getValue();
Vocab srcVocab =
new Vocab(
source.toArray(String[][]::new),
2,
new String[] {"<pad>", "<bos>", "<eos>"});
Vocab tgtVocab =
new Vocab(
target.toArray(String[][]::new),
2,
new String[] {"<pad>", "<bos>", "<eos>"});
Pair<NDArray, NDArray> pairArr = buildArrayNMT(source, srcVocab, numSteps);
NDArray srcArr = pairArr.getKey();
NDArray srcValidLen = pairArr.getValue();
pairArr = buildArrayNMT(target, tgtVocab, numSteps);
NDArray tgtArr = pairArr.getKey();
NDArray tgtValidLen = pairArr.getValue();
ArrayDataset dataset =
new ArrayDataset.Builder()
.setData(srcArr, srcValidLen)
.optLabels(tgtArr, tgtValidLen)
.setSampling(batchSize, true)
.build();
return new Pair<>(dataset, new Pair<>(srcVocab, tgtVocab));
}
Let us read the first minibatch from the English-French dataset.
Pair<ArrayDataset, Pair<Vocab, Vocab>> output = loadDataNMT(2, 8, 600);
ArrayDataset dataset = output.getKey();
srcVocab = output.getValue().getKey();
Vocab tgtVocab = output.getValue().getValue();
Batch batch = dataset.getData(manager).iterator().next();
NDArray X = batch.getData().get(0);
NDArray xValidLen = batch.getData().get(1);
NDArray Y = batch.getLabels().get(0);
NDArray yValidLen = batch.getLabels().get(1);
System.out.println(X);
System.out.println(xValidLen);
System.out.println(Y);
System.out.println(yValidLen);
numExamples
argument in the loadDataNMT
function. How does this affect the vocabulary sizes of the source language and the target language?