ifelse_transformer.py 14.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import copy
from collections import defaultdict

from paddle.fluid import unique_name
19
from paddle.jit.dy2static.static_analysis import AstNodeWrapper
20
from paddle.jit.dy2static.utils import (
21
    FOR_ITER_INDEX_PREFIX,
22 23
    FOR_ITER_ITERATOR_PREFIX,
    FOR_ITER_TARGET_PREFIX,
24
    FOR_ITER_TUPLE_INDEX_PREFIX,
25
    FOR_ITER_TUPLE_PREFIX,
26 27 28
    FOR_ITER_VAR_LEN_PREFIX,
    FOR_ITER_VAR_NAME_PREFIX,
    FOR_ITER_ZIP_TO_LIST_PREFIX,
29
    FunctionNameLivenessAnalysis,
30
    GetterSetterHelper,
31 32 33
    ast_to_source_code,
    create_funcDef_node,
    create_get_args_node,
34
    create_name_str,
35 36
    create_nonlocal_stmt_nodes,
    create_set_args_node,
37
)
38

39 40 41 42 43 44 45
# 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/
from paddle.utils import gast

from .base_transformer import BaseTransformer
46
from .utils import FALSE_FUNC_PREFIX, TRUE_FUNC_PREFIX
47

48
__all__ = []
49

50 51 52
GET_ARGS_FUNC_PREFIX = 'get_args'
SET_ARGS_FUNC_PREFIX = 'set_args'
ARGS_NAME = '__args'
53 54


55
class IfElseTransformer(BaseTransformer):
56 57 58 59 60
    """
    Transform if/else statement of Dygraph into Static Graph.
    """

    def __init__(self, wrapper_root):
61 62 63 64
        assert isinstance(wrapper_root, AstNodeWrapper), (
            "Type of input node should be AstNodeWrapper, but received %s ."
            % type(wrapper_root)
        )
65
        self.root = wrapper_root.node
66
        FunctionNameLivenessAnalysis(
67 68
            self.root
        )  # name analysis of current ast tree.
69 70 71 72 73 74 75 76 77

    def transform(self):
        """
        Main function to transform AST.
        """
        self.visit(self.root)

    def visit_If(self, node):
        self.generic_visit(node)
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        (
            true_func_node,
            false_func_node,
            get_args_node,
            set_args_node,
            return_name_ids,
            push_pop_ids,
        ) = transform_if_else(node, self.root)

        new_node = create_convert_ifelse_node(
            return_name_ids,
            push_pop_ids,
            node.test,
            true_func_node,
            false_func_node,
            get_args_node,
            set_args_node,
        )

        return [
            get_args_node,
            set_args_node,
            true_func_node,
            false_func_node,
        ] + [new_node]
103 104 105 106 107 108 109

    def visit_Call(self, node):
        # Remove `numpy()` statement, like `Tensor.numpy()[i]` -> `Tensor[i]`
        if isinstance(node.func, gast.Attribute):
            attribute = node.func
            if attribute.attr == 'numpy':
                node = attribute.value
110
        self.generic_visit(node)
111 112
        return node

113 114 115 116
    def visit_IfExp(self, node):
        """
        Transformation with `true_fn(x) if Tensor > 0 else false_fn(x)`
        """
117
        self.generic_visit(node)
118

119 120 121
        new_node = create_convert_ifelse_node(
            None, None, node.test, node.body, node.orelse, None, None, True
        )
122 123 124 125 126
        # Note: A blank line will be added separately if transform gast.Expr
        # into source code. Using gast.Expr.value instead to avoid syntax error
        # in python.
        if isinstance(new_node, gast.Expr):
            new_node = new_node.value
127

128 129
        return new_node

130

131
class NameVisitor(gast.NodeVisitor):
132 133 134
    def __init__(self, after_node=None, end_node=None):
        # The start node (exclusive) of the visitor
        self.after_node = after_node
135 136
        # The terminate node of the visitor.
        self.end_node = end_node
137 138 139 140
        # Dict to store the names and ctxs of vars.
        self.name_ids = defaultdict(list)
        # List of current visited nodes
        self.ancestor_nodes = []
141 142
        # True when in range (after_node, end_node).
        self._in_range = after_node is None
143
        self._candidate_ctxs = (gast.Store, gast.Load, gast.Param)
144
        self._def_func_names = set()
145 146 147

    def visit(self, node):
        """Visit a node."""
148 149 150 151 152
        if self.after_node is not None and node == self.after_node:
            self._in_range = True
            return
        if node == self.end_node:
            self._in_range = False
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            return

        self.ancestor_nodes.append(node)
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        ret = visitor(node)
        self.ancestor_nodes.pop()

        return ret

    def visit_If(self, node):
        """
        For nested `if/else`, the created vars are not always visible for parent node.
        In addition, the vars created in `if.body` are not visible for `if.orelse`.

        Case 1:
            x = 1
            if m > 1:
                res = new_tensor
            res = res + 1   # Error, `res` is not visible here.

        Case 2:
            if x_tensor > 0:
                res = new_tensor
            else:
                res = res + 1   # Error, `res` is not visible here.

        In above two cases, we should consider to manage the scope of vars to parsing
        the arguments and returned vars correctly.
        """
183
        if not self._in_range or not self.end_node:
184
            self.generic_visit(node)
185
            return
186
        else:
187 188 189
            before_if_name_ids = copy.deepcopy(self.name_ids)
            body_name_ids = self._visit_child(node.body)
            # If traversal process stops early in `if.body`, return the currently seen name_ids.
190
            if not self._in_range:
191 192 193 194
                self._update_name_ids(before_if_name_ids)
            else:
                else_name_ids = self._visit_child(node.orelse)
                # If traversal process stops early in `if.orelse`, return the currently seen name_ids.
195
                if not self._in_range:
196 197 198 199
                    self._update_name_ids(before_if_name_ids)
                else:
                    # Blocks the vars in `if.body` and only inserts the vars both created in 'if/else' branch
                    # into name_ids.
200
                    new_name_ids = self._find_new_name_ids(
201 202
                        body_name_ids, else_name_ids
                    )
203 204 205 206
                    for new_name_id in new_name_ids:
                        before_if_name_ids[new_name_id].append(gast.Store())

                    self.name_ids = before_if_name_ids
207 208

    def visit_Attribute(self, node):
209
        if not self._in_range or not self._is_call_func_name_node(node):
210 211 212
            self.generic_visit(node)

    def visit_Name(self, node):
213 214 215
        if not self._in_range:
            self.generic_visit(node)
            return
216
        blacklist = {'True', 'False', 'None'}
217 218
        if node.id in blacklist:
            return
219 220
        if node.id in self._def_func_names:
            return
221 222 223 224 225
        if not self._is_call_func_name_node(node):
            if isinstance(node.ctx, self._candidate_ctxs):
                self.name_ids[node.id].append(node.ctx)

    def visit_Assign(self, node):
226 227 228
        if not self._in_range:
            self.generic_visit(node)
            return
229 230 231 232
        # Visit `value` firstly.
        node._fields = ('value', 'targets')
        self.generic_visit(node)

233
    def visit_FunctionDef(self, node):
234 235 236
        # NOTE: We skip to visit names of get_args and set_args, because they contains
        # nonlocal statement such as 'nonlocal x, self' where 'self' should not be
        # parsed as returned value in contron flow.
237 238 239 240
        if (
            GET_ARGS_FUNC_PREFIX in node.name
            or SET_ARGS_FUNC_PREFIX in node.name
        ):
241 242
            return

243 244 245
        if not self._in_range:
            self.generic_visit(node)
            return
246
        self._def_func_names.add(node.name)
247 248 249 250 251 252 253
        if not self.end_node:
            self.generic_visit(node)
        else:
            before_name_ids = copy.deepcopy(self.name_ids)
            self.name_ids = defaultdict(list)
            self.generic_visit(node)

254
            if not self._in_range:
255 256 257 258
                self._update_name_ids(before_name_ids)
            else:
                self.name_ids = before_name_ids

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    def _visit_child(self, node):
        self.name_ids = defaultdict(list)
        if isinstance(node, list):
            for item in node:
                if isinstance(item, gast.AST):
                    self.visit(item)
        elif isinstance(node, gast.AST):
            self.visit(node)

        return copy.deepcopy(self.name_ids)

    def _find_new_name_ids(self, body_name_ids, else_name_ids):
        def is_required_ctx(ctxs, required_ctx):
            for ctx in ctxs:
                if isinstance(ctx, required_ctx):
                    return True
            return False

277
        candidate_name_ids = set(body_name_ids.keys()) & set(
278 279
            else_name_ids.keys()
        )
280 281 282
        store_ctx = gast.Store
        new_name_ids = set()
        for name_id in candidate_name_ids:
283 284 285
            if is_required_ctx(
                body_name_ids[name_id], store_ctx
            ) and is_required_ctx(else_name_ids[name_id], store_ctx):
286 287 288 289 290
                new_name_ids.add(name_id)

        return new_name_ids

    def _is_call_func_name_node(self, node):
291
        white_func_names = {'append', 'extend'}
292 293 294 295
        if len(self.ancestor_nodes) > 1:
            assert self.ancestor_nodes[-1] == node
            parent_node = self.ancestor_nodes[-2]
            if isinstance(parent_node, gast.Call) and parent_node.func == node:
296
                # e.g: var_list.append(elem), var_list is also a name_id.
297 298 299 300
                should_skip = (
                    isinstance(node, gast.Attribute)
                    and node.attr in white_func_names
                )
301 302
                if not should_skip:
                    return True
303 304
        return False

305
    def _update_name_ids(self, new_name_ids):
306
        for name_id, ctxs in new_name_ids.items():
307 308
            self.name_ids[name_id] = ctxs + self.name_ids[name_id]

309

310 311 312 313
def _valid_nonlocal_names(return_name_ids, nonlocal_names):
    """
    All var in return_name_ids should be in nonlocal_names.
    Moreover, we will always put return_name_ids in front of nonlocal_names.
314

315 316 317 318 319 320 321 322 323 324 325 326
    For Example:

        return_name_ids: [x, y]
        nonlocal_names : [a, y, b, x]

    Return:
        nonlocal_names : [x, y, a, b]
    """
    assert isinstance(return_name_ids, list)
    for name in return_name_ids:
        if name not in nonlocal_names:
            raise ValueError(
327 328 329 330
                "Required returned var '{}' must be in 'nonlocal' statement '', but not found.".format(
                    name
                )
            )
331 332 333 334 335
        nonlocal_names.remove(name)

    return return_name_ids + nonlocal_names


336 337 338 339
def transform_if_else(node, root):
    """
    Transform ast.If into control flow statement of Paddle static graph.
    """
340

341
    # TODO(liym27): Consider variable like `self.a` modified in if/else node.
342 343
    return_name_ids = sorted(node.pd_scope.modified_vars())
    push_pop_ids = sorted(node.pd_scope.variadic_length_vars())
344
    nonlocal_names = list(return_name_ids)
345 346 347 348 349
    nonlocal_names.sort()
    # NOTE: All var in return_name_ids should be in nonlocal_names.
    nonlocal_names = _valid_nonlocal_names(return_name_ids, nonlocal_names)

    # TODO(dev): Need a better way to deal this.
350 351
    # LoopTransformer will create some special vars, which is not visiable by users. so we can sure it's safe to remove them.
    filter_names = [
352 353 354 355 356 357 358 359 360
        ARGS_NAME,
        FOR_ITER_INDEX_PREFIX,
        FOR_ITER_TUPLE_PREFIX,
        FOR_ITER_TARGET_PREFIX,
        FOR_ITER_ITERATOR_PREFIX,
        FOR_ITER_TUPLE_INDEX_PREFIX,
        FOR_ITER_VAR_LEN_PREFIX,
        FOR_ITER_VAR_NAME_PREFIX,
        FOR_ITER_ZIP_TO_LIST_PREFIX,
361 362 363 364
    ]

    def remove_if(x):
        for name in filter_names:
365 366
            if x.startswith(name):
                return False
367 368 369 370
        return True

    nonlocal_names = list(filter(remove_if, nonlocal_names))
    return_name_ids = nonlocal_names
371

372
    nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
373

374 375 376 377 378 379 380 381 382
    empty_arg_node = gast.arguments(
        args=[],
        posonlyargs=[],
        vararg=None,
        kwonlyargs=[],
        kw_defaults=None,
        kwarg=None,
        defaults=[],
    )
383 384

    true_func_node = create_funcDef_node(
385
        nonlocal_stmt_node + node.body,
386
        name=unique_name.generate(TRUE_FUNC_PREFIX),
387
        input_args=empty_arg_node,
388 389
        return_name_ids=[],
    )
390
    false_func_node = create_funcDef_node(
391
        nonlocal_stmt_node + node.orelse,
392
        name=unique_name.generate(FALSE_FUNC_PREFIX),
393
        input_args=empty_arg_node,
394 395
        return_name_ids=[],
    )
396

397 398 399
    helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_ids)
    get_args_node = create_get_args_node(helper.union())
    set_args_node = create_set_args_node(helper.union())
400

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    return (
        true_func_node,
        false_func_node,
        get_args_node,
        set_args_node,
        return_name_ids,
        push_pop_ids,
    )


def create_convert_ifelse_node(
    return_name_ids,
    push_pop_ids,
    pred,
    true_func,
    false_func,
    get_args_func,
    set_args_func,
    is_if_expr=False,
):
421
    """
422
    Create `paddle.jit.dy2static.convert_ifelse(
423
            pred, true_fn, false_fn, get_args, set_args, return_name_ids)`
424
    to replace original `python if/else` statement.
425
    """
426 427 428 429 430 431 432 433
    if is_if_expr:
        true_func_source = "lambda : {}".format(ast_to_source_code(true_func))
        false_func_source = "lambda : {}".format(ast_to_source_code(false_func))
    else:
        true_func_source = true_func.name
        false_func_source = false_func.name

    convert_ifelse_layer = gast.parse(
434
        '_jst.IfElse('
435
        '{pred}, {true_fn}, {false_fn}, {get_args}, {set_args}, {return_name_ids}, push_pop_names={push_pop_ids})'.format(
436 437 438
            pred=ast_to_source_code(pred),
            true_fn=true_func_source,
            false_fn=false_func_source,
439 440 441
            get_args=get_args_func.name
            if not is_if_expr
            else 'lambda: None',  # TODO: better way to deal with this
442
            set_args=set_args_func.name
443 444
            if not is_if_expr
            else 'lambda args: None',
445
            return_name_ids=create_name_str(return_name_ids),
446 447 448
            push_pop_ids=create_name_str(push_pop_ids),
        )
    ).body[0]
449

450
    return convert_ifelse_layer