program_translator.py 42.6 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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
16

17
import collections
18
from paddle.utils import gast
19
import inspect
20
import six
21 22
import textwrap
import threading
23
import weakref
24 25

from paddle.fluid import framework
26
from paddle.fluid import in_dygraph_mode
27
from paddle.fluid.dygraph import layers
28 29
from paddle.fluid.data_feeder import check_type
from paddle.fluid.layers.utils import flatten
30
from paddle.fluid.dygraph.base import param_guard
31
from paddle.fluid.dygraph.base import switch_to_static_graph
32
from paddle.fluid.dygraph.dygraph_to_static import DygraphToStaticAst
33
from paddle.fluid.dygraph.dygraph_to_static import error
34
from paddle.fluid.dygraph.dygraph_to_static import logging_utils
35 36 37 38 39
from paddle.fluid.dygraph.dygraph_to_static.origin_info import attach_origin_info
from paddle.fluid.dygraph.dygraph_to_static.origin_info import create_and_update_origin_info_map
from paddle.fluid.dygraph.dygraph_to_static.origin_info import update_op_callstack_with_origin_info
from paddle.fluid.dygraph.dygraph_to_static.partial_program import partial_program_from
from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_func
40
from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code
41
from paddle.fluid.dygraph.dygraph_to_static.utils import func_to_source_code
42
from paddle.fluid.dygraph.dygraph_to_static.utils import input_specs_compatible
43
from paddle.fluid.dygraph.dygraph_to_static.utils import type_name
44
from paddle.fluid.dygraph.dygraph_to_static.utils import unwrap
45
from paddle.fluid.dygraph.dygraph_to_static.utils import make_hashable
46
from paddle.fluid.dygraph.dygraph_to_static.function_spec import FunctionSpec, _hash_spec_names
47
from paddle.fluid.dygraph.dygraph_to_static.function_spec import get_buffers, get_parameters
48
from paddle.fluid.wrapped_decorator import signature_safe_contextmanager
49

50
__all__ = ['ProgramTranslator', 'convert_to_static']
51

52 53 54 55
# For each traced function, we set `max_traced_program_count` = 10 to consider caching performance.
# Once exceeding the threshold, we will raise warning to users to make sure the conversion is as expected.
MAX_TRACED_PROGRAM_COUNT = 10

56 57 58 59 60 61 62

class FunctionCache(object):
    """
    Caches the transformed functions to avoid redundant conversions of the same function.
    """

    def __init__(self):
63 64 65 66 67
        # Caches the converted static functions. {dygraph_func: static_func}
        self._converted_static_func_caches = dict()
        # Caches the converted ast node for same source code. {source_code: ast_root}
        self._code_to_ast_caches = dict()
        self._dygraph_to_static = DygraphToStaticAst()
68

69 70 71 72 73 74
    def convert_with_cache(self, func):
        """
        Returns the cached static function or converts it when first encounters the function.
        """
        # If hit cache, return it directly.
        static_func = self._converted_static_func_caches.get(func, None)
75 76

        if static_func is None:
77 78
            static_func = self._convert(func)
            self._converted_static_func_caches[func] = static_func
79 80 81

        return static_func

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    def _convert(self, func):
        """
        Converts dygraph function into static function. For two functions with same dedent code,
        the second function will reuse the transformed ast node of previous one.

        For example:
            # A.py
            def foo(x, y):
                z = x + y
                return z

            # B.py
            def foo(x, y):
                z = x + y
                return z

        If the conversion of A.foo happens after B.foo, it will reuse the transformed ast node of B.foo
        to speed up the conversion.
        """
        # Note: In Python2, it will raise OSError when inspect function
        # with decorator directly and function.__wrapped__ holds the actual function.
103
        func = unwrap(func)
104
        source_code = func_to_source_code(func)
105 106 107 108 109

        # TODO(liym27):
        #  Consider this case: source_code in self._code_to_ast_caches,
        #  but actually they are methods in different classes.
        #  Maybe use (__class__, source_code) as key
110 111 112 113
        if source_code in self._code_to_ast_caches:
            root_wrapper = self._code_to_ast_caches[source_code]
        else:
            root = gast.parse(source_code)
114
            root = attach_origin_info(root, func)
115 116
            root_wrapper = self._dygraph_to_static.get_static_ast(root)
            self._code_to_ast_caches[source_code] = root_wrapper
117

118 119
        # Get static function from AST
        static_func, file_name = ast_to_func(root_wrapper.node, func)
120 121

        create_and_update_origin_info_map(root_wrapper.node, static_func)
122
        return static_func
123 124

    def exist(self, func):
125
        return func in self._converted_static_func_caches
126 127


128 129 130 131
_CACHE_LOCK = threading.Lock()
_FUNCTION_CACHE = FunctionCache()


132
def convert_to_static(function):
133
    """
134
    Transforms function of dygraph into static function using the cache mechanism.
135 136 137

    Args:
        function(callable): The function with dygraph layers that will be converted into static layers.
138 139
    """
    with _CACHE_LOCK:
140
        static_func = _FUNCTION_CACHE.convert_with_cache(function)
141 142 143
        return static_func


144 145 146 147
class CacheKey(object):
    """
    Cached key for ProgramCache.
    """
148 149
    __slots__ = [
        'function_spec', 'input_args_with_spec', 'input_kwargs_with_spec',
150
        'class_instance', 'kwargs', '_spec_names_id'
151
    ]
152

153
    def __init__(self, function_spec, input_args_with_spec,
154
                 input_kwargs_with_spec, class_instance, **kwargs):
155 156
        """
        Initializes a cache key.
157

158 159
        Args:
            functions_spec(FunctionSpec): a FunctionSpec instance of decorated function.
160 161
            input_args_with_spec(list[InputSpec]): actual input args with some arguments replaced by InputSpec.
            input_kwargs_with_spec(list[{string:InputSpec}]): actual input kwargs with some arguments replaced by InputSpec.
162
            class_instance(object): a instance of class `Layer`.
163
            **kwargs(dict): manage other arguments used for better scalability
164
        """
165
        self.function_spec = function_spec
166 167
        self.input_args_with_spec = input_args_with_spec
        self.input_kwargs_with_spec = input_kwargs_with_spec
168
        self.class_instance = class_instance
169 170
        # NOTE: `kwargs` is usually not considered as basic member for `__hash__`
        self.kwargs = kwargs
171 172
        self._spec_names_id = _hash_spec_names(input_args_with_spec,
                                               input_kwargs_with_spec)
173 174 175

    @classmethod
    def from_func_and_args(cls, function_spec, args, kwargs, class_instance):
176
        """
177 178 179 180 181 182 183 184 185 186 187
        Generated a CacheKey instance by given inputs.

        Args:
            functions_spec(FunctionSpec): a FunctionSpec instance of decorated function.
            args(tuple): tuple of actual inputs arguments.
            kwargs(dict): dict of actual inputs keyword arguments.
            class_instance(object): a instance of class `Layer`.
        """
        # 1. filter `self` in args
        if args and isinstance(args[0], layers.Layer):
            args = args[1:]
188
        # 2. convert tensor and numpy array into InputSpec
189
        _args, _kwargs = function_spec.unified_args_and_kwargs(args, kwargs)
190 191
        input_args_with_spec, input_kwargs_with_spec = function_spec.args_to_input_spec(
            _args, _kwargs)
192 193

        # 3. check whether hit the cache or build a new program for the input arguments
194 195
        return CacheKey(function_spec, input_args_with_spec,
                        input_kwargs_with_spec, class_instance)
196 197 198 199

    def __hash__(self):
        error_msg = "Arguments to a `@paddle.jit.to_static` must be a hashable Python objects (or nested structures of these types)."
        return hash((id(self.function_spec),
200 201
                     make_hashable(self.input_args_with_spec, error_msg),
                     make_hashable(self.input_kwargs_with_spec, error_msg),
202
                     self._spec_names_id, self.class_instance))
203 204 205 206 207 208 209 210

    def __eq__(self, other):
        return (type(self) is type(other)) and hash(self) == hash(other)

    def __neq__(self, other):
        return not self == other

    def __repr__(self):
211 212 213
        return "id(function_spec): {}, input_args_with_spec: {}, input_kwargs_with_spec: {}, class_instance: {}".format(
            id(self.function_spec), self.input_args_with_spec,
            self.input_kwargs_with_spec, self.class_instance)
214 215 216 217 218 219 220 221 222


def unwrap_decorators(func):
    """
    Unwraps a decorated function and returns the decorator list and inner target.
    """
    decorators = []
    cur = func
    while True:
223
        if isinstance(cur, StaticFunction):
224 225 226 227 228
            decorators.append(cur)
            # Note: if `cur` is a method, keep it as bound method of class.
            instance = cur._class_instance
            if instance is not None:
                cur = cur.dygraph_function.__get__(instance)
229
            else:
230 231 232 233
                cur = cur.dygraph_function
        else:
            break
    return decorators, cur
234

235

236
class StaticFunction(object):
237 238 239 240 241
    """
    Wrapper class to Manage program conversion of decorated function.

    """

242
    def __init__(self, function, input_spec=None, **kwargs):
243
        """
244
        Initializes a `StaticFunction`.
245 246 247 248

        Args:
            function(callable): A function or method that will be converted into static program.
            input_spec(list[InputSpec]): list of InputSpec to specify the `shape/dtype/name` information for each input argument, default None.
249
            **kwargs(dict): other arguments like `build_strategy` et.al.
250 251 252 253 254 255 256 257 258 259 260 261
        """
        # save the instance `self` while decorating a method of class.
        if inspect.ismethod(function):
            self._dygraph_function = getattr(function, '__func__')
            self._class_instance = getattr(function, '__self__')
        else:
            self._dygraph_function = function
            self._class_instance = None

        self._input_spec = input_spec
        self._function_spec = FunctionSpec(function, input_spec)
        self._program_cache = ProgramCache()
262
        self._descriptor_cache = weakref.WeakKeyDictionary()
263
        # Note: Hold a reference to ProgramTranslator for switching `enable_to_static`.
264
        self._program_trans = ProgramTranslator()
265
        self._kwargs = kwargs
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        self._training = True

    def train(self):
        if isinstance(self._class_instance,
                      layers.Layer) and self._class_instance.training == False:
            raise RuntimeError(
                "Failed to switch train mode. {} is a Layer's method, "
                "please use Layer.train() to switch train mode.".format(
                    self.dygraph_function))
        self._training = True

    def eval(self):
        if isinstance(self._class_instance,
                      layers.Layer) and self._class_instance.training == True:
            raise RuntimeError(
                "Failed to switch eval mode. {} is a Layer's method, "
                "please use Layer.eval() to switch eval mode.".format(
                    self.dygraph_function))
        self._training = False
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

    def __get__(self, instance, owner):
        """
        Overrides this method to parse the class instance and call bound method correctly.

        For example:
            
            '''
            class Net(Layer):
                def __init__(self):
                    pass
                
                @paddle.jit.to_static
                def forward(self, x, y):
                    return x + y

            net = Net()
            out = net(x, y)
            '''
        
        In above case, `net(x, y)` will call `net.forward(x, y)` firstly that is a bound method
        of `Net` instance. After decorated by `@paddle.jit.to_static`, it will firstly to call `__get__`
307
        to parse the class instance correctly instead of the `StaticFunction` instance.
308
        """
309 310 311
        if instance not in self._descriptor_cache:
            if instance is None:
                return self
312
            # Note(Aurelius84): To construct new instance of StaticFunction when we
313 314 315 316 317 318 319 320 321
            # first encouter the bound function of layer and cache it.
            new_static_layer = self._clone()
            new_static_layer._class_instance = instance
            self._descriptor_cache[instance] = new_static_layer

        return self._descriptor_cache[instance]

    def _clone(self):
        return self.__class__(self._dygraph_function, self._input_spec)
322 323

    def __call__(self, *args, **kwargs):
324
        """
325 326 327 328 329 330 331 332
        Supports to call the returned instance with input `args` and `kwargs` directly.

        Args:
            *args(tuple): tuple of all input arguments from original decorated function.
            **kwargs(dict): dict of all input keyward arguments from original decorated function. 

        Return:
            Outputs of decorated function.
333
        """
334

335
        # 1. call dygraph function directly if not enable `declarative`
336
        if not self._program_trans.enable_to_static:
337 338 339 340
            # NOTE(liym27):
            # Here calls `warnings.warn` but not `logging_utils.warn` because by default warnings.warn(message)
            # will show up **only once**. StaticFunction.__call__ will run many times, it is appropriate to
            # display this warning message only once.
341
            logging_utils.warn(
342 343 344
                "The decorator '@paddle.jit.to_static' does NOT work when setting ProgramTranslator.enable to False. "
                "We will just return dygraph output. If you would like to get static graph output, please call API "
                "ProgramTranslator.enable(True)")
345 346
            return self._call_dygraph_function(*args, **kwargs)

347
        if not in_dygraph_mode():
348 349
            raise RuntimeError(
                "Failed to run the callable object {} decorated by '@paddle.jit.to_static', "
350
                "because it is NOT in dynamic mode. Please disable the static mode to enter dynamic mode with the "
351 352 353
                "following API: paddle.disable_static().".format(
                    self.dygraph_function))

354 355
        # 2. trace ops from dygraph layers and cache the generated program.
        args, kwargs = self._function_spec.unified_args_and_kwargs(args, kwargs)
356

357 358 359 360 361 362 363
        try:
            concrete_program, partial_program_layer = self.get_concrete_program(
                *args, **kwargs)

            # 3. synchronize self.training attribute.
            if isinstance(self._class_instance, layers.Layer):
                partial_program_layer.training = self._class_instance.training
364 365
            else:
                partial_program_layer.training = self._training
366 367

            # 4. return outputs.
368 369 370 371 372 373 374
            try:
                return partial_program_layer(args)
            except Exception as e:
                if not hasattr(e, error.ERROR_DATA):
                    # runtime error
                    error.attach_error_data(e, in_runtime=True)
                    raise
375
        except Exception as e:
376
            error_data = getattr(e, error.ERROR_DATA, None)
377
            if error_data:
378
                error_data.raise_new_exception()
379
            else:
380 381 382 383
                logging_utils.warn(
                    "Please file an issue at 'https://github.com/PaddlePaddle/Paddle/issues'"
                    " if you can't handle this {} yourself.".format(type(e)))
                raise e
384

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    def _call_dygraph_function(self, *args, **kwargs):
        """
        Calls dygraph function directly and returns the outputs.

        Args:
            *args(tuple): tuple of all input arguments from original decorated function.
            **kwargs(dict): dict of all input keyward arguments from original decorated function. 

        Return:
            Outputs of dygraph function.
        """
        if self._class_instance is not None:
            dygraph_function = self._dygraph_function.__get__(
                self._class_instance)
        else:
            dygraph_function = self._dygraph_function

        return dygraph_function(*args, **kwargs)

    def get_concrete_program(self, *args, **kwargs):
        """
        Returns traced concrete program and inner executable partial layer.

        Args:
            *args(tuple): input arguments values or InputSpec
            **kwargs(dict) : input kwargs values.

        Returns:
            Traced ConcreteProgram and executable translated Layer.
        """
415

416 417 418 419
        # 1. unify args/kwargs and replace Tensor with InputSpec
        if len(args) != len(self._function_spec.args_name):
            args, kwargs = self._function_spec.unified_args_and_kwargs(args,
                                                                       kwargs)
420 421
        input_args_with_spec, input_kwargs_with_spec = self._function_spec.args_to_input_spec(
            args, kwargs)
422 423

        # 2. generate cache key
424
        cache_key = CacheKey(self._function_spec, input_args_with_spec,
425 426
                             input_kwargs_with_spec, self._class_instance,
                             **self._kwargs)
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

        # 3. check whether hit the cache or build a new program for the input arguments
        concrete_program, partial_program_layer = self._program_cache[cache_key]
        return concrete_program, partial_program_layer

    def get_traced_count(self):
        """
        Returns the number of traced programs for the decorated function.
        """
        return len(self._program_cache)

    @property
    def code(self):
        """
        Returns the source code of transformed static function for debugging.
        """
        static_func = convert_to_static(self._dygraph_function)
        source_code = func_to_source_code(static_func)
        return source_code

    @property
    def dygraph_function(self):
        """
        Returns the original decorated function.
        """
        return self._dygraph_function

    @property
    def concrete_program(self):
        """
        Returns recent ConcreteProgram instance of decorated function.
A
Aurelius84 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

        Examples:
            .. code-block:: python

                import paddle
                from paddle.jit import to_static
                from paddle.static import InputSpec

                paddle.disable_static()

                def foo(x, y):
                    z = x + y
                    return z
                
                # usage 1:
                decorated_foo = to_static(foo, input_spec=[InputSpec([10], name='x'), InputSpec([10], name='y')])
                print(decorated_foo.concrete_program)

                # usage 2:
                decorated_foo = to_static(foo)
                out_foo = decorated_foo(paddle.rand([10]), paddle.rand([10]))
                print(decorated_foo.concrete_program)
480
        """
481 482 483 484 485 486 487 488 489 490 491 492 493 494
        return self.concrete_program_specify_input_spec(input_spec=None)

    def concrete_program_specify_input_spec(self, input_spec=None):
        """
        Returns recent ConcreteProgram instance of decorated function while
        specifying input_spec. If the self._function_spec already has
        input_spce, it will check the compatibility of input input_spec and
        the self._function_spec.input_spec. If input input_spec=None, then
        this method uses self._function_spec.input_spec

        args:
            input_spec (list[InputSpec], optional): Describes the input of
                the translate function.
        """
495 496 497 498 499
        # if specific the `input_spec`, the length of program_cache will always 1,
        # else, return the last one.
        cached_program_len = len(self._program_cache)
        # If specific `input_spec`, apply convertion from dygraph layers into static Program.
        if cached_program_len == 0:
C
Chen Weihang 已提交
500 501 502
            desired_input_spec = input_spec
            if self._function_spec.input_spec is not None:
                if input_spec is not None and not input_specs_compatible(
503 504 505 506 507
                        flatten(input_spec),
                        flatten(self._function_spec.input_spec)):
                    raise ValueError(
                        "The `input_spec`: {} used to construct concrete_program is conflict with the `input_spec`: {} in `@paddle.jit.to_static`".
                        format(input_spec, self._function_spec.input_spec))
C
Chen Weihang 已提交
508 509 510
                # NOTE(chenweihang): we should always translated program based on the `input_spec`
                # decorated on forward if it is valid
                desired_input_spec = self._function_spec.input_spec
511 512 513 514
                if input_spec is not None:
                    logging_utils.warn(
                        "\n\nYou have specified `input_spec` both in function definition (higher priority) and `paddle.jit.save` (will be ignored.)\n\n\t Using: {}\n\n\t Ignore: {}\n".
                        format(desired_input_spec, input_spec))
515

C
Chen Weihang 已提交
516
            has_input_spec = (desired_input_spec is not None)
A
Aurelius84 已提交
517
            if has_input_spec:
C
Chen Weihang 已提交
518 519
                concrete_program, _ = self.get_concrete_program(
                    *desired_input_spec)
520
                return concrete_program
521
            else:
A
Aurelius84 已提交
522 523 524
                raise ValueError(
                    "No valid transformed program for {}.\n\t    Please specific `input_spec` in `@paddle.jit.to_static` or feed input tensor to call the decorated function at once.\n".
                    format(self._function_spec))
525 526
        # If more than one programs have been cached, return the recent converted program by default.
        elif cached_program_len > 1:
527
            logging_utils.warn(
528 529 530 531 532 533
                "Current {} has more than one cached programs: {}, the last traced progam will be return by default.".
                format(self._function_spec, cached_program_len))

        cache_key, (concrete_program,
                    partial_layer) = self._program_cache.last()
        return concrete_program
534

535 536 537 538 539 540 541 542 543 544 545
    @property
    def inputs(self):
        """
        Returns input tensors of recent converted static program.
        """
        concrete_program = self.concrete_program
        inputs = [
            var for var in flatten(concrete_program.inputs)
            if isinstance(var, framework.Variable)
        ]
        return inputs
546

547
    @property
548 549 550 551 552 553 554 555 556 557 558
    def outputs(self):
        """
        Returns output tensors of recent converted static program.
        """
        concrete_program = self.concrete_program
        outputs = [
            var for var in flatten(concrete_program.outputs)
            if isinstance(var, framework.Variable)
        ]

        return outputs
559

560
    @property
561 562 563 564 565 566 567
    def main_program(self):
        """
        Returns recent converted static main program.
        """
        concrete_program = self.concrete_program
        main_program = concrete_program.main_program
        return main_program
568

569 570 571
    @property
    def program_cache(self):
        return self._program_cache
572

573 574 575
    @property
    def function_spec(self):
        return self._function_spec
576 577


578 579 580 581 582 583 584 585 586 587 588 589 590
def _verify_init_in_dynamic_mode(class_instance):
    """
    Verifies the instance is initialized in dynamic mode.
    """
    if isinstance(class_instance, layers.Layer):
        if not class_instance._init_in_dynamic_mode:
            raise RuntimeError(
                " `paddle.jit.to_static` is only available in dynamic mode. Please call `paddle.disable_static()` before "
                "initializing your Layer class `{}` . Because parameters of Layer class should be initialized firstly "
                "in dynamic mode while applying transformation.".format(
                    class_instance))


591
class ConcreteProgram(object):
592 593 594

    __slots__ = [
        'inputs', 'outputs', 'main_program', "startup_program", "parameters",
595
        "function", 'kwargs'
596 597
    ]

598 599 600 601
    def __init__(self,
                 inputs,
                 outputs,
                 parameters,
602
                 function,
603
                 main_program,
604 605
                 startup_program=None,
                 **kwargs):
606 607 608
        self.inputs = inputs
        self.outputs = outputs
        self.main_program = main_program
609
        self.startup_program = startup_program
610
        self.parameters = parameters
611
        self.function = function
612
        self.kwargs = kwargs
613 614 615

    @staticmethod
    @switch_to_static_graph
616 617
    def from_func_spec(func_spec, input_spec, input_kwargs_spec, class_instance,
                       **kwargs):
618
        """
619 620
        Builds the main_program with specialized inputs and returns outputs
        of program as fetch_list.
621 622 623 624

        Args:
            func_spec(FunctionSpec): A FunctionSpec instance for decorated function.
            input_spec(list[InputSpec]): 
625
        """
626 627 628
        # verify the instance is initialized in imperative mode.
        _verify_init_in_dynamic_mode(class_instance)

629
        # Transforms dygraph function into static function and caches it.
630
        dygraph_function = func_spec.dygraph_function
631
        static_func = convert_to_static(dygraph_function)
632

633 634
        main_program, startup_program = framework.Program(), framework.Program()
        # Note: The random seed should be synchronized into cached program
635
        # if set in `fluid.dygraph_guard` because some ops rely on it, such as
636
        # `fluid.layers.dropout`.
637
        main_program.random_seed = framework.default_main_program().random_seed
638 639
        startup_program.random_seed = framework.default_startup_program(
        ).random_seed
640

641
        from paddle.fluid.dygraph.base import _switch_declarative_mode_guard_
642
        with framework.program_guard(main_program, startup_program):
643 644
            with _switch_declarative_mode_guard_(is_declarative=True):
                # 1. Adds `fluid.data` layers for input if needed
645 646
                inputs = func_spec.to_static_inputs_with_spec(input_spec,
                                                              main_program)
647 648
                _kwargs = func_spec.to_static_inputs_with_spec(
                    input_kwargs_spec, main_program)
649 650
                if class_instance:
                    inputs = tuple([class_instance] + list(inputs))
651

652
                # 2. Gets all ParamBases and buffered VarBases in the function
653 654
                all_parameters_and_buffers = _extract_indeed_params_buffers(
                    class_instance)
655 656

                # 3. Builds program only once and returns the output Variables.
657 658 659
                with param_guard(get_parameters(
                        class_instance, False)), param_guard(
                            get_buffers(class_instance, False)):
660
                    try:
661 662
                        if _kwargs:
                            outputs = static_func(*inputs, **_kwargs)
663 664
                        else:
                            outputs = static_func(*inputs)
665 666
                    except BaseException as e:
                        # NOTE: If e is raised in compile time, e should be attached to ERROR_DATA here.
667
                        error.attach_error_data(e)
668 669 670
                        error_data = getattr(e, error.ERROR_DATA, None)
                        if error_data:
                            error_data.raise_new_exception()
671 672
                        raise

673 674 675 676 677
                if outputs is not None:
                    need_wrap_into_list = not isinstance(outputs, (
                        tuple, list)) or len(outputs) == 1
                    if need_wrap_into_list:
                        outputs = [outputs]
678

679 680
        main_program = update_op_callstack_with_origin_info(main_program)

681 682 683
        return ConcreteProgram(
            inputs=inputs,
            outputs=outputs,
684
            parameters=all_parameters_and_buffers,
685
            function=dygraph_function,
686
            main_program=main_program,
687 688
            startup_program=startup_program,
            **kwargs)
689 690


691 692 693 694 695 696
def _extract_indeed_params_buffers(class_instance):
    """
    To filter not initialzed buffers.
    """
    params = list(get_parameters(class_instance).values())
    buffers = list(get_buffers(class_instance).values())
697
    buffers = [buffer for buffer in buffers if len(buffer.shape) != 0]
698 699 700 701

    return params + buffers


702 703 704 705
class ProgramCache(object):
    """
    Wrapper class for the program functions defined by dygraph function.
    """
706

707
    def __init__(self):
708
        # {hash_id : (concrete_program, partial_layer)}
709
        self._caches = collections.OrderedDict()
710

711 712 713
    def _build_once(self, cache_key):
        concrete_program = ConcreteProgram.from_func_spec(
            func_spec=cache_key.function_spec,
714 715
            input_spec=cache_key.input_args_with_spec,
            input_kwargs_spec=cache_key.input_kwargs_with_spec,
716 717
            class_instance=cache_key.class_instance,
            **cache_key.kwargs)
718
        return concrete_program, partial_program_from(concrete_program)
719

720
    def __getitem__(self, item):
721 722 723
        if not isinstance(item, CacheKey):
            raise ValueError('type(item) should be CacheKey, but received %s' %
                             type_name(item))
724 725 726
        item_id = hash(item)
        if item_id not in self._caches:
            self._caches[item_id] = self._build_once(item)
727 728 729
            # Note: raise warnings if number of traced program is more than `max_tracing_count`
            current_tracing_count = len(self._caches)
            if current_tracing_count > MAX_TRACED_PROGRAM_COUNT:
730
                logging_utils.warn(
731 732 733 734
                    "Current traced program number: {} > `max_tracing_count`:{}. Too much cached programs will bring expensive overhead. "
                    "The reason may be: (1) passing tensors with different shapes, (2) passing python objects instead of tensors.".
                    format(current_tracing_count, MAX_TRACED_PROGRAM_COUNT))

735
        return self._caches[item_id]
736

737
    def get_program(self, item):
738
        if not isinstance(item, CacheKey):
739 740
            raise ValueError(
                "Input item's type should be FunctionSpec, but received %s" %
741
                type_name(item))
742 743
        item_id = hash(item)
        if item_id not in self._caches:
744
            raise RuntimeError(
745
                "Failed to find program for input item, please decorate input function by `@paddle.jit.to_static`."
746
            )
747
        return self._caches[item_id]
748

749 750 751 752 753 754
    def last(self):
        assert len(
            self._caches) >= 1, "No valid cached program in ProgramCache."
        key = next(reversed(self._caches.keys()))
        return key, self._caches[key]

755 756 757 758
    def __len__(self):
        return len(self._caches)

    def concrete_programs(self):
759
        return [cp for key, (cp, _) in six.iteritems(self._caches)]
760

761

762 763
def synchronized(func):
    func.__lock__ = threading.Lock()
764

765 766 767
    def lock_func(*args, **kwargs):
        with func.__lock__:
            return func(*args, **kwargs)
768

769
    return lock_func
770 771


772
class ProgramTranslator(object):
773
    """
774 775 776 777 778 779 780 781 782 783 784 785
    Class to translate dygraph function into static graph function. The object
    of this class is a singleton.

    Args:
        None.

    Returns:
        ProgramTranslator: the singleton object.

    Examples:
        .. code-block:: python

786
            import paddle
787

788 789 790
            # Two methods get same object because ProgramTranslator is a singleton
            paddle.jit.ProgramTranslator()
            paddle.jit.ProgramTranslator.get_instance()
791

792 793
    """

794
    _singleton_lock = threading.Lock()
795 796 797 798 799 800
    _instance = None

    @synchronized
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = object.__new__(cls, *args, **kwargs)
801
            cls._instance._initialized = False
802 803 804 805 806
        return cls._instance

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
807 808
            with cls._singleton_lock:
                cls._instance = cls()
809 810 811 812 813
        return cls._instance

    @classmethod
    def reset(cls):
        if cls._instance is not None:
814
            cls._instance._initialized = False
815 816
            cls._instance.__init__()

817
    def __init__(self):
818
        # To make sure that calls __init__ only once.
819
        if self._initialized:
820
            return
821 822
        self._initialized = True
        self._program_cache = ProgramCache()
823
        self.enable_to_static = True
824

825
    def enable(self, enable_to_static):
826
        """
827
        Enable or disable the converting from imperative to static graph by
828 829 830
        ProgramTranslator globally.

        Args:
831
            enable_to_static (bool): True or False to enable or disable converting to static.
832 833 834 835 836 837 838

        Returns:
            None.

        Examples:
            .. code-block:: python

839
                import paddle
840 841


842 843 844 845 846 847 848
                @paddle.jit.to_static
                def func(x):
                    if paddle.mean(x) > 0:
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v
849

850 851 852 853 854 855

                prog_trans = paddle.jit.ProgramTranslator()
                prog_trans.enable(False)

                x = paddle.ones([1, 2])
                # ProgramTranslator is disabled so the func is run in dygraph
856
                print(func(x))  # [[0. 0.]]
L
liym27 已提交
857

858
        """
859
        check_type(enable_to_static, "enable_to_static", bool,
860
                   "ProgramTranslator.enable")
861
        self.enable_to_static = enable_to_static
862

863 864
    def get_output(self, dygraph_func, *args, **kwargs):
        """
865
        Returns the output dygraph Tensor for dygraph function. The dygraph
866
        function will be translated into static graph function so the under
867
        beneath numerical result will be calculated by static graph mode.
868 869 870

        Args:
            dygraph_func (callable): the dygraph function.
871 872
            *args (tuple): the input argument of dygraph_func.
            **kwargs (dict): the input argument of dygraph_func.
873 874

        Returns:
875
            Tensor or tuple of Tensors: the dygraph Tensor containing digital result.
876 877 878 879

        Examples:
            .. code-block:: python

880 881
                import paddle

882 883

                def func(x):
884
                    if paddle.mean(x) > 0:
885 886 887 888 889 890
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v


891 892 893 894
                prog_trans = paddle.jit.ProgramTranslator()

                x = paddle.ones([1, 2])
                x_v = prog_trans.get_output(func, x)
895
                print(x_v)  # [[0. 0.]]
896

897
        """
898 899 900
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_output"
901

902
        if not self.enable_to_static:
903 904
            # Here calls `warnings.warn` but not `logging_utils.warn` because by default warnings.warn(message)
            # will show up **only once**.
905
            logging_utils.warn(
906 907 908 909
                "The ProgramTranslator.get_output doesn't work when setting ProgramTranslator.enable to False. "
                "We will just return dygraph output. "
                "Please call ProgramTranslator.enable(True) if you would like to get static output."
            )
910
            return dygraph_func(*args, **kwargs)
911
        try:
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
            function_spec = FunctionSpec(dygraph_func)
            cache_key = CacheKey.from_func_and_args(function_spec, args, kwargs,
                                                    getattr(dygraph_func,
                                                            '__self__', None))
            _, partial_program_layer = self._program_cache[cache_key]

            if args and isinstance(args[0], layers.Layer):
                # Synchronize self.training attribute.
                partial_program_layer.training = args[0].training
                args = args[1:]
            try:
                return partial_program_layer(args)
            except BaseException as e:
                # NOTE:
                # 1. If e is raised in compile time, e should have been attached to ERROR_DATA before;
                # 2. If e raised in runtime, e should be attached to ERROR_DATA here.
                if not hasattr(e, error.ERROR_DATA):
                    # runtime error
                    error.attach_error_data(e, in_runtime=True)
                raise
932
        except BaseException as e:
933 934 935 936 937 938 939 940
            error_data = getattr(e, error.ERROR_DATA, None)
            if error_data:
                error_data.raise_new_exception()
            else:
                logging_utils.warn(
                    "Please file an issue at 'https://github.com/PaddlePaddle/Paddle/issues'"
                    " if you can't handle this {} yourself.".format(type(e)))
                raise e
941 942 943

    def get_func(self, dygraph_func):
        """
944 945 946 947 948 949 950 951 952 953 954
        Returns a callable function which converts imperative dygraph APIs of
        the input dygraph_func into declarative net-building APIs, which means
        it doesn't return immediate digital result as get_output does.
        Users should handle Program and Executor by themselves.

        Args:
            dygraph_func (callable): the dygraph function.

        Returns:
            callable: converting imperative dygraph APIs into declarative
            net-building APIs.
955 956 957 958

        Examples:
            .. code-block:: python

959 960
                import paddle

961 962

                def func(x):
963
                    if paddle.mean(x) > 0:
964 965 966 967 968 969
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v


970
                prog_trans = paddle.jit.ProgramTranslator()
971 972 973
                static_func = prog_trans.get_func(func)
                print(callable(static_func)) # True

974
        """
975 976 977
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_func"
978

979
        if not self.enable_to_static:
980
            logging_utils.warn(
981 982 983
                "The ProgramTranslator.get_func doesn't work when setting ProgramTranslator.enable to False. We will "
                "just return dygraph output. Please call ProgramTranslator.enable(True) if you would like to get static output."
            )
984
            return dygraph_func
985

986
        static_func = convert_to_static(dygraph_func)
987 988
        return static_func

989 990
    def get_program(self, dygraph_func, *args, **kwargs):
        """
991
        Returns the translated static program and input/output Tensors from
992 993 994 995
        dygraph function. The users can use the program to run by executor.

        Args:
            dygraph_func (callable): the dygraph function.
996 997
            *args (tuple): the input argument of dygraph_func.
            **kwargs (dict): the input argument of dygraph_func.
998 999 1000

        Returns:
            tuple of (main_program, startup_program, inputs, outputs) whose
1001
            types are (Program, Program, list of Tensors, list of Tensors).
1002 1003
            main_program: the converted main program.
            startup_program: the converted startup program.
1004 1005
            inputs: list of input Tensors which need to be fed.
            outputs: list of output Tensors which users can fetch.
1006 1007 1008 1009

        Examples:
            .. code-block:: python

1010 1011
                import paddle

1012 1013

                def func(x):
1014
                    if paddle.mean(x) > 0:
1015 1016 1017 1018 1019 1020
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v


1021 1022
                prog_trans = paddle.jit.ProgramTranslator()
                x = paddle.ones([1, 2])
1023 1024
                main_prog, start_prog, inputs, outputs = prog_trans.get_program(func, x)
                print([i.name for i in inputs])
1025
                # [u'generated_tensor_0'] the feed input Tensor name representing x
1026
                print([o.name for o in outputs])
1027
                # [u'_generated_var_4'] the fetch output Tensor name representing x_v        
1028

1029
        """
1030 1031 1032
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_program"
1033

1034
        if not self.enable_to_static:
1035
            logging_utils.warn(
1036 1037 1038 1039
                "The ProgramTranslator.get_program doesn't work when setting ProgramTranslator.enable to False."
                "We will just return dygraph output. "
                "Please call ProgramTranslator.enable(True) if you would like to get static output."
            )
1040
            return dygraph_func(*args, **kwargs)
1041

1042 1043 1044 1045 1046 1047
        function_spec = FunctionSpec(dygraph_func)
        cache_key = CacheKey.from_func_and_args(function_spec, args, kwargs,
                                                getattr(dygraph_func,
                                                        '__self__', None))
        concrete_program, partial_program_layer = self._program_cache[cache_key]

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        # Note: concrete_program hold all input/output infos include non-Variable
        input_vars = [
            var for var in concrete_program.inputs
            if isinstance(var, framework.Variable)
        ]
        output_vars = [
            var for var in concrete_program.outputs
            if isinstance(var, framework.Variable)
        ]

1058 1059
        return concrete_program.main_program, \
               concrete_program.startup_program, \
1060 1061
               input_vars, \
               output_vars
1062

1063 1064
    def get_code(self, dygraph_func):
        """
1065 1066 1067 1068 1069 1070
        Returns the translated static function string code from dygraph function.

        Args:
            dygraph_func (callable): the dygraph function.

        Returns:
1071 1072 1073 1074 1075
            str: the string code of translated static function.

        Examples:
            .. code-block:: python

1076 1077 1078 1079 1080 1081 1082 1083 1084
                import paddle


                def func(x):
                    if paddle.mean(x) > 0:
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v
1085 1086


1087
                prog_trans = paddle.jit.ProgramTranslator()
1088

1089 1090
                code = prog_trans.get_code(func)
                print(type(code)) # <class 'str'>
1091

1092
        """
1093 1094 1095
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_code"
1096
        # Gets AST from dygraph function
1097 1098 1099

        unwrap_func = unwrap(dygraph_func)
        raw_code = inspect.getsource(unwrap_func)
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        code = textwrap.dedent(raw_code)
        root = gast.parse(code)

        # Transform AST
        dygraph_to_static = DygraphToStaticAst()
        root_wrapper = dygraph_to_static.get_static_ast(root)

        # Get source_code
        source_code = ast_to_source_code(root_wrapper.node)
        return source_code

1111
    def get_program_cache(self):
1112
        """
1113 1114 1115 1116 1117 1118 1119 1120 1121
        Returns the ProgramCache instance. This method is used by PaddlePaddle
        developers to manage program cache in ProgramTranslator. Normal users
        don't have to call this method.

        Returns:
            ProgramCache: ProgramCache instance of ProgramTranslator.

        Examples:
            .. code-block:: python
1122

1123
                import paddle
1124

1125
                prog_trans = paddle.jit.ProgramTranslator()
1126 1127
                prog_cache = prog_trans.get_program_cache()

1128
        """
1129
        return self._program_cache