ifelse_simple_func.py 6.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#   Copyright (c) 2020 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.

from __future__ import print_function

import paddle.fluid as fluid
from paddle.fluid.dygraph.jit import dygraph_to_static_graph


def dyfunc_with_if_else(x_v, label=None):
    if fluid.layers.mean(x_v).numpy()[0] > 5:
        x_v = x_v - 1
    else:
        x_v = x_v + 1
    # plain if in python
    if label is not None:
        loss = fluid.layers.cross_entropy(x_v, label)
        return loss
    return x_v


def dyfunc_with_if_else2(x, col=100):
    row = 0
    if abs(col) > x.shape[-1]:
        col = -1
    if fluid.layers.reduce_mean(x).numpy()[0] > x.numpy()[row][col]:
        y = fluid.layers.relu(x)
    else:
        x_pow = fluid.layers.pow(x, 2)
        y = fluid.layers.tanh(x_pow)
    return y


def nested_if_else(x_v):
    batch_size = 16
    feat_size = x_v.shape[-1]
    bias = fluid.layers.fill_constant([feat_size], dtype='float32', value=1)
    if x_v.shape[0] != batch_size:
        batch_size = x_v.shape[0]
    if fluid.layers.mean(x_v).numpy()[0] < 0:
        y = x_v + bias
        w = fluid.layers.fill_constant([feat_size], dtype='float32', value=10)
        if y.numpy()[0] < 10:
            tmp = y * w
            y = fluid.layers.relu(tmp)
            if fluid.layers.mean(y).numpy()[0] < batch_size:
                y = fluid.layers.abs(y)
            else:
                tmp = fluid.layers.fill_constant(
                    [feat_size], dtype='float32', value=-1)
                y = y - tmp
    else:
        y = x_v - bias
    return y


68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
def nested_if_else_2(x):
    y = fluid.layers.reshape(x, [-1, 1])
    b = 2
    if b < 1:
        # var `z` is not visible for outer scope
        z = y
    x_shape_0 = x.shape[0]
    if x_shape_0 < 1:
        if fluid.layers.shape(y).numpy()[0] < 1:
            res = fluid.layers.fill_constant(
                value=2, shape=x.shape, dtype="int32")
            # `z` is a new var here.
            z = y + 1
        else:
            res = fluid.layers.fill_constant(
                value=3, shape=x.shape, dtype="int32")
    else:
        res = x
    return res


def nested_if_else_3(x):
    y = fluid.layers.reshape(x, [-1, 1])
    b = 2
    # var `z` is visible for func.body
    if b < 1:
        z = y
    else:
        z = x

    if b < 1:
        res = x
        # var `out` is only visible for current `if`
        if b > 1:
            out = x + 1
        else:
            out = x - 1
    else:
        y_shape = fluid.layers.shape(y)
        if y_shape.numpy()[0] < 1:
            res = fluid.layers.fill_constant(
                value=2, shape=x.shape, dtype="int32")
            # `z` is created in above code block.
            z = y + 1
        else:
            res = fluid.layers.fill_constant(
                value=3, shape=x.shape, dtype="int32")
            # `out` is a new var.
            out = x + 1
    return res


120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
class NetWithControlFlowIf(fluid.dygraph.Layer):
    def __init__(self, hidden_dim=16):
        super(NetWithControlFlowIf, self).__init__()
        self.hidden_dim = hidden_dim
        self.fc = fluid.dygraph.Linear(
            input_dim=hidden_dim,
            output_dim=5,
            param_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.99)),
            bias_attr=fluid.ParamAttr(
                initializer=fluid.initializer.Constant(value=0.5)))
        self.alpha = 10.
        self.constant_vars = {}

    @dygraph_to_static_graph
    def forward(self, input):
        hidden_dim = input.shape[-1]
        if hidden_dim != self.hidden_dim:
            raise ValueError(
                "hidden_dim {} of input is not equal to FC.weight[0]: {}"
                .format(hidden_dim, self.hidden_dim))

        self.constant_vars['bias'] = fluid.layers.fill_constant(
            [5], dtype='float32', value=1)
        # Control flow `if` statement
        fc_out = self.fc(input)
        if fluid.layers.mean(fc_out).numpy()[0] < 0:
            y = fc_out + self.constant_vars['bias']
            self.constant_vars['w'] = fluid.layers.fill_constant(
                [5], dtype='float32', value=10)
            if y.numpy()[0] < self.alpha:
                # Create new var, but is not used.
                x = 10
                tmp = y * self.constant_vars['w']
                y = fluid.layers.relu(tmp)
                # Nested `if/else`
                if y.numpy()[-1] < self.alpha:
                    # Modify variable of class
                    self.constant_vars['w'] = fluid.layers.fill_constant(
                        [hidden_dim], dtype='float32', value=9)
                    y = fluid.layers.abs(y)
                else:
                    tmp = fluid.layers.fill_constant(
                        [5], dtype='float32', value=-1)
                    y = y - tmp
        else:
            y = fc_out - self.constant_vars['bias']

        loss = fluid.layers.mean(y)
        return loss


def if_with_and_or(x_v, label=None):
    batch_size = fluid.layers.shape(x_v)
    if x_v and (fluid.layers.mean(x_v).numpy()[0] > 0 or
                label is not None) and batch_size[0] > 1 and True:
        x_v = x_v - 1
    else:
        x_v = x_v + 1

    if label is not None:
        loss = fluid.layers.cross_entropy(x_v, label)
        return loss
    return x_v


def if_with_and_or_1(x, y=None):
    batch_size = fluid.layers.shape(x)
    if batch_size[0] > 1 and y is not None:
        x = x + 1
    if y or batch_size[0] > 1:
        x = x - 1
    return x


def if_with_and_or_2(x, y=None):
    batch_size = fluid.layers.shape(x)
    if x and batch_size[0] > 1 and y is not None:
        x = x + 1
    if batch_size[0] > 1 or y or x is not None:
        x = x - 1
    return x


def if_with_and_or_3(x, y=None):
    batch_size = fluid.layers.shape(x)
    mean_res = fluid.layers.mean(x)
    if x and batch_size[0] > 1 and y is not None and mean_res.numpy()[0] > 0:
        x = x + 1
    if mean_res.numpy()[0] > 0 and (x and batch_size[0] > 1) and y:
        x = x - 1
    return x


def if_with_and_or_4(x, y=None):
    batch_size = fluid.layers.shape(x)
    mean_res = fluid.layers.mean(x)
    if (x and batch_size[0] > 1) or (y is not None and mean_res.numpy()[0] > 0):
        x = x + 1
    if (x or batch_size[0] > 1) and (y is not None or mean_res.numpy()[0] > 0):
        x = x - 1
    return x