Writing organized, reusable, clean training code using Trainer module

trainer3

 

Training code abstraction with Trainer

Until now, I was implementing the training code in “primitive” way to explain what kind of operations are going on in deep learning training (※). However, the code can be written in much clean way using Trainer modules in Chainer.

Trainer modules are implemented from version 1.11, and some of the open source projects are implemented without Trainer. So it helps to understand these codes by knowing the training implementation without Trainer module as well.

Motivation for using Trainer

We can notice there are many “typical” operations widely used in machine learning, for example

  • Iterating minibatch training, with minibatch sampled ramdomly
  • Separate train data & validation data, validation is used only for checking the loss to prevent overfitting
  • Output the log, save the trained model in regular interval

These operations are commonly applied, and Chainer provides these features in library level so that user don’t need to implement again and again. Trainer will mange the training code for you!

Details are also explained in official document of Trainer.

Source code with Trainer

Seeing is better than hearing, train_mnist_4_trainer.py is the source code which uses Trainer module. If I remove the comment, the source code looks like below,

 

See how clean the code is! Compare above code and train_mnist_2_predictor_classifier.py. The code even does not contains for loop, as well as random permutation for minibatch, and save function explicitly.

The code length also become shorten almost half, even it supports more functionality than previous train_mnist_2_predictor_classifier.py code,

  • Calculating validadtion loss, accuracy
  • Save trainer snapshot in regular interval (it is including optimizer and model data.)
    You can pause and resume training.
  • Print log in formatted way, together with the progress bar which showing training status.
  • Output the training result to log file in json formatted text.

 

However it has changed much from previous code, user might not understand what’s going on. Several modules are used for together with the Trainer. Let’s see overview of the role for each module one by one.

  • Dataset
  • Interator
  • Updater
  • Trainer
    • extensions
      – Evaluator
      – LogReport
      – PrintReport
      – ProgressBar
      – snapshot
      – dump_graph

More detail functionality and usage are explained later.

Dataset

Input data should be prepared in Dataset format so that Iterator can handle.

In this example, dataset does not explicitly appear but already prepared

 This train and test is TupleDataset. Recall MNIST dataset introduction.

There are several Dataset classes, TupleDataset, ImageDataset etc and even you can define your custom Dataset class by using DatasetMixin.

All the Dataset follows common rule that when data is Dataset instance data[i] points the i-th data.

Usually it consists of input data and target data (answer), where data[i][0] is the i-th input data, data[i][1] is the i-th target data. However, it can be only one element or even more than 2 elements depending on the problem.

Role: Used for preparing input value to provide index access of data. Specifically i-th data can be accessed by data[i], so that Iterator can handle.

See also official document

Iterator

For loop of training minibatch is replaced and managed by Iterator.

This one line provides almost same with following training loop,

and in the same way applies for validation (test) dataset,

is for

minibatch random sampling, implemented by np.permutation can be replaced by just setting shuffle flag to True or False (default True).

 

Currently 2 Iterator classes are provided, 

  • SerialIterator is the most basic class.
  • MultiProcessIterator provides multi process data preparation support in background.

Both of them have the

Role: Construct minibatch from Dataset (including background preparation support using multi process), and pass it to Updater.

See also official document

Updater

After creating Iterator, it is set to Updater together with optmizer,

Updater is in charge of calling optimizer’s update function, which means it corresponds to call

 

Currently 2 Updater classes are (and 1 Updater will be) provided, 

    • StandardUpdater is the basic class.
    • ParallelUpdater is for utilizing multiple GPU at the same time.

Role: Receiving minibatch from Iterator, calculate loss and call optimizer’s update.

Currently I could not find official document for Updater, but you can refer source code docstring,

Trainer

Finally, Trainer instance can be created via Updater

to start training, just call run

 

Usually extensions are registered before start calling run of trainer, see below

Role: Manages Training lifecycle. extension can be registered.

 

Trainer extension

Trainer extension can be registered by trainer.extend() function.

These extensions are used in this example,

  • Evaluator
    Calculate Validation loss and accuracy, and it is printed out and logged to file.
  • LogReport
    Print out log file in json format, in the directory specified by out argument in trainer.
  • PrintReport
    Print out log in standard out (console) to show training status.
  • ProgressBar
    Show progress bar to show current progress of training.
  • snapshot
    Save the trainer state (including model, optimizer information) in regular interval.
    By setting this extension, you can pause and resume training.
  • dump_graph
    dumps neural network computational graph

 

Role: hook trigger to trainer to do several events in specific timing

Trainer architecture summary

 

Refer above figure for the training abstraction procedure using Trainer module.

 

Advantage of using Trainer module

– Multi process data preparation using MultiProcessIterator

Python has GIL feature, so even you use multi-thread its threads are not executed in “parallel”. If the code contains heavy data preprocessing (e.g. data augmentation, adding noise before feeding as input) you can get benefit by using MultiProcessIterator.

– Multiple GPU utilization

 – ParallelUpdater or MultiProcessParallelUpdater

– Trainer extensions are useful and reusable once you made your own extension

 – PrintReport

 – ProgressBar

 – LogReport

 — The log is in json format, it is easy to load and plot learning curve graph etc.

 – snapshot

 etc etc… Why don’t we use it!

 

Sponsored Links

Leave a Reply

Your email address will not be published.