o
    "j%                    @  s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
 d dlmZ d dlmZ d dlZd dlmZmZ d dlmZmZmZ d dlmZ d d	lmZmZ d d
lmZmZ d dlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( d dl)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? ddl@mAZAmBZBmCZCmDZDmEZE e2ddZFed[ddZGdd ZHd\dd ZId\d!d"ZJd#d$ ZKe*eKZLd%d& ZMd]d)d*ZNd+d, ZO				d^d-d.ZPd_d/d0ZQG d1d2 d2ZRd3d4 ZSd5d6 ZTd7d8 ZUd`d:d;ZVd<d= ZWeX aYg aZG d>d? d?Z[d@dA Z\dBdC Z]dDdE Z^e*dFdG Z_dadLdMZ`e_ed_dNdOZae(dPdQ Zbe(	TdbdUdVZcG dWdX dXZddYdZ ZedS )c    )annotationsN)OrderedDict)contextmanager)Any)coredygraph)BuildStrategyCompiledProgramExecutionStrategy)
check_type)program_desc_tracing_guardswitch_to_static_graph)Executorscope_guard)	BlockEagerParamBase	ParameterProgramVariable_current_expected_place_dygraph_guard_dygraph_tracerdygraph_only)wrap_decorator)in_dynamic_mode)Layer)save_inference_model)BooleanEnvironmentVariableEnvironmentVariableGuard   )logging_utils)ConversionOptionsadd_ignore_module)ASTStaticFunctionProgramTranslatorStaticFunctionSymbolicStaticFunctionconvert_to_staticunwrap_decorators)INFER_MODEL_SUFFIXINFER_PARAMS_INFO_SUFFIXINFER_PARAMS_SUFFIXINFER_PROPERTY_SUFFIXTranslatedLayerZENABLE_FALL_BACKTvalueboolc                 c  s8    t t|  d V  W d    d S 1 sw   Y  d S N)r   ENV_ENABLE_SOT)r.    r2   O/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/jit/api.pysot_mode_guardS   s   "r4   c                 C  s&   t  }| |_t|dg|_|  |S Nr   )r   descr   blocksZ_sync_with_cpp)program_descprogramr2   r2   r3   create_program_from_descY   s
   r:   inputsc                 C  sT   t | tr||  d S t | ttfr | D ]}t||| qd S td|t| )NzlThe type of 'each element of {}' in paddle.jit.api.TracedLayer.trace must be base.Variable, but received {}.)	
isinstancer   appendlisttuple_extract_vars	TypeErrorformattype)r;   result_listerr_tagvarr2   r2   r3   r@   a   s   
r@   c                 C  s   g }t | || |S r0   )r@   )r;   rE   rD   r2   r2   r3   extract_varso   s   rG   c                   s    fdd}|S )a+  
    Converts imperative dygraph APIs into declarative function APIs. Decorator
    @dygraph_to_static_func only converts imperative dygraph APIs into
    declarative net-building APIs, which means it doesn't return immediate
    digital result as imperative mode. Users should handle Program and Executor
    by themselves.

    Note:
    This decorator is NOT our recommended way to transform imperative function
    to declarative function. We will remove this decorator after we finalize
    cleaning up code.

    Args:
        dygraph_func (callable): callable imperative function.

    Returns:
        Callable: converting imperative dygraph APIs into declarative
        net-building APIs.

    Examples:
        .. code-block:: python

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

            >>> @dygraph_to_static_func
            ... def func(x):
            ...     if paddle.mean(x) < 0:
            ...         x_v = x - 1
            ...     else:
            ...         x_v = x + 1
            ...
            ...     return x_v
            ...
            >>> paddle.enable_static()
            >>> x = paddle.full(shape=[3, 3], fill_value=0, dtype='float64')

            >>> x_v = func(x)
            >>> exe = paddle.static.Executor(paddle.CPUPlace())
            >>> out = exe.run(fetch_list=[x_v])
            >>> print(out[0])
            [[1. 1. 1.]
             [1. 1. 1.]
             [1. 1. 1.]]

    c                    s@   t  }t s	|jstd  | i |S t }|| i |S )NzThe decorator 'dygraph_to_static_func' doesn't work in dygraph mode or set 'paddle.jit.enable_to_static' to False. We will just return dygraph output.)r$   r   enable_to_staticr    warnr'   )argskwargsZprogram_translatorstatic_funcdygraph_funcr2   r3   __impl__   s   z*_dygraph_to_static_func_.<locals>.__impl__r2   )rN   rO   r2   rM   r3   _dygraph_to_static_func_u   s   2rP   c                 C  s6   d}| j |_ ||_| |_| j|_t| dr| j|_|S )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_static
__module__)__name__Z_decorator_name__wrapped____doc__hasattrrR   )original_funcdecorated_objZdecorator_namer2   r2   r3   copy_decorator_attrs   s   
rY   modules	list[Any]c                 C  s   t |  dS )a/  
    Adds modules that ignore transcription.
    Builtin modules that have been ignored are collections, pdb, copy, inspect, re, numpy, logging, six

    Args:
        modules (List[Any]): Ignored modules that you want to add

    Examples:
        .. code-block:: python

            >>> import scipy
            >>> import astor

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

    N)r"   )rZ   r2   r2   r3   ignore_module   s   r\   c                 C  s.   | dvrt d|  d| dkrd|_d S d S )N)CINNNz@The backend of to_static should be 'CINN' or None, but received .r]   T)
ValueErrorZbuild_cinn_pass)backendbuild_strategyr2   r2   r3   _check_and_set_backend   s   

rb   c                   s   | dd| dd fdd}pt tts*tdtjt  | durVt| trRt| j	t
rJ| jj}td| || j	| _	| S || S |S )	a  
    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 build_strategy,
            please refer to :code:`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.
        kwargs: Support keys including `property`, set `property` to True if the function
            is python property.

    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.]])

    propertyF
full_graphNc              	     sj   du rt  }| tjdkrstd dttd }t| \}} t	| ||  dd}|S )zN
        Decorates a python function into a ASTStaticFunction object.
        N)      zTfull_graph=False is not supported in Python 3.12+. Set full_graph=True automaticallyT)FT)function
input_specra   rc   r`   )rW   rX   )
r1   getsysversion_infowarningsrI   r&   r#   r(   rY   )Zpython_funcflagZStaticClass_Zstatic_layerr`   ra   rd   rh   rc   r2   r3   	decorated+  s2   zto_static.<locals>.decoratedzURequired type(build_strategy) shall be `paddle.static.BuildStrategy`, but received {}zb`{}.forward` has already been decorated somewhere. It will be redecorated to replace previous one.)ri   r   r<   rA   rB   rC   rS   rb   r   forwardr%   	__class__r    rI   )rg   rh   ra   r`   rK   rp   
class_namer2   ro   r3   rQ      s0   8
&


rQ   c                 C  s$   | du rt S tdd}||  | S )a  
    A Decorator to suppresses the convertion of a function.

    Args:
        func(callable): The function to decorate.

    Returns:
        callable: A function which won't be converted in Dynamic-to-Static.

    Examples:
        .. code-block:: python

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

            >>> @paddle.jit.not_to_static
            ... def func_not_to_static(x):
            ...     res = x - 1
            ...     return res

            >>> @paddle.jit.to_static
            ... def func(x):
            ...     if paddle.mean(x) < 0:
            ...         out = func_not_to_static(x)
            ...     else:
            ...         out = x + 1
            ...     return out
            ...
            >>> x = paddle.ones([1, 2], dtype='float32')
            >>> out = func(x)
            >>> print(out)
            Tensor(shape=[1, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[2., 2.]])
    NT)Znot_convert)not_to_staticr!   attach)funcoptionsr2   r2   r3   rt   m  s
   #

rt   c                   @  s|   e Zd Zdd Zedd Zejdd Zedd Zejdd Zed	d
 Zejdd
 Zedd Z	e	jdd Z	dS )_SaveLoadConfigc                 C  sF   d | _ d | _d | _d| _d| _d| _d| _d| _d| _d | _	d| _
d S )NFT)_output_spec_model_filename_params_filenameZ_separate_params_keep_name_tableZ_export_for_deployment_program_only	with_hookcombine_paramsinput_names_after_pruneskip_prune_programselfr2   r2   r3   __init__  s   
z_SaveLoadConfig.__init__c                 C     | j S r0   )ry   r   r2   r2   r3   output_spec     z_SaveLoadConfig.output_specc                 C  s0   |d u rd S t |tstdtt || _d S )NzIThe config `output_spec` should be 'list', but received input type is %s.)	r<   r>   rA   rC   inputr   eagerTensorry   )r   specrF   r2   r2   r3   r     s   


c                 C  r   r0   )rz   r   r2   r2   r3   model_filename  r   z_SaveLoadConfig.model_filenamec                 C  D   |d u rd S t |tstdt| t|dkrtd|| _d S )NzKThe config `model_filename` should be str, but received input's type is %s.r   z,The config `model_filename` is empty string.)r<   strrA   rC   lenr_   rz   r   filenamer2   r2   r3   r        

c                 C  r   r0   )r{   r   r2   r2   r3   params_filename  r   z_SaveLoadConfig.params_filenamec                 C  r   )NzLThe config `params_filename` should be str, but received input's type is %s.r   z-The config `params_filename` is empty string.)r<   r   rA   rC   r   r_   r{   r   r2   r2   r3   r     r   c                 C  r   r0   )r|   r   r2   r2   r3   keep_name_table  r   z_SaveLoadConfig.keep_name_tablec                 C  s0   |d u rd S t |tstdt| || _d S )NzSThe config `keep_name_table` should be bool value, but received input's type is %s.)r<   r/   rA   rC   r|   )r   r.   r2   r2   r3   r     s   

N)
rS   rR   __qualname__r   rc   r   setterr   r   r   r2   r2   r2   r3   rx     s$    






rx   c                 C  s   g d}| D ]}||vrt d| qt }| dd |_| dd|_| dd|_| dd|_| d	d|_| d
d |_| dd|_	|S )N)r   r~   r   
clip_extraskip_forwardr   r   zAThe additional config (%s) of `paddle.jit.save` is not supported.r   r~   Fr   r   Tr   r   r   )
r_   rx   ri   r   r~   r   r   r   r   r   configsZsupported_configskeyZinner_configr2   r2   r3   _parse_save_configs  s(   r   c                 C  sL   ddg}| D ]}||vrt d| qt }| dd |_| dd |_|S )Nr   r   zAThe additional config (%s) of `paddle.jit.load` is not supported.)r_   rx   ri   r   r   r   r2   r2   r3   _parse_load_config  s   r   c                   s   d}d} d ur fdd|D }g }dd t j| D }|d u r$|S dd |D }t|t|krX|}|D ]}|jd u rFt||  q7|j|vrTt||j  q7	 q7|S |D ]}|jd u rgt|| |j|vrst||j ||j qZ|S )NzThe %s's name is None. When using jit.save, please set InputSepc'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.c                   s(   g | ]}t |tjjr|j v r|qS r2   )r<   paddlestatic	InputSpecname).0xr   r2   r3   
<listcomp>@  s    
z(_get_input_var_names.<locals>.<listcomp>c                 S  s   g | ]
}t |tr|jqS r2   )r<   r   r   )r   rF   r2   r2   r3   r   H  s    c                 S  s   g | ]}t |tjjr|qS r2   )r<   r   r   r   )r   r   r2   r2   r3   r   R  s    )	r   utilsflattenr   r   rl   rI   r_   r=   )r;   rh   r   Zname_none_errorname_no_exists_errorrD   input_var_namesr   r2   r   r3   _get_input_var_names2  sB   





r   Fc                 C  s   d}|r
|r
t dg }t }tj| D ]}t|tr!|||j< q|d u r.t|	 }|S |d urTt
|t
|krTt|	 }|D ]}|j|vrQt||j  qB|S |D ]}|j|vrdt||j |||j  qV|S )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.z`Currently not support specify output_spec while founding pre/post hooks in your outermost layer.)RuntimeErrorr   r   r   r   r<   r   r   r>   valuesr   rl   rI   r_   r=   )outputsr   r~   r   rD   Zoutput_vars_dictrF   r2   r2   r3   _get_output_varss  s6   



r   c                 C  s   | t  }tj|}tj| }|r|rtd|  d|  d|s)|s)td|  |rYtj| }tj| }|jd urAt	
d |t  |_|jd urPt	
d |t |_||fS | }||fS )Nz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.zThe ``path`` (%s) to load model not exists. Please make sure that *.pdmodel 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)   ospathexistsisdirr_   basenamedirnamer   rl   rI   r   r+   )r   configZprefix_format_pathZprefix_format_existZdirectory_format_existfile_prefix
model_pathr2   r2   r3   _build_load_path_and_config  s:   



r   c                   @  s    e Zd ZdZdd Zdd ZdS )HookRemoveHelperz3A HookRemoveHelper that can be used to remove hook.c                 C  s
   || _ d S r0   )_hook)r   hookr2   r2   r3   r     s   
zHookRemoveHelper.__init__c                 C  s   t | j d S r0   )_remove_save_pre_hookr   r   r2   r2   r3   remove  s   zHookRemoveHelper.removeN)rS   rR   r   rU   r   r   r2   r2   r2   r3   r     s    r   c                 C  s*   t   | tvrt|  t   t| S )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   r2   r2   r3   _register_save_pre_hook  s
   5
r   c                   C  s   t   t  t   d S r0   )r   r   r   clearr   r2   r2   r2   r3   _clear_save_pre_hooks  s   r   c                 C  s&   t   | tv rt|  t   d S r0   )r   r   r   r   r   r   r2   r2   r3   r     s   
r   c                   s   d fdd	}|S )Nc                   s.   t D ]}|| || q | ||fi | d S r0   )r   )layerr   rh   r   r   rv   r2   r3   wrapper%  s   z$_run_save_pre_hooks.<locals>.wrapperr0   r2   )rv   r   r2   r   r3   _run_save_pre_hooks#  s   r   r   r   property_valslist[tuple[Any, str]]c                 C  sz   dd }t | d*}tjj }|D ]}|d |d }}|||| q||  W d   dS 1 s6w   Y  dS )zclass property serialization.

    Args:
        filename (str): *.meta
        property_vals (list[tuple[Any, str]]): class property.
    c                 S  s   t |tr| || d S t |tr| || d S t |tr'| || d S t |ttfr]t |d tr=| 	|| d S t |d trL| 
|| d S t |d tr[| || d S d S tdt| )Nr   zNote support val type: )r<   floatZ	set_floatintZset_intr   Z
set_stringr?   r>   Z
set_floatsZset_intsZset_stringsr_   rC   )metar   valr2   r2   r3   set_property6  s   


z$_save_property.<locals>.set_propertywbr   r   N)openr   	frameworkr   PropertywriteZserialize_to_string)r   r   r   fr   itemr   r   r2   r2   r3   _save_property.  s   "r   c           0        sf  t  }t o
t }|jstdt| ttfs&t	
| s&tdt|  t	
| s0t| tr5td t| tjr?| j}n| }tj|}|dkrOtdtj|}|rbtj|sbt| d}	|durt| trt|D ]}
t||
d}t|trd|
krtdt| qqt|ttfstd	t| g }	tj|D ](}t|tjj r|	!| qt|tj"j#t$fr|	!tjj %| q|	!| qt&|}|j'}|j(}|rd
|_)t* }i }t| trtt+t|}t,|}|j-s|j.rd
}n| g}i }g }d |D ]}
t| trdt/t||
d}t|tr;|j0r2| }|!|| j1j2d |
 f q|j3|	||d nrd|
krb|j4rFq|	rPtj5||	}	t6|j7|	d
d}|j3||d d}	nKqt|
trt/|
}|j0r~| }|!||f q|j3|	|d n't/|
}|	rtj5||	}	t6||	d
d}|j8 |j9du rtd|  d d}t|tr|: }nt|
tr|j9r|j9: }|ri }i }|; D ]\}}|||j<< |||j<< qt=> j  j?D ]^}|jtj@jAjBkr	|C D }|E|j<}|F| n|E|j<G }||j< C G }|H| |j<|vrIi } |j<|v r4||j< | d< |jI| d< t|tJrD|jK| d< | ||j<< qW d   n	1 sVw   Y  tL jM|	|jN}!tO jP|jQ|}"|}#d|
ksxt| ts|tR }$|tS }%|}&n|d |
 tR }$|d |
 tS }%|d |
 }tjT|#|}tU|$  fdd|!D }'tV||'|"tWtX  jYZ |j[|j\d W d   n	1 sw   Y  |r jYZ }(|(]|!|"}(|(j^D ]	})|_|)j` qq|rJt,|; dd d}g }*|D ]
\}+}|*!| q|tS }%tU| tjjatWtX |#ttbtjcjdje|*|%d W d   n	1 s3w   Y  tjTtjf|#|tg },th|,| d}- dura jYi D ]
}|-t|tjO }-qVt| tsj|-r|rtU|3 |tk }.tl|.d}/tmjn||/dd W d   n1 sw   Y  W d   dS W d   dS 1 sw   Y  dS dS dS )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]): 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.

    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):
            ...     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.z\The input of paddle.jit.save should be 'Layer' or 'Function', but received input type is %s.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. The input path MUST be format of dirname/file_prefix [dirname\file_prefix in Windows system], but received file_prefix is empty string.Nrq   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 %s.zLThe input input_spec should be 'list', but received input_spec's type is %s.Tr^   )r~   is_prim_infer)rh   rd   )r   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	trainablec                   s   g | ]
} j  |qS r2   )main_programglobal_blockrF   )r   r   concrete_programr2   r3   r     s    zsave.<locals>.<listcomp>)path_prefix	feed_vars
fetch_varsexecutorr9   r   r   c                 S  s   | d S r5   r2   )r   r2   r2   r3   <lambda>  s    zsave.<locals>.<lambda>)r   )r   varsr   Fr      )protocol)or$   r   Z_is_fwd_prim_enabledZ_is_bwd_prim_enabledrH   r   r<   r   r%   inspect
isfunctionrA   rC   rl   rI   r   ZDataParallelZ_layersr   r   r   r_   r   r   makedirsdirgetattrr>   r?   r   r   r   r   r=   r   r   r   Zfrom_tensorr   r~   r   r}   ScopesetsortedZ_forward_pre_hooksZ_forward_post_hooksget_ast_static_functionZis_propertyrr   rS   Z#concrete_program_specify_input_specr   Zpack_sequence_asrQ   rq   r   _class_instanceZto_static_state_dictitemsr   r   guard
parametersZVarDescZVarTypeZVOCABr.   Zget_map_tensorrF   Z	set_vocab
get_tensor_share_data_withr   r   r   r   r;   r   r   r   r   r)   r+   joinr   r   r   r   r   cloner   r   Z_prune_with_inputr7   updater   Z	save_varsfilterr   Zio_utilsZis_persistablenormpathr,   r   Z	list_varsr   r*   r   pickledump)0r   r   rh   r   Zprog_translatorr   Zinner_layerr   r   Zinner_input_specZ	attr_funcrL   rF   r~   r   scopeZextra_var_infoZ	functionsZcombine_varsr   Zimmediate_valZstatic_forwardZstatic_functionZdygraph_state_dictZstate_names_dictZstate_var_dictr   Zparam_or_bufferZ
scr_tensorZtgt_varZparam_or_buffer_tensor
src_tensorZextra_info_dictr   Zoutput_varsr   r   r   r   Z
input_varsZclone_main_programblockZordered_varsr   Zproperty_save_pathZcontain_parameterZextra_var_info_pathr   r2   r   r3   saveO  s   	













)









 $r  c                 K  s"   t |}t| |\}}t||S )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 LoDTensor. All original model's feed targets or parametars 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):
                ...     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):
                ...     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-   Z
_construct)r   r   r   r   r2   r2   r3   loadA  s    mr  feed_fetch_t_c                 C  s   t | tsJ t |ttfs|g}t  }t|}td0 | | }t |ttfs.|g}n|}t|dd}	||||	||\}
}}}|	  W d    n1 sQw   Y  t
d  t|
}W d    n1 siw   Y  |||||fS )NTr   )rE   )r<   r   r>   r?   r   Z_get_program_desc_tracerrG   r   Zcreate_program_descresetr   r:   )r   r;   Zfeed_prefixZfetch_prefixZ
tmp_prefixZtracerZvar_listZoriginal_outputsr   Zout_varsr8   
feed_namesfetch_namesr   r9   r2   r2   r3   _trace3  s2   





r  c                   @  s~   e Zd ZdZdd Zedd ZdddZee	d	d
 Z
dddZedd Zdd Zedd Zdd ZedddZdS )TracedLayera  
    :api_attr: imperative

    TracedLayer is used to convert a forward dygraph model to a static
    graph model. This is mainly used to save the dygraph model for online
    inference using C++. Besides, users can also do inference in Python
    using the converted static graph model, which usually has better
    performance than the original dygraph model.

    TracedLayer would run the static graph model using :code:`Executor`
    and :code:`CompiledProgram` . The static graph model would share
    parameters with the dygraph model.

    All TracedLayer objects should not be created by constructor and should
    be created by static method :code:`TracedLayer.trace(layer, inputs)` .

    The TracedLayer can only be used to convert the data-independent dygraph
    model into the static graph model, which means the dygraph model should
    be independent with the tensor data and shape.
    c                 C  s~   || _ || _|| _|| _t | _t | _|D ]}|	 
 }| j|j
 }|| qt| j| _d | _d | _d | _d S r0   )_program_feed_names_fetch_names_paramsr   Z_placer   r   _scoper.   r   rF   r   r   r   _exe_compiled_program_build_strategy_exec_strategy)r   r9   r   r
  r  pr  Z
dst_tensorr2   r2   r3   r   n  s   

zTracedLayer.__init__c                 C  r   r0   )r  r   r2   r2   r3   r9     r   zTracedLayer.programTc                 C  sD   t | jjD ]}| j|}|jD ]}|dr|d| qqd S )Nis_test)ranger  Z
num_blocksr  opsZhas_attrZ	_set_attr)r   r  Zblock_idr  opr2   r2   r3   _switch  s   

zTracedLayer._switchc                 C  sF   t | tsJ dt| t| |\}}}}}t||||}||fS )a{  
        This method is the only allowed method to create TracedLayer object.
        It would call the :code:`layer(*inputs)` method to run the dygraph
        model and convert it into a static graph model.

        Args:
            layer (paddle.nn.Layer): the layer object to be traced.
            inputs (list(Tensor)|tuple(Tensor)|Tensor): the input tensors of
                the layer object.

        Returns:
            tuple: A tuple of 2 items, whose the first item is the output of
                :code:`layer(*inputs)` , and the second item is the created
                TracedLayer object.

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> class ExampleLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._fc = paddle.nn.Linear(3, 10)
                ...
                ...     def forward(self, input):
                ...         return self._fc(input)


                >>> layer = ExampleLayer()
                >>> in_var = paddle.uniform(shape=[2, 3], dtype='float32')
                >>> out_dygraph, static_layer = paddle.jit.api.TracedLayer.trace(layer, inputs=[in_var])

                >>> # run the static graph model using Executor inside
                >>> out_static_graph = static_layer([in_var])

                >>> print(len(out_static_graph)) # 1
                >>> print(out_static_graph[0].shape) # (2, 10)

                >>> # save the static graph model for inference
                >>> static_layer.save_inference_model('./saved_infer_model')

        zaThe type of 'layer' in paddle.jit.api.TracedLayer.trace must be paddle.nn.Layer, but received {}.)r<   r   rB   rC   r  r  )r   r;   Zoutsprogfeedfetchr   Ztracedr2   r2   r3   trace  s   .zTracedLayer.traceNc                 C  sj   | j du s	J dt|tdtfsJ dt|t|tdtfs-J dt||| _|| _dS )a  
        Set the strategies when running static graph model.

        Args:
            build_strategy (BuildStrategy, optional): build strategy of
                :code:`CompiledProgram` inside TracedLayer. Default None.
            exec_strategy (ExecutionStrategy, optional): execution strategy of
                :code:`CompiledProgram` inside TracedLayer. Default None.

        Returns:
            None

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> class ExampleLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._fc = paddle.nn.Linear(3, 10)
                ...
                ...     def forward(self, input):
                ...         return self._fc(input)

                >>> layer = ExampleLayer()
                >>> in_var = paddle.uniform(shape=[2, 3], dtype='float32')

                >>> out_dygraph, static_layer = paddle.jit.api.TracedLayer.trace(layer, inputs=[in_var])

                >>> build_strategy = paddle.static.BuildStrategy()
                >>> build_strategy.enable_inplace = True

                >>> exec_strategy = paddle.static.ExecutionStrategy()
                >>> exec_strategy.num_threads = 2

                >>> static_layer.set_strategy(build_strategy=build_strategy, exec_strategy=exec_strategy)
                >>> out_static_graph = static_layer([in_var])

        NzCannot set strategy after runztThe type of 'build_strategy' in paddle.jit.api.TracedLayer.set_strategy must be base.BuildStrategy, but received {}.zwThe type of 'exec_strategy' in paddle.jit.api.TracedLayer.set_strategy must be base.ExecutionStrategy, but received {}.)r  r<   rC   r   rB   r
   r  r  )r   ra   Zexec_strategyr2   r2   r3   set_strategy  s"   )
zTracedLayer.set_strategyc                 C  s   t | j| jd| _d S )N)ra   )r	   r  r  r  r   r2   r2   r3   _compile  s   zTracedLayer._compilec                 C  s   t |ttfsJ dt|t| jksJ i }t r0t|| jD ]\}}|  ||< q!|S t|| jD ]\}}|||< q6|S )Nz-Inputs should be a list or tuple of variables)	r<   r>   r?   r   r  r   zipr.   r   )r   r;   Z	feed_dictr   r   r2   r2   r3   _build_feed  s   
zTracedLayer._build_feedc                 C  s   | j j| j|| jdS )N)r  Z
fetch_list)r  runr  r  )r   r  r2   r2   r3   _run  s   
zTracedLayer._runc                 C  sP   t | j | jd u r|   | | |W  d    S 1 s!w   Y  d S r0   )r   r  r  r"  r&  r$  )r   r;   r2   r2   r3   __call__  s
   
$zTracedLayer.__call__c              
   K  s  t |dtd t |dtdtfd t|tr#|D ]	}t |dtd qt |dtdtfd t|tr?|D ]	}t |dtd q5|dd	}tj	|}|d
krSt
dtj|}|rftj|sft| dd }	t| js |	| j|}
|	| j|}g }|
D ]}| j j|d}|dusJ | d|| qg }|D ]}| j j|d}|dusJ | d|| q|dd}tj||}t|||| j| j ||d W d   dS 1 sw   Y  dS )aG
  
        Save the TracedLayer to a model for inference. The saved
        inference model can be loaded by C++ inference APIs.

        ``path`` is the prefix of saved objects, and the saved translated program file
        suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` .

        Args:
            path(str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``.
            feed (list[int], optional): the input variable indices of the saved
                inference model. If None, all input variables of the
                TracedLayer object would be the inputs of the saved inference
                model. Default None.
            fetch (list[int], optional): the output variable indices of the
                saved inference model. If None, all output variables of the
                TracedLayer object would be the outputs of the saved inference
                model. Default None.
            kwargs: Supported keys including
                - clip_extra(bool): whether to clip extra information for every operator. Defaults to True.
                - legacy_format(bool): whether to save program in legacy format. Default to False.

        Returns:
            None

        Examples:
            .. code-block:: python

                >>> import numpy as np
                >>> import paddle

                >>> class ExampleLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._fc = paddle.nn.Linear(3, 10)
                ...
                ...     def forward(self, input):
                ...         return self._fc(input)

                >>> save_dirname = './saved_infer_model'
                >>> in_np = np.random.random([2, 3]).astype('float32')
                >>> in_var = paddle.to_tensor(in_np)
                >>> layer = ExampleLayer()

                >>> out_dygraph, static_layer = paddle.jit.api.TracedLayer.trace(layer, inputs=[in_var])
                >>> static_layer.save_inference_model(save_dirname, feed=[0], fetch=[0])

                >>> paddle.enable_static()
                >>> place = paddle.CPUPlace()
                >>> exe = paddle.static.Executor(place)
                >>> program, feed_vars, fetch_vars = paddle.static.load_inference_model(
                ...     save_dirname,
                ...     exe
                ... )

                >>> fetch, = exe.run(program, feed={feed_vars[0]: in_np}, fetch_list=fetch_vars)
                >>> print(fetch.shape)
                [2, 10]
        r   z/paddle.jit.api.TracedLayer.save_inference_modelr  Nzeach element of feedr  zeach element of fetchr   Tr   r   c                   s   |d u r S  fdd|D S )Nc                   s   g | ]} | qS r2   r2   )r   idxall_varsr2   r3   r     s    zLTracedLayer.save_inference_model.<locals>.get_feed_fetch.<locals>.<listcomp>r2   )r*  Zpartial_varsr2   r)  r3   get_feed_fetch  s   z8TracedLayer.save_inference_model.<locals>.get_feed_fetchz cannot be foundlegacy_formatF)r   r   r   r   r9   r   r,  )r   r   rC   r>   r<   r   ri   r   r   r   r_   r   r   r   r   r  r  r  r  r   r   r=   r   r   r  r   )r   r   r  r  rK   r   r   r   r   r+  Zfeeded_var_namesZtarget_var_namesr   r   Zfeed_varZtarget_varsZ
target_varr,  r2   r2   r3   r     s   <




"z TracedLayer.save_inference_model)T)NN)rS   rR   r   rU   r   rc   r9   r  staticmethodr   r   r!  r   r"  r$  r&  r'  r   r2   r2   r2   r3   r  X  s$    


57

r  c                 C  sn   t | tr5| jrt| j| j}n| j}| jjd u r't|| j	fi | j
}|S t|| jjfi | j
}|S | S r0   )r<   r&   r   types
MethodTypeZ_dygraph_functionZ_function_specZ_input_specr#   Zlast_call_input_spec_kwargs)rg   Zdygraph_functionZast_static_functionr2   r2   r3   r     s,   
r   )r.   r/   )r;   )rZ   r[   )NNNNr0   )F)r   r   r   r   )r  r  r  )f
__future__r   r   r   r   rj   	threadingr.  rl   collectionsr   
contextlibr   typingr   r   Zpaddle.baser   r   Zpaddle.base.compilerr   r	   r
   Zpaddle.base.data_feederr   Zpaddle.base.dygraph.baser   r   Zpaddle.base.executorr   r   Zpaddle.base.frameworkr   r   r   r   r   r   r   r   r   Zpaddle.base.wrapped_decoratorr   Zpaddle.frameworkr   Z	paddle.nnr   Zpaddle.static.ior   Zpaddle.utils.environmentsr   r   Z	dy2staticr    Zdy2static.convert_call_funcr!   r"   Zdy2static.program_translatorr#   r$   r%   r&   r'   r(   Ztranslated_layerr)   r*   r+   r,   r-   r1   r4   r:   r@   rG   rP   Zdygraph_to_static_funcrY   r\   rb   rQ   rt   rx   r   r   r   r   r   Lockr   r   r   r   r   r   r   r   r  r  r  r  r   r2   r2   r2   r3   <module>   s   , 


A



}+e"
A*+
<	


!   s
 r$  S