jit.py 15.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2019 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.

15 16
from __future__ import print_function

17
__all__ = ['TracedLayer', 'dygraph_to_static_output', 'dygraph_to_static_graph']
18

19
import gast
20
import inspect
21
import textwrap
22
import warnings
23 24

from ..wrapped_decorator import wrap_decorator
25
from .base import program_desc_tracing_guard, switch_to_static_graph
26
from .dygraph_to_static import DygraphToStaticAst
27
from .dygraph_to_static.ast_utils import ast_to_func
28
from .layers import Layer
29 30 31 32
from paddle.fluid import core
from paddle.fluid.framework import Program, Block, Variable, _dygraph_tracer, dygraph_only, _dygraph_guard, _current_expected_place, in_dygraph_mode
from paddle.fluid.executor import Executor, scope_guard
from paddle.fluid.compiler import CompiledProgram
33
from paddle.fluid import program_guard, data, default_startup_program, default_main_program
34 35 36 37 38 39 40 41 42 43 44 45


def create_program_from_desc(program_desc):
    program = Program()
    program.desc = program_desc
    program.blocks = [Block(program, 0)]
    program._sync_with_cpp()
    return program


def _extract_vars(inputs, result_list):
    if isinstance(inputs, Variable):
46
        result_list.append(inputs)
47 48 49 50 51 52 53 54 55 56 57 58

    if isinstance(inputs, (list, tuple)):
        for var in inputs:
            _extract_vars(var, result_list)


def extract_vars(inputs):
    result_list = []
    _extract_vars(inputs, result_list)
    return result_list


59 60 61 62 63
def to_static_func(dygraph_func):
    # Get AST from dygraph function
    dygraph_code = inspect.getsource(dygraph_func)
    dygraph_code = textwrap.dedent(dygraph_code)
    root = gast.parse(dygraph_code)
64

65 66 67
    # Transform AST
    dygraph_to_static = DygraphToStaticAst()
    root_wrapper = dygraph_to_static.get_static_ast(root)
68

69 70 71
    # Get static_func from AST
    func_name = dygraph_to_static.get_module_name()
    static_func, file_name = ast_to_func(root_wrapper.node, func_name)
72

73
    return static_func, dygraph_to_static
74

75

76 77 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 103 104 105 106 107
def _dygraph_to_static_graph_(dygraph_func):
    def __impl__(*args, **kwargs):
        if in_dygraph_mode():
            warnings.warn(
                "The decorator 'dygraph_to_static_graph' doesn't work in dygraph mode."
                " Please use it in static mode.")
            return dygraph_func(*args, **kwargs)
        static_func, dygraph_to_static = to_static_func(dygraph_func)
        return static_func(*args, **kwargs)

    return __impl__


def _dygraph_to_static_output_(dygraph_func):
    def __impl__(*args, **kwargs):
        if in_dygraph_mode():
            warnings.warn(
                "The decorator 'dygraph_to_static_output' doesn't work in dygraph mode."
                " Please use it in static mode.")
            return dygraph_func(*args, **kwargs)

        static_func, dygraph_to_static = to_static_func(dygraph_func)
        feed_name_to_idx = dygraph_to_static.get_feed_name_to_idx()
        feed_dict = {}
        for feed_name, idx in feed_name_to_idx.items():
            feed_dict[feed_name] = args[idx]

        # Run static_func in static mode
        startup_program = default_main_program()
        main_program = default_startup_program()
        static_res = run_static_func(main_program, startup_program, static_func,
                                     args, kwargs, feed_dict, feed_name_to_idx)
108
        return static_res
109 110 111 112

    return __impl__


113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
def run_static_func(main_program, startup_program, static_func, args, kwargs,
                    feed_dict, feed_name_to_idx):

    with program_guard(main_program, startup_program):
        args_list = list(args)
        for var_name, value in feed_dict.items():
            idx = feed_name_to_idx[var_name]
            args_list[idx] = data(
                name=var_name, shape=value.shape, dtype=str(value.dtype))
        args = tuple(args_list)
        static_out = static_func(*args, **kwargs)
        if not isinstance(static_out, (list, tuple)):
            static_out = [static_out]
        exe = Executor(core.CPUPlace())
        exe.run(startup_program)
        static_res = exe.run(main_program,
                             fetch_list=static_out,
                             feed=feed_dict)
    return static_res


134
dygraph_to_static_output = wrap_decorator(_dygraph_to_static_output_)
135
dygraph_to_static_graph = wrap_decorator(_dygraph_to_static_graph_)
136 137


138
@dygraph_only
Z
Zeng Jinle 已提交
139 140 141 142 143
def _trace(layer,
           inputs,
           feed_prefix='feed_',
           fetch_prefix='fetch_',
           tmp_prefix='t_'):
144
    assert isinstance(layer, Layer)
145 146 147 148 149 150 151 152 153

    if not isinstance(inputs, (list, tuple)):
        inputs = [inputs]

    tracer = _dygraph_tracer()._get_program_desc_tracer()

    var_list = extract_vars(inputs)

    with program_desc_tracing_guard(True):
154
        original_outputs = layer(*inputs)
155 156 157 158
        if not isinstance(original_outputs, (list, tuple)):
            outputs = [original_outputs]
        else:
            outputs = original_outputs
159
        out_vars = [var for var in outputs]
160

161
        program_desc, feed_names, fetch_names, parameters = tracer.create_program_desc(
Z
Zeng Jinle 已提交
162
            var_list, feed_prefix, out_vars, fetch_prefix, tmp_prefix)
163 164 165 166 167
        tracer.reset()

    with _dygraph_guard(None):
        program = create_program_from_desc(program_desc)

168
    return original_outputs, program, feed_names, fetch_names, parameters
169 170 171 172


class TracedLayer(object):
    """
173 174 175 176 177
    TracedLayer is used to convert a forward dygraph model to a static
    graph model. This is mainly used to save the dygraph model for online
    inference using C++. Besides, users can also do inference in Python
    using the converted static graph model, which usually has better
    performance than the original dygraph model.
178 179 180 181

    TracedLayer would run the static graph model using :code:`Executor`
    and :code:`CompiledProgram` . The static graph model would share
    parameters with the dygraph model.
182 183

    All TracedLayer objects should not be created by constructor and should
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    be created by static method :code:`TracedLayer.trace(layer, inputs)` .

    The TracedLayer can only be used to convert the data-independent dygraph
    model into the static graph model, which means the dygraph model should
    be independent with the tensor data and shape.
    """

    def __init__(self, program, parameters, feed_names, fetch_names):
        self._program = program
        self._feed_names = feed_names
        self._fetch_names = fetch_names

        self._place = _current_expected_place()

        self._scope = core.Scope()
        for p in parameters:
200
            src_tensor = p.value().get_tensor()
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
            dst_tensor = self._scope.var(p.name).get_tensor()
            dst_tensor._share_data_with(src_tensor)

        self._exe = Executor(self._place)
        self._compiled_program = None
        self._build_strategy = None
        self._exec_strategy = None

    @property
    def program(self):
        return self._program

    def _switch(self, is_test=True):
        for block_id in range(self._program.num_blocks):
            block = self._program.block(block_id)
            for op in block.ops:
                if op.has_attr("is_test"):
                    op._set_attr("is_test", is_test)

    @staticmethod
    @dygraph_only
    def trace(layer, inputs):
        """
224
        This method is the only allowed method to create TracedLayer object.
225 226 227 228
        It would call the :code:`layer(*inputs)` method to run the dygraph
        model and convert it into a static graph model.

        Args:
229 230
            layer (dygraph.Layer): the layer object to be traced.
            inputs (list(Variable)): the input variables of the layer object.
231 232

        Returns:
233
            tuple: A tuple of 2 items, whose the first item is the output of
234
            :code:`layer(*inputs)` , and the second item is the created
235
            TracedLayer object.
236

237
        Examples:
238 239 240
            .. code-block:: python:

                import paddle.fluid as fluid
241
                from paddle.fluid.dygraph import Linear, to_variable, TracedLayer
242 243 244
                import numpy as np

                class ExampleLayer(fluid.dygraph.Layer):
245 246 247
                    def __init__(self):
                        super(ExampleLayer, self).__init__()
                        self._fc = Linear(3, 10)
248 249 250 251 252

                    def forward(self, input):
                        return self._fc(input)

                with fluid.dygraph.guard():
253
                    layer = ExampleLayer()
254 255 256
                    in_np = np.random.random([2, 3]).astype('float32')
                    in_var = to_variable(in_np)
                    out_dygraph, static_layer = TracedLayer.trace(layer, inputs=[in_var])
257 258 259 260 261 262 263 264 265

                    # run the static graph model using Executor inside
                    out_static_graph = static_layer([in_var])

                    print(len(out_static_graph)) # 1
                    print(out_static_graph[0].shape) # (2, 10)

                    # save the static graph model for inference
                    static_layer.save_inference_model(dirname='./saved_infer_model')
266
        """
267 268
        outs, prog, feed, fetch, parameters = _trace(layer, inputs)
        traced = TracedLayer(prog, parameters, feed, fetch)
269 270 271 272 273 274 275
        return outs, traced

    def set_strategy(self, build_strategy=None, exec_strategy=None):
        """
        Set the strategies when running static graph model.

        Args:
276
            build_strategy (BuildStrategy, optional): build strategy of
277 278 279 280 281 282 283 284 285 286 287
                :code:`CompiledProgram` inside TracedLayer. Default None.
            exec_strategy (ExecutionStrategy, optional): execution strategy of
                :code:`CompiledProgram` inside TracedLayer. Default None.

        Returns:
            None

        Examples:
            .. code-block:: python:

                import paddle.fluid as fluid
288
                from paddle.fluid.dygraph import Linear, to_variable, TracedLayer
289 290 291
                import numpy as np

                class ExampleLayer(fluid.dygraph.Layer):
292 293 294
                    def __init__(self):
                        super(ExampleLayer, self).__init__()
                        self._fc = Linear(3, 10)
295 296 297 298 299

                    def forward(self, input):
                        return self._fc(input)

                with fluid.dygraph.guard():
300
                    layer = ExampleLayer()
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                    in_np = np.random.random([2, 3]).astype('float32')
                    in_var = to_variable(in_np)

                    out_dygraph, static_layer = TracedLayer.trace(layer, inputs=[in_var])

                    build_strategy = fluid.BuildStrategy()
                    build_strategy.enable_inplace = True

                    exec_strategy = fluid.ExecutionStrategy()
                    exec_strategy.num_threads = 2

                    static_layer.set_strategy(build_strategy=build_strategy, exec_strategy=exec_strategy)
                    out_static_graph = static_layer([in_var])
        """
        assert self._compiled_program is None, "Cannot set strategy after run"
        self._build_strategy = build_strategy
        self._exec_strategy = exec_strategy

    @switch_to_static_graph
    def _compile(self):
        self._compiled_program = CompiledProgram(
            self._program).with_data_parallel(
                build_strategy=self._build_strategy,
                exec_strategy=self._exec_strategy,
                places=self._place)

    def _build_feed(self, inputs):
        assert isinstance(inputs, (list, tuple)), \
            "Inputs should be a list or tuple of variables"
        assert len(inputs) == len(self._feed_names)
        feed_dict = {}
        if in_dygraph_mode():
            for x, name in zip(inputs, self._feed_names):
334
                feed_dict[name] = x.value().get_tensor()
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        else:
            for x, name in zip(inputs, self._feed_names):
                feed_dict[name] = x

        return feed_dict

    @switch_to_static_graph
    def _run(self, feed):
        return self._exe.run(self._compiled_program,
                             feed=feed,
                             fetch_list=self._fetch_names)

    def __call__(self, inputs):
        with scope_guard(self._scope):
            if self._compiled_program is None:
                self._compile()

            return self._run(self._build_feed(inputs))

    @switch_to_static_graph
    def save_inference_model(self, dirname, feed=None, fetch=None):
        """
357 358
        Save the TracedLayer to a model for inference. The saved
        inference model can be loaded by C++ inference APIs.
359 360

        Args:
361
            dirname (str): the directory to save the inference model.
362
            feed (list[int], optional): the input variable indices of the saved
363
                inference model. If None, all input variables of the
364 365 366 367 368 369 370 371
                TracedLayer object would be the inputs of the saved inference
                model. Default None.
            fetch (list[int], optional): the output variable indices of the
                saved inference model. If None, all output variables of the
                TracedLayer object would be the outputs of the saved inference
                model. Default None.

        Returns:
372
            None
373 374 375 376 377

        Examples:
            .. code-block:: python:

                import paddle.fluid as fluid
378
                from paddle.fluid.dygraph import Linear, to_variable, TracedLayer
379 380 381
                import numpy as np

                class ExampleLayer(fluid.dygraph.Layer):
382 383 384
                    def __init__(self):
                        super(ExampleLayer, self).__init__()
                        self._fc = Linear(3, 10)
385 386 387 388

                    def forward(self, input):
                        return self._fc(input)

389 390 391
                save_dirname = './saved_infer_model'
                in_np = np.random.random([2, 3]).astype('float32')

392
                with fluid.dygraph.guard():
393
                    layer = ExampleLayer()
394 395
                    in_var = to_variable(in_np)
                    out_dygraph, static_layer = TracedLayer.trace(layer, inputs=[in_var])
396 397 398 399 400 401 402 403 404
                    static_layer.save_inference_model(save_dirname, feed=[0], fetch=[0])
                
                place = fluid.CPUPlace() 
                exe = fluid.Executor(place)
                program, feed_vars, fetch_vars = fluid.io.load_inference_model(save_dirname,
                                                    exe) 

                fetch, = exe.run(program, feed={feed_vars[0]: in_np}, fetch_list=fetch_vars)
                print(fetch.shape) # (2, 10)
405
        """
406
        from paddle.fluid.io import save_inference_model
407 408 409 410 411

        def get_feed_fetch(all_vars, partial_vars):
            if partial_vars is None:
                return all_vars

412
            return [all_vars[idx] for idx in partial_vars]
413 414 415 416 417 418 419 420 421 422

        with scope_guard(self._scope):
            feeded_var_names = get_feed_fetch(self._feed_names, feed)
            target_var_names = get_feed_fetch(self._fetch_names, fetch)
            target_vars = []
            for name in target_var_names:
                target_var = self._program.global_block().vars.get(name, None)
                assert target_var is not None, "{} cannot be found".format(name)
                target_vars.append(target_var)

423
            save_inference_model(
424 425 426 427 428
                dirname=dirname,
                feeded_var_names=feeded_var_names,
                target_vars=target_vars,
                executor=self._exe,
                main_program=self._program.clone())