api.py 72.4 KB
Newer Older
1
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
M
Ming-Xu Huang 已提交
2
# Copyright (c) 2021 NVIDIA Corporation. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

16 17 18
# Temporary disable isort to avoid circular import
# This can be removed after the circular import is resolved
# isort: skip_file
19 20
from __future__ import annotations

21 22
import os
import pickle
23
import warnings
24
from collections import OrderedDict
25
import inspect
M
Ming-Xu Huang 已提交
26
import threading
27
from typing import Any
X
xiongkun 已提交
28
import types
29

30
import paddle
J
Jiabin Yang 已提交
31
from paddle.fluid import core, dygraph
32 33 34 35 36
from paddle.fluid.compiler import (
    BuildStrategy,
    CompiledProgram,
    ExecutionStrategy,
)
37
from paddle.fluid.data_feeder import check_type
38 39 40 41
from paddle.fluid.dygraph.base import (
    program_desc_tracing_guard,
    switch_to_static_graph,
)
42 43
from .dy2static import logging_utils
from .dy2static.convert_call_func import (
44
    ConversionOptions,
H
hjyp 已提交
45
    add_ignore_module,
46
)
47
from .dy2static.program_translator import (
48 49
    ProgramTranslator,
    StaticFunction,
X
xiongkun 已提交
50 51
    ASTStaticFunction,
    SymbolicStaticFunction,
52 53
    unwrap_decorators,
)
54
from paddle.jit.translated_layer import (
55 56 57 58 59 60
    TranslatedLayer,
    INFER_MODEL_SUFFIX,
    INFER_PARAMS_SUFFIX,
    INFER_PARAMS_INFO_SUFFIX,
    INFER_PROPERTY_SUFFIX,
)
61
from paddle.nn import Layer
62
from paddle.fluid.executor import Executor, scope_guard
63 64 65 66 67 68 69 70 71 72 73 74
from paddle.fluid.framework import (
    Block,
    Program,
    Variable,
    Parameter,
    EagerParamBase,
)
from paddle.fluid.framework import (
    _current_expected_place,
    _dygraph_guard,
    _dygraph_tracer,
)
75
from paddle.fluid.framework import dygraph_only
76
from paddle.fluid.wrapped_decorator import wrap_decorator
77
from paddle.static.io import save_inference_model
78
from paddle.framework import in_dynamic_mode
79

80 81 82 83 84 85 86 87 88

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


89
def _extract_vars(inputs, result_list, err_tag='inputs'):
90
    if isinstance(inputs, Variable):
91
        result_list.append(inputs)
92
    elif isinstance(inputs, (list, tuple)):
93
        for var in inputs:
94
            _extract_vars(var, result_list, err_tag)
95 96
    else:
        raise TypeError(
97
            "The type of 'each element of {}' in paddle.jit.TracedLayer.trace must be fluid.Variable, but received {}.".format(
98 99 100
                err_tag, type(inputs)
            )
        )
101 102


103
def extract_vars(inputs, err_tag='inputs'):
104
    result_list = []
105
    _extract_vars(inputs, result_list, err_tag)
106 107 108
    return result_list


109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
def _dygraph_to_static_func_(dygraph_func):
    """
    Converts imperative dygraph APIs into declarative function APIs. Decorator
    @dygraph_to_static_func only converts imperative dygraph APIs into
    declarative net-building APIs, which means it doesn't return immediate
    digital result as imperative mode. Users should handle Program and Executor
    by themselves.

    Note:
    This decorator is NOT our recommended way to transform imperative function
    to declarative function. We will remove this decorator after we finalize
    cleaning up code.

    Args:
        dygraph_func (callable): callable imperative function.

    Returns:
        Callable: converting imperative dygraph APIs into declarative
        net-building APIs.

    Examples:
        .. code-block:: python

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
            >>> import paddle
            >>> from paddle.jit.api import dygraph_to_static_func

            >>> @dygraph_to_static_func
            ... def func(x):
            ...     if paddle.mean(x) < 0:
            ...         x_v = x - 1
            ...     else:
            ...         x_v = x + 1
            ...
            ...     return x_v
            ...
            >>> paddle.enable_static()
            >>> x = paddle.full(shape=[3, 3], fill_value=0, dtype='float64')

            >>> x_v = func(x)
            >>> exe = paddle.static.Executor(paddle.CPUPlace())
            >>> out = exe.run(fetch_list=[x_v])
            >>> print(out[0])
            [[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]
154 155 156 157

    """

    # TODO: remove this decorator after we finalize training API
158 159
    def __impl__(*args, **kwargs):
        program_translator = ProgramTranslator()
160
        if in_dynamic_mode() or not program_translator.enable_to_static:
161
            logging_utils.warn(
162
                "The decorator 'dygraph_to_static_func' doesn't work in "
R
Ryan 已提交
163
                "dygraph mode or set 'paddle.jit.enable_to_static' to False. "
164 165
                "We will just return dygraph output."
            )
166 167 168
            return dygraph_func(*args, **kwargs)
        static_func = program_translator.get_func(dygraph_func)
        return static_func(*args, **kwargs)
169 170 171 172

    return __impl__


173
dygraph_to_static_func = wrap_decorator(_dygraph_to_static_func_)
174

175

176 177 178 179 180 181
def copy_decorator_attrs(original_func, decorated_obj):
    """
    Copies some necessary attributes from original function into decorated function.

    Args:
        original_func(callable): the original decorated function.
182
        decorated_obj(StaticFunction): the target decorated StaticFunction object.
183
    """
H
hjyp 已提交
184
    decorator_name = "to_static"
185 186 187 188 189 190 191 192 193 194 195

    decorated_obj.__name__ = original_func.__name__
    decorated_obj._decorator_name = decorator_name
    decorated_obj.__wrapped__ = original_func
    decorated_obj.__doc__ = original_func.__doc__
    if hasattr(original_func, "__module__"):
        decorated_obj.__module__ = original_func.__module__

    return decorated_obj


196
def ignore_module(modules: list[Any]):
H
hjyp 已提交
197 198 199 200 201 202 203 204 205 206
    """
    Adds modules that ignore transcription.
    Builtin modules that have been ignored are collections, pdb, copy, inspect, re, numpy, logging, six

    Args:
        modules (List[Any]): Ignored modules that you want to add

    Examples:
        .. code-block:: python

207 208
            >>> import scipy
            >>> import astor
H
hjyp 已提交
209

210 211 212 213 214 215 216
            >>> import paddle
            >>> from paddle.jit import ignore_module
            >>> modules = [
            ...     scipy,
            ...     astor,
            ... ]
            >>> ignore_module(modules)
H
hjyp 已提交
217 218 219 220 221

    """
    add_ignore_module(modules)


222 223 224 225 226 227 228 229 230 231 232
def _check_and_set_backend(backend, build_strategy):
    if backend not in ['CINN', None]:
        raise ValueError(
            "The backend of to_static should be 'CINN' or None, but received {}.".format(
                backend
            )
        )
    if backend == 'CINN':
        build_strategy.build_cinn_pass = True


H
hjyp 已提交
233
def to_static(
234 235 236 237
    function=None,
    input_spec=None,
    build_strategy=None,
    backend=None,
X
xiongkun 已提交
238
    enable_fallback=None,
239
    **kwargs,
240
):
241 242
    """
    Converts imperative dygraph APIs into declarative function APIs. Decorator
243
    @to_static handles the Program and Executor of static graph mode and returns
244 245 246 247
    the result as dygraph Tensor(s). Users could use the returned dygraph
    Tensor(s) to do imperative training, inference, or other operations. If the
    decorated function calls other imperative function, the called one will be
    converted into declarative function as well.
248
    Args:
249
        function (callable): callable imperative function.
250
        input_spec(list[InputSpec]|tuple[InputSpec]): list/tuple of InputSpec to specific the shape/dtype/name
251
            information of each input Tensor.
252 253 254 255 256
        build_strategy(BuildStrategy|None): This argument is used to compile the
            converted program with the specified options, such as operators' fusion
            in the computational graph and memory optimization during the execution
            of the computational graph. For more information about build_strategy,
            please refer to :code:`paddle.static.BuildStrategy`. The default is None.
257 258
        backend(str, Optional): Specifies compilation backend, which can be `CINN` or None. When backend is `CINN`, CINN compiler will be used to speed up training and inference.
        kwargs: Support keys including `property`, set `property` to True if the fucntion is python property.
259

260

261
    Returns:
262
        Tensor(s): containing the numerical result.
263

264 265
    Examples:
        .. code-block:: python
266

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            >>> # doctest: +SKIP
            >>> import paddle
            >>> from paddle.jit import to_static

            >>> @to_static
            >>> def func(x):
            ...     if paddle.mean(x) < 0:
            ...         x_v = x - 1
            ...     else:
            ...         x_v = x + 1
            ...     return x_v
            ...
            >>> x = paddle.ones([1, 2], dtype='float32')
            >>> x_v = func(x)
            >>> print(x_v)
            Tensor(shape=[1, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[2., 2.]])
284

285
    """
286
    property = kwargs.get("property", False)
287

288 289
    def decorated(python_func):
        """
X
xiongkun 已提交
290
        Decorates a python function into a ASTStaticFunction object.
291
        """
X
xiongkun 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305

        nonlocal enable_fallback
        if enable_fallback is None:
            flag = os.environ.get("ENABLE_FALL_BACK", None)
            if flag == "True":
                enable_fallback = True
            else:  # None or True
                enable_fallback = False

        StaticClass = StaticFunctionClass = {
            True: SymbolicStaticFunction,
            False: ASTStaticFunction,
        }[enable_fallback]

306 307
        # Step 1. unwrap the function if it is already decorated.
        _, python_func = unwrap_decorators(python_func)
308

309
        # Step 2. copy some attributes from original python function.
310 311
        static_layer = copy_decorator_attrs(
            original_func=python_func,
X
xiongkun 已提交
312
            decorated_obj=StaticClass(
313 314 315 316
                function=python_func,
                input_spec=input_spec,
                build_strategy=build_strategy,
                property=property,
317
                backend=backend,
318 319
            ),
        )
320 321

        return static_layer
322

323 324 325
    build_strategy = build_strategy or BuildStrategy()
    if not isinstance(build_strategy, BuildStrategy):
        raise TypeError(
326 327 328 329
            "Required type(build_strategy) shall be `paddle.static.BuildStrategy`, but received {}".format(
                type(build_strategy).__name__
            )
        )
330
    _check_and_set_backend(backend, build_strategy)
331

H
hjyp 已提交
332
    # for usage: `to_static(foo, ...)`
333
    if function is not None:
334
        if isinstance(function, Layer):
335
            if isinstance(function.forward, StaticFunction):
336
                class_name = function.__class__.__name__
337
                logging_utils.warn(
338 339 340 341
                    "`{}.forward` has already been decorated somewhere. It will be redecorated to replace previous one.".format(
                        class_name
                    )
                )
342 343 344 345
            function.forward = decorated(function.forward)
            return function
        else:
            return decorated(function)
346

H
hjyp 已提交
347
    # for usage: `@to_static`
348
    return decorated
349 350


351 352 353 354 355 356 357 358 359 360 361 362 363
def not_to_static(func=None):
    """
    A Decorator to suppresses the convertion of a function.

    Args:
        func(callable): The function to decorate.

    Returns:
        callable: A function which won't be converted in Dynamic-to-Static.

    Examples:
        .. code-block:: python

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            >>> # doctest: +SKIP
            >>> import paddle

            >>> @paddle.jit.not_to_static
            ... def func_not_to_static(x):
            ...     res = x - 1
            ...     return res

            >>> @paddle.jit.to_static
            ... def func(x):
            ...     if paddle.mean(x) < 0:
            ...         out = func_not_to_static(x)
            ...     else:
            ...         out = x + 1
            ...     return out
            ...
            >>> x = paddle.ones([1, 2], dtype='float32')
            >>> out = func(x)
            >>> print(out)
            Tensor(shape=[1, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[2., 2.]])
385 386 387 388 389
    """
    if func is None:
        return not_to_static

    options = ConversionOptions(not_convert=True)
390
    options.attach(func)
391 392 393
    return func


394
class _SaveLoadConfig:
395 396 397 398 399
    def __init__(self):
        self._output_spec = None
        self._model_filename = None
        self._params_filename = None
        self._separate_params = False
400 401
        # used for `paddle.load`
        self._keep_name_table = False
402 403 404 405

        # NOTE: Users rarely use following configs, so these configs are not open to users,
        # reducing user learning costs, but we retain the configuration capabilities

406 407
        # If True, programs are modified to only support direct inference deployment.
        # Otherwise,more information will be stored for flexible optimization and re-training.
408 409 410 411 412
        # Currently, only True is supported
        self._export_for_deployment = True

        # If True, It will save inference program only, and do not save params of Program
        self._program_only = False
413
        self.with_hook = False
414

415 416 417
        # if True, multi `StaticFunction` will share params in one file.
        self.combine_params = False

418 419 420
        # when need to save a prune model, use input_names_after_prune to specify the inputs left after pruning
        self.input_names_after_prune = None

421 422 423 424 425 426
    @property
    def output_spec(self):
        return self._output_spec

    @output_spec.setter
    def output_spec(self, spec):
427 428
        if spec is None:
            return
429 430
        if not isinstance(spec, list):
            raise TypeError(
431
                "The config `output_spec` should be 'list', but received input type is %s."
432 433
                % type(input)
            )
434
            for var in spec:
W
wanghuancoder 已提交
435
                if not isinstance(var, core.eager.Tensor):
436
                    raise TypeError(
437
                        "The element in config `output_spec` list should be 'Variable', but received element's type is %s."
438 439
                        % type(var)
                    )
440 441 442 443 444 445 446 447
        self._output_spec = spec

    @property
    def model_filename(self):
        return self._model_filename

    @model_filename.setter
    def model_filename(self, filename):
448 449
        if filename is None:
            return
450
        if not isinstance(filename, str):
451
            raise TypeError(
452
                "The config `model_filename` should be str, but received input's type is %s."
453 454
                % type(filename)
            )
455
        if len(filename) == 0:
456
            raise ValueError("The config `model_filename` is empty string.")
457 458 459 460 461 462 463 464
        self._model_filename = filename

    @property
    def params_filename(self):
        return self._params_filename

    @params_filename.setter
    def params_filename(self, filename):
465 466
        if filename is None:
            return
467
        if not isinstance(filename, str):
468
            raise TypeError(
469
                "The config `params_filename` should be str, but received input's type is %s."
470 471
                % type(filename)
            )
472
        if len(filename) == 0:
473
            raise ValueError("The config `params_filename` is empty string.")
474 475
        self._params_filename = filename

476 477 478 479 480 481
    @property
    def keep_name_table(self):
        return self._keep_name_table

    @keep_name_table.setter
    def keep_name_table(self, value):
482 483
        if value is None:
            return
484 485
        if not isinstance(value, bool):
            raise TypeError(
486
                "The config `keep_name_table` should be bool value, but received input's type is %s."
487 488
                % type(value)
            )
489 490
        self._keep_name_table = value

491

492
def _parse_save_configs(configs):
493
    supported_configs = [
494
        "output_spec",
495 496 497 498
        "with_hook",
        "combine_params",
        "clip_extra",
        "skip_forward",
499
        "input_names_after_prune",
500
    ]
501 502 503 504 505 506

    # input check
    for key in configs:
        if key not in supported_configs:
            raise ValueError(
                "The additional config (%s) of `paddle.jit.save` is not supported."
507 508
                % (key)
            )
509 510 511

    # construct inner config
    inner_config = _SaveLoadConfig()
512 513
    inner_config.output_spec = configs.get("output_spec", None)
    inner_config.with_hook = configs.get("with_hook", False)
514
    inner_config.combine_params = configs.get("combine_params", False)
515
    inner_config.clip_extra = configs.get("clip_extra", True)
H
Hui Zhang 已提交
516
    inner_config.skip_forward = configs.get("skip_forward", False)
517 518 519
    inner_config.input_names_after_prune = configs.get(
        "input_names_after_prune", None
    )
520 521 522 523 524 525 526 527 528 529 530 531

    return inner_config


def _parse_load_config(configs):
    supported_configs = ['model_filename', 'params_filename']

    # input check
    for key in configs:
        if key not in supported_configs:
            raise ValueError(
                "The additional config (%s) of `paddle.jit.load` is not supported."
532 533
                % (key)
            )
534 535 536 537 538 539 540 541 542

    # construct inner config
    inner_config = _SaveLoadConfig()
    inner_config.model_filename = configs.get('model_filename', None)
    inner_config.params_filename = configs.get('params_filename', None)

    return inner_config


543
def _get_input_var_names(inputs, input_spec, input_names_after_prune):
544 545 546 547
    name_none_error = (
        "The %s's name is None. "
        "When using jit.save, please set InputSepc's name in "
        "to_static(input_spec=[]) and jit.save(input_spec=[]) "
548
        "and make sure they are consistent."
549 550 551 552 553
    )
    name_no_exists_error = (
        "The tensor `%s` does not exists. "
        "Please make sure the name of InputSpec or example Tensor "
        "in input_spec is the same as the name of InputSpec in "
554
        "`to_static` decorated on the Layer.forward method."
555
    )
556 557 558 559 560 561 562 563
    if input_names_after_prune is not None:
        input_spec = [
            x
            for x in input_spec
            if isinstance(x, paddle.static.InputSpec)
            and x.name in input_names_after_prune
        ]

564
    result_list = []
565
    input_var_names = [
566 567 568
        var.name
        for var in paddle.utils.flatten(inputs)
        if isinstance(var, Variable)
569
    ]
570 571
    if input_spec is None:
        # no prune
572 573 574 575
        return input_var_names
    else:
        # fileter out non-tensor type spec infos.
        input_spec = [
576 577
            spec
            for spec in input_spec
578 579 580 581
            if isinstance(spec, paddle.static.InputSpec)
        ]

    if len(input_spec) == len(input_var_names):
582 583
        # no prune
        result_list = input_var_names
584
        # if input spec name not in input_var_names, only raise warning
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
        for spec in input_spec:
            if spec.name is None:
                warnings.warn(name_none_error % spec)
            elif spec.name not in input_var_names:
                warnings.warn(name_no_exists_error % spec.name)
            else:
                # do nothing
                pass
    else:
        # prune
        for spec in input_spec:
            if spec.name is None:
                # name is None, the input_spec only can be InputSpec
                raise ValueError(name_none_error % spec)
            elif spec.name not in input_var_names:
W
wanghuancoder 已提交
600
                # the input_spec can be `InputSpec` or `Tensor`
601 602 603 604 605 606 607
                raise ValueError(name_no_exists_error % spec.name)
            else:
                result_list.append(spec.name)

    return result_list


608
def _get_output_vars(outputs, output_spec, with_hook=False):
609 610 611 612
    name_no_exists_error = (
        "The tensor `%s` does not exists. "
        "Please make sure the name of example Tensor "
        "in configs.output_spec is the output tensor of "
613
        "Layer.forward method."
614
    )
615 616 617 618
    if output_spec and with_hook:
        raise RuntimeError(
            "Currently not support specify output_spec while founding pre/post hooks in your outermost layer."
        )
619 620
    result_list = []
    output_vars_dict = OrderedDict()
621
    for var in paddle.utils.flatten(outputs):
622 623 624
        if isinstance(var, Variable):
            output_vars_dict[var.name] = var
    if output_spec is None:
625
        result_list = list(output_vars_dict.values())
626
    elif output_spec is not None and len(output_spec) == len(output_vars_dict):
627
        result_list = list(output_vars_dict.values())
628 629 630 631 632 633 634 635 636 637 638 639
        for var in output_spec:
            if var.name not in output_vars_dict:
                warnings.warn(name_no_exists_error % var.name)
    else:
        for var in output_spec:
            if var.name not in output_vars_dict:
                raise ValueError(name_no_exists_error % var.name)
            else:
                result_list.append(output_vars_dict[var.name])
    return result_list


640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
# NOTE(chenweihang): [ Handling of use cases of API paddle.jit.load ]
# `paddle.jit.load` may be used to load saved results of:
# 1. Expected cases:
#   - paddle.jit.save
#   - paddle.static.save_inference_model
#   - paddle.fluid.io.save_inference_model
# 2. Error cases:
#   - paddle.save: no .pdmodel for prefix
#   - paddle.static.save: no .pdiparams but .pdparams exists
#   - paddle.fluid.io.save_params/save_persistables: no __model__
# TODO(chenweihang): polish error message in above error cases
def _build_load_path_and_config(path, config):
    # NOTE(chenweihang): If both [prefix save format] and [directory save format] exist,
    # raise error, avoid confusing behavior
    prefix_format_path = path + INFER_MODEL_SUFFIX
    prefix_format_exist = os.path.exists(prefix_format_path)
    directory_format_exist = os.path.isdir(path)
    if prefix_format_exist and directory_format_exist:
        raise ValueError(
659
            "The {}.pdmodel and {} directory exist at the same time, "
660
            "don't know which one to load, please make sure that the specified target "
661
            "of ``path`` is unique.".format(path, path)
662
        )
663
    elif not prefix_format_exist and not directory_format_exist:
664 665 666 667 668
        raise ValueError(
            "The ``path`` (%s) to load model not exists. "
            "Please make sure that *.pdmodel exists or "
            "don't using ``skip_forward=True`` to jit.save." % path
        )
669 670 671 672 673 674 675 676
    else:
        if prefix_format_exist:
            file_prefix = os.path.basename(path)
            model_path = os.path.dirname(path)
            if config.model_filename is not None:
                warnings.warn(
                    "When loading the result saved with the "
                    "specified file prefix, the ``model_filename`` config does "
677 678
                    "not take effect."
                )
679 680 681 682 683
            config.model_filename = file_prefix + INFER_MODEL_SUFFIX
            if config.params_filename is not None:
                warnings.warn(
                    "When loading the result saved with the "
                    "specified file prefix, the ``params_filename`` config does "
684 685
                    "not take effect."
                )
686 687 688 689
            config.params_filename = file_prefix + INFER_PARAMS_SUFFIX
        else:
            # Compatible with the old save_inference_model format
            model_path = path
690

691
    return model_path, config
692 693


M
Ming-Xu Huang 已提交
694 695 696 697
_save_pre_hooks_lock = threading.Lock()
_save_pre_hooks = []


698
class HookRemoveHelper:
699
    """A HookRemoveHelper that can be used to remove hook."""
M
Ming-Xu Huang 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726

    def __init__(self, hook):
        self._hook = hook

    def remove(self):
        _remove_save_pre_hook(self._hook)


def _register_save_pre_hook(hook):
    """
    Register a save pre-hook for `paddle.jit.save`.
    This hook will be executed before `save` function has been invoked.

    hook(layer, input_spec, configs) -> None
    - layer (Layer|function): This argument is corresponding to `layer` in `paddle.jit.save`.
    - input_spec (list or tuple[InputSpec|Tensor|Python built-in variable]): This argument is corresponding to `input_spec` in `paddle.jit.save`.
    - configs (dict): This argument is corresponding to `configs` in `paddle.jit.save`.

    Args:
        hook(function): a function registered as a save pre-hook

    Returns:
        HookRemoveHelper: a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()`.

    Examples:
        .. code-block:: python

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
            >>> import numpy as np
            >>> import paddle

            >>> IMAGE_SIZE = 256
            >>> CLASS_NUM = 10

            >>> class LinearNet(paddle.nn.Layer):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self._linear = paddle.nn.Linear(IMAGE_SIZE, CLASS_NUM)
            ...
            ...     def forward(self, x):
            ...         return self._linear(x)
            ...
            >>> saving_count = 0
            >>> def save_pre_hook(layer, input_spec, configs):
            ...     global saving_count
            ...     saving_count += 1
            ...
            >>> remove_handler = paddle.jit.api._register_save_pre_hook(save_pre_hook)

            >>> layer = LinearNet()
            >>> paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])])
            >>> print(saving_count)
            1

            >>> remove_handler.remove()
            >>> paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])])
            >>> print(saving_count)
            1
M
Ming-Xu Huang 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    """
    global _save_pre_hooks_lock
    global _save_pre_hooks
    _save_pre_hooks_lock.acquire()
    if hook not in _save_pre_hooks:
        _save_pre_hooks.append(hook)
    _save_pre_hooks_lock.release()
    return HookRemoveHelper(hook)


def _clear_save_pre_hooks():
    global _save_pre_hooks_lock
    global _save_pre_hooks
    _save_pre_hooks_lock.acquire()
    _save_pre_hooks.clear()
    _save_pre_hooks_lock.release()


def _remove_save_pre_hook(hook):
    global _save_pre_hooks_lock
    global _save_pre_hooks
    _save_pre_hooks_lock.acquire()
    if hook in _save_pre_hooks:
        _save_pre_hooks.remove(hook)
    _save_pre_hooks_lock.release()


784
@wrap_decorator
M
Ming-Xu Huang 已提交
785 786 787 788 789 790 791 792 793 794
def _run_save_pre_hooks(func):
    def wrapper(layer, path, input_spec=None, **configs):
        global _save_pre_hooks
        for hook in _save_pre_hooks:
            hook(layer, input_spec, configs)
        func(layer, path, input_spec, **configs)

    return wrapper


795
def _save_property(filename: str, property_vals: list[tuple[Any, str]]):
796 797 798
    """class property serialization.

    Args:
799 800
        filename (str): *.meta
        property_vals (list[tuple[Any, str]]): class property.
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
    """

    def set_property(meta, key, val):
        if isinstance(val, float):
            meta.set_float(key, val)
        elif isinstance(val, int):
            meta.set_int(key, val)
        elif isinstance(val, str):
            meta.set_string(key, val)
        elif isinstance(val, (tuple, list)):
            if isinstance(val[0], float):
                meta.set_floats(key, val)
            elif isinstance(val[0], int):
                meta.set_ints(key, val)
            elif isinstance(val[0], str):
                meta.set_strings(key, val)
        else:
            raise ValueError(f"Note support val type: {type(val)}")
        return

    with open(filename, 'wb') as f:
        meta = paddle.framework.core.Property()
        for item in property_vals:
            val, key = item[0], item[1]
            set_property(meta, key, val)
        f.write(meta.serialize_to_string())


M
Ming-Xu Huang 已提交
829
@_run_save_pre_hooks
830
@switch_to_static_graph
831
def save(layer, path, input_spec=None, **configs):
832
    """
833
    Saves input Layer or function as ``paddle.jit.TranslatedLayer``
834 835
    format model, which can be used for inference or fine-tuning after loading.

836
    It will save the translated program and all related persistable
837
    variables of input Layer to given ``path`` .
838 839

    ``path`` is the prefix of saved objects, and the saved translated program file
840
    suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` ,
841
    and here also saved some additional variable description information to a file,
842
    its suffix is ``.pdiparams.info``, these additional information is used in fine-tuning.
843 844

    The saved model can be loaded by follow APIs:
845 846
      - ``paddle.jit.load``
      - ``paddle.static.load_inference_model``
847 848
      - Other C++ inference APIs

849
    .. note::
850
        When using ``paddle.jit.save`` to save a function, parameters will not be saved. If you have to
851 852
        save the parameter, please pass the Layer containing function and parameter to ``paddle.jit.save``.

853
    Args:
854
        layer (Layer|function): The Layer or function to be saved.
855
        path (str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``.
856 857 858
        input_spec (list or tuple[InputSpec|Tensor|Python built-in variable], optional): Describes the input of the saved model's forward
            method, which can be described by InputSpec or example Tensor. Moreover, we support to specify non-tensor type argument,
            such as int, float, string, or list/dict of them.If None, all input variables of
859
            the original Layer's forward method would be the inputs of the saved model. Default None.
860 861
        **configs (dict, optional): Other save configuration options for compatibility. We do not
            recommend using these configurations, they may be removed in the future. If not necessary,
862 863 864
            DO NOT use them. Default None.
            The following options are currently supported:
            (1) output_spec (list[Tensor]): Selects the output targets of the saved model.
865 866 867
            By default, all return variables of original Layer's forward method are kept as the
            output of the saved model. If the provided ``output_spec`` list is not all output variables,
            the saved model will be pruned according to the given ``output_spec`` list.
868

869 870 871 872 873 874
    Returns:
        None

    Examples:
        .. code-block:: python

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
            >>> # doctest: +SKIP
            >>> # example 1: save layer
            >>> import numpy as np
            >>> import paddle
            >>> import paddle.nn as nn
            >>> import paddle.optimizer as opt

            >>> BATCH_SIZE = 16
            >>> BATCH_NUM = 4
            >>> EPOCH_NUM = 4

            >>> IMAGE_SIZE = 784
            >>> CLASS_NUM = 10

            >>> # define a random dataset
            >>> class RandomDataset(paddle.io.Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
            ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples

            >>> class LinearNet(nn.Layer):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
            ...
            ...     @paddle.jit.to_static
            ...     def forward(self, x):
            ...         return self._linear(x)

            >>> def train(layer, loader, loss_fn, opt):
            ...     for epoch_id in range(EPOCH_NUM):
            ...         for batch_id, (image, label) in enumerate(loader()):
            ...             out = layer(image)
            ...             loss = loss_fn(out, label)
            ...             loss.backward()
            ...             opt.step()
            ...             opt.clear_grad()
            ...             print("Epoch {} batch {}: loss = {}".format(
            ...                 epoch_id, batch_id, np.mean(loss.numpy())))

            >>> # 1. train & save model.

            >>> # create network
            >>> layer = LinearNet()
            >>> loss_fn = nn.CrossEntropyLoss()
            >>> adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())

            >>> # create data loader
            >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
            >>> loader = paddle.io.DataLoader(dataset,
            ...     batch_size=BATCH_SIZE,
            ...     shuffle=True,
            ...     drop_last=True,
            ...     num_workers=2
            ... )

            >>> # train
            >>> train(layer, loader, loss_fn, adam)

            >>> # save
            >>> path = "example_model/linear"
            >>> paddle.jit.save(layer, path)

            >>> # example 2: save function
            >>> import paddle
            >>> from paddle.static import InputSpec


            >>> def save_function():
            ...     @paddle.jit.to_static
            ...     def fun(inputs):
            ...         return paddle.tanh(inputs)
            ...
            ...     path = 'test_jit_save_load_function_1/func'
            ...     inps = paddle.rand([3, 6])
            ...     origin = fun(inps)
            ...
            ...     paddle.jit.save(fun, path)
            ...     load_func = paddle.jit.load(path)
            ...
            ...     load_result = load_func(inps)
            ...     print((load_result - origin).abs().max() < 1e-10)

            >>> save_function()
966 967
    """

968
    # 1. input build & check
969
    prog_translator = ProgramTranslator()
970
    is_prim_infer = core._is_fwd_prim_enabled() and core._is_bwd_prim_enabled()
971
    if not prog_translator.enable_to_static:
972
        raise RuntimeError(
R
Ryan 已提交
973
            "The paddle.jit.save doesn't work when setting 'paddle.jit.enable_to_static' to False."
974
        )
975

976
    if not (
977
        isinstance(layer, (Layer, StaticFunction)) or inspect.isfunction(layer)
978
    ):
979
        raise TypeError(
980
            "The input of paddle.jit.save should be 'Layer' or 'Function', but received input type is %s."
981 982
            % type(layer)
        )
983 984 985 986
    elif inspect.isfunction(layer) or isinstance(layer, StaticFunction):
        warnings.warn(
            'What you save is a function, and `jit.save` will generate the name of the model file according to `path` you specify. When loading these files with `jit.load`, you get a `TranslatedLayer` whose inference result is the same as the inference result of the function you saved.'
        )
987

988 989
    # NOTE(chenweihang): If the input layer be wrapped by DataParallel,
    # the args and kwargs of forward method will can't be parsed by
990
    # function_spec, so here we save DataParallel._layers instead
991 992 993 994 995 996 997
    # DataParallel it self
    # NOTE(chenweihang): using inner_layer, do not change input layer
    if isinstance(layer, paddle.DataParallel):
        inner_layer = layer._layers
    else:
        inner_layer = layer

998 999 1000 1001 1002 1003
    # path check
    file_prefix = os.path.basename(path)
    if file_prefix == "":
        raise ValueError(
            "The input path MUST be format of dirname/file_prefix "
            "[dirname\\file_prefix in Windows system], but received "
1004 1005
            "file_prefix is empty string."
        )
1006 1007 1008 1009

    dirname = os.path.dirname(path)
    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)
1010

1011 1012
    # avoid change user given input_spec
    inner_input_spec = None
1013
    if input_spec is not None:
1014 1015 1016
        if isinstance(layer, Layer):
            for attr_func in dir(inner_layer):
                static_func = getattr(inner_layer, attr_func, None)
1017 1018 1019 1020
                if (
                    isinstance(static_func, StaticFunction)
                    and 'forward' != attr_func
                ):
1021 1022
                    raise ValueError(
                        "If there are static functions other than 'forward' that need to be saved, the input 'input_spec' should be None, but received the type of 'input_spec' is %s."
1023 1024
                        % type(input_spec)
                    )
1025

1026
        if not isinstance(input_spec, (list, tuple)):
1027 1028
            raise TypeError(
                "The input input_spec should be 'list', but received input_spec's type is %s."
1029 1030
                % type(input_spec)
            )
1031
        inner_input_spec = []
1032
        for var in paddle.utils.flatten(input_spec):
1033 1034
            if isinstance(var, paddle.static.InputSpec):
                inner_input_spec.append(var)
W
wanghuancoder 已提交
1035
            elif isinstance(var, (core.eager.Tensor, Variable)):
1036
                inner_input_spec.append(
1037 1038
                    paddle.static.InputSpec.from_tensor(var)
                )
1039
            else:
1040 1041
                # NOTE(Aurelius84): Support non-Tensor type in `input_spec`.
                inner_input_spec.append(var)
1042

1043 1044
    # parse configs
    configs = _parse_save_configs(configs)
1045
    # whether outermost layer has pre/post hook, if does, we need also save
1046
    # these operators in program.
1047
    with_hook = configs.with_hook
1048 1049 1050
    combine_params = configs.combine_params
    if combine_params:
        configs._program_only = True
1051

1052
    scope = core.Scope()
1053
    extra_var_info = {}
1054 1055
    if isinstance(layer, Layer):
        functions = dir(inner_layer)
1056 1057
        if inner_layer._forward_pre_hooks or inner_layer._forward_post_hooks:
            with_hook = True
1058 1059
    else:
        # layer is function
1060 1061 1062
        functions = [
            layer,
        ]
1063

1064
    combine_vars = {}
1065
    property_vals = []  # (value, key)
H
Hui Zhang 已提交
1066
    concrete_program = None
1067 1068
    for attr_func in functions:
        if isinstance(layer, Layer):
X
xiongkun 已提交
1069 1070 1071
            static_func = get_ast_static_function(
                getattr(inner_layer, attr_func, None)
            )
1072
            if isinstance(static_func, StaticFunction):
1073 1074 1075 1076
                if static_func.is_property:
                    # property method to be exported
                    immediate_val = static_func()
                    property_vals.append(
1077 1078 1079 1080 1081
                        (
                            immediate_val,
                            layer.__class__.__name__ + '.' + attr_func,
                        )
                    )
1082 1083
                    continue

1084 1085
                concrete_program = (
                    static_func.concrete_program_specify_input_spec(
1086 1087 1088
                        inner_input_spec,
                        with_hook=with_hook,
                        is_prim_infer=is_prim_infer,
1089 1090
                    )
                )
1091
            elif 'forward' == attr_func:
H
Hui Zhang 已提交
1092 1093 1094 1095
                if configs.skip_forward:
                    # do not jit.save forward function
                    continue

1096
                # transform in jit.save, if input_spec is incomplete, declarative will throw error
1097
                # inner_input_spec is list[InputSpec], it should be packed with same structure
1098 1099
                # as original input_spec here.
                if inner_input_spec:
1100
                    inner_input_spec = paddle.utils.pack_sequence_as(
1101 1102
                        input_spec, inner_input_spec
                    )
H
hjyp 已提交
1103
                static_forward = to_static(
X
xiongkun 已提交
1104 1105 1106
                    inner_layer.forward,
                    input_spec=inner_input_spec,
                    enable_fallback=False,
1107 1108 1109
                )
                concrete_program = (
                    static_forward.concrete_program_specify_input_spec(
1110
                        with_hook=with_hook, is_prim_infer=is_prim_infer
1111 1112
                    )
                )
1113
                # the input_spec has been used in declarative, which is equal to
H
hjyp 已提交
1114
                # @to_static with input_spec and jit.save without input_spec,
1115 1116 1117 1118
                # avoid needless warning
                inner_input_spec = None
            else:
                continue
1119 1120 1121
        else:
            # When layer is a function
            if isinstance(attr_func, StaticFunction):
X
xiongkun 已提交
1122 1123 1124
                static_func = get_ast_static_function(attr_func)

                if static_func.is_property:
1125
                    # property method to be exported
X
xiongkun 已提交
1126 1127
                    immediate_val = static_func()
                    property_vals.append((immediate_val, static_func))
1128 1129
                    continue

1130
                concrete_program = (
X
xiongkun 已提交
1131
                    static_func.concrete_program_specify_input_spec(
1132
                        inner_input_spec, is_prim_infer=is_prim_infer
1133 1134
                    )
                )
1135
            else:
X
xiongkun 已提交
1136
                static_func = get_ast_static_function(attr_func)
1137
                if inner_input_spec:
1138
                    inner_input_spec = paddle.utils.pack_sequence_as(
1139 1140
                        input_spec, inner_input_spec
                    )
H
hjyp 已提交
1141
                static_function = to_static(
X
xiongkun 已提交
1142 1143 1144
                    static_func,
                    input_spec=inner_input_spec,
                    enable_fallback=False,
1145
                )
1146 1147 1148 1149
                concrete_program = static_function.concrete_program

                if static_function._class_instance is None:
                    warnings.warn(
1150 1151 1152 1153
                        '`jit.save` will only save the `Program`, not the parameters. If you have to save the parameters, please make sure that {} is a member function of `paddle.nn.Layer` and the saved parameters are in `state_dict`'.format(
                            layer
                        )
                    )
1154

1155
        # when save multi `StaticFunction`, all `StaticFunction` share params.
1156 1157
        dygraph_state_dict = None
        if isinstance(inner_layer, Layer):
1158
            dygraph_state_dict = inner_layer.to_static_state_dict()
1159
        elif isinstance(attr_func, StaticFunction):
X
xiongkun 已提交
1160
            if static_func._class_instance:
1161
                dygraph_state_dict = (
X
xiongkun 已提交
1162
                    static_func._class_instance.to_static_state_dict()
1163
                )
1164 1165

        if dygraph_state_dict:
1166 1167 1168 1169
            # NOTE(chenweihang): we maintain the mapping of variable name to
            # structured name, the buffer variable (non-persistable)
            # saved to inference program may not need by dygraph Layer,
            # we only record the state_dict variable's structured name
1170 1171
            state_names_dict = {}
            state_var_dict = {}
1172
            for structured_name, var in dygraph_state_dict.items():
1173
                state_names_dict[var.name] = structured_name
1174
                state_var_dict[var.name] = var
1175

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
        # 3. share parameters from Layer to scope & record var info
        with dygraph.guard():
            for param_or_buffer in concrete_program.parameters:
                # share to scope
                if param_or_buffer.type == core.VarDesc.VarType.VOCAB:
                    scr_tensor = param_or_buffer.value().get_map_tensor()
                    tgt_var = scope.var(param_or_buffer.name)
                    tgt_var.set_vocab(scr_tensor)
                else:
                    param_or_buffer_tensor = scope.var(
1186 1187 1188 1189 1190 1191 1192 1193
                        param_or_buffer.name
                    ).get_tensor()
                    # src_tensor = param_or_buffer.value().get_tensor()
                    src_tensor = (
                        state_var_dict[param_or_buffer.name]
                        .value()
                        .get_tensor()
                    )
1194 1195 1196
                    param_or_buffer_tensor._share_data_with(src_tensor)
                # record var info
                if param_or_buffer.name not in extra_var_info:
1197
                    extra_info_dict = {}
1198 1199
                    if param_or_buffer.name in state_names_dict:
                        extra_info_dict['structured_name'] = state_names_dict[
1200 1201
                            param_or_buffer.name
                        ]
1202
                    extra_info_dict[
1203 1204
                        'stop_gradient'
                    ] = param_or_buffer.stop_gradient
W
wanghuancoder 已提交
1205
                    if isinstance(param_or_buffer, EagerParamBase):
1206 1207
                        extra_info_dict['trainable'] = param_or_buffer.trainable
                    extra_var_info[param_or_buffer.name] = extra_info_dict
1208 1209

        # 4. build input & output of save_infernece_model
1210 1211 1212 1213 1214 1215 1216 1217
        # NOTE(chenweihang): [ Get input variables name ]
        # There are two cases, whether to prune the inputs or not
        # - not prune inputs (recommend):
        #   - the len(input_spec) == len((concrete_program.inputs) - 1
        #   - here can use concrete_program.inputs directly
        # - prune inputs:
        #   - the input_spec length < len((concrete_program.inputs) - 1
        #   - the input_spec's name should be in concrete_program.inputs
1218
        input_var_names = _get_input_var_names(
1219 1220 1221
            concrete_program.inputs,
            inner_input_spec,
            configs.input_names_after_prune,
1222
        )
1223 1224

        # NOTE(chenweihang): [ Get output variables ]
1225
        # the rule is like [ Get input variables name ]. For output var,
W
wanghuancoder 已提交
1226
        # we only support Tensor spec, and actually, we only need the
1227
        # var name of output, and we don't recommended to use output_spec
1228 1229
        # print(concrete_program.main_program)
        # print(concrete_program.outputs, configs.output_spec)
1230 1231 1232
        output_vars = _get_output_vars(
            concrete_program.outputs, configs.output_spec, with_hook
        )
1233 1234 1235 1236 1237

        # 5. save inference model
        # construct new save_inference_model arguments
        model_path = dirname
        # NOTE(chenweihang): because prefix contains model and params filename,
1238
        # so we don't support set model_filename & params_filename
1239
        if 'forward' == attr_func or not isinstance(layer, Layer):
1240 1241
            model_filename = file_prefix + INFER_MODEL_SUFFIX
            params_filename = file_prefix + INFER_PARAMS_SUFFIX
1242
            path_prefix = file_prefix
1243 1244
        else:
            model_filename = file_prefix + '.' + attr_func + INFER_MODEL_SUFFIX
1245 1246 1247
            params_filename = (
                file_prefix + '.' + attr_func + INFER_PARAMS_SUFFIX
            )
1248 1249
            file_prefix = file_prefix + '.' + attr_func
        file_prefix = os.path.join(model_path, file_prefix)
1250
        with scope_guard(scope):
1251 1252 1253 1254
            input_vars = []
            for var in concrete_program.main_program.clone().list_vars():
                if var.name in input_var_names:
                    input_vars.append(var)
1255
            save_inference_model(
1256 1257 1258
                path_prefix=file_prefix,
                feed_vars=input_vars,
                fetch_vars=output_vars,
1259
                executor=Executor(_current_expected_place()),
1260
                program=concrete_program.main_program.clone(),
1261 1262
                clip_extra=configs.clip_extra,
            )
1263

1264 1265 1266
        if combine_params:
            clone_main_program = concrete_program.main_program.clone()
            clone_main_program = clone_main_program._prune_with_input(
1267 1268
                input_var_names, output_vars
            )
1269 1270
            for block in clone_main_program.blocks:
                combine_vars.update(block.vars)
1271 1272 1273

    # save shared params
    if combine_params:
1274 1275 1276 1277 1278 1279
        # sort vars by name
        combine_vars = sorted(combine_vars.items(), key=lambda item: item[0])
        ordered_vars = []
        for name, var in combine_vars:
            ordered_vars.append(var)

1280 1281
        params_filename = file_prefix + INFER_PARAMS_SUFFIX
        with scope_guard(scope):
1282 1283 1284
            paddle.static.save_vars(
                Executor(_current_expected_place()),
                dirname=model_path,
1285 1286 1287 1288 1289
                vars=list(
                    filter(
                        paddle.framework.io_utils.is_persistable, ordered_vars
                    )
                ),
1290 1291
                filename=params_filename,
            )
1292
        # save property
1293 1294 1295
        property_save_path = os.path.join(
            os.path.normpath(model_path), file_prefix + INFER_PROPERTY_SUFFIX
        )
1296
        _save_property(property_save_path, property_vals)
1297

1298 1299 1300 1301 1302 1303 1304
    # NOTE(chenweihang): [ Save extra variable info ]
    # save_inference_model will lose some important variable information, including:
    #   - Variable name and correspondence (when saved variables as one file)
    #   - Variable.stop_gradient information
    #   - Which persistent variable are parameter and which are not
    #   - Parameter.trainable information
    #
1305 1306
    # The lost information cannot be recovered when it is loaded again,
    # so if we want to perform fine-tune after loading, we may need to
1307 1308
    # configure redundant information to proceed.
    #
1309 1310
    # Due to compatibility issues, we cannot change the original storage structure,
    # but we can save these information in `jit.save` without changing the original
1311 1312
    # storage to improve user experience. So we save extra information into
    # file `***.pdiparams.info`
1313 1314 1315

    # "layer" can only be Layer or function or StaticFunction.
    contain_parameter = False
H
Hui Zhang 已提交
1316 1317 1318
    if concrete_program is not None:
        for var in concrete_program.main_program.list_vars():
            contain_parameter |= isinstance(var, Parameter)
1319 1320

    if (isinstance(layer, Layer) or contain_parameter) and extra_var_info:
1321 1322 1323 1324
        with scope_guard(scope):
            extra_var_info_path = path + INFER_PARAMS_INFO_SUFFIX
            with open(extra_var_info_path, 'wb') as f:
                pickle.dump(extra_var_info, f, protocol=2)
1325 1326 1327


@dygraph_only
1328
def load(path, **configs):
1329 1330 1331
    """
    :api_attr: imperative

1332 1333
    Load model saved by ``paddle.jit.save`` or ``paddle.static.save_inference_model`` or
    paddle 1.x API ``paddle.fluid.io.save_inference_model`` as ``paddle.jit.TranslatedLayer``,
1334
    then performing inference or fine-tune training.
1335 1336

    .. note::
1337
        If you load model saved by ``paddle.static.save_inference_model`` ,
1338 1339
        there will be the following limitations when using it in fine-tuning:
        1. Imperative mode do not support LoDTensor. All original model's feed targets or parametars that depend on LoD are temporarily unavailable.
1340
        2. All saved model's feed targets need to be passed into TranslatedLayer's forward function.
1341 1342 1343 1344
        3. The variable's ``stop_gradient`` information is lost and can not be recovered.
        4. The parameter's ``trainable`` information is lost and can not be recovered.

    Args:
1345
        path (str): The path prefix to load model. The format is ``dirname/file_prefix`` or ``file_prefix`` .
1346 1347
        **configs (dict, optional): Other load configuration options for compatibility. We do not
            recommend using these configurations, they may be removed in the future. If not necessary,
1348 1349
            DO NOT use them. Default None.
            The following options are currently supported:
1350 1351 1352 1353
            (1) model_filename (str): The inference model file name of the paddle 1.x
            ``save_inference_model`` save format. Default file name is :code:`__model__` .
            (2) params_filename (str): The persistable variables file name of the paddle 1.x
            ``save_inference_model`` save format. No default file name, save variables separately
1354 1355
            by default.

1356 1357 1358 1359 1360

    Returns:
        TranslatedLayer: A Layer object can run saved translated model.

    Examples:
1361
        1. Load model saved by ``paddle.jit.save`` then performing inference and fine-tune training.
1362

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
            .. code-block:: python
                :name: code-example1

                >>> # doctest: +SKIP
                >>> import numpy as np
                >>> import paddle
                >>> import paddle.nn as nn
                >>> import paddle.optimizer as opt

                >>> BATCH_SIZE = 16
                >>> BATCH_NUM = 4
                >>> EPOCH_NUM = 4

                >>> IMAGE_SIZE = 784
                >>> CLASS_NUM = 10

                >>> # define a random dataset
                >>> class RandomDataset(paddle.io.Dataset):
                ...     def __init__(self, num_samples):
                ...         self.num_samples = num_samples
                ...
                ...     def __getitem__(self, idx):
                ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
                ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
                ...         return image, label
                ...
                ...     def __len__(self):
                ...         return self.num_samples

                >>> class LinearNet(nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
                ...
                ...     @paddle.jit.to_static
                ...     def forward(self, x):
                ...         return self._linear(x)
                ...
                >>> def train(layer, loader, loss_fn, opt):
                ...     for epoch_id in range(EPOCH_NUM):
                ...         for batch_id, (image, label) in enumerate(loader()):
                ...             out = layer(image)
                ...             loss = loss_fn(out, label)
                ...             loss.backward()
                ...             opt.step()
                ...             opt.clear_grad()
                ...             print("Epoch {} batch {}: loss = {}".format(
                ...                 epoch_id, batch_id, np.mean(loss.numpy())))

                >>> # 1. train & save model.

                >>> # create network
                >>> layer = LinearNet()
                >>> loss_fn = nn.CrossEntropyLoss()
                >>> adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())

                >>> # create data loader
                >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
                >>> loader = paddle.io.DataLoader(
                ...     dataset,
                ...     batch_size=BATCH_SIZE,
                ...     shuffle=True,
                ...     drop_last=True,
                ...     num_workers=2
                ... )

                >>> # train
                >>> train(layer, loader, loss_fn, adam)

                >>> # save
                >>> path = "example_model/linear"
                >>> paddle.jit.save(layer, path)

                >>> # 2. load model

                >>> # load
                >>> loaded_layer = paddle.jit.load(path)

                >>> # inference
                >>> loaded_layer.eval()
                >>> x = paddle.randn([1, IMAGE_SIZE], 'float32')
                >>> pred = loaded_layer(x)

                >>> # fine-tune
                >>> loaded_layer.train()
                >>> adam = opt.Adam(learning_rate=0.001, parameters=loaded_layer.parameters())
                >>> train(loaded_layer, loader, loss_fn, adam)
1450 1451


1452
        2. Load model saved by ``paddle.fluid.io.save_inference_model`` then performing and fine-tune training.
1453

1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
            .. code-block:: python
                :name: code-example2

                >>> import numpy as np
                >>> import paddle
                >>> import paddle.static as static
                >>> import paddle.nn as nn
                >>> import paddle.optimizer as opt
                >>> import paddle.nn.functional as F

                >>> BATCH_SIZE = 16
                >>> BATCH_NUM = 4
                >>> EPOCH_NUM = 4

                >>> IMAGE_SIZE = 784
                >>> CLASS_NUM = 10

                >>> # define a random dataset
                >>> class RandomDataset(paddle.io.Dataset):
                ...     def __init__(self, num_samples):
                ...         self.num_samples = num_samples
                ...
                ...     def __getitem__(self, idx):
                ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
                ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
                ...         return image, label
                ...
                ...     def __len__(self):
                ...         return self.num_samples

                >>> paddle.enable_static()

                >>> image = static.data(name='image', shape=[None, 784], dtype='float32')
                >>> label = static.data(name='label', shape=[None, 1], dtype='int64')
                >>> pred = static.nn.fc(x=image, size=10, activation='softmax')
                >>> loss = F.cross_entropy(input=pred, label=label)
                >>> avg_loss = paddle.mean(loss)

                >>> optimizer = paddle.optimizer.SGD(learning_rate=0.001)
                >>> optimizer.minimize(avg_loss)

                >>> place = paddle.CPUPlace()
                >>> exe = static.Executor(place)
                >>> exe.run(static.default_startup_program())

                >>> # create data loader
                >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
                >>> loader = paddle.io.DataLoader(dataset,
                ...     feed_list=[image, label],
                ...     places=place,
                ...     batch_size=BATCH_SIZE,
                ...     shuffle=True,
                ...     drop_last=True,
                ...     return_list=False,
                ...     num_workers=2
                ... )

                >>> # 1. train and save inference model
                >>> for data in loader():
                >>>     exe.run(
                ...         static.default_main_program(),
                ...         feed=data,
                ...         fetch_list=[avg_loss]
                ...     )

                >>> model_path = "fc.example.model"
                >>> paddle.fluid.io.save_inference_model(
                >>> model_path, ["image"], [pred], exe)

                >>> # 2. load model

                >>> # enable dygraph mode
                >>> paddle.disable_static(place)

                >>> # load
                >>> fc = paddle.jit.load(model_path)

                >>> # inference
                >>> fc.eval()
                >>> x = paddle.randn([1, IMAGE_SIZE], 'float32')
                >>> pred = fc(x)

                >>> # fine-tune
                >>> fc.train()
                >>> loss_fn = nn.CrossEntropyLoss()
                >>> adam = opt.Adam(learning_rate=0.001, parameters=fc.parameters())
                >>> loader = paddle.io.DataLoader(dataset,
                ...     places=place,
                ...     batch_size=BATCH_SIZE,
                ...     shuffle=True,
                ...     drop_last=True,
                ...     num_workers=2
                ... )
                >>> for epoch_id in range(EPOCH_NUM):
                ...     for batch_id, (image, label) in enumerate(loader()):
                ...         out = fc(image)
                ...         loss = loss_fn(out, label)
                ...         loss.backward()
                ...         adam.step()
                ...         adam.clear_grad()
                ...         print("Epoch {} batch {}: loss = {}".format(
                ...             epoch_id, batch_id, np.mean(loss.numpy())))
1556
    """
1557 1558 1559 1560
    # 1. construct correct config
    config = _parse_load_config(configs)
    model_path, config = _build_load_path_and_config(path, config)

1561
    return TranslatedLayer._construct(model_path, config)
1562 1563


1564
@dygraph_only
1565 1566 1567
def _trace(
    layer, inputs, feed_prefix='feed_', fetch_prefix='fetch_', tmp_prefix='t_'
):
1568
    assert isinstance(layer, Layer)
1569 1570 1571 1572 1573 1574 1575 1576 1577

    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):
1578
        original_outputs = layer(*inputs)
1579 1580 1581 1582
        if not isinstance(original_outputs, (list, tuple)):
            outputs = [original_outputs]
        else:
            outputs = original_outputs
1583
        out_vars = extract_vars(outputs, err_tag='outputs')
1584

1585 1586 1587 1588 1589 1590 1591 1592
        (
            program_desc,
            feed_names,
            fetch_names,
            parameters,
        ) = tracer.create_program_desc(
            var_list, feed_prefix, out_vars, fetch_prefix, tmp_prefix
        )
1593 1594 1595 1596 1597
        tracer.reset()

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

1598
    return original_outputs, program, feed_names, fetch_names, parameters
1599 1600


1601
class TracedLayer:
1602
    """
1603
    :api_attr: imperative
1604

1605 1606 1607 1608 1609
    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.
1610 1611 1612 1613

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

    All TracedLayer objects should not be created by constructor and should
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    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
1627
        self._params = parameters
1628 1629 1630 1631 1632

        self._place = _current_expected_place()

        self._scope = core.Scope()
        for p in parameters:
1633
            src_tensor = p.value().get_tensor()
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
            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):
        """
1657
        This method is the only allowed method to create TracedLayer object.
1658 1659 1660 1661
        It would call the :code:`layer(*inputs)` method to run the dygraph
        model and convert it into a static graph model.

        Args:
1662
            layer (paddle.nn.Layer): the layer object to be traced.
1663 1664
            inputs (list(Tensor)|tuple(Tensor)|Tensor): the input tensors of
                the layer object.
1665 1666

        Returns:
1667
            tuple: A tuple of 2 items, whose the first item is the output of
1668 1669
                :code:`layer(*inputs)` , and the second item is the created
                TracedLayer object.
1670

1671
        Examples:
G
gouzil 已提交
1672
            .. code-block:: python
1673

1674
                >>> import paddle
1675

1676 1677 1678 1679 1680 1681 1682
                >>> class ExampleLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._fc = paddle.nn.Linear(3, 10)
                ...
                ...     def forward(self, input):
                ...         return self._fc(input)
1683

1684

1685 1686 1687
                >>> layer = ExampleLayer()
                >>> in_var = paddle.uniform(shape=[2, 3], dtype='float32')
                >>> out_dygraph, static_layer = paddle.jit.TracedLayer.trace(layer, inputs=[in_var])
1688

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

1692 1693
                >>> print(len(out_static_graph)) # 1
                >>> print(out_static_graph[0].shape) # (2, 10)
1694

1695 1696
                >>> # save the static graph model for inference
                >>> static_layer.save_inference_model('./saved_infer_model')
1697

1698
        """
1699 1700
        assert isinstance(
            layer, Layer
1701
        ), "The type of 'layer' in paddle.jit.TracedLayer.trace must be paddle.nn.Layer, but received {}.".format(
1702 1703
            type(layer)
        )
1704 1705
        outs, prog, feed, fetch, parameters = _trace(layer, inputs)
        traced = TracedLayer(prog, parameters, feed, fetch)
1706 1707 1708 1709 1710 1711 1712
        return outs, traced

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

        Args:
1713
            build_strategy (BuildStrategy, optional): build strategy of
1714 1715 1716 1717 1718 1719 1720 1721
                :code:`CompiledProgram` inside TracedLayer. Default None.
            exec_strategy (ExecutionStrategy, optional): execution strategy of
                :code:`CompiledProgram` inside TracedLayer. Default None.

        Returns:
            None

        Examples:
G
gouzil 已提交
1722
            .. code-block:: python
1723

1724
                >>> import paddle
1725

1726 1727 1728 1729 1730 1731 1732
                >>> class ExampleLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._fc = paddle.nn.Linear(3, 10)
                ...
                ...     def forward(self, input):
                ...         return self._fc(input)
1733

1734 1735
                >>> layer = ExampleLayer()
                >>> in_var = paddle.uniform(shape=[2, 3], dtype='float32')
1736

1737
                >>> out_dygraph, static_layer = paddle.jit.TracedLayer.trace(layer, inputs=[in_var])
1738

1739 1740
                >>> build_strategy = paddle.static.BuildStrategy()
                >>> build_strategy.enable_inplace = True
1741

1742 1743
                >>> exec_strategy = paddle.static.ExecutionStrategy()
                >>> exec_strategy.num_threads = 2
1744

1745 1746
                >>> static_layer.set_strategy(build_strategy=build_strategy, exec_strategy=exec_strategy)
                >>> out_static_graph = static_layer([in_var])
1747 1748 1749

        """
        assert self._compiled_program is None, "Cannot set strategy after run"
1750 1751
        assert isinstance(
            build_strategy, (type(None), BuildStrategy)
1752
        ), "The type of 'build_strategy' in paddle.jit.TracedLayer.set_strategy must be fluid.BuildStrategy, but received {}.".format(
1753 1754
            type(build_strategy)
        )
1755 1756
        assert isinstance(
            exec_strategy, (type(None), ExecutionStrategy)
1757
        ), "The type of 'exec_strategy' in paddle.jit.TracedLayer.set_strategy must be fluid.ExecutionStrategy, but received {}.".format(
1758 1759
            type(exec_strategy)
        )
1760 1761 1762 1763 1764 1765
        self._build_strategy = build_strategy
        self._exec_strategy = exec_strategy

    @switch_to_static_graph
    def _compile(self):
        self._compiled_program = CompiledProgram(
K
kangguangli 已提交
1766
            self._program,
1767 1768
            build_strategy=self._build_strategy,
        )
1769 1770

    def _build_feed(self, inputs):
1771 1772 1773
        assert isinstance(
            inputs, (list, tuple)
        ), "Inputs should be a list or tuple of variables"
1774 1775
        assert len(inputs) == len(self._feed_names)
        feed_dict = {}
1776
        if in_dynamic_mode():
1777
            for x, name in zip(inputs, self._feed_names):
1778
                feed_dict[name] = x.value().get_tensor()
1779 1780 1781 1782 1783 1784 1785 1786
        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):
1787 1788 1789
        return self._exe.run(
            self._compiled_program, feed=feed, fetch_list=self._fetch_names
        )
1790 1791 1792 1793 1794 1795 1796 1797 1798

    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
1799
    def save_inference_model(self, path, feed=None, fetch=None, **kwargs):
1800
        """
1801 1802
        Save the TracedLayer to a model for inference. The saved
        inference model can be loaded by C++ inference APIs.
1803

1804 1805 1806
        ``path`` is the prefix of saved objects, and the saved translated program file
        suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` .

1807
        Args:
1808
            path(str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``.
1809
            feed (list[int], optional): the input variable indices of the saved
1810
                inference model. If None, all input variables of the
1811 1812 1813 1814 1815 1816
                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.
1817 1818 1819
            kwargs: Supported keys including
                - clip_extra(bool): whether to clip extra information for every operator. Defaults to True.
                - legacy_format(bool): whether to save program in legacy format. Default to False.
1820 1821

        Returns:
1822
            None
1823 1824

        Examples:
G
gouzil 已提交
1825
            .. code-block:: python
1826

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
                >>> import numpy as np
                >>> import paddle

                >>> class ExampleLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._fc = paddle.nn.Linear(3, 10)
                ...
                ...     def forward(self, input):
                ...         return self._fc(input)

                >>> save_dirname = './saved_infer_model'
                >>> in_np = np.random.random([2, 3]).astype('float32')
                >>> in_var = paddle.to_tensor(in_np)
                >>> layer = ExampleLayer()

                >>> out_dygraph, static_layer = paddle.jit.TracedLayer.trace(layer, inputs=[in_var])
                >>> static_layer.save_inference_model(save_dirname, feed=[0], fetch=[0])

                >>> paddle.enable_static()
                >>> place = paddle.CPUPlace()
                >>> exe = paddle.static.Executor(place)
                >>> program, feed_vars, fetch_vars = paddle.static.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]
1857
        """
1858 1859 1860 1861
        check_type(
            path,
            "path",
            str,
1862
            "paddle.jit.TracedLayer.save_inference_model",
1863 1864 1865 1866 1867
        )
        check_type(
            feed,
            "feed",
            (type(None), list),
1868
            "paddle.jit.TracedLayer.save_inference_model",
1869
        )
1870 1871
        if isinstance(feed, list):
            for f in feed:
1872
                check_type(
1873 1874 1875
                    f,
                    "each element of feed",
                    int,
1876
                    "paddle.jit.TracedLayer.save_inference_model",
1877 1878 1879 1880 1881
                )
        check_type(
            fetch,
            "fetch",
            (type(None), list),
1882
            "paddle.jit.TracedLayer.save_inference_model",
1883
        )
1884 1885
        if isinstance(fetch, list):
            for f in fetch:
1886
                check_type(
1887 1888 1889
                    f,
                    "each element of fetch",
                    int,
1890
                    "paddle.jit.TracedLayer.save_inference_model",
1891
                )
1892
        clip_extra = kwargs.get('clip_extra', True)
1893 1894 1895 1896 1897 1898
        # path check
        file_prefix = os.path.basename(path)
        if file_prefix == "":
            raise ValueError(
                "The input path MUST be format of dirname/file_prefix "
                "[dirname\\file_prefix in Windows system], but received "
1899 1900
                "file_prefix is empty string."
            )
1901 1902 1903 1904 1905

        dirname = os.path.dirname(path)
        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)

1906 1907 1908 1909
        def get_feed_fetch(all_vars, partial_vars):
            if partial_vars is None:
                return all_vars

1910
            return [all_vars[idx] for idx in partial_vars]
1911 1912 1913 1914

        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)
1915 1916 1917 1918 1919
            feed_vars = []
            for name in feeded_var_names:
                feed_var = self._program.global_block().vars.get(name, None)
                assert feed_var is not None, f"{name} cannot be found"
                feed_vars.append(feed_var)
1920 1921 1922
            target_vars = []
            for name in target_var_names:
                target_var = self._program.global_block().vars.get(name, None)
1923
                assert target_var is not None, f"{name} cannot be found"
1924
                target_vars.append(target_var)
1925
            legacy_format = kwargs.get('legacy_format', False)
1926
            file_prefix = os.path.join(dirname, file_prefix)
1927
            save_inference_model(
1928 1929 1930
                path_prefix=file_prefix,
                feed_vars=feed_vars,
                fetch_vars=target_vars,
1931
                executor=self._exe,
1932
                program=self._program.clone(),
1933
                clip_extra=clip_extra,
1934
                legacy_format=legacy_format,
1935
            )
X
xiongkun 已提交
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961


def get_ast_static_function(function):
    if isinstance(function, SymbolicStaticFunction):
        if function._class_instance:
            dygraph_function = types.MethodType(
                function._dygraph_function, function._class_instance
            )
        else:
            dygraph_function = function._dygraph_function

        if function._function_spec._input_spec is None:
            ast_static_function = ASTStaticFunction(
                dygraph_function,
                function.last_call_input_spec,
                **function._kwargs,
            )
            return ast_static_function
        else:
            ast_static_function = ASTStaticFunction(
                dygraph_function,
                function._function_spec._input_spec,
                **function._kwargs,
            )
            return ast_static_function
    return function