test_tensor.py 12.5 KB
Newer Older
Z
zhunaipan 已提交
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
# 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.
# ============================================================================
"""
@File  : test_tensor.py
@Author:
@Date  : 2019-03-14
@Desc  : test mindspore tensor's operation
"""
import numpy as np
import pytest

import mindspore as ms
import mindspore.common.api as me
import mindspore.nn as nn
K
kingfo 已提交
27
from mindspore import Tensor
W
Wei Luning 已提交
28
from mindspore.common.initializer import initializer
J
jinyaohui 已提交
29
from mindspore.common.parameter import Parameter
Z
zhunaipan 已提交
30 31 32 33
from ..ut_filter import non_graph_engine

ndarr = np.ones((2, 3))

J
jinyaohui 已提交
34

Z
zhunaipan 已提交
35 36
def test_tensor_flatten():
    with pytest.raises(AttributeError):
“liuxiao” 已提交
37
        lst = [1, 2, 3, 4,]
Z
zhunaipan 已提交
38 39 40 41
        tensor_list = ms.Tensor(lst, ms.float32)
        tensor_list = tensor_list.Flatten()
        print(tensor_list)

J
jinyaohui 已提交
42

Z
zhunaipan 已提交
43 44 45 46 47
def test_tensor_list():
    lst = [[1.0, 2.0, 1.0], [1.0, 10.0, 9.0]]
    tensor_list = ms.Tensor(lst, ms.float32)
    print(tensor_list)

J
jinyaohui 已提交
48

Z
zhunaipan 已提交
49 50 51 52
def test_tensor():
    """test_tensor"""
    t1 = ms.Tensor(ndarr)
    assert isinstance(t1, ms.Tensor)
53
    assert t1.dtype == ms.float64
Z
zhunaipan 已提交
54 55 56

    t2 = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)
    assert isinstance(t2, ms.Tensor)
57 58
    assert t2.shape == (1, 2, 3)
    assert t2.dtype == ms.float32
Z
zhunaipan 已提交
59 60 61

    t3 = ms.Tensor(0.1)
    assert isinstance(t3, ms.Tensor)
62
    assert t3.dtype == ms.float64
Z
zhunaipan 已提交
63 64 65

    t4 = ms.Tensor(1)
    assert isinstance(t4, ms.Tensor)
66
    assert t4.dtype == ms.int64
Z
zhunaipan 已提交
67

J
jinyaohui 已提交
68

Z
zhunaipan 已提交
69 70 71
def test_tensor_type_float16():
    t_float16 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float16))
    assert isinstance(t_float16, ms.Tensor)
72 73
    assert t_float16.shape == (2, 3)
    assert t_float16.dtype == ms.float16
Z
zhunaipan 已提交
74 75 76 77 78


def test_tensor_type_float32():
    t_float32 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
    assert isinstance(t_float32, ms.Tensor)
79 80
    assert t_float32.shape == (2, 3)
    assert t_float32.dtype == ms.float32
Z
zhunaipan 已提交
81 82 83 84 85


def test_tensor_type_float32_user_define():
    t = ms.Tensor(np.zeros([1, 2, 3]), ms.float32)
    assert isinstance(t, ms.Tensor)
86 87
    assert t.shape == (1, 2, 3)
    assert t.dtype == ms.float32
Z
zhunaipan 已提交
88 89 90 91 92


def test_tensor_type_float64():
    t = ms.Tensor([[1.0, 2, 3], [4, 5, 6]])
    assert isinstance(t, ms.Tensor)
93 94
    assert t.shape == (2, 3)
    assert t.dtype == ms.float64
Z
zhunaipan 已提交
95 96 97

    t_zero = ms.Tensor(np.zeros([1, 2, 3]))
    assert isinstance(t_zero, ms.Tensor)
98 99
    assert t_zero.shape == (1, 2, 3)
    assert t_zero.dtype == ms.float64
Z
zhunaipan 已提交
100 101 102 103 104


def test_tensor_type_float64_user_define():
    t = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=float))
    assert isinstance(t, ms.Tensor)
105 106
    assert t.shape == (2, 3)
    assert t.dtype == ms.float64
Z
zhunaipan 已提交
107 108 109

    t_float64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]]), ms.float64)
    assert isinstance(t_float64, ms.Tensor)
110 111
    assert t_float64.shape == (2, 3)
    assert t_float64.dtype == ms.float64
Z
zhunaipan 已提交
112

J
jinyaohui 已提交
113

Z
zhunaipan 已提交
114 115 116 117
def test_tensor_type_bool():
    # init a tensor with bool type
    ts_bool_array = ms.Tensor(np.zeros([2, 3], np.bool), ms.bool_)
    assert isinstance(ts_bool_array, ms.Tensor)
118
    assert ts_bool_array.dtype == ms.bool_
Z
zhunaipan 已提交
119 120 121

    t_bool = ms.Tensor(True)
    assert isinstance(t_bool, ms.Tensor)
122
    assert t_bool.dtype == ms.bool_
Z
zhunaipan 已提交
123 124 125

    t_bool_array = ms.Tensor(np.array([[True, False, True], [False, False, False]]))
    assert isinstance(t_bool_array, ms.Tensor)
126 127
    assert t_bool_array.shape == (2, 3)
    assert t_bool_array.dtype == ms.bool_
Z
zhunaipan 已提交
128

J
jinyaohui 已提交
129

Z
zhunaipan 已提交
130 131 132
def test_tensor_type_int8():
    t_int8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int8))
    assert isinstance(t_int8_array, ms.Tensor)
133 134
    assert t_int8_array.shape == (2, 3)
    assert t_int8_array.dtype == ms.int8
Z
zhunaipan 已提交
135 136 137 138 139


def test_tensor_type_int16():
    t_int16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16))
    assert isinstance(t_int16_array, ms.Tensor)
140 141
    assert t_int16_array.shape == (2, 3)
    assert t_int16_array.dtype == ms.int16
Z
zhunaipan 已提交
142 143 144 145 146


def test_tensor_type_int32():
    t_int = ms.Tensor([[1, 2, 3], [4, 5, 6]])
    assert isinstance(t_int, ms.Tensor)
147 148
    assert t_int.shape == (2, 3)
    assert t_int.dtype == ms.int64
Z
zhunaipan 已提交
149 150 151

    t_int_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32))
    assert isinstance(t_int_array, ms.Tensor)
152 153
    assert t_int_array.shape == (2, 3)
    assert t_int_array.dtype == ms.int32
Z
zhunaipan 已提交
154 155 156 157 158


def test_tensor_type_int64():
    t_int64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64))
    assert isinstance(t_int64, ms.Tensor)
159 160
    assert t_int64.shape == (2, 3)
    assert t_int64.dtype == ms.int64
Z
zhunaipan 已提交
161

J
jinyaohui 已提交
162

Z
zhunaipan 已提交
163 164 165
def test_tensor_type_uint8():
    t_uint8_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8))
    assert isinstance(t_uint8_array, ms.Tensor)
166 167
    assert t_uint8_array.shape == (2, 3)
    assert t_uint8_array.dtype == ms.uint8
Z
zhunaipan 已提交
168 169 170 171 172


def test_tensor_type_uint16():
    t_uint16_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint16))
    assert isinstance(t_uint16_array, ms.Tensor)
173 174
    assert t_uint16_array.shape == (2, 3)
    assert t_uint16_array.dtype == ms.uint16
Z
zhunaipan 已提交
175 176 177 178 179


def test_tensor_type_uint32():
    t_uint32_array = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint32))
    assert isinstance(t_uint32_array, ms.Tensor)
180 181
    assert t_uint32_array.shape == (2, 3)
    assert t_uint32_array.dtype == ms.uint32
Z
zhunaipan 已提交
182 183 184 185 186


def test_tensor_type_uint64():
    t_uint64 = ms.Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint64))
    assert isinstance(t_uint64, ms.Tensor)
187 188
    assert t_uint64.shape == (2, 3)
    assert t_uint64.dtype == ms.uint64
Z
zhunaipan 已提交
189

J
jinyaohui 已提交
190

Z
zhunaipan 已提交
191 192 193
def test_set_type():
    t = ms.Tensor(ndarr)
    t.set_dtype(ms.float32)
194
    assert t.dtype == ms.float32
Z
zhunaipan 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211


@non_graph_engine
def test_add():
    x = ms.Tensor(ndarr)
    y = ms.Tensor(ndarr)
    z = x + y
    assert isinstance(z, ms.Tensor)


@non_graph_engine
def test_sub():
    x = ms.Tensor(ndarr)
    y = ms.Tensor(ndarr)
    z = x - y
    assert isinstance(z, ms.Tensor)

J
jinyaohui 已提交
212

W
Wei Luning 已提交
213 214
@non_graph_engine
def test_div():
J
jinyaohui 已提交
215 216
    x = ms.Tensor(np.array([[2, 6, 10], [12, 4, 8]]).astype(np.float32))
    y = ms.Tensor(np.array([[2, 2, 5], [6, 1, 2]]).astype(np.float32))
W
Wei Luning 已提交
217 218 219 220 221
    z = x / y
    z2 = x / 2
    assert isinstance(z, ms.Tensor)
    assert isinstance(z2, ms.Tensor)

J
jinyaohui 已提交
222

W
Wei Luning 已提交
223 224 225
@non_graph_engine
def test_parameter():
    x = Parameter(initializer(1, [1], ms.float32), name="beta1_power")
226
    x.init_data()
W
Wei Luning 已提交
227 228 229
    z = x / 2
    print(z)

Z
zhunaipan 已提交
230 231 232

class Net(nn.Cell):
    """Net definition"""
J
jinyaohui 已提交
233

Z
zhunaipan 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    def __init__(self, dim):
        super(Net, self).__init__()
        self.dim = dim

    def construct(self, input_x):
        return input_x


@non_graph_engine
def test_return_tensor():
    """test_return_tensor"""
    net = Net(0)
    input_data = ms.Tensor(np.array([[1.2, 2.1], [2.2, 3.2]]).astype('float32'))
    input_data.set_dtype(ms.float32)
    exe = me._executor
    exe.compile(net, input_data)
    tensor_ = exe(net, input_data)

    # get shape
253
    shape_ = tensor_.shape
Z
zhunaipan 已提交
254 255 256
    print("shape = ", shape_)

    # get type
257
    type_ = tensor_.dtype
Z
zhunaipan 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    print("type = ", type_)

    # get value
    value_ = tensor_.asnumpy()
    print("numpy value = ", value_)


def test_tensor_contiguous():
    """test_tensor_contiguous"""
    input_c = np.arange(6).reshape(2, 3)
    input_f = input_c.T
    np.ascontiguousarray(input_c, dtype=np.float32)
    assert True, input_c.flags['C_CONTIGUOUS']

    print("input_f flags = ", input_f.flags)
    assert True, input_f.flags['F_CONTIGUOUS']

    tensor_f_float32 = ms.Tensor(input_f)
    rt_f = tensor_f_float32.asnumpy()
    assert True, rt_f.flags['C_CONTIGUOUS']
    print("rt_f flags = ", rt_f.flags)

J
jinyaohui 已提交
280

Z
zhunaipan 已提交
281 282 283 284 285 286 287 288
def test_tensor_contiguous2():
    input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)
    input_me = input_data.transpose(0, 3, 1, 2)
    print("input_me flags = ", input_me.flags)
    tensor_f_float32 = ms.Tensor(input_me)
    out_f = tensor_f_float32.asnumpy()
    print("out_f flags = ", out_f.flags)

J
jinyaohui 已提交
289

Z
zhunaipan 已提交
290 291 292 293 294
def test_tensor_input_string():
    with pytest.raises(TypeError):
        input_data = 'ccc'
        ms.Tensor(input_data)

J
jinyaohui 已提交
295

Z
zhunaipan 已提交
296 297 298 299 300
def test_tensor_input_tuple_string():
    with pytest.raises(TypeError):
        input_data = (2, 3, '4', 5)
        ms.Tensor(input_data)

J
jinyaohui 已提交
301

Z
zhunaipan 已提交
302 303 304 305 306
def test_tensor_input_list_string():
    with pytest.raises(TypeError):
        input_data = [[2, 3, '4', 5], [1, 2, 3, 4]]
        ms.Tensor(input_data)

J
jinyaohui 已提交
307

Z
zhunaipan 已提交
308 309 310 311 312
def test_tensor_input_none():
    with pytest.raises(TypeError):
        input_data = None
        ms.Tensor(input_data, np.int64)

J
jinyaohui 已提交
313

Z
zhunaipan 已提交
314 315 316 317 318
# pylint: disable=no-value-for-parameter
def test_tensor_input_empty():
    with pytest.raises(TypeError):
        ms.Tensor()

J
jinyaohui 已提交
319

Z
zhunaipan 已提交
320 321 322 323 324
def test_tensor_input_ndarray_str():
    with pytest.raises(TypeError):
        inp = np.array(["88", 2, 4])
        ms.Tensor(inp)

J
jinyaohui 已提交
325

Z
zhunaipan 已提交
326 327 328 329 330 331 332
def test_tensor_input_ndarray_bool():
    inp = np.array([True, 2, 4])
    ms.Tensor(inp)

    inp = np.array([False, 2, 4])
    ms.Tensor(inp)

J
jinyaohui 已提交
333

Z
zhunaipan 已提交
334 335 336 337 338
def test_tensor_input_ndarray_complex():
    with pytest.raises(TypeError):
        inp = np.array([20j, 2, 4])
        ms.Tensor(inp)

J
jinyaohui 已提交
339

Z
zhunaipan 已提交
340 341 342 343 344
def test_tensor_input_ndarray_none():
    with pytest.raises(TypeError):
        inp = np.array([None, 2, 4])
        ms.Tensor(inp)

J
jinyaohui 已提交
345

Z
zhunaipan 已提交
346 347 348 349 350
def test_tensor_input_ndarray_dict():
    with pytest.raises(TypeError):
        inp = {'a': 6, 'b': 7}
        ms.Tensor(inp)

J
jinyaohui 已提交
351

Z
zhunaipan 已提交
352 353 354 355 356
def test_tensor_input_np_nan():
    with pytest.raises(TypeError):
        input_data = (1, 2, 3, np.nan)
        ms.Tensor(input_data, np.int64)

J
jinyaohui 已提交
357

Z
zhunaipan 已提交
358 359 360 361 362
def test_tensor_input_tuple_inf():
    with pytest.raises(TypeError):
        input_data = (1, 2, 3, float("inf"))
        ms.Tensor(input_data, np.int64)

J
jinyaohui 已提交
363

Z
zhunaipan 已提交
364 365 366 367 368
def test_tensor_input_dict():
    with pytest.raises(TypeError):
        input_data = {'a': 6, 'b': 7}
        ms.Tensor(input_data, np.int64)

J
jinyaohui 已提交
369

Z
zhunaipan 已提交
370 371 372 373 374
def test_tensor_input_complex():
    with pytest.raises(TypeError):
        input_data = (1, 2j, 3)
        ms.Tensor(input_data, np.int64)

J
jinyaohui 已提交
375

Z
zhunaipan 已提交
376 377 378 379 380
def test_tensor_dtype_np_float():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.float)
        ms.Tensor(input_data, np.float)

J
jinyaohui 已提交
381

Z
zhunaipan 已提交
382 383 384 385 386
def test_tensor_dtype_np_float16():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.float16)
        ms.Tensor(input_data, np.float16)

J
jinyaohui 已提交
387

Z
zhunaipan 已提交
388 389 390 391 392
def test_tensor_dtype_np_float32():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.float32)
        ms.Tensor(input_data, np.float32)

J
jinyaohui 已提交
393

Z
zhunaipan 已提交
394 395 396 397 398
def test_tensor_dtype_np_float64():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.float64)
        ms.Tensor(input_data, np.float64)

J
jinyaohui 已提交
399

Z
zhunaipan 已提交
400 401 402 403 404
def test_tensor_dtype_np_int():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.int)
        ms.Tensor(input_data, np.int)

J
jinyaohui 已提交
405

Z
zhunaipan 已提交
406 407 408 409 410
def test_tensor_dtype_np_int8():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.int8)
        ms.Tensor(input_data, np.int8)

J
jinyaohui 已提交
411

Z
zhunaipan 已提交
412 413 414 415 416
def test_tensor_dtype_np_int16():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.int16)
        ms.Tensor(input_data, np.int16)

J
jinyaohui 已提交
417

Z
zhunaipan 已提交
418 419 420 421 422
def test_tensor_dtype_np_int32():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.int32)
        ms.Tensor(input_data, np.int32)

J
jinyaohui 已提交
423

Z
zhunaipan 已提交
424 425 426 427 428
def test_tensor_dtype_np_int64():
    with pytest.raises(TypeError):
        input_data = np.random.randn(32, 112, 112, 3).astype(np.int64)
        ms.Tensor(input_data, np.int64)

J
jinyaohui 已提交
429

Z
zhunaipan 已提交
430 431
def test_tensor_dtype_fp32_to_bool():
    with pytest.raises(RuntimeError):
J
jinyaohui 已提交
432 433 434
        input_ = np.random.randn(2, 3, 4, 5).astype(np.float32)
        input_ = ms.Tensor(input_)
        _ = ms.Tensor(input_, dtype=ms.bool_)
W
Wei Luning 已提交
435

K
kingfo 已提交
436 437

def test_tensor_operation():
J
jinyaohui 已提交
438
    x = Tensor(np.ones((3, 3)) * 4)
K
kingfo 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    res = x + 1
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 5)
    res = 1 + x
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 5)
    res = x - 2
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
    res = 6 - x
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
    res = x * 3
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 12)
    res = 3 * x
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 12)
    res = x / 2
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
    res = 8 / x
    assert np.all(res.asnumpy() == np.ones((3, 3)) * 2)
K
kingfo 已提交
455
    with pytest.raises(ValueError):
K
kingfo 已提交
456
        res = x * (2, 3)