test_elementwise_min_op.py 16.1 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2
#
D
dzhwinter 已提交
3 4 5
# 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
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
D
dzhwinter 已提交
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
fengjiayi 已提交
15
import unittest
16

F
fengjiayi 已提交
17
import numpy as np
18
from eager_op_test import OpTest, convert_float_to_uint16, skip_check_grad_ci
19

S
sneaxiy 已提交
20
import paddle
21
from paddle.fluid import core
S
sneaxiy 已提交
22 23

paddle.enable_static()
F
fengjiayi 已提交
24 25


26 27 28 29 30 31 32
def broadcast_wrapper(shape=[1, 10, 12, 1]):
    def min_wrapper(x, y, axis=-1):
        return paddle.minimum(x, y.reshape(shape))

    return min_wrapper


F
fengjiayi 已提交
33 34 35
class TestElementwiseOp(OpTest):
    def setUp(self):
        self.op_type = "elementwise_min"
36
        self.python_api = paddle.minimum
37 38 39
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
F
fengjiayi 已提交
40
        # If x and y have the same value, the min() is not differentiable.
F
fengjiayi 已提交
41 42
        # So we generate test data by the following method
        # to avoid them being too close to each other.
43 44 45
        x = np.random.uniform(0.1, 1, [13, 17]).astype("float64")
        sgn = np.random.choice([-1, 1], [13, 17]).astype("float64")
        y = x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype("float64")
F
fengjiayi 已提交
46 47 48 49
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}

    def test_check_output(self):
50
        self.check_output()
F
fengjiayi 已提交
51 52

    def test_check_grad_normal(self):
53 54 55 56 57 58 59
        if hasattr(self, 'attrs'):
            if self.attrs['axis'] == -1:
                self.check_grad(['X', 'Y'], 'Out', check_prim=True)
            else:
                self.check_grad(['X', 'Y'], 'Out')
        else:
            self.check_grad(['X', 'Y'], 'Out', check_prim=True)
F
fengjiayi 已提交
60 61

    def test_check_grad_ingore_x(self):
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        if hasattr(self, 'attrs') and self.attrs['axis'] != -1:
            self.check_grad(
                ['Y'],
                'Out',
                max_relative_error=0.005,
                no_grad_set=set("X"),
            )
        else:
            self.check_grad(
                ['Y'],
                'Out',
                max_relative_error=0.005,
                no_grad_set=set("X"),
                check_prim=True,
            )
F
fengjiayi 已提交
77 78

    def test_check_grad_ingore_y(self):
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        if hasattr(self, 'attrs') and self.attrs['axis'] != -1:
            self.check_grad(
                ['X'],
                'Out',
                max_relative_error=0.005,
                no_grad_set=set('Y'),
                check_dygraph=False,
            )
        else:
            self.check_grad(
                ['X'],
                'Out',
                max_relative_error=0.005,
                no_grad_set=set('Y'),
                check_prim=True,
            )

    def if_enable_cinn(self):
        pass
F
fengjiayi 已提交
98 99


100 101 102 103
class TestElementwiseFP16Op(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
104 105 106
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
107 108 109 110 111 112 113 114 115 116 117
        self.dtype = np.float16
        # If x and y have the same value, the min() is not differentiable.
        # So we generate test data by the following method
        # to avoid them being too close to each other.
        x = np.random.uniform(0.1, 1, [13, 17]).astype(np.float16)
        sgn = np.random.choice([-1, 1], [13, 17]).astype(np.float16)
        y = x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype(np.float16)
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


118 119 120 121
class TestElementwiseMinOp_ZeroDim1(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
122 123 124
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
125 126 127 128 129
        x = np.random.uniform(0.1, 1, []).astype("float64")
        y = np.random.uniform(0.1, 1, []).astype("float64")
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}

130 131 132
    def if_enable_cinn(self):
        self.enable_cinn = False

133

134 135 136 137 138
class TestElementwiseMinFP16Op_ZeroDim1(TestElementwiseFP16Op):
    def init_data(self):
        self.x = np.random.uniform(0.1, 1, []).astype(np.float16)
        self.y = np.random.uniform(0.1, 1, []).astype(np.float16)

139 140 141
    def if_enable_cinn(self):
        self.enable_cinn = False

142

143 144 145 146
class TestElementwiseMinOp_ZeroDim2(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
147 148 149
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
150 151 152 153 154
        x = np.random.uniform(0.1, 1, [13, 17]).astype("float64")
        y = np.random.uniform(0.1, 1, []).astype("float64")
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}

155 156 157
    def if_enable_cinn(self):
        self.enable_cinn = False

158

159 160 161 162 163
class TestElementwiseMinFP16Op_ZeroDim2(TestElementwiseFP16Op):
    def init_data(self):
        self.x = np.random.uniform(0.1, 1, [13, 17]).astype("float16")
        self.y = np.random.uniform(0.1, 1, []).astype("float16")

164 165 166
    def if_enable_cinn(self):
        self.enable_cinn = False

167

168 169 170 171
class TestElementwiseMinOp_ZeroDim3(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
172 173 174
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
175 176 177 178 179
        x = np.random.uniform(0.1, 1, []).astype("float64")
        y = np.random.uniform(0.1, 1, [13, 17]).astype("float64")
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}

180 181 182
    def if_enable_cinn(self):
        self.enable_cinn = False

183

184 185 186 187 188
class TestElementwiseMinFP16Op_ZeroDim3(TestElementwiseFP16Op):
    def init_data(self):
        self.x = np.random.uniform(0.1, 1, []).astype("float16")
        self.y = np.random.uniform(0.1, 1, [13, 17]).astype("float16")

189 190 191
    def if_enable_cinn(self):
        self.enable_cinn = False

192

193
@skip_check_grad_ci(
194 195
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
196 197 198
class TestElementwiseMinOp_scalar(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
199
        self.python_api = paddle.minimum
200 201 202
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
203 204
        x = np.random.random_integers(-5, 5, [10, 3, 4]).astype("float64")
        y = np.array([0.5]).astype("float64")
205 206 207 208
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


209 210 211 212 213 214 215
@skip_check_grad_ci(
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
class TestElementwiseMinFP16Op_scalar(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
216 217 218
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
219 220 221 222 223 224
        x = np.random.random_integers(-5, 5, [10, 3, 4]).astype(np.float16)
        y = np.array([0.5]).astype(np.float16)
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


225
class TestElementwiseMinOp_Vector(TestElementwiseOp):
F
fengjiayi 已提交
226 227
    def setUp(self):
        self.op_type = "elementwise_min"
228
        self.python_api = paddle.minimum
229 230 231
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
232 233 234
        x = np.random.random((100,)).astype("float64")
        sgn = np.random.choice([-1, 1], (100,)).astype("float64")
        y = x + sgn * np.random.uniform(0.1, 1, (100,)).astype("float64")
F
fengjiayi 已提交
235 236 237 238
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


239 240 241 242
class TestElementwiseMinFP16Op_Vector(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
243 244 245
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
246 247 248 249 250 251 252
        x = np.random.random((100,)).astype(np.float16)
        sgn = np.random.choice([-1, 1], (100,)).astype(np.float16)
        y = x + sgn * np.random.uniform(0.1, 1, (100,)).astype(np.float16)
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


253
class TestElementwiseMinOp_broadcast_2(TestElementwiseOp):
F
fengjiayi 已提交
254 255
    def setUp(self):
        self.op_type = "elementwise_min"
256
        self.python_api = broadcast_wrapper(shape=[1, 1, 100])
257 258 259
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
260
        x = np.random.uniform(0.5, 1, (2, 3, 100)).astype(np.float64)
261 262 263 264
        sgn = np.random.choice([-1, 1], (100,)).astype(np.float64)
        y = x[0, 0, :] + sgn * np.random.uniform(1, 2, (100,)).astype(
            np.float64
        )
F
fengjiayi 已提交
265 266 267
        self.inputs = {'X': x, 'Y': y}

        self.outputs = {
268 269 270
            'Out': np.minimum(
                self.inputs['X'], self.inputs['Y'].reshape(1, 1, 100)
            )
F
fengjiayi 已提交
271 272 273
        }


274 275 276 277
class TestElementwiseMinFP16Op_broadcast_2(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = broadcast_wrapper(shape=[1, 1, 100])
278 279 280
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
281 282 283 284 285 286 287 288 289 290 291 292 293 294
        x = np.random.uniform(0.5, 1, (2, 3, 100)).astype(np.float16)
        sgn = np.random.choice([-1, 1], (100,)).astype(np.float16)
        y = x[0, 0, :] + sgn * np.random.uniform(1, 2, (100,)).astype(
            np.float16
        )
        self.inputs = {'X': x, 'Y': y}

        self.outputs = {
            'Out': np.minimum(
                self.inputs['X'], self.inputs['Y'].reshape(1, 1, 100)
            )
        }


295 296 297
class TestElementwiseMinOp_broadcast_4(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
298
        self.python_api = paddle.minimum
299 300 301
        self.prim_op_type = "prim"
        self.public_python_api = paddle.minimum
        self.if_enable_cinn()
302 303
        x = np.random.uniform(0.5, 1, (2, 10, 2, 5)).astype(np.float64)
        sgn = np.random.choice([-1, 1], (2, 10, 1, 5)).astype(np.float64)
304
        y = x + sgn * np.random.uniform(1, 2, (2, 10, 1, 5)).astype(np.float64)
305 306 307 308 309
        self.inputs = {'X': x, 'Y': y}

        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


310 311 312 313
class TestElementwiseMinFP16Op_broadcast_4(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
314 315 316
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        x = np.random.uniform(0.5, 1, (2, 10, 2, 5)).astype(np.float16)
        sgn = np.random.choice([-1, 1], (2, 10, 1, 5)).astype(np.float16)
        y = x + sgn * np.random.uniform(1, 2, (2, 10, 1, 5)).astype(np.float16)
        self.inputs = {'X': x, 'Y': y}

        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


@unittest.skipIf(
    core.is_compiled_with_cuda()
    and (
        core.cudnn_version() < 8100
        or paddle.device.cuda.get_device_capability()[0] < 8
    ),
    "run test when gpu is availble and the minimum cudnn version is 8.1.0 and gpu's compute capability is at least 8.0.",
)
class TestElementwiseBF16Op(OpTest):
    def init_data(self):
        # If x and y have the same value, the max() is not differentiable.
        # So we generate test data by the following method
        # to avoid them being too close to each other.
        self.x = np.random.uniform(0.1, 1, [13, 17]).astype(np.float32)
        sgn = np.random.choice([-1, 1], [13, 17]).astype(np.float32)
        self.y = self.x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype(
            np.float32
        )

    def setUp(self):
        self.init_data()
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
350
        self.if_enable_cinn()
351 352 353 354 355 356 357 358 359 360 361 362 363
        self.dtype = np.uint16
        self.inputs = {
            'X': convert_float_to_uint16(self.x),
            'Y': convert_float_to_uint16(self.y),
        }
        self.outputs = {
            'Out': convert_float_to_uint16(np.minimum(self.x, self.y))
        }

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
        places = self._get_places()
        for place in places:
            if type(place) is paddle.fluid.libpaddle.CPUPlace:
                check_prim = False
            else:
                check_prim = True

            self.check_grad_with_place(
                place,
                inputs_to_check=['X', 'Y'],
                output_names='Out',
                no_grad_set=None,
                numeric_grad_delta=0.05,
                in_place=False,
                max_relative_error=0.005,
                user_defined_grads=None,
                user_defined_grad_outputs=None,
                check_dygraph=True,
                check_prim=check_prim,
                only_check_prim=False,
                atol=1e-5,
                check_cinn=False,
            )
387 388

    def test_check_grad_ingore_x(self):
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        places = self._get_places()
        for place in places:
            if type(place) is paddle.fluid.libpaddle.CPUPlace:
                check_prim = False
            else:
                check_prim = True

            self.check_grad_with_place(
                place,
                inputs_to_check=['Y'],
                output_names='Out',
                no_grad_set=set("X"),
                numeric_grad_delta=0.05,
                in_place=False,
                max_relative_error=0.005,
                user_defined_grads=None,
                user_defined_grad_outputs=None,
                check_dygraph=True,
                check_prim=check_prim,
                only_check_prim=False,
                atol=1e-5,
                check_cinn=False,
            )
412 413

    def test_check_grad_ingore_y(self):
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
        places = self._get_places()
        for place in places:
            if type(place) is paddle.fluid.libpaddle.CPUPlace:
                check_prim = False
            else:
                check_prim = True

            self.check_grad_with_place(
                place,
                inputs_to_check=['Y'],
                output_names='Out',
                no_grad_set=set("X"),
                numeric_grad_delta=0.05,
                in_place=False,
                max_relative_error=0.005,
                user_defined_grads=None,
                user_defined_grad_outputs=None,
                check_dygraph=True,
                check_prim=check_prim,
                only_check_prim=False,
                atol=1e-5,
                check_cinn=False,
            )

    def if_enable_cinn(self):
        self.enable_cinn = False
440 441 442 443 444 445 446


class TestElementwiseMinBF16Op_ZeroDim1(TestElementwiseBF16Op):
    def init_data(self):
        self.x = np.random.uniform(0.1, 1, []).astype("float32")
        self.y = np.random.uniform(0.1, 1, []).astype("float32")

S
sneaxiy 已提交
447

448 449 450 451 452
class TestElementwiseMinBF16Op_scalar(TestElementwiseBF16Op):
    def init_data(self):
        self.x = np.random.random_integers(-5, 5, [2, 3, 20]).astype("float32")
        self.y = np.array([0.5]).astype("float32")
        self.__class__.no_need_check_grad = True
S
sneaxiy 已提交
453 454


455 456 457 458 459 460
class TestElementwiseMinBF16Op_Vector(TestElementwiseBF16Op):
    def init_data(self):
        self.x = np.random.random((100,)).astype("float32")
        sgn = np.random.choice([-1, 1], (100,)).astype("float32")
        self.y = self.x + sgn * np.random.uniform(0.1, 1, (100,)).astype(
            "float32"
461
        )
S
sneaxiy 已提交
462 463


F
fengjiayi 已提交
464 465
if __name__ == '__main__':
    unittest.main()