trainer.py 16.7 KB
Newer Older
W
wuzewu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2020  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.

import os
import pickle
import time
from collections import defaultdict
W
wuzewu 已提交
19
from typing import Any, Callable, Generic, List
W
wuzewu 已提交
20

S
Steffy-zxf 已提交
21
import numpy as np
22
import paddle
W
wuzewu 已提交
23 24
from visualdl import LogWriter

W
wuzewu 已提交
25
from paddlehub.utils.log import logger
W
wuzewu 已提交
26 27 28 29 30
from paddlehub.utils.utils import Timer


class Trainer(object):
    '''
W
wuzewu 已提交
31 32 33 34
    Model trainer

    Args:
        model(paddle.nn.Layer) : Model to train or evaluate.
W
wuzewu 已提交
35
        optimizer(paddle.optimizer.Optimizer) : Optimizer for loss.
36
        use_gpu(bool) : Whether to use gpu to run.
W
wuzewu 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50
        use_vdl(bool) : Whether to use visualdl to record training data.
        checkpoint_dir(str) : Directory where the checkpoint is saved, and the trainer will restore the
            state and model parameters from the checkpoint.
        compare_metrics(callable) : The method of comparing the model metrics. If not specified, the main
            metric return by `validation_step` will be used for comparison by default, the larger the
            value, the better the effect. This method will affect the saving of the best model. If the
            default behavior does not meet your requirements, please pass in a custom method.

            Example:
                .. code-block:: python

                    def compare_metrics(old_metric: dict, new_metric: dict):
                        mainkey = list(new_metric.keys())[0]
                        return old_metric[mainkey] < new_metric[mainkey]
W
wuzewu 已提交
51 52 53
    '''

    def __init__(self,
54
                 model: paddle.nn.Layer,
W
wuzewu 已提交
55
                 optimizer: paddle.optimizer.Optimizer,
56
                 use_gpu: bool = False,
W
wuzewu 已提交
57 58
                 use_vdl: bool = True,
                 checkpoint_dir: str = None,
59 60 61
                 compare_metrics: Callable = None,
                 **kwargs):
        paddle.set_device('gpu') if use_gpu else paddle.set_device('cpu')
W
wuzewu 已提交
62 63
        self.nranks = paddle.distributed.get_world_size()
        self.local_rank = paddle.distributed.get_rank()
W
wuzewu 已提交
64
        self.model = model
W
wuzewu 已提交
65
        self.optimizer = optimizer
W
wuzewu 已提交
66 67
        self.checkpoint_dir = checkpoint_dir if checkpoint_dir else 'ckpt_{}'.format(time.time())

W
wuzewu 已提交
68 69 70
        if not isinstance(self.model, paddle.nn.Layer):
            raise TypeError('The model {} is not a `paddle.nn.Layer` object.'.format(self.model.__name__))

W
wuzewu 已提交
71 72 73 74 75 76 77 78 79 80 81 82
        if self.local_rank == 0 and not os.path.exists(self.checkpoint_dir):
            os.makedirs(self.checkpoint_dir)

        self.use_vdl = use_vdl
        if self.local_rank == 0 and self.use_vdl:
            vdl_dir = os.path.join(self.checkpoint_dir, 'visualization')
            self.log_writer = LogWriter(vdl_dir)

        self.current_epoch = 0
        self.best_metrics = defaultdict(int)

        if self.nranks > 1:
W
wuzewu 已提交
83
            paddle.distributed.init_parallel_env()
H
haoyuying 已提交
84
            self.model = paddle.DataParallel(self.model)
W
wuzewu 已提交
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 114 115 116
        self.compare_metrics = self._compare_metrics if not compare_metrics else compare_metrics
        self._load_checkpoint()

    def _load_checkpoint(self):
        '''Load checkpoint and state dict'''
        max_epoch = -1

        for file in os.listdir(self.checkpoint_dir):
            if not file.startswith('epoch_'):
                continue

            _epoch = file.split('_')[-1]
            if not _epoch.isdigit():
                continue

            max_epoch = max(max_epoch, int(_epoch))

        if max_epoch == -1:
            if self.local_rank == 0:
                logger.warning('PaddleHub model checkpoint not found, start from scratch...')
            return

        # load best metrics
        self._load_metrics()

        self.current_epoch = max_epoch
        metric_msg = ['{}={:.4f}'.format(metric, value) for metric, value in self.best_metrics.items()]
        metric_msg = ' '.join(metric_msg)
        if self.local_rank == 0:
            logger.info('PaddleHub model checkpoint loaded. current_epoch={} [{}]'.format(
                self.current_epoch, metric_msg))

oqqZun1's avatar
oqqZun1 已提交
117 118 119 120 121
        model_path = os.path.join(self.checkpoint_dir, 'epoch_{}'.format(self.current_epoch))
        self.load_model(model_path)

    def load_model(self, load_dir: str):
        """load model"""
W
wuzewu 已提交
122
        # load model checkpoint
oqqZun1's avatar
oqqZun1 已提交
123
        model_params_path = os.path.join(load_dir, 'model.pdparams')
W
wuzewu 已提交
124
        state_dict = paddle.load(model_params_path)
125
        self.model.set_state_dict(state_dict)
W
wuzewu 已提交
126

W
wuzewu 已提交
127
        # load optimizer checkpoint
oqqZun1's avatar
oqqZun1 已提交
128
        optim_params_path = os.path.join(load_dir, 'model.pdopt')
W
wuzewu 已提交
129
        state_dict = paddle.load(optim_params_path)
130
        self.optimizer.set_state_dict(state_dict)
W
wuzewu 已提交
131

W
wuzewu 已提交
132 133
    def _save_checkpoint(self):
        '''Save model checkpoint and state dict'''
W
wuzewu 已提交
134
        model_path = os.path.join(self.checkpoint_dir, 'epoch_{}'.format(self.current_epoch))
W
wuzewu 已提交
135 136 137 138 139
        logger.info('Saving model checkpoint to {}'.format(model_path))
        self.save_model(model_path)

    def save_model(self, save_dir: str):
        '''Save model'''
W
wuzewu 已提交
140 141 142
        model_params_path = os.path.join(save_dir, 'model.pdparams')
        optim_params_path = os.path.join(save_dir, 'model.pdopt')
        paddle.save(self.model.state_dict(), model_params_path)
143
        paddle.save(self.optimizer.state_dict(), optim_params_path)
W
wuzewu 已提交
144 145 146 147 148 149

    def _save_metrics(self):
        with open(os.path.join(self.checkpoint_dir, 'metrics.pkl'), 'wb') as file:
            pickle.dump(self.best_metrics, file)

    def _load_metrics(self):
150 151 152 153 154
        metrics_file = os.path.join(self.checkpoint_dir, 'metrics.pkl')
        if not os.path.exists(metrics_file):
            return

        with open(metrics_file, 'rb') as file:
W
wuzewu 已提交
155 156 157
            self.best_metrics = pickle.load(file)

    def train(self,
158
              train_dataset: paddle.io.Dataset,
W
wuzewu 已提交
159 160 161
              epochs: int = 1,
              batch_size: int = 1,
              num_workers: int = 0,
162
              eval_dataset: paddle.io.Dataset = None,
W
wuzewu 已提交
163
              log_interval: int = 10,
164 165
              save_interval: int = 10,
              collate_fn: Callable = None):
W
wuzewu 已提交
166 167 168 169
        '''
        Train a model with specific config.

        Args:
170
            train_dataset(paddle.io.Dataset) : Dataset to train the model
W
wuzewu 已提交
171 172 173
            epochs(int) : Number of training loops, default is 1.
            batch_size(int) : Batch size of per step, default is 1.
            num_workers(int) : Number of subprocess to load data, default is 0.
W
wuzewu 已提交
174 175
            eval_dataset(paddle.io.Dataset) : The validation dataset, deafult is None. If set, the Trainer will
                execute evaluate function every `save_interval` epochs.
W
wuzewu 已提交
176 177
            log_interval(int) : Log the train infomation every `log_interval` steps.
            save_interval(int) : Save the checkpoint every `save_interval` epochs.
178 179
            collate_fn(callable): function to generate mini-batch data by merging the sample list.
                None for only stack each fields of sample in axis 0(same as :attr::`np.stack(..., axis=0)`). Default None
W
wuzewu 已提交
180
        '''
181 182 183
        batch_sampler = paddle.io.DistributedBatchSampler(
            train_dataset, batch_size=batch_size, shuffle=True, drop_last=False)
        loader = paddle.io.DataLoader(
W
wuzewu 已提交
184 185 186 187
            train_dataset,
            batch_sampler=batch_sampler,
            num_workers=num_workers,
            return_list=True,
188 189
            use_buffer_reader=True,
            collate_fn=collate_fn)
W
wuzewu 已提交
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        steps_per_epoch = len(batch_sampler)
        timer = Timer(steps_per_epoch * epochs)
        timer.start()

        for i in range(epochs):
            self.current_epoch += 1
            avg_loss = 0
            avg_metrics = defaultdict(int)
            self.model.train()

            for batch_idx, batch in enumerate(loader):
                loss, metrics = self.training_step(batch, batch_idx)
                self.optimizer_step(self.current_epoch, batch_idx, self.optimizer, loss)
                self.optimizer_zero_grad(self.current_epoch, batch_idx, self.optimizer)

                # calculate metrics and loss
                avg_loss += loss.numpy()[0]
                for metric, value in metrics.items():
209 210 211
                    if isinstance(value, paddle.Tensor):
                        value = value.numpy()
                    avg_metrics[metric] += value
212 213 214 215

                timer.count()

                if (batch_idx + 1) % log_interval == 0 and self.local_rank == 0:
W
wuzewu 已提交
216
                    lr = self.optimizer.get_lr()
217 218 219 220 221 222 223
                    avg_loss /= log_interval
                    if self.use_vdl:
                        self.log_writer.add_scalar(tag='TRAIN/loss', step=timer.current_step, value=avg_loss)

                    print_msg = 'Epoch={}/{}, Step={}/{}'.format(self.current_epoch, epochs, batch_idx + 1,
                                                                 steps_per_epoch)
                    print_msg += ' loss={:.4f}'.format(avg_loss)
W
wuzewu 已提交
224

225 226 227 228 229
                    for metric, value in avg_metrics.items():
                        value /= log_interval
                        if self.use_vdl:
                            self.log_writer.add_scalar(
                                tag='TRAIN/{}'.format(metric), step=timer.current_step, value=value)
S
Steffy-zxf 已提交
230 231
                        if isinstance(value, np.ndarray):
                            value = value.item()
232 233 234
                        print_msg += ' {}={:.4f}'.format(metric, value)

                    print_msg += ' lr={:.6f} step/sec={:.2f} | ETA {}'.format(lr, timer.timing, timer.eta)
W
wuzewu 已提交
235

236
                    logger.train(print_msg)
W
wuzewu 已提交
237

238 239
                    avg_loss = 0
                    avg_metrics = defaultdict(int)
W
wuzewu 已提交
240

241 242
                if self.current_epoch % save_interval == 0 and batch_idx + 1 == steps_per_epoch and self.local_rank == 0:
                    if eval_dataset:
243
                        result = self.evaluate(eval_dataset, batch_size, num_workers, collate_fn=collate_fn)
244 245 246 247 248
                        eval_loss = result.get('loss', None)
                        eval_metrics = result.get('metrics', {})
                        if self.use_vdl:
                            if eval_loss:
                                self.log_writer.add_scalar(tag='EVAL/loss', step=timer.current_step, value=eval_loss)
W
wuzewu 已提交
249

250 251 252
                            for metric, value in eval_metrics.items():
                                self.log_writer.add_scalar(
                                    tag='EVAL/{}'.format(metric), step=timer.current_step, value=value)
W
wuzewu 已提交
253

254 255 256 257 258
                        if not self.best_metrics or self.compare_metrics(self.best_metrics, eval_metrics):
                            self.best_metrics = eval_metrics
                            best_model_path = os.path.join(self.checkpoint_dir, 'best_model')
                            self.save_model(best_model_path)
                            self._save_metrics()
W
wuzewu 已提交
259

260 261 262 263 264
                            metric_msg = [
                                '{}={:.4f}'.format(metric, value) for metric, value in self.best_metrics.items()
                            ]
                            metric_msg = ' '.join(metric_msg)
                            logger.eval('Saving best model to {} [best {}]'.format(best_model_path, metric_msg))
W
wuzewu 已提交
265

266
                    self._save_checkpoint()
W
wuzewu 已提交
267

268 269 270 271 272
    def evaluate(self,
                 eval_dataset: paddle.io.Dataset,
                 batch_size: int = 1,
                 num_workers: int = 0,
                 collate_fn: Callable = None):
W
wuzewu 已提交
273 274 275 276
        '''
        Run evaluation and returns metrics.

        Args:
277
            eval_dataset(paddle.io.Dataset) : The validation dataset
W
wuzewu 已提交
278 279
            batch_size(int) : Batch size of per step, default is 1.
            num_workers(int) : Number of subprocess to load data, default is 0.
280 281
            collate_fn(callable): function to generate mini-batch data by merging the sample list.
                None for only stack each fields of sample in axis 0(same as :attr::`np.stack(..., axis=0)`). Default None
W
wuzewu 已提交
282
        '''
283 284 285 286 287 288 289 290 291 292 293 294 295 296
        if self.local_rank == 0:
            batch_sampler = paddle.io.BatchSampler(eval_dataset, batch_size=batch_size, shuffle=False, drop_last=False)

            loader = paddle.io.DataLoader(
                eval_dataset,
                batch_sampler=batch_sampler,
                num_workers=num_workers,
                return_list=True,
                collate_fn=collate_fn)

            self.model.eval()
            avg_loss = num_samples = 0
            sum_metrics = defaultdict(int)
            avg_metrics = defaultdict(int)
W
wuzewu 已提交
297

298 299 300 301 302 303 304
            with logger.processing('Evaluation on validation dataset'):
                for batch_idx, batch in enumerate(loader):
                    result = self.validation_step(batch, batch_idx)
                    loss = result.get('loss', None)
                    metrics = result.get('metrics', {})
                    bs = batch[0].shape[0]
                    num_samples += bs
W
wuzewu 已提交
305

306 307
                    if loss:
                        avg_loss += loss.numpy()[0] * bs
W
wuzewu 已提交
308

309 310
                    for metric, value in metrics.items():
                        sum_metrics[metric] += value * bs
W
wuzewu 已提交
311

312 313 314 315 316
            # print avg metrics and loss
            print_msg = '[Evaluation result]'
            if loss:
                avg_loss /= num_samples
                print_msg += ' avg_loss={:.4f}'.format(avg_loss)
W
wuzewu 已提交
317

318
            for metric, value in sum_metrics.items():
319
                avg_metrics[metric] = float(value) / num_samples
320
                print_msg += ' avg_{}={:.4f}'.format(metric, avg_metrics[metric])
321

322
            logger.eval(print_msg)
323

324 325 326
            if loss:
                return {'loss': avg_loss, 'metrics': avg_metrics}
            return {'metrics': avg_metrics}
W
wuzewu 已提交
327

W
wuzewu 已提交
328 329 330 331 332 333 334 335
    def training_step(self, batch: List[paddle.Tensor], batch_idx: int):
        '''
        One step for training, which should be called as forward computation.

        Args:
            batch(list[paddle.Tensor]) : The one batch data
            batch_idx(int) : The index of batch.
        '''
W
wuzewu 已提交
336 337 338 339 340 341 342
        if self.nranks > 1:
            result = self.model._layers.training_step(batch, batch_idx)
        else:
            result = self.model.training_step(batch, batch_idx)

        # process result
        if not isinstance(result, dict):
W
wuzewu 已提交
343
            raise RuntimeError('The return value of `trainning_step` in {} is not a dict'.format(self.model.__class__))
W
wuzewu 已提交
344 345

        loss = result.get('loss', None)
346
        if loss is None:
W
wuzewu 已提交
347 348
            raise RuntimeError('Cannot find loss attribute in the return value of `trainning_step` of {}'.format(
                self.model.__class__))
W
wuzewu 已提交
349 350 351 352

        metrics = result.get('metrics', {})

        # back prop
W
wuzewu 已提交
353
        loss.backward()
W
wuzewu 已提交
354 355 356 357

        return loss, metrics

    def validation_step(self, batch: Any, batch_idx: int):
W
wuzewu 已提交
358 359 360 361 362 363 364
        '''
        One step for validation, which should be called as forward computation.

        Args:
            batch(list[paddle.Tensor]) : The one batch data
            batch_idx(int) : The index of batch.
        '''
W
wuzewu 已提交
365 366 367 368 369 370
        if self.nranks > 1:
            result = self.model._layers.validation_step(batch, batch_idx)
        else:
            result = self.model.validation_step(batch, batch_idx)
        return result

W
wuzewu 已提交
371
    def optimizer_step(self, epoch_idx: int, batch_idx: int, optimizer: paddle.optimizer.Optimizer,
372
                       loss: paddle.Tensor):
W
wuzewu 已提交
373 374 375 376 377 378 379 380 381
        '''
        One step for optimize.

        Args:
            epoch_idx(int) : The index of epoch.
            batch_idx(int) : The index of batch.
            optimizer(paddle.optimizer.Optimizer) : Optimizer used.
            loss(paddle.Tensor) : Loss tensor.
        '''
W
wuzewu 已提交
382
        self.optimizer.step()
383
        self.learning_rate_step(epoch_idx, batch_idx, self.optimizer._learning_rate, loss)
W
wuzewu 已提交
384 385

    def learning_rate_step(self, epoch_idx: int, batch_idx: int, learning_rate: Generic, loss: paddle.Tensor):
W
wuzewu 已提交
386
        if isinstance(learning_rate, paddle.optimizer.lr.LRScheduler):
W
wuzewu 已提交
387
            learning_rate.step()
W
wuzewu 已提交
388

W
wuzewu 已提交
389 390 391 392 393 394 395 396 397 398
    def optimizer_zero_grad(self, epoch_idx: int, batch_idx: int, optimizer: paddle.optimizer.Optimizer):
        '''
        One step for clear gradients.

        Args:
            epoch_idx(int) : The index of epoch.
            batch_idx(int) : The index of batch.
            optimizer(paddle.optimizer.Optimizer) : Optimizer used.
            loss(paddle.Tensor) : Loss tensor.
        '''
W
wuzewu 已提交
399 400 401 402 403 404
        self.model.clear_gradients()

    def _compare_metrics(self, old_metric: dict, new_metric: dict):
        '''Compare the whether the new metric value is better than the old one'''
        mainkey = list(new_metric.keys())[0]
        return old_metric[mainkey] < new_metric[mainkey]