• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2022 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
18import mindspore.context as context
19from mindspore import Tensor
20from mindspore.nn import Cell
21import mindspore.ops.operations as P
22
23
24class ElemwiseNet(Cell):
25    def __init__(self):
26        super(ElemwiseNet, self).__init__()
27        self.add = P.Add()
28        self.sub = P.Sub()
29        self.exp = P.Exp()
30        self.matmul = P.MatMul()
31
32    def construct(self, x, y, z):
33        res_1 = self.matmul(x, y)
34        res_2 = self.sub(res_1, z)
35        res_3 = self.exp(res_2)
36        res_4 = self.add(res_3, z)
37        return res_4
38
39
40def fusion_net_get_output(x, y, z, enable_auto_tensor_inplace=False):
41    context.set_context(enable_graph_kernel=True)
42    if enable_auto_tensor_inplace:
43        context.set_context(graph_kernel_flags="--enable_auto_tensor_inplace=true")
44    net = ElemwiseNet()
45    output = net(x, y, z)
46    return output
47
48
49def fusion_net_compare_result():
50    x = Tensor(np.random.normal(0, 1, [4, 16]).astype(np.float32))
51    y = Tensor(np.random.normal(0, 1, [16, 4]).astype(np.float32))
52    z = Tensor(np.random.normal(0, 1, [4, 4]).astype(np.float32))
53    expect = fusion_net_get_output(x, y, z, False)
54    output = fusion_net_get_output(x, y, z, True)
55    assert np.allclose(expect.asnumpy(), output.asnumpy(), 1.e-4, 1.e-7)
56
57
58@pytest.mark.level1
59@pytest.mark.platform_x86_gpu_training
60@pytest.mark.env_onecard
61def test_gpu_graph_mode():
62    """
63    Feature: graph kernel testcase for auto tensor inplace
64    Description: random input when using graph_kernel in graph mode
65    Expectation: get the same result when using and not using auto tensor inplace
66    """
67    context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
68    fusion_net_compare_result()
69