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 17import pytest 18 19import mindspore.context as context 20import mindspore.nn as nn 21from mindspore import Tensor 22from mindspore.ops.operations import _inner_ops as inner 23from mindspore.ops import operations as P 24 25 26@pytest.mark.level0 27@pytest.mark.platform_x86_gpu_training 28@pytest.mark.env_onecard 29def test_square_normal(): 30 context.set_context(mode=context.PYNATIVE_MODE, device_target="GPU") 31 x_np = np.random.rand(2, 3, 4, 4).astype(np.float32) 32 output_ms = P.Square()(Tensor(x_np)) 33 output_np = np.square(x_np) 34 assert np.allclose(output_ms.asnumpy(), output_np) 35 x_np = np.random.rand(2, 3, 1, 5, 4, 4).astype(np.float32) 36 output_ms = P.Square()(Tensor(x_np)) 37 output_np = np.square(x_np) 38 assert np.allclose(output_ms.asnumpy(), output_np) 39 x_np = np.random.rand(2,).astype(np.float32) 40 output_ms = P.Square()(Tensor(x_np)) 41 output_np = np.square(x_np) 42 assert np.allclose(output_ms.asnumpy(), output_np) 43 44 45# Dynamic Shape Testing 46class SqaureNetDynamic(nn.Cell): 47 def __init__(self): 48 super(SqaureNetDynamic, self).__init__() 49 self.square = P.Square() 50 self.gpu_convert_to_dynamic_shape = inner.GpuConvertToDynamicShape() 51 52 def construct(self, x): 53 x_dyn = self.gpu_convert_to_dynamic_shape(x) 54 return self.square(x_dyn) 55 56 57@pytest.mark.level0 58@pytest.mark.platform_x86_gpu_training 59@pytest.mark.env_onecard 60def test_square_dynamic(): 61 context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 62 net = SqaureNetDynamic() 63 x_np = np.random.rand(1, 3, 4, 4, 1).astype(np.float32) 64 output_ms = net(Tensor(x_np)) 65 output_np = np.square(x_np) 66 assert np.allclose(output_ms.asnumpy(), output_np) 67 x_np = np.random.rand(2, 3, 4, 4, 8, 9).astype(np.float16) 68 output_ms = net(Tensor(x_np)) 69 output_np = np.square(x_np) 70 assert np.allclose(output_ms.asnumpy(), output_np) 71 x_np = np.random.rand(1).astype(np.float32) 72 output_ms = net(Tensor(x_np)) 73 output_np = np.square(x_np) 74 assert np.allclose(output_ms.asnumpy(), output_np) 75