
    &VfS                     H   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  G d d          Zd Zd Z eddg          d             Zd Zd Z ed          d             Z ed          d             Zd Z G d d          ZdS )    N)keras_export)config)dtypes)global_state)current_path)get_stateless_scope)in_stateless_scope)
tensorflow)	auto_namec                   ~   e Zd ZdZ	 	 	 	 	 	 d@dZd Zd Zd Zd	 Ze	d
             Z
e	d             Zd Zd Zd Ze	d             Ze	d             Ze	d             Ze	d             Zej        d             Ze	d             Zej        d             Ze	d             Zej        d             Ze	d             Zej        d             Zd Zd ZdAdZd ZdAdZd Zd  Zd! Zd" Zd# Z d$ Z!d% Z"d& Z#d' Z$d( Z%d) Z&d* Z'd+ Z(d, Z)d- Z*d. Z+d/ Z,d0 Z-d1 Z.d2 Z/d3 Z0d4 Z1d5 Z2d6 Z3d7 Z4d8 Z5d9 Z6d: Z7d; Z8d< Z9d= Z:d> Z;d? Z<dS )BKerasVariablea  Represents a backend-agnostic variable in Keras.

    A `Variable` acts as a container for state. It holds a tensor value and can
    be updated. With the JAX backend, variables are used to implement
    "functionalization", the pattern of lifting stateful operations out of
    a piece of computation to turn it into a stateless function.

    Args:
        initializer: Initial value or callable for initialization.
            If a callable is used, it should take the arguments
            `shape` and `dtype`.
        shape: Optional. Tuple for the variable's shape.
            Required if `initializer` is a callable.
        dtype: Optional. Data type of the variable. Defaults to the global float
            dtype type (`"float32"` if never configured).
        trainable: Optional. Boolean indicating if variable is trainable.
            Defaults to `True`.
        name: Optional. A unique name for the variable. Automatically generated
            if not set.

    Attributes:
        name: The name of the variable (string).
        path: The path of the variable within the Keras model or layer (string).
        dtype: The data type of the variable (string).
        shape: The shape of the variable (tuple of integers).
        ndim: The number of dimensions of the variable (integer).
        trainable: Whether the variable is trainable (boolean).
        value: The current value of the variable (NumPy array or tensor).

    Examples:

    **Initializing a `Variable` with a NumPy array:**

    ```python
    import numpy as np
    import keras
    initial_array = np.ones((3, 3))
    variable_from_array = keras.Variable(initializer=initial_array)
    ```

    **Using a Keras initializer to create a `Variable`:**

    ```python
    from keras.src.initializers import Ones
    variable_from_initializer = keras.Variable(
        initializer=Ones(), shape=(3, 3), dtype="float32"
    )
    ```

    **Updating the value of a `Variable`:**

    ```python
    new_value = np.zeros((3, 3), dtype="float32")
    variable_from_array.assign(new_value)
    ```

    **Marking a `Variable` as non-trainable:**

    ```python
    non_trainable_variable = keras.Variable(
        initializer=np.ones((3, 3), dtype="float32"), trainable=False
    )
    ```
    NTmeanc                 R   |pt          | j        j                  }t          |t                    rd|v rt          d|           |dvrt          d|           || _        t                      }|rt                      dz   | j        z   | _        n| j        | _        t          |          }|| _
        d | _        d | _        d | _        d | _        || _        || _        || _        d| _        t          |t                    rddlm}	 |	                    |          }t-          |          r|t          d| d	|           t/                      rVt-          |          r8d | _        || _        |                     |          | _        t5          |            nvt          d
          t-          |          r#|                     |          } |||          }
n|}
|                     |
           t9          | j        j                  | _        t=          | j                  | _        d S )N/zRArgument `name` must be a string and cannot contain character `/`. Received: name=)r   sumonly_first_replicazwInvalid valid for argument `aggregation`. Expected one of {'mean', 'sum', 'only_first_replica'}. Received: aggregation=Fr   )initializersznWhen creating a Variable from an initializer, the `shape` argument should be specified. Received: initializer=z and shape=ad  You are attempting to create a variable while in a stateless scope. This is disallowed. Make sure that all variables are created before you start using your layer/model objects.

In some cases, you might be seeing this error because you need to implement a `def build(self, input_shape)` method on your layer/model, which will create its variables.

In some other cases, you might be seeing this error because you are instantiating a `Variable` and assigning it to a layer without going through self.add_variable()/self.add_weight(). Always prefer using these methods (with a `shape` and `initializer` argument).dtype) r   	__class____name__
isinstancestr
ValueErrornamer   pathstandardize_dtype_dtype_shape_initializer_regularizer_constraint
_trainable	_autocast_aggregation_overwrite_with_gradient	keras.srcr   getcallabler	   _value_validate_shaperegister_uninitialized_variable_initializetupleshapelen_ndim)selfinitializerr/   r   	trainableautocastaggregationr   parent_pathr   values              _/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/backend/common/variables.py__init__zKerasVariable.__init__P   s    9y!899$$$ 	t)"&) )  
 CCC7)47 7  
 	"nn 	"$,ty8DII	DI!%((  #!' ).%k3'' 	8......&**;77KK   	} )-8) ) "') )    	3$$ "$/!"22599/5555 C  $ $$ $,,U33#E777#U### 122DK%%


    c                     | j         t          d| j         d          t                      rt          d          |                     | j        | j                  }|                     |           d S )Nz	Variable z is already initialized.zYou are attempting to initialize a variable while in a stateless scope. This is disallowed. Make sure that all variables are initialized before you start using your layer/model objects.r   )r*   r   r   r	   r    r   r   r-   r2   r8   s     r9   _deferred_initializez"KerasVariable._deferred_initialize   s    ;"LLLLMMM 	C   !!$+T[!AAr;   c                 b    t          |          }d |v rt          d| d| j         d          |S )NzbShapes used to initialize variables must be fully-defined (no `None` dimensions). Received: shape=z for variable path='')standardize_shaper   r   )r2   r/   s     r9   r+   zKerasVariable._validate_shape   s]    !%((5==AA A48IA A A  
 r;   c                 ^    t                      }| j        r||                    |          S |S N)get_autocast_scoper$   
maybe_cast)r2   r8   autocast_scopes      r9   _maybe_autocastzKerasVariable._maybe_autocast   s5    +--> 	4n8!,,U333r;   c                 *    t          j        |           S rC   )nparrayr2   s    r9   numpyzKerasVariable.numpy   s    x~~r;   c                     | j         S rC   )r%   rK   s    r9   r6   zKerasVariable.aggregation         r;   c                 <   t                      r:t                      }|                    |           }||                     |          S | j        4|                     |                     | j        | j                            S |                     | j                  S Nr   )r	   r   get_current_valuerG   r*   r    r   r   )r2   scoper8   s      r9   r8   zKerasVariable.value   s     	3'))E++D11E ++E222;
 ''!!$+T[!AA   ##DK000r;   c                 T   |                      || j                  }t          |j        | j                  s't	          d| j        j         d|j         d|            t                      r't                      }|                    | |f           d S | 	                    |           d S )Nr   zzThe shape of the target variable and the shape of the target value in `variable.assign(value)` must match. variable.shape=z, Received: value.shape=z. Target variable: )
_convert_to_tensorr   shape_equalr/   r   r8   r	   r   
add_update_direct_assign)r2   r8   rR   s      r9   assignzKerasVariable.assign   s    ''TZ'@@5;
33 	+ #'*"2+ + */	+ +
 %)+ +    	''))EdE]+++++&&&&&r;   c                 6    |                      | |z              d S rC   rX   r=   s     r9   
assign_addzKerasVariable.assign_add       D5L!!!!!r;   c                 6    |                      | |z
             d S rC   rZ   r=   s     r9   
assign_subzKerasVariable.assign_sub   r\   r;   c                 t    t                      }| j        r|t          | j                  r|j        S | j        S rC   )rD   r$   is_float_dtyper   r   )r2   rF   s     r9   r   zKerasVariable.dtype   sB    +--N	(*t{++ + "''{r;   c                     | j         S rC   )r   rK   s    r9   r/   zKerasVariable.shape  s
    {r;   c                     | j         S rC   )r1   rK   s    r9   ndimzKerasVariable.ndim  s
    zr;   c                     | j         S rC   r#   rK   s    r9   r4   zKerasVariable.trainable	  s
    r;   c                     || _         d S rC   re   r=   s     r9   r4   zKerasVariable.trainable  s    r;   c                     | j         S )a  Whether this variable should be overwritten by the gradient.

        This property is designed for a special case where we want to overwrite
        the variable directly with its computed gradient. For example, in float8
        training, new `scale` and `amax_history` are computed as gradients, and
        we want to overwrite them directly instead of following the typical
        procedure such as gradient descent with a learning rate, gradient
        clipping and weight decaying.
        )r&   rK   s    r9   overwrite_with_gradientz%KerasVariable.overwrite_with_gradient  s     ,,r;   c                 b    t          |t                    st          d|           || _        d S )Nz7`overwrite_with_gradient` must be a boolean. Received: )r   bool	TypeErrorr&   r=   s     r9   rh   z%KerasVariable.overwrite_with_gradient  sH    %&& 	%"% %   ).%%%r;   c                     | j         S rC   )r!   rK   s    r9   regularizerzKerasVariable.regularizer'  rN   r;   c                 h    ddl m} |"t          ||          st          d|           || _        d S )Nr   )RegularizerzInvalid value for attribute `regularizer`. Expected an instance of `keras.regularizers.Regularizer`, or `None`. Received: regularizer=)keras.src.regularizersro   r   r   r!   )r2   r8   ro   s      r9   rm   zKerasVariable.regularizer+  s]    666666Z{%C%C1).1 1  
 "r;   c                     | j         S rC   )r"   rK   s    r9   
constraintzKerasVariable.constraint7  s    r;   c                 h    ddl m} |"t          ||          st          d|           || _        d S )Nr   )
ConstraintzInvalid value for attribute `constraint`. Expected an instance of `keras.constraints.Constraint`, or `None`. Received: constraint=)keras.src.constraintsrt   r   r   r"   )r2   r8   rt   s      r9   rr   zKerasVariable.constraint;  s]    444444Zz%B%B0(-0 0  
 !r;   c                 8    d| j          d| j         d| j         dS )Nz<KerasVariable shape=z, dtype=z, path=>)r/   r   r   rK   s    r9   __repr__zKerasVariable.__repr__G  s<    !DJ ! !
 ! !I! ! !	
r;   c                     t           rC   NotImplementedErrorr=   s     r9   r-   zKerasVariable._initializeM      !!r;   c                     t           rC   rz   )r2   r8   r   s      r9   rT   z KerasVariable._convert_to_tensorP  r|   r;   c                 6    | j                             |          S rC   )r8   __getitem__)r2   idxs     r9   r   zKerasVariable.__getitem__S  s    z%%c***r;   c                 Z    t          j        | j                            |                    S rC   )rI   asarrayr8   	__array__r2   r   s     r9   r   zKerasVariable.__array__V  s$    
 z$*..u55666r;   c                      t          d          )Nz-A Keras Variable cannot be used as a boolean.)rk   rK   s    r9   __bool__zKerasVariable.__bool__]  s    GHHHr;   c                 4    | j                                         S rC   )r8   __neg__rK   s    r9   r   zKerasVariable.__neg__`      z!!###r;   c                     | j         S rC   )r8   rK   s    r9   __pos__zKerasVariable.__pos__c  s
    zr;   c                 4    | j                                         S rC   )r8   __abs__rK   s    r9   r   zKerasVariable.__abs__f  r   r;   c                 4    | j                                         S rC   )r8   
__invert__rK   s    r9   r   zKerasVariable.__invert__i  s    z$$&&&r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __eq__rT   r   r2   otherr8   s      r9   r   zKerasVariable.__eq__l  0    
||D33E3MMNNNr;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __ne__rT   r   r   s      r9   r   zKerasVariable.__ne__p  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __lt__rT   r   r   s      r9   r   zKerasVariable.__lt__t  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __le__rT   r   r   s      r9   r   zKerasVariable.__le__x  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __gt__rT   r   r   s      r9   r   zKerasVariable.__gt__|  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __ge__rT   r   r   s      r9   r   zKerasVariable.__ge__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __add__rT   r   r   s      r9   r   zKerasVariable.__add__  0    
}}T44U%+4NNOOOr;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __radd__rT   r   r   s      r9   r   zKerasVariable.__radd__  0    
~~d55e5;5OOPPPr;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __sub__rT   r   r   s      r9   r   zKerasVariable.__sub__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rsub__rT   r   r   s      r9   r   zKerasVariable.__rsub__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __mul__rT   r   r   s      r9   r   zKerasVariable.__mul__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rmul__rT   r   r   s      r9   r   zKerasVariable.__rmul__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __truediv__rT   r   r   s      r9   r   zKerasVariable.__truediv__  9    
  ##E#==
 
 	
r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rtruediv__rT   r   r   s      r9   r   zKerasVariable.__rtruediv__  9    
!!##E#==
 
 	
r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __floordiv__rT   r   r   s      r9   r   zKerasVariable.__floordiv__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rfloordiv__rT   r   r   s      r9   r   zKerasVariable.__rfloordiv__  s9    
""##E#==
 
 	
r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __mod__rT   r   r   s      r9   r   zKerasVariable.__mod__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rmod__rT   r   r   s      r9   r   zKerasVariable.__rmod__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __pow__rT   r   r   s      r9   r   zKerasVariable.__pow__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rpow__rT   r   r   s      r9   r   zKerasVariable.__rpow__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   
__matmul__rT   r   r   s      r9   r   zKerasVariable.__matmul__  s9    
##E#==
 
 	
r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rmatmul__rT   r   r   s      r9   r   zKerasVariable.__rmatmul__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __and__rT   r   r   s      r9   r   zKerasVariable.__and__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rand__rT   r   r   s      r9   r   zKerasVariable.__rand__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __or__rT   r   r   s      r9   r   zKerasVariable.__or__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __ror__rT   r   r   s      r9   r   zKerasVariable.__ror__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __xor__rT   r   r   s      r9   r   zKerasVariable.__xor__  r   r;   c                 n    | j         }|                    |                     ||j                            S rP   )r8   __rxor__rT   r   r   s      r9   r   zKerasVariable.__rxor__  r   r;   )NNTTr   NrC   )=r   
__module____qualname____doc__r:   r>   r+   rG   rL   propertyr6   r8   rX   r[   r^   r   r/   rc   r4   setterrh   rm   rr   rx   r-   rT   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r;   r9   r   r      s       ? ?H W& W& W& W&r            ! ! X! 1 1 X1 ' ' '"" " "" " "   X   X   X   X       
- 
- X
- #. . $#. ! ! X! 	" 	" 	"     X  	! 	! 	!
 
 
" " "" " " "+ + +7 7 7 7I I I$ $ $  $ $ $' ' 'O O OO O OO O OO O OO O OO O OP P PQ Q QP P PQ Q QP P PQ Q Q
 
 

 
 

 
 

 
 
P P PQ Q QP P PQ Q Q
 
 

 
 
P P PQ Q QO O OP P PP P PQ Q Q Q Qr;   r   c                 ^    t          j        dg d          }|                    |            d S )Nuninitialized_variablesT)set_to_default)r   get_global_attributeappend)variabler   s     r9   r,   r,     s=    *?!2d   ""8,,,,,r;   c                      t          j        d          } | r| D ]}|                                 t          j        dg            d S )Nr   )r   r   r>   set_global_attribute)
collectionvs     r9   initialize_all_variablesr     sY    23LMMJ % 	% 	%A""$$$$%&?DDDDDr;   zkeras.utils.standardize_dtypezkeras.backend.standardize_dtypec                    | t          j                    S t          j                            | |           } t          | d          r| j        } nrt          | d          rKdt          |           v sdt          |           v r)t          |                               d          d         } nt          | d          r| j	        } | t          j
        vrt          d|            | S )	Nr   __str__torchz	jax.numpy.r   zInvalid dtype: )r   floatxr   PYTHON_DTYPES_MAPr(   hasattrr   r   splitr   ALLOWED_DTYPESr   r   s    r9   r   r     s     }}$((66Euf 
			"	" 3u::E

!:!:E

  %%b)	
	#	# F)))2522333Lr;   c                    t          | t                    s| t          d          t          | d          st          d|  d          t	          j                    dk    r.t          | t          j                  r|                                 } t          |           } t	          j                    dk    rt          t          d |                     } | D ]}|t	          j                    dk    rd	t          t          |                    v r;t          t          |                    s&t          d|  d
| dt          |           d          |dk     rt          d|  d          | S )Nz#Undefined shapes are not supported.__iter__zCannot convert 'z' to a shape.r
   r   c                 (    | t          |           nd S rC   )int)xs    r9   <lambda>z#standardize_shape.<locals>.<lambda>  s    amCFFF r;   jax_DimExprz#' to a shape. Found invalid entry 'z' of type 'z'. r   z2' to a shape. Negative dimensions are not allowed.)r   r.   r   r   r   backendtfTensorShapeas_listmapr   typeis_int_dtype)r/   es     r9   rA   rA     s   eU## 
=BCCCuj)) 	FDDDDEEE>|++%00 ( e~7"" cEEuMMNN  9>u$$s477||)C)CDGG$$ 	C5 C C()C C6:1ggC C C   q5575 7 7 7   
 Lr;   c                     t          |           t          |          k    rdS t          | |          D ]\  }}||	||k    r dS dS )z8Return whether a_shape == b_shape (allows None entries).FNT)r0   zip)a_shapeb_shapee1e2s       r9   rU   rU   2  sY    
7||s7||##ugw''  B>bnr554r;   zkeras.backend.is_float_dtypec                 t    t          |           } |                     d          p|                     d          S )Nfloatbfloatr   
startswithr   s    r9   r`   r`   <  s6    e$$EG$$B(8(8(B(BBr;   zkeras.backend.is_int_dtypec                 t    t          |           } |                     d          p|                     d          S )Nr   uintr  r   s    r9   r   r   B  s6    e$$EE"">e&6&6v&>&>>r;   c                  *    t          j        d          S NrF   )r   r   r   r;   r9   rD   rD   H  s    ,-=>>>r;   c                   *    e Zd ZdZd Zd Zd Zd ZdS )AutocastScopezContext manager that enables the autocasting of float variables.

    Under this context manager, float `KerasVariables`s will be cast to `dtype`
    (note that `dtype` must also be float).
    c                     |0t          |          }t          |          st          d|           || _        d | _        d S )Nzh`AutocastScope` can only be used with a floating-point target dtype, such as 'float16'. Received: dtype=)r   r`   r   r   original_scoper   s     r9   r:   zAutocastScope.__init__S  s`    %e,,E!%((  /',/ /  
 
"r;   c                     ddl m} | j        0t          |j                  r|                    || j                  S |S )Nr   )r   r   )r'   r   r   r`   cast)r2   r8   r   s      r9   rE   zAutocastScope.maybe_cast_  sH    %%%%%%:!nU[&A&A!<<TZ<888r;   c                 V    t                      | _        t          j        d|            d S r  )rD   r  r   r   rK   s    r9   	__enter__zAutocastScope.__enter__f  s*    022)*:DAAAAAr;   c                 :    t          j        d| j                   d S r  )r   r   r  )r2   argskwargss      r9   __exit__zAutocastScope.__exit__j  s    )*:D<OPPPPPr;   N)r   r   r   r   r:   rE   r  r  r   r;   r9   r
  r
  L  sb         
# 
# 
#  B B BQ Q Q Q Qr;   r
  )rL   rI   keras.src.api_exportr   keras.src.backendr   keras.src.backend.commonr   r   #keras.src.backend.common.name_scoper   (keras.src.backend.common.stateless_scoper   r	   keras.src.utils.module_utilsr
   r   keras.src.utils.namingr   r   r,   r   r   rA   rU   r`   r   rD   r
  r   r;   r9   <module>r     s       - - - - - - $ $ $ $ $ $ + + + + + + 1 1 1 1 1 1 < < < < < < H H H H H H G G G G G G 9 9 9 9 9 9 , , , , , ,XQ XQ XQ XQ XQ XQ XQ XQv- - -E E E $&GH   $" " "J   ,--C C .-C
 *++? ? ,+?
? ? ?Q Q Q Q Q Q Q Q Q Qr;   