test_unuseful_inputs.py 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

import numpy as np

import paddle
20
from paddle import nn
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
from paddle.jit import to_static

np.random.seed(1)


def apply_to_static(support_to_static, model, image_shape=None):
    if support_to_static:
        specs = None
        model = to_static(model, input_spec=specs)

    return model


class Layer0(nn.Layer):
    def __init__(self, level):
36
        super().__init__()
37 38 39 40 41 42 43 44
        self._linear1 = nn.Linear(10, 5)
        self._linear2 = nn.Linear(10, 5)
        self.layer1 = Layer1(level)
        apply_to_static(True, self.layer1)

    def forward(self, x):
        out1 = self._linear1(x)
        out2 = self._linear2(x)
45
        # out2.stop_gradient = True not raise error
46 47
        a = [out1, out2]
        b = self.layer1(a)
48
        # self.layer1(out1, out2) will raise error
49 50 51 52 53
        return b


class Layer1(nn.Layer):
    def __init__(self, level):
54
        super().__init__()
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        self.level = level
        self._linear = nn.Linear(5, 2)

    def forward(self, x):
        inp = x[self.level]
        val = self._linear(inp)
        return val


class TestDuplicateOutput(unittest.TestCase):
    """
    TestCase for the transformation from control flow `if/else`
    dependent on tensor in Dygraph into Static `fluid.layers.cond`.
    """

    def test_case(self):
        # create network
        layer = Layer0(0)
        a = paddle.rand(shape=[10, 10])
        out = layer(a)
        loss = out.mean()
        loss.backward()


if __name__ == '__main__':
    unittest.main()