test_elementwise_pow_op.py 10.2 KB
Newer Older
1
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Q
Qiao Longfei 已提交
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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.
14

Q
Qiao Longfei 已提交
15
import unittest
16

Q
Qiao Longfei 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
19

20
import paddle
21
from paddle import fluid
22
from paddle.fluid import core
Q
Qiao Longfei 已提交
23 24


25 26 27 28 29 30
def pow_grad(x, y, dout):
    dx = dout * y * np.power(x, (y - 1))
    dy = dout * np.log(x) * np.power(x, y)
    return dx, dy


Q
Qiao Longfei 已提交
31 32 33
class TestElementwisePowOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_pow"
34
        self.python_api = paddle.pow
35
        self.public_python_api = paddle.pow
36
        self.prim_op_type = "prim"
Q
Qiao Longfei 已提交
37
        self.inputs = {
38
            'X': np.random.uniform(1, 2, [20, 5]).astype("float64"),
39
            'Y': np.random.uniform(1, 2, [20, 5]).astype("float64"),
Q
Qiao Longfei 已提交
40 41 42 43
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}

    def test_check_output(self):
44
        if hasattr(self, 'attrs'):
W
wanghuancoder 已提交
45
            self.check_output(check_dygraph=False)
46
        else:
W
wanghuancoder 已提交
47
            self.check_output()
Q
Qiao Longfei 已提交
48

49
    def test_check_grad_normal(self):
50
        if hasattr(self, 'attrs'):
51
            self.check_grad(
W
wanghuancoder 已提交
52
                ['X', 'Y'], 'Out', check_prim=True, check_dygraph=False
53
            )
54
        else:
W
wanghuancoder 已提交
55
            self.check_grad(['X', 'Y'], 'Out', check_prim=True)
56

Q
Qiao Longfei 已提交
57

58 59 60 61
class TestElementwisePowOp_ZeroDim1(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
        self.python_api = paddle.pow
62
        self.public_python_api = paddle.pow
63 64 65
        self.enable_cinn = False
        self.prim_op_type = "prim"

66 67 68 69 70 71 72 73 74 75 76
        self.inputs = {
            'X': np.random.uniform(1, 2, []).astype("float64"),
            'Y': np.random.uniform(1, 2, []).astype("float64"),
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


class TestElementwisePowOp_ZeroDim2(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
        self.python_api = paddle.pow
77
        self.public_python_api = paddle.pow
78 79 80
        self.enable_cinn = False
        self.prim_op_type = "prim"

81 82 83 84 85 86 87 88 89 90 91
        self.inputs = {
            'X': np.random.uniform(1, 2, [20, 5]).astype("float64"),
            'Y': np.random.uniform(1, 2, []).astype("float64"),
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


class TestElementwisePowOp_ZeroDim3(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
        self.python_api = paddle.pow
92
        self.public_python_api = paddle.pow
93 94 95
        self.enable_cinn = False
        self.prim_op_type = "prim"

96 97 98 99 100 101 102
        self.inputs = {
            'X': np.random.uniform(1, 2, []).astype("float64"),
            'Y': np.random.uniform(1, 2, [20, 5]).astype("float64"),
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


103 104 105
class TestElementwisePowOp_big_shape_1(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
106
        self.python_api = paddle.pow
107
        self.public_python_api = paddle.pow
108 109
        self.prim_op_type = "prim"

110
        self.inputs = {
111
            'X': np.random.uniform(1, 2, [10, 10]).astype("float64"),
112
            'Y': np.random.uniform(0.1, 1, [10, 10]).astype("float64"),
113 114 115 116 117 118 119
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


class TestElementwisePowOp_big_shape_2(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
120
        self.python_api = paddle.pow
121
        self.public_python_api = paddle.pow
122 123
        self.prim_op_type = "prim"

124
        self.inputs = {
125
            'X': np.random.uniform(1, 2, [10, 10]).astype("float64"),
126
            'Y': np.random.uniform(0.2, 2, [10, 10]).astype("float64"),
127 128 129 130
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


131
@skip_check_grad_ci(
132 133
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
Q
Qiao Longfei 已提交
134 135 136
class TestElementwisePowOp_scalar(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
137
        self.python_api = paddle.pow
138
        self.public_python_api = paddle.pow
139 140
        self.prim_op_type = "prim"

Q
Qiao Longfei 已提交
141
        self.inputs = {
142
            'X': np.random.uniform(0.1, 1, [3, 3, 4]).astype(np.float64),
143
            'Y': np.random.uniform(0.1, 1, [1]).astype(np.float64),
144 145 146 147 148 149 150
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


class TestElementwisePowOp_tensor(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
151
        self.python_api = paddle.pow
152
        self.public_python_api = paddle.pow
153 154
        self.prim_op_type = "prim"

155
        self.inputs = {
156
            'X': np.random.uniform(0.1, 1, [100]).astype("float64"),
157
            'Y': np.random.uniform(1, 3, [100]).astype("float64"),
158 159 160 161 162 163 164
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


class TestElementwisePowOp_broadcast_0(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
165
        self.python_api = paddle.pow
166
        self.public_python_api = paddle.pow
167 168
        self.prim_op_type = "prim"

169
        self.inputs = {
170
            'X': np.random.uniform(0.1, 1, [2, 1, 100]).astype("float64"),
171
            'Y': np.random.uniform(0.1, 1, [100]).astype("float64"),
Q
Qiao Longfei 已提交
172 173 174 175
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


176 177 178
class TestElementwisePowOp_broadcast_4(TestElementwisePowOp):
    def setUp(self):
        self.op_type = "elementwise_pow"
179
        self.python_api = paddle.pow
180
        self.public_python_api = paddle.pow
181 182
        self.prim_op_type = "prim"

183
        self.inputs = {
184
            'X': np.random.uniform(0.1, 1, [2, 10, 3, 5]).astype("float64"),
185
            'Y': np.random.uniform(0.1, 1, [2, 10, 1, 5]).astype("float64"),
186 187 188 189
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}


190 191 192
class TestElementwisePowOpInt(OpTest):
    def setUp(self):
        self.op_type = "elementwise_pow"
193
        self.python_api = paddle.pow
194

195 196 197 198
        self.inputs = {'X': np.asarray([1, 3, 6]), 'Y': np.asarray([1, 1, 1])}
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}

    def test_check_output(self):
199
        if hasattr(self, 'attrs'):
W
wanghuancoder 已提交
200
            self.check_output(check_dygraph=False)
201
        else:
W
wanghuancoder 已提交
202
            self.check_output()
203 204 205 206 207 208 209


class TestElementwisePowGradOpInt(unittest.TestCase):
    def setUp(self):
        self.x = np.asarray([1, 3, 6])
        self.y = np.asarray([1, 1, 1])
        self.res = self.x**self.y
210

211 212 213
        # dout = 1
        self.grad_res = np.asarray([1, 1, 1])
        # dx = dout * y * pow(x, y-1)
214 215 216
        self.grad_x = (
            self.grad_res * self.y * (self.x ** (self.y - 1)).astype("int")
        )
217
        # dy = dout * log(x) * pow(x, y)
218 219 220
        self.grad_y = (
            self.grad_res * np.log(self.x) * (self.x**self.y)
        ).astype("int")
221 222 223 224 225 226 227 228 229 230 231 232

    def test_grad(self):
        places = [fluid.CPUPlace()]
        if fluid.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for place in places:
            with fluid.dygraph.guard(place):
                x = fluid.dygraph.to_variable(self.x, zero_copy=False)
                y = fluid.dygraph.to_variable(self.y, zero_copy=False)
                x.stop_gradient = False
                y.stop_gradient = False
                res = x**y
233
                res.retain_grads()
234
                res.backward()
235 236 237
                np.testing.assert_array_equal(res.gradient(), self.grad_res)
                np.testing.assert_array_equal(x.gradient(), self.grad_x)
                np.testing.assert_array_equal(y.gradient(), self.grad_y)
238 239


240 241 242
class TestElementwisePowOpFP16(OpTest):
    def setUp(self):
        self.op_type = "elementwise_pow"
243
        self.dtype = np.float16
244
        self.python_api = paddle.pow
245
        self.public_python_api = paddle.pow
246 247
        self.prim_op_type = "prim"

248 249
        self.inputs = {
            'X': np.random.uniform(1, 2, [20, 5]).astype("float16"),
250
            'Y': np.random.uniform(1, 2, [20, 5]).astype("float16"),
251 252 253 254 255
        }
        self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}

    def test_check_output(self):
        if hasattr(self, 'attrs'):
W
wanghuancoder 已提交
256
            self.check_output(check_dygraph=False)
257
        else:
W
wanghuancoder 已提交
258
            self.check_output()
259 260

    def test_check_grad(self):
261 262 263 264 265 266
        self.check_grad(
            ['X', 'Y'],
            'Out',
            user_defined_grads=pow_grad(
                self.inputs['X'], self.inputs['Y'], 1 / self.inputs['X'].size
            ),
267
            check_prim=True,
268
        )
269 270


271 272 273 274
@unittest.skipIf(
    not paddle.is_compiled_with_cuda() or paddle.is_compiled_with_rocm(),
    "BFP16 test runs only on CUDA",
)
275 276 277
class TestElementwisePowBF16Op(OpTest):
    def setUp(self):
        self.op_type = "elementwise_pow"
278
        self.prim_op_type = "prim"
279 280
        self.dtype = np.uint16
        self.python_api = paddle.pow
281
        self.public_python_api = paddle.pow
282 283 284 285 286 287 288 289 290 291 292 293

        x = np.random.uniform(0, 1, [20, 5]).astype(np.float32)
        y = np.random.uniform(0, 1, [20, 5]).astype(np.float32)
        out = np.power(x, y)
        self.inputs = {
            'X': convert_float_to_uint16(x),
            'Y': convert_float_to_uint16(y),
        }
        self.outputs = {'Out': convert_float_to_uint16(out)}

    def test_check_output(self):
        if hasattr(self, 'attrs'):
W
wanghuancoder 已提交
294
            self.check_output()
295
        else:
W
wanghuancoder 已提交
296
            self.check_output()
297 298

    def test_check_grad(self):
W
wanghuancoder 已提交
299
        self.check_grad(['X', 'Y'], 'Out')
300 301 302 303 304 305 306 307
        if core.is_compiled_with_cuda():
            self.check_grad_with_place(
                core.CUDAPlace(0),
                ['X', 'Y'],
                'Out',
                check_prim=True,
                only_check_prim=True,
            )
308 309


Q
Qiao Longfei 已提交
310 311
if __name__ == '__main__':
    unittest.main()