test_elementwise_min_op.py 15.7 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 130
        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'])}


131 132 133 134 135 136
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)


137 138 139 140
class TestElementwiseMinOp_ZeroDim2(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
141 142
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
143 144 145 146 147 148
        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'])}


149 150 151 152 153 154
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")


155 156 157 158
class TestElementwiseMinOp_ZeroDim3(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
159 160 161
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
162 163 164 165 166 167
        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'])}


168 169 170 171 172 173
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")


174
@skip_check_grad_ci(
175 176
    reason="[skip shape check] Use y_shape(1) to test broadcast."
)
177 178 179
class TestElementwiseMinOp_scalar(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
180
        self.python_api = paddle.minimum
181 182 183
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
184 185
        x = np.random.random_integers(-5, 5, [10, 3, 4]).astype("float64")
        y = np.array([0.5]).astype("float64")
186 187 188 189
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


190 191 192 193 194 195 196
@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
197 198 199
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
200 201 202 203 204 205
        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'])}


206
class TestElementwiseMinOp_Vector(TestElementwiseOp):
F
fengjiayi 已提交
207 208
    def setUp(self):
        self.op_type = "elementwise_min"
209
        self.python_api = paddle.minimum
210 211 212
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
213 214 215
        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 已提交
216 217 218 219
        self.inputs = {'X': x, 'Y': y}
        self.outputs = {'Out': np.minimum(self.inputs['X'], self.inputs['Y'])}


220 221 222 223
class TestElementwiseMinFP16Op_Vector(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
224 225 226
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
227 228 229 230 231 232 233
        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'])}


234
class TestElementwiseMinOp_broadcast_2(TestElementwiseOp):
F
fengjiayi 已提交
235 236
    def setUp(self):
        self.op_type = "elementwise_min"
237
        self.python_api = broadcast_wrapper(shape=[1, 1, 100])
238 239 240
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
241
        x = np.random.uniform(0.5, 1, (2, 3, 100)).astype(np.float64)
242 243 244 245
        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 已提交
246 247 248
        self.inputs = {'X': x, 'Y': y}

        self.outputs = {
249 250 251
            'Out': np.minimum(
                self.inputs['X'], self.inputs['Y'].reshape(1, 1, 100)
            )
F
fengjiayi 已提交
252 253 254
        }


255 256 257 258
class TestElementwiseMinFP16Op_broadcast_2(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = broadcast_wrapper(shape=[1, 1, 100])
259 260 261
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
262 263 264 265 266 267 268 269 270 271 272 273 274 275
        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)
            )
        }


276 277 278
class TestElementwiseMinOp_broadcast_4(TestElementwiseOp):
    def setUp(self):
        self.op_type = "elementwise_min"
279
        self.python_api = paddle.minimum
280 281 282
        self.prim_op_type = "prim"
        self.public_python_api = paddle.minimum
        self.if_enable_cinn()
283 284
        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)
285
        y = x + sgn * np.random.uniform(1, 2, (2, 10, 1, 5)).astype(np.float64)
286 287 288 289 290
        self.inputs = {'X': x, 'Y': y}

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


291 292 293 294
class TestElementwiseMinFP16Op_broadcast_4(TestElementwiseFP16Op):
    def setUp(self):
        self.op_type = "elementwise_min"
        self.python_api = paddle.minimum
295 296 297
        self.public_python_api = paddle.minimum
        self.prim_op_type = "prim"
        self.if_enable_cinn()
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
        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"
331
        self.if_enable_cinn()
332 333 334 335 336 337 338 339 340 341 342 343 344
        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):
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
        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,
            )
368 369

    def test_check_grad_ingore_x(self):
370 371
        places = self._get_places()
        for place in places:
372
            if isinstance(place, paddle.fluid.libpaddle.CPUPlace):
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
                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,
            )
393 394

    def test_check_grad_ingore_y(self):
395 396
        places = self._get_places()
        for place in places:
397
            if isinstance(place, paddle.fluid.libpaddle.CPUPlace):
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                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):
420
        pass
421 422 423 424 425 426 427


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 已提交
428

429 430 431 432 433
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 已提交
434 435


436 437 438 439 440 441
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"
442
        )
S
sneaxiy 已提交
443 444


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