train_seg.py 10.6 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#  Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

import os
import sys
import time
import shutil
import argparse
import ast
import logging
import numpy as np
import paddle.fluid as fluid
X
xiaosang 已提交
24
import paddle.fluid.framework as framework
K
Kaipeng Deng 已提交
25 26 27

from models import *
from data.indoor3d_reader import Indoor3DReader
K
Kaipeng Deng 已提交
28
from utils import *
K
Kaipeng Deng 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

logging.root.handlers = []
FORMAT = '%(asctime)s-%(levelname)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)
logger = logging.getLogger(__name__)


def parse_args():
    parser = argparse.ArgumentParser("PointNet++ semantic segmentation train script")
    parser.add_argument(
        '--model',
        type=str,
        default='MSG',
        help='SSG or MSG model to train, default MSG')
    parser.add_argument(
        '--use_gpu',
        type=ast.literal_eval,
        default=True,
        help='default use gpu.')
    parser.add_argument(
        '--batch_size',
        type=int,
        default=32,
        help='training batch size, default 32')
    parser.add_argument(
        '--num_points',
        type=int,
        default=4096,
        help='number of points in a sample, default: 4096')
    parser.add_argument(
        '--num_classes',
        type=int,
        default=13,
        help='number of classes in dataset, default: 13')
    parser.add_argument(
        '--lr',
        type=float,
        default=0.01,
        help='initial learning rate, default 0.01')
    parser.add_argument(
        '--lr_decay',
        type=float,
        default=0.5,
        help='learning rate decay gamma, default 0.5')
    parser.add_argument(
        '--bn_momentum',
        type=float,
        default=0.99,
        help='initial batch norm momentum, default 0.99')
    parser.add_argument(
        '--decay_steps',
        type=int,
        default=6250,
        help='learning rate and batch norm momentum decay steps, default 6250')
    parser.add_argument(
        '--weight_decay',
        type=float,
        default=0.,
        help='L2 regularization weight decay coeff, default 0.')
    parser.add_argument(
        '--epoch',
        type=int,
        default=201,
        help='epoch number. default 201.')
    parser.add_argument(
        '--data_dir',
        type=str,
        default='dataset/Indoor3DSemSeg/indoor3d_sem_seg_hdf5_data',
        help='dataset directory')
    parser.add_argument(
        '--save_dir',
        type=str,
        default='checkpoints_seg',
        help='directory name to save train snapshoot')
    parser.add_argument(
        '--resume',
        type=str,
        default=None,
        help='path to resume training based on previous checkpoints. '
        'None for not resuming any checkpoints.')
    parser.add_argument(
        '--log_interval',
        type=int,
        default=1,
        help='mini-batch interval for logging.')
X
xiaosang 已提交
114 115 116 117 118
    parser.add_argument(
        '--enable_ce',
        action='store_true',
        help='The flag indicating whether to run the task '
        'for continuous evaluation.')
K
Kaipeng Deng 已提交
119 120 121 122 123 124
    args = parser.parse_args()
    return args


def train():
    args = parse_args()
K
Kaipeng Deng 已提交
125
    print_arguments(args)
K
Kaipeng Deng 已提交
126 127 128 129 130 131 132 133 134 135
    # check whether the installed paddle is compiled with GPU
    check_gpu(args.use_gpu)

    if not os.path.isdir(args.save_dir):
        os.makedirs(args.save_dir)

    assert args.model in ['MSG', 'SSG'], \
            "--model can only be 'MSG' or 'SSG'"

    # build model
X
xiaosang 已提交
136 137 138 139 140
    if args.enable_ce:
        SEED = 102
        fluid.default_main_program().random_seed = SEED
        framework.default_startup_program().random_seed = SEED

K
Kaipeng Deng 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    startup = fluid.Program()
    train_prog = fluid.Program()
    with fluid.program_guard(train_prog, startup):
        with fluid.unique_name.guard():
            train_model = PointNet2SemSegMSG(args.num_classes, args.num_points) \
                            if args.model == "MSG" else \
                          PointNet2SemSegSSG(args.num_classes, args.num_points)
            train_model.build_model(bn_momentum=args.bn_momentum)
            train_feeds = train_model.get_feeds()
            train_pyreader = train_model.get_pyreader()
            train_outputs = train_model.get_outputs()
            train_loss = train_outputs['loss']
            lr = fluid.layers.exponential_decay(
                    learning_rate=args.lr,
                    decay_steps=args.decay_steps,
                    decay_rate=args.lr_decay,
                    staircase=True)
            lr = fluid.layers.clip(lr, 1e-5, args.lr)
            optimizer = fluid.optimizer.Adam(learning_rate=lr,
                    regularization=fluid.regularizer.L2Decay(args.weight_decay))
            optimizer.minimize(train_loss)
    train_keys, train_values = parse_outputs(train_outputs)

    test_prog = fluid.Program()
    with fluid.program_guard(test_prog, startup):
        with fluid.unique_name.guard():
            test_model = PointNet2SemSegMSG(args.num_classes, args.num_points) \
                           if args.model == "MSG" else \
                         PointNet2SemSegSSG(args.num_classes, args.num_points)
            test_model.build_model()
            test_feeds = test_model.get_feeds()
            test_outputs = test_model.get_outputs()
            test_pyreader = test_model.get_pyreader()
    test_prog = test_prog.clone(True)
    test_keys, test_values = parse_outputs(test_outputs)

    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
    exe = fluid.Executor(place)
    exe.run(startup)

    if args.resume:
        assert os.path.exists(args.resume), \
                "Given resume weight dir {} not exist.".format(args.resume)
        def if_exist(var):
            return os.path.exists(os.path.join(args.resume, var.name))
        fluid.io.load_vars(
            exe, args.resume, predicate=if_exist, main_program=train_prog)

    build_strategy = fluid.BuildStrategy()
    build_strategy.memory_optimize = False
    build_strategy.enable_inplace = False
    build_strategy.fuse_all_optimizer_ops = False
    train_compile_prog = fluid.compiler.CompiledProgram(
            train_prog).with_data_parallel(loss_name=train_loss.name,
                    build_strategy=build_strategy)
    test_compile_prog = fluid.compiler.CompiledProgram(test_prog)

    def save_model(exe, prog, path):
        if os.path.isdir(path):
            shutil.rmtree(path)
        logger.info("Save model to {}".format(path))
        fluid.io.save_persistables(exe, path, prog)

    # get reader
    indoor_reader = Indoor3DReader(args.data_dir)
    train_reader = indoor_reader.get_reader(args.batch_size, args.num_points, mode='train')
    test_reader = indoor_reader.get_reader(args.batch_size, args.num_points, mode='test')
    train_pyreader.decorate_sample_list_generator(train_reader, place)
    test_pyreader.decorate_sample_list_generator(test_reader, place)

    train_stat = Stat()
    test_stat = Stat()
X
xiaosang 已提交
213 214 215 216

    ce_time = 0
    ce_loss = []

K
Kaipeng Deng 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    for epoch_id in range(args.epoch):
        try:
            train_pyreader.start()
            train_iter = 0
            train_periods = []
            while True:
                cur_time = time.time()
                train_outs = exe.run(train_compile_prog, fetch_list=train_values + [lr.name])
                period = time.time() - cur_time
                train_periods.append(period)
                train_stat.update(train_keys, train_outs[:-1])
                if train_iter % args.log_interval == 0:
                    log_str = ""
                    for name, values in zip(train_keys + ['learning_rate'], train_outs):
                        log_str += "{}: {:.5f}, ".format(name, np.mean(values))
X
xiaosang 已提交
232 233
                        if name == 'loss':
                            ce_loss.append(np.mean(values))
K
Kaipeng Deng 已提交
234 235 236 237
                    logger.info("[TRAIN] Epoch {}, batch {}: {}time: {:.2f}".format(epoch_id, train_iter, log_str, period))
                train_iter += 1
        except fluid.core.EOFException:
            logger.info("[TRAIN] Epoch {} finished, {}average time: {:.2f}".format(epoch_id, train_stat.get_mean_log(), np.mean(train_periods[1:])))
X
xiaosang 已提交
238
            ce_time = np.mean(train_periods[1:])
K
Kaipeng Deng 已提交
239 240 241
            save_model(exe, train_prog, os.path.join(args.save_dir, str(epoch_id)))
            
            # evaluation
X
xiaosang 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
            if not args.enable_ce:
                try:
                    test_pyreader.start()
                    test_iter = 0
                    test_periods = []
                    while True:
                        cur_time = time.time()
                        test_outs = exe.run(test_compile_prog, fetch_list=test_values)
                        period = time.time() - cur_time
                        test_periods.append(period)
                        test_stat.update(test_keys, test_outs)
                        if test_iter % args.log_interval == 0:
                            log_str = ""
                            for name, value in zip(test_keys, test_outs):
                                log_str += "{}: {:.4f}, ".format(name, np.mean(value))
                            logger.info("[TEST] Epoch {}, batch {}: {}time: {:.2f}".format(epoch_id, test_iter, log_str, period))
                        test_iter += 1
                except fluid.core.EOFException:
                    logger.info("[TEST] Epoch {} finished, {}average time: {:.2f}".format(epoch_id, test_stat.get_mean_log(), np.mean(test_periods[1:])))
                finally:
                    test_pyreader.reset()
                    test_stat.reset()
                    test_periods = []
K
Kaipeng Deng 已提交
265 266 267 268 269 270

        finally:
            train_pyreader.reset()
            train_stat.reset()
            train_periods = []

X
xiaosang 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    # only for ce
    if args.enable_ce:
        card_num = get_cards()
        _loss = 0
        _time = 0
        try:
            _time = ce_time
            _loss = np.mean(ce_loss[1:])
        except:
            print("ce info error")
        print("kpis\ttrain_seg_%s_duration_card%s\t%s" % (args.model, card_num, _time))
        print("kpis\ttrain_seg_%s_loss_card%s\t%f" % (args.model, card_num, _loss))

def get_cards():
    num = 0
    cards = os.environ.get('CUDA_VISIBLE_DEVICES', '')
    if cards != '':
        num = len(cards.split(","))
    return num
K
Kaipeng Deng 已提交
290 291 292

if __name__ == "__main__":
    train()