• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019-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.operations import _grad_ops as G
24
25context.set_context(mode=context.PYNATIVE_MODE, device_target='GPU')
26
27
28class SliceGrad(nn.Cell):
29    def __init__(self):
30        super(SliceGrad, self).__init__()
31
32        self.slicegrad = G.SliceGrad()
33
34    @ms_function
35    def construct(self, dy, x):
36        return self.slicegrad(dy, x, (0, 1, 0), (2, 1, 3))
37
38
39@pytest.mark.level0
40@pytest.mark.platform_x86_gpu_training
41@pytest.mark.env_onecard
42def test_slice():
43    x = Tensor(np.array([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]]).astype(np.float32))
44    dy = Tensor(np.array([[[3., 1., 2.]], [[4., 1., 4.]]]).astype(np.float32))
45    slicegrad = SliceGrad()
46    output = slicegrad(dy, x)
47    expect = [[[0., 0., 0.],
48               [3., 1., 2.]],
49              [[0., 0., 0.],
50               [4., 1., 4.]],
51              [[0., 0., 0.],
52               [0., 0., 0.]]]
53    assert (output.asnumpy() == expect).all()
54
55
56@pytest.mark.level0
57@pytest.mark.platform_x86_gpu_training
58@pytest.mark.env_onecard
59def test_slice_float64():
60    x = Tensor(np.array([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]]).astype(np.float64))
61    dy = Tensor(np.array([[[3., 1., 2.]], [[4., 1., 4.]]]).astype(np.float64))
62    slicegrad = SliceGrad()
63    output = slicegrad(dy, x)
64    expect = np.array([[[0., 0., 0.],
65                        [3., 1., 2.]],
66                       [[0., 0., 0.],
67                        [4., 1., 4.]],
68                       [[0., 0., 0.],
69                        [0., 0., 0.]]]).astype(np.float64)
70    assert (output.asnumpy() == expect).all()
71