
    J-j_                   4   U 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Zd dlZd dl	Z	d dl
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mZ d dlmZmZmZmZmZ d dlmZ d dlmZ dd	lmZm Z  erd d
l!m"Z"m#Z#m$Z$ d dl%m&Z& d dl'm(Z( ddl)m*Z* d dl+Z+d dl,Z,d dl-Z,d dl.m/c m0Z1 d dl2m3Z3m4Z4 d dl5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z; d dl<m=Z=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZDmEZEmFZF d dlGmHZH ddlImJZJmKZKmLZLmMZMmZmNZN ddlOmPZP ddlQmRZRmSZSmTZT ddlUmVZVmWZW ddlMmXZXmYZYmZZZm[Z[ ddl\m]Z]m^Z^ ddl_m`Z` ddlmaZambZbmcZcmdZdmeZemfZf ddlgmhZh dd limjZjmkZk dd!llmmZmmnZn dd"lompZpmqZq dd#lrmsZs dd$l/mtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZ dd%lmZ  ej                  e      Ze,j                  j                  ed&      Ze,j                  j                  ed'      Ze,j                  j                  ed(      Ze,j                  j                  ed)      Zed*   Zd+ed,<    ed-      Z ed.      Zej,                   G d/ d0             Zej,                   G d1 d2             Z G d3 d4      Zej,                   G d5 d6             Zej,                   G d7 d8e             Z G d9 d*      Zej:                  dld:       Zdmd;Zdnd<Zdod=Z ej,                  d>?       G d@ dA             ZdpdBZ G dC dD      Z	 	 	 	 	 	 	 	 dqdEZ G dF dGe      Z G dH dIe      Z G dJ dKe      Z	 	 	 	 drdLZ	 	 	 	 	 	 	 	 dsdNZ G dO dPe      Z G dQ dRe      Z G dS dTe      Z G dU dVe      Z G dW dXe      Z	 dt	 	 	 	 	 	 	 dudYZ	 	 	 	 	 	 dvdZZdwd[Z	 	 	 	 	 	 	 	 	 	 	 	 dxd\Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dyd]Zej,                   G d^ d_             Z ejl                         Zdzd`Zd{daZ	 	 	 	 d|dbZd}dcZd}ddZd~deZd~dfZd~dgZd~dhZ G di dM      Z G dj dk      Zy)    )annotationsN)Counterdefaultdict)as_completedFuture)AnyGenericTYPE_CHECKING	TypeAliasTypeVar)	ParamSpec
OrderedSet   )ComputedBuffer	Pointwise)CallableIteratorSequence)
ModuleType)EnterCudaStreamContextLine)PythonWrapperCodegen)countersdynamo_timed)use_pipelined_autotuning)LambdaFuturePyCodeCache)TritonTemplateCallerBase)get_metric_tableis_metric_table_enabled)get_stream_name)free_symbols)free_symbol_is_typesymbol_is_typeSymT)
has_triton)commsconfigconfig_commsdependenciesirmetrics)can_codegen_without_upcasts)BackendFeatureget_scheduling_for_deviceKernel) estimate_nccl_collective_runtime/estimate_nccl_collective_runtime_nccl_estimator)Dep	MemoryDepStarDepWeakDep)GPUTooOldForTritonTritonMissing)count_flops_fx)assign_origin_nodeget_device_typeGraphPartitionSignatureMultiOutputMultiOutputLayout
NoneLayout)LoopBody)MemoryPlanningInfoForBufferMemoryPlanningInfoForNode)DevicePropertiesReductionHint)
green_textred_text)SimplifyIndexing)&_unstable_customized_partition_wrappercache_on_selfcmpdevice_need_guardget_current_backendget_device_tflopsget_dtype_sizeget_gpu_dram_gbpsget_op_namesGraphPartitionMapIndentedBufferis_collectiveis_cudagraph_unsafe_opis_gpuis_multi_outputs_template#is_output_of_multi_outputs_templateis_waitsympy_product)Vfusionloop_orderingcompute_dependencies
cudagraphsBaseSchedulerNoder   PartitionType_T_Pc                  l    e Zd ZU dZded<   dZded<   dZded<   d Zedd	       Z	e	 d	 	 	 dd
       Z
y)FusionResultNzbool | Noneshould_fusezCallable[[], bool] | Nonecallable_fnLambdaFuture | Nonefuturec                L    | j                   d u| j                  d uz  sJ d       y )NzLFusion result should contain either fusion decision or callable_fn, not both)re   rf   selfs    g/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/torch/_inductor/scheduler.py__post_init__zFusionResult.__post_init__s   s0      ,1A1A1MN 	
Z	
N    c                    t        |      S )N)re   rd   )clsre   s     rl   fusezFusionResult.fusex   s    44rn   c                    t        ||      S )Nrf   rh   rp   )rq   rf   rh   s      rl   from_callablezFusionResult.from_callable|   s     FCCrn   )re   boolN)rf   Callable[[], bool]rh   rg   )__name__
__module____qualname__re   __annotations__rf   rh   rm   classmethodrr   ru    rn   rl   rd   rd   m   sf    #K#-1K*1"&F&

 5 5 LPD,D6ID Drn   rd   c                  B    e Zd ZU ded<   ded<   ded<   dZded<   d
d	Zy)PendingFusionrx   rf   r_   node1node2Nrg   rh   c                2    | j                   | j                  fS rw   r   r   rj   s    rl   get_fusion_nodeszPendingFusion.get_fusion_nodes   s    

DJJ''rn   )return+tuple[BaseSchedulerNode, BaseSchedulerNode])ry   rz   r{   r|   rh   r   r~   rn   rl   r   r      s$    ##"&F&(rn   r   c                  $   e Zd ZdZedd       Zedd       Ze	 	 	 	 	 	 dd       Zedd       Z	e	 	 	 	 	 	 dd       Z
e	 	 	 	 	 	 dd       Zedd       Ze	 	 	 	 	 	 dd	       Zedd
       Ze	 	 	 	 	 	 dd       Zedd       Zedd       Zy)MixOrderReductionz
    This class contains utility functions to decide if we should fuse reductions
    reducing across different dimensions of the same input tensor.
    c                f    | j                         xr  t        d | j                         D              S )Nc              3     K   | ]V  }t        |t              rD|j                         r4t        |j                  t              r|j                  j
                  d u X y wrw   )
isinstanceSchedulerNodeis_reductionnoder   _split_size.0subnodes     rl   	<genexpr>z7MixOrderReduction.is_split_reduction.<locals>.<genexpr>   sK      +
+'=1$$&7<<8	 LL$$D0+s   AA)r   all	get_nodesr   s    rl   is_split_reductionz$MixOrderReduction.is_split_reduction   s3      " 
s +
>>++
 (
 	
rn   c                `   | j                  |      rd }d }|j                         D ]n  }t        |t              r*|j	                         rt        |j
                  t              s?|j
                  j                  J t        j                  j                  j                  t        |j
                  j                              }|j
                  j                  J t        j                  j                  j                  t        |j
                  j                              }||}|}t        j                  j                  j                  ||      sJ | d|        t        j                  j                  j                  ||      reJ | d|         |J ||fS |j                  d   S )N v.s. r   )r   r   r   r   r   r   r   _original_rangesrZ   graphsizevarssimplifyrY   _original_reduction_rangesstatically_known_equalsgroup)rq   r   xnumelrnumelr   	curxnumel	currnumels          rl   get_numel_rnumelz"MixOrderReduction.get_numel_rnumel   s   !!$'FF>>+w6,,."7<<@||44@@@GG,,55!',,"?"?@	 ||>>JJJGG,,55!',,"I"IJ	 >&F&F77++CC	 4 	{34  77++CC	 4 	{34 1 ,8 %%%F##::a= rn   c                    | j                  |      }| j                  |      }t        |      dk7  st        |      dk7  s||k(  ryt        |      t        t        |            k(  S )N   F)r   lentuplereversed)rq   r   r   g1g2s        rl   has_mix_reduction_ordersz*MixOrderReduction.has_mix_reduction_orders   sZ     !!%(!!%(r7a<3r7a<28RyE(2,///rn   c                R   d}|j                   j                  D ]&  }t        |t              s|j                  |k(  s$|} n |sy|j
                  }|j                   j                  }|sDt        |t              sJ t        |              |j                  d   j                   j                  }|sJ t        |      t        |j                        z
  syt        j                  j                  j                  t!        |j"                        t!        |j%                                     ryy)z@
        The access to 'buf' is not a broadcast access.
        NFr   T)read_writesreadsr   r4   nameindex
var_rangesFusedSchedulerNodetypesnodesr   r"   rZ   r   r   r   rY   sizevalues)rq   bufr   	found_depdepr   r   s          rl   _is_full_accessz!MixOrderReduction._is_full_access   s    
 	##))C#y)chh#o	 *
 %%00
d$67HDJ<H7Q33>>Jz:&E4F4F)GG
 7733)..)=9J9J9L+M
 rn   c                    g }|j                         |j                         z  }|D ]9  }| j                  ||      s| j                  ||      s)|j                  |       ; |S rw   )used_buffer_namesr   append)rq   r   r   outcommon_readsr   s         rl   get_common_readz!MixOrderReduction.get_common_read   s`     ..053J3J3LLC""3.33F3FsE3R

3   
rn   c                >    t        | j                  ||            dkD  S Nr   )r   r   rq   r   r   s      rl   has_common_readz!MixOrderReduction.has_common_read   s!     3&&ue4599rn   c                    | j                  |      }t        j                  j                  j	                  |d   |d   z  d      S )Nr   r   fallback)r   rZ   r   r   optimization_hint)rq   r   r   s      rl   	get_numelzMixOrderReduction.get_numel  s>    !!$'ww11"Q%"Q%-!1LLrn   c                $    | j                  |      S rw   )r   r   s      rl   get_fusion_scorez"MixOrderReduction.get_fusion_score	  s    
 }}U##rn   c                x   t         j                  j                  syt        j                  j
                  ry|j                         r|j                         sy|j                         j                  }|dvst        |      dk7  ry|j                         r|j                         sy|j                  |j                         z  s|j                  |j                         z  ry| j                  ||      syt        j                  ||      }t!        |      dk(  ry| j#                  |      r||}}n| j#                  |      r||}}ny| j%                  |      }|\  }}	t         j                  j&                  sd}
t        j                  j(                  j+                  t-        j.                  ||	z  |
            syt        j                  j(                  j+                  t-        j.                  ||	dz              syt        j                  j(                  j+                  t-        j.                  |d            syt1        d |j3                         D              ryt        j                  j(                  j5                  |	d	      syt        j7                  |      ryt9        d
 |j3                         D              }|S )zP
        Check whether we can fuse two reductions with mix loop orders.
        F)cudaxputritonr   i  P r   i   c              3     K   | ]T  }|j                         rB|j                  j                  j                  t        j
                  t        j                  fv V y wrw   )r   r   datareduction_hintrD   INNERDEFAULTr   s     rl   r   z-MixOrderReduction.can_fuse.<locals>.<genexpr>[  sT      
 7##% LL,,##%%
 7s   AAi @  c              3  t   K   | ]0  }|j                         r|j                  j                         d v  2 yw)>   sumprodN)r   r   get_reduction_typer   s     rl   r   z-MixOrderReduction.can_fuse.<locals>.<genexpr>q  s?      
 2##% LL++-
 2s   68)r(   r   mix_order_reductionrZ   r   cpp_wrapperrU   
get_devicer   rL   r   	ancestorsget_operation_namesr   r   r   r   is_contiguous_noder   #mix_order_reduction_non_strict_moder   guard_or_truesympyGeanyr   statically_known_leqr   r   )rq   r   r   device_typer   contiguous_node
other_noder   nrowncol
size_thresr   s               rl   can_fusezMixOrderReduction.can_fuse  sJ   
 }}00 77||~U\\^&&(--.";/8;!!#5+=+=+?OOe7799OOe7799  ++E59 )88F|!!!%(*/ZO##E**/ZO!!/2
d }}@@ #J
 77##11%((4$;
2ST
 77##11%((42JK
 77##11%((42FG  
 +446
 
 
 ww44T9E//@  
 &//1
 
 
rn   c                &    | j                  ||      S rw   )r   r   s      rl   are_mix_order_reductionsz*MixOrderReduction.are_mix_order_reductions|  s     ||E5))rn   c                \     t         fdj                  j                  D              syy)Nc              3  V   K   | ]   }j                  |j                         " y wrw   )is_contiguous_loadr   )r   r   rq   r   s     rl   r   z7MixOrderReduction.is_contiguous_node.<locals>.<genexpr>  s'      
>TsC""388T2>T   &)FT)r   r   r   )rq   r   s   ``rl   r   z$MixOrderReduction.is_contiguous_node  s,     
>B>N>N>T>T
 
 rn   c                   ddl m} |j                         D ]  }t        |t              sJ |j
                  }|j                  |j                     }|D cg c]  }|j                  |k(  s|j                    }}t        |      dk(  rr|D ]u  }	|j                  |	   }
|j                  }t        |j                               }t        j                   j"                  j%                  |
||      }|d   dk(  rk|d   dk(  rt  y  yc c}w )Nr   )MemoryUsageTyper   FT)torch._inductor.loop_bodyr   r   r   r   _bodymemory_usageLOADbuffer_name
index_namer   indexing_exprsr   listkeysrZ   r   r   stride_vars)rq   r   parent_noder   r   	loop_bodyentrieseindex_namesr   
index_exprr   var_symbolsr  s                 rl   r   z$MixOrderReduction.is_contiguous_load  s    =))+DdM222

I,,_-A-ABG18QAAMMS<P1<<KQ;1$ *
&55jA
&11
 #:??#45gg..:: $B1,B10D  * ,2 + Rs   D*DNr   r_   r   rv   )r   r_   r   ztuple[sympy.Expr, sympy.Expr]r   r_   r   r_   r   rv   )r   strr   r_   r   rv   )r   r_   r   r_   r   	list[str])r   r_   r   intr   r_   r   r_   r   r  )r   r  r  r_   r   rv   )ry   rz   r{   __doc__staticmethodr   r}   r   r   r   r   r   r   r   r   r   r   r   r~   rn   rl   r   r      sv   
 
 
 #! #!J 	0%	0.?	0		0 	0  B 	%	.?			 	 :%:.?:	: :
 M M $%$.?$	$ $ h hT *%*.?*	* *
    rn   r   c                      e Zd ZU ded<   ded<   ded<    ej
                  e      Zded	<    ej
                  e      Z	d
ed<   ddZ
ddZddZddZddZddZddZddZddZddZy)SchedulerBuffer	Scheduler	schedulerz	ir.Bufferr   BaseSchedulerNode | Nonedefining_op)default_factorylist[NodeUser]usersrA   
mpi_bufferc                B    | j                   }|J |j                         S rw   )r  get_name)rk   ops     rl   defining_op_namez SchedulerBuffer.defining_op_name  s#    ~~{{}rn   c                @    t        | j                  j                        S rw   )hashr   r   rj   s    rl   __hash__zSchedulerBuffer.__hash__  s    DIINN##rn   c                v   t               }| j                         }|j                  | dt        | j                        j
                          |j                  | d| j                  j                          | j                         r-|j                  | dt        | j                                       | j                         r-|j                  | dt        | j                                       t        | j                        dk  r0|j                  | d| j                          |j                         S |j                  | d       |j                  d      5  | j                  D ]  }|j                  | d        	 d d d        |j                  d	       |j                         S # 1 sw Y   *xY w)
N: z
.layout = z.aliases = z.mutations = r   z	.users = z
.users = [,])rR   r  	writeliner   r   ry   layoutget_aliasespformatget_mutationsr   r  indentgetrawvalue)rk   resultr   users       rl   	debug_strzSchedulerBuffer.debug_str  sy   !}}D6DO$<$<#=>?D6DII,<,<+=>?v[9I9I9K1L0MNOv]74;M;M;O3P2QRStzz?avYtzzl;< !!## vZ01q! JJD$$vQZ0 ' " S!!!##	 "!s   &F//F8c                6    | j                   j                         S rw   r   r  rj   s    rl   r  zSchedulerBuffer.get_name      yy!!##rn   c                   | j                   J | j                   j                         sy | j                   j                         sL| j                   j                         s2t	        | j                   j                         t        j                        r4t        j                  j                  j                  | j                          y t        t        j                  d      r| j                         t        j                  j                  v rt        j                  j                  | j                            }|| j                   j"                  v r$| j                   j"                  |   j                   }n#| j                   j$                  |   j                   }t        j                  j                  j'                  || j                          y t        j                  j                  j                  | j                          y )Nargs)r   should_allocateget_inputs_that_alias_outputget_mutation_namesr   get_output_specr+   CommBufferLayoutrZ   r   wrapper_codecodegen_allocationhasattrkernelr  inplace_update_buffersr  name_to_donated_buffername_to_bufcodegen_inplace_reuse)rk   input_buffer_nameinput_buffers      rl   allocatezSchedulerBuffer.allocate  sV   yy$$$yy((* II224yy++-$))335r7J7JKGG  33DII> AHHf%188#B#BB !" ? ? P DNN$I$II#~~DD% $   $~~99:KLQQGG  66		
 GG  33DII>rn   c                   | j                   J t        | j                   j                  t        j                        st        | j                         ry| j                  D ]  }t        |j                   t              s y yNFT)r   r   r'  r+   r?   rV   r  
OutputNode)rk   uses     rl   can_freezSchedulerBuffer.can_free  sb    yy$$$dii&&6:SII;
 ::C#((J/  rn   c                ,   i }|D ]o  }t        |j                        |v r>|j                  |t        |j                                 |t        |j                        <   X||t        |j                        <   q t        |j	                               | _        y rw   )idr   merger   r   r  )rk   r  r-  rH  s       rl   	set_userszSchedulerBuffer.set_users   so    &(C#((|v%'*yy3881E'Fr#((|$'*r#((|$	 
 &--/*
rn   c                R    | j                   J | j                   j                         S rw   )r   r6  rj   s    rl   r(  zSchedulerBuffer.get_aliases
  s%    yy$$$yy5577rn   c                R    | j                   J | j                   j                         S rw   )r   r7  rj   s    rl   r*  zSchedulerBuffer.get_mutations  %    yy$$$yy++--rn   c                R    | j                   j                         j                         S rw   )r   r8  r   rj   s    rl   r   zSchedulerBuffer.get_device  s    yy((*5577rn   Nr   r  r   r  r   Noner   rv   )r  r  r   rU  r   zSequence[str]r   torch.device | None)ry   rz   r{   r|   dataclassesfieldr   r  rA   r  r  r!  r/  r  rD  rI  rM  r(  r*  r   r~   rn   rl   r  r    sz    
O))-K--dCE>C.?k.?.?3/J+ 
$$($?B
+8.8rn   r  c                      e Zd ZU dZded<   y)SchedulerDonatedBufferNr  r  )ry   rz   r{   r  r|   r~   rn   rl   r]  r]    s    ,0K)0rn   r]  c                     e Zd ZU ded<   ded<   ded<   ded<   ded<   ded	<   ded
<   ded<   ded<   dZded<   ded<   ded<   dZded<   ded<   ded<   dZded<   dTdZdUd ZdVd!Z	dVd"Z
dVd#ZdWd$ZdVd%ZdXd&Z	 	 	 	 	 	 dYd'ZdZd(Zd[d)Zd\d*Zd]d+Z	 	 	 	 	 	 d^d,ZdXd-Zd_d.Zd_d/ZdXd0ZdXd1Z	 	 	 	 d`d2ZdVd3ZdVd4Zed_d5       Zed_d6       Zed\d7       Z ed\d8       Z!dad9Z"dbd:Z#dcd;Z$ddd<Z%d\d=Z&d\d>Z'd\d?Z(d\d@Z)d\dAZ*d\dBZ+d\dCZ,d\dDZ-dedEZ.d\dFZ/dXdGZ0	 df	 	 	 	 	 dgdHZ1edhdI       Z2edhdJ       Z3edhdK       Z4	 	 	 	 	 	 didLZ5	 	 	 	 	 	 djdMZ6edkdN       Z7dldOZ8edldP       Z9dmdQZ:dndRZ;e<	 	 	 	 dodS       Z=y)pr_   OrderedSet[str]r   z7tuple[torch.device, tuple[tuple[sympy.Expr, ...], ...]]r   
last_usager  min_input_distancemax_input_distance	min_order	max_orderrB   mpi_nodedict[str, str]mutation_renamesNir.Operation | Noner   list[SchedulerBuffer]outputsdict[str, SchedulerBuffer]outputs_by_namefloat | Noneoverride_estimated_runtimedependencies.ReadWritesr   OrderedSet[Dep]unmet_dependenciesFrv   writtenc                "    || _         d | _        y )Nc                     g S rw   r~   )r4  kwargss     rl   <lambda>z,BaseSchedulerNode.__init__.<locals>.<lambda>5  s    Brn   )r  debug_device_str)rk   r  s     rl   __init__zBaseSchedulerNode.__init__2  s    $-& 	rn   c                v   || _         t               | _        d| _        d| _        t        t
                  | _        d| _        |j                         D cg c]  }t        | j                  ||        c}| _        | j                  D ci c]  }|j                         | c}| _        i | _        y c c}w c c}w )Nr   F)r  r   r  )r   r   r   ra  rb  r  r`  rr  get_outputsr  r  rj  r  rl  rg  )rk   r   outputr   s       rl   _init_from_nodez!BaseSchedulerNode._init_from_node8  s    	#"#"#$
   **,
 - .. 
 -
 @D||L| 3|L !#
  Ms   B1	B6c                T    t        |       j                   d| j                         dS )Nz(name=)r   ry   r  rj   s    rl   __repr__zBaseSchedulerNode.__repr__R  s'    t*%%&fT]]_,?qAArn   c                   | j                         }t               }|j                  | dt        |       j                   dt        t        | dd            j                   d| dt        | j                  j                         d| dt        | j                         d| d	t        | j                  j                  | j                  z
         d| d
| j                   d| d| j                   d| d       |j                         5  | j                         D ]!  }|j                  |j                                # 	 ddd       |j!                  d       	 |j                  | j#                                |j+                         j-                         S # 1 sw Y   XxY w# t$        $ r t&        j)                  dd       Y Lw xY w)#Longer form printout for trace logsr#  (r   N)

.writes = 
.unmet_dependencies = .met_dependencies = .min_input_distance = .max_input_distance = z.outputs = [
        r%  Ignoring error in debug_str()Texc_info)r  rR   splicer   ry   getattrr)  r   writesrq  r   ra  rb  r+  rz  r/  r&  debug_str_extra	Exceptionlogwarningr,  rstrip)rk   r   r   r   s       rl   r/  zBaseSchedulerNode.debug_strU  s   }}

bd		QtGD&$$?@IIJ Kj))0012 3WT%<%<=> ?74#3#3#9#9D<S<S#STU VT445 6T445 6 	
	
 ZZ\'')

3==?+ *  	c	HJJt++-.  '')) \  	HKK7$KG	Hs   5FF F G Gc                     y)N r~   rj   s    rl   r  z!BaseSchedulerNode.debug_str_extrap      rn   c                $    | j                  |       S rw   )rw  rj   s    rl   _debug_str_for_devicez'BaseSchedulerNode._debug_str_for_devices  s    $$T**rn   c                   t        | j                  dd       }d}t        |t        j                  j
                  j                        r'd|j                  |j                         gdd      z   }nct        |t        j                  j
                  j                        r5d|j                  |j                         |j                         gdd      z   }|  | S )Nr   r  , F)shorten	multiline)r  r   r   torch	_inductorr+   r   
str_helperget_size	Reductionget_reduction_sizer   )rk   
maybe_datadata_strs      rl   debug_str_shortz!BaseSchedulerNode.debug_str_shortv  s    TYY5
j%//"4"4">">?j33$$&'% 4  H 
EOO$6$6$@$@Aj33..0*2O2O2QR 4  H
 z""rn   c                p    t         j                  d| | j                  | j                  j                         y )Nz(%s: unmet_dependencies = %s, writes = %s)r  inforq  r   r  rj   s    rl   log_detailszBaseSchedulerNode.log_details  s,    6####		
rn   c                     yNFr~   )rk   self_dep	other_deps      rl   reorder_loops_by_dep_pairz+BaseSchedulerNode.reorder_loops_by_dep_pair       rn   c                    d | j                   j                         D        D ci c]  }||v r|||    c}| _        | j                  | j                   j	                  | j                               y c c}w )Nc              3  4   K   | ]  }|j                     y wrw   r   r   r   s     rl   r   z9BaseSchedulerNode.update_mutated_names.<locals>.<genexpr>  s     Q-Pc-P   )r   reads_and_writesrg  set_read_writesrename)rk   renamesr   s      rl   update_mutated_namesz&BaseSchedulerNode.update_mutated_names  su     RT-=-=-N-N-PQ!
Qw '$-Q!

 	T--44T5J5JKL!
s   A2c                X    | j                  | j                  j                  |             y rw   )r  r   	with_readrk   r   s     rl   add_fake_depzBaseSchedulerNode.add_fake_dep  s!    T--77<=rn   c                B    t        d | j                         D              S )Nc              3  `   K   | ]&  }|j                         xs |j                          ( y wrw   )r(  r*  r   r   s     rl   r   z=BaseSchedulerNode.has_aliasing_or_mutation.<locals>.<genexpr>  s-      
@RCOO4!2!2!44@Rs   ,.)r   rz  rj   s    rl   has_aliasing_or_mutationz*BaseSchedulerNode.has_aliasing_or_mutation  s%     
@D@P@P@R
 
 	
rn   c                h    || _         | j                   j                  | _        | j                          y rw   )r   r   rq  
prune_deps)rk   rws     rl   r  z!BaseSchedulerNode.set_read_writes  s(    "&"2"2"8"8rn   c                b    | j                         }t        fd|D              }||z
  | _        y )Nc              3  B   K   | ]  }j                  ||        y wrw   )get)r   kmutation_real_names     rl   r   z3BaseSchedulerNode.set_last_usage.<locals>.<genexpr>  s      !U1"4"8"8A">   )used_or_aliased_buffer_namesr   r`  )rk   future_used_buffersr  used_bufferss     ` rl   set_last_usagez BaseSchedulerNode.set_last_usage  s0     88:!!U!UU&)<<rn   c                F    | j                   D ]  }|j                           y rw   )rj  rD  )rk   r   s     rl   mark_runzBaseSchedulerNode.mark_run  s    <<CLLN  rn   c                    t        d t        j                  | j                  j                  | j                  j
                        D              S )Nc              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   z6BaseSchedulerNode.used_buffer_names.<locals>.<genexpr>  s      
W HHWr  )r   	itertoolschainr   r   r  rj   s    rl   r   z#BaseSchedulerNode.used_buffer_names  s?     
 t'7'7'='=t?O?O?V?VW
 
 	
rn   c                \   t               t        j                  | j                  j                  | j                  j
                        D cg c]*  }t        |t              r|j                  s|j                  , }}t        |      dkD  r|j                         }j                  |       t        j                  j                  j!                  |      rC|j#                  fdt        j                  j                  |   j%                         D               t        |      dkD  rS c c}w )z
        Returns buffer names used by this node, including aliases.

        Note: is_fake WeakDeps are excluded since they are purely for ordering
        and should not affect buffer lifetime.
        r   c              3  *   K   | ]
  }|vr|  y wrw   r~   )r   alias
used_namess     rl   r   zABaseSchedulerNode.used_or_aliased_buffer_names.<locals>.<genexpr>  s'      "5 J.	 "5s   )r   r  r  r   r   r  r   r6   is_faker   r   popaddrZ   r   name_to_bufferr  extendr6  )rk   r   depsr  s      @rl   r  z.BaseSchedulerNode.used_or_aliased_buffer_names  s     '1l
 !t'7'7'='=t?O?O?V?VW
WsG, HHW 	 

 $i!m((*CNN3ww%%))#. !"!7!7"224"5 	 $i!m !
s   /D)c                L     t         fd j                  D               _        y )Nc              3  f   K   | ](  }|j                   j                  j                  vr| * y wrw   )r   r  available_buffer_namesr   r   rk   s     rl   r   z/BaseSchedulerNode.prune_deps.<locals>.<genexpr>  s/      -
.xxt~~DDD .s   .1r   rq  rj   s   `rl   r  zBaseSchedulerNode.prune_deps  s#    ", -
..-
 #
rn   c                     d fdt        fd j                  j                  D              } j                   j                  j	                  |             y )Nc                   t        | t              sy| j                  j                  j                  vryj                  j                  | j                     j                         }|t        j                  j                  v S r  )	r   r6   r   r  r@  r  rZ   r   removed_operations)r   op_namerk   s     rl   should_prunez7BaseSchedulerNode.prune_weak_deps.<locals>.should_prune  s_    c7+xxt~~999nn00:KKMGagg8888rn   c              3  4   K   | ]  } |      s|  y wrw   r~   r   r   r  s     rl   r   z4BaseSchedulerNode.prune_weak_deps.<locals>.<genexpr>  s      
1C\#5FC1   r   r3   r   rv   )r   r   r   r  remove_reads)rk   	to_remover  s   ` @rl   prune_weak_depsz!BaseSchedulerNode.prune_weak_deps  sN    	9  
++11
 
	 	T--::9EFrn   c                F    t        | || j                  j                         y rw   )_prune_redundant_depsr  r@  )rk   name_to_fused_nodes     rl   prune_redundant_depsz&BaseSchedulerNode.prune_redundant_deps  s     	d$68R8RSrn   c                R    | j                   J | j                   j                         S rw   )r   get_operation_namerj   s    rl   r  zBaseSchedulerNode.get_name  rP  rn   c                "    | j                         S rw   r  rj   s    rl   get_first_namez BaseSchedulerNode.get_first_name  s    }}rn   c                B    t        d | j                         D              S )Nc              3  <   K   | ]  }|j                           y wrw   r  r   r   s     rl   r   z8BaseSchedulerNode.get_operation_names.<locals>.<genexpr>  s     G6Fd$--/6F   )r   r   rj   s    rl   r   z%BaseSchedulerNode.get_operation_names  s    Gdnn6FGGGrn   c                :    t        d | j                  D              S )Nc              3  <   K   | ]  }|j                           y wrw   r  r   r   s     rl   r   z5BaseSchedulerNode.get_buffer_names.<locals>.<genexpr>  s     ALS#,,.Lr  )r   rj  rj   s    rl   get_buffer_namesz"BaseSchedulerNode.get_buffer_names  s    ADLLAAArn   c                B    t        d | j                         D              S )Nc              3  Z   K   | ]#  }t        |t              xr t        |d        % yw)T)disallow_fp32_opsNr   r   r-   r   ns     rl   r   zABaseSchedulerNode.can_codegen_in_low_precision.<locals>.<genexpr>   s7      
 & q-( G+AFG%s   )+r   r   rj   s    rl   can_codegen_in_low_precisionz.BaseSchedulerNode.can_codegen_in_low_precision  s%     
 ^^%
 
 	
rn   c                B    t        d | j                         D              S )Nc              3  V   K   | ]!  }t        |t              xr t        |       # y wrw   r  r  s     rl   r   z@BaseSchedulerNode.can_codegen_without_upcasts.<locals>.<genexpr>  s-      
% q-(K-H-KK%s   ')r  rj   s    rl   r-   z-BaseSchedulerNode.can_codegen_without_upcasts  s#     
^^%
 
 	
rn   c                    | gS rw   r~   rj   s    rl   r   zBaseSchedulerNode.get_nodes  s	    vrn   c                    | j                   S rw   )rj  rj   s    rl   rz  zBaseSchedulerNode.get_outputs  s    ||rn   c                     | j                   |   S rw   )rl  )rk   buf_names     rl   
get_outputzBaseSchedulerNode.get_output  s    ##H--rn   c                R    | j                   J | j                   j                         S rw   )r   r   rj   s    rl   r   zBaseSchedulerNode.get_device  s%    yy$$$yy##%%rn   c                L    | j                         }|d uxr |j                  dk(  S Ncpu)r   r   rk   devices     rl   is_cpuzBaseSchedulerNode.is_cpu  s'    "T!:fkkU&::rn   c                X    | j                         }|d uxr t        |j                        S rw   )r   rU   r   r  s     rl   rU   zBaseSchedulerNode.is_gpu  s'    "T!9fV[[&99rn   c                     yr  r~   rj   s    rl   r   zBaseSchedulerNode.is_reduction"      rn   c                     yr  r~   rj   s    rl   is_native_matmulz"BaseSchedulerNode.is_native_matmul%  r  rn   c                     yr  r~   rj   s    rl   is_split_scanzBaseSchedulerNode.is_split_scan(  r  rn   c                     yr  r~   rj   s    rl   is_templatezBaseSchedulerNode.is_template+  r  rn   c                     yr  r~   rj   s    rl   	is_externzBaseSchedulerNode.is_extern.  r  rn   c                     yr  r~   rj   s    rl   
is_foreachzBaseSchedulerNode.is_foreach1  r  rn   c                     yr  r~   rk   read_deps     rl   can_inplacezBaseSchedulerNode.can_inplace4  r  rn   c                     yr  r~   rj   s    rl   has_side_effectsz"BaseSchedulerNode.has_side_effects7  r  rn   c           	         ddl m} t         t              rt        j
                  rt        j                  j                   j                         t        j                        r{t        t        j                  t        j                  j                  j                   j"                        rt%        t        j                  dd      t'        t        j                  d      sy j(                  t        j                  j*                  z   j,                  j.                  z  }d fd} j1                         D ]Q  }|j2                  }|J |j5                         rr|j7                         sb|j9                         sR|j;                         t        j                  j<                  v s(t        |j?                         t@        jB                        r jD                  jF                  D ]  }|jH                   j,                  jJ                  v r$ j,                  jJ                  |jH                     }n/ j,                  jL                  jO                  |jH                        }|s|t        j                  jP                  jS                  |       st        |jT                  tV              r|jX                  J |jX                  D cg c]   }|j2                  j;                         |vr|" }	} j,                  j[                  |jH                         }
|
r/t]        |	      dk(  s?|	d   j^                  sP|	d   j2                   u sc|j2                  qt        |j2                  j?                         t@        j`                  t@        jb                  t@        jd                  t@        jB                  f      r|jT                  rft        |jT                  j2                  t@        jf                  t@        jh                  f      r(t]        |j2                  j7                               dkD  rE ||j2                  |j2                        sd ||      snt        j                  jj                  jm                  |j;                         |j;                                t        t        j                  t        j                  j                  j                   j"                        rnt        j                  jn                  jq                  |j;                                t        j                  jn                  jq                  |j;                                |j;                         t        j                  jr                  |j;                         <    Q T yc c}w )	z~
        Decide if there should be inplace updates for the node
        and record the decision in the active kernel.
        r   )can_match_buffer_size	mutationsNr4  c                   | j                   j                        }| j                         t               }| j                  D ]  }|j
                  }t        |t              s |j                         | j                   j                  vs| j                   j                  |      |urd|fd|j                  j                         D        z  }t        |      dkD  s y y)Nc              3  @   K   | ]  }|j                   k(  r|  y wrw   r  )r   or  s     rl   r   z^BaseSchedulerNode.decide_inplace_update.<locals>.single_index_in_fused_node.<locals>.<genexpr>m  s%      Evv) E   r   FT)r  get_fused_noder  r   r  r   r   r_   r  r  r   r  r   )buf_to_be_inplaced
fused_noder  r.  	user_noder  rk   s        @rl   single_index_in_fused_nodezKBaseSchedulerNode.decide_inplace_update.<locals>.single_index_in_fused_nodeU  s    
 ,55DDTJJ)224H %/LD*00 II	!)->? ,,.-77JJK)33BB9M%&  &22CCE 
 t9q= ' 1* rn   r   )r3  r  r   rv   ):codegen.wrapperr,  r   r   r(   inplace_buffersrZ   r   has_featurer   r.   INPLACE_BUFFERSr=  r  r  codegensimd
SIMDKernelr  r<  r   r  r  completed_operationsrz  r   r5  r6  r7  r  removed_buffersr8  r+   r9  r   r   r   r?  r@  r  r:  	can_reuser  NopKernelSchedulerNoder  has_cross_stream_hazardr   r(  r?   r>   MutationLayoutSHOULDREMOVEFallbackKernelr=   r4  make_inplacer-  r  r>  )rk   r,  inconsequential_nodesr6  r   buf_noderead	input_bufxremaining_usesrB  s   `          rl   decide_inplace_updatez'BaseSchedulerNode.decide_inplace_update:  s   
 	; t]+&&##DOO$5~7U7UVqxx)@)@)E)E)P)PQ188[$7C &) NNgg(()nn112 	 	D ##%CxxH''',,.88:..0<<>QWW%<%<< h668":M:MN((..99 E EE $ E Edii PI $ : : > >tyy II ,,66y$G&y'<'<>TU$??666 "+&!0A66??,4II !0 # &
 /3nn.T.T		4/+
 4/14*1-99*1-22d:%NN6 *%NN::< " " 4 4 " = = " 3 3	! &11 * ) 5 5 : :!#!2!2BNN C! !$INN$O$O$Q RUV V1)..#((K6yA
 2293E3E3GX%HHeoo&=&=&B&B&M&M HH..2293E3E3GHHH..223<<>B &..0 77G } / &6&s   ?%V
c                R   t         j                  sy |r| j                  ry | j                  J | j                  j	                         }g }|D ]0  }|j
                  dk(  r|j                  d       |j                  d       d|j
                   d|j                   }d|j                  v r|d|j                  d    z   }|j                  |       d|j                  v s|j                  d    }|j                  d	d
      d   }|j                  d|j                  dd      j                  dd      j                  dd      j                  dd      z          |j                  d       |j                  d       3 t        |      dk(  ry |j                  |       d| _        y )Nr{  r  z#pragma CMT ORIGIN:z#pragma CMT  seq_nrz seq_nr:stack_trace|r   )maxsplitr   {z{{}z}}r  \z\\z#pragma CMT END ORIGINr   T)r(   comment_originrr  r   get_originsr  r   targetmetarsplitreplacer   
writelines)	rk   buffer	only_onceorigins	out_linesr0  op_info_strrP  stack_trace_last_lines	            rl   codegen_originating_infoz*BaseSchedulerNode.codegen_originating_info  s    $$yy$$$))'')	AttxR 23(az:K166!)hqvvh7G6H,II[)&!"!6 7(3(:(:3(:(KB(O%  "+33C>WS$'WT4(Wf	   !9:  $3 6 y>Q 	)$rn   c                (    | j                  dd      S )NTinclude_readsinclude_writes!get_read_write_buffers_sizes_implrj   s    rl   get_read_write_buffers_sizesz.BaseSchedulerNode.get_read_write_buffers_sizes  s    55t 6 
 	
rn   c                (    | j                  dd      S )NTFre  rh  rj   s    rl   get_read_buffer_sizesz'BaseSchedulerNode.get_read_buffer_sizes  s    55u 6 
 	
rn   c                (    | j                  dd      S )NFTre  rh  rj   s    rl   get_write_buffer_sizesz(BaseSchedulerNode.get_write_buffer_sizes   s    55 6 
 	
rn   c                Z    t        | j                  ||      j                         d      S )Nre  r   )start)r   get_read_write_buffer_accessesr   )rk   rf  rg  s      rl   ri  z3BaseSchedulerNode.get_read_write_buffers_sizes_impl  s3     //+N 0 fh	
 	
rn   c                    t         t              ri S t         t              rt         j                  t              ri S t         t              r`t         j                  t
        j                        r< j                  j                  t        j                  j                  j                  u ri S ddt         t              r@ t         j                         d         t         j                         d         z        nt        d      t!        j"                  t$              }|r9 j&                  j(                  D ]   }||j*                     j-                  |       " |r9 j&                  j.                  D ]   }||j*                     j-                  |       " |r&t1        d  j&                  j(                  D              n	t1               }|r&t1        d  j&                  j.                  D              n	t1               }d fdt         t2              rt1         fd|D              }||z
  }||z
  }i }||z  D ]  }	t5        fd	||	   D              |	t6        j8                  j:                  v rt6        j8                  j:                  |	   }
n;|	t6        j8                  j<                  v rt6        j8                  j<                  |	   }
n	 	 	 	 d fd
 |
      }|	|vr|||	<   ||	xx   |z  cc<    |S )az  
        Counting the number of bytes accessed for a kernel is
        surprisingly tricky. In particular, there is a differentiation
        between 'theoretical' memory accesses and practical memory
        accesses. For example, a layernorm kernel may actually access an
        input 3 times, but in theory, it only needs to access its input
        once (and may be optimized to do so through say, persistent
        reductions)

        Another example is that even though a buffer is passed in, we may
        not access the entire buffer. This may occur if we are accessing
        a slice of the buffer. Another tricky case is for indirect
        indexing, where the amount of bytes accessed depends on the
        values of the input.

        What this function aims to compute is the memory accesses for
        worst-case inputs, best-case optimization. What this means is
        that for each buffer we compute the amount of potential accesses in two ways and take the minimum.

        1. Numel in ranges multiplied by number of deps the buffer has
        2. The buffer size

        Returns memory accesses per buffer.
        c                X    t         j                  j                  j                  | d      S )Nr   r   )rZ   r   r   r   )ss    rl   try_size_hintzGBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.try_size_hint:  s"    77##55a!5DDrn   r   r       eAc              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zCBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.<genexpr>O  s     B+ACsxx+Ar  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zCBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.<genexpr>T       C+BCsxx+Br  c                    j                   j                  |    j                  }t        d |D              }t	        |t        |      z
        dkD  S )Nc              3  4   K   | ]  }|j                     y wrw   r   )r   r.  s     rl   r   z\BaseSchedulerNode.get_read_write_buffer_accesses.<locals>.is_materialized.<locals>.<genexpr>[  s     !>$))r  r   )r  r@  r  r   r   )r   r   r  buf_usesrk   s       rl   is_materializedzIBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.is_materializedY  sG    NN..s399E!!>!>>Hx*V"44599rn   c              3  J   K   | ]  } |j                         r|  y wrw   r   )r   r   r}  rk   s     rl   r   zCBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.<genexpr>_  s"      )%_S$++-Nvs   ##c              3  "   K   | ]  }  y wrw   r~   )r   r   
node_numels     rl   r   zCBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.<genexpr>h  s     $R;QCZ;Qs   c                B   | syt        | t        j                        r| j                         S t        | j                  t
              r͉j                  j                  | j                            j                  }d}|D ]  }t        |j                  t              rt        |j                  t              sJ t        |j                  j                  t              r5|j                  j                         D ]  }| |j                        z  }  y |S t        | j                  t        j                        r"t!        fd| j#                         D              S  	t%        | j'                                     }t)        | j+                               t-        |      z  S )Nr   c              3  h   K   | ])  } t         j                  j                  |             + y wrw   )rZ   r   
get_buffer)r   mut_nameget_buf_bytess     rl   r   zZBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.get_buf_bytes.<locals>.<genexpr>  s-      (@H &agg&8&8&BC(@s   /2)r   r+   TorchBindObjectr  r'  r>   r  r@  r  r  r   rG  r_   r=   rz  r?   r   r7  rY   r  rN   	get_dtypemin)
r   r  totr.  	sched_buf	buf_elemsbuf_accessed_elemsr  rk   ru  s
         rl   r  zGBaseSchedulerNode.get_read_write_buffer_accesses.<locals>.get_buf_bytesq  sI    c2#5#56,,..

,=> !NN66s||~FLLEC %%dii<$)$))5FGGG%diinnkB-1YY-B-B-D	 #}Y^^'D D .E $% !& J

BMM: (+(>(>(@  
 !.mCLLN.K LI)#--/:S*I>  rn   )rt  z
sympy.Exprr   r  )r   r  r   Sequence[BaseSchedulerNode]r   rv   )r   z4ir.Buffer | ir.TensorBox | ir.TorchBindObject | Noner   r  )r   rA  ExternKernelSchedulerNoder   r=   r+   rD  op_overloadr  _prims	rng_primsgraphsafe_run_with_rng_stater   rY   
get_rangesr  collectionsr   r   r   r   r   r   r  r   r   r   rZ   r   r  graph_inputs)rk   rf  rg  buf_accessesr   r   r  r?  buf_byte_accessesr  r   	buf_bytesr  r  r}  r  ru  s   `           @@@@@rl   rq  z0BaseSchedulerNode.get_read_write_buffer_accesses  s   6 d23Id56:II{<
 It67499b&7&78		%%||%%BBC I	E dM*&doo/23 1! 456J
 SJ"..t4''--SXX&--c2 . ''..SXX&--c2 /
  B4+;+;+A+ABB 	  C4+;+;+B+BCC 		:
 d./( )%) O o-FO+E,.H!$$R<;Q$R!R177111gg,,X6QWW111gg**84#I## #J &c*I00.7!(+!(+y8+g 'j ! rn   c                T   | j                   y | j                   j                         }|y t        |      }|y t        |t        j
                        r|j                   j                  }t        j                  j                  j                  |d      }t        d   dxx   |z  cc<   |S )Nr   r   inductor
flop_count)r   get_origin_noder9   r   r  SymIntexprrZ   r   r   r   r   )rk   fx_nodeflopsresolved_flopss       rl   estimate_flopsz BaseSchedulerNode.estimate_flops  s    99))++-?w'=eU\\*JJOOE));;EA;N\*n<*rn   c                R    | j                   | j                   S | j                         S rw   )rn  _get_estimated_runtimerj   s    rl   get_estimated_runtimez'BaseSchedulerNode.get_estimated_runtime  s)    **6222**,,rn   c                   | j                         d   j                         d   }|j                  j                         }t	        t        |            syt        | j                        rt        | j                  t        j                        sJ 	 t        j                  rst        |       }t               }|j                  |      }|t        |t              sJ |S t!        |       }|t#        | j                        }|j%                  ||       |S t#        | j                        S t/        | j                        ryt1        |       }||S |j                  j3                         }		 t5               }
t7        |	      dz  }|
dk  rt9        d|
       |dk  rt9        d|       	 | j=                         }|dk(  s|| j?                         |
z  }|dz  }|S d}| j?                         }|dn|}||z  |z  d	z  }||
z  }tA        ||      }|dz  }|S # t&        $ r}t(        j+                  |       Y d}~yd}~wt,        $ r}t(        j+                  |       Y d}~yd}~ww xY w# t:        $ r Y yw xY w)
zC
        Returns estimated op runtime in milliseconds (ms)
        r   Nvaluel    J)z-gpu_memory_bandwidth cannot be <= 0, but got z"gpu_flops cannot be <= 0, but got g    .Ag      ?rv  )!r   rz  r   r8  rU   r;   rS   r   r+   IRNoder)   ,runtime_estimations_use_nccl_lib_estimations)get_estimate_runtime_cache_key_from_snodeget_estimate_runtime_cachelookupfloatr2   r1   	set_value
ValueErrorr  r  	TypeErrorrX    maybe_estimate_runtime_benchmarkmaybe_get_dtyperO   rM   AssertionErrorr  r  rj  max)rk   r   r'  	cache_keycache	cache_valmsr  retdtypegpu_memory_bandwidth	gpu_flops	flops_estnsfactorcounted_bytescompute_timetransfer_times                     rl   r  z(BaseSchedulerNode._get_estimated_runtime  sw   
 nnq!--/2))+of-. #dii333LL I$ OI68E %Y 7I ,))U;;;((HNBz=diiHOOIRO8I7		BB TYY
 .t4?J((*	#4#6 )%069I $q($CDXCYZ  A~$'I)%UVV 
 '')	>Y.2247KKBcBI 99;*2*Y6#=%(<< }-#X	o    :  		sC   AH 6H H (>I$ 	I!H66I!II!$	I0/I0c                     y rw   r~   rj   s    rl   get_template_nodez#BaseSchedulerNode.get_template_node      rn   c                .    | j                         }|J |S rw   r  )rk   templates     rl   get_template_node_or_throwz,BaseSchedulerNode.get_template_node_or_throw  s!    ))+###rn   c                f    t        d t        |       D              }| d| }| |   }| |dz   d }|||fS )zQ
        For the list of nodes, get the prologue, template, and epilogue
        c              3  H   K   | ]  \  }}|j                         s|  y wrw   r   )r   ir  s      rl   r   zCBaseSchedulerNode.get_prologue_template_epilogue.<locals>.<genexpr>  s     P,<DAqa,<s   ""Nr   )next	enumerate)nodestemplate_indexprologuetemplate_nodeepilogues        rl   get_prologue_template_epiloguez0BaseSchedulerNode.get_prologue_template_epilogue  sN     PIe,<PP.)n-!+-.00rn   )r  r  r   rU  )r   ir.Operationr   rU  rR  )r   r  rT  r  r4   r  r4   r   rv   r  rf  r   rU  )r   r3   r   rU  rV  )r  ro  r   rU  r  r_  r  rf  r   rU  r   r_  r  dict[str, BaseSchedulerNode]r   rU  r   r  )r   zSequence[SchedulerBuffer])r  r  r   r  rX  r'  zdependencies.Depr   rv   T)r]  rR   r^  rv   r   rU  rS  )rf  rv   rg  rv   r   r  )rf  rv   rg  rv   r   zdict[str, int]r   
int | Noner   r  r   zir.TemplateBuffer | None)r   zir.TemplateBuffer)r  list[BaseSchedulerNode]r   zJtuple[list[BaseSchedulerNode], BaseSchedulerNode, list[BaseSchedulerNode]])>ry   rz   r{   r|   r   rn  rr  rx  r|  r  r/  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  rI   r   r  r	  r-   r   rz  r  r   r  rU   r   r  r  r   r"  r$  r(  r*  rL  rc  rj  rl  rn  ri  rq  r  r  r  r  r  r  r  r~   rn   rl   r_   r_     s   BB NN''$$ $D
$""///33((''GT
#4B*6+#
!.7	
M>


=#2=HV=	=
6
G T">T	T
. H H B B 
 
 
 
.&;:IX 9=-$-15-	-^ 
 

 
 

 
 


!
37
	
L!!L!37L!	L!\  $- U Un
 1&1	S1 1rn   c                 R    t         j                  j                  j                         S rw   )r  r  	codecache
LocalCacher~   rn   rl   r  r  &  s    ??$$//11rn   c                   t        | j                  dd      }| j                  j                  }| j                  j                  g || j                  j                  | j                  j
                        }| j                  j
                  }t        j                  ||f      \  }}ddt        |ft        fd|D              z         }|S )Npython_kernel_namer  c                    t        | t        j                        xr+ t        | t        j                  t        j                  f       S rw   )r   r+   r  GeneratorStateOpaqueObjectStaterJ  s    rl   _is_tensor_irz@get_estimate_runtime_cache_key_from_snode.<locals>._is_tensor_ir5  s<    !RYY' 

!!2#7#781
 -
 	
rn   c              3  d   K   | ]'  } |      rt        |j                               nd  ) y wrw   )r   r  )r   ar  s     rl   r   z<get_estimate_runtime_cache_key_from_snode.<locals>.<genexpr><  s)     U9a}Q'7ajjl#TA9s   -0rV  )
r  r   inputsfill_non_provided_argsconstant_argsru  pytreetree_flattenr  r   )snoder  r4  ru  	flat_argsflat_args_pytree_specr  r  s          @rl   r  r  +  s     -A2F::D::,,*$*))*

D ZZF'-':':D&>'J$I$

 	
U9U
U	VI rn   c                   t        | t              sy t        j                  j                  j
                  t        j                  j                  j                  t        j                  j                  j                  d}t        | j                  dd      }||vry t        | j                  t        j                        sy ||   S )N)zextern_kernels.mmzextern_kernels.bmmzextern_kernels.addmmr  r  )r   r  r  opsatenmmbmmaddmmr  r   r+   ExternKernel)r  mms_fnsr  s      rl   _get_mm_like_fnr  A  s    e67"YY^^..#iinn00 %		 4 4G
 !-A2F(ejj"//2%&&rn   c                Z    d }d }t         j                  rt               }|y |} fd}ny t               }t	               }|j                  |      }|t        |t              sJ |S ddlm	  |       \  }}ddl
m}	 |	j                  |||ddd      }
|j                  ||
	       |
S )
Nc                             S rw   r~   )r  snode_args_kwargss   rl   rv  z2maybe_estimate_runtime_benchmark.<locals>.<lambda>Z  s    !25!9rn   r   )r  r   )benchmarker   
   )memory_warmup_itersbenchmark_itersmax_benchmark_durationr  )r(   !runtime_estimations_mms_benchmarkr  r  r  r  r   r  utilsr  $torch._inductor.runtime.benchmarkingr  	benchmarkr  )r  bench_fnargs_kwargs_fnmm_fnr  r  r  r4  ru  r  r  r  s   `          @rl   r  r  Q  s    HN//&=99%@I&(EY'I)U+++(!#LD&@			! 
 
B 
OOIRO(Irn   T)slotsc                  N    e Zd ZU ded<   ded<   ded<   ded<   ddZddZdd	Zy
)	WhyNoFuser  name1name2reasonztuple[Any, ...]r4  c                X    |j                         | _        |j                         | _        y rw   )r  r  r  rk   r   r   s      rl   rx  zWhyNoFuse.__init__~  s    ^^%
^^%
rn   c                J    || _         || _        t        j                  |        y rw   )r  r4  
fusion_logdebug)rk   r  r4  s      rl   __call__zWhyNoFuse.__call__  s    	rn   c                p    d| j                    d| j                   d| j                  | j                  z  z   S )Nzcannot fuse z with r#  )r  r  r  r4  rj   s    rl   __str__zWhyNoFuse.__str__  s6    djj\

|2>KK$))#
 	
rn   Nr   r_   r   r_   r   rU  )r  r  r4  r   r   rU  rR  )ry   rz   r{   r|   rx  r  r!  r~   rn   rl   r  r  w  s&    JJK
&

rn   r  c                    t        | t        t        f      rt        | t              } t        j                  | d      }d|v rdt        j                  |d       S |S )Nkey   )r+  r      )	r   r   setsortedr  pprintr)  textwrapr+  )objr-  s     rl   r)  r)    sR    #
C()Sc"^^C*Fv~HOOFG4566Mrn   c                  0    e Zd ZddZddZddZd	dZeZy)
rG  c                &    t        |g      | _        y rw   r  r  s     rl   rx  zOutputNode.__init__  s    ",cU"3rn   c                     yr  r~   rj   s    rl   r   zOutputNode.is_reduction  r  rn   c                     y)Nr~   r~   rj   s    rl   r6  z'OutputNode.get_inputs_that_alias_output  r  rn   c                     y)NOUTPUTr~   rj   s    rl   r  zOutputNode.get_name  s    rn   N)r   r5   r   rU  rV  rW  rR  )ry   rz   r{   rx  r   r6  r  r  r~   rn   rl   rG  rG    s    4 Hrn   rG  c                    t        j                          j                  D ]N  }t        |t              r|j
                     j                         }|   j                         xx   dz  cc<   P d fdt        fd j                  D              }|r? j                  |z
   _         j                   j                  j                  |             yy)am  
    Prunes weakdeps intended for mutation ordering
    on an upstream fused node if after fusion there is another dependency
    on the fused upstream node, making the weakdep redundant

    In essence this enforces an ordering on fusions. As fusions occur, weakdeps will
    be incrementally removed, enabling other fusions, ensuring they are fused in order.
    r   c                    t        | t              rf| j                     j                         }|   j	                            dkD  xr  j
                  j                  | |         }|   k(  }|xs |S y)Nr   F)r   r6   r   r  r  r  fusable_weak_dep)r   r  is_redundantis_self_depr@  name_to_dep_countr  r   s       rl   r  z+_prune_redundant_deps.<locals>.should_prune  s    c7#!#((+<<>G,"7+446 nn55'0$  -W5=K.;.rn   c              3  4   K   | ]  } |      s|  y wrw   r~   r  s     rl   r   z(_prune_redundant_deps.<locals>.<genexpr>  s      .,s2C.r  Nr  )r  r   rq  r   r6   r   r  r  r   r  r   r  )r   r  r@  r   r  deps_to_pruner8  r  s   ```   @@rl   r  r    s     '2&9&9&;&&#w'!#((+<<>G09BBDEJE '
    .. M "&"9"9M"IT--::=IJ rn   c                  H     e Zd Zd fdZddZd	dZd	dZd
dZddZ xZ	S )r  c                n   t         |   |       | j                  |       | j                  |j	                                t        |t        j                        r[|j                         rJt        j                  |j                  d   j                        }d}|j                         }|||ff| _        y y y Nr   r   )superrx  r|  r  get_read_writesr   r+   UserDefinedTritonKernelcan_fuse_epiloguemathr   mutable_argsshapeget_device_or_errorr   )rk   r  r   numelr   r  	__class__s         rl   rx  z"ExternKernelSchedulerNode.__init__  s    #T"T1134dB667D<R<R<TIId//2889EF--/F 5&/2DJ =U7rn   c                V    | j                          dt        | j                  dd        S )Nz.node.kernel = r  )r  r  r   rj   s    rl   r  z)ExternKernelSchedulerNode.debug_str_extra  s*    --/"/'$))EY[_2`1abbrn   c                     yNTr~   rj   s    rl   r"  z#ExternKernelSchedulerNode.is_extern  r  rn   c                    | j                   J t        | j                   d      xr | j                   j                         S )Nr*  )r   r<  r*  rj   s    rl   r*  z*ExternKernelSchedulerNode.has_side_effects  s6    yy$$$tyy"45V$)):T:T:VVrn   c                    t        | j                  t        j                        rU| j                  j	                         r;t        j                  | j                  j                  d   j                        }|gg fS g g fS r   )	r   r   r+   r@  rA  rB  r   rC  rD  )rk   rF  s     rl   r  z$ExternKernelSchedulerNode.get_ranges  s^    tyy""<"<=		++-IIdii44Q7==>EGR= Bxrn   c                    t        | j                  t        j                        sJ | j                  j	                  |      S rw   )r   r   r+   r  r;  )rk   wrappers     rl   r;  z!ExternKernelSchedulerNode.codegen  s/    $))R__555yy  ))rn   r  r  r   r  r   rU  rR  rV  r   Sequence[Sequence[sympy.Expr]]rN  r   r   rU  )
ry   rz   r{   rx  r  r"  r*  r  r;  __classcell__rG  s   @rl   r  r    s#    
3cW*rn   r  c                        e Zd Zd fdZ xZS )rA  c                    t         |   |       | j                  |       | j                  |j	                                y rw   )r>  rx  r|  r  r?  rk   r  r   rG  s      rl   rx  zNopKernelSchedulerNode.__init__  s5    #T"T1134rn   rO  )ry   rz   r{   rx  rS  rT  s   @rl   rA  rA    s    5 5rn   rA  c                      e Zd ZU dZded<   ded<   	 	 	 	 	 	 d! fdZ	 	 d"	 	 	 	 	 d#dZ	 	 d"	 	 	 	 	 d$dZ	 	 	 	 	 	 d%d	Zd&d
Z	d'dZ
d(dZd'dZ	 	 	 	 	 	 d)dZd'dZ	 	 	 	 	 	 d*dZd+dZd,dZd-dZd-dZd-dZd-dZd.dZd/dZ	 	 	 	 d0dZd1dZ	 d2	 	 	 d3dZed4d       Zed4d       Zd5dZed6d       Zed- fd        Z  xZ!S )7r   zu
    A SchedulerNode is a node for scheduling that encapsulates either
    a ComputedBuffer or a TemplateBuffer.
    z tuple[Sequence[sympy.Expr], ...]_sizesr@   r   c                f    t         |   |       | j                  |       | j                          y rw   )r>  rx  r|  _compute_attrsrW  s      rl   rx  zSchedulerNode.__init__	  s,    
 	#T"rn   c                   t        | j                  t        j                  t        j                  f      sJ | j                  j                  ||      \  | _        }|| _        | j                  j                         }| j                  j                  |      j                  }| || j                        f| _        t        j                   xs t        |j                          }t        | j                  t        j                        r,| j#                  | j                  j%                  |             y | j#                  t'        j$                  | j                  g| j                  d|i       y )Nextra_indexing_constraintsrecompute_sizes_body_func)	normalizer`  )r   r   r+   r   TemplateBuffersimplify_and_reorderrY  r   rE  r  get_backendgroup_fnr   r(   loop_ordering_after_fusionrU   r   r  extract_read_writesr*   )rk   r^  r_  bodyr  rd  should_normalizes          rl   r[  zSchedulerNode._compute_attrs  s7   
 $))b&7&79J9J%KLLL II::'A&? ; 
T 
..0>>--f5>>ht{{34
  &@@@ 
KKI
 E
 dii!2!23  		--8H-I   00JJ!%8Hrn   c                   t        d | j                  j                  D              }| j                  ||       |rD| j	                  | j                  j                  |      j                  | j                               y y )Nc              3  N   K   | ]  }t        |t        t        f      s|  y wrw   r   r6   r5   r  s     rl   r   z8SchedulerNode.recompute_size_and_body.<locals>.<genexpr>8  #      0
1CZgwEW5XC1   %%r]  )r   r   r   r[  r  r  r  rg  )rk   r^  r_  	fake_depss       rl   recompute_size_and_bodyz%SchedulerNode.recompute_size_and_body3  s    
 &0 0
++110
 &
	 	'A&? 	 	
     **95<<T=R=RS rn   c                   t        d | j                  j                  D              }| j                  t	        j
                  | j                  g| j                  d|ij                  |      j                  | j                               | j                  j                  |        |r!ddlm} |j                  j!                          y y )Nc              3  N   K   | ]  }t        |t        t        f      s|  y wrw   rk  r  s     rl   r   z5SchedulerNode.refresh_dependencies.<locals>.<genexpr>I  rl  rm  r`  r   SIMDScheduling)r   r   r   r  r*   rf  r   rY  r  r  rg  pointwise_read_writesclear_cachecodegen.simdrs  candidate_tilingscache_clear)rk   r`  need_clear_tiling_cachern  rs  s        rl   refresh_dependenciesz"SchedulerNode.refresh_dependenciesD  s    
 &0 0
++110
 &
	 	,,

![[4= Yy!VD))*	
 	""..t4"4 ,,88: #rn   c                    | j                   j                  |      | _         | j                   j                  | _        | j	                  dd       y )NFTr`  ry  )r   reorder_iter_loopssizesrY  rz  )rk   	new_orders     rl   apply_new_loop_orderz"SchedulerNode.apply_new_loop_orderb  sA    ZZ22

 jj&&!!E4!Prn   c                   | j                   j                         }t        | j                   j                        |z
  }t	        t        |            }t	        t        |||z               }| j                  ||z          t        | j                  d         dk(  sJ | j                  d   | j                  d   d   | j                  d   d   ff| _        y )Nr   r   r   )r   get_original_num_rdimsr   	iter_varsr   ranger  r   )rk   	num_rdims
num_pwdimspwdimsrdimss        rl   swap_pw_red_dimensionz#SchedulerNode.swap_pw_red_dimensionj  s    JJ557	--.:
uZ()eJ
Y(>?@!!%&.14::a=!Q&&&ZZ]TZZ]1%5tzz!}Q7G$HH
rn   c                D    | j                   j                         | _         | S rw   )r   extract_pw_from_reductionrj   s    rl   r  z'SchedulerNode.extract_pw_from_reductiont  s    ZZ99;
rn   c                    t         j                  |       sy t        | j                  t        j
                        sJ | j                  j                         5  | j                          d d d        y # 1 sw Y   y xY wrw   )r   r   r   r   r+   r   with_original_inner_fnr[  rj   s    rl   cancel_reduction_splitz$SchedulerNode.cancel_reduction_splitx  sU     33D9$))R%6%6777YY--/! 0//s   A11A:c                   t        | j                  t        j                  t        j                  f      sJ | j
                  j                  ||      | _        | j
                  j                  | _        | j                  j                         }| j                  j                  |      j                  }| || j                        f| _        | j                  dd       y )NTr|  )r   r   r+   r   ra  r   #expand_dimension_for_pointwise_noder~  rY  rE  r  rc  rd  r   rz  )rk   	dimension	new_ranger  rd  s        rl   r  z1SchedulerNode.expand_dimension_for_pointwise_node  s     $))b&7&79J9J%KLLLZZCCy

 jj&&..0>>--f5>>ht{{34
 	!!D$!Orn   c                    | j                   j                         | _         | j                   j                  | _        | j	                  dd       y )NTFr|  )r   merge_loopsr~  rY  rz  rj   s    rl   r  zSchedulerNode.merge_loops  s<    ZZ++-
jj&& 	!!D%!Prn   c                   d }| j                   d   }t        |      |j                  cxk(  r|j                  k(  rn n|j                  |      }|rPt        xj
                  dz  c_        t        j                  d| j                         |       | j                  |       yt        j                  d| j                                y)Nr   r   z"Reorder loops for %s with order %sTzEDon't reordering %s because we can not decide the suitable loop orderF)
rY  r   num_varsdecide_loop_order_to_matchr,   num_loop_reorderingloop_ordering_logr  r  r  )rk   r  r  r  
self_sizess        rl   r  z'SchedulerNode.reorder_loops_by_dep_pair  s     	[[^
z?h//E93E3EE ;;IFI''1,'##4dmmoy %%i0##W rn   c                $   | j                         }| d| j                  d    | d| j                  d    | d| j                   g}| j                  j	                         D ]  }t        |t              r|j                  }t        j                  j                  |      }t        |t        j                        rZ|j                  | dt        |j                                 t        | j                   t"              rR|j                  d| d       |j                  t%        j&                  | j                   j)                         d	             | j*                  J |j-                  | j/                                d
j1                  |      S )Nz.group.device = r   z.group.iteration = r   z	.sizes = z
_layout = zclass z_loop_body:r'  r  )r  r   rY  r   r  r   r6   r   rZ   r   r  r+   r  r   r)  r'  r   r@   r+  r+  r/  r   r  r  join)rk   r   linesr   r  r   s         rl   r  zSchedulerNode.debug_str_extra  sD   }}f$TZZ]O4f'

17fIdkk]+

 ##446Cc7+88gg((2!#r'9'9:LLH:Z

8K7L!MN 7 djj(+LL6${34LL)=)=)?HIyy$$$T//12yyrn   c                    | j                   S rw   )rY  rj   s    rl   r  zSchedulerNode.get_ranges      {{rn   c                <   t        | j                  t        j                  t        j                  f      sJ dt        | j                               t        | j                  j                               xr' | j                  d u xs | j                  j                   S Ntype(self.node)=)
r   r   r+   r   ra  r   rv   r   r   has_partial_accumulaterj   s    rl   r   zSchedulerNode.is_reduction  s    $))b&7&79J9J%KL 	
tDII !	
L DII0023 
JJ$Gdjj&G&G"G	
rn   c                    t        | j                  t        j                        sJ dt	        | j                               | j                  j                         dk(  S )Nr  dot)r   r   r+   r   r   r   rj   s    rl   r  zSchedulerNode.is_native_matmul  sJ    $))R%6%67N<LDO;M9NN7yy++-66rn   c                L   t        | j                  t        j                  t        j                  f      sJ dt        | j                               t        | j                  t        j                        xr. t        | j                  j                  t        j                        S r  )r   r   r+   r   ra  r   r   	SplitScanrj   s    rl   r  zSchedulerNode.is_split_scan  sy    $))b&7&79J9J%KL 	
tDII !	
L $))R%6%67 
JIINNBLL=
 	
rn   c                J    t        | j                  t        j                        S rw   r   r   r+   ra  rj   s    rl   r   zSchedulerNode.is_template  s    $))R%6%677rn   c                f    t        | j                  t        j                        r| j                  S d S rw   r  rj   s    rl   r  zSchedulerNode.get_template_node  s$    &tyy"2C2CDtyyN$Nrn   c                f    | j                          | j                          | j                  |       y rw   )rL  r  r;  )rk   
index_varss     rl   runzSchedulerNode.run  s#    ""$Z rn   c                &   | j                   }t        t        t        |            t        t        t        |            k(  sJ t	        t        t        j                  j                  |      t        j                  j                  |                  }|S rw   )	rY  r   mapr   dictzipr  r  from_iterable)rk   r  r~  r   s       rl   ranges_from_index_varsz$SchedulerNode.ranges_from_index_vars  sp     3sE?#s3sJ+?'@@@@--j9--e4

 rn   c                   | j                  |      }	 t        j                  t        t        j                         |            5  t        j
                  j                  |       5   | j                  |  ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w# t        $ r" t        j                  d| j                          w xY w)a  
        Generate code for this node using the provided index variables.

        This method sets up the appropriate context for code generation, including
        simplifying indexing expressions based on the variable ranges, and then
        calls the node's body function with the index variables.

        Args:
            index_vars: A sequence of sequences of sympy expressions representing
                        the index variables for each dimension of the computation.
        NzError in codegen for %s)r  rZ   set_ops_handlerrG   get_ops_handlerr=  set_current_noder   r  r  fatalr   )rk   r  r   s      rl   r;  zSchedulerNode.codegen  s     00<
	!!"213D3D3F
"ST))$/

J' 0 UT// UT  	II/;	sA   1B  B$B4B<B B	
BBB B +Cc                    |r| j                   nt        | j                         \  }}t        j                  | j                  |t
        j                  j                  gt        |      z  g      S )z\
        Get the memory dependencies in either the pointwise or the reduction axes.
        )hidden_args)	rY  r   r*   rf  r   r   SZeror   )rk   	pointwise
keep_sizesignore_sizess       rl   "pointwise_or_reduction_read_writesz0SchedulerNode.pointwise_or_reduction_read_writes  sT     3<4;;$++AV 
L//JJ
%'',,#lBS1S0T
 	
rn   c                &    | j                  d      S )zH
        Get the memory dependencies in the non-reduction axes.
        Tr  r  rj   s    rl   rt  z#SchedulerNode.pointwise_read_writes  s    
 666FFrn   c                &    | j                  d      S )zD
        Get the memory dependencies in the reduction axes.
        Fr  r  rj   s    rl   reduction_read_writesz#SchedulerNode.reduction_read_writes&  s    
 666GGrn   c                   | j                         ryt        d | j                         D              ryt        | j                  j
                        dk(  rt        |t        j                        rt        t        | j                  j
                              }t        |t        j                        sJ dt        |             |j                  |j                  k(  xr |j                  |j                  k(  S y)NFc              3  <   K   | ]  }|j                           y wrw   )r(  r   s     rl   r   z,SchedulerNode.can_inplace.<locals>.<genexpr>0  s     ?,>Ss ,>r  r   ztype(write_dep)=)r   r   rz  r   r   r  r   r*   r4   r  iterr   r   r   )rk   r'  	write_deps      rl   r(  zSchedulerNode.can_inplace-  s    ?D,<,<,>??t&&'1,l,,2
 T$"2"2"9"9:;Ii)?)?@WEUT)_DVBWW@>>Y__4X)..9XXrn   c                   t               }t        | j                  t              r| j                  j	                         D ]  }|j
                  dk(  s|j                  dk(  s#d|j                  v r|j                  d   dk(  s,t        |j                        dk(  s\|j                  d   dk(  so|j                  d|j                  v r|j                  d   n(t        |j                        dk\  r|j                  d	   nd
        |S )Ncall_methodstoremode
atomic_addr  r&  r   r   r   r  )r   r   r   r@   r   r  rX  ru  r   r4  r  )rk   buffers_store_as_atomic_addr   s      rl   _get_atomic_add_buffersz%SchedulerNode._get_atomic_add_buffers:  s    7A|#djj(+

,,.GG},w.4;;.4;;v3F,3V		Na/DIIaLL4P 033!T[[0 F+.1$))n.Adiilr / +*rn   c                p    | j                   | j                   j                  d      ryt        |          S )Ndevice_assert_asyncT)r   has_opr>  r*  rk   rG  s    rl   r*  zSchedulerNode.has_side_effectsN  s2     ::!djj&7&78M&Nw'))rn   )r  r  r   z%ir.ComputedBuffer | ir.TemplateBufferr   rU  NN)r^  'tuple[dict[Any, Any], list[Any]] | Noner_  zCallable[_P, _T] | Noner   rU  )r^  r  r_  zCallable[..., Any] | Noner   rU  )r`  rv   ry  rv   r   rU  )r  Sequence[int]r   rU  rT  r   r_   )r  r  r  r  r   rU  r  rR  rP  rV  r  )r  Sequence[sympy.Expr]r   rU  )r  rQ  r   zdict[sympy.Expr, sympy.Expr])r  rQ  r   rU  r  )r  rv   r   ro  )r   ro  r  r  )"ry   rz   r{   r  r|   rx  r[  ro  rz  r  r  r  r  r  r  r  r  r  r   r  r  r   r  r  r  r;  r  rI   rt  r  r(  r  r*  rS  rT  s   @rl   r   r      s   
 -,O 4 
	 OS=A$K $; 
	F OS?C$K $= 
	";;8<;	;<QI"PP),P	P"
Q!.7	. ,
7
8O!
8	%0 !%	
	
	 	
 G G H H + +& * *rn   r   c           	     n     j                   } j                  t        j                  j	                  |D cg c]  }|j
                   c}             t         fdt        j                  |D cg c]  }|j                   c} D               j
                  j                  z
   _        y c c}w c c}w )Nc              3  Z   K   | ]"  }|j                   j                         vr| $ y wrw   r   r  )r   r   group_snodes     rl   r   z2refresh_group_node_dependencies.<locals>.<genexpr>_  s.      
Pxx{;;== P   (+)
r   r  r*   
ReadWrites
merge_listr   r   unionrq  r  )r  r   rJ  s   `  rl   refresh_group_node_dependenciesr  V  s     F**6+J6aAMM6+JK
 	 
!'')O1!*>*>)OP
 	

 
!
!
(
(	) " ,K *Ps   B-0B2r  c                l   t        | t        t        f      sJ || _        || _        d | _        t        j                  |D cg c]  }|j                  |j                   c} | _        t        |        t        d | j                  D              | _        t        d | j                  D              | _        t        d | j                  D              | _        t        d | j                  D              | _        | j!                         D ci c]  }|j#                         | c}| _        y c c}w c c}w )Nc              3  4   K   | ]  }|j                     y wrw   rc  r   rJ  s     rl   r   z"init_group_node.<locals>.<genexpr>w       H5G5Gr  c              3  4   K   | ]  }|j                     y wrw   )rd  r  s     rl   r   z"init_group_node.<locals>.<genexpr>x  r  r  c              3  4   K   | ]  }|j                     y wrw   )ra  r  s     rl   r   z"init_group_node.<locals>.<genexpr>y        )&8&8r  c              3  4   K   | ]  }|j                     y wrw   )rb  r  s     rl   r   z"init_group_node.<locals>.<genexpr>|  r  r  )r   r   GroupedSchedulerNoder   r  r   r   r  r   r  r  rc  r  rd  ra  rb  rz  r  rl  )r  r  r   rJ  r   s        rl   init_group_noder  h  s!   
 k$68L#MNNNK%KK&,,%	Av!)@!++v	AK $K0H[5G5GHHKH[5G5GHHK%( )&1&8&8) &K" &) )&1&8&8) &K" (3'>'>'@#'@'@#K 
B#s   D,D,D1c                      e Zd ZU dZded<   e	 	 	 	 	 	 d!d       Zd"dZd#dZe	d$d       Z
	 	 	 	 	 	 d%dZd& fd	Ze	d'd
       Zd'dZe	d(d       Zd)dZd'dZd'dZ	 	 	 	 	 	 d* fdZe	d(d       Ze	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	d-d       Zd.dZe	d,d       Zd/dZd0dZ d1dZ!d'dZ"e	d, fd        Z# xZ$S )2r   z
    This is a "fake" scheduler node that represents a group of scheduler nodes
    that are meant to be fused together. The way it does this is by maintaining
    its unmet dependencies as the union of its constituent nodes.
    r  r   c                   |j                   |j                   u sJ t        |t        t        f      sJ |j	                         r6t        |t
              r&t        |j                  t        j                        sJ t        |t        t        f      sJ t        t        j                  |j                         |j                                     } | |j                   |      S rw   )r  r   r   r   r   r  r   r+   r=   r   r  r  r   )rq   r   r   r  s       rl   rr   zFusedSchedulerNode.fuse  s     %//111%-1C!DEEE:e5N#Oejj"..999em5G%HIIIY__U__%68IJK5??E**rn   c                    | j                   D ]6  }t        |t              sJ |j                         sJ |j	                          8 | S rw   )r   r   r   r   r  rk   r   s     rl   r  z,FusedSchedulerNode.extract_pw_from_reduction  sE    {{Gg}555'')))--/ # rn   c                j    | j                   D ]$  }t        |t              sJ |j                          & y rw   )r   r   r   r  r  s     rl   r  z(FusedSchedulerNode.swap_pw_red_dimension  s,    {{Gg}555))+ #rn   c                    t        t        d d | j                         D                    }t        |      dk(  ry t	        |      }|S )Nc              3  |   K   | ]4  }|j                         s|j                         r|j                          6 y wrw   r   r"  r  r  s     rl   r   z4FusedSchedulerNode.estimate_flops.<locals>.<genexpr>  6       0'')T^^-= '') 0   :<r   r   filterr   r   r   rk   fpsr  s      rl   r  z!FusedSchedulerNode.estimate_flops  K      $ 0	
 s8q=#h
rn   c                   | j                         ryd}| j                  D ]`  }t        |t              s y|;t	        |      t	        |j
                  d         k7  rt        j                  d        y|j
                  d   }b d}|J t        |      |j                  cxk(  r|j                  k(  rn n|j                  |      }|s%t        j                  d| j                                yt        xj                  dz  c_        t        j                  d| j                         |       | j                  D ]%  }t        |t              sJ |j                  |       ' t        |        y)	z@
        Return true if a loop reordering is performed.
        FNr   z1Can not reorder fused node due to different sizeszODont reordering fused node %s because we can not decide the suitable loop orderr   z-Reorder loops for fused node %s with order %sT)r   r   r   r   r   rY  r  r  r   r  r  r  r,   r  r  r  )rk   r  r  r  r  r  s         rl   r  z,FusedSchedulerNode.reorder_loops_by_dep_pair  s?    
[[Ee]3%%
*;uU\\RS_?U*U!''G aJ ! 	%%%z?h//E93E3EE ;;IFI##a ##q(#;T]]_i	
 [[Ee]333&&y1 ! 	(-rn   c                    t         |   |       t        | ||       g | _        t	        |d       j
                  | _        y )Nc                4    t        | j                               S rw   )r  r   r  s    rl   rv  z-FusedSchedulerNode.__init__.<locals>.<lambda>  s    s1>>3C/Drn   r$  )r>  rx  r  r  r  r   )rk   r  r   rG  s      rl   rx  zFusedSchedulerNode.__init__  s8    #i0%'
%DEKK
rn   c                z    dj                  | j                  D cg c]  }|j                          c}      S c c}w N_r  r   r  rk   rJ  s     rl   r  zFusedSchedulerNode.get_name  -    xxt{{;{!{;<<;   8c                <    | j                   d   j                         S r   r   r  rj   s    rl   r  z!FusedSchedulerNode.get_first_name      {{1~&&((rn   c                |    t        j                  | j                  D cg c]  }|j                          c} S c c}w rw   r   r  r   r  r  s     rl   r  z#FusedSchedulerNode.get_buffer_names  2    !L1!"4"4"6!LMM!L   9c                j    g }| j                   D ]!  }|j                  |j                                # |S rw   r   r  rz  rk   r-  r   s      rl   rz  zFusedSchedulerNode.get_outputs  /    (*KKDMM$**,-  rn   c           
     ~   t        | j                        D cg c]+  \  }}| j                          d| d|j                          - }}}| j                  d   j                  }||j                  | j                                t        j                  dj                  |      j                         d      S c c}}w )Nz.snodes[z] =
r   r  r'  )r  r   r  r/  r   r  r  r+  r+  r  r  )rk   r  r   r  s       rl   r  z"FusedSchedulerNode.debug_str_extra  s     %T[[1
14 }}xs%0@/AB1 	 
 {{1~""LL3356tyy/668&AA
s   0B9c                h    | j                   D cg c]  }|j                          }}|  d| S c c}w )Nz
, snodes: )r   r  )rk   r   
snodes_strs      rl   r  z"FusedSchedulerNode.debug_str_short  s:    9=Ed**,
Ez*.. Fs   /c                    t         |   ||       t               }t        | j                        D ]/  }|j                  ||       |j                  |j                         1 y rw   )r>  r  r   r   r   updater`  )rk   r  r  r   rG  s       rl   r  z!FusedSchedulerNode.set_last_usage	  sW    
 	24FG 0:|T[[)D 35GH&&t7 *rn   c                |    t        j                  | j                  D cg c]  }|j                          c} S c c}w rw   )r   r  r   r   r  s     rl   r   z$FusedSchedulerNode.used_buffer_names  s2    !MA!"5"5"7!MNN!Mr  c                |    t        j                  | j                  D cg c]  }|j                          c} S c c}w rw   )r   r  r   r  r  s     rl   r  z/FusedSchedulerNode.used_or_aliased_buffer_names  s7    8<D1a,,.D
 	
Dr  c                    | j                   S rw   r  rj   s    rl   r   zFusedSchedulerNode.get_nodes   r  rn   c                T    t        |       j                   d| j                          dS )Nz(nodes=r~  r  rj   s    rl   r  zFusedSchedulerNode.__repr__#  s'    t*%%&gdmmo->a@@rn   c                :    t        d | j                  D              S )Nc              3  <   K   | ]  }|j                           y wrw   )r   r  s     rl   r   z2FusedSchedulerNode.is_reduction.<locals>.<genexpr>(  s     9[1>>#[r  r   r   rj   s    rl   r   zFusedSchedulerNode.is_reduction&  s    9T[[999rn   c                :    t        d | j                  D              S )Nc              3  <   K   | ]  }|j                           y wrw   )r  r  s     rl   r   z6FusedSchedulerNode.is_native_matmul.<locals>.<genexpr>,  s     =A1%%'r  r  rj   s    rl   r  z#FusedSchedulerNode.is_native_matmul*  s    ====rn   c                :    t        d | j                  D              S )Nc              3  <   K   | ]  }|j                           y wrw   )r  r  s     rl   r   z3FusedSchedulerNode.is_split_scan.<locals>.<genexpr>0  s     :k1??$kr  r  rj   s    rl   r  z FusedSchedulerNode.is_split_scan.  s    :dkk:::rn   c                :    t        d | j                  D              S )Nc              3  <   K   | ]  }|j                           y wrw   r  r  s     rl   r   z1FusedSchedulerNode.is_template.<locals>.<genexpr>4  s     8Kq1==?Kr  r  rj   s    rl   r   zFusedSchedulerNode.is_template2  s    8DKK888rn   c                j    | j                   D ]$  }|j                         s|j                         c S  y rw   )r   r   r  rk   r   s     rl   r  z$FusedSchedulerNode.get_template_node6  s0    KKD!--//   rn   c                     | j                   d   S r   )r   rj   s    rl   r   zFusedSchedulerNode.get_device=  s    zz!}rn   c                :    t        d | j                  D              S )Nc              3  <   K   | ]  }|j                           y wrw   )r  r  s     rl   r   z>FusedSchedulerNode.has_aliasing_or_mutation.<locals>.<genexpr>B  s     EA1--/r  r  rj   s    rl   r  z+FusedSchedulerNode.has_aliasing_or_mutation@  s    EEEErn   c                    t         rw   NotImplementedError)rk   r  s     rl   r  z'FusedSchedulerNode.update_mutated_namesF      !!rn   c                    t         rw   r*  )rk   r   s     rl   r  zFusedSchedulerNode.add_fake_depI  r,  rn   c                    t         rw   r*  r&  s     rl   r(  zFusedSchedulerNode.can_inplaceL  r,  rn   c                   | j                         }dj                  d | j                  D              }t               }|j	                  | dt        |       j                   d| d| dt        | j                  j                         d| dt        | j                         d| d	t        | j                  j                  | j                  z
         d| d
| j                   d| d| j                   d| d       |j                         5  | j                         D ]!  }|j	                  |j!                                # 	 ddd       |j#                  d       	 |j	                  | j%                                |j-                         j/                         S # 1 sw Y   XxY w# t&        $ r t(        j+                  dd       Y Lw xY w)r  r$  c              3  F   K   | ]  }t        |      j                    y wrw   )r   ry   r  s     rl   r   z/FusedSchedulerNode.debug_str.<locals>.<genexpr>R  s     F+QQ 0 0+s   !r#  r  r  r  r  r  r  r  r  z.outputs = [
            Nr%  r  Tr  )r  r  r   rR   r  r   ry   r)  r   r  rq  r   ra  rb  r+  rz  r/  r&  r  r  r  r  r,  r  )rk   r   node_typestrr   r   s        rl   r/  zFusedSchedulerNode.debug_strO  s   }}xxF$++FF

bd		Q|n -j))0012 3WT%<%<=> ?74#3#3#9#9D<S<S#STU VT445 6T445 6 
	
 ZZ\'')

3==?+ *  	c	HJJt++-.  '')) \  	HKK7$KG	Hs   	5FF" F" GGc                p    | j                   t        d | j                   D              S t        |          S )Nc              3  <   K   | ]  }|j                           y wrw   )r*  r  s     rl   r   z6FusedSchedulerNode.has_side_effects.<locals>.<genexpr>n  s     G;4t,,.;r  )r   r   r>  r*  r  s    rl   r*  z#FusedSchedulerNode.has_side_effectsk  s0    ;;"G4;;GGGw'))rn   r   r_   r   r_   r   r   r  rT  r  r  )r  r  r   r  r   rU  rR  r  r   ri  r  r  rV  r  )r   torch.devicer  )r   r3   r   rU  r  )%ry   rz   r{   r  r|   r}   rr   r  r  rI   r  r  rx  r  r  r  rz  r  r  r  r   r  r   r  r   r  r  r   r  r   r  r  r  r(  r/  r*  rS  rT  s   @rl   r   r     s    $#
+%
+.?
+	
+ 
+,
  ")!).7)	)VL = =) N N	B/8#28HV8	8 O O 
 

A : : > > ; ; 9 9   F F
"""*8 * *rn   r   c                  D     e Zd Zd fdZ	 	 	 	 	 	 ddZddZddZ xZS )FusedMixOrderReductionsc                `   t         j                  |      st         j                  |      sJ ||}}|| _        || _        t        |   |j                  t        |j                               t        |j                               z          t         j                  | j                        | _
        y rw   )r   r   r   r   r>  rx  r  r   r   r   rF  )rk   r   r   rG  s      rl   rx  z FusedMixOrderReductions.__init__s  s     33E:$77>>> %5E

OOT%//"34tEOO<M7NN	
 '00<
rn   c                   t        |t              rJ t        |t              rJ | j                  j                  ||d      syt        j                  |      rt        j                  |      sydd}	 	 	 	 dd}|r' |||f       ||      z  s ||       |||f      z  ry|j                          xsC t        j                  t        | j                  j                  ||d            | j                  k\  S )a  
        node1 is from the current mix order reduction; node2 is another node we want to fuse in.

        other_nodes are passed in to check if fusion will introduce producer/consumer relationship
        between the inner and outer reduction. If yes, we don't fuse.
        Fallow_mix_order_reductionc                B    t               } |j                  d | D         S )Nc              3  4   K   | ]  }|j                     y wrw   )r   r  s     rl   r   zTFusedMixOrderReductions.sub_node_can_fuse.<locals>._get_ancestors.<locals>.<genexpr>  s     :Eqq{{Er  r   r  r  r   s     rl   _get_ancestorszAFusedMixOrderReductions.sub_node_can_fuse.<locals>._get_ancestors  s     ,C399:E:;;rn   c                B    t               } |j                  d | D         S )Nc              3  <   K   | ]  }|j                           y wrw   )r   r  s     rl   r   zZFusedMixOrderReductions.sub_node_can_fuse.<locals>._get_operation_names.<locals>.<genexpr>  s     F1q446r  r?  r@  s     rl   _get_operation_nameszGFusedMixOrderReductions.sub_node_can_fuse.<locals>._get_operation_names  s"     ,C399FFGGrn   )count_bytes)r  tuple[BaseSchedulerNode, ...]r   r_  )r   r8  r  r   r   r   r   typingcastr  score_fusion_memoryrF  )rk   r   r   other_nodesrA  rD  s         rl   sub_node_can_fusez)FusedMixOrderReductions.sub_node_can_fuse  s    e%<===e%<===
 ~~&&ueu&U //
#66u=	<	H0	H	H u~.1Ek1RR{+.BE5>.RR ""$$ {{T^^77uRW7X zz	
rn   c                   t        |t              sR| j                  | j                  || j                  f      xs( | j                  | j                  || j                  f      S | j                  | j                  |j                  | j                  |j                  f      xr/ | j                  | j                  |j                  t                     S rw   )r   r8  rK  r   r   r   rk   others     rl   can_fuse_withz%FusedMixOrderReductions.can_fuse_with  s    %!89))

EDJJ= J''

EDJJ=IJ ))

EKK$**ekk)B K((U[[%'JKrn   c                T   | j                   j                         }| j                  j                  |      }t	        |t
              rX|j                  | j                   |j                         }|j                  | j                  |j                        }t        ||      S | j                  | j                   || j                  f      r2|j                  | j                   |      }t        || j                        S |j                  | j                  |      }t        | j                   |      S rw   )	r   r   r  rc  r   r8  rr   r   rK  )rk   rN  r  backendfused_node1fused_node2r4  s          rl   	fuse_withz!FusedMixOrderReductions.fuse_with  s    &&(..,,V4e45!,,tzz5;;?K!,,tzz5;;?K*;DD%%djj%$**G$\\$**e<
.z4::FF$\\$**e<
.tzz:FFrn   r"  )r   r_   r   r_   rJ  rF  )rN  r_   )ry   rz   r{   rx  rK  rO  rT  rS  rT  s   @rl   r8  r8  r  s6    
=2
 2
 !2
 3	2
h
KGrn   r8  c                  f     e Zd Z	 	 	 	 	 	 	 	 d fdZe	 	 	 	 	 	 dd       ZddZd	dZd
dZ xZ	S )$FusedExternTritonKernelSchedulerNodec                ,   t        |j                  t        j                        sJ t	        j
                  t        t           ||g      }t        | %  ||       || _
        || _        | j                  j                  | _        |j                  | _        y rw   )r   r   r+   r@  rG  rH  r   r_   r>  rx  kernel_nodefused_epiloguerc  rj  )rk   r  rX  rY  r   rG  s        rl   rx  z-FusedExternTritonKernelSchedulerNode.__init__  s{     +**B,F,FGGGT"34{N6STF+&,))33%--rn   c                   |j                   }t        |j                        dk(  sJ |j                  t	        t        |j                              j                     }|j                  j                  t        |             t        |||      S Nr   )r  r   rq  r@  r  r  r   r  removeNodeUserrV  )rq   r   r   r  original_mutated_buffers        rl   epilogue_fusez2FusedExternTritonKernelSchedulerNode.epilogue_fuse  s{     OO	 5++,111"+"7"7e../055#
 	 %%,,Xe_=3IueLLrn   c                   t        | j                  j                  t        j                        sJ t        | j
                  j                  t        j                        sJ | j
                  j                  j                         sJ t        j                  | j
                  j                  j                  d   j                        }ddlm} |j                  | j                  g|      \  }}ddlm}  || j                  g|      }ddlm}  ||||       }	|	j'                         }
| j
                  j                  j)                  || j                  j                  |
f      S )Nr   rr  )SIMDKernelFeatures)FusedUserDefinedTritonKernel)r   rY  r   r+   r   rX  r@  rA  rB  r   rC  rD  torch._inductor.codegen.simdrs  get_tiling_and_scores,torch._inductor.codegen.simd_kernel_featuresra  torch._inductor.codegen.tritonrb  r;  codegen_with_epilogue_fusion)rk   rN  rF  rs  tilingr  ra  kernel_featuresrb  fused_user_kernelnew_kernel_srcs              rl   r;  z,FusedExternTritonKernelSchedulerNode.codegen  s    $--22B4E4EFFF$**//1K1KLLL$$66888		$**//<<Q?EEF?"88$:M:M9NPUV	S,d.A.A-BEJO8RVW*224$$AAd))..?
 	
rn   c                     yrJ  r~   rj   s    rl   r"  z.FusedExternTritonKernelSchedulerNode.is_extern	  r  rn   c                6    | j                   j                         S rw   )rX  r  rj   s    rl   r  z/FusedExternTritonKernelSchedulerNode.get_ranges		  s    **,,rn   )r  r  rX  r  rY  r   r   rU  )r   r  r   r   r   r   rR  rV  rP  )
ry   rz   r{   rx  r}   r_  r;  r"  r  rS  rT  s   @rl   rV  rV    sr    .. /. &	.
 
. M(M M 
	M M 
,-rn   rV  c                  N    e Zd ZU dZ	 	 	 	 ddZ	 	 	 	 ddZedd       Ze	 	 	 	 	 	 dd       Z	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	e	 	 	 	 dd       Z
e	 	 	 	 dd       ZeZd	ed
<   e	 	 	 	 dd       Ze	 	 	 	 dd       ZddZddZddZddZd dZd!dZ	 	 	 	 d"dZ xZS )#ForeachKernelSchedulerNodez
    This is a schedular node that consists of a set of scheduler nodes that
    has no data dependencies among them and can be executed in parallel.
    c                    |j                         D ]=  }|j                         | j                  v s | j                  |j                            c S  y rw   )rz  r  read_to_node)rk   producerr   s      rl   get_consumer_subnode_forz3ForeachKernelSchedulerNode.get_consumer_subnode_for	  sG     '')C||~!2!22((88 * rn   c                   t        t                  }|j                  j                  D ]  }|j                  | j
                  j                  vr&| j
                  j                  |j                     j                         }|| j                  v sf|j                  | j                  |           t        |      dk(  rt        t        |            S y r[  )r   r_   r   r   r   r  r@  r  name_to_noder  r   r  r  )rk   consumer	producersrd	node_names        rl   get_producer_subnode_forz3ForeachKernelSchedulerNode.get_producer_subnode_for	  s     013	&&,,Bwwdnn88822277;LLNID---d//	:; - y>QY((rn   c                   t        |      }j                         r|j                         rt        j                  t              t        j                  t        |      }t        j                        t        |j                        k(  }|s |d       |xr2 t        fdt        j                  |j                        D              S |j                         rkj                         r	 |d       yt        j                  t        |      }|j                        }||j                  j                  |      S  |d       yj                         rk|j                         r	 |d       yt        j                  t              j                  |      }|j                  j                  ||      S  |d       yt        d      )	Nzforeach do not have same lengthc              3  \   K   | ]#  \  }}j                   j                  ||       % y wrw   )r  r   )r   lrrr  s      rl   r   z6ForeachKernelSchedulerNode.can_fuse.<locals>.<genexpr>8	  s0      )ADAq ""++Aq1As   ),zXcandidate producer is a reduction, foreach ops cannot be fused with reductions currentlyFz5candidate producer is not dep of any foreach consumerzXcandidate consumer is a reduction, foreach ops cannot be fused with reductions currentlyz5candidate consumer has no dep in any foreach producerzXAt least one node passed to ForeachKernelSchedulerNode.can_fuse should be a foreach node)r  r$  rG  rH  ro  r   r   r   r  r   rs  r  r   rz  r  )rq   rr  rv  whyforeach_matchconsumer_subnodeproducer_subnodes    `     rl   r   z#ForeachKernelSchedulerNode.can_fuse/	  s   (+ X%8%8%:{{#=xHH{{#=xHH0C4HHM 56  S )A) &    "$$&n {{#=xHH'@@J+))228=MNNGH  "$$&n {{#=xHH'@@J+))223CXNNGHf
 	
rn   c                
   |j                         s|j                         sJ |j                         r3t        j                  t        |      }|j                  }|j
                  }n2t        j                  t        |      }|j                  }|j
                  }d }d }|j                         r|j                         r|t        j                  t        |      }t        j                  t        |      }t        |j                  |j                        D cg c]  \  }}t        j                  ||       }	}}n/|j                         rt        j                  t        |      }|j                  |      }
g }	|}d }|j                  D ]A  }||
u r*t        j                  ||      }|}|	j                  |       1|	j                  |       C n|j                         rt        j                  t        |      }|j                  |      }g }	|}d }|j                  D ]A  }||u r*t        j                  ||      }|}|	j                  |       1|	j                  |       C nt        d       | |j                  |	||||      S c c}}w )NzTAt least one node passed to ForeachKernelSchedulerNode.fuse should be a foreach node)use_custom_partition_algoprev_node_1prev_node_2enable_autotune)r$  rG  rH  ro  r  r  r  r   r   rr   rz  r   rs  r  r  )rq   rr  rv  r  r  r  r  r}  r~  fused_nodesr  r   new_noder  s                 rl   rr   zForeachKernelSchedulerNode.fuse^	  sS    ""$(;(;(=== {{#=xHH(0(J(J%&66O{{#=xHH(0(J(J%&66O X%8%8%:{{#=xHH{{#=xHH  AADAq #''1-A     "{{#=xHH'@@JK"KK ++166tXFH"*K&&x0&&t, (   "{{#=xHH'@@JK"KK ++166xFH"*K&&x0&&t, ( !f  &?##+
 	
Ks    I?c                n    i  _         i  _        ||qt           ||       |D ]Z  }|j                  j
                  D ]  }| j                   |j                  <    |j                         D ]  }	| j                  |	<    \ n<| _        | _	        d  _
        g  _         j                  t        j                  j                  |j                  |j                  g             t!         fdt!        j"                  |j$                  |j$                        D               j                  j&                  z
   _        t)        |j*                  |j*                  g       _        t-        |j.                  |j.                  g       _        t)        |j0                  |j0                         _        t-        |j2                  |j2                         _        |j5                         rt7        |t8              sJ ||}}
nt7        |t8              sJ ||}}
|
j:                   _         j:                  j=                  |j:                         |
j                   _        |j                         D ]  }	| j                  |	<     j                  D ci c]'  }|j>                  jA                         D ]  \  }}||
 ) c}}} _        | _!        |d   jE                         }|sJ |tG        jH                  d      fff _%        t!        tL        jN                  jP                             _)        | _*        y c c}}}w )Nc              3  Z   K   | ]"  }|j                   j                         vr| $ y wrw   r  r  s     rl   r   z6ForeachKernelSchedulerNode.__init__.<locals>.<genexpr>	  s4        xxt'<'<'>>	  r  r   combo_kernel)+rq  ru  r>  rx  r   r   r   r   r  r   r   r  r  r*   r  r  r   r  rq  r  r  rc  r  rd  ra  rb  r$  r   ro  r   r  rl  itemsr  r   r   Exprr   r  fxNoder_  r  )rk   r  r   r  r  r  r  r   rH  r   foreach_noder   r  r  vr  rG  s   `               rl   rx  z#ForeachKernelSchedulerNode.__init__	  s    +"5GY/ ,,22D37D%%dii0 3 !446D.2D%%d+ 7	  'DN DKDI)+DJ  ''22 ,,k.E.EF  )//#668V8V   ""))* # !+"7"79N9N!OPDN +"7"79N9N!OPDN&)..0N0N'D# '*..0N0N'D# %%'!+/IJJJ+6j!+/IJJJ+6j)33DNNN!!*"6"67 , 9 9D"668*4!!$' 9 #'++@"-%:O:O:U:U:W$!Q1:W+@D  *C&%%'v

> :<>?
!%((--02.@s   ,L0c           
        |D cg c]  }t        |t              s| }}|rSt        j                  dt	        |      |D cg c])  }|j
                  |j
                  j                         + c}       |D cg c]  }t        |t              s| }}|rt        j                  dt	        |             |D cg c]  }t        |t              s| }}|rt        j                  dt	        |             |D cg c]$  }t        |t        t        t        t        f      s|& }}|D cg c]  }t        |t              s| }}|rt        j                  dt	        |             |D cg c]  }t        |t              r| }}|D cg c]  }|j                         s| }	}|	r t        j                  dt	        |	      |	       |D cg c]	  }||	vs| }}t        j                  ra|D cg c]  }|j                         s| }
}|
rt        j                  dt	        |
             |D cg c]  }|j                         r| }}|S c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w )Nz/ComboKernels: %d external nodes are filtered %sz+ComboKernels: %d grouped nodes are filteredz;ComboKernels: %d FusedMixOrderReductions nodes are filteredz+ComboKernels: %d foreach nodes are filteredz0ComboKernels: %d template nodes are filtered: %szCComboKernels: %d reduction nodes are filtered (pointwise_only mode))r   r  r  r  r   r   rW  r  r8  rA  ro  r   r(   combo_kernels_pointwise_onlyr   )rq   r  rJ  externr   grouped	mix_orderfiltered_nodesforeach_nodestemplate_nodesreduction_nodess              rl   combinable_nodesz+ForeachKernelSchedulerNode.combinable_nodes	  sv    #OUj4M&N!UOIIAF5;UVTtyy?T&&(VU
 $Kez!5I'J1eKII=G !&P1A7N)OQ	PIIMI 
*-(+	  	 
 &
%!A7Q)RA~ 	 
 IICSEWX%
%!Z;U-VA~ 	 
 &4G^q}}!^GIIBN#
 &4O^q7N!^O ..*8M.QANN<Lq.OM		Y( *8PAq~~?OaNPy P
 VK Q



 H P N Qs|   IIII:II;I I <)I%+I*I*,I/I/I4"I4	I9I92I>I>3J	Jc                   | j                         }g }d}t        |D cg c]0  }|D ])  }t        |t              r|j	                         D ]  }| + 2 c}}}      }|D ]  }t        t              }	|D ][  }|j                         }
|
r|
j                  dk(  s|
j                  dk(  r4|j                         |z  rH|	|
   j                  |       ] |	j                         D ]  }t        t              }|D ]0  }|| j                  j                  |d         j                  |       2 |j                         D ];  }|j                  t        dt!        |      |      D cg c]
  }||||z     c}       =   |S c c}}}w c c}w )zS
        Returns a list of lists of nodes that are to be grouped together.
           mpsr  r   )_topological_sort_nodesr   r   r8  r  r   r   r   r   r   r   r   node_to_streamr  r  r  r   )r  sorted_nodesgrouped_nodesmax_num_nodesr   r   r  excluded_buffer_namesr  device_groupsr  device_nodesstream_groupsstream_nodesr  s                  rl   &_default_group_nodes_for_combo_kernelszAForeachKernelSchedulerNode._default_group_nodes_for_combo_kernels/
  s    !88:1; *)E!Dd$;< $ 5 5 7H	  !8	 ! )2
 "E D!  *v{{e3v{{e7K ))+.CCf%,,T2  !. 4 4 6DOPTDU(D!)":":">">tQ"GHOOPTU )$1$8$8$:L!(( &+1c,.?%O%O )Q->?%O %;	 !7% ": K@s   5E? F4Callable[[Scheduler], list[list[BaseSchedulerNode]]]!group_algorithm_for_combo_kernelsc                    | t         _        y rw   ro  r  )custom_group_algorithms    rl   %set_group_algorithm_for_combo_kernelsz@ForeachKernelSchedulerNode.set_group_algorithm_for_combo_kernelsf
  s    
 # 	#Drn   c                ,    t         j                  |       S rw   r  r  s    rl   group_nodes_for_combo_kernelsz8ForeachKernelSchedulerNode.group_nodes_for_combo_kernelsn
  s     *KKIVVrn   c                    t         rw   r*  rj   s    rl   r  z#ForeachKernelSchedulerNode.mark_runt
  r,  rn   c                    t         rw   r*  rj   s    rl   r;  z"ForeachKernelSchedulerNode.codegenw
  r,  rn   c                     yrJ  r~   rj   s    rl   r$  z%ForeachKernelSchedulerNode.is_foreachz
  r  rn   c                ,    t        | j                        S )zeReturns a list of nodes which comprise the combo kernel.
        These nodes may be vertically fused.)r   r   rj   s    rl   get_subkernel_nodesz.ForeachKernelSchedulerNode.get_subkernel_nodes}
  s     DKK  rn   c                t    t        t        j                  j                  d | j                  D                    S )zqReturns all nodes contained in this kernel, unpacking fused nodes
        into their constituent scheduler nodes.c              3  <   K   | ]  }|j                           y wrw   )r   r  s     rl   r   z7ForeachKernelSchedulerNode.get_nodes.<locals>.<genexpr>
  s     1UA!++-r  )r   r  r  r  r   rj   s    rl   r   z$ForeachKernelSchedulerNode.get_nodes
  s(     IOO111U1UUVVrn   c                <    | j                   d   j                         S r   )r   r  rj   s    rl   r  z)ForeachKernelSchedulerNode.get_first_name
  s    {{1~,,..rn   c                    t        | || j                  j                         | j                  D ]  }|j	                  |        y rw   )r  r  r@  r   r  )rk   r  r   s      rl   r  z/ForeachKernelSchedulerNode.prune_redundant_deps
  s8     	d$68R8RSKKD%%&89  rn   )rr  r_   r   r  )rv  r_   r   r  rr  r_   rv  r_   r   rv   )rr  r_   rv  r_   r   ro  )NNF)r  r  r   r  r  rv   r  r  r  r  r  rv   r   rU  r  r  r   r  )r  r  r   list[list[BaseSchedulerNode]])r  r  r   rU  rT  rV  r   r  r  rR  r  )ry   rz   r{   r  rs  rz  r}   r   rr   rx  r  r  r  r  r|   r  r  r  r;  r$  r  r   r  r  rS  rT  s   @rl   ro  ro  	  s   
)	!)	!& ,
 ,
\ >
(>
4E>
	#>
 >
J 1504 %L/L/ (L/ $(	L/
 .L/ .L/ L/ 
L/\ ?+?	 ? ?B 00	&0 0h 	/ & ( / 
 T
	
 
 WW	&W W
""!
W
/:">:	:rn   ro  c                       e Zd ZU dZded<   edd       Z	 d	 	 	 	 	 	 	 d fdZddZddZ	e
dd       Zdd	Ze
dd
       ZddZe
dd       ZddZddZedd       Z xZS )r  aC  
    This is a "fake" scheduler node that represents a group of scheduler nodes
    that are meant to be *grouped* together (it does not allow another node to be scheduled
    in between its constituent nodes, nor does it allow another node to fuse into any of its constituent nodes).
    The way it does this is by maintaining its unmet dependencies as the union of its constituent nodes.
    Fusion will still happen among the nodes within each GroupedSchedulerNode.
    At codegen time, this scheduler node will be unpacked and codegen is called on each constituent node.
    r  r   c                    |d   j                   t        fd|D              sJ  | |      }|D ]  }|j                  |j                         <   ! |j                  |j                         <   |S )Nr   c              3  :   K   | ]  }|j                   u   y wrw   r  )r   r   r  s     rl   r   z.GroupedSchedulerNode.create.<locals>.<genexpr>
  s     B644>>Y.6   )r  r   r  r  )rq   r   grouped_snoder  r  s       @rl   createzGroupedSchedulerNode.create
  sr    1I''	B6BBBBIv.E=JI(()9: AN	$$]%;%;%=>rn   c                L    t         |   |       t        | ||       || _        y rw   )r>  rx  r  temp_grouping)rk   r  r   r  rG  s       rl   rx  zGroupedSchedulerNode.__init__
  s(     	#i0 +rn   c                6   | j                   r| j                  S | j                  D ])  }|| j                  j                  |j	                         <   + | j                  j                  | j	                         = | j                  j                  | j                        S )z
        Do fusion among nodes within this GroupedSchedulerNode,
        and then unpack this GroupedSchedulerNode into regular nodes.
        )r  r   r  r  r  
fuse_nodes)rk   r  s     rl   unpackzGroupedSchedulerNode.unpack
  sq    
 ;;[[EBGDNN--enn.>? !NN--dmmo>~~((55rn   c                    | j                  | j                  j                  |             | j                  j	                  |       y rw   )r  r   r  rq  r  )rk   fake_deps     rl   r  z!GroupedSchedulerNode.add_fake_dep
  s5    T--77AB##H-rn   c                z    dj                  | j                  D cg c]  }|j                          c}      S c c}w r  r  r  s     rl   r  zGroupedSchedulerNode.get_name
  r  r  c                <    | j                   d   j                         S r   r  rj   s    rl   r  z#GroupedSchedulerNode.get_first_name
  r	  rn   c                |    t        j                  | j                  D cg c]  }|j                          c} S c c}w rw   r  r  s     rl   r  z%GroupedSchedulerNode.get_buffer_names
  r  r  c                j    g }| j                   D ]!  }|j                  |j                                # |S rw   r  r  s      rl   rz  z GroupedSchedulerNode.get_outputs
  r  rn   c                    t        t        d d | j                         D                    }t        |      dk(  ry t	        |      }|S )Nc              3  |   K   | ]4  }|j                         s|j                         r|j                          6 y wrw   r  r  s     rl   r   z6GroupedSchedulerNode.estimate_flops.<locals>.<genexpr>
  r  r  r   r  r  s      rl   r  z#GroupedSchedulerNode.estimate_flops
  r  rn   c                    | j                   S rw   r  rj   s    rl   r   zGroupedSchedulerNode.get_nodes
  r  rn   c                X    | j                   r| j                   d   j                         S d S r   )r   r   rj   s    rl   r   zGroupedSchedulerNode.get_device
  s$    .2kkt{{1~((*CtCrn   c                     yr  r~   )rq   rr  rv  s      rl   r   zGroupedSchedulerNode.can_fuse
  r  rn   )r   r  r   r  )F)r  r  r   r  r  rv   r   rU  r  )r  r3   r   rU  rR  r  r5  r  r  rX  r  )ry   rz   r{   r  r|   r}   r  rx  r  r  rI   r  r  r  rz  r  r   r   r   rS  rT  s   @rl   r  r  
  s     $#  $	++ (+ 	+
 
+6. = =) N N  "D  rn   r  c           
          t         j                  d fd       }t        t        t	        t         d                           }t        |      dkD  r|D cg c]  } |   	 c} t        j                  r|j                  |       |S c c}w )z
    A heuristic to decide loop iteration orders.  This has not been well
    tuned and may be something we should autotune.
    c                t   |    dk(  s|   dk(  rt        |    dk(  |   dk(        S D cg c]  }t        ||           }}D cg c]  }t        ||          }}t        d t        ||      D              }t        d t        ||      D              }||kD  ry||kD  ryt        ||       S c c}w c c}w )Nr   c              3  :   K   | ]  \  }}|d k(  xs ||k    ywr   Nr~   r   sl_asl_bs      rl   r   z5pick_loop_order.<locals>.index_cmp.<locals>.<genexpr>  )      
7VtDAI$$7V   c              3  :   K   | ]  \  }}|d k(  xs ||k    ywr  r~   r  s      rl   r   z5pick_loop_order.<locals>.index_cmp.<locals>.<genexpr>  r  r  r   )rJ   absr   r  )	r  bslstride_len_astride_len_ba_firstb_firstr~  stride_lengthss	          rl   	index_cmpz"pick_loop_order.<locals>.index_cmp  s    8q=E!HMuQx1}eAh!m44 .<<^rBqE
^<-;<^rBqE
^<  
7:<7V
 
  
7:<7V
 
 WW 1ay# =<s   B0	B5r   r$  )r  r  r  r  r   r  )		functools
cmp_to_keyr   r   r  r   r(   pick_loop_orderssort)r  r~  priority_idxr  orderpis   ``    rl   pick_loop_orderr  
  s      4 %N1$5 6789E
<17CD|.,|D

y
!L Es   Bc                   |j                         }| j                         }t        |t              rt        |t              sJ |j                         }| j                         }t        |t              rt        |t              sJ t        j
                  j                  |= ||_        t        j
                  j                  |= ||_	        t        j
                  j                  j                  |       }t        j
                  j                  j                  |       |t        j
                  j                  |<   |t        j
                  j                  |<   t        j
                  j                  j                  |       }t        j
                  j                  j                  |       |t        j
                  j                  |<   |t        j
                  j                  |<   y rw   )r  r   r  r  rZ   r   r  r   
name_to_opoperation_namebuffersr   r\  
operations)	orig_noder  replaced_buf_nameorig_buf_namereplaced_op_nameorig_op_nameorigs          rl   _replace_operation_bufferr  &  sU    !))+&&(MmS)j9JC.PPP224//1LlC(Z8H#-NNN	01!HM	+,*H77??  +DGGOO8$$AGGOOD,4AGG=)77##I.DGGh''AGGt'/AGG|$rn   c                p    | j                         }|j                         }||z
  }||z  }|d|z   z  }||z  S r[  )rn  rl  )r   r   epilogue_runtimetemplate_write_bytesepilogue_read_bytesextra_bytesextra_bytes_ratioextra_memory_ratios           rl    _estimate_fused_epilogue_runtimer  B  sX     779557%(<<K $&:: +a2C.CD 000rn   c                    |dk\  ry|j                   }|y|sJ ||j                  xs dz  }| |z  }||z  }||z  }	||z  }
|	|
fS )Nr  )r   r   )r   r       )regs_per_multiprocessor	warp_size)unfused_n_regsfused_n_regsfused_n_spills	num_warpsdevice_propsregs_per_smthreads_per_blockregs_per_block_unfusedregs_per_block_fusedblocks_unfusedblocks_fuseds              rl   "_occupancy_before_and_after_fusionr  O  s|      66K9!\%;%;%ArB+.??'*;; $::N"66L<''rn   c                    d}d}t        |||||      \  }	}
|d| z  kD  xr |
dkD  }|
dk7  xr |
|k\  xs |
|	z  |kD  xs |S )zE
    Determine whether to fuse an epilogue into a GEMM template.
    r&  g      ?r   r   r   )r  )ms1ms2r
  r  r  r  r  MIN_ACCEPTED_OCCUPANCYREGRESSED_OCCUPANCY_RATIOr  r  ,epilogue_dominated_with_sufficient_occupancys               rl   _fuse_epiloguer  j  s      # $Fni$ NL 47S=3U\TUEU0
 2 .. 	8.(+DD	87rn   c                  T    e Zd ZU ded<   dZded<   dZded<   ddZddZdd	Zdd
Z	y)r]  BaseSchedulerNode | OutputNoder   Frv   r(  is_weakc                v    t        | j                  j                         | j                  | j                  f      S rw   )r   r   r  r(  r  rj   s    rl   r!  zNodeUser.__hash__  s+    TYY'')4+;+;T\\JKKrn   c                    t        |t              xrW | j                         |j                         k(  xr4 | j                  |j                  k(  xr | j                  |j                  k(  S rw   )r   r]  r  r(  r  rM  s     rl   __eq__zNodeUser.__eq__  s[    uh' .5>>#33.  E$5$55. -		
rn   c                6    | j                   j                         S rw   r1  rj   s    rl   r  zNodeUser.get_name  r2  rn   c                    | j                   |j                   u sJ t        | j                   | j                  xr |j                  | j                  xr |j                        S rw   )r   r]  r(  r  rM  s     rl   rL  zNodeUser.merge  sP    yyEJJ&&&II2!2!2LL*U]]
 	
rn   NrS  )rN  objectr   rv   rR  )rN  r]  r   r]  )
ry   rz   r{   r|   r(  r  r!  r"  r  rL  r~   rn   rl   r]  r]    s3    
((K GTL
$
rn   r]  c                 "    t         j                  S rw   )r(   r  r~   rn   rl   *used_non_deterministic_runtime_estimationsr'    s    333rn   c                   t               }| j                         }t        |t        j                        r|j                  t        |j                        t        |j                        z  t        |j                        z         t        |t        j                        r$|j                  t        |j                               |S |
J d|        |S )z=Get free symbols from a node's layout (size, stride, offset).z*Expect layout to be None but found layout=)r   maybe_get_layoutr   r+   Layoutr  r"   r   strideoffsetrC  get_layout_symintsrX  )r   free_symbol_usesr'  s      rl   r-  r-    s    1;""$F&"))$%6==)*6==)*	

 fb;;<##$6v}}$EF  ~T!KF8TT~rn   c                "   t        | t              r( t               j                  d | j                  D         S | j
                  J | j
                  j                         } |j                  d | j
                  j                         D          |S )z
    Gets symbols used in a scheduler node, including free symbols from
    the node's operations and layout symints from outputs.
    c              3  2   K   | ]  }t        |        y wrw   get_scheduler_node_symbol_uses)r   r  s     rl   r   z1get_scheduler_node_symbol_uses.<locals>.<genexpr>  s     M,U3   c              3  2   K   | ]  }t        |        y wrw   )r-  )r   ir_nodes     rl   r   z1get_scheduler_node_symbol_uses.<locals>.<genexpr>  s     	M5L'
W
%5Lr3  )	r   r   r   r  r   r   get_free_symbol_usesr  rz  )r   r.  s     rl   r2  r2    s     $*+!z|!!MM
 	
 99   yy557	MTYY5J5J5L	M rn   c                v    | j                         }||j                  |j                  S t        j                  S z4Check per-template flag, fall back to global config.)r  allow_epilogue_fusionr(   epilogue_fusionr  tbs     rl   _is_epilogue_fusion_enabledr=    8    		(	(	*B	~"22>'''!!!rn   c                v    | j                         }||j                  |j                  S t        j                  S r8  )r  allow_prologue_fusionr(   prologue_fusionr;  s     rl   _is_prologue_fusion_enabledrB    r>  rn   c                b    | j                         xr |j                          xr t        |       S rw   )r   r=  r   s     rl   is_epilogue_fusionrD    4     	/!!##	/'.rn   c                b    |j                         xr | j                          xr t        |      S rw   )r   rB  r   s     rl   is_prologue_fusionrG    rE  rn   c                6    t        | |      xs t        | |      S rw   )rD  rG  r   s     rl   is_template_fusionrI    s    eU+O/A%/OOrn   c                "    t        | |      r|S | S rw   )rD  r   s     rl   template_fusion_pw_noderK    s    &ue45?%?rn   c                      e Zd ZdZdjdZdj fdZdkdZdldZdmdZdndZ	dodZ
edpd	       Zej                  dqd
       ZdldZdrdZdsdZdldZdldZdldZdldZdtdZ	 	 	 	 dudZdldZdvdZdwdZdldZdldZdldZdudZdldZ	 	 	 	 dxdZ	 dy	 	 	 	 	 	 	 dzdZ 	 	 	 	 	 	 d{dZ!	 	 	 	 d|dZ"dld Z#	 	 	 	 	 	 	 	 	 	 d}d!Z$d~d"Z%	 dy	 	 	 	 	 dd#Z&	 	 	 	 	 	 dd$Z'dd%Z(	 	 	 	 	 	 	 	 dd&Z)	 	 	 	 	 	 	 	 dd'Z*	 	 	 	 	 	 dd(Z+	 	 	 	 	 	 	 	 	 	 dd)Z,	 	 	 	 dd*Z-	 	 	 	 dd+Z.	 	 	 	 	 	 dd,Z/dydd-Z0dd.Z1	 	 	 	 	 	 dd/Z2	 	 	 	 	 	 dd0Z3	 	 	 	 	 	 dd1Z4	 	 	 	 	 	 	 	 dd2Z5	 	 	 	 	 	 dd3Z6	 	 	 	 	 	 	 	 dd4Z7	 	 	 	 	 	 dd5Z8	 	 	 	 	 	 dd6Z9dd7Z:	 	 	 	 	 	 	 	 dd8Z;	 	 	 	 	 	 dd9Z<	 	 d	 	 	 	 	 	 	 	 	 dd:Z=	 	 	 	 	 	 dd;Z>	 	 	 	 	 	 	 	 dd<Z?dd=Z@	 	 	 	 	 	 	 	 dd>ZAddd?ZB	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd@ZC	 	 	 	 	 	 ddAZD	 	 	 	 	 	 ddBZE	 	 	 	 ddCZF	 	 	 	 ddDZGdldEZHdldFZIdldGZJ	 	 	 	 ddHZKddIZLddJZMddKZN	 	 	 	 	 	 ddLZOddMZPeQddN       ZR	 	 	 	 ddOZS	 	 ddPZT	 	 	 	 ddQZU	 	 	 	 	 	 ddRZV	 	 	 	 	 	 ddSZW	 	 	 	 ddTZX	 	 	 	 dudUZY	 	 	 	 dudVZZ	 	 	 	 dudWZ[	 	 ddXZ\	 	 	 	 	 	 ddYZ]ddZZ^dld[Z_	 	 	 	 	 	 dd\Z`	 	 	 	 	 	 dd]Za	 	 	 	 	 	 dd^Zbdld_Zcdd`Zd	 	 	 	 ddaZeddbZfddcZgdlddZhedde       Zieddf       ZjddgZkdldhZlddiZm xZnS )r  z
    A Scheduler is a graph of BaseSchedulerNodes. It is responsible for
    optimizations such as fusion, reorder, and graph partition.
    c                f    t        d      5  | j                  |       d d d        y # 1 sw Y   y xY w)NzScheduler.__init__)r   _initrk   r  s     rl   rx  zScheduler.__init__  s#    ./JJu 0//s   '0c           
         t                     t        j                  _        i  _        t        t               _        t        j                          _        t                _        t        g t        j                  j                  j                         t        j                  j                   j                         t        j                  j"                  j                                _        |D cg c]  } j'                  |       c} _        d  _        d  _         j/                           j$                  j1                  t        j                  j                   j                                 j(                  D ]  }|j3                           d  _         j7                          _         j(                  D ci c]  }|j;                         | c} _         j(                  D ci c](  }|j?                         D ]  }|j;                         | * c}} _          j<                  jC                          _"        i  _#        i  _$        t                _%        tM        jN                   j(                   j@                   jD                         _         jQ                           jS                   j(                         _         jU                           j(                  D ci c]  }|j;                         | c} _"         jW                           jY                          tZ        xj\                  t_         j(                        z  c_.        ddl0m1}m2}  | j(                         t_         j(                         _3         ji                           jS                   j(                         _        t        tj        tl        tl        f              _7        tp        jr                  $tq        jr                   j(                         _        tp        jt                  r'ddl;m<} |j{                           jW                          i  _>        i  _?        d _@        i  _A         j                           j                   j(                         _        tp        j                  $tq        j                   j(                         _        t        d  j(                  D              r jU                           j                           j                          tp        j                  stp        j                  r<t               r2t        j                  j                  j                  j                          tp        j                  r)t        ddd	      5   j                  d 
       d d d         j                          tp        j                  rddlUmT}  | j(                   j@                   jD                  t        t        j                  j                  j                               t        t        j                  j                                      _        tp        j                  stp        j                  rtp        j                  s#ddlUmY}	  |	 j(                   j@                         t               rvt        j                  rftp        j                  st        j                  rFd}
 j(                  D ]  }t        |j                        sd}
 n |
rddl&ma}  | j(                         t        j                  rddlcmd}  |dd  fd       tM        j                   j(                         _         j                          tp        j                  rttp        j                  j                  rZtp        j                  j                  r@ j                   j(                         _         j                   j(                         _         j                          t        j                  jp                  j                  j                  r j                           | j(                         t        j                  j                   j(                          j                          t                _t        i  _u        d  _v        t        d      j                   fd       t                _y        y c c}w c c}w c c}}w c c}w # 1 sw Y   \xY w)Nr   )log_ir_post_fusionlog_ir_pre_fusionr   )distributed_autotuneFc              3  <   K   | ]  }t        |t                y wrw   )r   rV  r  s     rl   r   z"Scheduler._init.<locals>.<genexpr>q  s       
" tAB"r  z#Scheduler.create_combo_kernel_nodesTlog_pt2_compile_eventlog_waitcounter)num_ck_nodes)reorder_for_peak_memory)1assign_memory_planning_info_for_scheduler_buffers)6align_runtime_estimations_across_all_distributed_ranks)trace_structuredartifactc                     dddS )N#scheduler_nodes_before_comm_overlapstring)r   encodingr~   r~   rn   rl   rv  z!Scheduler._init.<locals>.<lambda>  s     E$,)rn   c            
         dj                  t        j                        D  cg c]0  \  } }d|  d|j                         z   d|j	                          z   2 c}}       S c c}} w )Nz

zsnode[r%  z buffer_names:)r  r  r  r/  r  )r  r  rk   s     rl   rv  z!Scheduler._init.<locals>.<lambda>  sq    v{{
 )2$**(=	 )>1 %QCqMkkm, .q/A/A/C.DEF )>	(s   5A"
)metadata_fn
payload_fngraph_statsc                 ^     j                    j                  t         j                        dS )N)graph_idnum_nodes_before_fusionnum_nodes_after_fusion)post_grad_graph_idnum_orig_nodesr   r  rj   s   rl   rv  z!Scheduler._init.<locals>.<lambda>  s%     33+/+>+>*-djj/rn   )zr>  rx  rZ   r   r  backendsr  _post_grad_graph_counterrj  r  count_graph_partition_counterr   r>  r  r   	constantstorchbind_constantsr  create_scheduler_noder  previous_nodecurrent_nodeupdate_zero_dim_cpu_tensorr  r  default_device_contextget_donated_buffersr?  r  ru  rz  r@  copyr  r  rg  seen_template_fusionsr'   decide_global_ordering_of_commsr]   topological_sort_scheduledead_node_eliminationcompute_ancestorscompute_input_distancesr,   ir_nodes_pre_fusionr   torch._inductor.debugrQ  rR  rk  create_foreach_nodesr   r  logged_slow_fusionr(   _pre_fusion_custom_passdistributed_max_autotune_gemmr  rS  scheduler  buff_to_stream_multi_stream_nodesstream_idx_to_user_obj_idx_populate_stream_assignmentsr  _post_fusion_custom_passr   r  finalize_multi_template_buffersmax_autotune_gemmmax_autotuner   r  r  select_algorithmPrecompileThreadPoolshutdown_instancecombo_kernelsr   create_combo_kernel_nodes_enforce_conditional_orderingrY  memoryget_output_namesdeterministic reorder_for_compute_comm_overlaprZ  r'  r)   6runtime_estimations_align_across_all_distributed_ranksr  r  rS   r   r[  reorder_sink_verbose_loggingtorch._loggingr\  $reorder_compute_and_comm_for_overlapprocess_grouped_nodesgraph_partitionr   r^   %reorder_for_reducing_graph_partitions&maybe_reorder_for_minimizing_partition,reorder_for_partition_with_simple_dependencycompute_last_usagetest_configstrack_memory_lifecycleinsert_memory_check_nodesr  graph_diagramdebug_draw_graphbuffer_names_to_freeorigin_to_index_current_stream_ctxr   add_rowremoved_ops)rk   r  r  r   r   rQ  rR  rS  rY  rZ  has_collectivesr[  r\  rG  s   `            rl   rN  zScheduler._init  s    <>"&'?"@(1(9%5?\!&0%%**,""'') ,,113'
# >CCUd003UC
7;6:'')##**177+<+<+A+A+CDJJDOO  <@# $$& 	# &*ZZ;
%/AJJL!OZ;

 -1JJ8
,6D$BRBRBT3CLLNCBTNJ8
 AE@Q@Q@V@V@X 35 13 L 	"
 ::JJ##

 	!!#33DJJ?
""$<@JJ"GJq1::<?J"G $$& 	##s4::6#O$**%!$**o!!#33DJJ?
",U38_"="?))577

CDJ//. ))$/""$ =?.0). :<'))+__TZZ0
**688DDJ 



 
 &&(,,.$$(;(;&(OO,,AASSU5&* $
 ..D.A 	**, ))70

  ''177//44671773356DJ ##(O(O11UAJJ 0 0
 ;< WW<<#PP #( JJD$TYY/*. ' # K4::V 88; !  CCDJJODJ""$ ""((CCDDTZZPDJJJ4::VDJ!??!!..EE**,4::&	djj) 6@\! :< GK '//	
 -7LA D;
8
H #Hh s$   5c$?c).-c.(c4c99dc                   i }t         j                  j                  D ]d  }t        t         j                  j                  |   t        j
                        s9t        | t         j                  j                  |   d       ||<   f |S )N)r  )rZ   r   graph_inputs_originalr   r+   DonatedBufferr]  )rk   name_to_donated_bufr   s      rl   rw  zScheduler.get_donated_buffers  sk     GG11D!''77=r?O?OP,BGG11$7 $-#D) 2 #"rn   c                v  
 ddl m
 i }t        j                  d      }| j                  D ]  }
}|j
                  D|j
                  j                         }|(||vrt        |      }|||<   || j                  |<   ||   }|| j                  |<   |j                         D ]  }|| j                  |<     t        
fd| j                  j                         D              rt        d | j                  D        d      }|| j                  D ]z  }|j
                  }	|j                          t        |	t         j"                        s;t        |	j$                  t         j&                        s`t!        j&                  |      |	_        | t        
fd| j                  j                         D              | _        y)a=  Populate node_to_stream and buff_to_stream from IR node stream_idx.

        Reads the stream_idx field set on IR nodes during lowering to determine
        which stream each scheduler node should run on. This field is propagated
        from 'custom.stream' FX node metadata via IRNode.current_stream_idx().
        r   )DEFAULT_STREAM_IDXNc              3  (   K   | ]	  }|k7    y wrw   r~   )r   rt  r  s     rl   r   z9Scheduler._populate_stream_assignments.<locals>.<genexpr>'  s     M0L1q&&0L   c              3  ^   K   | ]%  }|j                         |j                          ' y wrw   r   r  s     rl   r   z9Scheduler._populate_stream_assignments.<locals>.<genexpr>)  s"     RAq||~7Qs   --r  c              3  (   K   | ]	  }|k7    y wrw   r~   )r   
stream_idxr  s     rl   r   z9Scheduler._populate_stream_assignments.<locals>.<genexpr>7  s      '
:
 ,,:r  )stream_constantsr  r  rn  r  r   get_stream_idxr  r  r  r  r  r   r   r   r   r+   Bufferr'  r?   r  )rk   user_obj_to_stream_idxstream_idx_counterr   r  user_obj_idxnew_stream_idxr   r  r5  r  s             @rl   r  z&Scheduler._populate_stream_assignments  s    	9 24&__Q/JJD+Jyy$#yy779+#+AA)-.@)A?M.|<JV77G!7!EJ(2D% ,,.+5##C( /! , M0C0C0J0J0LMMRRTXF ! JJD"iiG)1&w		:&w~~r}}E *,f)E ' $' '
"1188:'
 $
 rn   c                    | j                   S )z7Check if any nodes are assigned to non-default streams.)r  rj   s    rl   _has_multi_stream_nodesz!Scheduler._has_multi_stream_nodes<  s    '''rn   c                    | j                   j                  ||      }| j                  j                  || j                  j                  |d            S )zAReturn the stream index for a buffer, resolving mutation renames.r   )rg  r  r  )rk   r  reals      rl   get_buf_streamzScheduler.get_buf_stream@  sF    $$((8<""&&tT-@-@-D-DXq-QRRrn   c                    | j                         sy| j                  |      | j                  j                  |d      k7  S )zTrue if buf_name was produced on a different stream than node.

        Resolves mutation renames so that mutated buffers inherit the
        stream of their original definition.
        Fr   )r  r  r  r  )rk   r  r   s      rl   rB  z!Scheduler.has_cross_stream_hazardE  s<     ++-""8,0C0C0G0Ga0PPPrn   c                6    t         j                  j                  S rw   rZ   r   current_devicerj   s    rl   r  zScheduler.current_deviceO  s    ww%%%rn   c                .    |t         j                  _        y rw   r  r  s     rl   r  zScheduler.current_deviceS  s    !'rn   c                    t         j                  j                  dd      dk(  rddlm}  || j
                  d       yy)z,Generate an image of the graph for debuggingINDUCTOR_WRITE_SCHEDULER_GRAPHN1r   )draw_buffersT)print_graph)osenvironr  r  r  r  )rk   r  s     rl   r  zScheduler.debug_draw_graphW  s1    ::>>:DASH+6 Irn   c                    t         j                  t        j                        r8t         j	                  d|       | j
                  D ]  }|j                           y y )Nz%s:)r  isEnabledForloggingINFOr  r  r  )rk   labelr   s      rl   debug_print_nodeszScheduler.debug_print_nodes^  sA    GLL)HHUE"

  " # *rn   c                6   |j                         J d       |j                         rt        | |      S t        |t        j
                  t        j                  f      rt        | |      S t        |t        j                        rt        | |      S t        |      )Nz2All nodes passed to scheduling must have an origin)rW  is_no_oprA  r   r+   r   ra  r   r  r  r+  r%  s     rl   rr  zScheduler.create_scheduler_noded  s    !- 	
@	
- ==?)$55r00"2C2CDE t,,boo.,T488%d++rn   c                   t               }g }| j                  j                         }t        j                  j
                  j                         D ]  }|D cg c]%  }||v rt        | j                  |   t              s|' }}|s6|j                  |       |D cg c]  }| j                  |    }}t        j                  dkD  }t        | |d|      }|j                  |       |D ]  }|| j                  |<     | j                  D 	cg c]  }	|	j!                         |vs|	 c}	t#        |      z   | _        y c c}w c c}w c c}	w )Nr   Fr  r  )r   r  r   rZ   r   listsr   r   ru  rA  r  r(   combo_kernels_autotunero  r   r  r  r   )
rk   removed_node_namesfe_nodeskept_node_namesnamesr   r   r  fe_noder   s
             rl   r  zScheduler.create_foreach_nodesq  sL   .8l11668WW]]))+E "!D?*"4#4#4T#:<RS !   %%e,:?@%$d''-%F@$;;a?O0*/ /	G OOG$07''- 1 ,8 "ZZ
'T4==?BT+TDZ
N
5 A
s   *D<EE#Ec                *   '()  G 'fddt         t                 't        j                  '      ( j                  D ]  }|j                         D ]  }|j                         }t        |j                  j                  t        j                        rt        |j                               dkD  r^|j                         D ]J  }|(v r/|(v r+(|   }(|   }||z   }(D ]  }(|   |u s(|   |u s|(|<    6|(v r	(|   (|<   C(|   (|<   L   d) fd)	 	 d	 	 	 	 	 	 	 	 	 d()fd}	i }
t        j                  j                   j#                         D ]  }t        |t$        j&                        r|j(                  D ]  }d|
|<   	 4t        |t        j*                        sO|j-                         D cg c]  }t        |t$        j&                        s|! }}|D ]  }|j(                  D ]  }d|
|<   	   d} j                  D ]s  }|j                  J t/        |j                  j1                         d 	      }|D ]8  }t        |t$        j2                        sJ d
}||
vs&|j                         |
|<   : u  j                  D ]@  }t4        j7                  d|j                         |r|j                  J t/        |j                  j9                  d
      d 	      }|D ]d  }||
v sJ | d|
        |
|   x} j:                  |   j                         D ]*  }|j=                  t?        |j                                      , f t        |j@                  jB                        dk(  rGtE        tG        |j@                  jB                              x}rt        |tH              r|jJ                  }nd}|j                         D ]7  }t        |jM                               dk  sJ |jM                         D ]  } )|      } |	||       |j=                  t?        ||             (|   jN                  D ]  }|j                         |j                         k(  r%t        |j                  tP              sJ |j                  j                         D ]c  }|j                         } )|      }||j                         v }|j=                  tS        ||j                         |               |	||d
       e   : t        j                  jT                  |j                            D ]8  } |	||d
       |j=                  tS        ||j                         d
             : t        j                  jV                  |j                            D ]'  } |	||d       |j=                  t?        |             ) |j@                  jX                  D ]6  }t        |tR              r |	|jZ                  ||j]                  |             8 |j_                   j`                         |j                         D ]  }|jM                         D ]y  }|j                          j`                   )|      <   |j                          j`                  |<    jb                  je                  ||       jb                  |j                         <   {  C t        j                  jg                         D ]3  }t4        j7                  d|        |	|ti        t?        |                   5 |rt        j                  jj                  D ]  }|j9                  d
      D ]|  }||
v sJ | d|
jm                                 |
|   x}s) j:                  |   jo                         D ]4  }t4        j7                  d||        |	|ti        t?        |                   6 ~   j`                  D ]  }|t        j                  j                   v rE |	|ti        t?        |                   t        j                  jp                  js                  |       d|t        j                  jt                  v s |	|ti        t?        |                    tw        t        j                  j                   jm                               D  ci c]  \  } }|| 
 }!} }t        j                  jp                  D cg c]  }|!|   	 c}t        j                  _<         j                  D ]C  }|j                         D ].  }|j{                  (|j                            jN                         0 E  j|                  D ]-  } j|                  |   j{                  (|   jN                         / t               }"|"j                  d       (jO                         D ]]  \  }}#|"j                         5  |#jN                  D $cg c]  }$|$j                          }%}$|"j                  d| d|% d       ddd       _ |"j                  d       |"j                         j                         }&t        j7                  d       t        j7                  d|&       yc c}w c c}} w c c}w c c}$w # 1 sw Y   xY w)zi
        Create dependency edges between nodes, handling aliasing and
        mutation properly.
        c                  >    e Zd ZdZ	 	 d	 	 	 	 	 ddZddZd	 fdZy)
1Scheduler.compute_dependencies.<locals>.DedupListan  
            This data structure behaves like a list except it makes sure the
            elements remain unique.
            Normally one could use a OrderedSet/dict for this purpose however
            the list in question gets elements appended as it is being
            iterated over which means that we need to keep the list
            semantics.
            Nc                @    |xs g | _         |xs
 t               | _        y rw   )r  r   
membership)rk   r  r  s      rl   rx  z:Scheduler.compute_dependencies.<locals>.DedupList.__init__  s    
 #[b
","<
rn   c                    || j                   v ry | j                  j                  |       | j                   j                  |       y rw   )r  r  r   r  )rk   	node_users     rl   r   z8Scheduler.compute_dependencies.<locals>.DedupList.append  s5    /

!!),##I.rn   c                    t        j                  | j                  |j                        }| j                  |j                  D cg c]  }|| j                  vs| c}z   } ||      S c c}w rw   )r   r  r  r  )rk   rN  new_membershiprJ  	new_items	DedupLists        rl   __add__z9Scheduler.compute_dependencies.<locals>.DedupList.__add__  sg    !+!1!1$//5CSCS!T JJ${{**!at.FA{* 	 !N;;*s   A+A+r  )r  zlist[_T] | Noner  zOrderedSet[_T] | Noner   rU  )r  ra   r   rU  )rN  DedupList[_T]r   r  )ry   rz   r{   r  rx  r   r  )r  s   rl   r  r    s;     *.48=&= 2= 	=/<rn   r  r   c                N    | j                   v r j                   |          S | S rw   )rg  )r  r  rk   s    rl   r  z.Scheduler.compute_dependencies.<locals>.rename  s,    D)))d33A677Hrn   Fc                P     |          j                  t        |||             y rw   )r   r]  )used_by_namer5  r(  r  name_to_usersr  s       rl   add_userz0Scheduler.compute_dependencies.<locals>.add_user  s)     &./66K9rn   Nc                    | j                   S rw   r  r  s    rl   rv  z0Scheduler.compute_dependencies.<locals>.<lambda>  s    AFFrn   r$  Tzscheduling %s)unbacked_onlyc                    | j                   S rw   r  r  s    rl   rv  z0Scheduler.compute_dependencies.<locals>.<lambda>  s    !&&rn   z not in )r  mutating_bufr  )r  )r  zscheduling output %sz+scheduling output %s for unbacked symint %srS  'z': r$  rT  zBUFFER USER LIST
z===== AFTER SCHEDULING =====
%s)r  r  r   r  )FF)
r  r  r5  r  r(  rv   r  rv   r   rU  )Er	   ra   r  r   r  rz  r  r   r   r'  r+   r?   r   r(  rZ   r   r  r   r   r  r"   	TensorBoxr  r)  get_unbacked_symbol_defsSymbolr  r  r6  ru  r  r5   r   r  r  r  r4   r  r*  r  r_   r6   additional_buffer_depsadditional_star_depsr   r   r(  r  rg  r  r  r  rG  graph_outputsr   r  mutated_inputsr  rp  r  mutated_input_idxsrM  r?  rR   r  r+  r,  r  compute_dependencies_log)*rk   r   buf1	buf1_name	buf2_namelist1list2combinedr%  r  unbacked_symbol_to_origin_nodevalfsrt  sym_sizehas_non_input_unbacked_defsunbacked_symbol_defsunbacked_symbol_usesr~  r   r   	node_modealt_namer.  out_buf
other_nameis_aliasadd_deprH  r  r   r   r   	inp_nameslogbufr  r  r  r  r  r  r  s*   `                                      @@@rl   r]   zScheduler.compute_dependencies  s}	   	< 	<@ @K?V?V@
 JJD((* MMO	 tyy//?D,,./!3!%!1!1!3I M1i=6P -i 8 -i 8#(5=#0C -c 2e ;#0#5#>5=c 2 $1 #m33@3Ki03@3Ki0 "4 + <	 !&!				 6		 			
 		 		 JL&
 77''..0C#uzz***B9=226 +C. (+||~S~!Auzz9RA~S!Ann=A6r: - " 1 ',#JJD99((( $*		224:J$  *!!U\\222 /3+::8<215 *   JJDIIotyy1*yy,,,'-II222F(($
 .A >> #X&D%EF> <A>>K#'#4#4Q#7#C#C#EC --gclln.EF $F . D$$++,1 d&6&6&=&=!>??S?sI.HH	 	 '')3,,./1444 # 1 1 3H%h/HXt,%%ghY&GH -h 7 = ===?dmmo=$)$))5FGGG'+yy'<'<'>G)0)9)9);J)/
);J (073F3F3H'HH -- '$.1408L!" %ZtD% (? !> !4 *B 7799$--/J$5 !!''4==?D"QR	 K 7777H$6!!''"23 I
 ((..!$0TYYd.>.>t.DE / %%d&;&;< '') # 1 1 3H>AllnD))&*:;69llnD))(3//33HhG ++CLLN; !4 *a r 002HII,h7Xz'(*;<= 3
 'ww,,111EA >> #X&D&I&I&K%LM> ;1==q=(,(9(9!(<(M(M(OHII M ( !
 %Xz'(:K/LM )P F - ))Dqww+++z'$-89&&**40***z'$-89 * ,5QWW5I5I5N5N5P+Q
+QKE4D%K+Q 	 
 )*(>(>&
(>IdO(>&
"
 JJD'')mCLLN;AAB *  //D''-77d8K8Q8QR 0  !c'--/JC/4{{;{!{;#c%23 ! 0 	c  "))+ &&';< &&'I3OK TX
&
" < !s6   5i4i42i9i?j	j5j	j		j	c           
         ddl m}m}m}m} t        t        j                  j                  j                               } | j                  |      }t        j                  j                  j                  s | j                   j                         t        t        j                  j!                               } | j                  ||      \  }}	}	t#        t%         j                              D 	cg c]  }	g g f c}	|D ]}  }
|
j&                  dk(  r|
j(                  dk(  r"|
j*                  j-                         }|
j.                     d   j1                  |       |
j2                     d   j1                  |        ddlm}  |        	 	 	 	 	 	 d fd}g }t9         j                        D ]H  \  }}|j1                  |       |j1                   |||t%         j                        dz
  k(               J | _
        y c c}	w )Nr   )rZ  compute_memory_timelineFreeableInputBufferget_freeable_input_bufr   )register_check_mem_opc                X   |    d   }|    d   }|||g}t        j                  t        t        j                  d            t        j
                  j                  j                  j                  g |d       }dj                  |    j                          |_        t        |      S )Nr   r   r  r  c                $    | |d   |d   |d   dfS )Nr   r   r   )alivedeadis_final_stepr~   )tensor_argsr  s     rl   rv  zWScheduler.insert_memory_check_nodes.<locals>.construct_mem_check_node.<locals>.<lambda>  s(    !.q!1 -a 0)6q)9Crn   )r'  r=  r#  nontensor_argsunflatten_args
mem_check_)r+   MemoryCheckKernelr?   r  r  r  _inductor_debugcheck_memory_stepdefaultr  r  r  r  )step_idxr"  expected_newly_aliveexpected_newly_deadr$  r   rk   step_allocs_deallocss         rl   construct_mem_check_nodezEScheduler.insert_memory_check_nodes.<locals>.construct_mem_check_node  s     $8#A!#D "6x"@"C24GWN''!e)<=yy00BBJJ- D %/tzz(/C/L/L/N.O"PD,T488rn   )r"  )r+  r  r"  rv   r   r  )r  rZ  r  r  r  r   rZ   r   r  r   r  r  r  r(   rY  r@  r  r  r   
size_alloc	size_freer]  r  
start_stepr   end_step#torch._inductor.runtime.debug_utilsr  r  )rk   rZ  r  r  r  r  name_to_freeable_input_bufr   buf_info_listr  buf_infor  r  r/  	new_nodesr  r   r.  s   `                @rl   r  z#Scheduler.insert_memory_check_nodes  s   	
 	
 )31773G3G3L3L3N(O"4::|< 	# %%===

D,, *4AGG4L4L4N)O5JJ&
q! $C

O4C
4RH4C
 &H""a'H,>,>!,C//1H !4!45a8??I !2!23A6==hG & 	N	9	9*.	9&	92 	 ,GAtT"(1DJJRS@S;SU - 
eC
s   3Hc                |  	 t         j                  syg }t        | j                        D ]  }dd	d}|j	                         D ]  }t        	fd|j                  D              }|r\t        j                  d|j                                t        j                  j                  j                  |j                                d} |j                          xr | }|s|j                  |       t        j                  d|j                                t        j                  j                   j                  |j                                |j"                  j$                  D ]  }|j&                  | j(                  v s| j(                  |j&                     j                  }|D cg c]0  }|j*                  j                         |j                         k7  s/|2 c}| j(                  |j&                     _          t-        t        |            | _        | j                  D ]  }|j/                           yc c}w )	z0
        Remove any nodes without users
        Nc                r    | j                   xs* | j                         t        j                  j                  v S rw   )r  r  rZ   r   r  )r.  s    rl   can_eliminate_userz;Scheduler.dead_node_elimination.<locals>.can_eliminate_user  s&    ||Tt}}!'':T:T'TTrn   Fc              3  .   K   | ]  } |        y wrw   r~   )r   ur;  s     rl   r   z2Scheduler.dead_node_elimination.<locals>.<genexpr>  s     #M9a$6q$99   zremoved dead buffer: %sTzremoved dead operation: %s)r.  r]  r   rv   )r(   use_dcer   r  rz  r   r  r  r  r  rZ   r   r?  r  r*  r   r  r   r   r   r@  r   r   r  )
rk   updated_nodesr   active_buffersr   can_eliminaterH  r  r=  r;  s
            @rl   r|  zScheduler.dead_node_elimination  s    ~~
 TZZ(DU #N'') ##M399#M M II7HGG++//?%)N * !% 5 5 77N<NM $$T* 		6H**..t}}? ,,22DyyD$4$44 $ 0 0 ; A A',=',!0AT]]_0TAu=((39 3- )8 (=12
 JJD  " =s   %0H9H9c                
    |duS )z:Check if store mode requires cross-thread synchronization.Nr~   )rk   r  s     rl   mode_requires_synchronizationz'Scheduler.mode_requires_synchronization  s    4rn   c                    t        t                  t               g dfd|D ]  }|j                         D ]  }||<   	  |D ]
  } |        S )z?
        Ensure nodes is in topologically sorted order
        c                    | vrdj                  |        t        | j                  d       D ]&  }|j                  vr |j                            ( j	                  |        y y )Nc                    | j                   S rw   r  )ds    rl   rv  zDScheduler.topological_sort_schedule.<locals>.visit.<locals>.<lambda>/  s    affrn   r$  )r  r)  rq  r   r   )r  r   ru  r-  seenvisits     rl   rJ  z2Scheduler.topological_sort_schedule.<locals>.visit,  sa    }!!"6"6<LMCxx|3 ,sxx01	 N
 a  rn   )r  r_   r   rU  )r   r_   r  r  )rk   r  r   r   ru  r-  rI  rJ  s       @@@@rl   r{  z#Scheduler.topological_sort_schedule"  sj     +,.59V*,	! 	! D--/%)T" 0  D$K rn   c                   | j                   D cg c])  }t        |j                  t        j                        s(|+ }}t        dt        |            D ]o  }t        t        ||   j                                     }t        t        ||dz
     j                                     }||   j                  t        ||d             q y c c}w )Nr   Tr  )r  r   r   r+   Conditionalr  r   r  r  r  r  r6   )rk   r  conditional_nodesr  r  prev_bufs         rl   r  z'Scheduler._enforce_conditional_ordering=  s    zz
!!Z%GAz 	 
 q#/01A%6q%9%J%J%L MNLD!21q5!9!J!J!LMNHa --|TJ 2
s
   )CCc                <    t               }t        |t        t        t        t
        t        f      r-|j                  D ]  }|j                  |j                          nt        dt        |       d       fd|D        }t        t         fd|D                    S )Nz+get_unmet_dep_nodes is not implemented for .c              3  X   K   | ]!  }j                   |   j                          # y wrw   )r@  r  r  s     rl   r   z1Scheduler._get_unmet_dep_nodes.<locals>.<genexpr>Z  s&     XZc))#.??AZs   '*c              3  <   K   | ]  }j                   |     y wrw   r  )r   r  rk   s     rl   r   z1Scheduler._get_unmet_dep_nodes.<locals>.<genexpr>[  s     Q=at66q9=   )r   r   r   r  rA  r   r  rq  r  r   RuntimeErrorr   r   )rk   r  
unmet_depsr   unmet_dep_opss   `    rl   _get_unmet_dep_nodeszScheduler._get_unmet_dep_nodesH  s    &0l
)&"$	
 //sxx( 0 =d5k]!L  YZXJQ=QQRRrn   c                z   g }t         j                  | j                  d      }i }| j                  D ]P  }| j                  |      }t	        |      ||<   |D ]*  }|j                  |g       }|j                  |       |||<   , R |j                         D 	cg c]  \  }}	|	dk(  s| }
}}	|
rx|j                  |
       |
D ]7  }|j                  |g       D ]  }||xx   dz  cc<    |j                  |       9 |j                         D 	cg c]  \  }}	|	dk(  s| }
}}	|
rx|rJ d       |S c c}	}w c c}	}w )zU
        Sort nodes by their topological order, return a list of node lists.
        r   r   zTopological sort failed!)	r  fromkeysr  rX  r   r  r   r  r  )rk   r  r  childrenr   r  r   cr  r  zero_deg_nodesr.  s               rl   r  z!Scheduler._topological_sort_nodes]  s4    djj!,#%JJD,,T2Dd)E$KLLb) !   ).@1a!@LL(#$LLB/D$K1$K 0		! $ -2KKMDMDAqQ!VaMND  444y A Es   D1%D1D7D7c                j   i }| j                   D ]w  }t               }|j                  D ]B  }| j                  |j                     j                         }|j                  |       |||   z  }D |||j                         <   ||_        y t        | j                         D ]  \  }}||_
        ||_         y)z.
        Populate each node.ancestors
        N)r  r   rq  r@  r   r  r  r  r   r  rc  rd  )rk   name_to_ancestorsr   r   r   dep_node_namer  s          rl   r}  zScheduler.compute_ancestorsw  s    
 9;JJD)3I.. $ 0 0 : K K Mm,.}==	 / 2;dmmo.&DN  %TZZ0KE4"DN"DN 1rn   c                   i }i }| j                   D ]  }|j                  sd}d}n|j                  D cg c]/  }|| j                  |j                     j	                            dz   1 }}|j                  D cg c]/  }|| j                  |j                     j	                            dz   1 }}t        |      }t        |      }|||j                         <   |||j                         <   ||_        ||_	         yc c}w c c}w )z
        Populate each node's min/max_input_distance with the depth from graph
        inputs, measured as dependency hops before fusion. Nodes whose
        dependencies are all satisfied by graph inputs/constants have depth 0.
        r   r   N)
r  rq  r@  r   r  r  r  r  ra  rb  )	rk   name_to_min_distancename_to_max_distancer   min_distmax_distr   dep_min_distsdep_max_distss	            rl   r~  z!Scheduler.compute_input_distances  s!    02/1JJD**
  $66!  7 ))9)9#(()C)T)T)VW6  !  $66!  7 ))9)9#(()C)T)T)VW6  !
 }-}-4< 14< 1&.D#&.D#) 
!
!s   4C:74C?c                H   t         j                  sy | j                  D ]  }t        |t        t
        f      r#|j                         st         j                  dk7  r=|j                         D ]3  }t        |t              r|j                         r$|j                          5  y )Nhalide)r(   re  r  r   r   r   rU   cpu_backendr   r   r  )rk   r   r  s      rl   r  zScheduler.merge_loops  s|    00JJD d]4F$GHKKMf&8&8H&D)!%75;L;L;N!!# * rn   c                   t        ddd      5  t        d      D ]  }t        |      }t        j	                  d|dz   |       | j                  |d      }t        |      }t        j	                  d	|dz   ||       ||k(  s|dk(  slt        j	                  d
|dz           n t        j                  st        j                  r| j                  |d      }|cddd       S # 1 sw Y   yxY w)zB
        Combine eligible nodes into FusedSchedulerNodes.
        zScheduler.fused_nodesTrU  r	  z/===== attempting fusion (%d/10): %d nodes =====r   F)is_reorder_roundz=completed fusion round (%d/10): fused %d nodes into %d nodes
z+===== fusion complete (%d iterations) =====N)	r   r  r   r  r  fuse_nodes_oncer(   re  loop_index_inversion_in_fusion)rk   r  r  old_lennew_lens        rl   r  zScheduler.fuse_nodes  s     #4QU
 2Ye*  EE
 ,,UU,Ke*  TE	 g%A$$Eq1u ' , 1188,,UT,J;
 
 
s   A7C!AC!!C*c                    g }| j                   D ]4  }|j                  t        |t              r|j	                         n|g       6 || _         y)zA
        Unpack GroupedSchedulerNode into regular nodes.
        N)r  r  r   r  r  )rk   r8  r   s      rl   r  zScheduler.process_grouped_nodes  sE     .0	JJD!+D2F!GdV  
rn   c                    t        |      dkD  sJ |d   j                         }|| _        | j                  |      }t	        ddd      5  |j                  |      cddd       S # 1 sw Y   yxY w)
        Benchmark fused list of nodes and return the execution time
        in milliseconds on randomly generated inputs.
        r   benchmark_fused_nodesTcompile_time_autotune_time_us)rV  dynamo_compile_column_usN)r   r   r  rc  r   rt  )rk   r  r  rQ  s       rl   rt  zScheduler.benchmark_fused_nodes  so     5zA~~q$$&$""6*#"&%D

 007
 
 
s   
A%%A.c                    t        |      dkD  sJ |d   j                         }|| _        | j                  |      }t	        d      5  |j                  |||      cddd       S # 1 sw Y   yxY w)rs  r   generate_kernel_code_from_nodeshint_overrideN)r   r   r  rc  r   rx  )rk   r  benchmark_kernelrz  r  rQ  s         rl   rx  z)Scheduler.generate_kernel_code_from_nodes  sn     5zA~~q$$&$""6*;<::'} ;  =<<s   A%%A.c                    || _         | j                  |      }t        d      5  |j                  |      cddd       S # 1 sw Y   yxY w)rs  benchmark_codegened_moduleN)r  rc  r   r}  )rk   moduler  rQ  s       rl   r}  z$Scheduler.benchmark_codegened_module  s?     %""6*6755f= 877s	   ?Ac                   t         j                  j                  }|syt        j	                  d||       |j
                  D ]  }|j                         }t        |dd      r||vst        |t        j                        r?|j                  }||   }t        |t        j                        r'|j                  |j                         |j                  }t        |t        j                        s||k7  st        j!                  d|||        y y)z
        Check if selecting a Triton template would cause layout conflicts.
        Returns True if there's a conflict and we should fall back to ATen.
        FzNode %s has constraints %sr'  NzOLayout conflict detected for %s: template expects %s but layout is frozen to %sT)rZ   r   buffer_layout_constraintsr  r  r  r  r  r   r+   ReinterpretViewr'  FlexibleLayout freeze_layout_with_exact_stridesr+  FixedLayoutr  )rk   
multi_nodeconstraintsinpinp_namer'  expected_layouts          rl   !_has_layout_conflict_for_templatez+Scheduler._has_layout_conflict_for_template"  s     gg77		.
KH$$C||~H C40;.c2#5#56ZZF)(3O&""3"34 44_5K5KL&"..1o6Oe#	 7 %: rn   c           
        t        | j                        D ]&  \  }}t        |t              st        |j                  t
        j                        s=|j                  }t        j                  j                  s|j                         \  }}n t        d |j                         D              }t        |t        j                  j
                  j                        r| j!                  |      r||j                         D ]4  }t        |t        j                  j"                  j$                        s2|} n t        t        j                  j"                  j$                        sJ d       t        |t        j                  j
                  j                        rt        j&                  ri }||d<   t        j&                  D ]k  }|j                  |      }	|	j)                         D 
ci c]  \  }
}t        |
t              r|
| }}
}t+        |j)                         d       d   }|||<   m |j                  j-                  |       n|j                  j/                  |       Nt
        j0                  j3                  |j4                        5  |j7                         }ddd       j8                  }t        |t
        j:                        sJ |j8                  }t        |t
        j<                        sJ |j>                  rtA        ||j>                         |jB                  |_!        | jE                  ||||       ) yc c}}
w # 1 sw Y   xY w)a  
        Finalize a backing choice for MultiTemplateBuffers which did not already have a
        choice finalized through fusion. In the case of an extern choice, this will result
        in replacing the SchedulerNode.

        If a MultiTemplateBuffer did not have any fusion opportunities, finalizing a choice
        will force completion of compilation and benchmarking.
        c              3  |   K   | ]4  }t        |t        j                  j                  j                        r| 6 y wrw   )r   r  r  r  ExternKernelCaller)r   timings     rl   r   z<Scheduler.finalize_multi_template_buffers.<locals>.<genexpr>`  s6      *E) & % @ @ S S  #*Er  zZNo extern kernel detected to fallback to when layout constraints fail for Triton templatesNry  c                    | d   S r[  r~   r  s    rl   rv  z;Scheduler.finalize_multi_template_buffers.<locals>.<lambda>  s	    qQRtrn   r$  r   )#r  r  r   r   r   r+   MultiTemplateBufferr(   r  %force_extern_kernel_in_multi_templateget_min_choicer  choice_timingsr  r  r   r  r  r  multi_kernel_hintsr  r  finalize_as_triton_callersfinalize_as_triton_callerr  current_originsr_  output_noder   
StorageBoxOperationBufferorigin_noder:   r'  _replace_node)rk   r  r   r  min_node_unfusedr  choicecallershinttimingsr  r  triton_timingsout_tensorboxout_storage
out_buffers                   rl   r  z)Scheduler.finalize_multi_template_buffersM  s    !,GAt$.:		2114 "YY
**PP*4*C*C*E'$a'+*4*C*C*E	($ $OO&&??
 ==jI&0&?&?&AF) & % @ @ S S  4: 0 % 'B  *"EOO$D$D$W$W   y   $OO&&??
 00NP(8 %+$=$=D&0&?&?d&?&SG -4MMO.,;DAq#-a1I#J !"1,; + .
 &))=)=)?^%TUV%WF,2GDM %> 		<<WE		;;<LMYY..z/A/AB$4$@$@$BM C+00!+r}}===(--
!*b.@.@AAA))&}j6L6LM$.$5$5
!"":z1dCY -h. CBs   %M
MM	c                   t        ||       | j                  |      }|| j                  |<   || j                  |j	                         <   || j
                  |j	                         <   i t        j                  |j                  j                  |j                        D ]:  }| j                  j                  |j                  d       x}s,|j                  |<   < dfd} ||j                        |_
         ||j                  j                        |j                  _	        t        |j                         |j                               D ]3  \  }	}
|	| j                   |
j	                         <   |
j"                  |	_        5 |j$                  |_        |j&                  |_        |j(                  |_        |j*                  |_        y )Nc                ,    t        fd| D              S )Nc              3  @   K   | ]  }|j                          y wrw   )r  )r   r   rg  s     rl   r   z?Scheduler._replace_node.<locals>.rename_deps.<locals>.<genexpr>  s     Kdscjj)9:dr1  r   )r  rg  s    rl   rename_depsz,Scheduler._replace_node.<locals>.rename_deps  s    KdKKKrn   )r  rp  r   rp  )r  rr  r  ru  r  r  r  r  r   r   rq  r  r  r   r  rz  r@  r  rc  rd  r   r`  )rk   r  r  r  r   new_scheduler_noder   	real_namer  new_outold_outrg  s              @rl   r  zScheduler._replace_node  s    	"*j9!77
C*

1-?$--/*3E0 ??4#3#3#9#94;R;RSC 3377$GGyG.1hh + T	L 1<111
- 0;**000
&&, !$**,d.>.>.@!
GW 4;DW--/0#MMGM	!
 (,~~$'+~~$'+~~$(,%rn   c                &    t        d |D              S )Nc              3     K   | ]q  }t        |j                  d       xrU |j                  duxrE t        |j                  j                  d      xr# |j                  j                  j                  dk(   s yw)r   Nscatter_moder  )r<  r   r   r  r  s     rl   r   z,Scheduler._any_atomic_add.<locals>.<genexpr>  sq      

 	 AFFF# 9d"9^49 ((L89 s   A7A9)r   )rk   	node_lists     rl   _any_atomic_addzScheduler._any_atomic_add  s     

 
 
 	
rn   c                "   | j                  |d|      }t        j                  |      }t        j                  j
                  j                         }|j                         sd }||fS |j                  d|      }t        |t              sJ ||fS )NT)r{  rz  triton_)kernel_namesource_code)rx  r   loadr  r  async_compileAsyncCompileuse_process_poolr   r   r   )rk   r  rz  src_codemodr  futs          rl   compile_kernelzScheduler.compile_kernel  s     77D 8 
 x(55BBD--/C
 Sz  &&9(&SCc<000Szrn   c                d    !"#$%&'()*+ t        d fD              }t        j                  s|st        j	                  d      S j                         r(t        j                         t        j                        r j                         sj                         rt        j	                  d      S j                         }|d   j                         sJ j                  dk(  r(t        j                  dk7  rt        j	                  d      S j                         }t        t!        j"                  ||            } j%                  |      rt        j	                  d      S ddlm t+              +|d   j                         J dfd%|rt        d	 fD              r
j                         durj                         nj                         *t        *t        j,                        sJ  j/                  *      rt        j	                  d
      S i $g "t        j0                  D ]A  }*j3                  |      t5        j7                         d       D ]~  \  }}	t        |t8        j:                  j<                  j>                        s5*jA                  |      5  "jC                  |g jE                  ||jF                               ddd        tI        d      }
d}i }"D ]V  \  }}}	 ||jK                          *jA                  |      5   jY                  |      \  }}|||<   ||
k  r|}
|}ddd       X |*jZ                  |<   t        |t\              sJ |$|<   D t        j^                  ta        d *jb                  D              }te               xr  xr |t        jf                  k  #tI        d      tI        d      c'(d&#sR*j3                         *ji                         \  &'t5        j7                         tk        jl                  d            }n*jb                  D cg c]  }|df }}r(r jo                  |      n jo                  |      \  (}n4st        j	                  d
      S jq                         (ts        (      )ddl:m;} g "d}|D ]  \  }}t        |t\              ss&ty        |d      r|jz                  *jz                  k7  r?r
|'(z   k\  r n\|dz  }|t        jf                  kD  r nB*jA                  |      5  	 "jC                  |g jE                  |             	 ddd        t}        "      dk(  rt        j	                  d
      S d"#$%&'()* fd}t        j                  |"d   d         S  jE                  |       jE                  |      ! jE                  |       d !% +fd}t        j                  | d         S # 1 sw Y   xY w# tL        $ rI}tN        jQ                  tR        jT                        rtN        jW                  dsdnd|       Y d}~qd}~ww xY w# 1 sw Y   xY wc c}w # |$ r Y ddd       w xY w# 1 sw Y   xY w)
        If config.benchmark_fusion is False, always return True.
        Otherwise, return True if fusion can brings speedup.
        c              3     K   | ]>  }|j                         xr( t        |j                         t        j                         @ y wrw   )r   r   r  r+   r  r  s     rl   r   z.Scheduler.speedup_by_fusion.<locals>.<genexpr>  sE       
 $ MMO J1..0"2H2HIJ#s   AATr   r  r   CompilationErrorNc           
     t   t         j                  t        j                        r| ||z   k  rFt         j	                  dj                         j                         t        ||z   | z  d             y t         j	                  dj                         j                         t        | ||z   z  d             y y )Nz9can fuse (benchmark): fusing %s with %s cause %sx speedup.3fz=cannot fuse (benchmark): fusing %s with %s cause %sx slowdown)r  r  r  DEBUGr  r  rE   rF   )ms_fusedr  r  r   r   s      rl   
log_fusionz/Scheduler.speedup_by_fusion.<locals>.log_fusion  s    &&w}}5cCi'$$S..0..0"sSyH&<S%AC	 $$W..0..0 Hc	$:3#?A	 6rn   c              3  @   K   | ]  }|j                         d u  y wrw   r  r  s     rl   r   z.Scheduler.speedup_by_fusion.<locals>.<genexpr>)  s"      %
7E!A!-~   Fc                    | d   S r[  r~   r  s    rl   rv  z-Scheduler.speedup_by_fusion.<locals>.<lambda>=  s	    aPQdrn   r$  ry  infException in compiling %s: %sr  r  c              3  <   K   | ]  }t        |t                y wrw   )r   r   )r   r\  s     rl   r   z.Scheduler.speedup_by_fusion.<locals>.<genexpr>h  s      %ASA
167ASr  r   )	CantSplitallowed_prologue_inpsc                    t        d      } d }i }rhrt        t        j                        sJ j	                         j                         \  D cg c]  }|d   v r| c}t        fd      D ]0  \  }}}	 ||j                         }n!s|j                  }|j                          nd }r>j!                  |      5  j#                  |      \  }	}
|	||<   |	| k  r|	} |}d d d        }|k(  xs z   |   z   kD  }|s|s|j                          |j$                  r|j&                  sJ |j$                  d   }|j&                  }|j(                  }t+        |j&                  |||j,                  j.                  t1        j2                              }|s/|} n r
 |        r| z   k  rL|Jt4        j6                  r|d <   j9                         nj;                  |       r|j<                  d <   yy	c c}w # t        $ rI}t        j                  t        j                        rt        j                  dsdnd|       Y d }~d }~ww xY w# 1 sw Y   xY w)
Nr  r   c                    | d      S r   r~   )rJ  r  s    rl   rv  zKScheduler.speedup_by_fusion.<locals>.benchmark_when_ready.<locals>.<lambda>  s    nQqT&:rn   r$  r  r  r  TF)r  r   r+   r  r  r  r)  r-  r  
precompiler  r  r  r  r  r  swap_as_triton_callerr}  	launchersn_regsn_spillsr  bmreqr  rC   r  r(   r  r  r  _choice_timings)min_ms_fusedms_fused_choicenew_timings
fut_choicer  rh   	mod_fusedresr  r  pathfusible_choicecompiled_kernelr  r  should_fuse_epiloguebench_epiloguer  r  r:  future_choicesget_choice_timings_async hint_override_best_fusion_choicer  
min_choicer  r  	ms2_fusedr  rk   s                   rl   benchmark_when_readyz9Scheduler.speedup_by_fusion.<locals>.benchmark_when_ready  s   $U|"& +%*ZAWAW*XXX%/%>%>%@N&0&?&?&AOJ
 +9&*8J%a=N: #*8&N &,&:&N
 2@-FFI!!-"(--/C!/"+"3"3CNN,"&C &'==fE-1-L-L ) &.NHd
 3;K/',6/728 FE '&0 N"Sy>&+AI+MM '
 >"--/#&==V]]B#B.1mmA.>O+:+A+AL-<-E-EN3A # # & , . & 6 6 0 7 7 ?40  428 %y 2@| "|S#6 ',#)*D%100AP8>"==<
 #<<_M%;F
2248 }&. % !%227==A&,, ?2A
z !
 !! FEs*   H4H$I.	I+">I&&I+.I8	c                    ddl m}  	 d   d   d   fD ]  }||j                           j                  d   
      \  t	        j
                        r	 d       yj                  d   
      \  t	        j
                        r	 d       yj                  d   
      \  t	        j
                        r	 d       y        t        d      rWz   k\  rOfj                  vr?j                  j                  f       t        d      j                  fd	       z   k  S # | $ r Y y	$ r}d
t        |      v rY d }~y d }~ww xY w)Nr   )NoTritonConfigsErrorr   z%register spilling of the first kernelFz&register spilling of the second kernelz%register spilling of the fused kernelslow_fusionc            	     $      z   z  dS )N)kernel1_pathkernel1_latencykernel2_pathkernel2_latencyfused_kernel_pathfused_kernel_latencyslow_down_ratior~   )r  r  r  path1path2
path_fuseds   rl   rv  zKScheduler.speedup_by_fusion.<locals>.benchmark_when_ready.<locals>.<lambda>`  s&    053605365?8@3;sSy3I%rn   Loop-carried variableT))torch._inductor.runtime.triton_heuristicsr  r-  r}  rB  isinfr    r  r  r   r  r  )r  r  r  r  r  r  r  r  r  r  r  future_and_mod_l1future_and_mod_l1_fusedfuture_and_mod_l2r  rk   r  s      @@@@@@rl   r  z9Scheduler.speedup_by_fusion.<locals>.benchmark_when_ready-  s   A *!,)!,/2 
 ?JJL  "&!@!@)!,"JC
 zz#CD$!%!@!@)!,"JC
 zz#DE$+/+J+J/2,(Hj
 zz(+CD$xc2 0>$c	1"EN$2I2II//33UENC(7?? 
 $cCi//+ ! ' .#a&8#s<   E AE +5E !5E A3E E.E.E)(E))E.rt   )r  r  r  r  r  r  r   rU  rV  )@r   r(   benchmark_fusionrd   rr   r   r   r  r+   TritonTemplateBufferr$  r   r   r   rj  r   r  r  r  triton.compiler.errorsr  r  r  r  r  r  r)  r  r  r  r  TritonTemplateCallerr  r   r  rz  r  r-  r  r  r  r  r  r  r}  r  r   benchmark_epilogue_fusionr   choicesr    max_epilogue_benchmarked_choicesr  operator
itemgetterrt  r  r  rc  r  r<  r  r   ru   ),rk   r   r   is_multi_templatenode_list_1node_list_2node_list_fusedrz  r  r  r  r  r  rh   r  r  r  r  num_triton_callerschoice_timings_iterr\  r  r  triton_choicesunfused_timer  r  r  r  r  r:  r  r  r  r  r  r  r  r  r  r  r  r  r  s,   ```                       @@@@@@@@@@@@@@@@@@rl   speedup_by_fusionzScheduler.speedup_by_fusion  s       
 U^ 
 

 &&/@$$T** u668":Q:QR!!  $$T**oo'Q**,v ;;%F$6$6($B$$T**oo'y{KHI
 0$$T**;u% #..0!!!	"  %
8=u~%
 "
 $557tCO # ''),,. 
 j"*@*@AAA55jA#((//  - QSN!'!:!:!+!:!:=!I!'(<(<(>N!SIFA% @ @ U U !#99&A&-- &!%!4!4$36CWCW "5 "" BA "T  %U|CG 1?-FFI
!!-"MMO $99&A)-)H)H%v*$ /7F+#l2+3L.4O BA 2@( =H
**=9!/3KLLLBQ0?U ";X $==N!$ %AKASAS% "
 )* R&&R&&*Q*QQ % U|U5\HC15J+!+!:!:!<",";";"=
C&,"((*0C0CA0F'# 8B7I7I&J7I!1v7I#&J ' ..{;33K@ U '',,U33224<UE3O	 ?PRNN(;$!&*BC ((?@44
8X8XX!lcCi&?!#!F$K$KK55f=!&--#Kd&9&9/&JK >=/ )<B >"a'#((//j! j! j!X  --$nQ&7&:  !% 3 3K @ $ 3 3K @&*&9&9/&J#F FP  --09PQR9S .  g	 BA" % !%227==A&,, ?2A
z !
 !! BAF 'Kb % ! ! >=
! >=s`   :1XX*1$Y?Z Z%$ZX'*	Y<3>Y77Y<?Z	Z"Z%!Z""Z%%Z/	c                <    | j                   |j                            S )z0Look up the node in Scheduler name_to_fused_node)r  r  r%  s     rl   r2  zScheduler.get_fused_nodey  s    &&t':':'<==rn   c                L   t         j                  d|j                         |j                                |j                         }|j                         |k(  sJ | j	                  |      j                  ||      }|j                  |       |j                  |       |j                  |       | j                  j                  |j                         D ci c]  }|j                         | c}       | j                  j                  |      }||| j                  |<   |S c c}w )Nzfusing %s with %s)r  r  r  r   rc  rr   r\  r  r  r  r   r  r  )rk   r   r   r  r  node3r  stream1s           rl   fuse_two_nodeszScheduler.fuse_two_nodes}  s     	,enn.>@PQ!!#!V+++  (--eU;5!5!&&U__EV'WEV

e(;EV'WX %%))%0)0D& (Xs   D!c                    | j                  ||      r-| j                  ||      s |       r| j                  |||       yyNTF)r   will_fusion_create_cycler  )rk   r   r   
speedup_fnr  s        rl   fuse_if_speedupzScheduler.fuse_if_speedup  s?     MM%'11%?uk:rn   c                   |rg }i }t               }|D ]  }||v rt        ||         dk\  sJ ||   j                  d      }t        ||         dk(  r|j                  |       |j	                         \  }}	|	|k(  rt        ||	      sJ |}
n||k(  sJ t        ||	      sJ |	}
| j                  |
      |
ur|j                  r3|j                  j                  }|J |j                  |       ||f||<   | j                  ||	|j                  |      s|j                  |        t        |      D ]l  }||   \  }}| j                  | j                  |j                        | j                  |j                        |j                  |      s\|j                  |       n |D ]  }|j                  |        |ryy)z
        Evaluate pending template fusions for a set of fusion candidate nodes.
        The fusion candidate nodes are pointwise nodes as potential epilogue
        or prologue fusions
        r   r   N)r   r   r  r  r   rD  rG  r2  rh   r   r  rf   r   r   r   )rk   template_fusion_candidatesr  template_futuresfuture_to_pending_fusionfusions_to_remove	candidatepending_fusionr   r   r  fcands                rl   "_evaluate_pending_template_fusionsz,Scheduler._evaluate_pending_template_fusions  s    )-/  % @J|7	!;;6yABaGH "<I!F!J!J1!M1)<=B%)))4->>@uI%-eU;;;$)M I----eU;;;$)M &&}5]J!((&--44A=(=$++A.3A92M,Q/ ++un&@&@+ *--i8K 8P ""23'?'B$''''(<(<=''(<(<="..	 &))$/ 4 '*..q1 'q )rn   c                    	 	 	 	 	 	 d fd}|D ]H  \  }} |||        j                  |      } j                  |      }t        ||      r||f j                  v rO j                  |||      sc j	                  ||      rv j                  ||      }	|	j                  t        |	j                  |||	j                        }
t        ||      rY||f j                  vsJ  j                  j                  ||f       t        ||      }||vrg ||<   ||   j                  |
       n
|
|<   |
|<   (|	j                  s6 j                  ||       K y )Nc                b   j                  |       v sj                  |      v rj                  j                  |       j                  j                  |                  }|J |j                         \  }}|j                  }j	                  |d        j	                  |d        j                  |      |u sJ j                  |      |u sJ  |       rj                  | |      rj                  ||       j                  |       v rj                  |      v ry y rw   )r2  r  r   rf   r  r  r  )	r   r   r!  	node_key1	node_key2
is_speedupr  pending_fusionsrk   s	         rl   resolve_pending_fusionsz<Scheduler._try_fusion_pairs.<locals>.resolve_pending_fusions  s1   
 ##E*o=&&u-@!0!4!4''.#''(;(;E(BC" &111'5'F'F'H$	9+77
##It4##It4**95BBB**95BBB!|t'D'DUE'R##Iy+F+ ##E*o=&&u-@rn   )rf   r   r   rh   r"  )r2  rI  ry  r   r  r  rf   r   rh   r  rK  r   re   r  )rk   possible_fusion_pairsr*  template_fusion_nodesr  rl  r+  r   r   
fusion_resr!  template_pw_nodes   ` ` `       rl   _try_fusion_pairszScheduler._try_fusion_pairs  s   	G$	G$	G 	G8 2LE5 $E51''.E''.E #5%0ENd&@&@@}}u.33E5A!33E5A
))5%2$.$:$:##)00	&N *%7 %u~T5O5OOOO2266u~F+B5%+P(+3HHFH12BC-.>?FF~V1?.1?.!--##E5+>W 2rn   c                @   t               }|j                         D ]  }|j                         \  }}|j                  }||v st	        ||      r3|j                  |       | j                  |      |u sJ | j                  |      |u sJ | j                  ||||        y rw   )r   r   r   rf   rI  r  r2  r  )rk   r  r*  seen_pair_speedup_fnr!  r'  r(  is_speedup_fns           rl   _finish_pending_fusionsz!Scheduler._finish_pending_fusions=  s    
 @J| .446N#1#B#B#D Iy*66M 448J99  $$]3&&y1Y>>>&&y1Y>>>  I}kR 7rn   c           
         t        |D cg c]  \  }}t        ||      s| c}}      }g }|D ]<  \  }}t        ||      r||v r|j                  ||f       *|j                  ||f       > |S c c}}w rw   )r   rD  rG  r   )rk   possible_fusionsdeferred_prologue_fusionsn1n2epilogue_template_nodesnew_possible_fusionss          rl   _handle_template_overlapz"Scheduler._handle_template_overlapU  s     #-.M.FB2DR2LR.M#
  "&FB!"b)b4K.K)00"b:$++RH5	 ' $# Ns
   A1
A1
c                   | j                  |       t        |      }t        j                  t        j
                        r@t        j                  d       |D ]&  }t        j                  d|j                                ( i }i }g }| j                  ||      }t        j                  st        j                  r| j                  ||      }| j                  |||||       | j                  ||       | j                  ||       |j!                          |r'| j                  |||||       | j                  ||       t#        |d       }| j%                  |      }|S )a  
        Combine eligible nodes into FusedSchedulerNodes.

        This relies on two key functions to control the logic:
            - self.can_fuse(): checks if a fusion is legal
            - self.score_fusion(): assigns priority to a given fusion
        zfuse_nodes_once, candidates:z  %sc                    | j                   S rw   r  r  s    rl   rv  z+Scheduler.fuse_nodes_once.<locals>.<lambda>  s    !++rn   r$  )r  r   r  r  r  r  r  r  get_possible_fusionsr(   r  r  r<  r0  r4  r$  clearr)  r{  )	rk   r  rl  r  r   r*  r-  r7  r6  s	            rl   rm  zScheduler.fuse_nodes_oncei  sd    	!!%( '""7==1;<#  )=)=)?@ $  	
 OQ  	"  44

 ##v':':#<< ";  	!	
 	$$[/B//0E{S##%$"")%  334I;W{(=>..u5rn   c                h   t        | j                        }d}t        | j                        }t        j	                  d|       t        t        j                  |             D ]P  \  }}t        j                  |      }t        |      dk  r+|||kD  r n| j                  |      st        j	                  d|       ]|dz  }t        j                  dkD  }t        |d   j                  |d|      }t        j                  d	t        |      |       |D ]  }	|j                  |	        |j                  |       | j                   j#                  |j%                         D 
ci c]  }
|
j'                         | c}
       | j(                  j+                  |d         }|B|| j(                  |<   S t-        |d
       | _        | j/                  | j                        | _        t        j                  d||t        | j                               | j1                  | j                         yc c}
w )z'
        Groups parallel nodes
        r   z2ComboKernels: Generating with num_ck_nodes = %s...r   Nz)ComboKernels: Not speeding up %d-th groupr   Tr  z0ComboKernels: Combining %d nodes for %d-th groupc                    | j                   S rw   r  r  s    rl   rv  z5Scheduler.create_combo_kernel_nodes.<locals>.<lambda>  s    q{{rn   r$  zDGenerated ComboKernel nodes: %d ComboKernels, totally %d -> %d nodes)r   r  r   r  r  r  ro  r  r  speedup_by_combo_kernelr(   r  r  r  r\  r  r  r  r   r  r  r  r)  r{  r  )rk   rX  r  rn  num_nodes_orignumr  r  r  r   r  streams               rl   r  z#Scheduler.create_combo_kernel_nodes  s    !,TZZ		FU'&DDTJ
NC 3CCINI9~!'EL,@//	:		EsKQJE$;;a?O4!&&*. /	K HHBI
 """4( "OOK(##**4?4I4I4KL4Kq{*4KL
 ((,,Yq\:F!39##K0E
F K-BC
33DJJ?
R

O		
 	!!$**- Ms   "H/
c                H    |D ]  }|j                  | j                          y rw   )r  r  )rk   r  r   s      rl   r  zScheduler.prune_redundant_deps  s     D%%d&=&=> rn   c                   
 g 
t        t        t        t        f             d
 fd}t        j                  t
              }|D ]=  } j                  |      r|j                         D ]  }||   j                  |        ? |j                         D ]
  } ||        t        j                  rat        j                  t
              }|D ]&  }t        |dd      }	|	s||	   j                  |       ( |j                         D ]
  } ||         j                  
      

j                   j                  d       t         j#                  dt%        
             
S )z^
        Helper to find all legal fusion opportunities, sorted by self.score_fusion()
        c                |   t        |       D ]  \  }}| |dz   |dz   t        j                  z    D ]  }||f}|v rj                  |       j	                  ||      rj                  |       B|j                         s|j                         scj	                  ||      swj                  ||f         y r[  )r  r(   )max_fusion_buffer_group_pairwise_attemptsr  r   r   r   r$  )	r  node1_indexr   r   r%  rl  r6  rI  rk   s	        rl   check_all_pairsz7Scheduler.get_possible_fusions.<locals>.check_all_pairs  s    &/&6"U"!Ok'FF'GE
 !%.Cd{ HHSM}}UE3CD(//4++-1A1A1Cu&6J )//?! '7rn   r   NT)r%  reversezfound %d possible fusionsr  r  r   rU  )r   r   r_   r  r   r   unfusable_noder   r   r   r(   aggressive_fusionr  *get_possible_fusions_with_highest_priorityr  score_fusion_keyr  r  r   )rk   r  rl  rL  buffer_names_groupingr   r   node_groupinggroup_groupingr   r6  rI  s   ` `       @@rl   r?  zScheduler.get_possible_fusions  sU    % 13D DEFH	@ 	@( !, 7 7 =D""4(--/%c*11$7 0 
 399;MM* < ##(44T:Ngt4"5)006  "0!6!6!8. "9  JJ
 	$"7"7F4c:J6KLrn   c                    t        t                  d fd|j                         j                  j	                         |j                         j                  j	                         z  |j
                  j                  j	                         |j
                  j                  j	                         z  z
  t         fdD              }|r t        ||      d       |S )z~
        Finds whether there's a path from node1 to node2 (or vice-versa)
        caused indirectly by other fusions.
        c                   t        | t              rq| vrmj                  |        | j                         j	                        ryt        | j                  z        xs" t        fd| j                  z
  D              S y)NFc              3  H   K   | ]  } j                   |           y wrw   rS  r   r  
found_pathrk   s     rl   r   zIScheduler.will_fusion_create_cycle.<locals>.found_path.<locals>.<genexpr>:  s*      H!DA #4#:#:1#=>!D   ")r   r   r  r   issubsetrv   r   r   )r   combined_ancestorscombined_namesrZ  rk   visiteds    rl   rZ  z6Scheduler.will_fusion_create_cycle.<locals>.found_path)  s    $ 23G8KD!++-667IJ !   ?@ C H!%2D!DH E  rn   c              3  H   K   | ]  } j                   |           y wrw   rS  rY  s     rl   r   z5Scheduler.will_fusion_create_cycle.<locals>.<genexpr>H  s$     WDVqJt66q9:DVr[  zwill create cycler	  )r   r   r   _dictr   r   r   r  )rk   r   r   cycler]  r^  rZ  r_  s   `   @@@@rl   r  z"Scheduler.will_fusion_create_cycle  s     /02	 	2 %%'--224'')//4467 	
 OO!!&&(5??+@+@+E+E+GG WDVWW#IeU#$78rn   c                    ddl m 	 	 	 	 d fd} ||      } ||      }t        fd|D              }t        fd|D              }|j                  |      }d}	|D ]  }
	 |	t	        |
d         z  }	  j                  ||      }t        j                  j                  j                  |	d	|z        ry
y# t
        $ r Y  yw xY w)a  
        Return true if fusing the two nodes can potentially increasing peak memory.

        The implementation is more like a heuristic since we don't really know if we are at peak
        or not when trying to fuse these two nodes. The order of nodes may change later which makes the
        peak memory estimation hard.

        Here is how we decide the LOWER BOUND of extra memory allocation if we fuse these 2 nodes:
        1. find all buffers read by each node with a single user. These buffers are supposed to
           be reused if we don't fuses these 2 nodes
        2. find the intersection of these buffers for the two node and sum the total buffer size.
           If we don't fuse these two nodes, we can at lease avoid this much memory allocation.
           Note that the extra memory allocation is not necessarily causing peak memory increase.
           This is just a heuristic.

        We return true only if the saving for fusion can not trade off the extra memory allocation.
        r   )buffer_reuse_keyc                0   g }| j                   j                  D ]y  }j                  j                  |j                        }|s+t        |j                        dk(  sD|j                  j                         s_|j                  |j                         { |S r[  )
r   r   r@  r  r   r   r  r   has_tensor_outputr   )r   r{  rx  r   rk   s       rl   _find_single_user_inputszKScheduler.can_fusion_increase_peak_memory.<locals>._find_single_user_inputsd  sr     F&&,,&&**27733syy>Q.3883M3M3OMM#((+ - Mrn   c              3  .   K   | ]  } |        y wrw   r~   r   r   rd  s     rl   r   z<Scheduler.can_fusion_increase_peak_memory.<locals>.<genexpr>r       #S]c$4S$9]r>  c              3  .   K   | ]  } |        y wrw   r~   ri  s     rl   r   z<Scheduler.can_fusion_increase_peak_memory.<locals>.<genexpr>s  rj  r>  r   r   Fr  T)r   r_   r   zlist[ir.Buffer])r7  rd  r   intersectionr  r  rI  rZ   r   r   statically_known_gt)rk   r   r   rg  lhs_dep_nodesrhs_dep_nodeslhs_reuse_keysrhs_reuse_keyscommon_reuse_keysmemory_overheadr%  	bw_savingrd  s   `           @rl   can_fusion_increase_peak_memoryz)Scheduler.can_fusion_increase_peak_memoryM  s    * 	6	#		 1707##S]#SS##S]#SS*77G$C3s1v;. % ,,UE:	 77//iP  s   $B88	CCc                   t        |j                         D cg c]  }|j                          c}|j                         D cg c]  }|j                          c}z         }t        d |j                  j                  D              }t        d |j                  j
                  D              }||z  }t               }	|j                  j                  D ]:  }
| j                  |
j                  |      s |	j                  |
j                         < t        d |j                  j
                  D              t        d |j                  j
                  D              z  }t        d |j                  j                  D              t        d |j                  j                  D              z  }||z
  }||	z
  }||z  }t        |      |kD  S c c}w c c}w )Nc              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zEScheduler.fusion_prevent_too_many_reads_and_writes.<locals>.<genexpr>  s     &T;SCsxx;Sr  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zEScheduler.fusion_prevent_too_many_reads_and_writes.<locals>.<genexpr>       %R:Q3chh:Qr  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zEScheduler.fusion_prevent_too_many_reads_and_writes.<locals>.<genexpr>  s      $
 7CHH 7r  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zEScheduler.fusion_prevent_too_many_reads_and_writes.<locals>.<genexpr>  ry  r  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zEScheduler.fusion_prevent_too_many_reads_and_writes.<locals>.<genexpr>  s      %
 8CHH 8r  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zEScheduler.fusion_prevent_too_many_reads_and_writes.<locals>.<genexpr>  s     D+CCsxx+Cr  )
r   r   r  r   r  r   $can_buffer_be_removed_through_fusionr   r  r   )rk   r   r   	thresholdr   fused_node_namesnode1_write_namesnode2_read_namesreads_removed_through_fusionwrites_removed_through_fusionr  all_read_namesall_write_namesunique_readsunique_writesunique_io_bufferss                   rl   (fusion_prevent_too_many_reads_and_writesz2Scheduler.fusion_prevent_too_many_reads_and_writes  s    &).):;):T]]_):;+0??+<=+<4t}}+<=>
 '&T5;L;L;S;S&TT%%R%:K:K:Q:Q%RR'7:K'K$ :D%**11I88 0 .11)..A	 2 $ $
 % 1 1 7 7$
 
C5+<+<+B+BCCD
 % %
 % 1 1 8 8%
 
D5+<+<+C+CDDE
 &(DD (*GG )=8$%	11M <=s   GG
c                    t        t        |j                  |j                  z
        t        |j                  |j                  z
              }|dkD  S )aA  
        This function prevents fusion for nodes that can increase memory
        footprint. This problem is more common in horizontal fusion, where nodes
        that are far apart in the original order get fused, lengthening the live
        intervals of tensors. This is very evident in models with activation
        checkpointing, where the recomputed nodes from different checkpointed
        regions get fused and significantly increase the memory footprint.

        The current attempt is a quick, possibly hacky, heuristic to prevent the
        fusion of nodes that are far away in the original order.

        A better but difficult to implement heuristic would be to use live
        intervals of the buffers, find region of peak pressure in the original
        program and prevent fusion that crosses that peak region. We might need
        special care or good approximation in this implementation, as fusion of
        node changes live intervals, and re-computing live intervals and peak
        memory after each fusion can introduce large compilation overhead.
        @   )r  r  rc  rd  )rk   r   r   proximity_scores       rl   are_long_distant_nodesz Scheduler.are_long_distant_nodes  sE    * %//12%//12
 ##rn   c                   i }|j                   j                         D ci c]  }|j                  | }}|j                   j                         D ci c]  }|j                  | }}|D ]}  }t        j                  j                  |      }	||   }
||   }t        |
t              rt        |t              sdt        |
       dt        |       ||<   k|
j                         |j                         k7  r(d|
j                          d|j                          ||<   t        |
j                        t        |j                        k7  rd||<   |
j                         }|j                         }||k7  rd| d| ||<   |
j                         |j                         k(  rd|
 d| ||<   Ed}t        |	t        j                        sd|	j                    }d	|
 d| d
| ||<    t#        |      S c c}w c c}w )z}
        Try to decide reasons why fusion fail due to no shared memory even though
        there are common buffers.
        znot MemoryDep: r   zdifferent numel: 	broadcastzdifferent offset: zMismatch loop orders: r  zLayout: zUnknown reason: z. )r   r  r   rZ   r   r  r   r4   r   r   rY   r   
get_offsetnormalize_with_stride_orderr+   r  r'  r  )rk   r   r   common_buf_namesreasonsr   node1_name2depnode2_name2depr  r   lhs_deprhs_deplhs_offrhs_off
layout_strs                  rl   decide_fusion_fail_reasonz#Scheduler.decide_fusion_fail_reason  s    383D3D3U3U3WX3WC#((C-3WX383D3D3U3U3WX3WC#((C-3WX(H''$$X.C$X.G$X.Ggy1GY9W%d7m_F4=/J !   "g&7&7&99'(9(9(;'<F7CTCTCVBWX !  W\\*mGLL.II$/!((*G((*G'! '9	y$Q! 3356689 '=WIVG9$U! Jc2#5#56'

|4
"7)6'"ZLI HU )\ 7|c YXs   G5G:c                   t         j                  syt        d ||fD              ry|j                  j	                         }|j                  j	                         }||z  }|syt        d |j                  D              }||z
  ryt        |      dkD  ryt        |j                  j                        dkD  s"t        |j                  j                        dkD  ryt        t        |j                  j                              }t        t        |j                  j                              }t        |t              rt        |t              sy|j                  j                  D 	ci c]  }	|	j                  |	 }
}	|j                  |
vry|
|j                     }t        |t              sy|j                         }|j                   |j                   k7  r|j"                  |j"                  k7  ry|j"                  |j"                  k7  st        |j$                        dk7  ryt        |j&                  j(                        dk7  ry|j&                  j*                  ryd|j&                  j(                  v rd|j&                  j(                  v sJ t        d |j&                  j-                         D              }t        |      dk7  ryt        t        |            }||j&                  j(                  d   k(  rd}d}n"||j&                  j(                  d   k(  sJ d}d}d	d
lm} |j&                  j2                  d	   }t        |      dk7  ryg }t4        j6                  j9                  |      D ]:  }|j;                  t<        j>                  j@                  jC                  |             < tE        |      } |||d	         }|y|j&                  j(                  |   |j&                  j(                  |<   ||j&                  j(                  |<   |jG                  dd       | jI                  ||      }t        |tJ              sJ tL        jO                  d|       |S c c}	w )aW  
        Attempts to enable fusion between two nodes by inverting indexing patterns.

        This optimization targets cases where node1 has a contiguous write and
        node2 has a contiguous write but discontiguous read. By inverting the
        indexing in node2's read and write operations, we can make them compatible
        with node1 for potential fusion.

        Args:
            node1: First scheduler node (source)
            node2: Second scheduler node (target for inversion)

        Returns:
            int: Fusion score if successful, 0 if optimization not applicable
        r   c              3  <   K   | ]  }|j                           y wrw   r  r  s     rl   r   zAScheduler.shared_data_after_inverting_indexing.<locals>.<genexpr>%  s     2>aqxxz>r  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zAScheduler.shared_data_after_inverting_indexing.<locals>.<genexpr>1  s      .
 8CHH 8r  r   r   index0index1c              3      K   | ]  }|  y wrw   r~   )r   r  s     rl   r   zAScheduler.shared_data_after_inverting_indexing.<locals>.<genexpr>l  s     %T7Std7Ss   r   )generate_inverse_formulaTFz!Shared memory after inversion: %d)(r(   rn  r   r   buffer_namesr   rq  r   r   r  r  r  r   r4   r   r`  r   r   	var_namesr   r   	subblocksget_read_exprs$torch._inductor.invert_expr_analysisr  varsr   Add	make_argsr   rZ   r   r   combine_modular_indexing_pairsr   rz  rI  r  r  r  )rk   r   r   node1_buffer_namesnode2_buffer_namescommon_buffer_namesnode2_unmet_dependencies
node2_readnode2_writer   node1_writesnode1_writenode2_read_exprs	read_exprread_expr_indexwrite_expr_indexr  r  simplified_termstermsimplified_read_exprinverse_formulascores                          rl   $shared_data_after_inverting_indexingz.Scheduler.shared_data_after_inverting_indexing  s   & 442E5>22 #..;;="..;;=03EE" $. .
 % 8 8.
 $
  $&88'(1, u  &&'!+s53D3D3K3K/Lq/P$u006678
4 1 1 8 89:*i0
9
 161B1B1I1IJ1I##1IJ??,.":??3+y1 "++- !2!22  K$4$44??k...#j6J6J2Kq2P u{{))*a/ ;;   222EKK666	
7
 &%Tu{{7Q7Q7S%TT A%./0	 228<<&O' : :8 DDDD&O'Q[[%%a(
z?aII''	2D##  ??E 3  ##3423GTUW "
 7<kk6P6P7
""?3 8G""#34 	""4/((6%%%%;UCm Ks   "Qc                t   t         j                  rt        d ||fD              ry|j                         s|j                         ry|j                  j                         }|j                  j                         }||z  }|sy|j                  j                         D ci c]  }|j                  | }}|j                  j                         D ci c]  }|j                  | }}g }	|D ]y  }
||
   }||
   }|j                         |j                         k(  s/|	j                  t        j                  j                  j                  |j                         d      ||f       { t        |	      dk(  ryt!        |	t#        j$                  d            \  }}}t'        |t(              rt'        |t(              sy|j*                  |j*                  k7  r3|j-                         |j-                         k(  r| j/                  |      S yd}|j1                         s|j3                  ||      }nV|j1                         s|j3                  ||      }n3t4        j7                  d|j9                         |j9                                |r*t;        j<                  t>        | jA                  ||            S dS c c}w c c}w )a  
        Right now just greedily reorder the loop of node1 to be compatible with node2,
        but ideally we should have some heuristics to reorder the loop for node2
        to be compatible with node1 if that's more efficient.

        Return the amount of shared data re-computed in this method.
        If no such recomputation happens, return -1 (not return 0 since 0 is a valid
        amount of shared data).

        c              3  <   K   | ]  }|j                           y wrw   r  r  s     rl   r   z>Scheduler.shared_data_after_reordering_loop.<locals>.<genexpr>  s      8
 .1AHHJr  r   r   r   r$  Fz?Don't reorder loops since both nodes are reductions: %s v.s. %s)!r(   re  r   r   r   r  r  r   r  r   rZ   r   r   r   r   r   r  r  r  r   r4   r  r`  dep_size_hintr   r  r  r  r  rG  rH  r  rI  )rk   r   r   r  r  r  r   r  r  
candidatesr   r  r  _numel	reordereds                  rl   !shared_data_after_reordering_loopz+Scheduler.shared_data_after_reordering_loop  s     00C 8
!&8
 5
 
 %"3"3"5"..;;="..;;=03EE"383D3D3U3U3WX3WC#((C-3WX383D3D3U3U3WX3WC#((C-3WX 
.K$[1G$[1G3356689 !!((::#--/! ;    /" z?a $'zx7J7J17M#N '9-Z5Sw///
   "g&7&7&99))'22	!!#77II##%77II##Q    KKT55eUCD	
 	
k YXs   J0J5c                f   t        |t              r)|j                          xr t        |j                         S t        |t
              rht        |j                  t        j                        r|j                  j                          S |j                          xr t        |j                         S y)z>
        Is this node unfusable under any conditions.
        F)	r   rA  r   rW   r   r  r+   r@  rA  r%  s     rl   rO  zScheduler.unfusable_node  s     d23'')) 2U		3 /  d56$))R%?%?@9966888'')) 2U		3 /  rn   c                   |j                         t        j                  j                  k  ry|j	                         }|j                         }d}|||z  kD  r	 |d       yt        d |j                         D              }|t        j                  j                  j                  j                  fk(  r	 |d       yd	d}|j                         }	|	j                         s+ ||	j                        r|j!                         s	 |d       yy)
zT
        Heuristics to avoid benchmarking predictably slow prologue fusions
        T皙?z@prologue fusion will not increase amount of bytes read in kernelFc              3     K   | ]J  }|j                   <|j                   j                         D ]  }|j                  dk(  r|j                   ! L y w)Ncall_function)r   rW  r  rX  )r   r  r  s      rl   r   zEScheduler.check_prologue_fusion_heuristics_fusable.<locals>.<genexpr>+  sN      
.vv!VV'')tt&	 HH * .s   AAz\prologue fusion will not increase attempt to fuse in padding bc it increases unaligned readsc                <    | j                   dk  xr | j                  S )Nr   )itemsizeis_floating_point)r  s    rl   low_prec_fpzGScheduler.check_prologue_fusion_heuristics_fusable.<locals>.low_prec_fp8  s    >>Q&B5+B+BBrn   zVprologue fusion that must be upcast to fp32 not profitable for low precision templates)r  ztorch.dtyper   rv   )r   rZ   r   invoke_quant_opsrl  rn  r   r   r  r  r  constant_pad_ndr*  r  rV   r  r	  )
rk   prologue_noder  r  
read_byteswrite_bytesBYTES_THRESHOLD_MULTIPLIERr_  r  template_bufs
             rl   (check_prologue_fusion_heuristics_fusablez2Scheduler.check_prologue_fusion_heuristics_fusable  s    ,,.!''2J2JJ"88:
#::< &)"'AABRS  
",,.
 
 uyy~~55==??n 	C %??A668L../!>>@h rn   c                <    t        |t              rt        |t              syt        |j                  t        j                        r$t        |j                  t        j                        sy|j                         s|j                         ryt        j                  dk(  ry|j                  |j                  }}|\  }}|\  }}|j                         s,|j                         s||k7  st        |      t        |      k7  ryt        |j                  j                        dkD  s"t        |j                  j                        dkD  ry j                  t        t        |j                  j                                    }	 j                  t        t        |j                  j                                    }
t!        |	|
      t        j"                  kD  ryd fd} ||      s ||      ryg }t%        t'        ||            D ]  \  }\  }}||k7  s|j)                  |       ! t        |      dk7  ry|d   }||   ||   }}t*        j,                  j.                  j1                  ||      r|||fS t*        j,                  j.                  j1                  ||      r|||fS y)ao  
        Fusing two small pointwise nodes significantly reduces kernel overhead
        and launch overhead. However, slightly different sizes would prevent fusion.
        Here, we decide if expanding sizes of one node is profitible by allowing
        fusion, and returns the dimension to expand, node with smaller sizes,
        and new size after expand.
        Nri  r   c                ~   | j                   j                  D ]  }|j                  j                  v rj                  |j                     }n%j                  j                  |j                        }|s]t        j                  j                  j                  ||       st        |j                  t              r y yr  )r   r   r   r?  r@  r  rZ   r   r:  r@  r   r  rA  )r   rH  rI  rk   s      rl   has_reusable_bufferzIScheduler.get_expand_dim_for_pointwise_nodes.<locals>.has_reusable_buffer  s    ((..99 ; ;; $ ; ;DII FI $ 0 0 4 4TYY ?I ,,66y$G&y'<'<>TU / rn   r   r	  )r   r   r   r+   r   r  r(   rj  rY  r   r   r   r  r  r  r  r  small_memory_access_thresholdr  r  r   rZ   r   r   statically_known_lt)rk   r   r   n1_sizesn2_sizesn1_iter_sizesn1_reduce_sizesn2_iter_sizesn2_reduce_sizesnode1_write_memorynode2_write_memoryr  mismatch_dimensionsidxn1_sizen2_sizemismatch_dimmismatch_size1mismatch_size2s   `                  rl   "get_expand_dim_for_pointwise_nodesz,Scheduler.get_expand_dim_for_pointwise_nodesH  sY    %/z%7W uzz2#4#455::r'8'89 ))+u/M/M/O ) #\\5<<()1&)1& !!#/1=!S%77 u  ''(1,E4E4E4L4L0MPQ0Q "//T%:K:K:R:R5S0TU!//T%:K:K:R:R5S0TU"$67223 	  u%)<U)C !'0]M1R'S#C#'7'!#**3/ (T "#q(*1-,',' ' 77//O66WW11..Q66rn   c                T   u ry| j                         r@| j                  j                        }| j                  j                        }||||k7  ryt        t              rj                        S t        t              ryt              }j                         r0| j                  j                               j                        ryt        t              st        t              r	 |d       yt        t              rj                         s	 |d       yt        t              r%t        j                  t        j                         s	 |d       yj                  j#                         s	 |d       yt        t$              s	 |d       yt        j                  t&              s	 |d	       yt        j                  j(                  t*              s	 |d
       yt-        j                  j.                        dk(  sJ j                  j.                  d   j0                  t3        fdj4                  j6                  D              r	 |d       yj                  j(                  j9                         }|D ];  }	j                  j(                  j;                  |	      }
t3        d |
D              s; y t-        j                  j<                        dk(  sJ j                  j<                  d   j>                  j                  j>                  k7  r	 |d       y	 	 d%fdt3        fd| j@                  D              ryt        t        t        f      rj                         s	 |d       yjC                         jD                  z  r	 |d       yj                         rtG              s	 |d       yjI                         sj                         r	 |d       yjK                         }|jM                         }|s	 |d       ytO        d |jP                  D              |z
  }jS                         |z  r	 |d       yjU                         sjU                         r	 |d       yjW                         dd D ]B  }|jY                         }|D ]+  }t[        fd|j\                  D              r" |d         y D t        t^              sgn*j`                  D cg c]  }|j                         s| c}}t-        |      dk(  sJ |d   }t-        d   jb                        dk(  rSt-        d   jb                  d   j\                        dk(  r+d   jb                  d   j\                  d   j                  |u s	 |d       y| je                  |      syj                         rjU                         sjI                         stg              s	 |d       yji                         }|J |jk                         r-t        j                  t        j&                        s	 |d        yjS                         tl        jn                  jp                  z  s+jS                         tl        jn                  jp                  z  r	 |d!       yj                         }j                         }||k7  r |d"||       y~| js                  |#      }t        |tt              sJ |r<|tv        jx                  k  r)tv        jz                  r| j}                        }|dk\  r|}tv        j~                  rP| j                        x}r<|\  }}}|j                  ||       | js                        }t        |tt              sJ tv        j                  r,|tv        jx                  k  r| j                        }|dk\  r|}t        j                  t        j                        r4t        j                  d$j                         j                         |       tl        j                  j                  | |      syjC                         jD                  z  rY| j                        xrE tl        j                  j                  | |      xr! | j                  |      j                        S tl        j                  j                  | |      xr! | j                  |      j                        S c c}w )&zj
        Determine if it is possible to combine node1 and node2 into a
        single fused node.
        FNTz/grouped node must not be fused with other nodesznode1 is nopz'node1 is extern but not a triton kernelz5node1's triton kernel doesn't support epilogue fusionz.node1 is extern but node2 is not SchedulerNodez3node1 is extern but node2.node is not SchedulerNodez4node1 is extern but node2.node.data is not Pointwiser   r   c              3  <   K   | ]  }|j                   k7    y wrw   r  )r   r   written_buffer_names     rl   r   z%Scheduler.can_fuse.<locals>.<genexpr>  s     V>Us38822>UrT  z9epilogue reads from buffers other than the mutated outputc              3  &   K   | ]	  }|d k7    yw)r  Nr~   )r   usages     rl   r   z%Scheduler.can_fuse.<locals>.<genexpr>  s     ;F5uFs   z*node1 and node2 uses different buf layoutsc                @    | uxr | uxr | j                         v S rw   )r   )r   r   r   r  s    rl   ._is_other_node_that_references_mutation_bufferzJScheduler.can_fuse.<locals>._is_other_node_that_references_mutation_buffer   s7      u, N#50N+z/K/K/MMrn   c              3  .   K   | ]  } |        y wrw   r~   )r   r   r  s     rl   r   z%Scheduler.can_fuse.<locals>.<genexpr>	  s      &D ?tD&r>  znode2 is extern or nopznode1 must go before node2zprologue fusion turned offz2prologue fusion only supported for pointwise nodesz'template has no allowed prologue inputsc              3  <   K   | ]  }|j                           y wrw   r  )r   r  s     rl   r   z%Scheduler.can_fuse.<locals>.<genexpr>*  s     E_c3<<>_r  z;prologue fusion not implemented for kernel for these inputsz:template prologue can only fuse functional pointwise nodesr   c              3  :   K   | ]  }|j                   v   y wrw   r   )r   r.  prologue_nodess     rl   r   z%Scheduler.can_fuse.<locals>.<genexpr>:  s     QyttyyN:yr  z7template prologue can only fuse nodes with a single usezEtemplate prologue can only fuse nodes with a single use into templateztemplate epilogue not satisfiedz6multi-output template epilogue requires ComputedBufferz#fusion for buffer explicit disabledzdevice mismatch (%s vs %s)r;  z%s and %s has %s shared data)r   r_   )Nr  r  r  r   r8  rO  r  r   rc  r   can_fuse_multi_outputs_templater  rA  r  r   r+   r@  rA  r   r   r   r   r   mutation_outputsr   r   r   r   inner_fn_free_symbolscollect_inner_fn_symbol_usagerC  r'  r  r   r   rB  r   r  get_allowed_prologue_inpsr   r  r  r  r   rz  r   r  r   r   rj  r  r=  r  rV   rZ   r   no_fuse_buffer_namesrI  r  r(   score_fusion_memory_thresholdre  r  $expand_dimension_for_pointwise_nodesr  r  rn  r  r  r  r  r  r  r  r  r   can_fuse_verticalcan_fuse_horizontal) rk   r   r   can_reorderr<  r  stream2r  node2_inner_fn_free_symbolssymbolusagesr  r  unsupported_prologue_argsr   	node_outsr   r  template_snodestemplate_snoder  r  device2shared_data_scorenew_shared_data_scoreexpand_analysis
expand_dimsmaller_nodeexpand_sizer  r  r  s     ``                          @@@rl   r   zScheduler.can_fuse  sG    E> '')))--e4G))--e4G"w':w'?Qe45&&u--e45 u%4#3#3$

)
)%
7$8 e12j'7
 ABe34U=N=N=Pe67ejj"*D*DE=>:://1KLe]3DEejj.9IJejjooy9JKuzz223q888"'**"="=a"@"E"E Ve>O>O>U>UVVOP +0**//*O*O*Q'5FFvN;F;;  6 uzz../1444zz&&q)00EJJ4E4EE@A-   JJ   u8:PQR%%'()$$&8,-.u501!!#u'8'8':HI779H$,$F$F$H!(=> EX__EE'( &
 %%'*CCQR--/53Q3Q3SPQ"__.N&s+ ,,.	$CQsyyQQUV$ % , "%);< !&AAaA 
 '1,,,,Q/N N2&../14r*2215;;<A"2&..q177:??>Q[ @@sS..0%%'25956 224L+++557


B--A LM""$qww'C'CC""$qww'C'CC56!!#""$W,fg> 4454M 5 
 +S111 !F$H$HH11$($J$J5RW$X!$)$9!66#FFueTTOT6E3Z{<<ZU $ 8 8 F/555 11!F$H$HH$($M$Mu%! %)$9!))'--8##.  !	 yy!!$u6GH$$&8 &&ue4 MII//eUDUVM$$V,>>ueL 9900eU$5 M""6*>>ueLMC Bs   d%$d%c                   |j                         }t        ||      }t        t              }|j                  D ]j  }| j
                  j                  |j                  |j                        }t        |t              r| j                  |||      rW||   j                  |       l |j                  j                  D ]  }t        |t              st        |t              s$|j                  | j
                  j                  |j                  |j                              }	|	sf|	D ]v  }
t        |t              r$| j!                  |
|      r|	j#                  |
       7t        |t              sH| j%                  |
||j&                        sf|	j#                  |
       x  t)        d t*        j,                  j/                  |j1                               D              }||z  r	 |d       y|j3                         }|D ]E  }| j4                  |   j7                         }|| j8                  |   j:                  z  s= |d        y y)a  
        Check if it is legal to fuse a consumer (node2) into a producer (node1).

        We can fuse them if all the reads of node2 either match
        corresponding writes in node1, or are written by nodes that can
        be scheduled before the fusion of node1 and node2.
        c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   z.Scheduler.can_fuse_vertical.<locals>.<genexpr>  s      $
U HHUr  zmemory deps did not matchFz(intermediate nodes between node1 & node2T)r  r  r   r   rq  rg  r  r   r   r6   r5  r   r   r  r4   r5   fusable_read_and_writer\  .fusable_stardep_write_and_read_on_empty_tensorr   r   r  r  r  r   r   r@  r  r  r   )rk   r   r   node1_buf_namesr  remaining_deps_by_namer   r   cd	remainingrx  remaining_depsnode1_op_namesr  s                 rl   r   zScheduler.can_fuse_vertical  s     002u%7B47H++C((,,SXXsxx@D#w'D,A,A#ue,T"4(//4	 , ##**Bb),ZG5L.22%%))"''277;I #B!"i0T5P5PB6 "((,#GMMB

 "((, $ +& $ $
 445K5R5R5TU$
 

 O+
 +,224"D&&t,==?G 7 7 @ J JJ>?	 # rn   c                   |j                   |j                         vry|j                  j                  D cg c]  }|j                   |j                  k(  r| }}t        |      dk7  ry|d   t        t              ryt        t              sJ t        j                  t        j                        ryt        j                        j                  j                  k  sy| j                   |j                     }|g}t        |t"              r|j$                  }d}|D ]R  }	|	j                  j&                  D 
cg c]  }
|
j                   |k(  r|
 }}
|s8|dz  }t)        fd|D              rR y |dk  S c c}w c c}
w )NFr   r   c              3     K   | ]q  }t        |t              xr[ t        |j                  t        j
                         xr4 |j                  j                  k(  xr |j                  j                  k(   s y wrw   )r   r4   r#   r   r%   TMPr   )r   rH  writes     rl   r   z-Scheduler.fusable_weak_dep.<locals>.<genexpr>  so      
 +D	 4+ ,+DJJAA,JJ%++-, II+, +s   A7A:)r   r  r   r  r  r   r   r5   r4   r#   r   r%   r  r   r  r"   r  ro  r   r   r   )rk   weak_depr   r   r  mutating_writesr  relevant_reading_nodesnum_concurrent_readsreading_noderH  relevant_readss       `       rl   r5  zScheduler.fusable_weak_dep  s    == 6 6 88 **11
1zzX222 1 	 

 1$"eW%%+++u{{DHH5
 %//*ekk.F.FF++H,A,AB	"'e78%*\\" 2L )44:::D99	) :  
 " A%  
 +  ! 3" $q((W
6s   "E:;E?c                $   t        |t              rd| j                  j                  |j                  |j                        }||j                  k7  sHt        |j                  t        j                        s$t        |j                  t        j                        ryt        j                  r9|j                  |j                  k7  r |j                         }|j                         }| j                  |j                        ry|j                  |j                  k(  xr\ t        |j                         t        |j                         k\  xr/ |j                   d t        |j                          |j                   k(  S t        |t"              r| j                  j                  |j                  |j                        }| j                  j                  |j                  |j                        }|j                  |j                  k(  r|j                  ||k(  ryyrF  )r   r4   rg  r  r   r#   r   r%   r  r(   re  r  r`  rD  r  r   r   r5   )rk   rH  r  	read_name
write_names        rl   r  z Scheduler.fusable_read_and_write  sw   dI&--11$))TYYGI UZZ'&tzz488<&u{{DHH=00T]]enn5T ~~') 11%**= 

ekk) ?		Nc%**o5?II/EJJ0EJJ>
 g&--11$))TYYGI..225::uzzJJ		UZZ'JJ*+rn   c                H   t        |t        j                        sy|j                         sy| j                  j                  |j                  |j                        }| j                  j                  |j                  |j                        }t        |t              r||k(  ryyrF  )r   r+   r@  rA  rg  r  r   r5   )rk   rH  r  writing_noder'  r(  s         rl   r  z8Scheduler.fusable_stardep_write_and_read_on_empty_tensorF  s}     ,(B(BC--/))--diiC	**..uzz5::F
eW%)z*Arn   c                B    t         j                  j                  ||      S rw   )rZ   r   get_dep_size_hint)rk   r   rE  s      rl   r  zScheduler.dep_size_hintS  s    ww((k::rn   c           	     B    fd}|r6t         j                  ||      r t         j                  ||      } ||dd      S t        |j                  t
        j                        r|j                  j                         s |j                         s|j                         r|j                  j                  |j                  j                  z  }|j                  j                  |j                  j                  z  }	d	d}
d}|D ]@  }|	D ]9  } |
||      s|t         j                  |       j                  |            z  }; B  ||dd      S t        |j                  j                        t        |j                  j                        z   }t        |j                  j                        t        |j                  j                        z   }t        ||      dz  t        ||      k  r||kD  r||}}|j                  j                  |j                  j                  z  D cg c]4  }||j                  j                  v s||j                  j                  v r|6 }} |t!         fd|D              dd      S |j                  j                  |j                  j                  z  |j                  j                  |j                  j                  z  z  }t!         fd|D              }d}|dk(  r$ j#                  ||      r j%                  ||      } |||d      S c c}w )
a4  
        The first term in our fusion score that estimates number of saved
        memory operations.

        This function scores fusion candidates based on shared memory access patterns.
        Higher scores indicate better fusion candidates.

        Scoring strategy:
        1. If nodes share exact memory deps (same buffer + same indexing), return
           the sum of shared dep sizes (original behavior).
        2. If no exact matches (score == 0), check for same-buffer reads with
           different indexing (e.g., split operations reading different slices).
           - Give bonus if nodes read from exactly the same set of buffers
           - Score based on overlap ratio: common_buffer_size / total_read_size
           - High overlap (>50%) suggests good cache locality benefit from fusion
        c                    r| ||fS | |z   S rw   r~   )r  buffer_overlap_scoreis_mix_order_reductionreturn_is_mix_order_reductions      rl   _construct_return_valuez>Scheduler.score_fusion_memory.<locals>._construct_return_valueo  s#     -35KLL///rn   r   Tc                    | |k(  ryt        | t        t        f      r/t        |t        t        f      r| j                  |j                  k(  S yr  )r   r5   r4   r   )dep1dep2s     rl   _matchz-Scheduler.score_fusion_memory.<locals>._match  sD    4<dWi$89j7I.?  99		11rn   Fr&  c              3  B   K   | ]  }j                  |        y wrw   r  )r   r   rE  rk   s     rl   r   z0Scheduler.score_fusion_memory.<locals>.<genexpr>  s     IDSD&&sK8Dr  c              3  @   K   | ]  }j                  |        y wrw   r8  r  s     rl   r   z0Scheduler.score_fusion_memory.<locals>.<genexpr>  s     J7ID&&s+7Ir1  )r4  r3   r5  r3   )r   r   r   r   r   r+   r@  rA  r   r   r   r  r  r  r   r  r   _can_use_buffer_overlap_scoring&_score_fusion_memory_by_buffer_overlap)rk   r   r   rE  r1  r<  r2  r  
node1_deps
node2_depsr6  	node1_dep	node2_depnode1_dep_lennode2_dep_lenr   r  common_memory_depsr/  s   `  ``              rl   rI  zScheduler.score_fusion_memoryV  s   2	0 %):)C)CE5)Q
 &66ueDE*5!T:: 5::r'A'ABJJ002  "  "**0053D3D3K3KKJ**0053D3D3K3KKJ E'	!+Ii3 ..y94;M;Mi;X"  ", ( +5!U;;E--334s5;L;L;S;S7TTE--334s5;L;L;S;S7TT }m,q03}m3TT},$eu !,,22U5F5F5M5MMMC%++111SE<M<M<T<T5T M   +IDII1e  $//558I8I8P8PP##e&7&7&>&>>
 J7IJJ
  !A:$>>ueL#'#N#Nu$  'u.BEJJ3s    9Lc                t   |j                         s|j                         ry|j                         s|j                         ryt        j                  st        j                  rU|j                         }|j                         }|r|syt        d |D              }t        d |D              }t               }|D ]  }|j                  D ]  }	t        |	j                  t              s|	j                  j                         s9t        |	j                        sO|	j                  j                         }
|
Lt        |
t        j                        r2|
j                         }||z  s|j!                  |	j                         |j!                  |	j                           |r|D ]  }|j                  D ]  }	t        |	j                  t              s|	j                  j                         s9|	j                  |v sH|	j                  j                         }
|
3t        |
t        j                        r|
j                         }||z  s  y  y  ||fD ]d  }|j"                  j$                  D ]I  }| j&                  j)                  |j*                        }|+|j                         s<t-        |      sH  y f y)a@  
        Check if buffer overlap scoring should be used for this node pair.

        Buffer overlap scoring handles split/cat patterns where nodes read from
        the same buffer at different indices. We skip it when:
        - Either node is a reduction (different memory access patterns)
        - Either node is a template
        - Both nodes are prologue/epilogue candidates for the same template,
          because horizontal fusion would prevent them from being absorbed
          into the template kernel. For example, in:
            q = a[:64, :]; k = a[64:, :]
            return mm(q + 2, k - 2)
          "q + 2" and "k - 2" both read from `a` and would get a high overlap
          score, but fusing them horizontally prevents prologue fusion into mm
          (resulting in 2 kernels instead of 1).

        We allow buffer overlap scoring when:
        - The node outputs are not actually in the template's allowed_prologue_inps,
          meaning they can't be prologue-fused anyway, so horizontal fusion doesn't
          prevent any optimization opportunity.
        FTc              3  <   K   | ]  }|j                           y wrw   r  r  s     rl   r   z<Scheduler._can_use_buffer_overlap_scoring.<locals>.<genexpr>       +TmsCLLNmr  c              3  <   K   | ]  }|j                           y wrw   r  r  s     rl   r   z<Scheduler._can_use_buffer_overlap_scoring.<locals>.<genexpr>  rE  r  )r   r   r(   r  r  rz  r   r  r   r   r_   rB  r  r+   r   r  r  r   r   r  r  r   r=  )rk   r   r   node1_outputsnode2_outputsnode1_output_namesnode2_output_names&node1_prologue_eligible_template_usersr   r.  r  allowed_inpsr   r   rr  s                  rl   r:  z)Scheduler._can_use_buffer_overlap_scoring  sD   4 5#5#5#7%"3"3"5&":":!--/M!--/M !!++Tm+T!T!++Tm+T!T
  3 %IID"499.?@ II1137		B
 )-		(C(C(E(4)2+B+B: ,9+R+R+TL1L@ F J J499 U CFFtyyQ% & %. 6(C #		&tyy2CD $		 5 5 7 $		-S S -1II,G,G,IM,8Z -r/F/F> 0=/V/V/X#5#D+0 (-! !* )& ++11C#66::388DH ,$0027A$ 2 ' rn   c                |    dd
 fdt        d |j                  j                  D              }t        d |j                  j                  D              }||z  syt        fd|j                  j                  D              }t        fd|j                  j                  D              }t	        ||      }|dk(  ryt        fd|j                  j                  D              }t        fd	|j                  j                  D              }	t	        ||	      }
|
|z  }|t
        j                  k\  r|
S dS )a8  
        Score fusion based on buffer name overlap when exact dep matching fails.

        This handles the split/cat fusion case where nodes read from the same buffer
        but at different indices (e.g., different slices from a split operation).

        Scoring logic:
        - If nodes read from exactly the same buffers: high bonus (encourages fusion)
        - For common buffers: score based on overlap ratio
          - overlap_ratio = common_buffer_size /
            max(node1_total_reads, node2_total_reads)
          - If overlap_ratio > threshold (e.g., 0.5): give proportional score
          - If overlap_ratio < threshold: minimal/no score (not worth fusing)

        Note on dynamic shapes:
        - When deps have unbacked symbols (dynamic shapes), dep_size_hint returns 0
        - In this case, we use count * 10 as a proxy for size
        - This ensures fusion still works for models with dynamic batch sizes

        Note on multiple deps from same buffer:
        - A node may have multiple MemoryDep entries for the same buffer name
          (e.g., 4 split reads from arg0_1 at different indices)
        - We sum ALL dep sizes for each buffer, not just take max
        - This ensures overlap ratio is calculated correctly when nodes read
          multiple slices from the same underlying buffer
        r	  c                8    j                  |       }|dkD  r|S S r   r8  )r   r   FALLBACK_DEP_SIZErk   s     rl   get_dep_sizezFScheduler._score_fusion_memory_by_buffer_overlap.<locals>.get_dep_sizeK  s%    %%c*D!84:)::rn   c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zCScheduler._score_fusion_memory_by_buffer_overlap.<locals>.<genexpr>O  ry  r  c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   zCScheduler._score_fusion_memory_by_buffer_overlap.<locals>.<genexpr>P  ry  r  r   c              3  .   K   | ]  } |        y wrw   r~   r   r   rP  s     rl   r   zCScheduler._score_fusion_memory_by_buffer_overlap.<locals>.<genexpr>Y        $
)@#L)@r>  c              3  .   K   | ]  } |        y wrw   r~   rT  s     rl   r   zCScheduler._score_fusion_memory_by_buffer_overlap.<locals>.<genexpr>\  rU  r>  c              3  J   K   | ]  }|j                   v r
 |        y wrw   r  r   r   common_namesrP  s     rl   r   zCScheduler._score_fusion_memory_by_buffer_overlap.<locals>.<genexpr>g  *      %
.xx<' .    #c              3  J   K   | ]  }|j                   v r
 |        y wrw   r  rX  s     rl   r   zCScheduler._score_fusion_memory_by_buffer_overlap.<locals>.<genexpr>l  rZ  r[  )r   r3   r   r  )r   r   r   r   r  r(   min_overlap_ratio)rk   r   r   node1_read_namesr  node1_total_read_sizenode2_total_read_sizemax_total_read_sizenode1_common_read_sizenode2_common_read_sizecommon_read_buffer_sizeoverlap_ratiorO  rY  rP  s   `           @@@rl   r;  z0Scheduler._score_fusion_memory_by_buffer_overlap+  sQ   < 	; &%R%:K:K:Q:Q%RR%%R%:K:K:Q:Q%RR (*:: !$ $
).):):)@)@$
 !
 !$ $
).):):)@)@$
 !
 ""79NO!#
 "% %
((..%
 "

 "% %
((..%
 "
 #&&<>T"U 02EE
 (58P8P'P#	
VW	
rn   c                   t        |      dk(  r|S i }|D ]  \  }}|j                         |j                         k(  sJ |j                         }t        | j                  |      j	                  ||            }||vr	||fg||<   p||   j                  ||f        t        |j                         t        j                  d            d   }t        |      dkD  sJ |S )Nr   r$  r   )
r   r   r  rc  get_fusion_pair_priorityr   r  r  r  r  )rk   r6  "possible_fusions_group_by_priorityr   r   r  fusion_pair_priority&possible_fusions_with_highest_prioritys           rl   rQ  z4Scheduler.get_possible_fusions_with_highest_priority  s   
  A%##  	+ -LE5##%)9)9);;;;%%'F#&  (AA%O$  $+MMENL23GH 33GHOOEN - 25.446H<O<OPQ<R2

2. 9:Q>>>55rn   c                B    t        j                  j                  | g| S )z-
        Shim for list.sort(key=...)
        )rZ   r  score_fusionrO  s     rl   rR  zScheduler.score_fusion_key  s     yy%%d3U33rn   c                    t        t        j                  j                               }t	        | j
                        D ]9  }|j                  || j                         |j                  |j                         ; y)zg
        Populate node.last_usage recursively (also for the nodes within a FusedSchedulerNode)
        N)
r   rZ   r   r  r   r  r  r  r  r`  )rk   r  r   s      rl   r  zScheduler.compute_last_usage  sX    
 ))A)A)CDTZZ(D 3T5L5LM&&t7 )rn   c                   t        | j                  t        j                  j                  z
  t        j                  j
                  j                  z
        D ]z  }|| j                  v rT| j                  |   }|j                         s2t        j                  j
                  j                  |j                         f|t        j                  j                  v st        j                  j                  |   }t        |t        j                        r*t        j                  j
                  j                  |       t        |t        j                  t        j                   f      r|j"                  }t        |t        j$                        r|j'                         sJ t        j                  j
                  j                  |j"                         } | j                  j)                          y)z*Free any buffers that are no longer neededN)r)  r  rZ   r   r?  r:  freedr@  rI  codegen_freer   r  r   r+   r  r  r  r   r  is_input_bufferr@  )rk   r   r   r  storages        rl   free_bufferszScheduler.free_buffers  sO   %%gg%%&gg""(()
D
 t'''&&t,<<>GG((55chh?---gg**40c2#5#56GG((55c:b&7&79M9M%NO!hhG"7BMM:w?V?V?XXGG((55gllC)
, 	!!'')rn   c                    | j                   j                         D ]  }|j                           | j                          y rw   )rl  r   flushrs  )rk   rQ  s     rl   ru  zScheduler.flush  s.    }}++-GMMO .rn   c                v   t        |t        t        f      sJ t        d   dxx   dz  cc<   t	        j
                  t        d            5  |j                          |j                          d d d        |j                  t        j                  j                         | j                          y # 1 sw Y   CxY w)Nr  extern_callsr   F)increase_kernel_count)r   r  rV  r   rZ   set_kernel_handlerr0   rL  r  r;  r   r:  rs  )rk   scheduler_nodes     rl   codegen_extern_callzScheduler.codegen_extern_call  s     &(LM
 	
 
 	^,1,!!&u"EF002##% G 	qww334	 GFs   !B//B8c                P   t        |j                        r|j                  
J | d       t        j                  j                  |       t        |j                        }|t        d|j                         t               s|j                  dk(  rLt        j                  j                  |      x}j                  dk  rt        |t        j                               t        |j                        r,|j                  dk(  st!        t        j                                ||       S )Nz( should have been normalized in loweringzUnsupported device type: r      r  )rU   r   r   rZ   r   add_device_infor/   rU  r&   r  r   get_device_propertiesmajorr7   inspectcurrentframer8   )rk   r  device_schedulingr  s       rl   create_backendzScheduler.create_backend  s    &++&&,,*B 	
h>?	
B 	
'5fkkB$!:6;;-HII|v%%*ZZ%E%Ef%MM\TTWXX(w7K7K7MNN$V[[E-A#G$8$8$:;; &&rn   c                    |J || j                   vr| j                  |      | j                   |<   | j                   |   S rw   )rl  r  r  s     rl   rc  zScheduler.get_backend  sB    !!!&$($7$7$?DMM&!}}V$$rn   c                    d fd}|j                         D ci c]8  }|j                  *|j                  j                         D ]  } ||      |fd  : }}}t        |j	                               }|rMt        |t        j                  d            \  }}t        j                  j                  j                  |       y y c c}}w )Nc                    | j                   vrLj                   j                  t        | j                  j                        D  ci c]  \  }} | |
 c} }       j                       S c c} }w rw   )r  r  r  r   r  )r  r  rk   s     rl   	get_orderz*Scheduler.enter_context.<locals>.get_order   sb    ,,,$$++i>V,W>VdaQT>V,WX''** -Xs   A+
r   r$  )r  ztorch.fx.Noder   r  )r   r   rW  r   r   r  r  r  rZ   r   r:  enter_context)rk   r   r  r  r  r_  r  lasts   `       rl   r  zScheduler.enter_context  s    	+ ^^%
%vv!VV'') q\1t# * % 	 
 w||~&'x':':1'=>GAtGG  ..t4 
s   =Cc                    	 | j                   |   j                  }t        fd|D              xr || j                  vxr || j
                  vS # t        $ r Y yw xY w)NFc              3  ^   K   | ]$  }|j                   xs |j                         v  & y wrw   )r  r  )r   r.  r  s     rl   r   zAScheduler.can_buffer_be_removed_through_fusion.<locals>.<genexpr>  s,     VPUC3C CCPUs   *-)r@  r  KeyErrorr   rg  r  )rk   r   r  r  s     ` rl   r~  z.Scheduler.can_buffer_be_removed_through_fusion  sn    	$$T*00E VPUVV 4D1114D333	
  		s   A 	AAc                   |j                   }t        |t        j                  j                  j
                        rk|j                  x}r]t        |      \  }}|t        j                  v s|t        j                  v r+t        |t        j                  j                        sJ d| S t        j                  j                  j                  j                  st        j                  yt        |t               r)|j"                  D ]  }| j%                  |      }|s|c S  y|j                   J |j'                         s|j)                          dS t        |j                   t        j*                        ryt        |j                   t        j,                        ryt/        |j                   dd      ryt1        |j                         ry	| j3                  |      x}r|S t        j                  j4                  rt7        |      ry
y)z
        Return the reason why we should partition the inductor graph on this node,
        or None if the node is cudagraphable.
        zcustom partition op: Nz6partition includes all ops when cudagraphs is disabledz opszDeviceCopy opszConditional opsunbacked_bindingszunbacked binding opszCUDAGraph-unsafe custom opszdynamic shape ops)r   r   r  r  r+   rD  r  rP   r(   custom_should_partition_ops_ops
OpOverloadr   r^   rH   rN  r   r   should_partitionrU   r   
DeviceCopyrL  r  rT   &_uses_cudagraph_unsafe_unbacked_symintcudagraph_skip_dynamic_graphsr2  )rk   r   r5  r  op_overload_packet_nameop_overload_namer  r  s           rl   r  zScheduler.should_partition  s    ))gu11@@A%%%B%8DR8H5#%5'6+M+MM#v'I'II!"ejj&;&;<<<./?.@AA &&--886>>FKd./..u5!M % yy$$${{}oo'(--dii/#dii0$499148)!$)),0@@FF6FM ==66-d3*rn   c                T   t               }t        j                  s|S | j                  D ]  }|j                  }|t        |t        j                  j                  j                        sA|j                  }|Pt        |      \  }}|t        j                  vr|t        j                  vr|j                         D ]g  }t        j                  j                  j!                  |      }t#        |t$        j&                  t$        j(                  f      sW|j+                  |       i  |S )zc
        Collect output unbacked symints from ops in config.cudagraph_unsafe_unbacked_ops.
        )r   r(   cudagraph_unsafe_unbacked_opsr  r   r   r  r  r+   rD  r  rP   r  rZ   r   r   r   r$   r%   UNBACKED_INTUNBACKED_FLOATr  )rk   unsafe_symintsr   r5  r  r  r  syms           rl   &_get_cudagraph_unsafe_unbacked_symintsz0Scheduler._get_cudagraph_unsafe_unbacked_symints]  s    
 4><33!!JJDiiGgu'9'9'H'HI$$Bz8DR8H5#%5'v/S/SS$F,P,PP779gg&&//4!#(9(94;N;N'OP"&&s+ :' 0 rn   c                    | j                         }|sy t        |      }|D ]I  }t        j                  j                  j                  |      }|j                  D ]  }||v sd| c c S  K y )Nz'uses cudagraph-unsafe unbacked symint: )r  r2  rZ   r   r   r   r"   )rk   r   r  node_symbolsr  simplified_symfree_syms          rl   r  z0Scheduler._uses_cudagraph_unsafe_unbacked_symint  sp     DDF5d;CWW--66s;N*77~-DXJOO 8   rn   c                    i }|j                  t        j                  j                         | j                  D ]3  }|j
                  j                         D ]  \  }}|j                  ||<    5 |S )z~
        Return a mapping from name strings to the corresponding graph inputs or
        base scheduler node outputs.
        )r  rZ   r   r  r  rl  r  r   )rk   ru  r   r   scheduler_buffers        rl   get_name_to_nodeszScheduler.get_name_to_nodes  si     PRAGG001JJD*.*>*>*D*D*F&&%5%:%:T" +G  rn   c           	        t        t        j                  j                        D ci c]  \  }}||
 }}}t        t        j                  j	                               D ci c]  \  }}||
 }}}g t        j                  _        t        |      D ]  \  }}|j                  rg }|j                  D ]"  }|j                  |j                  |             $ g }	|j                  D ]0  }
|	j                  |j                  |
j                                      2 t        j                  j
                  j                  t        |||	|j                                yc c}}w c c}}w )z
        computes a mapping from partition input/output indices to graph input/output
        indices for each partition.
        N)r  rZ   r   r  r  partition_mapsskip_cudagraphinput_nodesr   r  output_nodesr  rQ   constant_names)rk   
signaturesr  r   name_to_graph_input_indexname_to_graph_output_indexpartition_id	signatureinput_mappingoutput_mappingr   s              rl   compute_graph_partition_mapsz&Scheduler.compute_graph_partition_maps  sE    (11E1E'F%
'F)#tD#I'F 	" %
 (11I1I1K'L&
'L)#tD#I'L 	# &
 "$'0'<#L)''
 M!--$$%>%B%B4%HI .  N!..%%&@&D&DT]]_&UV / GG""))! !",,	! (=%
&
s   E!E c                   	 	 	 	 dd	 	 	 	 dd} t               j                  d |D         } |j                  fd|j                         D           ||      }t               }|D ]F  }t        j
                  j                  j                  |      }|j                  |j                         H t        t        |t        j                  d                  S )	ai  
        Returns all symbol inputs which are required to be in scope to successfully
        perform codegen for this graph partition, including:
        - free symbols used in partition nodes
        - free symbols in partition input/node shapes, strides, and offsets. This is needed
          for recording cudagraphs for tensors with dynamic shapes.
        c                    t        | t        j                        r
t               S t        | t        j                        rt        |       S t        dt        |              )zW
            Gets symbols used in input node shapes, strides, and offsets.
            zUnsupported input node type: )r   r+   r  r   r  r-  r+  r   r   s    rl   get_input_node_symbolszKScheduler.get_graph_partition_symbol_inputs.<locals>.get_input_node_symbols  sN     $ 2 23!|#D")),)$// *,I$t**VWWrn   c                &    t        d | D              S )z
            Filters a set of symbols that are required for codegen. Skip symbols
            that are always internal to kernels, such as SymT.TMP, SymT.INDEX,
            and SymT.R0_INDEX.
            c              3     K   | ]N  }t        |t        j                  t        j                  t        j                  t        j
                  f      r| P y wrw   )r$   r%   SIZEFLOATr  r  r   rt  s     rl   r   zVScheduler.get_graph_partition_symbol_inputs.<locals>.filter_symbols.<locals>.<genexpr>  sH       A!		

))++	  s   AAr   )symbolss    rl   filter_symbolszCScheduler.get_graph_partition_symbol_inputs.<locals>.filter_symbols  s         rn   c              3  2   K   | ]  }t        |        y wrw   r1  r  s     rl   r   z>Scheduler.get_graph_partition_symbol_inputs.<locals>.<genexpr>  s     Iyt,T2yr3  c              3  4   K   | ]  \  }} |        y wrw   r~   )r   r  r   r  s      rl   r   z>Scheduler.get_graph_partition_symbol_inputs.<locals>.<genexpr>  s     N:Mwq$$T*:Ms   r   r$  )r   z+ir.IRNode | sympy.Expr | ir.TorchBindObjectr   OrderedSet[sympy.Symbol])r  r  r   r  )r   r  r  r  rZ   r   r   r   r"   r)  r  
attrgetter)	rk   	partitionr  r  candidate_symbolsr  rt  symplified_sr  s	           @rl   !get_graph_partition_symbol_inputsz+Scheduler.get_graph_partition_symbol_inputs  s    	X=	X%	X 	-	%	, 7Ijl6H6HIyI7
 	!  N+:K:K:MN	
 ++<=(2"A77++44Q7LJJ|001 #
 &(*=*=f*EFGGrn   c           
         g }t        t        j                  j                               } j	                         }d fdt        t        |      t        |            D ]2  \  }}t               }|D ]+  }	|j                  |	j                  j                                - |j                  |      }
t        j                  j                  |D 	cg c]  }	|	j                   c}	      }t        |j                  |j                   z  D cg c]  }t#        |t$              s|j&                    c}      |z
  }t         fd|D              }t               }|D ]  }	|j                  |	j(                          ||z
  D cg c]  }||v r|
 }}|j                  |       |D ci c]  }||v r|||    }}|D ci c]  }||v r|||v  }}|D cg c]  }||v r||vr| }}|
j                  |       t         fd|
D              }
|
D cg c]  } |      s||    }}|D cg c]!  }|t        j                  j*                  v s |# }} j-                  ||      }t/        ||||||      }|j1                  |       |j3                  ||
z
        }5 |ddd   S c c}	w c c}w c c}w c c}w c c}w c c}w c c}w c c}w )z
        Gets signature for each graph partition, including input nodes, output nodes, and
        whether deallocating an input within graph partition.
        c                    j                   j                  | d      }|yt        |j                  j                  t
              r'j                  j                  | d      x}r |      S yy)z
            Checks if buf_name resolves to a NoneLayout buffer (following mutation_real_name).
            Buffers with NoneLayout are not allocated so graph partition should not
            take them as inputs or outputs.
            NFT)r@  r  r   r   r'  r?   r  )r  r   r  is_unallocated_bufferrk   s      rl   r  zFScheduler.get_graph_partition_signature.<locals>.is_unallocated_buffer  sh     ""&&x6C{#((//:6 !% 7 7 ; ;Hd KK9K0;;rn   c              3  V   K   | ]   }j                   j                  ||       " y wrw   r  r  r   r   rk   s     rl   r   z:Scheduler.get_graph_partition_signature.<locals>.<genexpr>N  ,      /1D ''++D$71r   c              3  V   K   | ]   }j                   j                  ||       " y wrw   r  r  s     rl   r   z:Scheduler.get_graph_partition_signature.<locals>.<genexpr>x  r  r   Nr   )r  r  r   rv   )r   rZ   r   r  r  r  r   r  rl  r   rl  r*   r  r  r   r   r  r   r6   r   r`  rp  r  r<   r   r  )rk   
partitionsskip_cudagraphsr  unmet_output_namesru  r  r  output_namesr   returned_output_namesr   rJ  partition_input_namesr  r   extra_input_namesr  input_deallocationextra_output_namesr  r  symbol_inputspartition_signaturer  s   `                       @rl   get_graph_partition_signaturez'Scheduler.get_graph_partition_signature  sc    
'(@(@(BC--/	, *-Z (?";*
%I~ -7LL!##D$8$8$=$=$?@ " %1$=$=>P$Q! '11<<.78id!!i8K  "-!2!2[5G5G!G!GA)!W5 !G  " %/ /1/ %!
 5?L !$++DOO< " 2L@!@D<' @  !
 "(():; 21D<' l4((1   2"1D<' d2221  " 2"1D<'D8L,L 1  " "(();<$. /1/ %! 21D,T2 T"1   "7!6$!''BSBS:S!6   !BB;M #:"# 12!6!<!<"%::"K*
R $B$y 9*!
""s6   J

#J$
>J)"J.9J3J8J=%!KKc                   |j                   j                         D ci c]$  \  }}|t        j                  j                  vr||& }}}|j
                  j                         D ci c]$  \  }}|t        j                  j                  vr||& }}}|j                  D cg c].  }|j                         t        j                  j                  vr|0 }}|j                  D cg c]   }|t        j                  j                  vr|" }	}t        |j                  ||||j                  |	      S c c}}w c c}}w c c}w c c}w )z
        Updates the partition signature by removing buffers specified in
        V.graph.removed_buffers. See [Note: Removed Graph Partition Arguments]
        )r  r  rZ   r   r?  r  r  maybe_get_namer  r<   r  r  )
rk   r  r   r]  r  r  r  r   r  r  s
             rl   .clean_removed_buffer_from_partition_signaturesz8Scheduler.clean_removed_buffer_from_partition_signatures  sV    !* 5 5 ; ; =
 =f177222 &L = 	 
 '99??A
A	c177222 #IA 	 
 "..
.""$AGG,C,CC . 	 
 "00
0177222 0 	 

 '##$$
 	
)






s   )D/')D5!3D;$%E c                p   	
 ddl 	t               g g t        |      D ci c]  \  }}||
 c}}d	 fd
d
fd}|D ]5  }t        |j                  j
                        |<   |   dk(  s. 
|       7 g }d}|t        |      k  rsr}r0	j                        \  }}|j                  |        ||       r0r0	j                        \  }}|j                  |        ||       r0|dz  }|t        |      k  rrzr}|t        |      kD  rt        d      |S c c}}w )a  
        Reorder nodes to minimize the number of partitions via a bfs
        topological sort. This is the optimal reordering such that the
        number of partitions cannot be reduced further. This may be
        sub-optimal for other metrics such as peak memory. This does not
        change relative orders of two cudagraphable nodes, nor the
        relative order of two non_cudagraphable nodes.
        r   Nc                    |    | f}j                  |       rj                  |       y j                  |       y rw   )r  heappush)r   node_with_indexcudagraphable_nodesheapqnode_to_indexnon_cudagraphable_nodesrk   s     rl   insert_pending_nodeszHScheduler.reorder_for_minimizing_partition.<locals>.insert_pending_nodes  s>    ,T2D9O$$T*6H2ODrn   c                    | j                   j                  D ]*  }|   dkD  sJ |xx   dz  cc<   |   dk(  s# |       , y r=  )re  
succ_nodes)r   	succ_noder  node_to_indegrees     rl   update_indegreezCScheduler.reorder_for_minimizing_partition.<locals>.update_indegree  sO    !]]55	'	2Q666 +q0+#I.!3(3	 6rn   r   z
                Failed to schedule, while loop ran too long when
                reordering for minimizing the num of partitions
                r   r_   r   rU  )	r  r  r  r   re  
pred_nodesheappopr   rU  )rk   r  r  r   r  r  	num_itersr  r  r  r  r  r  r  s   `       @@@@@@rl    reorder_for_minimizing_partitionz*Scheduler.reorder_for_minimizing_partition  sV    	9=CEGI4=e4DE4DysDs4DE	E 	E	4 D%()A)A%BT"%*$T* 
 -/	#e*$#':)--(?@4%% *
 &--(;<4%% &
 NI #e*$#': s5z!  ] Fs   D2c           	     X   ddl m}m} t        t        j
                  j                               } ||| j                  | j                  t        t        j
                  j                  j                               |      \  }}| j                  |      } ||||      \  }}	||dz  k  r|S |S )zx
        Reorder nodes to minimize the number of partitions if this only slightly
        increase peak memory.
        r   )estimate_peak_memoryprepare_planning_infor  )r  r  r  r   rZ   r   r  r@  r  r  r   r  )
rk   r  r  r  r   default_peak_memoryr5  reordered_nodesreorder_peak_memoryr  s
             rl   r  z0Scheduler.maybe_reorder_for_minimizing_partition  s     	H"177#;#;#=>:O##qww++0023;
77 ??F!57"
Q
 !4s!::""rn   c                   g }g }g }dd}|D ]n  }| j                  |      du}|r*t        |j                        dk(  r|j                  |       B|r ||      r|j                  |       ^|j                  |       p ||z   |z   S )a  
        Reorder a node if it should be partitioned and has simple dependency:
        1. move a partitioned node to the front if it has no dependency
        2. move a partitioned node to the back if it is only used by OutputNode
        3. otherwise do not reorder
        c                    | j                         D ]0  }|j                  D ]  }t        |j                  t              r  y 2 yrF  )rz  r  r   r   rG  )r   r   rH  s      rl   only_output_userzPScheduler.reorder_for_partition_with_simple_dependency.<locals>.only_output_user.  s9    '')99C%chh
;$ % * rn   Nr   r	  )r  r   rq  r   )rk   r  frontmiddlebackr  r   r  s           rl   r  z6Scheduler.reorder_for_partition_with_simple_dependency   s     *,*,(*	 D#44T:$FC(?(?$@A$ET"!&6t&<D!d#  v~$$rn   c                   g }d}g }g }| j                   D ]S  }| j                  |      du}|r)||k7  r$|j                  |       |j                  |       g }|}|j                  |       U |r"|j                  |       |j                  |       t        j                  j
                  }|dkD  rXt        t        ||            D ]@  \  }\  }	}
|
rt        d |	D              }||k  s$d||<   t        j                  d|||       B | j                  ||      }| j                  |       | j                  ||       ||fS )z
        Given a list of BaseSchedulerNodes, split into a list of
        graph partitions and compute partition input/output signatures.
        TNr   c              3  @   K   | ]  }t        |t              sd   ywr   N)r   rA  r  s     rl   r   z,Scheduler.graph_partition.<locals>.<genexpr>`  s#      '!*A)!-CD !*r  zFPartition %d has %d kernels, below minimum size %d, skipping cudagraph)r  r  )r  r  r   r(   r   cudagraph_min_partition_sizer  r  r   cudagraphs_logr  r  r  _log_graph_partitions)rk   r  r  cur_partitionr  r   node_should_partitionmin_sizer  r  skipkernel_countr  s                rl   r  zScheduler.graph_partition@  sd    +-
')JJD$($9$9$$?t$K!3H!H!!-0&&~6 "2N  &  m,"">2 ====a<(1#j/2R(S$$It#& '!*' $L
 $h.-1*&,,d($	 )T" 77!? 8 

 	))*5"":z::%%rn   c                `   t         j                  t        j                        sy t	        d t
        j                  j                  D              }|sy t        d |D              }t        |      |z
  }t         j                  dt        |      ||       t        t        ||            D ]  \  }\  }}t         j                  d|t        |      |j                  rdndt        |j                        t        |j                               |j                  sm|D ]  }	| j!                  |	         y )Nc              3  2   K   | ]  }t        |        y wrw   )rU   )r   r  s     rl   r   z2Scheduler._log_graph_partitions.<locals>.<genexpr>  s     O:NVF^:Nr3  c              3  :   K   | ]  }|j                   rd   ywr  )r  r  s     rl   r   z2Scheduler._log_graph_partitions.<locals>.<genexpr>  s     !PZq?O?O!Zs   zCCreated %d graph partitions: %d cudagraphable, %d non-cudagraphablez3  Partition %d: %d nodes, %s, inputs=%d, outputs=%dznon-cudagraphablecudagraphable)r	  r  r  r  r   rZ   r   device_typesr   r   r  r  r  r  r  r  _log_non_cudagraphable_node)
rk   r  r  has_gpu_devicecudagraphable_countnon_cudagraphable_countr  r  r  r   s
             rl   r	  zScheduler._log_graph_partitionsw  s   
 **7==9 O!'':N:NOO!!PZ!PP"%j/4G"GQ
O#		
 *33z:3N)O%A%	9  EI'0'?'?#_I))*I**+ ''%D44T: & *Prn   c                   | j                  |      }|sy|j                         }|j                  |j                  j                         nd}d| g}t	        |j                        j
                  }|j                  d|        |F|j                   ddj                  d |j                  D               d}|j                  d|        t        j                  d	|dj                  |             |Z|j                  j                  d
d      }|r;|j                         j                  d      D ]  }	t        j                  d|	        yyy)z)Log details for a non-cudagraphable node.Nzreason=zir=r  r  c              3  2   K   | ]  }t        |        y wrw   )r  )r   r  s     rl   r   z8Scheduler._log_non_cudagraphable_node.<locals>.<genexpr>  s     2P<a3q6<r3  r~  zfx=z
    %s: %srP  r  z         %s)r  r  r   r  r   ry   r   rX  r  r4  r	  r  rY  r  stripsplit)
rk   r   r  ry  r  partsir_typefx_strrP  lines
             rl   r	  z%Scheduler._log_non_cudagraphable_node  s,   &&t,MMO	151F$))++-D6(#$tyy/**s7)_%'q2P7<<2P)P(QQRSFLL3vh(\9dii6FG !,,**=$?K'--/55d;D"((= <  rn   c                    t        d      5  t        j                  j                  j                  r| j                         n| j                  | j                        	 cd d d        S # 1 sw Y   y xY w)NzScheduler.codegen)r   r  r  r(   r  _codegen_partitions_codegenr  rj   s    rl   r;  zScheduler.codegen  sO    -. ??))99 ((*]]4::. /..s   AA&&A/c                ^   ddl m} t        j                  j                  }t        | j                        }t        j                  j                         5  t        j                  j                  dd| ||       | j                  |       t        t        j                  j                  |      sJ | j                  |      }|t        j                  j                  _        t        j                  j                  j                          t        j                  j                  }t        j                  j                  j                  t        j                  j                         \  }}ddd       t        j                  j                  j#                         t        j                  j                  j%                  ||       t        j                  j                  j&                  j)                  |j*                  D 	cg c]  }	|	j-                          c}	       y# 1 sw Y   xY wc c}	w )z,Codegen a partition given its inputs/outputsr   )SubgraphPythonWrapperCodegenT
partition_)is_subgraphsubgraph_nameparent_wrapper_codepartition_signaturesN)r7  r	  rZ   r   r:  r  ro  set_current_wrapper_codeinit_wrapper_coder	  r   r  r"	  write_prefixr   generateis_inferencedefine_subgraph_launcher_fncodegen_partition_call	allocatedr  r  r  )
rk   r  r  r	  r!	  graph_partition_id
graph_namepartition_coder  r   s
             rl   _codegen_partition_wrapperz$Scheduler._codegen_partition_wrapper  s    	Bgg22!$"?"?@WW--/GG%%  *+=*>?$7%.	 &  MM)$ agg224PQQQKKIVI8AAGG  5GG  --/J ! 4 4 = =agg>R>R SNA/ 02 	
88^T	334F	R	&&--)2)?)?@)?T]]_)?@	
9 0/: As   DH?H*H'c                L     t         j                  d fd       } |       S )Nc               3    K   j                          j                  ryt        j                  j                        rZj                  j                  J d       t
        j                  j                  j                  j                  j                         	 d  j                  rGt        j                  j                        r(t
        j                  j                  j                          d _        y # j                  rGt        j                  j                        r(t
        j                  j                  j                          d _        w xY ww)Ndevice should have an index)
%update_graph_partition_default_devicerv  rK   r   r   rZ   r   r:  codegen_device_guard_entercodegen_device_guard_exit)r  rk   r  s   rl   ctxz1Scheduler.use_default_device_context.<locals>.ctx  s    66z:N**/@++000 2288D 1D $$??//553..3D//444 GG((BBD.2+	 ..3D//444 GG((BBD.2+s    BEC;  AE;AEE)r   zIterator[None])
contextlibcontextmanager)rk   r  r  r5	  s   ``` rl   use_default_device_contextz$Scheduler.use_default_device_context  s&     
	"	"	3 
#	3* urn   c                    t        |      dk(  r|d   j                  sy dd}	 	 	 	 	 	 dd}d }t        ||      D ]  \  }}|j                  r ||      } n |y t        ||      D ]  \  }}|j                  s |||      r y  || _        y )Nr   r   c                4    | d   j                         }|J |S r   r  )r  partition_devices     rl   get_cudagraph_partition_devicezWScheduler.update_graph_partition_default_device.<locals>.get_cudagraph_partition_device  s'    (|668#///##rn   c                @    | D ]  }|j                         }||k7  s y yrF  r  )r  target_devicer   r  s       rl   all_on_target_devicezMScheduler.update_graph_partition_default_device.<locals>.all_on_target_device  s*     "*]*  " rn   )r  r`   r   r6  )r  r`   r>	  r6  r   rv   )r   r  r  rv  )rk   r  r  r<	  r?	  cudagraph_partition_devicer  r  s           rl   r2	  z/Scheduler.update_graph_partition_default_device  s     z?a
1(D(D 	$
	$	5A		 &*"$'
J$? Iy++-KI-V* %@ &-$'
J$? Iy''0D51 	 %@ 'A#rn   c                   | j                         \  }}t        |      dkD  rt        d   dxx   t        |      z  cc<   | j                  ||      5  t	        ||      D ]V  \  }}t        |      dk\  sJ dt        |              |j
                  r| j                  |       E| j                  ||       X 	 ddd       t        | j                        }t        j                  j                  j                  |       |dkD  rqt        j                  j                  J |t        t        j                  j                        k(  s.J d| dt        t        j                  j                                yy# 1 sw Y   xY w)	z
        Split nodes into partitions and codegen each partition into separate functions.
        This allows further applying different optimizations (e.g., cudagraph) to
        each function.
        r   r  cudagraph_partitionsz5Each partition must have at least one node but found Nr   zExpect z partition maps but got )r  r   r   r8	  r  r  r	  r.	  r  ro  rZ   r   r:  set_all_partition_namesr  )rk   r  r  r  r  num_partitionss         rl   r	  zScheduler._codegen_partitions0  sY    "&!5!5!7
Jz?QZ !78C
OK8,,ZD(+J
(C$	99~* KCPYNK[\* ++MM),33IyI )D E d;;<	44^D A77))555!S)?)?%@@ .))A#aggF\F\B]A^_@  EDs   A&E55E>c                n   t         j                  rdd l}t        j                         }t               }t        |      D ]  }|j                  dk(  r/|j                  |j                  j                  j                  k(  r nQ|j                  |j                  f}||vs"J d|j                   d|j                   d       |j                  |        | j                  | _        | j                   J | j                  rBt         j"                  j$                  r(t&        j(                  j*                  j-                          t&        j(                  j*                  j/                          |D ]  }t0        j3                  t4        j6                        r4	 t0        j9                  d|j;                         |j=                                | jA                  |       t         jB                  rDt&        j(                  j*                  jE                  d |jF                  jH                  D               |jK                         x}rs|| j                  k7  s |jM                         s|jO                         r| jQ                          || j                  k7  r$| j                  rctS        | j                  jT                        rD| jV                  | jY                          t&        j(                  j*                  j[                          || _        tS        |jT                        r|j\                  J d	       d
}	| j_                         r5t        | j`                  jc                               }
|
rte        |
      d
z   nd
}	t&        j(                  j*                  jg                  |j\                  |	| jh                         | j_                         r| j                  | jk                  |       t&        j(                  j*                  jm                  d |jF                  jH                  D               || _7        | jp                  js                  |jt                         |jO                         rP|jw                  ty        |j{                                     \  }}}| j}                  |      j                  |||       n5|jM                         r| j                  |       n|j                         rxt        j                  t        |      }| j}                  |      }d
dlEmF} d
dlGmH} d
dlImJ} t        ||||f      r|}nt        dtU        |             |j                  |       nt        |t              r!| j}                  |      j                  |       nYt        |t        t        f      r!| j}                  |      j                  |       n"t        |t              sJ |j                          t         j"                  j                  r| j}                  |      j                          | j                  js                  |j                                | j                  js                  |j                                t        |t              sP|jK                         }|>|jT                  dk7  r/| j}                  |      j                         r| jQ                          t        d |j{                         D              r	|| _        d | _         | j                  | j                  k7  rU| j                  J tS        | j                  jT                        r(t&        j(                  j*                  j[                          d | _        | jQ                          y # t>        $ r( t0        j9                  d|j;                                Y w xY w)Nr   _compile_innerzDuplicate stack frame :zs; did you add a decorator to one of the functions in this stack trace?  If so, try using a context manager instead.z5Generating code for node %s with estimated runtime %fz6Generating code for node %s with estimated runtime 0.0c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   z%Scheduler._codegen.<locals>.<genexpr>  s      D(>CHH(>r  r1	  r   c              3  4   K   | ]  }|j                     y wrw   r  r  s     rl   r   z%Scheduler._codegen.<locals>.<genexpr>  s      C$:S$:r  )CUDACombinedSchedulingrr  )XPUCombinedSchedulingztype(self)=rY  c              3  <   K   | ]  }t        |t                y wrw   )r   r   r  s     rl   r   z%Scheduler._codegen.<locals>.<genexpr>  s     J9IA:a/9Ir  )]r(   "check_stack_no_cycles_TESTING_ONLYtorch._dynamo.convert_frame	tracebackextract_stackr   r   r   filename_dynamoconvert_frame__file__linenor  rv  r  rs  r   autotune_at_compile_timerZ   r   r:  write_get_raw_stream_headerregister_alignment_check_inputsr  r  r  r  r  r  r  r  r  size_assertscodegen_deferred_input_assertsr   r   r   r"  r   ru  rK   r   current_stream_idxgenerate_stream_ctx_exitr4	  r   r  r  r   r  r3	  r  generate_stream_ctx_switching!codegen_deferred_alignment_copiesrt  r  r  r`  r  r   r   rc  codegen_templater{  r$  rG  rH  ro   codegen.cuda_combined_schedulingrJ	  rv  rs  #codegen.xpu.xpu_combined_schedulingrK	  r   r  codegen_combo_kernelr8  codegen_mix_order_reductionr   r   codegen_noderA  r  debug_sync_kernelcodegen_syncr  r  r>  r   ready_to_flushr   )rk   r  r  stackrI  framer%  r   r  num_streamsunique_streamsr  r  r  backend_rJ	  rs  rK	  rQ  s                      rl   r	  zScheduler._codegenP  s   44.++-E7A|D!% JJ"22%--*E*E*N*NN~~u||4$ ,U^^,<Aell^ LJ J
  ) #99!!))) &&6==+Q+QGG  <<> 	
<<>D.
IIO224 t$ ""$$CC D(,(8(8(>(>D  **v*d111~~''')JJLT000**/@++000  22> 99;,,FFH*0D'(5%||7V9VV7&'779-78K8K8R8R8T-UN;IN 3a 7q ( ,,GG"LL' ;; ++-$2E2E2Q2248 GG  BB C$($4$4$:$:C  !%D%%,,T__=!484W4W)*51-   (99!8X !((."{{#=tD++F3T8V#%;=RS 'G(KDJ=)9::,,T2D"9:  (DDTJD#5}"EF  (55d;!$(>??? }}..  (557''..t/D/D/FG%%,,T-E-E-GHd$:;*&v-((0??AJJLJ9IJJ%)"%)"E H $"="== &&222 !4!4!9!9: $$>>@!

O ! IIPs   3^-^43^4c                    |d   j                         }| t        j                  _        || _        |J | j                  |      }|j                  ||      S )rs  r   )r   rZ   r   r  r  rc  benchmark_combo_kernel)rk   r  node_benchmark_resultsr  rQ  s        rl   rn	  z Scheduler.benchmark_combo_kernel  sZ     1((* $!!!""6*--i9OPPrn   c                   |}|d   j                         t        fd|D              sJ d       t        j                  syddlm} dg }}i }t        |      D ]  \  }}|j                         }	| j                  |	      rt        j                  d       	 | j                  |	      \  }
}|
|f||<   t        j                  |
      rt        j                  d|        y		 ||
z  }|j                  |        	 | j                  ||      \  }}}||z
  dk  xs |dk  }t        j!                  t"        j$                        rP||kD  s|r%t        j                  dt'        ||z  d             n$t        j                  dt)        ||z  d             ||z
  |k  xs |S # |$ r.}d
t        |      v rt        j                  d       Y d}~ y d}~ww xY w# |$ r-}d
t        |      v rt        j                  d       Y d}~y d}~ww xY w)r  r   c              3  D   K   | ]  }|j                         k(    y wrw   r  )r   r   r  s     rl   r   z4Scheduler.speedup_by_combo_kernel.<locals>.<genexpr>  s     K?44??$.?s    z<All nodes in a combo kernel group must be on the same deviceTr  g        z<ComboKernel: benchmarking may not accurate due to atomic_addz;ComboKernel benchmark: register spilling of %d-th subkernelFr  zCComboKernel benchmark: return True because of loop-carried variableNg333333?z/can fuse (benchmark): fusing causes %sx speedupr  z3cannot fuse (benchmark): fusing causes %sx slowdown)r   r   r(   rn	  r  r  r  r   r  r  r  rt  rB  r  r  r   r  r  r  rE   rF   )rk   r  subkernel_nodesr  r  
path1_listro	  r  r  r  r  r  r  r  	ms2_clone_path2_listsmall_kernelr  s                    @rl   rC  z!Scheduler.speedup_by_combo_kernel  s#      #..0K?KK 	
J	
K ,,;rZ!#!/2HAu)I ##I.  R55i@D13T
&u-::b>$$U ! " 2ICd#9 3<	*.*E*E!7+'CK Y,9c	""7==1SyL  E#)C2
   Ic	#0
 Y$44Q $ *c!f4$$]      	&#a&0  Y 	s=   AF9G G""G
GGH"H ?H  Hc                p    | j                   |   }|j                  J |j                  j                         S rw   )r@  r   
get_layout)rk   r  r   s      rl   get_buffer_layoutzScheduler.get_buffer_layout_  s5    x(xx###xx""$$rn   c                   | j                   D ]  }|j                         s|j                  j                  D ]  }t        j
                  j                  j                  |j                        }|s9t        |      dk(  sHt        |j                  t        t        f      ri|j                         g k(  s}t        j
                  j                  j!                  |j                           y r  )r  rU   r   r   rZ   r   r  r  r   r;   r   r'  r?   r>   r  zero_dim_cpu_tensor_listr  )rk   r   rH  r]  s       rl   ru  z$Scheduler.update_zero_dim_cpu_tensord  s    JJD{{} ,,22DWW3377		BF+F3u< *"MMJ8I+J! #OO-388<<TYYG 3 rn   c                H    | j                   | j                   j                  S y)z:CUDA Stream index that current scheduler node assigned to.N)r  r  rj   s    rl   r[	  zScheduler.current_stream_idxs  s%     ##/++666rn   c                6    | j                   x}t        |      S y)z9CUDA Stream name that current scheduler node assigned to.N)r[	  r!   )rk   r  s     rl   current_stream_namezScheduler.current_stream_name{  s#     111J>":..rn   c                    t        |t              rJ | j                  |   }t        j                  j
                  j                  |      | _        y)z6Code-gen to enter the Stream context assigned to node.)r  N)r   rA  r  rZ   r   r:  codegen_cuda_stream_enterr  )rk   r   node_streams      rl   generate_stream_ctx_enterz#Scheduler.generate_stream_ctx_enter  sI    d$:;;;))$/#$77#7#7#Q#Q" $R $
 rn   c                ~    | j                   J t        j                  j                  j	                          d| _         y)z1Code-gen to exit from the current Stream context.N)r  rZ   r   r:  codegen_cuda_stream_exitrj   s    rl   r\	  z"Scheduler.generate_stream_ctx_exit  s2    ''333	557#' rn   c                &   || j                   v sJ t        |t              rdn| j                   |   }| j                  |k(  ry| j                  |y| j                  || j	                  |       y| j                          | j	                  |       y)am  Generate stream entering and exiting to properly run node in a multi-stream scenario.

        Stream context switching is only generated if ``node``'s assigned stream is different from
        the previous node's stream. NopKernelSchedulerNodes have stream=None and inherit the
        enclosing stream context (or do nothing if no context is active yet).
        N)r  r   rA  r[	  r	  r\	  )rk   r   rF  s      rl   r]	  z'Scheduler.generate_stream_ctx_switching  s     t***** $ 67 $$T* 	
 ""f, $$0V^ $$,1C**40 ))+**40rn   )r  zlist[ir.Operation]r   rU  )r   z!dict[str, SchedulerDonatedBuffer]rT  rV  )r  r  r   r  )r  r  r   r_   r   rv   rX  )r  rY  r   rU  )r  r  r   rU  )r   r  r   r_   )r  
str | Noner   rv   r  )r  r_   r   r  )r   r  r  r  r   tuple[float, str]rw   r  r  r{  rv   rz  r  r   r  )r~  r   r  r6  r   r	  )r  ir.MultiTemplateBufferr   rv   )
r  ir.OperationBufferr  r	  r  r  r   r   r   rU  )r  r  r   rv   )r  r  rz  r  r   z&tuple[LambdaFuture | None, ModuleType])r   r_   r   r_   r   rd   )r   r_   r   r_   )r   r_   r   r_   r  OrderedSet[BaseSchedulerNode]r   r_   )r   r_   r   r_   r  rx   r  r	  )r  ,dict[BaseSchedulerNode, list[PendingFusion]]r  r	  r   rU  )
r,  1list[tuple[BaseSchedulerNode, BaseSchedulerNode]]r*  &dict[BaseSchedulerNode, PendingFusion]r-  r	  r  r	  rl  rv   )r  r	  r*  r	  )r6  r	  r7  r	  )r  r  rl  rv   r   r  )rX  r  r   rU  rN  )r  r  rl  rv   r   r	  r
  )r   r_   r   r_   r  r  r   rv   )r   r_   r   r_   r  z!tuple[str, ...] | OrderedSet[str]r   r  r  r	  )r  r_   r  r_   r  r  r   rv   )r   r_   r   r_   r   z,tuple[int, SchedulerNode, sympy.Expr] | None)FT)
r   r_   r   r_   r  rv   r<  rv   r   rv   )r   r6   r   r_   r   r_   r   rv   )rH  r3   r  r4   r   rv   )rH  r3   r  r5   r*  rh  r   rv   r  )r   r3   rE  rv   r   r  )TFT)r   r_   r   r_   rE  rv   r1  rv   r<  rv   r   zint | tuple[int, int, bool])r6  r	  r   r	  )r  r   r   r   )rz  r_   r   rU  )r  r6  r   BaseScheduling)r  rY  r   r	  r  )r   r  r  r_  r   rv   )r   r_   r   r	  )r   r  )r   6dict[str, ir.IRNode | ir.TorchBindObject | sympy.Expr])r  list[GraphPartitionSignature]r   rU  )r  r`   r  r	  r   r  )r  list[PartitionType]r  z
list[bool]r   r	  )r  r<   r   r<   )r   z9tuple[list[PartitionType], list[GraphPartitionSignature]])r  r	  r  r	  r   rU  )r  r`   r  r<   r   rU  )r  r	  r  r	  r   z'contextlib.AbstractContextManager[None]r  r  r   z%tuple[float, float, list[str | None]])r  r  r   rv   )r  r  r   z	ir.Layoutr  )r   r	  )ory   rz   r{   r  rx  rN  rw  r  r  r  rB  propertyr  setterr  r  rr  r  r]   r  r|  rD  r{  r  rX  r  r}  r~  r  r  r  rt  rx  r}  r  r  r  r  r  r  r2  r  r  r$  r0  r4  r<  rm  r  r  r?  r  ru  r  r  r  r  r  rO  r  r  r   r   r5  r  r  r  rI  r:  r;  rQ  rR  r  rs  ru  r{  r  rc  r  r~  r  rI   r  r  r  r  r  r  r  r  r  r  r  r	  r	  r;  r.	  r8	  r2	  r	  r	  rn	  rC  ry	  ru  r[	  r~	  r	  r\	  r]	  rS  rT  s   @rl   r  r    s6   
o9b	#6
p(S
Q & & ( (7#,"HMP^KZ+#Z ,	 6	S*4#&/<$6!F	808	8, %)	*  "	
 
&
> 
>*6
>	
>)0)	)VVDp'8&'8 +'8 	'8
 '8 
'8R
 OS0AK	/ P&P/@P	Pd>  ! 3	
 
0  ! '	
 3"D2$PD2 3D2 
	D2LO?PO? @O?  L	O?
 3O? O?bS2S @S0$K$ $U$(C&C C 
!	CJ3.j?6 &6  6  
;	6 p,&,/@,	,\7&7/@7	7r.2&.2/@.2MP.2	.2`$&$/@$	$6< < !< <	<
 
<|M&M/@M	M^[
&[
/@[
	[
z ;(; ); 	;
 
;z`&`/@`	5`L "*.zM zM !zM 	zM
 $(zM 
zMx;&;/@;	;z3)3)(93)BS3)	3)r%T '7J	; !.3*.mK mK !mK 	mK
 (,mK $(mK 
%mK^d d !d 
	dLR
&R
/@R
	R
h6 Q6	:6@4@4	4	8*4
) 
&'*%5$

+:
	
=~ ! !F%	"	? '1' 
'RBH BH LBH 
"	BHHK -K @JK 	&K Z"
0"
	 "
H?&? 
!?B& 
!>%,%	 %@5&	B5&n";'"; 2"; 
	";H>0)
 )
 +)
 
	)
V-;X	06-A--A;X-A	-A^@obQ4Q	.QN5`%
H    
(1rn   c                  <    e Zd Zd fdZddZddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZ		 	 	 	 ddZ
	 	 	 	 	 	 	 	 dd	Z	 d	 	 	 	 	 	 	 dd
ZddZddZddZd dZddZ	 	 	 	 d!dZd"dZ	 	 	 	 	 	 d#dZ	 	 	 	 d$dZ	 d	 	 	 	 	 d%dZ xZS )&r	  c                0    t         |           || _        y rw   )r>  rx  r  )rk   r  rG  s     rl   rx  zBaseScheduling.__init__  s    "rn   c                R    | j                   r| j                   j                          y y rw   )r  rs  rj   s    rl   free_buffers_in_schedulerz(BaseScheduling.free_buffers_in_scheduler  s    >>NN'') rn   c                    t               S )z0Return a set of .codegen.common.BackendFeature()r   r  s     rl   get_backend_featuresz#BaseScheduling.get_backend_features  s
    |rn   c                    t         )zO
        Check whether node1 and node2 can be vertically fused or not.
        r*  r  s      rl   r   z BaseScheduling.can_fuse_vertical  
     "!rn   c                    t         )zQ
        Check whether node1 and node2 can be horizontally fused or not.
        r*  r  s      rl   r  z"BaseScheduling.can_fuse_horizontal  r	  rn   c                   |j                         }t        |t        j                        sy|j	                         syt        |j
                  t        j                        rt        |j
                  j                        dk(  xrk t        |j
                  j                  d   t        j                        xr8 |j
                  j                  d   j                         |j                         k(  S y)av  
        A Multi-Output Template (referenced in #144012) is a template node
        with MultiOutputLayout, and its output buffers are instances of MultiOutput.
        In this context, we verify whether node1 represents the Multi-Output Template
        and node2 corresponds to one of its outputs. If so, we further check if
        backend supports this fusion.

        Fr   r   )r  r   r+   ra  rV   r   r=   r   r  r  r  )rk   r   r   r  s       rl   r  z.BaseScheduling.can_fuse_multi_outputs_template  s     ..0,(9(9:557ejj"..1EJJ%%&!+ Ouzz003RYY?OJJ%%a(113|7L7L7NN rn   c                   |j                         s|j                         rt        j                  ||      S t        j	                  ||      rt        ||      S t        |t
              r|j                  |      S t        |t              rLt        |t              r<t        |j                  t        j                        sJ t        j                  ||      S t        j                  ||      S )z 
        Fuse two nodes
        )r$  ro  rr   r   r   r8  r   rT  r  r   r   r+   r@  rV  r_  r   r  s      rl   rr   zBaseScheduling.fuse  s     !1!1!3-225%@@77uE*5%8867??5))89j=?
 ejj"*D*DEEE7EEeUSS%**5%88rn   c                    t         )z[
        Process the iteration sizes in case a transformation needs to be applied.
        r*  )rk   r~  s     rl   rd  zBaseScheduling.group_fn  r	  rn   c                    t         )z
        Given a template node, generate a kernel.

        This function is only available for triton now. If the third-party backend behaves as a sub-class
        of TritonScheduling, it can override it or reuse it.
        r*  )rk   r  epilogue_nodesr  s       rl   r_	  zBaseScheduling.codegen_template  s
     "!rn   c                    t         zD
        Generate a kernel given a list of pre-fused nodes.
        r*  )rk   r  r{  rz  s       rl   rx  z.BaseScheduling.generate_kernel_code_from_nodes  s
     "!rn   c                    t         r	  r*  r%  s     rl   rd	  zBaseScheduling.codegen_node  
     "!rn   c                    t         rw   r*  r%  s     rl   rc	  z*BaseScheduling.codegen_mix_order_reduction!  r,  rn   c                    t         )zt
        Generate synchronization code for the kernel. This method depends on the hardware characteristics.
        r*  rj   s    rl   rf	  zBaseScheduling.codegen_sync$  r	  rn   c                     y)z
        Check whether the backend is requesting the scheduler to flush the generated kernel.
        If not supported, please return False.
        Fr~   rj   s    rl   rg	  zBaseScheduling.ready_to_flush*  s    
 rn   c                    t         )z]
        Flush the generated kernel and python wrapper code to the source code file.
        r*  rj   s    rl   ru  zBaseScheduling.flush1  r	  rn   c                    t         )rs  r*  rO  s     rl   rt  z$BaseScheduling.benchmark_fused_nodes7  
     "!rn   c                    t         )z
        Benchmark a compiled module and return the execution time
        in milliseconds on randomly generated inputs.
        r*  )rk   r~  s     rl   r}  z)BaseScheduling.benchmark_codegened_module@  s
    
 "!rn   c                     y)z
        Return an unsigned integer which represents the priority of this fusion pair.
        The smaller is with higher priority.
        r   r~   r  s      rl   rg  z'BaseScheduling.get_fusion_pair_priorityG  s     rn   c                    t         )z
        Benchmark the list of nodes to combine and return the execution time
        and memory copy time in milliseconds on randomly generated inputs.
        r*  )rk   r  ro	  s      rl   rn	  z%BaseScheduling.benchmark_combo_kernelP  r	  rn   c                |    |r:ddl m}  |||      }t        j                  j                  j                  ||       y y )Nr   )'set_kernel_post_grad_provenance_tracing)r  r	  rZ   r   r:  write_provenance_debug_handle)rk   node_scheduler  r	  debug_handles        rl   codegen_commentzBaseScheduling.codegen_commentY  s>    
 UBL GG  >>\ rn   )r  zScheduler | NonerT  )r  r6  r   zOrderedSet[BackendFeature]r
  r4  )r~  rQ  r   z"tuple[tuple[sympy.Expr, ...], ...])r  r_   r	  r  r  r  r   r	  rw   r	  )r   z"FusedSchedulerNode | SchedulerNoder   rU  )r   r8  r   rU  rV  r	  )r~  r   r   r	  r  r	  )r	  r  r  r	  r   rU  )ry   rz   r{   rx  r	  r	  r   r  r  rr   rd  r_	  rx  rd	  rc	  rf	  rg	  ru  rt  r}  rg  rn	  r	  rS  rT  s   @rl   r	  r	    s   #*"&"/@"	""&"/@"	"&/@	49&9/@9	9("3"	+""(" 4" 4	"
 
"$ %)		"*	" 	" "		"
 
	""""""0"	""&/@	"4"	." #'2   
	rn   r	  )r   z$torch._inductor.codecache.LocalCache)r  r_   r   r  )r  r_   r   zCallable[[Any], Any] | None)r  r_   r   rm  )r,  r   r   r  )r   r_   r  r  r@  rk  r   rU  )r  )FusedSchedulerNode | GroupedSchedulerNoder   rU  )r  r	  r  r  r   r  r   rU  )r~   )r  zlist[list[int]]r~  r  r  r  r   z	list[int])r  r	  r  r	  r   rU  r  )r
  r  r  r  r  r  r  r  r  rC   r   ztuple[int, int])r  r  r  r  r
  r  r  r  r  r  r  r  r  rC   r   rv   rV  )r   z	ir.IRNoder   r  )r   r_   r   r  )r  r_   r   rv   )r   r_   r   r_   )
__future__r   r  r6	  rZ  r  r  r  r  rB  r  r  r*  r+  rO	  rG  r   r   concurrent.futuresr   r   r   r	   r
   r   r   typing_extensionsr   torch.utils._ordered_setr   r+   r   r   collections.abcr   r   r   typesr   torch._inductor.codegen.wrapperr   r7  r   r   r  torch._inductor.async_compiletorch.utils._pytreer  _pytreer  torch._dynamo.utilsr   r    torch._inductor.autotune_processr   torch._inductor.codecacher   r   torch._inductor.irr   torch._inductor.metricsr   r    torch._inductor.stream_utilsr!   %torch.fx.experimental.symbolic_shapesr"   torch.utils._sympy.symbolr#   r$   r%   torch.utils._tritonr&   r  r'   r(   r)   r*   r,   analyze_preserves_zero_maskr-   codegen.commonr.   r/   r0   comm_analysisr1   r2   r3   r4   r5   r6   excr7   r8   fx_utilsr9   r:   r;   r<   r=   r>   r?   r  r@   r  rA   rB   runtime.hintsrC   rD   runtime.runtime_utilsrE   rF   r   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   virtualizedrZ   	getLoggerry   r  _logginggetArtifactLoggerr  r  r  r	  r   r`   r|   ra   rb   	dataclassrd   r   r   r  r]  r_   r  r  r  r  r  r  r)  rG  r  r  rA  r   r  r  r   r8  rV  ro  r  r  r  r  r  r  r]  rn  rm  r'  r-  r2  r=  rB  rD  rG  rI  rK  r  r	  r~   rn   rl   <module>r	     s   "          	     , 3 B B ' / ) << J5   $ $ $ 6 E ? 7 M 8 > O O * D D D M M ; : 2 $    J : 7 &    (  g!^^--hA
NN44XO  >>;;$  11(LI 34y 4T]t_ D D D* ( ( (Y Yx h8 h8 h8V 1_ 1 1H1 H1V 2 2,' #L T"
 
 #
*  *K
*K4*K ,*K 
	*KZ"* 1 "*J5. 5S*% S*l
:	$: $ 
	8k** k*\[G0 [G|:-+= :-zC:!3 C:Lb, bP #%+#++  + 	+\0%01C0	08
1((( ( 	(
 #( (6		  	
   # 
@ 
 
 
> +9??, 4$
&""P@nJ1 nJ1bUx xrn   