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 22from mindspore.common.api import ms_function 23from mindspore.ops import functional as F 24from mindspore.ops.composite import GradOperation 25context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 26 27class Grad(nn.Cell): 28 def __init__(self, network): 29 super(Grad, self).__init__() 30 self.grad = GradOperation(get_all=True, sens_param=True) 31 self.network = network 32 33 @ms_function 34 def construct(self, input_x, grad): 35 return self.grad(self.network)(input_x, grad) 36 37class Net(nn.Cell): 38 def __init__(self, n): 39 super(Net, self).__init__() 40 self.ops = nn.BatchNorm2d(n, use_batch_statistics=True, gamma_init=0.5, beta_init=0.5) 41 42 def construct(self, x): 43 shape = F.shape(x) 44 return F.reshape(self.ops(F.reshape(x, (1, -1, shape[2], shape[3]))), shape) 45 46@pytest.mark.level0 47@pytest.mark.platform_x86_gpu_training 48@pytest.mark.env_onecard 49def test_InstanceNorm2d_fp32(): 50 x_np = np.random.randn(3, 3, 2, 2).astype(np.float32) 51 bn_instance_comp = Net(3 * 3) 52 bn_instance_op = nn.InstanceNorm2d(3, gamma_init=0.5, beta_init=0.5) 53 comp_out = bn_instance_comp(Tensor(x_np)) 54 op_out = bn_instance_op(Tensor(x_np)) 55 assert np.allclose(comp_out.asnumpy(), op_out.asnumpy()) 56 57 sens = np.random.randn(3, 3, 2, 2).astype(np.float32) 58 bn_comp_backward_net = Grad(bn_instance_comp) 59 bn_op_backward_net = Grad(bn_instance_op) 60 output1 = bn_comp_backward_net(Tensor(x_np), Tensor(sens)) 61 output2 = bn_op_backward_net(Tensor(x_np), Tensor(sens)) 62 assert np.allclose(output1[0].asnumpy(), output2[0].asnumpy()) 63