ema.py 1.6 KB
Newer Older
F
flytocc 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
L
littletomatodonkey 已提交
2 3 4 5 6
#
# 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
#
F
flytocc 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
L
littletomatodonkey 已提交
8 9 10 11 12 13 14
#
# 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.

F
flytocc 已提交
15 16
from copy import deepcopy

S
add ema  
shippingwang 已提交
17 18 19
import paddle


20
class ExponentialMovingAverage():
littletomatodonkey's avatar
littletomatodonkey 已提交
21 22
    """
    Exponential Moving Average
F
flytocc 已提交
23
    Code was heavily based on https://github.com/rwightman/pytorch-image-models/blob/master/timm/utils/model_ema.py
littletomatodonkey's avatar
littletomatodonkey 已提交
24 25
    """

F
flytocc 已提交
26 27 28 29 30 31 32 33 34
    def __init__(self, model, decay=0.9999):
        super().__init__()
        # make a copy of the model for accumulating moving average of weights
        self.module = deepcopy(model)
        self.module.eval()
        self.decay = decay

    @paddle.no_grad()
    def _update(self, model, update_fn):
Y
Yang Nie 已提交
35 36 37
        for ema_v, model_v in zip(self.module.state_dict().values(),
                                  model.state_dict().values()):
            ema_v.set_value(update_fn(ema_v.numpy(), model_v.numpy()))
F
flytocc 已提交
38 39

    def update(self, model):
Y
Yang Nie 已提交
40 41 42
        self._update(
            model,
            update_fn=lambda e, m: self.decay * e + (1. - self.decay) * m)
F
flytocc 已提交
43 44

    def set(self, model):
Y
Yang Nie 已提交
45
        self._update(model, update_fn=lambda e, m: m)