tracer.py 11.5 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
final_state_name_mapping = {
Y
YuanRisheng 已提交
25 26 27 28 29 30 31 32
    "graph_send_recv": {
        "final_op_name": "final_state_graph_send_recv",
        "x": "X",
        "src_index": "Src_index",
        "dst_index": "Dst_index",
        "out": "Out",
        "dst_count": "Dst_count"
    },
33 34 35 36 37 38 39
    "matmul_v2": {
        "final_op_name": "final_state_matmul",
        "transpose_x": "trans_x",
        "transpose_y": "trans_y",
        "x": "X",
        "y": "Y",
        "out": "Out",
H
hong 已提交
40
    },
H
hong 已提交
41 42 43 44 45
    # "elementwise_add": {
    #     "final_op_name": "final_state_add",
    #     "x": "X",
    #     "y": "Y",
    # },
H
hong 已提交
46 47 48 49 50
    "trunc": {
        "final_op_name": "final_state_trunc",
        "x": "X",
        "out": "Out",
    },
51 52 53 54 55 56
    # "pool2d": {
    #     "final_op_name": "final_state_pool2d",
    #     "x": "X",
    #     "kernel_size": "ksize",
    #     "out": "Out",
    # },
H
hong 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    "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 已提交
74
    },
75 76 77 78 79 80
    # "one_hot": {
    #     "final_op_name": "final_state_one_hot",
    #     "x": "X",
    #     "num_class": "depth",
    #     "out": "Out",
    # }
81 82
}

M
minqiyang 已提交
83 84 85

class Tracer(core.Tracer):
    """
86 87
    :api_attr: imperative
    
88 89 90 91 92 93 94
    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 已提交
95 96
    """

J
Jiabin Yang 已提交
97 98
    def __init__(self):
        super(Tracer, self).__init__()
M
minqiyang 已提交
99

M
minqiyang 已提交
100
        self._train_mode = True
M
minqiyang 已提交
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    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)):
121 122 123
            # initialized with None
            arg_to_append = None

124 125 126 127 128 129 130
            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:
131
                if "Num" in arg_name[-3:]:
132 133 134 135 136
                    # 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
137 138 139 140 141 142 143 144
                # NOTE(dev): For MasterParam/MasterParamOut in optimzer op
                elif "Var" in arg_name[-3:]:
                    out_name = arg_name[:-3]
                    print(out_name)
                    if out_name in outputs.keys():
                        arg_to_append = outputs[out_name]
                    elif out_name in inputs.keys():
                        arg_to_append = inputs[out_name]
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

            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)

0
0x45f 已提交
167 168 169 170 171 172 173
        if type == 'load_combine':
            assert len(outputs.keys()) == 1
            key = list(outputs.keys())[0]
            for j in range(len(returns)):
                returns[j]._share_underline_tensor_to(outputs[key][j])
            return

174 175 176 177 178 179 180 181 182 183
        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:
184 185 186 187 188 189
                        if isinstance(outputs[retname], list):
                            outputs[retname][0].reconstruct_from_(returns[i],
                                                                  False)
                        else:
                            outputs[retname].reconstruct_from_(returns[i],
                                                               False)
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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        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 已提交
286 287 288 289 290 291 292
    def trace_op(self,
                 type,
                 inputs,
                 outputs,
                 attrs,
                 stop_gradient=False,
                 inplace_map=None):
J
Jiabin Yang 已提交
293
        if not framework._in_legacy_dygraph():
294 295
            # inputs : {"sum": [tensor], ...}
            # outputs : {"sum": [tensor], ...}
296 297 298
            if type in final_state_name_mapping.keys():
                final_state_type = final_state_name_mapping[type][
                    "final_op_name"]
299

300 301 302
                assert final_state_type in _C_ops.__dict__
                self.eager_final_state_trace_op(type, inputs, outputs, attrs,
                                                stop_gradient, inplace_map)
303
            else:
304 305
                self.eager_trace_op(type, inputs, outputs, attrs, stop_gradient,
                                    inplace_map)
306 307 308 309
        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 已提交
310

M
minqiyang 已提交
311
    def train_mode(self):
M
minqiyang 已提交
312 313
        self._train_mode = True

M
minqiyang 已提交
314
    def eval_mode(self):
M
minqiyang 已提交
315
        self._train_mode = False