• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 import Tensor
22from mindspore.common import dtype as mstype
23from mindspore.common.api import ms_function
24from mindspore.ops import operations as P
25from mindspore.ops.operations import _grad_ops as G
26
27context.set_context(mode=context.GRAPH_MODE, device_target='CPU')
28
29
30class StridedSliceGrad(nn.Cell):
31    def __init__(self):
32        super(StridedSliceGrad, self).__init__()
33        self.ssg = G.StridedSliceGrad()
34        self.shape = P.Shape()
35
36    @ms_function
37    def construct(self, dy, x):
38        return self.ssg(dy, self.shape(x), (2, 0, 0), (3, 2, 3), (1, 1, 1))
39
40
41@pytest.mark.level0
42@pytest.mark.platform_x86_cpu
43@pytest.mark.env_onecard
44def test_slice():
45    x = Tensor(np.array([[[1., 1., 1.], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 7, 8]]]).astype(np.float32))
46    dy = Tensor(np.array([[[5., 1., 5.], [6., 1., 8.]]]).astype(np.float32))
47    ssg = StridedSliceGrad()
48    output = ssg(dy, x)
49    expect = [[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]], [[5, 1, 5], [6, 1, 8]]]
50    assert (output.asnumpy() == expect).all()
51
52
53class StridedSliceGrad2(nn.Cell):
54    def __init__(self):
55        super(StridedSliceGrad2, self).__init__()
56        self.ssg = G.StridedSliceGrad()
57        self.shape = P.Shape()
58
59    @ms_function
60    def construct(self, dy, x):
61        return self.ssg(dy, self.shape(x), (0, 0, 0), (1, 4, 2), (1, 1, 1))
62
63@pytest.mark.level0
64@pytest.mark.platform_x86_cpu
65@pytest.mark.env_onecard
66def test_slice2():
67    x = Tensor(np.arange(2 * 4 * 2).reshape(2, 4, 2), mstype.float32)
68    dy = Tensor(np.arange(4 * 2).reshape(4, 2), mstype.float32)
69    ssg = StridedSliceGrad2()
70    output = ssg(dy, x)
71    expect = [[[0., 1.], [2., 3.], [4., 5.], [6., 7.]], [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]]
72    assert (output.asnumpy() == expect).all()
73
74if __name__ == '__main__':
75    test_slice()
76    test_slice2()
77