test_elemwise.py 13.3 KB
Newer Older
1 2
# -*- coding: utf-8 -*-
import numpy as np
3
import pytest
4

5
import megengine as mge
6
import megengine.autodiff as ad
7
import megengine.functional as F
8
import megengine.functional.elemwise as elemwise
9
from megengine import tensor
10
from megengine.core.tensor import dtype
11
from megengine.core.tensor.utils import subgraph_fn
12
from megengine.functional.elemwise import Elemwise
13
from megengine.jit import trace
14 15 16


def test_abs():
17
    np.testing.assert_allclose(
18 19 20 21
        F.abs(tensor([-3.0, -4.0, -5.0])).numpy(),
        np.abs(np.array([-3.0, -4.0, -5.0], dtype=np.float32)),
    )

22
    np.testing.assert_allclose(F.abs(-3.0).numpy(), np.abs(np.float32(-3.0)))
23 24


25
def test_elemwise_mode_string():
26 27 28 29
    for key, mode in vars(Elemwise.Mode).items():
        if isinstance(mode, Elemwise.Mode):
            assert key == mode
            assert Elemwise(mode=key) == Elemwise(mode=mode)
30 31


32
def test_multiply():
33
    np.testing.assert_allclose(
34 35
        F.mul(-3.0, -4.0).numpy(), np.multiply(np.float32(-3.0), np.float32(-4.0))
    )
36

37
    np.testing.assert_allclose(
38 39 40 41
        F.mul(tensor([3.0, 4.0]), 4.0).numpy(),
        np.multiply(np.array([3.0, 4.0], dtype=np.float32), 4.0),
    )

42
    np.testing.assert_allclose(
43 44 45 46
        F.mul(4.0, tensor([3.0, 4.0])).numpy(),
        np.multiply(4.0, np.array([3.0, 4.0], dtype=np.float32)),
    )

47
    np.testing.assert_allclose(
48 49 50 51 52 53 54 55
        F.mul(tensor([3.0, 4.0]), tensor([3.0, 4.0])).numpy(),
        np.multiply(
            np.array([3.0, 4.0], dtype=np.float32),
            np.array([3.0, 4.0], dtype=np.float32),
        ),
    )


56 57
def test_div():
    np.testing.assert_allclose(
58
        F.div(tensor([3.0, 4.0]), 2).numpy(),
59 60 61 62 63 64 65
        np.divide(np.array([3, 4], dtype=np.float32), 2),
    )

    np.testing.assert_allclose(
        (tensor([3, 4]) / 2).numpy(), np.divide(np.array([3, 4], dtype=np.float32), 2),
    )

66 67 68 69 70 71 72 73 74 75
    np.testing.assert_allclose(
        F.floor_div(tensor([-5.0, -7.0]), 2).numpy(),
        np.floor_divide(np.array([-5.0, -7.0], dtype=np.float32), 2),
    )

    np.testing.assert_allclose(
        (tensor([-5, -7]) // 2).numpy(),
        np.floor_divide(np.array([-5, -7], dtype=np.int32), 2),
    )

76 77 78 79 80
    np.testing.assert_allclose(
        (tensor([[5, 4, 3], [4, 2, 6]]) // [1, 2, 1]).numpy(),
        np.floor_divide(np.array([[5, 4, 3], [4, 2, 6]], dtype=np.int32), [1, 2, 1]),
    )

81

82 83
def test_clamp():
    """Fix an issue when `lower` or `upper` is 0, it will be recognized as `False` and
84
    `F.clip` will fall into wrong conditions unexpectedly.
85 86
    """
    x = np.linspace(-6, 6, dtype="float32")
87
    np.testing.assert_allclose(
88
        F.clip(tensor(x) + 3, 0, 6).numpy(), np.clip(x + 3, 0, 6)
89 90
    )
    np.testing.assert_allclose(
91
        F.clip(tensor(x) - 3, -6, 0).numpy(), np.clip(x - 3, -6, 0)
92
    )
93 94


95 96
def test_isnan():
    for case in [[1, float("nan"), 0]]:
97
        np.testing.assert_allclose(F.isnan(tensor(case)).numpy(), np.isnan(case))
98 99 100 101


def test_isinf():
    for case in [[1, float("inf"), 0]]:
102
        np.testing.assert_allclose(F.isinf(tensor(case)).numpy(), np.isinf(case))
103 104 105 106 107


def test_sign():
    for case in [[1, -1, 0]]:
        x = tensor(case)
108
        np.testing.assert_allclose(F.sign(x).numpy(), np.sign(case).astype(x.dtype))
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157


def test_cosh():
    np.random.seed(42)
    x = np.random.randn(100).astype("float32")
    y_np = np.cosh(x)
    y_mge = F.cosh(tensor(x)).numpy()
    np.testing.assert_allclose(y_np, y_mge, rtol=1e-5)


def test_sinh():
    np.random.seed(42)
    x = np.random.randn(100).astype("float32")
    y_np = np.sinh(x)
    y_mge = F.sinh(tensor(x)).numpy()
    np.testing.assert_allclose(y_np, y_mge, rtol=1e-5)


def test_asinh():
    np.random.seed(42)
    x = np.random.randn(100).astype("float32")
    y_np = np.arcsinh(x)
    y_mge = F.asinh(tensor(x)).numpy()
    np.testing.assert_almost_equal(y_np, y_mge, decimal=5)


def test_acosh():
    x = np.arange(0, 10000).astype("float32") / 100 + 1
    y_np = np.arccosh(x)
    y_mge = F.acosh(tensor(x)).numpy()
    np.testing.assert_almost_equal(y_np, y_mge, decimal=6)


def test_atanh():
    np.random.seed(42)
    x = np.random.rand(100).astype("float32") * 2 - 1
    y_np = np.arctanh(x)
    y_mge = F.atanh(tensor(x)).numpy()
    np.testing.assert_almost_equal(y_np, y_mge, decimal=5)


def test_hswish():
    np.random.seed(42)
    x = np.random.randn(100).astype("float32")
    y_np = x * np.minimum(np.maximum(x + 3, 0), 6) / 6
    y_mge = F.hswish(tensor(x)).numpy()
    np.testing.assert_almost_equal(y_np, y_mge, decimal=6)


158 159 160 161 162 163 164
def test_silu():
    x = np.array([-1.5, 0.0, 1.0, 1.5]).astype("float32")
    y_np = x / (1 + np.exp(-x))
    y_mge = F.silu(tensor(x)).numpy()
    np.testing.assert_almost_equal(y_np, y_mge, decimal=6)


165 166 167 168 169
def test_hsigmoid():
    np.random.seed(42)
    x = np.random.randn(100).astype("float32")
    y_np = np.minimum(np.maximum(x + 3, 0), 6) / 6
    y_mge = F.hsigmoid(tensor(x)).numpy()
170
    np.testing.assert_almost_equal(y_np, y_mge, decimal=6)
171 172 173 174 175 176 177 178 179 180 181


def test_logical_oprs():
    x = np.array([[True, False], [False, True]])
    y = np.array([[True, True], [False, False]])
    xx = tensor(x)
    yy = tensor(y)
    np.testing.assert_equal(~x, (F.logical_not(xx)).numpy())
    np.testing.assert_equal(x & y, F.logical_and(xx, yy).numpy())
    np.testing.assert_equal(x | y, F.logical_or(xx, yy).numpy())
    np.testing.assert_equal(x ^ y, F.logical_xor(xx, yy).numpy())
182 183


184 185 186 187 188 189 190 191 192 193
def test_logaddexp():
    x = np.random.randn(2, 100)
    y = np.random.randn(2, 100)
    xx = tensor(x)
    yy = tensor(y)
    out_np = np.log(np.exp(x) + np.exp(y))
    out_mge = F.logaddexp(xx, yy)
    np.testing.assert_almost_equal(out_np, out_mge.numpy(), decimal=6)


194 195 196 197 198 199 200 201
def test_qadd():
    inp_scale = 0.5
    outp_scale = 0.2
    x = np.arange(6).reshape(2, 3).astype("float32")
    y = np.arange(6).reshape(2, 3).astype("float32")
    x = tensor(x, dtype=dtype.qint8(inp_scale))
    y = tensor(y, dtype=dtype.qint8(inp_scale))
    result_mge = F.elemwise._elemwise_multi_type(
202
        x, y, mode="qadd", dtype=dtype.qint8(outp_scale)
203 204 205 206
    )
    result_mge = result_mge.astype("float32").numpy()
    result_expect = x.astype("float32").numpy() + y.astype("float32").numpy()
    np.testing.assert_almost_equal(result_mge, result_expect, decimal=6)
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223


def test_int32_input():
    x = tensor(np.array([1, 2, 3, 4, 5]), dtype="int32")
    for op_name in elemwise.__all__:
        op = getattr(elemwise, op_name)
        nargs = op.__code__.co_argcount
        if op_name == "clip":
            inp = (x, 0, 1)
        elif op_name.endswith("_shift"):
            inp = (x, 1)
        elif op_name.startswith("logical_"):
            continue
        else:
            inp = (x,) * nargs
        y = op(*inp)
        y.numpy()
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259


@pytest.mark.parametrize("is_trace", [True, False])
def test_empty_tensor(is_trace):
    binary_func = []
    unary_func = []
    for op_name in elemwise.__all__:
        op = getattr(elemwise, op_name)
        nargs = op.__code__.co_argcount
        if op_name == "clip":
            unary_func.append(["clip", lambda x, f=op: f(x, lower=0, upper=1)])
        elif op_name.endswith("_shift"):
            unary_func.append(
                [op_name, lambda x, f=op: f(tensor(x.numpy(), dtype="int32"), 1)]
            )
        elif op_name.startswith("logical_"):  # logical_xxx op only accept boolean type
            if nargs == 1:
                unary_func.append(
                    [op_name, lambda x, f=op: f(tensor(x.numpy(), dtype="bool"))]
                )
            else:
                assert nargs == 2
                binary_func.append(
                    [
                        op_name,
                        lambda x, y, f=op: f(
                            tensor(x.numpy(), dtype="bool"),
                            tensor(y.numpy(), dtype="bool"),
                        ),
                    ]
                )
        elif nargs == 1:
            unary_func.append([op_name, op])
        elif nargs == 2:
            binary_func.append([op_name, op])
        else:
260
            raise NotImplementedError("nargs {}".format(nargs))
261 262 263 264 265 266 267 268 269 270

    def run_test(func, args, ref_shape, is_trace, sym=False):
        args = [tensor(t, dtype="float32") for t in args]
        if is_trace:
            func = trace(symbolic=sym)(func)
            for _ in range(3):
                out = func(*args)
                assert out.numpy().shape == ref_shape
        else:
            out = func(*args)
271
            assert out.numpy().shape == ref_shape, out.numpy().shape
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

    inps = [
        np.array([]).astype("float32"),
        np.random.randn(2, 0, 3).astype("float32"),
        123,
    ]
    for op_name, op in unary_func:
        if is_trace:
            for sym in [True, False]:
                run_test(op, [inps[0],], inps[0].shape, True, sym)
                run_test(op, [inps[1],], inps[1].shape, True, sym)
        else:
            run_test(op, [inps[0],], inps[0].shape, False)
            run_test(op, [inps[1],], inps[1].shape, False)

    for op_name, op in binary_func:
        if is_trace:
            for sym in [True, False]:
                run_test(op, [inps[0], inps[0]], (inps[0] + inps[0]).shape, True, sym)
                run_test(op, [inps[1], inps[1]], (inps[1] + inps[1]).shape, True, sym)
                run_test(op, [inps[0], inps[2]], (inps[0] + inps[2]).shape, True, sym)
                run_test(op, [inps[1], inps[2]], (inps[1] + inps[2]).shape, True, sym)
        else:
            run_test(op, [inps[0], inps[0]], (inps[0] + inps[0]).shape, False)
            run_test(op, [inps[1], inps[1]], (inps[1] + inps[1]).shape, False)
            run_test(op, [inps[0], inps[2]], (inps[0] + inps[2]).shape, False)
            run_test(op, [inps[1], inps[2]], (inps[1] + inps[2]).shape, False)
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320


@pytest.mark.parametrize("is_trace", [True, False])
def test_maximum_grad_consistency(is_trace):
    def f(x):
        with ad.GradManager() as gm:
            gm.attach(x)
            gm.backward(F.maximum(x, x))
        dx = x.grad
        x.grad = None
        return dx

    def run(f):
        x = F.arange(10)
        for i in range(3):
            np.testing.assert_equal(f(x).numpy(), np.ones(10))

    if is_trace:
        for symbolic in [False, True]:
            run(trace(symbolic=symbolic)(f))
    else:
        run(f)
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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399


def _get_logsigmoid_op(dtype=None, device=None):
    @subgraph_fn(
        "LogSigmoid",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=False,
        custom_grad=True,
    )
    def logsigmoid(inputs, f, c):
        (inp,) = inputs[0:1]
        neg_abs = f("-", f("abs", inp))
        exp = f("exp", neg_abs)
        oup0 = f("log1p", exp)
        oup1 = f("relu", f("-", inp))
        oup = f("+", oup0, oup1)
        oup = f("-", oup)
        (oup_grad,) = yield (oup,)
        oup_grad = f("-", oup_grad)
        inp_grad_0 = f("switch_gt0", oup1, oup_grad)
        inp_grad_0 = f("-", inp_grad_0)
        inp_grad_1 = oup_grad
        inp_grad_1 = f("/", inp_grad_1, f("+", exp, c(1)))
        inp_grad_1 = f("*", inp_grad_1, exp)
        inp_grad_1 = f("-", inp_grad_1)
        inp_grad_1 = f("abs_grad", inp, inp_grad_1)
        inp_grad = f("+", inp_grad_0, inp_grad_1)
        yield (inp_grad,)

    return logsigmoid


def origin_logsigmoid(inp: mge.tensor) -> mge.tensor:
    logsigmoid = _get_logsigmoid_op(inp.dtype, inp.device)
    (oup,) = logsigmoid(inp)
    return oup


def _get_softplus_op(dtype=None, device=None):
    @subgraph_fn(
        "Softplus",
        dtype=dtype,
        device=device,
        nr_inputs=1,
        jit_fusion=False,
        custom_grad=True,
    )
    def softplus(inputs, f, c):
        (inp,) = inputs[0:1]
        neg_abs = f("-", f("abs", inp))
        exp = f("exp", neg_abs)
        oup0 = f("log1p", exp)
        oup1 = f("relu", inp)
        oup = f("+", oup0, oup1)
        (oup_grad,) = yield (oup,)
        inp_grad_0 = f("switch_gt0", oup1, oup_grad)
        inp_grad_1 = oup_grad
        inp_grad_1 = f("/", oup_grad, f("+", exp, c(1)))
        inp_grad_1 = f("*", inp_grad_1, exp)
        inp_grad_1 = f("-", inp_grad_1)
        inp_grad_1 = f("abs_grad", inp, inp_grad_1)
        inp_grad = f("+", inp_grad_0, inp_grad_1)
        yield (inp_grad,)

    return softplus


def origin_softplus(inp: mge.tensor) -> mge.tensor:

    softplus = _get_softplus_op(inp.dtype, inp.device)
    (oup,) = softplus(inp)
    return oup


def test_subgraph_elemwise_mode():
    def _test_allclose(func, ori_func):
        targets = np.array(2)
400
        inp = np.random.uniform(size=(2, 16, 10, 16)).astype(np.float32)
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        ori_inp = mge.tensor(inp)
        mge_inp = mge.tensor(inp)

        mge_gm = mge.autodiff.GradManager().attach(mge_inp)
        ori_gm = mge.autodiff.GradManager().attach(ori_inp)

        for _ in range(2):
            with mge_gm:
                mge_output = func(mge_inp)
                loss = F.loss.square_loss(
                    mge_output.sum(), mge.tensor(targets, dtype=np.float32)
                )
                mge_gm.backward(loss)

            with ori_gm:
                ori_output = ori_func(ori_inp)
                loss = F.loss.square_loss(
                    ori_output.sum(), mge.tensor(targets, dtype=np.float32)
                )
                ori_gm.backward(loss)

            np.testing.assert_allclose(
                mge_output.numpy(), ori_output.numpy(), rtol=1e-06
            )
            np.testing.assert_allclose(
                ori_inp.grad.numpy(), mge_inp.grad.numpy(), rtol=1e-06
            )

    _test_allclose(F.logsigmoid, origin_logsigmoid)
    _test_allclose(F.softplus, origin_softplus)