train.py 6.7 KB
Newer Older
1 2 3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
D
Dun 已提交
4 5 6 7 8 9 10 11 12 13
import os
os.environ['FLAGS_fraction_of_gpu_memory_to_use'] = '0.98'

import paddle
import paddle.fluid as fluid
import numpy as np
import argparse
from reader import CityscapeDataset
import reader
import models
C
ccmeteorljh 已提交
14
import time
D
Dun 已提交
15

D
Dun 已提交
16

D
Dun 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
def add_argument(name, type, default, help):
    parser.add_argument('--' + name, default=default, type=type, help=help)


def add_arguments():
    add_argument('batch_size', int, 2,
                 "The number of images in each batch during training.")
    add_argument('train_crop_size', int, 769,
                 "'Image crop size during training.")
    add_argument('base_lr', float, 0.0001,
                 "The base learning rate for model training.")
    add_argument('total_step', int, 90000, "Number of the training step.")
    add_argument('init_weights_path', str, None,
                 "Path of the initial weights in paddlepaddle format.")
    add_argument('save_weights_path', str, None,
                 "Path of the saved weights during training.")
    add_argument('dataset_path', str, None, "Cityscape dataset path.")
    add_argument('parallel', bool, False, "using ParallelExecutor.")
    add_argument('use_gpu', bool, True, "Whether use GPU or CPU.")
D
Dun 已提交
36
    add_argument('num_classes', int, 19, "Number of classes.")
D
Dun 已提交
37 38 39 40
    parser.add_argument(
        '--enable_ce',
        action='store_true',
        help='If set, run the task with continuous evaluation logs.')
D
Dun 已提交
41 42 43


def load_model():
D
Dun 已提交
44 45 46 47 48
    myvars = [
        x for x in tp.list_vars()
        if isinstance(x, fluid.framework.Parameter) and x.name.find('logit') ==
        -1
    ]
D
Dun 已提交
49
    if args.init_weights_path.endswith('/'):
D
Dun 已提交
50 51 52 53 54
        if args.num_classes == 19:
            fluid.io.load_params(
                exe, dirname=args.init_weights_path, main_program=tp)
        else:
            fluid.io.load_vars(exe, dirname=args.init_weights_path, vars=myvars)
D
Dun 已提交
55
    else:
D
Dun 已提交
56 57
        if args.num_classes == 19:
            fluid.io.load_params(
D
Dun 已提交
58 59 60 61
                exe,
                dirname="",
                filename=args.init_weights_path,
                main_program=tp)
D
Dun 已提交
62 63 64
        else:
            fluid.io.load_vars(
                exe, dirname="", filename=args.init_weights_path, vars=myvars)
D
Dun 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93


def save_model():
    if args.save_weights_path.endswith('/'):
        fluid.io.save_params(
            exe, dirname=args.save_weights_path, main_program=tp)
    else:
        fluid.io.save_params(
            exe, dirname="", filename=args.save_weights_path, main_program=tp)


def loss(logit, label):
    label_nignore = (label < num_classes).astype('float32')
    label = fluid.layers.elementwise_min(
        label,
        fluid.layers.assign(np.array(
            [num_classes - 1], dtype=np.int32)))
    logit = fluid.layers.transpose(logit, [0, 2, 3, 1])
    logit = fluid.layers.reshape(logit, [-1, num_classes])
    label = fluid.layers.reshape(label, [-1, 1])
    label = fluid.layers.cast(label, 'int64')
    label_nignore = fluid.layers.reshape(label_nignore, [-1, 1])
    loss = fluid.layers.softmax_with_cross_entropy(logit, label)
    loss = loss * label_nignore
    no_grad_set.add(label_nignore.name)
    no_grad_set.add(label.name)
    return loss, label_nignore


Z
add ce  
zhengya01 已提交
94 95 96 97 98 99 100 101
def get_cards(args):
    if args.enable_ce:
        cards = os.environ.get('CUDA_VISIBLE_DEVICES')
        num = len(cards.split(","))
        return num
    else:
        return args.num_devices

D
Dun 已提交
102

D
Dun 已提交
103 104 105 106 107 108 109 110 111 112
CityscapeDataset = reader.CityscapeDataset
parser = argparse.ArgumentParser()

add_arguments()

args = parser.parse_args()

models.clean()
models.bn_momentum = 0.9997
models.dropout_keep_prop = 0.9
D
Dun 已提交
113
models.label_number = args.num_classes
D
Dun 已提交
114 115 116 117
deeplabv3p = models.deeplabv3p

sp = fluid.Program()
tp = fluid.Program()
Z
add ce  
zhengya01 已提交
118 119 120 121 122 123 124

# only for ce
if args.enable_ce:
    SEED = 102
    sp.random_seed = SEED
    tp.random_seed = SEED

D
Dun 已提交
125 126 127 128 129
crop_size = args.train_crop_size
batch_size = args.batch_size
image_shape = [crop_size, crop_size]
reader.default_config['crop_size'] = crop_size
reader.default_config['shuffle'] = True
D
Dun 已提交
130
num_classes = args.num_classes
D
Dun 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
weight_decay = 0.00004

base_lr = args.base_lr
total_step = args.total_step

no_grad_set = set()

with fluid.program_guard(tp, sp):
    img = fluid.layers.data(
        name='img', shape=[3] + image_shape, dtype='float32')
    label = fluid.layers.data(name='label', shape=image_shape, dtype='int32')
    logit = deeplabv3p(img)
    pred = fluid.layers.argmax(logit, axis=1).astype('int32')
    loss, mask = loss(logit, label)
    lr = fluid.layers.polynomial_decay(
        base_lr, total_step, end_learning_rate=0, power=0.9)
    area = fluid.layers.elementwise_max(
        fluid.layers.reduce_mean(mask),
        fluid.layers.assign(np.array(
            [0.1], dtype=np.float32)))
    loss_mean = fluid.layers.reduce_mean(loss) / area

    opt = fluid.optimizer.Momentum(
        lr,
        momentum=0.9,
        regularization=fluid.regularizer.L2DecayRegularizer(
            regularization_coeff=weight_decay), )
    retv = opt.minimize(loss_mean, startup_program=sp, no_grad_set=no_grad_set)

fluid.memory_optimize(
D
Dun 已提交
161
    tp, print_log=False, skip_opt_set=set([pred.name, loss_mean.name]), level=1)
D
Dun 已提交
162 163 164 165 166 167 168 169

place = fluid.CPUPlace()
if args.use_gpu:
    place = fluid.CUDAPlace(0)
exe = fluid.Executor(place)
exe.run(sp)

if args.init_weights_path:
170
    print("load from:", args.init_weights_path)
D
Dun 已提交
171 172 173 174 175 176 177 178 179 180
    load_model()

dataset = CityscapeDataset(args.dataset_path, 'train')

if args.parallel:
    exe_p = fluid.ParallelExecutor(
        use_cuda=True, loss_name=loss_mean.name, main_program=tp)

batches = dataset.get_batch_generator(batch_size, total_step)

Z
add ce  
zhengya01 已提交
181 182 183 184
total_time = 0.0
epoch_idx = 0
train_loss = 0

D
Dun 已提交
185
for i, imgs, labels, names in batches:
Z
add ce  
zhengya01 已提交
186 187
    epoch_idx += 1
    begin_time = time.time()
C
ccmeteorljh 已提交
188
    prev_start_time = time.time()
D
Dun 已提交
189 190 191 192 193 194 195 196 197
    if args.parallel:
        retv = exe_p.run(fetch_list=[pred.name, loss_mean.name],
                         feed={'img': imgs,
                               'label': labels})
    else:
        retv = exe.run(tp,
                       feed={'img': imgs,
                             'label': labels},
                       fetch_list=[pred, loss_mean])
C
ccmeteorljh 已提交
198
    end_time = time.time()
Z
add ce  
zhengya01 已提交
199
    total_time += end_time - begin_time
D
Dun 已提交
200
    if i % 100 == 0:
201
        print("Model is saved to", args.save_weights_path)
D
Dun 已提交
202
        save_model()
D
Dun 已提交
203 204
    print("step {:d}, loss: {:.6f}, step_time_cost: {:.3f}".format(
        i, np.mean(retv[1]), end_time - prev_start_time))
D
Dun 已提交
205

Z
add ce  
zhengya01 已提交
206 207 208 209 210 211
    # only for ce
    train_loss = np.mean(retv[1])

if args.enable_ce:
    gpu_num = get_cards(args)
    print("kpis\teach_pass_duration_card%s\t%s" %
D
Dun 已提交
212 213
          (gpu_num, total_time / epoch_idx))
    print("kpis\ttrain_loss_card%s\t%s" % (gpu_num, train_loss))
Z
add ce  
zhengya01 已提交
214

215
print("Training done. Model is saved to", args.save_weights_path)
D
Dun 已提交
216
save_model()