
    ukiL)                    H   U d Z ddlmZ ddlmZmZ ddlmZ ddlZddl	Z	ddl
Z
ddlZddlZddlmZ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 ej2                  ecZZej8                  ecZZ ej>                  e       Z!	 	 	 	 	 	 d$dZ"	 d%	 	 	 	 	 d&dZ#d'dZ$d f	 d(dZ%d)dZ&d)dZ'd)dZ(d)dZ)eejT                  df   Z+d)dZ,d)dZ-d*dZ.dZ/de0d<   d+dZ1	 d,	 	 	 	 	 d-dZ2dd	 	 	 d.dZ3d/d Z4d0d!Z5d1d"Z6 e	jn                         Z8	 	 	 	 	 	 d2d#Z9y)3zUtilities for the Jaxpr IR.    )annotations)Counterdefaultdict)CallableN)AnyUnion)Iterator)config)core)path)util)source_info_util)
xla_clientc              #     K   | j                   D ]  }| |f 
 t        j                  |       D ]C  }|t        ||      E d {    ||vs|j	                  |       t        ||      E d {    E y 7 27 	wN)eqnsr   	subjaxprs	_all_eqnsadd)jaxprvisitedeqnsubjaxprs       N/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/jax/_src/jaxpr_util.pyr   r   *   s      ZZ c#,..' .h8W---		 kk(8W---.- .s*   AA:A6	A: A:.A8/A:8A:c              #  P   K   t        | |rd n	t                     E d {    y 7 wr   )r   set)r   revisit_inner_jaxprss     r   all_eqnsr   6   s      u&:dFFFs   &$&c                    t        t              }t        |       D ]  \  }}| ||         j                  |       ! t	        |      S r   )r   listr   appenddict)r   keyd_r   s        r   collect_eqnsr&   <   sB    $! fac#hKs	a.    c                    | S r    )xs    r   <lambda>r+   C   s    A r'   c                    t        | |      }|j                         D ci c]  \  }} ||      t        |       c}}S c c}}w r   )r&   itemslen)r   r#   key_fmtr$   kvs         r   	histogramr2   B   s9    5#!)*	3A'!*c!f
	33	3s   A c                    t        | d       S )Nc                .    | j                   j                  S r   )	primitivenamer   s    r   r+   zprimitives.<locals>.<lambda>H   s    cmm&8&8 r'   r2   )r   s    r   
primitivesr9   G   s    	58	99r'   c                6    d }t        | |dj                        S )Nc                p    t        j                  | j                        }| j                  j                  |fS r   r   	summarizesource_infor5   r6   )r   srcs     r   r#   z!primitives_by_source.<locals>.keyK   s+    

$
$S__
5CMM$$r'    @ r2   joinr   r#   s     r   primitives_by_sourcerD   J   s    % 
5#uzz	**r'   c                B    d fd}t        | |dj                        S )Nc                n    t        | t        j                        rdS | j                  j	                         S )N*)
isinstancer   DropVaraval	str_short)vars    r   	shape_fmtz&primitives_by_shape.<locals>.shape_fmtQ   s'    S$,,/3ISXX5G5G5IIr'   c                z    | j                   j                  dj                  t        | j                              fS )N )r5   r6   rB   mapoutvars)r   rM   s    r   r#   z primitives_by_shape.<locals>.keyS   s,    MMY)D EFFr'   z :: rA   )r   r#   rM   s     @r   primitives_by_shaperR   P   s"    JG	5#v{{	++r'   c                     d }t        | |      S )Nc                @    t        j                  | j                        S r   )r   r=   r>   r7   s    r   r#   zsource_locations.<locals>.keyX   s    %%coo66r'   r8   rC   s     r   source_locationsrU   W   s    7	5#	r'   c                  	 i i 	d	fd}d	fd}| j                   D ]  } ||d         | j                  D ]  } ||d         | j                  D ]6  }|j                  D ]  } |||        |j                  D ]  } |||        8 | j                  D ]  } ||d         D cg c]  }||   	|   f }}t	        t
        t        j                  |             }|r| |fg|S | |fS c c}w )Nc                    t        | t        j                        s+| v sJ |        | v sJ |        |    j                  |       y y r   )rH   r   Literalr!   )ar   defsrefss     r   readzvar_defs_and_refs.<locals>.readb   sH    a&$YY$YY
1gnnS 'r'   c                |    | vsJ |        | vsJ |        t        | t        j                        s|| <   g | <   y y r   )rH   r   rI   )r1   r   rZ   r[   s     r   writez var_defs_and_refs.<locals>.writeh   sJ    D=!=D=!=a&d1gd1g 'r'   )rY   z	core.Atomr   MaybeEqn)r1   core.Varr   r_   )	constvarsinvarsr   rQ   rP   var_defs_and_refsr   r   )
r   r\   r^   r1   r   rY   ressubsrZ   r[   s
           @@r   rc   rc   ^   s   #%$)+$ ?? a	!TN<< a	!TN ZZ cZZ 
1cl[[ Asm == aDM )--1!T!Wd1g	-#-	u 5	6$"&5#,		8UCL8 	.s   ,C0c           	     n    d fd}t        |       D cg c]  \  }}| |||      f c}}S c c}}w )Nc                    ||  dS t        j                  |j                        }|  d|j                  j                   d| S )Nz	 <- invarz <- r@   r<   )rL   r   r?   s      r   fmt_keyzvars_by_fanout.<locals>.fmt_key   sJ    
{uI&&s7cuD++,Cu55r'   c           	     d    |D ci c]  \  }}} ||      t        |       c}}}S c c}}}w r   )r.   )r   readsrL   var_defvar_refsrh   s        r   histzvars_by_fanout.<locals>.hist   s>    */1 1&Wh C!3x=0 1 1 1s   +)rc   )r   rm   jrj   rh   s       @r   vars_by_fanoutro      s8    61 /@.F	G(!U1d1en
	GG	Gs   1c                   t        d | j                         D              }dt        |      z   dz   }| j                         D cg c]	  \  }}||f }}}t	        |d      D ]   \  }}t        |j                  |      |       " y c c}}w )Nc              3  D   K   | ]  }t        t        |              y wr   )r.   str).0r1   s     r   	<genexpr>z"print_histogram.<locals>.<genexpr>   s     <ACAK<s    z{:>zd}T)reverse)maxvaluesrr   r-   sortedprintformat)r2   count_width	count_fmtr0   r1   pairscountr6   s           r   print_histogramr      s    <)9)9);<<+c+&&-)'oo/
0daAq6
0%
0E40 )keT	)

5
!4() 1s   B
str | NoneDEFAULT_WORKSPACE_ROOTc                T    | j                  |      }|dk\  r| |t        |      z   d  S | S )Nr   )rfindr.   )filenameworkspace_rootis      r   _strip_workspace_rootr      s3    nn^$!-.!V!C''(	)AAr'   c                   t        t        j                  d      j                        }t        t        j                  d      j                        }t        t        j                  d      j                        }d|d<   |d   }g }| j	                         D ]  \  \  }}}	|g }
nNt        |j                          }|D cg c]+  \  }}t        j                  |j                        r|||f   - }
}}|j                  |
|	g|||j                     dgd        |j	                         D cg c]2  \  \  }}}|||   t        j                  j                  ||      dgd4 }}}}g }|j	                         D ]w  \  }}|j                  }|j                  }|2t!        ||      }|j#                  d	      j%                  d
d       d| }|j                  |||   ||   |j&                  d       y |d   |d   dg}t)        j*                  t-        |j/                               ||||d      }t1        j2                  t        j4                  j7                  |            S c c}}w c c}}}w )zConverts a profile into a compressed pprof protocol buffer.

  The input profile is a map from (traceback, primitive) pairs to counts.
     r    r5   )r#   rr   )location_idvaluelabel)function_idline)idr   z.py/.)r   r6   r   
start_line	equationsr~   )typeunit)string_tablelocationfunctionsample_typesample)r   	itertoolsr~   __next__r-   zip
raw_framesr   is_user_filenameco_filenamer!   r6   r   	Tracebackcode_addr2lineco_qualnamer   removesuffixreplaceco_firstlinenojsondumpsr    keysgzipcompress_xlajson_to_pprof_profile)profiler   sfunclocprimitive_keysamplestbr5   r~   framesr   codelastiloc_id	locations	functionsfunc_idr   r6   r   json_profiles                         r   _pprof_profiler      s    )//!$--.!	Y__Q'00	1$IOOA&//0#
!B%K.-' ' or9u	zf(j6@ H{tU#44T5E5EF T5M" Hf HNN)..!
  ( $'99;	   -4  $T
#--<<T5IK LM)  )zz| mdGHD!&x@h%%e,44S#>?qGd$hK))	+ K.!G*=>+ N , 
z<<\J	KKSHs   >0I%.7I+)r   c               d    t        d t        | d      D              }t        ||xs t              S )a  Generates a pprof profile that maps jaxpr equations to Python stack traces.

  By visualizing the profile using pprof, one can identify Python code that is
  responsible for yielding large numbers of jaxpr equations.

  Args:
    jaxpr: a Jaxpr.
    workspace_root: the root of the workspace. If specified, function names
      will be fully qualified, with respect to the workspace root.

  Returns:
    A gzip-compressed pprof Profile protocol buffer, suitable for passing to
    pprof tool for visualization.
  c              3  f   K   | ])  \  }}|j                   j                  |j                  f + y wr   )r>   	tracebackr5   )rs   r%   r   s      r   rt   z)pprof_equation_profile.<locals>.<genexpr>   s/      
!S   #--0s   /1F)r   )r   r   r   r   )r   r   r$   s      r   pprof_equation_profiler      s7       U? ! 
>C-C	DDr'   c              #     K   | j                   D ],  }t        |j                        D ]  \  }}||k(  s||f  , . yw)zMFind all the equations which use invar and the positional index of its binderN)r   	enumeraterb   )r   invarr   invar_indexeqn_vars        r   eqns_using_var_with_invar_indexr      sL     ZZ c )#** 5 W	E	;s   0??c              #    K   | j                         D ]  }t        |t              r|n|f}|D ]  }t        |t        j                        r;|t        |j                        k\  rt        d| d      ||j                  |   f Xt        |t        j                        ss|t        |j                  j                        k\  rt        d| d      |j                  |j                  j                  |   f   y w)NzFailed to find index z& in jaxpr.invars while building report)
rw   rH   tupler   Jaxprr.   rb   RuntimeErrorClosedJaxprr   )paramsindexvalvalsr1   s        r   jaxpr_and_binder_in_paramsr      s     ]]_ 
-cS%(3sfD -	Atzz	"CM!4UG;abc
c%  a))*C''4UG;abc
cggqww~~e,,,-
-s   BC= AC=c              #     K   t        | |      D ]I  \  }}t        t        |j                  |            x}r|D ]  \  } }t	        | |      E d{     F| K y7 w)z(Find the leaf equations using a variableN)r   r   r   r   eqns_using_var)r   r   r   r   child_jaxprs_and_varss        r   r   r     so      :%G c;!&'A#**k'Z![[[1 0.5%!%///0 i 	0s   AAAAc                6   t        j                  t        j                  j                        x}syt        j
                  j                  j                  d      }d|vrd|vryt        t              }d|v rRt        j                  t        j                  d| |       |d|dd|  d	z  }|j                  |j                                d|v rMt        j                  t        j                  d
| |       |d|dd|  dz  }|j                  t        |             | S )a"  Maybe dumps the `jaxpr` to a file.

  Dumps the jaxpr if JAX_DUMP_JAXPR_TO is defined.

  Args:
    fn: The name of the function whose jaxpr is being dumped.
    jaxpr: The jaxpr to dump.

  Returns:
    The path to the file where the jaxpr was dumped, or None if no file was
    dumped.
  N,r   eqn_count_pprofzDumping jaxpr for %s to %s.jax_06dr%   z
.jaxpr.txtz%Dumping eqn count pprof for %s to %s.z.eqn_count_pprof)r   make_jax_dump_dirr
   jax_dump_ir_tor   jax_dump_ir_modessplitnext_jaxpr_id_counterlogginglogINFO
write_textpretty_printwrite_bytesr   )fun_namer   out_dirmodesr   
jaxpr_patheqn_prof_paths          r   maybe_dump_jaxpr_to_filer     s    ++F,A,A,G,GH
H'
H

"
"
(
(
.
.s
3%E/u<"KK3Xw T"S8*J??J%,,./%KK=x RHAhZ7GHHM4U;<	/r'   )r   
core.Jaxprr   zset[core.Jaxpr] | Nonereturn*Iterator[tuple[core.Jaxpr, core.JaxprEqn]])T)r   r   r   boolr   r   )r   r   r#   r   )r   r   r#   r   r/   r   )r   r   )r2   zdict[Any, int])r   rr   r   rr   r   rr   r   )r   z=dict[tuple[xla_client.Traceback | None, core.Primitive], int]r   r   r   bytes)r   r   r   r   r   r   )r   r   r   r`   r   z#Iterator[tuple[core.JaxprEqn, int]])r   intr   z%Iterator[tuple[core.Jaxpr, core.Var]])r   r   r   r`   r   zIterator[core.JaxprEqn])r   rr   r   r   r   r   ):__doc__
__future__r   collectionsr   r   collections.abcr   r   r   r   r   typestypingr   r   r	   jax._srcr
   r   r   r   r   jax._src.libr   safe_maprP   
unsafe_mapsafe_zipr   
unsafe_zip	getLogger__name__loggerr   r   r&   r2   r9   rD   rR   rU   JaxprEqnr_   rc   ro   r   r   __annotations__r   r   r   r   r   r   r~   r   r   r)   r'   r   <module>r     s   " " , $       $     % #--Z--Z			8	$
.
. 6
./
. 59GG-1G/G #.44
:+,
 $%!9FH) &* 
 )B "&@LJ@L@L @LH 9=E+5EAFE,-	 $IOO% !!$!!r'   