a
    SicI                    @   s  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ZddlZddl	Z
ddlm  mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# ddl"m$Z$ ddl"m%Z% ddl"m&Z& ddl"m'Z' ddl"m(Z( ddl"m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl2m4Z4 ddl5m6Z6 e#7de8 dZ9d Z:ej;ej<ej=fZ>ej?j@Ad!d"d#ZBej?j@Ad$d%d#ZCej?j@Ad&d'd#ZDej?j@Ad(d)d*ZEd+aFeG ZHejId,d- ZJe4d.G d/d0 d0ejKe)jLZMG d1d2 d2eMZNG d3d4 d4eMZOG d5d6 d6eMZPd7d8 ZQd9d: ZRe4d;g d<d=d> ZSe4d?G d@dA dAeMZTdS )Bz=Contains the base Layer class, from which all layers inherit.    N)backend)constraints)initializers)regularizers)lazy_variable)base_layer_utils)
input_spec)keras_tensor)node)autocast_variable)loss_scale_optimizer)policy)layer_serialization)generic_utils)layer_utils)object_identity)
tf_inspect)tf_utils)traceback_utils)version_utils)to_snake_case)is_tensor_or_tensor_list)json_format)
tf_logging)get_canonical_name_for_symbol)keras_export)doc_controlsmetrics_modzkeras.metricstf_op_layer_z/tensorflow/api/keras/layerszkeras layers usagemethodz/tensorflow/api/keras/modelszkeras model usagez/tensorflow/api/keraszkeras api usagez$/tensorflow/api/keras/premade_modelszpremade keras model usagetypeFc                 c   sn   t tddsdgt_tj|  z<tjd } tjd }| |}|d}|V  W tj  ntj  0 dS )a  Helper to get relative name scope from fully specified nested name scopes.

    Args:
      full_name_scope: full(absolute) name scope path.

    Yields:
      Relative name scope path from the parent `_name_scope_unnester` context
      manager.

    Example:
    ```
    with _name_scope_unnester('a') as name1:  # name1 == 'a'
      with _name_scope_unnester('a/b') as name2:  # name2 == 'b'
        with _name_scope_unnester('a/b/c') as name3:  # name3 == 'c'
          pass
    ```
    valueN /)getattr_name_scope_unnester_stackr!   appendlstrippop)Zfull_name_scopeZouter_name_scoperelative_name_scope r,   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/engine/base_layer.py_name_scope_unnester`   s    



r.   zkeras.layers.Layerc                       s  e Zd ZdZejjjdddZejjje	j
dd Zejd	d
 Zejddddddddejjejjf
ddZe	j
dd Zedd Zdd Zejdd Ze	j
dddZejdd Zdd Zedd Zedd Z edd  Z!e!j"d!d  Z!ed"d# Z#eej$d$d% Z%e%j"d&d% Z%ed'd( Z&e&j"d)d( Z&ed*d+ Z'e'j"d,d+ Z'ed-d. Z(e(j"ejjjd/d. Z(ed0d1 Z)ed2d3 Z*ed4d5 Z+eej,d6d7 Z-ed8d9 Z.d:d; Z/ed<d= Z0dd>d?Z1ej$d@dA Z2dBdC Z3dDdE Z4ej,dFdG Z5ej$dHdI Z6ej$dJdK Z7eej$dLdM Z8eej$dNdO Z9ej$dPdQ Z:ej$dRdS Z;ej$dTdU Z<ej$dVdW Z=edXdY Z>edZd[ Z?eej$d\d] Z@d^d_ ZAeej$d`da ZBedbdc ZCeddde ZDedfdg ZEeej$dhdi ZFeej$djdk ZGeej,dldm ZHeej,dndo ZIeej,dpdq ZJej$drds ZKeLeMNdtejOjPZPdZQdudv ZRdwdx ZSejdydz ZTd{d| ZUd}d~ ZVdd ZWdd ZXdd ZYdd ZZedd Z[e[j"ejjjdd Z[edd Z\e\j"ejjjdd Z\dd Z]edd Z^dddZ_dd Z`dd Zaedd Zbebj"dd Zbdd ZcdddZddddZedd Zfdd Zgdd Zhdd Zidd Zjdd Zkdd Zldd Zmdd Zndd Zoedd Zpejjjdd Zq fddZr fddZsdd ZtdddZudddZvddÄ ZwdddńZxeddǄ ZyeddɄ Zzedd˄ Z{e{j"dd˄ Z{dd΄ Z|ejjjdddЄZ}ddd҄Z~eddԄ Zeddք Zedd؄ Zd fddۄ	Zedd݄ Zdd߄ Zdd Z  ZS )Layera   This is the class from which all layers inherit.

    A layer is a callable object that takes as input one or more tensors and
    that outputs one or more tensors. It involves *computation*, defined
    in the `call()` method, and a *state* (weight variables). State can be
    created in various places, at the convenience of the subclass implementer:

    * in `__init__()`;
    * in the optional `build()` method, which is invoked by the first
      `__call__()` to the layer, and supplies the shape(s) of the input(s),
      which may not have been known at initialization time;
    * in the first invocation of `call()`, with some caveats discussed
      below.

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

    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. Can also be a
        `tf.keras.mixed_precision.Policy`, which allows the computation and
        weight dtype to differ. Default of `None` means to use
        `tf.keras.mixed_precision.global_policy()`, which is a float32 policy
        unless set to different value.
      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 weights.
      variable_dtype: Alias of `dtype`.
      compute_dtype: The dtype of the layer's computations. Layers automatically
        cast inputs to this dtype which causes the computations and output to
        also be in this dtype. When mixed precision is used with a
        `tf.keras.mixed_precision.Policy`, this will be different than
        `variable_dtype`.
      dtype_policy: The layer's dtype policy. See the
        `tf.keras.mixed_precision.Policy` documentation for details.
      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), i.e. whether
        its potentially-trainable weights should be returned as part of
        `layer.trainable_weights`.
      input_spec: Optional (list of) `InputSpec` object(s) specifying the
        constraints on inputs that can be accepted by the layer.

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

    * `__init__()`: Defines custom layer attributes, and creates layer weights
      that do not depend on input shapes, using `add_weight()`, or other state.
    * `build(self, input_shape)`: This method can be used to create weights that
      depend on the shape(s) of the input(s), using `add_weight()`, or other
      state. `__call__()` will automatically build the layer (if it has not been
      built yet) by calling `build()`.
    * `call(self, inputs, *args, **kwargs)`: Called in `__call__` after making
      sure `build()` has been called. `call()` performs the logic of applying
      the layer to the `inputs`. The first invocation may additionally create
      state that could not be conveniently created in `build()`; see its
      docstring for details.
      Two reserved keyword arguments you can optionally use in `call()` are:
        - `training` (boolean, whether the call is in inference mode or training
          mode). See more details in [the layer/model subclassing guide](
          https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_training_argument_in_the_call_method)
        - `mask` (boolean tensor encoding masked timesteps in the input, used
          in RNN layers). See more details in
          [the layer/model subclassing guide](
          https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_mask_argument_in_the_call_method)
      A typical signature for this method is `call(self, inputs)`, and user
      could optionally add `training` and `mask` if the layer need them. `*args`
      and `**kwargs` is only useful for future extension when more input
      parameters are planned to be added.
    * `get_config(self)`: Returns a dictionary containing the configuration used
      to initialize this layer. If the keys differ from the arguments
      in `__init__`, then override `from_config(self)` as well.
      This method is used when saving
      the layer or a model that contains this layer.

    Examples:

    Here's a basic example: a layer with two variables, `w` and `b`,
    that returns `y = w . x + b`.
    It shows how to implement `build()` and `call()`.
    Variables set as attributes of a layer are tracked as weights
    of the layers (in `layer.weights`).

    ```python
    class SimpleDense(Layer):

      def __init__(self, units=32):
          super(SimpleDense, self).__init__()
          self.units = units

      def build(self, input_shape):  # Create the state of the layer (weights)
        w_init = tf.random_normal_initializer()
        self.w = tf.Variable(
            initial_value=w_init(shape=(input_shape[-1], self.units),
                                 dtype='float32'),
            trainable=True)
        b_init = tf.zeros_initializer()
        self.b = tf.Variable(
            initial_value=b_init(shape=(self.units,), dtype='float32'),
            trainable=True)

      def call(self, inputs):  # Defines the computation from inputs to outputs
          return tf.matmul(inputs, self.w) + self.b

    # Instantiates the layer.
    linear_layer = SimpleDense(4)

    # This will also call `build(input_shape)` and create the weights.
    y = linear_layer(tf.ones((2, 2)))
    assert len(linear_layer.weights) == 2

    # These weights are trainable, so they're listed in `trainable_weights`:
    assert len(linear_layer.trainable_weights) == 2
    ```

    Note that the method `add_weight()` offers a shortcut to create weights:

    ```python
    class SimpleDense(Layer):

      def __init__(self, units=32):
          super(SimpleDense, self).__init__()
          self.units = units

      def build(self, input_shape):
          self.w = self.add_weight(shape=(input_shape[-1], self.units),
                                   initializer='random_normal',
                                   trainable=True)
          self.b = self.add_weight(shape=(self.units,),
                                   initializer='random_normal',
                                   trainable=True)

      def call(self, inputs):
          return tf.matmul(inputs, self.w) + self.b
    ```

    Besides trainable weights, updated via backpropagation during training,
    layers can also have non-trainable weights. These weights are meant to
    be updated manually during `call()`. Here's a example layer that computes
    the running sum of its inputs:

    ```python
    class ComputeSum(Layer):

      def __init__(self, input_dim):
          super(ComputeSum, self).__init__()
          # Create a non-trainable weight.
          self.total = tf.Variable(initial_value=tf.zeros((input_dim,)),
                                   trainable=False)

      def call(self, inputs):
          self.total.assign_add(tf.reduce_sum(inputs, axis=0))
          return self.total

    my_sum = ComputeSum(2)
    x = tf.ones((2, 2))

    y = my_sum(x)
    print(y.numpy())  # [2. 2.]

    y = my_sum(x)
    print(y.numpy())  # [4. 4.]

    assert my_sum.weights == [my_sum.total]
    assert my_sum.non_trainable_weights == [my_sum.total]
    assert my_sum.trainable_weights == []
    ```

    For more information about creating layers, see the guide
    [Making new Layers and Models via subclassing](
      https://www.tensorflow.org/guide/keras/custom_layers_and_models)
    TNFc           	      K   s   |    h d}t|| t|tsRt|tjtjfrD|jtju sRt	d| || _
d| _d| _d | _d | _d | _d | _t| j | _| | t|dd | _| dg  | dg  g | _t | _g | _g | _g | _ t! | _"| #| |dt$% | _&| dg  g | _'g | _(| )  t|tsDt	d	| || _*d
|v rld|vrl|d
 f|d< d|v sd|v rd|v rt+|d }n4d|v rd|v r|d }nd }|ft+|d  }|| _,|dd | _-d| _.d| _/t0 | _1g | _2d S )N>   	input_dimweightsautocastimplementationinput_shapebatch_input_shapeactivity_regularizer
batch_sizez8Expected `trainable` argument to be a boolean, but got: Fr6   _trainable_weights_non_trainable_weightsr2   _self_tracked_trackablesz6Expected `dynamic` argument to be a boolean, but got: r0   r4   r5   r7   r1   T)3_instrument_layer_creationr   validate_kwargs
isinstancebooltfTensorVariabledtype	TypeError
_trainable	_statefulbuilt_input_spec_build_input_shape_saved_model_inputs_spec_saved_model_arg_spec
is_defaultcompute_mask_supports_masking_init_set_namer   getr*   _activity_regularizer_maybe_create_attribute_updates	threadinglocal_thread_local_callable_losses_losses_metricsLock_metrics_lock_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#_preserve_input_structure_in_configget_current_name_scope_name_scope_on_declaration_captured_weight_regularizer)	self	trainablenamerB   dynamickwargsallowed_kwargsr5   r7   r,   r,   r-   __init__:  s    










zLayer.__init__c                 C   s   || _ d| _dS )a  Creates the variables of the layer (optional, for subclass implementers).

        This is a method that implementers of subclasses of `Layer` or `Model`
        can override if they need a state-creation step in-between
        layer instantiation and layer call. It is invoked automatically before
        the first execution of `call()`.

        This is typically used to create the weights of `Layer` subclasses
        (at the discretion of the subclass implementer).

        Args:
          input_shape: Instance of `TensorShape`, or list of instances of
            `TensorShape` if the layer expects a list of inputs
            (one instance per input).
        TN)rH   rF   rj   r4   r,   r,   r-   build  s    zLayer.buildc                 O   s   |S )a	  This is where the layer's logic lives.

        The `call()` method may not create state (except in its first
        invocation, wrapping the creation of variables or other resources in
        `tf.init_scope()`).  It is recommended to create state in `__init__()`,
        or the `build()` method that is called automatically before `call()`
        executes the first time.

        Args:
          inputs: Input tensor, or dict/list/tuple of input tensors.
            The first positional `inputs` argument is subject to special rules:
            - `inputs` must be explicitly passed. A layer cannot have zero
              arguments, and `inputs` cannot be provided via the default value
              of a keyword argument.
            - NumPy array or Python scalar values in `inputs` get cast as
              tensors.
            - Keras mask metadata is only collected from `inputs`.
            - Layers are built (`build(input_shape)` method)
              using shape info from `inputs` only.
            - `input_spec` compatibility is only checked against `inputs`.
            - Mixed precision input casting is only applied to `inputs`.
              If a layer has tensor arguments in `*args` or `**kwargs`, their
              casting behavior in mixed precision should be handled manually.
            - The SavedModel input specification is generated using `inputs`
              only.
            - Integration with various ecosystem packages like TFMOT, TFLite,
              TF.js, etc is only supported for `inputs` and not for tensors in
              positional and keyword arguments.
          *args: Additional positional arguments. May contain tensors, although
            this is not recommended, for the reasons above.
          **kwargs: Additional keyword arguments. May contain tensors, although
            this is not recommended, for the reasons above.
            The following optional keyword arguments are reserved:
            - `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, 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).

        Returns:
          A tensor or list/tuple of tensors.
        r,   )rj   inputsargsrn   r,   r,   r-   call  s    .z
Layer.callc                    s  |du rd}| dd |D ]}|dvrtd|q| dd}| dd}| d	d}| d
d}|s||r|t| |d d}|du r| jpt }t|}| jj	du r| 
t|jj t|}t|}t|}|	tjjkr|rtdnd}n|du rd}|du rz|jr&td}nT|js>|js>|jrJtd}n0d|vrztd| d|j d| j d| d	| dtj}|r| jj| jj	kr|jr|  fdd}|durtd d}|rtj ||d}| j!|||d|||||||	|
|d}|dur6|jd|j"d }| #||| t$|rz|D ]0}t%| |rh| j&'| n| j('| qFn*t%| |r| j&'| n| j('| |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`.
          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).
          use_resource: Whether to use a `ResourceVariable` or not.
            See [this guide](
            https://www.tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables)
            for more information.
          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 variable created.

        Raises:
          ValueError: When giving unsupported dtype and no initializer or when
            trainable has been set to True with synchronization set as
            `ON_READ`.
        Nr,   partitioner)collectionsexperimental_autocastcaching_devicegetterlayoutzUnknown keyword argument:rw   rx   Try   r{   _layoutzSynchronization 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_uniformzerosrz   zAn initializer for variable z	 of type z is required for layer z. Received: .c                     s    | i |}t |S N)r   create_autocast_variable)rt   rn   variable
old_getterr,   r-   rz     s    z Layer.add_weight.<locals>.getterzb`caching_device` does not work with mixed precision API. Ignoring user specified `caching_device`.)r{   )rl   shaperz   	overwriteinitializerrB   
constraintrk   use_resourcerw   synchronizationaggregationry   :))r*   rC   r&   rB   r   floatxr?   as_dtype_dtype_policyvariable_dtyper[   r   Policy
base_dtyperl   r   rO   r   r   VariableSynchronizationON_READ
ValueErroris_floating
is_integeris_unsignedis_boolr   make_variablecompute_dtyper   warning	functoolspartial _add_variable_with_custom_getterfind_handle_weight_regularizationis_split_variabletrack_variabler8   r(   r9   )rj   rl   r   rB   r   regularizerrk   r   r   r   r   rn   kwargcollections_argr2   ry   r{   rz   r   name_in_scopevr,   r   r-   
add_weight!  s    5




	






zLayer.add_weightc                    s   t | jjdd }| j| jd}t| dr8| j|d< t	| j
|d< t| drv| jrd| j|d< nd|v rv|d |   fdd	|D }|rt| jd
rttd| jj d| d|S )a  Returns the config of the layer.

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

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

        Note that `get_config()` does not guarantee to return a fresh copy of
        dict every time it is called. The callers should make a copy of the
        returned dict if they want to modify it.

        Returns:
            Python dictionary.
           N)rl   rk   rc   r5   rB   rm   c                    s   g | ]}| vr|qS r,   r,   ).0argexpected_argsr,   r-   
<listcomp>      z$Layer.get_config.<locals>.<listcomp>_is_defaultz
          Layer z has arguments a!  
          in `__init__` and therefore must override `get_config()`.

          Example:

          class CustomLayer(keras.layers.Layer):
              def __init__(self, arg1, arg2):
                  super().__init__()
                  self.arg1 = arg1
                  self.arg2 = arg2

              def get_config(self):
                  config = super().get_config()
                  config.update({
                      "arg1": self.arg1,
                      "arg2": self.arg2,
                  })
                  return config)r   getfullargspecrp   rt   rl   rk   hasattrrc   r   	serializer   rm   removekeys
get_configNotImplementedErrortextwrapdedent	__class____name__)rj   all_argsconfig
extra_argsr,   r   r-   r     s2    



zLayer.get_configc                 C   s   | f i |S )a  Creates a layer from its config.

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

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

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

        This method will cause the layer's state to be built, if that has not
        happened before. This requires 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.
        _scratch_graphF	to_tuplesc                    s   t j|  jd}d |_|S N)r   rB   )r   placeholderrB   _keras_mask)r   phrj   r,   r-   _make_placeholder_like]  s    z:Layer.compute_output_shape.<locals>._make_placeholder_like)trainingzWe could not automatically infer the static shape of the layer's output. Please implement the `compute_output_shape` method on your layer (%s).Nc                 S   s   | j S r   )r   tr,   r,   r-   <lambda>n  r   z,Layer.compute_output_shape.<locals>.<lambda>z[Please run in eager mode or implement the `compute_output_shape` method on your layer (%s).)r?   executing_eagerly_maybe_buildstrrl   __internal__	FuncGraph
as_defaultr   convert_shapesnestmap_structurerC   r   r   r   )rj   r4   
graph_namer   rs   outputser,   r   r-   compute_output_shape>  s6    
6zLayer.compute_output_shapec                    sb   dd }t j||}| |}| j  du rLdd t j|D }|d  t j fdd|S )	a  Compute the output tensor signature of the layer based on the inputs.

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

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

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

        Raises:
          TypeError: If input_signature contains a non-TensorSpec object.
        c                 S   s"   t | tjstd|  d| jS )Nz9Only TensorSpec signature types are supported. Received: r   )r=   r?   
TensorSpecrC   r   sr,   r,   r-   check_type_return_shape  s    z?Layer.compute_output_signature.<locals>.check_type_return_shapeNc                 S   s   g | ]
}|j qS r,   rB   r   r   r,   r,   r-   r     r   z2Layer.compute_output_signature.<locals>.<listcomp>r   c                    s   t j | dS )N)rB   r   )r?   r   r   r   r,   r-   r     r   z0Layer.compute_output_signature.<locals>.<lambda>)r?   r   r   r   _compute_dtypeflatten)rj   input_signaturer   r4   output_shapeinput_dtypesr,   r   r-   compute_output_signaturet  s    
zLayer.compute_output_signaturec                 C   sB   | j s>tdd tj|D r:td| j d t| dS |S )a  Computes an output mask tensor.

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

        Returns:
            None or a tensor (or list of tensors,
                one per output tensor of the layer).
        c                 s   s   | ]}|d uV  qd S r   r,   r   mr,   r,   r-   	<genexpr>  r   z%Layer.compute_mask.<locals>.<genexpr>Layer z9 does not support masking, but was passed an input_mask: N)rM   anyr?   r   r   rC   rl   r   )rj   rs   maskr,   r,   r-   rL     s    zLayer.compute_maskc              
   O   s  t | dstd| j||\}}}tj|}t| ||||rR| ||||S t	
 }tdd |D rtjt|}tj|}| ||||\}}| jr|r||d< | |||\}}}|js|   t }	|j| ||	 |d~ t| j|| j |	r| j}
| j}n|  }|  }
tj|
d| j d| jj d	d
}
t !  }t"rh|#t$| j% |#t&| | j's| (| | j)r| *||}t+,| j-& |
|g|R i |}W d   n1 s0    Y  | j.r| /|| | j0r| 1||||	  | j2du r*| 3||| |W  d   W  d   S 1 sR0    Y  W d   n1 sr0    Y  dS )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.
          - If the layer is not built, the method will call `build`.

        Raises:
          ValueError: if the layer's `call` method returns None (an invalid
            value).
          RuntimeError: if `super().__init__()` was not called in the
            constructor.
        rU   z<You must call `super().__init__()` in the layer constructor.c                 s   s$   | ]}t |tjtjttfV  qd S r   r=   r?   r@   npndarrayfloatintr   xr,   r,   r-   r     s   z!Layer.__call__.<locals>.<genexpr>r   layerrs   build_graphr   layer "z" "                 f"(type )object_nameN)4r   RuntimeError
_call_specsplit_out_first_argr?   r   r    _in_functional_construction_mode_functional_construction_callr   call_contextr   r   _convert_numpy_or_python_types_get_input_masks_expects_mask_arg_set_training_modein_call_clear_lossesr   enterr   assert_input_compatibilityrl   ru   _name_get_unnested_name_scope_autographed_callr   !inject_argument_info_in_tracebackr   r   
contextlib	ExitStack+_is_name_scope_on_model_declaration_enabledenter_contextr.   rh   
name_scoperF   r   r]   _maybe_cast_inputsr   enable_auto_cast_variables_compute_dtype_objectrP   _handle_activity_regularizationrM   _set_mask_metadatarI   _set_save_spec)rj   rt   rn   rs   
input_listr  input_masksmask_is_implicittraining_modeeagercall_fnr  Znamescope_stackr   r,   r,   r-   __call__  s    







6
zLayer.__call__c              	   C   s   t rt| jp}td t |g}d|d }|dkr>| j}t| |  }W d    n1 sf0    Y  W d    q1 s0    Y  n|  }|S Nr%   )	r  r.   rh   filterr?   rg   joinr  _name_scope)rj   Z"relative_name_scope_on_declarationr+   current_name_scoper  r,   r,   r-   r  V  s$    FzLayer._get_unnested_name_scopec                 C   s   | j jS )zThe dtype of the layer weights.

        This is equivalent to `Layer.dtype_policy.variable_dtype`. Unless
        mixed precision is used, this is the same as `Layer.compute_dtype`, the
        dtype of the layer's computations.
        r   r   r   r,   r,   r-   rB   m  s    zLayer.dtypec                 C   s   | j S )z3Name of the layer (string), set in the constructor.)r
  r   r,   r,   r-   rl   w  s    z
Layer.namec                 C   s   | j S )zBWhether this layer supports computing a mask using `compute_mask`.rM   r   r,   r,   r-   supports_masking|  s    zLayer.supports_maskingc                 C   s
   || _ d S r   r&  rj   r!   r,   r,   r-   r'    s    c                 C   s   t dd |  D S )zBWhether the layer is dynamic (eager-only); set in the constructor.c                 s   s   | ]}|j V  qd S r   )ra   r   r   r,   r,   r-   r     r   z Layer.dynamic.<locals>.<genexpr>r   _flatten_layersr   r,   r,   r-   rm     s    zLayer.dynamicc                 C   s   t dd |  D S )Nc                 s   s   | ]}|j V  qd S r   rE   r)  r,   r,   r-   r     r   z!Layer.stateful.<locals>.<genexpr>r*  r   r,   r,   r-   stateful  s    zLayer.statefulc                 C   s
   || _ d S r   r,  r(  r,   r,   r-   r-    s    c                 C   s   | j S r   )rD   r   r,   r,   r-   rk     s    zLayer.trainablec                 C   s   |   D ]
}||_qdS )a  Sets trainable attribute for the layer and its sublayers.

        When this value is changed during training (e.g. with a
        `tf.keras.callbacks.Callback`) you need to call the parent
        `tf.keras.Model.make_train_function` with `force=True` in order to
        recompile the training graph.

        Args:
          value: Boolean with the desired state for the layer's trainable
            attribute.
        N)r+  rD   )rj   r!   r   r,   r,   r-   rk     s    c                 C   s   | j S );Optional regularizer function for the output of this layer.rP   r   r,   r,   r-   r6     s    zLayer.activity_regularizerc                 C   s
   || _ dS )r.  Nr/  )rj   r   r,   r,   r-   r6     s    c                 C   s   | j S )a|  `InputSpec` instance(s) describing the input format for this layer.

        When you create a layer subclass, you can set `self.input_spec` to
        enable the layer to run input compatibility checks when it is called.
        Consider a `Conv2D` layer: it can only be called on a single input
        tensor of rank 4. As such, you can set, in `__init__()`:

        ```python
        self.input_spec = tf.keras.layers.InputSpec(ndim=4)
        ```

        Now, if you try to call the layer on an input that isn't rank 4
        (for instance, an input of shape `(2,)`, it will raise a
        nicely-formatted error:

        ```
        ValueError: Input 0 of layer conv2d is incompatible with the layer:
        expected ndim=4, found ndim=1. Full shape received: [2]
        ```

        Input checks that can be specified via `input_spec` include:
        - Structure (e.g. a single input, a list of 2 inputs, etc)
        - Shape
        - Rank (ndim)
        - Dtype

        For more information, see `tf.keras.layers.InputSpec`.

        Returns:
          A `tf.keras.layers.InputSpec` instance, or nested structure thereof.
        )rG   r   r,   r,   r-   r     s    !zLayer.input_specc                 C   s>   t j|D ]&}|d urt|tjstd|q|| _d S )Nz:Layer input_spec must be an instance of InputSpec. Got: {})	r?   r   r   r=   r   	InputSpecrC   formatrG   )rj   r!   r   r,   r,   r-   r     s    c                 C   s(   | j r | d}| | j| S g S dS )zList of all trainable weights tracked by this layer.

        Trainable weights are updated via gradient descent during training.

        Returns:
          A list of trainable variables.
        trainable_variablesN)rk   _gather_children_attribute_dedup_weightsr8   )rj   children_weightsr,   r,   r-   trainable_weights  s    	zLayer.trainable_weightsc                 C   s@   | j r| d}| j| }n| d}| j| j | }| |S )a   List of all non-trainable weights tracked by this layer.

        Non-trainable weights are *not* updated during training. They are
        expected to be updated manually in `call()`.

        Returns:
          A list of non-trainable variables.
        non_trainable_variables	variables)rk   r3  r9   r8   r4  )rj   r5  non_trainable_weightsr,   r,   r-   r9    s    

zLayer.non_trainable_weightsc                 C   s   | j | j S )zjReturns the list of all layer variables/weights.

        Returns:
          A list of variables.
        )r6  r9  r   r,   r,   r-   r1     s    zLayer.weightsc                 C   s   t jddd g S )Nz`layer.updates` will be removed in a future version. This property should not be used in TensorFlow 2.0, as `updates` are applied automatically.   
stacklevel)warningswarnr   r,   r,   r-   updates  s
    zLayer.updatesc                 C   sj   g }|   D ]X}|jr4|jd tjur@||j n||j |jD ]}| }|durF|| qFq|S )a  List of losses added using the `add_loss()` API.

        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.

        Examples:

        >>> class MyLayer(tf.keras.layers.Layer):
        ...   def call(self, inputs):
        ...     self.add_loss(tf.abs(tf.reduce_mean(inputs)))
        ...     return inputs
        >>> l = MyLayer()
        >>> l(np.ones((10, 1)))
        >>> l.losses
        [1.0]

        >>> 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.
        >>> len(model.losses)
        0
        >>> model.add_loss(tf.abs(tf.reduce_mean(x)))
        >>> len(model.losses)
        1

        >>> inputs = tf.keras.Input(shape=(10,))
        >>> d = tf.keras.layers.Dense(10, kernel_initializer='ones')
        >>> x = d(inputs)
        >>> outputs = tf.keras.layers.Dense(1)(x)
        >>> model = tf.keras.Model(inputs, outputs)
        >>> # Weight regularization.
        >>> model.add_loss(lambda: tf.reduce_mean(d.kernel))
        >>> model.losses
        [<tf.Tensor: shape=(), dtype=float32, numpy=1.0>]

        Returns:
          A list of tensors.
        r   N)r+  _eager_lossesr   REVIVED_LOSS_PLACEHOLDERextendrW   rV   r(   )rj   collected_lossesr   r   loss_tensorr,   r,   r-   losses"  s    ,
zLayer.lossesc           
      K   s@  | dd |r"td| f dd }tj|}g }g }g }|D ]}t|rf|t	|| qF|du rpqFt
|st|tjstj|t d}t|st|tjrt s|| qFt
|rF|| qF| j| t j}|r|std| j| |D ],}	t| dd	r,| |	 n| j|	 qdS )
a	  Add loss tensor(s), potentially dependent on layer inputs.

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

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

        Example:

        ```python
        class MyLayer(tf.keras.layers.Layer):
          def call(self, inputs):
            self.add_loss(tf.abs(tf.reduce_mean(inputs)))
            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,))
        d = tf.keras.layers.Dense(10)
        x = d(inputs)
        outputs = tf.keras.layers.Dense(1)(x)
        model = tf.keras.Model(inputs, outputs)
        # Weight regularization.
        model.add_loss(lambda: tf.reduce_mean(d.kernel))
        ```

        Args:
          losses: Loss tensor, or list/tuple of tensors. Rather than tensors,
            losses may also be zero-argument callables which create a loss
            tensor.
          **kwargs: Used for backwards compatibility only.
        rs   NzUnknown keyword arguments: %sc                 S   sj   t | r8td |  } W d   n1 s.0    Y  | du rDdS t| s`tj| t d} d| _| S )z3Tags callable loss tensor as `_unconditional_loss`.Nr   T)	callabler   r  r?   	is_tensorconvert_to_tensorr   r   _unconditional_loss)lossr,   r,   r-   _tag_callable  s    $
z%Layer.add_loss.<locals>._tag_callabler   z|Expected a symbolic Tensors or a callable for the loss value. Please wrap your loss computation in a zero argument `lambda`._is_graph_networkF)r*   rC   r   r?   r   r   rF  r(   r   r   rG  r=   r	   KerasTensorrH  r   r   r   is_symbolic_tensorr   is_in_tf_functionrV   rB  r  r  r   r@  r&   _graph_network_add_lossrW   )
rj   rE  rn   rK  callable_losseseager_lossessymbolic_lossesrJ  in_call_contextsymbolic_lossr,   r,   r-   add_lossc  sL    =


zLayer.add_lossc              	   C   sT   g }|   D ]B}t|dsq|j ||j W d   q1 sD0    Y  q|S )a  List of metrics added using the `add_metric()` API.

        Example:

        >>> input = tf.keras.layers.Input(shape=(3,))
        >>> d = tf.keras.layers.Dense(2)
        >>> output = d(input)
        >>> d.add_metric(tf.reduce_max(output), name='max')
        >>> d.add_metric(tf.reduce_min(output), name='min')
        >>> [m.name for m in d.metrics]
        ['max', 'min']

        Returns:
          A list of `Metric` objects.
        rZ   N)r+  r   rZ   rB  rX   )rj   collected_metricsr   r,   r,   r-   metrics  s    
,zLayer.metricsc                 K   s~  t | }t|dks0t|dkrD|d dkrDtd|  dt|d}t|tj}t	 j
}|du rz|sztdn|r|jj}|s|std	t| |st| d
dsPt|dd}| }	|r|jn|}| jX | |}
|
r|
}n4|r| j| n"tj|t|ddd}| j| W d   n1 s60    Y  |	rz|| n*|r^td|rhdnd}| ||| dS )aM  Adds metric tensor to the layer.

        This method can be used inside the `call()` method of a subclassed layer
        or model.

        ```python
        class MyMetricLayer(tf.keras.layers.Layer):
          def __init__(self):
            super(MyMetricLayer, self).__init__(name='my_metric_layer')
            self.mean = tf.keras.metrics.Mean(name='metric_1')

          def call(self, inputs):
            self.add_metric(self.mean(inputs))
            self.add_metric(tf.reduce_sum(inputs), name='metric_2')
            return inputs
        ```

        This method can also be called directly on a Functional Model during
        construction. In this case, any tensor passed to this Model must
        be symbolic and be able to be traced back to the model's `Input`s. These
        metrics become part of the model's topology and are tracked when you
        save the model via `save()`.

        ```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)
        model.add_metric(math_ops.reduce_sum(x), name='metric_1')
        ```

        Note: Calling `add_metric()` with the result of a metric object on a
        Functional Model, as shown in the example below, is not supported. This
        is because we cannot trace the metric result tensor back to the model's
        inputs.

        ```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)
        model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1')
        ```

        Args:
          value: Metric tensor.
          name: String metric name.
          **kwargs: Additional keyword arguments for backward compatibility.
            Accepted values:
            `aggregation` - When the `value` tensor provided is not the result
            of calling a `keras.Metric` instance, it will be aggregated by
            default using a `keras.Metric.Mean`.
        r   r   r   zUnknown keyword arguments: z. Expected `aggregation`._metric_objNzkPlease provide a name for your metric like `self.add_metric(tf.reduce_sum(inputs), name='mean_activation')`z;Expected a symbolic Tensor for the metric value, received: rL  FrB   )rl   rB   zUsing 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.mean)listr   lenrC   r   r=   r	   rM  r   r  r  r   rY  rl   r   r&   rZ   _get_existing_metricrX   r(   r   Mean_graph_network_add_metric)rj   r!   rl   rn   kwargs_keysfrom_metric_objis_symbolicrT  
metric_objshould_update_statematchr   r,   r,   r-   
add_metric  s\    6




,
zLayer.add_metricc                 C   s<   t  }|jrdS |js8tj|D ]}t|r$|  q$dS )a  Add update op(s), potentially dependent on layer inputs.

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

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

        Args:
          updates: Update op, or list/tuple of update ops, or zero-arg callable
            that returns an update op. A zero-arg callable should be passed in
            order to disable running the updates by setting `trainable=False`
            on this Layer, when executing in Eager mode.
        N)r   r  in_keras_graphfrozenr?   r   r   rF  )rj   r?  r  updater,   r,   r-   
add_update}  s    zLayer.add_updatec              	   C   s4  | j }d}|D ]$}t|tjr*||j7 }q|d7 }q|t|krftd| jt||t|dd f d}g }|D ]}t|tjr|j}||||  }|	| ||7 }qr|| }	t
|	dr|	jnd}
|j}||
std| j d	| d
|
 d|||	f |d7 }qrt| |  D ]}|  q dS )a  Sets the weights of the layer, from NumPy arrays.

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

        For example, a `Dense` layer returns a list of two values: the kernel
        matrix and the bias vector. These can be used to set the weights of
        another `Dense` layer:

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

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

        Raises:
          ValueError: If the provided weights list does not match the
            layer's specifications.
        r   r   zYou called `set_weights(weights)` on layer "%s" with a weight list of length %s, but the layer was expecting %s weights. Provided weights: %s...N2   r   r,   r   z weight shape z. is not compatible with provided weight shape r   )r1   r=   r   TrackableWeightHandlernum_tensorsr\  r   rl   r   set_weightsr   r   is_compatible_withr(   r   batch_set_valuer+  finalize_state)rj   r1   paramsexpected_num_weightsparamweight_indexweight_value_tuplesrm  tensorsweightweight_shape	ref_shaper   r,   r,   r-   rn    sL    ,





zLayer.set_weightsc                 C   sD   | j }g }|D ]*}t|tjr.||  q|| qt|S )a  Returns the current weights of the layer, as NumPy arrays.

        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: the kernel
        matrix and the bias vector. These can be used to set the weights of
        another `Dense` layer:

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

        Returns:
            Weights values as a list of NumPy arrays.
        )	r1   r=   r   rl  rB  get_tensorsr(   r   batch_get_value)rj   r1   output_weightsrx  r,   r,   r-   get_weights  s    #zLayer.get_weightsc                 C   s   dS )az  Finalizes the layers state after updating layer weights.

        This function can be subclassed in a layer and will be called after
        updating a layer weights. It can be overridden to finalize any
        additional layer state after a weight update.

        This function will be called after weights of a layer have been restored
        from a loaded model.
        Nr,   r   r,   r,   r-   rq  &  s    zLayer.finalize_statec                 C   s2   |  |}t|tr"dd |D S t|ddS dS )a  Retrieves the input mask tensor(s) of a layer at a given node.

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

        Returns:
            A mask tensor
            (or list of tensors if the layer has multiple inputs).
        c                 S   s   g | ]}t |d dqS r   Nr&   r   r,   r,   r-   r   C  r   z+Layer.get_input_mask_at.<locals>.<listcomp>r   N)get_input_atr=   r[  r&   )rj   
node_indexrs   r,   r,   r-   get_input_mask_at3  s    

zLayer.get_input_mask_atc                 C   s2   |  |}t|tr"dd |D S t|ddS dS )a  Retrieves the output mask tensor(s) of a layer at a given node.

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

        Returns:
            A mask tensor
            (or list of tensors if the layer has multiple outputs).
        c                 S   s   g | ]}t |d dqS r  r  r   r,   r,   r-   r   W  r   z,Layer.get_output_mask_at.<locals>.<listcomp>r   N)get_output_atr=   r[  r&   )rj   r  outputr,   r,   r-   get_output_mask_atG  s    

zLayer.get_output_mask_atc                 C   s.   | j }t|trdd |D S t|ddS dS )a  Retrieves the input mask tensor(s) of a layer.

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

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

        Raises:
            AttributeError: if the layer is connected to
            more than one incoming layers.
        c                 S   s   g | ]}t |d dqS r  r  r   r,   r,   r-   r   m  r   z$Layer.input_mask.<locals>.<listcomp>r   N)inputr=   r[  r&   rj   rs   r,   r,   r-   
input_mask[  s    
zLayer.input_maskc                 C   s.   | j }t|trdd |D S t|ddS dS )a  Retrieves the output mask tensor(s) of a layer.

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

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

        Raises:
            AttributeError: if the layer is connected to
            more than one incoming layers.
        c                 S   s   g | ]}t |d dqS r  r  r   r,   r,   r-   r     r   z%Layer.output_mask.<locals>.<listcomp>r   N)r  r=   r[  r&   )rj   r  r,   r,   r-   output_maskq  s    
zLayer.output_maskc                 C   s   |  |ddS )a  Retrieves the input shape(s) of a layer at a given node.

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

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

        Raises:
          RuntimeError: If called in Eager mode.
        input_shapeszinput shape_get_node_attribute_at_indexrj   r  r,   r,   r-   get_input_shape_at  s    zLayer.get_input_shape_atc                 C   s   |  |ddS )a  Retrieves the output shape(s) of a layer at a given node.

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

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

        Raises:
          RuntimeError: If called in Eager mode.
        output_shapeszoutput shaper  r  r,   r,   r-   get_output_shape_at  s    zLayer.get_output_shape_atc                 C   s   |  |ddS )a  Retrieves the input tensor(s) of a layer at a given node.

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

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

        Raises:
          RuntimeError: If called in Eager mode.
        input_tensorsr  r  r  r,   r,   r-   r    s    zLayer.get_input_atc                 C   s   |  |ddS )a  Retrieves the output tensor(s) of a layer at a given node.

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

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

        Raises:
          RuntimeError: If called in Eager mode.
        output_tensorsr  r  r  r,   r,   r-   r    s    zLayer.get_output_atc                 C   s&   | j std| j d | dddS )af  Retrieves the input tensor(s) of a layer.

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

        Returns:
            Input tensor or list of input tensors.

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

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

        Returns:
          Output tensor or list of output tensors.

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

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

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

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

        Returns:
            An integer count.

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

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

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

        Raises:
            AttributeError: if the layer has no defined output shape.
            RuntimeError: if called in Eager mode.
        r  z=" has never been called and thus has no defined output shape.c                 S   s   g | ]}t |jqS r,   )r   r  r  r,   r,   r-   r   Y  r   z&Layer.output_shape.<locals>.<listcomp>r   r   zThe layer "%s" has multiple inbound nodes, with different output shapes. Hence the notion of "output shape" is ill-defined for the layer. Use `get_output_shape_at(node_index)` instead.N)r  r  rl   r  r\  r  )rj   all_output_shapesr,   r,   r-   r   C  s    zLayer.output_shapec                 C   s   | j S )zzThe dtype policy associated with this layer.

        This is an instance of a `tf.keras.mixed_precision.Policy`.
        )r   r   r,   r,   r-   dtype_policyh  s    zLayer.dtype_policyc                 C   s   | j jS )a-  The dtype of the layer's computations.

        This is equivalent to `Layer.dtype_policy.compute_dtype`. Unless
        mixed precision is used, this is the same as `Layer.dtype`, the dtype of
        the weights.

        Layers automatically cast their inputs to the compute dtype, which
        causes computations and the output to be in the compute dtype as well.
        This is done by the base Layer class in `Layer.__call__`, so you do not
        have to insert these casts if implementing your own layer.

        Layers often perform certain internal computations in higher precision
        when `compute_dtype` is float16 or bfloat16 for numeric stability. The
        output will still typically be float16 or bfloat16 in such cases.

        Returns:
          The layer's compute dtype.
        r   r   r   r,   r,   r-   r   p  s    zLayer.compute_dtypec                 C   s   | j S )z1Alias of `Layer.dtype`, the dtype of the weights.r   r   r,   r,   r-   r     s    zLayer.variable_dtypec                 C   s   | j S )z3Return Functional API nodes upstream of this layer.)r  r   r,   r,   r-   inbound_nodes  s    zLayer.inbound_nodesc                 C   s   | j S )z5Return Functional API nodes downstream of this layer.)_outbound_nodesr   r,   r,   r-   outbound_nodes  s    zLayer.outbound_nodesc                 C   s   | j S )a   Returns the list of all layer variables/weights.

        Alias of `self.weights`.

        Note: This will not track the weights of nested `tf.Modules` that are
        not themselves Keras layers.

        Returns:
          A list of variables.
        )r1   r   r,   r,   r-   r8    s    zLayer.variablesc                 C   s   | j S r   )r6  r   r,   r,   r-   r2    s    zLayer.trainable_variablesc                 C   s   | j S r   )r9  r   r,   r,   r-   r7    s    zLayer.non_trainable_variablesc                 O   s   t jddd | j|i |S )z/Deprecated, do NOT use! Alias for `add_weight`.z`layer.add_variable` is deprecated and will be removed in a future version. Please use the `layer.add_weight()` method instead.r:  r;  )r=  r>  r   )rj   rt   rn   r,   r,   r-   add_variable  s
    zLayer.add_variable)_obj_reference_counts_dictc                 C   s6   t | jddd}|d ur"d|S | jjd | jj S )NkerasT)api_nameadd_prefix_to_v1_namesztf.{}r   )r   r   r1  
__module__r   )rj   canonical_namer,   r,   r-   _get_cell_name  s    
zLayer._get_cell_namec                 C   s   d| _ d| _d| _t| ddsxtdd d| _ t| ddr\t|  d d| _qt	|  d d| _ntdd d S )NF_disable_keras_instrumentationr   T_is_model_for_instrumentationZlegacy_layer)
_instrumented_keras_api_instrumented_keras_layer_class_instrumented_keras_model_classr&   keras_api_gaugeget_cellr  keras_models_gauger  keras_layers_gauger   r,   r,   r-   r;     s    z Layer._instrument_layer_creationc                 C   s>   t |tjr|}n
t|}|r.| j| n| j| |S )a  Adds a Trackable object to this layer's state.

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

        Returns:
          The TrackableWeightHandler used to track this object.
        )r=   r   rl  r8   r(   r9   )rj   trackable_objectrk   handlerr,   r,   r-   _add_trackable  s    
zLayer._add_trackablec                 C   s0   t | ddsg | j_n|  D ]}g |j_qdS )z)Used every step in eager to reset losses.r:   N)r&   rU   r@  r+  )rj   r   r,   r,   r-   r  	  s    
zLayer._clear_lossesc                 C   sF   | j r2tjdd |}| |}tjtj|S | ||||S d S )Nc                 S   s   t j| j| jdS r   )r?   r   r   rB   r   r,   r,   r-   r   "	  r   z3Layer._keras_tensor_symbolic_call.<locals>.<lambda>)rm   r?   r   r   r   r	   rM  _infer_output_signature)rj   rs   r  rt   rn   r   output_signaturer,   r,   r-   _keras_tensor_symbolic_call	  s    
z!Layer._keras_tensor_symbolic_callc           	   
   C   s  |}| j }t| r8t| s8tjj| j tjj }t	j
|d| j d| jj dd}tjt| jd }|  tjtj|}tjtj|}tjtj|}tjtj|}t|  t t| j: | | | |}||g|R i |}W d   n1 s0    Y  | || W d   n1 sF0    Y  | j|||dd tjtj|}W d   n1 s0    Y  |  ||| t!| d	r| j"s| #|| ~|S )
zBCall the layer on input KerasTensors, returns output KerasTensors.r   z" (type r   r   r   NF)r   _set_inputs)$ru   r   is_subclassedfrom_saved_modelr?   r   	autograph
tf_convertcontrol_status_ctxr   r  rl   r   r   r   r   r   r   r   r	   keras_tensor_to_placeholderr   r  r#  r   r  r  r   r  r  r  keras_tensor_from_tensorr  r   rs   r  )	rj   rs   rt   rn   r  Zkeras_tensor_inputsr  scratch_graphr   r,   r,   r-   r  -	  sb    


6,$zLayer._infer_output_signaturec                 C   s  t  }tdd |D r<dd }tj||}tj|}d}| ||||\}}	| jrj|	rj||d< d}d }
d}| j	
d||r| j	d||}
| js|d |
d u r|jd ur|j}
n<t rt }
t|
rt|
tj}
qt|
}
n| j	j}
| jr| j	d|
||\}}d}|j| |d|
d	 | ||||}|d u r\td
| j d |r|| j	jdd ||dd\}}|r|d | |f| ||}|W  d    S 1 s0    Y  d S )Nc                 s   s$   | ]}t |tjtjttfV  qd S r   r   r   r,   r,   r-   r   {	  s   z6Layer._functional_construction_call.<locals>.<genexpr>c                 S   s$   t | tjtjttfr t| S | S r   r=   r?   r@   r   r   r   r   rH  r  r,   r,   r-   _convert_non_tensor	  s    
z@Layer._functional_construction_call.<locals>._convert_non_tensorFr   Tr   r   zVA layer's `call` method should return a Tensor or a list of Tensors, not None (layer: z).)pop_kwarg_if_none)r   r  r   r?   r   r   r   r  r  r   arg_was_passedget_arg_value_expects_training_argr*   r   r   global_learning_phase_is_setlearning_phaserG  castr>   default_training_argset_arg_valuer  r  r   rl   _set_connectivity_metadata)rj   rs   rt   rn   r  r  r  mask_arg_passed_by_frameworkr  r  training_value training_arg_passed_by_frameworkr   r,   r,   r-   r   w	  sx    









z#Layer._functional_construction_callc                 C   s   d }| j r| jd||r*| jd||}|d u r|j}|d urF|}nHt rt }t|t	rbqt
|r|t
|t
j	}qt	|}n| jj}| jd|||\}}nd|v r|d}n|j}|||fS )Nr   )r  r   r  r  r   r   r  r  r=   r>   r?   rG  r  r  r  r*   )rj   rt   rn   r  r  call_ctx_trainingr,   r,   r-   r  	  s2    



zLayer._set_training_modec                 C   s8   t | r.t | s.tjj| jtjj S | jS d S r   )	r   r  r  r?   r   r  r  ru   r  r   r,   r,   r-   r  
  s    zLayer._autographed_callc                 C   s   | j S r   r^   r   r,   r,   r-   r  
  s    zLayer._inbound_nodesc                 C   s
   || _ d S r   r  r(  r,   r,   r-   r  
  s    c                 C   s   | j S r   r_   r   r,   r,   r-   r   
  s    zLayer._outbound_nodesc                 C   s
   || _ d S r   r  r(  r,   r,   r-   r  $
  s    c                 C   s   t |tjr|| _n\t |tr,t|| _nDt |trL|dv rLt|| _n$|rftt|j	| _n
t
 | _| jj	dkrt stj }td|jj| jj	f | jjrt| jj| _nd| _dS )zSets self._dtype_policy.)mixed_float16mixed_bfloat16r  zMixed precision is not supported with the tf.distribute.Strategy: %s. Either stop using mixed precision by removing the use of the "%s" policy or use a different Strategy, e.g. a MirroredStrategy.N)r=   r   r   r   dictdeserializer   r?   r   rl   global_policyr   strategy_supports_loss_scaling
distributeget_strategyr   r   r   r   r  )rj   rB   strategyr,   r,   r-   r[   )
  s0    



zLayer._set_dtype_policyc                 C   s   | j jS )z$Deprecated alias of `compute_dtype`.r  r   r,   r,   r-   r   V
  s    zLayer._compute_dtypec                 C   sR   |st j|}| j}| jo$|o$|j}|rJtt| j|rJt j	| j
|S |S dS )a  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.
          input_list: Flat list of input tensors.

        Returns:
          `inputs`, but tensors may have been casted to self._compute_dtype
        N)r?   r   r   r  r]   r   r   map_should_cast_single_inputr   _cast_single_input)rj   rs   r  compute_dtype_objectshould_autocastr,   r,   r-   r  [
  s    
zLayer._maybe_cast_inputsc                 C   s(   t |tr$| jo"|j| jko"|jjS dS )NF)r=   _AUTOCAST_TYPESr  rB   r   rj   r   r,   r,   r-   r  z
  s    

zLayer._should_cast_single_inputc                 C   s    |  |rt|| jS |S dS )z8Cast a single Tensor or TensorSpec to the compute dtype.N)r  r?   r  r  r  r,   r,   r-   r  
  s    
zLayer._cast_single_inputc                 C   s   | j jS r   r%  r   r,   r,   r-   _dtype
  s    zLayer._dtypec                 C   s    t |j}| t| d S r   )r?   r   rl   r[   r   r   r(  r,   r,   r-   r  
  s    c                 C   sB   t jj s| jS | j}t j }|r2|d | }|r>|d7 }|S r   )r?   r   tf2enabledrl   get_name_scope)rj   r  r$  r,   r,   r-   r#  
  s    
zLayer._name_scopec                 C   sR   |d u r$t jt| jj|d| _n*t|tr@t 	| || _nt
d| d S )N)
zero_basedz2Expected `name` argument to be a string, but got: )r   unique_object_namer   r   r   r   r
  r=   r   observe_object_namerC   )rj   rl   r  r,   r,   r-   rN   
  s    


zLayer._init_set_namec                    sD    fdd| j D }|sd S t|dkr<tdt| |d S )Nc                    s   g | ]}|j  kr|qS r,   rl   r   r  r,   r-   r   
  r   z.Layer._get_existing_metric.<locals>.<listcomp>r   zfPlease provide different names for the metrics you have added. We found {} metrics with the name: "{}"r   )rX   r\  r   r1  )rj   rl   re  r,   r  r-   r]  
  s    zLayer._get_existing_metricc                    sl    fdd}t |r6|D ]}| t|| qn2t|tjrV| j	 |f n| t|| dS )z3Create lambdas which compute regularization losses.c                    s:   t  d  | }W d   n1 s,0    Y  |S )z8Creates a regularization loss `Tensor` for variable `v`.z/RegularizerN)r   r  )r   regularizationrl   r   r,   r-   _loss_for_variable
  s    &z?Layer._handle_weight_regularization.<locals>._loss_for_variableN)
r   r   rV  r   r   r=   r   LazyInitVariableri   r(   )rj   rl   r   r   r  r   r,   r  r-   r   
  s    
z#Layer._handle_weight_regularizationc                 C   s   | j rtj|}tdT |D ]>}t|  |}tt|d |j	}|| }| 
| q"W d    n1 sv0    Y  d S )NActivityRegularizerr   )rP   r?   r   r   r   r  rH  r  r   rB   rV  )rj   rs   r   output_listr  activity_lossr7   mean_activity_lossr,   r,   r-   r  
  s    z%Layer._handle_activity_regularizationc              	   C   s   | j s
d S tj|}t| ddp2tdd |D }|rJ|rF| | d S | ||}|d u rbd S tj|}t||D ]&\}	}
z
|
|	_	W qx t
y   Y qx0 qx|r| | d S )N _compute_output_and_mask_jointlyFc                 s   s   | ]}t |d dduV  qdS r  r  r   r,   r,   r-   r   
  s   z+Layer._set_mask_metadata.<locals>.<genexpr>)rM   r?   r   r   r&   all_set_mask_keras_history_checkedrL   zipr   r  )rj   rs   r   previous_maskr   flat_outputsmask_already_computedoutput_masks
flat_maskstensorr   r,   r,   r-   r  
  s2    

zLayer._set_mask_metadatac                 C   s&   |D ]}t |dd d urd|j_qd S )Nr   T)r&   r   _keras_history_checked)rj   r  r  r,   r,   r-   r  	  s    z%Layer._set_mask_keras_history_checkedc                 C   s   | j s| jsd }d}nb| jd||r<| jd||}d}n<dd |D }tdd |D rfd }d}ntj||}d}||fS )NFr   c                 S   s   g | ]}t |d dqS r  r  )r   r   r,   r,   r-   r     r   z*Layer._get_input_masks.<locals>.<listcomp>c                 s   s   | ]}|d u V  qd S r   r,   )r   r   r,   r,   r-   r     r   z)Layer._get_input_masks.<locals>.<genexpr>T)	rM   r  r   r  r  r  r?   r   pack_sequence_as)rj   rs   r  rt   rn   r  implicit_maskr,   r,   r-   r    s    zLayer._get_input_masksc           	   	   C   s   t j|}t j||f}dd |D }g }|D ]P}t||v rxt| j t |}W d    n1 sn0    Y  || q2t j	||}t
j| |||d |S )Nc                 S   s   h | ]}t |qS r,   )id)r   ir,   r,   r-   	<setcomp>)  r   z3Layer._set_connectivity_metadata.<locals>.<setcomp>)	call_argscall_kwargsr   )r?   r   r   r  r   r  rl   identityr(   r  node_moduleNode)	rj   rt   rn   r   r  flat_inputsinput_ids_setoutputs_copyr   r,   r,   r-   r  $  s    (z Layer._set_connectivity_metadatac                 C   s   | j std| j d| dt| j |ksNtd| d| dt| j  dt| j | |}t|tr|t|dkr||d	 S |S d
S )a  Private utility to retrieves an attribute (e.g. inputs) from a node.

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

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

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

        Raises:
            RuntimeError: If the layer has no inbound nodes, or if called in
                Eager mode.
            ValueError: If the index provided does not match any node.
        z
The layer z/ has never been called and thus has no defined r   zAsked to get z	 at node z, but the layer has only z inbound nodes.r   r   N)r  r   rl   r\  r   r&   r=   r[  )rj   r  attr	attr_namevaluesr,   r,   r-   r  <  s$    
z"Layer._get_node_attribute_at_indexc                 C   sJ  | j st| j|| j tj|}|rj| jjd u rjz|d j	j
j}W n tyX   Y n0 | t| d }tdd |D rt|}n&ztj|dd}W n ty   Y n0 t| jdst|  | | W d    n1 s0    Y  t| | | jd urFt  | | j W d    n1 s60    Y  d | _d S )Nr   c                 s   s   | ]}t |d V  qdS )r   N)r   r   r,   r,   r-   r   t  r   z%Layer._maybe_build.<locals>.<genexpr>Fr   r   )rF   r   r	  rl   r?   r   r   r   r   rB   r   r  r[   r   r   r   r   
get_shapesr   r   r   rr   r  r/   rd   
init_scopern  )rj   rs   r  rB   r  r,   r,   r-   r   d  s8    

(
,zLayer._maybe_buildc                 C   s$   t  }|  D ]}|j||< q|S )zGet the `trainable` state of each sublayer.

        Returns:
          A dict mapping all sublayers to their `trainable` value.
        )weakrefWeakKeyDictionaryr+  rk   rj   trainable_stater   r,   r,   r-   _get_trainable_state  s    zLayer._get_trainable_statec                 C   s$   |   D ]}||v r|| |_qdS )z(Set `trainable` state for each sublayer.N)r+  rk   r  r,   r,   r-   _set_trainable_state  s    zLayer._set_trainable_statec                 C   s   |  dt  | jS )z?A dict counting the number of attributes referencing an object.r  )rQ   r   ObjectIdentityDictionaryr  r   r,   r,   r-   _obj_reference_counts  s
    zLayer._obj_reference_countsc                 C   s   t | |s| || dS )a+  Create the attribute with the default value if it hasn't been created.

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

        Args:
          name: String, the name of the attribute.
          default_value: Object, the default value of the attribute.
        N)r   __setattr__)rj   rl   default_valuer,   r,   r-   rQ     s    
zLayer._maybe_create_attributec                    s$  t | |d  | j} |vr4ttjjj| | d S |  }|dkrj|d | < ttjjj| | d S | = ttjjj| | t t	st
 rttjjj| d fdd| jD  t tjr ttjjj| d fdd| jD  ttjjj| d fdd| jD  d S )	Nr   r:   c                    s   g | ]}| ur|qS r,   r,   )r   lexisting_valuer,   r-   r     s   z%Layer.__delattr__.<locals>.<listcomp>r8   c                    s   g | ]}| ur|qS r,   r,   r   wr  r,   r-   r     r   r9   c                    s   g | ]}| ur|qS r,   r,   r   r  r,   r-   r     s   )r&   r  superr?   r   trackingAutoTrackable__delattr__r=   r/   r   has_weightsr  r:   rA   r8   r9   )rj   rl   reference_countsreference_countr   r  r-   r%    sH    	

zLayer.__delattr__c                    s  |dks t | ddr t| j|rbzttjjj| | W n  t	y\   t	d
|Y n0 d S tjjj| |d| j}|dd |< z| | W n t	y   Y n0 tjD ]& t tjrt| dr| j  qt | ddrRttjstrR| d	g  tfd
d| jD sR| j tdrRd_tjjddD ] t tjsxqb| dg  | dg   jrt fdd| jD rqb| j  n*t fdd| j D rqb| j   t!"  qbttjjj| | d S )N_self_setattr_trackingTzCan't set the attribute "{}", likely because it conflicts with an existing read-only @property of the object. Please choose a different name.)	trackabler!   rl   r   r   rX   re   r:   c                 3   s   | ]}| u V  qd S r   r,   r)  )r!   r,   r-   r   .  r   z$Layer.__setattr__.<locals>.<genexpr>_use_resource_variables)expand_compositesr8   r9   c                 3   s   | ]} |u V  qd S r   r,   r   valr,   r-   r   B  r   c                 3   s   | ]} |u V  qd S r   r,   r   r.  r,   r-   r   F  r   )#r&   r   r   r"  r?   r   r#  r$  r  r  r1  sticky_attribute_assignmentr  rO   r%  r   r   r=   r   MetricrX   r(   Moduler   r&  rQ   r   r:   r,  rA   rk   r8   r9   r   r   )rj   rl   r!   r'  r)  )r/  r!   r-   r    sx    



zLayer.__setattr__c                    sF    dv sJ t | drB| jddd}ttj fdd|D S g S )N>   r2  r7  r8  r:   F)include_self	recursivec                 3   s   | ]}t | V  qd S r   r  r)  	attributer,   r-   r   ]  s   z3Layer._gather_children_attribute.<locals>.<genexpr>)r   _flatten_modulesr[  	itertoolschainfrom_iterable)rj   r6  nested_layersr,   r5  r-   r3  R  s    
z Layer._gather_children_attributec                 c   s(   | j ||dD ]}t|tr|V  qd S )N)r4  r3  )r7  r=   r/   )rj   r4  r3  r   r,   r,   r-   r+  c  s
    

zLayer._flatten_layersc           
      c   s   |r
| V  t | dd}|rt }t|}|r| }t|}||v rHq*|| t|tj	rt|t
js|V  |rt |dd}|r|t| q*t|tjjjr*|j}	|	r*|t|	 q*dS )a   Flattens `tf.Module` instances (excluding `Metrics`).

        Args:
          recursive: Whether to recursively flatten through submodules.
          include_self: Whether to include this `Layer` instance.

        Yields:
          `tf.Module` instance tracked by this `Layer`.
        r:   N)r&   r  rw   dequepopleftr  addr=   r?   r2  r   r1  
extendleftreversedr   r#  TrackableDataStructure_values)
rj   r4  r3  
trackablesseen_object_idsr<  trackable_objtrackable_idsubtrackablestracked_valuesr,   r,   r-   r7  j  s:    


zLayer._flatten_modulesc                 C   s   dS )NTr,   r   r,   r,   r-   	_is_layer  s    zLayer._is_layerc                 C   s(   t t| j| _|d ur$|| j_d S r   )r   CallFunctionSpecr   r   ru   r   expects_training_arg)rj   rK  r,   r,   r-   r`     s
    
zLayer._init_call_fn_argsc                 C   s   | j jS )z9Whether the call function uses 'training' as a parameter.)r   rK  r   r,   r,   r-   r    s    zLayer._expects_training_argc                 C   s   | j jS r   )r   expects_mask_argr   r,   r,   r-   r    s    zLayer._expects_mask_argc                 C   s   t | jdsg | j_| jjS )Nr@  )r   rU   r@  r   r,   r,   r-   r@    s    zLayer._eager_lossesc                 C   s   || j _d S r   )rU   r@  )rj   rE  r,   r,   r-   r@    s    c                 C   s>   g t   }}|D ](}t||vr|| |t| q|S )z;Dedupe weights while maintaining order as much as possible.)r  r  r(   r>  )rj   r1   r  seen_idsr!  r,   r,   r-   r4    s    
zLayer._dedup_weightsc                 C   s   | j durdS tjtj|}tjtj|p.g }i }| D ]H\}}tj|}	dd |	D }
tdd |
D rtq>tj	||
||< q>|| _ |gt
| |f| _dS )a  Defines the save spec so that serialization is able to trace layer call.

        The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
        saved into a tuple of `([inputs] + args, kwargs)`.

        Args:
          inputs: possibly nested inputs passed into the call function.
          args: a list of positional arguments passed into call.
          kwargs: a dictionary of keyword arguments passed into call.
        Nc                 S   s   g | ]}t |qS r,   r   get_tensor_specr   r,   r,   r-   r     r   z(Layer._set_save_spec.<locals>.<listcomp>c                 s   s   | ]}|d u V  qd S r   r,   r   r,   r,   r-   r     r   z'Layer._set_save_spec.<locals>.<genexpr>)rI   r?   r   r   r   rO  itemsr   r   r  r[  rJ   )rj   rs   rt   rn   Zinputs_spec	args_specZkwargs_speckeyr   Z
flat_kwarg
flat_specsr,   r,   r-   r    s    
zLayer._set_save_specc                    s:   | j d u rd S tj fdd| j}|r6|d d S |S )Nc                    s   t j|  dS )Ndynamic_batchrN  r   rT  r,   r-   r     r   z&Layer._get_save_spec.<locals>.<lambda>r   )rI   r?   r   r   rJ   )rj   rU  inputs_onlyspecr,   rT  r-   _get_save_spec  s    

zLayer._get_save_specc                 C   s
   t | S r   )r   LayerSavedModelSaverr   r,   r,   r-   _trackable_saved_model_saver  s    z"Layer._trackable_saved_model_saverc                 C   s   | j jS r   )rZ  object_identifierr   r,   r,   r-   _object_identifier  s    zLayer._object_identifierc                 C   s   | j jS )z6Info about this layer to be saved into the SavedModel.)rZ  tracking_metadatar   r,   r,   r-   _tracking_metadata  s    zLayer._tracking_metadata
checkpointc                    s@   |dkr|d }| j |}ni }|t j|fi | |S )N
savedmodelcache)rZ  trackable_childrenri  r"  _trackable_childrenrj   	save_typern   ra  childrenr)  r,   r-   rc    s    zLayer._trackable_childrenc                 C   s   t t| ddd uS )Nr  )r  )r   r    r   r,   r,   r-   !_use_input_spec_as_call_signature  s    z'Layer._use_input_spec_as_call_signaturec                 C   s&   | j  }|dd  |dd  |S )NrU   rZ   )__dict__copyr*   rj   stater,   r,   r-   __getstate__  s    
zLayer.__getstate__c                 C   s*   t  |d< t  |d< t| d| d S )NrU   rZ   rh  )rS   rT   rY   objectr  rj  r,   r,   r-   __setstate__'  s    zLayer.__setstate__)TNNF)N)N)N)T)N)TT)TT)N)NN)TT)r_  )r   r  __qualname____doc__r?   r   r#   no_automatic_dependency_trackingrp   r   defaultrr   r   for_subclass_implementersru   r   AUTOVariableAggregationNONEr   r   classmethodr   r   r   rL   r   filter_tracebackr  r  propertyrB   rl   r'  setterrm   do_not_doc_inheritabler-  rk   r6   r   r6  r9  r1   do_not_generate_docsr?  rE  rV  rX  rf  rj  rn  r~  rq  r  r  r  r  r  r  r  r  r  r  r4   r  r   r  r   r   r  r  r8  r2  r7  r  	frozensetr8  r9  r2  _TF_MODULE_IGNORED_PROPERTIES_must_restore_from_configr  r;   r  r  r  r  r   r  r  r  r  r[   r   r  r  r  r  r#  rN   r]  r   r  r  r  r  r  r  r   r  r  r  rQ   r%  r  r3  r+  r7  rI  r`   r  r  r@  r4  r  rX  rZ  r\  r^  rc  rg  rl  rn  __classcell__r,   r,   r)  r-   r/      s   7  "
/ I
A
6
,
 
	









"	


	
@z

 
],








'#




Ja/

-

	




"(/

=W

2











r/   c                       s^   e Zd ZdZejjjd fdd	Zdd Z	dd	 Z
d
d Zejdd Z fddZ  ZS )TensorFlowOpLayera  Wraps a TensorFlow Operation in a Layer.

    This class is used internally by the Functional API. When a user
    uses a raw TensorFlow Operation on symbolic tensors originating
    from an `Input` Layer, the resultant operation will be wrapped
    with this Layer object in order to make the operation compatible
    with the Keras API.

    This Layer will create a new, identical operation (except for inputs
    and outputs) every time it is called. If `run_eagerly` is `True`,
    the op creation and calculation will happen inside an Eager function.

    Instances of this Layer are created when `autolambda` is called, which
    is whenever a Layer's `__call__` encounters symbolic inputs that do
    not have Keras metadata, or when a Network's `__init__` encounters
    outputs that do not have Keras metadata.

    Attributes:
      node_def: String, the serialized NodeDef of the Op this layer will wrap.
      name: String, the name of the Layer.
      constants: Dict of NumPy arrays, the values of any Tensors needed for this
        Operation that do not originate from a Keras `Input` Layer. Since all
        placeholders must come from Keras `Input` Layers, these Tensors must be
        treated as constant in the Functional API.
      trainable: Bool, whether this Layer is trainable. Currently Variables are
        not supported, and so this parameter has no effect.
      dtype: The default dtype of this Layer. Inherited from `Layer` and has no
        effect on this class, however is used in `get_config`.
    NTc                    s   t t| jt| ||dd t|tr>t|tj	j
 | _n&t|tsR|d}tj	j
j|| _|d ur~dd | D ni | _d| _d| _d S )NF)rl   rk   rB   r2   zutf-8c                 S   s   i | ]\}}t ||qS r,   )r   )r   indexconstantr,   r,   r-   
<dictcomp>c  r   z.TensorFlowOpLayer.__init__.<locals>.<dictcomp>T)r"  r  rp   _TF_OP_LAYER_NAME_PREFIXr=   r  r   	ParseDictr?   compatv1NodeDefnode_defbytesencode
FromStringrP  	constantsrF   r  )rj   r  rl   r  rk   rB   r)  r,   r-   rp   M  s&    



zTensorFlowOpLayer.__init__c                 C   s   t  r| |S | |S r   )r?   r   _defun_call_make_opr  r,   r,   r-   ru   n  s    
zTensorFlowOpLayer.callc                 C   s6   t jj }|| j d|jd _||j	|_	|S )NT_cloned)
r?   r  r  r  CopyFromr  r  bunique_namerl   )rj   graphr  r,   r,   r-   _make_node_defs  s
    z TensorFlowOpLayer._make_node_defc                 C   sR  t j|}|d j}| |}|  | j D ]:\}}t |}|d urdt j	||j
| d}||| q6t jj|||g d}||}|  t j|jj}	dd |jjD }
g }|
D ]}|| ||| qt|}t j|	|j||j t|jdkr(|jd W  d    S |jW  d    S 1 sD0    Y  d S )Nr   r  )control_inputsc                 S   s   g | ]}t j|jqS r,   )r?   r  as_strrl   )r   r  r,   r,   r-   r     s   z.TensorFlowOpLayer._make_op.<locals>.<listcomp>r   )r?   r   r   r  r  r   r  rP  get_static_valuer  r  insertr   create_c_op_create_op_from_tf_operation_control_flow_post_processingr  r  op_defrl   r  r(   get_attrrb   record_gradientrs   r   r\  )rj   rs   r  r  r  r  r!   c_opopop_type
attr_namesattrsr  r,   r,   r-   r  |  s:    




zTensorFlowOpLayer._make_opc                 C   s
   |  |S )z@Wraps op creation method in an Eager function for `run_eagerly`.)r  r  r,   r,   r-   r    s    zTensorFlowOpLayer._defun_callc                    sL   t t|  }||d ttd  t| jdd | j	
 D d |S )Nrl   c                 S   s   i | ]\}}|t |qS r,   )r   	get_value)r   r  cr,   r,   r-   r    s   z0TensorFlowOpLayer.get_config.<locals>.<dictcomp>)rl   r  r  )r"  r  r   ri  r\  r  r   MessageToDictr  r  rP  rj   r   r)  r,   r-   r     s    
zTensorFlowOpLayer.get_config)NTN)r   r  ro  rp  r?   r   r#  rq  rp   ru   r  r  functionr  r   r  r,   r,   r)  r-   r  .  s     	&
r  c                       s4   e Zd ZdZ fddZdd Z fddZ  ZS )AddLosszAdds its inputs as a loss.

    Attributes:
      unconditional: Whether or not the loss should be conditioned on the
        inputs.
    c                    s(   d|d< t t| jf i | || _d S )NFr2   )r"  r  rp   unconditional)rj   r  rn   r)  r,   r-   rp     s    zAddLoss.__init__c                 C   s   | j || j d |S )N)rs   )rV  r  r  r,   r,   r-   ru     s    zAddLoss.callc                    s"   t t|  }|d| ji |S )Nr  )r"  r  r   ri  r  r  r)  r,   r-   r     s    zAddLoss.get_configr   r  ro  rp  rp   ru   r   r  r,   r,   r)  r-   r    s   r  c                       s6   e Zd ZdZd	 fdd	Zdd Z fddZ  ZS )
	AddMetriczAdds its inputs as a metric.

    Attributes:
      aggregation: 'mean' or None. How the inputs should be aggregated.
      metric_name: The name to use for this metric.
    Nc                    s&   t t| jf i | || _|| _d S r   )r"  r  rp   r   metric_name)rj   r   r  rn   r)  r,   r-   rp     s    zAddMetric.__init__c                 C   s   | j || j| jd |S )N)r   rl   )rf  r   r  r  r,   r,   r-   ru     s    
zAddMetric.callc                    s&   t t|  }|| j| jd |S )N)r   r  )r"  r  r   ri  r   r  r  r)  r,   r-   r     s
    zAddMetric.get_config)NNr  r,   r,   r)  r-   r    s   r  c                 C   s    t dd tj|||gD S )zECheck the arguments to see if we are constructing a functional model.c                 s   s   | ]}t |tjV  qd S r   )r=   r	   rM  )r   r  r,   r,   r-   r     s   z3_in_functional_construction_mode.<locals>.<genexpr>)r   r?   r   r   )r   rs   rt   rn   r  r,   r,   r-   r     s    r   c                 C   s$   t | tjtjttfr t| S | S r   r  r  r,   r,   r-   r    s    
r  z8keras.__internal__.apply_name_scope_on_model_declaration)r  c                 C   s    t | tstd| | adS )a<  Apply `with tf.name_scope(...)` on model declaration.

    ```python
    tf.keras.__internal__.apply_name_scope_on_model_declaration(True)

    inputs = input_layer.Input((3,))
    with tf.name_scope('MyScope'):
      outputs = layers.Dense(10, name='MyDense')(inputs)
    model = tf.keras.Model(inputs, outputs)

    # with `tf.keras.__internal__.apply_name_scope_on_model_declaration(True)`,
    # The name of the dense layer is "model/MyScope/MyDense/*", and without,
    # "model/MyDense/*"
    ```

    Args:
      enable: Enables if `True`, disables if `False`.
    z3`enable` argument must be `True` or `False`, got {}N)r=   r>   rC   r1  r  )enabler,   r,   r-   &_apply_name_scope_on_model_declaration  s
    
r  z)keras.__internal__.layers.BaseRandomLayerc                       sR   e Zd ZdZejjjd fdd	Z fddZ	d fd	d
	Z
 fddZ  ZS )BaseRandomLayerzAA layer handle the random number creation and savemodel behavior.NFc                    s(   t  jf i | tj|||d| _dS )a  Initialize the BaseRandomLayer.

        Note that the constructor is annotated with
        @no_automatic_dependency_tracking. This is to skip the auto
        tracking of self._random_generator instance, which is an AutoTrackable.
        The backend.RandomGenerator could contain a tf.random.Generator instance
        which will have tf.Variable as the internal state. We want to avoid
        saving that state into model.weights and checkpoints for backward
        compatibility reason. In the meantime, we still need to make them
        visible to SavedModel when it is tracing the tf.function for the
        `call()`.
        See _list_extra_dependencies_for_serialization below for more details.

        Args:
          seed: optional integer, used to create RandomGenerator.
          force_generator: boolean, default to False, whether to force the
            RandomGenerator to use the code branch of tf.random.Generator.
          rng_type: string, the rng type that will be passed to backend
            RandomGenerator. Default to `None`, which will allow RandomGenerator
            to choose types by itself. Valid values are "stateful", "stateless",
            "legacy_stateful".
          **kwargs: other keyword arguments that will be passed to the parent
            *class
        )force_generatorrng_typeN)r"  rp   r   RandomGenerator_random_generator)rj   seedr  r  rn   r)  r,   r-   rp     s    zBaseRandomLayer.__init__c                    s   t  | | j  d S r   )r"  rr   r  _maybe_initrq   r)  r,   r-   rr   =  s    zBaseRandomLayer.buildr_  c                    sJ   |dkr(|d }| j |}| j|d< ni }|t j|fi | |S )Nr`  ra  r  )rZ  rb  r  ri  r"  rc  rd  r)  r,   r-   rc  A  s    z#BaseRandomLayer._trackable_childrenc                    s   |dkr| j S t |S d S )Nr  )r  r"  _lookup_dependency)rj   rl   r)  r,   r-   r  R  s    z"BaseRandomLayer._lookup_dependency)NFN)r_  )r   r  ro  rp  r?   r   r#  rq  rp   rr   rc  r  r  r,   r,   r)  r-   r    s     r  )Urp  rw   r  r   r8  r   rS   r=  r  numpyr   tensorflow.compat.v2r  v2r?   r  r   r   r   r   keras.dtensorr   keras.enginer   r   r	   r
   r	  keras.mixed_precisionr   r   r   keras.saving.saved_modelr   keras.utilsr   r   r   r   r   r   r   keras.utils.generic_utilsr   keras.utils.tf_utilsr   google.protobufr   tensorflow.python.platformr    tensorflow.python.util.tf_exportr   r   tensorflow.tools.docsr   
LazyLoaderglobalsr   r  r@   SparseTensorRaggedTensorr  r   
monitoring	BoolGauger  r  r  Zkeras_premade_model_gauger  rT   r'   contextmanagerr.   r2  LayerVersionSelectorr/   r  r  r  r   r  r  r  r,   r,   r,   r-   <module>   s   
!                         D 



