snapshot.py 4.8 KB
Newer Older
H
Hui Zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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.
H
Hui Zhang 已提交
14
# Modified from chainer(https://github.com/chainer/chainer)
H
Hui Zhang 已提交
15 16 17 18 19 20 21 22 23
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List

import jsonlines

H
Hui Zhang 已提交
24 25 26
from . import extension
from ..reporter import get_observations
from ..updaters.trainer import Trainer
27 28
from paddlespeech.s2t.utils.log import Log
from paddlespeech.s2t.utils.mp_tools import rank_zero_only
H
Hui Zhang 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

logger = Log(__name__).getlog()


def load_records(records_fp):
    """Load record files (json lines.)"""
    with jsonlines.open(records_fp, 'r') as reader:
        records = list(reader)
    return records


class Snapshot(extension.Extension):
    """An extension to make snapshot of the updater object inside
    the trainer. It is done by calling the updater's `save` method.
    An Updater save its state_dict by default, which contains the
    updater state, (i.e. epoch and iteration) and all the model
    parameters and optimizer states. If the updater inside the trainer
    subclasses StandardUpdater, everything is good to go.
    Parameters
    ----------
    checkpoint_dir : Union[str, Path]
        The directory to save checkpoints into.
    """

    trigger = (1, 'epoch')
    priority = -100
    default_name = "snapshot"

H
Hui Zhang 已提交
57 58 59 60 61 62
    def __init__(self,
                 mode='latest',
                 max_size: int=5,
                 indicator=None,
                 less_better=True,
                 snapshot_on_error: bool=False):
H
Hui Zhang 已提交
63
        self.records: List[Dict[str, Any]] = []
H
Hui Zhang 已提交
64 65 66 67 68 69
        assert mode in ('latest', 'kbest'), mode
        if mode == 'kbest':
            assert indicator is not None
        self.mode = mode
        self.indicator = indicator
        self.less_is_better = less_better
H
Hui Zhang 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82
        self.max_size = max_size
        self._snapshot_on_error = snapshot_on_error
        self._save_all = (max_size == -1)
        self.checkpoint_dir = None

    def initialize(self, trainer: Trainer):
        """Setting up this extention."""
        self.checkpoint_dir = trainer.out / "checkpoints"

        # load existing records
        record_path: Path = self.checkpoint_dir / "records.jsonl"
        if record_path.exists():
            self.records = load_records(record_path)
H
Hui Zhang 已提交
83 84 85
            ckpt_path = self.records[-1]['path']
            logger.info(f"Loading from an existing checkpoint {ckpt_path}")
            trainer.updater.load(ckpt_path)
H
Hui Zhang 已提交
86 87 88

    def on_error(self, trainer, exc, tb):
        if self._snapshot_on_error:
H
Hui Zhang 已提交
89
            self.save_checkpoint_and_update(trainer, 'latest')
H
Hui Zhang 已提交
90 91

    def __call__(self, trainer: Trainer):
H
Hui Zhang 已提交
92
        self.save_checkpoint_and_update(trainer, self.mode)
H
Hui Zhang 已提交
93 94 95 96 97 98 99

    def full(self):
        """Whether the number of snapshots it keeps track of is greater
        than the max_size."""
        return (not self._save_all) and len(self.records) > self.max_size

    @rank_zero_only
H
Hui Zhang 已提交
100
    def save_checkpoint_and_update(self, trainer: Trainer, mode: str):
H
Hui Zhang 已提交
101 102 103
        """Saving new snapshot and remove the oldest snapshot if needed."""
        iteration = trainer.updater.state.iteration
        epoch = trainer.updater.state.epoch
H
Hui Zhang 已提交
104
        num = epoch if self.trigger[1] == 'epoch' else iteration
H
Hui Zhang 已提交
105
        path = self.checkpoint_dir / f"{num}.np"
H
Hui Zhang 已提交
106 107 108 109 110 111 112 113

        # add the new one
        trainer.updater.save(path)
        record = {
            "time": str(datetime.now()),
            'path': str(path.resolve()),  # use absolute path
            'iteration': iteration,
            'epoch': epoch,
H
Hui Zhang 已提交
114
            'indicator': get_observations()[self.indicator]
H
Hui Zhang 已提交
115 116 117 118 119
        }
        self.records.append(record)

        # remove the earist
        if self.full():
H
Hui Zhang 已提交
120 121 122 123 124
            if mode == 'kbest':
                self.records = sorted(
                    self.records,
                    key=lambda record: record['indicator'],
                    reverse=not self.less_is_better)
H
Hui Zhang 已提交
125 126 127 128 129 130 131 132 133
            eariest_record = self.records[0]
            os.remove(eariest_record["path"])
            self.records.pop(0)

        # update the record file
        record_path = self.checkpoint_dir / "records.jsonl"
        with jsonlines.open(record_path, 'w') as writer:
            for record in self.records:
                # jsonlines.open may return a Writer or a Reader
H
Hui Zhang 已提交
134
                writer.write(record)  # pylint: disable=no-member