ast_transformer.py 6.1 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
#
# 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.

15 16 17 18
# 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/
19

20
import os
21 22 23 24 25 26
from paddle.fluid.dygraph.dygraph_to_static.base_transformer import (
    BaseTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.early_return_transformer import (
    EarlyReturnTransformer,
)
27
from .assert_transformer import (
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    AssertTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.basic_api_transformer import (
    BasicApiTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.break_continue_transformer import (
    BreakContinueTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.break_continue_transformer import (
    BreakTransformOptimizer,
)
from paddle.fluid.dygraph.dygraph_to_static.call_transformer import (
    CallTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.cast_transformer import (
    CastTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.typehint_transformer import (
    TypeHintTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.ifelse_transformer import (
    IfElseTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.logical_transformer import (
    LogicalTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.loop_transformer import (
    LoopTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.print_transformer import (
    PrintTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.return_transformer import (
    ReturnTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.create_variable_transformer import (
    CreateVariableTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import (
    StaticAnalysisVisitor,
)
from paddle.fluid.dygraph.dygraph_to_static.tensor_shape_transformer import (
    TensorShapeTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.decorator_transformer import (
    DecoratorTransformer,
)
75

76 77
from paddle.fluid.dygraph.dygraph_to_static import logging_utils
from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code
78

79
__all__ = ['DygraphToStaticAst']
80

81

82 83 84 85 86 87
def apply_optimization(transformers):
    """
    Judge wheter to apply optimized transformation, such as BreakTransformOptimizer.
    And not all optimized transformations are applied by default. It's controlled by
    'export FLAGS_optim_transformation=1'
    """
88 89 90 91 92
    flag = str(os.environ.get('FLAGS_optim_transformation')) in [
        '1',
        'True',
        'true',
    ]
93 94 95 96
    if flag:
        transformers.insert(3, BreakTransformOptimizer)


97
class DygraphToStaticAst(BaseTransformer):
98 99 100 101
    """
    Main class to transform Dygraph to Static Graph
    """

102 103 104
    def __init__(self):
        self.translator_logger = logging_utils.TranslatorLogger()

105
    def get_static_ast(self, root):
106
        # save root for some analysis may need global AST
107
        self.root = root
108
        self.static_analysis_visitor = StaticAnalysisVisitor(root)
109 110
        self.static_analysis_root = (
            self.static_analysis_visitor.get_node_wrapper_root()
111
        )
112
        self.decorate_func_name = None
113 114 115
        self.transfer_from_node_type(self.static_analysis_root)
        return self.static_analysis_root

116 117
    def _apply(self, transformer, node_wrapper, log_level):
        transformer(node_wrapper).transform()
118 119 120
        self.translator_logger.log_transformed_code(
            log_level, self.root, transformer.__name__
        )
121

122
    def transfer_from_node_type(self, node_wrapper):
123
        self.translator_logger.log(
124 125
            1, "Source code: \n{}".format(ast_to_source_code(self.root))
        )
126
        # Generic transformation
127
        self.visit(node_wrapper.node)
128

129
        transformers = [
130
            EarlyReturnTransformer,
131 132 133 134 135
            BasicApiTransformer,  # Basic Api
            TensorShapeTransformer,  # Tensor.shape -> layers.shape(Tensor)
            BreakContinueTransformer,  # break/continue in loops
            ReturnTransformer,  # return in functions
            LogicalTransformer,  # logical and/or/not
136
            CreateVariableTransformer,  # create undefined var for if / while / for
137 138 139 140 141 142
            LoopTransformer,  # for/while -> while_op
            IfElseTransformer,  # if/else -> cond_op
            AssertTransformer,  # assert statement
            PrintTransformer,  # print statement
            CallTransformer,  # transform call recursively
            CastTransformer,  # type casting statement
143
            DecoratorTransformer,  # transform decorators to function call
144
            TypeHintTransformer,  # remove all typehint in gast.Name
145 146
        ]

147 148
        apply_optimization(transformers)

149 150 151 152
        for index, transformer in enumerate(transformers):
            self._apply(transformer, node_wrapper, log_level=index + 1)

        self.translator_logger.log_transformed_code(
153 154
            logging_utils.LOG_AllTransformer, self.root, "All Transformers"
        )
155

156 157 158
    def visit_FunctionDef(self, node):
        if self.decorate_func_name is None:
            self.decorate_func_name = node.name
159

160 161 162 163 164 165 166 167 168 169 170
        self.generic_visit(node)
        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