program.py 12.0 KB
Newer Older
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
3 4 5
# 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
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# 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.
W
WuHaobo 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import time

from collections import OrderedDict

import paddle.fluid as fluid

from ppcls.optimizer import LearningRateBuilder
from ppcls.optimizer import OptimizerBuilder
from ppcls.modeling import architectures
from ppcls.modeling.loss import CELoss
from ppcls.modeling.loss import MixCELoss
littletomatodonkey's avatar
littletomatodonkey 已提交
31
from ppcls.modeling.loss import JSDivLoss
W
WuHaobo 已提交
32 33 34 35
from ppcls.modeling.loss import GoogLeNetLoss
from ppcls.utils.misc import AverageMeter
from ppcls.utils import logger

W
WuHaobo 已提交
36
from paddle.fluid.dygraph.base import to_variable
W
WuHaobo 已提交
37 38 39 40
from paddle.fluid.incubate.fleet.collective import fleet
from paddle.fluid.incubate.fleet.collective import DistributedStrategy


W
WuHaobo 已提交
41
def create_dataloader():
W
WuHaobo 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    """
    Create a dataloader with model input variables

    Args:
        feeds(dict): dict of model input variables

    Returns:
        dataloader(fluid dataloader):
    """
    trainer_num = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))
    capacity = 64 if trainer_num <= 1 else 8
    dataloader = fluid.io.DataLoader.from_generator(
        capacity=capacity,
        use_double_buffer=True,
        iterable=True)

    return dataloader


W
WuHaobo 已提交
61
def create_model(architecture, classes_num):
W
WuHaobo 已提交
62 63 64 65
    """
    Create a model

    Args:
66 67
        architecture(dict): architecture information,
            name(such as ResNet50) is needed
W
WuHaobo 已提交
68 69 70 71 72 73
        image(variable): model input variable
        classes_num(int): num of classes

    Returns:
        out(variable): model output variable
    """
littletomatodonkey's avatar
littletomatodonkey 已提交
74
    name = architecture["name"]
littletomatodonkey's avatar
littletomatodonkey 已提交
75
    params = architecture.get("params", {})
W
WuHaobo 已提交
76
    return architectures.__dict__[name](class_dim=classes_num, **params)
W
WuHaobo 已提交
77 78 79


def create_loss(out,
W
WuHaobo 已提交
80
                label,
W
WuHaobo 已提交
81 82 83
                architecture,
                classes_num=1000,
                epsilon=None,
littletomatodonkey's avatar
littletomatodonkey 已提交
84 85
                use_mix=False,
                use_distillation=False):
W
WuHaobo 已提交
86 87 88 89 90 91 92 93 94 95 96
    """
    Create a loss for optimization, such as:
        1. CrossEnotry loss
        2. CrossEnotry loss with label smoothing
        3. CrossEnotry loss with mix(mixup, cutmix, fmix)
        4. CrossEnotry loss with label smoothing and (mixup, cutmix, fmix)
        5. GoogLeNet loss

    Args:
        out(variable): model output variable
        feeds(dict): dict of model input variables
97 98
        architecture(dict): architecture information,
            name(such as ResNet50) is needed
W
WuHaobo 已提交
99 100
        classes_num(int): num of classes
        epsilon(float): parameter for label smoothing, 0.0 <= epsilon <= 1.0
littletomatodonkey's avatar
littletomatodonkey 已提交
101
        use_mix(bool): whether to use mix(include mixup, cutmix, fmix)
W
WuHaobo 已提交
102 103 104 105

    Returns:
        loss(variable): loss variable
    """
littletomatodonkey's avatar
littletomatodonkey 已提交
106
    if architecture["name"] == "GoogLeNet":
W
WuHaobo 已提交
107 108
        assert len(out) == 3, "GoogLeNet should have 3 outputs"
        loss = GoogLeNetLoss(class_dim=classes_num, epsilon=epsilon)
W
WuHaobo 已提交
109
        return loss(out[0], out[1], out[2], label)
W
WuHaobo 已提交
110

littletomatodonkey's avatar
littletomatodonkey 已提交
111
    if use_distillation:
112 113
        assert len(out) == 2, ("distillation output length must be 2, "
                               "but got {}".format(len(out)))
littletomatodonkey's avatar
littletomatodonkey 已提交
114 115 116 117
        loss = JSDivLoss(class_dim=classes_num, epsilon=epsilon)
        return loss(out[1], out[0])

    if use_mix:
W
WuHaobo 已提交
118
        loss = MixCELoss(class_dim=classes_num, epsilon=epsilon)
W
WuHaobo 已提交
119 120 121 122 123
        raise NotImplementedError
        #feed_y_a = feeds['feed_y_a']
        #feed_y_b = feeds['feed_y_b']
        #feed_lam = feeds['feed_lam']
        #return loss(out, feed_y_a, feed_y_b, feed_lam)
W
WuHaobo 已提交
124 125
    else:
        loss = CELoss(class_dim=classes_num, epsilon=epsilon)
W
WuHaobo 已提交
126
        return loss(out, label)
W
WuHaobo 已提交
127 128


W
WuHaobo 已提交
129
def create_metric(out,
W
WuHaobo 已提交
130
                  label,
W
WuHaobo 已提交
131 132 133
                  architecture,
                  topk=5,
                  classes_num=1000,
littletomatodonkey's avatar
littletomatodonkey 已提交
134
                  use_distillation=False):
W
WuHaobo 已提交
135 136 137 138 139 140 141 142 143 144 145 146
    """
    Create measures of model accuracy, such as top1 and top5

    Args:
        out(variable): model output variable
        feeds(dict): dict of model input variables(included label)
        topk(int): usually top5
        classes_num(int): num of classes

    Returns:
        fetchs(dict): dict of measures
    """
W
WuHaobo 已提交
147 148 149 150 151 152 153 154 155
    if architecture["name"] == "GoogLeNet":
        assert len(out) == 3, "GoogLeNet should have 3 outputs"
        softmax_out = out[0]
    else:
        # just need student label to get metrics
        if use_distillation:
            out = out[1]
        softmax_out = fluid.layers.softmax(out, use_cudnn=False)

W
WuHaobo 已提交
156
    fetchs = OrderedDict()
W
WuHaobo 已提交
157
    # set top1 to fetchs
W
WuHaobo 已提交
158 159
    top1 = fluid.layers.accuracy(softmax_out, label=label, k=1)
    fetchs['top1'] = top1
W
WuHaobo 已提交
160
    # set topk to fetchs
W
WuHaobo 已提交
161
    k = min(topk, classes_num)
W
WuHaobo 已提交
162
    topk = fluid.layers.accuracy(softmax_out, label=label, k=k)
W
WuHaobo 已提交
163
    topk_name = 'top{}'.format(k)
W
WuHaobo 已提交
164
    fetchs[topk_name] = topk
W
WuHaobo 已提交
165 166 167 168 169

    return fetchs


def create_fetchs(out,
W
WuHaobo 已提交
170
                  label,
W
WuHaobo 已提交
171 172 173 174
                  architecture,
                  topk=5,
                  classes_num=1000,
                  epsilon=None,
littletomatodonkey's avatar
littletomatodonkey 已提交
175 176
                  use_mix=False,
                  use_distillation=False):
W
WuHaobo 已提交
177 178
    """
    Create fetchs as model outputs(included loss and measures),
littletomatodonkey's avatar
littletomatodonkey 已提交
179
    will call create_loss and create_metric(if use_mix).
W
WuHaobo 已提交
180 181 182

    Args:
        out(variable): model output variable
W
WuHaobo 已提交
183 184
        feeds(dict): dict of model input variables.
            If use mix_up, it will not include label.
185 186
        architecture(dict): architecture information,
            name(such as ResNet50) is needed
W
WuHaobo 已提交
187 188 189
        topk(int): usually top5
        classes_num(int): num of classes
        epsilon(float): parameter for label smoothing, 0.0 <= epsilon <= 1.0
littletomatodonkey's avatar
littletomatodonkey 已提交
190
        use_mix(bool): whether to use mix(include mixup, cutmix, fmix)
W
WuHaobo 已提交
191 192 193 194 195

    Returns:
        fetchs(dict): dict of model outputs(included loss and measures)
    """
    fetchs = OrderedDict()
W
WuHaobo 已提交
196
    fetchs['loss'] = create_loss(out, label, architecture, classes_num, epsilon, use_mix,
littletomatodonkey's avatar
littletomatodonkey 已提交
197 198
                       use_distillation)
    if not use_mix:
W
WuHaobo 已提交
199
        metric = create_metric(out, label, architecture, topk, classes_num,
W
WuHaobo 已提交
200
                               use_distillation)
W
WuHaobo 已提交
201 202 203 204 205
        fetchs.update(metric)

    return fetchs


W
WuHaobo 已提交
206
def create_optimizer(config, parameter_list=None):
W
WuHaobo 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    """
    Create an optimizer using config, usually including
    learning rate and regularization.

    Args:
        config(dict):  such as
        {
            'LEARNING_RATE':
                {'function': 'Cosine',
                 'params': {'lr': 0.1}
                },
            'OPTIMIZER':
                {'function': 'Momentum',
                 'params':{'momentum': 0.9},
                 'regularizer':
                    {'function': 'L2', 'factor': 0.0001}
                }
        }

    Returns:
        an optimizer instance
    """
    # create learning_rate instance
    lr_config = config['LEARNING_RATE']
    lr_config['params'].update({
        'epochs': config['epochs'],
        'step_each_epoch':
        config['total_images'] // config['TRAIN']['batch_size'],
    })
    lr = LearningRateBuilder(**lr_config)()

    # create optimizer instance
    opt_config = config['OPTIMIZER']
    opt = OptimizerBuilder(**opt_config)
W
WuHaobo 已提交
241
    return opt(lr, parameter_list)
W
WuHaobo 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267


def dist_optimizer(config, optimizer):
    """
    Create a distributed optimizer based on a normal optimizer

    Args:
        config(dict):
        optimizer(): a normal optimizer

    Returns:
        optimizer: a distributed optimizer
    """
    exec_strategy = fluid.ExecutionStrategy()
    exec_strategy.num_threads = 3
    exec_strategy.num_iteration_per_drop_scope = 10

    dist_strategy = DistributedStrategy()
    dist_strategy.nccl_comm_num = 1
    dist_strategy.fuse_all_reduce_ops = True
    dist_strategy.exec_strategy = exec_strategy
    optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy)

    return optimizer


268 269 270 271 272 273 274 275 276 277 278 279 280
def mixed_precision_optimizer(config, optimizer):
    use_fp16 = config.get('use_fp16', False)
    amp_scale_loss = config.get('amp_scale_loss', 1.0)
    use_dynamic_loss_scaling = config.get('use_dynamic_loss_scaling', False)
    if use_fp16:
        optimizer = fluid.contrib.mixed_precision.decorate(
            optimizer,
            init_loss_scaling=amp_scale_loss,
            use_dynamic_loss_scaling=use_dynamic_loss_scaling)

    return optimizer


W
WuHaobo 已提交
281
def compute(config, out, label, mode='train'):
W
WuHaobo 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    """
    Build a program using a model and an optimizer
        1. create feeds
        2. create a dataloader
        3. create a model
        4. create fetchs
        5. create an optimizer

    Args:
        config(dict): config
        main_prog(): main program
        startup_prog(): startup program
        is_train(bool): train or valid

    Returns:
        dataloader(): a bridge between the model and the data
        fetchs(dict): dict of model outputs(included loss and measures)
    """
W
WuHaobo 已提交
300 301 302 303 304 305 306 307 308
    fetchs = create_fetchs(
        out,
        label,
        config.ARCHITECTURE,
        config.topk,
        config.classes_num,
        epsilon=config.get('ls_epsilon'),
        use_mix=config.get('use_mix') and mode == 'train',
        use_distillation=config.get('use_distillation'))
W
WuHaobo 已提交
309

W
WuHaobo 已提交
310
    return fetchs
W
WuHaobo 已提交
311 312


W
WuHaobo 已提交
313
def run(dataloader, config, net, optimizer=None, epoch=0, mode='train'):
W
WuHaobo 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326
    """
    Feed data to the model and fetch the measures and loss

    Args:
        dataloader(fluid dataloader):
        exe():
        program():
        fetchs(dict): dict of measures and the loss
        epoch(int): epoch of training or validation
        model(str): log only

    Returns:
    """
W
WuHaobo 已提交
327 328 329 330 331 332 333 334 335
    topk_name = 'top{}'.format(config.topk)
    metric_list = OrderedDict([
        ("loss", AverageMeter('loss', '7.4f')),
        ("top1", AverageMeter('top1', '.4f')),
        (topk_name, AverageMeter(topk_name, '.4f')),
        ("lr", AverageMeter('lr', 'f', need_avg=False)),
        ("batch_time", AverageMeter('elapse', '.3f')),
    ])

W
WuHaobo 已提交
336
    tic = time.time()
W
WuHaobo 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    for idx, (img, label) in enumerate(dataloader()):
        label = to_variable(label.numpy().astype('int64').reshape(-1, 1))
        fetchs = compute(config, net(img), label, mode)
        if mode == 'train':
            avg_loss = net.scale_loss(fetchs['loss'])
            avg_loss.backward()
            net.apply_collective_grads()

            optimizer.minimize(avg_loss)
            net.clear_gradients()
            metric_list['lr'].update(
                    optimizer._global_learning_rate().numpy()[0], len(img))

        for name, fetch in fetchs.items():
            metric_list[name].update(fetch.numpy()[0], len(img))
        metric_list['batch_time'].update(time.time() - tic)
W
WuHaobo 已提交
353
        tic = time.time()
W
WuHaobo 已提交
354 355

        fetchs_str = ' '.join([str(m.value) for m in metric_list.values()])
W
WuHaobo 已提交
356
        if mode == 'eval':
W
WuHaobo 已提交
357 358
            logger.info("{:s} step:{:<4d} {:s}s".format(mode, idx, fetchs_str))
        else:
S
shippingwang 已提交
359 360 361
            epoch_str = "epoch:{:<3d}".format(epoch)
            step_str = "{:s} step:{:<4d}".format(mode, idx)

W
WuHaobo 已提交
362
            logger.info("{:s} {:s} {:s}s".format(
363 364 365 366
                logger.coloring(epoch_str, "HEADER")
                if idx == 0 else epoch_str,
                logger.coloring(step_str, "PURPLE"),
                logger.coloring(fetchs_str, 'OKGREEN')))
S
refine  
shippingwang 已提交
367

W
WuHaobo 已提交
368
    end_str = ' '.join([str(m.mean) for m in metric_list.values()] + [metric_list['batch_time'].total])
W
WuHaobo 已提交
369
    if mode == 'eval':
S
refine  
shippingwang 已提交
370
        logger.info("END {:s} {:s}s".format(mode, end_str))
W
WuHaobo 已提交
371
    else:
S
shippingwang 已提交
372 373
        end_epoch_str = "END epoch:{:<3d}".format(epoch)

W
WuHaobo 已提交
374
        logger.info("{:s} {:s} {:s}s".format(
375 376 377
            logger.coloring(end_epoch_str, "RED"),
            logger.coloring(mode, "PURPLE"),
            logger.coloring(end_str, "OKGREEN")))
littletomatodonkey's avatar
littletomatodonkey 已提交
378

W
WuHaobo 已提交
379
    # return top1_acc in order to save the best model
W
WuHaobo 已提交
380
    if mode == 'valid':
W
WuHaobo 已提交
381
        return metric_list['top1'].avg