test_tensor.py 18.5 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
4
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
5 6 7 8
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9
import os
10 11
import platform

12 13
import numpy as np
import pytest
14
from utils import make_tensor, opr_test
15 16

import megengine.functional as F
M
Megvii Engine Team 已提交
17
from megengine import tensor
18
from megengine.core._trace_option import use_symbolic_shape
19
from megengine.core.tensor import megbrain_graph as G
20
from megengine.core.tensor.utils import astensor1d
21
from megengine.distributed.helper import get_device_count_by_fork
22
from megengine.utils.network import Network, set_symbolic_shape
23
from megengine.utils.network_node import VarNode
24 25 26 27


def test_eye():
    dtype = np.float32
28
    cases = [{"input": [10, 20]}, {"input": [30]}]
29
    for case in cases:
30
        np.testing.assert_allclose(
31 32 33
            F.eye(case["input"], dtype=dtype).numpy(),
            np.eye(*case["input"]).astype(dtype),
        )
34 35 36 37 38 39 40 41
        np.testing.assert_allclose(
            F.eye(*case["input"], dtype=dtype).numpy(),
            np.eye(*case["input"]).astype(dtype),
        )
        np.testing.assert_allclose(
            F.eye(tensor(case["input"]), dtype=dtype).numpy(),
            np.eye(*case["input"]).astype(dtype),
        )
42 43


44 45 46 47 48 49 50
@pytest.mark.parametrize("is_varnode", [True, False])
def test_concat(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

51 52 53 54 55 56 57 58 59 60 61
    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]}]
62
    opr_test(cases, run, ref_fn=lambda x, y: np.concatenate([x, y]), network=network)
63 64


65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
@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)
    np.testing.assert_equal(val.numpy(), x[y])
    np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])


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

    data1 = make_tensor(np.random.random((3, 2, 2)).astype("float32"), network, "cpu0")
    data2 = make_tensor(np.random.random((2, 2, 2)).astype("float32"), network, "cpu1")
90 91 92 93 94

    out = F.concat([data1, data2], device="cpu0")
    assert str(out.device).split(":")[0] == "cpu0"


95 96 97 98 99 100 101
@pytest.mark.parametrize("is_varnode", [True, False])
def test_stack(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

102 103 104 105 106 107 108 109 110 111
    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)

112 113 114 115
        opr_test(
            cases, run, ref_fn=lambda x, y: np.stack([x, y], axis=ai), network=network
        )

116

117 118 119 120
@pytest.mark.parametrize("is_varnode", [True, False])
def test_split(is_varnode):
    if is_varnode:
        network = Network()
121
        saved_symbolic_shape = set_symbolic_shape(False)
122 123
    else:
        network = None
124 125

    data = np.random.random((2, 3, 4, 5)).astype(np.float32)
126
    inp = make_tensor(data, network)
127 128 129

    mge_out0 = F.split(inp, 2, axis=3)
    mge_out1 = F.split(inp, [3], axis=3)
130 131 132

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

133 134 135 136
    assert len(mge_out0) == 2
    assert len(mge_out1) == 2

    np.testing.assert_equal(mge_out0[0].numpy(), np_out[0])
137 138
    np.testing.assert_equal(mge_out1[0].numpy(), np_out[0])

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    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:
        F.split(inp, [3, 3, 5], axis=3)
        assert False
    except ValueError as e:
        assert str(e) == "Invalid nsplits_or_secions: [3, 3, 5]"

154 155 156
    if is_varnode:
        set_symbolic_shape(saved_symbolic_shape)

157

158 159 160 161 162 163 164
@pytest.mark.parametrize("is_varnode", [True, False])
def test_reshape(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

165
    x = np.arange(6, dtype="float32")
166
    xx = make_tensor(x, network)
167 168 169 170 171
    y = x.reshape(1, 2, 3)

    for shape in [
        (1, 2, 3),
        (1, -1, 3),
172
        (1, make_tensor(-1, network), 3),
173
        np.array([1, -1, 3], dtype="int32"),
174
        make_tensor([1, -1, 3], network),
175 176 177 178 179
    ]:
        yy = F.reshape(xx, shape)
        np.testing.assert_equal(yy.numpy(), y)


180 181 182 183
@pytest.mark.parametrize("is_varnode", [True, False])
def test_reshape_shape_inference(is_varnode):
    if is_varnode:
        network = Network()
184
        saved_symbolic_shape = set_symbolic_shape(False)
185 186 187 188 189 190 191 192 193 194
    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
    )
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    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
        if isinstance(source, tensor):
            source = source.numpy()
        np.testing.assert_equal(source, target)

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

    cases = [
        {"input": [x_shape_known, tshp_unknown], "output": [(2, 2),]},
        {"input": [x_shape_unknown, tshp_unknown], "output": [(2, 2),]},
        {"input": [x_shape_known, tshp_known], "output": [(2, 2),]},
        {"input": [x_shape_known, tshp_known_unspec], "output": [(2, 2),]},
        {"input": [x_shape_unknown, tshp_known], "output": [(2, 2),]},
        {"input": [x_shape_unknown, tshp_known_unspec], "output": [(2, 2),]},
    ]
215
    opr_test(cases, func, compare_fn=check_shape, test_trace=True, network=network)
216 217
    if is_varnode:
        set_symbolic_shape(saved_symbolic_shape)
218

219

220 221 222 223
@pytest.mark.parametrize("is_varnode", [True, False])
def test_squeeze(is_varnode):
    if is_varnode:
        network = Network()
224
        saved_symbolic_shape = set_symbolic_shape(False)
225 226
    else:
        network = None
227

228
    x = np.arange(6, dtype="float32").reshape(1, 2, 3, 1)
229
    xx = make_tensor(x, network)
230 231 232

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

236 237 238
    if is_varnode:
        set_symbolic_shape(saved_symbolic_shape)

239

240 241 242 243 244 245 246
@pytest.mark.parametrize("is_varnode", [True, False])
def test_expand_dims(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

247
    x = np.arange(6, dtype="float32").reshape(2, 3)
248
    xx = make_tensor(x, network)
249 250 251

    for axis in [2, -3, (3, -4), (1, -4)]:
        y = np.expand_dims(x, axis)
252
        yy = F.expand_dims(xx, axis)
253 254 255
        np.testing.assert_equal(y, yy.numpy())


256 257 258 259 260 261 262 263 264 265 266 267 268
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)
        np.testing.assert_raises(AssertionError, F.expand_dims, xx, axis)


269 270 271 272 273 274 275
@pytest.mark.parametrize("is_varnode", [True, False])
def test_elemwise_dtype_promotion(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

276 277
    x = np.random.rand(2, 3).astype("float32")
    y = np.random.rand(1, 3).astype("float16")
278 279
    xx = make_tensor(x, network)
    yy = make_tensor(y, network)
280 281 282 283 284 285 286 287 288 289
    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)


290 291 292 293 294 295 296
@pytest.mark.parametrize("is_varnode", [True, False])
def test_linspace(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

297 298 299 300 301 302 303 304
    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),
305
        network=network,
306 307 308 309 310 311 312 313 314 315
    )

    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),
316
        network=network,
317 318 319
    )

    cases = [
320 321
        {"input": [1, make_tensor(9, network), 9]},
        {"input": [make_tensor(1, network), 9, make_tensor(9, network)]},
322 323 324 325 326
    ]
    opr_test(
        cases,
        F.linspace,
        ref_fn=lambda start, end, step: np.linspace(1, 9, 9, dtype=np.float32),
327
        network=network,
328 329 330
    )


331 332 333 334 335 336 337
@pytest.mark.parametrize("is_varnode", [True, False])
def test_arange(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

338 339 340 341 342 343 344 345
    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),
346
        network=network,
347 348 349 350 351 352 353 354 355 356
    )

    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),
357
        network=network,
358 359 360 361 362 363 364 365 366 367
    )

    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),
368
        network=network,
369 370 371
    )


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

379 380 381 382 383 384
    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}]
385
    opr_test(cases, F.round, ref_fn=np.round, network=network)
386 387


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

395 396 397 398 399 400
    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)

    def compare_fn(x, y):
401
        assert x._tuple_shape[0] == y
402 403 404 405

    output0 = (2 * 3 * 4 * 5,)
    output1 = (4 * 5 * 6 * 7,)
    cases = [
406 407
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
408
    ]
409
    opr_test(cases, F.flatten, compare_fn=compare_fn, network=network)
410 411 412 413

    output0 = (2, 3 * 4 * 5)
    output1 = (4, 5 * 6 * 7)
    cases = [
414 415
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
416
    ]
417
    opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1, network=network)
418 419 420 421

    output0 = (2, 3, 4 * 5)
    output1 = (4, 5, 6 * 7)
    cases = [
422 423
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
424
    ]
425
    opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=2, network=network)
426 427 428 429

    output0 = (2, 3 * 4, 5)
    output1 = (4, 5 * 6, 7)
    cases = [
430 431
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
432
    ]
433 434 435 436 437 438 439 440 441
    opr_test(
        cases,
        F.flatten,
        compare_fn=compare_fn,
        start_axis=1,
        end_axis=2,
        network=network,
    )

442

443 444 445 446 447 448
@pytest.mark.parametrize("is_varnode", [True, False])
def test_broadcast(is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None
449

450 451 452 453
    input1_shape = (20, 30)
    output1_shape = (30, 20, 30)
    data1 = np.random.random(input1_shape).astype(np.float32)

454
    input2_shape = (10, 1)
455 456 457
    output2_shape = (20, 10, 20)
    data2 = np.random.random(input2_shape).astype(np.float32)

458 459 460 461
    input3_shape = (10, 10)
    output3_shape = (10, 10)
    data3 = np.random.random(input3_shape).astype(np.float32)

462
    def compare_fn(x, y):
463
        assert x._tuple_shape[0] == y
464 465 466 467

    cases = [
        {"input": [data1, output1_shape], "output": output1_shape},
        {"input": [data2, output2_shape], "output": output2_shape},
468
        {"input": [data3, output3_shape], "output": output3_shape},
469
    ]
470
    opr_test(cases, F.broadcast_to, compare_fn=compare_fn, network=network)
471

472
    x = F.ones((2, 1, 3))
473
    with pytest.raises(RuntimeError):
474
        F.broadcast_to(x, (2, 3, 4))
475

476
    with pytest.raises(RuntimeError):
477
        F.broadcast_to(x, (4, 1, 3))
478

479
    with pytest.raises(RuntimeError):
480
        F.broadcast_to(x, (1, 3))
481

482

483 484 485 486 487 488 489 490
@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)
491 492 493 494 495

    # literal
    x = [1, 2, 3]
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
496
        assert isinstance(xx, type(reference))
497 498 499 500 501 502
        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)
503
        assert isinstance(xx, type(reference))
504 505 506
        np.testing.assert_equal(xx.numpy(), x.astype(dtype) if dtype else x)

    # tensor
507
    x = make_tensor([1, 2, 3], network)
508 509
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
510
        assert isinstance(xx, type(reference))
511 512 513
        np.testing.assert_equal(xx.numpy(), x.numpy())

    # mixed
514
    x = [1, make_tensor(2, network), 3]
515 516
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
517
        assert isinstance(xx, type(reference))
518 519 520 521 522 523 524 525 526 527 528
        np.testing.assert_equal(xx.numpy(), [1, 2, 3])


def test_device():
    x = tensor([1, 2, 3], dtype="float32")

    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")
529
    y4 = F.eye(x.shape, dtype="float32", device=x.device)
530 531 532 533 534
    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())
535 536


537 538 539 540 541 542 543 544
@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 已提交
545
    y = F.copy(x)
546 547 548
    np.testing.assert_equal(y.numpy(), x)


549
def copy_test(dst, src, network):
550
    data = np.random.random((2, 3)).astype(np.float32)
551
    x = make_tensor(data, device=src, network=network)
552 553
    y = F.copy(x, dst)
    assert np.allclose(data, y.numpy())
554 555 556
    if network is None:
        z = x.to(dst)
        assert np.allclose(data, z.numpy())
557 558


559
@pytest.mark.require_ngpu(1)
560 561 562 563 564 565 566 567
@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)
568 569


570
@pytest.mark.require_ngpu(1)
571 572 573 574 575 576 577 578
@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)
579 580


581
@pytest.mark.require_ngpu(2)
582 583 584 585 586 587 588 589 590
@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)
591 592 593 594 595 596 597 598 599 600 601 602 603 604


@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),
    ],
)
605 606 607 608 609 610 611
@pytest.mark.parametrize("is_varnode", [True, False])
def test_repeat(shape, repeats, axis, is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

612 613 614 615 616 617 618 619 620 621 622
    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(
623 624 625 626
        cases,
        repeat_func,
        ref_fn=lambda inp: np.repeat(inp, repeats, axis),
        network=network,
627 628 629 630 631 632 633 634 635 636 637 638
    )


@pytest.mark.parametrize(
    "shape, reps",
    [
        ((2,), (2,)),
        ((2, 3, 4, 5), (1, 1, 1, 1)),
        ((2, 3, 4, 5), (1, 2, 3, 4)),
        ((2, 3, 4, 5), (2, 2, 2, 2, 2, 2, 2)),
    ],
)
639 640 641 642 643 644 645
@pytest.mark.parametrize("is_varnode", [True])
def test_tile(shape, reps, is_varnode):
    if is_varnode:
        network = Network()
    else:
        network = None

646 647 648
    def tile_func(inp):
        return F.tile(inp=inp, reps=reps)

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

651
    opr_test(cases, tile_func, ref_fn=lambda inp: np.tile(inp, reps), network=network)
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681


@pytest.mark.parametrize(
    "shape, shifts, axis",
    [
        ((2, 3), 0, None),
        ((2, 3), 1, 0),
        ((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

    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
    )