a
    Sic                    @   s<  d Z ddlZddlZddlZddlZddlm  mZ	 ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& G dd dej'Z'dS )z=Contains the base Layer class, from which all layers inherit.    N)backend)constraints)initializers)regularizers)
base_layer)base_layer_utils)
input_spec)autocast_variable)loss_scale_optimizer)policy)layer_serialization)generic_utils)layer_utils)object_identity)
tf_inspect)tf_utils)to_snake_case)is_tensor_or_tensor_list)
tf_logging)doc_controlsc                       sN  e Zd ZdZeedejj	Z	ej
jjdddZej
jjejdd	 Zejd
d Zejdd ZejdddddddddejjejjjjfddZejdd Zedd Zdd Zejdd Z ejdddZ!dd Z"dd Z#e$dd Z%e$d d! Z&e$d"d# Z'e$ej(d$d% Z)e)j*d&d% Z)e$d'd( Z+e+j*d)d( Z+e$d*d+ Z,e,j*d,d+ Z,e$d-d. Z-e-j*ej
jjd/d. Z-e$d0d1 Z.e$d2d3 Z/ejdd4d5Z0e$d6d7 Z1ejdd8d9Z2ejd:d; Z3d<d= Z4d>d? Z5d@dA Z6dBdC Z7dDdE Z8dFdG Z9e$dHdI Z:e$dJdK Z;dLdM Z<dNdO Z=dPdQ Z>dRdS Z?e$dTdU Z@e$dVdW ZAe$dXdY ZBdZd[ ZCe$d\d] ZDe$ejEd^d_ ZFe$ejEd`da ZGe$dbdc ZHe$ddde ZIe$dfdg ZJe$dhdi ZKeKj*ej
jjdjdi ZKe$dkdl ZLeLj*ej
jjdmdl ZLdndo ZMe$dpdq ZNdrds ZOe$dtdu ZPePj*dvdu ZPdwdx ZQddydzZRdd{d|ZSdd}d~ZTdd ZUdd ZVdd ZWdd ZXdd ZYdd ZZdd Z[dd Z\dd Z]e$dd Z^ej
jjdd Z_ fddZ` fddZadd Zbe$ecjddd Zedd Zfe$dd Zge$dd Zhe$dd Zid fdd	Zjdd Zkdd Zl  ZmS )Layera  Base layer class.

    This is the class from which all layers inherit.

    A layer is a class implementing common neural networks operations, such
    as convolution, batch norm, etc. These operations require managing weights,
    losses, updates, and inter-layer connectivity.

    Users will just instantiate a layer and then treat it as a callable.

    We recommend that descendants of `Layer` implement the following methods:

    * `__init__()`: Save configuration in member variables
    * `build()`: Called once from `__call__`, when we know the shapes of inputs
      and `dtype`. Should have the calls to `add_weight()`, and then
      call the super's `build()` (which sets `self.built = True`, which is
      nice in case the user wants to call `build()` manually before the
      first `__call__`).
    * `call()`: Called in `__call__` after making sure `build()` has been called
      once. Should actually perform the logic of applying the layer to the
      input tensors (which should be passed in as the first argument).

    Args:
      trainable: Boolean, whether the layer's variables should be trainable.
      name: String name of the layer.
      dtype: The dtype of the layer's computations and weights (default of
        `None` means use `tf.keras.backend.floatx` in TensorFlow 2, or the type
        of the first input in TensorFlow 1).
      dynamic: Set this to `True` if your layer should only be run eagerly, and
        should not be used to generate a static computation graph.
        This would be the case for a Tree-RNN or a recursive network,
        for example, or generally for any layer that manipulates tensors
        using Python control flow. If `False`, we assume that the layer can
        safely be used to generate a static computation graph.

    Attributes:
      name: The name of the layer (string).
      dtype: The dtype of the layer's computations and weights. If mixed
        precision is used with a `tf.keras.mixed_precision.Policy`, this is
        instead just the dtype of the layer's weights, as the computations are
        done in a different dtype.
      updates: List of update ops of this layer.
      losses: List of losses added by this layer.
      trainable_weights: List of variables to be included in backprop.
      non_trainable_weights: List of variables that should not be
        included in backprop.
      weights: The concatenation of the lists trainable_weights and
        non_trainable_weights (in this order).
      trainable: Whether the layer should be trained (boolean).
      input_spec: Optional (list of) `InputSpec` object(s) specifying the
        constraints on inputs that can be accepted by the layer.

    Each layer has a dtype, which is typically the dtype of the layer's
    computations and variables. A layer's dtype can be queried via the
    `Layer.dtype` property. The dtype is specified with the `dtype` constructor
    argument. In TensorFlow 2, the dtype defaults to `tf.keras.backend.floatx()`
    if no dtype is passed. `floatx()` itself defaults to "float32".
    Additionally, layers will cast their inputs to the layer's dtype in
    TensorFlow 2. When mixed precision is used, layers may have different
    computation and variable dtypes.  See `tf.keras.mixed_precision.Policy` for
    details on layer dtypes.
    )_obj_reference_counts_dictTNFc           	      K   s  |    h d}t|| || _d| _d| _d | _d | _d| _| 	| t
|dd | _| dg  | dg  g | _t | _g | _g | _g | _| | |dt | _| dg  g | _g | _|   || _d|v rd	|vr|d f|d	< d	|v sd
|v r^d
|v r$t|d
 }n4d	|v rXd|v rB|d }nd }|ft|d	  }|| _|dd | _ d| _!d| _"d| _#d S )N>   	input_dimweightsautocastimplementationinput_shapebatch_input_shapeactivity_regularizer
batch_sizeFr   _trainable_weights_non_trainable_weightsr   _self_tracked_trackablesr   r   r   r   r   T)$_instrument_layer_creationr   validate_kwargs
_trainable	_statefulbuilt_build_input_shape_input_specsupports_masking_init_set_namer   getpop_activity_regularizer_maybe_create_attribute_updates	threadinglocal_thread_local_callable_losses_losses_metrics_set_dtype_policyr   v2_dtype_behavior_enabled	_autocast_inbound_nodes_value_outbound_nodes_value_init_call_fn_args_dynamictuple_batch_input_shape_initial_weights_auto_track_sub_layers_originally_built_as_v1#_preserve_input_structure_in_config)	self	trainablenamedtypedynamickwargsallowed_kwargsr   r    rK   V/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/engine/base_layer_v1.py__init__   sX    







zLayer.__init__c                 C   s   t | jds|| _d| _dS )a  Creates the variables of the layer (optional, for subclass implementers).

        This is a method that implementers of subclasses of `Layer` or `Model`
        can override if they need a state-creation step in-between
        layer instantiation and layer call.

        This is typically used to create the weights of `Layer` subclasses.

        Args:
          input_shape: Instance of `TensorShape`, or list of instances of
            `TensorShape` if the layer expects a list of inputs
            (one instance per input).
        _is_defaultTN)hasattrbuildr(   r'   )rD   r   rK   rK   rL   rP      s    zLayer.buildc                 K   s   |S )zThis is where the layer's logic lives.

        Args:
            inputs: Input tensor, or list/tuple of input tensors.
            **kwargs: Additional keyword arguments.

        Returns:
            A tensor or list/tuple of tensors.
        rK   )rD   inputsrI   rK   rK   rL   call  s    z
Layer.callc                 C   s>   t |tjr|}n
t|}|r.| j| n| j| |S )a  Adds a Trackable object to this layer's state.

        Args:
          trackable_object: The tf.tracking.Trackable object to add.
          trainable: Boolean, whether the variable should be part of the layer's
            "trainable_variables" (e.g. variables, biases) or
            "non_trainable_variables" (e.g. BatchNorm mean and variance).

        Returns:
          The TrackableWeightHandler used to track this object.
        )
isinstancer   TrackableWeightHandlerr    appendr!   )rD   trackable_objectrE   handlerrK   rK   rL   _add_trackable  s    
zLayer._add_trackablec                    sZ  |du rd}|D ]}|dvrt d|qd|v }|dtj}|dd}|dd}|d	d}|du rx| jpvt }t|}| j	j
du r| t|jj t|}t|}t|}|
tjjkr|rtd
qd}n|du rd}|du rL|jr
td}nB|js"|js"|jr0tjj }n|sLtd||j| jf |r| j	j| j	j
kr|jr|  fdd}|durt d d}| j!|||d||||||	||
||d}|dur|jd|j"d }| #||| t$|r,|D ]0}t%| |r| j&'| n| j('| qn*t%| |rJ| j&'| n| j('| |S )aa  Adds a new variable to the layer.

        Args:
          name: Variable name.
          shape: Variable shape. Defaults to scalar if unspecified.
          dtype: The type of the variable. Defaults to `self.dtype` or
            `float32`.
          initializer: Initializer instance (callable).
          regularizer: Regularizer instance (callable).
          trainable: Boolean, whether the variable should be part of the layer's
            "trainable_variables" (e.g. variables, biases)
            or "non_trainable_variables" (e.g. BatchNorm mean and variance).
            Note that `trainable` cannot be `True` if `synchronization`
            is set to `ON_READ`.
          constraint: Constraint instance (callable).
          partitioner: Partitioner to be passed to the `Trackable` API.
          use_resource: Whether to use `ResourceVariable`.
          synchronization: Indicates when a distributed a variable will be
            aggregated. Accepted values are constants defined in the class
            `tf.VariableSynchronization`. By default the synchronization is set
            to `AUTO` and the current `DistributionStrategy` chooses when to
            synchronize. If `synchronization` is set to `ON_READ`, `trainable`
            must not be set to `True`.
          aggregation: Indicates how a distributed variable will be aggregated.
            Accepted values are constants defined in the class
            `tf.VariableAggregation`.
          **kwargs: Additional keyword arguments. Accepted values are `getter`,
            `collections`, `experimental_autocast` and `caching_device`.

        Returns:
          The created variable. Usually either a `Variable` or
          `ResourceVariable` instance. If `partitioner` is not `None`, a
          `PartitionedVariable` instance is returned.

        Raises:
          RuntimeError: If called with partitioned variable regularization and
            eager execution is enabled.
          ValueError: When giving unsupported dtype and no initializer or when
            trainable has been set to True with synchronization set as
            `ON_READ`.
        NrK   )gettercollectionsexperimental_autocastcaching_devicezUnknown keyword argument:rY   rZ   r[   Tr\   zSynchronization value can be set to VariableSynchronization.ON_READ only for non-trainable variables. You have specified trainable=True and synchronization=VariableSynchronization.ON_READ.Fglorot_uniformzBAn initializer for variable %s of type %s is required for layer %sc                     s    | i |}t |S N)r	   create_autocast_variable)argsrI   variable
old_getterrK   rL   rY     s    z Layer.add_weight.<locals>.getterzb`caching_device` does not work with mixed precision API. Ignoring user specified `caching_device`.)rF   shaperY   	overwriteinitializerrG   
constraintrE   partitioneruse_resourcerZ   synchronizationaggregationr\   :))	TypeErrorr-   r   make_variablerG   r   floatxtfas_dtype_dtype_policyvariable_dtyper7   r   Policy
base_dtyperF   r   r,   r   r   VariableSynchronizationON_READ
ValueErroris_floating
is_integeris_unsignedis_boolcompatv1zeros_initializercompute_dtyper   warning _add_variable_with_custom_getterfind_handle_weight_regularizationis_split_variabletrack_variabler    rU   r!   )rD   rF   rd   rG   rf   regularizerrE   rg   rh   ri   rj   rk   rI   kwargZhas_custom_getterrY   collections_argr   r\   ra   name_in_scopevrK   rb   rL   
add_weight8  s    9



	




zLayer.add_weightc                    s   t | jj}| j| jd}t| dr0| j|d< t	| j
|d< t| drn| jr\| j|d< nd|v rn|d |   fdd|D }t|dkrt| jd	rtd
|S )a  Returns the config of the layer.

        A layer config is a Python dictionary (serializable)
        containing the configuration of a layer.
        The same layer can be reinstantiated later
        (without its trained weights) from this configuration.

        The config of a layer does not include connectivity
        information, nor the layer class name. These are handled
        by `Network` (one layer of abstraction above).

        Returns:
            Python dictionary.
        )rF   rE   r?   r   rG   rH   c                    s   g | ]}| vr|qS rK   rK   ).0argexpected_argsrK   rL   
<listcomp>      z$Layer.get_config.<locals>.<listcomp>   rN   z?Layers with arguments in `__init__` must override `get_config`.)r   getfullargspecrM   r`   rF   rE   rO   r?   r   	serializerr   rH   removekeyslen
get_configNotImplementedError)rD   all_argsconfig
extra_argsrK   r   rL   r     s"    



zLayer.get_configc                 C   s   | f i |S )a  Creates a layer from its config.

        This method is the reverse of `get_config`,
        capable of instantiating the same layer from the config
        dictionary. It does not handle layer connectivity
        (handled by Network), nor weights (handled by `set_weights`).

        Args:
            config: A Python dictionary, typically the
                output of get_config.

        Returns:
            A layer instance.
        rK   )clsr   rK   rK   rL   from_config  s    zLayer.from_configc                 C   s   t  r| | t jj   t jd}| v t	j
|dd}t jtj|}z| |dd}W n6 ty } ztd| jj |W Y d}~n
d}~0 0 W d   n1 s0    Y  W d   n1 s0    Y  t jdd |S tdS )	a/  Computes the output shape of the layer.

        If the layer has not been built, this method will call `build` on the
        layer. This assumes that the layer will later be used with inputs that
        match the input shape provided here.

        Args:
            input_shape: Shape tuple (tuple of integers)
                or list of shape tuples (one per output tensor of the layer).
                Shape tuples can include None for free dimensions,
                instead of an integer.

        Returns:
            An input shape tuple.
        graphF)	to_tuples)trainingzWe could not automatically infer the static shape of the layer's output. Please implement the `compute_output_shape` method on your layer (%s).Nc                 S   s   | j S r^   rd   trK   rK   rL   <lambda>Z  r   z,Layer.compute_output_shape.<locals>.<lambda>)rp   executing_eagerly_maybe_buildr}   r~   get_default_graph
as_default__internal__	FuncGraphr   convert_shapesnestmap_structurer    generate_placeholders_from_shaperm   r   	__class____name__)rD   r   r   rQ   outputserK   rK   rL   compute_output_shape.  s0    

TzLayer.compute_output_shapec                    sb   dd }t j||}| |}| j  du rLdd t j|D }|d  t j fdd|S )	a  Compute the output tensor signature of the layer based on the inputs.

        Unlike a TensorShape object, a TensorSpec object contains both shape
        and dtype information for a tensor. This method allows layers to provide
        output dtype information if it is different from the input dtype.
        For any layer that doesn't implement this function,
        the framework will fall back to use `compute_output_shape`, and will
        assume that the output dtype matches the input dtype.

        Args:
          input_signature: Single TensorSpec or nested structure of TensorSpec
            objects, describing a candidate input for the layer.

        Returns:
          Single TensorSpec or nested structure of TensorSpec objects,
            describing how the layer would transform the provided input.

        Raises:
          TypeError: If input_signature contains a non-TensorSpec object.
        c                 S   s    t | tjstd| | jS )NzKOnly TensorSpec signature types are supported, but saw signature entry: {}.)rS   rp   
TensorSpecrm   formatrd   srK   rK   rL   check_type_return_shapet  s    z?Layer.compute_output_signature.<locals>.check_type_return_shapeNc                 S   s   g | ]
}|j qS rK   rG   )r   r   rK   rK   rL   r     r   z2Layer.compute_output_signature.<locals>.<listcomp>r   c                    s   t j | dS )N)rG   rd   )rp   r   r   r   rK   rL   r     r   z0Layer.compute_output_signature.<locals>.<lambda>)rp   r   r   r   _compute_dtypeflatten)rD   input_signaturer   r   output_shapeinput_dtypesrK   r   rL   compute_output_signature]  s    
zLayer.compute_output_signaturec                 C   sB   | j s>tdd tj|D r:td| j d t| dS |S )a  Computes an output mask tensor.

        Args:
            inputs: Tensor or list of tensors.
            mask: Tensor or list of tensors.

        Returns:
            None or a tensor (or list of tensors,
                one per output tensor of the layer).
        c                 s   s   | ]}|d uV  qd S r^   rK   r   mrK   rK   rL   	<genexpr>  r   z%Layer.compute_mask.<locals>.<genexpr>Layer z9 does not support masking, but was passed an input_mask: N)r*   anyrp   r   r   rm   rF   str)rD   rQ   maskrK   rK   rL   compute_mask  s    zLayer.compute_maskc                 O   s  |    t| dstd|r4|d }|dd }n,| jjd |v rX|| jjd }ntdt }t	j
|}t|}tdd |D rd	d
 }t	j
||}t	j
|}d}| |||}	| jr|	dur| jd||sd}|	|d< d}
d}| jd||r*| jd||}
| js*|d |
du r|jdurH|j}
nZt r\t }
nF|rt  " t rt }
W d   n1 s0    Y  | jr|
durt	|
rt	|
t	j}
nt|
}
| jd|
||\}}d}|rt |rt!| |"| |||
 |r@t#$| j#|| j% t }|  t&| '  | (| | )|}t*| rt+| st	j,j-.| j/t	j,j-0 }n| j/}| j1s@zHt23| j4& ||g|R i |}W d   n1 s0    Y  W n> t	j5j6y< } z t7dt8| d W Y d}~n
d}~0 0 n
| 9|}|du rftd| j% d t:|r|r| jjdd||dd\}}|r|d | ;|f| ||}| <|| | =|||	 t| dr| j>s| ?||| | @|| W d   n1 s0    Y  W d   n1 s40    Y  nt&| '  | (| | )|}t23| j4( | j/|g|R i |}W d   n1 s0    Y  | <|| | =|||	 W d   n1 s0    Y  W d   n1 s0    Y  |S )aa  Wraps `call`, applying pre- and post-processing steps.

        Args:
          *args: Positional arguments to be passed to `self.call`.
          **kwargs: Keyword arguments to be passed to `self.call`.

        Returns:
          Output tensor(s).

        Note:
          - The following optional keyword arguments are reserved for specific
            uses:
            * `training`: Boolean scalar tensor of Python boolean indicating
              whether the `call` is meant for training or inference.
            * `mask`: Boolean input mask.
          - If the layer's `call` method takes a `mask` argument (as some Keras
            layers do), its default value will be set to the mask generated
            for `inputs` by the previous layer (if `input` did come from
            a layer that generated a corresponding mask, i.e. if it came from
            a Keras layer with masking support.

        Raises:
          ValueError: if the layer's `call` method returns None (an invalid
            value).
          RuntimeError: if `super().__init__()` was not called in the
            constructor.
        r3   z<You must call `super().__init__()` in the layer constructor.r   r   Nz9The first argument to `Layer.call` must always be passed.c                 s   s    | ]}t |tjttfV  qd S r^   )rS   npndarrayfloatintr   xrK   rK   rL   r     r   z!Layer.__call__.<locals>.<genexpr>c                 S   s    t | tjttfrt| S | S r^   )rS   r   r   r   r   rp   convert_to_tensorr   rK   rK   rL   _convert_non_tensor  s    
z+Layer.__call__.<locals>._convert_non_tensorFr   Tr   zYou are attempting to use Python control flow in a layer that was not declared to be dynamic. Pass `dynamic=True` to the class constructor.
Encountered error:
"""
z
"""zVA layer's `call` method should return a Tensor or a list of Tensors, not None (layer: z).)pop_kwarg_if_none_set_inputs)A_assert_built_as_v1rO   RuntimeError
_call_spec	arg_namesr-   rx   r   call_contextrp   r   r   r   are_all_symbolic_tensorsr   r   _collect_input_masks_expects_mask_argarg_was_passedget_arg_value_expects_training_argr   r   global_learning_phase_is_setlearning_phase	get_graphr   is_in_keras_graph	is_tensorcastboolset_arg_valueneeds_keras_historycreate_keras_historyenterr   assert_input_compatibilityrF   
name_scope_name_scoper   _maybe_cast_inputsis_subclassedfrom_saved_modelr   	autograph
tf_convertrR   control_status_ctxrH   r	   enable_auto_cast_variables_compute_dtype_objecterrorsOperatorNotAllowedInGraphErrorrm   r   _symbolic_callhave_all_keras_metadata_set_connectivity_metadata_handle_activity_regularization_set_mask_metadatarQ   _set_save_specr   )rD   r`   rI   rQ   r   
input_listbuild_graphr   mask_arg_passed_by_frameworkinput_maskstraining_value training_arg_passed_by_frameworkr   cast_inputscall_fnr   r   rK   rK   rL   __call__  s    






(




:



N

8NzLayer.__call__c                 C   s    t | dstdt| f d S )NrB   a  Your Layer or Model is in an invalid state. This can happen for the following cases:
 1. You might be interleaving estimator/non-estimator models or interleaving models/layers made in tf.compat.v1.Graph.as_default() with models/layers created outside of it. Converting a model to an estimator (via model_to_estimator) invalidates all models/layers made before the conversion (even if they were not the model converted to an estimator). Similarly, making a layer or a model inside a a tf.compat.v1.Graph invalidates all layers/models you previously made outside of the graph.
2. You might be using a custom keras layer implementation with custom __init__ which didn't call super().__init__.  Please check the implementation of %s and its bases.)rO   rx   typerD   rK   rK   rL   r     s    
zLayer._assert_built_as_v1c                 C   s   | j jS r^   rr   rs   r  rK   rK   rL   rG     s    zLayer.dtypec                 C   s   | j S r^   )_namer  rK   rK   rL   rF     s    z
Layer.namec                 C   s   t dd |  D S )Nc                 s   s   | ]}|j V  qd S r^   )r=   r   layerrK   rK   rL   r     r   z Layer.dynamic.<locals>.<genexpr>r   _flatten_layersr  rK   rK   rL   rH     s    zLayer.dynamicc                 C   s   t dd |  D S )Nc                 s   s   | ]}|j V  qd S r^   r&   r  rK   rK   rL   r     r   z!Layer.stateful.<locals>.<genexpr>r  r  rK   rK   rL   stateful  s    zLayer.statefulc                 C   s
   || _ d S r^   r  rD   valuerK   rK   rL   r    s    c                 C   s   | j S r^   )r%   r  rK   rK   rL   rE     s    zLayer.trainablec                 C   s"   || _ t| dg D ]
}||_qd S )Nr"   )r%   getattrrE   )rD   r  r  rK   rK   rL   rE     s    c                 C   s   | j S );Optional regularizer function for the output of this layer.r.   r  rK   rK   rL   r     s    zLayer.activity_regularizerc                 C   s
   || _ dS )r  Nr  )rD   r   rK   rK   rL   r     s    c                 C   s   | j S r^   )r)   r  rK   rK   rL   r     s    zLayer.input_specc                 C   s>   t j|D ]&}|d urt|tjstd|q|| _d S )Nz:Layer input_spec must be an instance of InputSpec. Got: {})	rp   r   r   rS   r   	InputSpecrm   r   r)   )rD   r  r   rK   rK   rL   r     s    c                 C   s   g }|   }t   |D ]}|js0|js0q|jD ]r}t|rz
| }W nB ty } z*dt	|j
v rxtjddd  W Y d }~n
d }~0 0 tj|dd || q6qW d    n1 s0    Y  |S )NInaccessibleTensorError
add_updateT)methodforce_raiser  )r  r   r   r   rE   r  r0   callablerx   r  r   r   check_graph_consistencyrU   )rD   Zcollected_updates
all_layersr  ur   rK   rK   rL   updates  s*    

,zLayer.updatesc                 C   sJ   g }|   }|D ]4}||j |jD ]}| }|dur&|| q&q|S )aS  Losses which are associated with this `Layer`.

        Variable regularization tensors are created when this property is
        accessed, so it is eager safe: accessing `losses` under a
        `tf.GradientTape` will propagate gradients back to the corresponding
        variables.

        Returns:
          A list of tensors.
        N)r  extendr5   r4   rU   )rD   collected_lossesr  r  r   loss_tensorrK   rK   rL   losses  s    
zLayer.lossesc           	         s    fdd}t j|}g }g }|D ]t}t|rD|t|| q$|du rNq$t |sjt j|t	
 d}t|r$t s$||| tj|dd q$| j| t j}|r|D ]}| j| qn.|D ](}t| ddr| | q| j| qdS )	a
  Add loss tensor(s), potentially dependent on layer inputs.

        Some losses (for instance, activity regularization losses) may be
        dependent on the inputs passed when calling a layer. Hence, when reusing
        the same layer on different inputs `a` and `b`, some entries in
        `layer.losses` may be dependent on `a` and some on `b`. This method
        automatically keeps track of dependencies.

        This method can be used inside a subclassed layer or model's `call`
        function, in which case `losses` should be a Tensor or list of Tensors.

        Example:

        ```python
        class MyLayer(tf.keras.layers.Layer):
          def call(inputs, self):
            self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True)
            return inputs
        ```

        This method can also be called directly on a Functional Model during
        construction. In this case, any loss Tensors passed to this Model must
        be symbolic and be able to be traced back to the model's `Input`s. These
        losses become part of the model's topology and are tracked in
        `get_config`.

        Example:

        ```python
        inputs = tf.keras.Input(shape=(10,))
        x = tf.keras.layers.Dense(10)(inputs)
        outputs = tf.keras.layers.Dense(1)(x)
        model = tf.keras.Model(inputs, outputs)
        # Activity regularization.
        model.add_loss(tf.abs(tf.reduce_mean(x)))
        ```

        If this is not the case for your loss (if, for example, your loss
        references a `Variable` of one of the model's layers), you can wrap your
        loss in a zero-argument lambda. These losses are not tracked as part of
        the model's topology since they can't be serialized.

        Example:

        ```python
        inputs = tf.keras.Input(shape=(10,))
        x = tf.keras.layers.Dense(10)(inputs)
        outputs = tf.keras.layers.Dense(1)(x)
        model = tf.keras.Model(inputs, outputs)
        # Weight regularization.
        model.add_loss(lambda: tf.reduce_mean(x.kernel))
        ```

        Args:
          losses: Loss tensor, or list/tuple of tensors. Rather than tensors,
            losses may also be zero-argument callables which create a loss
            tensor.
          inputs: Ignored when executing eagerly. If anything other than None is
            passed, it signals the losses are conditional on some of the layer's
            inputs, and thus they should only be run where these inputs are
            available. This is the case for activity regularization losses, for
            instance. If `None` is passed, the losses are assumed
            to be unconditional, and will apply across all dataflows of the
            layer (e.g. weight regularization losses).
        c                    sn   t | r8td |  } W d   n1 s.0    Y  | du rDdS t| s`tj| t d}  du | _| S )z<Process the loss and tag it by setting ._unconditional_loss.Nr   )	r  r	   r   rp   r   r   r   ro   _unconditional_loss)lossrQ   rK   rL   _tag_unconditionalS  s    $

z*Layer.add_loss.<locals>._tag_unconditionalNr   add_lossr  _is_graph_networkF)rp   r   r   r  rU   	functoolspartialr   r   r   ro   r   is_symbolic_tensorr   is_in_tf_functionr  r4   r!  r   in_callr5   r  _graph_network_add_loss)	rD   r$  rQ   r(  callable_lossessymbolic_lossesr&  in_call_contextsymbolic_lossrK   r'  rL   r)    s>    D


zLayer.add_lossc                 C   s"   g }|   D ]}||j q|S r^   )r  r!  r6   )rD   collected_metricsr  rK   rK   rL   metrics  s    zLayer.metricsc                 C   s   |dur|dkrt d| t|d}t|}t j}|du rP|sPt dn|r\|jj}|rp| 	||| nx|st dt
| t| ddst   | 	||| W d   n1 s0    Y  dS |rt d	| ||| dS )
a  Adds metric tensor to the layer.

        Args:
          value: Metric tensor.
          aggregation: Sample-wise metric reduction function. If
            `aggregation=None`, it indicates that the metric tensor provided has
            been aggregated already. eg, `bin_acc = BinaryAccuracy(name='acc')`
            followed by `model.add_metric(bin_acc(y_true, y_pred))`. If
            aggregation='mean', the given metric tensor will be sample-wise
            reduced using `mean` function.  eg,
            `model.add_metric(tf.reduce_sum(outputs), name='output_mean',
            aggregation='mean')`.
          name: String metric name.

        Raises:
          ValueError: If `aggregation` is anything other than None or `mean`.
        Nmeanz^We currently support only `mean` sample-wise metric aggregation. You provided aggregation=`%s`_metric_objzPlease provide a name for your metric like `self.add_metric(tf.reduce_sum(inputs), name='mean_activation', aggregation='mean')`z;Expected a symbolic Tensor for the metric value, received: r*  FzUsing the result of calling a `Metric` object when calling `add_metric` on a Functional Model is not supported. Please pass the Tensor to monitor directly.)rx   rO   r   r-  r   r   r/  r8  rF   _symbolic_add_metricr   r  r   r   r   _graph_network_add_metric)rD   r  rk   rF   from_metric_objis_symbolicr3  rK   rK   rL   
add_metric  s@    


,zLayer.add_metricc                    s   t  }tj r&tj r&|js&dS t|}|j	r>|j
nt| dg }dd |D  fdd  fdd|D }| j| dS )a=  Add update op(s), potentially dependent on layer inputs.

        Weight updates (for instance, the updates of the moving mean and
        variance in a BatchNormalization layer) may be dependent on the inputs
        passed when calling a layer. Hence, when reusing the same layer on
        different inputs `a` and `b`, some entries in `layer.updates` may be
        dependent on `a` and some on `b`. This method automatically keeps track
        of dependencies.

        The `get_updates_for` method allows to retrieve the updates relevant to
        a specific set of inputs.

        This call is ignored when eager execution is enabled (in that case,
        variable updates are run on the fly and thus do not need to be tracked
        for later execution).

        Args:
          updates: Update op, or list/tuple of update ops, or zero-arg callable
            that returns an update op. A zero-arg callable should be passed in
            order to disable running the updates by setting `trainable=False`
            on this Layer, when executing in Eager mode.
        N_inbound_nodesc                 S   s   g | ]
}|j qS rK   )input_tensorsr   noderK   rK   rL   r     r   z$Layer.add_update.<locals>.<listcomp>c                    sf   t  r fdd}| S t tjr. }nt dr@ j}n
t }t|g}||v|_	|S )zStandardize update ops.

            Args:
              x: Tensor, op, or callable.

            Returns:
              An update op.
            c                      s
     S r^   rK   rK   )process_updater   rK   rL   r     r   z:Layer.add_update.<locals>.process_update.<locals>.<lambda>op)
r  rS   rp   	OperationrO   rC  r   r   get_reachable_from_inputs_unconditional_update)r   update	reachablerB  Zrelevant_inputsr   rL   rB    s    	


z(Layer.add_update.<locals>.process_updatec                    s   g | ]} |qS rK   rK   r   )rB  rK   rL   r   !  r   )r   r   rp   
distributehas_strategyin_cross_replica_contextsavingr   to_listr/  rQ   r  r0   r!  )rD   r   r   inbound_nodesrK   rI  rL   r    s     
zLayer.add_updatec                 C   s  | j }d}|D ]$}t|tjr*||j7 }q|d7 }q|t|krftd| jt||t|dd f d}g }|D ]}t|tjr|j}||||  }|	| ||7 }qr|| }	t
|	dr|	jnd}
|j}||
std||
f |||	f |d7 }qrt| dS )	a  Sets the weights of the layer, from Numpy arrays.

        The weights of a layer represent the state of the layer. This function
        sets the weight values from numpy arrays. The weight values should be
        passed in the order they are created by the layer. Note that the layer's
        weights must be instantiated before calling this function by calling
        the layer.

        For example, a Dense layer returns a list of two values-- per-output
        weights and the bias value. These can be used to set the weights of
        another Dense layer:

        >>> a = tf.keras.layers.Dense(1,
        ...   kernel_initializer=tf.constant_initializer(1.))
        >>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
        >>> a.get_weights()
        [array([[1.],
               [1.],
               [1.]], dtype=float32), array([0.], dtype=float32)]
        >>> b = tf.keras.layers.Dense(1,
        ...   kernel_initializer=tf.constant_initializer(2.))
        >>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
        >>> b.get_weights()
        [array([[2.],
               [2.],
               [2.]], dtype=float32), array([0.], dtype=float32)]
        >>> b.set_weights(a.get_weights())
        >>> b.get_weights()
        [array([[1.],
               [1.],
               [1.]], dtype=float32), array([0.], dtype=float32)]

        Args:
            weights: a list of Numpy arrays. The number
                of arrays and their shape must match
                number of the dimensions of the weights
                of the layer (i.e. it should match the
                output of `get_weights`).

        Raises:
            ValueError: If the provided weights list does not match the
                layer's specifications.
        r   r   zYou called `set_weights(weights)` on layer "%s" with a weight list of length %s, but the layer was expecting %s weights. Provided weights: %s...N2   rd   rK   zBLayer weight shape %s not compatible with provided weight shape %s)r   rS   r   rT   num_tensorsr   rx   rF   r   set_weightsrO   rd   is_compatible_withrU   r   batch_set_value)rD   r   paramsexpected_num_weightsparamweight_indexweight_value_tuplesrQ  tensorsweightweight_shape	ref_shaperK   rK   rL   rR  $  sH    ,




zLayer.set_weightsc                 C   sD   | j }g }|D ]*}t|tjr.||  q|| qt|S )ac  Returns the current weights of the layer.

        The weights of a layer represent the state of the layer. This function
        returns both trainable and non-trainable weight values associated with
        this layer as a list of Numpy arrays, which can in turn be used to load
        state into similarly parameterized layers.

        For example, a Dense layer returns a list of two values-- per-output
        weights and the bias value. These can be used to set the weights of
        another Dense layer:

        >>> a = tf.keras.layers.Dense(1,
        ...   kernel_initializer=tf.constant_initializer(1.))
        >>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
        >>> a.get_weights()
        [array([[1.],
               [1.],
               [1.]], dtype=float32), array([0.], dtype=float32)]
        >>> b = tf.keras.layers.Dense(1,
        ...   kernel_initializer=tf.constant_initializer(2.))
        >>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
        >>> b.get_weights()
        [array([[2.],
               [2.],
               [2.]], dtype=float32), array([0.], dtype=float32)]
        >>> b.set_weights(a.get_weights())
        >>> b.get_weights()
        [array([[1.],
               [1.],
               [1.]], dtype=float32), array([0.], dtype=float32)]

        Returns:
            Weights values as a list of numpy arrays.
        )	r   rS   r   rT   r!  get_tensorsrU   r   batch_get_value)rD   r   output_weightsr[  rK   rK   rL   get_weights|  s    #zLayer.get_weightsc                    sR   |du rdd | j D S dd | j D }tj|}t||  fdd|D S )zRetrieves updates relevant to a specific set of inputs.

        Args:
          inputs: Input tensor or list/tuple of input tensors.

        Returns:
          List of update ops of the layer that depend on `inputs`.
        Nc                 S   s   g | ]}|j r|qS rK   rF  r   r  rK   rK   rL   r     r   z)Layer.get_updates_for.<locals>.<listcomp>c                 S   s   g | ]}|j s|qS rK   rb  rc  rK   rK   rL   r     r   c                    s   g | ]}| v r|qS rK   rK   rc  rH  rK   rL   r     r   )r   rp   r   r   r   rE  )rD   rQ   r   rK   rd  rL   get_updates_for  s    	zLayer.get_updates_forc                    sR   |du rdd | j D S dd | j D }tj|}t||  fdd|D S )zRetrieves losses relevant to a specific set of inputs.

        Args:
          inputs: Input tensor or list/tuple of input tensors.

        Returns:
          List of loss tensors of the layer that depend on `inputs`.
        Nc                 S   s   g | ]}|j r|qS rK   r%  r   lrK   rK   rL   r     r   z(Layer.get_losses_for.<locals>.<listcomp>c                 S   s   g | ]}|j s|qS rK   rf  rg  rK   rK   rL   r     r   c                    s   g | ]}| v r|qS rK   rK   rg  rd  rK   rL   r     r   )r$  rp   r   r   r   rE  )rD   rQ   r$  rK   rd  rL   get_losses_for  s    	zLayer.get_losses_forc                 C   s2   |  |}t|tr"dd |D S t|ddS dS )a  Retrieves the input mask tensor(s) of a layer at a given node.

        Args:
            node_index: Integer, index of the node
                from which to retrieve the attribute.
                E.g. `node_index=0` will correspond to the
                first time the layer was called.

        Returns:
            A mask tensor
            (or list of tensors if the layer has multiple inputs).
        c                 S   s   g | ]}t |d dqS _keras_maskNr  r   rK   rK   rL   r     r   z+Layer.get_input_mask_at.<locals>.<listcomp>rk  N)get_input_atrS   listr  )rD   
node_indexrQ   rK   rK   rL   get_input_mask_at  s    

zLayer.get_input_mask_atc                 C   s2   |  |}t|tr"dd |D S t|ddS dS )a  Retrieves the output mask tensor(s) of a layer at a given node.

        Args:
            node_index: Integer, index of the node
                from which to retrieve the attribute.
                E.g. `node_index=0` will correspond to the
                first time the layer was called.

        Returns:
            A mask tensor
            (or list of tensors if the layer has multiple outputs).
        c                 S   s   g | ]}t |d dqS rj  rl  r   rK   rK   rL   r     r   z,Layer.get_output_mask_at.<locals>.<listcomp>rk  N)get_output_atrS   rn  r  )rD   ro  outputrK   rK   rL   get_output_mask_at  s    

zLayer.get_output_mask_atc                 C   s.   | j }t|trdd |D S t|ddS dS )a  Retrieves the input mask tensor(s) of a layer.

        Only applicable if the layer has exactly one inbound node,
        i.e. if it is connected to one incoming layer.

        Returns:
            Input mask tensor (potentially None) or list of input
            mask tensors.

        Raises:
            AttributeError: if the layer is connected to
            more than one incoming layers.
        c                 S   s   g | ]}t |d dqS rj  rl  r   rK   rK   rL   r     r   z$Layer.input_mask.<locals>.<listcomp>rk  N)inputrS   rn  r  )rD   rQ   rK   rK   rL   
input_mask  s    
zLayer.input_maskc                 C   s.   | j }t|trdd |D S t|ddS dS )a  Retrieves the output mask tensor(s) of a layer.

        Only applicable if the layer has exactly one inbound node,
        i.e. if it is connected to one incoming layer.

        Returns:
            Output mask tensor (potentially None) or list of output
            mask tensors.

        Raises:
            AttributeError: if the layer is connected to
            more than one incoming layers.
        c                 S   s   g | ]}t |d dqS rj  rl  r   rK   rK   rL   r     r   z%Layer.output_mask.<locals>.<listcomp>rk  N)rr  rS   rn  r  )rD   rr  rK   rK   rL   output_mask	  s    
zLayer.output_maskc                 C   s   |  |ddS )a  Retrieves the input shape(s) of a layer at a given node.

        Args:
            node_index: Integer, index of the node
                from which to retrieve the attribute.
                E.g. `node_index=0` will correspond to the
                first time the layer was called.

        Returns:
            A shape tuple
            (or list of shape tuples if the layer has multiple inputs).

        Raises:
          RuntimeError: If called in Eager mode.
        input_shapeszinput shape_get_node_attribute_at_indexrD   ro  rK   rK   rL   get_input_shape_at  s    zLayer.get_input_shape_atc                 C   s   |  |ddS )a  Retrieves the output shape(s) of a layer at a given node.

        Args:
            node_index: Integer, index of the node
                from which to retrieve the attribute.
                E.g. `node_index=0` will correspond to the
                first time the layer was called.

        Returns:
            A shape tuple
            (or list of shape tuples if the layer has multiple outputs).

        Raises:
          RuntimeError: If called in Eager mode.
        output_shapeszoutput shaperx  rz  rK   rK   rL   get_output_shape_at2  s    zLayer.get_output_shape_atc                 C   s   |  |ddS )a  Retrieves the input tensor(s) of a layer at a given node.

        Args:
            node_index: Integer, index of the node
                from which to retrieve the attribute.
                E.g. `node_index=0` will correspond to the
                first input node of the layer.

        Returns:
            A tensor (or list of tensors if the layer has multiple inputs).

        Raises:
          RuntimeError: If called in Eager mode.
        r?  rt  rx  rz  rK   rK   rL   rm  F  s    zLayer.get_input_atc                 C   s   |  |ddS )a  Retrieves the output tensor(s) of a layer at a given node.

        Args:
            node_index: Integer, index of the node
                from which to retrieve the attribute.
                E.g. `node_index=0` will correspond to the
                first output node of the layer.

        Returns:
            A tensor (or list of tensors if the layer has multiple outputs).

        Raises:
          RuntimeError: If called in Eager mode.
        output_tensorsrr  rx  rz  rK   rK   rL   rq  Y  s    zLayer.get_output_atc                 C   s&   | j std| j d | dddS )af  Retrieves the input tensor(s) of a layer.

        Only applicable if the layer has exactly one input,
        i.e. if it is connected to one incoming layer.

        Returns:
            Input tensor or list of input tensors.

        Raises:
          RuntimeError: If called in Eager mode.
          AttributeError: If no inbound nodes are found.
        r   z& is not connected, no input to return.r   r?  rt  r>  AttributeErrorrF   ry  r  rK   rK   rL   rt  l  s
    zLayer.inputc                 C   s&   | j std| j d | dddS )a  Retrieves the output tensor(s) of a layer.

        Only applicable if the layer has exactly one output,
        i.e. if it is connected to one incoming layer.

        Returns:
          Output tensor or list of output tensors.

        Raises:
          AttributeError: if the layer is connected to more than one incoming
            layers.
          RuntimeError: if called in Eager mode.
        r   z has no inbound nodes.r   r~  rr  r  r  rK   rK   rL   rr    s
    zLayer.outputc                 C   s^   | j std| j dtdd | j D }t|dkrD| j d jS tdt| j d dS )	a  Retrieves the input shape(s) of a layer.

        Only applicable if the layer has exactly one input,
        i.e. if it is connected to one incoming layer, or if all inputs
        have the same shape.

        Returns:
            Input shape, as an integer shape tuple
            (or list of shape tuples, one tuple per input tensor).

        Raises:
            AttributeError: if the layer has no defined input_shape.
            RuntimeError: if called in Eager mode.
        zThe layer "z" has never been called and thus has no defined input shape. Note that the `input_shape` property is only available for Functional and Sequential models.c                 S   s   g | ]}t |jqS rK   )r   rw  r@  rK   rK   rL   r     r   z%Layer.input_shape.<locals>.<listcomp>r   r   z has multiple inbound nodes, with different input shapes. Hence the notion of "input shape" is ill-defined for the layer. Use `get_input_shape_at(node_index)` instead.N)r>  r  rF   setr   rw  r   )rD   all_input_shapesrK   rK   rL   r     s    zLayer.input_shapec                 C   sr   | j sft| ddrJt|  | | j W d   qf1 s>0    Y  ntd| j d | j d t	| j
S )zCount the total number of scalars composing the weights.

        Returns:
            An integer count.

        Raises:
            ValueError: if the layer isn't yet built
              (in which case its weights aren't yet defined).
        r*  FNz$You tried to call `count_params` on z=, but the layer isn't built. You can build it manually via: `z.build(batch_input_shape)`.)r'   r  r   maybe_init_scoper   rQ   rx   rF   r   count_paramsr   r  rK   rK   rL   r    s     
,zLayer.count_paramsc                 C   sL   | j stdtdd | j D }t|dkr:| j d jS td| j dS )a  Retrieves the output shape(s) of a layer.

        Only applicable if the layer has one output,
        or if all outputs have the same shape.

        Returns:
            Output shape, as an integer shape tuple
            (or list of shape tuples, one tuple per output tensor).

        Raises:
            AttributeError: if the layer has no defined output shape.
            RuntimeError: if called in Eager mode.
        zEThe layer has never been called and thus has no defined output shape.c                 S   s   g | ]}t |jqS rK   )r   r|  r@  rK   rK   rL   r     r   z&Layer.output_shape.<locals>.<listcomp>r   r   zThe layer "%s" has multiple inbound nodes, with different output shapes. Hence the notion of "output shape" is ill-defined for the layer. Use `get_output_shape_at(node_index)` instead.N)r>  r  r  r   r|  rF   )rD   all_output_shapesrK   rK   rL   r     s    zLayer.output_shapec                 C   s   | j S z?Deprecated, do NOT use! Only for external Keras compatibility .)r>  r  rK   rK   rL   rO    s    zLayer.inbound_nodesc                 C   s   | j S r  )_outbound_nodesr  rK   rK   rL   outbound_nodes  s    zLayer.outbound_nodesc                 C   s   | j S )zReturns the list of all layer variables/weights.

        Alias of `self.weights`.

        Returns:
          A list of variables.
        )r   r  rK   rK   rL   	variables  s    	zLayer.variablesc                 C   s   | j S r^   )trainable_weightsr  rK   rK   rL   trainable_variables  s    zLayer.trainable_variablesc                 C   s   | j S r^   )non_trainable_weightsr  rK   rK   rL   non_trainable_variables  s    zLayer.non_trainable_variablesc                 C   s   | j S r^   r:   r  rK   rK   rL   r>    s    zLayer._inbound_nodesc                 C   s
   || _ d S r^   r  r  rK   rK   rL   r>  #  s    c                 C   s   | j S r^   r;   r  rK   rK   rL   r  (  s    zLayer._outbound_nodesc                 C   s
   || _ d S r^   r  r  rK   rK   rL   r  ,  s    c                 C   s   t |tjr|| _n\t |tr,t|| _nDt |trL|dv rLt|| _n$|rftt|j	| _n
t
 | _| jj	dkrt stj }td|jj| jj	f | jjrt| jj| _nd| _dS )zSets self._dtype_policy.)mixed_float16mixed_bfloat16r  zMixed precision is not supported with the tf.distribute.Strategy: %s. Either stop using mixed precision by removing the use of the "%s" policy or use a different Strategy, e.g. a MirroredStrategy.N)rS   r   rt   rr   dictdeserializer   rp   rq   rF   global_policyr
   strategy_supports_loss_scalingrJ  get_strategyrx   r   r   r   r   )rD   rG   strategyrK   rK   rL   r7   1  s0    



zLayer._set_dtype_policyc                 C   s   | j jS )a  The layer's compute dtype.

        Unless mixed-precision is used, this is the same as `Layer.dtype`.

        If self._autocast is True, layer's will cast floating-point inputs to
        this.

        Returns:
          The layer's compute dtype.
        )rr   r   r  rK   rK   rL   r   ^  s    zLayer._compute_dtypec                    s>   | j  | jr6 r6t jr6 fdd}tj||S |S dS )ap  Maybe casts the inputs to the compute dtype.

        If self._compute_dtype is floating-point, and self_autocast is True,
        floating-point inputs are casted to self._compute_dtype.

        Args:
          inputs: Input tensor, or structure of input tensors.

        Returns:
          `inputs`, but tensors may have been casted to self._compute_dtype
        c                    sj   t jt jt jf}t| |r<| jjr<| jjj kr<t 	|  S t| t j
rb| jjrbt 
| j | jS | S dS )z8Cast a single Tensor or TensorSpec to the compute dtype.N)rp   TensorSparseTensorRaggedTensorrS   rG   ry   ru   rF   r   r   rd   )r   Z
cast_typesr   rK   rL   f  s    z#Layer._maybe_cast_inputs.<locals>.fN)r   r9   rp   rq   ry   r   r   )rD   rQ   r  rK   r  rL   r   l  s    
zLayer._maybe_cast_inputsc                 C   s   | j jS r^   r	  r  rK   rK   rL   _dtype  s    zLayer._dtypec                 C   s    t |j}| t| d S r^   )rp   rq   rF   r7   r   rt   r  rK   rK   rL   r    s    c                 C   s   | j S r^   rF   r  rK   rK   rL   r     s    zLayer._name_scopec                 C   s*   |s t jt| jj|d| _n|| _d S )N)
zero_based)r   unique_object_namer   r   r   r   r
  )rD   rF   r  rK   rK   rL   r+     s    
zLayer._init_set_namec                    sD    fdd| j D }|sd S t|dkr<tdt| |d S )Nc                    s   g | ]}|j  kr|qS rK   r  r   r  rK   rL   r     r   z.Layer._get_existing_metric.<locals>.<listcomp>r   zfPlease provide different names for the metrics you have added. We found {} metrics with the name: "{}"r   )r6   r   rx   r   )rD   rF   matchrK   r  rL   _get_existing_metric  s    zLayer._get_existing_metricc                 C   s   t j|dd | |}|d u rZ|r.|}|}qt|drP|}|j}| j| qtdn.|rl||}|}nt ||\}}| j| d S )Nr=  r  r8  a  We do not support adding an aggregated metric result tensor that is not the output of a `tf.keras.metrics.Metric` metric instance. Without having access to the metric instance we cannot reset the state of a metric after every epoch during training. You can create a `tf.keras.metrics.Metric` instance and pass the result here or pass an un-aggregated result with `aggregation` parameter set as `mean`. For example: `self.add_metric(tf.reduce_sum(inputs), name='mean_activation', aggregation='mean')` )	r   r  r  rO   r8  r6   rU   rx   create_mean_metric)rD   r  rk   rF   r  result_tensor
metric_objrK   rK   rL   r9    s(    

zLayer._symbolic_add_metricc                    sL    fdd}t |r6|D ]}| t|| qn| t|| dS )z3Create lambdas which compute regularization losses.c                    s:   t  d  | }W d   n1 s,0    Y  |S )z8Creates a regularization loss `Tensor` for variable `v`.z/RegularizerN)r   r   )r   regularizationrF   r   rK   rL   _loss_for_variable  s    &z?Layer._handle_weight_regularization.<locals>._loss_for_variableN)r   r   r)  r+  r,  )rD   rF   ra   r   r  r   rK   r  rL   r     s
    
z#Layer._handle_weight_regularizationc                 C   s   | j rtj|}tdj |D ]T}t|  |}ttjj	
|d |j}|| }tj|dd | j||d q"W d    n1 s0    Y  d S )NActivityRegularizerr   r   r  r'  )r.   rp   r   r   r   r   r   r   r}   r~   rd   rG   r   r  r)  )rD   rQ   r   output_listrr  activity_lossr   mean_activity_lossrK   rK   rL   r     s    z%Layer._handle_activity_regularizationc              	   C   s  t j|}t| ddp(tdd |D }t| doH| jpHt| jdd }|r^dd |D }nD|srd	d |D }n0| ||}|d u rd
d |D }nt j|}t||D ]&\}	}
z
|
|	_	W q t
y   Y q0 qt|r|D ]}	t|	dd d urd|	j	_qd S )N _compute_output_and_mask_jointlyFc                 s   s   | ]}t |d dduV  qdS rj  rl  r   rK   rK   rL   r     s   z+Layer._set_mask_metadata.<locals>.<genexpr>r   rN   c                 S   s   g | ]}t |d dqS rj  rl  r   rK   rK   rL   r     r   z,Layer._set_mask_metadata.<locals>.<listcomp>c                 S   s   g | ]}d qS r^   rK   r   _rK   rK   rL   r     r   c                 S   s   g | ]}d qS r^   rK   r  rK   rK   rL   r   !  r   rk  T)rp   r   r   r  allrO   r*   r   ziprk  r  r   r   _keras_history_checked)rD   rQ   r   previous_maskflat_outputsmask_already_computedZshould_compute_mask
flat_masksoutput_masksrr  r   rK   rK   rL   r     s:    

zLayer._set_mask_metadatac                 C   sN   | j d||r | j d||S | js*dS tjdd |}t|rJdS |S )zBChecks if mask argument was passed, else gathers mask from inputs.r   Nc                 S   s   t | dd S )Nrk  rl  r   rK   rK   rL   r   ;  r   z,Layer._collect_input_masks.<locals>.<lambda>)	r   r   r   _should_compute_maskrp   r   r   r   is_all_none)rD   rQ   r`   rI   r  rK   rK   rL   r   2  s    
zLayer._collect_input_masksc                 C   s   | j std| d t| j |ksRtd| d t| d tt| j  d t| j | |}t|trt|dkr|d S |S d	S )
a  Private utility to retrieves an attribute (e.g. inputs) from a node.

        This is used to implement the methods:
            - get_input_shape_at
            - get_output_shape_at
            - get_input_at
            etc...

        Args:
            node_index: Integer index of the node from which
                to retrieve the attribute.
            attr: Exact node attribute name.
            attr_name: Human-readable attribute name, for error messages.

        Returns:
            The layer's attribute `attr` at the node of index `node_index`.

        Raises:
            RuntimeError: If the layer has no inbound nodes, or if called in
                Eager mode.
            ValueError: If the index provided does not match any node.
        z8The layer has never been called and thus has no defined .zAsked to get z	 at node z, but the layer has only z inbound nodes.r   r   N)r>  r   r   rx   r   r  rS   rn  )rD   ro  attr	attr_namevaluesrK   rK   rL   ry  A  s8    	z"Layer._get_node_attribute_at_indexc                 C   s   | j st| j|| j tj|}|rj| jjd u rjz|d j	j
j}W n tyX   Y n0 | t| d }tdd |D rtjdd |}t| jdst|  | | W d    n1 s0    Y  t| | | jd ur| | j d | _d S )Nr   c                 s   s   | ]}t |d V  qdS )rd   N)rO   r   rK   rK   rL   r   |  r   z%Layer._maybe_build.<locals>.<genexpr>c                 S   s   | j S r^   r   r   rK   rK   rL   r   }  r   z$Layer._maybe_build.<locals>.<lambda>rN   )r'   r   r   rF   rp   r   r   rr   r   rG   ru   r  r7   r   rt   r  r   rO   rP   r   r  r   r@   rR  )rD   rQ   r   rG   rw  rK   rK   rL   r   m  s*    
(
zLayer._maybe_buildc                    s6   t jdd |} |} fdd}t j||S )Nc                 S   s   | j S r^   r   r   rK   rK   rL   r     r   z&Layer._symbolic_call.<locals>.<lambda>c                    s   t j|  jd}d |_|S )N)rd   rG   )r   placeholderrG   rk  )rd   phr  rK   rL   _make_placeholder_like  s    z4Layer._symbolic_call.<locals>._make_placeholder_like)rp   r   r   r   )rD   rQ   rw  r|  r  rK   r  rL   r     s    
zLayer._symbolic_callc                 C   s4   | j ddd}| | ji}|D ]}||  q|S )zGet the `trainable` state of each sublayer.

        Returns:
          A dict mapping all sublayers to their `trainable` value.
        Finclude_self	recursive)r  rE   rG  _get_trainable_state)rD   layerstrainable_staterh  rK   rK   rL   r    s
    
zLayer._get_trainable_statec                 C   s@   | |v r||  | _ | jddd}|D ]}||v r$|| q$dS )z(Set `trainable` state for each sublayer.Fr  N)rE   r  _set_trainable_state)rD   r  r  rh  rK   rK   rL   r    s    
zLayer._set_trainable_statec                 C   s   |  dt  | jS )z?A dict counting the number of attributes referencing an object.r   )r/   r   ObjectIdentityDictionaryr   r  rK   rK   rL   _obj_reference_counts  s
    zLayer._obj_reference_countsc                 C   s   t | |s| || dS )a+  Create the attribute with the default value if it hasn't been created.

        This is useful for fields that is used for tracking purpose,
        _trainable_weights, or _layers. Note that user could create a layer
        subclass and assign an internal field before invoking the
        Layer.__init__(), the __setattr__() need to create the tracking fields
        and __init__() need to not override them.

        Args:
          name: String, the name of the attribute.
          default_value: Object, the default value of the attribute.
        N)rO   __setattr__)rD   rF   default_valuerK   rK   rL   r/     s    
zLayer._maybe_create_attributec                    s$  t | |d  | j} |vr4ttjjj| | d S |  }|dkrj|d | < ttjjj| | d S | = ttjjj| | t t	st
 rttjjj| d fdd| jD  t tjr ttjjj| d fdd| jD  ttjjj| d fdd| jD  d S )	Nr   r"   c                    s   g | ]}| ur|qS rK   rK   rg  existing_valuerK   rL   r     s   z%Layer.__delattr__.<locals>.<listcomp>r    c                    s   g | ]}| ur|qS rK   rK   r   wr  rK   rL   r     r   r!   c                    s   g | ]}| ur|qS rK   rK   r  r  rK   rL   r    	  s   )r  r  superrp   r   trackingAutoTrackable__delattr__rS   r   r   has_weightsr  r"   Variabler    r!   )rD   rF   reference_countsreference_countr   r  rL   r    sH    	

zLayer.__delattr__c                    s  |dks t | ddr t| j|rbzttjjj| | W n  t	y\   t	d
|Y n0 d S tjjj| |d| j}|dd |< z| | W n t	y   Y n0 ddlm} tjD ]& t |jrt| dr| j  qt | d	dr\ttstr\| d
g  tfdd| jD s\| j tdr\d_tjD ] t tjs~qh| dg  | dg   jrt fdd| j D rqh| j   n*t fdd| j!D rqh| j!  t"#  qhttjjj| | d S )N_self_setattr_trackingTzCan't set the attribute "{}", likely because it conflicts with an existing read-only @property of the object. Please choose a different name.)	trackabler  rF   r   r   )r6  r6   rA   r"   c                 3   s   | ]}| u V  qd S r^   rK   r  )r  rK   rL   r   ?	  r   z$Layer.__setattr__.<locals>.<genexpr>_use_resource_variablesr    r!   c                 3   s   | ]} |u V  qd S r^   rK   r  valrK   rL   r   S	  r   c                 3   s   | ]} |u V  qd S r^   rK   r  r  rK   rL   r   W	  r   )$r  rO   r   r  rp   r   r  r  r  r  r   sticky_attribute_assignmentr  r,   r  kerasr6  r   r   rS   Metricr6   rU   r   r   r  r/   r   r"   r  r  rE   r    r!   r   r   )rD   rF   r  r  metrics_moduler  )r  r  rL   r  	  sz    


zLayer.__setattr__c                 C   s   dS )NTrK   r  rK   rK   rL   	_is_layerf	  s    zLayer._is_layerc                 C   s   d| j jv pt| dd d uS )Nr   r   )r   r   r  r  rK   rK   rL   r  i	  s    zLayer._should_compute_maskc                 C   s>   g t   }}|D ](}t||vr|| |t| q|S )z;Dedupe weights while maintaining order as much as possible.)r  idrU   add)rD   r   rr  seen_idsr  rK   rK   rL   _dedup_weightsq	  s    
zLayer._dedup_weightsc                 C   s
   t | S r^   )r   LayerSavedModelSaverr  rK   rK   rL   _trackable_saved_model_saver~	  s    z"Layer._trackable_saved_model_saverc                 C   s   | j jS r^   )r  object_identifierr  rK   rK   rL   _object_identifier	  s    zLayer._object_identifierc                 C   s   | j jS r^   )r  tracking_metadatar  rK   rK   rL   _tracking_metadata	  s    zLayer._tracking_metadata
checkpointc                    s@   |dkr|d }| j |}ni }|t j|fi | |S )N
savedmodelcache)r  trackable_childrenrG  r  _trackable_children)rD   	save_typerI   r  childrenr  rK   rL   r  	  s    zLayer._trackable_childrenc                 C   s   | j  }|dd  |S )Nr3   )__dict__copyr-   rD   staterK   rK   rL   __getstate__	  s    
zLayer.__getstate__c                 C   s   t  |d< t| d| d S )Nr3   r  )r1   r2   objectr  r  rK   rK   rL   __setstate__	  s    zLayer.__setstate__)TNNF)N)N)NN)T)N)NN)r  )nr   
__module____qualname____doc__	frozenset	itertoolschainrp   Module_TF_MODULE_IGNORED_PROPERTIESr   r   no_automatic_dependency_trackingrM   r   defaultrP   r   for_subclass_implementersrR   rX   rv   AUTOr}   r~   VariableAggregationNONEr   r   classmethodr   r   r   r   r  r   propertyrG   rF   rH   do_not_generate_docsr  setterrE   r   r   r   r$  r)  r6  r=  r  rR  ra  re  ri  rp  rs  ru  rv  r{  r}  rm  rq  rt  rr  r   r  r   do_not_doc_inheritablerO  r  r  r  r  r>  r  r7   r   r   r  r   r+   r  r9  r   r   r   r   ry  r   r   r  r  r  r/   r  r  r  r   cached_per_instancer  r  r  r  r  r  r  r  __classcell__rK   rK   r  rL   r   4   sJ  F {


 =
&
/
, g








	

y
K
GX,




%
#





-
*


	

)*,#	

=_


	r   )(r  r+  r  r1   numpyr   tensorflow.compat.v2r}   v2rp   r  r   r   r   r   keras.enginer   r   r   keras.mixed_precisionr	   r
   r   keras.saving.saved_modelr   keras.utilsr   r   r   r   r   keras.utils.generic_utilsr   keras.utils.tf_utilsr   tensorflow.python.platformr   tensorflow.tools.docsr   r   rK   rK   rK   rL   <module>   s4   