test_resnet_pure_fp16.py 5.5 KB
Newer Older
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 time
import unittest

import numpy as np
19
from dygraph_to_static_util import test_and_compare_with_new_ir
20
from test_resnet import SEED, ResNet, optimizer_setting
21 22

import paddle
23
from paddle import fluid
24
from paddle.fluid import core
25 26 27 28 29 30 31 32 33 34 35 36

# NOTE: Reduce batch_size from 8 to 2 to avoid unittest timeout.
batch_size = 2
epoch_num = 1


if fluid.is_compiled_with_cuda():
    fluid.set_flags({'FLAGS_cudnn_deterministic': True})


def train(to_static, build_strategy=None):
    """
37
    Tests model decorated by `dygraph_to_static_output` in static graph mode. For users, the model is defined in dygraph mode and trained in static graph mode.
38 39 40 41 42 43 44 45 46 47 48
    """
    np.random.seed(SEED)
    paddle.seed(SEED)
    paddle.framework.random._manual_program_seed(SEED)

    resnet = ResNet()
    if to_static:
        resnet = paddle.jit.to_static(resnet, build_strategy=build_strategy)
    optimizer = optimizer_setting(parameter_list=resnet.parameters())
    scaler = paddle.amp.GradScaler(init_loss_scaling=1024)

49 50 51
    resnet, optimizer = paddle.amp.decorate(
        models=resnet, optimizers=optimizer, level='O2', save_dtype='float32'
    )
52 53 54 55 56 57 58 59 60 61 62

    for epoch in range(epoch_num):
        loss_data = []
        total_loss = 0.0
        total_acc1 = 0.0
        total_acc5 = 0.0
        total_sample = 0

        for batch_id in range(100):
            start_time = time.time()
            img = paddle.to_tensor(
63 64
                np.random.random([batch_size, 3, 224, 224]).astype('float32')
            )
65
            label = paddle.to_tensor(
66 67
                np.random.randint(0, 100, [batch_size, 1], dtype='int64')
            )
68 69 70
            img.stop_gradient = True
            label.stop_gradient = True

71 72 73 74 75 76
            with paddle.amp.auto_cast(
                enable=True,
                custom_white_list=None,
                custom_black_list=None,
                level='O2',
            ):
77
                pred = resnet(img)
78 79 80
                loss = paddle.nn.functional.cross_entropy(
                    input=pred, label=label, reduction='none', use_softmax=False
                )
81
            avg_loss = paddle.mean(x=pred)
82 83
            acc_top1 = paddle.static.accuracy(input=pred, label=label, k=1)
            acc_top5 = paddle.static.accuracy(input=pred, label=label, k=5)
84 85 86 87 88 89

            scaled = scaler.scale(avg_loss)
            scaled.backward()
            scaler.minimize(optimizer, scaled)
            resnet.clear_gradients()

90
            loss_data.append(float(avg_loss))
91 92 93 94 95 96 97
            total_loss += avg_loss
            total_acc1 += acc_top1
            total_acc5 += acc_top5
            total_sample += 1

            end_time = time.time()
            if batch_id % 2 == 0:
98 99 100 101 102 103 104 105 106 107 108
                print(
                    "epoch %d | batch step %d, loss %0.3f, acc1 %0.3f, acc5 %0.3f, time %f"
                    % (
                        epoch,
                        batch_id,
                        total_loss.numpy() / total_sample,
                        total_acc1.numpy() / total_sample,
                        total_acc5.numpy() / total_sample,
                        end_time - start_time,
                    )
                )
109 110 111 112 113 114 115 116
            if batch_id == 10:
                break

    return loss_data


class TestResnet(unittest.TestCase):
    def train(self, to_static):
R
Ryan 已提交
117
        paddle.jit.enable_to_static(to_static)
118 119 120 121 122
        build_strategy = paddle.static.BuildStrategy()
        # Why set `build_strategy.enable_inplace = False` here?
        # Because we find that this PASS strategy of PE makes dy2st training loss unstable.
        build_strategy.enable_inplace = False
        return train(to_static, build_strategy)
123

124
    @test_and_compare_with_new_ir(False)
125 126 127 128 129
    def test_resnet(self):
        if fluid.is_compiled_with_cuda():
            static_loss = self.train(to_static=True)
            dygraph_loss = self.train(to_static=False)
            # NOTE: In pure fp16 training, loss is not stable, so we enlarge atol here.
130 131 132 133 134 135
            np.testing.assert_allclose(
                static_loss,
                dygraph_loss,
                rtol=1e-05,
                atol=0.001,
                err_msg='static_loss: {} \n dygraph_loss: {}'.format(
136 137 138
                    static_loss, dygraph_loss
                ),
            )
139

140 141
    def test_resnet_composite(self):
        if fluid.is_compiled_with_cuda():
142
            core._set_prim_backward_enabled(True)
143
            static_loss = self.train(to_static=True)
144
            core._set_prim_backward_enabled(False)
145 146 147 148 149 150 151 152 153 154 155 156
            dygraph_loss = self.train(to_static=False)
            # NOTE: In pure fp16 training, loss is not stable, so we enlarge atol here.
            np.testing.assert_allclose(
                static_loss,
                dygraph_loss,
                rtol=1e-05,
                atol=0.001,
                err_msg='static_loss: {} \n dygraph_loss: {}'.format(
                    static_loss, dygraph_loss
                ),
            )

157 158

if __name__ == '__main__':
159
    unittest.main()