train.py 3.1 KB
Newer Older
D
dongshuilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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
from ppcls.engine.train.utils import update_loss, update_metric, log_info
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()
W
weishengyu 已提交
24 25
    for iter_id, batch in enumerate(engine.train_dataloader):
        if iter_id >= engine.max_iter:
D
dongshuilong 已提交
26
            break
D
dongshuilong 已提交
27
        profiler.add_profiler_step(engine.config["profiler_options"])
D
dongshuilong 已提交
28
        if iter_id == 5:
W
weishengyu 已提交
29 30 31 32
            for key in engine.time_info:
                engine.time_info[key].reset()
        engine.time_info["reader_cost"].update(time.time() - tic)
        if engine.use_dali:
D
dongshuilong 已提交
33 34 35 36 37
            batch = [
                paddle.to_tensor(batch[0]['data']),
                paddle.to_tensor(batch[0]['label'])
            ]
        batch_size = batch[0].shape[0]
38
        if not engine.config["Global"].get("use_multilabel", False):
C
cuicheng01 已提交
39
            batch[1] = batch[1].reshape([-1, 1]).astype("int64")
W
weishengyu 已提交
40
        engine.global_step += 1
D
dongshuilong 已提交
41 42

        # image input
W
weishengyu 已提交
43
        if engine.amp:
D
dongshuilong 已提交
44 45 46
            with paddle.amp.auto_cast(custom_black_list={
                    "flatten_contiguous_range", "greater_than"
            }):
W
weishengyu 已提交
47 48
                out = forward(engine, batch)
                loss_dict = engine.train_loss_func(out, batch[1])
D
dongshuilong 已提交
49
        else:
W
weishengyu 已提交
50
            out = forward(engine, batch)
D
dongshuilong 已提交
51 52

        # calc loss
W
weishengyu 已提交
53
        if engine.config["DataLoader"]["Train"]["dataset"].get(
D
dongshuilong 已提交
54
                "batch_transform_ops", None):
W
weishengyu 已提交
55
            loss_dict = engine.train_loss_func(out, batch[1:])
D
dongshuilong 已提交
56
        else:
W
weishengyu 已提交
57
            loss_dict = engine.train_loss_func(out, batch[1])
D
dongshuilong 已提交
58 59

        # step opt and lr
W
weishengyu 已提交
60 61
        if engine.amp:
            scaled = engine.scaler.scale(loss_dict["loss"])
D
dongshuilong 已提交
62
            scaled.backward()
W
weishengyu 已提交
63
            engine.scaler.minimize(engine.optimizer, scaled)
D
dongshuilong 已提交
64 65
        else:
            loss_dict["loss"].backward()
W
weishengyu 已提交
66 67 68
            engine.optimizer.step()
        engine.optimizer.clear_grad()
        engine.lr_sch.step()
D
dongshuilong 已提交
69 70 71

        # below code just for logging
        # update metric_for_logger
W
weishengyu 已提交
72
        update_metric(engine, out, batch, batch_size)
D
dongshuilong 已提交
73
        # update_loss_for_logger
W
weishengyu 已提交
74 75
        update_loss(engine, loss_dict, batch_size)
        engine.time_info["batch_cost"].update(time.time() - tic)
D
dongshuilong 已提交
76
        if iter_id % print_batch_step == 0:
W
weishengyu 已提交
77
            log_info(engine, batch_size, epoch_id, iter_id)
D
dongshuilong 已提交
78
        tic = time.time()
D
dongshuilong 已提交
79

D
dongshuilong 已提交
80

C
cuicheng01 已提交
81 82 83
def forward(engine, batch):
    if not engine.is_rec:
        return engine.model(batch[0])
D
dongshuilong 已提交
84
    else:
C
cuicheng01 已提交
85
        return engine.model(batch[0], batch[1])