
    ϑiH                      % 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Jr  S SKJr  S SK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  S SKrS S	KJ r J!r!  S S
K"J#r#  S SK$J%r%  S SK&J'r'J(r(  S SK)J*r*J+r+J,r,J-r-J.r.  S SK/J0r0  S SK1J2r2  S SK3J4r4  S SK5J6r6  S SK7J8r8  SSK9J:r:  SSK;J<r<  SSK=J>r>J?r?J@r@JArAJBrB  SSKCJDrDJErEJFrF  SSKGJHrHJIrI  SSKJJKrKJLrLJMrMJNrNJOrO  \(       a(  S SKJPrP  S SKQJRrR  S SKSJTrT   " S S\5      rU " S S \5      rV\" S!\4S"9rW\" S#5      rX\" S$5      rY\S%   rZS&\[S''   \SJS( j5       r\S) r]SKS* jr^ " S+ S,\5      r_ " S- S.\5      r`\   SL           SMS/ jj5       ra\   SL           SNS0 jj5       ra\    SO           SPS1 jj5       ra    SQS2 jra " S3 S45      rbSRS5 jrcSSS6 jrdS7 reS8 rfSTS9 jrgS: rh\R                  " 5       qj/ qk " S; S<5      rlS= rmS> rnS? ro " S@ SA\5      rp\0SUSB j5       rqSVSC jrrSWSD jrs\q\% SX         SYSE jj5       5       rt\.      SZSF j5       ruSG rvSH rwSI rxg)[    )annotationsN)OrderedDict)Sequence)contextmanager)
ModuleType)TYPE_CHECKINGAnyCallableProtocol	TypedDictTypeVaroverload)LiteralNotRequired	ParamSpec	TypeAliasUnpack)coredygraph)BuildStrategy)switch_to_static_graph)Executorscope_guard)EagerParamBase	ParameterVariable_current_expected_placedygraph_only)wrap_decorator)use_pir_api)Layer)save_inference_model)EnvironmentVariableGuard   )logging_utilsadd_ignore_module)ASTStaticFunctionProgramTranslatorStaticFunctionSymbolicStaticFunctionunwrap_decorators)ENV_ENABLE_SOTBackendinfer_use_cinn_backend)PIR_INFER_MODEL_SUFFIXPirTranslatedLayer)INFER_MODEL_SUFFIXINFER_PARAMS_INFO_SUFFIXINFER_PARAMS_SUFFIXINFER_PROPERTY_SUFFIXTranslatedLayer)Tensor)NestedStructure)	InputSpecc                  f    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S'   S	\S
'   S\S'   S\S'   Srg)_SaveOptionsc   z#NotRequired[Sequence[Tensor | int]]output_specNotRequired[bool]	with_hookcombine_params
clip_extraskip_forwardzNotRequired[list[str]]input_names_after_pruneskip_prune_programseparate_parameters N__name__
__module____qualname____firstlineno____annotations____static_attributes__rF       N/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/jit/api.pyr;   r;   c   s2    88$$))%%''!77--..rN   r;   c                  *    \ rS rSr% S\S'   S\S'   Srg)_LoadOptionsm   zNotRequired[str]model_filenameparams_filenamerF   NrG   rF   rN   rO   rQ   rQ   m   s    (())rN   rQ   _LayerT)bound_RetT_InputTCINNr   Backendsc              #  h   #    [        [        U 5         S v   S S S 5        g ! , (       d  f       g = f7fN)r#   r-   )values    rO   sot_mode_guardr^   x   s     	!.%	8 
9	8	8s   2!	2
/2c                    SnU R                   Ul         X!l        [        R                  " U 5      (       d  Xl        U R
                  Ul        [        U S5      (       a  U R                  Ul        U$ )z
Copies some necessary attributes from original function into decorated function.

Args:
    original_func(callable): the original decorated function.
    decorated_obj(StaticFunction): the target decorated StaticFunction object.
	to_staticrI   )rH   _decorator_nameinspectismethod__wrapped____doc__hasattrrI   )original_funcdecorated_objdecorator_names      rO   copy_decorator_attrsrj   ~   sc     !N*33M$2!M**$1!)11M}l++#0#;#; rN   c                    [        U 5        g)a  
Adds modules that ignore transcription.
Builtin modules that have been ignored are collections, pdb, copy, inspect, re, numpy, logging, six

Args:
    modules (list[ModuleType]): Ignored modules that you want to add

Examples:
    .. code-block:: python

        >>> import scipy
        >>> import networkx

        >>> import paddle
        >>> from paddle.jit import ignore_module
        >>> modules = [
        ...     scipy,
        ...     networkx,
        ... ]
        >>> ignore_module(modules)

Nr&   )moduless    rO   ignore_modulerm      s    . grN   c                  *    \ rS rSr% S\S'   S\S'   Srg)_ToStaticOptions   r>   property
full_graphrF   NrG   rF   rN   rO   ro   ro      s    !!rN   ro   c                  D    \ rS rSr\SS j5       r\    SS j5       rSrg)_ToStaticDecorator   c                    g r\   rF   selffunctions     rO   __call___ToStaticDecorator.__call__   s    69rN   c                    g r\   rF   rw   s     rO   rz   r{      s     *-rN   rF   N)ry   rU   returnrU   )ry   Callable[_InputT, _RetT]r}   StaticFunction[_InputT, _RetT])rH   rI   rJ   rK   r   rz   rM   rF   rN   rO   rt   rt      s2    9 9-0-	'- -rN   rt   c                    g r\   rF   ry   
input_specbuild_strategybackendkwargss        rO   r`   r`      s     rN   c                    g r\   rF   r   s        rO   r`   r`      s     &)rN   c                    g r\   rF   r   s        rO   r`   r`      s     rN   c                  ^^^^^ UR                  SS5      mUR                  SS5      mT=(       d
    [        5       m[        T[        5      (       d!  [        S[	        T5      R
                   35      e[        R                  " T5      m[        TT5      (       a  [        R                  mO&TR                  5       (       a  O[        R                  mUUUUU4S jnU b  [        U [        5      (       a  [        U R                  [        5      (       a0  U R                  R
                  n[         R"                  " SU S35        U R                  U R$                  S	'   U" U R                  5      U l        U $ U" U 5      $ U$ )
aj	  
Converts dynamic graph APIs into static graph function APIs. Decorator
@to_static handles the Program and Executor of static graph mode and returns
the result as dynamic graph Tensor(s). Users could use the returned dynamic
graph Tensor(s) to do dynamic graph training, inference, or other operations.
If the decorated function calls other dynamic graph function, the called one
will be converted into static graph function as well.

Args:
    function (callable): Callable dynamic graph function. If it used as a
        decorator, the decorated function will be parsed as this parameter.
    input_spec (list[InputSpec]|tuple[InputSpec]): list/tuple of InputSpec to
        specific the shape/dtype/name information of each input Tensor.
    build_strategy (BuildStrategy|None): This argument is used to compile the
        converted program with the specified options, such as operators' fusion
        in the computational graph and memory optimization during the execution
        of the computational graph. For more information about :attr:`build_strategy`,
        please refer to :ref:`paddle.static.BuildStrategy <cn_api_paddle_static_BuildStrategy>`.
        The default is ``None``.
    backend(str, Optional): Specifies compilation backend, which can be ``"CINN"`` or
        ``None``. When backend is ``"CINN"``, CINN compiler will be used to speed up
        training and inference. default value is ``"CINN"``.
    kwargs: Support keys including :attr:`property` and :attr:`full_graph`.

      - property (bool): If True, the function will be treated as a property
        function. The default is False.
      - full_graph (bool): If True, the function will be converted into a
        full static graph. The default is False.

Returns:
    Tensor(s): containing the numerical result.

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP('`paddle.jit.to_static` can not run in xdoctest')
        >>> import paddle
        >>> from paddle.jit import to_static

        >>> @to_static
        >>> def func(x):
        ...     if paddle.mean(x) < 0:
        ...         x_v = x - 1
        ...     else:
        ...         x_v = x + 1
        ...     return x_v
        ...
        >>> x = paddle.ones([1, 2], dtype='float32')
        >>> x_v = func(x)
        >>> print(x_v)
        Tensor(shape=[1, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
        [[2., 2.]])

rq   Frr   NzSRequired type(build_strategy) shall be `paddle.static.BuildStrategy`, but received c                  > Tc  [         R                  " 5       nU(       + m[        R                  S:  a  T(       d  [        R
                  " S5        SmT(       a  [        O[        n[        U 5      u  p0[        U U" U TTT	TS9S9nU$ )zX
Decorates a python function into a ASTStaticFunction or SymbolicStaticFunction object.
)      zTfull_graph=False is not supported in Python 3.15+. Set full_graph=True automaticallyT)ry   r   r   rq   r   )rg   rh   )
r-   getsysversion_infowarningswarnr(   r+   r,   rj   )
python_funcflagStaticClass_static_layerr   r   rr   r   rq   s
        rO   	decoratedto_static.<locals>.decorated&  s     !%%'D!Jw&zMMf J ",1G 	
 +;7 ,%%$%-!	
 rN   `z_.forward` has already been decorated somewhere. It will be redecorated to replace previous one.forward)r   r   
isinstance	TypeErrortyperH   r.   from_argr/   rY   is_pccPHIr!   r   r*   	__class__r%   r   _original_funcs)	ry   r   r   r   r   r   
class_namerr   rq   s	    ```   @@rO   r`   r`      sT   z zz*e,HL$/J#6}Nnm44abfgubvbb  bA  B
 	
 w'Gg~66,,			++# #L h&&(**N;;%//88
""
|  $C  D 3;2B2BH$$Y/()9)9:HOX&& rN   c                      \ rS rSrS r\S 5       r\R                  S 5       r\S 5       r\R                  S 5       r\S 5       r	\	R                  S 5       r	\S	 5       r
\
R                  S
 5       r
Srg)_SaveLoadConfigi]  c                    S U l         S U l        S U l        SU l        SU l        SU l        SU l        SU l        SU l        S U l	        SU l
        SU l        g )NFT)_output_spec_model_filename_params_filename_separate_params_keep_name_table_export_for_deployment_program_onlyr?   r@   rC   rD   rE   rx   s    rO   __init___SaveLoadConfig.__init__^  sm     # $ % % '+# # $ (,$ #( $) rN   c                    U R                   $ r\   )r   r   s    rO   r=   _SaveLoadConfig.output_spec~  s       rN   c                z    Uc  g [        U[        5      (       d  [        S[        [        5       S35      eXl        g )NzFThe config `output_spec` should be 'list', but received input type is .)	r   listr   r   inputr   eagerr7   r   )rx   specvars      rO   r=   r     sA    <$%%XY]^cYdXeefg  !rN   c                    U R                   $ r\   )r   r   s    rO   rS   _SaveLoadConfig.model_filename  s    ###rN   c                    Uc  g [        U[        5      (       d  [        S[        U5       S35      e[	        U5      S:X  a  [        S5      eXl        g )NzHThe config `model_filename` should be str, but received input's type is r   r   z,The config `model_filename` is empty string.)r   strr   r   len
ValueErrorr   rx   filenames     rO   rS   r     sZ    (C((Z[_`h[iZjjkl  x=AKLL'rN   c                    U R                   $ r\   )r   r   s    rO   rT   _SaveLoadConfig.params_filename      $$$rN   c                    Uc  g [        U[        5      (       d  [        S[        U5       S35      e[	        U5      S:X  a  [        S5      eXl        g )NzIThe config `params_filename` should be str, but received input's type is r   r   z-The config `params_filename` is empty string.)r   r   r   r   r   r   r   r   s     rO   rT   r     sZ    (C(([\`ai\j[kklm  x=ALMM (rN   c                    U R                   $ r\   )r   r   s    rO   keep_name_table_SaveLoadConfig.keep_name_table  r   rN   c                r    Uc  g [        U[        5      (       d  [        S[        U5       S35      eXl        g )NzPThe config `keep_name_table` should be bool value, but received input's type is r   )r   boolr   r   r   )rx   r]   s     rO   r   r     sA    =%&&bcghmcnboopq  !&rN   )r   r   r   r   r   r   r   r@   rC   rE   rD   r?   N)rH   rI   rJ   rK   r   rq   r=   setterrS   rT   r   rM   rF   rN   rO   r   r   ]  s    )@ ! ! ! ! $ $ 	( 	( % % 	) 	) % % & &rN   r   c                   / SQnU  H  nX!;  d  M
  [        SU S35      e   [        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 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@   rA   rB   rC   rD   rE   The additional config (z() of `paddle.jit.save` is not supported.r=   r?   Fr@   rA   TrB   rC   rD   rE   )r   r   r   r=   r?   r@   rA   rB   rC   rD   rE   configssupported_configskeyinner_configs       rO   _parse_save_configsr     s    	 ')#.VW   #$L&{{=$?L$[[e<L")++.>"FL%kk,=L 'NE BL+2;;!4,L( '.kk2F&NL#'.{{3H%'PL$rN   c                    SS/nU  H  nX!;  d  M
  [        SU S35      e   [        5       nU R                  SS 5      Ul        U R                  SS 5      Ul        U$ )NrS   rT   r   z() of `paddle.jit.load` is not supported.)r   r   r   rS   rT   r   s       rO   _parse_load_configr     sr    )+<= ')#.VW   #$L")++.>"EL#*;;/@$#GL rN   c                   SnSnUbO  U Vs/ s HB  n[        U[        R                  R                  5      (       d  M.  UR                  U;   d  M@  UPMD     nn[        R
                  R                  U 5       Vs/ s H6  n[        U[        [        R                  R                  45      (       d  M4  UPM8     nn[        R
                  R                  U 5       Vs/ s H@  n[        U[        [        R                  R                  45      (       d  M4  UR                  PMB     nnUc  Xx4$ U V	s/ s H0  n	[        U	[        R                  R                  5      (       d  M.  U	PM2     nn	/ n
/ n[        U5      [        U5      :X  ak  Un
UnU H^  n	U	R                  c  [        R                  " X9-  5        M*  U	R                  U;  a$  [        R                  " XIR                  -  5        M^  M`     X4$ U Hp  n	U	R                  c  [        X9-  5      eU	R                  U;  a  [        XIR                  -  5      eU
R                  U	5        UR                  U	R                  5        Mr     X4$ s  snf s  snf s  snf s  sn	f )NzThe %s's name is None. When using jit.save, please set InputSpec's name in to_static(input_spec=[]) and jit.save(input_spec=[]) and make sure they are consistent.zThe tensor `%s` does not exists. Please make sure the name of InputSpec or example Tensor in input_spec is the same as the name of InputSpec in `to_static` decorated on the Layer.forward method.)r   paddlestaticr9   nameutilsflattenr   pirValuer   r   r   r   append)inputsr   rC   name_none_errorname_no_exists_errorxr   
input_varsinput_var_namesr   result_var_listresult_name_lists               rO   _get_input_var_and_namesr     sF   	- 	=  *  
!V]]445  11  	 
 <<''//CcHfjj&6&678 	/   <<''//CcHfjj&6&678 	/   **
 #
"$ 7 78 " 	 

 O
:#o..$*Dyy o45/12YY>? ( ,, Dyy  !788/1 !5		!ABB&&t, ''		2  ,,o


s4   -I$I$I$83I)/I)3I.I.+-I3I3c                    [        U [        5      (       a  g[        U [        5      (       a'  [        U [        5      (       d  [	        S U  5       5      $ g)NTc              3  8   #    U  H  n[        U5      v   M     g 7fr\   )_contains_dict).0is     rO   	<genexpr>!_contains_dict.<locals>.<genexpr>A  s     5f>!$$fs   F)r   dictr   r   any)outputs    rO   r   r   =  s?    &$&(##Jvs,C,C5f555rN   c                   SnSnU(       a  U(       a  [        S5      e/ n[        U 5      (       a  [        R                  " S5        [	        5       (       Ga  SSKJn  [        R                  R                  U 5       HL  n[        U[        R                  R                  5      (       d  M.  Xv" U5      ;  d  M;  UR                  U5        MN     UGbe  [        U5      n[        U5      U:X  a  U H  n[        U[        R                  R                  [        45      (       d$  [        R                  " XGR                   -  5        MV  Xv" U5      ;  d  Mc  [        R                  " X7R                   -  5        M     U$ U" U5      n	/ n
U H  n[        U[        R                  R                  5      (       a/  Xy;  a  [#        X7R                   -  5      eU
R                  U5        M[  [        U[        5      (       a'  Xx:  a  [#        SUU5      eU
R                  XW   5        M  [#        XGR                   -  5      e   U
$  U$ [%        5       n[        R                  R                  U 5       H(  n[        U[&        5      (       d  M  X{UR                   '   M*     Uc  [)        UR+                  5       5      nU$ Ubp  [        U5      [        U5      :X  aX  [)        UR+                  5       5      nU H7  nUR                   U;  d  M  [        R                  " X7R                   -  5        M9     U$ U HG  nUR                   U;  a  [#        X7R                   -  5      eUR                  XR                      5        MI     U$ )NzThe tensor `%s` does not exists. Please make sure the name of example Tensor in configs.output_spec is the output tensor of Layer.forward method.ztensor `%s` is not support in pir mode, because pir value has no name sometimes, especially as output,so we can't check tensor's name with output var name, pleasechange as pir.value(to_static layer's output)or int(the position of to_static layer's output)z`Currently not support specify output_spec while founding pre/post hooks in your outermost layer.zwFound 'dict' in given outputs, the values will be returned in a sequence sorted in lexicographical order by their keys.r   )ValueSetz1position %d should smaller than output's size % d)RuntimeErrorr   r   r   r    paddle.autograd.backward_utilsr   r   r   r   r   r   r   r   r   intr   r   r   r   r   values)outputsr=   r?   r   output_spec_is_not_value_errorresult_listr   r   output_size
result_setpart_result_listoutput_vars_dicts               rO   _get_output_varsr   E  s
   	  	; # yn
 	
 Kg F	
 }};<<''0C#vzz//00SA 6 ""3'	 1 "k*K;;.&C%cFJJ,<,<c+BCC &Dxx&OPh{&;;$MM*>*IJ 'h [ &k2
#% &C!#vzz'7'7880",-AHH-L"MM,33C8#C---", S # +#  -33K4DE ):XXE # '* ('C #n ) '=<<''0C#**-0* 1 /6689K  $[)9S>
 *
 /6689K"88#33MM"6"AB #  #88#33$%9HH%DEE&&'7'AB	 # rN   c                   [        5       (       a  [        nO[        n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(       d  U(       d  [        SU  S35      eU(       a  [        R                  R                  U 5      n[        R                  R                  U 5      nUR                  b  [        R                  " S5        Xb-   Ul
        UR                  b  [        R                  " S5        U[        -   Ul        Xq4$ U nXq4$ )NzThe z.pdmodel(json) 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`` (zz) to load model not exists. Please make sure that *.pdmodel(json) exists or don't using ``skip_forward=True`` to jit.save.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    r0   r2   ospathexistsisdirr   basenamedirnamerS   r   r   rT   r4   )r  configmodel_suffixprefix_format_pathprefix_format_existdirectory_format_existfile_prefix
model_paths           rO   _build_load_path_and_configr    s3    }}-),''..);<WW]]4054&+D6 2% %
 	

 !)?TF #= =
 	
 ''**40K.J$$0'
 %0$>F!%%1'
 &13F%FF"
  JrN   c                  $    \ rS rSrSrS rS rSrg)HookRemoveHelperi  z3A HookRemoveHelper that can be used to remove hook.c                    Xl         g r\   _hook)rx   hooks     rO   r   HookRemoveHelper.__init__  s    
rN   c                .    [        U R                  5        g r\   )_remove_save_pre_hookr  r   s    rO   removeHookRemoveHelper.remove  s    djj)rN   r  N)rH   rI   rJ   rK   re   r   r  rM   rF   rN   rO   r  r    s    =*rN   r  c                    [         R                  5         U [        ;  a  [        R                  U 5        [         R	                  5         [        U 5      $ )a  
Register a save pre-hook for `paddle.jit.save`.
This hook will be executed before `save` function has been invoked.

hook(layer, input_spec, configs) -> None
- layer (Layer|function): This argument is corresponding to `layer` in `paddle.jit.save`.
- input_spec (list or tuple[InputSpec|Tensor|Python built-in variable]): This argument is corresponding to `input_spec` in `paddle.jit.save`.
- configs (dict): This argument is corresponding to `configs` in `paddle.jit.save`.

Args:
    hook(function): a function registered as a save pre-hook

Returns:
    HookRemoveHelper: a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()`.

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP('`paddle.jit.api.to_static` can not run in xdoctest')
        >>> import numpy as np
        >>> import paddle

        >>> IMAGE_SIZE = 256
        >>> CLASS_NUM = 10

        >>> class LinearNet(paddle.nn.Layer):
        ...     def __init__(self):
        ...         super().__init__()
        ...         self._linear = paddle.nn.Linear(IMAGE_SIZE, CLASS_NUM)
        ...
        ...     def forward(self, x):
        ...         return self._linear(x)
        ...
        >>> saving_count = 0
        >>> def save_pre_hook(layer, input_spec, configs):
        ...     global saving_count
        ...     saving_count += 1
        ...
        >>> remove_handler = paddle.jit.api._register_save_pre_hook(save_pre_hook)

        >>> layer = LinearNet()
        >>> paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])])
        >>> print(saving_count)
        1

        >>> remove_handler.remove()
        >>> paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])])
        >>> print(saving_count)
        1
)_save_pre_hooks_lockacquire_save_pre_hooksr   releaser  r  s    rO   _register_save_pre_hookr    s>    j   "?"t$  "D!!rN   c                 |    [         R                  5         [        R                  5         [         R	                  5         g r\   )r  r  r  clearr  rF   rN   rO   _clear_save_pre_hooksr"  "  s(       "  "rN   c                    [         R                  5         U [        ;   a  [        R                  U 5        [         R	                  5         g r\   )r  r  r  r  r  r  s    rO   r  r  *  s2       "t$  "rN   c                  6    \ rS rSr S         SS jjrSrg)_SaveFunctioni3  c                    g r\   rF   )rx   layerr  r   r   s        rO   rz   _SaveFunction.__call__4  s     rN   rF   N).
r'  zLayer | Callable[..., Any]r  r   r   z,Sequence[InputSpec | Tensor | object] | Noner   zUnpack[_SaveOptions]r}   None)rH   rI   rJ   rK   rz   rM   rF   rN   rO   r%  r%  3  sD    
 DG	)  A	
 ( 
 rN   r%  c                0   ^   S         SU 4S jjjnU$ )Nc                F   > [          H  nU" XU5        M     T" XU40 UD6  g r\   )r  )r'  r  r   r   r  funcs        rO   wrapper$_run_save_pre_hooks.<locals>.wrapper?  s(     $DG, $U*00rN   r\   r)  rF   )r-  r.  s   ` rO   _run_save_pre_hooksr0  =  sJ    
 DH	1)	1	1 A	1 (		1
 
	1 	1 NrN   c                   S n[        U S5       n[        R                  R                  R	                  5       nU H  nUS   US   pvU" XGU5        M     UR                  UR                  5       5        SSS5        g! , (       d  f       g= f)z{class property serialization.

Args:
    filename (str): *.meta
    property_vals (list[tuple[Any, str]]): class property.
c                N   [        U[        5      (       a  U R                  X5        g [        U[        5      (       a  U R	                  X5        g [        U[
        5      (       a  U R                  X5        g [        U[        [        45      (       a  [        US   [        5      (       a  U R                  X5        g [        US   [        5      (       a  U R                  X5        g [        US   [
        5      (       a  U R                  X5        g g [        S[        U5       35      e)Nr   zNote support val type: )r   float	set_floatr   set_intr   
set_stringtupler   
set_floatsset_intsset_stringsr   r   )metar   vals      rO   set_property$_save_property.<locals>.set_propertyU  s    c5!!NN3$S!!LL"S!!OOC%eT]++#a&%(()CFC((c'CFC((  * ) 6tCykBCCrN   wbr   r$   N)openr   	frameworkr   Propertywriteserialize_to_string)r   property_valsr=  fr;  itemr<  r   s           rO   _save_propertyrH  M  sv    D" 
h	$$--/!DAwQC( " 	
((*+ 
		s   A#A<<
B
c                "   U R                   n[        R                  " U5       VVs/ s HZ  u  p#[        R                  " U5      (       d8  [        R                  " U5      (       d  [        R
                  " U5      (       d  MX  UPM\     snn$ s  snnf r\   )r   rb   
getmembers
isfunctionrc   ismethoddescriptor)r'  clsmember_namemembers       rO   _get_function_names_from_layerrP  n  sp    
//C $+#5#5c#:#:Kv&&''))&1 	#:  s   ABBc                   [        5       n[        R                  " 5       =(       a    [        R                  " 5       nUR                  (       d  [        S5      e[        U [        [        45      (       d3  [        R                  " U 5      (       d  [        S[        U 5       S35      e[        R                  " U 5      (       d  [        U [        5      (       a  [        R                  " S5        [        U [        R                   5      (       a  U R"                  nOU n[$        R&                  R)                  U5      nUS:X  a  [+        S5      e[$        R&                  R-                  U5      nU(       a:  [$        R&                  R/                  U5      (       d  [$        R0                  " U5        Sn	UGb  [        U [        5      (       aS  [3        U5       HD  n
[5        XjS5      n[        U[        5      (       d  M&  SU
:w  d  M.  [+        S	[        U5       S35      e   [        U[6        [8        45      (       d  [        S
[        U5       S35      e/ n	[        R:                  R=                  U5       H  n[        U[        R>                  R@                  5      (       a  U	RC                  U5        M?  [        U[        RD                  RF                  [H        [        RJ                  RL                  45      (       a:  U	RC                  [        R>                  R@                  RO                  U5      5        M  U	RC                  U5        M     [Q        U5      nURR                  nURT                  nU(       a  SUl+        [        RX                  " 5       n0 n[        U [        5      (       aM  [7        [[        [3        U5      5      5      n[]        U5      nUR^                  (       d  UR`                  (       a  SnOU /n0 n/ n/ nSnU GH(  n[        U [        5      (       a  [c        [5        UUS5      5      n[        U[        5      (       aZ  URd                  (       a6  U" 5       nURC                  UU Rf                  Rh                  S-   U-   45        M  URk                  U	UUS9nGO8SU:X  aa  URl                  (       a  M  U	(       a  [        R:                  Ro                  X)5      n	[q        URr                  U	SSS9nURk                  XS9nSn	OGM  [        U[        5      (       aI  [c        U5      nURd                  (       a  U" 5       nURC                  UU45        GMV  URk                  XS9nOp[c        U5      nU	(       a  [        R:                  Ro                  X)5      n	[q        UU	SSS9nURt                  nURv                  c  [        R                  " SU  S35        Sn[        U[        5      (       a  URy                  5       nO@[        U[        5      (       a+  URv                  (       a  URv                  Ry                  5       nU(       a<  0 n0 nUR{                  5        H$  u  nnUUUR|                  '   UUUR|                  '   M&     [~        R                  " 5          [        5       (       a  [        UR                  6  H~  u  nnUR                  (       d  M  UR                  UR|                  5      R                  5       n WUR|                     R                  5       R                  5       n!U R                  U!5        M     GOoUR                   GH^  n"U"R                  [        R                  R                  R                  :X  aK  U"R                  5       R                  5       n#UR                  U"R|                  5      n$U$R                  U#5        OeUR                  U"R|                  5      R                  5       n WU"R|                     R                  5       R                  5       n!U R                  U!5        U"R|                  U;  d  M  0 n%U"R|                  W;   a  UU"R|                     U%S'   U"R                  U%S'   [        U"[        5      (       a  U"R                  U%S'   U%UU"R|                  '   GMa     SSS5        [        UR                  U	UR                  5      u  n&n'[        UR                  UR                  U5      n(Un)SU:X  d  [        U [        5      (       d  U[        -   n*U[        -   n+Un,O&US-   U-   [        -   n*US-   U-   [        -   n+US-   U-   n,[$        R&                  R                  U)U,5      n-[        U5         [        5       (       Ga*  [        RJ                  R                  5       n.UR                  R                  U.5      n// n0U& H  n1[        U15      [        R>                  R@                  L a~  U1R|                  n2U/R                  5       R                   HR  n3U3R}                  5       S:X  d  M  U3R                  5       S   U2:X  d  M2  U0RC                  U3R                  S5      5        MT     M  U0RC                  U.R                  U15      5        M     U( V1s/ s H  n1U.R                  U15      PM     n4n1OWU' V2s/ s H,  n2UR                  R                  5       R                  U25      PM.     n&n2UR                  R                  5       n/U&n0U(n4[        U-U0U4[        [        5       5      U/UR                  UR                  UR                  S9  SSS5        U(       d  GM^  [        5       (       aa  UR                  R                  5        H%  nUR                  (       d  M  UUUR|                  '   M'     URC                  UR                  5        GM  UR                  R                  5       n5U5R                  U'U(5      n5U5R                   H  n6UR                  U6R                  5        M      GM+     U(       GaL  []        UR{                  5       S S9n/ n7U H  u  n2nU7RC                  U5        M     U[        -   n+[        U5         [        5       (       a2  [        R>                  R                  [        [        5       5      W)U7U+S9  Of[        R>                  R                  [        [        5       5      W)[7        [        [        R                  R                  R                  U75      5      U+S9  SSS5        [$        R&                  R                  [$        R&                  R                  W)5      U[        -   5      n8[        U8U5        Sn9Ub  UR                  R                  5        Hu  n[        5       (       aP  UR                  5       R                  S5      =(       a#    UR                  5       R                  5       S   SL n:U9U:-  n9Mb  U9[        U[        5      -  n9Mw     [        U [        5      (       d  U9(       aO  U(       aH  [        U5         U[        -   n;[        U;S5       n<[        R                  " UU<SS9  SSS5        SSS5        UR                  UR                  5       5        g! , (       d  f       GN = fs  sn1f s  sn2f ! , (       d  f       GN{= f! , (       d  f       GN= f! , (       d  f       Nv= f! , (       d  f       N= f) a  
Saves input Layer or function as ``paddle.jit.TranslatedLayer``
format model, which can be used for inference or fine-tuning after loading.

It will save the translated program and all related persistable
variables of input Layer to given ``path`` .

``path`` is the prefix of saved objects, and the saved translated program file
suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` ,
and here also saved some additional variable description information to a file,
its suffix is ``.pdiparams.info``, these additional information is used in fine-tuning.

The saved model can be loaded by follow APIs:
  - ``paddle.jit.load``
  - ``paddle.static.load_inference_model``
  - Other C++ inference APIs

.. note::
    When using ``paddle.jit.save`` to save a function, parameters will not be saved. If you have to
    save the parameter, please pass the Layer containing function and parameter to ``paddle.jit.save``.

Args:
    layer (Layer|function): The Layer or function to be saved.
    path (str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``.
    input_spec (list or tuple[InputSpec|Tensor|Python built-in variable], optional): Describes the input of the saved model's forward
        method, which can be described by InputSpec or example Tensor. Moreover, we support to specify non-tensor type argument,
        such as int, float, string, or list/dict of them.If None, all input variables of
        the original Layer's forward method would be the inputs of the saved model. Default None.
    **configs (dict, optional): Other save 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) output_spec (list[Tensor|Value|int]): Selects the output targets of the saved model,
        By default, all return variables of original Layer's forward method are kept as the
        output of the saved model. If the provided ``output_spec`` list is not all output variables,
        the saved model will be pruned according to the given ``output_spec`` list.
        in pir mode, Tensor is not supported, because value has no name in most cases,
        which can't be used to judge which tensor corresponds to which value; the value can't be found
        if the saved program is not the same as the program that includes output_spec, so we need to
        use the position of the output.

Returns:
    None

Examples:
    .. code-block:: python

        >>> # doctest: +SKIP('`paddle.jit.to_static` can not run in xdoctest')
        >>> # example 1: save layer
        >>> import numpy as np
        >>> import paddle
        >>> import paddle.nn as nn
        >>> import paddle.optimizer as opt

        >>> BATCH_SIZE = 16
        >>> BATCH_NUM = 4
        >>> EPOCH_NUM = 4

        >>> IMAGE_SIZE = 784
        >>> CLASS_NUM = 10

        >>> # define a random dataset
        >>> class RandomDataset(paddle.io.Dataset): # type: ignore[type-arg]
        ...     def __init__(self, num_samples):
        ...         self.num_samples = num_samples
        ...
        ...     def __getitem__(self, idx):
        ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
        ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
        ...         return image, label
        ...
        ...     def __len__(self):
        ...         return self.num_samples

        >>> class LinearNet(nn.Layer):
        ...     def __init__(self):
        ...         super().__init__()
        ...         self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
        ...
        ...     @paddle.jit.to_static
        ...     def forward(self, x):
        ...         return self._linear(x)

        >>> def train(layer, loader, loss_fn, opt):
        ...     for epoch_id in range(EPOCH_NUM):
        ...         for batch_id, (image, label) in enumerate(loader()):
        ...             out = layer(image)
        ...             loss = loss_fn(out, label)
        ...             loss.backward()
        ...             opt.step()
        ...             opt.clear_grad()
        ...             print("Epoch {} batch {}: loss = {}".format(
        ...                 epoch_id, batch_id, np.mean(loss.numpy())))

        >>> # 1. train & save model.

        >>> # create network
        >>> layer = LinearNet()
        >>> loss_fn = nn.CrossEntropyLoss()
        >>> adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())

        >>> # create data loader
        >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
        >>> loader = paddle.io.DataLoader(dataset,
        ...     batch_size=BATCH_SIZE,
        ...     shuffle=True,
        ...     drop_last=True,
        ...     num_workers=2
        ... )

        >>> # train
        >>> train(layer, loader, loss_fn, adam)

        >>> # save
        >>> path = "example_model/linear"
        >>> paddle.jit.save(layer, path)

        >>> # example 2: save function
        >>> import paddle
        >>> from paddle.static import InputSpec


        >>> def save_function():
        ...     @paddle.jit.to_static
        ...     def fun(inputs):
        ...         return paddle.tanh(inputs)
        ...
        ...     path = 'test_jit_save_load_function_1/func'
        ...     inps = paddle.rand([3, 6])
        ...     origin = fun(inps)
        ...
        ...     paddle.jit.save(fun, path)
        ...     load_func = paddle.jit.load(path)
        ...
        ...     load_result = load_func(inps)
        ...     print((load_result - origin).abs().max() < 1e-10)

        >>> save_function()
zUThe paddle.jit.save doesn't work when setting 'paddle.jit.enable_to_static' to False.zYThe input of paddle.jit.save should be 'Layer' or 'Function', but received input type is r   a  What you save is a function, and `jit.save` will generate the name of the model file according to `path` you specify. When loading these files with `jit.load`, you get a `TranslatedLayer` whose inference result is the same as the inference result of the function you saved. zThe input path MUST be format of dirname/file_prefix [dirname\file_prefix in Windows system], but received file_prefix is empty string.Nr   zIf there are static functions other than 'forward' that need to be saved, the input 'input_spec' should be None, but received the type of 'input_spec' is zIThe input input_spec should be 'list', but received input_spec's type is T)r?   is_prim_infer)r   rr   r   )rS  zw`jit.save` will only save the `Program`, not the parameters. If you have to save the parameters, please make sure that zW is a member function of `paddle.nn.Layer` and the saved parameters are in `state_dict`structured_namestop_gradient	trainablez
pd_op.datar   r   )path_prefix	feed_vars
fetch_varsexecutorprogramrA   rD   rE   c                    U S   $ )Nr   rF   )rG  s    rO   <lambda>save.<locals>.<lambda>t  s    T!WrN   )r   )r  varsr   Fpersistabler?     )protocol)r)   r   _is_fwd_prim_enabled_is_bwd_prim_enabledenable_to_staticr   r   r!   r*   rb   rK  r   r   r   r   r   DataParallel_layersr   r  r  r   r  r  makedirsrP  getattrr   r7  r   r   r   r9   r   r   r7   r   r   r   from_tensorr   r?   r@   r   Scopesetsorted_forward_pre_hooks_forward_post_hooksget_ast_static_functionis_propertyr   rH   #concrete_program_specify_input_specrB   pack_sequence_asr`   r   concrete_programclass_instanceto_static_state_dictitemsr   r   guardr    zip
parametersr`  r   
get_tensorr]   _share_data_withVarDescVarTypeVOCABget_map_tensor	set_vocabrU  r   rV  r   r   rC   r   r   r=   r2   r4   joinr   	IrMappingmain_programcloneglobal_blockopsattrsresultlook_upr"   r   r   rA   rD   rE   	list_vars_prune_with_inputblocksupdater_  	save_varsfilterrA  io_utilsis_persistablenormpathr5   rH  get_defining_ophas_attrr   r3   r@  pickledumperaselocal_var_names)=r'  r  r   r   prog_translatorrS  inner_layerr  r  inner_input_specrN  static_funcr   r?   r@   scopeextra_var_info	functionscombine_varscombine_programrE  rt  	attr_funcimmediate_valstatic_forwardstatic_functiondygraph_state_dictstate_names_dictstate_var_dictrT  tensorr]   param_or_buffer_tensor
src_tensorparam_or_buffer
scr_tensortgt_varextra_info_dictr   r   output_varsr  rS   rT   rW  	file_path	value_mapclone_programclone_input_varsvr   opclone_output_varsclone_main_programblockordered_varsproperty_save_pathcontain_parameterr  extra_var_info_pathrF  s=                                                                rO   saver  {  s   h ()O--/OD4M4M4OM++c
 	

 	55.122g6H6H6O6Oghlmrhsgttuv
 	
 
		E	"	"j&G&G `	
 %,,--mm ''""4(Kb+
 	
 ggood#Grww~~g..
G eU##=kJ%kE{N;;![0$ u  vz  {E  vF  uG  GH  I   K *tUm44[\`ak\l[mmno  <<''
3C#v}}6677 '',djj''6::3C3CD  !''MM++77<
 !'', 4 "'*G !!I++N $JJLEN%;KHIJ	9%	))[-L-LI G	LOM	eU##1Y5K +~66**$/MM!(()!OO44s:YF   CC("+&3 D  ! i'''
 $'-||'D'D"($ "+''/# 	" #FF"+ G  ! $(  )^445i@**$/MM!((-)EF  CC( D  ! 6i@#'-||'D'D"($ #,/# 	# $3#C#C "119MM R  SX  RY  Yp  q
 "k5))!,!A!A!C	>22))..CCE # 
  "N(:(@(@(B$-< *+.sxx( )C ]]_}}%(*:*E*E%FMFE ,, -2YYuzz-B-M-M-O*&v{{399;FFH  +;;JG &G (8'B'BO&++t||/C/C/I/II%4%:%:%<%K%K%M
"'))O,@,@"A))*516+002$*, /
 +?+?+?@"UW'Z\ #
 /??
K&++>A*,*//3CC 01E1E F ,,=> ,99 (8 &o~FF / 9 9 ,K8 @O';';<? (C l '?##++'
#
O '$$g&9&99
 
 	!E5)A)A(+==N),??O%K(3.:=OONc!I-0CC  &+i7KGGLL[9	}}"JJ002	 0 = = C CI N#% #AAw&--"9"99 vv"/"<"<">"B"BB "	\ 9$&HHJv$6$$> 0 7 7		! E #C )//	0A0A!0DE $ DO$O;aY%6%6q%9;!$O!
 !0 / %11>>@DDTJ /   !1 = = C C E#- $/! %*,!"9";<%"--#*#=#=$+$?$?	7  L >}} ,88BBDC14SXX. E
  &&'7'D'DE%5%B%B%H%H%J"%7%I%I#[&" 066E ''

3 7} D l0028LM%ID#$ & &(;;}}''467&%,	 (  ''467&",,55DD( - ( 
  *  WW\\GGZ(+8M*M
 	)=9& ##00::<C}}'')22=A M++-335mDL  "^3!!ZY%??! = 	5%  $5>"&)A"A)40ANA: 1   
KK%%'(o _T %P)  D  t 10  s~   F&z9A+z4B2z9*z9Az9z/,z933z4&Az9:B({ {.{-{.
z,	/
z99
{	
{
{+	'{..
{<c                    [        U5      n[        X5      u  p2[        5       (       a  [        R                  " X25      $ [
        R                  " X25      $ )a#  
:api_attr: imperative

Load model saved by ``paddle.jit.save`` or ``paddle.static.save_inference_model`` or
paddle 1.x API ``paddle.static.save_inference_model`` as ``paddle.jit.TranslatedLayer``,
then performing inference or fine-tune training.

.. note::
    If you load model saved by ``paddle.static.save_inference_model`` ,
    there will be the following limitations when using it in fine-tuning:
    1. Imperative mode do not support DenseTensor. All original model's feed targets or parameters that depend on LoD are temporarily unavailable.
    2. All saved model's feed targets need to be passed into TranslatedLayer's forward function.
    3. The variable's ``stop_gradient`` information is lost and can not be recovered.
    4. The parameter's ``trainable`` information is lost and can not be recovered.

Args:
    path (str): The path prefix to load model. The format is ``dirname/file_prefix`` or ``file_prefix`` .
    **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.


Returns:
    TranslatedLayer: A Layer object can run saved translated model.

Examples:
    1. Load model saved by ``paddle.jit.save`` then performing inference and fine-tune training.

        .. code-block:: python
            :name: code-example1

            >>> # doctest: +SKIP('`paddle.jit.to_static` can not run in xdoctest')
            >>> import numpy as np
            >>> import paddle
            >>> import paddle.nn as nn
            >>> import paddle.optimizer as opt

            >>> BATCH_SIZE = 16
            >>> BATCH_NUM = 4
            >>> EPOCH_NUM = 4

            >>> IMAGE_SIZE = 784
            >>> CLASS_NUM = 10

            >>> # define a random dataset
            >>> class RandomDataset(paddle.io.Dataset): # type: ignore[type-arg]
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
            ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples

            >>> class LinearNet(nn.Layer):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
            ...
            ...     @paddle.jit.to_static
            ...     def forward(self, x):
            ...         return self._linear(x)
            ...
            >>> def train(layer, loader, loss_fn, opt):
            ...     for epoch_id in range(EPOCH_NUM):
            ...         for batch_id, (image, label) in enumerate(loader()):
            ...             out = layer(image)
            ...             loss = loss_fn(out, label)
            ...             loss.backward()
            ...             opt.step()
            ...             opt.clear_grad()
            ...             print("Epoch {} batch {}: loss = {}".format(
            ...                 epoch_id, batch_id, np.mean(loss.numpy())))

            >>> # 1. train & save model.

            >>> # create network
            >>> layer = LinearNet()
            >>> loss_fn = nn.CrossEntropyLoss()
            >>> adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())

            >>> # create data loader
            >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
            >>> loader = paddle.io.DataLoader(
            ...     dataset,
            ...     batch_size=BATCH_SIZE,
            ...     shuffle=True,
            ...     drop_last=True,
            ...     num_workers=2
            ... )

            >>> # train
            >>> train(layer, loader, loss_fn, adam)

            >>> # save
            >>> path = "example_model/linear"
            >>> paddle.jit.save(layer, path)

            >>> # 2. load model

            >>> # load
            >>> loaded_layer = paddle.jit.load(path)

            >>> # inference
            >>> loaded_layer.eval()
            >>> x = paddle.randn([1, IMAGE_SIZE], 'float32')
            >>> pred = loaded_layer(x)

            >>> # fine-tune
            >>> loaded_layer.train()
            >>> adam = opt.Adam(learning_rate=0.001, parameters=loaded_layer.parameters())
            >>> train(loaded_layer, loader, loss_fn, adam)


    2. Load model saved by ``paddle.static.save_inference_model`` then performing and fine-tune training.

        .. code-block:: python
            :name: code-example2

            >>> # doctest: +SOLO('can not use multiprocessing testing `DataLoader`')
            >>> import numpy as np
            >>> import paddle
            >>> import paddle.static as static
            >>> import paddle.nn as nn
            >>> import paddle.optimizer as opt
            >>> import paddle.nn.functional as F

            >>> BATCH_SIZE = 16
            >>> BATCH_NUM = 4
            >>> EPOCH_NUM = 4

            >>> IMAGE_SIZE = 784
            >>> CLASS_NUM = 10

            >>> # define a random dataset
            >>> class RandomDataset(paddle.io.Dataset): # type: ignore[type-arg]
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([IMAGE_SIZE]).astype('float32')
            ...         label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples

            >>> paddle.enable_static()

            >>> image = static.data(name='image', shape=[None, 784], dtype='float32')
            >>> label = static.data(name='label', shape=[None, 1], dtype='int64')
            >>> pred = static.nn.fc(x=image, size=10, activation='softmax')
            >>> loss = F.cross_entropy(input=pred, label=label)
            >>> avg_loss = paddle.mean(loss)

            >>> optimizer = paddle.optimizer.SGD(learning_rate=0.001)
            >>> optimizer.minimize(avg_loss)

            >>> place = paddle.CPUPlace()
            >>> exe = static.Executor(place)
            >>> exe.run(static.default_startup_program())

            >>> # create data loader
            >>> dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
            >>> loader = paddle.io.DataLoader(dataset,
            ...     feed_list=[image, label],
            ...     places=place,
            ...     batch_size=BATCH_SIZE,
            ...     shuffle=True,
            ...     drop_last=True,
            ...     return_list=False,
            ...     num_workers=2
            ... )

            >>> # 1. train and save inference model
            >>> for data in loader():
            ...     exe.run(
            ...         static.default_main_program(),
            ...         feed=data,
            ...         fetch_list=[avg_loss]
            ...     )

            >>> model_path = "fc.example.model"
            >>> paddle.static.save_inference_model(
            ...     model_path,
            ...     [image],
            ...     [pred],
            ...     exe
            ... )

            >>> # 2. load model

            >>> # enable dygraph mode
            >>> paddle.disable_static(place)

            >>> # load
            >>> fc = paddle.jit.load(model_path)

            >>> # inference
            >>> fc.eval()
            >>> x = paddle.randn([1, IMAGE_SIZE], 'float32')
            >>> pred = fc(x)

            >>> # fine-tune
            >>> fc.train()
            >>> loss_fn = nn.CrossEntropyLoss()
            >>> adam = opt.Adam(learning_rate=0.001, parameters=fc.parameters())
            >>> loader = paddle.io.DataLoader(dataset,
            ...     places=place,
            ...     batch_size=BATCH_SIZE,
            ...     shuffle=True,
            ...     drop_last=True,
            ...     num_workers=2
            ... )
            >>> for epoch_id in range(EPOCH_NUM):
            ...     for batch_id, (image, label) in enumerate(loader()):
            ...         out = fc(image)
            ...         loss = loss_fn(out, label)
            ...         loss.backward()
            ...         adam.step()
            ...         adam.clear_grad()
            ...         print("Epoch {} batch {}: loss = {}".format(
            ...             epoch_id, batch_id, np.mean(loss.numpy())))
)r   r  r    r1   
_constructr6   )r  r   r  r  s       rO   loadr    sE    \  (F4TBJ}}!,,Z@@))*==rN   c                   [         R                  R                  R                  R                  5       (       a  [	        U [         R                  R
                  R                  5      (       a  U R                  R                  U5        g [	        U [         R                  R                  5      (       a  U R                  U5        g [        S5      eg )Nz7In to_static mode, variable must be a Variable or Value)r   baser   in_to_static_moder   rA  r   desc	set_shaper   r   r   )variable
shape_lists     rO   set_dynamic_shaper    s    {{1133h 5 5 > >??MM##J/&**"2"233z*I 
 	rN   c                   [        U [        5      (       a  U R                  (       a,  [        R                  " U R
                  U R                  5      nOU R
                  nU R                  R                  c#  [        UU R                  40 U R                  D6nU$ [        UU R                  R                  40 U R                  D6nU$ U $ r\   )r   r+   ru  types
MethodType_dygraph_function_function_spec_input_specr(   last_call_input_spec_kwargs)ry   dygraph_functionast_static_functions      rO   rp  rp    s    (233""$//**H,C,C   (99""..6"3 --# ""#
 '&"3 ''33# ""#
 '&OrN   c                ,   [         R                  R                  U5      n0 nUR                  5       R	                  5        H/  nUR
                  S UR
                  R                  S5       nXeU'   M1     0 nU R                  5       R                  5        H  u  pyXYR
                     X'   M     U R                  U5        [         R                  R                  5          [         R                  R                  XU5        S S S 5        g ! , (       d  f       g = f)Nr   )r   jitr  
state_dictr   r   rfindrv  rw  set_state_dict	pir_utils
OldIrGuardr  )
netr   	load_path	save_pathnet1r  r<  r   name_state_dictr   s
             rO   json_to_pdmodelr    s    ::??9%DJ '')xx-#((..-.4 * O--/557	 *88 4 8 '				$	$	&


3 
'	&	&s   !D
D)r]   r   )rl   zlist[ModuleType]r}   r*  )...)ry   rU   r   !NestedStructure[InputSpec] | Noner   BuildStrategy | Noner   Backends | Noner   Unpack[_ToStaticOptions]r}   rU   )ry   r~   r   r  r   r  r   r  r   r  r}   r   )....)ry   r*  r   r  r   r  r   r  r   r  r}   rt   )NNNrY   )r   r;   r}   r   )r   rQ   r}   r   )F)r-  r%  r}   r%  )r   r   rE  zlist[tuple[Any, str]])r'  r!   r}   z	list[str]r\   r)  )r  r   r   zUnpack[_LoadOptions]r}   z$TranslatedLayer | PirTranslatedLayer)y
__future__r   rb   r   r  r   	threadingr  r   collectionsr   collections.abcr   
contextlibr   r   typingr   r	   r
   r   r   r   r   typing_extensionsr   r   r   r   r   r   paddle.baser   r   paddle.base.compilerr   paddle.base.dygraph.baser   paddle.base.executorr   r   paddle.base.frameworkr   r   r   r   r   paddle.base.wrapped_decoratorr   paddle.frameworkr    	paddle.nnr!   paddle.static.ior"   paddle.utils.environmentsr#   	dy2staticr%   dy2static.convert_call_funcr'   dy2static.program_translatorr(   r)   r*   r+   r,   dy2static.utilsr-   r.   r/   pir_translated_layerr0   r1   translated_layerr2   r3   r4   r5   r6   r7   paddle._typingr8   paddle.staticr9   r;   rQ   rU   rW   rX   rZ   rL   r^   rj   rm   ro   rt   r`   r   r   r   r   r   r   r  Lockr  r  r  r  r"  r  r%  r0  rH  rP  r  r  r  rp  r  rF   rN   rO   <module>r      so    #  	  
    # $ %      % 7  9 (  1 % :  
 M  .'/y /*y *
 )5
)
I
fo) %  
*4"y "
- - 
 58+."	1 ) 	
 '  
 
 58+."	)&)1) )) 	)
 ') $) 
) 
47+."	1 ) 	
 '  
 	@F`& `&F F$E-PWH,^ !~~' * *9"x##H   ,B
  @Dy)%y)
y) =y) $	y)
 
y)  y)x s>
s>.s>)s> s>l44rN   