program_translator.py 34.9 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
import gast
17
import collections
18
import logging
19
import inspect
20
import six
21 22
import textwrap
import threading
23 24 25 26
import warnings

import gast
from paddle.fluid import framework
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 34 35 36 37 38 39
from paddle.fluid.dygraph.dygraph_to_static.error import ERROR_DATA
from paddle.fluid.dygraph.dygraph_to_static.error import attach_error_data
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 type_name
43
from paddle.fluid.dygraph.dygraph_to_static.utils import unwrap
44 45 46
from paddle.fluid.dygraph.dygraph_to_static.utils import make_hashable
from paddle.fluid.dygraph.dygraph_to_static.function_spec import FunctionSpec
from paddle.fluid.dygraph.dygraph_to_static.function_spec import get_buffers, get_parameters
47
from paddle.fluid.wrapped_decorator import signature_safe_contextmanager
48

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

51 52 53 54
# 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

55 56 57 58 59 60 61

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

    def __init__(self):
62 63 64 65 66
        # 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()
67

68 69 70 71 72 73
    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)
74 75

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

        return static_func

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    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.
102
        func = unwrap(func)
103
        source_code = func_to_source_code(func)
104 105 106 107 108

        # 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
109 110 111 112
        if source_code in self._code_to_ast_caches:
            root_wrapper = self._code_to_ast_caches[source_code]
        else:
            root = gast.parse(source_code)
113
            root = attach_origin_info(root, func)
114 115
            root_wrapper = self._dygraph_to_static.get_static_ast(root)
            self._code_to_ast_caches[source_code] = root_wrapper
116

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

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

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


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


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

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


143 144 145 146
class CacheKey(object):
    """
    Cached key for ProgramCache.
    """
147

148
    __slots__ = ['function_spec', 'input_with_spec', 'class_instance']
149

150 151 152
    def __init__(self, function_spec, input_with_spec, class_instance):
        """
        Initializes a cache key.
153

154 155 156 157
        Args:
            functions_spec(FunctionSpec): a FunctionSpec instance of decorated function.
            input_with_spec(list[InputSpec]): actual inputs with some arguments replaced by InputSpec.
            class_instance(object): a instance of class `Layer`.
158
        """
159 160 161 162 163 164
        self.function_spec = function_spec
        self.input_with_spec = input_with_spec
        self.class_instance = class_instance

    @classmethod
    def from_func_and_args(cls, function_spec, args, kwargs, class_instance):
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
        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:]
        # 2. convert tensor and numpy array into InputSpec 
        _args, _kwargs = function_spec.unified_args_and_kwargs(args, kwargs)
        input_with_spec = function_spec.args_to_input_spec(_args, _kwargs)

        # 3. check whether hit the cache or build a new program for the input arguments
        return CacheKey(function_spec, input_with_spec, class_instance)

    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),
                     make_hashable(self.input_with_spec, error_msg),
                     self.class_instance))

    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):
        return "id(function_spec): {}, input_with_spec: {}, class_instance: {}".format(
            id(self.function_spec), self.input_with_spec, self.class_instance)


def unwrap_decorators(func):
    """
    Unwraps a decorated function and returns the decorator list and inner target.
    """
    decorators = []
    cur = func
    while True:
        if isinstance(cur, StaticLayer):
            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)
214
            else:
215 216 217 218
                cur = cur.dygraph_function
        else:
            break
    return decorators, cur
219

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

class StaticLayer(object):
    """
    Wrapper class to Manage program conversion of decorated function.

    """

    def __init__(self, function, input_spec=None):
        """
        Initializes a `StaticLayer`.

        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.
        """
        # 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()
        # Note: Hold a reference to ProgramTranslator for switching `enable_declarative`.
        self._program_trans = ProgramTranslator()

    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__`
        to parse the class instance correctly instead of the `StaticLayer` instance.
        """
        self._class_instance = instance
        return self

    def __call__(self, *args, **kwargs):
276
        """
277 278 279 280 281 282 283 284
        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.
285
        """
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
        # 1. call dygraph function directly if not enable `declarative`
        if not self._program_trans.enable_declarative:
            warnings.warn(
                "The decorator '@paddle.jit.to_static' doesn't work when setting ProgramTranslator.enable=False. "
                "We will just return dygraph output.")
            return self._call_dygraph_function(*args, **kwargs)

        # 2. trace ops from dygraph layers and cache the generated program.
        args, kwargs = self._function_spec.unified_args_and_kwargs(args, kwargs)
        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

            # 4. return outputs.
            return partial_program_layer(args)
        except Exception as e:
            if not hasattr(e, ERROR_DATA):
                # runtime error
                attach_error_data(e, in_runtime=True)
            error_data = getattr(e, ERROR_DATA, None)
            if error_data:
                new_exception = error_data.create_exception()
                if six.PY3:
                    # NOTE(liym27):
                    # 1. Why `raise new_exception from None`?
                    #   In Python 3, by default, an new exception is raised with trace information of the caught exception.
                    #   This only raises new_exception and hides unwanted implementation details from tracebacks of the
                    #   caught exception.
                    # 2. Use exec to bypass syntax error checking in Python 2.

                    six.exec_("raise new_exception from None")
                else:
                    raise new_exception
323
            else:
324
                raise
325

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    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.
        """
        # 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)
        input_with_spec = self._function_spec.args_to_input_spec(args, kwargs)

        # 2. generate cache key
        cache_key = CacheKey(self._function_spec, input_with_spec,
                             self._class_instance)

        # 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.
        """
        # 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:
            if len(self._function_spec.flat_input_spec) > 0:
                input_spec = self._function_spec.input_spec
                concrete_program, _ = self.get_concrete_program(*input_spec)
                return concrete_program
406
            else:
407 408 409 410 411 412 413 414 415 416 417
                raise ValueError("No valid transformed program for {}".format(
                    self._function_spec))
        # If more than one programs have been cached, return the recent converted program by default.
        elif cached_program_len > 1:
            logging.warning(
                "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
418

419 420 421 422 423 424 425 426 427 428 429
    @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
430

431
    @property
432 433 434 435 436 437 438 439 440 441 442
    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
443

444
    @property
445 446 447 448 449 450 451
    def main_program(self):
        """
        Returns recent converted static main program.
        """
        concrete_program = self.concrete_program
        main_program = concrete_program.main_program
        return main_program
452

453 454 455
    @property
    def program_cache(self):
        return self._program_cache
456

457 458 459
    @property
    def function_spec(self):
        return self._function_spec
460 461


462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
# Flag that indicates whether running code under `@declarative`
_in_declarative_mode_ = False


def in_declarative_mode():
    """
    Return a bool value that indicates whether running code under `@declarative`

    """
    return _in_declarative_mode_


@signature_safe_contextmanager
def _switch_declarative_mode_guard_(is_declarative=True):

    global _in_declarative_mode_
    original_val = _in_declarative_mode_
    _in_declarative_mode_ = is_declarative
    yield
    _in_declarative_mode_ = original_val


484
class ConcreteProgram(object):
485 486 487 488 489 490

    __slots__ = [
        'inputs', 'outputs', 'main_program', "startup_program", "parameters",
        "function"
    ]

491 492 493 494
    def __init__(self,
                 inputs,
                 outputs,
                 parameters,
495
                 function,
496
                 main_program,
497
                 startup_program=None):
498 499 500
        self.inputs = inputs
        self.outputs = outputs
        self.main_program = main_program
501
        self.startup_program = startup_program
502
        self.parameters = parameters
503
        self.function = function
504 505 506

    @staticmethod
    @switch_to_static_graph
507
    def from_func_spec(func_spec, input_spec, class_instance):
508
        """
509 510
        Builds the main_program with specialized inputs and returns outputs
        of program as fetch_list.
511 512 513 514

        Args:
            func_spec(FunctionSpec): A FunctionSpec instance for decorated function.
            input_spec(list[InputSpec]): 
515
        """
516
        # Transforms dygraph function into static function and caches it.
517
        dygraph_function = func_spec.dygraph_function
518
        static_func = convert_to_static(dygraph_function)
519

520 521
        main_program, startup_program = framework.Program(), framework.Program()
        # Note: The random seed should be synchronized into cached program
522
        # if set in `fluid.dygraph_guard` because some ops rely on it, such as
523
        # `fluid.layers.dropout`.
524
        main_program.random_seed = framework.default_main_program().random_seed
525 526
        startup_program.random_seed = framework.default_startup_program(
        ).random_seed
527

528
        with framework.program_guard(main_program, startup_program):
529 530
            with _switch_declarative_mode_guard_(is_declarative=True):
                # 1. Adds `fluid.data` layers for input if needed
531 532 533 534
                inputs = func_spec.to_static_inputs_with_spec(input_spec,
                                                              main_program)
                if class_instance:
                    inputs = tuple([class_instance] + list(inputs))
535

536
                # 2. Gets all ParamBases and buffered VarBases in the function
537 538 539
                all_parameters_and_buffers = list(
                    get_parameters(class_instance).values()) + list(
                        get_buffers(class_instance).values())
540 541

                # 3. Builds program only once and returns the output Variables.
542 543 544
                with param_guard(get_parameters(
                        class_instance, False)), param_guard(
                            get_buffers(class_instance, False)):
545 546 547 548 549 550 551
                    try:
                        outputs = static_func(*inputs)
                    except BaseException as e:
                        # NOTE: If e is raised in compile time, e should be attached to ERROR_DATA here.
                        attach_error_data(e)
                        raise

552 553 554
                if not isinstance(outputs,
                                  (tuple, list)) and outputs is not None:
                    outputs = [outputs]
555

556 557
        main_program = update_op_callstack_with_origin_info(main_program)

558 559 560
        return ConcreteProgram(
            inputs=inputs,
            outputs=outputs,
561
            parameters=all_parameters_and_buffers,
562
            function=dygraph_function,
563
            main_program=main_program,
564
            startup_program=startup_program)
565 566


567 568 569 570
class ProgramCache(object):
    """
    Wrapper class for the program functions defined by dygraph function.
    """
571

572
    def __init__(self):
573
        self._caches = collections.OrderedDict()
574

575 576 577 578 579
    def _build_once(self, cache_key):
        concrete_program = ConcreteProgram.from_func_spec(
            func_spec=cache_key.function_spec,
            input_spec=cache_key.input_with_spec,
            class_instance=cache_key.class_instance)
580
        return concrete_program, partial_program_from(concrete_program)
581

582
    def __getitem__(self, item):
583 584 585 586
        if not isinstance(item, CacheKey):
            raise ValueError('type(item) should be CacheKey, but received %s' %
                             type_name(item))

587 588
        if item not in self._caches:
            self._caches[item] = self._build_once(item)
589 590 591 592 593 594 595 596
            # 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:
                logging.warning(
                    "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))

597
        return self._caches[item]
598

599
    def get_program(self, item):
600
        if not isinstance(item, CacheKey):
601 602
            raise ValueError(
                "Input item's type should be FunctionSpec, but received %s" %
603
                type_name(item))
604 605
        if item not in self._caches:
            raise RuntimeError(
606
                "Failed to find program for input item, please decorate input function by `@paddle.jit.to_static`."
607 608 609
            )
        return self._caches[item]

610 611 612 613 614 615
    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]

616 617 618 619 620 621
    def __len__(self):
        return len(self._caches)

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

622

623 624
def synchronized(func):
    func.__lock__ = threading.Lock()
625

626 627 628
    def lock_func(*args, **kwargs):
        with func.__lock__:
            return func(*args, **kwargs)
629

630
    return lock_func
631 632


633
class ProgramTranslator(object):
634
    """
635 636 637 638 639 640 641 642 643 644 645 646 647 648
    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

        import paddle.fluid as fluid

649
        # Two methods get same object because ProgramTranslator is a singleton
650 651 652
        fluid.dygraph.ProgramTranslator()
        fluid.dygraph.ProgramTranslator.get_instance()

653 654
    """

655
    _singleton_lock = threading.Lock()
656 657 658 659 660 661
    _instance = None

    @synchronized
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = object.__new__(cls, *args, **kwargs)
662
            cls._instance._initialized = False
663 664 665 666 667
        return cls._instance

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
668 669
            with cls._singleton_lock:
                cls._instance = cls()
670 671 672 673 674
        return cls._instance

    @classmethod
    def reset(cls):
        if cls._instance is not None:
675
            cls._instance._initialized = False
676 677
            cls._instance.__init__()

678
    def __init__(self):
679
        # To make sure that calls __init__ only once.
680
        if self._initialized:
681
            return
682 683
        self._initialized = True
        self._program_cache = ProgramCache()
684 685
        self.enable_declarative = True

686
    def enable(self, enable_declarative):
687 688 689 690 691
        """
        Enable or disable the converting from imperative to declarative by
        ProgramTranslator globally.

        Args:
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
            enable_declarative (bool): True or False to enable or disable declarative.

        Returns:
            None.

        Examples:
            .. code-block:: python

            import paddle.fluid as fluid
            import numpy as np

            @fluid.dygraph.jit.declarative
            def func(x):
                x = fluid.dygraph.to_variable(x)
                if fluid.layers.mean(x) > 0:
                    x_v = x - 1
                else:
                    x_v = x + 1
                return x_v

            prog_trans = fluid.dygraph.ProgramTranslator()
            prog_trans.enable(False)

            x = np.ones([1, 2])
L
liym27 已提交
716
            # The declarative is disabled so the func is run in dygraph
717 718
            with fluid.dygraph.guard():
                print(func(x).numpy()) # [[2. 2.]]
L
liym27 已提交
719

720
        """
721 722
        check_type(enable_declarative, "enable_declarative", bool,
                   "ProgramTranslator.enable")
723
        self.enable_declarative = enable_declarative
724

725 726
    def get_output(self, dygraph_func, *args, **kwargs):
        """
727 728 729 730 731 732
        Returns the output dygraph VarBase for dygraph function. The dygraph
        function will be translated into static graph function so the under
        beneath numerical result will be calculated by declarative mode.

        Args:
            dygraph_func (callable): the dygraph function.
L
liym27 已提交
733
            *args, **kwargs : the input argument of dygraph_func.
734 735 736 737

        Returns:
            VarBase or tuple of VarBase: the dygraph VarBase containing digital
                result.
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754

        Examples:
            .. code-block:: python

                import paddle.fluid as fluid
                import numpy as np

                def func(x):
                    x = fluid.dygraph.to_variable(x)
                    if fluid.layers.mean(x) > 0:
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v

                prog_trans = fluid.dygraph.ProgramTranslator()

755 756 757 758
                with fluid.dygraph.guard():
                    x = np.ones([1, 2])
                    x_v = prog_trans.get_output(func, x)
                    print(x_v.numpy()) # [[0. 0.]]
759

760
        """
761 762 763
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_output"
764
        if not self.enable_declarative:
765
            warnings.warn(
766 767
                "The ProgramTranslator.get_output doesn't work when setting ProgramTranslator.enable = False. "
                "We will just return dygraph output.")
768 769
            return dygraph_func(*args, **kwargs)

770 771 772 773 774
        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]
775 776

        if args and isinstance(args[0], layers.Layer):
777 778
            # Synchronize self.training attribute.
            partial_program_layer.training = args[0].training
779
            args = args[1:]
780 781 782 783 784 785 786 787 788
        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_DATA):
                # runtime error
789
                attach_error_data(e, in_runtime=True)
790
            raise
791 792 793

    def get_func(self, dygraph_func):
        """
794 795 796 797 798 799 800 801 802 803 804
        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.
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

        Examples:
            .. code-block:: python

                import paddle.fluid as fluid
                import numpy as np

                def func(x):
                    x = fluid.dygraph.to_variable(x)
                    if fluid.layers.mean(x) > 0:
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v

                prog_trans = fluid.dygraph.ProgramTranslator()

                static_func = prog_trans.get_func(func)
                print(callable(static_func)) # True

825
        """
826 827 828
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_func"
829
        if not self.enable_declarative:
830
            warnings.warn(
831
                "The ProgramTranslator.get_func doesn't work when setting ProgramTranslator.enable=False. We will "
832
                "just return dygraph output.")
833
            return dygraph_func
834

835
        static_func = convert_to_static(dygraph_func)
836 837
        return static_func

838 839
    def get_program(self, dygraph_func, *args, **kwargs):
        """
840
        Returns the translated static program and input/output variables from
841 842 843 844 845 846 847 848 849 850 851 852 853
        dygraph function. The users can use the program to run by executor.

        Args:
            dygraph_func (callable): the dygraph function.
            *args, **kwargs : the input argument of dygraph_func.

        Returns:
            tuple of (main_program, startup_program, inputs, outputs) whose
            types are (Program, Program, list of Variable, list of Variable).
            main_program: the converted main program.
            startup_program: the converted startup program.
            inputs: list of input Variables which need to be fed.
            outputs: list of output Variables which users can fetch.
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873

        Examples:
            .. code-block:: python

                import paddle.fluid as fluid
                import numpy as np

                def func(x):
                    x = fluid.dygraph.to_variable(x)
                    if fluid.layers.mean(x) > 0:
                        x_v = x - 1
                    else:
                        x_v = x + 1
                    return x_v

                prog_trans = fluid.dygraph.ProgramTranslator()

                x = np.ones([1, 2])
                main_prog, start_prog, inputs, outputs = prog_trans.get_program(func, x)
                print([i.name for i in inputs])
874
                # ['feed_0'] the feed input variable name representing x
875 876 877
                print([o.name for o in outputs])
                # ['_generated_var_4'] the fetch output variable name representing x_v        

878
        """
879 880 881
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_program"
882
        if not self.enable_declarative:
883
            warnings.warn(
884 885
                "The ProgramTranslator.get_program doesn't work when setting ProgramTranslator.enable=False."
                "We will just return dygraph output.")
886
            return dygraph_func(*args, **kwargs)
887

888 889 890 891 892 893
        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]

894 895 896 897 898 899 900 901 902 903
        # 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)
        ]

904 905
        return concrete_program.main_program, \
               concrete_program.startup_program, \
906 907
               input_vars, \
               output_vars
908

909 910
    def get_code(self, dygraph_func):
        """
911 912 913 914 915 916
        Returns the translated static function string code from dygraph function.

        Args:
            dygraph_func (callable): the dygraph function.

        Returns:
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
            str: the string code of translated static function.

        Examples:
            .. code-block:: python

            import paddle.fluid as fluid
            import numpy as np

            def func(x):
                x = fluid.dygraph.to_variable(x)
                if fluid.layers.mean(x) > 0:
                    x_v = x - 1
                else:
                    x_v = x + 1
                return x_v

            prog_trans = fluid.dygraph.ProgramTranslator()

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

938
        """
939 940 941
        assert callable(
            dygraph_func
        ), "Input dygraph_func is not a callable in ProgramTranslator.get_code"
942
        # Gets AST from dygraph function
943 944 945

        unwrap_func = unwrap(dygraph_func)
        raw_code = inspect.getsource(unwrap_func)
946 947 948 949 950 951 952 953 954 955 956
        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

957
    def get_program_cache(self):
958
        """
959 960 961 962 963 964 965 966 967
        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
968

969 970 971 972 973
                import paddle.fluid as fluid

                prog_trans = fluid.dygraph.ProgramTranslator()
                prog_cache = prog_trans.get_program_cache()

974
        """
975
        return self._program_cache