test_math_ops.py 13.7 KB
Newer Older
Z
zhunaipan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
""" test math ops """
import functools
J
jinyaohui 已提交
17

Z
zhunaipan 已提交
18
import numpy as np
J
jinyaohui 已提交
19

Z
zhunaipan 已提交
20
import mindspore as ms
J
jinyaohui 已提交
21
import mindspore.context as context
Z
zhunaipan 已提交
22 23
import mindspore.nn as nn
from mindspore import Tensor
J
jinyaohui 已提交
24
from mindspore.common import dtype as mstype
Z
zhunaipan 已提交
25
from mindspore.ops import composite as C
J
jinyaohui 已提交
26 27
from mindspore.ops import operations as P
from mindspore.ops import prim_attr_register, PrimitiveWithInfer
Z
zhunaipan 已提交
28 29 30 31 32 33
from ..ut_filter import non_graph_engine
from ....mindspore_test_framework.mindspore_test import mindspore_test
from ....mindspore_test_framework.pipeline.forward.compile_forward \
    import pipeline_for_compile_forward_ge_graph_for_case_by_case_config
from ....mindspore_test_framework.pipeline.forward.verify_exception \
    import pipeline_for_verify_exception_for_case_by_case_config
J
jinyaohui 已提交
34

H
huangdongrun 已提交
35
context.set_context(mode=context.GRAPH_MODE)
36

Z
zhunaipan 已提交
37 38 39 40 41
# pylint: disable=W0613
# pylint: disable=W0231
# W0613: unused-argument
# W0231: super-init-not-called

P
panyifeng 已提交
42
grad = C.GradOperation()
P
panyifeng 已提交
43

Z
zhunaipan 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
def test_multiply():
    """ test_multiply """
    input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]))
    input_y = Tensor(np.array([[0.1, 0.3, -3.6], [0.4, 0.5, -3.2]]))

    mul = P.Mul()
    result = mul(input_x, input_y)
    expect = np.array([[-0.01, 0.09, -12.96], [0.16, 0.25, 10.24]])
    diff = result.asnumpy() - expect
    error = np.ones(shape=[2, 3]) * 1.0e-6
    assert np.all(diff < error)
    assert np.all(-diff < error)


def test_sub():
    """ test_sub """
    input_x = Tensor(np.ones(shape=[3]))
    input_y = Tensor(np.zeros(shape=[3]))

    sub = P.Sub()
    result = sub(input_x, input_y)
    expect = np.ones(shape=[3])
    assert np.all(result.asnumpy() == expect)


def test_square():
    """ test_square """
    input_tensor = Tensor(np.array([[1, 2, 3], [4, 5, 6]]))
    square = P.Square()
    result = square(input_tensor)
    expect = np.array([[1, 4, 9], [16, 25, 36]])
    assert np.all(result.asnumpy() == expect)


def test_sqrt():
    """ test_sqrt """
    input_tensor = Tensor(np.array([[4, 4], [9, 9]]))

    sqrt = P.Sqrt()
    expect = np.array([[2, 2], [3, 3]])
    result = sqrt(input_tensor)
    assert np.all(result.asnumpy() == expect)


C
candanzg 已提交
88 89 90 91 92 93 94 95 96
class PowNet(nn.Cell):
    def __init__(self):
        super(PowNet, self).__init__()
        self.pow = P.Pow()

    def construct(self, x, y):
        return self.pow(x, y)


Z
zhunaipan 已提交
97 98 99
def test_pow():
    """ test_pow """
    input_tensor = Tensor(np.array([[2, 2], [3, 3]]))
100
    power = Tensor(np.array(3.0, np.int64))
C
candanzg 已提交
101
    power2 = Tensor(np.array(True, np.bool))
Z
zhunaipan 已提交
102 103
    testpow = P.Pow()
    expect = np.array([[8, 8], [27, 27]])
104
    result = testpow(input_tensor, power)
Z
zhunaipan 已提交
105
    assert np.all(result.asnumpy() == expect)
C
candanzg 已提交
106
    net = PowNet()
107 108
    net(input_tensor, True)
    net(input_tensor, power2)
Z
zhunaipan 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127


def test_exp():
    """ test_exp """
    input_tensor = Tensor(np.array([[2, 2], [3, 3]]))
    testexp = P.Exp()
    result = testexp(input_tensor)
    expect = np.exp(np.array([[2, 2], [3, 3]]))
    assert np.all(result.asnumpy() == expect)


def test_realdiv():
    """ test_realdiv """
    x = Tensor(2048.0)
    y = Tensor(128.0)
    div = P.RealDiv()
    result = div(x, y)
    x = x.asnumpy()
    y = y.asnumpy()
128
    expect = x / y
Z
zhunaipan 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    assert np.all(result.asnumpy() == expect)


def test_eye():
    """ test_eye """
    x = np.arange(3)
    expect = np.ones_like(x)
    expect = np.diag(expect)
    eye = P.Eye()
    eye_output = eye(3, 3, ms.float32)
    assert np.all(eye_output.asnumpy() == expect)


class VirtualLossGrad(PrimitiveWithInfer):
    """ VirtualLossGrad definition """
144

Z
zhunaipan 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    @prim_attr_register
    def __init__(self):
        """init VirtualLossGrad"""

    def __call__(self, x, out, dout):
        raise NotImplementedError

    def infer_shape(self, x_shape, out_shape, dout_shape):
        return x_shape

    def infer_dtype(self, x_dtype, out_dtype, dout_dtype):
        return x_dtype


class VirtualLoss(PrimitiveWithInfer):
    """ VirtualLoss definition """
161

Z
zhunaipan 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174
    @prim_attr_register
    def __init__(self):
        """init VirtualLoss"""

    def __call__(self, x):
        raise NotImplementedError

    def get_bprop(self):
        loss_grad = VirtualLossGrad()

        def bprop(x, out, dout):
            dx = loss_grad(x, out, dout)
            return (dx,)
175

Z
zhunaipan 已提交
176 177 178 179 180 181 182 183 184 185 186
        return bprop

    def infer_shape(self, x_shape):
        return [1]

    def infer_dtype(self, x_dtype):
        return x_dtype


class NetWithLoss(nn.Cell):
    """ NetWithLoss definition """
187

Z
zhunaipan 已提交
188 189 190 191 192 193 194 195 196 197 198 199
    def __init__(self, network):
        super(NetWithLoss, self).__init__()
        self.loss = VirtualLoss()
        self.network = network

    def construct(self, x, y, b):
        predict = self.network(x, y, b)
        return self.loss(predict)


class GradWrap(nn.Cell):
    """ GradWrap definition """
200

Z
zhunaipan 已提交
201 202 203 204 205
    def __init__(self, network):
        super(GradWrap, self).__init__()
        self.network = network

    def construct(self, x, y, b):
P
panyifeng 已提交
206
        return grad(self.network)(x, y, b)
Z
zhunaipan 已提交
207 208 209 210


class MatMulNet(nn.Cell):
    """ MatMulNet definition """
211

Z
zhunaipan 已提交
212 213 214 215 216 217 218 219 220 221 222
    def __init__(self):
        super(MatMulNet, self).__init__()
        self.matmul = P.MatMul()
        self.biasAdd = P.BiasAdd()

    def construct(self, x, y, b):
        return self.biasAdd(self.matmul(x, y), b)


class NetWithLossSub(nn.Cell):
    """ NetWithLossSub definition """
223

Z
zhunaipan 已提交
224 225 226 227 228 229 230 231 232 233 234 235
    def __init__(self, network):
        super(NetWithLossSub, self).__init__()
        self.loss = VirtualLoss()
        self.network = network

    def construct(self, x, y):
        predict = self.network(x, y)
        return self.loss(predict)


class GradWrapSub(nn.Cell):
    """ GradWrapSub definition """
236

Z
zhunaipan 已提交
237 238 239 240 241
    def __init__(self, network):
        super(GradWrapSub, self).__init__()
        self.network = network

    def construct(self, x, y):
P
panyifeng 已提交
242
        return grad(self.network)(x, y)
Z
zhunaipan 已提交
243 244 245 246


class SubNet(nn.Cell):
    """ SubNet definition """
247

Z
zhunaipan 已提交
248 249 250 251 252 253 254 255 256 257
    def __init__(self):
        super(SubNet, self).__init__()
        self.sub = P.Sub()

    def construct(self, x, y):
        return self.sub(x, y)


class NpuFloatNet(nn.Cell):
    """ NpuFloat definition """
258

Z
zhunaipan 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    def __init__(self):
        super(NpuFloatNet, self).__init__()
        self.mul = P.Mul()
        self.alloc_status = P.NPUAllocFloatStatus()
        self.get_status = P.NPUGetFloatStatus()
        self.clear_status = P.NPUClearFloatStatus()
        self.fill = P.Fill()
        self.shape_op = P.Shape()
        self.select = P.Select()
        self.less = P.Less()
        self.cast = P.Cast()
        self.dtype = P.DType()
        self.reduce_sum = P.ReduceSum(keep_dims=True)
        self.sub = P.Sub()
        self.neg = P.Neg()

W
Wei Luning 已提交
275
    @C.add_flags(has_effect=True)
Z
zhunaipan 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289
    def construct(self, x):
        init = self.alloc_status()
        self.clear_status(init)
        res = self.sub(x, self.neg(x))
        self.get_status(init)
        flag_sum = self.reduce_sum(init, (0,))
        base = self.cast(self.fill(self.dtype(res), self.shape_op(res), 0.0), self.dtype(flag_sum))
        cond = self.less(base, flag_sum)
        out = self.select(cond, self.cast(base, self.dtype(res)), res)
        return out


class DiagNet(nn.Cell):
    """ DiagNet definition """
290

Z
zhunaipan 已提交
291 292 293 294 295 296 297 298 299 300 301
    def __init__(self):
        super(DiagNet, self).__init__()
        self.fill = P.Fill()
        self.diag = P.Diag()

    def construct(self, x):
        return x - self.diag(self.fill(mstype.float32, (3,), 1.0))


class NetWithLossCumSum(nn.Cell):
    """ NetWithLossCumSum definition """
302

Z
zhunaipan 已提交
303 304 305 306 307
    def __init__(self, network):
        super(NetWithLossCumSum, self).__init__()
        self.loss = VirtualLoss()
        self.network = network

308 309
    def construct(self, input_):
        predict = self.network(input_)
Z
zhunaipan 已提交
310 311 312 313 314
        return self.loss(predict)


class GradWrapCumSum(nn.Cell):
    """ GradWrap definition """
315

Z
zhunaipan 已提交
316 317 318 319
    def __init__(self, network):
        super(GradWrapCumSum, self).__init__()
        self.network = network

320
    def construct(self, input_):
P
panyifeng 已提交
321
        return grad(self.network)(input_)
Z
zhunaipan 已提交
322 323 324 325


class NetCumSum(nn.Cell):
    """ NetCumSum definition """
326

Z
zhunaipan 已提交
327 328 329 330 331
    def __init__(self):
        super(NetCumSum, self).__init__()
        self.cumsum = P.CumSum()
        self.axis = 1

332 333
    def construct(self, input_):
        return self.cumsum(input_, self.axis)
Z
zhunaipan 已提交
334 335 336 337 338 339 340 341 342 343


class SignNet(nn.Cell):
    def __init__(self):
        super(SignNet, self).__init__()
        self.sign = P.Sign()

    def construct(self, x):
        return self.sign(x)

J
jinyaohui 已提交
344

345 346 347 348 349 350 351 352 353
class AssignAdd(nn.Cell):
    def __init__(self):
        super().__init__()
        self.op = P.AssignAdd()
        self.inputdata = Parameter(initializer(1, [1], ms.float32), name="global_step")

    def construct(self, input_):
        self.inputdata = input_
        return self.op(self.inputdata, input_)
Z
zhunaipan 已提交
354

J
jinyaohui 已提交
355

J
jiangjinsheng 已提交
356 357 358 359 360 361 362 363
class FloorNet(nn.Cell):
    def __init__(self):
        super(FloorNet, self).__init__()
        self.floor = P.Floor()

    def construct(self, x):
        return self.floor(x)

J
jinyaohui 已提交
364

J
jiangjinsheng 已提交
365 366 367 368 369 370 371 372
class Log1pNet(nn.Cell):
    def __init__(self):
        super(Log1pNet, self).__init__()
        self.log1p = P.Log1p()

    def construct(self, x):
        return self.log1p(x)

J
jiangjinsheng 已提交
373

J
jiangjinsheng 已提交
374 375 376 377 378 379 380 381 382
class ErfcNet(nn.Cell):
    def __init__(self):
        super(ErfcNet, self).__init__()
        self.erfc = P.Erfc()

    def construct(self, x):
        return self.erfc(x)


Z
zhunaipan 已提交
383 384 385 386 387 388 389 390 391 392 393 394
test_case_math_ops = [
    ('MatMulGrad', {
        'block': GradWrap(NetWithLoss(MatMulNet())),
        'desc_inputs': [Tensor(np.ones([3, 3]).astype(np.int32)),
                        Tensor(np.ones([3, 3]).astype(np.int32)),
                        Tensor(np.ones([3]).astype(np.int32))],
        'desc_bprop': [Tensor(np.ones([3, 3]).astype(np.int32)),
                       Tensor(np.ones([3, 3]).astype(np.int32)),
                       Tensor(np.ones([3]).astype(np.int32))],
        'skip': ['backward']}),
    ('CumSumGrad', {
        'block': GradWrapCumSum(NetWithLossCumSum(NetCumSum())),
395 396
        'desc_inputs': [Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float16))],
        'desc_bprop': [Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float16))],
Z
zhunaipan 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        'skip': ['backward']}),
    ('Diag', {
        'block': DiagNet(),
        'desc_inputs': [Tensor(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]], np.float32))],
        'desc_bprop': [Tensor(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]], np.float32))],
        'skip': ['backward']}),
    ('SubBroadcast', {
        'block': GradWrapSub(NetWithLossSub(SubNet())),
        'desc_inputs': [Tensor(np.ones([5, 3])), Tensor(np.ones([8, 5, 3]))],
        'desc_bprop': [Tensor(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]], np.float32))],
        'skip': ['backward']}),
    ('NpuFloat_NotOverflow', {
        'block': NpuFloatNet(),
        'desc_inputs': [Tensor(np.full((8, 5, 3, 1), 655, dtype=np.float16), dtype=ms.float16)],
        'desc_bprop': [Tensor(np.full((8, 5, 3, 1), 655, dtype=np.float16), dtype=ms.float16)],
        'skip': ['backward']}),
    ('NpuFloat_Overflow', {
        'block': NpuFloatNet(),
        'desc_inputs': [Tensor(np.full((8, 5, 3, 1), 65504, dtype=np.float16), dtype=ms.float16)],
        'desc_bprop': [Tensor(np.full((8, 5, 3, 1), 65504, dtype=np.float16), dtype=ms.float16)],
        'skip': ['backward']}),
    ('Sign', {
        'block': SignNet(),
        'desc_inputs': [Tensor(np.array([[1., 0., -2.]], np.float32))],
        'desc_bprop': [Tensor(np.array([[1., 0., -2.]], np.float32))],
        'skip': ['backward']}),
J
jiangjinsheng 已提交
423 424 425 426 427
    ('Floor', {
        'block': FloorNet(),
        'desc_inputs': [Tensor(np.array([[1., 0., -2.]], np.float32))],
        'desc_bprop': [Tensor(np.array([[1., 0., -2.]], np.float32))],
        'skip': ['backward']}),
J
jiangjinsheng 已提交
428 429 430 431 432
    ('Log1p', {
        'block': Log1pNet(),
        'desc_inputs': [Tensor(np.array([[1.0, 2.0, 4.0]], np.float32))],
        'desc_bprop': [Tensor(np.array([[1.0, 2.0, 4.0]], np.float32))],
        'skip': ['backward']}),
J
jiangjinsheng 已提交
433 434 435 436 437
    ('Erfc', {
        'block': ErfcNet(),
        'desc_inputs': [Tensor(np.array([[1.0, 2.0, 4.0]], np.float32))],
        'desc_bprop': [Tensor(np.array([[1.0, 2.0, 4.0]], np.float32))],
    }),
Z
zhunaipan 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
]

test_case_lists = [test_case_math_ops]
test_exec_case = functools.reduce(lambda x, y: x + y, test_case_lists)
# use -k to select certain testcast
# pytest tests/python/ops/test_ops.py::test_backward -k LayerNorm


@non_graph_engine
@mindspore_test(pipeline_for_compile_forward_ge_graph_for_case_by_case_config)
def test_exec():
    context.set_context(mode=context.GRAPH_MODE)
    return test_exec_case


raise_set = [
    ('StridedSlice_1_Error', {
Z
zhaojichen 已提交
455
        'block': (lambda x: P.StridedSlice(begin_mask="1"), {'exception': TypeError}),
Z
zhunaipan 已提交
456 457
        'desc_inputs': [0]}),
    ('StridedSlice_2_Error', {
Z
zhaojichen 已提交
458
        'block': (lambda x: P.StridedSlice(end_mask="1"), {'exception': TypeError}),
Z
zhunaipan 已提交
459 460
        'desc_inputs': [0]}),
    ('StridedSlice_3_Error', {
Z
zhaojichen 已提交
461
        'block': (lambda x: P.StridedSlice(ellipsis_mask=1.1), {'exception': TypeError}),
Z
zhunaipan 已提交
462 463
        'desc_inputs': [0]}),
    ('StridedSlice_4_Error', {
Z
zhaojichen 已提交
464
        'block': (lambda x: P.StridedSlice(new_axis_mask="1.1"), {'exception': TypeError}),
Z
zhunaipan 已提交
465
        'desc_inputs': [0]}),
466
    ('AssignAdd_Error', {
C
candanzg 已提交
467
        'block': (P.AssignAdd(), {'exception': IndexError}),
468
        'desc_inputs': [[1]]}),
Z
zhunaipan 已提交
469 470 471 472 473 474
]


@mindspore_test(pipeline_for_verify_exception_for_case_by_case_config)
def test_check_exception():
    return raise_set