1# Copyright 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 AssignAdd(nn.Cell): 26 def __init__(self, value): 27 super(AssignAdd, self).__init__() 28 self.var = Parameter(value, name="var") 29 self.add = P.AssignAdd() 30 31 def construct(self, y): 32 self.add(self.var, y) 33 return self.var 34 35def get_output(x2, y2, enable_graph_kernel=False): 36 context.set_context(enable_graph_kernel=enable_graph_kernel) 37 add = AssignAdd(x2) 38 result_gk_on_1 = add(y2) 39 add_2 = AssignAdd(result_gk_on_1) 40 result_gk_on_2 = add_2(y2) 41 output = [result_gk_on_1, result_gk_on_2] 42 return output 43 44def assign_add(): 45 x2 = Tensor(np.arange(1 * 3 * 3 * 3).reshape(1, 3, 3, 3).astype(np.float32)) 46 y2 = Tensor(np.arange(1 * 3 * 3 * 3).reshape(1, 3, 3, 3).astype(np.float32)) 47 48 expect = get_output(x2, y2, False) 49 output = get_output(x2, y2, True) 50 e1, e2 = list(expect) 51 o1, o2 = list(output) 52 53 assert np.allclose(o1.asnumpy(), e1.asnumpy()) 54 assert np.allclose(o2.asnumpy(), e2.asnumpy()) 55 56@pytest.mark.level0 57@pytest.mark.platform_x86_gpu_training 58@pytest.mark.env_onecard 59def test_assign_add_gpu(): 60 context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 61 assign_add() 62 63@pytest.mark.level0 64@pytest.mark.platform_arm_ascend_training 65@pytest.mark.platform_x86_ascend_training 66@pytest.mark.env_onecard 67def test_assign_add_ascend(): 68 context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") 69 assign_add() 70