
    ij`                     "   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  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y)    Nbackend)keras_export)config)dtypes)global_state)current_path)get_stateless_scope)in_stateless_scope)
tensorflow)	auto_namec                      e Zd ZdZ	 	 	 	 	 	 	 	 dEdZd Zd Zd Zd Ze	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	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d ZdFdZd Zd  Zd! Z dFd"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 Z0d2 Z1d3 Z2d4 Z3d5 Z4d6 Z5d7 Z6d8 Z7d9 Z8d: Z9d; Z:d< Z;d= Z<d> Z=d? Z>d@ Z?dA Z@dB ZAdC ZBdFdDZCy)GVariablear  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`.
        autocast: Optional. Boolean indicating whether the variable supports
            autocasting. If `True`, the layer may first convert the variable
            to the compute data type when accessed. Defaults to `True`.
        aggregation: Optional string, one of `None`, `"none"`, `"mean"`,
            `"sum"` or `"only_first_replica"` specifying how a distributed
            variable will be aggregated. This serves as a semantic annotation,
            to be taken into account by downstream backends or users. Defaults
            to `"none"`.
        name: Optional. A unique name for the variable. Automatically generated
            if not set.
        layout: Optional. Sharding layout for the variable. Can be a
            `keras.distribution.TensorLayout` or a backend-specific layout.
        kwargs: Additional backend-specific keyword arguments.

    Attributes:
        shape: The shape of the variable (tuple of integers).
        ndim: The number of dimensions of the variable (integer).
        dtype: The data type of the variable (string).
        trainable: Whether the variable is trainable (boolean).
        autocast: Whether the variable supports autocasting (boolean).
        aggregation: How a distributed variable will be aggregated (string).
        value: The current value of the variable (NumPy array or tensor).
        name: The name of the variable (string).
        path: The path of the variable within the Keras model or layer (string).

    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
    )
    ```
    Nc
                    |xs t        | j                  j                        }t        |t              rd|v rt        d|       |dvrt        d|       |d}|dvrt        d|       |d}|| _        t               }|r| d| | _        n|| _        d | _	        d | _
        d | _        d | _        t        |      | _        t        |      | _        || _        || _        |	| _        d| _        t        |t              rd	d
lm} |j-                  |      }t/        |      r|2t        d| d|       | j1                  ||      }||j2                  }t5        |      | _        t9               rFt/        |      r0d | _        || _
        | j=                  |      | _	        t?        |        nyt        d      t/        |      r(| j=                  |      | _	        | jA                  |       n;| jC                  |       | j=                  | j:                  jD                        | _	        tG        | j                        | _$        y )N/zRArgument `name` must be a string and cannot contain character `/`. Received: name=)Nnonemeansumonly_first_replicazInvalid value for argument `aggregation`. Expected one of `None`, `'none'`, `'mean'`, `'sum'`, `'only_first_replica'`. Received: aggregation=r   )Nr   on_readon_writeautozInvalid value for argument `synchronization`. Expected one of `None`, `'none'`, `'on_read'`, `'on_write'`, `'auto'`. Received: synchronization=Fr   )initializersznWhen creating a Variable from an initializer, the `shape` argument should be specified. Received: initializer=z and shape=dtypead  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).)%r   	__class____name__
isinstancestr
ValueError_namer	   _path_shape_initializer_regularizer_constraintbool
_trainable	_autocast_aggregation_synchronization_layout_overwrite_with_gradient	keras.srcr   getcallable_convert_to_tensorr   standardize_dtype_dtyper   _value_validate_shaperegister_uninitialized_variable_initialize_with_initializer_initializeshapelen_ndim)selfinitializerr9   r   	trainableautocastaggregationsynchronizationnamelayoutkwargsparent_pathr   s                w/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/backend/common/variables.py__init__zVariable.__init__^   sq    9y!8!89$$t""&) 
  
 
 ) *57   K #
 
 - .=,=?  "$O
"n'=$0DJDJ  y/h' /
 ).%k3'.&**;7KK } --8M :!!&)  11+U1KK}#))'.$"$/!"2259/5 C $ $"225911+>  -"224;;3D3DE%
    c                     | j                   .t        j                         ry t        d| j                   d      t               rt        d      | j                  | j                         d | _        y )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.)r4   r   is_nnx_enabledr    pathr   r7   r$   r<   s    rF   _deferred_initializezVariable._deferred_initialize   sm    ;;" $$&y3KLMMC  	))$*;*;< rH   c                 \    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    rK   )r<   r9   s     rF   r5   zVariable._validate_shape   sD    !%(5=3DII;aA 
 rH   c                 X    t               }| j                  r||j                  |      S |S N)get_autocast_scoper)   
maybe_cast)r<   valueautocast_scopes      rF   _maybe_autocastzVariable._maybe_autocast   s,    +->>n8!,,U33rH   c                 ,    t        j                  |       S rR   )nparrayrL   s    rF   numpyzVariable.numpy   s    xx~rH   c                     | j                   S )z+The strategy for aggregating this variable.)r*   rL   s    rF   r@   zVariable.aggregation   s        rH   c                     | j                   S )z-The strategy for synchronizing this variable.)r+   rL   s    rF   rA   zVariable.synchronization  s     $$$rH   c                 ,   t               r.t               }|j                  |       }|| j                  |      S | j                  6| j                  | j                  | j                  | j                              S | j                  | j                        S )zBThe current value of the variable (numpy array or backend tensor).r   )r   r
   get_current_valuerW   r4   r$   r#   r3   )r<   scoperU   s      rF   rU   zVariable.value  s     ')E++D1E ++E22;;
 ''!!$++T[[!A  ##DKK00rH   c                 D   | j                  || j                        }t        |j                  | j                        s(t	        d| j                   d|j                   d|        t               rt               }|j                  | |f       |S | j                  |       |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: )	r1   r3   shape_equalr9   r    r   r
   
add_update_direct_assign)r<   rU   r`   s      rF   assignzVariable.assign  s    ''T[['A5;;

3" #'** .)). 6$$(6+  ')EdE]+  &rH   c                 *    | j                  | |z         S rR   re   r<   rU   s     rF   
assign_addzVariable.assign_add,      {{4%<((rH   c                 *    | j                  | |z
        S rR   rg   rh   s     rF   
assign_subzVariable.assign_sub/  rj   rH   c                     t               }| j                  r$|"t        | j                        r|j                  }n| j                  }t        j                  |      S )zThe data type of the variable.)rS   r)   is_float_dtyper3   r   r   r2   )r<   rV   r   s      rF   r   zVariable.dtype2  sJ     ,-NN*t{{+"((EKKE((//rH   c                     | j                   S )zThe shape of the variable.)r#   rL   s    rF   r9   zVariable.shape@  s     {{rH   c                     | j                   S )z)The number of dimensions of the variable.)r;   rL   s    rF   ndimzVariable.ndimE       zzrH   c                     | j                   S )z"Whether the variable is trainable.)r(   rL   s    rF   r>   zVariable.trainableJ  s     rH   c                 $    t        |      | _        y rR   )r'   r(   rh   s     rF   r>   zVariable.trainableO  s    u+rH   c                     | j                   S )zThe name of the variable.)r!   rL   s    rF   rB   zVariable.nameS  rr   rH   c                     | j                   S )z9The path of the variable within the Keras model or layer.)r"   rL   s    rF   rK   zVariable.pathX  rr   rH   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-   rL   s    rF   overwrite_with_gradientz Variable.overwrite_with_gradient]  s     ,,,rH   c                 N    t        |t              st        d|       || _        y )Nz7`overwrite_with_gradient` must be a boolean. Received: )r   r'   	TypeErrorr-   rh   s     rF   rx   z Variable.overwrite_with_gradientj  s2    %&"G%  ).%rH   c                     | j                   S rR   )r%   rL   s    rF   regularizerzVariable.regularizers  s       rH   c                 H    |t        |      st        d|       || _        y )NzInvalid value for attribute `regularizer`. Expected a callable (such as a `keras.regularizers.Regularizer` instance) or `None`. Received: regularizer=)r0   r    r%   rh   s     rF   r|   zVariable.regularizerw  s5    Xe_>>CWF 
 "rH   c                     | j                   S rR   )r&   rL   s    rF   
constraintzVariable.constraint  s    rH   c                 H    |t        |      st        d|       || _        y )NzInvalid value for attribute `constraint`. Expected a callable (such as a `keras.constraints.Constraint` instance) or `None`. Received: constraint=)r0   r    r&   rh   s     rF   r   zVariable.constraint  s4    Xe_338'; 
 !rH   c                    d }t        | d      r6| j                  *	 t        j                  j	                  | j                        }|d| nd}d| j
                   d| j                   d| j                   | dS #  Y 9xY w)Nr4   z, value= z<Variable path=z, shape=z, dtype=>)hasattrr4   r   coreconvert_to_numpyrK   r9   r   )r<   rU   	value_strs      rF   __repr__zVariable.__repr__  s    4"t{{'>55dkkB +0*;hug&	dii[ =ZZL1.	
	s   )A: :A>c                     t         rR   NotImplementedErrorrh   s     rF   r8   zVariable._initialize      !!rH   c                     | j                   || j                  | j                              }| j                  |       y )Nr   )r1   r#   r3   r8   )r<   r=   rU   s      rF   r7   z%Variable._initialize_with_initializer  s4    ''4;;7
 	rH   c                     t         rR   r   )r<   rU   r   s      rF   r1   zVariable._convert_to_tensor  r   rH   c                 8    | j                   j                  |      S rR   )rU   __getitem__)r<   idxs     rF   r   zVariable.__getitem__  s    zz%%c**rH   c                 z    | j                   dkD  rt        d| j                         t        | j                        S Nr   zBOnly scalar arrays can be converted to Python scalars. Got: shape=)rq   rz   r9   intrU   rL   s    rF   __int__zVariable.__int__  s=    99q="jj\+  4::rH   c                 z    | j                   dkD  rt        d| j                         t        | j                        S r   )rq   rz   r9   floatrU   rL   s    rF   	__float__zVariable.__float__  s>    99q="jj\+  TZZ  rH   c                 ^    t        j                  | j                  j                  |            S rR   )rY   asarrayrU   	__array__r<   r   s     rF   r   zVariable.__array__  s"    
 zz$**..u566rH   c                     t        d      )Nz-A Keras Variable cannot be used as a boolean.)rz   rL   s    rF   __bool__zVariable.__bool__  s    GHHrH   c                 6    | j                   j                         S rR   )rU   __neg__rL   s    rF   r   zVariable.__neg__      zz!!##rH   c                     | j                   S rR   )rU   rL   s    rF   __pos__zVariable.__pos__  s    zzrH   c                 6    | j                   j                         S rR   )rU   __abs__rL   s    rF   r   zVariable.__abs__  r   rH   c                 6    | j                   j                         S rR   )rU   
__invert__rL   s    rF   r   zVariable.__invert__  s    zz$$&&rH   c                 V    t         j                  j                  | j                  |      S rR   )r   r[   equalrU   r<   others     rF   __eq__zVariable.__eq__      }}""4::u55rH   c                 V    t         j                  j                  | j                  |      S rR   )r   r[   	not_equalrU   r   s     rF   __ne__zVariable.__ne__  s    }}&&tzz599rH   c                 V    t         j                  j                  | j                  |      S rR   )r   r[   lessrU   r   s     rF   __lt__zVariable.__lt__  s    }}!!$**e44rH   c                 V    t         j                  j                  | j                  |      S rR   )r   r[   
less_equalrU   r   s     rF   __le__zVariable.__le__      }}''

E::rH   c                 V    t         j                  j                  | j                  |      S rR   )r   r[   greaterrU   r   s     rF   __gt__zVariable.__gt__  s    }}$$TZZ77rH   c                 V    t         j                  j                  | j                  |      S rR   )r   r[   greater_equalrU   r   s     rF   __ge__zVariable.__ge__  s    }}**4::u==rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   addrU   r   s     rF   __add__zVariable.__add__      }}  U33rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __radd__zVariable.__radd__      }}  

33rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   subtractrU   r   s     rF   __sub__zVariable.__sub__      }}%%djj%88rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rsub__zVariable.__rsub__      }}%%eTZZ88rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   multiplyrU   r   s     rF   __mul__zVariable.__mul__  r   rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rmul__zVariable.__rmul__  r   rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   true_dividerU   r   s     rF   __truediv__zVariable.__truediv__      }}((U;;rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rtruediv__zVariable.__rtruediv__      }}((

;;rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   floor_dividerU   r   s     rF   __floordiv__zVariable.__floordiv__  s    }}))$**e<<rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rfloordiv__zVariable.__rfloordiv__  s    }}))%<<rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   modrU   r   s     rF   __mod__zVariable.__mod__  r   rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rmod__zVariable.__rmod__  r   rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   powerrU   r   s     rF   __pow__zVariable.__pow__  r   rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rpow__zVariable.__rpow__  s    }}""5$**55rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   matmulrU   r   s     rF   
__matmul__zVariable.__matmul__  s    }}##DJJ66rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rmatmul__zVariable.__rmatmul__  s    }}##E4::66rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   logical_andrU   r   s     rF   __and__zVariable.__and__  r   rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __rand__zVariable.__rand__  r   rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   
logical_orrU   r   s     rF   __or__zVariable.__or__  r   rH   c                 V    t         j                  j                  || j                        S rR   r   r   s     rF   __ror__zVariable.__ror__  s    }}''tzz::rH   c                 V    t         j                  j                  | j                  |      S rR   r   r[   logical_xorrU   r   s     rF   __xor__zVariable.__xor__   r   rH   c                 V    t         j                  j                  || j                        S rR   r  r   s     rF   __rxor__zVariable.__rxor__#  r   rH   c                 d    |xs d}t         j                  j                  | j                  |      S )Nr   )decimals)r   r[   roundrU   )r<   ndigitsr  s      rF   	__round__zVariable.__round__&  s)    <a}}""4::"AArH   )NNTTr   r   NNrR   )Dr   
__module____qualname____doc__rG   rM   r5   rW   r[   propertyr@   rA   rU   re   ri   rl   r   r9   rq   r>   setterrB   rK   rx   r|   r   r   r8   r7   r1   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  r  r
   rH   rF   r   r      sy   Lb x&t!& ! ! % % 1 1"$)) 0 0       & &     
- 
- ##. $. ! ! " "     ! !
" "+!7I$$'6:5;8>449999<<==446677<<;;<<BrH   r   c                 V    t        j                  dg d      }|j                  |        y )Nuninitialized_variablesT)set_to_default)r   get_global_attributeappend)variabler  s     rF   r6   r6   +  s*    *??!2d ""8,rH   c                      t        j                  d      } | r| D ]  }|j                           t        j                  dg        y )Nr  )r   r  rM   set_global_attribute)
collectionvs     rF   initialize_all_variablesr  2  sB    223LMJ 	%A""$	%%%&?DrH   zkeras.utils.standardize_dtypezkeras.backend.standardize_dtypec                    | t        j                         S t        j                  j	                  | |       } t        | d      r| j                  } n\t        | d      r| j                  } nCt        | d      r7dt        |       v sdt        |       v rt        |       j                  d      d   } | t        j                  vrt        d|        | S )	NrB   r   __str__torchz	jax.numpy.zInvalid dtype: )r   floatxr   PYTHON_DTYPES_MAPr/   r   rB   r   r   splitALLOWED_DTYPESr    r   s    rF   r2   r2   :  s     }}}$$((6Euf

	
	#			"3u:E
!:E
  %b)F)))?5'233LrH   c                 2   t        | t              si| t        d      t        | d      st        d|  d      t	        j
                         dk(  r*t        | t        j                        r| j                         } t	        j
                         dk(  rddl	m
 t        fd	| D              } t	        j
                         d
k(  rdd lt        fd| D              } g }| D ]{  }||j                  |       t        |t        t        f      rt        d|  d| dt        |       d      	 t!        |      }|dk  rt        d|  d      |j                  |       } t        |      S # t"        $ r$}t        d|  d| dt        |       d      |d }~ww xY w)Nz#Undefined shapes are not supported.__iter__zCannot convert 'z' to a shape.r   jaxr   )exportc              3   H   K   | ]  }j                  |      rd n|  y wrR   )is_symbolic_dim).0d
jax_exports     rF   	<genexpr>z$standardize_shape.<locals>.<genexpr>_  s(      
=>J..q1Dq8
s   "r  c              3   R   K   | ]  }t        |j                        rd n|   y wrR   )r   SymInt)r+  r,  r  s     rF   r.  z$standardize_shape.<locals>.<genexpr>h  s#     PQjELL9dq@Ps   $'z'' to a shape. Found invalid dimension 'z' of type 'z'. z2' to a shape. Negative dimensions are not allowed.)r   tupler    r   r   r   tfTensorShapeas_listr'  r(  r  r  r   r   typer   	Exception)r9   standardized_shaper,  er-  r  s       @@rF   rP   rP   O  s   eU#=BCCuj)/wmDEE>>|+%0 ~~5 , 
BG
 
 ~~7" 	P%PP  %9%%a( a#u&"5' *,,-3k$q'#G 
	AA q5"5' *7 7  	!!!$3%8 #$$  	"5' *,,-3k$q'#G 	s   ,E))	F2FFc                 v    t        |       t        |      k7  ryt        | |      D ]  \  }}|	|||k7  s y y)z8Return whether a_shape == b_shape (allows None entries).FT)r:   zip)a_shapeb_shapee1e2s       rF   rb   rb     sF    
7|s7|#gw' B>bnr rH   zkeras.backend.is_float_dtypec                 `    t        |       } | j                  d      xs | j                  d      S )Nr   bfloatr2   
startswithr   s    rF   rn   rn     s-    e$EG$B(8(8(BBrH   zkeras.backend.is_int_dtypec                 `    t        |       } | j                  d      xs | j                  d      S )Nr   uintrA  r   s    rF   is_int_dtyperE    s-    e$EE">e&6&6v&>>rH   c                  ,    t        j                  d      S NrV   )r   r  r  rH   rF   rS   rS     s    ,,-=>>rH   c                   (    e Zd ZdZd Zd Zd Zd Zy)AutocastScopezContext manager that enables the autocasting of float variables.

    Under this context manager, float `Variables`s will be cast to `dtype`
    (note that `dtype` must also be float).
    c                 l    |$t        |      }t        |      st        d|       || _        d | _        y )Nzh`AutocastScope` can only be used with a floating-point target dtype, such as 'float16'. Received: dtype=)r2   rn   r    r   original_scoper   s     rF   rG   zAutocastScope.__init__  sG    %e,E!%( '',g/ 
 
"rH   c                     ddl m} | j                  3t        |j                        r |j                  || j                        S |S )Nr   r   r   )r.   r   r   rn   cast)r<   rU   r   s      rF   rT   zAutocastScope.maybe_cast  s6    %::!nU[[&A7<<TZZ88rH   c                 N    t               | _        t        j                  d|        y rG  )rS   rK  r   r  rL   s    rF   	__enter__zAutocastScope.__enter__  s    02))*:DArH   c                 D    t        j                  d| j                         y rG  )r   r  rK  )r<   argsrD   s      rF   __exit__zAutocastScope.__exit__  s    ))*:D<O<OPrH   N)r   r  r  r  rG   rT   rO  rR  r  rH   rF   rI  rI    s    
#BQrH   rI  )r[   rY   r.   r   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   r2  keras.src.utils.namingr   r   r6   r  r2   rP   rb   rn   rE  rS   rI  r  rH   rF   <module>rZ     s      - $ + 1 < H G 9 ,YB YBx-E $&GH$9%x ,-C .C
 *+? ,?
?Q QrH   