1# Copyright 2020-2021 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, Parameter 22from mindspore.ops import operations as P 23 24 25class Net(nn.Cell): 26 def __init__(self, param): 27 super(Net, self).__init__() 28 self.var = Parameter(param, name="var") 29 self.assign = P.Assign() 30 31 def construct(self, param): 32 return self.assign(self.var, param) 33 34 35x = np.array([[1.2, 1], [1, 0]]).astype(np.float32) 36value = np.array([[1, 2], [3, 4.0]]).astype(np.float32) 37 38 39@pytest.mark.level0 40@pytest.mark.platform_x86_gpu_training 41@pytest.mark.env_onecard 42def test_assign(): 43 context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 44 var = Tensor(x) 45 assign = Net(var) 46 output = assign(Tensor(value)) 47 48 error = np.ones(shape=[2, 2]) * 1.0e-6 49 diff1 = output.asnumpy() - value 50 diff2 = assign.var.data.asnumpy() - value 51 assert np.all(diff1 < error) 52 assert np.all(-diff1 < error) 53 assert np.all(diff2 < error) 54 assert np.all(-diff2 < error) 55 56 57@pytest.mark.level0 58@pytest.mark.platform_x86_gpu_training 59@pytest.mark.env_onecard 60def test_assign_float64(): 61 context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 62 var = Tensor(x.astype(np.float64)) 63 assign = Net(var) 64 output = assign(Tensor(value.astype(np.float64))) 65 66 error = np.ones(shape=[2, 2]) * 1.0e-6 67 diff1 = output.asnumpy() - value 68 diff2 = assign.var.data.asnumpy() - value 69 assert np.all(diff1 < error) 70 assert np.all(-diff1 < error) 71 assert np.all(diff2 < error) 72 assert np.all(-diff2 < error) 73