ast_transformer.py 6.4 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 18 19 20
# gast is a generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST).
# It provides a compatibility layer between the AST of various Python versions,
# as produced by ast.parse from the standard ast module.
# See details in https://github.com/serge-sans-paille/gast/
21
import gast
22 23
import inspect
import textwrap
24

25
from paddle.fluid.dygraph.dygraph_to_static.basic_api_transformer import BasicApiTransformer
26 27
from paddle.fluid.dygraph.dygraph_to_static.break_continue_transformer import BreakContinueTransformer
from paddle.fluid.dygraph.dygraph_to_static.ifelse_transformer import IfElseTransformer
28
from paddle.fluid.dygraph.dygraph_to_static.list_transformer import ListTransformer
29
from paddle.fluid.dygraph.dygraph_to_static.loop_transformer import LoopTransformer
30
from paddle.fluid.dygraph.dygraph_to_static.tensor_shape_transformer import TensorShapeTransformer
31
from paddle.fluid.dygraph.dygraph_to_static.call_transformer import CallTransformer
32
from paddle.fluid.dygraph.dygraph_to_static.print_transformer import PrintTransformer
33

34
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import StaticAnalysisVisitor
35
from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_func
36
from paddle.fluid.dygraph.dygraph_to_static.utils import get_attribute_full_name
37

38
__all__ = ['DygraphToStaticAst', 'convert_to_static']
39

40
DECORATOR_NAMES = ['declarative', 'dygraph_to_static_func']
41 42


43
class DygraphToStaticAst(gast.NodeTransformer):
44 45 46 47 48
    """
    Main class to transform Dygraph to Static Graph
    """

    def get_static_ast(self, root):
49
        # save root for some analysis may need global AST
50
        self.root = root
51 52 53
        self.static_analysis_visitor = StaticAnalysisVisitor(root)
        self.static_analysis_root = self.static_analysis_visitor.get_node_wrapper_root(
        )
54
        self.decorate_func_name = None
55
        self.arg_name_to_idx = {}
56 57 58
        self.transfer_from_node_type(self.static_analysis_root)
        return self.static_analysis_root

59
    def transfer_from_node_type(self, node_wrapper):
60
        # Generic transformation
61
        self.visit(node_wrapper.node)
62

63 64 65
        # Transform basic api of dygraph to static graph and get feed_name_to_arg_name
        basic_api_trans = BasicApiTransformer(node_wrapper)
        basic_api_trans.transform()
66
        self.feed_name_to_arg_name = basic_api_trans.get_feed_name_to_arg_id()
67

68 69 70 71
        # Transform Tensor.shape into fluid.layers.shape(Tensor)
        TensorShapeTransformer(node_wrapper).transform()

        # Transform list used in control flow
72
        ListTransformer(node_wrapper).transform()
73

74 75
        # Transform break/continue in loops
        BreakContinueTransformer(node_wrapper).transform()
76

77
        # Transform for loop and while loop
78
        LoopTransformer(node_wrapper).transform()
79

80 81 82
        # Transform all if/else statement of Dygraph into Static Graph.
        IfElseTransformer(node_wrapper).transform()

83 84 85
        # Transform all python print statement
        PrintTransformer(node_wrapper).transform()

86 87 88
        # Transform call recursively
        CallTransformer(node_wrapper).transform()

89 90 91
    def visit_FunctionDef(self, node):
        if self.decorate_func_name is None:
            self.decorate_func_name = node.name
92 93
            for idx, arg in enumerate(node.args.args):
                self.arg_name_to_idx[arg.id] = idx
94

95 96 97
        self.generic_visit(node)
        # Remove the decorated name of dygraph_to_static
        if hasattr(node, 'decorator_list'):
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            decorator_list = []
            for d in node.decorator_list:
                if isinstance(d, gast.Name) and d.id not in DECORATOR_NAMES:
                    raise NotImplementedError(
                        "ProgramTranslator hasn't implemented multiple decorators. Please remove "
                        + d.id + " in " + self.decorate_func_name)
                if isinstance(d, gast.Attribute):
                    full_attribute_name = get_attribute_full_name(d)
                    has_translate_decorator = False
                    for deco in DECORATOR_NAMES:
                        if deco in full_attribute_name:
                            has_translate_decorator = True
                            break
                    if not has_translate_decorator:
                        raise NotImplementedError(
                            "ProgramTranslator hasn't implemented multiple decorators. Please remove "
                            + full_attribute_name + " in " +
                            self.decorate_func_name)
116 117 118 119 120 121 122 123 124 125 126
            node.decorator_list = decorator_list
        return node

    def get_module_name(self):
        """
        Return the main function name which will be used as module name
        in ast_to_func.
        """
        # Should consider BaseAPITransformer which add new module name in Yamei's PR.
        assert self.decorate_func_name, "decorate_func_name shall not be None."
        return self.decorate_func_name
127

128 129 130 131 132 133
    def get_feed_name_to_idx(self):
        feed_name_to_idx = {}
        for feed_name, arg_name in self.feed_name_to_arg_name.items():
            feed_name_to_idx[feed_name] = self.arg_name_to_idx.get(arg_name)
        return feed_name_to_idx

134

135 136 137 138 139
def convert_to_static(dyfunc):
    """
    Converts dygraph function into static function.
    """
    # Get AST from dygraph function
140 141 142
    # Note: In Python2, it will raise OSError when inspect function
    # with decorator directly and dyfunc.__wrapped__ holds the actual function.
    dyfunc = getattr(dyfunc, '__wrapped__', dyfunc)
143 144 145 146 147 148 149 150 151
    raw_code = inspect.getsource(dyfunc)
    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 static_func from AST
152
    static_func, file_name = ast_to_func(root_wrapper.node, dyfunc)
153
    return static_func, dygraph_to_static