1# Copyright 2020 Huawei Technologies Co., Ltd 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15 16import numpy as np 17 18import mindspore.context as context 19import mindspore.nn as nn 20from mindspore import Tensor 21from mindspore.common import dtype as mstype 22from mindspore.ops import operations as P 23 24context.set_context(mode=context.GRAPH_MODE, device_target='CPU') 25 26 27class Net(nn.Cell): 28 def __init__(self): 29 super(Net, self).__init__() 30 self.uniq = P.Unique() 31 32 def construct(self, x): 33 return self.uniq(x) 34 35 36def test_net_fp32(): 37 x = Tensor(np.array([1, 2, 5, 2]), mstype.float32) 38 uniq = Net() 39 output = uniq(x) 40 print("x:\n", x) 41 print("y:\n", output[0]) 42 print("idx:\n", output[1]) 43 expect_y_result = [1., 2., 5.] 44 expect_idx_result = [0, 1, 2, 1] 45 46 assert (output[0].asnumpy() == expect_y_result).all() 47 assert (output[1].asnumpy() == expect_idx_result).all() 48 49def test_net_fp16(): 50 x = Tensor(np.array([1, 5, 2, 2]), mstype.float16) 51 uniq = Net() 52 output = uniq(x) 53 print("x:\n", x) 54 print("y:\n", output[0]) 55 print("idx:\n", output[1]) 56 expect_y_result = [1., 5., 2.] 57 expect_idx_result = [0, 1, 2, 2] 58 59 assert (output[0].asnumpy() == expect_y_result).all() 60 assert (output[1].asnumpy() == expect_idx_result).all() 61 62def test_net_int32(): 63 x = Tensor(np.array([1, 2, 5, 2]), mstype.int32) 64 uniq = Net() 65 output = uniq(x) 66 print("x:\n", x) 67 print("y:\n", output[0]) 68 print("idx:\n", output[1]) 69 expect_y_result = [1, 2, 5] 70 expect_idx_result = [0, 1, 2, 1] 71 72 assert (output[0].asnumpy() == expect_y_result).all() 73 assert (output[1].asnumpy() == expect_idx_result).all() 74 75 76def test_net_int64(): 77 x = Tensor(np.array([1, 2, 5, 2]), mstype.int64) 78 uniq = Net() 79 output = uniq(x) 80 print("x:\n", x) 81 print("y:\n", output[0]) 82 print("idx:\n", output[1]) 83 expect_y_result = [1, 2, 5] 84 expect_idx_result = [0, 1, 2, 1] 85 86 assert (output[0].asnumpy() == expect_y_result).all() 87 assert (output[1].asnumpy() == expect_idx_result).all() 88