o
    Ne                     @   s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dl
mZ d dlmZ d dlmZmZmZ d dlmZ d dlmZmZmZ d dlmZmZmZmZmZmZmZmZ d d	l m!Z! d d
l"m#Z#m$Z$ d dl"m%Z%m&Z&m'Z' zd dl(m)Z) W n
   d dlm)Z) Y g Z*dd Z+dd Z,dd Z-dd Z.dd Z/dd Z0dd Z1dd Z2dd Z3dd  Z4d!d" Z5d#d$ Z6d%d& Z7d'd( Z8d)d* Z9d+d, Z:d-d. Z;d/d0 Z<d1d2 Z=d3d4 Z>d5d6 Z?d7d8 Z@dCd:d;ZAdDd=d>Zd?d@ ZBdAdB ZCdS )E    )print_functionN)fluid)core)_unpack_saved_dict_pack_loaded_dict_pickle_loads_mac)_legacy_save)_open_file_buffer_is_file_path_is_memory_buffer)Variable_varbase_creator_dygraph_tracer_non_static_mode	ParamBaseEagerParamBase_current_expected_placeProgram)_SaveLoadConfig)_construct_program_holders_construct_params_and_buffers)INFER_MODEL_SUFFIXINFER_PARAMS_SUFFIXINFER_PARAMS_INFO_SUFFIX)Iterablec                 C   s   i }i }|   D ]<\}}t|ttjtjjfr@|jtjj	j
kr(|  ||< n|   s4td| ||< |j||< q|||< q||d< |S )NzdThe saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model.StructuredToParameterName@@)items
isinstancer   r   VarBaseeagerTensortypeZVarDescZVarTypeZVOCABvalueZget_map_tensor
get_tensor_is_initialized
ValueErrornumpyname)Z
state_dict	save_dictZ
name_tablekeyr"    r*   CD:\Projects\ConvertPro\env\Lib\site-packages\paddle/framework/io.py_build_saved_state_dictB   s   
r,   c              	   C   s  t | |j}tj z t| ||jdd}t }|D ]
}||  ||< qt	|jd }t
j| |}t
j|r}t|d}t|}	W d    n1 sNw   Y  t }
|D ]}|	| dd }|d uslJ d| || |
|< qX|
}W d    |S W d    |S 1 sw   Y  |S )NF)Zappend_suffixz.inforbstructured_namezACannot find saved variable (%s)'s structured name in saved model.)r   model_filenamer   dygraphguardr   params_filenamedictr&   strospathjoinexistsopenpickleloadget)
model_pathconfigZprogramsZpersistable_var_dictload_param_dictvar_nameZvar_info_filenameZvar_info_pathfZextra_var_infoZstructured_para_dictr.   r*   r*   r+   *_load_state_dict_from_save_inference_modelW   sF   




rB   c                 C   s   g }g }t | D ]#\}}}|D ]}t j||}t j|| }|dd}	||	 qq	tj	 + |D ] }
t
|
dd}t jdi d|idt j| |
id || q5W d    n1 s`w   Y  t }|D ]	}| ||j< qj|S )	N\/T)r'   Zpersistabler;   ZOut	file_path)r!   ZinputsZoutputsattrs)r5   walkr6   r7   relpathreplaceappendr   r0   r1   r   r   Ztrace_opr3   r&   r'   )r=   Zload_var_listZvar_name_listroot_filesfilenamerE   Ztmp_var_namer@   r'   Znew_varr?   varr*   r*   r+   !_load_state_dict_from_save_params}   s2   rP   c           
      C   s   | t  }tj|}tj| }|r|rtd| | f |s@|s@d}| d }| d }tj|s6tj|r:|d7 }t||  |rptj| }tj| }	|jd urXt	
d |t  |_|jd urgt	
d |t |_|	|fS | }	|	|fS )NzThe %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.z+The ``path`` (%s) to load model not exists.z	.pdparamsz.pdoptz 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')`.zqWhen loading the result saved with the specified file prefix, the ``model_filename`` config does not take effect.zrWhen loading the result saved with the specified file prefix, the ``params_filename`` config does not take effect.)r   r5   r6   r8   isdirr%   basenamedirnamer/   warningswarnr2   r   )
r6   r>   Zprefix_format_pathZprefix_format_existZdirectory_format_exist	error_msgZparams_file_pathZopti_file_pathZfile_prefixr=   r*   r*   r+   _build_load_path_and_config   sD   



rW   c                 C   sh   g d}| D ]}||vrt d| qt }| dd |_| dd |_| dd |_| dd|_|S )N)r/   r2   keep_name_tablereturn_numpyz=The additional config (%s) of `paddle.load` is not supported.r/   r2   rX   rY   F)r%   r   r<   r/   r2   rX   rY   configsZsupported_configsr)   Zinner_configr*   r*   r+   _parse_load_config   s   r\   c                 C   sL   ddg}| D ]}||vrt d| qt }| dd|_| dd |_|S )Nuse_binary_formatpickle_protocolz=The additional config (%s) of `paddle.save` is not supported.F)r%   r   r<   r]   r^   rZ   r*   r*   r+   _parse_save_config   s   r_   c           
         s^  t |tstdt||dk s|dkrtd|dd dd d	d
 t   fdd}t| dd |  fdd} fdd}tjdkrytj	j
dkry|  t| }|  d}tdt||D ]}|||||   qid S t||}	tj |	_|	jtj< |	jtj< |	jt< |	jtjj< |	jt< |	j  |	|  d S )N-The 'protocol' MUST be `int`, but received {}      1Expected 1<'protocol'<5, but received protocol={}c                 S   s   |   }| j}t||fffS N)r&   r'   tuple)selfdatar'   r*   r*   r+   reduce_varbase  s   z$_pickle_save.<locals>.reduce_varbasec                 S   s   t | }tdd|iffS )Nrg   )nparrayeval)rf   rg   r*   r*   r+   reduce_LoDTensor#  s   
z&_pickle_save.<locals>.reduce_LoDTensorc                 S   s   t d)Nz6paddle do not support saving `paddle.nn.Layer` object.)r%   )rf   r*   r*   r+   reduce_Layer(  s   z"_pickle_save.<locals>.reduce_Layerc                    s    | j < | S rd   )	__class__)layer)dispatch_table_layerrm   r*   r+   create_layer_dispatch_table/  s   
z1_pickle_save.<locals>.create_layer_dispatch_tablec                 S      t | tjS rd   r   r   Layer)vr*   r*   r+   <lambda>4  s    z_pickle_save.<locals>.<lambda>c                      sJ   t jtj< t jt< t jtjj< t jt< t jtj< t j	  d S rd   )
r:   dispatch_tabler   r   r   r   r    r   	LoDTensorupdater*   )rp   rl   rh   r*   r+   add_dispatch_table7  s   

z(_pickle_save.<locals>.add_dispatch_tablec                     s^   t jtj t jtj t jt t jtjj t jt	  D ]} t j|  q$d S rd   )
r:   rw   popr   r   rx   r   r   r    r   )k)rp   r*   r+   pop_dispatch_table@  s   z(_pickle_save.<locals>.pop_dispatch_tabledarwin      @r   )r   intr%   formatr!   r3   _parse_every_objectsysplatformversion_infomajorr:   dumpsrangelenwritePicklercopyregrw   copyr   r   rx   r   r   r    r   ry   dump)
objrA   protocolrq   rz   r}   pickle_bytes	max_bytesiZpicklerr*   )rp   rm   rl   rh   r+   _pickle_save  sJ   

	



r   c                 C   s   t | tjr
td|| rdS t| ttjtt	fv rHt| ttjfv r+t| 
 }ntt| }d}|D ]}|t| | |O }|rE dS q5|S dS )Nz3`paddle.save` do not support saving 'SelectedRows'.TF)r   r   SelectedRowsNotImplementedErrorr!   r3   collectionsOrderedDictlistre   keysr   r   
_contain_x)r   condition_funcr   flagr)   r*   r*   r+   r   _  s$   r   c                 C   sz   t | tr;dd }|  D ]+\}}t |tr)| D ]\}}t||r'  dS qqt |tjtjjtjfs8 dS qdS dS )Nc                 S   s"   t | tjttjtjjtjtj	fS rd   )
r   r   rt   r   r   r   r   r    rx   r   r   r*   r*   r+   	conditiony  s   z!_is_state_dict.<locals>.conditionFT)	r   r3   r   r   r   r   r   r    rx   )r   r   r)   r"   r|   ru   r*   r*   r+   _is_state_dictv  s    


r   c                 C   s@   t | trt| dkrt}t | d |rt | d tjrdS dS )Nra   r      TF)r   re   r   r4   ri   ndarray)r   Z
name_typesr*   r*   r+   _transformed_from_varbase  s
   r   c                 C   s   t | tjrdS dS )NTF)r   ri   r   r   r*   r*   r+   _transformed_from_lodtensor  s   r   c                 C   s<   t | tjstdt| t }t }|	| | |S )Nz;Type of `ndarray` should be numpy.ndarray, but received {}.)
r   ri   r   	TypeErrorr   r!   r   rx   r   set)r   tZplacer*   r*   r+   _to_LodTensor  s   r   c                 C   s:   |r| d S t  rt| d }| d |_|S t| d S )Nr   r   )r   paddle	to_tensorr'   r   )r   rY   r   r*   r*   r+   _tuple_to_tensor  s   
r   c                 C   s    |r| S t  rt| S t| S rd   )r   r   r   r   )r   rY   r*   r*   r+   _ndarray_to_tensor  s
   
r   c                 C   s    t  }|  | t  |S rd   )r   r"   r#   r   r   )tensorZ
return_varr*   r*   r+   _lod_tensor2varbase  s   r   c                 C   s  || r|| S t | ttjtfv rEt | tkrtt| }nt|  }|D ]}|| | r8|| | | |< q't| | ||| |< q'| S t | t	krUt	tt| ||S t | t
kret
tt| ||S t| trt| ttjtjtjjtjfstdt | | S )Nz]The iteratable objects supported are tuple, list, dict, OrderedDict, string. But received {}.)r!   r3   r   r   r   r   r   r   r   re   r   r   r   r4   ri   r   r   r   r   r    rx   r   r   )r   r   Zconvert_funcr   r)   r*   r*   r+   r     s:   

r   c                    sn   dd }dd }t | |rt stdt| ||  fdd} fdd	}t | tr1t| t|S t| t|S )
Nc                 S   rr   rd   rs   r   r*   r*   r+   is_layer     z$_parse_load_result.<locals>.is_layerc                 S   s   t | jd}| j| | S )NF)_parse_load_result__dict__ry   )r   Z	temp_dictr*   r*   r+   parse_layer  s   z'_parse_load_result.<locals>.parse_layerzMLayer can only be loaded in dynamic graph mode, but now in static graph mode.c                       t |  dS NrY   )r   r   r   r*   r+   tuple_to_tensor  r   z+_parse_load_result.<locals>.tuple_to_tensorc                    r   r   )r   r   r   r*   r+   ndarray_to_tensor	  r   z-_parse_load_result.<locals>.ndarray_to_tensor)r   r   r%   r   r   r   )r   rY   r   r   r   r   r*   r   r+   r     s"   

r   c                 C   s   |   stdt|rt| |}|S t|r>t| }t|d}|| |	 }W d    |S 1 s7w   Y  |S t
dt|)NzlThe saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model firstly.wb@Only supports saving objects to file or BytesIO, but received {})r$   r%   r
   r   Zsave_lod_tensorr   Zsave_lod_tensor_to_memoryr	   r   tellr   r   r!   )r   	file_name_seektensor_bytesrA   r*   r*   r+   _save_lod_tensor  s*   





r   c                 C   s   t jj }t| rt jj|| }||fS t| rFt| d}| }t jj	|| |
 }W d    ||fS 1 s=w   Y  ||fS tdt| Nr-   z@Only supports load objects from file or BytesIO, but received {})r   r   r   rx   r
   Zload_lod_tensorr   r	   readZload_lod_tensor_from_memoryr   r   r   r!   )r   Ztemp_tr   rA   r   r*   r*   r+   _load_lod_tensor3  s$   

r   c                 C   s   |    s
tdt|rt| |}|S t|r@t| }t|d}|	| |
 }W d    |S 1 s9w   Y  |S tdt|)Nz$The saved tensor is not initialized.r   r   )r#   r$   r%   r
   r   Zsave_selected_rowsr   Zsave_selected_rows_to_memoryr	   r   r   r   r   r!   )Zselected_rowsr   r   selected_rows_bytesrA   r*   r*   r+   _save_selected_rowsI  s&   



		r   c                 C   s   t  }t| rt || }||fS t| r?t| d}| }tjj 	|| W d    n1 s2w   Y  |
 }||fS tdt| r   )r   r   r
   Zload_selected_rowsr   r	   r   r   r   Zload_selected_rows_from_memoryr   r   r   r!   )r   Ztemp_srr   rA   r   r*   r*   r+   _load_selected_rows^  s$   	r   c                 C   sp   t | tjrt| | d S t | tjrt| | d S t | tjtjjfr/t| 	 
 | d S tdt| )NzOWhen use_binary_format = True, `paddle.save`  expected Tensor, but received {}.)r   r   rx   r   r   r   r   r   r    r"   r#   r   r   r!   )r   r6   r*   r*   r+   _save_binary_varv  s   r   rb   c                 K   sz  t |r&tj|}|dkrtdtj|}|r%tj|s%t| nt|s3td	t
|t|}t|jtsGtd	t
|j|jrQt| | dS |jdur^|j}td t| tr| j  t|d}|| j  W d   dS 1 sw   Y  dS t| rt rt| || dS t| || dS t|d}t| || W d   dS 1 sw   Y  dS )a  
    Save an object to the specified path.

    Note:
        Now supports saving ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program.

    Note:
        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.

    Args:
        obj(Object) : The object to be saved.
        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.
        protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5.
                                 Default: 4
        **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

    Returns:
        None

    Examples:
        .. code-block:: python

            # example 1: dynamic graph
            import paddle
            emb = paddle.nn.Embedding(10, 10)
            layer_state_dict = emb.state_dict()

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

            scheduler = paddle.optimizer.lr.NoamDecay(
                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()

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

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

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


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

     ~The input path MUST be format of dirname/filename [dirname\filename in Windows system], but received filename is empty string.z>only supports saving objects to file and `BytesIO`, but got {}z<Type of `use_binary_format` should be bool, but received {}.NzJ'pickle_protocol' is a deprecated argument. Please use 'protocol' instead.r   )r
   r5   r6   rR   r%   rS   r8   makedirsr   r   r!   r_   r   r]   boolr   r   r^   rT   rU   r   descflushr	   r   Zserialize_to_stringr   r   r   _legacy_static_saver   )r   r6   r   r[   rN   rS   r>   rA   r*   r*   r+   save  sT   v



""r   ra   c           
      C   s  t | tstdt|  t| dkrtd t |ts&td	t||dk s.|dkr5td	|t
|rZtj|}|dkrGtd	tj|}|rZtj|sZt| t | trct| }t||}t
|rtjd
krtjjdkrtj||d}t|d!}d}tdt||D ]}	|||	|	|   qW d    d S 1 sw   Y  d S t|d}tj|||d W d    d S 1 sw   Y  d S )NzVNow only supports save state_dict of Layer or Optimizer, expect dict, but received %s.r   z/The input state dict is empty, no need to save.r`   ra   rb   rc   r   r   r~   r   )r   r   r   )r   r3   r   r!   r   rT   rU   r   r%   r   r
   r5   r6   rR   rS   r8   r   r,   r   r   r   r   r   r:   r   r9   r   r   r	   r   )
r   r6   r   rN   rS   Z	saved_objr   rA   r   r   r*   r*   r+   r   3  sX   






""r   c                 K   sT  t | stj| r t|}tj}zut| db}t| r.t	j
dkr.t	jjdkr.t| |}ntj|dd}t|trmt|}d|v rf|d D ]}t|| tjrZt|| |j||< qF|jsed|v re|d= nt||j}nt||j}W d   n1 s}w   Y  W |S W |S  |y } zzt| \}}	|W W  Y d}~S    z2t| \}}	|jrt|W  Y W  Y d}~S t rt|W  Y W  Y d}~S |W  Y W  Y d}~S    z.t| d}| }
t|
}|W  d   W  Y  Y W  Y d}~S 1 sw   Y  W n
   t d!| Y Y W Y d}~|S d}~ww t"| fi |}|S )	a"  
    Load an object can be used in paddle from specified path.

    Note:
        Now supports loading ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program.

    Note:
        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:
        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:
        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
        ``Layer.set_state_dict`` later.

    Args:
        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
            the inference model, the path may be a file prefix or directory.
        **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:
            (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.
            Default False.

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

    Examples:
        .. code-block:: python

            # example 1: dynamic graph
            import paddle
            emb = paddle.nn.Embedding(10, 10)
            layer_state_dict = emb.state_dict()

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

            scheduler = paddle.optimizer.lr.NoamDecay(
                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()

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

            # load state_dict of emb
            load_layer_state_dict = paddle.load("emb.pdparams")
            # load state_dict of optimizer
            load_opt_state_dict = paddle.load("adam.pdopt")
            # load weight of emb
            load_weight = paddle.load("emb.weight.pdtensor")


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


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


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

    r-   r~   r   latin1encodingr   Nz(`paddle.load` can not parse the file:{}.)#r   r5   r6   isfiler\   r:   UnpicklingErrorr	   r
   r   r   r   r   r   r;   r   r3   r   ri   r   r   rY   rX   r   r   r   rj   r   r   r   r   Zparse_from_stringr%   r   _legacy_load)r6   r[   r>   Zexception_typerA   load_resultr)   Z
msg_pickler   rL   Zprogram_desc_strprogramr*   r*   r+   r;   l  s    


FF<r;   c                 K   s   d }t |}tj| st| r<t| d}tj|dd}W d    n1 s'w   Y  t|}|j	s:d|v r:|d= |S t
| |\}}|jd u rKd}n|j}tj||}tj|rbt||}|S t|}|S )Nr-   r   r   r   Z	__model__)r\   r5   r6   r   r   r	   r:   r;   r   rX   rW   r/   r7   r8   rB   rP   )r6   r[   r   r>   rA   r=   r/   Zmodel_file_pathr*   r*   r+   r   T  s0   
r   )rb   )ra   )D
__future__r   r5   r   r:   rT   r   r&   ri   r   r   r   Zpaddle.fluidr   Zpaddle.fluid.ior   r   r   r   r   r	   r
   r   Zpaddle.fluid.frameworkr   r   r   r   r   r   r   r   Zpaddle.fluid.dygraph.jitr   Zpaddle.fluid.dygraph.ior   r   r   r   r   collections.abcr   __all__r,   rB   rP   rW   r\   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r;   r   r*   r*   r*   r+   <module>   sf   (
&14P!
	#%
 
.9 i