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.common.parameter import Parameter 22from mindspore.common.initializer import initializer 23from mindspore import Tensor 24from mindspore.ops import operations as P 25from mindspore.ops.operations import _grad_ops as G 26 27 28class Conv2dBpropInputInplace(nn.Cell): 29 def __init__(self, w1, w2): 30 super(Conv2dBpropInputInplace, self).__init__() 31 self.conv2d_1 = P.Conv2DBackpropInput(out_channel=256, kernel_size=1) 32 self.w1 = Parameter(initializer(w1, w1.shape), name='w1') 33 self.conv2d_2 = P.Conv2DBackpropInput(out_channel=256, kernel_size=1) 34 self.w2 = Parameter(initializer(w2, w2.shape), name='w2') 35 self.add = P.Add() 36 self.maxpool = P.MaxPool(kernel_size=3, strides=2, pad_mode='SAME') 37 self.maxpool_grad = G.MaxPoolGrad(kernel_size=3, strides=2, pad_mode='SAME') 38 self.shape = (32, 64, 56, 56) 39 40 def construct(self, x1, x2, x3): 41 dx1 = self.conv2d_1(x1, self.w1, self.shape) 42 dx2 = self.conv2d_2(x2, self.w2, self.shape) 43 44 dx = self.add(dx1, dx2) 45 y = self.maxpool(x3) 46 y = self.maxpool_grad(x3, y, dx) 47 return y 48 49 50@pytest.mark.level0 51@pytest.mark.platform_x86_gpu_training 52@pytest.mark.env_onecard 53def test_inplace_fusion1(): 54 55 np.random.seed(42) 56 w1_np = np.random.randn(64, 64, 1, 1) 57 w2_np = np.random.randn(256, 64, 1, 1) 58 x1_np = np.random.randn(32, 64, 56, 56) 59 x2_np = np.random.randn(32, 256, 56, 56) 60 x3_np = np.random.randn(32, 64, 112, 112) 61 62 w1 = Tensor(w1_np.astype(np.float32)) 63 w2 = Tensor(w2_np.astype(np.float32)) 64 x1 = Tensor(x1_np.astype(np.float32)) 65 x2 = Tensor(x2_np.astype(np.float32)) 66 x3 = Tensor(x3_np.astype(np.float32)) 67 68 context.set_context(device_target='GPU', mode=context.GRAPH_MODE) 69 net = Conv2dBpropInputInplace(w1, w2) 70 fusion_output = net(x1, x2, x3) 71 72 context.set_context(device_target='GPU', mode=context.PYNATIVE_MODE) 73 no_fusion_output = net(x1, x2, x3) 74 75 assert np.allclose(fusion_output.asnumpy(), no_fusion_output.asnumpy(), atol=2e-5) 76