• 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""" test nn pad """
16import numpy as np
17
18import mindspore.nn as nn
19from mindspore import Tensor
20from mindspore.common.api import ms_function
21from mindspore.ops.composite import GradOperation
22
23
24class Net(nn.Cell):
25    def __init__(self, raw_paddings, mode):
26        super(Net, self).__init__()
27        self.pad = nn.Pad(raw_paddings, mode=mode)
28
29    @ms_function
30    def construct(self, x):
31        return self.pad(x)
32
33
34class Grad(nn.Cell):
35    def __init__(self, network):
36        super(Grad, self).__init__()
37        self.grad = GradOperation(get_all=True, sens_param=True)
38        self.network = network
39
40    @ms_function
41    def construct(self, x, grads):
42        return self.grad(self.network)(x, grads)
43
44
45def test_pad_train():
46    mode = 'CONSTANT'
47    x = np.random.random(size=(2, 3)).astype(np.float32)
48    raw_paddings = ((1, 1), (2, 2))
49    grads = np.random.random(size=(4, 7)).astype(np.float32)
50    grad = Grad(Net(raw_paddings, mode))
51    output = grad(Tensor(x), Tensor(grads))
52    print("=================output====================")
53    print(output)
54
55
56def test_pad_infer():
57    mode = 'CONSTANT'
58    x = np.random.random(size=(2, 3)).astype(np.float32)
59    raw_paddings = ((1, 1), (2, 2))
60    net = Net(raw_paddings, mode)
61    output = net(Tensor(x))
62    print("=================output====================")
63    print(output)
64