|
| 1 | +# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). You |
| 4 | +# may not use this file except in compliance with the License. A copy of |
| 5 | +# the License is located at |
| 6 | +# |
| 7 | +# http://aws.amazon.com/apache2.0/ |
| 8 | +# |
| 9 | +# or in the "license" file accompanying this file. This file is |
| 10 | +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF |
| 11 | +# ANY KIND, either express or implied. See the License for the specific |
| 12 | +# language governing permissions and limitations under the License. |
| 13 | + |
| 14 | +from __future__ import print_function, absolute_import |
| 15 | + |
| 16 | +import argparse |
| 17 | +import os |
| 18 | + |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +import chainer |
| 22 | +import chainer.functions as F |
| 23 | +import chainer.links as L |
| 24 | +from chainer import training |
| 25 | +from chainer import serializers |
| 26 | +from chainer.training import extensions |
| 27 | + |
| 28 | +import net |
| 29 | + |
| 30 | +if __name__ =='__main__': |
| 31 | + |
| 32 | + parser = argparse.ArgumentParser() |
| 33 | + |
| 34 | + # retrieve the hyperparameters we set from the client (with some defaults) |
| 35 | + parser.add_argument('--epochs', type=int, default=50) |
| 36 | + parser.add_argument('--batch-size', type=int, default=64) |
| 37 | + parser.add_argument('--learning-rate', type=float, default=0.05) |
| 38 | + |
| 39 | + # Data, model, and output directories These are required. |
| 40 | + parser.add_argument('--output-dir', type=str, default=os.environ['SM_OUTPUT_DIR']) |
| 41 | + parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR']) |
| 42 | + parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAIN']) |
| 43 | + parser.add_argument('--test', type=str, default=os.environ['SM_CHANNEL_TEST']) |
| 44 | + |
| 45 | + args, _ = parser.parse_known_args() |
| 46 | + |
| 47 | + num_gpus = int(os.environ['SM_NUM_GPUS']) |
| 48 | + |
| 49 | + train_data = np.load(os.path.join(args.train, 'train.npz'))['data'] |
| 50 | + train_labels = np.load(os.path.join(args.train, 'train.npz'))['labels'] |
| 51 | + |
| 52 | + test_data = np.load(os.path.join(args.test, 'test.npz'))['data'] |
| 53 | + test_labels = np.load(os.path.join(args.test, 'test.npz'))['labels'] |
| 54 | + |
| 55 | + train = chainer.datasets.TupleDataset(train_data, train_labels) |
| 56 | + test = chainer.datasets.TupleDataset(test_data, test_labels) |
| 57 | + |
| 58 | + print('# Minibatch-size: {}'.format(args.batch_size)) |
| 59 | + print('# epoch: {}'.format(args.epochs)) |
| 60 | + print('# learning rate: {}'.format(args.learning_rate)) |
| 61 | + |
| 62 | + # Set up a neural network to train. |
| 63 | + # Classifier reports softmax cross entropy loss and accuracy at every |
| 64 | + # iteration, which will be used by the PrintReport extension below. |
| 65 | + model = L.Classifier(net.VGG(10)) |
| 66 | + |
| 67 | + optimizer = chainer.optimizers.MomentumSGD(args.learning_rate) |
| 68 | + optimizer.setup(model) |
| 69 | + optimizer.add_hook(chainer.optimizer.WeightDecay(5e-4)) |
| 70 | + |
| 71 | + # Set up a trainer |
| 72 | + device = 0 if num_gpus > 0 else -1 # -1 indicates CPU, 0 indicates first GPU device. |
| 73 | + if num_gpus > 1: |
| 74 | + devices = range(num_gpus) |
| 75 | + train_iters = [chainer.iterators.MultiprocessIterator(i, args.batch_size, n_processes=4) \ |
| 76 | + for i in chainer.datasets.split_dataset_n_random(train, len(devices))] |
| 77 | + test_iter = chainer.iterators.MultiprocessIterator(test, args.batch_size, repeat=False, n_processes=num_gpus) |
| 78 | + updater = training.updaters.MultiprocessParallelUpdater(train_iters, optimizer, devices=range(num_gpus)) |
| 79 | + else: |
| 80 | + train_iter = chainer.iterators.MultiprocessIterator(train, args.batch_size) |
| 81 | + test_iter = chainer.iterators.MultiprocessIterator(test, args.batch_size, repeat=False) |
| 82 | + updater = training.updater.StandardUpdater(train_iter, optimizer, device=device) |
| 83 | + |
| 84 | + stop_trigger = (args.epochs, 'epoch') |
| 85 | + |
| 86 | + output_data_dir = os.path.join(args.output_dir, 'data') |
| 87 | + trainer = training.Trainer(updater, stop_trigger, out=output_data_dir) |
| 88 | + # Evaluate the model with the test dataset for each epoch |
| 89 | + trainer.extend(extensions.Evaluator(test_iter, model, device=device)) |
| 90 | + |
| 91 | + # Reduce the learning rate by half every 25 epochs. |
| 92 | + trainer.extend(extensions.ExponentialShift('lr', 0.5), trigger=(25, 'epoch')) |
| 93 | + |
| 94 | + # Dump a computational graph from 'loss' variable at the first iteration |
| 95 | + # The "main" refers to the target link of the "main" optimizer. |
| 96 | + trainer.extend(extensions.dump_graph('main/loss')) |
| 97 | + |
| 98 | + # Write a log of evaluation statistics for each epoch |
| 99 | + trainer.extend(extensions.LogReport()) |
| 100 | + |
| 101 | + if extensions.PlotReport.available(): |
| 102 | + trainer.extend( |
| 103 | + extensions.PlotReport(['main/loss', 'validation/main/loss'], |
| 104 | + 'epoch', file_name='loss.png')) |
| 105 | + trainer.extend( |
| 106 | + extensions.PlotReport( |
| 107 | + ['main/accuracy', 'validation/main/accuracy'], |
| 108 | + 'epoch', file_name='accuracy.png')) |
| 109 | + |
| 110 | + # Print selected entries of the log to stdout |
| 111 | + # Here "main" refers to the target link of the "main" optimizer again, and |
| 112 | + # "validation" refers to the default name of the Evaluator extension. |
| 113 | + # Entries other than 'epoch' are reported by the Classifier link, called by |
| 114 | + # either the updater or the evaluator. |
| 115 | + trainer.extend(extensions.PrintReport( |
| 116 | + ['epoch', 'main/loss', 'validation/main/loss', |
| 117 | + 'main/accuracy', 'validation/main/accuracy', 'elapsed_time'])) |
| 118 | + |
| 119 | + # Run the training |
| 120 | + trainer.run() |
| 121 | + |
| 122 | + # Save the model to model_dir. It's loaded below in `model_fn`. |
| 123 | + serializers.save_npz(os.path.join(args.model_dir, 'model.npz'), model) |
| 124 | + |
| 125 | + |
| 126 | +def model_fn(model_dir): |
| 127 | + """ |
| 128 | + This function is called by the Chainer container during hosting when running on SageMaker with |
| 129 | + values populated by the hosting environment. |
| 130 | + |
| 131 | + This function loads models written during training into `model_dir`. |
| 132 | +
|
| 133 | + Args: |
| 134 | + model_dir (str): path to the directory containing the saved model artifacts |
| 135 | +
|
| 136 | + Returns: |
| 137 | + a loaded Chainer model |
| 138 | + |
| 139 | + For more on `model_fn`, please visit the sagemaker-python-sdk repository: |
| 140 | + https://github.com/aws/sagemaker-python-sdk |
| 141 | + |
| 142 | + For more on the Chainer container, please visit the sagemaker-chainer-containers repository: |
| 143 | + https://github.com/aws/sagemaker-chainer-containers |
| 144 | + """ |
| 145 | + chainer.config.train = False |
| 146 | + model = L.Classifier(net.VGG(10)) |
| 147 | + serializers.load_npz(os.path.join(model_dir, 'model.npz'), model) |
| 148 | + return model.predictor |
0 commit comments