test_custom_relu_op_xpu_setup.py 4.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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.

import os
import site
import sys
import unittest

import numpy as np
21
from utils import check_output, check_output_allclose
22 23

import paddle
24
from paddle import static
25
from paddle.utils.cpp_extension.extension_utils import run_cmd
26
from paddle.vision.transforms import Compose, Normalize
27 28 29 30 31 32


def custom_relu_dynamic(func, device, dtype, np_x, use_func=True):
    paddle.set_device(device)

    t = paddle.to_tensor(np_x, dtype=dtype)
33
    t.stop_gradient = False
姜永久 已提交
34
    t.retain_grads()
35

36
    out = func(t) if use_func else paddle.nn.functional.relu(t)
37
    return out.numpy()
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52


def custom_relu_static(
    func, device, dtype, np_x, use_func=True, test_infer=False
):
    paddle.enable_static()
    paddle.set_device(device)

    with static.scope_guard(static.Scope()):
        with static.program_guard(static.Program()):
            x = static.data(name='X', shape=[None, 8], dtype=dtype)
            out = func(x) if use_func else paddle.nn.functional.relu(x)

            exe = static.Executor()
            exe.run(static.default_startup_program())
53
            # in static graph mode, x data has been covered by out
54 55 56 57 58 59 60 61 62 63
            out_v = exe.run(
                static.default_main_program(),
                feed={'X': np_x},
                fetch_list=[out.name],
            )

    paddle.disable_static()
    return out_v


64
class TestNewCustomOpXpuSetUpInstall(unittest.TestCase):
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    def setUp(self):
        cur_dir = os.path.dirname(os.path.abspath(__file__))
        cmd = 'cd {} && {} custom_relu_xpu_setup.py install'.format(
            cur_dir, sys.executable
        )
        run_cmd(cmd)

        site_dir = site.getsitepackages()[0]
        custom_egg_path = [
            x
            for x in os.listdir(site_dir)
            if 'custom_relu_xpu_module_setup' in x
        ]
        assert len(custom_egg_path) == 1, "Matched egg number is %d." % len(
            custom_egg_path
        )
        sys.path.append(os.path.join(site_dir, custom_egg_path[0]))

        # usage: import the package directly
        import custom_relu_xpu_module_setup

        self.custom_op = custom_relu_xpu_module_setup.custom_relu

88
        self.dtypes = ['float32']
89
        self.device = 'xpu'
90 91 92 93 94 95 96

        # config seed
        SEED = 2021
        paddle.seed(SEED)
        paddle.framework.random._manual_program_seed(SEED)

    def test_static(self):
97 98 99 100 101 102
        for dtype in self.dtypes:
            x = np.random.uniform(-1, 1, [4, 8]).astype(dtype)
            out = custom_relu_static(self.custom_op, self.device, dtype, x)
            pd_out = custom_relu_static(
                self.custom_op, self.device, dtype, x, False
            )
103
            check_output(out, pd_out, "out")
104

姜永久 已提交
105
    def test_dynamic(self):
106 107
        for dtype in self.dtypes:
            x = np.random.uniform(-1, 1, [4, 8]).astype(dtype)
108 109
            out = custom_relu_dynamic(self.custom_op, self.device, dtype, x)
            pd_out = custom_relu_dynamic(
110
                self.custom_op, self.device, dtype, x, False
111
            )
112
            check_output(out, pd_out, "out")
113 114

    def test_with_dataloader(self):
姜永久 已提交
115
        paddle.disable_static()
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        paddle.set_device(self.device)
        # data loader
        transform = Compose(
            [Normalize(mean=[127.5], std=[127.5], data_format='CHW')]
        )
        train_dataset = paddle.vision.datasets.MNIST(
            mode='train', transform=transform
        )
        train_loader = paddle.io.DataLoader(
            train_dataset,
            batch_size=64,
            shuffle=True,
            drop_last=True,
            num_workers=0,
        )
131

132 133 134
        for batch_id, (image, _) in enumerate(train_loader()):
            out = self.custom_op(image)
            pd_out = paddle.nn.functional.relu(image)
135
            check_output_allclose(out, pd_out, "out", atol=1e-2)
136

137 138
            if batch_id == 5:
                break
姜永久 已提交
139
        paddle.enable_static()
140

141 142

if __name__ == '__main__':
143 144 145
    # compile, install the custom op egg into site-packages under background
    # Currently custom XPU op does not support Windows
    if os.name == 'nt':
146
        sys.exit()
147
    unittest.main()