train.py 4.1 KB
Newer Older
D
dongshuilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
from __future__ import absolute_import, division, print_function

import time
import paddle
18
from ppcls.engine.train.utils import update_loss, update_metric, log_info, type_name
D
dongshuilong 已提交
19
from ppcls.utils import profiler
D
dongshuilong 已提交
20 21


W
weishengyu 已提交
22
def train_epoch(engine, epoch_id, print_batch_step):
D
dongshuilong 已提交
23
    tic = time.time()
H
add xbm  
HydrogenSulfate 已提交
24 25 26 27

    if not hasattr(engine, "train_dataloader_iter"):
        engine.train_dataloader_iter = iter(engine.train_dataloader)

D
dongshuilong 已提交
28
    for iter_id in range(engine.iter_per_epoch):
H
add xbm  
HydrogenSulfate 已提交
29 30 31 32 33 34 35
        # fetch data batch from dataloader
        try:
            batch = engine.train_dataloader_iter.next()
        except Exception:
            engine.train_dataloader_iter = iter(engine.train_dataloader)
            batch = engine.train_dataloader_iter.next()

D
dongshuilong 已提交
36
        profiler.add_profiler_step(engine.config["profiler_options"])
D
dongshuilong 已提交
37
        if iter_id == 5:
W
weishengyu 已提交
38 39 40
            for key in engine.time_info:
                engine.time_info[key].reset()
        engine.time_info["reader_cost"].update(time.time() - tic)
41

D
dongshuilong 已提交
42
        batch_size = batch[0].shape[0]
43
        if not engine.config["Global"].get("use_multilabel", False):
G
gaotingquan 已提交
44
            batch[1] = batch[1].reshape([batch_size, -1])
W
weishengyu 已提交
45
        engine.global_step += 1
46

D
dongshuilong 已提交
47
        # image input
W
weishengyu 已提交
48
        if engine.amp:
H
add xbm  
HydrogenSulfate 已提交
49
            amp_level = engine.config["AMP"].get("level", "O1").upper()
50 51 52 53 54
            with paddle.amp.auto_cast(
                    custom_black_list={
                        "flatten_contiguous_range", "greater_than"
                    },
                    level=amp_level):
W
weishengyu 已提交
55
                out = forward(engine, batch)
56
                loss_dict = engine.train_loss_func(out, batch[1])
D
dongshuilong 已提交
57
        else:
W
weishengyu 已提交
58
            out = forward(engine, batch)
59
            loss_dict = engine.train_loss_func(out, batch[1])
D
dongshuilong 已提交
60

61 62 63
        # loss
        loss = loss_dict["loss"] / engine.update_freq

H
HydrogenSulfate 已提交
64
        # backward & step opt
W
weishengyu 已提交
65
        if engine.amp:
66
            scaled = engine.scaler.scale(loss)
D
dongshuilong 已提交
67
            scaled.backward()
68 69 70
            if (iter_id + 1) % engine.update_freq == 0:
                for i in range(len(engine.optimizer)):
                    engine.scaler.minimize(engine.optimizer[i], scaled)
D
dongshuilong 已提交
71
        else:
72 73 74 75 76 77 78
            loss.backward()
            if (iter_id + 1) % engine.update_freq == 0:
                for i in range(len(engine.optimizer)):
                    engine.optimizer[i].step()

        if (iter_id + 1) % engine.update_freq == 0:
            # clear grad
79
            for i in range(len(engine.optimizer)):
80
                engine.optimizer[i].clear_grad()
Y
Yang Nie 已提交
81
            # step lr(by step)
82
            for i in range(len(engine.lr_sch)):
Y
Yang Nie 已提交
83 84
                if not getattr(engine.lr_sch[i], "by_epoch", False):
                    engine.lr_sch[i].step()
85 86 87
            # update ema
            if engine.ema:
                engine.model_ema.update(engine.model)
D
dongshuilong 已提交
88 89 90

        # below code just for logging
        # update metric_for_logger
W
weishengyu 已提交
91
        update_metric(engine, out, batch, batch_size)
D
dongshuilong 已提交
92
        # update_loss_for_logger
W
weishengyu 已提交
93 94
        update_loss(engine, loss_dict, batch_size)
        engine.time_info["batch_cost"].update(time.time() - tic)
D
dongshuilong 已提交
95
        if iter_id % print_batch_step == 0:
W
weishengyu 已提交
96
            log_info(engine, batch_size, epoch_id, iter_id)
D
dongshuilong 已提交
97
        tic = time.time()
D
dongshuilong 已提交
98

H
HydrogenSulfate 已提交
99 100
    # step lr(by epoch)
    for i in range(len(engine.lr_sch)):
101 102
        if getattr(engine.lr_sch[i], "by_epoch", False) and \
                type_name(engine.lr_sch[i]) != "ReduceOnPlateau":
H
HydrogenSulfate 已提交
103 104
            engine.lr_sch[i].step()

D
dongshuilong 已提交
105

C
cuicheng01 已提交
106 107 108
def forward(engine, batch):
    if not engine.is_rec:
        return engine.model(batch[0])
D
dongshuilong 已提交
109
    else:
C
cuicheng01 已提交
110
        return engine.model(batch[0], batch[1])