sr_model.py 3.8 KB
Newer Older
Q
qingqing01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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.

L
LielinJiang 已提交
15 16
import paddle
import paddle.nn as nn
L
LielinJiang 已提交
17

L
LielinJiang 已提交
18
from .generators.builder import build_generator
19
from .criterions.builder import build_criterion
20
from .base_model import BaseModel, apply_to_static
L
LielinJiang 已提交
21
from .builder import MODELS
22
from ..utils.visual import tensor2img
W
wangna11BD 已提交
23
from ..modules.init import reset_parameters
L
LielinJiang 已提交
24 25 26


@MODELS.register()
27 28 29
class BaseSRModel(BaseModel):
    """Base SR model for single image super-resolution.
    """
B
Birdylx 已提交
30

31 32
    def __init__(self, generator, pixel_criterion=None, use_init_weight=False, to_static=False,
                 image_shape=None):
33 34 35 36 37 38
        """
        Args:
            generator (dict): config of generator.
            pixel_criterion (dict): config of pixel criterion.
        """
        super(BaseSRModel, self).__init__()
L
LielinJiang 已提交
39

40
        self.nets['generator'] = build_generator(generator)
41 42
        # set @to_static for benchmark, skip this by default.
        apply_to_static(to_static, image_shape, self.nets['generator'])
L
LielinJiang 已提交
43

44 45
        if pixel_criterion:
            self.pixel_criterion = build_criterion(pixel_criterion)
W
wangna11BD 已提交
46 47
        if use_init_weight:
            init_sr_weight(self.nets['generator'])
L
LielinJiang 已提交
48

49
    def setup_input(self, input):
W
wangna11BD 已提交
50
        self.lq = paddle.to_tensor(input['lq'])
51
        self.visual_items['lq'] = self.lq
L
LielinJiang 已提交
52
        if 'gt' in input:
W
wangna11BD 已提交
53
            self.gt = paddle.to_tensor(input['gt'])
54
            self.visual_items['gt'] = self.gt
L
LielinJiang 已提交
55 56 57 58
        self.image_paths = input['lq_path']

    def forward(self):
        pass
L
LielinJiang 已提交
59

60 61
    def train_iter(self, optims=None):
        optims['optim'].clear_grad()
L
LielinJiang 已提交
62

63 64
        self.output = self.nets['generator'](self.lq)
        self.visual_items['output'] = self.output
L
LielinJiang 已提交
65
        # pixel loss
66 67 68 69 70
        loss_pixel = self.pixel_criterion(self.output, self.gt)
        self.losses['loss_pixel'] = loss_pixel

        loss_pixel.backward()
        optims['optim'].step()
L
LielinJiang 已提交
71

B
Birdylx 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    # amp training
    def train_iter_amp(self, optims=None, scalers=None, amp_level='O1'):
        optims['optim'].clear_grad()

        # put fwd and loss computation in amp context
        with paddle.amp.auto_cast(enable=True, level=amp_level):
            self.output = self.nets['generator'](self.lq)
            self.visual_items['output'] = self.output
            # pixel loss
            loss_pixel = self.pixel_criterion(self.output, self.gt)
            self.losses['loss_pixel'] = loss_pixel

        scaled_loss_pixel = scalers[0].scale(loss_pixel)
        scaled_loss_pixel.backward()
        scalers[0].minimize(optims['optim'], scaled_loss_pixel)

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    def test_iter(self, metrics=None):
        self.nets['generator'].eval()
        with paddle.no_grad():
            self.output = self.nets['generator'](self.lq)
            self.visual_items['output'] = self.output
        self.nets['generator'].train()

        out_img = []
        gt_img = []
        for out_tensor, gt_tensor in zip(self.output, self.gt):
            out_img.append(tensor2img(out_tensor, (0., 1.)))
            gt_img.append(tensor2img(gt_tensor, (0., 1.)))

        if metrics is not None:
            for metric in metrics.values():
                metric.update(out_img, gt_img)
W
wangna11BD 已提交
104 105 106


def init_sr_weight(net):
B
Birdylx 已提交
107

W
wangna11BD 已提交
108 109 110 111 112 113
    def reset_func(m):
        if hasattr(m, 'weight') and (not isinstance(
                m, (nn.BatchNorm, nn.BatchNorm2D))):
            reset_parameters(m)

    net.apply(reset_func)