
    Αi                    |   S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	J
r
  S SKJr  S SKrS SKrS SKJr  S SKJr  S SKJrJrJrJrJrJrJrJrJr  SS	KJrJrJ r J!r!J"r"J#r#J$r$  \(       aK  S S
K%J&r&  S SKJ'r'J(r(J)r)  S SK*J+r+J,r,  S SKJ-r-  S SK.J/r/  S SK0J1r1   " S S\)5      r2 " S S\)5      r3 " S S\)5      r4/ r5/ r6S3S jr7  S4           S5S jjr8S r9S r:S r;S r<S r=S r>S r?S r@S  rAS! rBS" rCS# rDS$ rES% rFS& rGS' rHS( rIS) rJS* rKS+ rLS, rMS- rN S6         S7S. jjrOS/ rPS8S0 jrQS9S1 jrRS2 rSg):    )annotationsN)Iterable)TYPE_CHECKING)base)core)	EagerParamBaseProgramVariable_create_tensor_current_expected_place_current_expected_place__dygraph_tracerin_dygraph_modein_pir_mode   )_is_file_path_is_memory_buffer_legacy_static_save_open_file_buffer_pack_loaded_dict_pickle_loads_mac_unpack_saved_dict)BytesIO)AnyLiteral	TypedDict)NotRequiredUnpack)Tensor)NestedStructure)
_StateDictc                      \ rS rSrSrg)
_EmptyDictB    N)__name__
__module____qualname____firstlineno____static_attributes__r%       S/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/framework/io.pyr#   r#   B   s    r+   r#   c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   Srg	)
_LoadOptionsE   zNotRequired[str]model_filenameparams_filenameNotRequired[bool]keep_name_tablereturn_numpyr%   Nr&   r'   r(   r)   __annotations__r*   r%   r+   r,   r.   r.   E   s    (())**''r+   r.   c                  *    \ rS rSr% S\S'   S\S'   Srg)_SaveOptionsK   r2   use_binary_formatzNotRequired[Literal[2, 3, 4]]pickle_protocolr%   Nr5   r%   r+   r,   r8   r8   K   s    ,,66r+   r8   c                     [        [        5      S:  aV  [        R                  5       n U (       a%  U R                  5       (       a  U R	                  5         [        [        5      S:  a  MU  gg)z,
wait until all async save task to be done.
r   N)lenasync_save_queuepopis_alivejoin)tasks    r,   clear_async_save_task_queuerC   T   sF     
!
###%DMMOOIIK 
!
#r+   c                H  ^ [        5       (       d  [        S5      e[        U5      S:  a  [        R                  " S5        U4S jm[        U [        5      (       a	  T" U 5        Om[        U [        R                  R                  5      (       a-  [        R                  " 5       (       a  U R                  5       OU n O[        S[        U 5       35      eU(       a
  [        5         [        R                   " ["        XU4S9nUR%                  5         [&        R)                  U5        g)a  
async version of paddle.save.
Note:
    currently only support dygraph mode.
Note:
    any argument passed through configs will be overridden by default setting.
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
    sync_other_task(bool) : Determine whether to wait other async save task to be finished before this one be put in queue.
    **configs(dict, optional): compatible argument to paddle.save, but will be overridden by default setting.
Examples:
    .. code-block:: python
        :name: code-example-1

        import paddle
        emb = paddle.nn.Embedding(10, 10)
        layer_state_dict = emb.state_dict()

        # call paddle.async_save with the same style of paddle.save
        paddle.async_save(layer_state_dict, "emb.pdparams")
        for i in range(10):
            # do some calculations here
        # wait if any async_save task has not been done
        paddle.clear_async_task_queue()
z5async_save currently is not supported in static mode.r   zPconfigs are not supported in async mode, will be overridden by default settings.c                (  > U R                  5        H}  u  p[        U[        5      (       a
  T" U5        M$  [        U[        R                  R
                  5      (       d  MO  [        R                  " 5       (       a  UR                  5       OUX'   M     g N)items
isinstancedictr   eagerr   is_compiled_with_cuda
pin_memory)sdkvmove_state_dict_to_cpus      r,   rP   *async_save.<locals>.move_state_dict_to_cpu   s^    HHJDA!T""&q)Atzz0011*.*D*D*F*FA	 r+   z1currently async_save does not support this type: )targetargsN)r   
ValueErrorr=   warningswarnrH   rI   r   rJ   r   rK   rL   	TypeErrortyperC   	threadingThreadsavestartr>   append)objpathprotocolsync_other_taskconfigstrP   s         @r,   
async_saverd   ^   s    H C
 	
 7|a^	

N #ts#	C**	+	+"&"<"<">">cnnC ?S	{K
 	
 #%Cx+@AAGGIAr+   c                   0 n0 nU R                  5        GHo  u  p4[        U[        [        R                  R
                  45      (       Ga5  UR                  [        R                  R                  R                  :X  a!  UR                  5       R                  5       X'   OUR                  5       R                  5       R                  5       (       d  [        S5      eUR                  5       (       aZ  UR                   R#                  5       (       a;  [        R$                  " S5      (       a   [&        R(                  R+                  US5      n[,        R.                  " UR1                  5       5      X'   UR2                  X#'   GMk  XAU'   GMr     X!S'   U$ )NzdThe saved tensor is not initialized. If you used group sharded, please use save_group_sharded_model.npuStructuredToParameterName@@)rG   rH   r
   r   rJ   r   rX   VarDescVarTypeVOCABvalueget_map_tensor
get_tensor_is_initializedrT   is_denseplaceis_custom_placeis_compiled_with_custom_devicepaddle_C_opsnpu_identitynparraycpuname)
state_dict	save_dict
name_tablekeyrl   s        r,   _build_saved_state_dictr      s   IJ &&(
eh

(9(9:;;zzT\\11777!&!=!=!?	{{}//1AACC$~  NN$$3355;;EBB"MM66ubAE!#%))+!6	#jjJO"cN% )& 0:+,r+   c                    [        5       (       a  SSKJnJn  U" XR                  5      nOSSKJnJn  U" XR                  5      n[        R                  R                  5          U" XUR                  5      n0 nU H  nXW   nUR                  5       (       ae  UR                  R                  5       (       aF  [        R                  " [        R                   R#                  US5      R%                  5       5      Xg'   M  [        R                  " UR%                  5       5      Xg'   M     ['        UR                  5      S-   n	[(        R*                  R-                  X	5      n
[(        R*                  R/                  U
5      (       ab  [1        U
S5       n[2        R4                  " U5      nS S S 5        0 nU H-  nWU   R7                  SS 5      nUc   SU S35       eUU   X'   M/     UnS S S 5        U$ ! , (       d  f       NO= f! , (       d  f       W$ = f)	Nr   )_construct_params_and_buffers_construct_program_holdersrg   z.inforbstructured_namezCannot find saved variable (z#)'s structured name in saved model.)r   paddle.jit.pir_translated_layerr   r   r0   paddle.jit.translated_layerr   dygraphguardr1   rp   rq   rr   rw   rx   rt   ru   rv   ry   strosr_   rA   existsopenpickleloadget)
model_pathconfigr   r   programspersistable_var_dictload_param_dictvar_nametmp_varvar_info_filenamevar_info_pathfextra_var_infostructured_para_dictr   s                  r,   *_load_state_dict_from_save_inference_modelr      s    }}	

 .j:O:OP	

 .j:O:OP 
			<&"8"8 

 ,H*4G!!gmm&C&C&E&E,.HHMM..w;??A-) -/HHW[[],C) -   6 67'AZC77>>-((mT*a!'Q +#% +"0":">">%t# '2 28*<_`2 9H9$5 , 3OC 
F  +*) 
	F s%   #D*G>G-$?G>-
G;	7G>>
Hc                n   / n/ n[         R                  " U 5       Hp  u  p4nU Hd  n[         R                  R                  X65      n[         R                  R	                  Xp5      nUR                  SS5      n	UR                  U	5        Mf     Mr     [        R                  R                  5          U HY  n
[        U
SS9n[        5       R                  S0 SU0S[         R                  R                  X
5      0S9  UR                  U5        M[     S S S 5        0 nU H  nUR                  5       (       a?  UR                  R                  5       (       a   [         R"                  R%                  US	5      n[&        R(                  " UR+                  5       5      XR,                  '   M     U$ ! , (       d  f       N= f)
N\/T)rz   persistabler   Out	file_path)rX   inputsoutputsattrsrg   )r   walkr_   rA   relpathreplacer]   r   r   r   r   r   trace_oprp   rq   rr   rt   ru   rv   rw   rx   ry   rz   )r   load_var_listvar_name_listroot_filesfilenamer   tmp_var_namer   rz   new_varr   vars                 r,   !_load_state_dict_from_save_paramsr      s[    M M''*-HT4I77??9AL#++D#6H  *	  . 
			!D$$DAG&&("BGGLL$BC	 '    ) " 
 O<<>>cii7799--,,S"5C$&HHSWWY$7! 
 % 
	s   -A F&&
F4c                n   SSK Jn  SSKJnJn  [        5       (       a  X-   nOX-   n[        R                  R                  U5      n[        R                  R                  U 5      nU(       a  U(       a  [        SU  SU  S35      eU(       dm  U(       df  SnU S-   n	U S	-   n
[        R                  R                  U	5      (       d$  [        R                  R                  U
5      (       a  US
-  n[        X-  5      eU(       a  [        R                  R                  U 5      n[        R                  R                  U 5      nUR                  b  [        R                  " S5        [        5       (       a
  X-   Ul        O	X-   Ul        UR                   b  [        R                  " S5        X-   Ul        X4$ U nX4$ )Nr   )PIR_INFER_MODEL_SUFFIX)INFER_MODEL_SUFFIXINFER_PARAMS_SUFFIXzThe z.pdmodel and z 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.pdoptzplease 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   r   r   r   r   r   r   r_   r   isdirrT   basenamedirnamer0   rU   rV   r1   )r_   r   r   r   r   prefix_format_pathprefix_format_existdirectory_format_exist	error_msgparams_file_pathopti_file_pathfile_prefixr   s                r,   _build_load_path_and_configr   +  s   

 }}!:!6''..);<WW]]4054&dV ,% %
 	

 !)?A	  +-77>>*++rww~~n/M/M*I
 )**''**40K.J$$0'
 }}(3(L%(3(H%%%1'
 &1%FF"
  Jr+   c                H   / SQnU  H  nX!;  d  M
  [        SU S35      e   SSKJn  U" 5       nU R                  SS 5      Ul        U R                  SS 5      Ul        U R                  SS 5      Ul        U R                  S	S
5      Ul        U R                  SS
5      Ul        U$ )N)r0   r1   r3   r4   safetensorsThe additional config (z$) of `paddle.load` is not supported.r   _SaveLoadConfigr0   r1   r3   r4   Fr   )	rT   paddle.jit.apir   r   r0   r1   r3   r4   r   rb   supported_configsr~   r   inner_configs        r,   _parse_load_configr   n  s     ')#.RS   /"$L")++.>"EL#*;;/@$#GL #*;;/@$#GL  'NE BL&{{=%@Lr+   c                    / SQnU  H  nX!;  d  M
  [        SU S35      e   SSKJn  U" 5       nU R                  SS5      Ul        U R                  SS 5      Ul        U R                  S	S5      Ul        U$ )
N)r:   r;   r   r   z$) of `paddle.save` is not supported.r   r   r:   Fr;   r   )rT   r   r   r   r:   r;   r   r   s        r,   _parse_save_configr     s    O ')#.RS   /"$L%,[[1De%LL"#*;;/@$#GL &{{=%@Lr+   c                  ^
^^^ [        U[        5      (       d  [        S[        U5       35      eUS:  d  US:  a  [        SU 35      eS mS mS m0 m
U
U4S jn[	        U S	 U5        U
UU4S
 jnU
4S jn[
        R                  S:X  aw  [
        R                  R                  S:X  aY  U" 5         [        R                  " U 5      nU" 5         Sn[        S[        U5      U5       H  nUR                  XhX-    5        M     g [        R                  " X5      n	[        R                   R#                  5       U	l        TU	R                   [$        R&                  '   TU	R                   [$        R(                  R*                  '   TU	R                   [,        '   U	R                   R/                  T
5        U	R1                  U 5        g )N+The 'protocol' MUST be `int`, but received       /Expected 1<'protocol'<5, but received protocol=c                   U R                  5       (       a}  U R                  R                  5       (       a^  [        R                  " S5      (       aC  [
        R                  " [        R                  R                  U S5      R                  5       5      nO$[
        R                  " U R                  5       5      nU R                  n[        X!444$ )Nrf   rg   )rp   rq   rr   r   rs   rw   rx   rt   ru   rv   ry   rz   tuple)selfdatarz   s      r,   reduce_varbase$_pickle_save.<locals>.reduce_varbase  s    MMOO

**,,33E::88FMM66tR@DDFGD88DHHJ'Dyy''r+   c                   [         R                  " 5       nUR                  [        R                  " 5       5        U R                  5       R                  5       (       aD  [        R                  " [        R                  R                  U S5      R                  U5      5      nO%[        R                  " U R                  U5      5      n[        SSU044$ )Nrg   r   )r   Place	set_placert   CPUPlace_placerr   rw   rx   ru   rv   _copyeval)r   pr   s      r,   reduce_DenseTensor(_pickle_save.<locals>.reduce_DenseTensor  s    JJL	FOO%&;;=((**88FMM66tR@FFqIJD88DJJqM*Dv~.//r+   c                    [        S5      e)Nz6paddle do not support saving `paddle.nn.Layer` object.)rT   )r   s    r,   reduce_Layer"_pickle_save.<locals>.reduce_Layer  s    D
 	
r+   c                &   > TTU R                   '   U $ rF   )	__class__)layerdispatch_table_layerr   s    r,   create_layer_dispatch_table1_pickle_save.<locals>.create_layer_dispatch_table  s    0<U__-r+   c                J    [        U [        R                  R                  5      $ rF   rH   rt   nnLayer)rO   s    r,   <lambda>_pickle_save.<locals>.<lambda>  s    *Q		0r+   c                 
  > T[         R                  [        R                  R                  '   T[         R                  [
        '   T[         R                  [        R                  '   [         R                  R                  T 5        g rF   )r   dispatch_tabler   rJ   r   r   DenseTensorupdate)r   r   r   s   r,   add_dispatch_table(_pickle_save.<locals>.add_dispatch_table  sX    3Adjj//00>n-2Dd../$$%9:r+   c                 d  > [         R                  R                  [        R                  5        [         R                  R                  [        R
                  R                  5        [         R                  R                  [        5        T H"  n [         R                  R                  U 5        M$     g rF   )r   r   r?   r   r   rJ   r   r   )rN   r   s    r,   pop_dispatch_table(_pickle_save.<locals>.pop_dispatch_table  sm    !!$"2"23!!$**"3"34!!.1%A!!%%a( &r+   darwin      @r   )rH   intrT   rX   _parse_every_objectsysplatformversion_infomajorr   dumpsranger=   writePicklercopyregr   copyr   r   rJ   r   r   r   dump)r^   r   r`   r   r   r   pickle_bytes	max_bytesipicklerr   r   r   r   s             @@@@r,   _pickle_saver    s~   h$$9$x.9IJ
 	
 !|x!|=hZH
 	
(0

  0#;) ||xC$4$4$:$:a$?||C(	q#l+Y7AGGLQ]34 8 ..-!(!7!7!<!<!>3Et//04Btzz0011?~.%%&:;Sr+   c                   [        U [        R                  5      (       a  [        S5      eU" U 5      (       a  g[	        U 5      [
        [        R                  [        [        4;   ax  [	        U 5      [
        [        R                  4;   a  [        U R                  5       5      nO[        [        U 5      5      nSnU H  nU[        X   U5      -  nU(       d  M    g   U$ g)Nz3`paddle.save` do not support saving 'SelectedRows'.TF)rH   r   SelectedRowsNotImplementedErrorrX   rI   collectionsOrderedDictlistr   keysr  r=   
_contain_x)r^   condition_funcr  flagr~   s        r,   r  r    s    #t(())!A
 	
 c	ct[44dEB	B9{6677
#DS?DCJsx88Dt  r+   c                d   [        U [        5      (       a  S nU R                  5        H  u  p#[        U[        5      (       a.  UR                  5        H  u  pE[        XQ5      (       d  M      g   MH  [        U[        R
                  R                  [        R                  45      (       a  M    g   gg)Nc                    [        U [        R                  R                  [        [
        R                  R                  [
        R                  [
        R                  45      $ rF   )
rH   rt   r   r   r	   r   rJ   r   r   r  r^   s    r,   	condition!_is_state_dict.<locals>.condition  sD    IIOOJJ%%$$%%	 	r+   FT)rH   rI   rG   r  r   rJ   r   r   )r^   r  r~   rl   rN   rO   s         r,   _is_state_dictr     s    #t
	 ))+JC%&&!KKMDA!!//$ *  

(9(94;K;K'LMM & r+   c                    [        U [        5      (       aL  [        U 5      S:X  a=  [        n[        U S   U5      (       a#  [        U S   [        R
                  5      (       a  gg)Nr   r   r   TF)rH   r   r=   r   rw   ndarray)r^   
name_typess     r,   _transformed_from_varbaser$  /  sK     #u#c(a-
c!fj))jQ.L.Lr+   c                D    [        U [        R                  5      (       a  gg)NTF)rH   rw   r"  r  s    r,   _transformed_from_lodtensorr&  9  s     #rzz""r+   c                    [        U [        R                  5      (       d  [        S[	        U 5       S35      e[
        R                  " 5       n[        5       nUR                  X5        U$ )Nz8Type of `ndarray` should be numpy.ndarray, but received .)	rH   rw   r"  rW   rX   r   r   r   set)r"  rc   rq   s      r,   _to_LodTensorr*  A  sZ    grzz**FtG}oUVW
 	
 	A$&EEE'Hr+   c                    U(       a  U S   $ [        5       (       a%  [        R                  " U S   5      nU S   Ul        U$ [	        U S   5      $ )Nr   r   )r   rt   	to_tensorrz   r*  )r^   r4   rc   s      r,   _tuple_to_tensorr-  L  sL    1vSV$ QSV$$r+   c                t    U(       a  U $ [        5       (       a  [        R                  " U 5      $ [        U 5      $ rF   )r   rt   r,  r*  r^   r4   s     r,   _ndarray_to_tensorr0  Y  s/    
$$S!!r+   c                    [        5       nUR                  5       R                  5       R                  U [	        5       5        U$ rF   )r   rl   rn   r)  r   )tensor
return_vars     r,   _lod_tensor2varbaser4  b  s6    !J!!#''0G0IJr+   c                *   U" U 5      (       a  U" U 5      $ [        U 5      [        [        R                  [        4;   ay  [        U 5      [        :X  a  [        [        U 5      5      nO[	        U R                  5       5      nU H0  nU" X   5      (       a  U" X   5      X'   M   [        X   X5      X'   M2     U $ [        U 5      [        :X  a  [        [        [	        U 5      X5      5      $ [        U 5      [        :X  a  [        [        [	        U 5      X5      5      $ [        U [        5      (       ae  [        U [        [        R                  [         R"                  R$                  [         R&                  45      (       d  [)        S[        U 5       S35      eU $ )NzXThe iterable objects supported are tuple, list, dict, OrderedDict, string. But received r(  )rX   rI   r  r  r  r  r=   r  r   r   r)  rH   r   r   rw   r"  r   rJ   r   r   r  )r^   r  convert_funcr  r~   s        r,   r   r   h  sL   cC  	ct[44d;	;9S?D
#DCch'''1.Hn	  
	ce	S	>H
 	
 
cc	&tCy.OPPc8$$Z"**djj//1A1AB.
 .
 &jkopsktjuuvw  
r+   c                  ^ S nS n[        X5      (       a&  [        5       (       d  [        S5      e[        XU5        U4S jnU4S jn[        U [        5      (       a  [        U [        U5      $ [        U [
        U5      $ )Nc                J    [        U [        R                  R                  5      $ rF   r   r  s    r,   is_layer$_parse_load_result.<locals>.is_layer  s    #vyy//r+   c                h    [        U R                  S5      nU R                  R                  U5        U $ )NF)_parse_load_result__dict__r   )r^   	temp_dicts     r,   parse_layer'_parse_load_result.<locals>.parse_layer  s)    &s||U;	I&
r+   zMLayer can only be loaded in dynamic graph mode, but now in static graph mode.c                   > [        U TS9$ N)r4   )r-  r/  s    r,   tuple_to_tensor+_parse_load_result.<locals>.tuple_to_tensor  s    ,??r+   c                   > [        U TS9$ rB  )r0  r/  s    r,   ndarray_to_tensor-_parse_load_result.<locals>.ndarray_to_tensor  s    !#LAAr+   )r  r   rT   r   r$  r&  )r^   r4   r9  r?  rC  rF  s    `    r,   r<  r<    s    0
 #    _  	C;7@B
 #011"*O
 	
 #,.?
 	
r+   c                   U R                  5       (       d  [        S5      e[        U5      (       a  [        R                  " X5      nU$ [        U5      (       aN  [        R                  " U 5      n[        US5       nUR                  U5        UR                  5       nS S S 5        U$ [        S[        U5       35      e! , (       d  f       W$ = f)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 )ro   rT   r   r   save_dense_tensorr   save_dense_tensor_to_memoryr   r  tellr  rX   )r2  	file_name_seektensor_bytesr   s        r,   _save_dense_tensorrQ    s    !!##z
 	
 Y&&v9 L 
9	%	%77?y$/1GGL!FFHE 0 L "LTR[_L]^
 	
 0/ Ls   ;"B>>
Cc                   [         R                  R                  R                  5       n[	        U 5      (       a,  [         R                  R                  R                  X5      nX4$ [        U 5      (       aa  [        U S5       nUR                  5       n[         R                  R                  R                  X5        UR                  5       nS S S 5        X4$ [        S[        U 5       35      e! , (       d  f       UW4$ = fNr   z>Only supports load objects from file or BytesIO, but received )rt   r   r   r   r   load_dense_tensorr   r   readload_dense_tensor_from_memoryrM  r  rX   )rN  temp_trO  r   rP  s        r,   _load_dense_tensorrX    s    [[))+FY  226E = 
9	%	%y$/1668LKK::6PFFHE 0 =	 "LTR[_L]^
 	
 0/ 5=s   A
C--
C>c                   U R                  5       R                  5       (       d  [        S5      e[        U5      (       a  [        R
                  " X5      nU$ [        U5      (       aN  [        R                  " U 5      n[        US5       nUR                  U5        UR                  5       nS S S 5        U$ [        S[        U5       35      e! , (       d  f       W$ = f)Nz$The saved tensor is not initialized.rI  rJ  )rn   ro   rT   r   r   save_selected_rowsr   save_selected_rows_to_memoryr   r  rM  r  rX   )selected_rowsrN  rO  selected_rows_bytesr   s        r,   _save_selected_rowsr^    s    ##%5577?@@Y''A L 
9	%	%"??Ny$/1GG'(FFHE 0 L "LTR[_L]^
 	
	 0/ Ls   	"C
Cc                   [         R                  " 5       n[        U 5      (       a  [         R                  " X5      nX4$ [	        U 5      (       aa  [        U S5       nUR                  5       n[        R                  R                   R                  X5        S S S 5        WR                  5       nX4$ [        S[        U 5       35      e! , (       d  f       N8= frS  )r   r  r   load_selected_rowsr   r   rU  rt   r   load_selected_rows_from_memoryrM  r  rX   )rN  temp_srrO  r   r]  s        r,   _load_selected_rowsrc    s    !GY''; > 
9	%	%y$/1"#&&(KK;; 0
  >	 "LTR[_L]^
 	
 0/s   :C
Cc                   [        U [        R                  5      (       a  [        X5        g [        U [        R                  5      (       a  [        X5        g [        U [        R                  R                  5      (       a)  [        U R                  5       R                  5       U5        g [        S[        U 5       S35      e)NzLWhen use_binary_format = True, `paddle.save`  expected Tensor, but received r(  )rH   r   r   rQ  r  r^  rJ   r   rl   rn   r  rX   )r^   r_   s     r,   _save_binary_varre    s    #t''((3%	C**	+	+C&	C**	+	+399;113T: "Z[_`c[dZeefg
 	
r+   c                V   [        U5      (       a  [        R                  R                  U5      nUS:X  a  [	        S5      e[        R                  R                  U5      nU(       a9  [        R                  R                  U5      (       d  [        R                  " USS9  O'[        U5      (       d  [	        S[        U5       35      e[        U5      n[        UR                  [        5      (       d"  [        S[        UR                  5       S35      eUR                  (       a  [        X5        gUR                   b"  UR                   n["        R$                  " S	5        [        U [&        R(                  R*                  5      (       a  [-        5       (       a   [&        R.                  R1                  X5        gU R2                  R5                  5         [7        US
5       nUR9                  U R2                  R;                  5       5        SSS5        g[=        U 5      (       aF  [?        5       (       a*  UR@                  (       a  [C        X5        g[E        XU5        g[G        XU5        g[7        US
5       n[I        XU5        SSS5        g! , (       d  f       g= f! , (       d  f       g= f)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
        :name: code-example-1

        >>> # 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=100, 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")

    .. code-block:: python
        :name: code-example-2

        >>> # example 2: Save multiple state_dict at the same time
        >>> import paddle
        >>> 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)

    .. code-block:: python
        :name: code-example-3

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

    .. code-block:: python
        :name: code-example-4

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

    .. code-block:: python
        :name: code-example-5

        >>> # 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)
        >>> paddle.seed(2023)
        >>> 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.Texist_okz<only supports saving objects to file and `BytesIO`, but got z9Type of `use_binary_format` should be bool, but received r(  NzJ'pickle_protocol' is a deprecated argument. Please use 'protocol' instead.rI  )%r   r   r_   r   rT   r   r   makedirsr   rX   r   rH   r:   boolrW   re  r;   rU   rV   rt   staticr	   r   r   serialize_pir_programdescflushr   r  serialize_to_stringr   r   r   
_safe_save_legacy_saver   r  )r^   r_   r`   rb   r   r   r   r   s           r,   r[   r[     s   P T77##D)r>,  ''//$'277>>'22KK$/t$$J4PT:,W
 	
  (Ff..55GVMeMeHfGgghi
 	
 # !!---HMM\ c6==0011}}11#< &tT2aGGCHH88:; 32 C    %%s) H5#Cx8"4.!SX. /. 32 /.s   *J	3J	
J
J(c                   [        U [        5      (       d  [        S[        U 5       S35      e[	        U 5      S:X  a  [
        R                  " S5        [        U5      (       a  [        R                  R                  U5      nUS:X  a  [        S5      e[        R                  R                  U5      nU(       a9  [        R                  R                  U5      (       d  [        R                  " USS9  SS	KJn  U" X5        g )
NSNow only supports save state_dict of Layer or Optimizer, expect dict, but received r(  r   /The input state dict is empty, no need to save.rg  rh  Tri  )	save_file)rH   rI   r  rX   r=   rU   rV   r   r   r_   r   rT   r   r   rk  safetensors.paddlerw  )r^   r_   r   r   rw  s        r,   rr  rr    s    c4  !))-c16
 	

 3x1}GHT77##D)r>,  ''//$'277>>'22KK$/,cr+   c           
       ^^ [        U [        5      (       d  [        S[        U 5       S35      e[	        U 5      S:X  a  [
        R                  " S5        [        U[        5      (       d  [        S[        U5       35      eUS:  d  US:  a  [        SU 35      e[        U5      (       a  [        R                  R                  U5      nUS	:X  a  [        S
5      e[        R                  R                  U5      nU(       a9  [        R                  R                  U5      (       d  [        R                  " USS9  [        U [        5      (       a  [!        U 5      n[#        WU5      n[        U5      (       a  [$        R&                  S:X  az  [$        R(                  R*                  S:X  a\  [,        R.                  " XRS9m[1        US5       nSmUR3                  UU4S j[5        S[	        T5      T5       5       5        S S S 5        g [7        US5       n[,        R8                  " XVUS9  S S S 5        g ! , (       d  f       g = f! , (       d  f       g = f)Nru  r(  r   rv  r   r   r   r   rg  rh  Tri  r   r   )r`   rI  r   c              3  2   >#    U  H  nTXT-    v   M     g 7frF   r%   ).0r  r  r  s     r,   	<genexpr>_legacy_save.<locals>.<genexpr>  s!      ?A QY/?s   )rH   rI   r  rX   r=   rU   rV   r   rT   r   r   r_   r   r   r   rk  r   r   r  r  r  r  r   r  r   
writelinesr  r   r  )	r^   r_   r`   r   r   	saved_objr   r  r  s	          @@r,   rs  rs    s   c4  !))-c16
 	

 3x1}GHh$$9$x.9IJ
 	
 !|x!|=hZH
 	
 T77##D)r>,  ''//$'277>>'22KK$/#t+C0	"9h7I 	dLLH$""a'||IA$ILL q#l"3Y?   tT*aKK	x8 +*  +*s   3H/I /
H= 
Ic                   [        U 5      (       d%  [        R                  R                  U 5      (       Ga  [	        U5      n[
        R                  n UR                  (       a  UR                  (       a  SSK	J
n  U" U 5      n[        U5      nU$ SSKnSSKJ
n  [        [        5       [        R                   5      (       a  UR"                  S:  a`  [$        R"                  S:  aL  UR'                  U SS9n0 nUR)                  5        H$  nUR+                  U5      R-                  5       XX'   M&     U$ U" U [        5       S9n U$ U" U S	S9nU$ [/        U S
5       n[1        U 5      (       a>  [2        R4                  S:X  a*  [2        R6                  R8                  S:X  a  [;        X5      nO[
        R<                  " USS9n[        U[>        5      (       a  [        U5      nSU;   a  US   RA                  5        Ht  u  p[        XY   [B        RD                  5      (       d  M(  [G        XY   UR                  5      XY'   UR                  (       a  MU  [I        XY   SS5      (       d  Mk  XU	   l%        Mv     URL                  (       d	  SU;   a  US	 O+[O        XRR                  5      nO[O        XRR                  5      nSSS5        U$ [        U 40 UD6nU$ ! , (       d  f       W$ = f! U Ga  n [Q        U 5      u  pUs SnA$ !    [S        U 5      u  pUR                  (       a  [        RT                  " 5       nURW                  [$        RX                  " 5       5        UR[                  5       R]                  5       (       aJ  [B        R^                  " [$        R`                  Rc                  US5      Re                  U5      5      s s SnA$ [B        R^                  " URe                  U5      5      s s SnA$ [g        5       (       a  [i        U5      s s SnA$ Us s SnA$ !    [k        5       (       aH  [$        Rl                  Ro                  5       n[$        R                  Rq                  X5        Us s s SnA$ [/        U S
5       nURs                  5       n[n        Rt                  " U5      n[$        Rv                  Ry                  5       (       Gal  [$        Rz                  R}                  5          [$        R~                  R                  UR                  5      nUR                  5       n/ nUR                   H  nURK                  5       S:X  d  M  UR                  5       S   nUR                  S5      nU   [$        Rl                  R                  UUR                  UR                  S9nUR                  U5        UR                  5       R                  U5        SSS5        O! , (       d  f       O= fUR                  U5        M     U H  nUR                  U5        M     SSS5        O! , (       d  f       O= fUsSSS5        s s s SnA$ ! , (       d  f         O= f!   [        SU  S35      e= f= f= f SnAW$ SnAff = f)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`` needs 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.base.io.save_inference_model`` or
    ``paddle.base.io.save_params/save_persistables`` , ``path`` needs to be a
    directory, such as ``model`` and model is a directory.

Note:
    If you load ``state_dict`` from the saved result of static graph mode API such as
    ``paddle.static.save`` or ``paddle.static.save_inference_model`` ,
    the structured variable name in dynamic mode 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:: pycon
        :name: code-example-1

        >>> # 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=100,
        ...     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")

    .. code-block:: pycon
        :name: code-example-2

        >>> # example 2: Load multiple state_dict at the same time
        >>> import paddle
        >>> 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)

    .. code-block:: pycon
        :name: code-example-3

        >>> # 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 = paddle.static.global_scope().find_var(var.name).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)

    .. code-block:: pycon
        :name: code-example-4

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

    .. code-block:: pycon
        :name: code-example-5

        >>> # 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)
        >>> paddle.seed(2023)
        >>> tensor = paddle.randn([2, 3], dtype='float32')
        >>> paddle.save(tensor, byio)
        >>> byio.seek(0)
        >>> # load state_dict
        >>> dict_load = paddle.load(byio)

r   	load_fileNz0.6.2z3.2.0rt   )	framework)devicery   r   r   r   latin1encodingrh   rz   rg  rg   z
pd_op.feed)rz   shapedtypez%`paddle.load` can not parse the file:r(  )Pr   r   r_   isfiler   r   UnpicklingErrorr   r4   safetensors.numpyr  r   rx  rH   r   r   	CUDAPlace__version__rt   	safe_openr  rn   cudar   r   r  r  r  r  r   r   rI   rG   rw   r"  r0  getattrrz   r3   r<  rc  rX  r   r   r   r   rr   rx   ru   rv   r   r   r4  r   rm  r	   deserialize_pir_programrU  parse_from_stringr  in_pir_executor_mode	pir_utilsIrGuardpirtranslate_to_pirro  global_blockopsr   resultr   r  r  replace_all_uses_withget_defining_opmove_beforer]   	remove_oprT   _legacy_load)r_   rb   r   exception_typer  load_resultr   r   rN   r~   rz   
msg_pickler2  r   r   programprogram_desc_strblockremove_op_listopr   	org_valuerl   s                          r,   r   r   &  sW   P "''.."6"6#G,//I	!!&&;"+D/K"3K"@K. #"+ '<!"9";T^^LL'33g= & 2 2g = !, 5 5dh 5 OA*,K%&VVX12a1E1E1G &. #" +4 $-D-F+K #" '0U&C"""4.! "$''0((..!3"3D"<K"(++a("CK k400"3K"@K4C)49*%'*"IC  *+*:BJJGG3E$/$4f6I6I4" 0 (.':':':w$/$4fb@" @" =A$4$9*" !' 6 6 = L +,I J '9')<)<'
 #5#%8%8#KS /^  #4373_ /.^ E  =	</5	98 24 8IF** JJLFOO$56!==?::<<#%88 & : :62 F L LQ O$  $&88FLLO#<<*,,#6v#>>%)(&==&,mm&;&;&=G"KK??N#*NN.tT:a/0vvx,&-&?&? 0'G  &//DDFF%+%5%5%=%=%?.4jj.I.I(//&G -4,@,@,BE57N.3ii+-779+D79xxz&7IH8:		!I168>8J8J9A:C//:C// 9K 92
 1:0O0O4912 160E0E0G0S0S4612 27 -;,A,A",E! /8" /=(-(; /=/ &@%?%?2 $+? ;::::@(CD6K C ;P E=	s  <K B K 0K K K CK
)K
	K
AK
2K 

KK K Y>$K82Y>8Y0;B<P7Y08Y99Y>?$P#Y0$Y9%Y>+PY0Y9Y>PY0Y9Y>Y-AY%Y-&Y0(Y9)Y>/Y;A)Y	$AX!&X!+A$W	X!
W&"6X!	Y	!
X/+Y	3	Y<Y-=Y0?Y9 Y>
YYY0Y9YY*	*Y--Y00Y99Y>c                   S n[        U5      n[        R                  R                  U 5      (       d  [	        U 5      (       aq  UR
                  (       a  SSKJn  U" U 5      nO*[        U S5       n[        R                  " USS9nS S S 5        [        U5      nUR                  (       d	  SU;   a  US	 U$ [        X5      u  pcUR                  c  SnOUR                  n[        R                  R                  Xg5      n[        R                  R!                  U5      (       a  [#        Xc5      nU$ [%        U5      nU$ ! , (       d  f       N= f)Nr   r  r   r  r  rh   	__model__)r   r   r_   r  r   r   rx  r  r   r   r   r   r3   r   r0   rA   r   r   r   )	r_   rb   r  r   r  r   r   r0   model_file_paths	            r,   r  r  b  s   K(F	ww~~d0664#D/K"4.!$kk!h? /'4&&-<9:> 9 9F
  ((N#22N'',,zB77>>/** EK  <JGKM /.s   .D99
E)returnNone)r   F)r^   objectr_   str | BytesIOr`   Literal[2, 3, 4]ra   rl  rb   zUnpack[_EmptyDict]r  r  )r   )
r^   z._StateDict | NestedStructure[Tensor] | Programr_   r  r`   r  rb   zUnpack[_SaveOptions]r  r  )r   )r_   r  rb   zUnpack[_LoadOptions]r  r   )T
__future__r   r  r	  r   r   r  rY   rU   collections.abcr   typingr   numpyrw   rt   r   paddle.baser   paddle.base.frameworkr   r	   r
   r   r   r   r   r   r   io_utilsr   r   r   r   r   r   r   ior   r   r   r   typing_extensionsr   r   r   paddle._typingr    paddle.nn.layer.layersr!   r#   r.   r8   __all__r>   rC   rd   r   r   r   r   r   r   r  r  r   r$  r&  r*  r-  r0  r4  r   r<  rQ  rX  r^  rc  re  r[   rr  rs  r   r  r%   r+   r,   <module>r     s   #   	  
   $      
 
 
   ..5.1Y (y (7y 7
   "#!	B	B
B B 	B
 "B 
BJ68v!d@F>.Sl.<
%"B"
J.(&,
" "#~/	7~/
~/ ~/ $	~/
 
~/B869ryx	1r+   