tracer.py 10.6 KB
Newer Older
M
minqiyang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Copyright (c) 2018 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.

from __future__ import print_function

import six

from collections import defaultdict
from paddle.fluid import core
from paddle.fluid import framework
22
from paddle import _C_ops
M
minqiyang 已提交
23

24 25 26 27 28 29 30 31
final_state_name_mapping = {
    "matmul_v2": {
        "final_op_name": "final_state_matmul",
        "transpose_x": "trans_x",
        "transpose_y": "trans_y",
        "x": "X",
        "y": "Y",
        "out": "Out",
H
hong 已提交
32
    },
H
hong 已提交
33 34 35 36 37
    # "elementwise_add": {
    #     "final_op_name": "final_state_add",
    #     "x": "X",
    #     "y": "Y",
    # },
H
hong 已提交
38 39 40 41 42
    "trunc": {
        "final_op_name": "final_state_trunc",
        "x": "X",
        "out": "Out",
    },
F
From00 已提交
43 44 45 46 47 48
    "pool2d": {
        "final_op_name": "final_state_pool2d",
        "x": "X",
        "kernel_size": "ksize",
        "out": "Out",
    },
H
hong 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    "abs": {
        "final_op_name": "final_state_abs",
        "x": "X",
        "out": "Out",
    },
    "digamma": {
        "final_op_name": "final_state_digamma",
        "x": "X",
        "out": "Out",
    },
    "diagonal": {
        "final_op_name": "final_state_diagonal",
        "x": "Input",
        "offset": "offset",
        "axis1": "axis1",
        "axis2": "axis2",
        "out": "Out",
H
hong 已提交
66 67 68 69 70 71
    },
    "one_hot": {
        "final_op_name": "final_state_one_hot",
        "x": "X",
        "num_class": "depth",
        "out": "Out",
72 73 74
    }
}

M
minqiyang 已提交
75 76 77

class Tracer(core.Tracer):
    """
78 79
    :api_attr: imperative
    
80 81 82 83 84 85 86
    Tracer is used to execute and record the operators executed, to construct the 
    computation graph in dygraph model. Tracer has two mode, :code:`train_mode`
    and :code:`eval_mode`. In :code:`train_mode`, Tracer would add backward network 
    automatically and perform AutoGrad by method :code:`loss.backward()`. 
    In :code:`eval_mode`, Tracer would not add backward network.

    This is a low level API, users don't need to use it directly.
M
minqiyang 已提交
87 88
    """

J
Jiabin Yang 已提交
89 90
    def __init__(self):
        super(Tracer, self).__init__()
M
minqiyang 已提交
91

M
minqiyang 已提交
92
        self._train_mode = True
M
minqiyang 已提交
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    def eager_trace_op(self,
                       type,
                       inputs,
                       outputs,
                       attrs,
                       stop_gradient=False,
                       inplace_map=None):
        function_ptr = _C_ops.__dict__[type]

        core_ops_args_info = _C_ops.get_core_ops_args_info()
        core_ops_args_type_info = _C_ops.get_core_ops_args_type_info()
        core_ops_returns_info = _C_ops.get_core_ops_returns_info()

        op_args = core_ops_args_info[type]
        op_args_type = core_ops_args_type_info[type]
        op_returns = core_ops_returns_info[type]

        arg_list = []
        for i in range(len(op_args)):
            arg_name = op_args[i]
            arg_type = op_args_type[i]
            if arg_name in inputs.keys():
                arg_to_append = inputs[arg_name]
            elif arg_name in outputs.keys():
                arg_to_append = outputs[arg_name]
            else:
                if "Num" in arg_name:
                    # Remove "Num" suffix to get out_name
                    out_name = arg_name[:-3]
                    assert out_name in outputs.keys()
                    num_outs = len(outputs[out_name])
                    arg_to_append = num_outs
                else:
                    arg_to_append = None

            if arg_to_append is None:
                arg_list.append(arg_to_append)
            elif arg_type == "tensor":
                if isinstance(arg_to_append, list):
                    arg_list.append(arg_to_append[0])
                else:
                    arg_list.append(arg_to_append)
            elif arg_type == "list":
                assert isinstance(arg_to_append, list)
                arg_list.append(arg_to_append)
            else:
                assert arg_type == "int"
                assert isinstance(arg_to_append, int)
                arg_list.append(arg_to_append)

        attrs_list = []
        for k, v in attrs.items():
            attrs_list.append(k)
            attrs_list.append(v)
        returns = function_ptr(*arg_list, *attrs_list)

        if isinstance(returns, tuple):
            for i in range(len(op_returns)):
                retname = op_returns[i]
                if retname in outputs.keys():
                    # Replaced outputs by function returns
                    if isinstance(returns[i], list):
                        for j in range(len(returns[i])):
                            outputs[retname][j].reconstruct_from_(returns[i][j],
                                                                  False)
                    else:
160 161 162 163 164 165
                        if isinstance(outputs[retname], list):
                            outputs[retname][0].reconstruct_from_(returns[i],
                                                                  False)
                        else:
                            outputs[retname].reconstruct_from_(returns[i],
                                                               False)
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 214 215 216 217 218 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
        elif isinstance(returns, list):
            assert len(outputs.keys()) == 1
            key = list(outputs.keys())[0]
            for j in range(len(returns)):
                outputs[key][j].reconstruct_from_(returns[j], False)
        else:
            assert len(outputs.keys()) == 1
            key = list(outputs.keys())[0]
            if isinstance(outputs[key], list):
                outputs[key][0].reconstruct_from_(returns, False)
            else:
                outputs[key].reconstruct_from_(returns, False)

    def eager_final_state_trace_op(self,
                                   type,
                                   inputs,
                                   outputs,
                                   attrs,
                                   stop_gradient=False,
                                   inplace_map=None):
        assert type in final_state_name_mapping.keys()

        final_state_type = final_state_name_mapping[type]["final_op_name"]
        function_ptr = _C_ops.__dict__[final_state_type]

        core_ops_args_info = _C_ops.get_final_state_core_ops_args_info()
        core_ops_args_type_info = _C_ops.get_final_state_core_ops_args_type_info(
        )
        core_ops_returns_info = _C_ops.get_final_state_core_ops_returns_info()

        op_args = core_ops_args_info[final_state_type]
        op_args_type = core_ops_args_type_info[final_state_type]
        op_returns = core_ops_returns_info[final_state_type]

        arg_list = []
        for i in range(len(op_args)):
            eager_arg_name = op_args[i]
            arg_type = op_args_type[i]

            assert eager_arg_name in final_state_name_mapping[type].keys()
            arg_name = final_state_name_mapping[type][eager_arg_name]

            if arg_name in inputs.keys():
                arg_to_append = inputs[arg_name]
            elif arg_name in outputs.keys():
                arg_to_append = outputs[arg_name]
            elif arg_name in attrs.keys() and arg_type == "":
                arg_to_append = attrs[arg_name]
            else:
                # dispensable
                arg_to_append = None

            if arg_type == "":
                # attribute
                arg_list.append(arg_to_append)
            elif arg_type == "tensor":
                if isinstance(arg_to_append, list):
                    arg_list.append(arg_to_append[0])
                else:
                    arg_list.append(arg_to_append)
            elif arg_type == "list":
                assert isinstance(arg_to_append, list)
                arg_list.append(arg_to_append)
            else:
                assert arg_to_append is None
                arg_list.append(arg_to_append)

        returns = function_ptr(*arg_list)

        if isinstance(returns, tuple):
            for i in range(len(op_returns)):
                eager_retname = op_returns[i]

                assert eager_retname in final_state_name_mapping[type].keys()
                retname = final_state_name_mapping[type][eager_retname]
                if retname in outputs.keys():
                    # Replaced outputs by function returns
                    if isinstance(returns[i], list):
                        for j in range(len(returns[i])):
                            outputs[retname][j].reconstruct_from_(returns[i][j],
                                                                  False)
                    else:
                        outputs[retname][0].reconstruct_from_(returns[i], False)
        elif isinstance(returns, list):
            assert len(outputs.keys()) == 1
            key = list(outputs.keys())[0]
            for j in range(len(returns)):
                outputs[key][j].reconstruct_from_(returns[j], False)
        else:
            assert len(outputs.keys()) == 1
            key = list(outputs.keys())[0]
            if isinstance(outputs[key], list):
                outputs[key][0].reconstruct_from_(returns, False)
            else:
                outputs[key].reconstruct_from_(returns, False)

Z
zyfncg 已提交
262 263 264 265 266 267 268
    def trace_op(self,
                 type,
                 inputs,
                 outputs,
                 attrs,
                 stop_gradient=False,
                 inplace_map=None):
269 270 271
        if framework._in_eager_mode():
            # inputs : {"sum": [tensor], ...}
            # outputs : {"sum": [tensor], ...}
272 273 274
            if type in final_state_name_mapping.keys():
                final_state_type = final_state_name_mapping[type][
                    "final_op_name"]
275

276 277 278
                assert final_state_type in _C_ops.__dict__
                self.eager_final_state_trace_op(type, inputs, outputs, attrs,
                                                stop_gradient, inplace_map)
279
            else:
280 281
                self.eager_trace_op(type, inputs, outputs, attrs, stop_gradient,
                                    inplace_map)
282 283 284 285
        else:
            self.trace(type, inputs, outputs, attrs,
                       framework._current_expected_place(), self._has_grad and
                       not stop_gradient, inplace_map if inplace_map else {})
M
minqiyang 已提交
286

M
minqiyang 已提交
287
    def train_mode(self):
M
minqiyang 已提交
288 289
        self._train_mode = True

M
minqiyang 已提交
290
    def eval_mode(self):
M
minqiyang 已提交
291
        self._train_mode = False