engine.py 12.1 KB
Newer Older
D
dongshuilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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
from __future__ import division
from __future__ import print_function

D
dongshuilong 已提交
17
import os
D
dongshuilong 已提交
18 19 20
import paddle
import paddle.distributed as dist
from visualdl import LogWriter
D
dongshuilong 已提交
21
from paddle import nn
D
dongshuilong 已提交
22 23
import numpy as np
import random
D
dongshuilong 已提交
24

G
gaotingquan 已提交
25
from ..utils.amp import AMPForwardDecorator
D
dongshuilong 已提交
26 27 28
from ppcls.utils import logger
from ppcls.utils.logger import init_logger
from ppcls.utils.config import print_config
W
dbg  
weishengyu 已提交
29
from ppcls.arch import build_model, RecModel, DistillationModel, TheseusLayer
D
dongshuilong 已提交
30 31 32 33 34
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

from ppcls.data.utils.get_image_list import get_image_list
from ppcls.data.postprocess import build_postprocess
from ppcls.data import create_operators
35
from .train import build_train_func
36
from .evaluation import build_eval_func
D
dongshuilong 已提交
37
from ppcls.engine import evaluation
D
dongshuilong 已提交
38 39 40
from ppcls.arch.gears.identity_head import IdentityHead


D
dongshuilong 已提交
41
class Engine(object):
D
dongshuilong 已提交
42
    def __init__(self, config, mode="train"):
D
dongshuilong 已提交
43
        assert mode in ["train", "eval", "infer", "export"]
D
dongshuilong 已提交
44 45
        self.mode = mode
        self.config = config
D
dongshuilong 已提交
46

D
dongshuilong 已提交
47
        # init logger
48 49
        log_file = os.path.join(self.config['Global']['output_dir'],
                                self.config["Arch"]["name"], f"{mode}.log")
G
gaotingquan 已提交
50
        init_logger(log_file=log_file)
D
dongshuilong 已提交
51

G
debug  
gaotingquan 已提交
52 53 54
        # set seed
        self._init_seed()

D
dongshuilong 已提交
55
        # set device
56
        self._init_device()
D
dongshuilong 已提交
57 58

        # build model
littletomatodonkey's avatar
littletomatodonkey 已提交
59
        self.model = build_model(self.config, self.mode)
D
dongshuilong 已提交
60

T
Tingquan Gao 已提交
61 62 63 64 65
        # load_pretrain
        self._init_pretrained()

        self._init_amp()

66 67 68 69 70
        # init train_func and eval_func
        self.eval = build_eval_func(
            self.config, mode=self.mode, model=self.model)
        self.train = build_train_func(
            self.config, mode=self.mode, model=self.model, eval_func=self.eval)
71 72

        # for distributed
G
gaotingquan 已提交
73
        self._init_dist()
D
dongshuilong 已提交
74

G
gaotingquan 已提交
75
        print_config(self.config)
76

D
dongshuilong 已提交
77 78 79
    @paddle.no_grad()
    def infer(self):
        assert self.mode == "infer" and self.eval_mode == "classification"
G
gaotingquan 已提交
80 81 82 83 84 85

        self.preprocess_func = create_operators(self.config["Infer"][
            "transforms"])
        self.postprocess_func = build_postprocess(self.config["Infer"][
            "PostProcess"])

86 87
        total_trainer = dist.get_world_size()
        local_rank = dist.get_rank()
D
dongshuilong 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
        image_list = get_image_list(self.config["Infer"]["infer_imgs"])
        # data split
        image_list = image_list[local_rank::total_trainer]

        batch_size = self.config["Infer"]["batch_size"]
        self.model.eval()
        batch_data = []
        image_file_list = []
        for idx, image_file in enumerate(image_list):
            with open(image_file, 'rb') as f:
                x = f.read()
            for process in self.preprocess_func:
                x = process(x)
            batch_data.append(x)
            image_file_list.append(image_file)
            if len(batch_data) >= batch_size or idx == len(image_list) - 1:
                batch_tensor = paddle.to_tensor(batch_data)
105
                out = self.model(batch_tensor)
G
gaotingquan 已提交
106

D
dongshuilong 已提交
107 108
                if isinstance(out, list):
                    out = out[0]
littletomatodonkey's avatar
littletomatodonkey 已提交
109 110
                if isinstance(out, dict) and "Student" in out:
                    out = out["Student"]
111 112 113
                if isinstance(out, dict) and "logits" in out:
                    out = out["logits"]
                if isinstance(out, dict) and "output" in out:
W
dbg  
weishengyu 已提交
114
                    out = out["output"]
D
dongshuilong 已提交
115 116 117 118 119 120 121
                result = self.postprocess_func(out, image_file_list)
                print(result)
                batch_data.clear()
                image_file_list.clear()

    def export(self):
        assert self.mode == "export"
Z
zhiboniu 已提交
122 123
        use_multilabel = self.config["Global"].get(
            "use_multilabel",
C
cuicheng01 已提交
124
            False) or "ATTRMetric" in self.config["Metric"]["Eval"][0]
C
cuicheng01 已提交
125
        model = ExportModel(self.config["Arch"], self.model, use_multilabel)
126 127 128 129 130 131 132 133 134
        if self.config["Global"]["pretrained_model"] is not None:
            if self.config["Global"]["pretrained_model"].startswith("http"):
                load_dygraph_pretrain_from_url(
                    model.base_model,
                    self.config["Global"]["pretrained_model"])
            else:
                load_dygraph_pretrain(
                    model.base_model,
                    self.config["Global"]["pretrained_model"])
D
dongshuilong 已提交
135 136

        model.eval()
G
gaotingquan 已提交
137

138
        # for re-parameterization nets
H
HydrogenSulfate 已提交
139
        for layer in self.model.sublayers():
140 141 142
            if hasattr(layer, "re_parameterize") and not getattr(layer,
                                                                 "is_repped"):
                layer.re_parameterize()
G
gaotingquan 已提交
143

D
dongshuilong 已提交
144 145
        save_path = os.path.join(self.config["Global"]["save_inference_dir"],
                                 "inference")
littletomatodonkey's avatar
littletomatodonkey 已提交
146 147 148 149 150 151 152 153 154 155 156 157

        model = paddle.jit.to_static(
            model,
            input_spec=[
                paddle.static.InputSpec(
                    shape=[None] + self.config["Global"]["image_shape"],
                    dtype='float32')
            ])
        if hasattr(model.base_model,
                   "quanter") and model.base_model.quanter is not None:
            model.base_model.quanter.save_quantized_model(model,
                                                          save_path + "_int8")
D
dongshuilong 已提交
158 159
        else:
            paddle.jit.save(model, save_path)
G
gaotingquan 已提交
160 161 162
        logger.info(
            f"Export succeeded! The inference model exported has been saved in \"{self.config['Global']['save_inference_dir']}\"."
        )
D
dongshuilong 已提交
163

G
gaotingquan 已提交
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
    def _init_seed(self):
        seed = self.config["Global"].get("seed", False)
        if dist.get_world_size() != 1:
            # if self.config["Global"]["distributed"]:
            # set different seed in different GPU manually in distributed environment
            if not seed:
                logger.warning(
                    "The random seed cannot be None in a distributed environment. Global.seed has been set to 42 by default"
                )
                self.config["Global"]["seed"] = seed = 42
            logger.info(
                f"Set random seed to ({int(seed)} + $PADDLE_TRAINER_ID) for different trainer"
            )
            dist_seed = int(seed) + dist.get_rank()
            paddle.seed(dist_seed)
            np.random.seed(dist_seed)
            random.seed(dist_seed)
        elif seed or seed == 0:
            assert isinstance(seed, int), "The 'seed' must be a integer!"
            paddle.seed(seed)
            np.random.seed(seed)
            random.seed(seed)

    def _init_device(self):
        device = self.config["Global"]["device"]
        assert device in ["cpu", "gpu", "xpu", "npu", "mlu", "ascend"]
        logger.info('train with paddle {} and device {}'.format(
            paddle.__version__, device))
192
        paddle.set_device(device)
G
gaotingquan 已提交
193 194 195 196 197

    def _init_pretrained(self):
        if self.config["Global"]["pretrained_model"] is not None:
            if self.config["Global"]["pretrained_model"].startswith("http"):
                load_dygraph_pretrain_from_url(
T
Tingquan Gao 已提交
198
                    [self.model, getattr(self, 'train_loss_func', None)],
G
gaotingquan 已提交
199 200 201
                    self.config["Global"]["pretrained_model"])
            else:
                load_dygraph_pretrain(
T
Tingquan Gao 已提交
202
                    [self.model, getattr(self, 'train_loss_func', None)],
G
gaotingquan 已提交
203 204 205
                    self.config["Global"]["pretrained_model"])

    def _init_amp(self):
206 207 208 209 210 211 212 213
        if "AMP" in self.config and self.config["AMP"] is not None:
            paddle_version = paddle.__version__[:3]
            # paddle version < 2.3.0 and not develop
            if paddle_version not in ["2.3", "2.4", "0.0"]:
                msg = "When using AMP, PaddleClas release/2.6 and later version only support PaddlePaddle version >= 2.3.0."
                logger.error(msg)
                raise Exception(msg)

G
gaotingquan 已提交
214 215 216 217 218 219 220
            AMP_RELATED_FLAGS_SETTING = {'FLAGS_max_inplace_grad_add': 8, }
            if paddle.is_compiled_with_cuda():
                AMP_RELATED_FLAGS_SETTING.update({
                    'FLAGS_cudnn_batchnorm_spatial_persistent': 1
                })
            paddle.set_flags(AMP_RELATED_FLAGS_SETTING)

221 222
            amp_level = self.config['AMP'].get("level", "O1").upper()
            if amp_level not in ["O1", "O2"]:
G
gaotingquan 已提交
223 224 225
                msg = "[Parameter Error]: The optimize level of AMP only support 'O1' and 'O2'. The level has been set 'O1'."
                logger.warning(msg)
                self.config['AMP']["level"] = "O1"
226
                amp_level = "O1"
G
gaotingquan 已提交
227

228
            amp_eval = self.config["AMP"].get("use_fp16_test", False)
G
gaotingquan 已提交
229 230 231
            # TODO(gaotingquan): Paddle not yet support FP32 evaluation when training with AMPO2
            if self.mode == "train" and self.config["Global"].get(
                    "eval_during_train",
232
                    True) and amp_level == "O2" and amp_eval == False:
G
gaotingquan 已提交
233 234 235
                msg = "PaddlePaddle only support FP16 evaluation when training with AMP O2 now. "
                logger.warning(msg)
                self.config["AMP"]["use_fp16_test"] = True
236
                amp_eval = True
G
gaotingquan 已提交
237

238 239 240
            if self.mode == "train" or amp_eval:
                AMPForwardDecorator.amp_level = amp_level
                AMPForwardDecorator.amp_eval = amp_eval
G
gaotingquan 已提交
241

G
gaotingquan 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    def _init_dist(self):
        # check the gpu num
        world_size = dist.get_world_size()
        self.config["Global"]["distributed"] = world_size != 1
        # TODO(gaotingquan):
        if self.mode == "train":
            std_gpu_num = 8 if isinstance(
                self.config["Optimizer"],
                dict) and self.config["Optimizer"]["name"] == "AdamW" else 4
            if world_size != std_gpu_num:
                msg = f"The training strategy provided by PaddleClas is based on {std_gpu_num} gpus. But the number of gpu is {world_size} in current training. Please modify the stategy (learning rate, batch size and so on) if use this config to train."
                logger.warning(msg)

        if self.config["Global"]["distributed"]:
            dist.init_parallel_env()
            self.model = paddle.DataParallel(self.model)
T
Tingquan Gao 已提交
258
            if self.mode == 'train' and len(self.train_loss_func.parameters(
G
gaotingquan 已提交
259
            )) > 0:
T
Tingquan Gao 已提交
260 261
                self.train_loss_func = paddle.DataParallel(
                    self.train_loss_func)
G
gaotingquan 已提交
262

D
dongshuilong 已提交
263

W
dbg  
weishengyu 已提交
264
class ExportModel(TheseusLayer):
D
dongshuilong 已提交
265 266 267 268
    """
    ExportModel: add softmax onto the model
    """

C
cuicheng01 已提交
269
    def __init__(self, config, model, use_multilabel):
D
dongshuilong 已提交
270 271 272 273 274 275 276 277 278 279 280 281
        super().__init__()
        self.base_model = model
        # we should choose a final model to export
        if isinstance(self.base_model, DistillationModel):
            self.infer_model_name = config["infer_model_name"]
        else:
            self.infer_model_name = None

        self.infer_output_key = config.get("infer_output_key", None)
        if self.infer_output_key == "features" and isinstance(self.base_model,
                                                              RecModel):
            self.base_model.head = IdentityHead()
C
cuicheng01 已提交
282 283
        if use_multilabel:
            self.out_act = nn.Sigmoid()
D
dongshuilong 已提交
284
        else:
C
cuicheng01 已提交
285 286 287 288
            if config.get("infer_add_softmax", True):
                self.out_act = nn.Softmax(axis=-1)
            else:
                self.out_act = None
D
dongshuilong 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    def eval(self):
        self.training = False
        for layer in self.sublayers():
            layer.training = False
            layer.eval()

    def forward(self, x):
        x = self.base_model(x)
        if isinstance(x, list):
            x = x[0]
        if self.infer_model_name is not None:
            x = x[self.infer_model_name]
        if self.infer_output_key is not None:
            x = x[self.infer_output_key]
C
cuicheng01 已提交
304
        if self.out_act is not None:
wc晨曦's avatar
wc晨曦 已提交
305 306
            if isinstance(x, dict):
                x = x["logits"]
C
cuicheng01 已提交
307
            x = self.out_act(x)
D
dongshuilong 已提交
308
        return x