|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | +# |
| 19 | + |
| 20 | +from singa import device |
| 21 | +from singa import opt |
| 22 | +from singa import tensor |
| 23 | +import argparse |
| 24 | +import numpy as np |
| 25 | +import time |
| 26 | +from PIL import Image |
| 27 | + |
| 28 | +import sys |
| 29 | + |
| 30 | +sys.path.append(".") |
| 31 | +print(sys.path) |
| 32 | + |
| 33 | +import examples.cnn.model.cnn as cnn |
| 34 | +from examples.cnn.data import cifar10 |
| 35 | +import model as cpl |
| 36 | + |
| 37 | + |
| 38 | +def accuracy(pred, target): |
| 39 | + # y is network output to be compared with ground truth (int) |
| 40 | + y = np.argmax(pred, axis=1) |
| 41 | + a = y == target |
| 42 | + correct = np.array(a, "int").sum() |
| 43 | + return correct |
| 44 | + |
| 45 | + |
| 46 | +def resize_dataset(x, image_size): |
| 47 | + num_data = x.shape[0] |
| 48 | + dim = x.shape[1] |
| 49 | + X = np.zeros(shape=(num_data, dim, image_size, image_size), dtype=np.float32) |
| 50 | + for n in range(0, num_data): |
| 51 | + for d in range(0, dim): |
| 52 | + X[n, d, :, :] = np.array( |
| 53 | + Image.fromarray(x[n, d, :, :]).resize( |
| 54 | + (image_size, image_size), Image.BILINEAR |
| 55 | + ), |
| 56 | + dtype=np.float32, |
| 57 | + ) |
| 58 | + return X |
| 59 | + |
| 60 | + |
| 61 | +def run( |
| 62 | + local_rank, |
| 63 | + max_epoch, |
| 64 | + batch_size, |
| 65 | + sgd, |
| 66 | + graph, |
| 67 | + verbosity, |
| 68 | + dist_option="plain", |
| 69 | + spars=None, |
| 70 | +): |
| 71 | + dev = device.create_cuda_gpu_on(local_rank) |
| 72 | + dev.SetRandSeed(0) |
| 73 | + np.random.seed(0) |
| 74 | + |
| 75 | + train_x, train_y, val_x, val_y = cifar10.load() |
| 76 | + |
| 77 | + num_channels = train_x.shape[1] |
| 78 | + data_size = np.prod(train_x.shape[1 : train_x.ndim]).item() |
| 79 | + num_classes = (np.max(train_y) + 1).item() |
| 80 | + |
| 81 | + backbone = cnn.create_model(num_channels=num_channels, num_classes=num_classes) |
| 82 | + model = cpl.create_model(backbone, prototype_count=10, lamb=0.5, temp=10) |
| 83 | + |
| 84 | + if backbone.dimension == 4: |
| 85 | + tx = tensor.Tensor( |
| 86 | + (batch_size, num_channels, backbone.input_size, backbone.input_size), dev |
| 87 | + ) |
| 88 | + train_x = resize_dataset(train_x, backbone.input_size) |
| 89 | + val_x = resize_dataset(val_x, backbone.input_size) |
| 90 | + elif backbone.dimension == 2: |
| 91 | + tx = tensor.Tensor((batch_size, data_size), dev) |
| 92 | + np.reshape(train_x, (train_x.shape[0], -1)) |
| 93 | + np.reshape(val_x, (val_x.shape[0], -1)) |
| 94 | + |
| 95 | + ty = tensor.Tensor((batch_size,), dev, tensor.int32) |
| 96 | + num_train_batch = train_x.shape[0] // batch_size |
| 97 | + num_val_batch = val_x.shape[0] // batch_size |
| 98 | + idx = np.arange(train_x.shape[0], dtype=np.int32) |
| 99 | + |
| 100 | + model.set_optimizer(sgd) |
| 101 | + model.compile([tx], is_train=True, use_graph=graph, sequential=True) |
| 102 | + dev.SetVerbosity(verbosity) |
| 103 | + |
| 104 | + for epoch in range(max_epoch): |
| 105 | + print(f"Epoch {epoch}") |
| 106 | + np.random.shuffle(idx) |
| 107 | + |
| 108 | + train_correct = np.zeros(shape=[1], dtype=np.float32) |
| 109 | + test_correct = np.zeros(shape=[1], dtype=np.float32) |
| 110 | + train_loss = np.zeros(shape=[1], dtype=np.float32) |
| 111 | + |
| 112 | + model.train() |
| 113 | + for b in range(num_train_batch): |
| 114 | + x = train_x[idx[b * batch_size : (b + 1) * batch_size]] |
| 115 | + y = train_y[idx[b * batch_size : (b + 1) * batch_size]] |
| 116 | + tx.copy_from_numpy(x) |
| 117 | + ty.copy_from_numpy(y) |
| 118 | + |
| 119 | + out, loss = model(tx, ty, dist_option, spars) |
| 120 | + train_correct += accuracy(tensor.to_numpy(out), y) |
| 121 | + train_loss += tensor.to_numpy(loss)[0] |
| 122 | + print( |
| 123 | + "Training loss = %f, training accuracy = %f" |
| 124 | + % (train_loss, train_correct / (num_train_batch * batch_size)), |
| 125 | + flush=True, |
| 126 | + ) |
| 127 | + |
| 128 | + model.eval() |
| 129 | + for b in range(num_val_batch): |
| 130 | + x = val_x[b * batch_size : (b + 1) * batch_size] |
| 131 | + y = val_y[b * batch_size : (b + 1) * batch_size] |
| 132 | + |
| 133 | + tx.copy_from_numpy(x) |
| 134 | + ty.copy_from_numpy(y) |
| 135 | + |
| 136 | + out_test = model(tx, ty, dist_option="fp32", spars=None) |
| 137 | + test_correct += accuracy(tensor.to_numpy(out_test), y) |
| 138 | + |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + parser = argparse.ArgumentParser(description="Train a CPL model") |
| 142 | + parser.add_argument( |
| 143 | + "-m", |
| 144 | + "--max-epoch", |
| 145 | + default=20, |
| 146 | + type=int, |
| 147 | + help="maximum epochs", |
| 148 | + dest="max_epoch", |
| 149 | + ) |
| 150 | + parser.add_argument( |
| 151 | + "-b", "--batch-size", default=64, type=int, help="batch size", dest="batch_size" |
| 152 | + ) |
| 153 | + parser.add_argument( |
| 154 | + "-l", |
| 155 | + "--learning-rate", |
| 156 | + default=0.005, |
| 157 | + type=float, |
| 158 | + help="initial learning rate", |
| 159 | + dest="lr", |
| 160 | + ) |
| 161 | + parser.add_argument( |
| 162 | + "-i", |
| 163 | + "--device-id", |
| 164 | + default=0, |
| 165 | + type=int, |
| 166 | + help="which GPU to use", |
| 167 | + dest="device_id", |
| 168 | + ) |
| 169 | + parser.add_argument( |
| 170 | + "-g", |
| 171 | + "--disable-graph", |
| 172 | + default="True", |
| 173 | + action="store_false", |
| 174 | + help="disable graph", |
| 175 | + dest="graph", |
| 176 | + ) |
| 177 | + parser.add_argument( |
| 178 | + "-v", |
| 179 | + "--log-verbosity", |
| 180 | + default=0, |
| 181 | + type=int, |
| 182 | + help="logging verbosity", |
| 183 | + dest="verbosity", |
| 184 | + ) |
| 185 | + args = parser.parse_args() |
| 186 | + print(args) |
| 187 | + |
| 188 | + sgd = opt.SGD(lr=args.lr, momentum=0.9, weight_decay=1e-5) |
| 189 | + run( |
| 190 | + args.device_id, args.max_epoch, args.batch_size, sgd, args.graph, args.verbosity |
| 191 | + ) |
0 commit comments