B
    ӻdV                @   s4  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
mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddl$m%Z% ddl$m&Z& ddl$m'Z' ddl$m(Z( ddl)m*Z* ddl)m+Z+ ddl)m,Z, ddl)m-Z. ddl/m0Z0 ddl/m1Z1 ddl/m2Z2 ddl3m4Z4 ddl5m6Z6 dd l5m7Z7 dd!l5m8Z8 dd"l5m9Z9 dd#l5m:Z: dd$l5m;Z; dd%l<m=Z= dd&l>m?Z? dd'l@mAZA dd(lBmCZC dd)lBmDZD dd*lBmEZF dd+lGmHZH dd,lImJZJ dd-lKmLZL dd.lMmNZN dd/lMmOZP dd0lMmQZQ dd1lRmSZS dd2lRmTZT dd3lUmVZV dd4lUmWZW dd5lXmYZY e6Zd6e[ d7Z\d8Z]e j^e!j_eJj`fZaeWd9G d:d; d;eAjbe;jcZdG d<d= d=edZeG d>d? d?edZfG d@dA dAedZgdBdC ZhdDdE Zie+jjZjdS )Fz=Contains the base Layer class, from which all layers inherit.    N)json_format)node_def_pb2)tf2)ag_ctx)api)distribution_strategy_context)backprop)context)def_function)constant_op)dtypes)
func_graph)ops)sparse_tensor)tensor_spec)tensor_util)backend)constraints)initializers)regularizers)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)version_utils)to_snake_case)is_tensor_or_tensor_list)module)	array_ops)math_ops)	variables)	np_arrays)ragged_tensor)
tf_logging)autotrackable)base)data_structures)compat)nest)get_canonical_name_for_symbol)keras_export)doc_controlsmetrics_modztensorflow.python.keras.metricsZtf_op_layer_zkeras.layers.Layerc                   s@  e Zd ZdZeedejj	Z	dZ
dd Zdd Zejdd
dZejejdd Zejdd Zejdd Zejd	d	d	d	d	d	d	d	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!dd Z"dd Z#ejdd d!Z$d"d# Z%d$d% Z&d&d' Z'd(d) Z(e)d*d+ Z*e)d,d- Z+e)d.d/ Z,e,j-d0d/ Z,e)d1d2 Z.e)ej/d3d4 Z0e0j-d5d4 Z0e)d6d7 Z1e1j-d8d7 Z1e)d9d: Z2e2j-d;d: Z2e)d<d= Z3e3j-ejd>d= Z3e)d?d@ Z4e)dAdB Z5e)dCdD Z6e)ej7dEdF Z8e)dGdH Z9dIdJ Z:dKdL Z;e)dMdN Z<ddOdPZ=ej/ddQdRZ>dSdT Z?dUdV Z@ej7dWdX ZAej7dYdZ ZBej7d[d\ ZCej/d]d^ ZDej/d_d` ZEe)ej/dadb ZFe)ej/dcdd ZGej/dedf ZHej/dgdh ZIej/didj ZJej/dkdl ZKe)dmdn ZLe)dodp ZMe)ej/dqdr ZNdsdt ZOe)ej/dudv ZPe)ej/dwdx ZQe)ej/dydz ZRej/d{d| ZSej/d}d~ ZTe)ej7dd ZUe)ej7dd ZVe)ej7dd ZWe)dd ZXeXj-ejdd ZXe)dd ZYeYj-ejdd ZYdd ZZe)dd Z[e)dd Z\e)dd Z]e)dd Z^dddZ_dd Z`dd Zae)dd Zbebj-dd Zbdd ZcdddZddddZedd Zfdd Zgdd Zhdd Zidd ZjdddZkdddZldddZmdd Zndd Zodd Zpdd Zqdd Zrdd Zse)dd ZtejddÄ Zu fddńZv fddǄZwddɄ Zxd dd˄Zyddd̈́Zzddτ Z{dddфZ|e)e}j~ddӄ Ze)e}j~ddՄ Ze)e}j~ddׄ Ze)e}j~ddل Ze)e}j~ddۄ Ze)dd݄ Zej-dd݄ Zdd Zdd Zejdd ZdddZe)dd Ze)dd Ze)dd Zd 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), defined
  either in the constructor `__init__()` or in the `build()` method.

  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 state
    variables that do not depend on input shapes, using `add_weight()`.
  * `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()`. `__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 input tensors (which should be passed in as argument).
    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)
  )_obj_reference_counts_dictFc             C   s6   t | jddd}|d k	r"d|S | jjd | jj S )NkerasT)api_nameZadd_prefix_to_v1_namesztf.{}.)r2   	__class__format
__module____name__)selfcanonical_name rA   [/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py_get_cell_name$  s
    
zLayer._get_cell_namec             C   sB   d| _ d| _d| _t| dds>d| _ t| ddr8d| _nd| _d S )NFZ_disable_keras_instrumentationTZ_is_model_for_instrumentation)Z_instrumented_keras_apiZ_instrumented_keras_layer_classZ_instrumented_keras_model_classgetattr)r?   rA   rA   rB   _instrument_layer_creation+  s    z Layer._instrument_layer_creationTNc       	      K   s  |    ddddddddh}t|| || _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 | _ | !  || _"d|kr"d|kr"|d f|d< d|ks6d|krd|krNt#|d }n4d|krd|krl|d }nd }|ft#|d  }|| _$|dd | _%d| _&d	| _'d S )NZ	input_diminput_shapebatch_input_shape
batch_sizeweightsactivity_regularizerautocastimplementationF_trainable_weights_non_trainable_weights_self_tracked_trackablesT)(rE   r   Zvalidate_kwargs
_trainable	_statefulbuilt_input_spec_build_input_shape_saved_model_inputs_spec
is_defaultcompute_mask_supports_masking_init_set_namer   getpop_activity_regularizer_maybe_create_attributeZ_updates	threadinglocal_thread_local_callable_losses_losses_metricsLock_metrics_lock_set_dtype_policyr   Z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_layersZ#_preserve_input_structure_in_config)	r?   	trainablenamedtypedynamickwargsZallowed_kwargsrG   rH   rA   rA   rB   __init__6  sd    







zLayer.__init__c             C   s   t | jds|| _d| _dS )a  Creates the variables of the layer (optional, for subclass implementers).

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

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

    Args:
      input_shape: Instance of `TensorShape`, or list of instances of
        `TensorShape` if the layer expects a list of inputs
        (one instance per input).
    _is_defaultTN)hasattrbuildrT   rR   )r?   rF   rA   rA   rB   rx     s    zLayer.buildc             O   s   |S )a  This is where the layer's logic lives.

    Note here that `call()` method in `tf.keras` is little bit different
    from `keras` API. In `keras` API, you can pass support masking for
    layers as additional arguments. Whereas `tf.keras` has `compute_mask()`
    method to support masking.

    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.
    rA   )r?   inputsargsrt   rA   rA   rB   call  s    +z
Layer.callc             C   s>   t |tjr|}n
t|}|r.| j| n| j| |S )a  Adds a Trackable object to this layer's state.

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

    Returns:
      The TrackableWeightHandler used to track this object.
    )
isinstancer   TrackableWeightHandlerrM   appendrN   )r?   Ztrackable_objectrp   handlerrA   rA   rB   _add_trackable  s    
zLayer._add_trackablec                sf  |dkrd}| dd x|D ]}|dkrtd|qW | dd}| dd}| d	d}|dkrr| jppt }t|}| jjdkr| 	t
|jj t|}t|}t|}|	tjjkr|rtd
qd}n|dkrd}|dkrH|jrtd}nD|js|js|jr(td}n d|krHtd||j| jf | dtj}|r| jj| jjkr|jr|  fdd}|dk	rtd d}| j|||d|||||||	|
|d}|dk	r|jd|j d }| !||| t"|r8xd|D ]0}t#| |r$| j$%| n| j&%| qW n*t#| |rV| j$%| n| j&%| |S )ag  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 `ResourceVariable`.
      synchronization: Indicates when a distributed a variable will be
        aggregated. Accepted values are constants defined in the class
        `tf.VariableSynchronization`. By default the synchronization is set to
        `AUTO` and the current `DistributionStrategy` chooses
        when to synchronize. If `synchronization` is set to `ON_READ`,
        `trainable` must not be set to `True`.
      aggregation: Indicates how a distributed variable will be aggregated.
        Accepted values are constants defined in the class
        `tf.VariableAggregation`.
      **kwargs: Additional keyword arguments. Accepted values are `getter`,
        `collections`, `experimental_autocast` and `caching_device`.

    Returns:
      The 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`.
    NrA   Zpartitioner)collectionsexperimental_autocastcaching_devicegetterzUnknown keyword argument:r   r   Tr   zSynchronization value can be set to VariableSynchronization.ON_READ only for non-trainable variables. You have specified trainable=True and synchronization=VariableSynchronization.ON_READ.FZglorot_uniformZzerosr   zBAn initializer for variable %s of type %s is required for layer %sc                 s    | |}t |S )N)r   Zcreate_autocast_variable)rz   rt   variable)
old_getterrA   rB   r     s    
z Layer.add_weight.<locals>.getterzb`caching_device` does not work with mixed precision API. Ignoring user specified `caching_device`.)rq   shaper   	overwriteinitializerrr   
constraintrp   use_resourcer   synchronizationaggregationr   :)'r[   	TypeErrorrr   r   floatxr   as_dtype_dtype_policyvariable_dtyperf   r   Policy
base_dtyperq   r   rZ   r   r   tf_variablesVariableSynchronizationZON_READ
ValueErroris_floating
is_integerZis_unsignedZis_boolr   Zmake_variablecompute_dtyper,   warningZ _add_variable_with_custom_getterfind_handle_weight_regularizationis_split_variabletrack_variablerM   r~   rN   )r?   rq   r   rr   r   regularizerrp   r   r   r   r   rt   kwargZcollections_argrK   r   r   r   Zname_in_scopevrA   )r   rB   
add_weight  s    /











zLayer.add_weightc                s   t | jj}| j| jd}t| dr0| j|d< t	| j
|d< t| drn| jr\| j|d< nd|krn|d |   fdd|D }t|dkrt| jd	rtd
| jj |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.
    )rq   rp   rm   rG   rr   rs   c                s   g | ]}| kr|qS rA   rA   ).0arg)expected_argsrA   rB   
<listcomp>  s    z$Layer.get_config.<locals>.<listcomp>   rv   zNLayer %s has arguments in `__init__` and therefore must override `get_config`.)r!   getfullargspecru   rz   rq   rp   rw   rm   r   	serializer   rs   removekeyslen
get_configNotImplementedErrorr;   r>   )r?   all_argsconfig
extra_argsrA   )r   rB   r     s"    




zLayer.get_configc             C   s
   | f |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.
    rA   )clsr   rA   rA   rB   from_config  s    zLayer.from_configc                s   t  r | tt jd  r tj	|dd} fdd}t
||}y |dd}W n4 tk
r } ztd jj |W dd}~X Y nX W dQ R X t
d	d
 |S td jj dS )a  Computes the output shape of the layer.

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

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

    Returns:
        An input shape tuple.
    _scratch_graphF)	to_tuplesc                s   t j|  jd}d |_|S )N)r   rr   )r   placeholderrr   _keras_mask)r   ph)r?   rA   rB   _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 )N)r   )trA   rA   rB   <lambda>      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_buildr   	FuncGraphstrrq   
as_defaultr"   convert_shapesr1   map_structurer   r   r;   r>   )r?   rF   r   ry   outputserA   )r?   rB   compute_output_shape  s     
*zLayer.compute_output_shapec                s\   dd }t ||}| |}| j  dkrHdd t |D }|d  t  fdd|S )	a^  Compute the output tensor signature of the layer based on the inputs.

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

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

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

    Raises:
      TypeError: If input_signature contains a non-TensorSpec object.
    c             S   s    t | tjstd| | jS )NzKOnly TensorSpec signature types are supported, but saw signature entry: {}.)r|   r   
TensorSpecr   r<   r   )srA   rA   rB   check_type_return_shape7  s    z?Layer.compute_output_signature.<locals>.check_type_return_shapeNc             S   s   g | ]
}|j qS rA   )rr   )r   r   rA   rA   rB   r   @  s    z2Layer.compute_output_signature.<locals>.<listcomp>r   c                s   t j | dS )N)rr   r   )r   r   )r   )rr   rA   rB   r   E  r   z0Layer.compute_output_signature.<locals>.<lambda>)r1   r   r   _compute_dtypeflatten)r?   input_signaturer   rF   output_shapeZinput_dtypesrA   )rr   rB   compute_output_signature!  s    

zLayer.compute_output_signaturec             C   sB   | j r.tdd |}| |}ttj|S | ||||S d S )Nc             S   s   t j| j| jdS )N)r   rr   )r   r   r   rr   )xrA   rA   rB   r   Q  r   z3Layer._keras_tensor_symbolic_call.<locals>.<lambda>)rs   r1   r   r   r   KerasTensor_infer_output_signature)r?   ry   input_masksrz   rt   r   Zoutput_signaturerA   rA   rB   _keras_tensor_symbolic_callH  s    
z!Layer._keras_tensor_symbolic_callc             C   s4  | j }t| r,t| s,t| j t }t	t
| jd }|  ttj|}ttj|}ttj|}ttj|}t|  N t| j* | | | |}||f||}W dQ R X | || W dQ R X | j|||dd ttj|}W dQ R X t| dr.| js.| || ~|S )zTODO(kaftan): Docstring.r   NF)build_graph_set_inputs)r{   r   is_subclassedfrom_saved_model	autograph
tf_convertr   control_status_ctxr   r   r   rq   r   r1   r   r   Zkeras_tensor_to_placeholderr   
name_scope_name_scoper   enable_auto_cast_variables_compute_dtype_objectr   _maybe_cast_inputs_handle_activity_regularization_set_mask_metadataZkeras_tensor_from_tensorrw   ry   r   )r?   ry   rz   rt   r   call_fnZscratch_graphr   rA   rA   rB   r   X  s:    










zLayer._infer_output_signaturec             C   s@   | j s<tdd t|D r8td| j d t| dS |S )zComputes an output mask tensor.

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

    Returns:
        None or a tensor (or list of tensors,
            one per output tensor of the layer).
    c             s   s   | ]}|d k	V  qd S )NrA   )r   mrA   rA   rB   	<genexpr>  s    z%Layer.compute_mask.<locals>.<genexpr>zLayer z9 does not support masking, but was passed an input_mask: N)rX   anyr1   r   r   rq   r   )r?   ry   maskrA   rA   rB   rW     s    zLayer.compute_maskc             O   s  t | dstd| ||\}}}t|}t| ||||rN| ||||S t }t	dd |D r~t
t|}t|}| ||||\}}| jr|r||d< | |||\}}}|js|   t }	|j| ||	 |d t| j|| j |	r
| j}
| j}n|  }|  }
t| | js8| | | jrL|  ||}t!"| j# |
|f||}W dQ R X | j$r| %|| | j&r| '||||	  | j(dkr| )| |S Q R X W dQ R X dS )a2  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.
    r`   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 )N)r|   r*   ndarraynpfloatint)r   r   rA   rA   rB   r     s   z!Layer.__call__.<locals>.<genexpr>r   )layerry   r   r   N)*rw   RuntimeError_split_out_first_argr1   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	   r   enterr   assert_input_compatibilityrq   r{   _namer   _autographed_callr   Zname_scope_v2rR   r   rg   r   r   r   r   r\   r   rX   r   rU   _set_save_spec)r?   rz   rt   ry   
input_listr   r   mask_is_implicittraining_modeeagerr   r   r   rA   rA   rB   __call__  s`    





	



zLayer.__call__c          	   C   s  t  }tdd |D r8dd }t||}t|}d}| ||||\}}	| jrf|	rf||d< d}d }
d}| d||r| 	d||}
| j
s|d |
d kr|jd k	r|j}
n:t rt }
t|
rt|
tj}
qt|
}
n| j}
| j
r| d|
||\}}d}|j| |d|
d	t | ||||}|d krPtd
| j d |rn| jdd ||dd\}}|r~|d | |f| ||}|S Q R X d S )Nc             s   s$   | ]}t |tjtjttfV  qd S )N)r|   r*   r   r   r   r   )r   r   rA   rA   rB   r   #  s   z6Layer._functional_construction_call.<locals>.<genexpr>c             S   s$   t | tjtjttfr t| S | S )N)r|   r*   r   r   r   r   r   "convert_to_tensor_v2_with_dispatch)r   rA   rA   rB   _convert_non_tensor&  s    
z@Layer._functional_construction_call.<locals>._convert_non_tensorFr   Tr   )r   ry   r   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   r1   r   r   r   r   _call_arg_was_passed_get_call_arg_value_expects_training_argr[   r   r   global_learning_phase_is_setlearning_phaser   
is_tf_typer(   castr   bool_default_training_arg_set_call_arg_valuer   r   r   rq   _set_connectivity_metadata)r?   ry   rz   rt   r   r   r  Zmask_arg_passed_by_frameworkr   r   Ztraining_valueZ training_arg_passed_by_frameworkr   rA   rA   rB   r     s\    









z#Layer._functional_construction_callc             C   s   d }| j r| d||r&| d||}|d kr|j}|d k	rB|}nFt rt }t|tr^qt	
|rxt|tj}qt|}n| j}| d|||\}}nd|kr|d}n|j}|||fS )Nr   )r	  r  r  r   r   r
  r  r|   r  r   r  r(   r  r   r  r  r[   )r?   rz   rt   r   r  Zcall_ctx_trainingrA   rA   rB   r   r  s,    



zLayer._set_training_modec             C   s0   t | r&t | s&t| jt S | jS d S )N)r   r   r   r   r   r{   r   r   )r?   rA   rA   rB   r     s    

zLayer._autographed_callc             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?   rA   rA   rB   rr     s    zLayer.dtypec             C   s   | j S )z3Name of the layer (string), set in the constructor.)r   )r?   rA   rA   rB   rq     s    z
Layer.namec             C   s   | j S )zBWhether this layer supports computing a mask using `compute_mask`.)rX   )r?   rA   rA   rB   supports_masking  s    zLayer.supports_maskingc             C   s
   || _ d S )N)rX   )r?   valuerA   rA   rB   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 )N)rk   )r   r   rA   rA   rB   r     s    z Layer.dynamic.<locals>.<genexpr>)r   _flatten_layers)r?   rA   rA   rB   rs     s    zLayer.dynamicc             C   s   t dd |  D S )Nc             s   s   | ]}|j V  qd S )N)rQ   )r   r   rA   rA   rB   r     s    z!Layer.stateful.<locals>.<genexpr>)r   r  )r?   rA   rA   rB   stateful  s    zLayer.statefulc             C   s
   || _ d S )N)rQ   )r?   r  rA   rA   rB   r    s    c             C   s   | j S )N)rP   )r?   rA   rA   rB   rp     s    zLayer.trainablec             C   s   x|   D ]
}||_q
W d S )N)r  rP   )r?   r  r   rA   rA   rB   rp     s    c             C   s   | j S )z;Optional regularizer function for the output of this layer.)r\   )r?   rA   rA   rB   rJ     s    zLayer.activity_regularizerc             C   s
   || _ dS )z;Optional regularizer function for the output of this layer.N)r\   )r?   r   rA   rA   rB   rJ     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.
    )rS   )r?   rA   rA   rB   r     s    !zLayer.input_specc             C   s>   x2t |D ]$}|d k	rt|tstd|qW || _d S )Nz:Layer input_spec must be an instance of InputSpec. Got: {})r1   r   r|   	InputSpecr   r<   rS   )r?   r  r   rA   rA   rB   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)rp   _gather_children_attribute_dedup_weightsrM   )r?   children_weightsrA   rA   rB   trainable_weights  s    	
zLayer.trainable_weightsc             C   s@   | j r| d}| j| }n| d}| j| j | }| |S )zList 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_variablesr)   )rp   r  rN   rM   r  )r?   r  non_trainable_weightsrA   rA   rB   r     s    


zLayer.non_trainable_weightsc             C   s   | j | j S )z^Returns the list of all layer variables/weights.

    Returns:
      A list of variables.
    )r  r  )r?   rA   rA   rB   rI   5  s    zLayer.weightsc             C   s   t 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.)warningswarn)r?   rA   rA   rB   updates>  s    
zLayer.updatesc             C   sr   g }xh|   D ]\}|jr6|jd tjk	rB||j n||j x&|jD ]}| }|dk	rJ|| qJW qW |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   ZREVIVED_LOSS_PLACEHOLDERextendrb   ra   r~   )r?   Zcollected_lossesr   r   Zloss_tensorrA   rA   rB   lossesF  s    +zLayer.lossesc       
      K   sJ  | dd |r"td| f dd }t|}g }g }g }x|D ]}t|rf|t|| qF|dkrpqFt	
|st|tjstj|t d}t|st|tjrt s|| qFt	
|rF|| qFW | j| t j}|r|std| j| x4|D ],}	t| dd	r4| |	 n| j|	 qW 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: Additional keyword arguments for backward compatibility.
        Accepted values:
          inputs - Deprecated, will be automatically inferred.
    ry   NzUnknown keyword arguments: %sc          	   S   sV   t | r$td |  } W dQ R X | dkr0dS t| sLtj| t d} d| _	| S )z3Tags callable loss tensor as `_unconditional_loss`.N)rr   T)
callabler   r   r   r  r   r  r   r   Z_unconditional_loss)lossrA   rA   rB   _tag_callable  s    
z%Layer.add_loss.<locals>._tag_callable)rr   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[   r   r   r1   r   r$  r~   	functoolspartialr   r  r|   r   r   r   r  r   r   r"   Zis_symbolic_tensorr   Zis_in_tf_functionra   r"  r   r   r   r!  rD   Z_graph_network_add_lossrb   )
r?   r#  rt   r&  Zcallable_lossesZeager_lossesZsymbolic_lossesr%  in_call_contextZsymbolic_lossrA   rA   rB   add_loss  sD    =






zLayer.add_lossc             C   s4   t | ddsg | j_nx|  D ]}g |j_q W dS )z)Used every step in eager to reset losses.rO   N)rD   r`   r!  r  )r?   r   rA   rA   rB   r     s
    
zLayer._clear_lossesc          
   C   s8   g }x.|   D ]"}|j ||j W dQ R X qW |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.
    N)r  re   r"  rc   )r?   Zcollected_metricsr   rA   rA   rB   metrics  s
    zLayer.metricsc          	   K   sf  t | }t|dks0t|dkrB|d dkrBtdt| t|d}t|tj}t	
 j}|dkrx|sxtdn|r|jj}|s|stdt| |st| d	d
s8t|dd}| }	|r|jn|}| jN | |}
|
r|
}n4|r| j| n"tj|t|ddd}| j| W dQ R X |	rb|| n*|rFtd|rPdnd}| ||| dS )a  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: _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: r'  Frr   )rq   rr   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.Zmean)listr   r   r   r   rw   r|   r   r   r   r   r   r   r-  rq   rD   re   _get_existing_metricrc   r~   r5   ZMeanZ_graph_network_add_metric)r?   r  rq   rt   Zkwargs_keysZfrom_metric_objZis_symbolicr*  Z
metric_objZshould_update_statematchr   rA   rA   rB   
add_metric  sB    5




zLayer.add_metricc             C   sP   |dk	rt d t }|jr$dS |jsLx t|D ]}t|r6|  q6W 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.
      inputs: Deprecated, will be automatically inferred.
    Nz`add_update` `inputs` kwarg has been deprecated. You no longer need to pass a value to `inputs` as it is being automatically inferred.)	r,   r   r   r   Zin_keras_graphfrozenr1   r   r$  )r?   r   ry   r   updaterA   rA   rB   
add_update  s    zLayer.add_updatec             C   s2  | j }d}x,|D ]$}t|tjr,||j7 }q|d7 }qW |t|krjtd| jt||t|dd f d}g }x|D ]}t|tjr|j}||||  }|	| ||7 }qx|| }	t
|	dr|	jnd}
|j}||
std||
f |||	f |d7 }qxW t| x|  D ]}|  qW dS )	at  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   rA   zBLayer weight shape %s not compatible with provided weight shape %s)rI   r|   r   r}   num_tensorsr   r   rq   r   set_weightsrw   r   Zis_compatible_withr~   r   Zbatch_set_valuer  finalize_state)r?   rI   paramsZexpected_num_weightsparamZweight_indexZweight_value_tuplesr6  ZtensorsweightZweight_shapeZ	ref_shaper   rA   rA   rB   r7    s<    ,
"




zLayer.set_weightsc             C   sH   | j }g }x2|D ]*}t|tjr0||  q|| qW t|S )a9  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.
    )	rI   r|   r   r}   r"  Zget_tensorsr~   r   Zbatch_get_value)r?   rI   Zoutput_weightsr;  rA   rA   rB   get_weights  s    #
zLayer.get_weightsc             C   s   dS )zFinalizes 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.
    NrA   )r?   rA   rA   rB   r8  <  s    zLayer.finalize_statec             C   s   t d | jS )zDeprecated, do NOT use!

    Retrieves updates relevant to a specific set of inputs.

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

    Returns:
      List of update ops of the layer that depend on `inputs`.
    zy`layer.get_updates_for` is deprecated and will be removed in a future version. Please use `layer.updates` method instead.)r  r  r   )r?   ry   rA   rA   rB   get_updates_forF  s    
zLayer.get_updates_forc             C   s   t d | jS )zDeprecated, do NOT use!

    Retrieves losses relevant to a specific set of inputs.

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

    Returns:
      List of loss tensors of the layer that depend on `inputs`.
    zp`layer.get_losses_for` is deprecated and will be removed in a future version. Please use `layer.losses` instead.)r  r  r#  )r?   ry   rA   rA   rB   get_losses_forW  s    
zLayer.get_losses_forc             C   s2   |  |}t|tr"dd |D S t|ddS dS )av  Retrieves the input mask tensor(s) of a layer at a given node.

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

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

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

    Returns:
        A mask tensor
        (or list of tensors if the layer has multiple outputs).
    c             S   s   g | ]}t |d dqS )r   N)rD   )r   r   rA   rA   rB   r     s    z,Layer.get_output_mask_at.<locals>.<listcomp>r   N)get_output_atr|   r.  rD   )r?   r@  outputrA   rA   rB   get_output_mask_at|  s    

zLayer.get_output_mask_atc             C   s.   | j }t|trdd |D S t|ddS dS )aq  Retrieves the input mask tensor(s) of a layer.

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

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

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

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

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

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

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

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

    Raises:
      RuntimeError: If called in Eager mode.
    input_shapeszinput shape)_get_node_attribute_at_index)r?   r@  rA   rA   rB   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 shape)rI  )r?   r@  rA   rA   rB   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_tensorsrE  )rI  )r?   r@  rA   rA   rB   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_tensorsrC  )rI  )r?   r@  rA   rA   rB   rB    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.
    zLayer z& is not connected, no input to return.r   rM  rE  )_inbound_nodesAttributeErrorrq   rI  )r?   rA   rA   rB   rE  
  s    
zLayer.inputc             C   s&   | j std| j d | dddS )am  Retrieves the output tensor(s) of a layer.

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

    Returns:
      Output tensor or list of output tensors.

    Raises:
      AttributeError: if the layer is connected to more than one incoming
        layers.
      RuntimeError: if called in Eager mode.
    zLayer z has no inbound nodes.r   rN  rC  )rO  rP  rq   rI  )r?   rA   rA   rB   rC    s    zLayer.outputc             C   sT   | j stdtdd | j D }t|dkr:| 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.
    zDThe layer has never been called and thus has no defined input shape.c             S   s   g | ]}t |jqS rA   )r   rH  )r   r   rA   rA   rB   r   E  s    z%Layer.input_shape.<locals>.<listcomp>r   r   zThe layer "z has multiple inbound nodes, with different input shapes. Hence the notion of "input shape" is ill-defined for the layer. Use `get_input_shape_at(node_index)` instead.N)rO  rP  setr   rH  r   rq   )r?   Zall_input_shapesrA   rA   rB   rF   0  s    zLayer.input_shapec          	   C   s^   | j sRt| ddr6t|  | | j W dQ R X ntd| j d | j d t	| j
S )zCount the total number of scalars composing the weights.

    Returns:
        An integer count.

    Raises:
        ValueError: if the layer isn't yet built
          (in which case its weights aren't yet defined).
    r'  FNz$You tried to call `count_params` on z=, but the layer isn't built. You can build it manually via: `z.build(batch_input_shape)`.)rR   rD   r"   maybe_init_scoper   ry   r   rq   r   count_paramsrI   )r?   rA   rA   rB   rS  Q  s    
zLayer.count_paramsc             C   sL   | j stdtdd | j D }t|dkr:| j d jS td| j dS )a  Retrieves the output shape(s) of a layer.

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

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

    Raises:
        AttributeError: if the layer has no defined output shape.
        RuntimeError: if called in Eager mode.
    zEThe layer has never been called and thus has no defined output shape.c             S   s   g | ]}t |jqS rA   )r   rK  )r   r   rA   rA   rB   r   z  s    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)rO  rP  rQ  r   rK  rq   )r?   Zall_output_shapesrA   rA   rB   r   f  s    zLayer.output_shapec             C   s   | j S )zCDeprecated, do NOT use! Only for compatibility with external Keras.)rO  )r?   rA   rA   rB   inbound_nodes  s    zLayer.inbound_nodesc             C   s   | j S )zCDeprecated, do NOT use! Only for compatibility with external Keras.)_outbound_nodes)r?   rA   rA   rB   outbound_nodes  s    zLayer.outbound_nodesc             O   s   t d | j|f||S )a*  Deprecated, do NOT use!

    This is an alias of `self.__call__`.

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

    Returns:
      Output tensor(s).
    zp`layer.apply` is deprecated and will be removed in a future version. Please use `layer.__call__` method instead.)r  r  r  )r?   ry   rz   rt   rA   rA   rB   apply  s    
zLayer.applyc             O   s   t d | j||S )z/Deprecated, do NOT use! Alias for `add_weight`.zy`layer.add_variable` is deprecated and will be removed in a future version. Please use `layer.add_weight` method instead.)r  r  r   )r?   rz   rt   rA   rA   rB   add_variable  s    
zLayer.add_variablec             C   s   | j S )zReturns 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.
    )rI   )r?   rA   rA   rB   r)     s    zLayer.variablesc             C   s   | j S )N)r  )r?   rA   rA   rB   r    s    zLayer.trainable_variablesc             C   s   | j S )N)r  )r?   rA   rA   rB   r    s    zLayer.non_trainable_variablesc             C   s   | j S )N)rh   )r?   rA   rA   rB   rO    s    zLayer._inbound_nodesc             C   s
   || _ d S )N)rh   )r?   r  rA   rA   rB   rO    s    c             C   s   | j S )N)ri   )r?   rA   rA   rB   rU    s    zLayer._outbound_nodesc             C   s
   || _ d S )N)ri   )r?   r  rA   rA   rB   rU    s    c             C   s   t |tjr|| _n\t |tr,t|| _nDt |trL|dkrLt|| _n$|rftt|j	| _n
t
 | _| jj	dkrt st }td|jj| jj	f | jjrt| jj| _nd| _dS )zSets self._dtype_policy.)mixed_float16Zmixed_bfloat16rY  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   dictZdeserializer   r   r   rq   Zglobal_policyr   Zstrategy_supports_loss_scaling
ds_contextZget_strategyr   r;   r>   r   r   )r?   rr   ZstrategyrA   rA   rB   rf     s$    

zLayer._set_dtype_policyc             C   s   | j S )zrThe dtype policy associated with this layer.

    This is an instance of a `tf.keras.mixed_precision.Policy`.
    )r   )r?   rA   rA   rB   dtype_policy	  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?   rA   rA   rB   r   	  s    zLayer.compute_dtypec             C   s   | j jS )z$Deprecated alias of `compute_dtype`.)r   r   )r?   rA   rA   rB   r   #	  s    zLayer._compute_dtypec             C   s   | j S )z1Alias of `Layer.dtype`, the dtype of the weights.)rr   )r?   rA   rA   rB   r   (	  s    zLayer.variable_dtypec             C   sN   |st |}| j}| jo"|o"|j}|rFtt| j|rFt | 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)
r1   r   r   rg   r   r   map_should_cast_single_inputr   _cast_single_input)r?   ry   r   Zcompute_dtype_objectZshould_autocastrA   rA   rB   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   rr   r   )r?   r   rA   rA   rB   r^  I	  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   rA   rA   rB   r_  O	  s    
zLayer._cast_single_inputc             C   s   | j jS )N)r   r   )r?   rA   rA   rB   _dtypeY	  s    zLayer._dtypec             C   s    t |j}| t| d S )N)r   r   rq   rf   r   r   )r?   r  rA   rA   rB   ra  `	  s    c             C   s<   t  s| jS | j}t }|r,|d | }|r8|d7 }|S )N/)r   enabledrq   r   Zget_name_scope)r?   r   Zcurrent_name_scoperA   rA   rB   r   e	  s    zLayer._name_scopec             C   s4   |s t jt| jj|d| _nt | || _d S )N)
zero_based)r   Zunique_object_namer   r$   r;   r>   r   Zobserve_object_name)r?   rq   rd  rA   rA   rB   rY   s	  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 rA   )rq   )r   r   )rq   rA   rB   r   }	  s    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   )rc   r   r   r<   )r?   rq   r0  rA   )rq   rB   r/  |	  s    zLayer._get_existing_metricc                sP    fdd}t |r:x2|D ]}| t|| qW n| t|| dS )z3Create lambdas which compute regularization losses.c          	      s&   t  d  | }W dQ R X |S )z8Creates a regularization loss `Tensor` for variable `v`.z/RegularizerN)r   r   )r   Zregularization)rq   r   rA   rB   _loss_for_variable	  s    z?Layer._handle_weight_regularization.<locals>._loss_for_variableN)r   r   r+  r(  r)  )r?   rq   r   r   re  r   rA   )rq   r   rB   r   	  s
    

z#Layer._handle_weight_regularizationc          	   C   sl   | j rht|}tdH x@|D ]8}|  |}tt|d |j	}|| }| 
| q"W W d Q R X d S )NZActivityRegularizerr   )r\   r1   r   r   r   r(   r  r'   r   rr   r+  )r?   ry   r   Zoutput_listrC  Zactivity_lossrH   Zmean_activity_lossrA   rA   rB   r   	  s    


z%Layer._handle_activity_regularizationc          	   C   s   | j s
d S t|}t| ddp0tdd |D }|rH|rD| | d S | ||}|d kr`d S t|}x6t||D ](\}	}
y
|
|	_W qv t	k
r   Y qvX qvW |r| | d S )NZ _compute_output_and_mask_jointlyFc             s   s   | ]}t |d ddk	V  qdS )r   N)rD   )r   r   rA   rA   rB   r   	  s    z+Layer._set_mask_metadata.<locals>.<genexpr>)
rX   r1   r   rD   all_set_mask_keras_history_checkedrW   zipr   rP  )r?   ry   r   Zprevious_maskr   flat_outputsZmask_already_computedZoutput_masksZ
flat_maskstensorr   rA   rA   rB   r   	  s(    




zLayer._set_mask_metadatac             C   s*   x$|D ]}t |dd d k	rd|j_qW d S )Nr   T)rD   r   Z_keras_history_checked)r?   ri  rC  rA   rA   rB   rg  	  s    
z%Layer._set_mask_keras_history_checkedc             C   sz   | j s| jsd }d}n\| d||r8| d||}d}n:dd |D }tdd |D rbd }d}nt||}d}||fS )NFr   c             S   s   g | ]}t |d dqS )r   N)rD   )r   r   rA   rA   rB   r   	  s    z*Layer._get_input_masks.<locals>.<listcomp>c             s   s   | ]}|d kV  qd S )NrA   )r   r   rA   rA   rB   r   	  s    z)Layer._get_input_masks.<locals>.<genexpr>T)rX   r   r  r  rf  r1   pack_sequence_as)r?   ry   r   rz   rt   r   Zimplicit_maskrA   rA   rB   r   	  s    zLayer._get_input_masksc             C   s@   |s|sdS ||krdS | j }|s.|dd  }|tt||kS )NFTr   )_call_fn_argsrZ  rh  )r?   arg_namerz   rt   inputs_in_argscall_fn_argsrA   rA   rB   r  	  s    zLayer._call_arg_was_passedc             C   s<   ||kr|| S | j }|s&|dd  }tt||}|| S )Nr   )rl  rZ  rh  )r?   rm  rz   rt   rn  ro  Z	args_dictrA   rA   rB   r  	  s    zLayer._get_call_arg_valuec             C   st   | j |d }|d k	rJ|s"|d }t||krJt|}|||< t||fS |d krd|rd||d  n|||< ||fS )Nr   )_call_fn_arg_positionsrZ   r   r.  rl   r[   )r?   rm  	new_valuerz   rt   rn  r  Zarg_posrA   rA   rB   r  	  s    zLayer._set_call_arg_valuec       	   
   C   s   t |}t ||f}dd |D }g }xD|D ]<}t||krbt| j t|}W d Q R X || q0W t 	||}t
j| |||d |S )Nc             S   s   h | ]}t |qS rA   )id)r   irA   rA   rB   	<setcomp>
  s    z3Layer._set_connectivity_metadata.<locals>.<setcomp>)	call_argsZcall_kwargsr   )r1   r   rr  r   r   rq   r'   identityr~   rk  node_moduleNode)	r?   rz   rt   r   ri  Zflat_inputsZinput_ids_setZoutputs_copyr   rA   rA   rB   r  
  s    

z Layer._set_connectivity_metadatac             C   s   | j std| d t| j |ksRtd| d t| d tt| j  d t| j | |}t|trt|dkr|d S |S d	S )
a  Private utility to retrieves an attribute (e.g. inputs) from a node.

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

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

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

    Raises:
        RuntimeError: If the layer has no inbound nodes, or if called in Eager
        mode.
        ValueError: If the index provided does not match any node.
    z8The layer has never been called and thus has no defined r:   zAsked to get z	 at node z, but the layer has only z inbound nodes.r   r   N)rO  r   r   r   r   rD   r|   r.  )r?   r@  attr	attr_namevaluesrA   rA   rB   rI  
  s    ,z"Layer._get_node_attribute_at_indexc          	   C   s"  | j st| j|| j t|}|rj| jjd krjy|d jj	j}W n t
k
rX   Y nX | t| d }tdd |D rt|}n(ytj|dd}W n tk
r   Y nX t| jdst|  | | W d Q R X t| | | jd k	rt  | | j W d Q R X d | _d S )Nr   c             s   s   | ]}t |d V  qdS )r   N)rw   )r   r   rA   rA   rB   r   P
  s    z%Layer._maybe_build.<locals>.<genexpr>F)r   rv   )rR   r   r   rq   r1   r   r   r   rr   r   rP  rf   r   r   rf  r"   Z
get_shapesr   r   rw   rx   rR  r6   rn   r   Z
init_scoper7  )r?   ry   r   rr   rH  rA   rA   rB   r   A
  s2    

zLayer._maybe_buildc                s@   t dd |} |}tj|dd} fdd}t ||S )Nc             S   s   | j S )N)r   )r   rA   rA   rB   r   m
  r   z&Layer._symbolic_call.<locals>.<lambda>F)r   c                s   t j|  jd}d |_|S )N)r   rr   )r   r   rr   r   )r   r   )r?   rA   rB   r   s
  s    z4Layer._symbolic_call.<locals>._make_placeholder_like)r1   r   r   r"   r   )r?   ry   rH  rK  r   rA   )r?   rB   _symbolic_calll
  s
    
zLayer._symbolic_callc             C   s(   t  }x|  D ]}|j||< qW |S )z}Get the `trainable` state of each sublayer.

    Returns:
      A dict mapping all sublayers to their `trainable` value.
    )weakrefWeakKeyDictionaryr  rp   )r?   trainable_stater   rA   rA   rB   _get_trainable_statey
  s    zLayer._get_trainable_statec             C   s(   x"|   D ]}||kr
|| |_q
W dS )z(Set `trainable` state for each sublayer.N)r  rp   )r?   r  r   rA   rA   rB   _set_trainable_state
  s    zLayer._set_trainable_statec             C   s   |  dt  | jS )zEA dictionary counting the number of attributes referencing an object.r7   )r]   r    ZObjectIdentityDictionaryr7   )r?   rA   rA   rB   _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)rw   __setattr__)r?   rq   default_valuerA   rA   rB   r]   
  s    
zLayer._maybe_create_attributec                s  t | |d  | j} |kr0ttj| | d S |  }|dkrb|d | < ttj| | d S | = ttj| | t tst	 rttj| 
d fdd| jD  t tjrttj| 
d fdd| jD  ttj| 
d fdd| jD  d S )	Nr   rO   c                s   g | ]}| k	r|qS rA   rA   )r   l)existing_valuerA   rB   r   
  s    z%Layer.__delattr__.<locals>.<listcomp>rM   c                s   g | ]}| k	r|qS rA   rA   )r   w)r  rA   rB   r   
  s    rN   c                s   g | ]}| k	r|qS rA   rA   )r   r  )r  rA   rB   r   
  s    )rD   r  superr-   AutoTrackable__delattr__r|   r6   r   has_weightsr  rO   r   VariablerM   rN   )r?   rq   reference_countsZreference_count)r;   )r  rB   r  
  s0    

zLayer.__delattr__c                s  |dks t | ddr t| j|r`yttj| | W n" tk
rZ   td|Y nX d S t	j
| |d| j}|dd |< y| | W n tk
r   Y nX x4tD ]& t tjrt| dr| j  qW t | ddrPttjstrP| d	g  tfd
d| jD sP| j tdrPd_xtjddD ] t tjsvq`| dg  | dg   jrt fdd| j D rq`| j   n*t fdd| j!D rq`| j!  t"#  q`W ttj| | d S )NZ_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  rq   r   r   rc   ro   rO   c             3   s   | ]}| kV  qd S )NrA   )r   r   )r  rA   rB   r   
  s    z$Layer.__setattr__.<locals>.<genexpr>_use_resource_variables)Zexpand_compositesrM   rN   c             3   s   | ]} |kV  qd S )NrA   )r   r  )valrA   rB   r   	  s    c             3   s   | ]} |kV  qd S )NrA   )r   r  )r  rA   rB   r     s    )$rD   rw   r;   r  r-   r  r  rP  r<   r/   Zsticky_attribute_assignmentr  rZ   r  r1   r   r|   r5   Metricrc   r~   r&   Moduler   r  r]   r   rO   r  r   r  rp   rM   rN   r   r   )r?   rq   r  r  )r;   )r  r  rB   r  
  sV    zLayer.__setattr__c                sF    dkst t| drB| jddd}ttj fdd|D S g S )N>   r  r  r)   rO   F)include_self	recursivec             3   s   | ]}t | V  qd S )N)rD   )r   r   )	attributerA   rB   r     s    z3Layer._gather_children_attribute.<locals>.<genexpr>)AssertionErrorrw   _flatten_modulesr.  	itertoolschainfrom_iterable)r?   r  Znested_layersrA   )r  rB   r    s    
z Layer._gather_children_attributec             c   s,   x&| j ||dD ]}t|tr|V  qW d S )N)r  r  )r  r|   r6   )r?   r  r  r   rA   rA   rB   r  "  s    
zLayer._flatten_layersc       
      c   s   |r
| V  t | dd}|rt }t|}x|r| }t|}||krJq,|| t|tj	rt|t
js|V  |rt |dd}|r|t| q,t|tjr,|j}	|	r,|t|	 q,W 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`.
    rO   N)rD   rQ  r   dequepopleftrr  addr|   r&   r  r5   r  
extendleftreversedr/   ZTrackableDataStructureZ_values)
r?   r  r  Z
trackablesZseen_object_idsr  Ztrackable_objZtrackable_idZsubtrackablesZtracked_valuesrA   rA   rB   r  (  s0    


zLayer._flatten_modulesc             C   s   dS )NTrA   )r?   rA   rA   rB   	_is_layerT  s    zLayer._is_layerc             C   s   | j jjj| d  | j jjj| d  | j jjj| d  | j}|| jjpNg 7 }|d krld|kpf| j| _n|| _| j	
 }|| jjpi  |d| _d|kp| j| _d S )Nr   r   )r;   _call_full_argspecfgetcacher[   rl  _call_accepts_kwargs
kwonlyargsr	  _call_fn_arg_defaultscopyr3  kwonlydefaultsrZ   r  r   )r?   Zexpects_training_argro  Zcall_fn_arg_defaultsrA   rA   rB   rj   W  s    

zLayer._init_call_fn_argsc             C   s   t | jS )N)r!   r   r{   )r?   rA   rA   rB   r  n  s    zLayer._call_full_argspecc             C   s(   | j j}|r$|d dkr$|dd  S |S )Nr   r?   r   )r  rz   )r?   r   rA   rA   rB   rl  u  s    zLayer._call_fn_argsc             C   sH   | j }| jjpg }t }x*tdt| dD ]}|| ||| < q,W |S )Nr   )rl  r  defaultsrZ  ranger   )r?   ro  Zcall_fn_defaultsr  rs  rA   rA   rB   r  ~  s    zLayer._call_fn_arg_defaultsc             C   s*   t  }xt| jD ]\}}|||< qW |S )N)rZ  	enumeraterl  )r?   Zcall_fn_arg_positionsposr   rA   rA   rB   rp    s    zLayer._call_fn_arg_positionsc             C   s   | j jd k	S )N)r  varkw)r?   rA   rA   rB   r    s    zLayer._call_accepts_kwargsc             C   s   t | jdsg | j_| jjS )Nr!  )rw   r`   r!  )r?   rA   rA   rB   r!    s    zLayer._eager_lossesc             C   s   || j _d S )N)r`   r!  )r?   r#  rA   rA   rB   r!    s    c             C   sB   g t   }}x0|D ](}t||kr|| |t| qW |S )z;Dedupe weights while maintaining order as much as possible.)rQ  rr  r~   r  )r?   rI   rC  Zseen_idsr  rA   rA   rB   r    s    

zLayer._dedup_weightsc             C   sV   |r|d }|dd  }n2| j d |krDt|}|| j d }ntd|||fS )Nr   r   z9The first argument to `Layer.call` must always be passed.)rl  r  r[   r   )r?   rz   rt   ry   rA   rA   rB   r     s    
zLayer._split_out_first_argc             C   s"   | j d k	rd S ttj|| _ d S )N)rU   r1   r   r"   get_tensor_spec)r?   ry   rA   rA   rB   r     s    
zLayer._set_save_specc                s$   | j d krd S t fdd| j S )Nc                s   t j|  dS )N)dynamic_batch)r"   r  )r   )r  rA   rB   r     r   z&Layer._get_save_spec.<locals>.<lambda>)rU   r1   r   )r?   r  rA   )r  rB   _get_save_spec  s
    

zLayer._get_save_specc             C   s
   t | S )N)r   ZLayerSavedModelSaver)r?   rA   rA   rB   _trackable_saved_model_saver  s    z"Layer._trackable_saved_model_saverc             C   s   | j jS )N)r  Zobject_identifier)r?   rA   rA   rB   _object_identifier  s    zLayer._object_identifierc             C   s   | j jS )z6Info about this layer to be saved into the SavedModel.)r  Ztracking_metadata)r?   rA   rA   rB   _tracking_metadata  s    zLayer._tracking_metadata
checkpointc                s<   |dkr|d }| j |}ni }|t j|f| |S )NZ
savedmodelr  )r  Ztrackable_childrenr3  r  _trackable_children)r?   	save_typert   r  children)r;   rA   rB   r    s    zLayer._trackable_childrenc             C   s   t t| ddd k	S )Nr8   )r9   )r2   type)r?   rA   rA   rB   !_use_input_spec_as_call_signature  s    z'Layer._use_input_spec_as_call_signaturec             C   s&   | j  }|dd  |dd  |S )Nr`   re   )__dict__r  r[   )r?   staterA   rA   rB   __getstate__  s    
zLayer.__getstate__c             C   s*   t  |d< t  |d< t| d| d S )Nr`   re   r  )r^   r_   rd   objectr  )r?   r  rA   rA   rB   __setstate__   s    zLayer.__setstate__)TNNF)N)N)N)N)T)N)F)F)FF)TT)TT)N)T)r  )r>   r=   __qualname____doc__	frozensetr  r  r&   r  Z_TF_MODULE_IGNORED_PROPERTIES_must_restore_from_configrC   rE   r   no_automatic_dependency_trackingru   r   defaultrx   r4   Zfor_subclass_implementersr{   r   r   r   ZAUTOZVariableAggregationNONEr   r   classmethodr   r   r   r   r   rW   r  r   r   r   propertyrr   rq   r  setterrs   Zdo_not_doc_inheritabler  rp   rJ   r   r  r  rI   Zdo_not_generate_docsr   r#  r+  r   r,  r1  r4  r7  r<  r8  r=  r>  rA  rD  rF  rG  rJ  rL  r?  rB  rE  rC  rF   rS  r   rT  rV  rW  rX  r)   r  r  rO  rU  rf   r\  r   r   r   r   r^  r_  ra  r   rY   r/  r   r   r   rg  r   r  r  r  r  rI  r   r|  r  r  r  r]   r  r  r  r  r  r  rj   r   Zcached_per_instancer  rl  r  rp  r  r!  r  r   r   r  r  r  r  r  r  r  r  __classcell__rA   rA   )r;   rB   r6   a   sP   -	
    - --'6{S+
#	>x

y$U,
 	%


	

 


$+,I,	
r6   c                   sZ   e Zd ZdZe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	 | _
n"t|tsN|d}tj	|| _
|d k	rvdd | D ni | _d| _d| _d S )NF)rq   rp   rr   rK   zutf-8c             S   s   i | ]\}}|t |qS rA   )r   )r   indexconstantrA   rA   rB   
<dictcomp>9  s   z.TensorFlowOpLayer.__init__.<locals>.<dictcomp>T)r  r  ru   _TF_OP_LAYER_NAME_PREFIXr|   rZ  r   Z	ParseDictr   NodeDefnode_defbytesencodeZ
FromStringitems	constantsrR   r  )r?   r  rq   r  rp   rr   )r;   rA   rB   ru   &  s    	




 zTensorFlowOpLayer.__init__c             C   s   t  r| |S | |S )N)r	   r   _defun_call_make_op)r?   ry   rA   rA   rB   r{   C  s    
zTensorFlowOpLayer.callc             C   s2   t  }|| j d|jd _||j|_|S )NTZ_cloned)r   r  ZCopyFromr  ry  bZunique_namerq   )r?   graphr  rA   rA   rB   _make_node_defH  s
    z TensorFlowOpLayer._make_node_defc          	   C   s(  t |}|d j}| |}|  xH| j D ]:\}}t|}|d k	rbt	j
||j| d}||| q4W tj|||g d}||}|  t|jj}	dd |jjD }
g }x&|
D ]}|| ||| qW t|}t|	|j||j t|jdkr|jd S |jS Q R X d S )Nr   )rq   )Zcontrol_inputsc             S   s   g | ]}t |jqS rA   )r0   as_strrq   )r   ry  rA   rA   rB   r   e  s    z.TensorFlowOpLayer._make_op.<locals>.<listcomp>r   )r1   r   r  r  r   r  r  r   Zconstant_valuer   r  rE  insertr   Z_create_c_opZ_create_op_from_tf_operationZ_control_flow_post_processingr0   r  Zop_defrq   ry  r~   Zget_attrrl   r   Zrecord_gradientry   r   r   )r?   ry   r  r  r  r  r  Zc_opopZop_typeZ
attr_namesattrsrz  rA   rA   rB   r  Q  s.    








zTensorFlowOpLayer._make_opc             C   s
   |  |S )zDWraps the op creation method in an Eager function for `run_eagerly`.)r  )r?   ry   rA   rA   rB   r  q  s    zTensorFlowOpLayer._defun_callc                sL   t t|  }||d ttd  t| jdd | j	
 D d |S )Nrq   c             S   s   i | ]\}}t ||qS rA   )r   	get_value)r   rs  crA   rA   rB   r  |  s   z0TensorFlowOpLayer.get_config.<locals>.<dictcomp>)rq   r  r  )r  r  r   r3  r   r  r   ZMessageToDictr  r  r  )r?   r   )r;   rA   rB   r   v  s    
zTensorFlowOpLayer.get_config)NTN)r>   r=   r  r  r  r  ru   r{   r  r  r
   functionr  r   r  rA   rA   )r;   rB   r    s     	 r  c                   s4   e Zd ZdZ fddZdd Z fddZ  ZS )AddLossz|Adds 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 | || _d S )NFrK   )r  r  ru   unconditional)r?   r  rt   )r;   rA   rB   ru     s    zAddLoss.__init__c             C   s   | j || j d |S )N)ry   )r+  r  )r?   ry   rA   rA   rB   r{     s    zAddLoss.callc                s"   t t|  }|d| ji |S )Nr  )r  r  r   r3  r  )r?   r   )r;   rA   rB   r     s    zAddLoss.get_config)r>   r=   r  r  ru   r{   r   r  rA   rA   )r;   rB   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 | || _|| _d S )N)r  r  ru   r   metric_name)r?   r   r  rt   )r;   rA   rB   ru     s    zAddMetric.__init__c             C   s   | j || j| jd |S )N)r   rq   )r1  r   r  )r?   ry   rA   rA   rB   r{     s    zAddMetric.callc                s&   t t|  }|| j| jd |S )N)r   r  )r  r  r   r3  r   r  )r?   r   )r;   rA   rB   r     s
    zAddMetric.get_config)NN)r>   r=   r  r  ru   r{   r   r  rA   rA   )r;   rB   r    s   r  c             C   s   t dd t|||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 )N)r|   r   r   )r   rj  rA   rA   rB   r     s   z3_in_functional_construction_mode.<locals>.<genexpr>)r   r1   r   )r   ry   rz   rt   r   rA   rA   rB   r     s    r   c             C   s$   t | tjtjttfr t| S | S )N)r|   r*   r   r   r   r   r   r  )r   rA   rA   rB   r     s    
r   )kr  r   r  r(  r  r^   r  r}  numpyr   Zgoogle.protobufr   Ztensorflow.core.frameworkr   Ztensorflow.pythonr   Z tensorflow.python.autograph.corer   Z tensorflow.python.autograph.implr   r   Ztensorflow.python.distributer   r[  Ztensorflow.python.eagerr   r	   r
   Ztensorflow.python.frameworkr   r   r   r   r   r   r   Ztensorflow.python.kerasr   r   r   r   Ztensorflow.python.keras.enginer   r   r   r   rw  Z'tensorflow.python.keras.mixed_precisionr   r   r   Z*tensorflow.python.keras.saving.saved_modelr   Ztensorflow.python.keras.utilsr   r   r    r!   r"   r#   Z+tensorflow.python.keras.utils.generic_utilsr$   Z&tensorflow.python.keras.utils.tf_utilsr%   Ztensorflow.python.moduler&   Ztensorflow.python.opsr'   r(   r)   r   Ztensorflow.python.ops.numpy_opsr*   Ztensorflow.python.ops.raggedr+   Ztensorflow.python.platformr,   Ztensorflow.python.trackabler-   r.   r  r/   Ztensorflow.python.utilr0   r1   Z tensorflow.python.util.tf_exportr2   r3   Ztensorflow.tools.docsr4   
LazyLoaderglobalsr5   r  ZTensorZSparseTensorZRaggedTensorr`  r  ZLayerVersionSelectorr6   r  r  r  r   r   r  rA   rA   rA   rB   <module>   s                          <|	