
    BVh}             	          d Z ddlZddlZddlZddlZddlZddlZddlm	Z	 ddl
mZ ddlmZ ddl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* ddl)m+Z+ ddl)m,Z, ddl)m-Z- ddl)m.Z. ddl/m0Z0 dd l1m2Z2 dd!l3m4Z4 dd"l5m6Z6 dd#l5m7Z7 dd$l5m8Z9 dd%l:m;Z; dd&l<m=Z= dd'l>m?Z? dd(l>m@ZA dd)l>mBZB dd*lCmDZD dd+lEmFZF  G d, d-e j                        ZG G d. d/ ej                  d/g d0            ZIe"j                  ZJy)1z=Contains the base Layer class, from which all layers inherit.    N)ag_ctx)api)distribute_lib)context)dtypes)errors)
func_graph)ops)sparse_tensor)tensor)tensor_conversion)tensor_util)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)module)	array_ops)math_ops)	variables)ragged_tensor)
tf_logging)autotrackable)base)data_structures)nest)doc_controlsc                   ~    e Zd ZdZ e ej                  dej                  j                              Z	e
j                  ddd       Ze
j                  ej                  d               Zej"                  d        Zej"                  d        Zej"                  dddddddddej*                  j,                  ej.                  j0                  fd       Zej                  d	        Zed
        Zd Zej"                  d        Zej                  ded       Zd Z d Z!e"d        Z#e"d        Z$e"d        Z%e"ejL                  d               Z'e'jP                  d        Z'e"d        Z)e)jP                  d        Z)e"d        Z*e*jP                  d        Z*e"d        Z+e+jP                  e
j                  d               Z+e"d        Z,e"d        Z-ej"                  ded       Z.e"d        Z/ej"                  dfd       Z0ej"                  ded        Z1d! Z2d" Z3d# Z4d$ Z5d% Z6d& Z7e"d'        Z8e"d(        Z9d) Z:d* Z;d+ Z<d, Z=e"d-        Z>e"d.        Z?e"d/        Z@d0 ZAe"d1        ZBe"ej                  d2               ZDe"ej                  d3               ZEej                  d4        ZFej                  d5        ZGe"d6        ZHe"d7        ZIe"d8        ZJe"d9        ZKeKjP                  e
j                  d:               ZKe"d;        ZLeLjP                  e
j                  d<               ZLd= ZMe"d>        ZNd? ZOe"d@        ZPePjP                  dA        ZPdB ZQdgdCZRdedDZSdfdEZTdF ZUdG ZVdH ZWdI ZXdhdJZYdhdKZZ	 didLZ[dM Z\dN Z]dO Z^dP Z_dQ Z`e"dR        Zae
j                  dS        Zb fdTZc fdUZddV ZededWZfe"egj                  dX               Zie"egj                  dY               Zje"egj                  dZ               Zke"egj                  d[               Zle"egj                  d\               Zmd] Zne"d^        Zoe"d_        Zpe"d`        Zqdj fda	Zrdb Zsdc Zt xZuS )k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_dictNc                    | j                          h d}t        j                  ||       || _        d| _        d| _        d | _        d | _        d| _        | j                  |       t        j                  |j                  dd             | _        | j                  dg        | j                  dg        g | _        t!        j"                         | _        g | _        g | _        g | _        | j-                  |       |j                  dt/        j0                               | _        | j                  dg        g | _        g | _        | j9                          || _        d|v rd	|vr	|d   f|d	<   d	|v sd
|v r<d
|v rt=        |d
         }n"d	|v rd|v r|d   }nd }|ft=        |d	         z   }| _        |j                  dd       | _         d| _!        d| _"        d| _#        y )N>   weightsautocast	input_dim
batch_sizeinput_shapeimplementationbatch_input_shapeactivity_regularizerFr7   _trainable_weights_non_trainable_weightsr1   _self_tracked_trackablesr2   r4   r6   r3   r0   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_kwargsr6   r3   s	            \/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/engine/base_layer_v1.py__init__zLayer.__init__   s
    	##%N
 !!&.9
  DO DN DJ"DD!D!-!1!1

)40"2D  !5r:  !92>DM"*D D DL DM 	5! ZZ
 0 J J LNDN 	  !;R@
 !#D!#D
 DM ff!<%k24f]"5"? 
	&!&)<"=>F"6!l+**'ME&2G,HH 1d #JJy$7D #'D $(D  05D,    c                 L    t        | j                  d      s|| _        d| _        y)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?   )r\   r4   s     rc   ri   zLayer.build  s!      4::}- +dDJre   c                     |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.
     )r\   inputsra   s      rc   callz
Layer.call  s	     Mre   c                     t        |t        j                        r|}nt        j                  |      }|r| j                  j	                  |       |S | j
                  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   TrackableWeightHandlerr8   appendr9   )r\   trackable_objectr]   handlers       rc   _add_trackablezLayer._add_trackable&  se     "$4$K$KL g 778HIg
$$W- N !!((1Nre   c                    |d}|D ]  }|dvst        d|       d|v }|j                  dt        j                        }|j                  dd      }|j                  dd      }|j                  d	d      }|"| j                  xs t        j                         }t        j                  |      }| j                  j                  8| j                  t        j                  |j                  j                               t!        j"                  |      }t%        j"                  |      }t'        j"                  |      }|
t(        j*                  j,                  k(  r|rt/        d
      d}n|d}||j0                  rt!        j"                  d      }nc|j2                  s|j4                  s|j6                  rt!        j8                         }n*|s(t/        d|d|j                  d| j                        |rY| j                  j:                  | j                  j                  k7  r,|j0                  r |fd}|t=        j>                  d       d}| jA                  |||d||||||	||
||      }|;|j                  d|j                  jC                  d       }| jE                  |||       t        jF                  |      rW|D ]P  }t        jH                  |       |r| jJ                  jM                  |       6| jN                  jM                  |       R |S t        jH                  |       |r| jJ                  jM                  |       |S | jN                  jM                  |       |S )a  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:rv   rw   rx   Try   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_uniformzAn initializer for variable z	 of type z is required for layer c                  >     | i |}t        j                  |      S N)r   create_autocast_variable)argsra   variable
old_getters      rc   rv   z Layer.add_weight.<locals>.getter  s#    t.v. 99(CCre   zb`caching_device` does not work with mixed precision API. Ignoring user specified `caching_device`.)r^   shaperv   	overwriteinitializerr_   
constraintr]   partitioneruse_resourcerw   synchronizationaggregationry   :)(	TypeErrorrE   r   make_variabler_   r   floatxr   as_dtype_dtype_policyvariable_dtyperO   r   Policy
base_dtyper^   r   rD   r   r   tf_variablesVariableSynchronizationON_READ
ValueErroris_floating
is_integeris_unsignedis_boolzeroscompute_dtyper&   warning _add_variable_with_custom_getterfind_handle_weight_regularizationis_split_variabletrack_variabler8   rq   r9   )r\   r^   r   r_   r   regularizerr]   r   r   r   r   r   ra   kwarghas_custom_getterrv   collections_argr1   ry   r   name_in_scopevr   s                         @rc   
add_weightzLayer.add_weight=  sR   j }e <	 ) 
)3U;;< !F*ZZ"2"@"@AFjj5O zz148HZZ 0$7N}jj,GNN,eOOE"E((0
V]]5+;+;+@+@AB"";/K"";/K,J,>>FFF	?@ 	@ 			i 			"&&'78 u00EMM"((*  ,0%2B2BDIIO P 	P 	((D,>,>,M,MMjD 
	#/	0 44 !#'%# 5 'H$  mm$<X]]%7%7%<=m
(()1)46 ))(3 0!q!

!
!
(
(
+

%
%
,
,Q
/0 O X&	&&x0 O 	##**84Ore   c                 .   t        j                  | j                        j                  }| j                  | j
                  d}t        | d      r| j                  |d<   t        j                  | j                        |d<   t        | d      r1| j                  r| j                  |d<   nd|v r|j                  d       |j                         }|D cg c]	  }||vs| }}t        |      dkD  r!t        | j                  d      rt!        d      |S c c}w )	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.
    )r^   r]   rW   r6   r_   r`      rg   z?Layers with arguments in `__init__` must override `get_config`.)r   getfullargspecrd   r~   r^   r]   rh   rW   r   	serializer   r`   removekeyslen
get_configNotImplementedError)r\   all_argsconfigexpected_argsarg
extra_argss         rc   r   zLayer.get_config  s      ((7<<Hiidnn=Ft)*$($;$;f !&&t'9'9:F7OtY	 LLy 	"KKMM!)F#S-E#FJF :wtF !9 : :M Gs   	DDc                      | d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   rk   )clsr   s     rc   from_configzLayer.from_config	  s      ==re   c                 ^   t        j                         r| j                  |       t        j                         j                         5  t        j                  d      }|j                         5  t        j                  |d      }t        j                  t        j                  |      }	  | |d      }	 ddd       ddd       t        j                  d       S t        # t        $ r(}t        d| j                   j"                  z        |d}~ww xY w# 1 sw Y   bxY w# 1 sw Y   fxY w)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                     | j                   S r|   r   ts    rc   <lambda>z,Layer.compute_output_shape.<locals>.<lambda>B  s
    !'' re   )r   executing_eagerly_maybe_buildr
   get_default_graph
as_defaultr	   	FuncGraphr   convert_shapesr*   map_structurer    generate_placeholders_from_shaper   r   	__class____name__)r\   r4   r   rl   outputses         rc   compute_output_shapezLayer.compute_output_shape  s       " $  "--/ 0$$W- 	0 //uM+%%??N&06E2G	00  17;;
  0%D ''() /0	00	0 	00 0sB   &D#.<D+
C#6D##	D,#DDDD 	D##D,c                    d }t        j                  ||      }| j                  |      }| j                  1t        j                  |      D cg c]  }|j
                   }}|d   t        j                  fd|      S c c}w )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                     t        | t        j                        st        dj	                  |             | j
                  S )NzKOnly TensorSpec signature types are supported, but saw signature entry: {}.)ro   r   
TensorSpecr   formatr   )ss    rc   check_type_return_shapez?Layer.compute_output_signature.<locals>.check_type_return_shape[  s8    6,,- 77=vayB 	BWWnre   r   c                 2    t        j                  |       S )N)r_   r   )r   r   )r   r_   s    rc   r   z0Layer.compute_output_signature.<locals>.<lambda>i  s    &##%q9 re   )r*   r   r   _compute_dtypeflattenr_   )r\   input_signaturer   r4   output_shaper   input_dtypesr_   s          @rc   compute_output_signaturezLayer.compute_output_signatureE  s    ,
 $$%<oNK,,[9LE}'+||O'DE!aggElE 1oe9 	 Fs   Bc                     | j                   sMt        d t        j                  |      D              r't	        d| j
                  z   dz   t        |      z         y|S )zComputes 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              3   $   K   | ]  }|d u 
 y wr|   rk   ).0ms     rc   	<genexpr>z%Layer.compute_mask.<locals>.<genexpr>y  s     7qQd]7s   Layer z9 does not support masking, but was passed an input_mask: N)rB   anyr*   r   r   r^   str)r\   rl   masks      rc   compute_maskzLayer.compute_maskl  sa       	7DLL$67	7499, 09 9;>t9E F 	F  Kre   c           
      Z   | j                          t        | d      st        d      |r|d   }|dd }n;| j                  d   |v r|j	                  | j                  d         }nt        d      t        j                         }t        j                  |      }t        j                  |      }t        d |D              r.d }t        j                  ||      }t        j                  |      }d	}| j                  |||      }	| j                  r|	| j!                  d
||      sd}|	|d
<   d}
d	}| j!                  d||      r0| j#                  d||      }
| j$                  s|j	                  d       |
|j&                  |j&                  }
n~t)        j*                         rt)        j,                         }
nU|rSt)        j.                         j1                         5  t        j2                         rt)        j,                         }
ddd       | j$                  r`|
^t5        j6                  |
      r%t9        j:                  |
t<        j>                        }
nt?        |
      }
| jA                  d|
||      \  }}d}|r*t        jB                  |      rt        jD                  |       |jG                  | |||
      5  |r)tI        jJ                  | jH                  || jL                         t)        j.                         }|j1                         5  t)        jN                  | jQ                               5  | jS                  |       | jU                  |      }t        jV                  |       rHt        jX                  |       s3t[        j\                  | j^                  ta        jb                               }n| j^                  }| jd                  s6	 tg        jh                  | jj                        5   ||g|i |}ddd       n| ju                  |      }t        d| jL                  z   dz         t        jv                  |      rE|r| jA                  dd||d      \  }}|r|j	                  d
       | jy                  |f|z   ||      }| j{                  ||       | j}                  |||	       t        | d      r| j~                  s| j                  ||       ddd       ddd       nt)        jN                  | jQ                               5  | jS                  |       | jU                  |      }tg        jh                  | jj                        5   | j^                  |g|i |}ddd       | j{                  |       | j}                  |||	       ddd       ddd       S # 1 sw Y   xY w# 1 sw Y   xY w# tl        jn                  $ r}tq        dts        |      z   dz         d}~ww xY w# 1 sw Y   xY w# 1 sw Y   oxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   S xY w)a  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.
    rK   z<You must call `super().__init__()` in the layer constructor.r   r   Nz9The first argument to `Layer.call` must always be passed.c              3   f   K   | ])  }t        |t        j                  t        t        f       + y wr|   )ro   npndarrayfloatintr   xs     rc   r   z!Layer.__call__.<locals>.<genexpr>  s"     
Gq:a"**eS12
Gs   /1c                 z    t        | t        j                  t        t        f      rt        j                  |       S | S r|   )ro   r   r   r   r   r   "convert_to_tensor_v2_with_dispatchr   s    rc   _convert_non_tensorz+Layer.__call__.<locals>._convert_non_tensor  s/     a"**eS12"EEaH
Hre   Fr   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_v1rh   RuntimeError_call_fn_argsrE   r   r   call_contextr*   r   r   are_all_symbolic_tensorsr   r   _collect_input_masks_expects_mask_arg_call_arg_was_passed_get_call_arg_value_expects_training_argr   r   global_learning_phase_is_setlearning_phase	get_graphr   is_in_keras_graphr   
is_tf_typer#   castr   bool_set_call_arg_valueneeds_keras_historycreate_keras_historyenterr   assert_input_compatibilityr^   
name_scope_name_scoper   _maybe_cast_inputsis_subclassedfrom_saved_model	autograph
tf_convertrm   r   control_status_ctxr`   r   enable_auto_cast_variables_compute_dtype_objectr   OperatorNotAllowedInGraphErrorr   r   _symbolic_callhave_all_keras_metadata_set_connectivity_metadata_handle_activity_regularization_set_mask_metadatarl   r   )r\   r~   ra   rl   r   
input_listbuild_graphr   mask_arg_passed_by_frameworkinput_maskstraining_value training_arg_passed_by_frameworkr   cast_inputscall_fnr   r   s                    rc   __call__zLayer.__call__  s   2 	4)
HJ J Awf!"Xd			A	&	(zz$,,Q/0f
EG G $002Lf%J 33J?K 
GJ
GG !!"5v>f<<'j $) ++FD&AK;#:%%fdF;%)""fVn N',$  T6://
D&In''

:				*%..//1 //1 ++- 	6//1$335N	6 
	#	#(B !!.1#==E././/f6f+/(
 ';;FC++F3			D&+~	F N@	 	--doov.2ii	9!!# <	.!3!3D4D4D4F!G <	. 

F
#//7+ ,,T2"33D9**		64468G iiG
0$??,,. @!+???@" ))&1G_ (*.))46:; < < 55f=/!55dD&D 6 JldF+jj 55vi$6F6=?G

.
.vw
?

!
!&';
?T=)$++ VW-y<	. <	. <	.~  0 0 23 	@


F
#//7+ ;;((* >dii=d=f=G> 
.
.vw
?

!
!&';
?	@ON@` NK	6 	6d@ @ 88 0 H "!f	% (/	/ 0 003<	. <	. <	. <	.D> >	@ 	@ON@` Ns   )V 8AX $W</BW/V:'V-	4V:<CW/W<,X AX
X!-XX  V*-V72V::W,	W'	'W,	,W//W94W<<X	X XXX	X  X*c                 L    t        | d      st        dt        |       d      y )NrZ   a  Your Layer or Model is in an invalid state. This can happen for the following cases:
 1. You might be interleaving models/layers made in tf.compat.v1.Graph.as_default() with models/layers created outside of it.
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 z and its bases.)rh   r   typer\   s    rc   r   zLayer._assert_built_as_v1D  s-    423 :  4re   c                 .    | j                   j                  S r|   r   r   r&  s    rc   r_   zLayer.dtypeT  s    ,,,re   c                     | j                   S r|   )_namer&  s    rc   r^   z
Layer.nameX  s    ::re   c                 B    t        d | j                         D              S )Nc              3   4   K   | ]  }|j                     y wr|   )rU   r   layers     rc   r   z Layer.dynamic.<locals>.<genexpr>^  s     B%u~~B   r   _flatten_layersr&  s    rc   r`   zLayer.dynamic\  s    B4+?+?+ABBBre   c                 B    t        d | j                         D              S )Nc              3   4   K   | ]  }|j                     y wr|   r>   r-  s     rc   r   z!Layer.stateful.<locals>.<genexpr>c  s     C5uCr/  r0  r&  s    rc   statefulzLayer.stateful`  s     CD,@,@,BCCCre   c                     || _         y r|   r4  r\   values     rc   r5  zLayer.statefule  s	    DNre   c                     | j                   S r|   )r=   r&  s    rc   r]   zLayer.trainablei  s    ??re   c                 D    || _         t        | dg       D ]	  }||_         y )Nr:   )r=   getattrr]   )r\   r8  r.  s      rc   r]   zLayer.trainablem  s)    DO92> eore   c                     | j                   S );Optional regularizer function for the output of this layer.rF   r&  s    rc   r7   zLayer.activity_regularizers  s     %%%re   c                     || _         y)r=  Nr>  )r\   r   s     rc   r7   zLayer.activity_regularizerx  s     "-Dre   c                     | j                   S r|   )rA   r&  s    rc   r   zLayer.input_spec}  s    re   c                     t        j                  |      D ]9  }|t        |t        j                        r!t        dj                  |             || _        y )Nz:Layer input_spec must be an instance of InputSpec. Got: {})r*   r   ro   r   	InputSpecr   r   rA   )r\   r8  r   s      rc   r   zLayer.input_spec  sU    
 \\%  -	
z!Z-A-AB ""(&)- 	-- Dre   c                    g }| j                         }t        j                         j                         5  |D ]g  }|j                  s|j
                  s|j                  D ]=  }t        |      r	  |       }t        j                  |d       |j                  |       ? i 	 d d d        |S # t        $ r4}dt        |      j                  v rt        j                  dd        d }~ww xY w# 1 sw Y   |S xY w)NInaccessibleTensorError
add_updateT)methodforce_raiserF  )r1  r   r  r   r]   r5  rH   callabler   r%  r   r   check_graph_consistencyrq   )r\   collected_updates
all_layersr.  ur   s         rc   updateszLayer.updates  s    %%'J					'	'	) & &%u~~
 	&Aa[#a 
2
21\
J

"
"1
%	&&&(   	*d1g.>.>> !88'T;	&( s/   9C-/B-6,C--	C*	6/C%	%C*	*C--C7c                     g }| j                         }|D ]I  }|j                  |j                         |j                  D ]  } |       }||j	                  |        K |S )a3  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.
    )r1  extendrM   rL   rq   )r\   collected_lossesrL  r.  r   loss_tensors         rc   losseszLayer.losses  ss     %%'J / emm,// /+!m"

!
!+
.// re   c                 $   fd}t        j                  |      }g }g }|D ]  }t        |      r&|j                  t	        j
                  ||             4|7t        j                  |      s)t        j                  |t        j                               }t        j                  |      st        j                         r|j                   ||             t        j                   |d        | j"                  j%                  |       t        j&                         j(                  }|r#|D ]  }| j*                  j                  |        y|D ]<  }t-        | dd      r| j/                  |       "| j*                  j                  |       > y)ac
  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))
    ```

    The `get_losses_for` method allows to retrieve the losses relevant to a
    specific set of inputs.

    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                    t        |       r%t        j                  d      5   |        } ddd       | yt        j                  |       s)t        j                  | t        j                               } du | _	        | S # 1 sw Y   UxY w)z@Process the loss and tag it by setting loss._unconditional_loss.Nr_   )
rI  r   r  r   r  r   r   r   r   _unconditional_loss)lossrl   s    rc   _tag_unconditionalz*Layer.add_loss.<locals>._tag_unconditional  s{    	$ 99$? 	$		##D) CC(
 #)D.dk	 	s   A>>BNrV  add_lossrH  _is_graph_networkF)r*   r   rI  rq   	functoolspartialr   r  r   r   r   r   r   is_symbolic_tensorr   is_in_tf_functionrJ  rL   rP  r   in_callrM   r;  _graph_network_add_loss)	r\   rS  rl   rY  callable_lossessymbolic_lossesrX  in_call_contextsymbolic_losss	     `      rc   rZ  zLayer.add_loss  sZ   H  \\&!FOO J	$y001CTJK	##D) CC(
 
%
%d
+0021$7800jIJ  	  1&335==O* +-M*+ + --4,e4

&
&}
5 ,,

m
,-re   c                 j    g }| j                         D ]  }|j                  |j                          |S r|   )r1  rP  rN   )r\   collected_metricsr.  s      rc   metricszLayer.metrics5  s8    %%' /u~~./re   c                 H   ||dk7  rt        d|z        t        |d      }t        j                  |      }t	        j
                         j                  }||st        d      |r|j                  j                  }|r| j                  |||       y|st        dt        |      z         t        | dd      s?t        j                         j                         5  | j                  |||       ddd       y|rt        d	      | j                  |||       y# 1 sw Y   yxY w)
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.)r   rh   r   r^  r   r   r`  rk  r^   _symbolic_add_metricr   r;  r   r  r   _graph_network_add_metric)r\   r8  r   r^   from_metric_objis_symbolicrd  s          rc   
add_metriczLayer.add_metric<  s<   $ ;&#8*,789 9 e]3O--e4K&335==O|O  J K K 
##d
{D9 &(+E
3 4 	4 T.6 ++- 	>

#
#E;
=	>	 7 8 	8 $$UK>	>s   DD!c                    |t        j                  d       t        j                         }t	        j
                         r!t	        j                         r|j                  syt        j                  |      }|j                  r|j                  n't        | dg       }|D cg c]  }|j                   c}fd|D cg c]
  } |       }}| j                  j                  |       yc c}w c c}w )a3  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.
      inputs: Deprecated, will be automatically inferred.
    Nz`add_update` `inputs` kwarg has been deprecated. You no longer need to pass a value to `inputs` as it is being automatically inferred._inbound_nodesc                     t               r fd} |       S t         t        j                        r }n.t	         d      r j
                  }nt        j                         }t        j                  |g      }||v|_
        |S )zuStandardize update ops.

      Args:
        x: Tensor, op, or callable.

      Returns:
        An update op.
      c                                      S r|   rk   )process_updater   s   rc   r   z:Layer.add_update.<locals>.process_update.<locals>.<lambda>  s    , re   op)rI  ro   r
   	Operationrh   rv  r   r   r   get_reachable_from_inputs_unconditional_update)r   update	reachableru  relevant_inputss   `  rc   ru  z(Layer.add_update.<locals>.process_update  st     
!,xa'1d"EEaH44_vhOi%+9%<f"mre   )r&   r   r   r   r   has_strategyin_cross_replica_contextsavingr   to_listr`  rl   r;  input_tensorsrH   rP  )	r\   rN  rl   r   inbound_nodesnoder   ru  r|  s	          @@rc   rE  zLayer.add_update  s    2 OP $002L##%//1 ##G,G$++od$4b9m8EF++Fo. +22Q~a 2G2MM!5 G2 3s   "C/C4c                    | j                   }d}|D ]1  }t        |t        j                        r||j                  z  }-|dz  }3 |t        |      k7  r7t        d| j                  dt        |      d|dt        |      dd d		      d}g }|D ]  }t        |t        j                        r+|j                  }||||z    }|j                  |       ||z  }H||   }	t        |	d
      r|	j                  nd}
|j                  }|j                  |
      st        d|d|
      |j                  ||	f       |dz  } t        j                  |       y)aR  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   z,You called `set_weights(weights)` on layer "z" with a weight list of length z, but the layer was expecting z weights. Provided weights: N2   z...r   rk   zLayer weight shape z+ not compatible with provided weight shape )r0   ro   r   rp   num_tensorsr   r   r^   r   set_weightsrh   r   is_compatible_withrq   r   batch_set_value)r\   r0   paramsexpected_num_weightsparamweight_indexweight_value_tuplesr  tensorsweightweight_shape	ref_shapes               rc   r  zLayer.set_weights  sn   X \\F "	E+BB	C 1 11!	" s7|+ 99c'l$8#g,s:KMN N L 	E+BB	C'',|k'AB'"#&'.vw'?v||RKK	++L9%|56 6 	""E6?3" /0re   c                     | j                   }g }|D ]M  }t        |t        j                        r |j	                  |j                                =|j                  |       O t        j                  |      S )a  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.
    )	r0   ro   r   rp   rP  get_tensorsrq   r   batch_get_value)r\   r0   output_weightsr  s       rc   get_weightszLayer.get_weights  sk    F llGN &	F,CC	Df0023f%	&
 "">22re   c                 >   |'| j                   D cg c]  }|j                  s| c}S | j                   D cg c]  }|j                  r| }}t        j                  |      }t	        j
                  ||      }|D cg c]	  }||v s| c}S c c}w c c}w c c}w )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`.
    )rN  ry  r*   r   r   rx  )r\   rl   rM  rN  r{  s        rc   get_updates_forzLayer.get_updates_forF  s     ~AA)@)@aAA ,,FQa.E.EqFGF\\&!F2267CI1!!y.A11 B G 2!   BBB
B?	B	Bc                 >   |'| j                   D cg c]  }|j                  s| c}S | j                   D cg c]  }|j                  r| }}t        j                  |      }t	        j
                  ||      }|D cg c]	  }||v s| c}S c c}w c c}w c c}w )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`.
    )rS  rW  r*   r   r   rx  )r\   rl   lrS  r{  s        rc   get_losses_forzLayer.get_losses_forY  s     ~>A(=(=a>> BAA,A,AaBFB\\&!F2266BI0!iA00 ? C 1r  c                     | j                  |      }t        |t              r|D cg c]  }t        |dd       c}S t        |dd      S c c}w )av  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).
    _keras_maskN)get_input_atro   listr;  )r\   
node_indexrl   r   s       rc   get_input_mask_atzLayer.get_input_mask_atl  sL     z*F&$7=>!ga->>V]D11 ?   A
c                     | j                  |      }t        |t              r|D cg c]  }t        |dd       c}S t        |dd      S c c}w )ax  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).
    r  N)get_output_atro   r  r;  )r\   r  outputr   s       rc   get_output_mask_atzLayer.get_output_mask_at  sL     
+F&$7=>!ga->>V]D11 ?r  c                     | j                   }t        |t              r|D cg c]  }t        |dd       c}S t        |dd      S c c}w )aq  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.
    r  N)inputro   r  r;  )r\   rl   r   s      rc   
input_maskzLayer.input_mask  sE     ZZF&$7=>!ga->>V]D11 ?   Ac                     | j                   }t        |t              r|D cg c]  }t        |dd       c}S t        |dd      S c c}w )at  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.
    r  N)r  ro   r  r;  )r\   r  r   s      rc   output_maskzLayer.output_mask  sE     [[F&$7=>!ga->>V]D11 ?r  c                 (    | j                  |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r\   r  s     rc   get_input_shape_atzLayer.get_input_shape_at  s      ,,Z-:< <re   c                 (    | j                  |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 shaper  r  s     rc   get_output_shape_atzLayer.get_output_shape_at  s      ,,Z-;= =re   c                 (    | j                  |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  r  r  r  s     rc   r  zLayer.get_input_at  s     ,,Z-46 6re   c                 (    | j                  |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_tensorsr  r  r  s     rc   r  zLayer.get_output_at  s     ,,Z9I-57 7re   c                 v    | j                   st        d| j                  z   dz         | j                  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  r  rr  AttributeErrorr^   r  r&  s    rc   r  zLayer.input  sE     8dii/CD E E,,QIIre   c                 v    | j                   st        d| j                  z   dz         | j                  ddd      S )am  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  r  r  r&  s    rc   r  zLayer.output  s=     8dii/2JJKK,,Q0@(KKre   c                 <   | j                   st        d      t        | j                   D cg c]  }t        |j                         c}      }t        |      dk(  r| j                   d   j                  S t        dt        | j                        z   dz         c c}w )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.
    zDThe layer has never been called and thus has no defined input shape.r   r   zThe layer "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.)rr  r  setr   r  r   r^   )r\   r  all_input_shapess      rc   r4   zLayer.input_shape,  s       B C C,0,?,?@DT	@B
!  #000=3tyy>9&& ' '	 	As   Bc                 T   | j                   srt        | dd      r:t        j                  |       5  | j	                  | j
                         ddd       n+t        d| j                  z   dz   | j                  z   dz         t        j                  | j                        S # 1 sw Y   (xY w)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   rl   r   r^   r   count_paramsr0   r&  s    rc   r  zLayer.count_paramsL  s     ::	*E	2&&t, 	)


DKK
(	) 	) ?$))K<<>BiiH 77 8 	8 ##DLL11	) 	)s   BB'c                 $   | j                   st        d      t        | j                   D cg c]  }t        |j                         c}      }t        |      dk(  r| j                   d   j                  S t        d| j                  z        c c}w )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.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.)rr  r  r  r   r  r   r^   )r\   r  all_output_shapess      rc   r   zLayer.output_shapea  s      C D D-1-@-@ATT	 AC
"  #111 & )-		2 3 3	 	Bs   Bc                     | j                   S zCDeprecated, do NOT use! Only for compatibility with external Keras.)rr  r&  s    rc   r  zLayer.inbound_nodes  s     re   c                     | j                   S r  )_outbound_nodesr&  s    rc   outbound_nodeszLayer.outbound_nodes  s     re   c                 X    t        j                  d        | j                  |g|i |S )a*  Deprecated, do NOT use!

    This is an alias of `self.__call__`.

    Args:
      inputs: Input tensor(s).
      *args: additional positional arguments to be passed to `self.call`.
      **kwargs: additional keyword arguments to be passed to `self.call`.

    Returns:
      Output tensor(s).
    zp`layer.apply` is deprecated and will be removed in a future version. Please use `layer.__call__` method instead.)warningswarnr#  )r\   rl   r~   ra   s       rc   applyzLayer.apply  s4     MM @ A 4==1$1&11re   c                 P    t        j                  d        | j                  |i |S )z/Deprecated, do NOT use! Alias for `add_weight`.zy`layer.add_variable` is deprecated and will be removed in a future version. Please use `layer.add_weight` method instead.)r  r  r   )r\   r~   ra   s      rc   add_variablezLayer.add_variable  s/     MM B C 4??D+F++re   c                     | j                   S )z|Returns the list of all layer variables/weights.

    Alias of `self.weights`.

    Returns:
      A list of variables.
    )r0   r&  s    rc   r$   zLayer.variables  s     <<re   c                     | j                   S r|   )trainable_weightsr&  s    rc   trainable_variableszLayer.trainable_variables  s    !!!re   c                     | j                   S r|   )non_trainable_weightsr&  s    rc   non_trainable_variableszLayer.non_trainable_variables      %%%re   c                     | j                   S r|   rR   r&  s    rc   rr  zLayer._inbound_nodes  s    $$$re   c                     || _         y r|   r  r7  s     rc   rr  zLayer._inbound_nodes  s     !&Dre   c                     | j                   S r|   rS   r&  s    rc   r  zLayer._outbound_nodes  r  re   c                     || _         y r|   r  r7  s     rc   r  zLayer._outbound_nodes  s     "'Dre   c                 0   t        |t        j                        r|| _        nt        |t              rt        j
                  |      | _        nt        |t              r|dv rt        j                  |      | _        nS|r8t        j                  t        j                  |      j                        | _        nt        j                         | _        | j                  j                  dk(  rbt        j                         sNt        j                         }t        d|j                   j"                  d| j                  j                  d      | j                  j$                  r/t        j                  | j                  j$                        | _        yd| _        y)zSets self._dtype_policy.)mixed_float16mixed_bfloat16r  zBMixed precision is not supported with the tf.distribute.Strategy: z@. Either stop using mixed precision by removing the use of the "z>" policy or use a different Strategy, e.g. a MirroredStrategy.N)ro   r   r   r   dictdeserializer   r   r   r^   global_policyr   strategy_supports_loss_scalingr   get_strategyr   r   r   r   r  )r\   r_   strategys      rc   rO   zLayer._set_dtype_policy  s3   %' d	E4	 !--e4d	E3	E .@ %@ "==/d	!==)?)D)DEd!//1d?2 ??A
  ,,.h !**33T5G5G5L5L	N O O ''#)??



*
*$,d  $(d re   c                 .    | j                   j                  S )zThe 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.
    )r   r   r&  s    rc   r   zLayer._compute_dtype  s     +++re   c                     | j                   | j                  r<r:t        j                        j                  rfd}t        j                  ||      S |S )aT  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                    t         j                  t        j                  t        j
                  f}t        | |      rO| j                  j                  r9| j                  j                  j                  k7  rt        j                  |       S t        | t         j                        rA| j                  j                  r+t        j                  | j                  | j                        S | S )z8Cast a single Tensor or TensorSpec to the compute dtype.)r   Tensorr   SparseTensorr%   RaggedTensorro   r_   r   r   r^   r#   r  r   r   )r   
cast_typesr   s     rc   fz#Layer._maybe_cast_inputs.<locals>.f  s    mm]%?%?#002
q*%!''*=*=GG##}4q-0
06,,-!''2E2E ""177M166B
B(re   )r   rQ   r   r   r   r*   r   )r\   rl   r  r   s      @rc   r  zLayer._maybe_cast_inputs  sJ     ''M=&22 6**mre   c                 .    | j                   j                  S r|   r(  r&  s    rc   _dtypezLayer._dtype)  s    
 ,,,re   c                     t        j                  |      j                  }| j                  t	        j
                  |             y r|   )r   r   r^   rO   r   r   r7  s     rc   r  zLayer._dtype0  s-    OOE"''E6==/0re   c                     | j                   S r|   )r^   r&  s    rc   r  zLayer._name_scope5  s    99re   c                     |sDt        j                  t        j                  | j                  j
                        |      | _        y || _        y )N)
zero_based)r   unique_object_namer   r   r   r   r*  )r\   r^   r  s      rc   rC   zLayer._init_set_name8  s;    --

%
%dnn&=&=
>!dj djre   c                     | j                   D cg c]  }|j                  |k(  s| }}|sy t        |      dkD  r$t        dj	                  t        |      |            |d   S c c}w )Nr   zfPlease provide different names for the metrics you have added. We found {} metrics with the name: "{}"r   )rN   r^   r   r   r   )r\   r^   r   matchs       rc   _get_existing_metriczLayer._get_existing_metric@  sh    814Q8E8
5zA~44:F3u:t4LN N 8O 9s
   A$A$c                 j   t        j                  |d       | j                  |      }|H|r|}|}y t        |d      r*|}|j                  }| j
                  j                  |       y t        d      |r ||      }|}y t        j                  ||      \  }}| j
                  j                  |       y )Nrp  rH  rk  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   rJ  r  rh   rk  rN   rq   r   create_mean_metric)r\   r8  r   r^   r  result_tensor
metric_objs          rc   rl  zLayer._symbolic_add_metricJ  s    ,,U<H%%d+E
 

5-("..
Z(AB 	B 
e
$4$G$G4%!
MZ(re   c                     fd}t        j                  |      r-|D ]'  }| j                  t        j                  ||             ) y| j                  t        j                  ||             y)z3Create lambdas which compute regularization losses.c                 t    t        j                  dz         5   |       }ddd       |S # 1 sw Y   S xY w)z8Creates a regularization loss `Tensor` for variable `v`.z/RegularizerN)r   r  )r   regularizationr^   r   s     rc   _loss_for_variablez?Layer._handle_weight_regularization.<locals>._loss_for_variabler  s;    d^34 ($Q((s   	-7N)r   r   rZ  r\  r]  )r\   r^   r   r   r  r   s    ` `  rc   r   z#Layer._handle_weight_regularizationo  s_     ))(3 @!i''(:A>?@ mmI%%&8(CDre   c                    | j                   rt        j                  |      }t        j                  d      5  |D ]x  }| j                  |      }t        j                  t        j                  |      d   |j                        }||z  }t        j                  |d       | j                  ||       z 	 d d d        y y # 1 sw Y   y xY w)NActivityRegularizerr   r7   rH  )rl   )rF   r*   r   r   r  r#   r  r"   r   r_   r   rJ  rZ  )r\   rl   r   output_listr  activity_lossr3   mean_activity_losss           rc   r  z%Layer._handle_activity_regularization~  s     !!LL)k34 	;! 	;F44V<-}}oof%a(-*=*=?*  -z9


2
2 )?A
--*6-
:	;	; 	; "	; 	;s   A>C  C	c                    t        j                  |      }t        | dd      xs t        d |D              }t	        | d      xr& | j
                  xs t        | j                  dd       }|r|D cg c]  }t        |dd        }}nK|s|D 	cg c]  }	d  }}	n9| j                  ||      }
|
|D 	cg c]  }	d  }}	nt        j                  |
      }t        ||      D ]  \  }}	 ||_         t        j                  |      r'|D ]!  }t        |dd       d|j                  _        # y y c c}w c c}	w c c}	w # t        $ r Y gw xY w)N _compute_output_and_mask_jointlyFc              3   :   K   | ]  }t        |d d      du  yw)r  Nr;  r   s     rc   r   z+Layer._set_mask_metadata.<locals>.<genexpr>  s     NAGA}d+47Ns   r   rg   r  T)r*   r   r;  allrh   rB   r   zipr  r  r   r   _keras_history_checked)r\   rl   r   previous_maskflat_outputsmask_already_computedshould_compute_maskr   
flat_masks_output_masksr  r   s                rc   r  zLayer._set_mask_metadata  sm   <<(L 	8%@ 	ONNN  	n% 	?			 
>T&&u=	= 
 =IJGA}d3JjJ "./QD/j/&&v}=l 
	$01qd1
1\\,/
L*5 ! ((6  ;&6=$/;6:&


3; 7' K/ 2  s$   1D,	D12	D6&D;;	EEc                     | j                  d||      r| j                  d||      S | j                  syt        j                  d |      }t        j                  |      ry|S )zDChecks if `mask` argument was passed, else gathers mask from inputs.r   Nc                     t        | dd       S )Nr  r  r   s    rc   r   z,Layer._collect_input_masks.<locals>.<lambda>  s    wq-/N re   )r   r   _should_compute_maskr*   r   r   is_all_none)r\   rl   r~   ra   r  s        rc   r   zLayer._collect_input_masks  sb      v6%%fdF;;$$$$%N%+-K  -re   c                 d    ||v ry| j                   }|s|dd  }|t        t        ||            v ryy)NTr   Fr   r  r  )r\   arg_namer~   ra   inputs_in_argscall_fn_argss         rc   r   zLayer._call_arg_was_passed  sA    6%%L!!"%l4L$/00re   c                 n    ||v r||   S | j                   }|s|dd  }t        t        ||            }||   S Nr   r  )r\   r  r~   ra   r  r  	args_dicts          rc   r   zLayer._get_call_arg_value  sK    6H%%L!!"%lSt,-IXre   c                     | j                   j                  |d       }|)|s|dz
  }t        |      |kD  rt        |      }|||<   ||fS ||r|j	                  |d        ||fS |||<   ||fS r   )_call_fn_arg_positionsrD   r   r  rE   )r\   r  	new_valuer~   ra   r  r   arg_poss           rc   r  zLayer._set_call_arg_value  s     ))--h=GA+	TW	Dz!WV|.jj4  < #fX<re   c                 l   | j                   st        d|z   dz         t        | j                         |kD  sBt        d|z   dz   t	        |      z   dz   t	        t        | j                               z   dz         t        | j                   |   |      }t        |t              rt        |      dk(  r|d   S |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   )rr  r   r   r   r   r;  ro   r  )r\   r  attr	attr_namevaluess        rc   r  z"Layer._get_node_attribute_at_index  s    .  46?@BEF G Gt""#j02[@:')DE3t223457HI J J T((4d;F&$CK1$4AYmre   c                    | j                   s&t        j                  | j                  || j                         t	        j
                  |      }|r^| j                  j                  H	 |d   j                  j                  j                  }| j                  t        j                  |             d }t        d |D              rt	        j                  d |      }t!        | j"                  d      s/t%        j&                  |       5  | j#                  |       d d d        t(        j#                  | |       | j*                  #| j-                  | j*                         d | _        y y # t        $ r Y w xY w# 1 sw Y   ^xY w)Nr   c              3   4   K   | ]  }t        |d         yw)r   N)rh   r   s     rc   r   z%Layer._maybe_build.<locals>.<genexpr>  s     5QWQ 5r/  c                     | j                   S r|   r   r   s    rc   r   z$Layer._maybe_build.<locals>.<lambda>  s
    AGG re   rg   )r?   r   r
  r^   r*   r   r   r   r_   r   rO   r   r   r  r  r   rh   ri   r   r  r-   rX   r  )r\   rl   r  r_   r  s        rc   r   zLayer._maybe_build  s9   ::++
//6499.<<'j	**88@	7Q-%%0055% 
 
 u!5
6l	5*5	5))*;VDTZZ/ &&t, 	#
**\
"	#
 kk$% (
t,,-"d ))  	
		# 	#s   '#E$ E3$	E0/E03E<c                      t        j                  d |      } j                  |      } fd}t        j                  ||      S )Nc                     | j                   S r|   r   r   s    rc   r   z&Layer._symbolic_call.<locals>.<lambda>2  s
     re   c                 X    t        j                  | j                        }d |_        |S )N)r   r_   )r   placeholderr_   r  )r   phr\   s     rc   _make_placeholder_likez4Layer._symbolic_call.<locals>._make_placeholder_like5  s%    U$**=bbnire   )r*   r   r   )r\   rl   r  r  r3  s   `    rc   r  zLayer._symbolic_call1  sA    %%&7@L--l;M
 4mDDre   c                     | j                  dd      }| | j                  i}|D ]!  }|j                  |j                                # |S )z}Get the `trainable` state of each sublayer.

    Returns:
      A dict mapping all sublayers to their `trainable` value.
    Finclude_self	recursive)r1  r]   rz  _get_trainable_state)r\   layerstrainable_stater  s       rc   r8  zLayer._get_trainable_state<  sS     !!u!FFT^^,O 7Q33567re   c                     | |v r
||    | _         | j                  dd      }|D ]  }||v s|j                  |        y)z(Set `trainable` state for each sublayer.Fr5  N)r]   r1  _set_trainable_state)r\   r:  r9  r  s       rc   r<  zLayer._set_trainable_stateH  sP    &t,dn!!u!FF 0	
o		/0re   c                 b    | j                  dt        j                                | j                  S )zEA dictionary counting the number of attributes referencing an object.r.   )rG   r   ObjectIdentityDictionaryr.   r&  s    rc   _obj_reference_countszLayer._obj_reference_countsQ  s.     	  !=!0!I!I!KM***re   c                 B    t        | |      s| j                  ||       yy)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)rh   __setattr__)r\   r^   default_values      rc   rG   zLayer._maybe_create_attributeX  s#     4
t]+ re   c                    t        | |d       }| j                  }||vrt        t        j                  |   |       y ||   }|dkD  r&|dz
  ||<   t        t        j                  |   |       y ||= t        t        j                  |   |       t        |t              st        j                  |      r;t        t        j                  | +  d| j                  D cg c]	  }||us| c}       t        |t        j                        rwt        t        j                  | +  d| j                  D cg c]	  }||us| c}       t        t        j                  | +  d| j                  D cg c]	  }||us| c}       y y c c}w c c}w c c}w )Nr   r:   r8   r9   )r;  r?  superr'   AutoTrackable__delattr__ro   r-   r   has_weightsrA  r:   r   Variabler8   r9   )r\   r^   existing_valuereference_countsreference_countr  wr   s          rc   rF  zLayer.__delattr__i  s|    T4.N
 11--M'':4@&~6O *91)<~&M'':4@ >
*	-
%
%t8>>5)''7M'':
$33
Oq7N1
OQ .,"7"78M'':
--
I.1H1
IK M'':
"11
MQn5L1
MO	 9 P J Ns$   	E?
"E?
-	F
7F
(	F	
2F	
c                    |dk(  s#t        | dd      rt        | j                  |      r 	 t        t        j
                  |   |       y t        j                  | |      | j                  }|j                  d      dz   |<   	 | j                  |       ddlm} t!        j"                        D ]A  t%        |j&                        st        | d      s'| j(                  j+                         C t        | d	d      rt%        t,              st/        j0                        r^| j3                  d
g        t5        fd| j6                  D              s.| j6                  j+                         t        d      rd_        t!        j"                        D ]  t%        t:        j<                        s| j3                  dg        | j3                  dg        j>                  r;t5        fd| j@                  D              rm| j@                  j+                         n:t5        fd| jB                  D              r| jB                  j+                         tE        jF                          t        t        j
                  |   |       y # t        $ r t        dj                  |            w xY w# t        $ r Y 0w xY w)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.)	trackabler8  r^   r   r   )rh  rN   rY   r:   c              3   &   K   | ]  }|u  
 y wr|   rk   )r   r.  r8  s     rc   r   z$Layer.__setattr__.<locals>.<genexpr>  s     LU%5.L   _use_resource_variablesr8   r9   c              3   &   K   | ]  }|u  
 y wr|   rk   r   rL  vals     rc   r   z$Layer.__setattr__.<locals>.<genexpr>  s     9Asax9rQ  c              3   &   K   | ]  }|u  
 y wr|   rk   rT  s     rc   r   z$Layer.__setattr__.<locals>.<genexpr>  s     =Asax=rQ  )$r;  rh   r   rD  r'   rE  rA  r  r   r)   sticky_attribute_assignmentr?  rD   rF  tensorflow.python.kerasrh  r*   r   ro   MetricrN   rq   r-   r   rG  rG   r   r:   rR  r   rH  r]   r8   r9   r   r   )r\   r^   r8  rJ  metrics_modulerU  r   s     `  @rc   rA  zLayer.__setattr__  st   ((D2D9%.m))4<T5I  77e$0E 11.225!<q@U
t
 B||E" "	C..	/GD*4MS!" 	.5	E5	!%5%A%A%%H
""#=rB Ld.K.KLM%%,,U3534 +/%
'
 ||E" "\223 ""#7<
""#;R@	9!8!899
&&s+=!<!<==
##**3/S!#"* 
-
%
%t8uEE  . &t. 	..$  
s   J 	J> $J;>	K
Kc                      y)NTrk   r&  s    rc   	_is_layerzLayer._is_layer  s    re   c                    | j                   j                  j                  j                  j	                  | d        | j                   j
                  j                  j                  j	                  | d        | j                   j                  j                  j                  j	                  | d        | j
                  }|d|v xs | j                  | _        n|| _        d|v xs | j                  | _        y )Nr   r   )	r   _call_full_argspecfgetcacherE   r   _call_accepts_kwargsr   r   )r\   expects_training_argr  s      rc   rT   zLayer._init_call_fn_args  s    NN%%**0044T4@NN  %%++//d;NN'',,2266tTB%%L#$.,$> %>$($=$=   $8d $4 8"77 	re   c                 @    t        j                  | j                        S r|   )r   r   rm   r&  s    rc   r^  zLayer._call_full_argspec  s    
 $$TYY//re   c                 P    | j                   j                  }|r|d   dk(  r|dd  S |S )Nr   r\   r   )r^  r~   )r\   r   s     rc   r   zLayer._call_fn_args  s4     &&++HHQK6)ab\Ore   c                 ^    t               }t        | j                        D ]
  \  }}|||<    |S r|   )r  	enumerater   )r\   call_fn_arg_positionsposr   s       rc   r#  zLayer._call_fn_arg_positions	  s;     !Fd001 'S#&C '  re   c                 2    | j                   j                  d uS r|   )r^  varkwr&  s    rc   ra  zLayer._call_accepts_kwargs	  s     ""((44re   c                 @    d| j                   v xs t        | dd       d uS )Nr   r   )r   r;  r&  s    rc   r  zLayer._should_compute_mask	  s-     d((( <D.$/t;=re   c                     g t               }}|D ];  }t        |      |vs|j                  |       |j                  t        |             = |S )z;Dedupe weights while maintaining order as much as possible.)r  idrq   add)r\   r0   r  seen_idsrL  s        rc   _dedup_weightszLayer._dedup_weights	  sK    35HF 	Ah	aRU	 Mre   c                 ,    t        j                  |       S r|   )r   LayerSavedModelSaverr&  s    rc   _trackable_saved_model_saverz"Layer._trackable_saved_model_saver&	  s    33D99re   c                 .    | j                   j                  S r|   )rs  object_identifierr&  s    rc   _object_identifierzLayer._object_identifier*	      ,,>>>re   c                 .    | j                   j                  S r|   )rs  tracking_metadatar&  s    rc   _tracking_metadatazLayer._tracking_metadata.	  rw  re   c                     |dk(  r!|d   }| j                   j                  |      }ni }|j                  t        |   |fi |       |S )N
savedmodelr`  )rs  trackable_childrenrz  rD  _trackable_children)r\   	save_typera   r`  childrenr   s        rc   r~  zLayer._trackable_children2	  sQ    L Woe 22EEeLhhOOEG/	DVDEOre   c                 ^    | j                   j                         }|j                  dd        |S )NrK   )__dict__copyrE   r\   states     rc   __getstate__zLayer.__getstate__>	  s)    
 MM E	IIot$Lre   c                 `    t        j                         |d<   t        j                  | d|       y )NrK   r  )rI   rJ   objectrA  r  s     rc   __setstate__zLayer.__setstate__G	  s%    &__.E/
tZ/re   )TNNFr|   )NN)T)F)FF)
checkpoint)vr   
__module____qualname____doc__	frozenset	itertoolschainr!   Module_TF_MODULE_IGNORED_PROPERTIESrO   no_automatic_dependency_trackingrd   r   defaultri   r+   for_subclass_implementersrm   rt   r   r   AUTOVariableAggregationNONEr   r   classmethodr   r   r   r   r#  r   propertyr_   r^   r`   do_not_generate_docsr5  setterr]   r7   r   rN  rS  rZ  rh  rp  rE  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r4   r  r   do_not_doc_inheritabler  r  r  r  r$   r  r  rr  r  rO   r   r  r  r  rC   r  rl  r   r  r  r   r   r   r  r  r   r  r8  r<  r?  rG   rF  rA  r\  rT   r   cached_per_instancer^  r   r#  ra  r  rp  rs  rv  rz  r~  r  r  __classcell__)r   s   @rc   r-   r-   G   s   <J #,OIOO%mm11- #
 --p5 .p5d --  .$ ))
 *
 )) *, ))!! !"!-!E!E!J!J)==BBd *dL " "H  "(T ))$ *$L  *@D  - -   C C $$D % D ??     
 & & - -    -- .   2  . ))t- *t-l   ))A? *A?F ))F" *F"PO1b*3X2&1&2&2& 2 2( 2 2(<&=&6$7$ J J$ L L$ ' '>2* 3 3< && '  &&  '   &&2 '2$ &&, ',   " " & & % % --& . & & & --' . '"(J 
, 
,F - - 
==1 1#)JE;"&;P	 7<$"H#B	E
0 + + --, ., *OXIF\9  ""0 # 0
 "" #  ""! # ! ""5 # 5 ""= # =	 : : ? ? ? ?
0re   r-   c                       e Zd ZdZdZy)KerasHistorya~  Tracks the Layer call that created a Tensor, for Keras Graph Networks.

  During construction of Keras Graph Networks, this metadata is added to
  each Tensor produced as the output of a Layer, starting with an
  `InputLayer`. This allows Keras to track how each Tensor was produced, and
  this information is later retraced by the `keras.engine.Network` class to
  reconstruct the Keras Graph Network.

  Attributes:
    layer: The Layer that produced the Tensor.
    node_index: The specific call to the Layer that produced this Tensor. Layers
      can be called multiple times in order to share weights. A new node is
      created every time a Tensor is called.
    tensor_index: The output index for this Tensor. Always zero if the Layer
      that produced this Tensor only has one output. Nested structures of
      Tensors are deterministically assigned an index via `nest.flatten`.
  rk   N)r   r  r  r  	__slots__rk   re   rc   r  r  M	  s    & )re   r  )r.  r  tensor_index)Kr  rw   r\  r  rI   r  numpyr    tensorflow.python.autograph.corer    tensorflow.python.autograph.implr   r  tensorflow.python.distributer   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   r	   r
   r   r   r   r   rX  r   r   r   r   tensorflow.python.keras.enginer   r   r   'tensorflow.python.keras.mixed_precisionr   r   r   *tensorflow.python.keras.saving.saved_modelr   tensorflow.python.keras.utilsr   r   r   r   r   +tensorflow.python.keras.utils.generic_utilsr   &tensorflow.python.keras.utils.tf_utilsr    tensorflow.python.moduler!   tensorflow.python.opsr"   r#   r$   r   tensorflow.python.ops.raggedr%   tensorflow.python.platformr&   tensorflow.python.trackabler'   r(   rO  r)   tensorflow.python.utilr*   tensorflow.tools.docsr+   r-   
namedtupler  rB  rk   re   rc   <module>r     s     D       3 = 7 + . . 2 + 5 . 9 3 + / 0 0 5 ; 5 E H : J 7 5 9 4 2 E K + + * ; 6 1 5 9 7 ' .C$0J C$0LHK>BD6   	re   