test_tensor.py 33.0 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
import os
3 4
import platform

5 6
import numpy as np
import pytest
7
from utils import get_var_value, make_tensor, opr_test
8 9

import megengine.functional as F
10
from megengine import Tensor
11
from megengine.core._trace_option import use_symbolic_shape
12
from megengine.core.tensor import megbrain_graph as G
13
from megengine.core.tensor.utils import astensor1d
14
from megengine.jit import trace
15
from megengine.utils.network import Network, set_symbolic_shape
16
from megengine.utils.network_node import VarNode
17 18 19


def test_eye():
20
    dtypes = [np.float32, np.bool]
21
    cases = [{"input": [10, 20]}, {"input": [30]}]
22 23 24 25 26 27 28 29 30 31 32
    for dtype in dtypes:
        for case in cases:
            np.testing.assert_allclose(
                F.eye(case["input"], dtype=dtype).numpy(),
                np.eye(*case["input"]).astype(dtype),
            )
            np.testing.assert_allclose(
                F.eye(*case["input"], dtype=dtype).numpy(),
                np.eye(*case["input"]).astype(dtype),
            )
            np.testing.assert_allclose(
33
                F.eye(Tensor(case["input"]), dtype=dtype).numpy(),
34 35
                np.eye(*case["input"]).astype(dtype),
            )
36 37


38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
@pytest.mark.parametrize("is_varnode", [False, True])
def test_diag(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    shapes = [(10, 10), (6, 9), (8, 7), (8,)]
    cases = []
    for shp in shapes:
        cases.append({"input": [np.random.random(shp).astype("float32")]})

    for axis in range(-2, 3):

        def run(data):
            return F.diag(data, k=axis)

        opr_test(cases, run, ref_fn=lambda x: np.diag(x, axis), network=network)


58 59 60 61 62
def test_full():
    shape = (2, 3)
    values = [True, 4, 5.0]
    for value in values:
        np.testing.assert_allclose(F.full(shape, value).numpy(), np.full(shape, value))
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        assert F.full(shape, value).dtype == Tensor(value).dtype


@pytest.mark.parametrize("is_varnode", [True, False])
def test_cumsum(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    x = Tensor([[1, 2, 3], [4, 5, 6]], np.int32)
    y = F.cumsum(x, -1)
    np.testing.assert_equal(
        y.numpy(), np.array([[1, 3, 6], [4, 9, 15]]).astype(np.int32)
    )
78 79


80 81 82 83 84 85 86
@pytest.mark.parametrize("is_varnode", [True, False])
def test_concat(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

87 88 89 90 91 92 93 94 95 96 97
    def get_data_shape(length: int):
        return (length, 2, 3)

    data1 = np.random.random(get_data_shape(5)).astype("float32")
    data2 = np.random.random(get_data_shape(6)).astype("float32")
    data3 = np.random.random(get_data_shape(7)).astype("float32")

    def run(data1, data2):
        return F.concat([data1, data2])

    cases = [{"input": [data1, data2]}, {"input": [data1, data3]}]
98
    opr_test(cases, run, ref_fn=lambda x, y: np.concatenate([x, y]), network=network)
99

100 101 102 103 104 105 106 107
    x1 = Tensor(np.arange(0, 6, dtype=np.float32).reshape((2, 3)))
    x2 = Tensor(np.arange(6, 12, dtype=np.float32).reshape((2, 3)))
    y = F.concat([x1, x2], axis=-1)
    np.testing.assert_equal(
        y.numpy(),
        np.array([[0, 1, 2, 6, 7, 8], [3, 4, 5, 9, 10, 11]]).astype(np.float32),
    )

108

109 110 111 112 113 114 115 116 117 118 119 120
@pytest.mark.parametrize("is_varnode", [True, False])
def test_condtake(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    x = np.array([[1, 2, 3], [4, 5, 6]]).astype("float32")
    y = np.array([[True, False, True], [False, True, True]])
    xx = make_tensor(x, network)
    yy = make_tensor(y, network)
    val, idx = F.cond_take(yy, xx)
121 122 123 124 125 126
    if is_varnode:
        np.testing.assert_equal(get_var_value(val), x[y])
        np.testing.assert_equal(get_var_value(idx), np.where(y.reshape(-1))[0])
    else:
        np.testing.assert_equal(val.numpy(), x[y])
        np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
127 128


129
@pytest.mark.parametrize("is_varnode", [True, False])
130
def test_concat_stack_device(is_varnode):
131 132 133 134 135
    if is_varnode:
        network = Network()
    else:
        network = None

136
    data1 = make_tensor(np.random.random((2, 2, 2)).astype("float32"), network, "cpu0")
137
    data2 = make_tensor(np.random.random((2, 2, 2)).astype("float32"), network, "cpu1")
138
    data3 = make_tensor(np.random.random((2, 2, 2)).astype("float32"), network, "cpu0")
139

140 141 142 143 144 145 146 147 148 149 150
    for func in [F.concat, F.stack]:
        out = F.concat([data1, data2], device="cpu1")
        assert str(out.device).split(":")[0] == "cpu1"
        out = F.concat([data1, data3])
        assert str(out.device).split(":")[0] == "cpu0"

        with pytest.raises(RuntimeError):
            try:
                out = F.concat([data1, data2])
            except:
                raise RuntimeError("inputs have different devices")
151 152


153 154 155 156 157 158 159
@pytest.mark.parametrize("is_varnode", [True, False])
def test_stack(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

160 161 162 163 164 165 166 167 168 169
    data1 = np.random.random((3, 2, 2)).astype("float32")
    data2 = np.random.random((3, 2, 2)).astype("float32")
    data3 = np.random.random((3, 2, 2)).astype("float32")

    cases = [{"input": [data1, data2]}, {"input": [data1, data3]}]
    for ai in range(3):

        def run(data1, data2):
            return F.stack([data1, data2], axis=ai)

170 171 172 173
        opr_test(
            cases, run, ref_fn=lambda x, y: np.stack([x, y], axis=ai), network=network
        )

174 175 176 177 178 179 180 181 182 183 184 185 186 187
    x1 = Tensor(np.arange(0, 3, dtype=np.float32).reshape((3)))
    x2 = Tensor(np.arange(6, 9, dtype=np.float32).reshape((3)))
    y = F.stack([x1, x2], axis=-1)
    np.testing.assert_equal(
        y.numpy(), np.array([[0, 6], [1, 7], [2, 8]]).astype(np.float32)
    )

    x1 = Tensor(np.arange(0, 3, dtype=np.float32).reshape((3)))
    x2 = Tensor(np.arange(6, 9, dtype=np.float32).reshape((3)))
    y = F.stack([x1, x2], axis=-1)
    np.testing.assert_equal(
        y.numpy(), np.array([[0, 6], [1, 7], [2, 8]]).astype(np.float32)
    )

188

189
@pytest.mark.parametrize("is_varnode", [True, False])
190
def test_split_basic(is_varnode):
191 192
    if is_varnode:
        network = Network()
193
        saved_symbolic_shape = set_symbolic_shape(False)
194 195
    else:
        network = None
196 197

    data = np.random.random((2, 3, 4, 5)).astype(np.float32)
198
    inp = make_tensor(data, network)
199 200 201

    mge_out0 = F.split(inp, 2, axis=3)
    mge_out1 = F.split(inp, [3], axis=3)
202 203 204

    np_out = np.split(data, [3, 5], axis=3)

205 206 207 208
    assert len(mge_out0) == 2
    assert len(mge_out1) == 2

    np.testing.assert_equal(mge_out0[0].numpy(), np_out[0])
209 210
    np.testing.assert_equal(mge_out1[0].numpy(), np_out[0])

211 212 213 214 215 216 217 218 219 220
    np.testing.assert_equal(mge_out0[1].numpy(), np_out[1])
    np.testing.assert_equal(mge_out1[1].numpy(), np_out[1])

    try:
        F.split(inp, 4)
        assert False
    except ValueError as e:
        pass

    try:
221
        F.split(inp, [3, 2, 5], axis=3)
222 223
        assert False
    except ValueError as e:
224
        assert str(e) == "Invalid nsplits_or_secions: [3, 2, 5]"
225

226 227 228
    if is_varnode:
        set_symbolic_shape(saved_symbolic_shape)

229

230 231
def test_concat_and_stack():
    import copy
232 233
    from megengine.autodiff import GradManager
    import torch
234 235

    def generate_test_data(max_nr_inp, max_dim, max_dim_len, test_concat=True):
236
        nr_inp = np.random.randint(1, max_nr_inp) if max_nr_inp > 1 else 1
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        dims = np.random.randint(1, max_dim)
        cat_axis = (
            np.random.randint(-dims, dims)
            if test_concat
            else np.random.randint(-dims - 1, dims + 1)
        )

        ishape = [np.random.randint(0, max_dim_len) for _ in range(dims)]
        ishapes = [copy.deepcopy(ishape) for _ in range(nr_inp)]
        if test_concat:
            for i in range(nr_inp):
                ishapes[i][cat_axis] = np.random.randint(0, max_dim_len)

        inp_nps = []
        for ishape in ishapes:
            inp_nps.append(np.random.randn(*ishape))
        return inp_nps, cat_axis

    def test_impl(max_nr_inp, max_dim, max_dim_len, test_concat):
        inp_nps, cat_axis = generate_test_data(
            max_nr_inp, max_dim, max_dim_len, test_concat
        )
        inp_mges = [Tensor(inp_np) for inp_np in inp_nps]
260
        inp_torchs = [torch.tensor(inp_np, requires_grad=True) for inp_np in inp_nps]
261
        if test_concat:
262
            np_func, mge_func, torch_func = np.concatenate, F.concat, torch.cat
263
        else:
264 265
            np_func, mge_func, torch_func = np.stack, F.stack, torch.stack

266
        res_np = np_func(inp_nps, axis=cat_axis)
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        grad_np = np.random.randn(*res_np.shape).astype(np.float32)

        gm = GradManager().attach(inp_mges)
        with gm:
            res_mge = mge_func(inp_mges, axis=cat_axis)
            gm.backward(res_mge, Tensor(grad_np))

        res_torch = torch_func(inp_torchs, dim=cat_axis)
        res_torch.backward(torch.tensor(grad_np))

        np.testing.assert_allclose(res_mge.numpy(), res_torch.detach().cpu().numpy())
        for inp_mge, inp_torch in zip(inp_mges, inp_torchs):
            np.testing.assert_allclose(
                inp_mge.grad.numpy(), inp_torch.grad.detach().cpu().numpy()
            )
282 283 284 285 286 287 288

    def test_concat(max_nr_inp, max_dim, max_dim_len):
        test_impl(max_nr_inp, max_dim, max_dim_len, test_concat=True)

    def test_stack(max_nr_inp, max_dim, max_dim_len):
        test_impl(max_nr_inp, max_dim, max_dim_len, test_concat=False)

289 290 291 292 293 294 295 296
    # test only one input
    test_concat(1, 7, 16)
    test_stack(1, 7, 16)

    # test zero shape
    test_concat(10, 7, 1)
    test_stack(10, 7, 1)

297 298 299 300 301 302 303
    for _ in range(3):
        test_concat(10, 7, 16)

    for _ in range(3):
        test_stack(10, 7, 16)


304 305
@pytest.mark.parametrize("symbolic", [None, False, True])
def test_split(symbolic):
306 307 308 309 310 311
    x = Tensor(np.random.random((10, 20)), dtype=np.float32)
    y = F.split(x, 3, axis=-1)
    z = F.split(x, [6, 17], axis=-1)
    assert str([i.numpy().shape for i in y]) == "[(10, 7), (10, 7), (10, 6)]"
    assert str([i.numpy().shape for i in z]) == "[(10, 6), (10, 11), (10, 3)]"

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    inp1 = np.random.random((3, 4, 5, 6)).astype(np.float32)
    inp2 = np.random.random((0, 4, 5, 6)).astype(np.float32)

    def ref(inp, nsplits_or_sections, axis):
        return np.split(inp, nsplits_or_sections, axis)

    def func(inp, nsplits_or_sections, axis):
        return F.split(inp, nsplits_or_sections, axis)

    cases = [
        (inp1, 2, 3),
        (inp1, [3], 3),
        (inp1, [3, 3, 5], 3),
        (inp2, 2, 3),
        (inp2, [3], 3),
        (inp2, [3, 3, 5], 3),
    ]

    for case in cases:
        if symbolic is None:
            fn = func
        else:
            fn = trace(symbolic=symbolic)(func)
        for i in range(3 if symbolic is not None else 1):
            ref_out = ref(*case)
337
            out = fn(Tensor(case[0]), case[1], case[2])
338 339 340 341 342
            assert len(ref_out) == len(out)
            for idx in range(len(ref_out)):
                np.testing.assert_equal(ref_out[idx], out[idx].numpy())


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
def test_gather():
    x = Tensor([[1, 2], [3, 4], [5, 6],])
    index = Tensor([[0, 1], [1, 0], [1, 1]])
    y = F.gather(x, 1, index)
    np.testing.assert_equal(
        y.numpy(), np.array([[1, 2], [4, 3], [6, 6]]).astype(np.int32)
    )


def test_scatter():
    x = Tensor(np.zeros(shape=(3, 5), dtype=np.float32))
    source = Tensor(
        [
            [0.9935, 0.9465, 0.2256, 0.8926, 0.4396],
            [0.7723, 0.0718, 0.5939, 0.357, 0.4576],
        ]
    )
    index = Tensor([[0, 2, 0, 2, 1], [2, 0, 1, 1, 2]])
    y = F.scatter(x, -2, index, source)
    np.testing.assert_equal(
        y.numpy().round(decimals=4),
        np.array(
            [
                [0.9935, 0.0718, 0.2256, 0.0, 0.0],
                [0.0, 0.0, 0.5939, 0.357, 0.4396],
                [0.7723, 0.9465, 0.0, 0.8926, 0.4576],
            ]
        ).astype(np.float32),
    )


374 375 376 377 378 379 380
@pytest.mark.parametrize("is_varnode", [True, False])
def test_swapaxes(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

381
    x = Tensor(np.array([[1, 2, 3]], dtype=np.int32))
382 383 384 385
    y = F.swapaxes(x, 0, 1)
    np.testing.assert_equal(y.numpy(), np.array([[1], [2], [3]]).astype(np.int32))


386 387 388 389 390 391 392
@pytest.mark.parametrize("is_varnode", [True, False])
def test_reshape(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

393
    x = np.arange(6, dtype="float32")
394
    xx = make_tensor(x, network)
395 396 397 398 399
    y = x.reshape(1, 2, 3)

    for shape in [
        (1, 2, 3),
        (1, -1, 3),
400
        (1, make_tensor(-1, network), 3),
401
        np.array([1, -1, 3], dtype="int32"),
402
        make_tensor([1, -1, 3], network),
403 404 405 406 407
    ]:
        yy = F.reshape(xx, shape)
        np.testing.assert_equal(yy.numpy(), y)


408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
@pytest.mark.parametrize("is_varnode", [True, False])
def test_broadcast_auto_infer(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    x = np.random.random((1, 2, 3)).astype(np.float32)
    xx = make_tensor(x, network)

    for shape in [
        (1, 2, 3),
        (1, None, 3),
    ]:
        yy = F.broadcast_to(xx, shape)
        np.testing.assert_equal(yy.numpy(), x)

    with pytest.raises(ValueError):
        F.broadcast_to(xx, (1, -1, 3))

    with pytest.raises(ValueError):
        F.broadcast_to(xx, (None, 1, 2, 3))

    F.broadcast_to(xx, (1, None, 2, 3))
432
    t = make_tensor(2, network)
433 434 435
    F.broadcast_to(xx, (t, None, 2, 3))


436 437 438 439
@pytest.mark.parametrize("is_trace", [True, False])
def test_reshape_on_empty_tensor(is_trace):
    input1_shape = (100, 0, 1)
    output1_shape = (100, 0, 10)
440
    data1 = Tensor(np.random.random(input1_shape).astype(np.float32))
441 442 443

    input2_shape = (10, 0)
    output2_shape = (0,)
444
    data2 = Tensor(np.random.random(input2_shape).astype(np.float32))
445 446 447

    input3_shape = (10, 0, 10)
    output3_shape = (0, 1, 2, 3)
448
    data3 = Tensor(np.random.random(input3_shape).astype(np.float32))
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

    def comp(out, target_shp):
        assert out._tuple_shape == target_shp

    def func(x, shp):
        return F.reshape(x, shp)

    cases = [
        [data1, output1_shape],
        [data2, output2_shape],
        [data3, output3_shape],
    ]

    def test(func, inp, comp, target_shp):
        out = func(inp, target_shp)
        comp(out, target_shp)

    if is_trace:
        for symbolic in [False, True]:
            for inp, target_shp in cases:
                func_traced = trace(symbolic=symbolic)(func)
                test(func_traced, inp, comp, target_shp)
                test(func_traced, inp, comp, target_shp)
                test(func_traced, inp, comp, target_shp)
    else:
        for inp, target_shp in cases:
            test(func, inp, comp, target_shp)


478 479 480 481
@pytest.mark.parametrize("is_varnode", [True, False])
def test_reshape_shape_inference(is_varnode):
    if is_varnode:
        network = Network()
482
        saved_symbolic_shape = set_symbolic_shape(False)
483 484 485 486 487 488 489 490 491 492
    else:
        network = None

    x_shape_known = make_tensor([1, 2, 3, 4], network)
    x_shape_unknown = F.broadcast_to(
        make_tensor([1.0], network), shape=make_tensor([1, 1, 1, 1], network).sum()
    )
    tshp_unknown = astensor1d(
        (make_tensor([2], network), make_tensor([2], network)), x_shape_known
    )
493 494 495 496 497
    tshp_known = astensor1d((2, 2), x_shape_known)
    tshp_known_unspec = astensor1d((2, -1), x_shape_known)

    def check_shape(output, target):
        source = output.shape
498
        if isinstance(source, Tensor):
499
            source = source.numpy()
500
        np.testing.assert_equal(source, target.shape)
501 502 503 504 505

    def func(x, target_shape):
        return x.reshape(target_shape)

    cases = [
506 507 508 509 510 511
        {"input": [x_shape_known, tshp_unknown], "output": [np.zeros((2, 2)),]},
        {"input": [x_shape_unknown, tshp_unknown], "output": [np.zeros((2, 2)),]},
        {"input": [x_shape_known, tshp_known], "output": [np.zeros((2, 2)),]},
        {"input": [x_shape_known, tshp_known_unspec], "output": [np.zeros((2, 2)),]},
        {"input": [x_shape_unknown, tshp_known], "output": [np.zeros((2, 2)),]},
        {"input": [x_shape_unknown, tshp_known_unspec], "output": [np.zeros((2, 2)),]},
512
    ]
513
    opr_test(cases, func, compare_fn=check_shape, test_trace=True, network=network)
514 515
    if is_varnode:
        set_symbolic_shape(saved_symbolic_shape)
516

517

518 519 520 521
@pytest.mark.parametrize("is_varnode", [True, False])
def test_squeeze(is_varnode):
    if is_varnode:
        network = Network()
522
        saved_symbolic_shape = set_symbolic_shape(False)
523 524
    else:
        network = None
525

526 527 528 529
    x = Tensor(np.array([1, 2], dtype=np.int32).reshape(1, 1, 2, 1))
    y = F.squeeze(x, -1)
    np.testing.assert_equal(y.numpy(), np.array([[[1, 2]]]).astype(np.int32))

530
    x = np.arange(6, dtype="float32").reshape(1, 2, 3, 1)
531
    xx = make_tensor(x, network)
532 533 534

    for axis in [None, 3, -4, (3, -4)]:
        y = np.squeeze(x, axis)
535
        yy = F.squeeze(xx, axis)
536 537
        np.testing.assert_equal(y, yy.numpy())

538 539 540
    if is_varnode:
        set_symbolic_shape(saved_symbolic_shape)

541

542 543 544 545 546 547 548
@pytest.mark.parametrize("is_varnode", [True, False])
def test_expand_dims(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

549 550 551 552 553 554
    x = Tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
    y = F.expand_dims(x, -1)
    np.testing.assert_equal(
        y.numpy(), np.array([[[1], [2], [3]], [[4], [5], [6]]]).astype(np.int32)
    )

555
    x = np.arange(6, dtype="float32").reshape(2, 3)
556
    xx = make_tensor(x, network)
557 558 559

    for axis in [2, -3, (3, -4), (1, -4)]:
        y = np.expand_dims(x, axis)
560
        yy = F.expand_dims(xx, axis)
561 562 563
        np.testing.assert_equal(y, yy.numpy())


564 565 566 567 568 569 570 571 572 573
def test_expand_dims_for_scalar():
    x = np.array(1, dtype="float32")
    xx = make_tensor(x, None)
    for axis in [0, -1, (0, 1), (-1, -2), (0, -1)]:
        y = np.expand_dims(x, axis)
        yy = F.expand_dims(xx, axis)
        np.testing.assert_equal(y, yy.numpy())

    for axis in [1, -2, (1, 2), (-2, -3)]:
        np.testing.assert_raises(np.AxisError, np.expand_dims, x, axis)
574
        np.testing.assert_raises(RuntimeError, F.expand_dims, xx, axis)
575 576


577 578 579 580 581 582 583
@pytest.mark.parametrize("is_varnode", [True, False])
def test_elemwise_dtype_promotion(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

584 585
    x = np.random.rand(2, 3).astype("float32")
    y = np.random.rand(1, 3).astype("float16")
586 587
    xx = make_tensor(x, network)
    yy = make_tensor(y, network)
588 589 590 591 592 593 594 595 596 597
    z = xx * yy
    np.testing.assert_equal(z.numpy(), x * y)

    z = xx + y
    np.testing.assert_equal(z.numpy(), x + y)

    z = x - yy
    np.testing.assert_equal(z.numpy(), x - y)


598 599 600 601 602 603 604
@pytest.mark.parametrize("is_varnode", [True, False])
def test_linspace(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

605 606 607 608 609 610 611 612
    cases = [
        {"input": [1, 9, 9]},
        {"input": [3, 10, 8]},
    ]
    opr_test(
        cases,
        F.linspace,
        ref_fn=lambda start, end, step: np.linspace(start, end, step, dtype=np.float32),
613
        network=network,
614 615 616 617 618 619 620 621 622 623
    )

    cases = [
        {"input": [9, 1, 9]},
        {"input": [10, 3, 8]},
    ]
    opr_test(
        cases,
        F.linspace,
        ref_fn=lambda start, end, step: np.linspace(start, end, step, dtype=np.float32),
624
        network=network,
625 626 627
    )

    cases = [
628 629
        {"input": [1, make_tensor(9, network), 9]},
        {"input": [make_tensor(1, network), 9, make_tensor(9, network)]},
630 631 632 633 634
    ]
    opr_test(
        cases,
        F.linspace,
        ref_fn=lambda start, end, step: np.linspace(1, 9, 9, dtype=np.float32),
635
        network=network,
636 637 638
    )


639 640 641 642 643 644 645
@pytest.mark.parametrize("is_varnode", [True, False])
def test_arange(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

646 647 648 649 650 651 652 653
    cases = [
        {"input": [1, 9, 1]},
        {"input": [2, 10, 2]},
    ]
    opr_test(
        cases,
        F.arange,
        ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
654
        network=network,
655 656 657 658 659 660 661 662 663 664
    )

    cases = [
        {"input": [9, 1, -1]},
        {"input": [10, 2, -2]},
    ]
    opr_test(
        cases,
        F.arange,
        ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
665
        network=network,
666 667 668 669 670 671 672 673 674 675
    )

    cases = [
        {"input": [9.3, 1.2, -0.5]},
        {"input": [10.3, 2.1, -1.7]},
    ]
    opr_test(
        cases,
        F.arange,
        ref_fn=lambda start, end, step: np.arange(start, end, step, dtype=np.float32),
676
        network=network,
677 678 679
    )


680 681 682 683 684 685 686
@pytest.mark.parametrize("is_varnode", [True, False])
def test_round(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

687 688 689 690 691 692
    data1_shape = (15,)
    data2_shape = (25,)
    data1 = np.random.random(data1_shape).astype(np.float32)
    data2 = np.random.random(data2_shape).astype(np.float32)

    cases = [{"input": data1}, {"input": data2}]
693
    opr_test(cases, F.round, ref_fn=np.round, network=network)
694 695


696 697 698 699 700 701 702
@pytest.mark.parametrize("is_varnode", [True, False])
def test_flatten(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    inp_shape = (2, 2, 3, 3)
    x = Tensor(np.arange(36, dtype=np.int32).reshape(inp_shape),)
    y = F.flatten(x, -2, -1)
    np.testing.assert_equal(
        y.numpy(),
        np.array(
            [
                [[0, 1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16, 17]],
                [
                    [18, 19, 20, 21, 22, 23, 24, 25, 26],
                    [27, 28, 29, 30, 31, 32, 33, 34, 35],
                ],
            ]
        ).astype(np.int32),
    )

719 720 721 722 723 724
    data0_shape = (2, 3, 4, 5)
    data1_shape = (4, 5, 6, 7)
    data0 = np.random.random(data0_shape).astype(np.float32)
    data1 = np.random.random(data1_shape).astype(np.float32)

    cases = [
725 726
        {"input": data0, "output": data0.flatten()},
        {"input": data1, "output": data1.flatten()},
727
    ]
728
    opr_test(cases, F.flatten, network=network)
729 730

    cases = [
731 732
        {"input": data0, "output": data0.reshape(2, -1)},
        {"input": data1, "output": data1.reshape(4, -1)},
733
    ]
734
    opr_test(cases, F.flatten, start_axis=1, network=network)
735 736

    cases = [
737 738
        {"input": data0, "output": data0.reshape(2, 3, -1)},
        {"input": data1, "output": data1.reshape(4, 5, -1)},
739
    ]
740
    opr_test(cases, F.flatten, start_axis=2, network=network)
741 742

    cases = [
743 744
        {"input": data0, "output": data0.reshape(2, -1, 5)},
        {"input": data1, "output": data1.reshape(4, -1, 7)},
745
    ]
746
    opr_test(
747
        cases, F.flatten, start_axis=1, end_axis=2, network=network,
748 749
    )

750

751 752 753 754 755 756
@pytest.mark.parametrize("is_varnode", [True, False])
def test_broadcast(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None
757

758 759 760 761
    input1_shape = (20, 30)
    output1_shape = (30, 20, 30)
    data1 = np.random.random(input1_shape).astype(np.float32)

762
    input2_shape = (10, 1)
763 764 765
    output2_shape = (20, 10, 20)
    data2 = np.random.random(input2_shape).astype(np.float32)

766 767 768 769
    input3_shape = (10, 10)
    output3_shape = (10, 10)
    data3 = np.random.random(input3_shape).astype(np.float32)

770
    cases = [
771 772 773 774 775 776 777 778 779 780 781 782
        {
            "input": [data1, output1_shape],
            "output": np.broadcast_to(data1, output1_shape),
        },
        {
            "input": [data2, output2_shape],
            "output": np.broadcast_to(data2, output2_shape),
        },
        {
            "input": [data3, output3_shape],
            "output": np.broadcast_to(data3, output3_shape),
        },
783
    ]
784 785

    opr_test(cases, F.broadcast_to, network=network)
786

787
    x = F.ones((2, 1, 3))
788
    with pytest.raises(RuntimeError):
789
        F.broadcast_to(x, (2, 3, 4))
790

791
    with pytest.raises(RuntimeError):
792
        F.broadcast_to(x, (4, 1, 3))
793

794
    with pytest.raises(RuntimeError):
795
        F.broadcast_to(x, (1, 3))
796

797

798 799 800 801
@pytest.mark.parametrize("is_trace", [True, False])
def test_broadcast_on_empty_tensor(is_trace):
    input1_shape = (100, 0, 1)
    output1_shape = (100, 0, 10)
802
    data1 = Tensor(np.random.random(input1_shape).astype(np.float32))
803 804 805

    input2_shape = (10, 0)
    output2_shape = (10, 10, 0)
806
    data2 = Tensor(np.random.random(input2_shape).astype(np.float32))
807 808 809

    input3_shape = (0, 0, 1, 10)
    output3_shape = (10, 0, 0, 10, 10)
810
    data3 = Tensor(np.random.random(input3_shape).astype(np.float32))
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839

    def comp(out, target_shp):
        assert out._tuple_shape == target_shp

    def func(x, shp):
        return F.broadcast_to(x, shp)

    cases = [
        [data1, output1_shape],
        [data2, output2_shape],
        [data3, output3_shape],
    ]

    def test(func, inp, comp, target_shp):
        out = func(inp, target_shp)
        comp(out, target_shp)

    if is_trace:
        for symbolic in [False, True]:
            for inp, target_shp in cases:
                func_traced = trace(symbolic=symbolic)(func)
                test(func_traced, inp, comp, target_shp)
                test(func_traced, inp, comp, target_shp)
                test(func_traced, inp, comp, target_shp)
    else:
        for inp, target_shp in cases:
            test(func, inp, comp, target_shp)


840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
@pytest.mark.parametrize(
    "input_shape, target_shapes",
    [
        ((3,), [(2, 1, 3), (1, 2, 3), (2, 2, 3)]),
        ((1, 3, 1), [(2, None, 3), (3, None, 3), (1, None, 1)]),
    ],
)
@pytest.mark.parametrize("is_symbolic", [True, False])
def test_broadcast_on_trace(is_symbolic, input_shape, target_shapes):
    x = F.ones(input_shape)

    @trace(symbolic=is_symbolic)
    def broadcast(inp, shape):
        return F.broadcast_to(inp, shape)

    for target_shape in target_shapes:
        if None in target_shape:
            symbolic_target_shape = tuple(
                map(lambda x: None if x is None else Tensor(x), target_shape)
            )
            output = broadcast(x, symbolic_target_shape)
            for i in range(len(target_shape)):
                if target_shape[i] is not None:
                    assert output._tuple_shape[i] == target_shape[i]
                else:
                    assert (
                        output._tuple_shape[i] == x._tuple_shape[i - len(target_shape)]
                    )
        else:
            symbolic_target_shape = Tensor(target_shape)
            output = broadcast(x, symbolic_target_shape)
            assert output._tuple_shape == target_shape


874 875 876 877 878 879 880 881
@pytest.mark.parametrize("is_varnode", [True, False])
def test_utils_astensor1d(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    reference = make_tensor(0, network)
882 883 884 885 886

    # literal
    x = [1, 2, 3]
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
887
        assert isinstance(xx, type(reference))
888 889 890 891 892 893
        np.testing.assert_equal(xx.numpy(), x)

    # numpy array
    x = np.asarray([1, 2, 3], dtype="int32")
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
894
        assert isinstance(xx, type(reference))
895 896 897
        np.testing.assert_equal(xx.numpy(), x.astype(dtype) if dtype else x)

    # tensor
898
    x = make_tensor([1, 2, 3], network)
899 900
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
901
        assert isinstance(xx, type(reference))
902 903 904
        np.testing.assert_equal(xx.numpy(), x.numpy())

    # mixed
905
    x = [1, make_tensor(2, network), 3]
906 907
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
908
        assert isinstance(xx, type(reference))
909 910
        np.testing.assert_equal(xx.numpy(), [1, 2, 3])

911 912 913 914 915 916 917 918 919 920 921 922
    # varnode
    if is_varnode:
        a = np.array([[1, 2, 3], [4, 5, 6]]).astype("float32")
        b = np.array([[True, False, True], [False, True, True]])
        aa = make_tensor(a, network)
        bb = make_tensor(b, network)
        x, y = F.cond_take(bb, aa)
        for dtype in [None, "float32"]:
            xx = astensor1d(x, reference, dtype=dtype)
            assert isinstance(xx, type(reference))
            np.testing.assert_equal(get_var_value(xx), get_var_value(x))

923 924

def test_device():
925
    x = Tensor([1, 2, 3], dtype="float32")
926 927 928 929 930 931

    y1 = F.eye(x.shape, dtype="float32")
    y2 = F.eye(x.shape, dtype="float32", device=None)
    np.testing.assert_almost_equal(y1.numpy(), y2.numpy())

    y3 = F.eye(x.shape, dtype="float32", device="xpux")
932
    y4 = F.eye(x.shape, dtype="float32", device=x.device)
933 934 935 936 937
    np.testing.assert_almost_equal(y3.numpy(), y4.numpy())

    y5 = F.full((3, 2), 4, device=x.device)
    y6 = F.full((3, 2), 4, device="xpux")
    np.testing.assert_almost_equal(y5.numpy(), y6.numpy())
938 939


940 941 942 943 944 945 946 947
@pytest.mark.parametrize("is_varnode", [True, False])
def test_identity(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    x = make_tensor(np.random.random((5, 10)).astype(np.float32), network)
M
Megvii Engine Team 已提交
948
    y = F.copy(x)
949 950 951
    np.testing.assert_equal(y.numpy(), x)


952
def copy_test(dst, src, network):
953
    data = np.random.random((2, 3)).astype(np.float32)
954
    x = make_tensor(data, device=src, network=network)
955 956
    y = F.copy(x, dst)
    assert np.allclose(data, y.numpy())
957 958 959
    if network is None:
        z = x.to(dst)
        assert np.allclose(data, z.numpy())
960 961


962
@pytest.mark.require_ngpu(1)
963 964 965 966 967 968 969 970
@pytest.mark.parametrize("is_varnode", [True, False])
def test_copy_h2d(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    copy_test("cpu0", "gpu0", network=network)
971 972


973
@pytest.mark.require_ngpu(1)
974 975 976 977 978 979 980 981
@pytest.mark.parametrize("is_varnode", [True, False])
def test_copy_d2h(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    copy_test("gpu0", "cpu0", network=network)
982 983


984
@pytest.mark.require_ngpu(2)
985 986 987 988 989 990 991 992 993
@pytest.mark.parametrize("is_varnode", [True, False])
def test_copy_d2d(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

    copy_test("gpu0", "gpu1", network=network)
    copy_test("gpu0:0", "gpu0:1", network=network)
994 995


996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
@pytest.mark.require_ngpu(2)
@pytest.mark.parametrize(
    "shape, device_src, device_dst",
    [
        ((0,), "cpu0", "cpu0"),
        ((10, 0), "cpu0", "cpu1"),
        ((2, 0, 3), "cpu0", "gpu0"),
        ((1, 0, 1, 0), "gpu0", "cpu0"),
        ((2, 3, 4, 5, 0), "gpu0", "gpu1"),
    ],
)
@pytest.mark.parametrize("is_symbolic", [None, True, False])
def test_copy_empty(shape, device_src, device_dst, is_symbolic):
1009
    inp = Tensor(np.random.randn(*shape).astype("float32"), device=device_src)
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

    def func(inp):
        return F.copy(inp, device_dst)

    if is_symbolic is not None:
        func = trace(symbolic=is_symbolic)(func)

    for _ in range(3):
        out = func(inp)
        assert out.numpy().shape == shape
        assert out.device == device_dst
        if is_symbolic is None:
            break


1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
@pytest.mark.parametrize(
    "shape, repeats, axis",
    [
        ((2,), 2, 0),
        ((2, 3, 4, 5), 3, 0),
        ((2, 3, 4, 5), 4, 3),
        ((2,), 2, None),
        ((2, 3, 4, 5), 3, None),
        ((), 1, None),
        ((), 10, None),
    ],
)
1037 1038 1039 1040 1041 1042 1043
@pytest.mark.parametrize("is_varnode", [True, False])
def test_repeat(shape, repeats, axis, is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    def repeat_func(inp):
        return F.repeat(inp=inp, repeats=repeats, axis=axis)

    if shape != ():
        cases = [
            {"input": np.random.randn(*shape).astype("float32")},
        ]
    else:
        cases = [{"input": np.array(1.23)}]

    opr_test(
1055 1056 1057 1058
        cases,
        repeat_func,
        ref_fn=lambda inp: np.repeat(inp, repeats, axis),
        network=network,
1059 1060 1061 1062 1063 1064 1065 1066 1067
    )


@pytest.mark.parametrize(
    "shape, reps",
    [
        ((2,), (2,)),
        ((2, 3, 4, 5), (1, 1, 1, 1)),
        ((2, 3, 4, 5), (1, 2, 3, 4)),
1068 1069
        # FIXME: tile does not support ndim 7
        # ((2, 3, 4, 5), (2, 2, 2, 2, 2, 2, 2)),
1070 1071
    ],
)
1072 1073 1074 1075 1076 1077 1078
@pytest.mark.parametrize("is_varnode", [True])
def test_tile(shape, reps, is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

1079 1080 1081
    def tile_func(inp):
        return F.tile(inp=inp, reps=reps)

1082
    cases = [{"input": np.random.randn(*shape).astype("float32")}]
1083

1084
    opr_test(cases, tile_func, ref_fn=lambda inp: np.tile(inp, reps), network=network)
1085 1086 1087 1088 1089 1090 1091


@pytest.mark.parametrize(
    "shape, shifts, axis",
    [
        ((2, 3), 0, None),
        ((2, 3), 1, 0),
1092 1093
        ((2, 3), 100, 0),
        ((2, 3), -100, 0),
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        ((2, 3, 4, 5), (-1, 1), (0, 1)),
        ((2, 3, 4, 5), (-2, 1, 2), (1, 2, 3)),
    ],
)
@pytest.mark.parametrize("is_varnode", [True, False])
def test_roll(shape, shifts, axis, is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

1105 1106 1107 1108 1109 1110
    x = Tensor([[1, 2], [3, 4], [5, 6]], np.int32)
    y = F.roll(x, 1, -1)
    np.testing.assert_equal(
        y.numpy(), np.array([[2, 1], [4, 3], [6, 5]]).astype(np.int32)
    )

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    inp = np.random.randn(*shape).astype("float32")

    def func(inp):
        return F.roll(inp, shifts, axis)

    cases = [
        {"input": inp},
    ]

    opr_test(
        cases, func, ref_fn=lambda inp: np.roll(inp, shifts, axis), network=network
    )
1123 1124 1125 1126 1127 1128 1129


@pytest.mark.parametrize(
    "shape, shifts, axis", [((10, 0), 5, 1), ((10, 0), -10, 1),],
)
@pytest.mark.parametrize("is_symbolic", [None, True, False])
def test_roll_empty_tensor(shape, shifts, axis, is_symbolic):
1130
    inp = Tensor(np.random.randn(*shape).astype("float32"))
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

    def func(inp):
        return F.roll(inp, shifts, axis)

    if is_symbolic is not None:
        func = trace(symbolic=is_symbolic)(func)

    out_ref = np.roll(inp.numpy(), shifts, axis)
    for _ in range(3):
        out = F.roll(inp, shifts, axis)
        np.testing.assert_equal(out.numpy(), out_ref)
        if is_symbolic is None:
            break