o
    Ne/                     @   s   d dl mZ d dlZd dlZd dlZddlmZmZmZm	Z	m
Z
mZmZmZmZ d dlZddlmZ d dlZddlmZ ddlmZ d d	lmZ d d
lmZmZ ddgZdd Ze	dd Zdd ZdS )    )print_functionN   )	Variabledefault_main_program_non_static_modedygraph_only	Parameter	ParamBase_varbase_creator_dygraph_tracerEagerParamBase   )learning_rate_scheduler)core)guard)_SaveLoadConfig)_construct_program_holders_construct_params_and_bufferssave_dygraphload_dygraphc                 C   sZ   g d}| D ]}||vrt d| qt }| dd |_| dd |_| dd |_|S )N)model_filenameparams_filenamekeep_name_tablezKThe additional config (%s) of `paddle.fluid.load_dygraph` is not supported.r   r   r   )
ValueErrorr   getr   r   r   )configsZsupported_configskeyZinner_config r   OD:\Projects\ConvertPro\env\Lib\site-packages\paddle/fluid/dygraph/checkpoint.py_parse_load_config#   s   r   c                 C   s2  t j|}|dksJ dd}t| dksJ dd}|  D ]\}}t|ttfr/|d7 }q |dkr6d}i }i }|  D ]\}}t|tt	j
t	jjfrY| ||< |j||< q>|||< q>||d< || }	t j|	}
|
ryt j|
syt |
 t|	d	}tj||d
d W d   dS 1 sw   Y  dS )a  
    :api_attr: imperative

    Save Layer's state_dict to disk. This will generate a file with suffix ".pdparams"
    
    The state_dict is get from Layers.state_dict function
    
    Args:
        state_dict(dict) : The state dict to be saved.
        model_path(str) : the file prefix to save the state_dict. The format is "dirname/file_prefix". If file_prefix is empty str. A exception will be raised

    Returns:
        None

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            with fluid.dygraph.guard():
                emb = fluid.dygraph.Embedding([10, 10])

                state_dict = emb.state_dict()
                fluid.save_dygraph( state_dict, "paddle_dy")

                adam = fluid.optimizer.Adam( learning_rate = fluid.layers.noam_decay( 100, 10000),
                                             parameter_list = emb.parameters() )

                state_dict = adam.state_dict()
                fluid.save_dygraph( state_dict, "paddle_dy")

     zThe input model_path MUST be format of dirname/filename [dirname\filename in Windows system], but received filename is empty string.	.pdparamsr   z$state_dict is empty, no need to saver   .pdoptStructuredToParameterName@@wbr   )protocolN)ospathbasenamelenitems
isinstancer	   r   r   r   ZVarBaseeagerZTensornumpynamedirnameexistsmakedirsopenpickledump)Z
state_dict
model_path	base_namesuffixZ	param_numkvZ
model_dictZ
name_table	file_namedir_namefr   r   r   r   6   s4   #

"c                 K   s  | }| dr|dd }n| dr|dd }d}d}|d }|d }t|}tj|s5tj|ri }tj|rYt|d}tj|dd}W d   n1 sTw   Y  |jscd	|v rc|d	= tj|rt|d}tj|dd}W d   ||fS 1 sw   Y  ||fS tj	|st
d
| |jdu rd}	n|j}	tj| |	}
tj|
rHt| |j}t  t|||jdd}t }|D ]
}||  ||< qt|jd }tj||}tj|r1t|d}t|}W d   n1 sw   Y  t }|D ]}|| dd}|dusJ d| || ||< q|}W d   ||fS W d   ||fS 1 s?w   Y  ||fS g }g }t| D ]%\}}}|D ]}tj||}tj|| }|dd}|| qXqQt , |D ]!}t|dd}t jdi d|idtj| |id || q}W d   n	1 sw   Y  t }|D ]
}| ||j< q||fS )a  
    :api_attr: imperative
    
    Load parameter state dict from disk.

    .. note::
        Due to some historical reasons, if you load ``state_dict`` from the saved 
        result of `paddle.static.save_inference_model`, the structured variable name 
        will cannot be restored. You need to set the argument `use_structured_name=False` 
        when using `Layer.set_state_dict` later.

    Args:
        model_path(str) : The file prefix store the state_dict. 
            (The path should Not contain suffix '.pdparams') 
        **configs (dict, optional): Other load configuration options for compatibility. We do not 
            recommend using these configurations, 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.

    Returns:
        state_dict(dict) : the dict store the state_dict

    Examples:
        .. code-block:: python

            import paddle
            import paddle.fluid as fluid

            paddle.disable_static()

            emb = paddle.nn.Embedding(10, 10)

            state_dict = emb.state_dict()
            fluid.save_dygraph(state_dict, "paddle_dy")

            scheduler = paddle.optimizer.lr.NoamDecay(	
                d_model=0.01, warmup_steps=100, verbose=True)
            adam = paddle.optimizer.Adam(
                learning_rate=scheduler,
                parameters=emb.parameters())
            state_dict = adam.state_dict()
            fluid.save_dygraph(state_dict, "paddle_dy")

            para_state_dict, opti_state_dict = fluid.load_dygraph("paddle_dy")
    r!   Nir"   irblatin1)encodingr#   z)Model saved directory '%s' is not exists.Z	__model__F)Zappend_suffixz.infostructured_namezACannot find saved variable (%s)'s structured name in saved model.\/T)r.   ZpersistableloadZOut	file_path)typeZinputsZoutputsattrs)endswithr   r&   r'   r0   r2   r3   rC   r   isdirr   r   joinr   r   r   r   dictr-   strr   walkrelpathreplaceappendr
   r   Ztrace_opr.   )r5   r   Zmodel_prefixZ	para_dictZ	opti_dictZparams_file_pathZopti_file_pathconfigr<   r   Zmodel_file_pathZprogramsZpersistable_var_dictvar_nameZvar_info_filenameZvar_info_pathZextra_var_infoZstructured_para_dictr@   Zload_var_listZvar_name_listroot_filesfilenamerD   Ztmp_var_namer.   Znew_varvarr   r   r   r      s   2


]]


?
??)
__future__r   r&   collections	functoolsZ	frameworkr   r   r   r   r   r	   r
   r   r   r3   r    r   warningsr   baser   Zpaddle.fluid.dygraph.jitr   Zpaddle.fluid.dygraph.ior   r   __all__r   r   r   r   r   r   r   <module>   s&   ,
H