
    BVh~\                     0   d 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 ej:                  Zdaej>                  d        Z d Z!d Z" G d dejF                        Z#d Z$y)z=Contains the base Layer class, from which all layers inherit.    N)context)dtypes)ops)backend)
base_layer)base_layer_utils)variable_scope_shim)policy)tf_contextlib)variable_scope)	variables)base)nestFc               #   8   K   t         } da 	 d | a y# | a w xY ww)a  Use Keras-style variable management.

  All tf.layers and tf RNN cells created in this scope use Keras-style
  variable management.  Creating such layers with a scope= argument is
  disallowed, and reuse=True is disallowed.

  The purpose of this scope is to allow users of existing layers to
  slowly transition to a Keras layers API without breaking existing
  functionality.

  One example of this is when using TensorFlow's RNN classes with Keras
  Models or Networks.  Because Keras models do not properly set variable
  scopes, users of RNNs may either accidentally share scopes between two
  different models, or get errors about variables that already exist.

  Example:

  ```python
  class RNNModel(tf.keras.Model):

    def __init__(self, name):
      super(RNNModel, self).__init__(name=name)
      self.rnn = tf.compat.v1.nn.rnn_cell.MultiRNNCell(
        [tf.compat.v1.nn.rnn_cell.LSTMCell(64) for _ in range(2)])

    def call(self, input, state):
      return self.rnn(input, state)

  model_1 = RNNModel("model_1")
  model_2 = RNNModel("model_2")

  # OK
  output_1, next_state_1 = model_1(input, state)
  # Raises an error about trying to create an already existing variable.
  output_2, next_state_2 = model_2(input, state)
  ```

  The solution is to wrap the model construction and execution in a keras-style
  scope:

  ```python
  with keras_style_scope():
    model_1 = RNNModel("model_1")
    model_2 = RNNModel("model_2")

    # model_1 and model_2 are guaranteed to create their own variables.
    output_1, next_state_1 = model_1(input, state)
    output_2, next_state_2 = model_2(input, state)

    assert len(model_1.weights) > 0
    assert len(model_2.weights) > 0
    assert(model_1.weights != model_2.weights)
  ```

  Yields:
    A keras layer style scope.
  TN_KERAS_STYLE_SCOPE)stacks    ]/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/legacy_tf_layers/base.pykeras_style_scoper   )   s(     x %	s   	 c                      da y)a  Use Keras-style variable management.

  All tf.layers and tf RNN cells created after keras style ha been enabled
  use Keras-style variable management.  Creating such layers with a
  scope= argument is disallowed, and reuse=True is disallowed.

  The purpose of this function is to allow users of existing layers to
  slowly transition to Keras layers API without breaking existing
  functionality.

  For more details, see the documentation for `keras_style_scope`.

  Note, once keras style has been set, it is set globally for the entire
  program and cannot be unset.

  Example:

  ```python
  set_keras_style()

  model_1 = RNNModel(name="model_1")
  model_2 = RNNModel(name="model_2")

  # model_1 and model_2 are guaranteed to create their own variables.
  output_1, next_state_1 = model_1(input, state)
  output_2, next_state_2 = model_2(input, state)

  assert len(model_1.weights) > 0
  assert len(model_2.weights) > 0
  assert(model_1.weights != model_2.weights)
  ```
  TNr        r   set_keras_styler   m   s    D r   c                      t         S Nr   r   r   r   _is_in_keras_style_scoper      s    	r   c            	           e Zd ZdZd fd	Zed        Zd Z	 	 ddZed        Z	d fd	Z
 fd	Zdd
Zddddddej                  j                  ej                   j"                  df	 fd	Z fdZd Z fdZed        Z xZS )Layera"  Base layer class.

  It is considered legacy, and we recommend the use of `tf.keras.layers.Layer`
  instead.

  Args:
    trainable: Boolean, whether the layer's variables should be trainable.
    name: String name of the layer.
    dtype: Default dtype of the layer's weights (default of `None` means use the
      type of the first input).

  Read-only properties:
    name: The name of the layer (string).
    dtype: Default dtype of the layer's weights (default of `None` means use the
      type of the first input).
    trainable_variables: List of trainable variables.
    non_trainable_variables: List of non-trainable variables.
    variables: List of all variables of this layer, trainable and
      non-trainable.
    updates: List of update ops of this layer.
    losses: List of losses added by this layer.
    trainable_weights: List of variables to be included in backprop.
    non_trainable_weights: List of variables that should not be
      included in backprop.
    weights: The concatenation of the lists trainable_weights and
      non_trainable_weights (in this order).

  Mutable properties:
    trainable: Whether the layer should be trained (boolean).
    input_spec: Optional (list of) `InputSpec` object(s) specifying the
      constraints on inputs that can be accepted by the layer.
  Nc                    d| _         |j                  dd       }|j                  dd       | _        g | _        d| _        |t        j                  d      }d|vrd|d<   d| _        t        t        | *  d|||d| t               rT|t        dj                  |            | j                  $t        d	j                  | j                              d| _        nd| _        d
| j                  v | _        |r-t#        j$                  |      5 }|| _        d d d        d | _        y d | _        d | _        y # 1 sw Y   d | _        y xY w)NF_scope_reuse_inferautocastT)	trainablenamedtypeKscope argument not allowed when keras style layers are enabled, but saw: {}zKreuse argument not allowed when keras style layers are enabled, but saw: {}scoper   )_use_resource_variablespopr!   _trainable_weightsbuiltr
   Policy_disable_keras_instrumentationsuperr   __init__r   
ValueErrorformat_keras_style_call_fn_args_call_has_scope_argvsr   r    _current_scope)selfr$   r%   r&   kwargsr(   captured_scope	__class__s          r   r0   zLayer.__init__   s\    $)D JJx&E**Xt,DK !DDJ} mmH%e fZ +/D'	% *)$e *"(*  !		 &-) 	) 
	  &-/ 	/ dd&$*<*<<DU# %~$% D dkD	% Ds   D44Ec                 l    t        j                  d       t        j                         rt	        d      y )Nz`Layer.graph` is deprecated and will be removed in a future version. Please stop using this property because tf.layers layers no longer track their graph.z1Layer.graph not supported when executing eagerly.)warningswarnr   executing_eagerlyRuntimeErrorr8   s    r   graphzLayer.graph   s0    MM . /   "LMMr   c                     t        |t        j                        r%|j                  }| j	                         \  | _        }n	|}|| _        |s| j	                         \  | _        }|| _        y r   )
isinstancer6   VariableScoper%   _make_unique_name_name
_base_name)r8   r%   	base_name_s       r   _init_set_namezLayer._init_set_name   sZ    $(()))i,,.mdj!idj"446dj)DOr   c                     t        j                  | j                  j                        }t	        j
                  |||||      }||fS )N)name_uid_mapavoid_names	namespace
zero_based)r   to_snake_caser;   __name__r   unique_object_name)r8   rM   rN   rO   rP   rI   r%   s          r   rF   zLayer._make_unique_name  sH    (()@)@AI%%!D )r   c                     | j                   s$t        d| j                  z   dz   dz   dz   dz         | j                   j                  S )Nz5No name available for layer scope because the layer "z(" has not been used yet. The scope name z4 is determined the first time the layer instance is z1called. You must therefore call the layer before zquerying `scope_name`.)r    r1   rG   r%   rA   s    r   
scope_namezLayer.scope_name  s_    ;;Nzz"$NOMN KK 0	0 1 1
 ;;r   c                 v   t        | j                        }t        | j                        }t        t        |   ||       t        j                         se| j                  |d  }| j                  |d  }|D ]  } |       }||j                  |        t        |t        j                  j                         y y )N)inputs)len_losses_callable_lossesr/   r   add_lossr   r?   append_add_elements_to_collectionr   	GraphKeysREGULARIZATION_LOSSES)
r8   lossesrW   previous_losses_lengthprevious_callable_losses_length
new_lossesnew_callable_lossesregularizerloss_tensorr;   s
            r   r[   zLayer.add_loss  s     .&)$*?*?&@#	%v6$$&<< 6 78j 11
)
*,, )+!m"


K
() "

--
-
-/ 'r   c                 l    | j                   rt        t        |          S | j                  j
                  S )z#Determines op naming for the Layer.)r3   r/   r   _name_scoper7   original_name_scope)r8   r;   s    r   rh   zLayer._name_scope'  s.    5$+--222r   c                 0   | j                   r| j                  r4t        j                  ||n| j                        5 }|| _         d d d        y t        j                  || j                        5 }|| _         d d d        y y # 1 sw Y   y xY w# 1 sw Y   y xY w)N)default_name)r    r!   r6   r   rH   )r8   r(   r:   s      r   
_set_scopezLayer._set_scope-  s    {{	&EDOO= 	'@N&$+	' 	' 1 	'4B&$+	' 	' 	' 	'	' 	's   B .B B	Bc                 p   |D ]  }|dk7  s	t        d|       | j                  r]t        t        |   d||||||xr | j
                  ||t        j                  j                  t        j                  j                  |d|S |	t        j                  j                  k(  r|rt        d      d}n|d}d }d}t        j                         st        j                          }|j"                  rct        j$                         5  t        j                         s1t        j                          }t'        t)        j*                               }ddd       n|}t'        t)        j*                               }|| j,                  xs t.        j0                  }| j3                  d       | j4                  xs | j6                  }t9        | j:                        }t        j<                  | j>                  |d	      5 }|| _         tC        jD                  | jG                               5  |xs | jH                  xs |jJ                  }||jL                  }t        t        |   ||ft/        jN                  |      ||xr | j
                  ||||	|
t        jP                  d
	|}|rbt        jR                         s	 ||      rE| jU                  |||       t        jV                         }tY        |d      r|j[                  ||       |w|j]                         5  t)        j^                         }ddd       |rH| j
                  r<|vr8| j:                  |d }| j:                  d| | _        | xj`                  |z  c_0        ddd       ddd       S # 1 sw Y   !xY w# 1 sw Y   rxY w# 1 sw Y   ,xY w# 1 sw Y   S xY w)a	  Adds a new variable to the layer, or gets an existing one; returns it.

    Args:
      name: variable name.
      shape: variable shape.
      dtype: The type of the variable. Defaults to `self.dtype` or `float32`.
      initializer: initializer instance (callable).
      regularizer: regularizer instance (callable).
      trainable: whether the variable should be part of the layer's
        "trainable_variables" (e.g. variables, biases)
        or "non_trainable_variables" (e.g. BatchNorm mean, stddev).
        Note, if the current variable scope is marked as non-trainable
        then this parameter is ignored and any added variables are also
        marked as non-trainable. `trainable` defaults to `True` unless
        `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`.
      partitioner: (optional) partitioner instance (callable).  If
        provided, when the requested variable is created it will be split
        into multiple partitions according to `partitioner`.  In this case,
        an instance of `PartitionedVariable` is returned.  Available
        partitioners include `tf.compat.v1.fixed_size_partitioner` and
        `tf.compat.v1.variable_axis_size_partitioner`.  For more details, see
        the documentation of `tf.compat.v1.get_variable` and the  "Variable
        Partitioners and Sharding" section of the API guide.
      **kwargs: Additional keyword arguments.

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

    Raises:
      RuntimeError: If called with partitioned variable regularization and
        eager execution is enabled.
      ValueError: When trainable has been set to True with synchronization
        set as `ON_READ`.
    experimental_autocastzUnknown keyword argument:)r%   shaper&   initializerre   r$   
constraintuse_resourcesynchronizationaggregationpartitionerzSynchronization value can be set to VariableSynchronization.ON_READ only for non-trainable variables. You have specified trainable=True and synchronization=VariableSynchronization.ON_READ.FNTc                 P    t        j                  |       r| D ]  }||v s y y| |vS )NFT)r   is_split_variable)variableexisting_variable_setvars      r   _should_add_regularizerz1Layer.add_weight.<locals>._should_add_regularizer  s<    		+	+H	5 	C))	 444r   reuseauxiliary_name_scope)	r&   rp   r$   rq   ru   rr   rs   rt   getteradd_regularizerr   )1	TypeErrorr3   r/   r   
add_weightr$   r6   VariableSynchronizationAUTOVariableAggregationNONEON_READr1   r   r?   r   get_default_graphbuilding_function
init_scopesettf_variablesglobal_variablesr&   r   float32rl   r,   r!   rX   r+   r   r    r7   r   
name_scoperh   r)   rr   rp   as_dtypeget_variable#executing_eagerly_outside_functions_handle_weight_regularization_get_default_variable_storehasattrr   
as_defaulttrainable_variables_non_trainable_weights)r8   r%   ro   r&   rp   re   r$   rq   rr   rs   rt   ru   r9   kwargr{   
init_graphdefault_graphexisting_variablesr}   prev_len_trainabler(   rx   	var_storer   extra_trainable_varsr;   s                            r   r   zLayer.add_weight9  s   x  <	)	)3U;;< 5$* !!0$..#4499,,11!   "44<<<	?@ 	@ 			i5 J$$&++-m		(	(^^ 	F
 **,..0J!$\%B%B%D!E	F 	F #
 !>!>!@A}jj*FNNeOODJJ%$++ET445			5u
> /@AF!dd..01 ,@$ +44+** 	 ))+0 //%(#2DNN!#%+#??  557(3EF..tX{K668I y"34''+>!
 $$& E"."B"B"DEDNN11#'#:#:;M;N#O &*&=&=##'%D#''+??'Y,@/@` OG	F 	FtE EI,@ ,@/@` OsK   AN1+N+C1NN"AN4N+NNNN(	$N++N5c                    |j                  dd      }| j                  r3|t        dj                  |            t	        t
        |   |g|i |S | j                  |       | j                  rM	 | j                  }|jt        j                  | j                  dd      }t        j                         s4|| _	        n,t        j                  | j                  | j                   d      }|5 }|| _        	 | j$                  }|r||d<   t	        t
        |   |g|i |}ddd       t/        j0                         s.t3        | j4                  t        j6                  j8                         S # t        $ r d}Y w xY w# t        $ rF t'        j(                  | j*                        | _        d| j,                  v | _        | j$                  }Y w xY w# 1 sw Y   xY w)a  Wraps `call`, applying pre- and post-processing steps.

    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`.
        **Note**: kwarg `scope` is reserved for use by the layer.

    Returns:
      Output tensor(s).

    Note:
      - If the layer's `call` method takes a `scope` keyword argument,
        this argument will be automatically set to the current variable scope.
      - If the layer's `call` method takes a `mask` argument (as some Keras
        layers do), its default value will be set to the mask generated
        for `inputs` by the previous layer (if `input` did come from
        a layer that generated a corresponding mask, i.e. if it came from
        a Keras layer with masking support.

    Raises:
      ValueError: if the layer's `call` method returns None (an invalid value).
    r(   Nr'   TFr|   )r*   r3   r1   r2   r/   r   __call__rl   r,   _always_reuse_variable_scopeAttributeErrorr6   r   r    r   r   r!   r7   r5   r	   fn_argscallr4   r   r?   r]   updatesr^   
UPDATE_OPS)	r8   rW   argsr9   r(   scope_context_managercall_has_scope_argoutputsr;   s	           r   r   zLayer.__call__  s   0 JJw%E		 &-) 	) 5$(A$A&AAOOEzz% !% A A 
	& !# 1 1KKt%!A 668.C$
+ //
++T[[uF 
 E%!d6!55
 
w eT+FDTDVDgE $$&!$,,0H0HINK  % $%0  6088C#*d.@.@#@ !556E EsC   1E* +G4E; G*E87E8;AG
G	G

GGc           	         t        g d      }t        ddg      }| j                  }|j                  |      }||t        |       <   | j                  j                         D ]  \  }}||v rt        |||       ||v r!t        ||t        j                  |             =t        j                  |      rt        |||       `t        ||t        j                  ||              |S )N)_graph_thread_local_metrics_lockr    r   )r   r;   __new__id__dict__itemssetattrcopyr   is_tensor_or_tensor_listdeepcopy)r8   memono_copyshallow_copyclsresultkvs           r   __deepcopy__zLayer.__deepcopy__5  s    >?G"@ABL
..C[[FDDN##% 31	
g1499Q<(..q114==D123 Mr   c                 B    t         t        j                  |   ||       y r   )r/   	trackable	Trackable__setattr__)r8   valuer%   r;   s      r   r   zLayer.__setattr__F  s    	)

t0=r   c                      y)zDUsed by keras to check compatibility. This should not be overridden.Tr   rA   s    r   _is_legacy_layerzLayer._is_legacy_layerJ  s     r   )TNN)NN Fr   )rR   
__module____qualname____doc__r0   propertyrB   rK   rF   rU   r[   rh   rl   r6   r   r   r   r   r   r   r   r   r   __classcell__)r;   s   @r   r   r      s    B.d  
  >B16	  /"3
' !! "!#!;!;!@!@3388!kZM^">  r   r   c                 `   t        j                         rt        d| d|      t        j                  |       } t        j                  |      }|D ]U  }t        j                  |      }|D ch c]  }t        |       }}| D ]!  }t        |      |vs|j                  |       # W y c c}w )NzHUsing collections from Layers not supported in Eager mode. Tried to add z to )	r   r?   r@   r   flattenr   get_collection_refr   r\   )elementscollection_listr%   
collectionecollection_setelements          r   r]   r]   P  s     
8@8GI J J \\(#(LL1/ #d''-J%/0be0N0 #	GN	*'"##0s   .B+)%r   r   r=   tensorflow.python.eagerr   tensorflow.python.frameworkr   r   tensorflow.python.kerasr   tensorflow.python.keras.enginer   r   (tensorflow.python.keras.legacy_tf_layersr	   'tensorflow.python.keras.mixed_precisionr
   tensorflow.python.keras.utilsr   tensorflow.python.opsr   r6   r   r   tensorflow.python.trackabler   r   tensorflow.python.utilr   	InputSpecr   contextmanagerr   r   r   r   r]   r   r   r   <module>r      s     D   + . + + 5 ; H : 7 6 ; 9 '   	  @ @F"J
vJ vr#r   