o
    2h%]                     @   s   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 dZdd Zdd Zeddgdd Zdd Zdd Zeddd Zeddd Zd d! ZG d"d# d#ZdS )$    Nbackend)keras_export)config)dtypes)global_state)current_path)get_stateless_scope)in_stateless_scope)
tensorflow)	auto_namec                   @   s~  e Zd ZdZ							dddZdd	 Zd
d Zdd Zdd Ze	dd Z
e	dd Ze	dd Zdd Zdd Zdd Ze	dd Ze	dd Ze	d d! Ze	d"d# Zejd$d# Ze	d%d& Ze	d'd( Ze	d)d* Zejd+d* Ze	d,d- Zejd.d- Ze	d/d0 Zejd1d0 Zd2d3 Zd4d5 Zd6d7 Zdd8d9Zd:d; Zd<d= Zd>d? Z dd@dAZ!dBdC Z"dDdE Z#dFdG Z$dHdI Z%dJdK Z&dLdM Z'dNdO Z(dPdQ Z)dRdS Z*dTdU Z+dVdW Z,dXdY Z-dZd[ Z.d\d] Z/d^d_ Z0d`da Z1dbdc Z2ddde Z3dfdg Z4dhdi Z5djdk Z6dldm Z7dndo Z8dpdq Z9drds Z:dtdu Z;dvdw Z<dxdy Z=dzd{ Z>d|d} Z?d~d Z@dd ZAdd ZBdddZCdS )Variablea  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.

    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).
        kwargs: Additional backend-specific keyword arguments.

    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noneautoc	                 K   s  ~	|pt | jj}t|trd|v rtd| |dvr$td| |d u r*d}|dvr5td| |d u r;d}|| _t }
|
rLt d | | _n|| _d | _	d | _
d | _d | _t|| _t|| _|| _|| _d| _t|tr~d	d
lm} ||}t|r|d u rtd| d| n| j||d}|d u r|j}t|| _t rt|rd | _|| _
| || _	t|  n!tdt|r| || _	| | n|  | | | jj!| _	t"| j	| _#d S )N/zRArgument `name` must be a string and cannot contain character `/`. Received: name=)Nr   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_writer   zInvalid 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_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initializerr5   r   	trainableautocastaggregationsynchronizationnamekwargsparent_pathr    rA   ]/var/www/html/chatgem/venv/lib/python3.10/site-packages/keras/src/backend/common/variables.py__init__\   s   






zVariable.__init__c                 C   sL   | j d urt rd S td| j dt rtd| | j d | _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.)r0   r   is_nnx_enabledr   pathr
   r3   r!   r8   rA   rA   rB   _deferred_initialize   s   

zVariable._deferred_initializec                 C   s,   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   rE   )r8   r5   rA   rA   rB   r1      s   zVariable._validate_shapec                 C   s"   t  }| jr|d ur||S |S N)get_autocast_scoper&   
maybe_cast)r8   valueautocast_scoperA   rA   rB   _maybe_autocast   s   
zVariable._maybe_autocastc                 C   s
   t | S rJ   )nparrayrF   rA   rA   rB   numpy      
zVariable.numpyc                 C      | j S )z+The strategy for aggregating this variable.)r'   rF   rA   rA   rB   r<         zVariable.aggregationc                 C   rT   )z-The strategy for synchronizing this variable.)r(   rF   rA   rA   rB   r=      rU   zVariable.synchronizationc                 C   sV   t  rt }|| }|dur| |S | jdu r%| | j| j| jdS | | jS )zBThe current value of the variable (numpy array or backend tensor).Nr   )r
   r	   get_current_valuerO   r0   r!   r    r/   )r8   scoperM   rA   rA   rB   rM     s   


zVariable.valuec                 C   sj   | j || jd}t|j| jstd| jj d|j d|  t r.t }|| |f |S | 	| |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: )
r-   r   shape_equalr5   r   rM   r
   r	   
add_update_direct_assign)r8   rM   rW   rA   rA   rB   assign  s"   
zVariable.assignc                 C   s   |  | | S rJ   r[   r8   rM   rA   rA   rB   
assign_add(     zVariable.assign_addc                 C   s   |  | | S rJ   r\   r]   rA   rA   rB   
assign_sub+  r_   zVariable.assign_subc                 C   s6   t  }| jr|durt| jr|j}n| j}t|S )zThe data type of the variable.N)rK   r&   is_float_dtyper/   r   r   r.   )r8   rN   r   rA   rA   rB   r   .  s   
zVariable.dtypec                 C   rT   )zThe shape of the variable.)r    rF   rA   rA   rB   r5   <  rU   zVariable.shapec                 C   rT   )z)The number of dimensions of the variable.)r7   rF   rA   rA   rB   ndimA  rU   zVariable.ndimc                 C   rT   )z"Whether the variable is trainable.)r%   rF   rA   rA   rB   r:   F  rU   zVariable.trainablec                 C   s   t || _d S rJ   )r$   r%   r]   rA   rA   rB   r:   K  s   c                 C   rT   )zThe name of the variable.)r   rF   rA   rA   rB   r>   O  rU   zVariable.namec                 C   rT   )z9The path of the variable within the Keras model or layer.)r   rF   rA   rA   rB   rE   T  rU   zVariable.pathc                 C   rT   )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)   rF   rA   rA   rB   overwrite_with_gradientY  s   z Variable.overwrite_with_gradientc                 C   s"   t |tstd| || _d S )Nz7`overwrite_with_gradient` must be a boolean. Received: )r   r$   	TypeErrorr)   r]   rA   rA   rB   rc   f  s   

c                 C   rT   rJ   )r"   rF   rA   rA   rB   regularizero     zVariable.regularizerc                 C   6   ddl m} |d ur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.regularizersrh   r   r   r"   )r8   rM   rh   rA   rA   rB   re   s     
c                 C   rT   rJ   )r#   rF   rA   rA   rB   
constraint  rf   zVariable.constraintc                 C   rg   )Nr   )
ConstraintzInvalid value for attribute `constraint`. Expected an instance of `keras.constraints.Constraint`, or `None`. Received: constraint=)keras.src.constraintsrl   r   r   r#   )r8   rM   rl   rA   rA   rB   rk     rj   c                 C   s^   d }t | dr| jd urtj| j}|d urd| nd}d| j d| j d| j | dS )Nr0   z, value= z<Variable path=z, shape=z, dtype=>)hasattrr0   r   coreconvert_to_numpyrE   r5   r   )r8   rM   	value_strrA   rA   rB   __repr__  s   zVariable.__repr__c                 C      t rJ   NotImplementedErrorr]   rA   rA   rB   r4        zVariable._initializec                 C   s$   |  || j| jd}| | d S )Nr   )r-   r    r/   r4   )r8   r9   rM   rA   rA   rB   r3     s   z%Variable._initialize_with_initializerc                 C   ru   rJ   rv   )r8   rM   r   rA   rA   rB   r-     rx   zVariable._convert_to_tensorc                 C   s   | j |S rJ   )rM   __getitem__)r8   idxrA   rA   rB   ry     s   zVariable.__getitem__c                 C   $   | j dkrtd| j t| jS Nr   zBOnly scalar arrays can be converted to Python scalars. Got: shape=)rb   rd   r5   intrM   rF   rA   rA   rB   __int__     

zVariable.__int__c                 C   r{   r|   )rb   rd   r5   floatrM   rF   rA   rA   rB   	__float__  r   zVariable.__float__c                 C   s   t | j|S rJ   )rP   asarrayrM   	__array__r8   r   rA   rA   rB   r     s   zVariable.__array__c                 C   s   t d)Nz-A Keras Variable cannot be used as a boolean.)rd   rF   rA   rA   rB   __bool__  s   zVariable.__bool__c                 C   
   | j  S rJ   )rM   __neg__rF   rA   rA   rB   r     rS   zVariable.__neg__c                 C   rT   rJ   )rM   rF   rA   rA   rB   __pos__  s   zVariable.__pos__c                 C   r   rJ   )rM   __abs__rF   rA   rA   rB   r     rS   zVariable.__abs__c                 C   r   rJ   )rM   
__invert__rF   rA   rA   rB   r     rS   zVariable.__invert__c                 C      t j| j|S rJ   )r   rR   equalrM   r8   otherrA   rA   rB   __eq__     zVariable.__eq__c                 C   r   rJ   )r   rR   	not_equalrM   r   rA   rA   rB   __ne__  r   zVariable.__ne__c                 C   r   rJ   )r   rR   lessrM   r   rA   rA   rB   __lt__  r   zVariable.__lt__c                 C   r   rJ   )r   rR   
less_equalrM   r   rA   rA   rB   __le__  r   zVariable.__le__c                 C   r   rJ   )r   rR   greaterrM   r   rA   rA   rB   __gt__  r   zVariable.__gt__c                 C   r   rJ   )r   rR   greater_equalrM   r   rA   rA   rB   __ge__  r   zVariable.__ge__c                 C   r   rJ   r   rR   addrM   r   rA   rA   rB   __add__  r   zVariable.__add__c                 C      t j|| jS rJ   r   r   rA   rA   rB   __radd__  r   zVariable.__radd__c                 C   r   rJ   r   rR   subtractrM   r   rA   rA   rB   __sub__  r   zVariable.__sub__c                 C   r   rJ   r   r   rA   rA   rB   __rsub__  r   zVariable.__rsub__c                 C   r   rJ   r   rR   multiplyrM   r   rA   rA   rB   __mul__  r   zVariable.__mul__c                 C   r   rJ   r   r   rA   rA   rB   __rmul__  r   zVariable.__rmul__c                 C   r   rJ   r   rR   true_dividerM   r   rA   rA   rB   __truediv__  r   zVariable.__truediv__c                 C   r   rJ   r   r   rA   rA   rB   __rtruediv__  r   zVariable.__rtruediv__c                 C   r   rJ   r   rR   floor_dividerM   r   rA   rA   rB   __floordiv__  r   zVariable.__floordiv__c                 C   r   rJ   r   r   rA   rA   rB   __rfloordiv__  r   zVariable.__rfloordiv__c                 C   r   rJ   r   rR   modrM   r   rA   rA   rB   __mod__  r   zVariable.__mod__c                 C   r   rJ   r   r   rA   rA   rB   __rmod__  r   zVariable.__rmod__c                 C   r   rJ   r   rR   powerrM   r   rA   rA   rB   __pow__  r   zVariable.__pow__c                 C   r   rJ   r   r   rA   rA   rB   __rpow__  r   zVariable.__rpow__c                 C   r   rJ   r   rR   matmulrM   r   rA   rA   rB   
__matmul__
  r   zVariable.__matmul__c                 C   r   rJ   r   r   rA   rA   rB   __rmatmul__  r   zVariable.__rmatmul__c                 C   r   rJ   r   rR   logical_andrM   r   rA   rA   rB   __and__  r   zVariable.__and__c                 C   r   rJ   r   r   rA   rA   rB   __rand__  r   zVariable.__rand__c                 C   r   rJ   r   rR   
logical_orrM   r   rA   rA   rB   __or__  r   zVariable.__or__c                 C   r   rJ   r   r   rA   rA   rB   __ror__  r   zVariable.__ror__c                 C   r   rJ   r   rR   logical_xorrM   r   rA   rA   rB   __xor__  r   zVariable.__xor__c                 C   r   rJ   r   r   rA   rA   rB   __rxor__  r   zVariable.__rxor__c                 C   s   |pd}t jj| j|dS )Nr   )decimals)r   rR   roundrM   )r8   ndigitsr   rA   rA   rB   	__round__"  s   zVariable.__round__)NNTTr   r   NrJ   )Dr   
__module____qualname____doc__rC   rG   r1   rO   rR   propertyr<   r=   rM   r[   r^   r`   r   r5   rb   r:   setterr>   rE   rc   re   rk   rt   r4   r3   r-   ry   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   rA   rA   rA   rB   r      s    O
x



















r   c                 C   s   t jdg dd}||  d S )Nuninitialized_variablesT)set_to_default)r   get_global_attributeappend)variabler   rA   rA   rB   r2   '  s   r2   c                  C   s0   t d} | r| D ]}|  q	t dg  d S )Nr   )r   r   rG   set_global_attribute)
collectionvrA   rA   rB   initialize_all_variables.  s
   

r   zkeras.utils.standardize_dtypezkeras.backend.standardize_dtypec                 C   s   | d u rt  S tj| | } t| dr| j} n#t| dr!| j} nt| dr;dt| v s2dt| v r;t| 	dd } | tj
vrGtd|  | S )	Nr>   r   __str__torchz	jax.numpy.zInvalid dtype: )r   floatxr   PYTHON_DTYPES_MAPr+   rp   r>   r   r   splitALLOWED_DTYPESr   r   rA   rA   rB   r.   6  s   



r.   c              	   C   s   t | ts.| d u rtdt| dstd|  dt dkr*t | tjr*|  } t| } t dkr=tt	dd | } | D ]8}|d u rFq?t d	krUd
t
t|v rUq?tt|sktd|  d| dt| d|dk rwtd|  dq?| S )Nz#Undefined shapes are not supported.__iter__zCannot convert 'z' to a shape.r   r   c                 S   s   | d urt | S d S rJ   )r}   )xrA   rA   rB   <lambda>[  s    z#standardize_shape.<locals>.<lambda>jax_DimExprz#' to a shape. Found invalid entry 'z' of type 'z'. r   z2' to a shape. Negative dimensions are not allowed.)r   tupler   rp   r   r   tfTensorShapeas_listmapr   typeis_int_dtype)r5   erA   rA   rB   rI   K  s<   


rI   c                 C   sJ   t | t |kr
dS t| |D ]\}}|dur"|dur"||kr" dS qdS )z8Return whether a_shape == b_shape (allows None entries).FNT)r6   zip)a_shapeb_shapee1e2rA   rA   rB   rX   p  s   rX   zkeras.backend.is_float_dtypec                 C      t | } | dp| dS )Nr   bfloatr.   
startswithr   rA   rA   rB   ra   z     ra   zkeras.backend.is_int_dtypec                 C   r   )Nr}   uintr   r   rA   rA   rB   r     r   r   c                   C   s
   t dS NrN   )r   r   rA   rA   rA   rB   rK     rS   rK   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )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                 C   s6   |d urt |}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.   ra   r   r   original_scoper   rA   rA   rB   rC     s   
zAutocastScope.__init__c                 C   s4   ddl m} | jd urt|jr|j|| jdS |S )Nr   r   r   )r*   r   r   ra   cast)r8   rM   r   rA   rA   rB   rL     s   zAutocastScope.maybe_castc                 C   s   t  | _td|  d S r   )rK   r   r   r   rF   rA   rA   rB   	__enter__  s   zAutocastScope.__enter__c                 O   s   t d| j d S r   )r   r   r   )r8   argsr?   rA   rA   rB   __exit__  s   zAutocastScope.__exit__N)r   r   r   r   rC   rL   r   r   rA   rA   rA   rB   r     s    r   )rR   rP   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   r   keras.src.utils.namingr   r   r2   r   r.   rI   rX   ra   r   rK   r   rA   rA   rA   rB   <module>   s<        
%


