
    PiX+                        d dl Z d dlZd dlZd dlmZ d dlZd dlmZm	Z	m
Z
mZ  ed e j                            d          dd         D                       Zedk     r ede j                   d	 Zej                            d
          Z G d d          Z	 dde	e j        j        j        e j        j        j        e j        j        j        f         de
e         fdZej        j        j        d             Z G d de j        j                  Z ed             Z! G d de j        j                  Z"ed             Z# G d de j        j                  Z$ed             Z%dS )    N)partial)CallableUnionOptionalAnyc              #   4   K   | ]}t          |          V  d S N)int).0is     a/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/einx/nn/torch.py	<genexpr>r      s(      BBAQBBBBBB    .   )r   r   z7einx.nn.torch requires PyTorch version >= 2, but found c                     dt          t                    v rt          j                            |           S dd lm} |                    |           S )Ncompilerr   )dirtorchr   allow_in_graphtorch._dynamo_dynamo)funcr   s     r   _allow_in_graphr      sO    SZZ~,,T222''''''%%d+++r   r   c                       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                 "    || _         || _        d S r	   )paraminit)selfr    r!   s      r   __init__zParamFactory.Concrete.__init__   s    DJDIIIr   c                 N    | j         t                              | j                  fS r	   )r    r   CacheKeyr!   r"   s    r   to_value_and_keyz&ParamFactory.Concrete.to_value_and_key   s    :|44TY????r   N)__name__
__module____qualname__r#   r'    r   r   Concreter      s7        	 	 		@ 	@ 	@ 	@ 	@r   r,   c                   &    e Zd Zd Zd Zd Zd ZdS )ParamFactory.CacheKeyc                     || _         d S r	   r!   r"   r!   s     r   r#   zParamFactory.CacheKey.__init__#       DIIIr   c                 *    t          | j                  S r	   )hashr!   r&   s    r   __hash__zParamFactory.CacheKey.__hash__&   s    	??"r   c                 V    t          |t          j                  o| j        |j        k    S r	   )
isinstancer   r%   r!   )r"   others     r   __eq__zParamFactory.CacheKey.__eq__)   s#    e\%:;;W	UZ@WWr   c                 H    t                               | j                  }||fS r	   )r   Tracerr!   )r"   backendvirtual_argxs       r   	to_tracerzParamFactory.CacheKey.to_tracer,   s     ##DI..Aa4Kr   N)r(   r)   r*   r#   r5   r9   r?   r+   r   r   r%   r.   "   sS        	 	 		# 	# 	#	X 	X 	X	 	 	 	 	r   r%   c                       e Zd Zd Zd ZdS )ParamFactory.Tracerc                     || _         d S r	   r0   r1   s     r   r#   zParamFactory.Tracer.__init__1   r2   r   c                     | j         | j         n|                    dd           }| }t          j                                      }t          j                            |j        g|||fg          }|t          d          t          |t                    r|dk    s|dk    r&t          t          j        j         j        d          }n|dk    rt          j        j         j        }n|d	k    rt          j        j         j        }n|d
k    rit!          j        fd|d         D                       }t!          j        d|z            dz  }t          t          j        j         j        d|dd          }nTt          d| d          t          |t(          t*          f          r%t          t          j        j         j        |          }t          j                                      }t          j                            ||g|||fg          }|S )Nr!   )argsoutputinplace_updateszFMust specify init for tensor factory torch.nn.parameter.Uninitialized*get_at	rearrangeg{Gz?)stdaddmultiplydotc                      g | ]
}|         S r+   r+   )r   r   shapes     r   
<listcomp>z0ParamFactory.Tracer.__call__.<locals>.<listcomp>M   s    %J%J%J1eAh%J%J%Jr   in_axisg      ?g۶%?g        g       g       @)meanrI   abz3Don't know which initializer to use for operation '')val)r!   geteinxtracerTensorapplymaterialize
ValueErrorr7   strr   ttorchnnnormal_zeros_ones_npprodsqrttrunc_normal_r
   float	constant_)r"   rN   kwargsr!   r>   rE   fan_inrI   s    `      r   __call__zParamFactory.Tracer.__call__4   s   $(I$54996::fd;S;SDA[''..F!!W"#V	 "  A | \   D#&& C8##t{':':"69>#9tDDDDDU]]!9>0DDZ''!9>/DDU]]W%J%J%J%Jy8I%J%J%JKKF'#,//2EEC"69>#?csVZ^abbbDD$%b[_%b%b%bcccD3,// Cvy~7TBBB[''..F!!S"#V	 "  A Hr   N)r(   r)   r*   r#   rk   r+   r   r   r;   rA   0   s2        	 	 	)	 )	 )	 )	 )	r   r;   N)r(   r)   r*   rW   rX   inputInputr,   r%   TensorFactoryr;   r+   r   r   r   r      s        @ @ @ @ @4;$* @ @ @    4;$-   - - - - -* - - - - -r   r   r>   r!   c                     t          | t          j        j        j        t          j        j        j        f          r:t          | t          j        j                  st          	                    | |          S | S )a  Create a tensor factory for an uninitialized PyTorch parameter or buffer.

    If the given parameter is not initialized, this returns a tensor factory that calls
    the ``materialize`` method of ``uninitialized`` with the given shape and returns
    ``uninitialized``. Otherwise, the parameter is returned as is.

    Args:
        x: An instance of ``torch.nn.parameter.UninitializedParameter``,
            ``torch.nn.parameter.UninitializedBuffer`` or ``torch.nn.parameter.Parameter``.
        init: Initializer for the parameter. If ``None``, uses a default init method determined
            from the calling operation. Defaults to ``None``.

    Returns:
        A tensor factory with the given default parameters, or the parameter itself if it is
        already materialized.
    )
r7   r   r_   	parameterUninitializedParameterUninitializedBuffer_subclasses
FakeTensorr   r,   )r>   r!   s     r   r    r    `   sg    0 	EH5ux7I7]^  E-899 $$Q--- r   c                     t          | t          j        j        j        t          j        j        j        f          r@t          | t          j        j                  s!t          |           	                                S d S r	   )
r7   r   r_   rp   rq   rr   rs   rt   r    r'   )r>   s    r   tensor_factoryrv      se    	EH5ux7I7]^  E-899 Qxx((***tr   c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 ddeded	ed
edededededeej	        ef         de
e         def fdZd Z xZS )Norma  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``.
        **kwargs: Additional parameters that specify values for single axes, e.g. ``a=4``.
    b... [c]Th㈵>float32NstatsparamsrQ   varscalebiasepsilonfastvardtype
decay_rateri   c                 R   t                                                       || _        || _        || _        || _        || _        || _        |
| _        || _	        |rT|
R| 
                    dt          j        j                            t          t                    |	                              nd | _        |rT|
R| 
                    dt          j        j                            t          t                    |	                              nd | _        |r=t          j        j                            t          t                    |	                   nd | _        |r=t          j        j                            t          t                    |	                   nd | _        d| _        d S )NrQ   r   r~   F)superr#   r|   r}   use_meanuse_varr   r   r   ri   register_bufferr   r_   rp   rr   varsrQ   r~   rq   r   r   initialized)r"   r|   r}   rQ   r~   r   r   r   r   r   r   ri   	__class__s               r   r#   zNorm.__init__   s    	
$ 	J*  *>>T%[[QVEW>XX    DI 	:)  ux)==DKKPUDV=WW    DHSXbEH55DKK<N5OOO^b 	
 TXaEH55DKK<N5OOO]a 		 !r   c                    | j         d uo| j         p| j         }t          || j        | j        |r| j        r| j        n| j        |r| j        r| j	        n| j        | j
        | j
        nd | j        | j        nd | j        | j        | j        
  
        \  }}}| j         d uo| j        }|rt          j                    5  |5| j                            | j         | j        z  d| j         z
  |z  z              |5| j	                            | j         | j	        z  d| j         z
  |z  z              d d d            n# 1 swxY w Y   | j        sd| _        |S )N)rQ   r~   r   r   r   r   ri      T)r   trainingr   _normr|   r}   r   rQ   r   r~   r   r   r   r   ri   r   no_gradcopy_)r"   r>   use_emarQ   r~   
update_emas         r   forwardzNorm.forward   s   /-]t}3D3\DL\H\JK%J$-JT]#FF$, $
 6$**D"i3LL;
 
 
4 _D0BT]
 	] ] ]#IOODOdi$?1tCVZ^B^$^___?HNN4?TX#=T_ATX[@[#[\\\	] ] ] ] ] ] ] ] ] ] ] ] ] ] ]
  	$#Ds   ;A/D66D:=D:)	ry   TTTTrz   Tr{   N)r(   r)   r*   __doc__r]   boolrg   r   r   r   r   r   r#   r   __classcell__r   s   @r   rx   rx      s         . !)2&*+! +!+! +! 	+!
 +! +! +! +! +! U[#%&+! UO+! +! +! +! +! +! +!Z      r   rx   c
                     | j         5  t          j        j        | ||f||||||dd|	cd d d            S # 1 swxY w Y   d S )Nr   )rQ   r~   r   r   r   r   r<   )devicerW   r_   norm)
r>   r|   r}   rQ   r~   r   r   r   r   ri   s
             r   r   r      s    	
 
 
w|
 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   !6::c            	       Z     e Zd ZdZ	 	 d
dededeej        ef         de	f fdZ
d	 Z xZS )Lineara  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"``.
        **kwargs: Additional parameters that specify values for single axes, e.g. ``a=4``.
    Tr{   exprr   r   ri   c                    t                                                       t          j        j                            t          t                    |                   | _        |rCt          j        j                            t          t                    |                   | _        nd | _        || _	        || _
        d S )Nr   )r   r#   r   r_   rp   rq   r   weightr   r   ri   )r"   r   r   r   ri   r   s        r   r#   zLinear.__init__  s     	h(??d5kkRWFX?YY 	*AAUTYHZA[[DIIDI	r   c                 P    t          || j        | j        | j        | j                  S r	   )_linearr   r   r   ri   r"   r>   s     r   r   zLinear.forward  s     q$)T[$)T[IIIr   )Tr{   )r(   r)   r*   r   r]   r   r   r   r   r   r#   r   r   r   s   @r   r   r      s          )2	   U[#%&	
      $J J J J J J Jr   r   c                 |    | j         5  t          j        j        | |||fddi|cd d d            S # 1 swxY w Y   d S )Nr<   r   )r   rW   r_   linear)r>   r   r   r   ri   s        r   r   r     s    	
 
 
w~	
 

 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   155c                   6     e Zd ZdZdededef fdZd Z xZ	S )Dropouta  Dropout layer.

    Args:
        expr: Einstein string determining the axes along which dropout is applied. Will be
            passed to ``einx.elementwise``.
        drop_rate: Drop rate.
        **kwargs: Additional parameters that specify values for single axes, e.g. ``a=4``.
    r   	drop_rateri   c                 r    t                                                       || _        || _        || _        d S r	   )r   r#   r   r   ri   )r"   r   r   ri   r   s       r   r#   zDropout.__init__3  s2    	"r   c                 V    | j         r!t          || j        | j        | j                  S |S r	   )r   _dropoutr   r   ri   r   s     r   r   zDropout.forward:  s+    = 	Aty$.$+FFFHr   )
r(   r)   r*   r   r]   rg   r   r#   r   r   r   s   @r   r   r   )  sk         S U c            r   r   c                 z    | j         5  t          j        j        | |f|dd|cd d d            S # 1 swxY w Y   d S )Nr   )r   r<   )r   rW   r_   dropout)r>   r   r   ri   s       r   r   r   A  s    	
 
 
w
  	
 

 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   044r	   )&r   rW   math	functoolsr   numpyrc   typingr   r   r   r   tuple__version__split_versionImportErrorr   rX   import_r^   r   r_   rp   rq   rr   	Parameterr    rl   register_tensor_factoryrv   Modulerx   r   r   r   r   r   r+   r   r   <module>r      s                1 1 1 1 1 1 1 1 1 1 1 15BB!2!8!8!=!=bqb!ABBBBBf
+cPUPacc
d
dd, , , 
		W	%	%D D D D D D D DZ  1.$	& 3-   F *  +*Y Y Y Y Y58? Y Y Yx 
 
 
"J J J J JUX_ J J JB 	
 	
 	
    eho   0 
 
 
 
 
r   