updater.py 3.2 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
from dataclasses import dataclass
H
Hui Zhang 已提交
16

H
Hui Zhang 已提交
17 18
import paddle

19
from paddlespeech.s2t.utils.log import Log
H
Hui Zhang 已提交
20 21 22 23 24 25 26 27 28 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

__all__ = ["UpdaterBase", "UpdaterState"]

logger = Log(__name__).getlog()


@dataclass
class UpdaterState:
    iteration: int = 0
    epoch: int = 0


class UpdaterBase():
    """An updater is the abstraction of how a model is trained given the
    dataloader and the optimizer.
    The `update_core` method is a step in the training loop with only necessary
    operations (get a batch, forward and backward, update the parameters).
    Other stuffs are made extensions. Visualization, saving, loading and
    periodical validation and evaluation are not considered here.
    But even in such simplist case, things are not that simple. There is an
    attempt to standardize this process and requires only the model and
    dataset and do all the stuffs automatically. But this may hurt flexibility.
    If we assume a batch yield from the dataloader is just the input to the
    model, we will find that some model requires more arguments, or just some
    keyword arguments. But this prevents us from over-simplifying it.
    From another perspective, the batch may includes not just the input, but
    also the target. But the model's forward method may just need the input.
    We can pass a dict or a super-long tuple to the model and let it pick what
    it really needs. But this is an abuse of lazy interface.
    After all, we care about how a model is trained. But just how the model is
    used for inference. We want to control how a model is trained. We just
    don't want to be messed up with other auxiliary code.
    So the best practice is to define a model and define a updater for it.
    """

    def __init__(self, init_state=None):
H
Hui Zhang 已提交
56
        # init state
H
Hui Zhang 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        if init_state is None:
            self.state = UpdaterState()
        else:
            self.state = init_state

    def update(self, batch):
        raise NotImplementedError(
            "Implement your own `update` method for training a step.")

    def state_dict(self):
        state_dict = {
            "epoch": self.state.epoch,
            "iteration": self.state.iteration,
        }
        return state_dict

    def set_state_dict(self, state_dict):
        self.state.epoch = state_dict["epoch"]
        self.state.iteration = state_dict["iteration"]

    def save(self, path):
        logger.debug(f"Saving to {path}.")
        archive = self.state_dict()
        paddle.save(archive, str(path))

    def load(self, path):
        logger.debug(f"Loading from {path}.")
        archive = paddle.load(str(path))
H
Hui Zhang 已提交
85
        self.set_state_dict(archive)