Download this tutorial

Google Neural Machine Translation (GNMT)

In this notebook, we are going to train Google NMT on IWSLT 2015 English-Vietnamese Dataset. The building process includes four key steps:

  1. Load and preprocess the dataset

  2. Create a sampler and DataLoader

  3. Build the actual model

  4. Write the training algorithm

This tutorial will guide you through each of the steps and explain briefly how each works. Please remember to click the download button at the top of the page to download the necessary files to follow this tutorial.

Setup

Firstly, we need to setup the environment and import the necessary modules. For this tutorial, a GPU is highly important.

In [1]:
import warnings
warnings.filterwarnings('ignore')

import argparse
import time
import random
import os
import io
import logging
import numpy as np
import mxnet as mx
from mxnet import gluon
import gluonnlp as nlp
import nmt
nlp.utils.check_version('0.7.0')

Next, we need to specify the hyperparameters for the dataset, the model, and for training and testing time.

In [2]:
np.random.seed(100)
random.seed(100)
mx.random.seed(10000)
ctx = mx.gpu(0)

# parameters for dataset
dataset = 'IWSLT2015'
src_lang, tgt_lang = 'en', 'vi'
src_max_len, tgt_max_len = 50, 50

# parameters for model
num_hidden = 512
num_layers = 2
num_bi_layers = 1
dropout = 0.2

# parameters for training
batch_size, test_batch_size = 128, 32
num_buckets = 5
epochs = 1
clip = 5
lr = 0.001
lr_update_factor = 0.5
log_interval = 10
save_dir = 'gnmt_en_vi_u512'

#parameters for testing
beam_size = 10
lp_alpha = 1.0
lp_k = 5

nmt.utils.logging_config(save_dir)
All Logs will be saved to gnmt_en_vi_u512/<ipython-input-2-4699ac3a1bfb>.log
Out[2]:
'gnmt_en_vi_u512'

Loading and processing the dataset

The following shows how to process the dataset and cache the processed dataset for future use. The processing steps include the following:

  1. Clipping the source and target sequences

  2. Splitting the string input to a list of tokens

  3. Mapping the string token onto its integer index in the vocabulary

  4. Appending the end-of-sentence (EOS) token to source sentence and adding BOS and EOS tokens to the target sentence

Firstly, we load and cache the dataset with the two helper functions cache_dataset and load_cached_dataset. The functions are straightforward and well commented so no further explanation will be given.

In [3]:
def cache_dataset(dataset, prefix):
    """Cache the processed npy dataset  the dataset into an npz file

    Parameters
    ----------
    dataset : gluon.data.SimpleDataset
    file_path : str
    """
    if not os.path.exists(nmt._constants.CACHE_PATH):
        os.makedirs(nmt._constants.CACHE_PATH)
    src_data = np.concatenate([e[0] for e in dataset])
    tgt_data = np.concatenate([e[1] for e in dataset])
    src_cumlen = np.cumsum([0]+[len(e[0]) for e in dataset])
    tgt_cumlen = np.cumsum([0]+[len(e[1]) for e in dataset])
    np.savez(os.path.join(nmt._constants.CACHE_PATH, prefix + '.npz'),
             src_data=src_data, tgt_data=tgt_data,
             src_cumlen=src_cumlen, tgt_cumlen=tgt_cumlen)


def load_cached_dataset(prefix):
    cached_file_path = os.path.join(nmt._constants.CACHE_PATH, prefix + '.npz')
    if os.path.exists(cached_file_path):
        print('Load cached data from {}'.format(cached_file_path))
        npz_data = np.load(cached_file_path)
        src_data, tgt_data, src_cumlen, tgt_cumlen = [npz_data[n] for n in
                ['src_data', 'tgt_data', 'src_cumlen', 'tgt_cumlen']]
        src_data = np.array([src_data[low:high] for low, high in zip(src_cumlen[:-1], src_cumlen[1:])])
        tgt_data = np.array([tgt_data[low:high] for low, high in zip(tgt_cumlen[:-1], tgt_cumlen[1:])])
        return gluon.data.ArrayDataset(np.array(src_data), np.array(tgt_data))
    else:
        return None

Next, we write the class TrainValDataTransform to have easy access to transforming and clipping the source and target sentences. This class also adds the EOS and BOS tokens for cleaner data. Please refer to the comments in the code for more details.

In [4]:
class TrainValDataTransform(object):
    """Transform the machine translation dataset.

    Clip source and the target sentences to the maximum length. For the source sentence, append the
    EOS. For the target sentence, append BOS and EOS.

    Parameters
    ----------
    src_vocab : Vocab
    tgt_vocab : Vocab
    src_max_len : int
    tgt_max_len : int
    """

    def __init__(self, src_vocab, tgt_vocab, src_max_len, tgt_max_len):
        # On initialization of the class, we set the class variables
        self._src_vocab = src_vocab
        self._tgt_vocab = tgt_vocab
        self._src_max_len = src_max_len
        self._tgt_max_len = tgt_max_len

    def __call__(self, src, tgt):
        # On actual calling of the class, we perform the clipping then the appending of the EOS and BOS tokens.
        if self._src_max_len > 0:
            src_sentence = self._src_vocab[src.split()[:self._src_max_len]]
        else:
            src_sentence = self._src_vocab[src.split()]
        if self._tgt_max_len > 0:
            tgt_sentence = self._tgt_vocab[tgt.split()[:self._tgt_max_len]]
        else:
            tgt_sentence = self._tgt_vocab[tgt.split()]
        src_sentence.append(self._src_vocab[self._src_vocab.eos_token])
        tgt_sentence.insert(0, self._tgt_vocab[self._tgt_vocab.bos_token])
        tgt_sentence.append(self._tgt_vocab[self._tgt_vocab.eos_token])
        src_npy = np.array(src_sentence, dtype=np.int32)
        tgt_npy = np.array(tgt_sentence, dtype=np.int32)
        return src_npy, tgt_npy

We leverage the class written above to create a helper function that processes the dataset in very few lines of code.

In [5]:
def process_dataset(dataset, src_vocab, tgt_vocab, src_max_len=-1, tgt_max_len=-1):
    start = time.time()
    dataset_processed = dataset.transform(TrainValDataTransform(src_vocab, tgt_vocab,
                                                                src_max_len,
                                                                tgt_max_len), lazy=False)
    end = time.time()
    print('Processing time spent: {}'.format(end - start))
    return dataset_processed

Here we define a function load_translation_data that combines all the above steps to load the data, check if it’s been processed, and if not, process the data. The method returns all of the required data for training, validating, and testing our model. Please refer to the comments in the code for more information on what each piece does.

In [6]:
def load_translation_data(dataset, src_lang='en', tgt_lang='vi'):
    """Load translation dataset

    Parameters
    ----------
    dataset : str
    src_lang : str, default 'en'
    tgt_lang : str, default 'vi'

    Returns
    -------
    data_train_processed : Dataset
        The preprocessed training sentence pairs
    data_val_processed : Dataset
        The preprocessed validation sentence pairs
    data_test_processed : Dataset
        The preprocessed test sentence pairs
    val_tgt_sentences : list
        The target sentences in the validation set
    test_tgt_sentences : list
        The target sentences in the test set
    src_vocab : Vocab
        Vocabulary of the source language
    tgt_vocab : Vocab
        Vocabulary of the target language
    """
    common_prefix = 'IWSLT2015_{}_{}_{}_{}'.format(src_lang, tgt_lang,
                                                   src_max_len, tgt_max_len)

    # Load the three datasets from files
    data_train = nlp.data.IWSLT2015('train', src_lang=src_lang, tgt_lang=tgt_lang)
    data_val = nlp.data.IWSLT2015('val', src_lang=src_lang, tgt_lang=tgt_lang)
    data_test = nlp.data.IWSLT2015('test', src_lang=src_lang, tgt_lang=tgt_lang)
    src_vocab, tgt_vocab = data_train.src_vocab, data_train.tgt_vocab
    data_train_processed = load_cached_dataset(common_prefix + '_train')

    # Check if each dataset has been processed or not, and if not, process and cache them.
    if not data_train_processed:
        data_train_processed = process_dataset(data_train, src_vocab, tgt_vocab,
                                               src_max_len, tgt_max_len)
        cache_dataset(data_train_processed, common_prefix + '_train')
    data_val_processed = load_cached_dataset(common_prefix + '_val')
    if not data_val_processed:
        data_val_processed = process_dataset(data_val, src_vocab, tgt_vocab)
        cache_dataset(data_val_processed, common_prefix + '_val')
    data_test_processed = load_cached_dataset(common_prefix + '_test')
    if not data_test_processed:
        data_test_processed = process_dataset(data_test, src_vocab, tgt_vocab)
        cache_dataset(data_test_processed, common_prefix + '_test')

    # Pull out the target sentences for both test and validation
    fetch_tgt_sentence = lambda src, tgt: tgt.split()
    val_tgt_sentences = list(data_val.transform(fetch_tgt_sentence))
    test_tgt_sentences = list(data_test.transform(fetch_tgt_sentence))

    # Return all of the necessary pieces we can extract from the data for training our model
    return data_train_processed, data_val_processed, data_test_processed, \
           val_tgt_sentences, test_tgt_sentences, src_vocab, tgt_vocab

We define a last helper function get_data_lengths to get the length of the datasets, again, for simplified cleaner code later.

In [7]:
def get_data_lengths(dataset):
    return list(dataset.transform(lambda srg, tgt: (len(srg), len(tgt))))

And for the last step of processing, we leverage all of our helper functions to keep the code concise and to these 15-20 lines for use in our main. This does all of the aforementioned processing along with storing the necessary information in memory for training our model.

In [8]:
data_train, data_val, data_test, val_tgt_sentences, test_tgt_sentences, src_vocab, tgt_vocab\
    = load_translation_data(dataset=dataset, src_lang=src_lang, tgt_lang=tgt_lang)
data_train_lengths = get_data_lengths(data_train)
data_val_lengths = get_data_lengths(data_val)
data_test_lengths = get_data_lengths(data_test)

with io.open(os.path.join(save_dir, 'val_gt.txt'), 'w', encoding='utf-8') as of:
    for ele in val_tgt_sentences:
        of.write(' '.join(ele) + '\n')

with io.open(os.path.join(save_dir, 'test_gt.txt'), 'w', encoding='utf-8') as of:
    for ele in test_tgt_sentences:
        of.write(' '.join(ele) + '\n')


data_train = data_train.transform(lambda src, tgt: (src, tgt, len(src), len(tgt)), lazy=False)
data_val = gluon.data.SimpleDataset([(ele[0], ele[1], len(ele[0]), len(ele[1]), i)
                                     for i, ele in enumerate(data_val)])
data_test = gluon.data.SimpleDataset([(ele[0], ele[1], len(ele[0]), len(ele[1]), i)
                                      for i, ele in enumerate(data_test)])
Downloading /root/.mxnet/datasets/iwslt2015/iwslt15.zip from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/dataset/iwslt2015/iwslt15.zip...
Processing time spent: 5.5106165409088135
Processing time spent: 0.06022286415100098
Processing time spent: 0.05553174018859863

Sampler and DataLoader construction

Now, we have obtained and stored all of the relevant data information. The next step is to construct the sampler and DataLoader. The first step is to use the batchify function, which pads and stacks sequences to form mini-batches.

In [9]:
train_batchify_fn = nlp.data.batchify.Tuple(nlp.data.batchify.Pad(),
                                            nlp.data.batchify.Pad(),
                                            nlp.data.batchify.Stack(dtype='float32'),
                                            nlp.data.batchify.Stack(dtype='float32'))
test_batchify_fn = nlp.data.batchify.Tuple(nlp.data.batchify.Pad(),
                                           nlp.data.batchify.Pad(),
                                           nlp.data.batchify.Stack(dtype='float32'),
                                           nlp.data.batchify.Stack(dtype='float32'),
                                           nlp.data.batchify.Stack())

We can then construct bucketing samplers, which generate batches by grouping sequences with similar lengths. Here, the bucketing scheme is empirically determined.

In [10]:
bucket_scheme = nlp.data.ExpWidthBucket(bucket_len_step=1.2)
train_batch_sampler = nlp.data.FixedBucketSampler(lengths=data_train_lengths,
                                                  batch_size=batch_size,
                                                  num_buckets=num_buckets,
                                                  shuffle=True,
                                                  bucket_scheme=bucket_scheme)
logging.info('Train Batch Sampler:\n{}'.format(train_batch_sampler.stats()))
val_batch_sampler = nlp.data.FixedBucketSampler(lengths=data_val_lengths,
                                                batch_size=test_batch_size,
                                                num_buckets=num_buckets,
                                                shuffle=False)
logging.info('Valid Batch Sampler:\n{}'.format(val_batch_sampler.stats()))
test_batch_sampler = nlp.data.FixedBucketSampler(lengths=data_test_lengths,
                                                 batch_size=test_batch_size,
                                                 num_buckets=num_buckets,
                                                 shuffle=False)
logging.info('Test Batch Sampler:\n{}'.format(test_batch_sampler.stats()))
2019-10-11 21:36:02,261 - root - Train Batch Sampler:
FixedBucketSampler:
  sample_num=133166, batch_num=1043
  key=[(9, 10), (16, 17), (26, 27), (37, 38), (51, 52)]
  cnt=[11414, 34897, 37760, 23480, 25615]
  batch_size=[128, 128, 128, 128, 128]
2019-10-11 21:36:02,264 - root - Valid Batch Sampler:
FixedBucketSampler:
  sample_num=1553, batch_num=52
  key=[(22, 28), (40, 52), (58, 76), (76, 100), (94, 124)]
  cnt=[1037, 432, 67, 10, 7]
  batch_size=[32, 32, 32, 32, 32]
2019-10-11 21:36:02,267 - root - Test Batch Sampler:
FixedBucketSampler:
  sample_num=1268, batch_num=42
  key=[(23, 29), (43, 53), (63, 77), (83, 101), (103, 125)]
  cnt=[770, 381, 84, 26, 7]
  batch_size=[32, 32, 32, 32, 32]

Given the samplers, we can create a DataLoader, which is iterable. This simply is a data construct (an iterator) that can feed the model batches at a time. For more information refer to this page.

In [11]:
train_data_loader = gluon.data.DataLoader(data_train,
                                          batch_sampler=train_batch_sampler,
                                          batchify_fn=train_batchify_fn,
                                          num_workers=4)
val_data_loader = gluon.data.DataLoader(data_val,
                                        batch_sampler=val_batch_sampler,
                                        batchify_fn=test_batchify_fn,
                                        num_workers=4)
test_data_loader = gluon.data.DataLoader(data_test,
                                         batch_sampler=test_batch_sampler,
                                         batchify_fn=test_batchify_fn,
                                         num_workers=4)

Building the GNMT model

After obtaining the DataLoader, we can finally build the model. The GNMT encoder and decoder can be easily constructed by calling get_gnmt_encoder_decoder function. Then, we feed the encoder and decoder to the NMTModel to construct the GNMT model.

model.hybridize allows computation to be done using the symbolic backend. To understand what it means to be “hybridized,” please refer to this page on MXNet hybridization and its advantages.

In [12]:
encoder, decoder = nmt.gnmt.get_gnmt_encoder_decoder(hidden_size=num_hidden,
                                                     dropout=dropout,
                                                     num_layers=num_layers,
                                                     num_bi_layers=num_bi_layers)
model = nlp.model.translation.NMTModel(src_vocab=src_vocab, tgt_vocab=tgt_vocab, encoder=encoder,
                                       decoder=decoder, embed_size=num_hidden, prefix='gnmt_')
model.initialize(init=mx.init.Uniform(0.1), ctx=ctx)
static_alloc = True
model.hybridize(static_alloc=static_alloc)
logging.info(model)

# Due to the paddings, we need to mask out the losses corresponding to padding tokens.
loss_function = nlp.loss.MaskedSoftmaxCELoss()
loss_function.hybridize(static_alloc=static_alloc)
2019-10-11 21:36:06,019 - root - NMTModel(
  (encoder): GNMTEncoder(
    (dropout_layer): Dropout(p = 0.2, axes=())
    (rnn_cells): HybridSequential(
      (0): BidirectionalCell(forward=LSTMCell(None -> 2048), backward=LSTMCell(None -> 2048))
      (1): LSTMCell(None -> 2048)
    )
  )
  (decoder): GNMTDecoder(
    (attention_cell): DotProductAttentionCell(
      (_dropout_layer): Dropout(p = 0.0, axes=())
      (_proj_query): Dense(None -> 512, linear)
    )
    (dropout_layer): Dropout(p = 0.2, axes=())
    (rnn_cells): HybridSequential(
      (0): LSTMCell(None -> 2048)
      (1): LSTMCell(None -> 2048)
    )
  )
  (src_embed): HybridSequential(
    (0): Embedding(17191 -> 512, float32)
    (1): Dropout(p = 0.0, axes=())
  )
  (tgt_embed): HybridSequential(
    (0): Embedding(7709 -> 512, float32)
    (1): Dropout(p = 0.0, axes=())
  )
  (tgt_proj): Dense(None -> 7709, linear)
)

Here, we build the BeamSearchTranslator and define a predetermined BeamSearchScorer as the heuristical mechanism for the search. For more information on Beam Search and its applications to NLP, check here.

In [13]:
translator = nmt.translation.BeamSearchTranslator(model=model, beam_size=beam_size,
                                                  scorer=nlp.model.BeamSearchScorer(alpha=lp_alpha,
                                                                                    K=lp_k),
                                                  max_length=tgt_max_len + 100)
logging.info('Use beam_size={}, alpha={}, K={}'.format(beam_size, lp_alpha, lp_k))
2019-10-11 21:36:06,032 - root - Use beam_size=10, alpha=1.0, K=5

We define the evaluation function as shown in the code block below. The evaluate function uses the beam search translator to generate outputs for the validation and testing datasets. Please refer to the comments in the code for more information on what each piece does. In addition, we add the write_sentences helper method to easily output the sentences.

In [14]:
def evaluate(data_loader):
    """Evaluate given the data loader

    Parameters
    ----------
    data_loader : gluon.data.DataLoader

    Returns
    -------
    avg_loss : float
        Average loss
    real_translation_out : list of list of str
        The translation output
    """
    translation_out = []
    all_inst_ids = []
    avg_loss_denom = 0
    avg_loss = 0.0

    for _, (src_seq, tgt_seq, src_valid_length, tgt_valid_length, inst_ids) \
            in enumerate(data_loader):
        src_seq = src_seq.as_in_context(ctx)
        tgt_seq = tgt_seq.as_in_context(ctx)
        src_valid_length = src_valid_length.as_in_context(ctx)
        tgt_valid_length = tgt_valid_length.as_in_context(ctx)

        # Calculate Loss
        out, _ = model(src_seq, tgt_seq[:, :-1], src_valid_length, tgt_valid_length - 1)
        loss = loss_function(out, tgt_seq[:, 1:], tgt_valid_length - 1).mean().asscalar()
        all_inst_ids.extend(inst_ids.asnumpy().astype(np.int32).tolist())
        avg_loss += loss * (tgt_seq.shape[1] - 1)
        avg_loss_denom += (tgt_seq.shape[1] - 1)

        # Translate the sequences and score them
        samples, _, sample_valid_length =\
            translator.translate(src_seq=src_seq, src_valid_length=src_valid_length)
        max_score_sample = samples[:, 0, :].asnumpy()
        sample_valid_length = sample_valid_length[:, 0].asnumpy()

        # Iterate through the tokens and stitch the tokens together for the sentence
        for i in range(max_score_sample.shape[0]):
            translation_out.append(
                [tgt_vocab.idx_to_token[ele] for ele in
                 max_score_sample[i][1:(sample_valid_length[i] - 1)]])

    # Calculate the average loss and initialize a None-filled translation list
    avg_loss = avg_loss / avg_loss_denom
    real_translation_out = [None for _ in range(len(all_inst_ids))]

    # Combine all the words/tokens into a sentence for the final translation
    for ind, sentence in zip(all_inst_ids, translation_out):
        real_translation_out[ind] = sentence

    # Return the loss and the translation
    return avg_loss, real_translation_out


def write_sentences(sentences, file_path):
    with io.open(file_path, 'w', encoding='utf-8') as of:
        for sent in sentences:
            of.write(' '.join(sent) + '\n')

Training

Before entering the training stage, we need to create a trainer for updating the parameters based on the loss. In the following example, we create a trainer that uses the ADAM optimizer.

In [15]:
trainer = gluon.Trainer(model.collect_params(), 'adam', {'learning_rate': lr})

We can then write the training loop. During the training, we evaluate on the validation and testing datasets every epoch, and record the parameters that give the highest Bilingual Evaluation Understudy Score (BLEU) score on the validation dataset. Before performing forward and backward computation, we first use the as_in_context function to copy the mini-batch to the GPU. The statement with mx.autograd.record() tells Gluon’s backend to compute the gradients for the part inside the block.

In [16]:
best_valid_bleu = 0.0

# Run through each epoch
for epoch_id in range(epochs):
    log_avg_loss = 0
    log_avg_gnorm = 0
    log_wc = 0
    log_start_time = time.time()

    # Iterate through each batch
    for batch_id, (src_seq, tgt_seq, src_valid_length, tgt_valid_length)\
            in enumerate(train_data_loader):

        src_seq = src_seq.as_in_context(ctx)
        tgt_seq = tgt_seq.as_in_context(ctx)
        src_valid_length = src_valid_length.as_in_context(ctx)
        tgt_valid_length = tgt_valid_length.as_in_context(ctx)

        # Compute gradients and losses
        with mx.autograd.record():
            out, _ = model(src_seq, tgt_seq[:, :-1], src_valid_length, tgt_valid_length - 1)
            loss = loss_function(out, tgt_seq[:, 1:], tgt_valid_length - 1).mean()
            loss = loss * (tgt_seq.shape[1] - 1) / (tgt_valid_length - 1).mean()
            loss.backward()

        grads = [p.grad(ctx) for p in model.collect_params().values()]
        gnorm = gluon.utils.clip_global_norm(grads, clip)
        trainer.step(1)
        src_wc = src_valid_length.sum().asscalar()
        tgt_wc = (tgt_valid_length - 1).sum().asscalar()
        step_loss = loss.asscalar()
        log_avg_loss += step_loss
        log_avg_gnorm += gnorm
        log_wc += src_wc + tgt_wc
        if (batch_id + 1) % log_interval == 0:
            wps = log_wc / (time.time() - log_start_time)
            logging.info('[Epoch {} Batch {}/{}] loss={:.4f}, ppl={:.4f}, gnorm={:.4f}, '
                         'throughput={:.2f}K wps, wc={:.2f}K'
                         .format(epoch_id, batch_id + 1, len(train_data_loader),
                                 log_avg_loss / log_interval,
                                 np.exp(log_avg_loss / log_interval),
                                 log_avg_gnorm / log_interval,
                                 wps / 1000, log_wc / 1000))
            log_start_time = time.time()
            log_avg_loss = 0
            log_avg_gnorm = 0
            log_wc = 0

    # Evaluate the losses on validation and test datasets and find the corresponding BLEU score and log it
    valid_loss, valid_translation_out = evaluate(val_data_loader)
    valid_bleu_score, _, _, _, _ = nmt.bleu.compute_bleu([val_tgt_sentences], valid_translation_out)
    logging.info('[Epoch {}] valid Loss={:.4f}, valid ppl={:.4f}, valid bleu={:.2f}'
                 .format(epoch_id, valid_loss, np.exp(valid_loss), valid_bleu_score * 100))
    test_loss, test_translation_out = evaluate(test_data_loader)
    test_bleu_score, _, _, _, _ = nmt.bleu.compute_bleu([test_tgt_sentences], test_translation_out)
    logging.info('[Epoch {}] test Loss={:.4f}, test ppl={:.4f}, test bleu={:.2f}'
                 .format(epoch_id, test_loss, np.exp(test_loss), test_bleu_score * 100))

    # Output the sentences we predicted on the validation and test datasets
    write_sentences(valid_translation_out,
                    os.path.join(save_dir, 'epoch{:d}_valid_out.txt').format(epoch_id))
    write_sentences(test_translation_out,
                    os.path.join(save_dir, 'epoch{:d}_test_out.txt').format(epoch_id))

    # Save the model if the BLEU score is better than the previous best
    if valid_bleu_score > best_valid_bleu:
        best_valid_bleu = valid_bleu_score
        save_path = os.path.join(save_dir, 'valid_best.params')
        logging.info('Save best parameters to {}'.format(save_path))
        model.save_parameters(save_path)

    # Update the learning rate based on the number of epochs that have passed
    if epoch_id + 1 >= (epochs * 2) // 3:
        new_lr = trainer.learning_rate * lr_update_factor
        logging.info('Learning rate change to {}'.format(new_lr))
        trainer.set_learning_rate(new_lr)
2019-10-11 21:36:08,104 - root - [Epoch 0 Batch 10/1043] loss=7.7676, ppl=2362.8908, gnorm=1.4796, throughput=26.93K wps, wc=54.27K
2019-10-11 21:36:09,368 - root - [Epoch 0 Batch 20/1043] loss=6.3611, ppl=578.9110, gnorm=1.5742, throughput=39.78K wps, wc=50.20K
2019-10-11 21:36:10,973 - root - [Epoch 0 Batch 30/1043] loss=6.3601, ppl=578.3155, gnorm=0.7517, throughput=42.26K wps, wc=67.78K
2019-10-11 21:36:12,536 - root - [Epoch 0 Batch 40/1043] loss=6.1855, ppl=485.6495, gnorm=0.6348, throughput=40.45K wps, wc=63.19K
2019-10-11 21:36:14,063 - root - [Epoch 0 Batch 50/1043] loss=6.1790, ppl=482.5140, gnorm=0.3973, throughput=40.61K wps, wc=61.93K
2019-10-11 21:36:15,499 - root - [Epoch 0 Batch 60/1043] loss=6.0819, ppl=437.8770, gnorm=0.6059, throughput=41.28K wps, wc=59.19K
2019-10-11 21:36:17,231 - root - [Epoch 0 Batch 70/1043] loss=6.1416, ppl=464.8015, gnorm=0.4327, throughput=42.18K wps, wc=72.99K
2019-10-11 21:36:18,796 - root - [Epoch 0 Batch 80/1043] loss=6.0572, ppl=427.1715, gnorm=0.3842, throughput=41.30K wps, wc=64.58K
2019-10-11 21:36:20,135 - root - [Epoch 0 Batch 90/1043] loss=5.9290, ppl=375.7702, gnorm=0.3821, throughput=39.65K wps, wc=53.02K
2019-10-11 21:36:21,549 - root - [Epoch 0 Batch 100/1043] loss=5.8691, ppl=353.9285, gnorm=0.4121, throughput=42.06K wps, wc=59.42K
2019-10-11 21:36:23,109 - root - [Epoch 0 Batch 110/1043] loss=5.8672, ppl=353.2725, gnorm=0.3576, throughput=42.02K wps, wc=65.50K
2019-10-11 21:36:24,538 - root - [Epoch 0 Batch 120/1043] loss=5.8555, ppl=349.1445, gnorm=0.3396, throughput=40.92K wps, wc=58.43K
2019-10-11 21:36:26,162 - root - [Epoch 0 Batch 130/1043] loss=5.9227, ppl=373.4105, gnorm=0.3729, throughput=36.62K wps, wc=59.39K
2019-10-11 21:36:27,740 - root - [Epoch 0 Batch 140/1043] loss=5.8796, ppl=357.6661, gnorm=0.2840, throughput=38.79K wps, wc=61.18K
2019-10-11 21:36:29,188 - root - [Epoch 0 Batch 150/1043] loss=5.8039, ppl=331.5820, gnorm=0.2895, throughput=38.96K wps, wc=56.34K
2019-10-11 21:36:30,715 - root - [Epoch 0 Batch 160/1043] loss=5.7360, ppl=309.8295, gnorm=0.3834, throughput=37.97K wps, wc=57.93K
2019-10-11 21:36:32,303 - root - [Epoch 0 Batch 170/1043] loss=5.7510, ppl=314.5042, gnorm=0.3103, throughput=40.62K wps, wc=64.42K
2019-10-11 21:36:33,494 - root - [Epoch 0 Batch 180/1043] loss=5.4506, ppl=232.8866, gnorm=0.3432, throughput=37.27K wps, wc=44.31K
2019-10-11 21:36:35,062 - root - [Epoch 0 Batch 190/1043] loss=5.6019, ppl=270.9381, gnorm=0.3587, throughput=39.86K wps, wc=62.45K
2019-10-11 21:36:36,414 - root - [Epoch 0 Batch 200/1043] loss=5.4951, ppl=243.4914, gnorm=0.3420, throughput=40.17K wps, wc=54.24K
2019-10-11 21:36:37,749 - root - [Epoch 0 Batch 210/1043] loss=5.3113, ppl=202.6213, gnorm=0.4617, throughput=39.51K wps, wc=52.68K
2019-10-11 21:36:39,014 - root - [Epoch 0 Batch 220/1043] loss=5.2986, ppl=200.0586, gnorm=0.3575, throughput=39.94K wps, wc=50.47K
2019-10-11 21:36:40,509 - root - [Epoch 0 Batch 230/1043] loss=5.2991, ppl=200.1598, gnorm=0.4078, throughput=41.29K wps, wc=61.65K
2019-10-11 21:36:41,935 - root - [Epoch 0 Batch 240/1043] loss=5.2974, ppl=199.8198, gnorm=0.3500, throughput=40.95K wps, wc=58.32K
2019-10-11 21:36:43,635 - root - [Epoch 0 Batch 250/1043] loss=5.4192, ppl=225.7033, gnorm=0.3043, throughput=41.72K wps, wc=70.84K
2019-10-11 21:36:45,078 - root - [Epoch 0 Batch 260/1043] loss=5.2749, ppl=195.3753, gnorm=0.3685, throughput=41.75K wps, wc=60.22K
2019-10-11 21:36:46,808 - root - [Epoch 0 Batch 270/1043] loss=5.3724, ppl=215.3891, gnorm=0.2905, throughput=42.22K wps, wc=72.96K
2019-10-11 21:36:48,344 - root - [Epoch 0 Batch 280/1043] loss=5.2446, ppl=189.5370, gnorm=0.2720, throughput=39.62K wps, wc=60.80K
2019-10-11 21:36:49,523 - root - [Epoch 0 Batch 290/1043] loss=4.9690, ppl=143.8873, gnorm=0.3475, throughput=38.90K wps, wc=45.79K
2019-10-11 21:36:50,934 - root - [Epoch 0 Batch 300/1043] loss=5.0739, ppl=159.8025, gnorm=0.3238, throughput=41.91K wps, wc=59.05K
2019-10-11 21:36:52,435 - root - [Epoch 0 Batch 310/1043] loss=5.0908, ppl=162.5122, gnorm=0.2890, throughput=41.07K wps, wc=61.58K
2019-10-11 21:36:53,785 - root - [Epoch 0 Batch 320/1043] loss=4.9666, ppl=143.5367, gnorm=0.3037, throughput=39.38K wps, wc=53.10K
2019-10-11 21:36:55,307 - root - [Epoch 0 Batch 330/1043] loss=5.0227, ppl=151.8277, gnorm=0.2923, throughput=40.37K wps, wc=61.37K
2019-10-11 21:36:56,748 - root - [Epoch 0 Batch 340/1043] loss=5.0462, ppl=155.4309, gnorm=0.2800, throughput=39.50K wps, wc=56.88K
2019-10-11 21:36:58,186 - root - [Epoch 0 Batch 350/1043] loss=4.9100, ppl=135.6395, gnorm=0.3177, throughput=38.21K wps, wc=54.86K
2019-10-11 21:36:59,729 - root - [Epoch 0 Batch 360/1043] loss=5.0255, ppl=152.2445, gnorm=0.2879, throughput=41.85K wps, wc=64.55K
2019-10-11 21:37:01,373 - root - [Epoch 0 Batch 370/1043] loss=4.8954, ppl=133.6707, gnorm=0.3112, throughput=40.80K wps, wc=66.97K
2019-10-11 21:37:02,734 - root - [Epoch 0 Batch 380/1043] loss=4.8063, ppl=122.2752, gnorm=0.2958, throughput=38.81K wps, wc=52.79K
2019-10-11 21:37:04,041 - root - [Epoch 0 Batch 390/1043] loss=4.7849, ppl=119.6837, gnorm=0.3415, throughput=39.04K wps, wc=50.94K
2019-10-11 21:37:05,292 - root - [Epoch 0 Batch 400/1043] loss=4.6345, ppl=102.9775, gnorm=0.3773, throughput=38.59K wps, wc=48.22K
2019-10-11 21:37:06,543 - root - [Epoch 0 Batch 410/1043] loss=4.8019, ppl=121.7458, gnorm=0.3209, throughput=38.64K wps, wc=48.27K
2019-10-11 21:37:08,023 - root - [Epoch 0 Batch 420/1043] loss=4.8333, ppl=125.6294, gnorm=0.3212, throughput=38.00K wps, wc=56.14K
2019-10-11 21:37:09,665 - root - [Epoch 0 Batch 430/1043] loss=4.8755, ppl=131.0356, gnorm=0.3049, throughput=42.27K wps, wc=69.33K
2019-10-11 21:37:11,304 - root - [Epoch 0 Batch 440/1043] loss=4.7747, ppl=118.4706, gnorm=0.2912, throughput=40.96K wps, wc=67.08K
2019-10-11 21:37:12,639 - root - [Epoch 0 Batch 450/1043] loss=4.6695, ppl=106.6450, gnorm=0.3057, throughput=40.25K wps, wc=53.68K
2019-10-11 21:37:13,916 - root - [Epoch 0 Batch 460/1043] loss=4.4654, ppl=86.9524, gnorm=0.3602, throughput=39.51K wps, wc=50.38K
2019-10-11 21:37:15,413 - root - [Epoch 0 Batch 470/1043] loss=4.7366, ppl=114.0458, gnorm=0.2981, throughput=40.59K wps, wc=60.70K
2019-10-11 21:37:16,742 - root - [Epoch 0 Batch 480/1043] loss=4.3846, ppl=80.2091, gnorm=0.3479, throughput=40.72K wps, wc=54.04K
2019-10-11 21:37:17,952 - root - [Epoch 0 Batch 490/1043] loss=4.4868, ppl=88.8347, gnorm=0.3920, throughput=38.34K wps, wc=46.32K
2019-10-11 21:37:19,208 - root - [Epoch 0 Batch 500/1043] loss=4.5352, ppl=93.2402, gnorm=0.2991, throughput=38.69K wps, wc=48.55K
2019-10-11 21:37:20,288 - root - [Epoch 0 Batch 510/1043] loss=4.3114, ppl=74.5458, gnorm=0.3361, throughput=38.61K wps, wc=41.62K
2019-10-11 21:37:21,349 - root - [Epoch 0 Batch 520/1043] loss=4.2189, ppl=67.9553, gnorm=0.9955, throughput=37.75K wps, wc=39.98K
2019-10-11 21:37:22,830 - root - [Epoch 0 Batch 530/1043] loss=4.6506, ppl=104.6509, gnorm=0.3478, throughput=39.59K wps, wc=58.58K
2019-10-11 21:37:24,113 - root - [Epoch 0 Batch 540/1043] loss=4.5211, ppl=91.9385, gnorm=0.3462, throughput=39.60K wps, wc=50.72K
2019-10-11 21:37:25,673 - root - [Epoch 0 Batch 550/1043] loss=4.5431, ppl=93.9786, gnorm=0.3433, throughput=40.39K wps, wc=62.95K
2019-10-11 21:37:26,851 - root - [Epoch 0 Batch 560/1043] loss=4.3212, ppl=75.2826, gnorm=0.3519, throughput=39.24K wps, wc=46.13K
2019-10-11 21:37:28,374 - root - [Epoch 0 Batch 570/1043] loss=4.3355, ppl=76.3647, gnorm=0.3066, throughput=40.17K wps, wc=61.12K
2019-10-11 21:37:29,763 - root - [Epoch 0 Batch 580/1043] loss=4.3548, ppl=77.8487, gnorm=0.3106, throughput=39.96K wps, wc=55.43K
2019-10-11 21:37:31,523 - root - [Epoch 0 Batch 590/1043] loss=4.5831, ppl=97.8166, gnorm=0.2712, throughput=42.03K wps, wc=73.93K
2019-10-11 21:37:32,955 - root - [Epoch 0 Batch 600/1043] loss=4.4829, ppl=88.4936, gnorm=0.2782, throughput=38.99K wps, wc=55.80K
2019-10-11 21:37:34,270 - root - [Epoch 0 Batch 610/1043] loss=4.3033, ppl=73.9404, gnorm=0.3320, throughput=39.83K wps, wc=52.28K
2019-10-11 21:37:36,005 - root - [Epoch 0 Batch 620/1043] loss=4.5532, ppl=94.9339, gnorm=0.2835, throughput=41.75K wps, wc=72.39K
2019-10-11 21:37:36,973 - root - [Epoch 0 Batch 630/1043] loss=4.0419, ppl=56.9340, gnorm=0.3385, throughput=35.64K wps, wc=34.44K
2019-10-11 21:37:38,404 - root - [Epoch 0 Batch 640/1043] loss=4.3252, ppl=75.5829, gnorm=0.3175, throughput=40.12K wps, wc=57.32K
2019-10-11 21:37:40,029 - root - [Epoch 0 Batch 650/1043] loss=4.4597, ppl=86.4636, gnorm=0.2738, throughput=40.91K wps, wc=66.42K
2019-10-11 21:37:41,220 - root - [Epoch 0 Batch 660/1043] loss=4.1899, ppl=66.0165, gnorm=0.3416, throughput=37.34K wps, wc=44.42K
2019-10-11 21:37:43,020 - root - [Epoch 0 Batch 670/1043] loss=4.5826, ppl=97.7651, gnorm=0.2507, throughput=43.20K wps, wc=77.68K
2019-10-11 21:37:44,508 - root - [Epoch 0 Batch 680/1043] loss=4.4134, ppl=82.5487, gnorm=0.2794, throughput=39.70K wps, wc=59.02K
2019-10-11 21:37:45,805 - root - [Epoch 0 Batch 690/1043] loss=4.2060, ppl=67.0879, gnorm=0.3235, throughput=39.03K wps, wc=50.54K
2019-10-11 21:37:47,123 - root - [Epoch 0 Batch 700/1043] loss=4.2920, ppl=73.1147, gnorm=0.3057, throughput=39.82K wps, wc=52.45K
2019-10-11 21:37:48,246 - root - [Epoch 0 Batch 710/1043] loss=4.1729, ppl=64.9030, gnorm=0.3506, throughput=36.87K wps, wc=41.32K
2019-10-11 21:37:49,554 - root - [Epoch 0 Batch 720/1043] loss=4.2519, ppl=70.2403, gnorm=0.3156, throughput=38.32K wps, wc=50.09K
2019-10-11 21:37:50,904 - root - [Epoch 0 Batch 730/1043] loss=4.1860, ppl=65.7624, gnorm=0.3219, throughput=38.59K wps, wc=52.02K
2019-10-11 21:37:52,390 - root - [Epoch 0 Batch 740/1043] loss=4.3324, ppl=76.1271, gnorm=0.3059, throughput=40.31K wps, wc=59.86K
2019-10-11 21:37:53,753 - root - [Epoch 0 Batch 750/1043] loss=4.1877, ppl=65.8744, gnorm=0.3209, throughput=39.21K wps, wc=53.35K
2019-10-11 21:37:55,418 - root - [Epoch 0 Batch 760/1043] loss=4.2839, ppl=72.5257, gnorm=0.3088, throughput=42.14K wps, wc=70.09K
2019-10-11 21:37:56,547 - root - [Epoch 0 Batch 770/1043] loss=4.1096, ppl=60.9223, gnorm=0.3156, throughput=38.33K wps, wc=43.21K
2019-10-11 21:37:58,340 - root - [Epoch 0 Batch 780/1043] loss=4.2977, ppl=73.5280, gnorm=0.2854, throughput=42.38K wps, wc=75.93K
2019-10-11 21:37:59,574 - root - [Epoch 0 Batch 790/1043] loss=4.1334, ppl=62.3908, gnorm=0.3025, throughput=38.01K wps, wc=46.81K
2019-10-11 21:38:01,058 - root - [Epoch 0 Batch 800/1043] loss=4.1909, ppl=66.0831, gnorm=0.3155, throughput=39.61K wps, wc=58.72K
2019-10-11 21:38:02,470 - root - [Epoch 0 Batch 810/1043] loss=4.0763, ppl=58.9267, gnorm=0.3077, throughput=40.67K wps, wc=57.38K
2019-10-11 21:38:03,870 - root - [Epoch 0 Batch 820/1043] loss=3.9656, ppl=52.7506, gnorm=0.3219, throughput=41.86K wps, wc=58.52K
2019-10-11 21:38:05,257 - root - [Epoch 0 Batch 830/1043] loss=4.1119, ppl=61.0607, gnorm=0.3460, throughput=41.31K wps, wc=57.24K
2019-10-11 21:38:06,587 - root - [Epoch 0 Batch 840/1043] loss=4.0804, ppl=59.1688, gnorm=0.3082, throughput=39.60K wps, wc=52.57K
2019-10-11 21:38:08,094 - root - [Epoch 0 Batch 850/1043] loss=4.1242, ppl=61.8196, gnorm=0.3029, throughput=42.60K wps, wc=64.14K
2019-10-11 21:38:09,459 - root - [Epoch 0 Batch 860/1043] loss=4.1267, ppl=61.9747, gnorm=0.2965, throughput=40.09K wps, wc=54.64K
2019-10-11 21:38:11,015 - root - [Epoch 0 Batch 870/1043] loss=4.1446, ppl=63.0909, gnorm=0.3095, throughput=42.33K wps, wc=65.81K
2019-10-11 21:38:12,292 - root - [Epoch 0 Batch 880/1043] loss=4.0867, ppl=59.5410, gnorm=0.3045, throughput=39.42K wps, wc=50.27K
2019-10-11 21:38:13,767 - root - [Epoch 0 Batch 890/1043] loss=4.1501, ppl=63.4378, gnorm=0.2947, throughput=38.06K wps, wc=56.11K
2019-10-11 21:38:15,244 - root - [Epoch 0 Batch 900/1043] loss=4.1710, ppl=64.7784, gnorm=0.3102, throughput=41.28K wps, wc=60.91K
2019-10-11 21:38:16,588 - root - [Epoch 0 Batch 910/1043] loss=3.9920, ppl=54.1649, gnorm=0.3159, throughput=38.50K wps, wc=51.65K
2019-10-11 21:38:18,067 - root - [Epoch 0 Batch 920/1043] loss=4.1635, ppl=64.2961, gnorm=0.2856, throughput=40.96K wps, wc=60.52K
2019-10-11 21:38:19,236 - root - [Epoch 0 Batch 930/1043] loss=3.9781, ppl=53.4148, gnorm=0.3047, throughput=37.25K wps, wc=43.51K
2019-10-11 21:38:20,501 - root - [Epoch 0 Batch 940/1043] loss=3.9274, ppl=50.7769, gnorm=0.3409, throughput=39.33K wps, wc=49.71K
2019-10-11 21:38:22,145 - root - [Epoch 0 Batch 950/1043] loss=4.2063, ppl=67.1091, gnorm=0.2907, throughput=43.19K wps, wc=70.92K
2019-10-11 21:38:23,872 - root - [Epoch 0 Batch 960/1043] loss=4.1562, ppl=63.8287, gnorm=0.2785, throughput=42.92K wps, wc=74.06K
2019-10-11 21:38:25,075 - root - [Epoch 0 Batch 970/1043] loss=3.8764, ppl=48.2516, gnorm=0.3496, throughput=36.63K wps, wc=44.03K
2019-10-11 21:38:26,797 - root - [Epoch 0 Batch 980/1043] loss=4.1856, ppl=65.7304, gnorm=0.2874, throughput=42.28K wps, wc=72.73K
2019-10-11 21:38:28,363 - root - [Epoch 0 Batch 990/1043] loss=4.0939, ppl=59.9704, gnorm=0.2977, throughput=41.77K wps, wc=65.39K
2019-10-11 21:38:29,789 - root - [Epoch 0 Batch 1000/1043] loss=3.9921, ppl=54.1671, gnorm=0.3649, throughput=39.09K wps, wc=55.65K
2019-10-11 21:38:31,371 - root - [Epoch 0 Batch 1010/1043] loss=4.0889, ppl=59.6722, gnorm=0.2920, throughput=41.52K wps, wc=65.61K
2019-10-11 21:38:32,594 - root - [Epoch 0 Batch 1020/1043] loss=3.8276, ppl=45.9530, gnorm=0.3339, throughput=37.44K wps, wc=45.72K
2019-10-11 21:38:33,979 - root - [Epoch 0 Batch 1030/1043] loss=3.9861, ppl=53.8435, gnorm=0.3066, throughput=40.47K wps, wc=55.97K
2019-10-11 21:38:35,312 - root - [Epoch 0 Batch 1040/1043] loss=3.9453, ppl=51.6938, gnorm=0.3517, throughput=40.02K wps, wc=53.27K
2019-10-11 21:38:48,527 - root - [Epoch 0] valid Loss=2.8535, valid ppl=17.3487, valid bleu=2.79
2019-10-11 21:39:00,079 - root - [Epoch 0] test Loss=2.9866, test ppl=19.8174, test bleu=2.62
2019-10-11 21:39:00,085 - root - Save best parameters to gnmt_en_vi_u512/valid_best.params
2019-10-11 21:39:00,255 - root - Learning rate change to 0.0005

Conclusion

In this notebook, we have shown how to train a GNMT model on the IWSLT 2015 English-Vietnamese dataset using the Gluon NLP toolkit. The complete training script can be found here. The code sequence to reproduce the results can be seen on the machine translation page.