
    Pi,                     \   d dl Z ddlmZ d dlZd dlmZ d dlmZ  e j	        d           dd            Z
e j        dd	d
            Ze j        j         e j	        d           ddddede j        dee j        edf         dedej        de j        fd                        Zee_        dS )    N   )util)Unionc                      d fd	S )Nc                 6     | fd|D             |          S )Nc                 &    g | ]} |          S  r	   .0xts     _/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/einx/op/dot.py
<listcomp>z.<lambda>.<locals>.<lambda>.<locals>.<listcomp>
   s!    ,,,A11Q44,,,    r	   )exprs_in
tensors_inexpr_outbackendcr   s       r   <lambda>z<lambda>.<locals>.<lambda>	   s1    AA,,,,,,,hM M r   Nr	   r   r   s   ``r   r   r   	   s$           r   )tracec                     t                     |gz   D ]L}|                                D ]5}t          |t          j        j        j                  rt          d          6M|                                D ]5}t          |t          j        j        j                  rt          d          6d |                                D             } D ]}|                                D ]}t          |t          j        j        j	                  r[|j
        |v}	t          j        j                            |          }
|	r|
st          d| d          |	s|
rt          d| d          d |                                D              fd	fd
t          t          |                     D             }                    |          }t          j         |          \   }t          j        |g          d         }t          d  D                       sJ t          j        j                            |          sJ i fdfdd  D             d                    fd D                       dz    fdt          j        j                            |          D                       z   } j        |g|R  }t          j        j                            fdt          j        j                            |          D                       }t          j        |||          d         }                    ||j                  }||fS )NzConcatenation not allowedz-Brackets in the output expression not allowedc                 d    h | ]-}t          |t          j        j        j                  &|j        .S r	   
isinstanceeinxexprstage3Axisnamer   as     r   	<setcomp>zdot_stage3.<locals>.<setcomp>   s1    ]]]
1diFVF[8\8\]af]]]r   zReduced axis z must be markedzMarked axis z# cannot appear in output expressionc                 d    h | ]-}t          |t          j        j        j                  &|j        .S r	   r   r#   s     r   r%   zdot_stage3.<locals>.<setcomp>!   s1    ```A:aIYI^;_;_````r   c                       fdt          	          D             g }g }g }t          	                    D ]\  }}t          fd|                                D                       }t          
fd|                                D                       }|r|s|                    |           y|r|s|                    |           |                    |           t	          |          t	          |          t	          |          dS )Nc                     h | ]M\  }}|                                 D ]3}|k    t          |t          j        j        j                  ,|j        4NS r	   )allr   r   r   r    r!   r"   )r   iexpr_inr$   idxs       r   r%   z/dot_stage3.<locals>.get_fans.<locals>.<setcomp>$   sd     "
 "
 "
7[[]]"
 "
 CxxJq$)*:*?@@x F xxxr   c              3   r   K   | ]1}t          |t          j        j        j                  o|j        v V  2d S r   r   )r   r$   other_input_axis_namess     r   	<genexpr>z/dot_stage3.<locals>.get_fans.<locals>.<genexpr>.   sV       % % 1di.344YCY9Y% % % % % %r   c              3   r   K   | ]1}t          |t          j        j        j                  o|j        v V  2d S r   r   )r   r$   output_axis_namess     r   r/   z/dot_stage3.<locals>.get_fans.<locals>.<genexpr>2   sV           1di.344TCT9T           r   )in_axisout_axis
batch_axis)	enumerateanyr)   appendtuple)r,   r2   r3   r4   r*   childany_in_other_inputany_in_outputr.   r   r1   s   `       @r   get_fanszdot_stage3.<locals>.get_fans#   sq   "
 "
 "
 "
'11"
 "
 "
 
!(3-00 	% 	%HAu!$ % % % %% % % " "                 M " %- %q!!!! %'9 %""""!!!$$$$W~~h
++
 
 	
r   c           	      t    g | ]4\  }\  }}t          j        j        ||j        fi  |          d dd5S )weightdot)r"   init)r   tracercall_factoryshape)r   r*   tensorr   r   r<   s       r   r   zdot_stage3.<locals>.<listcomp>B   st        A~ 	 DJ	
 	
+38A;;	
=EE	
 	
 	
 	
  r   r   r   c              3   ^   K   | ](}t           j        j                            |          V  )d S r   )r   r   r    is_flat)r   r   s     r   r/   zdot_stage3.<locals>.<genexpr>M   s5      CC$ty''--CCCCCCr   c                 (   | v r|          S t          t          d          t                    z             }t          |          t          d          k    r3t          dt          d          t          d          z
  dz    d          || <   |S )Nr$   zzOnly supports up to r   z unique input axes)chrordlen
ValueError)keyveinsum_variabless     r   get_einsum_variablez'dot_stage3.<locals>.get_einsum_variableS   s    """#C((CHHs#344455A1vvC   !cC3s888Ka8O!c!c!cddd$%S!Hr   c                 F    d                     fd| D                       S )N c              3   8   K   | ]} |j                   V  d S r   r"   )r   r$   rQ   s     r   r/   z0dot_stage3.<locals>.to_einsum.<locals>.<genexpr>^   s1      AAq**1622AAAAAAr   )join)axesrQ   s    r   	to_einsumzdot_stage3.<locals>.to_einsum]   s*    wwAAAADAAAAAAr   c                 j    h | ]0}t           j        j                            |          D ]	}|j        
1S r	   )r   r   r    get_axesr"   )r   r   r$   s      r   r%   zdot_stage3.<locals>.<setcomp>`   s;    ]]]4TY=M=V=VW[=\=\]]]]]]r   ,c              3   r   K   | ]1} t           j        j                            |                    V  2d S r   )r   r   r    rZ   )r   r   rX   s     r   r/   zdot_stage3.<locals>.<genexpr>c   s@      QQ49+44T::;;QQQQQQr   z->c                 &    g | ]}|j         v |S r	   rU   r   r$   input_axis_namess     r   r   zdot_stage3.<locals>.<listcomp>e   s-     
 
 
16M]C]C]AC]C]C]r   c                 J    g | ]}|j         v |                                 S r	   )r"   __deepcopy__r^   s     r   r   zdot_stage3.<locals>.<listcomp>k   s;     " " "6%%% 	
%%%r   )listr)   r   r   r   r    ConcatenationrM   Markerr!   r"   	is_markedr5   zipall_to_tensorr   flattenrG   rV   rZ   einsumListtranspose_broadcastreshaperC   )r   r   r   r   rootr   out_axis_namesr+   axisis_reduced_axisre   expr_out_flat
einsum_strrD   rP   rQ   r<   r_   r1   rX   s   `  `          @@@@@@r   
dot_stage3rs      s-    X(+ > >HHJJ 	> 	>D$	 0 >?? > !<===>	>  N NdDI,344 	NLMMM	N]]hllnn]]]N _ _KKMM 	_ 	_D$	 0 566 _"&)>"A I,66t<<	" _9 _$%JT%J%J%JKKK( _Y _$%]D%]%]%]^^^	_ a````
 
 
 
 
 
>     "+3z8+D+D!E!E	  J &&z22J  <*gNNNHjL(,,Q/MCC(CCCCCCCC9##M22222     B B B B B ^]8]]] 	QQQQQQQQQ
	
) 
 
 
 
y'00??
 
 
  	  W^J4444F9   " " " "!**=99" " "  D %dFM7SSSTUVF __VX^44F8r   T)csec          	      	   t           j        j                            | |          \  } }t           j        j                            |           }t          |d                   dk    rt          |          dk    r|d         d         |d         d         fD ]~}|                                D ]g}t          |t           j        j        j
                  rA|j        dk    r6t           j        j                            |          rt          d|           ht                      }g }|d         d         |d         d         fD ]}|                                D ]}t          |t           j        j        j                  rt           j        j                            |          r|j        |vr|                    |j                   |                                }	|}
|
j        ]t          |
t           j        j        j                  r+t           j        j                            |	|
j                  }	|
j        }
|
j        ]|                    |	           t           j        j                            |          }t           j        j                            t           j        j                            t           j        j                            |d         d                   |g          t           j        j                            t           j        j                            |d         d                   g          g          }t          |d                   t          |          k    r5t          dt          |d                    dt          |                     t          |d                   dk    r%t          dt          |d                              t           j                            d	 t9          |d         |          D             t           j                            |d         d                   gz   d
 |                                D             z   |d          d t          |d                   dz            }|d d         |d         }}t?          d |D                       s,d |                                D             fd|D             }||fS )Nr   r      z0Cannot mark unnamed non-trivial axes, but found )ellipsis_idz	Expected z input tensor(s), got z&Expected 1 output expression, but got c                 T    g | ]%\  }}t           j                            ||          &S r	   )r   r   Equation)r   r+   tensor_shapes      r   r   zparse.<locals>.<listcomp>   s>     	
 	
 	
% Iw55	
 	
 	
r   c                     g | ]L\  }}t           j                            |t          j        |          d t          j        f         dd          MS ).N)depth1depth2)r   r   ry   npasarraynewaxis)r   krO   s      r   r   zparse.<locals>.<listcomp>   sY     
 
 
1 Iq"*Q--RZ"@VZ[[
 
 
r   F)rt   
cse_concatc              3      K   | ]?}|                                 D ](}t          j        j                            |          V  )@d S r   )r)   r   r   r    re   )r   r+   r   s      r   r/   zparse.<locals>.<genexpr>   sO      bbGT[T_T_TaTabbDty))$//bbbbbbbr   c                 d    h | ]-}t          |t          j        j        j                  &|j        .S r	   r   )r   ro   s     r   r%   zparse.<locals>.<setcomp>   sA     
 
 
JtTYEUEZ4[4[
I
 
 
r   c                 `    g | ]*}t           j        j                            |fd           +S )c                 ^    t          | t          j        j        j                  o| j        vS r   r   )r   axes_names_outs    r   r   z"parse.<locals>.<listcomp>.<lambda>   s+    Zdi.>.CDD 4I^3 r   )r   r   r    mark)r   r+   r   s     r   r   zparse.<locals>.<listcomp>   sW     
 
 
  I!!4 4 4 4 
 
 
r   ) r   opr   !_clean_description_and_parametersr   stage1parse_oprL   r)   r   UnnamedAxisvaluere   rM   set	NamedAxisr"   addra   parentEllipsisrw   r7   rj   OpArgsdemarksolverf   ry   itemsr6   )descriptionrt   tensor_shapes
parametersr   rm   r   namesexpr_in2expr2r   exprsr   r   r   s                 @r   parser   z   s   "glLLZ K 
		"	";	/	/B 2a5zzQ3}--22U1Xr!uQx( 	` 	`D

 ` `tTY%5%ABB`
a	(22488 ( %%^X\%^%^___` U1Xr!uQx( 	+ 	+D

 + +tTY%5%?@@+	(22488+ 	..IIdi((( !--//E "F -3%fdi.>.GHH e$(I$4$=$=eQWQc$=$d$dE!' !-3 OOE***'+( 9#((22Y  I!!	 ''1a11#   I!!	 ''1a11#  "
   2a5zzS''''[SAZZ[[s=GYGY[[\\\
2a5zzQN#be**NNOOOIOO	
 	
),RUM)B)B	
 	
 	
 9beAh''
(		)

 
"((**
 
 
	
     BqE

QE ssU2YhH bbxbbbbb 

 
"*,,..
 
 

 
 
 
 $
 
 
 Xr   c                      d d fd
S )NrE   c                4     | gfd|D             R i |S )Nc                 &    g | ]} |          S r	   r	   r
   s     r   r   z.<lambda>.<locals>.<lambda>.<locals>.<listcomp>   s!    ---qqtt---r   r	   )r   r   tensorskwargsr   r   s       r   r   z<lambda>.<locals>.<lambda>   sJ    QQN----W---N N N17N N r   r	   r   s   ``r   r   r      s+    T        r   )r   rt   r   r   r   rt   r   returnc                p    t          | gd |D             R d|i|\  }}t          ||||          \  }}|S )a  Computes a general dot-product of the input tensors.

    The following shorthand notation is supported:

    * When no brackets are found, brackets are placed implicitly around all axes that do not
      appear in the output.

      Example: ``a b, b c -> a c`` expands to ``a [b], [b] c -> a c``

    * When given two input tensors, the expression of the second input is determined implicitly
      from the marked axes in the input and output expression.

      Example: ``a [b] -> a [c]`` expands to ``a b, b c -> a c``

      Axes marked multiple times appear only once in the implicit second input expression.

      Example: ``[a b] -> [a c]`` expands to ``a b, a b c -> a c``

    The function additionally passes the ``in_axes``, ``out_axes`` and ``batch_axes`` arguments
    to tensor factories that can be used to determine the fan-in and fan-out of a neural network
    layer and initialize weights accordingly (see e.g. `jax.nn.initializers.lecun_normal
    <https://jax.readthedocs.io/en/latest/_autosummary/jax.nn.initializers.lecun_normal.html#jax.nn.initializers.lecun_normal>`_)

    Args:
        description: Description string for the operation in einx notation.
        tensors: Input tensors or tensor factories matching the description string.
        backend: Backend to use for all operations. If None, determines the backend from the
            input tensors. Defaults to None.
        cse: Whether to apply common subexpression elimination to the expressions. Defaults
            to True.
        graph: Whether to return the graph representation of the operation instead of computing
            the result. Defaults to False.
        **parameters: Additional parameters that specify values for single axes, e.g. ``a=4``.

    Returns:
        The result of the dot-product operation if ``graph=False``, otherwise the graph
        representation of the operation.

    Examples:
        Compute an inner product between two vectors:

        >>> a, b = np.random.uniform(size=(10,)), np.random.uniform(size=(10,))
        >>> einx.dot("a, a ->", a, b).shape
        ()

        Compute a matrix-vector product:

        >>> a, b = np.random.uniform(size=(10, 10)), np.random.uniform(size=(10,))
        >>> einx.dot("a b, b -> a", a, b).shape
        (10,)
        >>> einx.dot("a [b] -> a", a, b).shape
        (10,)
        >>> einx.dot("a [b->]", a, b).shape
        (10,)

        Compute a vector-matrix product:

        >>> a, b = np.random.uniform(size=(10,)), np.random.uniform(size=(10, 10))
        >>> einx.dot("a, a b -> b", a, b).shape
        (10,)
        >>> einx.dot("[a] -> [b]", a, b).shape
        (10,)
        >>> einx.dot("[a->b]", a, b).shape
        (10,)

        Multiply a tensor with a weight matrix:

        >>> x, w = (
        ...     np.random.uniform(size=(4, 16, 16, 64)),
        ...     np.random.uniform(
        ...         size=(
        ...             64,
        ...             32,
        ...         )
        ...     ),
        ... )
        >>> einx.dot("b... [c1->c2]", x, w).shape
        (4, 16, 16, 32)
    c                 L    g | ]!}t           j                            |          "S r	   )r   rA   	get_shape)r   rD   s     r   r   zdot.<locals>.<listcomp>3  s(    KKKt{,,V44KKKr   rt   rE   )r   rs   )	r   r   rt   r   r   r   r   rD   _exprs	            r   r?   r?      sm    x KK7KKK  QTXb Hh x(GLLLMFEMr   r   )r   rS   r   numpyr~   typingr   numpy.typingnptjitrs   	lru_cacher   traceback_utilfilterstrTensorBackendbool	ArrayLiker?   r	   r   r   <module>r      s                          
   
j j j 
jZ +/ X X X X Xv 	    /3	Z Z ZZkZ 4<d*+Z 
	Z
 -Z 
[Z Z Z  Zz 			r   