
    6biӋ                        S r SSKrSSKrSSKJs  Jr  SSKJs  Jr	  SSK
Jr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  \R*                  " 5       rS0S	 jrS0S
 jrS\	R2                  SSSSSSS\	R4                  R6                  \	R8                  R:                  SSS4S jrS rS r S r!S r"Sr#S r$S r%S1S jr&S r'S r(S r)S r*S r+S r,\	RZ                  R]                  \,5         " S S5      r/ " S S5      r0S r1S  r2S! r3S2S" jr4S# r5Sq6\" S$/S%9S& 5       r7\" S'/S%9S( 5       r8S) r9 " S* S+5      r:S, r;S- r<S. r=S/r>g)3z?Contains private utilities used mainly by the base Layer class.    N)backend)dtensor_api)control_flow_util)
tf_inspect)tf_utils)keras_exportc                 R    SSK Jn  UR                  XR                  S9nX3" U 5      4$ )Nr   )metrics)namedtype)tf_keras.srcr
   Meanr   )valuer   metrics_module
metric_objs       ^/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/engine/base_layer_utils.pycreate_mean_metricr   #   s.     7$$$kk$BJz%(((    c                     U b  [        U 5      (       d  U nS nXE4$ [        R                  " U 5      (       a  U " 5       n U(       a  [        R                  " XXS9nO[        R                  " XUS9nUR
                  nXE4$ )N)r   layout)r   )callabler   isclass	functoolspartial
base_dtype)initializerr   shaper   init_valvariable_dtypes         r   infer_init_val_and_dtyper    ,   s    x'<'< ## k**%-K ((%H !((5IH))##r   Tc                    [        X2X5      u  nn[        R                  " U5      nUc  SnUc,  [        R                  " UU UUUUUUU	U
UU(       a  UUS9$ SUS9$ [
        R                  " UU UUUUUU	U
UU(       a  US9$ SS9$ )a7  Util to create a variable (relies on `variable_scope.variable`).

Some reuse-related technicalities prevent us from using
`variable_scope.get_variable()` directly, so we use a subcomponent
that has fewer constraints (`variable_scope.variable()`).

In the longer term, it seems like a similar "default variable creator"
method should exist in `Trackable` instead. When this happens, we can get
rid of this temporary solution.

TODO(fchollet): remove this method when no longer needed.

Args:
  name: Variable name.
  shape: Variable shape.
  dtype: The type of the variable. Defaults to `self.dtype` or `float32`.
  initializer: Initializer 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` becomes `True` unless
    `synchronization` is set to `ON_READ`. Defaults to `None`.
  caching_device: Passed to `tf.Variable`.
  validate_shape: Passed to `tf.Variable`.
  constraint: Constraint instance (callable).
  use_resource: Whether to use a `ResourceVariable`.
  collections: List of graph collections keys. The new variable is added to
    these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
  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: Not handled at this time.
  layout: the optional DTensor layout, used for creating DVariable.

Returns:
  Variable instance.
NT)initial_valuer   	trainablecaching_devicer   validate_shape
constraintuse_resourcecollectionssynchronizationaggregationr   $experimental_enable_variable_lifting)r"   r   r#   r$   r   r%   r&   r(   r)   r*   r   )r    tfTensorShapetf1Variabledtensor	DVariable)r   r   r   r   r#   r$   r%   r&   r'   r(   r)   r*   partitionerr   r+   r   r   variable_shapes                     r   make_variabler4   >   s    |  8E Hn ^^E*N~
 ||") )!%#+#$2.1U
 	
 9=1U
 	
    ") )!#+#$2.
 	
 9=
 	
r   c                 F    S n[         R                  R                  X5      $ )zRetrieves the output mask(s) of the previous node.

Args:
    input_tensors: An arbitrary structure of Tensors.

Returns:
    A mask tensor or list of mask tensors.
c                     [        U SS 5      $ )N_keras_maskgetattr)xs    r   _collect_previous_mask5collect_previous_mask.<locals>._collect_previous_mask   s    q-..r   r,   nestmap_structure)input_tensorsr;   s     r   collect_previous_maskrA      s    / 77  !7GGr   c                 `    [        S [        R                  R                  U 5       5       5      $ )Nc              3   :   #    U  H  n[        US 5      v   M     g7f_keras_historyN)hasattr.0r:   s     r   	<genexpr>*have_all_keras_metadata.<locals>.<genexpr>   s     N5Mwq*++5Ms   )allr,   r>   flatten)tensorss    r   have_all_keras_metadatarN      s     NRWW__W5MNNNr   c                 R    [         R                  " U [        R                  " 5       S9$ )N)r   r   )r.   placeholderr   floatx)r   s    r    generate_placeholders_from_shaperR      s    ??gnn.>??r   c                 4    [        U [        5       / 5      u  pU$ )a  Wraps TensorFlow Operations for compatibility with the Functional API.

This method checks to see if a Tensor in `tensors` is missing TF-Keras
metadata and has its origin in a TF-Keras `Input` Layer. If so, this method
will replace the raw TensorFlow Operations that created this tensor with
`TensorFlowOpLayer` instances that create identical operations.

Any Tensors not originating from a TF-Keras `Input` Layer will be treated as
constants when constructing `TensorFlowOpLayer` instances.

Args:
  tensors: A structure of Tensors, some of which come from raw TensorFlow
    operations and need to have TF-Keras metadata assigned to them.

Returns:
  created_layers: List. The `TensorFlowOpLayer` instances created to wrap
    the raw Tensorflow operations.
)_create_keras_history_helperset)rM   _created_layerss      r   create_keras_historyrX      s    & 5WceRHAr   Fc           	         [         R                  " 5       (       a  [        S5      eSSKJn  [
        R                  R                  U 5      n/ n/ nU GHD  n[        USS5      b  M  [        U[
        R                  [         R                  45      (       a  UR                  UR                  5        M`  [        R                  " U5      (       a  UR                  U5        M  UR                  nX;  d  M  [!        UR"                  5      n	0 n
/ n[%        U	5       H  u  p['        U5      (       a  UR                  U5        M(  [
        R(                  R+                  5       =(       a    [         R                  " 5       (       + n[,        R.                  " [         R0                  " 5       5      nU(       d  U(       d  [2        (       a  XU'   M  [
        R4                  " 5          [6        R8                  " / U5      " / 5      X'   SSS5        M     [;        U5      n[=        XU5      u  pUR>                  nUR@                  RC                  5       nURE                  UU
US9nUR                  U5        URG                  U40 URH                  S9  URK                  U/5        GMG     U(       d  U(       a.  Sn[        S	RM                  U[O        U5      [O        U5      S
95      eX4$ ! , (       d  f       GM  = f)a  Helper method for `create_keras_history`.

Args:
  tensors: A structure of Tensors for which to create TF-Keras metadata.
  processed_ops: Set. TensorFlow operations that have already been wrapped
    in `TensorFlowOpLayer` instances.
  created_layers: List. The `TensorFlowOpLayer` instances created.

Returns:
  Tuple. First element is the updated set of TensorFlow Operations that
  have been wrapped in `TensorFlowOpLayer` instances. Second element is
  a list of the `TensorFlowOpLayer` instances created.
zB`create_keras_history` should only be called if eager is disabled!r   )
base_layerrE   N)	constantsr   )argskwargsoutputsz
    weights_mult = lambda x: tf.sparse.sparse_dense_matmul(x, weights)
    output = tf.keras.layers.Lambda(weights_mult)(input)
    a  Tensorflow ops that generate ragged or sparse tensor outputs are currently not supported by TF-Keras automatic op wrapping. Please wrap these ops in a Lambda layer: 

```
{example}
```
Sparse ops encountered: {sparse_ops}
Ragged tensors encountered: {ragged_tensors}
)example
sparse_opsragged_tensors)(r.   #executing_eagerly_outside_functions
ValueErrortf_keras.src.enginerZ   r,   r>   rL   r9   
isinstanceSparseTensorSparseTensorValueappendopr   	is_raggedlistinputs	enumerateuses_keras_history
distributein_cross_replica_contextr   GraphOrParentsInXlaContextget_default_graph_UNSAFE_GRAPH_OP_LAYER_CREATION
init_scoper   functionunnest_if_single_tensorrT   r   node_defSerializeToStringTensorFlowOpLayer_set_connectivity_metadatar^   updateformatstr)rM   processed_opsrW   rZ   tensor_listr`   ra   tensorri   	op_inputsr[   layer_inputsiop_inputds_with_session	using_xlar   rw   op_layerlambda_examples                       r   rT   rT      s    ..00P
 	
 /''//'*KJN6+T2>fr0E0EFGGfii(f%%!!&)YY"RYYIIL(3%h// ''1
 >>@ J # G G II $ !2 L L--/!I ($:: (0!]]_+2+;+;B+I"+MIL -_1  44 3<@L,H^-)M 77D{{446H!33ID 4 H !!(+//"_R 0    "&o p ^ =
 >DV&z?">2 >D >
 	
 ((C -_s    K
K)c                     [         R                  R                  U 5      n[        U [        5      (       d  [        U5      S:X  a  US   n U $ )N   r   )r,   r>   rL   re   dictlen)r@   flat_input_tensorss     r   rv   rv   J  sA    7 mT**s3E/F!/K*1-r   c                     [         R                  R                  U 5      n[        5       R                  (       a  U(       d  g[        S U 5       5      (       a  g[        U 5      $ )a  Check if any Tensors need to be wrapped in TensorFlowOpLayers.

This will never return True inside a sublayer, because sublayers
do not need to create TF-Keras History. Otherwise, this returns True
if one or more of `tensors` originates from a `keras.Input` and
does not have `_keras_history` set.

Args:
  tensors: An arbitrary nested structure of Tensors.
  ignore_call_context: Whether to ignore the check of if currently
    outside of a `call` context. This is `True` when creating
    KerasHistory inside `Node`, where we always know that Tensors
    are being used with the Functional API.

Returns:
  Bool, whether at least one Tensor needs to be wrapped.
Fc              3   @   #    U  H  n[        US S5      SLv   M     g7frD   r8   )rH   r   s     r   rI   &needs_keras_history.<locals>.<genexpr>j  s&      #F 	($/t;#s   )r,   r>   rL   call_contextin_callrK   rn   )rM   ignore_call_contextr@   s      r   needs_keras_historyr   U  sQ    $ GGOOG,M~&9
 #  
 g&&r   c                  *    [        5       R                  $ )z:Returns if currently executing inside of a TF-Keras graph.)r   in_keras_graph r   r   is_in_keras_graphr   s  s    >(((r   c                  N    [         R                  " 5       =(       d
    [        5       $ )z4Returns if in eager mode or inside of a tf.function.)r,   executing_eagerlyis_in_tf_functionr   r   r   is_in_eager_or_tf_functionr   x  s    !8%6%88r   c                      [         R                  " 5       (       d  g[        R                  " 5       (       d  g[	        5       (       a  g[         R
                  " 5       n [        U SS5      (       a!  U R                  R                  S5      (       a  gg)z#Returns if inside of a tf.function.Fr   wrapped_functionT)	r.   rb   r,   inside_functionr   rr   r9   r   
startswith)graphs    r   r   r   }  sr     2244!!#Eufe$$)>)>* * r   c                    [        5       n[        R                  R                  U 5      nU(       a  / nU Ht  n[	        U5      U;   a  M  UR                  [	        U5      5        [        USS5      b  M>  [        USS5      b    g UR                  UR                  R                  5        Mv     UnU(       a  M  [        U 5        g! [         a     M  f = f)a  Check if at least one Tensor originates from a `keras.Input`.

This is `True` if at least one Tensor has its origin in a `keras.Input`.
Any Tensor that originates from a `keras.Input` will have a dependency
Tensor with a `_keras_history` attribute attached. Tensors that have
already been checked to not originate from a `keras.Input`
are marked as `_keras_history_checked`.

Args:
  tensors: An arbitrary nested structure of Tensors.

Returns:
  Bool, whether at least one Tensor originates from a `keras.Input`.
_keras_history_checkedNrE   TF)rU   r,   r>   rL   idaddr9   extendri   rl   AttributeErrormark_checked)rM   checked_tensorstensors_to_checknew_tensors_to_checkr   s        r   rn   rn     s     eOwww/
!&F&z_,6
+v7>Jv/6B$++FII,<,<= '" 0' 
.  " s   %C
CCc                 H    S n[         R                  R                  X5        g)zMarks that these Tensors should not be tracked.

This prevents Layers from attempting to create TensorFlowOpLayers
for these Tensors.

Args:
  tensors: An arbitrary structure of Tensors.
c                     SU l         g )NT)r   )r   s    r   _mark_checked#mark_checked.<locals>._mark_checked  s
    (,%r   Nr=   )rM   r   s     r   r   r     s    - GG-1r   c                  X    [        [        SS5      n U c  [        5       n U [        l        U $ )z'Returns currently active `CallContext`.r   N)r9   _call_contextCallContextr   )call_ctxs    r   r   r     s*    }nd;H=%-"Or   c                       \ rS rSrSrS rSS jr\S 5       r\S 5       r	\S 5       r
\S	 5       r\S
 5       r\S 5       r\S 5       rSrg)r   i  aJ  Keeps track of properties currently inside a Layer/Model's `call`.

Attributes:
  in_call: Whether currently inside the `call` of a Layer.
  layer: The `Layer` whose `call` is currently active.
  inputs: The inputs to the currently active `Layer`.
  build_graph: Whether currently inside a Graph or FuncGraph.
  training: Whether currently executing in training or inference mode.
  saving: Whether currently saving to SavedModel.
  frozen: Whether currently executing inside a `Layer` with `trainable` set
    to `False`.
  in_keras_graph: Whether executing inside the TF-Keras Graph.
c                 :    SU l         S S SS S S.U l        SU l        g )NFlayerrl   build_graphtrainingsaving)r   _state_in_keras_graphselfs    r   __init__CallContext.__init__  s-      
  %r   Nc                 (    UUUUUS.n[        X5      $ )a  Push a Layer and its inputs and state onto the current call context.

Args:
  layer: The `Layer` whose `call` is currently active.
  inputs: The inputs to the currently active `Layer`.
  build_graph: Whether currently inside a Graph or FuncGraph.
  training: Whether currently executing in training or inference mode.
  saving: Whether currently saving to SavedModel.

Returns:
  Context manager.
r   )CallContextManager)r   r   rl   r   r   r   states          r   enterCallContext.enter  s'     & 
 "$..r   c                      U R                   S   $ )Nr   r   r   s    r   r   CallContext.layer  s    {{7##r   c                      U R                   S   $ )Nrl   r   r   s    r   rl   CallContext.inputs      {{8$$r   c                      U R                   S   $ Nr   r   r   s    r   r   CallContext.build_graph  s    {{=))r   c                      U R                   S   $ )Nr   r   r   s    r   r   CallContext.training  s    {{:&&r   c                      U R                   S   $ )Nr   r   r   s    r   r   CallContext.saving  r   r   c                 R    U R                   S   nU(       d  gUR                  (       + $ )Nr   F)r   r#   )r   r   s     r   frozenCallContext.frozen#  s#    G$??""r   c                     [         R                  " 5       (       a  gU R                  =(       d#    [        [        R
                  " 5       SS 5      S:H  $ )NFr   keras_graph)r,   r   r   r9   r   	get_graphr   s    r   r   CallContext.in_keras_graph*  sD     !!   Kw((*FD9]J	
r   )r   r   r   N)__name__
__module____qualname____firstlineno____doc__r   r   propertyr   rl   r   r   r   r   r   __static_attributes__r   r   r   r   r     s    %/, $ $ % % * * ' ' % % # # 
 
r   r   c                   *    \ rS rSrSrS rS rS rSrg)r   i6  z"Context manager for `CallContext`.c                 0    Xl         X l        US   U l        g r   )	_call_ctxr   _build_graph)r   r   r   s      r   r   CallContextManager.__init__9  s    !!-0r   c                 L   U R                   nUR                  U l        UR                  U l        SUl        U R                  Ul        U R
                  (       aM  UR                  U l        UR                  =(       d#    [        [        R                  " 5       SS 5      S:H  Ul        g g )NTr   r   )r   r   _prev_in_callr   _prev_stater   r   _prev_in_keras_graphr9   r   r   )r   r   s     r   	__enter__CallContextManager.__enter__>  s    >>%--#??++ (0(@(@D%(( O7,,.=N $ r   c                     U R                   nU R                  Ul        U R                  Ul        U R
                  (       a  U R                  Ul        g g r   )r   r   r   r   r   r   r   r   )r   exc_infor   s      r   __exit__CallContextManager.__exit__O  sB    >>--**'+'@'@H$ r   )r   r   r   r   r   r   N)	r   r   r   r   r   r   r   r   r   r   r   r   r   r   6  s    ,1
"Ar   r   c                     [        [        U R                  SS U5      5      nUR                  U5        SU;   =(       a    US   SL$ )zDReturns whether a user passed the `training` argument in `__call__`.   Nr   )r   zipr\   r{   )argspecr\   r]   	full_argss       r   training_arg_passed_to_callr   X  sH     Sab)401IV"Hy'<D'HHr   c                     SU R                   ;  =(       a;    SU R                   ;  =(       a%    SU R                   ;  =(       a    SU R                   ;  $ )zEReturns True if the object is a subclassed layer or subclassed model.zkeras.enginezkeras.src.enginezkeras.layerszkeras.src.layersr   r   s    r   is_subclassedr   `  sR     	e... 	7e&6&66	7%"2"22	7 e&6&66	r   c                      SU R                   ;   $ )z6Returns whether the layer is loaded from a SavedModel.zlegacy.saved_modelr   r   s    r   from_saved_modelr   j  s    5#3#333r   c                 B   U(       dF  [         R                  " 5       (       a~  [        U S5      (       al  U R                  R                  (       aP  US:X  a  SnSn[        SU SU S35      eUS:X  a  S	nS
nOUS:X  a  SnSnOSnSn[        SR                  UUUS95      eggg)a>  Checks that tensors passed to `add_*` method match the TF-Keras graph.

When one of the `add_*` method is called inside a V2 conditional branch, the
underlying tensor gets created in a FuncGraph managed by control_flow_v2.
We need to raise clear error messages in such cases.

Args:
  tensor: Tensor to check, or `False` if it is known that an error
    should be raised.
  method: Caller method, one of {'add_metric', 'add_loss', 'add_update'}.
  force_raise: If an error should be raised regardless of `tensor`.

Raises:
  RuntimeError: In case of an out-of-graph tensor.
r   activity_regularizerag  
      class TestModel(tf.keras.Model):

        def __init__(self):
          super(TestModel, self).__init__(name='test_model')
          self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2')

        def call(self, x, training=None):
          if training:
            return self.dense(x)
          else:
            return self.dense(x)
      a  
      class TestModel(tf.keras.Model):

        def __init__(self):
          super(TestModel, self).__init__(name='test_model')
          self.dense = tf.keras.layers.Dense(2, activity_regularizer='l2')

        def call(self, x, training=None):
          return self.dense(x)
      zRYou are using a layer with `activity_regularizer` in a control flow branch, e.g.:
z
This is currently not supported. Please move your call to the layer with `activity_regularizer` out of the control flow branch, e.g.:
aC  
You can also resolve this by marking your outer model/layer dynamic (eager-only) by passing `dynamic=True` to the layer constructor. Any kind of control flow is supported with dynamic layers. Note that using `dynamic=True` requires you to implement static shape inference in the `compute_output_shape(input_shape)` method.
add_metricz
      def call(self, inputs, training=None):
        if training:
          metric = compute_metric(inputs)
          self.add_metric(metric, name='my_metric', aggregation='mean')
        return inputs
      z
      def call(self, inputs, training=None):
        if training:
          metric = compute_metric(inputs)
        else:
          metric = 0.
        self.add_metric(metric, name='my_metric', aggregation='mean')
        return inputs
      add_lossz
      def call(self, inputs, training=None):
        if training:
          loss = compute_loss(inputs)
          self.add_loss(loss)
        return inputs
      z
      def call(self, inputs, training=None):
        if training:
          loss = compute_loss(inputs)
        else:
          loss = 0.
        self.add_loss(loss)
        return inputs
      z
      def call(self, inputs, training=None):
        if training:
          self.add_update(self.w.assign_add(1))
        return inputs
      z
      def call(self, inputs, training=None):
        if training:
          increment = 1
        else:
          increment = 0
        self.add_update(self.w.assign_add(increment))
        return inputs
      a  You are using the method `{method}` in a control flow branch in your layer, e.g.:
{bad_example}
This is not currently supported. Please move your call to {method} out of the control flow branch, e.g.:
{correct_example}
You can also resolve this by marking your layer as dynamic (eager-only) by passing `dynamic=True` to the layer constructor. Any kind of control flow is supported with dynamic layers. Note that using `dynamic=True` requires you to implement static shape inference in the `compute_output_shape(input_shape)` method.)methodbad_examplecorrect_exampleN)r.   rb   rF   r   is_control_flow_graphRuntimeErrorr|   )r   r  force_raiser  r  s        r   check_graph_consistencyr  o  s      //11FG$$LL..++
K	
O //:m < ** +	
  \!
K
O z!
K
O
K
O A BH' / BH B
 	
u / % 	2r   c                 N   ^ U4S jn[         R                  R                  X 5      $ )z@Marks `outputs` as the return values for automatic control deps.c                   > [         R                  " U 5      (       d  U $ TR                  U 5      n[        U SS5      b!  TR                  U R                  5      Ul        OSUl        [        U SS5      b  U R
                  Ul        U$ )z>Marks `tensor` as the return value for automatic control deps.r7   N_tfp_distribution)r,   	is_tensormark_as_returnr9   r7   r
  )r   return_tensoracds     r   _mark_as_return'mark_as_return.<locals>._mark_as_return  s}    ||F##M**626=$/;(+(:(:6;M;M(NM%(,M% 6.5A.4.F.FM+r   r=   )r^   r  r  s    ` r   r  r    s    $ 77  ::r   z%keras.layers.enable_v2_dtype_behavior)v1c                      Sq g)a0  Enable the V2 dtype behavior for TF-Keras layers.

By default, the V2 dtype behavior is enabled in TensorFlow 2, so this
function is only useful if `tf.compat.v1.disable_v2_behavior` has been
called. Since mixed precision requires V2 dtype behavior to be enabled, this
function allows you to use mixed precision in TF-Keras layers if
`disable_v2_behavior` has been called.

When enabled, the dtype of TF-Keras layers defaults to floatx (which is
typically float32) instead of None. In addition, layers will automatically
cast floating-point inputs to the layer's dtype.

>>> x = tf.ones((4, 4, 4, 4), dtype='float64')
>>> layer = tf.keras.layers.Conv2D(filters=4, kernel_size=2)
>>> print(layer.dtype)  # float32 since V2 dtype behavior is enabled
float32
>>> y = layer(x)  # Layer casts inputs since V2 dtype behavior is enabled
>>> print(y.dtype.name)
float32

A layer author can opt-out their layer from the automatic input casting by
passing `autocast=False` to the base Layer's constructor. This disables the
autocasting part of the V2 behavior for that layer, but not the defaulting
to floatx part of the V2 behavior.

When a global `tf.keras.mixed_precision.Policy` is set, a TF-Keras layer's
dtype will default to the global policy instead of floatx. Layers will
automatically cast inputs to the policy's compute_dtype.
TNV2_DTYPE_BEHAVIORr   r   r   enable_v2_dtype_behaviorr    s    @ r   z&keras.layers.disable_v2_dtype_behaviorc                      Sq g)zoDisables the V2 dtype behavior for TF-Keras layers.

See `tf.compat.v1.keras.layers.enable_v2_dtype_behavior`.
FNr  r   r   r   disable_v2_dtype_behaviorr  .  s
     r   c                  l    [         c(  [        R                  R                  R	                  5       $ [         $ )z1Returns True if the V2 dtype behavior is enabled.)r  r,   __internal__tf2enabledr   r   r   v2_dtype_behavior_enabledr  8  s'     ""**,,r   c                   @    \ rS rSrSrS r\S 5       rS rS r	S r
Srg	)
TrackableWeightHandleri?  aq  Keras wrapper for handling Trackable object saving and restoring.

This class handles Trackables in both V1 and V2 modes, ensuring that they
can be saved and restored with the correct data and without adding
additional ops on every save.

Attributes:
  trackable: The trackable to wrap.
  num_tensors: The number of tensors that this trackable requires for
    saving.
c                   ^  [        U[        R                  R                  R                  5      (       d  [        U S35      eUT l        [        R                  R                  5       T l	        [        R                  R                  R                  U5      R                  5       nU(       d  ST l        S T l        S T l        g [        U5      S:X  GaZ  [!        U5      S   n["        R$                  " 5       (       aF  UT l        [        T R'                  5       R(                  5      T l        U 4S jT l        U 4S jT l        g / T l        U" 5       T l        [        T R&                  R(                  5      T l        T R&                  R(                   HS  nUR,                  nT R*                  R/                  ["        R0                  " UR2                  UR4                  5      5        MU     T R&                  R7                  T R*                  S 5      T l        T R:                  T l        U 4S jT l        g [        S	U S
[        U5       S35      e)Nz is not a Trackable object.r   c                     g r   r   )weightss    r   <lambda>1TrackableWeightHandler.__init__.<locals>.<lambda>Y  s    4r   c                      / $ r   r   r   r   r   r"  r#  Z  s    2r   r   c                 D   > TR                  5       R                  U S 5      $ r   )	_saveablerestore)r!  r   s    r   r"  r#  g  s    t~~/?/G/GT0r   c                  v   > TR                  5       R                   V s/ s H  o R                  PM     sn $ s  sn f r   r&  specsr   specr   s    r   r"  r#  j  s/    ,0NN,<,B,B(,BDKK,B( (s   6c                  n   > TR                   R                   V s/ s H  o R                  PM     sn $ s  sn f r   r)  r+  s    r   r"  r#  ~  s,    ,0NN,@,@(,@DKK,@( (s   2z?Only Trackables with one Saveable are supported. The Trackable z has z Saveables.)re   r,   r  tracking	Trackablerc   
_trackablero   get_strategy_distribute_strategysaveable_objects_from_trackablevalues_num_tensors_setter_getterr   rk   r.   rb   r&  r*  _placeholder_tensorsr   rh   rP   r   r   r'  
_assign_op_set_weights_v1)r   	trackable	saveablessaveabler,  r   s   `     r   r   TrackableWeightHandler.__init__L  s   )R__%=%=%G%GHH	{*EFGG#$&MM$>$>$@!OO,,LL

&( 	
  !D/DL%DL^q Iq)H6688 "*$'(8(>(>$?!   -/)!)$'(<(<$=! NN00D![[F--44fllC 1
 #'.."8"8--t#  $33  !!*5Y0@M r   c                     U R                   $ r   )r5  r   s    r   num_tensors"TrackableWeightHandler.num_tensors  s       r   c           
          [        U5      U R                  :w  a2  [        SU R                   SU R                   S[        U5       S35      eU R	                  U5        g )NzWeight handler for trackable z3 received an incorrect number of weights: expected z weights, got z	 weights.)r   r5  rc   r0  r6  )r   r!  s     r   set_weights"TrackableWeightHandler.set_weights  sb    w<4,,,//@ A --. /7|nI/  	Wr   c                 "    U R                  5       $ r   )r7  r   s    r   get_tensors"TrackableWeightHandler.get_tensors  s    ||~r   c                     0 n[        U5       H  u  p4XBU R                  U   '   M     [        R                  " 5       R	                  U R
                  U5        g r   )rm   r8  r   get_sessionrunr9  )r   r!  	feed_dictidxr   s        r   r:  &TrackableWeightHandler._set_weights_v1  sH    	$W-KC8>d//45 .!!$//9=r   )r9  r2  r7  r5  r8  r&  r6  r0  N)r   r   r   r   r   r   r   r@  rC  rF  r:  r   r   r   r   r  r  ?  s0    
9v ! !>r   r  c                     [         R                  R                  U 5      n[        S U 5       5      (       a  [	        SU SU  S35      eg )Nc              3   V   #    U  H  n[        U[        R                  5      v   M!     g 7fr   )re   r,   RaggedTensorrG   s     r   rI   $no_ragged_support.<locals>.<genexpr>  s     
>:a:a)):s   ')zLayer z; does not support RaggedTensors as input. Inputs received: z@. You can try converting your input to a dense (uniform) tensor.)r,   r>   rL   anyrc   )rl   
layer_name
input_lists      r   no_ragged_supportrU    sR    (J

>:
>>>ZL !  &x (11
 	
 ?r   c                     U R                   R                   Vs1 s H  oR                  iM     snR                  SS15      (       + $ s  snf )zBReturns True if `v` is a PartitionedVariable or a ShardedVariable.PartitionedVariableShardedVariable)	__class____mro__r   
isdisjoint)vclzs     r   is_split_variabler^    sC    ()(;(;<(;(;<GG	 12  <s   Ac                     [        U 5      n[        US5      =(       a(    [        US5      =(       a    [        U [         5      (       + $ )Ntrainable_weightsnon_trainable_weights)typerF   re   )objobj_types     r   has_weightsre    s=    CyH-. 	&H56	&3%%r   z8This layer's losses have been added to the parent layer.r   )F)Nr   F)?r   r   	threadingtensorflow.compat.v1compatr  r.   tensorflow.compat.v2v2r,   r   r   tf_keras.src.dtensorr   r0   tf_keras.src.utilsr   r   r    tensorflow.python.util.tf_exportr   localr   r   r    float32VariableSynchronizationAUTOVariableAggregationNONEr4   rA   rN   rR   rX   rs   rT   rv   r   r   r   r   rn   r   r   r  register_call_context_functionr   r   r   r   r   r  r  r  r  r  r  r  rU  r^  re  REVIVED_LOSS_PLACEHOLDERr   r   r   <module>rv     s   F   " " ! !   7 0 ) ' :!)$( 
**..33&&++)-g
TH O@B #( c)L'<)
9
&*Z2   . .| <X
 X
vA ADI4
~
B;0   9:; <D :;< =]> ]>@
  ? r   