
    PiR2                        d dl mZ d dlZd dlZd dlmZ d dlmZ	 d dl
mZmZmZmZ ej                            dd          Z G d d          Z	 	 	 	 d*deeej        f         d	ee         d
ee         deej        j                 dee         f
dZej        j        j        d             Z G d dej                  Z	 	 	 	 	 	 	 	 	 	 d+dededededededee         dededej        j        d	ee         defdZ G d  d!ej                  Z	 	 	 d,d"ededej        j        d	ee         def
d#Z  G d$ d%ej                  Z!	 	 d-d"ed'ed(ed	ee         def
d)Z"dS ).    N)partial)CallableUnionOptionalAnyz
flax.linennnc                       e Zd Z G d dej        j        j                  Z G d dej        j        j                  Z G d dej        j	                  Z
dS )ParamFactoryc                       e Zd Zd Zd ZdS )ParamFactory.Concretec                    || _         || _        || _        |t          |d          r|j        }nd}|| _        || _        |dk    r|t          d          n*|dk    r|t          d          nt          d|           || _        d S )Ndtypefloat32paramz/col is not accepted for flax.linen.Module.paramvariablez4col must be specified for flax.linen.Module.variablez)Unknown tensor factory flax.linen.Module.)modulenameinithasattrr   col
ValueError
param_type)selfr   r   r   r   r   r   s          `/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/einx/nn/flax.py__init__zParamFactory.Concrete.__init__   s     DKDIDI}67++ &"LEE%EDJDHW$$?$%VWWW #z));$%[\\\  !!YZ!Y!YZZZ(DOOO    c                 ~    | j         t                              | j        | j        | j        | j        | j                  fS N)r   r
   CacheKeyr   r   r   r   r   r   s    r   to_value_and_keyz&ParamFactory.Concrete.to_value_and_key%   s8    ; 5 5	49dj$(DO! !  r   N)__name__
__module____qualname__r   r!    r   r   Concreter      s2        	) 	) 	)0	 	 	 	 	r   r&   c                   &    e Zd Zd Zd Zd Zd ZdS )ParamFactory.CacheKeyc                 L    || _         || _        || _        || _        || _        d S r   r   r   r   r   r   r   r   r   r   r   r   s         r   r   zParamFactory.CacheKey.__init__+   )    DIDIDJDH(DOOOr   c                 \    t          | j        | j        | j        | j        | j        f          S r   )hashr   r   r   r   r   r    s    r   __hash__zParamFactory.CacheKey.__hash__2   s%    DItz48T_UVVVr   c                     t          |t          j                  oO| j        |j        k    o?| j        |j        k    o/| j        |j        k    o| j        |j        k    o| j        |j        k    S r   )
isinstancer
   r   r   r   r   r   r   )r   others     r   __eq__zParamFactory.CacheKey.__eq__5   ss    5,"788 8I+8I+8 J%+-8 H	)	8
 Ou'77r   c                 x    t                               | j        | j        | j        | j        | j                  }||fS r   )r
   Tracerr   r   r   r   r   )r   backendvirtual_argxs       r   	to_tracerzParamFactory.CacheKey.to_tracer?   s2    ##DIty$*dhPTP_``Aa4Kr   N)r"   r#   r$   r   r/   r3   r9   r%   r   r   r   r(   *   sS        	) 	) 	)	W 	W 	W	 	 		 	 	 	 	r   r   c                       e Zd Zd Zd ZdS )ParamFactory.Tracerc                 L    || _         || _        || _        || _        || _        d S r   r*   r+   s         r   r   zParamFactory.Tracer.__init__D   r,   r   c           	      0   | j         | j         n|                    dd           }| j        | j        n|                    dd           }| j        | j        n|                    dd           }| j        }|t          d          |t          d          t          |t                    r|dk    s|dk    r!t          j	        
                    d	          }n|d
k    rt          j	                                        }n|dk    rt          j	                                        }n|dk    r4t          j	                            |d         |d         |d                   }nPt          d| d          t          |t          t          f          r!t          j	                            ||          }| j        dk    rIt$          j                            | j        ||||gt$          j                            |                    }n| j        dk    sJ t$          j                            | j        |||d ||g          }t$          j                            t$          j                                        |dgt$          j                            |                    }|S )Nr   r   r   zGMust specify name for tensor factory flax.linen.Module.{param|variable}zGMust specify init for tensor factory flax.linen.Module.{param|variable}get_at	rearrangeg{Gz?)stddevaddmultiplydotin_axisout_axis
batch_axisz3Don't know which initializer to use for operation '')r   r   )argsoutputr   )rH   value)r   getr   r   r   r   r1   strtnninitializersnormal
zeros_init	ones_initlecun_normalintfloatconstantr   einxtracerapplyr   Tensorr   MemberAccess)r   shapekwargsr   r   r   r   r8   s           r   __call__zParamFactory.Tracer.__call__K   s   $(I$54996::fd;S;SD$(I$54996::fd;S;SD&*j&8DJJfjjRV>W>WE(C| ]   | ]   D#&& D8##t{':':+22$2??DDU]]+6688DDZ''+5577DDU]]+88y)6*+=vl?S DD %%b[_%b%b%bcccD3,// D'00U0CC'))K%%JdD%%?HZHZ[`HaHa &   *4444K%%MtT4> &   K%%K,,..a\$+J\J\]bJcJc &   Hr   N)r"   r#   r$   r   r]   r%   r   r   r5   r;   C   s2        	) 	) 	)-	 -	 -	 -	 -	r   r5   N)r"   r#   r$   rV   rW   inputInputr&   r   TensorFactoryr5   r%   r   r   r
   r
      s            4;$*   <    4;$-   25 5 5 5 5* 5 5 5 5 5r   r
   r8   r   r   r   r   c                 l   t          | d          r$| j        t          j        j        k    r
| j        }d}nbt          | d          r$| j        t          j        j        k    r
| j        }d}n.t          | t          j                  r| }d}nt          d          t          
                    ||||||          S )av  Create a tensor factory for Flax parameters.

    Args:
        x: The bound method of a Flax module, i.e. ``nn.Module.param`` or
            ``nn.Module.variable``, or a module instance in which case its ``param`` method
            is used.
        name: Name of the parameter. If ``None``, uses a default name determined from the calling
            operation. Defaults to ``None``.
        init: Initializer for the parameter. If ``None``, uses a default init method determined
            from the calling operation. Defaults to ``None``.
        dtype: Data type of the parameter. If ``None``, uses the ``dtype`` member of the calling
            module or ``float32`` if it does not exist. Defaults to ``None``.
        col: The collection name to use when ``bound_method`` is ``nn.Module.variable``.

    Returns:
        A tensor factory with the given default parameters.
    __func__r   r   zCx must be a bound method of a Flax module or a Flax module instance)r   rb   r   Moduler   __self__r   r1   r   r
   r&   )r8   r   r   r   r   r   r   s          r   r   r   {   s    0 q* 
`!*	"?"?

	J		 `AJ")2D$D$D

	Ary	!	! `

^___  tUCLLLr   c                    t          | t          j                  sDt          | d          rU| j        t          j        j        k    s| j        t          j        j        k    r!t          |                                           S d S )Nrb   )r1   r   rc   r   rb   r   r   r!   )r8   s    r   tensor_factoryrf      sg    !RY :Z29?**ajBI<N.N.NQxx((***tr   c                       e Zd ZU eed<   dZeed<   dZeed<   dZeed<   dZ	eed<   dZ
eed<   d	Zeed
<   dZeed<   dZeed<   dZej        j        ed<   d	Zeed<   ej        dd            Zd	S )_Normstatsb... [c]paramsTmeanvarscalebiasN
decay_rateh㈵>epsilonfastvarr   r   r\   c                 ~   | j         |t          d          | j         d uo| p|                                 }t          j        j        || j        | j        f|r$| j        rt          | j
        dd| j                  n| j        |r$| j        rt          | j
        dd| j                  n| j        | j        rt          | j	        d| j                  nd | j        rt          | j	        d| j                  nd | j        | j        d	| j        | j        ni \  }}}| j         d uo|o|                                  }|r| j        r9| 
                    ddd           }| j         |j        z  d
| j         z
  |z  z   |_        | j        r9| 
                    ddd           }| j         |j        z  d
| j         z
  |z  z   |_        |S )Nz2training must be specified when decay_rate is usedri   rl   )r   r   r   rm   rn   r   r   ro   )rl   rm   rn   ro   rr   rs      )rp   r   is_initializingrV   r   normri   rk   rl   r   r   r   rm   rn   ro   rr   rs   r\   rJ   )	r   r8   traininguse_emarl   rm   
update_emamean_emavar_emas	            r   r]   z_Norm.__call__   s   ?&8+;QRRR/-Zx<3Y4CWCWCYCYw|JK

 9t}'djQQQQ8dmuDJOOOOGKz[%

CCCCW[EIYXtzdjAAAATXLL
 
 #k5t{{2
 
4" _D0\X\dFZFZF\F\B\
 	^y a==&$??!%8>!AQEX\`D`!`x ^--== $'- ?1tCVZ]B] ]r   r   )r"   r#   r$   rL   __annotations__rk   rl   boolrm   rn   ro   rp   rT   rr   rs   r   r   dtypesDtyper\   dictcompactr]   r%   r   r   rh   rh      s         JJJFCD$CE4D$JGUGT&E29?&&&FDZ   Z  r   rh   rj   Trq   r   ri   rk   rl   rm   rn   ro   rp   rr   rs   r\   c                 8    t          | |||||||||	|
|          S )a  Normalization layer.

    Args:
        stats: Einstein string determining the axes along which mean and variance are computed.
            Will be passed to ``einx.reduce``.
        params: Einstein string determining the axes along which learnable parameters are applied.
            Will be passed to ``einx.elementwise``. Defaults to ``"b... [c]"``.
        mean: Whether to apply mean normalization. Defaults to ``True``.
        var: Whether to apply variance normalization. Defaults to ``True``.
        scale: Whether to apply a learnable scale according to ``params``. Defaults to ``True``.
        bias: Whether to apply a learnable bias according to ``params``. Defaults to ``True``.
        epsilon: A small float added to the variance to avoid division by zero. Defaults
            to ``1e-5``.
        fastvar: Whether to use a fast variance computation. Defaults to ``True``.
        dtype: Data type of the weights. Defaults to ``"float32"``.
        decay_rate: Decay rate for exponential moving average of mean and variance. If ``None``,
            no moving average is applied. Defaults to ``None``.
        name: Name of the module. Defaults to ``None``.
        **kwargs: Additional parameters that specify values for single axes, e.g. ``a=4``.
    )rk   rl   rm   rn   ro   rp   rr   rs   r   r   r\   )rh   )ri   rk   rl   rm   rn   ro   rp   rr   rs   r   r   r\   s               r   Normr      s@    F    r   c                   x    e Zd ZU eed<   dZeed<   dZej	        j
        ed<   dZeed<   ej        d             ZdS )	_LinearexprTro   r   r   Nr\   c           	          t          j        j        || j        f| j        rt          | j        d| j                  nd t          | j        d| j                  d| j        | j        ni S )Nro   ru   weight)ro   r   )rV   r   linearr   ro   r   r   r\   )r   r8   s     r   r]   z_Linear.__call__  s~    w~I
 FJYXtzdjAAAATX($*EEE	
 

 #k5t{{2
 
 	
r   )r"   r#   r$   rL   r~   ro   r   r   r   r   r   r\   r   r   r]   r%   r   r   r   r     sn         
IIID$&E29?&&&FDZ
 
 Z
 
 
r   r   r   c                 *    t          | ||||          S )a  Linear layer.

    Args:
        expr: Einstein string determining the axes along which the weight matrix is
            multiplied. Will be passed to ``einx.dot``.
        bias: Whether to apply a learnable bias. Defaults to ``True``.
        dtype: Data type of the weights. Defaults to ``"float32"``.
        name: Name of the module. Defaults to ``None``.
        **kwargs: Additional parameters that specify values for single axes, e.g. ``a=4``.
    )ro   r   r   r\   )r   )r   ro   r   r   r\   s        r   Linearr   &  s    $ 4d%d6JJJJr   c                   `    e Zd ZU eed<   eed<   dZeed<   dZeed<   e	j
        d             ZdS )_Dropoutr   	drop_ratedropoutrng_collectionNr\   c                     |rKt          j        j        || j        f| j        |                     | j                  d| j        | j        ni S |S )N)r   rng)rV   r   r   r   r   make_rngr   r\   )r   r8   ry   s      r   r]   z_Dropout.__call__A  si     		7?	 .MM$"566	 
 #'+"94;;r   Hr   )r"   r#   r$   rL   r~   rT   r   r\   r   r   r   r]   r%   r   r   r   r   ;  sf         
III#NC###FDZ
 
 Z
 
 
r   r   r   r   r   c                 *    t          | ||||          S )a  Dropout layer.

    Args:
        expr: Einstein string determining the axes along which dropout is applied. Will be passed
            to ``einx.elementwise``.
        drop_rate: Drop rate.
        rng_collection: the rng collection name to use when requesting an rng key. Defaults
            to ``"dropout"``.
        name: Name of the module. Defaults to ``None``.
        **kwargs: Additional parameters that specify values for single axes, e.g. ``a=4``.
    )r   r   r\   )r   )r   r   r   r   r\   s        r   Dropoutr   O  s    & D)NV\]]]]r   )NNNN)
rj   TTTTNrq   Tr   N)Tr   N)r   N)#
flax.linenlinenr   rV   flax	functoolsr   	jax.numpynumpyjnptypingr   r   r   r   rW   import_rM   r
   rc   rL   r   r   r   r^   register_tensor_factoryrf   rh   r   rT   r   r   r   r   r   r%   r   r   <module>r      sj                       1 1 1 1 1 1 1 1 1 1 1 1
k,--m m m m m m m md '+$M $MXry !$M
3-$M 3-$M BIO$	$M
 
#$M $M $M $MP *  +*- - - - -BI - - -d "&&0 000 0 
	0
 0 0 0 0 0 9?0 3-0 0 0 0 0f
 
 
 
 
bi 
 
 
& &	K K
K
K 9?K 3-	K
 K K K K*    ry   . $	^ ^
^^ ^ 3-	^
 ^ ^ ^ ^ ^ ^r   