
    {-j             	         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m	Z	m
Z
 d dlmZmZmZmZ d dlZd dlmZmZ d dlZd dlmZmZmZmZ d dlmZ d dlmZmZmZ d d	lm Z  d d
l!m"Z" d dl#m$Z$m%Z%m&Z&m'Z' d dl(m)Z) d dl*m+Z+m,Z, d dl-m.Z.m/Z/m0Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZD erd dlEmFZFmGZGmHZHmIZI d dlJmKZKmLZLmMZMmNZN d dlOmPZP g ZQeedegef         edeeReSef         geTeeReSef         f         f         f         ZUeedeegef         edeeReSef         egef         f         ZVeeReSef         ej	        eSef         f         ZWeeWgdf         ZX ejY        d          ZZ ejY        d          Z[d Z\d Z]d Z^d Z_d Z`d  Za G d! d" e
d#d$d%g                    Zb G d& d'e9          Zc G d( d)          Zd G d* d+          Ze G d, d          ZfdS )-    )annotationsN)OrderedDict
namedtuple)TYPE_CHECKINGAnyCallableUnion)Selfoverload)Tensordtypennprofiler)ValueSet)core	frameworkunique_name)VarDesc)no_grad)_convert_into_variablein_declarative_modein_sot_simulation_modein_to_static_mode)_append_activation_in_dygraph)Executorglobal_scope)		ParameterProgram_current_expected_placeconvert_np_dtype_to_dtype_default_main_programin_dygraph_modein_pir_modename_structpaddle_type_to_proto_type)LayerHelperBase)ShardedStateDictbuild_sharded_state_dict)	ParamAttr)in_profiler_mode)
deprecated)param_one_alias)IterableIteratorMappingSequence)	DTypeLikeParamAttrLike	PlaceLike	ShapeLike)InitializerLayerz(.)([A-Z][a-z]+)z([a-z])([A-Z])c                *   t                      s| j        j        dk     rJt          t	                                                      j                  | j        _        d| j        _        dS d| j        _        t          j	        | j
         d           dS dS )zC
    A pre-hook to mark op numbers before enter layer.forward.
    r   TFzX has recorded the op information before. Please check whether you call this layer twice.N)r"   _op_recorderstartlenr!   current_blockopsis_validwarningswarn
_full_name)layerinputss     V/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/paddle/nn/layer/layers.pyrecord_program_ops_pre_hookrD   \   s      
#a'''*$&&4466:( (E$ +/E'''*/E'M#}}}    
 
    c                   t                      s| j        j        r| j        j        }t	          t                                                      j                  }|dk    r||k    sJ t                                                      j        ||         }|| j        _        || j        _        |D ]7}| j	        
                                D ]\  }}|                    ||           8| j        j        D ]}	|	                                 dS dS dS )zd
    A post-hook to append customized attributes into all operators generated in current layer.
    r   N)r"   r8   r=   r9   r:   r!   r;   r<   end_customized_attrsitems	_set_attrhooksremove)
rA   rB   outputsr9   rG   r<   op	attr_namevalhook_helpers
             rC   !set_op_customized_attrs_post_hookrR   m   s3     !!3!< !"(&((6688<==zzcUlll*"$$22448sC!$!$ 	- 	-B"'"9"?"?"A"A - -	3Y,,,,- !-3 	! 	!K    ! ! ! !	! 	!rE   c                :    dddd}|                     | |           S )Nlinear	embedding)row_parallel_linearcolumn_parallel_linearvocab_parallel_embedding)get)
dist_scopemappings     rC   _scope_dist2singler\      s-    '"*$/ G ;;z:...rE   c                    t                               d|           }t                              d|                                          S )Nz\1_\2)_first_cap_resub_all_cap_relower)names1s     rC   _convert_camel_to_snakerd      s7    			8T	*	*B??8R((..000rE   c                "   |                      d          }t          |          dk    r| S g }t          |          D ]3\  }}|dk    r(|                    t	          |dz  |z                        4|d         dz   d                    |          z   S )N
   r    )splitr:   	enumerateappendstrjoin)stringindentrc   s2idxlines         rC   
_addindentrs      s    	d		B
2ww!||	Br]] 2 2	T77IIc6C<4/00111a54<$))B--''rE   c                \    t          |           |v rd S |                     |dd           d S )NTFr   floating_onlyinclude_sublayers)type_to_impl)rA   r   excluded_layerss      rC   _layer_trans_dtyper{      s6    E{{o%%	NNdeNLLLLLrE   c                  (     e Zd ZdZd fdZeZ xZS )_IncompatibleKeys returnrl   c                d    | j         s	| j        sdS t                                                      S )Nz<All keys matched successfully>)missing_keysunexpected_keyssuper__repr__)self	__class__s    rC   r   z_IncompatibleKeys.__repr__   s4      	5)= 	544ww!!!rE   r   rl   )__name__
__module____qualname__	__slots__r   __str____classcell__r   s   @rC   r}   r}      s?         I" " " " " "
 GGGGGrE   r}   IncompatibleKeysr   r   c                  f     e Zd Z fdZ	 	 	 	 	 ddZd Zd ZddZddZd Z	d	 Z
dd
Zd Z xZS )LayerObjectHelperc                N    t                                          ||           d S )N)
layer_type)r   __init__)r   rb   r   s     rC   r   zLayerObjectHelper.__init__   s&    $/////rE   Nc                d    | j                                                             |||||          S )a  append an operator for this layer object.

           Args:
               type: operator type
               inputs: input variable of the operator
               dtype: data type of this parameter
               is_bias: if this is a bias parameter
               default_initializer: set the default initializer for this parameter

        Returns created parameter Variable.
        )rx   rB   rM   attrsstop_gradient)main_programr;   	append_op)r   rx   rB   rM   r   r   s         rC   r   zLayerObjectHelper.append_op   s?    &  ..00::' ; 
 
 	
rE   c                    |}g }t          |t          t          f          r.|D ]*}|                    |                     |                     +n(|                    |                     |                     |S N)
isinstancelisttuplerk   to_variable)r   	inputs_inrB   retinps        rC   _multiple_inputz!LayerObjectHelper._multiple_input   s    ftUm,, 	1 2 2

4++C0011112 JJt''//000
rE   c                v    |                      |          }t          |          dk    r
| j         d|d         S )Nrg   z layer only takes one input inr   )r   r:   r   )r   r   rB   s      rC   _inputzLayerObjectHelper._input   sA    %%i00v;;!_DDDDayrE   c                T   |}t          |t                    r|g}t          |          dk    r*t          |          |k    rt          d| j                   t          |          dk    r=|dk    r7d g|z  }t          |          D ]}t          j        |d                   ||<    |}|S )Nrg   zparameter number mismatch in r   )r   r)   r:   
ValueErrorrb   rangecopydeepcopy)r   lengthparam_attr_in
param_attrtmpis         rC   _multiple_param_attrz&LayerObjectHelper._multiple_param_attr   s    "
j),, 	&$Jz??aC
OOv$=$=HTYHHIII__!!fkk&6/C6]] 6 6z!}55AJrE   c              #  2  K   t          j        |          }t          |t                    rt	          d| j                   ||ng }|                     |          }|                     t          |          |          }t          ||          E d{V  dS )zAccess all inputs and params one by one

           Args:
               inputs_in: inputs to be iter
               param_attr_in: param_attr to be iter

        Returns input, param_attr
        z"Param_attr should not be False in N)
r)   _to_attrr   boolr   rb   r   r   r:   zip)r   r   r   rB   param_attrss        rC   iter_inputs_and_paramsz(LayerObjectHelper.iter_inputs_and_params   s       "*=99mT** 	OM$)MMNNN(42%%f--//F]KKv{+++++++++++rE   c           	         ||ng }|                      |          }d}|D ]9}||j        }||j        k    r"t          d| d|j         d| j                   :|S )zGet input data type

           Args:
               inputs_in: inputs wanted know the data type

        Returns dtype of the input
        NzData Type mismatch: z to z in )r   r   r   rb   )r   r   rB   r   eachs        rC   input_dtypezLayerObjectHelper.input_dtype  s     #,"7IIb	%%i00 	 	D}
$*$$ Q5QQdjQQdiQQ   % rE   c                    | j                                                             |          }t          |t                    st          d| d| j                   |S )z}Get parameter specifically

           Args:
               name: parameter's name

        Returns target parameter
        zno Parameter name z
 found in )r   global_blockvarr   r   r   rb   r   rb   params      rC   get_parameterzLayerObjectHelper.get_parameter  s_     !..0044T::%++ 	OM$MM$)MMNNNrE   c                j   |}||S t          |t                    rd|i}nt          | d| j                   ||r||d<   |                    d          }t                      rt          |||          }|S |                     |j                  }| 	                    |d|gid|gi|           |S )	a%  Append activation

            Args:
                input_var: the input variable. The len(input_var.shape) is
                larger or equal than 2.
                act: activation type
                use_cudnn: if use cudnn

        Return the Variable of after append activation
        Nrx   z should be unicode or str in 	use_cudnnr   XOut)rx   rB   rM   r   )
r   rl   	TypeErrorrb   popr"   r   "create_variable_for_type_inferencer   r   )r   	input_varactr   act_typeresr   s          rC   append_activationz#LayerObjectHelper.append_activation#  s     ;c3 	N3-CCsLLLLMMM!y!(C776?? 	/	8YOOCJ99	9PPCNNi[)	     JrE   c                n    |}t          ||          s"t          d|| j        |j        | j                  dS )zCheck if the input parameter is instance of input class

            Args:
                param: parameter to be check
                cls: class of the parameter

        Return result of the check (True or False)
        z?The input {0} parameter of method {1} must be {2}, in layer {3}N)r   r   r   r   rb   )r   r   clss      rC   is_instancezLayerObjectHelper.is_instanceF  sL     %%% 	Q	  	 	rE   )NNNNNr   )NN)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @rC   r   r      s        0 0 0 0 0
 
 
 
 
6       , , , ,"  (  ! ! ! !F      rE   r   c                      e Zd ZdZddZdS )LayerOpsRecorderz=
    Record generated operators information in nn.Layer.
    NFc                L    || _         || _        || _        || _        || _        d S r   )r9   rG   r<   r=   rK   )r   r9   rG   r<   r=   rK   s         rC   r   zLayerOpsRecorder.__init___  s)    
 


rE   )r   r   NFN)r   r   r   __doc__r   r~   rE   rC   r   r   Z  s2              rE   r   c                  8    e Zd ZU dZdZded<   ddddZddZdS )HookRemoveHelperz3A HookRemoveHelper that can be used to remove hook.r   intnext_hook_idNextra_hook_dictrK   +typing.OrderedDict[int, Callable[..., Any]]r   r   r   Nonec               8   t          j        |          | _        t          j        | _        t          xj        dz  c_        d| _        |Qt          |t                    r t          d |D                       | _        d S t          j        |          f| _        d S d S )Nrg   r~   c              3  >   K   | ]}t          j        |          V  d S r   )weakrefref).0ds     rC   	<genexpr>z,HookRemoveHelper.__init__.<locals>.<genexpr>y  s;       . .'(GKNN. . . . . .rE   )
r   r   
_hooks_refr   r   _hook_id_extra_hooks_refr   r   r   )r   rK   r   s      rC   r   zHookRemoveHelper.__init__l  s     "+e,,(5%%*%%')&/400 H(- . .,;. . . ) )%%% *1_)E)E(G%%% '&rE   c                    |                                  }|| j        |v r|| j        = | j        D ]} |            }|| j        |v r|| j        =  d S r   )r   r   r   )r   rK   r   extra_hookss       rC   rL   zHookRemoveHelper.remove  sq    !!%!7!7dm$( 	/ 	/C#%%K&4=K+G+G.	/ 	/rE   )rK   r   r   r   r   r   )r   r   )r   r   r   r   r   __annotations__r   rL   r~   rE   rC   r   r   g  sj         ==L  $	H H H H H H&/ / / / / /rE   r   c                  z   e Zd ZU dZded<   	 dddZed             Zej        d             Zed             Z	e	j        d             Z	dddZ
ddZddZddZdddddd#ZeZddd$dd&Z	 	 	 	 	 ddd2Zdd5Z ed6d7d89          	 	 	 ddd=            Z	 	 	 ddd>Z ed?d@g          dddB            ZdddCZddEZddGZdddJZ ed?d@g          	 	 	 dddO            Z	 	 	 	 dddRZddTZ	 	 	 dddVZ ed;dWg          	 dddY            Z  ed?d@g          dddZ            Z!dd[Z" ed?d@g          	 	 	 ddd\            Z#ddd^Z$ddbZ%dddZ&ddeZ'ddfZ(ddgZ)ddiZ*ddjZ+ edkdlg          	 dddn            Z,e+Z-e,Z.ddpZ/e/Z0ddrZ1dduZ2dv Z3ddxZ4ddzZ5dd{Z6dd}Z7dd~Z8ddZ9ddZ:ddZ;ddZ<	 	 	 dddZ=	 	 	 	 	 	 dddZ>	 	 	 	 	 dddZ?e@	 	 	 	 	 ddd            ZAe@ddddd            ZAe@ddddd            ZAe@ddKdddd            ZAddZA	 dddZB	 dddZCeDjE        	 ddd            ZF	 	 d ddZG	 	 	 	 dddZH	 dŐddZIddZJ	 	 	 	 	 	 dddZKddZLeFZMeFZNd	dZOddZPddZQ	 dҐd
dZR	 dҐd
dZS	 dҐd
dZTdҐddZUdҐddZVddZWddZXdŐddZYdŐddZZd Z[dS (  r6   a  
    Dynamic graph Layer based on OOD, includes the parameters of the layer, the structure of the forward graph and so on.

    Parameters:
        name_scope (str, optional): prefix name used by the layer to name parameters.
            If prefix is "my_layer", parameter name in MyLayer
            can be "my_layer_0.w_n", where "w" is the parameter
            base name and "n" is an unique suffix auto-generated.
            If None, prefix name will be snake cased class name. Default: None.
        dtype(str, optional): data type of this parameter.
                If set str, it can be "bool",  "float16", "float32", "float64",
                "int8", "int16", "int32", "int64", "uint8" or "uint16".
                Default: "float32"

    Returns:
        None

    Examples:
        .. code-block:: python

            >>> import paddle
            >>> paddle.seed(100)

            >>> class MyLayer(paddle.nn.Layer):
            ...     def __init__(self):
            ...         super().__init__()
            ...         self._linear = paddle.nn.Linear(1, 1)
            ...         self._dropout = paddle.nn.Dropout(p=0.5)
            ...
            ...     def forward(self, input):
            ...         temp = self._linear(input)
            ...         temp = self._dropout(temp)
            ...         return temp
            ...
            >>> x = paddle.randn([10, 1], 'float32')
            >>> mylayer = MyLayer()
            >>> mylayer.eval()  # set mylayer._dropout to eval mode
            >>> out = mylayer(x)
            >>> mylayer.train()  # set mylayer._dropout to train mode
            >>> out = mylayer(x)
            >>> print(out)
            Tensor(shape=[10, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[-3.44879317],
             [ 0.        ],
             [ 0.        ],
             [-0.73825276],
             [ 0.        ],
             [ 0.        ],
             [ 0.64444798],
             [-3.22185946],
             [ 0.        ],
             [-0.68077987]])
    r   trainingNfloat32
name_scope
str | Noner   r1   r   r   c                   d| _         |(t          | j        j                  }t	          |          }t          j        |          | _        t          | j                  | _	        d| _
        || _        t                      | _        t                      | _        t                      | _        t#                      | _        t                      | _        t                      | _        t+          g g           | _        i | _        t                      | _        t                      | _        t                      | _        t                      | _        t                      | _        d| _        t                      | _        t                      | _        d S )NTF)r<   rK   ) r   rd   r   r   r\   r   generater@   r   _helper_built_dtyper"   _init_in_dynamic_moder   _parameters_buffersset!_non_persistable_buffer_names_set_sub_layers_loaddict_holderr   r8   rH   _forward_pre_hooks_forward_post_hooks#_forward_pre_hooks_with_kwargs_flag$_forward_post_hooks_with_kwargs_flag!_forward_post_hooks_always_called_cast_to_low_precision_state_dict_hooks_original_funcs)r   r   r   s      rC   r   zLayer.__init__  sM    01HIIJ+J77J%.z::(99%4%6%6"&==#14.&== + -2>>>!# MM 	 MM 	 
 MM 	0
 MM 	1
 MM 	.
 '+# MM 	  +}}rE   c                    | j         S r   )r   r   s    rC   _moduleszLayer._modules  s    rE   c                    t          |t                    st          dt          |                     | j                                         | j                            |           d S )Nz _modules must be dict-like, got )r   dictr   rx   r   clearupdater   values     rC   r  zLayer._modules  sd    %&& 	NLtE{{LLMMM   &&&&&rE   c                    | j         S r   )r   r  s    rC   _non_persistent_buffers_setz!Layer._non_persistent_buffers_set  s    55rE   c                    t          |t                    st          dt          |                     | j                                         | j                            |           d S )Nz/_non_persistent_buffers_set must be a set, got )r   r   r   rx   r   r  r	  r
  s     rC   r  z!Layer._non_persistent_buffers_set  sk    %%% 	O$u++OO   	.44666.55e<<<<<rE   Tmoder
   c                N   t          |t                    st          d          t                      rM|r&t	          j                                                     n%t	          j                                                     || _        | 	                                D ]	}||_        
| S )a=  

        Sets this Layer and all its sublayers to training mode.
        This only effects certain modules like `Dropout` and `BatchNorm`.

        Returns:
            Layer: self

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(100)

                >>> class MyLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._linear = paddle.nn.Linear(1, 1)
                ...         self._dropout = paddle.nn.Dropout(p=0.5)
                ...
                ...     def forward(self, input):
                ...         temp = self._linear(input)
                ...         temp = self._dropout(temp)
                ...         return temp
                ...
                >>> x = paddle.randn([10, 1], 'float32')
                >>> mylayer = MyLayer()
                >>> mylayer.eval()  # set mylayer._dropout to eval mode
                >>> out = mylayer(x)
                >>> mylayer.train()  # set mylayer._dropout to train mode
                >>> out = mylayer(x)
                >>> print(out)
                Tensor(shape=[10, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[-3.44879317],
                 [ 0.        ],
                 [ 0.        ],
                 [-0.73825276],
                 [ 0.        ],
                 [ 0.        ],
                 [ 0.64444798],
                 [-3.22185946],
                 [ 0.        ],
                 [-0.68077987]])

        z'training mode is expected to be boolean)
r   r   r   r"   r   _dygraph_tracer
train_mode	eval_moder   	sublayers)r   r  rA   s      rC   trainzLayer.train  s    \ $%% 	HFGGG  	8 8)++668888)++55777 ^^%% 	" 	"E!ENNrE   c                    t                      r%t          j                                                     d| _        |                                 D ]	}d|_        
| S )a  
        Sets this Layer and all its sublayers to evaluation mode.
        This only effects certain modules like `Dropout` and `BatchNorm`.

        Returns:
            Layer: self

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(100)
                >>> class MyLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._linear = paddle.nn.Linear(1, 1)
                ...         self._dropout = paddle.nn.Dropout(p=0.5)
                ...
                ...     def forward(self, input):
                ...         temp = self._linear(input)
                ...         temp = self._dropout(temp)
                ...         return temp
                ...
                >>> x = paddle.randn([10, 1], 'float32')
                >>> mylayer = MyLayer()
                >>> mylayer.eval()  # set mylayer._dropout to eval mode
                >>> out = mylayer(x)
                >>> print(out)
                Tensor(shape=[10, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[-1.72439659],
                 [ 0.31532824],
                 [ 0.01192369],
                 [-0.36912638],
                 [-1.63426113],
                 [-0.93169814],
                 [ 0.32222399],
                 [-1.61092973],
                 [ 0.77209264],
                 [-0.34038994]])

        F)r"   r   r  r  r   r  )r   rA   s     rC   evalz
Layer.evalL  s\    Z  	4%''11333^^%% 	# 	#E"ENNrE   fnCallable[[Self], None]c                t    |                                  D ]}|                    |            ||            | S )a	  

        Applies ``fn`` recursively to every sublayer (as returned by ``.sublayers()``)
        as well as self. Typical use includes initializing the parameters of a model.

        Parameters:
            fn (function): a function to be applied to each sublayer

        Returns:
            Layer, self

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> import paddle.nn as nn
                >>> paddle.seed(2023)

                >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))

                >>> def init_weights(layer):
                ...     if type(layer) == nn.Linear:
                ...         print('before init weight:', layer.weight.numpy())
                ...         new_weight = paddle.full(shape=layer.weight.shape, dtype=layer.weight.dtype, fill_value=0.9)
                ...         layer.weight.set_value(new_weight)
                ...         print('after init weight:', layer.weight.numpy())
                ...
                >>> net.apply(init_weights)

                >>> print(net.state_dict())
                before init weight: [[ 0.89611185  0.04935038]
                                     [-0.5888344   0.99266374]]
                after init weight: [[0.9 0.9]
                                    [0.9 0.9]]
                before init weight: [[-0.18615901 -0.22924072]
                                     [ 1.1517721   0.59859073]]
                after init weight: [[0.9 0.9]
                                    [0.9 0.9]]
                OrderedDict([('0.weight', Parameter containing:
                Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[0.89999998, 0.89999998],
                 [0.89999998, 0.89999998]])), ('0.bias', Parameter containing:
                Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,
                [0., 0.])), ('1.weight', Parameter containing:
                Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[0.89999998, 0.89999998],
                 [0.89999998, 0.89999998]])), ('1.bias', Parameter containing:
                Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,
                [0., 0.]))])
        )childrenapply)r   r  rA   s      rC   r  zLayer.apply  s?    f ]]__ 	 	EKKOOOO
4rE   rl   c                    | j         S )a  

        Full name for this layer, composed by name_scope + "/" + MyLayer.__class__.__name__

        Returns:
            str, full name of this layer.

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> class LinearNet(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__(name_scope = "demo_linear_net")
                ...         self._linear = paddle.nn.Linear(1, 1)
                ...
                ...     def forward(self, x):
                ...         return self._linear(x)
                ...
                >>> linear_net = LinearNet()
                >>> print(linear_net.full_name())
                demo_linear_net_0

        )r@   r  s    rC   	full_namezLayer.full_name  s    4 rE   F)prependwith_kwargsalways_callhook_ForwardPostHookr  r   r!  r   c                   t          | j        | j        | j        g          }|| j        |j        <   |rd| j        |j        <   |rd| j        |j        <   |r!| j                            |j        d           |S )a	  

        Register a forward post-hook for Layer. The hook will be called after `forward` function has been computed.

        It should have the following form, `input` and `output` of the `hook` is `input` and `output` of the `Layer` respectively.
        User can use forward post-hook to change the output of the Layer or perform information statistics tasks on the Layer.

        hook(Layer, input, output) -> None or modified output

        Parameters:
            hook(function): a function registered as a forward post-hook
            prepend (bool): If ``True``, the provided ``hook`` will be fired
                before all existing ``forward_post`` hooks on this
                :class:`paddle.nn.Layer`.
                Default: ``False``
            with_kwargs (bool): If ``True``, the ``hook`` will be passed the
                kwargs given to the forward function.
                Default: ``False``
            always_call (bool): If ``True`` the ``hook`` will be run regardless of
                whether an exception is raised while calling the Module.
                Default: ``False``

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

        Examples:
            .. code-block:: python

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

                >>> # the forward_post_hook change the output of the layer: output = output * 2
                >>> def forward_post_hook(layer, input, output):
                ...     # user can use layer, input and output for information statistics tasks
                ...
                ...     # change the output
                ...     return output * 2
                ...
                >>> linear = paddle.nn.Linear(13, 5)

                >>> # register the hook
                >>> forward_post_hook_handle = linear.register_forward_post_hook(forward_post_hook)

                >>> value1 = np.arange(26).reshape(2, 13).astype("float32")
                >>> in1 = paddle.to_tensor(value1)

                >>> out0 = linear(in1)

                >>> # remove the hook
                >>> forward_post_hook_handle.remove()

                >>> out1 = linear(in1)

                >>> # hook change the linear's output to output * 2, so out0 is equal to out1 * 2.
                >>> assert (out0.numpy() == (out1.numpy()) * 2).any()

        r   TFlast)r   r   r   r   r   move_to_end)r   r"  r  r   r!  hook_remove_helpers         rC   register_forward_post_hookz Layer.register_forward_post_hook  s    B .$96
 
 
 AE !3!<= 	  5"+  	  2"+  	$00"+% 1    "!rE   )r  r   _ForwardPreHookc                   t          | j        | j                  }|| j        |j        <   |rd| j        |j        <   |r!| j                            |j        d           |S )a	  

        Register a forward pre-hook for Layer. The hook will be called before `forward` function has been computed.

        It should have the following form, `input` of the `hook` is `input` of the `Layer`,
        hook can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if
        a single value is returned(unless that value is already a tuple).
        User can use forward pre-hook to change the input of the Layer or perform information statistics tasks on the Layer.

        hook(Layer, input) -> None or modified input

        Parameters:
            hook(function): a function registered as a forward pre-hook
            prepend (bool): If ``True``, the provided ``hook`` will be fired
                before all existing ``forward_pre`` hooks on this
                :class:`paddle.nn.Layer`.
                Default: ``False``
            with_kwargs (bool): If true, the ``hook`` will be passed the kwargs
                given to the forward function.
                Default: ``False``

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

        Examples:
            .. code-block:: python

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

                >>> # the forward_pre_hook change the input of the layer: input = input * 2
                >>> def forward_pre_hook(layer, input):
                ...     # user can use layer and input for information statistics tasks
                ...
                ...     # change the input
                ...     input_return = (input[0] * 2)
                ...     return input_return
                ...
                >>> linear = paddle.nn.Linear(13, 5)

                >>> # register the hook
                >>> forward_pre_hook_handle = linear.register_forward_pre_hook(forward_pre_hook)

                >>> value0 = np.arange(26).reshape(2, 13).astype("float32")
                >>> in0 = paddle.to_tensor(value0)
                >>> out0 = linear(in0)

                >>> # remove the hook
                >>> forward_pre_hook_handle.remove()

                >>> value1 = value0 * 2
                >>> in1 = paddle.to_tensor(value1)
                >>> out1 = linear(in1)

                >>> # hook change the linear's input to input * 2, so out0 is equal to out1.
                >>> assert (out0.numpy() == out1.numpy()).any()
        r   TFr%  )r   r   r   r   r'  )r   r"  r  r   r(  s        rC   register_forward_pre_hookzLayer.register_forward_pre_hook2  s    @ .# D
 
 
 @D 2 ;< 	  4"+  	#//"+% 0    "!rE   shaper4   attrParamAttrLike | NoneDTypeLike | Noneis_biasdefault_initializerInitializer | NonedevicePlaceLike | Noner   c                    t          j        |          }t          |t                    r|dk    rd}| j                            ||||||          S )aB	  Create parameters for this layer.

        Parameters:
            shape(list): Shape of the parameter. The data type in the list must be int.
            attr(ParamAttr, optional): Parameter attribute of weight. Please refer to :ref:`api_paddle_ParamAttr`. Default: None.
            dtype(str, optional): Data type of this parameter.
                If set str, it can be "bool",  "float16", "float32", "float64",
                "int8", "int16", "int32", "int64", "uint8" or "uint16". Default: "float32".
            is_bias(bool, optional): if this is a bias parameter. Default: False.
            default_initializer(Initializer, optional): the default initializer for this parameter.
                If set None, default initializer will be set to paddle.nn.initializer.Xavier and paddle.nn.initializer.Constant
                for non-bias and bias parameter, respectively. Default: None.
            device(PlaceLike, optional): the device place for the parameter. Default: None.

        Returns:
            :Tensor, created parameter.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(2023)

                >>> class MyLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._linear = paddle.nn.Linear(1, 1)
                ...         w_tmp = self.create_parameter([1,1])
                ...         self.add_parameter("w_tmp", w_tmp)
                ...
                ...     def forward(self, input):
                ...         return self._linear(input)
                ...
                >>> mylayer = MyLayer()
                >>> for name, param in mylayer.named_parameters():
                ...     print(name, param)      # will print w_tmp,_linear.weight,_linear.bias
                w_tmp Parameter containing:
                Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[0.06979191]])
                _linear.weight Parameter containing:
                Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[1.26729357]])
                _linear.bias Parameter containing:
                Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [0.])
         Nr4  )r   r   r   rl   r   create_parameter)r   r-  r.  r   r1  r2  r4  	temp_attrs           rC   r9  zLayer.create_parameter  s`    n M$''	i%% 	)r//I|,,ueW.A& - 
 
 	
rE   targetr   c                v   |                     d          \  }}}|                     |          }t          ||          s*t          |                                dz   |z   dz             t          ||          }t          |t          j        j	        t          j
        f          st          d|z   dz             |S )a  
        Return the parameter given by ``target`` if it exists, otherwise throw an error.
        Parameters:
            target(str): The fully-qualified string name of the Parameter to look for.

        Returns:
            Parameter: The Parameter referenced by ``target``.
        . has no attribute ``z` is not an nn.Parameter)
rpartitionget_sublayerhasattrAttributeError	_get_namegetattrr   paddler   r   r   )r   r;  module_path_
param_namemodr   s          rC   r   zLayer.get_parameter  s     &,%6%6s%;%;"Q
#00==sJ'' 	 "77*DsJ   &-S*%=%=%&)"5v}!EFF 	P z!14N!NOOOrE   z2.0.0zpaddle.nn.Layer.create_tensorz(New api in create_tensor, easier to use.)since	update_toreasonrb   persistablebool | Nonec                .   |d                     | j        |g          }n.t          j        d                     | j        dg                    }| j        j                                                            |||t          j	        j
        j                  S )a,  

        Create Tensor for this layer.

        Parameters:
            name(str, optional): name of the tensor. Please refer to :ref:`api_guide_Name` . Default: None

            persistable(bool, optional): if set this tensor persistable. Default: False

            dtype(str, optional): data type of this parameter. If set str, it can be "bool", "float16", "float32", "float64","int8", "int16", "int32", "int64", "uint8" or "uint16". If set None, it will be "float32". Default: None

        Returns:
            Tensor, created Tensor.

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> class MyLinear(paddle.nn.Layer):
                ...     def __init__(self,
                ...                 in_features,
                ...                 out_features):
                ...         super().__init__()
                ...         self.linear = paddle.nn.Linear( 10, 10)
                ...
                ...         self.back_var = self.create_variable(name = "linear_tmp_0", dtype=self._dtype)
                ...
                ...     def forward(self, input):
                ...         out = self.linear(input)
                ...         paddle.assign( out, self.back_var)
                ...
                ...         return out

        Nr=  _generated_varrb   rN  r   rx   rm   r@   r   r   r   r   r;   
create_varr   r   VarTypeDENSE_TENSORr   rb   rN  r   var_names        rC   create_variablezLayer.create_variable  s    \ xx$ 788HH"+$/+;<== H |(6688CC#%2	 D 
 
 	
rE   c                .   |d                     | j        |g          }n.t          j        d                     | j        dg                    }| j        j                                                            |||t          j	        j
        j                  S )a]  

        Create Tensor for this layer.

        Parameters:
            name(str, optional): name of the tensor. Please refer to :ref:`api_guide_Name` . Default: None.
            persistable(bool, optional): if set this tensor persistable. Default: False.
            dtype(str, optional): data type of this parameter.
                If set str, it can be "bool",  "float16", "float32", "float64",
                "int8", "int16", "int32", "int64", "uint8" or "uint16".
                If set None, it will be "float32". Default: None.

        Returns:
            Tensor, created Tensor.

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> class MyLinear(paddle.nn.Layer):
                ...     def __init__(self,
                ...                  in_features,
                ...                  out_features):
                ...         super().__init__()
                ...         self.linear = paddle.nn.Linear(10, 10)
                ...
                ...         self.back_var = self.create_tensor(name = "linear_tmp_0", dtype=self._dtype)
                ...
                ...     def forward(self, input):
                ...         out = self.linear(input)
                ...         paddle.assign(out, self.back_var)
                ...
                ...         return out

        Nr=  rQ  rR  rS  rW  s        rC   create_tensorzLayer.create_tensor  s    T xx$ 788HH"+$/+;<== H |(6688CC#%2	 D 
 
 	
rE   rw   recurselist[Tensor]c                F    d |                      |          D             }|S )a  

        Returns a list of all Parameters from current layer and its sub-layers.

        Parameters:
            include_sublayers (bool, optional): Whether to return the parameters of the sublayer.
                If True, the returned list contains the parameters of the sublayer.
                Default: True.

        Returns:
            list, list of Tensor, a list of Parameters.

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(100)

                >>> linear = paddle.nn.Linear(1, 1)
                >>> print(linear.parameters())
                [Parameter containing:
                Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[0.18551230]]), Parameter containing:
                Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [0.])]

        c                    g | ]\  }}|S r~   r~   )r   rH  r   s      rC   
<listcomp>z$Layer.parameters.<locals>.<listcomp>k  s,     
 
 
5 
 
 
rE   rw   )named_parametersr   rw   r   s      rC   
parameterszLayer.parametersN  s?    :
 
 11"3 2  
 
 
 
rE   c                H   g d}t          |t          j        t          j        f          st	          |          t
          u r||v rt          |t
          t          j        f          rt          j        |          }|| _        | 	                                D ]	}||_        
| 
                    d          D ]\  }}|                    d|           |                     d          D ]\  }}|                    d|           | S t          dt          |          z             )a  

        Casts all parameters and buffers to dtype and then return the Layer.

        Parameters:
            dtype(str|paddle.dtype|numpy.dtype): target data type of layer.
                If set str, it can be "bool", "bfloat16", "float16", "float32", "float64",
                "int8", "int16", "int32", "int64", "uint8", "complex64", "complex128".
                Default: None

        Returns:
            Layer, self

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> import paddle.nn as nn
                >>> weight_attr = paddle.ParamAttr(name="weight",initializer=paddle.nn.initializer.Constant(value=1.5))
                >>> bias_attr = paddle.ParamAttr(name="bias",initializer=paddle.nn.initializer.Constant(value=2.5))

                >>> linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr).to(device="cpu",dtype="float32")
                >>> print(linear)
                Linear(in_features=2, out_features=2, dtype=float32)
                >>> print(linear.parameters())
                [Parameter containing:
                Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
                    [[1.50000000, 1.50000000],
                        [1.50000000, 1.50000000]]), Parameter containing:
                Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,
                    [2.50000000, 2.50000000])]

                >>> linear=linear.astype("int8")
                >>> print(linear)
                Linear(in_features=2, out_features=2, dtype=paddle.int8)
                >>> print(linear.parameters())
                >>> # doctest: +SKIP("There are bugs in the `Layer.astype`. For details, refer to the following webpage: https://github.com/PaddlePaddle/Paddle/issues/76614")
                [Parameter containing:
                Tensor(shape=[2, 2], dtype=int8, place=Place(cpu), stop_gradient=False,
                    [[1, 1],
                        [1, 1]]), Parameter containing:
                Tensor(shape=[2], dtype=int8, place=Place(cpu), stop_gradient=False,
                    [2, 2])]
                >>> # doctest: -SKIP

        bfloat16float16r   float64int8int16int32int64uint8	complex64
complex128r   Tra  Ndtype value error, must be 'bfloat16', 'float16', 'float32', 'float64', 'int8', 'int16', 'int32', 'int64', 'uint8', 'complex64', 'complex128', 'bool', or paddle.dtype, numpy.dtype, but receive )r   rF  r   nprx   rl   r   r    r   r  rb  _tonamed_bufferstor   )r   r   valid_dtypesrA   rH  r   buffers          rC   astypezLayer.astypes  s@   ^
 
 
 uv|RX677	E{{c!!%%%#rx11 D!<UCCDK)) % %$ 11D1II ' '5		$&&&&!//$/GG ' '	6		$&&&&K Te**  rE   Iterable[Layer]c              #  F   K   |                                  D ]	\  }}|V  
dS )ar  

        Returns an iterator over immediate children layers.

        Yields:
            Layer: a child layer

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> linear1 = paddle.nn.Linear(10, 3)
                >>> linear2 = paddle.nn.Linear(3, 10, bias_attr=False)
                >>> model = paddle.nn.Sequential(linear1, linear2)

                >>> layer_list = list(model.children())

                >>> print(layer_list)
                [Linear(in_features=10, out_features=3, dtype=float32), Linear(in_features=3, out_features=10, dtype=float32)]

        N)named_children)r   rH  rA   s      rC   r  zLayer.children  s<      . ++-- 	 	HAuKKKK	 	rE   Iterable[tuple[str, Layer]]c              #     K   t                      }| j                                        D ]&\  }}|||vr|                    |           ||fV  'dS )a  Returns an iterator over immediate children layers, yielding both
        the name of the layer as well as the layer itself.

        Yields:
            (string, Layer): Tuple containing a name and child layer

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> linear1 = paddle.nn.Linear(10, 3)
                >>> linear2 = paddle.nn.Linear(3, 10, bias_attr=False)
                >>> model = paddle.nn.Sequential(linear1, linear2)
                >>> for prefix, layer in model.named_children():
                ...     print(prefix, layer)
                0 Linear(in_features=10, out_features=3, dtype=float32)
                1 Linear(in_features=3, out_features=10, dtype=float32)
        N)r   r   rI   add)r   memorb   rA   s       rC   r{  zLayer.named_children  sm      ( uu+1133 	" 	"KD% U$%6%6Ek!!!	" 	"rE   include_selflist[Layer]c                F    d |                      |          D             }|S )a  

        Returns a list of sub layers.

        Parameters:
            include_self(bool, optional): Whether return self as sublayers. Default: False.

        Returns:
            list of Layer, a list of sub layers.

        Examples:
            .. code-block:: pycon

                >>> import paddle

                >>> class MyLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._linear = paddle.nn.Linear(1, 1)
                ...         self._dropout = paddle.nn.Dropout(p=0.5)
                ...
                ...     def forward(self, input):
                ...         temp = self._linear(input)
                ...         temp = self._dropout(temp)
                ...         return temp
                >>> mylayer = MyLayer()
                >>> print(mylayer.sublayers())
                [Linear(in_features=1, out_features=1, dtype=float32), Dropout(p=0.5, axis=None, mode=upscale_in_train, inplace=False)]

        c                    g | ]\  }}|S r~   r~   )r   rH  rA   s      rC   r`  z#Layer.sublayers.<locals>.<listcomp>  s,     
 
 
5 
 
 
rE   )r  named_sublayers)r   r  r   s      rC   r  zLayer.sublayers  s8    >
 
 00l0KK
 
 
 
rE   r7  prefixremove_duplicateIterable[tuple[str, Tensor]]c              #    K   t                      rt                      st                      nt                      }|r|                     |d|          nt          |g| g          }|D ]V\  }}|j                                        }|D ]5\  }	}
|
|
|v r|r|                    |
           ||rdndz   |	z   }||
fV  6WdS )a	  
        Returns an iterator over all parameters in the Layer, yielding tuple of name and parameter.

        Parameters:
            prefix(str, optional): Prefix to prepend to all parameter names. Default: ''.
            include_sublayers(bool, optional): Whether include the parameters of sublayers.
                If True, also include the named parameters from sublayers. Default: True.
            remove_duplicate(bool, optional): Whether to remove duplicated parameters in the result.
                Default: True.

        Yields:
            (string, Parameter): Tuple of name and Parameter

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(100)

                >>> fc1 = paddle.nn.Linear(10, 3)
                >>> fc2 = paddle.nn.Linear(3, 10, bias_attr=False)
                >>> model = paddle.nn.Sequential(fc1, fc2)
                >>> for name, param in model.named_parameters():
                ...     print(name, param)
                0.weight Parameter containing:
                Tensor(shape=[10, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[ 0.07276392, -0.39791510, -0.66356444],
                 [ 0.02143478, -0.18519843, -0.32485050],
                 [-0.42249614,  0.08450919, -0.66838276],
                 [ 0.38208580, -0.24303678,  0.55127048],
                 [ 0.47745085,  0.62117910, -0.08336520],
                 [-0.28653207,  0.47237599, -0.05868882],
                 [-0.14385653,  0.29945642,  0.12832761],
                 [-0.21237159,  0.38539791, -0.62760031],
                 [ 0.02637231,  0.20621127,  0.43255770],
                 [-0.19984481, -0.26259184, -0.29696006]])
                0.bias Parameter containing:
                Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=False,
                [0., 0., 0.])
                1.weight Parameter containing:
                Tensor(shape=[3, 10], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[ 0.01985580, -0.40268910,  0.41172385, -0.47249708, -0.09002256,
                 -0.00533628, -0.52048630,  0.62360322,  0.20848787, -0.02033746],
                 [ 0.58281910,  0.12841827,  0.12907702,  0.02325618, -0.07746267,
                 0.31950659, -0.37924835, -0.59209681, -0.11732036, -0.58378261],
                 [-0.62100595,  0.22293305,  0.28229684, -0.03687060, -0.59323978,
                 0.08411229,  0.53275704,  0.40431368,  0.03171402, -0.17922515]])
        Tr  r  r  Nr=  r7  )	r#   r   r   r   r  r   r   rI   r~  )r   r  rw   r  
params_setr  layer_prefixsublayerparamskeyr   rb   s               rC   rb  zLayer.named_parameters  s     p &--N0A0C0CNHJJJ 	 !'D  !!1 !    fXv&& 	 '6 	" 	""L()//11F$ " "
U=EZ$7$7# *NN5)))#l'BssCcIEk!!!!"	" 	"rE   
layers_setset[Layer] | Nonec              #  
  K   |t                      }|r!| |vr|r|                    |            || fV  | j                                        D ]3\  }}|||rdndz   |z   }|                    |d||          E d{V  4dS )a		  
        Returns an iterator over all sublayers in the Layer, yielding tuple of name and sublayer.
        The duplicate sublayer will only be yielded once.

        Parameters:
            prefix(str, optional): Prefix to prepend to all parameter names. Default: ''.
            include_self(bool, optional): Whether include the Layer itself. Default: False.
            layers_set(set, optional): The set to record duplicate sublayers. Default: None.
            remove_duplicate(bool, optional): Whether to remove duplicated sublayers in the result.
                Default: True.

        Yields:
            (string, Layer): Tuple of name and Layer

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> fc1 = paddle.nn.Linear(10, 3)
                >>> fc2 = paddle.nn.Linear(3, 10, bias_attr=False)
                >>> model = paddle.nn.Sequential(fc1, fc2)
                >>> for prefix, layer in model.named_sublayers():
                ...     print(prefix, layer)
                0 Linear(in_features=10, out_features=3, dtype=float32)
                1 Linear(in_features=3, out_features=10, dtype=float32)

                >>> l = paddle.nn.Linear(10, 3)
                >>> model = paddle.nn.Sequential(l, l)
                >>> for prefix, layer in model.named_sublayers(include_self=True, remove_duplicate=True):
                ...     print(prefix, layer)
                 Sequential(
                  (0): Linear(in_features=10, out_features=3, dtype=float32)
                  (1): Linear(in_features=10, out_features=3, dtype=float32)
                )
                0 Linear(in_features=10, out_features=3, dtype=float32)

                >>> l = paddle.nn.Linear(10, 3)
                >>> model = paddle.nn.Sequential(l, l)
                >>> for prefix, layer in model.named_sublayers(include_self=True, remove_duplicate=False):
                ...     print(prefix, layer)
                 Sequential(
                  (0): Linear(in_features=10, out_features=3, dtype=float32)
                  (1): Linear(in_features=10, out_features=3, dtype=float32)
                )
                0 Linear(in_features=10, out_features=3, dtype=float32)
                1 Linear(in_features=10, out_features=3, dtype=float32)

        Nr=  r7  Tr  r  r  r  )r   r~  r   rI   r  )r   r  r  r  r  r  rA   r  s           rC   r  zLayer.named_sublayersk  s      p J 	D
22 %t$$$$,*0022 		 		JC}!F%:SS;cAL,,#!%!1	 -          			 		rE   Iterator[Layer]c              #  F   K   |                                  D ]	\  }}|V  
dS )z
        Return an iterator over all modules in the network.

        Yields:
            Layer: a layer in the network.

        N)named_modules)r   rH  modules      rC   moduleszLayer.modules  s<       ++-- 	 	IAvLLLL	 	rE   r  c                <    d}|}|                      ||||          S )a4  
        Returns an iterator over all sublayers in the Layer, yielding tuple of name and sublayer.
        The duplicate sublayer will only be yielded once.

        Parameters:
            memo(set, optional): The set to record duplicate sublayers. Default: None.
            prefix(str, optional): Prefix to prepend to all parameter names. Default: ''.
            remove_duplicate(bool, optional): Whether to remove duplicated sublayers in the result.
                Default: True.

        Yields:
            (string, Layer): Tuple of name and Layer
        Tr  r  )r   r  r  r  r  r  s         rC   r  zLayer.named_modules  s7    & 
##%!-	 $ 
 
 	
rE   
persistenttensorc                h   d| j         vrt          d          t          |t                    s%t	          dt          |          j         d          d|v rt          d          |dk    rt          d          t          | |          r|| j	        vrt          d| d	          |Gt          |          t          j        j        k    s%t	          dt          |          j         d          || j	        |<   |r| j                            |           d
S | j                            |           d
S )a  
        Registers a tensor as buffer into the layer.

        `buffer` is a non-trainable tensor and will not be updated by optimizer,
        but is necessary for evaluation and inference. For example, the mean and variance in BatchNorm layers.
        The registered buffer is persistable by default, and will be saved into
        `state_dict` alongside parameters. If set persistable=False, it registers
        a non-persistable buffer, so that it will not be a part of `state_dict` .

        Buffers can be accessed as attributes using given names.

        Parameters:
            name (string): name of the buffer. The buffer can be accessed
                from this layer using the given name
            tensor (Tensor): the tensor to be registered as buffer.
            persistable (bool): whether the buffer is part of this layer's
                state_dict.

        Returns:
            None

        Examples:
            .. code-block:: python

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

                >>> linear = paddle.nn.Linear(10, 3)
                >>> value = np.array([0]).astype("float32")
                >>> buffer = paddle.to_tensor(value)
                >>> linear.register_buffer("buf_name", buffer, persistable=True)

                >>> # get the buffer by attribute.
                >>> print(linear.buf_name)
                Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.])

        r   )super().__init__() should be called firstz4The name of buffer should be a string, but received r=  zThe name of buffer can not contain `.`, because when you access the newly added buffer in the form of `self.**.**`, it will cause AttributeError.r7  z$The name of buffer can not be empty.zattribute '' already exists.Nz>The registered buffer should be a Paddle.Tensor, but received )__dict__r   r   rl   r   rx   r   KeyErrorrB  r   r   eagerr   r   discardr~  )r   rb   r  rN  s       rC   register_bufferzLayer.register_buffer  sl   V T]**HIIID#&& 	A]tDzzGZ]]]   D[[F  
 RZZABBBT4   	AT%>%>@@@@AAAf9J)J)JiQUV\Q]Q]Qfiii   #)DM$ A6>>tDDDDD6::4@@@@@rE   c                F    d |                      |          D             }|S )a\  

        Returns a list of all buffers from current layer and its sub-layers.

        Parameters:
            include_sublayers(bool, optional): Whether include the buffers of sublayers. If True, also include the buffers from sublayers. Default: True.

        Returns:
            list of Tensor, a list of buffers.

        Examples:
            .. code-block:: python

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

                >>> linear = paddle.nn.Linear(10, 3)
                >>> value = np.array([0]).astype("float32")
                >>> buffer = paddle.to_tensor(value)
                >>> linear.register_buffer("buf_name", buffer, persistable=True)

                >>> print(linear.buffers())
                [Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.])]

        c                    g | ]\  }}|S r~   r~   )r   rH  rw  s      rC   r`  z!Layer.buffers.<locals>.<listcomp>=  s,     
 
 
6 
 
 
rE   ra  )rt  rc  s      rC   bufferszLayer.buffers!  s?    8
 
!//"3 0  
 
 
 
rE   c                2   |                     d          \  }}}|                     |          }t          ||          s*t          |                                dz   |z   dz             t          ||          }||j        vrt          d|z   dz             |S )a  
        Return the buffer given by ``target`` if it exists, otherwise throw an error.

        See the docstring for ``get_sublayer`` for a more detailed
        explanation of this method's functionality as well as how to
        correctly specify ``target``.

        Parameters:
            target(str): The fully-qualified string name of the buffer to look for.

        Returns:
            Tensor: The buffer referenced by ``target``.
        r=  r>  r?  z` is not a buffer)r@  rA  rB  rC  rD  rE  r   )r   r;  rG  rH  buffer_namerJ  rw  s          rC   
get_bufferzLayer.get_bufferE  s     '-&7&7&<&<#Q,,sK(( 	 "77+EK   k**cl** {!25H!HIIIrE   c              #  0  K   t                      }|r|                     |d|          nt          |g| g          }|D ]V\  }}|j                                        }|D ]5\  }	}
|
|
|v r|r|                    |
           ||rdndz   |	z   }||
fV  6WdS )a  
        Returns an iterator over all buffers in the Layer, yielding tuple of name and Tensor.

        Parameters:
            prefix(str, optional): Prefix to prepend to all buffer names. Default: ''.
            include_sublayers(bool, optional): Whether include the buffers of sublayers.
                If True, also include the named buffers from sublayers. Default: True.
            remove_duplicate(bool, optional): Whether to remove duplicated buffers in the result.
                Default: True.

        Yields:
            (string, Tensor): Tuple of name and tensor

        Examples:
            .. code-block:: python

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

                >>> fc1 = paddle.nn.Linear(10, 3)
                >>> buffer1 = paddle.to_tensor(np.array([0]).astype("float32"))
                >>> # register a tensor as buffer by specific `persistable`
                >>> fc1.register_buffer("buf_name_1", buffer1, persistable=True)

                >>> fc2 = paddle.nn.Linear(3, 10)
                >>> buffer2 = paddle.to_tensor(np.array([1]).astype("float32"))
                >>> # register a buffer by assigning an attribute with Tensor.
                >>> # The `persistable` can only be False by this way.
                >>> fc2.buf_name_2 = buffer2

                >>> model = paddle.nn.Sequential(fc1, fc2)

                >>> # get all named buffers
                >>> for name, buffer in model.named_buffers():
                ...     print(name, buffer)
                0.buf_name_1 Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [0.])
                1.buf_name_2 Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
                [1.])
        Tr  Nr=  r7  )r   r  r   r   rI   r~  )r   r  rw   r  buffers_setr  r  r  r  r  rw  rb   s               rC   rt  zLayer.named_buffersc  s      ^ ee !'D  !!1 !    fXv&& 	 '6 	# 	#"L('--//G& # #V>V{%:%:# ,OOF+++#l'BssCcIFl""""#	# 	#rE   set_to_zeroc                l    |                                  D ]}|j        r|                    |           dS )ad  
        Clear the gradients of all parameters for this layer.

        Args:
            set_to_zero (bool, optional): Whether to set the trainable parameters'
                gradients to zero or None. Default is True.

        Returns:
            None

        Examples:
            .. code-block:: python

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

                >>> value = np.arange(26).reshape(2, 13).astype("float32")
                >>> a = paddle.to_tensor(value)
                >>> linear = paddle.nn.Linear(13, 5)
                >>> adam = paddle.optimizer.Adam(learning_rate=0.01,
                ...                              parameters=linear.parameters())
                >>> out = linear(a)
                >>> out.backward()
                >>> adam.step()
                >>> linear.clear_gradients()

        N)rd  	trainableclear_gradient)r   r  ps      rC   clear_gradientszLayer.clear_gradients  sF    8 "" 	. 	.A{ .  ---	. 	.rE   argsr   kwargsc                    d S r   r~   )r   r  r  s      rC   _build_oncezLayer._build_once  s    rE   rB   c                |   	 d 	t                      	 fd}	  |            S # t          $ r  j                                        D ]k\  }}| j        v r]|vrY	 | j        v r | 	          }n | 	          }||	=# t          $ r!}t          j        d|           Y d }~cd }~ww xY wl w xY w)Nc                    	j                                         D ]\  } }| 	j        v rQ |	          }|At          |t                    rt          |          dk    r|\  Kt          d| d          _ |	          }|t          |t                    s|f}|	j        s 	j        i  d	_        t                      rTt          j        	j        j        t          j        j                  5   	j        i d d d            n# 1 swxY w Y   n>t#          	j        j                  5   	j        i d d d            n# 1 swxY w Y   	j                                        D ]L\  } }| 	j        v r                    |            | 	j        v r |	          }n |	          }||MS )N   zPforward pre-hook must return None or a tuple of (new_args, new_kwargs), but got r=  T)r   rI   r   r   r   r:   RuntimeErrorr   r  r*   r   RecordEventr   r   TracerEventTypeForwardforwardr$   r   r   r~  r   )
hook_idforward_pre_hookargs_kwargs_resulthook_resultforward_post_hookcalled_always_called_hooksrB   r  rM   r   s
        rC   innerz'Layer._dygraph_call_func.<locals>.inner  s    .2-D-J-J-L-L - -))dFFF)9)9$)O)O&)5&'95AA	 #$6 7 71 < <-?NFFF".!\FX!\ !\ !\# #  6 #3"24"@"@K".)+u== 9+6.K!,; #  &3F333"!! >)N+X-E-M  > > +dlF=f==G> > > > > > > > > > > > > > >
 !!899 > >*dlF=f==G> > > > > > > > > > > > > > > /3.F.L.L.N.N * ***dDDD.227;;;dGGG"3"3ffg# #KK #4"3D&'"J"JK*)GNs$   :DDD9EEEzuforward hook with ``always_call=True`` raised an exception that was silenced as another error was raised in forward: )r   	Exceptionr   rI   r   r   r>   r?   )
r   rB   r  r  r  r  r  er  rM   s
   ```     @@rC   _dygraph_call_funczLayer._dygraph_call_func  sa   %(UU"5	 5	 5	 5	 5	 5	 5	 5	 5	n	577N 	 	 	.2.F.L.L.N.N ! !**tEEE%???!"d&OOO*;*; $ffg+ +KK +<*; $fg+ +K '2&1G$ ! ! ! _YZ_ _   !! 1	s3   	* 5B; )B
	B;

B5B0+B;0B55B;c                    t                      sd| j        s]| j        sV| j        j        t
          j        u s| j        r7t                      r)t                      rt                      r | j
        |i |S  | j        |i |S r   )r   r   r   r   r  r6   r   r"   r*   r   r  r  r   rB   r  s      rC   __call__zLayer.__call__   s    "$$
	>,
	> -
	> +u/@@@DK@!! A%'' A+A+C+C A  4<26222*4*F=f===rE   c                    t           )z
        Defines the computation performed at every call.
        Should be overridden by all subclasses.

        Parameters:
            *inputs(tuple): unpacked tuple arguments
            **kwargs(dict): unpacked dict arguments
        )NotImplementedErrorr  s      rC   r  zLayer.forward-  s
     "!rE   c                     t          d          )Nz"Layer shouldn't implement backward)r   )r   rB   s     rC   backwardzLayer.backward8  s    =>>>rE   r  c                L    t          |t                    s|J || j        |<   |S )a+  

        Adds a sub Layer instance.

        Added sublayer can be accessed by self.name

        Parameters:
            name(str): name of this sublayer.
            sublayer(Layer): an instance of Layer.
        Returns:
            Layer, the sublayer passed in.

        Examples:
            .. code-block:: python

                >>> import paddle

                >>> class MySequential(paddle.nn.Layer):
                ...     def __init__(self, *layers):
                ...         super().__init__()
                ...         if len(layers) > 0 and isinstance(layers[0], tuple):
                ...             for name, layer in layers:
                ...                 self.add_sublayer(name, layer)
                ...         else:
                ...             for idx, layer in enumerate(layers):
                ...                 self.add_sublayer(str(idx), layer)
                ...
                ...     def forward(self, input):
                ...         for layer in self._sub_layers.values():
                ...             input = layer(input)
                ...         return input
                ...
                >>> fc1 = paddle.nn.Linear(10, 3)
                >>> fc2 = paddle.nn.Linear(3, 10, bias_attr=False)
                >>> model = MySequential(fc1, fc2)
                >>> for prefix, layer in model.named_sublayers():
                ...     print(prefix, layer)
                0 Linear(in_features=10, out_features=3, dtype=float32)
                1 Linear(in_features=3, out_features=10, dtype=float32)
        )r   r6   r   )r   rb   r  s      rC   add_sublayerzLayer.add_sublayer;  s2    R (E**>h.>.>>!)rE   c                J   |dk    r| S |                     d          }| }|D ]}t          ||          s*t          |                                dz   |z   dz             t	          ||          }t          |t          j        j                  st          d|z   dz             |S )a  
        Return the submodule given by ``target`` if it exists, otherwise throw an error.

        Parameters:
            target(str): The fully-qualified string name of the submodule to look for.

        Returns:
            Layer: The sublayer referenced by ``target``.
        r7  r=  r>  r?  ` is not an nn.Layer)	ri   rB  rC  rD  rE  r   rF  r   r6   )r   r;  atomsrJ  items        rC   rA  zLayer.get_sublayeri  s     R<<K!<<,,# 		J 		JD3%% $MMOO&;;dBSH   #t$$Cc69?33 J$S4Z2H%HIIIJ 
rE   rA   r  strictc                   |dk    rt          d          |                    d          }t          |t          j        j                  s"t          ddt          |           z             t          |          dk    r| }n2d                    |dd                   }| 	                    |          }|rFt          ||d                   s0t          |                                d	z   |d         z   d
z             t          ||d                   rPt          ||d                   }t          |t          j        j                  st          d
|d         z   dz             t          ||d         |           dS )aD  
        Set the sublayer given by ``target`` if it exists, otherwise throw an error.

        Parameters:
            target(str): The fully-qualified string name of the sublayer to look for.
            layer(Layer): The layer to set the sublayer to.
            strict(bool): If ``False``, the method will replace an existing sublayer
                or create a new sublayer if the parent module exists. If ``True``,
                the method will only attempt to replace an existing sublayer and throw an error
                if the sublayer doesn't already exist.
        r7  z.Cannot set the sublayer without a target name!r=  z`modulez` is not an nn.Layer, found rg   Nr   r>  r?  r  )r   ri   r   rF  r   r6   rx   r:   rm   rA  rB  rC  rD  rE  setattr)r   r;  rA   r  r  parent
parent_keyrJ  s           rC   set_sublayerzLayer.set_sublayer  s}    R<<MNNN!<<,,%11 	!MU!M!MM   u::??&*FF%*--J&&z22F 	'&%)44 	   ""%::U2YFL   659%% 	O&%),,Cc69?33 O$S59_7M%MNNNb	5)))))rE   Layer | Nonec                2    |                      ||           dS )z
        Adds a sub layer instance. Added layer can be accessed by self.name

        Parameters:
            name(str): name of this sublayer.
            layer(Layer): an instance of Layer.
        Returns:
            None
        N)r  )r   rb   r  s      rC   
add_modulezLayer.add_module  s      	$'''''rE   	parameterc                   d| j         vrt          d          t          |t                    s%t	          dt          |          j         d          d|v rt          d          |dk    rt          d          t          | |          r|| j	        vrt          d| d	          |Pt          |t          j        t          j        j        f          s%t	          dt          |          j         d          |
d
| j	        |<   t          | j                  dk    rF|j        | j        v sJ d|j         d            |                    | j        |j                            || j	        |<   |S )a  Adds a Parameter instance.

        Added parameter can be accessed by self.name

        Parameters:
            name(str): name of this sublayer.
            parameter(Parameter): an instance of Parameter.
        Returns:
            Parameter, the parameter passed in.
        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(100)

                >>> class MyLayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self._linear = paddle.nn.Linear(1, 1)
                ...         w_tmp = self.create_parameter([1,1])
                ...         self.add_parameter("w_tmp", w_tmp)
                ...
                ...     def forward(self, input):
                ...         return self._linear(input)
                ...
                >>> mylayer = MyLayer()
                >>> for name, param in mylayer.named_parameters():
                ...     print(name, param)
                w_tmp Parameter containing:
                Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[-1.01448846]])
                _linear.weight Parameter containing:
                Tensor(shape=[1, 1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [[0.18551230]])
                _linear.bias Parameter containing:
                Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=False,
                [0.])
        r   z,super().__init__() should be called firstly.z7The name of parameter should be a string, but received r=  zThe name of parameter can not contain `.`, because when you access the newly added parameter in the form of `self.**.**`, it will cause AttributeError.r7  z'The name of parameter can not be empty.zThe parameter 'r  Nz>The parameter to be added should be a Parameter, but received r   &Parameter not found, Can't not find [  ] in state_dict)r  r  r   rl   r   rx   r   r  rB  r   r   r   rF  pirValuer:   r   rb   	set_value)r   rb   r  s      rC   add_parameterzLayer.add_parameter  s   N --MNNND#&& 	/`$t**J]```   D[[F  
 RZZDEEET4   	/T1A%A%ADTDDDEEE":	+VZ-=>,
 ,
" lQUV_Q`Q`Qilll    )- &4())A-- ~)>>>>]Y^]]] ?>> ##D$9).$IJJJ%.DT"rE   r   Parameter | Nonec                2    |                      ||           dS )a  
        Adds a Parameter instance. Added parameter can be accessed by self.name

        Parameters:
            name(str): name of this submodule.
            parameter(Optional[Parameter]): an instance of Parameter.
        Returns:
            None
        N)r  r   s      rC   register_parameterzLayer.register_parameter	  s      	4'''''rE   c                     fd}t          |t                    s$t          dt          |          j                    j                            |            |d          sF                     t                    }t           j
        j                  dk    sJ |g j
        _         |d          s                     t                    }t           j                  dk    r! j                            |j        d           t           j
        j                  dk    sJ  j
        j                            |           d	S d	S )
aY  
        Add customized attribute while append_op. In case of quantization, we want to save
        some attributes into op_desc while exporting inference model by @to_static.

        Arguments:
            attrs(dict): customized attributes that will be added into op_descs.

        NOTE: The interface is only exposed to developers.
        c                    | rj         nj        }| rt          nt          }d}|r(t	          t          |                    }||         |k    }|S )NF)r   r   rD   rR   nextreversed)is_pre_hooklayers_hookscandidate_hookalready_registeredlast_keyr   s        rC   is_already_registeredz2Layer._set_op_attrs.<locals>.is_already_registered   st     .''-  7++6  "' N 6 677%1(%;~%M"%%rE   z)attrs should be type(dict), but received T)r  r   Frg   r%  N)r   r  r   rx   r   rH   r	  r,  rD   r:   r8   rK   r)  rR   r   r'  r   rk   )r   r   r  pre_hook_helperpost_hook_helpers   `    rC   _set_op_attrszLayer._set_op_attrs  s   	& 	& 	& 	& 	&& %&& 	RDKK<PRR  
 	%%e,,,$$666 	8"<<+ O t(.//14444'6&7D# %$777 	=#>>1    4+,,q00(44$-E 5    t(.//14444 #**+;<<<<<	= 	=rE   dict[str, Any]c                    | j         S r   )r  r  s    rC   __getstate__zLayer.__getstate__Q  s
    }rE   statec                :    | j                             |           d S r   )r  r	  )r   r  s     rC   __setstate__zLayer.__setstate__T  s    U#####rE   c                   d| j         v rK| j         d         }|| j        v r5t                      rt          | j        |                   S | j        |         S d| j         v r#| j         d         }|| j        v r| j        |         S d| j         v r<| j         d         }||v r+t                      rt          ||                   S ||         S t
                              | |          S )Nr   r   r   )r  r   r   r   r   object__getattribute__)r   rb   r   r   r   s        rC   __getattr__zLayer.__getattr__W  s    DM))-6Kt'''$&& J1$2B42HIII'--DM))-6Kt''''--&&}Z0Hx$&& B1(4.AAA~%&&tT222rE   r  c           	     0	   fd}t          |t          j        j        j        j                  r%t                              | |           |_        d S t          t          t          |           d           t                    rt                              | |           | j                            dd           }t          |t          j                  r|t!          d          t#          | j                  dk    rF|j        | j        v sJ d|j         d            |                    | j        |j                             || j        | j        | j                   ||<   d S t          |t          j        j                  r^|                                                                dk    r4|t!          d           || j        | j        | j                   ||<   d S |5|v r1|(t5          d d	t          |          j         d
          d |<   d S | j                            dd           }t          |t8                    r4|t!          d           || j        | j        | j                   ||<   d S |5|v r1|(t5          d dt          |          j         d
          d |<   d S | j                            dd           }t          |t<          j        j                   rz|t!          d           || j        | j        | j                   | j        vr| j!        "                               |j        stG          j$        dz             |_        ||<   d S ||v rt          |          t          j%        k    st          |t          j        j                  rddlm&} tO                      r!|         tQ          d d d d          |         0t          t          |                     t<          j        j         k    r ||          |<   d S  ||t          |                      d S |(t5          d dt          |          j         d
          d |<   d S t                              | |           d S )Nc                      | D ]	}|v r|= 
d S r   r~   )dictsr   rb   s     rC   _remove_if_existz+Layer.__setattr__.<locals>._remove_if_existk  s-        199$   rE   r   r  r   r  r  zbuiltin.parameterzassignment to parameter 'z0' should be of type Parameter or None, but got ''r   zassignment to sublayer 'z,' should be of type Layer or None, but got 'r   	_buffers_)assignzIn Dy2stat, self.z is a buffer and self.z0 is not allowed to be set to Variable when self.z	 is None.zassignment to buffers 'z7' should be of type core.DenseTensor or None, but got '))r   rF  jit	dy2staticprogram_translatorStaticFunctionr  __setattr___patched_namerE  rx   propertyr  rY   r   r   r   r:   r   rb   r  r   r   r  r  get_defining_opr   r   r6   r   r   r  r   r   r~  r   r   Variabler  r   r  )r   rb   r  r  r  layersr   r  s    `      rC   r  zLayer.__setattr__j  sd   	  	  	  	  	 
 6:':I
 
 	 tT5111"&EFgd4jj$55x@@ 	2tT5111""=$77eY011 ]	:~ !LMMM4())A--zT%::::YUZYYY ;::  5ej ABBBT]DM4;KLLL F4LLLufj.//Q	:%%'',,..2EEE~ !LMMMT]DM4;KLLL F4LLLDFNN }}}fjkpfqfqfz}}}    F4LLL]&&}d;;F%'' A:>$C   ! 0@$-PPP$t#$#|4||eijoepepey|||    $t=,,Z>>eTZ%677 1:'(G   %$t'79I  
 4=00>BB4HHH : N%0%9+:L%M%M
%*HTNNN)dh.>.> E{{i&888Jvz/= =8 211111 -.. ?8D>3I".!_D !_ !_PT !_ !_OS!_ !_ !_# # 
 %TN2#GD$$7$788DJ<MMM-3VE]]HTNNN"F5'$*=*=>>>>>*' Kd  K  Kswx}s~s~  tH  K  K  K   *.&&tT599999rE   c                    || j         v r
| j         |= d S || j        v r
| j        |= d S || j        v r$| j        |= | j                            |           d S t
                              | |           d S r   )r   r   r   r   r  r  __delattr__)r   rb   s     rC   r  zLayer.__delattr__  s    4### &&&T%%% &&&T]""d#2::4@@@@@tT*****rE   	list[str]c                z   t          | j                  }t          | j                                                  }t          | j                                                  }t          | j                                                  }t          | j                                                  }||z   |z   |z   |z   }|S )a  
        Return a list. Get all parameters, buffers(non-parameter tensors), sublayers, method and attr of Layer.

        Examples:
            .. code-block:: python
                >>> import paddle
                >>> import numpy as np

                >>> class Mylayer(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self.linear1 = paddle.nn.Linear(10, 10)
                ...         self.linear2 = paddle.nn.Linear(5, 5)
                ...         self.conv2d = paddle.nn.Conv2D(3, 2, 3)
                ...         self.embedding = paddle.nn.Embedding(128, 16)
                ...         self.h_0 = paddle.to_tensor(np.zeros([10, 10]).astype('float32'))
                ...
                >>> mylayer = Mylayer()
                >>> print(dir(mylayer))
                ['__call__', '__class__', '__delattr__', '__dict__', ..., 'training']
        )dirr   r   r  keysr   r   r   )r   methodr   rd  r  r  r  s          rC   __dir__zLayer.__dir__  s    , T^$$T]''))**$*//1122
)..0011	t}))++,,~
*Y6@rE   c                    dS )zs
        Extra representation of this layer, you can have custom implementation
        of your own layer.
        r7  r~   r  s    rC   
extra_reprzLayer.extra_repr	  s	    
 rrE   c                $   g }|                                  }|                    d          }g }| j                                        D ]B\  }}t	          |          }t          |d          }|                    d|z   dz   |z              C| j        j        dz   }|rPt          |          dk    r|dd
                    |          z   dz   z  }nt          |          dk    r||d         z  }|r|dd
                    |          z   dz   z  }|dz  }|S )	Nrf   r  (z): rg   z
  r   ))r  ri   r   rI   reprrs   rk   r   r   r:   rm   )r   extra_linesr  sublayer_linesrb   rA   sublayer_str	final_strs           rC   r   zLayer.__repr__
	  s7   __&&
 &&t,,+1133 	E 	EKD%;;L%lA66L!!#*u"4|"CDDDDN+c1	 	,;!##Vfkk+&>&>>EE		[!!Q&&[^+	 	E&++n"="==DDIS	rE   _StateDictHookc                L    t          | j                  }|| j        |j        <   |S r   )r   r  r   )r   r"  r(  s      rC   register_state_dict_hookzLayer.register_state_dict_hook 	  s,     .d.DEE>B1:;!!rE   destination_StateDict | Nonestructured_name_prefix
_StateDictc                \   |t                      }| j                                        D ]\  }}|||||z   <   | j                                        D ]\  }}||| j        vr||||z   <   |r>| j                                        D ]$\  }}||                    ||||z   dz              %|S )z
        The difference from state_dict() is that state_dict_hook will not be called,
        but the original types of parameters and buffers will be maintained.
        Nr=  )r   r   rI   r   r   r   _obtain_parameters_buffers)	r   r&  rw   r(  rb   datarw  
layer_name
layer_items	            rC   r+  z Layer._obtain_parameters_buffers'	  s     %--K*0022 	B 	BJD$=A2T9: M//11 	D 	DLD&" FFF=C2T9: 	*.*:*@*@*B*B  &
J)99#).;cA   rE   include_non_persistable_bufferuse_hook	keep_varsc           	     Z   |t                      }| j                                        D ]%\  }}||r|n|                                |||z   <   &| j                                        D ]Q\  }}	|s*|	'|| j        vr|r|	n|	                                |||z   <   1|	|r|	n|	                                |||z   <   R|rA| j                                        D ]'\  }
}| |                    ||||
z   dz   |||           (|r+| j        	                                D ]} ||          }||}|S )a|  
        Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict

        Parameters:
            destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None.
            include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True.
            include_non_persistable_buffer(bool, optional): If true, include non persistable buffers of current layer and its sub-layers, it is used in pure fp16 and jit.save. Default: False.
            use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True.
            keep_vars(bool, optional) : If false, the returned tensors in the state dict are detached from autograd. Default: True.
        Nr=  )
r   r   rI   detachr   r   r   _state_dict_implr  values)r   r&  rw   r(  r/  r0  r1  rb   r,  rw  r-  r.  state_dict_hookr  s                 rC   r4  zLayer._state_dict_implH	  s   ( %--K*0022 	 	JD$%8DD4;;== 2T9: !M//11 	 	LD&1 &D$JJJ #,@   6 => %"+@   6 =>  
	*.*:*@*@*B*B 	 	&
J)//#).;cA6 !    	.#'#9#@#@#B#B . .-ok::*"-KrE   c                8    |                      |||d||          S )a"  

        Get all parameters and buffers of current layer and its sub-layers. And set them into a dict

        Parameters:
            destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None.
            include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True.
            use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True.
            keep_vars(bool, optional) : If false, the returned tensors in the state dict are detached from autograd. Default: True.

        Returns:
            dict, a dict contains all the parameters and persistable buffers.

        Examples:
            .. code-block:: python

                >>> import paddle

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

                >>> state_dict = emb.to_static_state_dict()
                >>> paddle.save( state_dict, "paddle_dy.pdparams")

        Tr&  rw   r(  r/  r0  r1  )r4  r   r&  rw   r(  r0  r1  s         rC   to_static_state_dictzLayer.to_static_state_dict	  s4    @ $$#/#9+/ % 
 
 	
rE   c                    d S r   r~   r9  s         rC   
state_dictzLayer.state_dict	  s	     SrE   .)r  r1  c                   d S r   r~   )r   r&  r  r1  s       rC   r<  zLayer.state_dict	  s	     SrE   c                   d S r   r~   )r   r  r1  s      rC   r<  zLayer.state_dict	  s	     SrE   r&  r  r1  c                   d S r   r~   )r   r&  r  r1  r  s        rC   r<  zLayer.state_dict	  s	     SrE   c                   t          |          }dfd}|dk    rt          |d         t                    sdv rg d	}t          t	          |t          |                              D ]} |||         ||                    |                                         d
d          d                    dd          dd                    dd                    S  | j        |i S )a"  
        Get all parameters and persistable buffers of current layer and its sub-layers. And set them into a dict

        Parameters:
            destination(dict, optional) : If provide, all the parameters and persistable buffers will be set to this dict . Default: None.
            include_sublayers(bool, optional) : If true, also include the parameters and persistable buffers from sublayers. Default: True.
            use_hook(bool, optional) : If true, the operations contained in _state_dict_hooks will be appended to the destination. Default: True.
            keep_vars(bool, optional) : If false, the returned tensors in the state dict are detached from autograd. Default: True.

        Returns:
            dict: a dict contains all the parameters and persistable buffers.

        Examples:
            .. code-block:: python

                >>> import paddle

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

                >>> state_dict = emb.state_dict()
                >>> paddle.save(state_dict, "paddle_dy.pdparams")

        r  rl   r  r   c                @    | v rt          d|  d          || <   d S )Nz"got multiple values for argument 'r  )r   )r  r  r  s     rC   safe_set_paramz(Layer.state_dict.<locals>.safe_set_param	  s3    f}} KS K K KLLLF3KKKrE   r  rg   r  r?  r&  NTr7  Fr1  r8  )r  rl   r  r   )r:   r   rl   r   minr4  rY   )r   r  r  len_argsrC  base_param_keysrq   s     `    rC   r<  zLayer.state_dict	  s   0 t99	  	  	  	  	  	  MMja#66MDDDOS3+?+?@@AA @ @s3T#Y????(("JJ}d;;"&'-zz(B'?'?/4 **[%88 )    %t$d5f555rE   r'   c                (   i }|                      dd          }t          |d|          }|                    |           | j                                        D ]7\  }}|0|                    | | d          }|                    |           8|S )a  Recursively builds a sharded state dictionary for the model and its sub-layers.

        Args:
            structured_name_prefix: Prefix to prepend to all tensor names for hierarchical naming.

        Returns:
            Dictionary mapping tensor names to ShardedWeight.
            The dictionary contains both the current layer's parameters and all sub-layer parameters.
        r7  F)r(  rw   N)r<  shard_rulesr  r=  )r(  )r<  r(   r	  r   rI   sharded_state_dict)r   r(  rI  r<  current_sharded_dictr-  r.  sub_shardeds           rC   rI  zLayer.sharded_state_dict 
  s      __#%# % 
 

  8!) 
  
  

 	!!"6777 '+&6&<&<&>&> 	7 	7"J
%(;;.D+Sj+S+S+S <   #))+666!!rE   
aoa_configdict[str:list[str]] | Nonec                F    ddl m}  ||                                 |fi |S )aI  
        Returns an iterator over the full, unsharded model parameters.
        The output parameters can be customized using the `aoa_config` argument.

        Args:
        sharded_state_dict (ShardedStateDict):
            The state dict containing parameter shards local to the current process.
        aoa_config (dict[str, list[str]] | None, optional):
            AoA (Almost AllReduce) configuration. Default is None.
        kwargs:
            Optional keyword arguments:
            - h_group: The horizontal communication group.
                If using group communication, both h_group and v_group must be provided.
            - v_group: The vertical communication group.
            - process_group: The communication group in single-group setups (when h_group and v_group are not used).
            - num_splits (int): The number of splits to divide the parameters.
            - shard_idx (int): The index of the split handled by the current process. Default is 0.
            - memory_growth_threshold (int): The memory threshold (in bytes) for controlling memory growth during parameter assembly.
                Default is 8 * (2 ** 30), i.e., 8GB.

        Returns:
            Iterator:
                An iterator over the full, unsharded model parameters, optionally filtered and customized according to `aoa_config`.

        r   )
full_param)1paddle.distributed.flex_checkpoint.dcp.full_paramrO  rI  )r   rL  r  rO  s       rC   fullz
Layer.full&
  sH    >	
 	
 	
 	
 	
 	
 z$1133ZJJ6JJJrE   r<  use_structured_nametuple[list[str], list[str]]c                   g t                      g }fd}g }|                     d                                          D ]q\  }}|r|n|j        }	  |||          }	|                    |	           3# t
          $ r2}
t          j        d| dt          |
          z              Y d}
~
jd}
~
ww xY w	                                D ]}|vr|                    |           t                      r|D ]\  }}|                    |           n'd }	 t                      rwt          t          j        j                                                  j        }t          j        j        j                            d |D             t-                      |           nLt          t/                                j        }t1          j        d	 |D             t-                      |           |D ]\  }} |||           n=# t
          $ r}t          d
          d}~wt4          $ r}t          d
          d}~ww xY w|fS )a  
        Set parameters and persistable buffers from state_dict. All the parameters and buffers will be reset by the tensor in the state_dict

        Parameters:
            state_dict(dict) : Dict contains all the parameters and persistable buffers.
            use_structured_name(bool, optional) : If true, use structured name as key, otherwise, use parameter or buffer name as key.
                                                  Default: True.
        Returns:
            missing_keys(list):A list of str containing the missing keys
            unexpected_keys(list):A list of str containing the unexpected keys

        Examples:
            .. code-block:: python

                >>> import paddle

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

                >>> state_dict = emb.state_dict()
                >>> paddle.save(state_dict, "paddle_dy.pdparams")
                >>> para_state_dict = paddle.load("paddle_dy.pdparams")
                >>> emb.set_state_dict(para_state_dict)

        c           	     4                        | d           }|'                    |            t          |  d          t          |t          t
          f          rt          |          t          |          k    rF                    |            t          |  dt          |           dt          |                                         |            ||fS t          j	        |j
                  r|
                                n|j
        }t          |          t          |j
                  k    rL                    |            t          |  dt          |           dt          |j
                   d                              |            ||fS )Nz# is not found in the provided dict.z receives the length of z, but the expected shape is z receives a shape r=  )rY   rk   r   r   r  r   r:   r~  inspectismethodr-  )r  r   r  state_shape
match_keysr   r<  s       rC   _check_matchz*Layer.set_state_dict.<locals>._check_matchm
  s   NN3--E}##C((( C!L!L!LMMM%$.. $u::U++ '',,,$ B BE

 B B58ZZB B  
 NN3''' %<' '44%EKKMMM  $$U[(9(999 '',,,$uu${2C2Cuuaefkfqararuuu   s###e|#rE   F)r0  zSkip loading for z. Nc                p   t                                          | j                                                  }|                                }|                                rt          j                    }n|                                rt          j	                    }n|
                                rbt          j                    }|                    |                                           t          j        |                                          }n|                                rt          j                    }|                    |                                           t          j        t"          j                                                            d          d         |                                          }n`t          j                    }|                    |                                           t          j        |                                          }|                    ||           d S )N:r   )r   find_varrb   
get_tensor_placeis_cpu_placer   CPUPlaceis_cuda_pinned_placeCUDAPinnedPlaceis_xpu_placePlace	set_placeXPUPlacexpu_device_idis_custom_placeCustomPlacerF  r4  
get_deviceri   custom_device_id	CUDAPlacegpu_device_idr   )r   ndarraytr  places        rC   _set_varz&Layer.set_state_dict.<locals>._set_var
  s    NN++CH55@@BBHHJJ>>## > MOOEE++-- > 022EE^^%% >
AKK

+++ M!//*;*;<<EE&&(( 
>
AKK

+++ ,002288==a@**,, EE
 
AKK

+++ N1??+<+<==Egu%%%%%rE   c                    g | ]\  }}|S r~   r~   r   r   r  s      rC   r`  z(Layer.set_state_dict.<locals>.<listcomp>
      GGG<5%GGGrE   c                    g | ]\  }}|S r~   r~   rt  s      rC   r`  z(Layer.set_state_dict.<locals>.<listcomp>
  ru  rE   zThis error might happens in dy2static, while calling 'set_state_dict' dynamically in 'forward', which is not supported. If you only need call 'set_state_dict' once, move it to '__init__'.)r   r4  rI   rb   rk   r   r>   r?   rl   r  r"   r  r#   r   rF  baser   _current_expected_place__default_executor	libpaddler  create_loaded_parameterr   _get_devicer   _create_loaded_parameterr   )r   r<  rR  r   rZ  matched_param_stater  r   key_name	match_reserrr  rr  executorr  rY  r   s    `             @@rC   set_state_dictzLayer.set_state_dictK
  s   < UU
	$ 	$ 	$ 	$ 	$ 	$ 	$< !///??EEGG 	F 	FJC1AssuzHF(L599	#**95555 F F F9#999CHHDEEEEEEEEF??$$ 	, 	,C*$$&&s+++ 8	 3 ' 'u&&&&'& & &0== '-FFHH   '  K)-EEGG3FGGG$      (66HH1GG3FGGG$   
 %8 + +LE5HUE****+     R        R  
 _,,s=   !A::
B6(B11B6C%H   
H:
HH:&H55H:Mapping[str, Any]r  c           	     h   g }|                      |d          \  }}|rt          |          dk    rF|                    dd                    d                    d |D                                            t          |          dk    rF|                    dd                    d                    d |D                                            t          |          dk    r@t          d	                    | j        j        d
                    |                              t          ||          S )a  
        Copy parameters and buffers from :attr:`state_dict` into this module and its descendants.

        If :attr:`strict` is ``True``, then
        the keys of :attr:`state_dict` must exactly match the keys returned
        by this module's :meth:`~torch.nn.Module.state_dict` function.


        Parameters:
            state_dict (dict): a dict containing parameters and persistent buffers.
            strict (bool, optional): whether to strictly enforce that the keys
                in :attr:`state_dict` match the keys returned by this module's
                :meth:`~torch.nn.Module.state_dict` function. Default: ``True``
            assign (bool, optional): When set to ``False``, the properties of the tensors
                in the current module are preserved whereas setting it to ``True`` preserves
                properties of the Tensors in the state dict. The only
                exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`
                for which the value from the module is preserved. Default: ``False``

        Returns:
            ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
                * ``missing_keys`` is a list of str containing any keys that are expected
                    by this module but missing from the provided ``state_dict``.
                * ``unexpected_keys`` is a list of str containing the keys that are not
                    expected by this module but present in the provided ``state_dict``.
        T)rR  r   z%Unexpected key(s) in state_dict: {}. z, c              3  "   K   | ]
}d | d V  dS "Nr~   r   ks     rC   r   z(Layer.load_state_dict.<locals>.<genexpr>
  s*      !D!Dq(a(((!D!D!D!D!D!DrE   z"Missing key(s) in state_dict: {}. c              3  "   K   | ]
}d | d V  dS r  r~   r  s     rC   r   z(Layer.load_state_dict.<locals>.<genexpr>  s*      !A!Aq(a(((!A!A!A!A!A!ArE   z*Error(s) in loading state_dict for {}:
	{}z
	)	r  r:   insertformatrm   r  r   r   r}   )r   r<  r  r  
error_msgsr   r   s          rC   load_state_dictzLayer.load_state_dict
  sX   @ !#
(,(;(;D )< )
 )
%o  	?##a''!!;BB		!D!DO!D!D!DDD    <  1$$!!8??		!A!AL!A!A!AAA    z??Q>EEN+V[[-D-D   
 !???rE   blockingnon_blockingc                8    |                      ||||dd          S )a
  
        Cast the parameters and buffers of Layer by the give device, dtype and blocking.

        Parameters:
            device(str|paddle.CPUPlace()|paddle.CUDAPlace()|paddle.CUDAPinnedPlace()|paddle.XPUPlace()|None, optional): The device of the Layer which want to be stored.
            If None, the device is the same with the original Tensor. If device is string, it can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the
            index of the GPUs or XPUs. Default: None.

            dtype(str|numpy.dtype|paddle.dtype|None, optional): The type of the data. If None, the dtype is the same with the original Tensor. Default: None.

            blocking(bool|None, optional): If False and the source is in pinned memory, the copy will be
              asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the blocking is set True. Default: None.

            non_blocking(bool|None, optional): If True and the source is in pinned memory, the copy will be
              asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the non_blocking is set False. Default: None.

        Returns:
            self

        Examples:
            .. code-block:: python

                >>> import paddle
                >>> paddle.seed(2023)

                >>> linear=paddle.nn.Linear(2, 2)
                >>> linear.weight
                >>> print(linear.weight)
                Parameter containing:
                Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=False,
                [[ 0.89611185,  0.04935038],
                 [-0.58883440,  0.99266374]])

                >>> linear.to(dtype='float64')
                >>> linear.weight
                >>> print(linear.weight)
                Parameter containing:
                Tensor(shape=[2, 2], dtype=float64, place=Place(gpu:0), stop_gradient=False,
                [[ 0.89611185,  0.04935038],
                 [-0.58883440,  0.99266374]])

                >>> linear.to(device='cpu')
                >>> linear.weight
                >>> print(linear.weight)
                Parameter containing:
                Tensor(shape=[2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
                [[ 0.89611185,  0.04935038],
                 [-0.58883440,  0.99266374]])

                >>> # doctest: +REQUIRES(env:GPU)
                >>> linear.to(device=paddle.CUDAPinnedPlace(), blocking=False)
                >>> linear.weight
                >>> print(linear.weight)
                Parameter containing:
                Tensor(shape=[2, 2], dtype=float64, place=Place(gpu_pinned), stop_gradient=False,
                [[ 0.89611185,  0.04935038],
                 [-0.58883440,  0.99266374]])

        TF)r4  r   r  r  rw   rv   ry   )r   r4  r   r  r  s        rC   ru  zLayer.to  s2    D }}%"  
 
 	
rE   funcICallable[[Tensor, PlaceLike | None, DTypeLike | None, bool | None], None]c                *   |r0|                                  D ]}|                    |||||           | j                                        D ]\  }}|t	                      5   |||||          }	d d d            n# 1 swxY w Y   |j        Ft	                      5   ||                                |||          }
d d d            n# 1 swxY w Y   | j                                        D ]\  }}| |||||          | j        |<   || _        d S r   )	r  _applyr   rI   r   grad
_grad_ivarr   r   )r   r  r4  r   r  rw   rA   r  r   param_appliedgrad_appliedbufs               rC   r  zLayer._apply[  s     	O O OT65(<MNNNN*0022 		 		JC YY I I$(Dx$H$HMI I I I I I I I I I I I I I I :)   '+t!,,..x( (              
 ++-- 	H 	HHC%)T#vuh%G%Gc"s$   !A<<B 	B 	!C		C	C	rp  c                   ||j         }||j        }t          |t          j        t
          j        f          st          |          }|j                                         rt          |t
          j                  rt          |         n|}t          j
        |          }t          j        |j                  |z  dz  dz   dz  dz  }t          j                    }||k     r`|                    t!          j                    |          }	|                                                                                                 n|}	n|}	|d||	j        k    rYt           j        j                            |	j                   5  |	                    |          }
d d d            n# 1 swxY w Y   n|	}
|1|
j                             |          s|
                    ||          }n|
}|                                                                }|                                                                }|                                r|                    |           n|                    |           |S )N   rg   g333333?)rq  r   )rq  r   r   r   rU  r   DataTyper    is_gpu_placer%   size_of_dtyperr  prodr-  gpu_memory_available_copy_torF  ra  r  r^  _clearrw  r   _dygraph_place_guardcast_equals_is_initialized_share_data_with_share_data_nocheck_with)r   rp  r4  r   r  proto_dtype
size_dtypewaiting_alloc_memoryr  t_usedt_castednew_t
dst_tensor
src_tensors                 rC   
_transformzLayer._transformz  s    >WF=GE%'/4=!ABB 	6.u55E 7!! 	 eT]33)%00 
 +K88J '!'""Z/36:cACG ! $(#<#>#> #&:::O%%x  		$$&&--////F &,!6!6&;;&,;OO 4 4!;;U;334 4 4 4 4 4 4 4 4 4 4 4 4 4 4 H hn&<&<V&D&D%%fh77EEE WWYY))++
[[]]--//
 	<''
3333 //
;;;s   ;FF"%F"rv   c                    |||| S |tt          |t                    r t          j                            |          }n?t          |t
          j                  rn$t          dt          |          j	                   |d}nt          |t                    s
J d            |d}nt          |t                    s
J d            |r|rdnd} fd}t          j                    5  t          j        dt          	                                |||||           ddd           n# 1 swxY w Y   | _         S )
a  
        Cast the parameters and buffers of Layer by the give device, dtype and blocking.

        Parameters:
            device(str|paddle.CPUPlace()|paddle.CUDAPlace()|paddle.CUDAPinnedPlace()|paddle.XPUPlace()|None, optional): The device of the Layer which want to be stored.
            If None, the device is the same with the original Tensor. If device is string, it can be ``cpu``, ``gpu:x`` and ``xpu:x``, where ``x`` is the
            index of the GPUs or XPUs. Default: None.

            dtype(str|numpy.dtype|paddle.dtype|None, optional): The type of the data. If None, the dtype is the same with the original Tensor. Default: None.

            blocking(bool|None, optional): If False and the source is in pinned memory, the copy will be
              asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the blocking is set True. Default: None.

            non_blocking(bool|None, optional): If True and the source is in pinned memory, the copy will be
              asynchronous with respect to the host. Otherwise, the argument has no effect. If None, the non_blocking is set False. Default: None.

            include_sublayers(bool, optional): If True, deal with self and all sublayers parameters and buffers, if not only deal with self parameters and buffers. Default: True.

            floating_only(bool, optional): If True, only cast all floating point parameters and buffers of Layer by the give device, dtype and blocking.

        Returns:
            self

        Nzdevice should be type of str, paddle.CPUPlace, paddle.CUDAPlace, paddle.CUDAPinnedPlace, paddle.XPUPlace, or paddle.base.libpaddle.Place, but got Tz5blocking value error, must be the True, False or NoneFz9non_blocking value error, must be the True, False or Nonec                d    rt          j        |           s| S                     | |||          S r   )rF  is_floating_pointr  )rp  r4  r   r  rv   r   s       rC   	transformz!Layer._to_impl.<locals>.transform  s:     f&>q&A&A ??1feX>>>rE   ignore)category)r   rl   rF  r4  _convert_to_placer   re  r   rx   r   r   r>   catch_warningsfilterwarningsUserWarningr  r   )r   r4  r   r  r  rw   rv   r  s   `     ` rC   ry   zLayer._to_impl  s   F N $K&#&& 
88@@
     A  jn  ou  jv  jv  j  A  A   HHh--  G -  LLlD11  K 1 !)BLB55d	? 	? 	? 	? 	? 	?
 $&& 	O 	O#H{CCCCKK	65(<MNNN	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O s   ,5D--D14D1r   c                   t           j                                        }t           j                                        }t           j                            ||          5  |                                 D ])}|                    |                                           *	 ddd           n# 1 swxY w Y   t           j                                        r|S |S )z
        Return startup program containing initialization operations of all parameters.

        NOTE(dev): This is a very low level API and only for inner developer.
        N)	rF  rw  r   program_guardrd  _create_init_opr   r   use_pir_api)r   startup_programr   r   s       rC   _startup_programzLayer._startup_program  s    !+--//{**,,[&&|_EE 	F 	F** F F%%o&B&B&D&DEEEEF	F 	F 	F 	F 	F 	F 	F 	F 	F 	F 	F 	F 	F 	F 	F '')) 	#""s   ?B))B-0B-dst_typedtype | strc                r   g d}t          t          j        t          j        f          st	                    t
          u rS|v rOt          t
          t          j        f          rt          j                  fd}|                     |          S t          dt          t                    z             )a  
        Casts all parameters and buffers to :attr:`dst_type`.

        Parameters:
            dtype(str|paddle.dtype): target data type of layer.
                If set str, it can be "bool", "bfloat16", "float16", "float32", "float64",
                "int8", "int16", "int32", "int64", "uint8", "complex64", "complex128".
                Default: None

        Returns:
            Layer: self
        rf  c                8    |                      dd           d S )NFTru   r  )rA   r  s    rC   layer_transzLayer.type.<locals>.layer_transE  s/    "%4      rE   rq  )
r   rF  r   rr  rx   rl   r   r    r  r   )r   r  rv  r  s    `  rC   rx   z
Layer.type"  s    
 
 
 x&,!9::	H~~$$L(((S"(O44 J$?II    
 ::k*** Te**  rE   c                @    |                      t          j                  S )z
        Casts all floating point parameters and buffers to ``double`` datatype.

        Returns:
            Module: self
        )rx   rF  ri  r  s    rC   doublezLayer.doubleQ       yy(((rE   c                @    |                      t          j                  S )z
        Casts all floating point parameters and buffers to ``half`` datatype.

        Returns:
            Module: self
        )rx   rF  rh  r  s    rC   halfz
Layer.halfZ  r  rE   rz   Layer | Sequence[Layer] | Nonec                   g nt          t                    rgnQt          t          t          f          rt                    n%t	          dt                    j         d          fd}|                     |          S )a  
        Casts all floating point parameters and buffers to ``float`` data type.

        Parameters:
            excluded_layers(nn.Layer|list|tuple|None, optional): Specify the layers that need to be kept original data type. if excluded_layers is None, casts all floating point parameters and buffers. Default: None.

        Returns:
            Layer: self

        Examples:
            .. code-block:: pycon

                >>> import paddle

                >>> class Model(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self.linear = paddle.nn.Linear(1, 1)
                ...         self.dropout = paddle.nn.Dropout(p=0.5)
                ...
                ...     def forward(self, input):
                ...         out = self.linear(input)
                ...         out = self.dropout(out)
                ...         return out
                >>> model = Model()
                >>> model.float()
                Model(
                    (linear): Linear(in_features=1, out_features=1, dtype=paddle.float32)
                    (dropout): Dropout(p=0.5, axis=None, mode=upscale_in_train, inplace=False)
                )
        N9excluded_layers should be type nn.Layer or list, but got r=  c                >    t          | t          j                   d S r   )r{   rF  r   rA   rz   s    rC   r  z Layer.float.<locals>.layer_trans      ufnoFFFFFrE   )r   rx   r   r   r   r   r  r   rz   r  s    ` rC   floatzLayer.floatc  s    F !0 7""_ot,, 	./OO$77 	"?33OOmDQ`LaLaLjmmm  	G 	G 	G 	G 	G zz+&&&rE   c                   t           j                                        du rt          j        d           | S t
          j        gnt          t                    rgnQt          t          t          f          rt                    n%t          dt                    j         d          fd}|                     |          S )a  
        Casts all floating point parameters and buffers to ``float16`` data type.


        .. note::
            ``nn.BatchNorm`` does not support ``bfloat16`` weights, so it would not be converted by default.


        Parameters:
           excluded_layers(nn.Layer|list|tuple|None, optional): Specify the layers that need to be kept original data type. if excluded_layers is None, casts all floating point parameters and buffers except ``nn.BatchNorm``. Default: None.

        Returns:
            Layer: self

        Examples:
            .. code-block:: python

                >>> # doctest: +SKIP('Paddle compiled by the user does not support float16, so keep original data type.')
                >>> import paddle

                >>> class Model(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self.linear = paddle.nn.Linear(1, 1)
                ...         self.dropout = paddle.nn.Dropout(p=0.5)
                ...
                ...     def forward(self, input):
                ...         out = self.linear(input)
                ...         out = self.dropout(out)
                ...         return out
                ...
                >>> model = Model()
                >>> model.float16()
                Model(
                    (linear): Linear(in_features=1, out_features=1, dtype=float32)
                    (dropout): Dropout(p=0.5, axis=None, mode=upscale_in_train)
                )
        FzQPaddle compiled by the user does not support float16, so keep original data type.Nr  r=  c                >    t          | t          j                   d S r   )r{   rF  rh  r  s    rC   r  z"Layer.float16.<locals>.layer_trans  r  rE   )rF  ampis_float16_supportedr>   r?   r   	BatchNormr   rx   r   r   r   r   r  r  s    ` rC   rh  zLayer.float16  s    T :**,,55Mc   K .5R\NN? 	 ot,, 	./OO$77 	"?33OOmDQ`LaLaLjmmm  	G 	G 	G 	G 	G zz+&&&rE   c                   t           j                                        du rt          j        d           | S t
          j        gnt          t                    rgnQt          t          t          f          rt                    n%t          dt                    j         d          fd}|                     |          S )a/  
        Casts all floating point parameters and buffers to ``bfloat16`` data type.


        .. note::
            ``nn.BatchNorm`` does not support ``bfloat16`` weights, so it would not be converted by default.


        Parameters:
            excluded_layers(nn.Layer|list|tuple|None, optional): Specify the layers that need to be kept original data type. if excluded_layers is None, casts all floating point parameters and buffers except ``nn.BatchNorm``. Default: None.

        Returns:
            Layer: self

        Examples:
            .. code-block:: python

                >>> # doctest: +SKIP('bfloat need V100 compile')
                >>> import paddle

                >>> class Model(paddle.nn.Layer):
                ...     def __init__(self):
                ...         super().__init__()
                ...         self.linear = paddle.nn.Linear(1, 1)
                ...         self.dropout = paddle.nn.Dropout(p=0.5)
                ...
                ...     def forward(self, input):
                ...         out = self.linear(input)
                ...         out = self.dropout(out)
                ...         return out
                ...
                >>> model = Model()
                >>> model.bfloat16()
                >>> #UserWarning: Paddle compiled by the user does not support bfloat16, so keep original data type.
                Model(
                    (linear): Linear(in_features=1, out_features=1, dtype=float32)
                    (dropout): Dropout(p=0.5, axis=None, mode=upscale_in_train)
                )
        FzRPaddle compiled by the user does not support bfloat16, so keep original data type.Nr  r=  c                >    t          | t          j                   d S r   )r{   rF  rg  r  s    rC   r  z#Layer.bfloat16.<locals>.layer_trans  s    ufoGGGGGrE   )rF  r  is_bfloat16_supportedr>   r?   r   r  r   rx   r   r   r   r   r  r  s    ` rC   rg  zLayer.bfloat16  s    V :++--66Md   K .5R\NN? 	 ot,, 	./OO$77 	"?33OOmDQ`LaLaLjmmm  	H 	H 	H 	H 	H zz+&&&rE   int | PlaceLike | Nonec                \   |1t          j        t           j                                                  }ndt	          |t
                    rt          j        |          }n:t	          |t           j                  rnt          dt          |                     |                     |          S )a  
        Move all model parameters and buffers to the GPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing the optimizer if the layer will
        live on GPU while being optimized.

        Parameters:
            device(int, optional): if specified, all parameters will be copied to that device.

        Returns:
            Layer: self
        Nz2device must be int, paddle.CUDAPlace or None, got r8  )	rF  rm  cudacurrent_devicer   r   r   rx   ry   r   r4  s     rC   r  z
Layer.cuda  s     >%fk&@&@&B&BCCFF$$ 	%f--FF 011 	ST&\\SS   }}F}+++rE   c                $   |t          j        d          }ndt          |t                    rt          j        |          }n:t          |t           j                  rnt	          dt          |                     |                     |          S )a  
        Move all model parameters and buffers to the XPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing optimizer if the layer will
        live on XPU while being optimized.

        Parameters:
            device(int, optional): if specified, all parameters will be copied to that device.

        Returns:
            Layer: self
        Nr   z1device must be int, paddle.XPUPlace or None, got r8  )rF  rg  r   r   r   rx   ry   r  s     rC   xpuz	Layer.xpu6  s     >_Q''FF$$ 	_V,,FF00 	RDLLRR   }}F}+++rE   c                P    |                      t          j                              S )zm
        Move all model parameters and buffers to the CPU.

        Returns:
            Layer: self
        r8  )ry   rF  ra  r  s    rC   cpuz	Layer.cpuQ  s      }}FO$5$5}666rE   c                     t          d          )NzMReached a code path in Module.get_extra_state() that should never be called. )r  r  s    rC   get_extra_statezLayer.get_extra_stateZ  s    [
 
 	
rE   requires_gradc                D    |                                  D ]
}| |_        | S )a7  
        Change if autograd should record operations on parameters in this layer.

        Parameters:
            requires_grad (bool): whether autograd should record operations on
                                  parameters in this layer. Default: ``True``.

        Returns:
            Layer: self
        )rd  r   )r   r  r  s      rC   requires_grad_zLayer.requires_grad__  s.     "" 	0 	0A"//AOOrE   set_to_nonec                n    |                                  D ]}|j        |                    |             dS )z
        Reset gradients of all model parameters.

        Parameters:
            set_to_none (bool): instead of setting to zero, set the grads to None. Currently, set_to_none=True
            is not fully supported.
        N)rd  r  r  )r   r  r  s      rC   	zero_gradzLayer.zero_gradn  sF     "" 	2 	2Av!  [111	2 	2rE   c                    | j         j        S r   )r   r   r  s    rC   rD  zLayer._get_namez  s    ~&&rE   )Nr   )r   r   r   r1   r   r   )T)r  r   r   r
   )r   r
   )r  r  r   r
   r   )
r"  r#  r  r   r   r   r!  r   r   r   )r"  r*  r  r   r   r   r   r   )NNFNN)r-  r4   r.  r/  r   r0  r1  r   r2  r3  r4  r5  r   r   )r;  rl   r   r   )NNN)rb   r   rN  rO  r   r0  r   r   )rw   r   r   r]  r   )r   r0  r   r
   )r   ry  )r   r|  )F)r  r   r   r  )r7  TT)r  rl   rw   r   r  r   r   r  )r7  FNT)
r  rl   r  r   r  r  r  r   r   r|  )r   r  )Nr7  T)r  r  r  rl   r  r   )rb   rl   r  r   rN  r   r   r   )r;  rl   r   r   )r  r   r   r   )r  r   r  r   r   r   )rB   r   r  r   r   r   )rB   r   r   r   )rb   rl   r  r6   r   r6   )r;  rl   r   r6   )r;  rl   rA   r6   r  r   r   r   )rb   rl   r  r  r   r   )rb   rl   r  r   r   r   )rb   rl   r   r  r   r   )r   r  )r  r  r   r   )rb   rl   r   r   )rb   rl   r  r   r   r   )rb   rl   r   r   )r   r  )r"  r#  r   r   )NTr7  )r&  r'  rw   r   r(  rl   r   r)  )NTr7  FTT)r&  r'  rw   r   r(  rl   r/  r   r0  r   r1  r   r   r)  )NTr7  TT)r&  r'  rw   r   r(  rl   r0  r   r1  r   r   r)  )r&  r)  r  rl   r1  r   r   r)  )r  rl   r1  r   r   r)  )r   r)  )r  r   r  r   r   r)  )r7  )r(  rl   r   r'   )rL  rM  )r<  r)  rR  r   r   rS  )TF)r<  r  r  r   r  r   )NNNN)
r4  r5  r   r0  r  rO  r  rO  r   r
   )r  r  r4  r5  r   r0  r  rO  rw   r   r   r   )
rp  r   r4  r5  r   r0  r  rO  r   r   )NNNNTF)r4  r5  r   r0  r  rO  r  rO  rw   r   rv   r   )r   r   )r  r  r   r
   )rz   r  r   r
   )r4  r  r   r
   )r   r   )r  r   r   r
   )r  r   r   r   )\r   r   r   r   r   r   r  r  setterr  r  r  r  r  r)  register_forward_hookr,  r9  r   r+   rY  r[  r,   rd  rx  r  r{  r  rb  r  r  r  r  r  r  rt  r  r  r  r  r  r  r  rA  r  get_submoduleset_submoduler  register_moduler  r  r  r  r  r  r  r  r  r  r   r%  r+  r4  r:  r   r<  rI  rQ  r   deprecate_stat_dictr  r  ru  r  r  ry   r  set_dict	load_dictrx   r  r  r  rh  rg  r  r  r  r  r  r  rD  r~   rE   rC   r6   r6     sC
        4 4l NNN AJ/- /- /- /- /-b     X  _' ' _' 6 6 X6 !'= = ('=> > > > >@4 4 4 4l8 8 8 8t   @ !!U" U" U" U" U" U"p 7 !N" N" N" N" N" N"f &*"&26#'<
 <
 <
 <
 <
|   2 Z19    #'"&	5
 5
 5
 5
 
5
t  #'"&	6
 6
 6
 6
 6
p _)9566" " " " 76"HP P P P Pd   4" " " "4# # # # #J _)9566 "&!%	J" J" J" J" 76J"\ "(,!%G G G G GR	 	 	 	 #'!%	
 
 
 
 
8 _m\233=ACA CA CA CA 43CAJ _)9566! ! ! ! 76!F   < _)9566 "&!%	@# @# @# @# 76@#D. . . . .@   U U U Un> > > >	" 	" 	" 	"? ? ? ?, , , ,\   : _gx())8=$* $* $* $* *)$*L !M M
( 
( 
( 
( !OI I I IV
( 
( 
( 
(:= := :=x   $ $ $ $3 3 3 3&l: l: l: l:\	+ 	+ 	+ 	+   @      ," " " " *."&&(	    F *."&&(/4< < < < <@ *."&&('
 '
 '
 '
 '
R  *."&&(    X 
      X  	     X !%bE     X/6 /6 /6 /6f ')$" $" $" $" $"P 48#K #K #K #K #KJ " %)D- D- D- D- #"D-R 	<@ <@ <@ <@ <@@ $("& $$(I
 I
 I
 I
 I
f #'    >@ @ @ @H $("& $$("&#P P P P Pd# # # #" HI- - - -^) ) ) )) ) ) ) AE1' 1' 1' 1' 1'h AE@' @' @' @' @'F AEA' A' A' A' A'F, , , , ,6, , , , ,67 7 7 7
 
 
 

    
2 
2 
2 
2 
2' ' ' ' 'rE   )g
__future__r   r   rV  retypingr>   r   collectionsr   r   r   r   r   r	   numpyrr  typing_extensionsr
   r   rF  r   r   r   r   paddle.autograd.backward_utilsr   paddle.baser   r   r   paddle.base.corer   paddle.base.dygraphr   paddle.base.dygraph.baser   r   r   r   paddle.base.dygraph_utilsr   paddle.base.executorr   r   paddle.base.frameworkr   r   r   r|  r    r!   r"   r#   r$   r%   paddle.base.layer_helper_baser&   5paddle.distributed.flex_checkpoint.dcp.sharded_weightr'   r(   paddle.frameworkr)   paddle.profiler.utilsr*   paddle.utilsr+   paddle.utils.decorator_utilsr,   collections.abcr-   r.   r/   r0   paddle._typingr1   r2   r3   r4   paddle.nn.initializerr5   __all__r  rl   r   r*  r#  r)  r#  compiler^   r`   rD   rR   r\   rd   rs   r{   r}   r   r   r   r6   r~   rE   rC   <module>r     sV   # " " " " "   				    / / / / / / / / 6 6 6 6 6 6 6 6 6 6 6 6     , , , , , , , ,  . . . . . . . . . . . . 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 $ $ $ $ $ $ ' ' ' ' ' '            D C C C C C 7 7 7 7 7 7 7 7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 : 9 9 9 9 9        ' & & & & & 2 2 2 2 2 2 # # # # # #       2EEEEEEEEEEEEMMMMMMMMMMMM111111  gv&'gvtCH~.fd38n6L0MMNP 	&&!6) gvtCH~v6>?A  4V$f&8f&EEF
:,,-
-..bj)**  "! ! !,/ / /1 1 1
( ( (M M M
 
 
 
 
J!N4E#FGG
 
 
e e e e e e e eP
 
 
 
 
 
 
 
 /  /  /  /  /  /  /  /Fq/' q/' q/' q/' q/' q/' q/' q/' q/' q/'rE   