NVIDIA Deep Learning Examples
GNMT v2 for PyTorch
Resource
NVIDIA Deep Learning Examples
GNMT v2 for PyTorch

The GNMT v2 model is an improved version of the first Google's Neural Machine Translation System with a modified attention mechanism.

  • The following sections provide greater details of the dataset, running training and inference, and the training results.

    Scripts and sample code

    In the root directory, the most important files are:

    • train.py: serves as the entry point to launch the training
    • translate.py: serves as the entry point to launch inference
    • Dockerfile: container with the basic set of dependencies to run GNMT v2
    • requirements.txt: set of extra requirements for running GNMT v2

    The seq2seq/model directory contains the implementation of GNMT v2 building blocks:

    • attention.py: implementation of normalized Bahdanau attention
    • encoder.py: implementation of recurrent encoder
    • decoder.py: implementation of recurrent decoder with attention
    • seq2seq_base.py: base class for seq2seq models
    • gnmt.py: implementation of GNMT v2 model

    The seq2seq/train directory encapsulates the necessary tools to execute training:

    • trainer.py: implementation of training loop
    • smoothing.py: implementation of cross-entropy with label smoothing
    • lr_scheduler.py: implementation of exponential learning rate warmup and step decay
    • fp_optimizers.py: implementation of optimizers for various floating point precisions

    The seq2seq/inference directory contains scripts required to run inference:

    • beam_search.py: implementation of beam search with length normalization and length penalty
    • translator.py: implementation of auto-regressive inference

    The seq2seq/data directory contains implementation of components needed for data loading:

    • dataset.py: implementation of text datasets
    • sampler.py: implementation of batch samplers with bucketing by sequence length
    • tokenizer.py: implementation of tokenizer (maps integer vocabulary indices to text)

    Parameters

    Training

    The complete list of available parameters for the train.py training script contains:

    dataset setup:
      --dataset-dir DATASET_DIR
                            path to the directory with training/test data
                            (default: data/wmt16_de_en)
      --src-lang SRC_LANG   source language (default: en)
      --tgt-lang TGT_LANG   target language (default: de)
      --vocab VOCAB         path to the vocabulary file (relative to DATASET_DIR
                            directory) (default: vocab.bpe.32000)
      -bpe BPE_CODES, --bpe-codes BPE_CODES
                            path to the file with bpe codes (relative to
                            DATASET_DIR directory) (default: bpe.32000)
      --train-src TRAIN_SRC
                            path to the training source data file (relative to
                            DATASET_DIR directory) (default:
                            train.tok.clean.bpe.32000.en)
      --train-tgt TRAIN_TGT
                            path to the training target data file (relative to
                            DATASET_DIR directory) (default:
                            train.tok.clean.bpe.32000.de)
      --val-src VAL_SRC     path to the validation source data file (relative to
                            DATASET_DIR directory) (default:
                            newstest_dev.tok.clean.bpe.32000.en)
      --val-tgt VAL_TGT     path to the validation target data file (relative to
                            DATASET_DIR directory) (default:
                            newstest_dev.tok.clean.bpe.32000.de)
      --test-src TEST_SRC   path to the test source data file (relative to
                            DATASET_DIR directory) (default:
                            newstest2014.tok.bpe.32000.en)
      --test-tgt TEST_TGT   path to the test target data file (relative to
                            DATASET_DIR directory) (default: newstest2014.de)
      --train-max-size TRAIN_MAX_SIZE
                            use at most TRAIN_MAX_SIZE elements from training
                            dataset (useful for benchmarking), by default uses
                            entire dataset (default: None)
    
    results setup:
      --save-dir SAVE_DIR   path to directory with results, it will be
                            automatically created if it does not exist (default:
                            gnmt)
      --print-freq PRINT_FREQ
                            print log every PRINT_FREQ batches (default: 10)
    
    model setup:
      --hidden-size HIDDEN_SIZE
                            hidden size of the model (default: 1024)
      --num-layers NUM_LAYERS
                            number of RNN layers in encoder and in decoder
                            (default: 4)
      --dropout DROPOUT     dropout applied to input of RNN cells (default: 0.2)
      --share-embedding     use shared embeddings for encoder and decoder (use '--
                            no-share-embedding' to disable) (default: True)
      --smoothing SMOOTHING
                            label smoothing, if equal to zero model will use
                            CrossEntropyLoss, if not zero model will be trained
                            with label smoothing loss (default: 0.1)
    
    general setup:
      --math {fp16,fp32,tf32,manual_fp16}
                            precision (default: fp16)
      --seed SEED           master seed for random number generators, if "seed" is
                            undefined then the master seed will be sampled from
                            random.SystemRandom() (default: None)
      --prealloc-mode {off,once,always}
                            controls preallocation (default: always)
      --dllog-file DLLOG_FILE
                            Name of the DLLogger output file (default:
                            train_log.json)
      --eval                run validation and test after every epoch (use '--no-
                            eval' to disable) (default: True)
      --env                 print info about execution env (use '--no-env' to
                            disable) (default: True)
      --cuda                enables cuda (use '--no-cuda' to disable) (default:
                            True)
      --cudnn               enables cudnn (use '--no-cudnn' to disable) (default:
                            True)
      --log-all-ranks       enables logging from all distributed ranks, if
                            disabled then only logs from rank 0 are reported (use
                            '--no-log-all-ranks' to disable) (default: True)
    
    training setup:
      --train-batch-size TRAIN_BATCH_SIZE
                            training batch size per worker (default: 128)
      --train-global-batch-size TRAIN_GLOBAL_BATCH_SIZE
                            global training batch size, this argument does not
                            have to be defined, if it is defined it will be used
                            to automatically compute train_iter_size using the
                            equation: train_iter_size = train_global_batch_size //
                            (train_batch_size * world_size) (default: None)
      --train-iter-size N   training iter size, training loop will accumulate
                            gradients over N iterations and execute optimizer
                            every N steps (default: 1)
      --epochs EPOCHS       max number of training epochs (default: 6)
      --grad-clip GRAD_CLIP
                            enables gradient clipping and sets maximum norm of
                            gradients (default: 5.0)
      --train-max-length TRAIN_MAX_LENGTH
                            maximum sequence length for training (including
                            special BOS and EOS tokens) (default: 50)
      --train-min-length TRAIN_MIN_LENGTH
                            minimum sequence length for training (including
                            special BOS and EOS tokens) (default: 0)
      --train-loader-workers TRAIN_LOADER_WORKERS
                            number of workers for training data loading (default:
                            2)
      --batching {random,sharding,bucketing}
                            select batching algorithm (default: bucketing)
      --shard-size SHARD_SIZE
                            shard size for "sharding" batching algorithm, in
                            multiples of global batch size (default: 80)
      --num-buckets NUM_BUCKETS
                            number of buckets for "bucketing" batching algorithm
                            (default: 5)
    
    optimizer setup:
      --optimizer OPTIMIZER
                            training optimizer (default: Adam)
      --lr LR               learning rate (default: 0.002)
      --optimizer-extra OPTIMIZER_EXTRA
                            extra options for the optimizer (default: {})
    
    mixed precision loss scaling setup:
      --init-scale INIT_SCALE
                            initial loss scale (default: 8192)
      --upscale-interval UPSCALE_INTERVAL
                            loss upscaling interval (default: 128)
    
    learning rate scheduler setup:
      --warmup-steps WARMUP_STEPS
                            number of learning rate warmup iterations (default:
                            200)
      --remain-steps REMAIN_STEPS
                            starting iteration for learning rate decay (default:
                            0.666)
      --decay-interval DECAY_INTERVAL
                            interval between learning rate decay steps (default:
                            None)
      --decay-steps DECAY_STEPS
                            max number of learning rate decay steps (default: 4)
      --decay-factor DECAY_FACTOR
                            learning rate decay factor (default: 0.5)
    
    validation setup:
      --val-batch-size VAL_BATCH_SIZE
                            batch size for validation (default: 64)
      --val-max-length VAL_MAX_LENGTH
                            maximum sequence length for validation (including
                            special BOS and EOS tokens) (default: 125)
      --val-min-length VAL_MIN_LENGTH
                            minimum sequence length for validation (including
                            special BOS and EOS tokens) (default: 0)
      --val-loader-workers VAL_LOADER_WORKERS
                            number of workers for validation data loading
                            (default: 0)
    
    test setup:
      --test-batch-size TEST_BATCH_SIZE
                            batch size for test (default: 128)
      --test-max-length TEST_MAX_LENGTH
                            maximum sequence length for test (including special
                            BOS and EOS tokens) (default: 150)
      --test-min-length TEST_MIN_LENGTH
                            minimum sequence length for test (including special
                            BOS and EOS tokens) (default: 0)
      --beam-size BEAM_SIZE
                            beam size (default: 5)
      --len-norm-factor LEN_NORM_FACTOR
                            length normalization factor (default: 0.6)
      --cov-penalty-factor COV_PENALTY_FACTOR
                            coverage penalty factor (default: 0.1)
      --len-norm-const LEN_NORM_CONST
                            length normalization constant (default: 5.0)
      --intra-epoch-eval N  evaluate within training epoch, this option will
                            enable extra N equally spaced evaluations executed
                            during each training epoch (default: 0)
      --test-loader-workers TEST_LOADER_WORKERS
                            number of workers for test data loading (default: 0)
    
    checkpointing setup:
      --start-epoch START_EPOCH
                            manually set initial epoch counter (default: 0)
      --resume PATH         resumes training from checkpoint from PATH (default:
                            None)
      --save-all            saves checkpoint after every epoch (default: False)
      --save-freq SAVE_FREQ
                            save checkpoint every SAVE_FREQ batches (default:
                            5000)
      --keep-checkpoints KEEP_CHECKPOINTS
                            keep only last KEEP_CHECKPOINTS checkpoints, affects
                            only checkpoints controlled by --save-freq option
                            (default: 0)
    
    benchmark setup:
      --target-perf TARGET_PERF
                            target training performance (in tokens per second)
                            (default: None)
      --target-bleu TARGET_BLEU
                            target accuracy (default: None)
    

    Inference

    The complete list of available parameters for the translate.py inference script contains:

    data setup:
      -o OUTPUT, --output OUTPUT
                            full path to the output file if not specified, then
                            the output will be printed (default: None)
      -r REFERENCE, --reference REFERENCE
                            full path to the file with reference translations (for
                            sacrebleu, raw text) (default: None)
      -m MODEL, --model MODEL
                            full path to the model checkpoint file (default: None)
      --synthetic           use synthetic dataset (default: False)
      --synthetic-batches SYNTHETIC_BATCHES
                            number of synthetic batches to generate (default: 64)
      --synthetic-vocab SYNTHETIC_VOCAB
                            size of synthetic vocabulary (default: 32320)
      --synthetic-len SYNTHETIC_LEN
                            sequence length of synthetic samples (default: 50)
      -i INPUT, --input INPUT
                            full path to the input file (raw text) (default: None)
      -t INPUT_TEXT [INPUT_TEXT ...], --input-text INPUT_TEXT [INPUT_TEXT ...]
                            raw input text (default: None)
      --sort                sorts dataset by sequence length (use '--no-sort' to
                            disable) (default: False)
    
    inference setup:
      --batch-size BATCH_SIZE [BATCH_SIZE ...]
                            batch size per GPU (default: [128])
      --beam-size BEAM_SIZE [BEAM_SIZE ...]
                            beam size (default: [5])
      --max-seq-len MAX_SEQ_LEN
                            maximum generated sequence length (default: 80)
      --len-norm-factor LEN_NORM_FACTOR
                            length normalization factor (default: 0.6)
      --cov-penalty-factor COV_PENALTY_FACTOR
                            coverage penalty factor (default: 0.1)
      --len-norm-const LEN_NORM_CONST
                            length normalization constant (default: 5.0)
    
    general setup:
      --math {fp16,fp32,tf32} [{fp16,fp32,tf32} ...]
                            precision (default: ['fp16'])
      --env                 print info about execution env (use '--no-env' to
                            disable) (default: False)
      --bleu                compares with reference translation and computes BLEU
                            (use '--no-bleu' to disable) (default: True)
      --cuda                enables cuda (use '--no-cuda' to disable) (default:
                            True)
      --cudnn               enables cudnn (use '--no-cudnn' to disable) (default:
                            True)
      --batch-first         uses (batch, seq, feature) data format for RNNs
                            (default: True)
      --seq-first           uses (seq, batch, feature) data format for RNNs
                            (default: True)
      --save-dir SAVE_DIR   path to directory with results, it will be
                            automatically created if it does not exist (default:
                            gnmt)
      --dllog-file DLLOG_FILE
                            Name of the DLLogger output file (default:
                            eval_log.json)
      --print-freq PRINT_FREQ, -p PRINT_FREQ
                            print log every PRINT_FREQ batches (default: 1)
    
    benchmark setup:
      --target-perf TARGET_PERF
                            target inference performance (in tokens per second)
                            (default: None)
      --target-bleu TARGET_BLEU
                            target accuracy (default: None)
      --repeat REPEAT [REPEAT ...]
                            loops over the dataset REPEAT times, flag accepts
                            multiple arguments, one for each specified batch size
                            (default: [1])
      --warmup WARMUP       warmup iterations for performance counters (default:
                            0)
      --percentiles PERCENTILES [PERCENTILES ...]
                            Percentiles for confidence intervals for
                            throughput/latency benchmarks (default: (90, 95, 99))
      --tables              print accuracy, throughput and latency results in
                            tables (use '--no-tables' to disable) (default: False)
    

    Command-line options

    To see the full list of available options and their descriptions, use the -h or --help command line option. For example, for training:

    python3 train.py --help
    
    usage: train.py [-h] [--dataset-dir DATASET_DIR] [--src-lang SRC_LANG]
                    [--tgt-lang TGT_LANG] [--vocab VOCAB] [-bpe BPE_CODES]
                    [--train-src TRAIN_SRC] [--train-tgt TRAIN_TGT]
                    [--val-src VAL_SRC] [--val-tgt VAL_TGT] [--test-src TEST_SRC]
                    [--test-tgt TEST_TGT] [--save-dir SAVE_DIR]
                    [--print-freq PRINT_FREQ] [--hidden-size HIDDEN_SIZE]
                    [--num-layers NUM_LAYERS] [--dropout DROPOUT]
                    [--share-embedding] [--smoothing SMOOTHING]
                    [--math {fp16,fp32,tf32,manual_fp16}] [--seed SEED]
                    [--prealloc-mode {off,once,always}] [--dllog-file DLLOG_FILE]
                    [--eval] [--env] [--cuda] [--cudnn] [--log-all-ranks]
                    [--train-max-size TRAIN_MAX_SIZE]
                    [--train-batch-size TRAIN_BATCH_SIZE]
                    [--train-global-batch-size TRAIN_GLOBAL_BATCH_SIZE]
                    [--train-iter-size N] [--epochs EPOCHS]
                    [--grad-clip GRAD_CLIP] [--train-max-length TRAIN_MAX_LENGTH]
                    [--train-min-length TRAIN_MIN_LENGTH]
                    [--train-loader-workers TRAIN_LOADER_WORKERS]
                    [--batching {random,sharding,bucketing}]
                    [--shard-size SHARD_SIZE] [--num-buckets NUM_BUCKETS]
                    [--optimizer OPTIMIZER] [--lr LR]
                    [--optimizer-extra OPTIMIZER_EXTRA] [--init-scale INIT_SCALE]
                    [--upscale-interval UPSCALE_INTERVAL]
                    [--warmup-steps WARMUP_STEPS] [--remain-steps REMAIN_STEPS]
                    [--decay-interval DECAY_INTERVAL] [--decay-steps DECAY_STEPS]
                    [--decay-factor DECAY_FACTOR]
                    [--val-batch-size VAL_BATCH_SIZE]
                    [--val-max-length VAL_MAX_LENGTH]
                    [--val-min-length VAL_MIN_LENGTH]
                    [--val-loader-workers VAL_LOADER_WORKERS]
                    [--test-batch-size TEST_BATCH_SIZE]
                    [--test-max-length TEST_MAX_LENGTH]
                    [--test-min-length TEST_MIN_LENGTH] [--beam-size BEAM_SIZE]
                    [--len-norm-factor LEN_NORM_FACTOR]
                    [--cov-penalty-factor COV_PENALTY_FACTOR]
                    [--len-norm-const LEN_NORM_CONST] [--intra-epoch-eval N]
                    [--test-loader-workers TEST_LOADER_WORKERS]
                    [--start-epoch START_EPOCH] [--resume PATH] [--save-all]
                    [--save-freq SAVE_FREQ] [--keep-checkpoints KEEP_CHECKPOINTS]
                    [--target-perf TARGET_PERF] [--target-bleu TARGET_BLEU]
                    [--local_rank LOCAL_RANK]
    

    For example, for inference:

    python3 translate.py --help
    
    usage: translate.py [-h] [-o OUTPUT] [-r REFERENCE] [-m MODEL] [--synthetic]
                        [--synthetic-batches SYNTHETIC_BATCHES]
                        [--synthetic-vocab SYNTHETIC_VOCAB]
                        [--synthetic-len SYNTHETIC_LEN]
                        [-i INPUT | -t INPUT_TEXT [INPUT_TEXT ...]] [--sort]
                        [--batch-size BATCH_SIZE [BATCH_SIZE ...]]
                        [--beam-size BEAM_SIZE [BEAM_SIZE ...]]
                        [--max-seq-len MAX_SEQ_LEN]
                        [--len-norm-factor LEN_NORM_FACTOR]
                        [--cov-penalty-factor COV_PENALTY_FACTOR]
                        [--len-norm-const LEN_NORM_CONST]
                        [--math {fp16,fp32,tf32} [{fp16,fp32,tf32} ...]] [--env]
                        [--bleu] [--cuda] [--cudnn] [--batch-first | --seq-first]
                        [--save-dir SAVE_DIR] [--dllog-file DLLOG_FILE]
                        [--print-freq PRINT_FREQ] [--target-perf TARGET_PERF]
                        [--target-bleu TARGET_BLEU] [--repeat REPEAT [REPEAT ...]]
                        [--warmup WARMUP]
                        [--percentiles PERCENTILES [PERCENTILES ...]] [--tables]
                        [--local_rank LOCAL_RANK]
    

    Getting the data

    The GNMT v2 model was trained on the WMT16 English-German dataset. Concatenation of the newstest2015 and newstest2016 test sets are used as a validation dataset and the newstest2014 is used as a testing dataset.

    This repository contains the scripts/wmt16_en_de.sh download script which automatically downloads and preprocesses the training, validation and test datasets. By default, data is downloaded to the data directory.

    Our download script is very similar to the wmt16_en_de.sh script from the tensorflow/nmt repository. Our download script contains an extra preprocessing step, which discards all pairs of sentences which can't be decoded by latin-1 encoder. The scripts/wmt16_en_de.sh script uses the subword-nmt package to segment text into subword units (Byte Pair Encodings - BPE). By default, the script builds the shared vocabulary of 32,000 tokens.

    In order to test with other datasets, the script needs to be customized accordingly.

    Dataset guidelines

    The process of downloading and preprocessing the data can be found in the scripts/wmt16_en_de.sh script.

    Initially, data is downloaded from www.statmt.org. Then europarl-v7, commoncrawl and news-commentary corpora are concatenated to form the training dataset, similarly newstest2015 and newstest2016 are concatenated to form the validation dataset. Raw data is preprocessed with Moses, first by launching Moses tokenizer (tokenizer breaks up text into individual words), then by launching clean-corpus-n.perl which removes invalid sentences and does initial filtering by sequence length.

    Second stage of preprocessing is done by launching the scripts/filter_dataset.py script, which discards all pairs of sentences that can't be decoded by latin-1 encoder.

    Third state of preprocessing uses the subword-nmt package. First it builds shared byte pair encoding vocabulary with 32,000 merge operations (command subword-nmt learn-bpe), then it applies generated vocabulary to training, validation and test corpora (command subword-nmt apply-bpe).

    Training process

    The default training configuration can be launched by running the train.py training script. By default, the training script saves only one checkpoint with the lowest value of the loss function on the validation dataset. An evaluation is then performed after each training epoch. Results are stored in the gnmt directory.

    The training script launches data-parallel training with batch size 128 per GPU on all available GPUs. We have tested reliance on up to 16 GPUs on a single node. After each training epoch, the script runs an evaluation on the validation dataset and outputs a BLEU score on the test dataset (newstest2014). BLEU is computed by the SacreBLEU package. Logs from the training and evaluation are saved to the gnmt directory.

    The summary after each training epoch is printed in the following format:

    0: Summary: Epoch: 3	Training Loss: 3.1336	Validation Loss: 2.9587	Test BLEU: 23.18
    0: Performance: Epoch: 3	Training: 418772 Tok/s	Validation: 1445331 Tok/s
    

    The training loss is averaged over an entire training epoch, the validation loss is averaged over the validation dataset and the BLEU score is computed on the test dataset. Performance is reported in total tokens per second. The result is averaged over an entire training epoch and summed over all GPUs participating in the training.

    By default, the train.py script will launch mixed precision training with Tensor Cores. You can change this behavior by setting:

    • the --math fp32 flag to launch single precision training (for NVIDIA Volta and NVIDIA Turing architectures) or
    • the --math tf32 flag to launch TF32 training with Tensor Cores (for NVIDIA Ampere architecture)

    for the train.py training script.

    To view all available options for training, run python3 train.py --help.

    Inference process

    Inference can be run by launching the translate.py inference script, although, it requires a pre-trained model checkpoint and tokenized input.

    The inference script, translate.py, supports batched inference. By default, it launches beam search with beam size of 5, coverage penalty term and length normalization term. Greedy decoding can be enabled by setting the beam size to 1.

    To view all available options for inference, run python3 translate.py --help.