test_tensor.py 10.0 KB
Newer Older
1 2 3 4 5 6 7 8
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# 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 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_tensor_shape
19
from megengine.core.tensor.utils import astensor1d
20
from megengine.distributed.helper import get_device_count_by_fork
21 22 23 24 25 26


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


def test_concat():
    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]}]
    opr_test(cases, run, ref_fn=lambda x, y: np.concatenate([x, y]))


48 49 50 51 52 53 54 55
def test_concat_device():
    data1 = tensor(np.random.random((3, 2, 2)).astype("float32"), device="cpu0")
    data2 = tensor(np.random.random((2, 2, 2)).astype("float32"), device="cpu1")

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


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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
def test_stack():
    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)

        opr_test(cases, run, ref_fn=lambda x, y: np.stack([x, y], axis=ai))


def test_split():
    data = np.random.random((2, 3, 4, 5)).astype(np.float32)
    mge_out1 = F.split(tensor(data), 2, axis=3)
    mge_out2 = F.split(tensor(data), [3, 5], axis=3)

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

    np.testing.assert_equal(mge_out1[0].numpy(), mge_out2[0].numpy())
    np.testing.assert_equal(mge_out1[0].numpy(), np_out[0])


def test_reshape():
    x = np.arange(6, dtype="float32")
    xx = tensor(x)
    y = x.reshape(1, 2, 3)

    for shape in [
        (1, 2, 3),
        (1, -1, 3),
        (1, tensor(-1), 3),
        np.array([1, -1, 3], dtype="int32"),
        tensor([1, -1, 3]),
    ]:
        yy = F.reshape(xx, shape)
        np.testing.assert_equal(yy.numpy(), y)


def test_squeeze():
    x = np.arange(6, dtype="float32").reshape(1, 2, 3, 1)
    xx = tensor(x)

    for axis in [None, 3, -4, (3, -4)]:
        y = np.squeeze(x, axis)
103
        yy = F.squeeze(xx, axis)
104 105 106 107 108 109 110 111 112
        np.testing.assert_equal(y, yy.numpy())


def test_expand_dims():
    x = np.arange(6, dtype="float32").reshape(2, 3)
    xx = tensor(x)

    for axis in [2, -3, (3, -4), (1, -4)]:
        y = np.expand_dims(x, axis)
113
        yy = F.expand_dims(xx, axis)
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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        np.testing.assert_equal(y, yy.numpy())


def test_elemwise_dtype_promotion():
    x = np.random.rand(2, 3).astype("float32")
    y = np.random.rand(1, 3).astype("float16")
    xx = tensor(x)
    yy = tensor(y)
    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)


def test_linspace():
    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),
    )

    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),
    )


def test_arange():
    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),
    )

    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),
    )

    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),
    )


def test_round():
    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}]
    opr_test(cases, F.round, ref_fn=np.round)


196 197 198 199 200 201 202
def test_flatten():
    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):
203
        assert x.shape[0] == y
204 205 206 207

    output0 = (2 * 3 * 4 * 5,)
    output1 = (4 * 5 * 6 * 7,)
    cases = [
208 209
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
210 211 212 213 214 215
    ]
    opr_test(cases, F.flatten, compare_fn=compare_fn)

    output0 = (2, 3 * 4 * 5)
    output1 = (4, 5 * 6 * 7)
    cases = [
216 217
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
218 219 220 221 222 223
    ]
    opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1)

    output0 = (2, 3, 4 * 5)
    output1 = (4, 5, 6 * 7)
    cases = [
224 225
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
226 227 228 229 230 231
    ]
    opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=2)

    output0 = (2, 3 * 4, 5)
    output1 = (4, 5 * 6, 7)
    cases = [
232 233
        {"input": data0, "output": output0},
        {"input": data1, "output": output1},
234 235 236 237
    ]
    opr_test(cases, F.flatten, compare_fn=compare_fn, start_axis=1, end_axis=2)


238 239 240 241 242
def test_broadcast():
    input1_shape = (20, 30)
    output1_shape = (30, 20, 30)
    data1 = np.random.random(input1_shape).astype(np.float32)

243
    input2_shape = (10, 1)
244 245 246 247
    output2_shape = (20, 10, 20)
    data2 = np.random.random(input2_shape).astype(np.float32)

    def compare_fn(x, y):
248
        assert x.shape[0] == y
249 250 251 252 253

    cases = [
        {"input": [data1, output1_shape], "output": output1_shape},
        {"input": [data2, output2_shape], "output": output2_shape},
    ]
254
    opr_test(cases, F.broadcast_to, compare_fn=compare_fn)
255

256 257
    x = F.ones((2, 1, 3))
    with pytest.raises(ValueError):
258
        F.broadcast_to(x, (2, 3, 4))
259 260

    with pytest.raises(ValueError):
261
        F.broadcast_to(x, (4, 1, 3))
262 263

    with pytest.raises(ValueError):
264
        F.broadcast_to(x, (1, 3))
265

266 267 268 269 270 271 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 299 300 301 302 303 304 305 306 307 308 309 310 311 312

def test_utils_astensor1d():
    reference = tensor(0)

    # literal
    x = [1, 2, 3]
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
        assert type(xx) is tensor
        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)
        assert type(xx) is tensor
        np.testing.assert_equal(xx.numpy(), x.astype(dtype) if dtype else x)

    # tensor
    x = tensor([1, 2, 3], dtype="int32")
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
        assert type(xx) is tensor
        np.testing.assert_equal(xx.numpy(), x.numpy())

    # mixed
    x = [1, tensor(2), 3]
    for dtype in [None, "float32"]:
        xx = astensor1d(x, reference, dtype=dtype)
        assert type(xx) is tensor
        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")
    y4 = F.eye(x.shape, dtype="float32", device=x.device.to_c())
    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())
313 314


315 316 317 318 319 320
def test_identity():
    x = tensor(np.random.random((5, 10)).astype(np.float32))
    y = F.identity(x)
    np.testing.assert_equal(y.numpy(), x)


321 322 323 324 325
def copy_test(dst, src):
    data = np.random.random((2, 3)).astype(np.float32)
    x = tensor(data, device=src)
    y = F.copy(x, dst)
    assert np.allclose(data, y.numpy())
326 327
    z = x.to(dst)
    assert np.allclose(data, z.numpy())
328 329


330 331 332 333 334 335 336
@pytest.mark.skipif(
    platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
)
@pytest.mark.skipif(
    platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
)
@pytest.mark.skipif(get_device_count_by_fork("gpu") == 0, reason="CUDA is disabled")
337 338 339 340
def test_copy_h2d():
    copy_test("cpu0", "gpu0")


341 342 343 344 345 346 347
@pytest.mark.skipif(
    platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
)
@pytest.mark.skipif(
    platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
)
@pytest.mark.skipif(get_device_count_by_fork("gpu") == 0, reason="CUDA is disabled")
348 349 350 351
def test_copy_d2h():
    copy_test("gpu0", "cpu0")


352 353 354 355 356 357 358
@pytest.mark.skipif(
    platform.system() == "Darwin", reason="do not imp GPU mode at macos now"
)
@pytest.mark.skipif(
    platform.system() == "Windows", reason="do not imp GPU mode at Windows now"
)
@pytest.mark.skipif(get_device_count_by_fork("gpu") < 2, reason="need more gpu device")
359 360 361
def test_copy_d2d():
    copy_test("gpu0", "gpu1")
    copy_test("gpu0:0", "gpu0:1")