io.py 41.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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 warnings
21
import sys
W
WeiXin 已提交
22
import numpy as np
T
tianshuo78520a 已提交
23
import copyreg
24 25 26 27 28
import paddle

# deprecated module import
from paddle import fluid
from paddle.fluid import core
L
Ligoml 已提交
29 30 31 32 33
from paddle.fluid.io import (
    _unpack_saved_dict,
    _pack_loaded_dict,
    _pickle_loads_mac,
)
34
from paddle.fluid.io import _legacy_save as _legacy_static_save
35
from paddle.fluid.io import _open_file_buffer, _is_file_path, _is_memory_buffer
36

L
Ligoml 已提交
37 38 39 40 41 42 43 44 45 46
from paddle.fluid.framework import (
    Variable,
    _varbase_creator,
    _dygraph_tracer,
    _non_static_mode,
    ParamBase,
    EagerParamBase,
    _current_expected_place,
    Program,
)
47
from paddle.fluid.dygraph.jit import _SaveLoadConfig
L
Ligoml 已提交
48 49 50 51 52 53 54 55 56 57
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,
)

58 59 60 61
try:
    from collections.abc import Iterable
except:
    from collections import Iterable
62

63 64
__all__ = []

65 66 67 68 69

def _build_saved_state_dict(state_dict):
    save_dict = {}
    name_table = {}
    for key, value in state_dict.items():
70
        if isinstance(value, (Variable, core.VarBase, core.eager.Tensor)):
S
Steffy-zxf 已提交
71 72 73
            if value.type == core.VarDesc.VarType.VOCAB:
                save_dict[key] = value.value().get_map_tensor()
            else:
B
Baibaifan 已提交
74 75 76 77
                if not value.value().get_tensor()._is_initialized():
                    raise ValueError(
                        "The saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model."
                    )
S
Steffy-zxf 已提交
78
                save_dict[key] = value.numpy()
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            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(
L
Ligoml 已提交
94 95
            model_path, programs, config.params_filename, append_suffix=False
        )
96 97 98 99 100 101

        # 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()

102 103 104
        # 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)
105 106 107 108 109 110
        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(
L
Ligoml 已提交
111 112 113 114 115 116
                    'structured_name', None
                )
                assert structured_name is not None, (
                    "Cannot find saved variable (%s)'s structured name in saved model."
                    % var_name
                )
117
                structured_para_dict[structured_name] = load_param_dict[
L
Ligoml 已提交
118 119
                    var_name
                ]
120 121 122 123 124 125
            load_param_dict = structured_para_dict

    return load_param_dict


def _load_state_dict_from_save_params(model_path):
126
    # Try to load all the files in the directory in VarBase format,
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    # 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},
L
Ligoml 已提交
147 148
                attrs={'file_path': os.path.join(model_path, name)},
            )
149 150 151 152 153 154 155 156 157 158
            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


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
# 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 "
L
Ligoml 已提交
184 185
            "of ``path`` is unique." % (path, path)
        )
186 187 188
    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
189
        # is exist, users may want use `paddle.load` load the result of
190 191 192 193
        # `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):
L
Ligoml 已提交
194 195 196 197
            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 "
198
                "`paddle.load('model')`."
L
Ligoml 已提交
199
            )
200 201 202 203 204 205 206 207 208
        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 "
L
Ligoml 已提交
209 210
                    "not take effect."
                )
211 212 213 214 215
            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 "
L
Ligoml 已提交
216 217
                    "not take effect."
                )
218 219 220 221 222 223 224 225 226
            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):
227
    supported_configs = [
L
Ligoml 已提交
228 229 230 231
        'model_filename',
        'params_filename',
        'keep_name_table',
        'return_numpy',
232
    ]
233 234 235 236 237 238

    # input check
    for key in configs:
        if key not in supported_configs:
            raise ValueError(
                "The additional config (%s) of `paddle.load` is not supported."
L
Ligoml 已提交
239 240
                % key
            )
241 242 243 244 245 246

    # 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)
247
    inner_config.return_numpy = configs.get('return_numpy', False)
248 249 250 251

    return inner_config


252 253 254 255 256 257 258 259
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."
L
Ligoml 已提交
260 261
                % key
            )
262 263 264 265 266 267 268 269 270 271 272 273

    # 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):
L
Ligoml 已提交
274 275 276 277 278
        raise ValueError(
            "The 'protocol' MUST be `int`, but received {}".format(
                type(protocol)
            )
        )
279 280

    if protocol < 2 or protocol > 4:
281
        raise ValueError(
L
Ligoml 已提交
282 283
            "Expected 1<'protocol'<5, but received protocol={}".format(protocol)
        )
284

285
    def reduce_varbase(self):
286 287 288
        data = self.numpy()
        name = self.name

L
Ligoml 已提交
289
        return (tuple, ((name, data),))
290 291 292 293 294 295

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

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

296
    def reduce_Layer(self):
297
        raise ValueError(
L
Ligoml 已提交
298 299
            "paddle do not support saving `paddle.nn.Layer` object."
        )
300 301 302 303 304 305 306

    dispatch_table_layer = dict()

    def create_layer_dispatch_table(layer):
        dispatch_table_layer[layer.__class__] = reduce_Layer
        return layer

L
Ligoml 已提交
307 308 309
    _parse_every_object(
        obj, lambda v: isinstance(v, fluid.Layer), create_layer_dispatch_table
    )
310

311 312
    def add_dispatch_table():
        # This is not a good method, because the pickle module has been modified.
313 314
        pickle.dispatch_table[core.VarBase] = reduce_varbase
        pickle.dispatch_table[ParamBase] = reduce_varbase
315 316
        pickle.dispatch_table[core.eager.Tensor] = reduce_varbase
        pickle.dispatch_table[EagerParamBase] = reduce_varbase
317
        pickle.dispatch_table[core.LoDTensor] = reduce_LoDTensor
318
        pickle.dispatch_table.update(dispatch_table_layer)
319 320 321 322 323

    def pop_dispatch_table():
        pickle.dispatch_table.pop(core.VarBase)
        pickle.dispatch_table.pop(core.LoDTensor)
        pickle.dispatch_table.pop(ParamBase)
324 325
        pickle.dispatch_table.pop(core.eager.Tensor)
        pickle.dispatch_table.pop(EagerParamBase)
326 327
        for k in dispatch_table_layer:
            pickle.dispatch_table.pop(k)
328 329 330 331 332 333 334 335 336

    # 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):
L
Ligoml 已提交
337
            f.write(pickle_bytes[i : i + max_bytes])
338
    else:
T
tianshuo78520a 已提交
339 340
        pickler = pickle.Pickler(f, protocol)
        pickler.dispatch_table = copyreg.dispatch_table.copy()
341

T
tianshuo78520a 已提交
342 343 344
        pickler.dispatch_table[core.VarBase] = reduce_varbase
        pickler.dispatch_table[core.LoDTensor] = reduce_LoDTensor
        pickler.dispatch_table[ParamBase] = reduce_varbase
345 346
        pickler.dispatch_table[core.eager.Tensor] = reduce_varbase
        pickler.dispatch_table[EagerParamBase] = reduce_varbase
T
tianshuo78520a 已提交
347 348
        pickler.dispatch_table.update(dispatch_table_layer)
        pickler.dump(obj)
349 350


351 352 353
def _contain_x(obj, condition_func):
    if isinstance(obj, core.SelectedRows):
        raise NotImplementedError(
L
Ligoml 已提交
354 355
            "`paddle.save` do not support saving 'SelectedRows'."
        )
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

    if condition_func(obj):
        return True
    elif type(obj) in (dict, collections.OrderedDict, list, tuple):
        if type(obj) in (dict, collections.OrderedDict):
            keys = list(obj.keys())
        else:
            keys = range(len(obj))
        flag = False
        for key in keys:
            flag |= _contain_x(obj[key], condition_func)
            if flag:
                return True
        return flag
    else:
371
        return False
372 373 374 375 376 377


def _is_state_dict(obj):
    if isinstance(obj, dict):

        def condition(obj):
378
            return isinstance(
L
Ligoml 已提交
379 380 381 382 383 384 385 386 387 388
                obj,
                (
                    fluid.Layer,
                    Program,
                    core.VarBase,
                    core.eager.Tensor,
                    core.LoDTensor,
                    core.SelectedRows,
                ),
            )
389

390 391
        # If the value of a dict is a core.VarBase/LoDTensor or a dict
        # that does not contain a paddle type(Layer, Program, VarBase, LoDTensor, SelectedRows),
392 393 394 395 396 397
        # the dict is considered to be a state_ dict.
        for key, value in obj.items():
            if isinstance(value, dict):
                for k, v in value.items():
                    if _contain_x(v, condition):
                        return False
398
            elif not isinstance(
L
Ligoml 已提交
399 400
                value, (core.VarBase, core.eager.Tensor, core.LoDTensor)
            ):
401 402 403 404
                return False
        return True

    return False
405 406 407 408 409 410


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:
T
tianshuo78520a 已提交
411
        name_types = str
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        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(
L
Ligoml 已提交
428 429 430 431
            'Type of `ndarray` should be numpy.ndarray, but received {}.'.format(
                type(ndarray)
            )
        )
432 433 434 435 436 437 438 439 440
    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]
J
Jiabin Yang 已提交
441
    if _non_static_mode():
442 443 444 445 446 447 448 449 450 451 452 453
        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
J
Jiabin Yang 已提交
454
    if _non_static_mode():
455 456 457 458 459
        return paddle.to_tensor(obj)
    else:
        return _to_LodTensor(obj)


460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
def _lod_tensor2varbase(tensor):
    return_var = _varbase_creator()
    return_var.value().get_tensor().set(tensor, _current_expected_place())
    return return_var


def _parse_every_object(obj, condition_func, convert_func):
    if condition_func(obj):
        return convert_func(obj)
    elif type(obj) in (dict, collections.OrderedDict, list):
        if type(obj) == list:
            keys = range(len(obj))
        else:
            keys = list(obj.keys())
        for key in keys:
            if condition_func(obj[key]):
                obj[key] = convert_func(obj[key])
            else:
L
Ligoml 已提交
478 479 480
                obj[key] = _parse_every_object(
                    obj[key], condition_func, convert_func
                )
481 482 483
        return obj
    elif type(obj) == tuple:
        return tuple(
L
Ligoml 已提交
484 485
            _parse_every_object(list(obj), condition_func, convert_func)
        )
486 487 488
    elif type(obj) == set:
        return set(_parse_every_object(list(obj), condition_func, convert_func))
    else:
489
        if isinstance(obj, Iterable) and not isinstance(
L
Ligoml 已提交
490 491 492
            obj,
            (str, np.ndarray, core.VarBase, core.eager.Tensor, core.LoDTensor),
        ):
493
            raise NotImplementedError(
L
Ligoml 已提交
494 495 496 497
                "The iteratable objects supported are tuple, list, dict, OrderedDict, string. But received {}.".format(
                    type(obj)
                )
            )
498 499 500 501 502
        return obj


def _parse_load_result(obj, return_numpy):
    def is_layer(obj):
J
Jiabin Yang 已提交
503
        return isinstance(obj, fluid.Layer)
504 505 506 507 508 509 510

    def parse_layer(obj):
        temp_dict = _parse_load_result(obj.__dict__, False)
        obj.__dict__.update(temp_dict)
        return obj

    if _contain_x(obj, is_layer):
J
Jiabin Yang 已提交
511
        if not _non_static_mode():
512 513 514 515 516 517 518 519 520 521 522 523
            raise ValueError(
                "Layer can only be loaded in dynamic graph mode, but now in static graph mode."
            )

        _parse_every_object(obj, is_layer, parse_layer)

    def tuple_to_tensor(obj):
        return _tuple_to_tensor(obj, return_numpy=return_numpy)

    def ndarray_to_tensor(obj):
        return _ndarray_to_tensor(obj, return_numpy=return_numpy)

524
    # tuple(name, ndarry) was converted from varbase of paddle2.1,
525 526
    # and all tuple(name, ndarry) are converted to tensor.
    if _contain_x(obj, _transformed_from_varbase):
L
Ligoml 已提交
527 528 529
        return _parse_every_object(
            obj, _transformed_from_varbase, tuple_to_tensor
        )
530
    # If there is no tuple(name, ndary), it is considered to be saved by paddle2.0
531 532
    # or converted from LoDTensor, and all ndarrays are converted to tensor.
    else:
L
Ligoml 已提交
533 534 535
        return _parse_every_object(
            obj, _transformed_from_lodtensor, ndarray_to_tensor
        )
536 537


538 539
def _save_lod_tensor(tensor, file_name):
    if not tensor._is_initialized():
B
Baibaifan 已提交
540 541 542
        raise ValueError(
            "The saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model firstly."
        )
543 544 545 546 547 548 549 550 551 552 553 554 555
    if _is_file_path(file_name):
        _seek = core.save_lod_tensor(tensor, file_name)
        # '_seek' is the end position of this tensor in the file.

    elif _is_memory_buffer(file_name):
        tensor_bytes = core.save_lod_tensor_to_memory(tensor)

        with _open_file_buffer(file_name, 'wb') as f:
            f.write(tensor_bytes)
            _seek = f.tell()

    else:
        raise NotImplementedError(
L
Ligoml 已提交
556 557 558 559
            'Only supports saving objects to file or BytesIO, but received {}'.format(
                type(file_name)
            )
        )
560 561 562 563 564
    return _seek


def _load_lod_tensor(file_name):
    temp_t = paddle.fluid.core.LoDTensor()
565 566 567 568 569 570 571 572 573 574 575 576
    if _is_file_path(file_name):
        # '_seek' is the end position of this tensor in the file.
        _seek = paddle.fluid.core.load_lod_tensor(temp_t, file_name)

    elif _is_memory_buffer(file_name):
        with _open_file_buffer(file_name, 'rb') as f:
            tensor_bytes = f.read()
            paddle.fluid.core.load_lod_tensor_from_memory(temp_t, tensor_bytes)
            _seek = f.tell()

    else:
        raise NotImplementedError(
L
Ligoml 已提交
577 578 579 580
            'Only supports load objects from file or BytesIO, but received {}'.format(
                type(file_name)
            )
        )
581

582 583 584 585 586 587
    return temp_t, _seek


def _save_selected_rows(selected_rows, file_name):
    if not selected_rows.get_tensor()._is_initialized():
        raise ValueError("The saved tensor is not initialized.")
588 589 590 591 592 593 594 595 596 597 598
    if _is_file_path(file_name):
        # '_seek' is the end position of this SelectedRows in the file.
        _seek = core.save_selected_rows(selected_rows, file_name)

    elif _is_memory_buffer(file_name):
        selected_rows_bytes = core.save_selected_rows_to_memory(selected_rows)
        with _open_file_buffer(file_name, 'wb') as f:
            f.write(selected_rows_bytes)
            _seek = f.tell()
    else:
        raise NotImplementedError(
L
Ligoml 已提交
599 600 601 602
            'Only supports saving objects to file or BytesIO, but received {}'.format(
                type(file_name)
            )
        )
603 604 605 606 607
    return _seek


def _load_selected_rows(file_name):
    temp_sr = core.SelectedRows()
608 609 610 611 612 613 614 615
    if _is_file_path(file_name):
        # '_seek' is the end position of this SelectedRows in the file.
        _seek = core.load_selected_rows(temp_sr, file_name)

    elif _is_memory_buffer(file_name):
        with _open_file_buffer(file_name, 'rb') as f:
            selected_rows_bytes = f.read()
            paddle.fluid.core.load_selected_rows_from_memory(
L
Ligoml 已提交
616 617
                temp_sr, selected_rows_bytes
            )
618 619 620 621
        _seek = f.tell()

    else:
        raise NotImplementedError(
L
Ligoml 已提交
622 623 624 625
            'Only supports load objects from file or BytesIO, but received {}'.format(
                type(file_name)
            )
        )
626

627 628 629 630 631 632 633 634
    return temp_sr, _seek


def _save_binary_var(obj, path):
    if isinstance(obj, core.LoDTensor):
        _save_lod_tensor(obj, path)
    elif isinstance(obj, core.SelectedRows):
        _save_selected_rows(obj, path)
635
    elif isinstance(obj, (core.VarBase, core.eager.Tensor)):
636
        _save_lod_tensor(obj.value().get_tensor(), path)
637 638 639
    else:
        # Since the concept of 'Tensor' is only exposed to users, the error message can only contain tensor instead of 'LoDTensor' or 'SelectedRows'
        raise NotImplementedError(
L
Ligoml 已提交
640 641 642 643
            "When use_binary_format = True, `paddle.save`  expected Tensor, but received {}.".format(
                type(obj)
            )
        )
644 645


646
def save(obj, path, protocol=4, **configs):
647 648
    '''
    Save an object to the specified path.
L
Ligoml 已提交
649

650
    .. note::
651
        Now supports saving ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program.
652 653

    .. note::
L
Ligoml 已提交
654 655 656
        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.
657
        In order to unify the saved file name format, we recommend using the paddle standard suffix:
L
Ligoml 已提交
658 659
        1. for ``Layer.state_dict`` , recommend to use ``.pdparams`` ;
        2. for ``Optimizer.state_dict`` , recommend to use ``.pdopt`` .
660
        For specific examples, please refer to API code examples.
L
Ligoml 已提交
661

662 663
    Args:
        obj(Object) : The object to be saved.
L
Ligoml 已提交
664 665
        path(str|BytesIO) : The path/buffer of the object to be saved.
          If saved in the current directory, the input path string will be used as the file name.
666
        protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5.
667
                                 Default: 4
668
        **configs(dict, optional): optional keyword arguments. The following options are currently supported:
L
Ligoml 已提交
669
          use_binary_format(bool): When the saved object is static graph variable, you can specify ``use_binary_for_var``.
670 671
          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
672 673 674 675 676 677 678

    Returns:
        None

    Examples:
        .. code-block:: python

679
            # example 1: dynamic graph
680 681 682
            import paddle
            emb = paddle.nn.Embedding(10, 10)
            layer_state_dict = emb.state_dict()
683 684

            # save state_dict of emb
685
            paddle.save(layer_state_dict, "emb.pdparams")
686 687

            scheduler = paddle.optimizer.lr.NoamDecay(
688 689 690 691 692
                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()
693 694

            # save state_dict of optimizer
695
            paddle.save(opt_state_dict, "adam.pdopt")
696 697 698
            # save weight of emb
            paddle.save(emb.weight, "emb.weight.pdtensor")

W
WeiXin 已提交
699 700 701 702 703 704 705 706 707 708 709 710
            # example 2: Save multiple state_dict at the same time
            from paddle import nn
            from paddle.optimizer import Adam

            layer = paddle.nn.Linear(3, 4)
            adam = Adam(learning_rate=0.001, parameters=layer.parameters())
            obj = {'model': layer.state_dict(), 'opt': adam.state_dict(), 'epoch': 100}
            path = 'example/model.pdparams'
            paddle.save(obj, path)


            # example 3: static graph
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
            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]:
W
WeiXin 已提交
726
                    tensor = var.get_value()
727 728 729 730 731 732 733 734 735
                    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)
W
WeiXin 已提交
736 737 738 739 740 741 742 743 744 745 746 747

            # example 4: save program
            import paddle

            paddle.enable_static()

            data = paddle.static.data(
                name='x_static_save', shape=(None, 224), dtype='float32')
            y_static = z = paddle.static.nn.fc(data, 10)
            main_program = paddle.static.default_main_program()
            path = "example/main_program.pdmodel"
            paddle.save(main_program, path)
748

749 750 751 752 753 754 755 756 757 758 759 760 761

            # example 5: save object to memory
            from io import BytesIO
            import paddle
            from paddle.nn import Linear
            paddle.disable_static()

            linear = Linear(5, 10)
            state_dict = linear.state_dict()
            byio = BytesIO()
            paddle.save(state_dict, byio)
            tensor = paddle.randn([2, 3], dtype='float32')
            paddle.save(tensor, byio)
L
Ligoml 已提交
762

763 764 765 766 767 768 769 770
    '''
    if _is_file_path(path):
        # 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 "
L
Ligoml 已提交
771 772
                "filename is empty string."
            )
773 774 775 776 777 778 779

        # 2. save object
        dirname = os.path.dirname(path)
        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)
    elif not _is_memory_buffer(path):
        raise ValueError(
L
Ligoml 已提交
780 781 782 783
            "only supports saving objects to file and `BytesIO`, but got {}".format(
                type(path)
            )
        )
784 785 786 787 788

    config = _parse_save_config(configs)

    if not isinstance(config.use_binary_format, bool):
        raise TypeError(
L
Ligoml 已提交
789 790 791 792
            "Type of `use_binary_format` should be bool, but received {}.".format(
                type(config.use_binary_format)
            )
        )
793

794 795
    if config.use_binary_format:
        _save_binary_var(obj, path)
796
    else:
797 798 799 800 801 802
        # `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."
            )
803

804 805
        if isinstance(obj, Program):
            obj.desc.flush()
806
            with _open_file_buffer(path, "wb") as f:
807
                f.write(obj.desc.serialize_to_string())
808 809

        elif _is_state_dict(obj):
J
Jiabin Yang 已提交
810
            if _non_static_mode():
811 812 813 814
                _legacy_save(obj, path, protocol)
            else:
                _legacy_static_save(obj, path, protocol)
        else:
815
            with _open_file_buffer(path, 'wb') as f:
816
                _pickle_save(obj, f, protocol)
817

818 819

def _legacy_save(obj, path, protocol=2):
820 821 822 823
    # 1. input check
    if not isinstance(obj, dict):
        raise NotImplementedError(
            "Now only supports save state_dict of Layer or Optimizer, "
L
Ligoml 已提交
824 825
            "expect dict, but received %s." % type(obj)
        )
826 827 828 829

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

830
    if not isinstance(protocol, int):
L
Ligoml 已提交
831 832 833 834 835
        raise ValueError(
            "The 'protocol' MUST be `int`, but received {}".format(
                type(protocol)
            )
        )
W
WeiXin 已提交
836

837
    if protocol < 2 or protocol > 4:
838
        raise ValueError(
L
Ligoml 已提交
839 840
            "Expected 1<'protocol'<5, but received protocol={}".format(protocol)
        )
W
WeiXin 已提交
841

842 843 844 845 846 847
    if _is_file_path(path):
        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 "
L
Ligoml 已提交
848 849
                "filename is empty string."
            )
850 851 852 853
        # 2. save object
        dirname = os.path.dirname(path)
        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)
854

W
WeiXin 已提交
855 856 857
    if isinstance(obj, dict):
        saved_obj = _build_saved_state_dict(obj)

858
    saved_obj = _unpack_saved_dict(saved_obj, protocol)
859

860
    # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3'
L
Ligoml 已提交
861 862 863 864 865
    if (
        _is_file_path(path)
        and sys.platform == 'darwin'
        and sys.version_info.major == 3
    ):
866
        pickle_bytes = pickle.dumps(saved_obj, protocol=protocol)
867 868 869
        with open(path, 'wb') as f:
            max_bytes = 2**30
            for i in range(0, len(pickle_bytes), max_bytes):
L
Ligoml 已提交
870
                f.write(pickle_bytes[i : i + max_bytes])
871
    else:
872
        with _open_file_buffer(path, 'wb') as f:
873
            pickle.dump(saved_obj, f, protocol=protocol)
874 875


876
def load(path, **configs):
877 878 879 880
    '''
    Load an object can be used in paddle from specified path.

    .. note::
881
        Now supports loading ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program.
882 883

    .. note::
L
Ligoml 已提交
884 885 886
        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
887
        different:
L
Ligoml 已提交
888 889 890 891 892 893
        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
894
        ``mnist.pdmodel`` and ``mnist.pdiparams`` ;
L
Ligoml 已提交
895 896
        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
897 898 899
        directory, such as ``model`` and model is a directory.

    .. note::
L
Ligoml 已提交
900 901 902 903
        If you load ``state_dict`` from the saved result of static mode API such as
        ``paddle.static.save`` or ``paddle.static.save_inference_model`` ,
        the structured variable name in dynamic mode will cannot be restored.
        You need to set the argument ``use_structured_name=False`` when using
904
        ``Layer.set_state_dict`` later.
905 906

    Args:
L
Ligoml 已提交
907 908
        path(str|BytesIO) : The path/buffer to load the target object. Generally, the path is the target
            file path. When loading state_dict from the saved result of the API used to save
909
            the inference model, the path may be a file prefix or directory.
L
Ligoml 已提交
910 911
        **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,
912 913
            DO NOT use them. Default None.
            The following options are currently supported:
L
Ligoml 已提交
914 915 916 917 918 919
            (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
            by default.
            (3) return_numpy(bool): If specified as True, return tensor as numpy.ndarray, otherwise return tensor as paddle.Tensor.
920
            Default False.
921 922 923 924 925 926 927

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

    Examples:
        .. code-block:: python

928 929
            # example 1: dynamic graph
            import paddle
930 931
            emb = paddle.nn.Embedding(10, 10)
            layer_state_dict = emb.state_dict()
932 933

            # save state_dict of emb
934
            paddle.save(layer_state_dict, "emb.pdparams")
935 936

            scheduler = paddle.optimizer.lr.NoamDecay(
937 938 939 940 941
                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()
942 943

            # save state_dict of optimizer
944
            paddle.save(opt_state_dict, "adam.pdopt")
945 946
            # save weight of emb
            paddle.save(emb.weight, "emb.weight.pdtensor")
947

948
            # load state_dict of emb
949
            load_layer_state_dict = paddle.load("emb.pdparams")
950
            # load state_dict of optimizer
951
            load_opt_state_dict = paddle.load("adam.pdopt")
952 953 954 955
            # load weight of emb
            load_weight = paddle.load("emb.weight.pdtensor")


W
WeiXin 已提交
956 957 958 959 960 961 962 963 964 965 966 967 968
            # example 2: Load multiple state_dict at the same time
            from paddle import nn
            from paddle.optimizer import Adam

            layer = paddle.nn.Linear(3, 4)
            adam = Adam(learning_rate=0.001, parameters=layer.parameters())
            obj = {'model': layer.state_dict(), 'opt': adam.state_dict(), 'epoch': 100}
            path = 'example/model.pdparams'
            paddle.save(obj, path)
            obj_load = paddle.load(path)


            # example 3: static graph
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
            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]:
W
WeiXin 已提交
984
                    tensor = var.get_value()
985 986 987 988 989 990 991 992 993 994 995 996
                    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)

W
WeiXin 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012

            # example 4: load program
            import paddle

            paddle.enable_static()

            data = paddle.static.data(
                name='x_static_save', shape=(None, 224), dtype='float32')
            y_static = z = paddle.static.nn.fc(data, 10)
            main_program = paddle.static.default_main_program()
            path = "example/main_program.pdmodel"
            paddle.save(main_program, path)
            load_main = paddle.load(path)
            print(load_main)


1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
            # example 5: save object to memory
            from io import BytesIO
            import paddle
            from paddle.nn import Linear
            paddle.disable_static()

            linear = Linear(5, 10)
            state_dict = linear.state_dict()
            byio = BytesIO()
            paddle.save(state_dict, byio)
            tensor = paddle.randn([2, 3], dtype='float32')
            paddle.save(tensor, byio)
            byio.seek(0)
            # load state_dict
            dict_load = paddle.load(byio)

1029
    '''
1030

1031
    if _is_memory_buffer(path) or os.path.isfile(path):
1032
        config = _parse_load_config(configs)
T
tianshuo78520a 已提交
1033
        exception_type = pickle.UnpicklingError
W
WeiXin 已提交
1034
        try:
1035
            with _open_file_buffer(path, 'rb') as f:
W
WeiXin 已提交
1036
                # When value of dict is lager than 4GB ,there is a Bug on 'MAC python3'
L
Ligoml 已提交
1037 1038 1039 1040 1041
                if (
                    _is_file_path(path)
                    and sys.platform == 'darwin'
                    and sys.version_info.major == 3
                ):
W
WeiXin 已提交
1042 1043
                    load_result = _pickle_loads_mac(path, f)
                else:
T
tianshuo78520a 已提交
1044
                    load_result = pickle.load(f, encoding='latin1')
1045

W
WeiXin 已提交
1046 1047
                # TODO(weixin):If `obj` is any object, the judgment condition should be more precise.
                if isinstance(load_result, dict):
1048
                    load_result = _pack_loaded_dict(load_result)
W
WeiXin 已提交
1049 1050 1051 1052
                    # paddle2.0: paddle.save/load
                    if "StructuredToParameterName@@" in load_result:

                        for key in load_result["StructuredToParameterName@@"]:
S
Steffy-zxf 已提交
1053 1054
                            if isinstance(load_result[key], np.ndarray):
                                load_result[key] = _ndarray_to_tensor(
L
Ligoml 已提交
1055 1056
                                    load_result[key], config.return_numpy
                                )
W
WeiXin 已提交
1057

L
Ligoml 已提交
1058 1059 1060 1061
                        if (
                            not config.keep_name_table
                            and "StructuredToParameterName@@" in load_result
                        ):
W
WeiXin 已提交
1062 1063 1064
                            del load_result["StructuredToParameterName@@"]
                    else:
                        # paddle2.1 static.save/load
1065
                        load_result = _parse_load_result(
L
Ligoml 已提交
1066 1067
                            load_result, config.return_numpy
                        )
1068 1069

                else:
L
Ligoml 已提交
1070 1071 1072
                    load_result = _parse_load_result(
                        load_result, config.return_numpy
                    )
1073 1074 1075 1076 1077 1078 1079 1080

        except exception_type as msg_pickle:
            try:
                tensor, _ = _load_selected_rows(path)
                return tensor
            except:
                try:
                    tensor, _ = _load_lod_tensor(path)
1081 1082 1083
                    if config.return_numpy:
                        return np.array(tensor)
                    else:
J
Jiabin Yang 已提交
1084
                        if _non_static_mode():
1085 1086
                            return _lod_tensor2varbase(tensor)
                        return tensor
1087 1088
                except:
                    try:
1089
                        with _open_file_buffer(path, "rb") as f:
1090 1091
                            program_desc_str = f.read()
                            program = Program.parse_from_string(
L
Ligoml 已提交
1092 1093
                                program_desc_str
                            )
1094 1095 1096 1097
                            return program
                    except:
                        raise ValueError(
                            "`paddle.load` can not parse the file:{}.".format(
L
Ligoml 已提交
1098 1099 1100
                                path
                            )
                        )
1101 1102 1103 1104 1105 1106 1107 1108

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

    return load_result


def _legacy_load(path, **configs):
1109
    load_result = None
1110 1111
    config = _parse_load_config(configs)

1112
    if os.path.isfile(path) or _is_memory_buffer(path):
1113
        # we think path is file means this file is created by paddle.save
1114
        with _open_file_buffer(path, 'rb') as f:
T
tianshuo78520a 已提交
1115
            load_result = pickle.load(f, encoding='latin1')
1116
        load_result = _pack_loaded_dict(load_result)
L
Ligoml 已提交
1117 1118 1119 1120
        if (
            not config.keep_name_table
            and "StructuredToParameterName@@" in load_result
        ):
1121
            del load_result["StructuredToParameterName@@"]
1122 1123 1124
    else:
        # file prefix and directory are compatible cases
        model_path, config = _build_load_path_and_config(path, config)
1125 1126 1127 1128 1129
        # check whether model file exists
        if config.model_filename is None:
            model_filename = '__model__'
        else:
            model_filename = config.model_filename
1130
        model_file_path = os.path.join(model_path, model_filename)
1131 1132 1133 1134

        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 ]
1135 1136 1137
            # 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
1138
            # the user to configure the `use_structured_name` argument when `set_state_dict`
1139 1140
            # NOTE(chenweihang): `jit.save` doesn't save optimizer state
            load_result = _load_state_dict_from_save_inference_model(
L
Ligoml 已提交
1141 1142
                model_path, config
            )
1143 1144
        else:
            # load state dict by `io.save_params/persistables` save format
1145
            # TODO(chenweihang): [ Now only supports loading parameters separately ]
1146
            # If users save all parameters as one file, the [ variable.name -> variable ]
1147
            # mapping info will lost, so users need to give variable list, but users build
1148 1149
            # variable list in dygraph mode is difficult, we recommend users to use
            # paddle.static.load_program_state in this case
1150
            load_result = _load_state_dict_from_save_params(model_path)
1151 1152

    return load_result