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

from __future__ import print_function

import os
import collections
import pickle
import six
import warnings
22
import sys
W
WeiXin 已提交
23
import numpy as np
24

25 26 27
if not six.PY2:
    import copyreg

28 29 30 31 32
import paddle

# deprecated module import
from paddle import fluid
from paddle.fluid import core
33 34 35 36
from paddle.fluid.io import _unpack_saved_dict, _pack_loaded_dict, _pickle_loads_mac
from paddle.fluid.io import _legacy_save as _legacy_static_save

from paddle.fluid.framework import Variable, _varbase_creator, _dygraph_tracer, in_dygraph_mode, ParamBase, _current_expected_place
37 38 39
from paddle.fluid.dygraph.jit import _SaveLoadConfig
from paddle.fluid.dygraph.io import _construct_program_holders, _construct_params_and_buffers
from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX, INFER_PARAMS_INFO_SUFFIX
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

__all__ = [
    'save',
    'load',
]


def _build_saved_state_dict(state_dict):
    save_dict = {}
    name_table = {}
    for key, value in state_dict.items():
        if isinstance(value, (Variable, core.VarBase)):
            save_dict[key] = value.numpy()
            name_table[key] = value.name
        else:
            save_dict[key] = value
    save_dict["StructuredToParameterName@@"] = name_table

    return save_dict


def _load_state_dict_from_save_inference_model(model_path, config):
    # 1. load program desc & construct _ProgramHolder
    programs = _construct_program_holders(model_path, config.model_filename)

    # 2. load layer parameters & buffers
    with fluid.dygraph.guard():
        persistable_var_dict = _construct_params_and_buffers(
68
            model_path, programs, config.params_filename, append_suffix=False)
69 70 71 72 73 74

        # 3. construct state_dict
        load_param_dict = dict()
        for var_name in persistable_var_dict:
            load_param_dict[var_name] = persistable_var_dict[var_name].numpy()

75 76 77
        # if *.info exists, we can recover structured_name
        var_info_filename = str(config.params_filename) + ".info"
        var_info_path = os.path.join(model_path, var_info_filename)
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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        if os.path.exists(var_info_path):
            with open(var_info_path, 'rb') as f:
                extra_var_info = pickle.load(f)
            structured_para_dict = dict()
            for var_name in load_param_dict:
                structured_name = extra_var_info[var_name].get(
                    'structured_name', None)
                assert structured_name is not None, "Cannot find saved variable (%s)'s structured name in saved model." % var_name
                structured_para_dict[structured_name] = load_param_dict[
                    var_name]
            load_param_dict = structured_para_dict

    return load_param_dict


def _load_state_dict_from_save_params(model_path):
    # Try to load all the files in the directory in VarBase format, 
    # the file name is used as the name of VarBase
    load_var_list = []

    # 1. load file names
    var_name_list = []
    for root, _, files in os.walk(model_path):
        for filename in files:
            file_path = os.path.join(root, filename)
            tmp_var_name = os.path.relpath(file_path, model_path)
            var_name = tmp_var_name.replace("\\", "/")
            var_name_list.append(var_name)

    # 2. create and load VarBase
    with fluid.dygraph.guard():
        for name in var_name_list:
            new_var = _varbase_creator(name=name, persistable=True)
            _dygraph_tracer().trace_op(
                type='load',
                inputs={},
                outputs={'Out': new_var},
                attrs={'file_path': os.path.join(model_path, name)})
            load_var_list.append(new_var)

    # 3. construct state_dict
    load_param_dict = dict()
    for var in load_var_list:
        load_param_dict[var.name] = var.numpy()

    return load_param_dict


126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
# NOTE(chenweihang): [ Handling of use cases of API paddle.load ]
# `paddle.load` may be used to load saved results of:
# 1. Expected cases:
#   - need [full filename] when loading
#       - paddle.save
#       - paddle.static.save
#       - paddle.fluid.save_dygraph
#   - need [prefix] when loading [compatible for paddle 2.x]
#       - paddle.jit.save
#       - paddle.static.save_inference_model
#   - need [directory] when loading [compatible for paddle 1.x]
#       - paddle.fluid.io.save_inference_model
#       - paddle.fluid.io.save_params/save_persistable
# 2. Error cases:
#   - no error case
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(
            "The %s.pdmodel and %s directory exist at the same time, "
            "don't know which one to load, please make sure that the specified target "
            "of ``path`` is unique." % (path, path))
    elif not prefix_format_exist and not directory_format_exist:
        error_msg = "The ``path`` (%s) to load model not exists."
        # if current path is a prefix, and the path.pdparams or path.pdopt
        # is exist, users may want use `paddle.load` load the result of 
        # `fluid.save_dygraph`, we raise error here for users
        params_file_path = path + ".pdparams"
        opti_file_path = path + ".pdopt"
        if os.path.exists(params_file_path) or os.path.exists(opti_file_path):
            error_msg += " If you want to load the results saved by `fluid.save_dygraph`, " \
                "please specify the full file name, not just the file name prefix. For " \
                "example, it should be written as `paddle.load('model.pdparams')` instead of " \
                "`paddle.load('model')`."
        raise ValueError(error_msg % path)
    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 "
                    "not take effect.")
            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 "
                    "not take effect.")
            config.params_filename = file_prefix + INFER_PARAMS_SUFFIX
        else:
            # Compatible with the old save_inference_model format
            model_path = path

    return model_path, config


def _parse_load_config(configs):
189 190 191
    supported_configs = [
        'model_filename', 'params_filename', 'keep_name_table', 'return_numpy'
    ]
192 193 194 195 196 197 198 199 200 201 202 203 204

    # input check
    for key in configs:
        if key not in supported_configs:
            raise ValueError(
                "The additional config (%s) of `paddle.load` is not supported."
                % key)

    # construct inner config
    inner_config = _SaveLoadConfig()
    inner_config.model_filename = configs.get('model_filename', None)
    inner_config.params_filename = configs.get('params_filename', None)
    inner_config.keep_name_table = configs.get('keep_name_table', None)
205
    inner_config.return_numpy = configs.get('return_numpy', False)
206 207 208 209

    return inner_config


210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
def _parse_save_config(configs):
    supported_configs = ['use_binary_format', 'pickle_protocol']

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

    # construct inner config
    inner_config = _SaveLoadConfig()
    inner_config.use_binary_format = configs.get('use_binary_format', False)
    inner_config.pickle_protocol = configs.get('pickle_protocol', None)

    return inner_config


def _pickle_save(obj, f, protocol):
    # TODO(weixin):add support for BytesIO.
    if not isinstance(protocol, int):
        raise ValueError("The 'protocol' MUST be `int`, but received {}".format(
            type(protocol)))

    if protocol < 2 or protocol > 4:
        raise ValueError("Expected 1<'protocol'<5, but received protocol={}".
                         format(protocol))

    if not isinstance(obj, (core.LoDTensor, core.VarBase)):
        raise NotImplementedError(
            "Support 'paddle.Tensor' or 'paddle.core.LoDTensor', but received {}.".
            format(type(obj)))

    def reudce_varbase(self):
        data = self.numpy()
        name = self.name

        return (tuple, ((name, data), ))

    def reduce_LoDTensor(self):
        data = np.array(self)

        return (eval, ('data', {'data': data}))

    def add_dispatch_table():
        # This is not a good method, because the pickle module has been modified.
        pickle.dispatch_table[core.VarBase] = reudce_varbase
        pickle.dispatch_table[ParamBase] = reudce_varbase
        pickle.dispatch_table[core.LoDTensor] = reduce_LoDTensor

    def pop_dispatch_table():
        pickle.dispatch_table.pop(core.VarBase)
        pickle.dispatch_table.pop(core.LoDTensor)
        pickle.dispatch_table.pop(ParamBase)

    # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3'
    if sys.platform == 'darwin' and sys.version_info.major == 3:
        add_dispatch_table()
        pickle_bytes = pickle.dumps(obj)
        pop_dispatch_table()

        max_bytes = 2**30
        for i in range(0, len(pickle_bytes), max_bytes):
            f.write(pickle_bytes[i:i + max_bytes])
    else:
        if six.PY2:
            add_dispatch_table()
            pickle_bytes = pickle.dump(obj, f, protocol)
            pop_dispatch_table()
        else:
            pickler = pickle.Pickler(f, protocol)
            pickler.dispatch_table = copyreg.dispatch_table.copy()

            pickler.dispatch_table[core.VarBase] = reudce_varbase
            pickler.dispatch_table[core.LoDTensor] = reduce_LoDTensor
            pickler.dispatch_table[ParamBase] = reudce_varbase

            pickler.dump(obj)


def _use_legacy(obj):
    # TODO(weixin):If `obj` is any object, the judgment condition should be more precise.
    if not isinstance(obj, dict):
        return False
    return True


def _transformed_from_varbase(obj):
    # In paddle2.1 version, VarBase is saved as tuple(tensor.name, tensor.numpy()).
    # When executing paddle.load, use this function to determine whether to restore to VarBase/LoDTensor.
    if isinstance(obj, tuple) and len(obj) == 2:
        if six.PY2:
            name_types = (str, unicode)
        else:
            name_types = str
        if isinstance(obj[0], name_types) and isinstance(obj[1], np.ndarray):
            return True
    return False


def _transformed_from_lodtensor(obj):
    # In paddle2.1 version, LoDTensor is saved as np.array(tensor).
    # When executing paddle.load, use this function to determine whether to restore to VarBase/LoDTensor.
    if isinstance(obj, np.ndarray):
        return True
    return False


def _to_LodTensor(ndarray):
    if not isinstance(ndarray, np.ndarray):
        raise TypeError(
            'Type of `ndarray` should be numpy.ndarray, but received {}.'.
            format(type(ndarray)))
    t = core.LoDTensor()
    place = _current_expected_place()
    t.set(ndarray, place)
    return t


def _tuple_to_tensor(obj, return_numpy):
    if return_numpy:
        return obj[1]
    if in_dygraph_mode():
        t = paddle.to_tensor(obj[1])
        # This function does modify the name of return value.
        # Loading the same variable multiple times may cause the same name.
        t.name = obj[0]
        return t
    else:
        return _to_LodTensor(obj[1])


def _ndarray_to_tensor(obj, return_numpy):
    if return_numpy:
        return obj
    if in_dygraph_mode():
        return paddle.to_tensor(obj)
    else:
        return _to_LodTensor(obj)


def save(obj, path, protocol=2, **configs):
352 353 354 355
    '''
    Save an object to the specified path.
    
    .. note::
356
        Now supports saving ``state_dict`` of Layer or Optimizer, Tensor.
357 358

    .. note::
359 360 361 362 363 364 365
        Different from ``paddle.jit.save``, since the save result of ``paddle.save`` is a single file, 
        there is no need to distinguish multiple saved files by adding a suffix. The argument ``path`` 
        of ``paddle.save`` will be directly used as the saved file name instead of a prefix. 
        In order to unify the saved file name format, we recommend using the paddle standard suffix:
        1. for ``Layer.state_dict`` , recommend to use ``.pdparams`` ; 
        2. for ``Optimizer.state_dict`` , recommend to use ``.pdopt`` . 
        For specific examples, please refer to API code examples.
366 367 368 369 370
    
    Args:
        obj(Object) : The object to be saved.
        path(str) : The path of the object to be saved. 
          If saved in the current directory, the input path string will be used as the file name. 
371
        protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5.
W
WeiXin 已提交
372
                                 Default: 2
373 374 375 376
        **configs(dict, optional): optional keyword arguments. The following options are currently supported:
          use_binary_format(bool): When the saved object is static graph variable, you can specify ``use_binary_for_var``. 
          If True, save the file in the c++ binary format when saving a single static graph variable; otherwise, save it in pickle format.
          Default: False
377 378 379 380 381 382 383

    Returns:
        None

    Examples:
        .. code-block:: python

384
            # example 1: dynamic graph
385 386 387
            import paddle
            emb = paddle.nn.Embedding(10, 10)
            layer_state_dict = emb.state_dict()
388 389

            # save state_dict of emb
390
            paddle.save(layer_state_dict, "emb.pdparams")
391 392

            scheduler = paddle.optimizer.lr.NoamDecay(
393 394 395 396 397
                d_model=0.01, warmup_steps=100, verbose=True)
            adam = paddle.optimizer.Adam(
                learning_rate=scheduler,
                parameters=emb.parameters())
            opt_state_dict = adam.state_dict()
398 399

            # save state_dict of optimizer
400
            paddle.save(opt_state_dict, "adam.pdopt")
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
            # save weight of emb
            paddle.save(emb.weight, "emb.weight.pdtensor")

            # example 2: static graph
            import paddle
            import paddle.static as static

            paddle.enable_static()

            # create network
            x = paddle.static.data(name="x", shape=[None, 224], dtype='float32')
            z = paddle.static.nn.fc(x, 10)

            place = paddle.CPUPlace()
            exe = paddle.static.Executor(place)
            exe.run(paddle.static.default_startup_program())
            prog = paddle.static.default_main_program()
            for var in prog.list_vars():
                if list(var.shape) == [224, 10]:
                    tensor = var.get_tensor()
                    break

            # save/load tensor
            path_tensor = 'temp/tensor.pdtensor'
            paddle.save(tensor, path_tensor)

            # save/load state_dict
            path_state_dict = 'temp/model.pdparams'
            paddle.save(prog.state_dict("param"), path_tensor)
430
    '''
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    # 1. input check
    filename = os.path.basename(path)
    if filename == "":
        raise ValueError("The input path MUST be format of dirname/filename "
                         "[dirname\\filename in Windows system], but received "
                         "filename is empty string.")

    # 2. save object
    dirname = os.path.dirname(path)
    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)

    config = _parse_save_config(configs)

    if not isinstance(config.use_binary_format, bool):
        raise TypeError(
            "Type of `use_binary_format` should be bool, but received {}.".
            format(type(config.use_binary_format)))

    # `protocol` need to be used, `pickle_protocol` is a deprecated arg.
    if config.pickle_protocol is not None:
        protocol = config.pickle_protocol
        warnings.warn(
            "'pickle_protocol' is a deprecated argument. Please use 'protocol' instead."
        )

    if _use_legacy(obj):
        if in_dygraph_mode():
            _legacy_save(obj, path, protocol)
        else:
            _legacy_static_save(obj, path, protocol)
    else:
        # save single variable
        with open(path, 'wb') as f:
            _pickle_save(obj, f, protocol)
466

467 468

def _legacy_save(obj, path, protocol=2):
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    # 1. input check
    if not isinstance(obj, dict):
        raise NotImplementedError(
            "Now only supports save state_dict of Layer or Optimizer, "
            "expect dict, but received %s." % type(obj))

    if len(obj) == 0:
        warnings.warn("The input state dict is empty, no need to save.")

    filename = os.path.basename(path)
    if filename == "":
        raise ValueError("The input path MUST be format of dirname/filename "
                         "[dirname\\filename in Windows system], but received "
                         "filename is empty string.")

484
    if not isinstance(protocol, int):
W
WeiXin 已提交
485
        raise ValueError("The 'protocol' MUST be `int`, but received {}".format(
486
            type(protocol)))
W
WeiXin 已提交
487

488
    if protocol < 2 or protocol > 4:
W
WeiXin 已提交
489
        raise ValueError("Expected 1<'protocol'<5, but received protocol={}".
490
                         format(protocol))
W
WeiXin 已提交
491

492 493 494 495 496 497
    # 2. save object
    dirname = os.path.dirname(path)
    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)

    # TODO(chenweihang): supports save other object
W
WeiXin 已提交
498 499 500
    if isinstance(obj, dict):
        saved_obj = _build_saved_state_dict(obj)

501
    saved_obj = _unpack_saved_dict(saved_obj, protocol)
502

503 504 505
    # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3'
    if sys.platform == 'darwin' and sys.version_info.major == 3:
        pickle_bytes = pickle.dumps(saved_obj, protocol=protocol)
506 507 508 509 510 511
        with open(path, 'wb') as f:
            max_bytes = 2**30
            for i in range(0, len(pickle_bytes), max_bytes):
                f.write(pickle_bytes[i:i + max_bytes])
    else:
        with open(path, 'wb') as f:
512
            pickle.dump(saved_obj, f, protocol=protocol)
513 514


515
def load(path, **configs):
516 517 518 519
    '''
    Load an object can be used in paddle from specified path.

    .. note::
520
        Now supports load ``state_dict`` of Layer or Optimizer, Tensor.
521 522

    .. note::
523 524 525 526
        In order to use the model parameters saved by paddle more efficiently, 
        ``paddle.load`` supports loading ``state_dict`` of Layer from the result of 
        other save APIs except ``paddle.save`` , but the argument ``path`` format is 
        different:
527 528 529 530 531 532 533 534 535 536 537 538
        1. loading from ``paddle.static.save`` or ``paddle.Model().save(training=True)`` ,  
        ``path`` needs to be a complete file name, such as ``model.pdparams`` or 
        ``model.pdopt`` ; 
        2. loading from ``paddle.jit.save`` or ``paddle.static.save_inference_model`` 
        or ``paddle.Model().save(training=False)`` , ``path`` need to be a file prefix, 
        such as ``model/mnist``, and ``paddle.load`` will get information from 
        ``mnist.pdmodel`` and ``mnist.pdiparams`` ;
        3. loading from paddle 1.x APIs ``paddle.fluid.io.save_inference_model`` or 
        ``paddle.fluid.io.save_params/save_persistables`` , ``path`` need to be a 
        directory, such as ``model`` and model is a directory.

    .. note::
539
        If you load ``state_dict`` from the saved result of static mode API such as 
540
        ``paddle.static.save`` or ``paddle.static.save_inference_model`` , 
541 542 543
        the structured variable name in dynamic mode will cannot be restored. 
        You need to set the argument ``use_structured_name=False`` when using 
        ``Layer.set_state_dict`` later.
544 545 546

    Args:
        path(str) : The path to load the target object. Generally, the path is the target 
547 548
            file path. When loading state_dict from the saved result of the API used to save 
            the inference model, the path may be a file prefix or directory.
549 550 551 552
        **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, 
            DO NOT use them. Default None.
            The following options are currently supported:
553
            (1) model_filename (str): The inference model file name of the paddle 1.x 
554
            ``save_inference_model`` save format. Default file name is :code:`__model__` . 
555
            (2) params_filename (str): The persistable variables file name of the paddle 1.x 
556
            ``save_inference_model`` save format. No default file name, save variables separately 
557 558 559
            by default.            
            (3) return_numpy(bool): If specified as True, return tensor as numpy.ndarray, otherwise return tensor as paddle.Tensor. 
            Default False.
560 561 562 563 564 565 566 567 568

    Returns:
        Object(Object): a target object can be used in paddle

    Examples:
        .. code-block:: python

            import paddle

569 570
            # example 1: dynamic graph
            import paddle
571 572
            emb = paddle.nn.Embedding(10, 10)
            layer_state_dict = emb.state_dict()
573 574

            # save state_dict of emb
575
            paddle.save(layer_state_dict, "emb.pdparams")
576 577

            scheduler = paddle.optimizer.lr.NoamDecay(
578 579 580 581 582
                d_model=0.01, warmup_steps=100, verbose=True)
            adam = paddle.optimizer.Adam(
                learning_rate=scheduler,
                parameters=emb.parameters())
            opt_state_dict = adam.state_dict()
583 584

            # save state_dict of optimizer
585
            paddle.save(opt_state_dict, "adam.pdopt")
586 587
            # save weight of emb
            paddle.save(emb.weight, "emb.weight.pdtensor")
588

589
            # load state_dict of emb
590
            load_layer_state_dict = paddle.load("emb.pdparams")
591
            # load state_dict of optimizer
592
            load_opt_state_dict = paddle.load("adam.pdopt")
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
            # load weight of emb
            load_weight = paddle.load("emb.weight.pdtensor")


            # example 2: static graph
            import paddle
            import paddle.static as static

            paddle.enable_static()

            # create network
            x = paddle.static.data(name="x", shape=[None, 224], dtype='float32')
            z = paddle.static.nn.fc(x, 10)

            place = paddle.CPUPlace()
            exe = paddle.static.Executor(place)
            exe.run(paddle.static.default_startup_program())
            prog = paddle.static.default_main_program()
            for var in prog.list_vars():
                if list(var.shape) == [224, 10]:
                    tensor = var.get_tensor()
                    break

            # save/load tensor
            path_tensor = 'temp/tensor.pdtensor'
            paddle.save(tensor, path_tensor)
            load_tensor = paddle.load(path_tensor)

            # save/load state_dict
            path_state_dict = 'temp/model.pdparams'
            paddle.save(prog.state_dict("param"), path_tensor)
            load_state_dict = paddle.load(path_tensor)

626
    '''
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677

    if os.path.isfile(path):
        config = _parse_load_config(configs)
        with open(path, 'rb') as f:
            # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3'
            if sys.platform == 'darwin' and sys.version_info.major == 3:
                load_result = _pickle_loads_mac(path, f)
            else:
                load_result = pickle.load(f) if six.PY2 else pickle.load(
                    f, encoding='latin1')

            # TODO(weixin):If `obj` is any object, the judgment condition should be more precise.
            if isinstance(load_result, dict):
                if isinstance(load_result, dict):
                    load_result = _pack_loaded_dict(load_result)
                # paddle2.0: paddle.save/load
                if "StructuredToParameterName@@" in load_result:

                    for key in load_result["StructuredToParameterName@@"]:
                        load_result[key] = _ndarray_to_tensor(
                            load_result[key], config.return_numpy)

                    if not config.keep_name_table and "StructuredToParameterName@@" in load_result:
                        del load_result["StructuredToParameterName@@"]
                else:
                    # paddle2.1 static.save/load
                    for key in load_result:
                        load_result[key] = _ndarray_to_tensor(
                            load_result[key], config.return_numpy)

            else:
                # TODO(weixin): support complex objects such as layer.
                # If `obj` is any object, the judgment condition should be more precise.
                if _transformed_from_lodtensor(load_result):
                    load_result = _ndarray_to_tensor(load_result,
                                                     config.return_numpy)
                elif _transformed_from_varbase(load_result):
                    load_result = _tuple_to_tensor(load_result,
                                                   config.return_numpy)
                else:
                    raise NotImplementedError(
                        'Only support tensor and state_dict, but received {}.'.
                        format(type(load_result)))

    else:
        load_result = _legacy_load(path, **configs)

    return load_result


def _legacy_load(path, **configs):
678
    load_result = None
679 680
    config = _parse_load_config(configs)

681 682 683 684 685
    if os.path.isfile(path):
        # we think path is file means this file is created by paddle.save
        with open(path, 'rb') as f:
            load_result = pickle.load(f) if six.PY2 else pickle.load(
                f, encoding='latin1')
686
        load_result = _pack_loaded_dict(load_result)
687 688
        if not config.keep_name_table and "StructuredToParameterName@@" in load_result:
            del load_result["StructuredToParameterName@@"]
689 690 691
    else:
        # file prefix and directory are compatible cases
        model_path, config = _build_load_path_and_config(path, config)
692 693 694 695 696
        # check whether model file exists
        if config.model_filename is None:
            model_filename = '__model__'
        else:
            model_filename = config.model_filename
697
        model_file_path = os.path.join(model_path, model_filename)
698 699 700 701 702 703 704 705 706

        if os.path.exists(model_file_path):
            # Load state dict by `jit.save/io.save_inference_model` save format
            # NOTE(chenweihang): [ Compatibility of save_inference_model save format ]
            # The model saved by `save_inference_model` does not completely correspond to 
            # the information required by the `state_dict` under the dygraph. 
            # `save_inference_model` not save structured name, we need to remind 
            # the user to configure the `use_structured_name` argument when `set_state_dict`
            # NOTE(chenweihang): `jit.save` doesn't save optimizer state 
707
            load_result = _load_state_dict_from_save_inference_model(model_path,
708 709 710 711 712 713 714 715
                                                                     config)
        else:
            # load state dict by `io.save_params/persistables` save format
            # TODO(chenweihang): [ Now only supports loading parameters seperately ]
            # If users save all parameters as one file, the [ variable.name -> variable ]
            # mapping info will lost, so users need to give variable list, but users build 
            # variable list in dygraph mode is difficult, we recommend users to use
            # paddle.static.load_program_state in this case
716
            load_result = _load_state_dict_from_save_params(model_path)
717 718

    return load_result