convert_call_func.py 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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.

import collections
import copy
import functools
18
import logging
19 20 21 22 23 24
import inspect
import pdb
import re
import types

import numpy
25
import builtins
26

27
from paddle.fluid.dygraph.container import Sequential
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
from paddle.fluid.dygraph.dygraph_to_static.convert_operators import (
    convert_len,
    convert_zip,
)
from paddle.fluid.dygraph.dygraph_to_static.convert_operators import (
    convert_range,
    convert_enumerate,
)
from paddle.fluid.dygraph.dygraph_to_static.logging_utils import (
    TranslatorLogger,
)
from paddle.fluid.dygraph.dygraph_to_static.program_translator import (
    StaticFunction,
)
from paddle.fluid.dygraph.dygraph_to_static.program_translator import (
    convert_to_static,
)
from paddle.fluid.dygraph.dygraph_to_static.program_translator import (
    unwrap_decorators,
)
48
from paddle.fluid.dygraph.dygraph_to_static.utils import is_paddle_func, unwrap
49 50
from paddle.fluid.dygraph.layers import Layer

51 52
__all__ = ["convert_call"]

53

54 55 56
# The api(s) should be considered as plain function and convert
# them into static layer code.
PADDLE_NEED_CONVERT_APIS = [Sequential]
57 58

translator_logger = TranslatorLogger()
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
CONVERSION_OPTIONS = "An attribute for a function that indicates conversion flags of the function in dynamic-to-static."


class ConversionOptions(object):
    """
    A container for conversion flags of a function in dynamic-to-static.

    Attributes:
        not_convert(bool): An attribute indicates that the function won't be converted in dynamic-to-static.

    NOTE(liym27): More attributes and methods can be added in this class.
    """

    def __init__(self, not_convert=False):
        self.not_convert = not_convert

76

77
def is_builtin(func, name=None):
78 79
    """predict whether a function is a builtin function with name={name}.
    if name == None, then any builtin function will return True
80 81 82 83 84 85
    """

    def name_judge():
        return name is None or func.__name__ == name

    if isinstance(func, types.BuiltinFunctionType) and name_judge():
86
        return True
87
    elif func in builtins.__dict__.values() and name_judge():
88 89 90 91 92
        return True
    else:
        return False


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
def builtin_modules():
    """
    Return builtin modules.
    """
    modules = [
        collections,
        pdb,
        copy,
        inspect,
        re,
        numpy,
        logging,
    ]
    try:
        import six

        modules.append(six)
    except ImportError:
        pass  # do nothing

    return modules


BUILTIN_LIKELY_MODULES = builtin_modules()


119 120 121 122 123
def is_unsupported(func):
    """
    Checks whether the func is supported by dygraph to static graph.
    """

H
Huihuang Zheng 已提交
124 125 126 127
    for m in BUILTIN_LIKELY_MODULES:
        for v in m.__dict__.values():
            func_in_dict = func == v
            if isinstance(func_in_dict, (list, numpy.ndarray)):
128
                func_in_dict = numpy.array(func_in_dict).any()
H
Huihuang Zheng 已提交
129 130 131
            if func_in_dict:
                translator_logger.log(
                    2,
132 133 134 135
                    "Whitelist: {} is part of built-in module and does not have to be transformed.".format(
                        func
                    ),
                )
H
Huihuang Zheng 已提交
136
                return True
137

138 139 140 141
    # NOTE: should be placed before `is_paddle_func`
    if type(func) in PADDLE_NEED_CONVERT_APIS:
        return False

142 143 144
    if is_paddle_func(func):
        translator_logger.log(
            2,
145 146 147 148
            "Whitelist: {} is part of Paddle module and does not have to be transformed.".format(
                func
            ),
        )
149 150 151
        return True


152 153
def convert_call(func):
    """
154
    Converts a function call which needs to be transformed to static function.
155 156 157 158 159 160 161 162 163 164

    Args:
        func (callable): A callable function or method to convert.

    Returns:
        Callable: A converted function.

    Examples:
        .. code-block:: python

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            import paddle
            from paddle.jit.dy2static import convert_call

            paddle.enable_static()
            def dyfunc(x):
                if paddle.mean(x) < 0:
                    x_v = x - 1
                else:
                    x_v = x + 1
                return x_v

            new_func = convert_call(dyfunc)
            x = paddle.tensor.manipulation.fill_constant(shape=[3, 3], value=0, dtype='float64')
            x_v = new_func(x)

            exe = paddle.static.Executor(paddle.CPUPlace())
            out = exe.run(fetch_list=[x_v])
            print(out[0])
            # [[1. 1. 1.]
            #  [1. 1. 1.]
            #  [1. 1. 1.]]
186 187

    """
188 189 190
    translator_logger.log(
        1, "Convert callable object: convert {}.".format(func)
    )
191 192 193
    func_self = None
    converted_call = None

194
    # Function in convert_call may be decorated by another `@to_static`,
195
    # in this case, unwraps it into a raw method or function.
196
    _, func = unwrap_decorators(func)
197

198 199 200 201
    options = getattr(func, CONVERSION_OPTIONS, None)
    if options is not None and options.not_convert:
        translator_logger.log(
            2,
202 203 204 205
            "{} is not converted when it is decorated by 'paddle.jit.not_to_static'.".format(
                func
            ),
        )
206 207
        return func

208
    if is_builtin(func, "len"):
209
        return convert_len
210

211
    if is_builtin(func, "zip"):
212 213
        return convert_zip

214 215 216 217 218 219
    if is_builtin(func, "range"):
        return convert_range

    if is_builtin(func, "enumerate"):
        return convert_enumerate

220
    if is_builtin(func) or is_unsupported(func):
221 222
        return func

223
    if inspect.isgeneratorfunction(func):
224
        # NOTE(xiongkun03): inspect.isfunction() will return True even though func is a generator function.
225 226 227 228
        # If we don't deal generatorfunction here, we will regard it as normal function and get errors in some
        # occasion.
        number_of_stars = 30
        translator_logger.warn(
229 230 231 232 233 234 235 236 237
            "\n\n"
            + "*" * number_of_stars
            + "\nYour function:`{}` doesn't support to transform to static function because it is a generator function, it will be run as-is.".format(
                func.__name__
            )
            + "\n"
            + "*" * number_of_stars
            + "\n\n"
        )
238 239
        return func

240 241 242 243 244
    if inspect.isfunction(func):
        # TODO(liym27): If func is a lambda function, special conversion is needed.
        if func.__name__ == '<lambda>':
            return func
        try:
245 246 247
            # Note(Aurelius84): Because `@declarative` returns a class instance instead of
            # a function. This will modify the value referring to itself in `__globals__`.

248
            # For example:
249 250 251 252 253
            #
            #      @declarative
            #      def foo(x):
            #          return x
            #
254 255
            # `foo` will be converted into a wrapper class, suppose as `StaticFunction`.
            # And `foo.__globals__['foo']` will still return this `StaticFunction` instead of
256
            # `foo` function. So `isinstance(fn, StaticFunction)` is added here.
257
            _origfunc = unwrap(func)
258
            global_functions = set()
259
            for fn in _origfunc.__globals__.values():
260 261
                if inspect.isfunction(fn):
                    global_functions.add(fn)
262
                elif isinstance(fn, StaticFunction):
263 264
                    _, fn = unwrap_decorators(fn)
                    global_functions.add(fn)
265
                elif inspect.isclass(fn):
266 267 268
                    if isinstance(
                        fn.__dict__.get(func.__name__, None), staticmethod
                    ):
269
                        global_functions.add(
270 271
                            func
                        )  # Add func to ensure that we will convert
272 273 274

            if func in global_functions:
                converted_call = convert_to_static(func)
275
                func_self = getattr(func, '__self__', None)
276 277 278 279 280
            else:
                # NOTE:
                # If func is not in __globals__, it does not need to be transformed
                # because it has been transformed before.
                translator_logger.warn(
281 282 283 284
                    "{} doesn't have to be transformed to static function because it has been transformed before, it will be run as-is.".format(
                        func
                    )
                )
285
                converted_call = func
286 287 288 289 290 291 292
        except AttributeError:
            # NOTE:
            # If func is not in __globals__, it does not need to be transformed
            # because it has been transformed before.
            converted_call = None
        except (IOError, OSError):
            # NOTE:
293
            # If func has been decorated, its source code can not be get
294 295 296 297
            # so that it can not be transformed to static function.
            converted_call = None
    elif inspect.ismethod(func):
        try:
298
            converted_call = convert_to_static(func)
299
            func_self = getattr(func, '__self__', None)
300
        except (IOError, OSError):
301
            # NOTE: func may have been decorated.
302 303 304 305 306
            converted_call = None

    elif hasattr(func, '__class__') and hasattr(func.__class__, '__call__'):
        if hasattr(func, 'forward') and isinstance(func, Layer):
            try:
307
                _, forward_func = unwrap_decorators(func.forward)
308
                func._original_funcs['forward'] = forward_func.__func__
309
                forward_func = convert_to_static(forward_func)
310 311 312 313
                # Bound mothod will be convert into plain function after `convert_to_static`.
                # So descriptor mechanism is used to bound `self` instance on function to
                # keep it as bound method.
                setattr(func, 'forward', forward_func.__get__(func))
314
            except (IOError, OSError, TypeError):
315
                # NOTE: func.forward may have been decorated.
316 317 318 319 320
                func_self = None if func_self else func_self
            converted_call = func
        else:
            try:
                call_func = func.__class__.__call__
321
                converted_call = convert_to_static(call_func)
322
                func_self = func
323
            except (IOError, OSError, TypeError):
324 325 326 327
                # NOTE:
                # If `func` is a class which is being initialized, for example `convert_call(Foo)()`,
                # it doesn't need to be transformed
                func_self = None if func_self else func_self
328 329
    else:
        raise NotImplementedError(
330 331
            "Callable {} can not be transformed at present.".format(func)
        )
332 333

    if converted_call is None:
334
        translator_logger.warn(
335 336 337 338
            "{} doesn't have to be transformed to static function, and it will be run as-is.".format(
                func
            )
        )
339 340 341 342 343
        return func

    if func_self:
        converted_call = functools.partial(converted_call, func_self)
    return converted_call