
    `i                      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mZ d dlmZ d dlmZmZmZmZmZmZ d dlZd dlmZ d dlZd dlZd dlZd dlmZmZ d dlmZ d d	lmZm Z  d d
l!m"Z" d dl#m$Z$ d dlm%Z%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; d dl<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZC ddlDmEZEmFZFmGZG ddlHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZRmSZSmTZTmUZU ddlVmWZW ddlFmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZc ddldmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZp ddlqmrZr ddlsmtZt dd lumvZv dd!lwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZ dd"lmZmZ er>d d#lmZmZmZ d d$lmZ d d%lmZ d d&lmZ d d'lmZ dd(lmZ dd)lmZ dd*lmZ eeeKf         Zd d+lmZ  ej        e          Zej                            ed,          Zej        j        Z ej                    Z eEj                    rd d-lmZ ndKd3ZdLd7ZdMd:ZdNd@ZdOdDZdPdFZ G dG dHej        j                  Z G dI dJe          ZdS )Q    )annotationsN)defaultdict)contextmanager)AnyCallableNoReturnOptionalTYPE_CHECKINGUnion)Expr)deviceTensor)get_decompositions)defakedynamo_timed)FakeScriptObject)get_layout_constraint_tag)
LazyStringtrace_structured)compute_required_storage_lengthmake_channels_last_strides_for)
FakeTensor)full_aoti_runtime_assert)BackwardState)magic_methodsmethod_to_operator)_get_placeholder_exprfree_unbacked_symbolshas_free_symbolsresolve_unbacked_bindingsRuntimeAssertShapeEnvSympyBooleanSymTypes)Node)no_dispatch)
OrderedSet)int_oo   )configirmetrics)BackendFeatureDeviceOpOverridesFileBackedGraphModuleget_backend_featuresget_device_op_overridesget_wrapper_codegen_for_deviceinit_backend_registrationWorkspaceArg)CppWrapperCodegenErrorLoweringExceptionMissingOperatorWithDecompMissingOperatorWithoutDecomp)count_flops_fx)ConstantDonatedBufferFixedLayoutget_device_typeGraphPartitionSignatureInputBuffer	Pointwise	ReductionShapeAsConstantBuffer
StorageBox	TensorBoxTorchBindObject)constrain_to_fake_tensorsconstrain_to_fx_stridesFALLBACK_ALLOW_LISTfallback_handler%fallback_node_due_to_unsupported_type	loweringsmake_fallbackmaybe_layout_constraintsneeds_realized_inputsrequire_contiguoustag_to_layout_constraintunsupported_output_tensor)autotune_cache)AutotuneCacheBundler)SizeVarAllocator)convert_shape_to_inductorgather_origins get_cloned_parameter_buffer_nameget_donated_idxsget_sympy_Expr_dtypeGraphPartitionMapis_same_tensor#maybe_get_suppress_shape_guards_ctxnormalize_nameshould_assume_input_alignedSUPPORTED_MKLDNN_DEVICESValueWithLineMap)NullHandlerV)IterableIteratorSequence)
ModuleType)_EffectType)GraphModule)Graph)PythonWrapperCodegen)Dep)BaseSchedulerNode)output_code_log
perf_hints)log_module_codeargsr   kwargsreturnNonec                     d S N )rp   rq   s     i/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/torch/_inductor/graph.pyro   ro      s        constant_buffer
sympy.ExprOptional[torch.dtype]c                   t          | t          j        t          j        t          j        j        j        f          s
J d            t          | t          j        j        j                  rt          j        S t          | t          j                  rt          |           S | j
        rt          j        S | j        rt          j        S d S )Nzgget_constant_buffer_dtype only supports input of sympy.Symbol, sympy.Expr or sympy.core.numbers.Integer)
isinstancesympySymbolr   corenumbersIntegertorchint64rY   
is_integeris_floatfloat32)ry   s    rw   may_get_constant_buffer_dtyper      s    %,
EJ4F4NO    	r  
 /5:#5#=>> {/5:.. 5#O444! {		! }trx   opboolc                F    t          d t          D                       }| |v S )Nc              3  4   K   | ]}t          |          V  d S ru   )r   ).0ms     rw   	<genexpr>z"is_magic_method.<locals>.<genexpr>   s+      HHQ-a00HHHHHHrx   )r'   r   )r   	magic_opss     rw   is_magic_methodr      s(    HH-HHHHHI?rx   objrh   targetstr1Union[Tensor, torch._C.ScriptObject, GraphModule]c           	         |                     d          }| }t          |          D ]R\  }}t          ||          s-t          dd                    |d |                              t          ||          }S|S )N.z#Node referenced nonexistent target )split	enumeratehasattrRuntimeErrorjoingetattr)r   r   target_atomsattr_itriatoms         rw   getattr_recursiver      s     <<$$LH\** + +4x&& 	Rchh|BQB?O6P6PRR   8T**Orx   gri   dict[Node, tuple[int, ...]]c                J   i }|                      d          d         }d|j        vr|S t          |j        d         t          j        j                  s|j        d         }n|j        }t          |          D ]*\  }}||j        d         v r|j        d         |         ||<   +|S )Noutputr   r   user_visible_output_idxsoriginal_output_strides)
find_nodesmetar}   rp   r   fxr%   r   )r   retoutput_nodeoutput_node_argsidxnodes         rw   get_user_visible_output_stridesr      s    ')C,,(,++A.K!)999
k&q)58=99 ,&+A.&+/00 I I	T+"#=>>>#()BCCHCIJrx   user_visible_output_stridesc                   t           j        sdS t          t          j        t          j        t          j        g          }t          t          j        t          j        t          j	        t          j
        t          j        t          j        t          j        t          j        t          j        t          j        t          j        t          j        g          }d
d}t'          | j                  D ]	}t+          |j        t.          j        j        j                  rd|j        d<   7t+          |j        t.          j        j                  r7t=          |j                  t.          j        j         j!        k    rd|j        d<    ||          }|s||v r
d|j        d<   |j        "                    dd	          r&|j#        D ]} ||          }|s||vr
d|j        d<   t           j$        s||v r
d|j        d<   dS )a  
    Nodes like convolution/convolution_backward want its input to be dense.
    If we pad their inputs, we result in extra calls to copy kernels!  On the other hand, padding usually helps reduction.

    The pass finds nodes that dislike padding. These are nodes that can be reached
    from a convolution/convolution_backward in the backward direction without
    going thru a reduction.
    Nr   torch.fx.Noderr   %Optional[torch._ops.OpOverloadPacket]c                    | j         dk    rEt          | j        t          j        j                  r!t          | j        d          r| j        j        nd S )Ncall_function_overloadpacket)r   r}   r   r   _ops
OpOverloadr   r   )r   s    rw   _get_overload_packetz8mark_nodes_dislike_padding.<locals>._get_overload_packet   sX    
 w/))4;
(=>> * %677 * K''
 	
rx   Tdislike_paddingF)r   r   rr   r   )%r*   comprehensive_paddingr'   atenconvolutionconvolution_backward
_scaled_mmvar_meansummeanprodanyaminamaxminmaxargminargmaxscatter_reducereversednodesr}   r   r   _higher_order_opstriton_kernel_wrapTritonKernelWrapperMutationr   r   r   r   _CTagneeds_exact_stridesgetall_input_nodespad_outputs)	r   r   ops_dislike_paddingops_like_paddingr   curr   priorprior_ops	            rw   mark_nodes_dislike_paddingr      s    ' $%O	
  "MHIIHIIHHKK	
 "

 

 

 

     /  /J#6R
 
 	 +/CH&' sz5:#899	)#*55x|/0 0 +/CH&'!!#&& 	$$$*.CH&'8<<)511 	9, 9 9//66 #33348EJ01! 	/c-H&H&H*.CH&'A /  /rx   c                      e Zd ZU ded<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd fd$Zdd%Zdd)Zdd+Zdd/Zdd2Z	dd7Z
dd;Zdd=Zej        dd?            ZddAZeddC            ZddDZddHZddJZddKZddLZeddN            ZddQZddTZddVZddXZddZZdΈ fd]Zdd`Z ddaddeZ!ddhZ"ddkZ#ddlZ$ddmZ%ddpZ&	 dddsZ'ddvZ(d؈ fd|Z)dو fdZ*edd            Z+ddZ,ddZ-ddZ.d݈ fdZ/ddZ0edd            Z1edd            Z2ddZ3d fdZ4ddZ5ddZ6	 	 	 	 dddZ7ddZ8ddZ9ddZ:ddZ;ddZ<ddZ=dZ>ded<   ddZ?ddZ@ddZAddZBddZCddZD xZES )GraphLoweringlist[ir.IRNode]graph_outputsNFgmtorch.fx.GraphModuleexample_inputsOptional[Sequence[object]]	shape_envOptional[ShapeEnv]graph_idOptional[int]cpp_wrapperr   aot_mode
layout_optOptional[bool]extern_node_serializer4Optional[Callable[[list[ir.ExternKernelNode]], Any]]is_inferenceis_backwardis_const_graphconst_output_indexOptional[dict[str, int]]const_wrapper_codeOptional[str]const_kernel_codeconst_moduleOptional[GraphLowering]nameinputs_to_checkOptional[Sequence[int]]
fx_wrapperrr   rs   c                (   t                                          |           || _        ||n|                     ||	          | _        d| _        |	| _        |
| _        || _        || _	        || _
        || _        || _        d| _        |t                      }d| _        nd| _        || _        |j                                        | _        t)          t*          j                             | _        t1          |          | _        g | _        i | _        i | _        d | _        t)                      | _        |r|j        nt)                      | _        |r|j         nt)                      | _         d| _!        i | _"        g | _#        g | _$        |r|ni | _%        |r!t)          |&                                          nt)                      | _'        |r|j(        ni | _(        |r|j)        ni | _)        |r|j*        ni | _*        i | _+        i | _,        i | _-        t)                      | _.        t)                      | _/        t)                      | _0        t)                      | _1        t)                      | _2        t)                      | _3        d | _4        d | _5        ddl6m7} tq          j9                    r|r|n|| _:        d | _;        i | _<        t)                      | _=        g | _>        i | _?        t          t                    | _B        i | _C        t          jD                    | _E        || _F        || _G        || _H        || _I        i | _J        || _K        || _L        t          t                    | _O        d | _P        d | _Q        d | _R        d | _S        d | _T        | j        r| U                                nt)                      | _V        t)          dg          | _W        t          |jY                  | _Z        t          |jY        | jZ                   d| _\        d| _]        g | _^        d | __        i | _`        |a                                | _b        | jb        )                                D ]\  }}|| j)        |<   | jb        *                                D ]\  }}|| j*        |<   | jc        jd        e                    d	i           | _f        ||jg        ni | _g        t                        t          jj        d           t                    | _k        i | _l        t)                      | _m        t)                      | _n        t)                      | _o        t)                      | _p        t)                      | _q        t          js                    | _t        d
| _u        t                      | _w        i | _x        d S )N)r   r   FTcpu)extern_node_json_serializerzaten.convolution_backward  dynamo_flat_name_to_original_fqn)ysuper__init__r   decide_layout_optr   num_channels_last_convr   r   r   r   r   r   r   extra_tracebackr"   reuse_shape_env
_shape_envdeferred_runtime_assertscopyras_by_symbolr'   r~   r   bound_unbacked_symbolsrT   sizevarsgraph_input_namesgraph_inputsgraph_inputs_originalpartition_mapszero_dim_cpu_tensor_listdevice_typesdevice_idxsdevice_typebuffer_to_padded_sizebuffers
operationsr   keysfolded_constants	constantsnamed_buffersnamed_parameterstorchbind_constantsseen_subgraphsconstant_reprsremoved_operationsremoved_buffersremoved_inplace_buffersmutated_buffersnever_reuse_buffersinplaced_to_remove
device_opswrapper_code&torch._inductor.extern_node_serializerr  r*   	is_fbcoder   current_nodelistsmutated_inputsmutated_input_idxsname_to_bufferr   listname_to_users
name_to_optimecreation_timer   r   r   record_multi_kernel_choicemulti_kernel_to_choicer   r   next_post_grad_graph_counterpost_grad_graph_id	schedulerautotuning_inputsautotuning_mappingautotuning_gridscurrent_devicefind_nodes_prefer_channels_lastnodes_prefer_channels_last_warned_fallbackr   graphr   r   	cache_key
cache_pathcache_linemapdisable_cudagraphs_reasondevice_node_mapping__copy__orig_gmmoduler   r   r  allocated_constant_namer3   	functools	lru_cacher0   effectful_opsunaligned_buffersno_fuse_buffer_nameslow_precision_codegen_opsinvoke_quant_opsall_codegen_kernel_names	itertoolscountworkspace_idplaceholder_idxrX   bw_donated_idxsdep_size_hint_cache)selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  kv	__class__s                         rw   r  zGraphLowering.__init__&  s   . 	, % J'''FF 	
 '(#(&,"4!2(.$ 

I#(D  #'D # .3355 	 '1&>&@&@#(33,.VX=?"AE9C%)5GL%%:<< 	 )5FL$$*,, 	 ! <>"(*.0"4<" 	
 "J)..00111 	 '3:L"" 	 +7>L&&B 	 .:AL))r 	
  	  79.03=<<0:8B$0:4>LL 3=<<-126VVVVVV !!-&<-"", 	# ,0+-
/9||-/46@KD@Q@Q35!Y[[	&$
 +6'68#  "&'?"@"@>B @DGK:> 7; 7;oWD00222:<< 	' !+,G+H I I+J28+T+T("28T-MNNN !  	 9=& GI -/[[]]L..00 	& 	&DAq$%Dq!!L1133 	) 	)DAq'(D!!$$040@0D0D.1
 1
- 5A4LL00RT 	$ 	"###$=I$7$=$=>R$S$S!;= 3=,,5?\\!:D,,&1; :D% &O--  "/11 46   rx   c                8    | j                                          d S ru   )r  freeze_runtime_assertsr^  s    rw   rc  z$GraphLowering.freeze_runtime_asserts  s    ..00000rx   extorch.Tensor=tuple[Sequence[Union[int, Expr]], Sequence[Union[int, Expr]]]c                `   | j         rBt          |                                          t          |                                          fS ddlm}  |dt          | j        j                             }| j        	                    ||          \  }}}d |D             }d |D             }||fS )z
        Support dynamic shapes and dynamic strides by assigning variables
        to each dimension.  We duck-shape tensors, so if two tensors
        have the same size they get assigned the same symbolic variable.
        r   )ConstantSource__inductor_unknown_tensor_c                ^    g | ]*}t          |t          j                  r|j        j        n|+S rv   r}   r   SymIntr   exprr   r   s     rw   
<listcomp>z8GraphLowering.symbolic_sizes_strides.<locals>.<listcomp>  s1    RRRAu|!<!<C!&++!RRRrx   c                ^    g | ]*}t          |t          j                  r|j        j        n|+S rv   rl  ro  s     rw   rp  z8GraphLowering.symbolic_sizes_strides.<locals>.<listcomp>  s1    VVV!:a#>#>EAFKKAVVVrx   )
r  rU   sizestridetorch._dynamo.sourceri  lenr  
var_to_val,create_symbolic_sizes_strides_storage_offset)	r^  re  ri  sourcerr  rs  _r_sizer_strides	            rw   symbolic_sizes_stridesz$GraphLowering.symbolic_sizes_strides  s      	,RWWYY779R		: :   <;;;;; $^NS1K-L-LNN F LL 	 SRTRRRVVvVVVxrx   )tuple[list[sympy.Expr], list[sympy.Expr]]c                    d |                                 D             }d |                                D             }||fS )z+
        Primarily used to weights
        c                6    g | ]}t          j        |          S rv   r~   r   ro  s     rw   rp  z6GraphLowering.static_sizes_strides.<locals>.<listcomp>  s"    444Qa  444rx   c                6    g | ]}t          j        |          S rv   r  ro  s     rw   rp  z6GraphLowering.static_sizes_strides.<locals>.<listcomp>  s"    888q%-""888rx   )rr  rs  )r^  re  rr  rs  s       rw   static_sizes_stridesz"GraphLowering.static_sizes_strides  sD     54"''))44488BIIKK888V|rx   r   OUnion[ir.TensorBox, ir.StorageBox, ir.Buffer, WorkspaceArg, ir.TorchBindObject]Sequence[Expr]c                "   t          |t          j                  r|j        }t          |t          j                  r|j        }t          |t          j                  r |j        | j        v r| j        |j                 S |                                S ru   )	r}   r+   rD   datarC   ComputedBufferr   r  get_size)r^  r   s     rw   get_allocation_sizez!GraphLowering.get_allocation_size  s}     dBL)) 	9DdBM** 	9DtR.//	#	T777-di88==??"rx   2Union[ir.Buffer, WorkspaceArg, ir.TorchBindObject]r   c                    |                                 }|                     |          }|j        }|j        }t	          |||          S ru   )
get_layoutr  rs  offsetr   )r^  r   layoutrr  rs  r  s         rw   get_allocation_storage_sizez)GraphLowering.get_allocation_storage_size1  sF     ""''--.tVVDDDrx   r   .Union[torch._inductor.ir.IRNode, device, None]featurer-   c                    t          |t                    s
J |            ||                     t          |                    v S ru   )r}   r-   r0   r=   )r^  r   r  s      rw   has_featurezGraphLowering.has_feature:  sC    
 '>22;;G;;2$33OF4K4KLLLLrx   deprk   intc                    || j         vrFd}	 |                                s|                                }n# t          $ r Y nw xY w|| j         |<   | j         |         S )zc
        Get the size hint for a dependency with caching to avoid expensive recomputation.
        r   )r]  has_unbacked_symbolsnumbytes_hintKeyError)r^  r  ress      rw   get_dep_size_hintzGraphLowering.get_dep_size_hintB  s     d...C//11 .++--C    	
 -0D$S)',,s   (6 
AAtorch.devicec                6    | j         x}r|S t          d          )NzNo current device)rB  r   r^  r   s     rw   get_current_device_or_throwz)GraphLowering.get_current_device_or_throwS  s&    ((6 	4M2333rx   Iterator[None]c              #  V   K   | j         }|| _         	 d V  || _         d S # || _         w xY wru   )rB  )r^  r   r   s      rw   set_current_devicez GraphLowering.set_current_deviceY  sF      #$	(EEE"'D%D''''s    	(r   c                *    | j         rdS | j        rdS dS )N	inferencebackwardforward)r   r   rd  s    rw   get_training_phasez GraphLowering.get_training_phaseb  s'     	; 	:yrx   rh   c                  t           j        sdS t           j        rdS d | j        j        D             }t          |          }|dk    rdS t          j        j        j	        r>t          j        j        
                                rt          d |D                       rdS t          t          | j        j                            d|z  k    rt                              d           dS t          d |D                       rt                              d	           dS d d}d!d}d!d}|rt!          t"                    }|D ]P}t%          |          }	|	 ||          rd}
n ||          rd}
n ||          rd}
nd}
||
xx         |	z  cc<   Qt                              d           d}d}d}d}t'          |                                          }|d         |z  |d         |z  z   |d         |z  z   |d         |z  z   }||k    }|st                              d||           |S t          t+          ||                    rt                              d           dS t          t+          ||                    rt                              d           dS t          t+          ||                    rt                              d           dS dS )"zl
        Decide if we should enable layout optimization for this graph based on
        heuristics.
        FTc                Z    g | ](}|j         t          j        j        j        j        k    &|)S rv   )r   r   opsr   r   default)r   ns     rw   rp  z3GraphLowering.decide_layout_opt.<locals>.<listcomp>u  s5     
 
 
UY^5O5W)W)WA)W)W)Wrx   r   c              3  r   K   | ]2}d D ]-}|j         |         j        d         j        j        t          v V  .3dS )r   r)   valN)rp   r   r   typer_   r   r  r   s      rw   r   z2GraphLowering.decide_layout_opt.<locals>.<genexpr>  sg        !   s '.37OO      rx   i,  z*Skipped layout opt because only a few convc              3  j   K   | ].}d D ])}t          |j        |         j        d                   V  */dS r  )r   rp   r   r  s      rw   r   z2GraphLowering.decide_layout_opt.<locals>.<genexpr>  sc       
 

 
  QVC[-e455
 
 
 
 
 
 
rx   zeSee perf regression with dynamic shape. Follow up in https://github.com/pytorch/pytorch/issues/102670r  r   rr   r   c                    | j         d         j        d         }t          |t          j                  sJ | j         d         dk    o|                    d          dk    S )Nr)   r  r  )rp   r   r}   r   r   rr  )r  meta_vals     rw   
is_groupedz3GraphLowering.decide_layout_opt.<locals>.is_grouped  sR    vay~e,Hh555556":>:hmmA&6&6&::rx   r   c                   | j         d         j        d                             d          dz  | j         d         j        d                             d          k    o.| j         d         j        d                             d          dk    S )Nr)   r  r      rp   r   rr  r  s    rw   is_in_out_channelz:GraphLowering.decide_layout_opt.<locals>.is_in_out_channel  ss    q	u%**1--1QVAY^E5J5O5OPQ5R5RR 6F1IN5)..q11A5rx   c                    | j         d         j        d                             d          dk    o.| j         d         j        d                             d          dk    S )Nr)   r  r   @   r  r  s    rw   is_small_channelz9GraphLowering.decide_layout_opt.<locals>.is_small_channel  sR    q	u%**1--3 8F1IN5)..q11R7rx   Ngroupedsmallin_outr  zConv inputs meta not foundg|?5^?gtV?g333333?guV?zhSkipped layout opt in inference because weighted flops indicate slowdown, default: %d, channels last: %dzFSkip layout opt because found grouped convolution with >1 in_channels!zBSkip layout opt because some convolutions have smaller out_channelz>Skip layout opt because all convolution channels are too small)r  r   rr   r   )r  r   rr   r   )r*   layout_optimizationforce_layout_optimizationrF  r   ru  r   backendsmkldnnenabledis_availableallr4  logdebugr   r   floatr9   r   valuesmap)r   r   
conv_nodesnconvr  r  r  flop_countsr   counted_flops	node_typeGROUPED_MULTIPLIERDEFAULT_MULTIPLIERIN_OUT_MULTIPLIERSMALL_MULTIPLIERtotal_flopsweighted_flopsdo_layout_opts                     rw   r  zGraphLowering.decide_layout_opti  s    ) 	5+ 	4
 
x~
 
 

 JA::5 N!)		%2244		   #    		 4
 tBHN##$$e33IIBCCC5 
 

 
 
 
 
 	
 IIw   5	; 	; 	; 	;
	 	 	 		 	 	 	  +	!,7,>,>K" 8 8 .t 4 4 (:d## * )II%%d++ * 'II&&t,, * (II )II&&&-7&&&&		6777
 "'!& %$k002233K I&);;g&)99:h'*;;< i(+==>  +k9M  		~"  
 ! & s:z**++ 	IIX   5 s$j1122 	IIT   5 s#Z0011 	IIVWWW5trx   c                ,    | j         | j          d| S |S )z2Prepend the given name with the graph name if any.Nry  r   r^  r   s     rw   qualify_namezGraphLowering.qualify_name  s%    9 i(($(((rx   list[torch.Tensor]subgraph_nameSubgraphLoweringc                    t          | ||| j        | j        | j        | j        | j        | j        |                     |          
  
        S )a  
        Make a subgraph of the current graph with all inherited parts, except
        the graph module (`gm`) and `example_inputs`.  The subgraphs are lowered
        separately and lifted into a separate function in the parent output
        wrapper code.  The subgraph name is qualified by the parent graph's
        name. Note that the lifting of subgraph is supported for python wrapper
        only. For cpp wrapper, we inline the subgraphs in the parent wrapper.
        )
parentr   r   r   r   r   r   r   r   r   )r  r  r   r   r   r   r   r  )r^  r   r   r  s       rw   make_subgraphzGraphLowering.make_subgraph  sW      )o(]#'#>*(""=11
 
 
 	
rx   OrderedSet[Node]c                   t          t                               }t          | j        j        j                  D ]a}|j        t          j        j	        j
        j        k    r|                    |           <|j        D ]}||v r|                    |            nb| j        j        j        D ] }||v r|                    |j                   !|S )aC  
        The rule to decide if an node prefer channels last is simple.
        1. if it's input/output of a convolution
        2. if one of its user prefers channels last

        We have rule 1 because cudnn runs a faster convolution kernel for channels last inputs;
        Rule 2 is also important. It makes sure that indirect inputs to convolution also prefers
        channels last.

        Consider the scenario: conv -> batch-norm -> relu -> conv
        Without rule 2, batch-norm output may use a contiguous layout. That will cause 2 extra copies:
        1. the output of batch-norm should be channels last initially since its input is a conv's output.
           Forcing the batch-norm's output to be contiguous results in the first copy
        2. The second conv's input is initially contiguous. This layout is propagated from the batch-norm's output.
           We need convert it to channels last layout which results in the second copy.
        With rule 2, we makes sure all the tensors in the chain uses channels last layout. So both copies
        can be saved.
        )r'   r%   r   rN  rF  r   r   r   r  r   r   r  addusersupdate)r^  
output_setr  users       rw   rC  z-GraphLowering.find_nodes_prefer_channels_last&  s    &  %''
$++122 	 	Ax59>5===q!!!  :%%NN1%%%E &$ "( 	+ 	+AJ!!!'***rx   c                    || j         vr7| j                             |           t                              d|           d S d S )NzUsing FallbackKernel: %s)rE  r  perf_hint_loginfor  s     rw   warn_fallbackzGraphLowering.warn_fallbackX  sL    t,,,!%%d+++94@@@@@ -,rx   c                    | j                             |j                   |j        | j                            |j                   t
          j        j        r$|| j        vrt
          j        j        | j        |<   d S d S d S ru   )	r  r  r  indexr  rb   rF  r/  rK  r  s     rw   add_device_infozGraphLowering.add_device_info]  s    fk***<#  ...7 	DF$2J$J$J/0w/CD$V,,,	D 	D$J$Jrx   ,torch._subclasses.fake_tensor.FakeTensorModec                    t           j        S ru   )rb   	fake_moderd  s    rw   r  zGraphLowering.fake_moded  s
    {rx   buffer_name<Optional[Union[ir.TensorBox, ir.Buffer, ir.TorchBindObject]]c           	     :   || j         v r| j         |         S || j        v r| j        |         S || j        v ret          j        j        |         }t          j        |t          j        |j        |j	        gt          j        
                    |          R            S d S Nr   r  )r3  r  r  rb   rF  r+   ConstantBufferr<   r   dtyper  )r^  r  r  s      rw   try_get_bufferzGraphLowering.try_get_bufferh  s     $---&{33$+++$[11$.((7$[1D$ ~K./g.J.J4.P.P      trx   symbolrz   c                     t          d          )Nz'Should not be called for the main graph)r   )r^  r  s     rw   add_symbol_graph_inputz$GraphLowering.add_symbol_graph_inputz  s    DEEErx   2Union[ir.TensorBox, ir.Buffer, ir.TorchBindObject]c                X    |                      |          }||S t          d|           )Nz$Failed to find buffer matching name )r  r   r^  r  bufs      rw   
get_bufferzGraphLowering.get_buffer}  s8     !!+..?JO+OOPPPrx   torch.dtypec                   || j         v r| j         |         j        S t          | j        d          rp|| j        j        v rb| j        j        |         }|| j        v r| j        |                                         S || j        v r| j        |                                         S || j        v r| j        |                                         S || j        v r| j        |                                         S t          j	        d|          }|r(|                     |
                    d                    S t          d|           )Nmutation_real_namez1(as_strided|reinterpret_tensor)\(([a-zA-Z0-9_]+),r)   could not find )r  r  r   r>  r  r3  	get_dtyper  rematchgroupr  )r^  r  mutated_bufr   s       rw   r  zGraphLowering.get_dtype  sC   $.((>+.44 DN$899	Bt~@@@.;KHKd111*;7AACCCd///(5??AAA$---&{3==???$+++$[1;;===HI;WW 	.>>!''!**---666777rx   Union[int, Expr]c                F   || j         v r| j         |                                         S || j        v r7| j        |         }|                                sdS |                                S || j        v r| j        |                                         S t          d|           )Nr)   r  )r  numelr3  has_tensor_output	get_numelr  r  r  s      rw   r  zGraphLowering.get_numel  s    $.((>+.44666$---%k2C((** q==??"$+++$[1;;===666777rx   rp   r   c                    t          d          5   t                      j        | cd d d            S # 1 swxY w Y   d S )NzGraphLowering.run)r   r  run)r^  rp   ra  s     rw   r  zGraphLowering.run  s    -.. 	& 	&577;%	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   488r   ir.Operationc                   |j         J d|             t          |t          j                  sJ |                     dt          | j                             }| j                            |           || j        |<   ||_         |S )NzOperation registered twice: r   )	operation_namer}   r+   	Operationr  ru  r  appendr6  )r^  r   r   s      rw   register_operationz GraphLowering.register_operation  s     ((*M*M*M((("bl+++++  !<c$/&:&:!<!<==r""" " rx   set_namebuffer	ir.Bufferr  c                  |                      dt          | j                             }| j                            |           || j        |<   |                                }|[t          |t          j                  r,|	                                r|t          j        d          k    s|                     |           |r||_        |S )Nr  r  )r  ru  r  r  r3  
get_devicer}   r+   r  is_zero_elementsr   r   r  r   )r^  r  r  r   r   s        rw   register_bufferzGraphLowering.register_buffer  s      !:s4<'8'8!:!:;;F###$*D!""$$ 62#455  ++--  el51111   ((( 	FKrx   operation_names	list[str]c                p    |                      dd                    |          z             }|| j        |<   |S )Nlist_ry  )r  r   r0  )r^  r"  r   s      rw   register_operation_listz%GraphLowering.register_operation_list  s7      388O+D+D!DEE*
4rx   node_output%Union[Iterable[ir.IRNode], ir.IRNode]c                .     d fd |           d S )Nvaluer(  rr   rs   c                   t          | t          t          f          r| D ]} |           t          | t          j                  r7|                                 D ]$}j        |                             |            #d S d S ru   )r}   r4  tupler+   rD   get_read_namesr5  r  )r*  x	read_nameregisterr^  s      rw   r0  z1GraphLowering.register_users_of.<locals>.register  s    %$//      AHQKKKK%.. @!&!5!5!7!7 @ @I&y188????@ @@ @rx   )r*  r(  rr   rs   rv   )r^  r'  r0  s   ` @rw   register_users_ofzGraphLowering.register_users_of  sF    	@ 	@ 	@ 	@ 	@ 	@ 	@ 	rx   c                    t          |t                    sJ | j                            |           || j        vrdS | j        |         D ]}|                                 dS )z
        When a buffer is mutated we need to make sure all the reads to
        the old version are realized before the mutation happens.
        N)r}   r   r(  r  r5  realize)r^  r   r  s      rw   mark_buffer_mutatedz!GraphLowering.mark_buffer_mutated  st    
 $$$$$$  &&&t)))F&t, 	 	DLLNNNN	 	rx   c                    || j         v r	|| j        v sJ d|z               t          | j         |                   }|| j        j        v r| j        j        |         n| j        |         S )z
        In AOTI, module buffers may have been mutated during the tracing and compilation.
        Thus we need to read from previously stored original buffers, to make sure the
        generated model.so uses correct initial values.
        z$Can not find the original value for )rO  r  rW   rN  r   )r^  r   	orig_names      rw   get_original_value_of_constantz,GraphLowering.get_original_value_of_constant  s     t3338N8N8N2T9 9O8NN 5T5QRV5WXX	 DK,,, KY''%	
rx   r  Union[Tensor]c                   t           j        j        s3| j                                        D ]\  }}t          ||          r|c S |dt          | j                   }|}|d                                         rd| }|                     |          }t          |          }|}d}|| j        v r| d| }|dz  }|| j        v || j        |<   |j
        d|j        dt          |                                          dt          |                                          dt          |          d	| j        |<   || j        |<   |S )Nconstantr   	constant_ry  r)    r.  )r*   aot_inductoruse_runtime_constant_foldingr  itemsr[   ru  isdigitr  r]   r   r  r,  rr  rs  hashr$  rO  )r^  r   r  constant_namer*  r6  prefixcnts           rw   allocate_non_dup_const_namez)GraphLowering.allocate_non_dup_const_name  s    "? 	)(,(<(<(>(> ) )$u!$.. )(((() <3c$.1133D	7?? 	&%t%%D  &&  %%dn$$$$s$$D1HC dn$$  $t{  tz  TYY[[!! &+DKKMM&:&: Dzz  	D!
 .7$T*rx   r   *Union[TensorBox, ir.ShapeAsConstantBuffer]c                    |                      ||          }t          j        t          j        |t          |j        |j        g|                     |          R                      S r  )	rE  rD   creater+   r  r<   r   r  r  )r^  r  r   new_names       rw   add_tensor_constantz!GraphLowering.add_tensor_constant  sw     33D$??"K.2.G.G.M.M    
 
 	
rx   device_overrideOptional[torch.device]c                >   | j         |         j        |k    s||S t          j        j                                        5  |                     | d|j         |j        pd | j         |         	                    |                    cddd           S # 1 swxY w Y   dS )z
        We AOT copy constants to the devices they are needed on.
        If device_override doesn't match the constant's device, then
        copy it and return a different name.
        Nry  r   )
r  r   r   utils_python_dispatch_disable_current_modesrE  r  r  to)r^  r   rK  s      rw   rB  zGraphLowering.constant_name$  s     >$&/99_=TK[)@@BB 	 	 33LL/.L0E0JLLt$''88 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   ABBBr   tuple[object]rq   dict[str, object]Union[Expr, TensorBox, None]c                j   | xj         dz  c_         t                                          |||          }|                     |          }t	          |t
                    rXt          j        j        st          |j
                  }n|j
        j        }|| j        |<   | j                            |           |S t	          |t          t           t"          f          r:t%          j        |          }|| j        |<   | j                            |           |S t	          |t(                    r7t+          ||          }|| j        |<   | j                            |           |S || j                            |           d S t	          |t,                    r| j                            |           d S t	          |t.          j                  rt3          t          j        j        j                  dk    rat9          t;          t          j        j        j                            j        t.          j        j         j!        t.          j"        j#        j$        fv sJ tK          j&        ||j'                  }|| j        |<   | j                            |           |S t	          |t.          j(                  s
J |            |j)        s| *                    |          \  }}	n| +                    |          \  }}	| j        rS| j,        rL| j         | j,        v r>t[          j.        t_          |ta          |j'        |j1        ||	                              }
n=t[          j.        te          |ta          |j'        |j1        ||	                              }
|
| j        |<   | j                            |           |
j3        j3        | j4        |<   | j        j        r| 5                    |j'                   tm                      5  to          |          s| j8        9                    |           d d d            n# 1 swxY w Y   |
S )Nr)   r   r*  )r   r   r  ):r[  r  placeholderr  r}   r$   rb   rF  r   r   r   rn  r  r  r  r  r   r  r~   sympifyr   rE   r   r   	Generatorru  r/  r  r;  iterr   _prims	rng_primsgraphsafe_run_with_rng_stater  higher_orderinvoke_subgraphr+   GeneratorStater   r   _has_symbolic_sizes_stridesr  r|  r\  rD   rH  r;   r<   r  r?   r  r  r  r\   r^   rS  r  )r^  r   rp   rq   examplern  r   gensizesstridestensorra  s              rw   rW  zGraphLowering.placeholder4  sP    	!''%%fdF;;""6**gx(( 	 7& ),W\::|((,Df%"))&111K#tU!344 	=))D(,Df%"))&111K!122 	!vW===C(+Df%"))&111J_"))&1114g}-- 	 "))&111411 
	qw+122a77DQW)/00= =&C	&6= = =  #GGGC(+Df%"))&111J'5<0099'990
 2 	B!66w??NE77!88AANE7 	$	 $(<<<%&w~w}eWUU   FF %&w~w}eWUU   F %+&!%%f----3[-="6*" 	1  000 122 	3 	3.w77 3&**6222	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 s   2*P((P,/P,r   dict[str, Any]c                   t           j        u rKt          |d         t          t          t
          f          r#t                                          ||          S t          t          j	        j
                  st          d          r |i |S t          vrzt          t          j	        j                  sJ  d                                                                d          d         }|t           v rt#          dd           nt$          j        rt)          g          rt*          nt,          }t.                              d|                    ||                     t5          d	          }|3t          j        j                                      r| j        rt>          }n t5          d	          }tA          |          }t#          |
           n2t)          g          rt+          ||          t-          ||          	 t.          !                    dt                              | j"        }	tG                    }
|
r||}}|
tH          u rd|	j%        v ry|	j%        d         \  }}t          t          j	        j                  sJ dfd} |||          \  }} |||          \  }} |||          \  }}tI          ||||          \  }}n |
|	g|R i |\  }}t                   |i |}|
r| &                    |	||||           |S # tN          $ r0}tQ          |||          )                    |j*                  d d }~ww xY w)Nr   _inductor_lowering_functionz is not an OpOverloadr   FT)warnoverride_decompz"Creating implicit fallback for:
%s)with_default)layout_constraintz  via %seager_input_valsrp   r   rq   rr   tuple[Any, Any]c                x    t           j        j                            | |          }|J |d         |d         fS )Nr   r)   )r   r   operator_schemasnormalize_function)rp   rq   resultr   s      rw   	normalizez.GraphLowering.call_function.<locals>.normalize  sE    %*X%>%Q%Q &f& &F $*#5#5#5#)!9fQi#77rx   )rp   r   rq   r   rr   ro  )+operatorgetitemr}   r4  r,  dictr  r   r   r   OpOverloadPacketr   rK   r   r   r   rH   rL   r*   implicit_fallbacksr   r7   r8   r  r  operator_strr   _libraryrN  
is_builtinr   rO   rP   r  r/  rM   rF   r   propagate_mutation	Exceptionr6   with_traceback__traceback__)r^  r   rp   rq   	base_nameerrortagdecided_constraintdefault_tagr  layout_constraintsold_args
old_kwargs	fake_argsfake_kwargsrt  outera  s    `                rw   r   zGraphLowering.call_function  s   X%%%*T!WtUD>Q*R*R%77((v>>> &%*"=>> 	+71D
 D
 	+ 64*6***""fej&;<<  000 < ++C003I///f5$GGGGG* +I *6(336--5 
 9&&vtV<<  
 /H/ / / K,77??  (   *<&&0IT1 1 1K *B+)N)N&f8JKKKKK#VH-- I 0fEEE264HHH0	IIj)F"3444!A!9&!A!A! J'+V*%)BBB
 *QV33128J1K.	;  *&%*2GHHHHH8 8 8 8 8 8 2;9k1R1R.	;'0yv'>'>f/8y:/N/N,*'@ &)[( (f $6#5a#I$#I#I#I&#I#ILD&F#T4V44C! O ''8ZvNNNJ 	 	 	#AvtV<<KK 	s   DL$ $
M.+MMtc                T    t          | j                  dk    o| j        d         dk    S )zM
        True if this is a small constant attr that will be inlined.
        r)   r      )ru  shape)r  s    rw   can_inline_constantz!GraphLowering.can_inline_constant  s&    
 17||q 4QWQZ1_4rx   	tuple[()]OUnion[Constant, TensorBox, ShapeAsConstantBuffer, ir.Subgraph, TorchBindObject]c                   t          | j        |          }t          |t          j        j                  r8|| j        v r| j        |         S t          j        ||          }|| j        |<   |S t          |t          j	        j
                  r%|| j        |<   d| j        |<   t          ||          S t          |t                    r%|| j        |<   d| j        |<   t          ||          S t          |t          j                  sJ t           j        j        st           j        st)          |          r|                     ||          S t-                      5  |j        dk    r:t1          |                                |j        |j                  cd d d            S |                     |          rdt:                              dt?          |                     ddl m!}  ||"                                |j        |j        	          cd d d            S 	 d d d            n# 1 swxY w Y   |                     ||          S )
N)r   graph_moduler  rV  rv   )r*  r  r   zInlining constant: %s r)   )rf  )r  r   )#r   rN  r}   r   r   rh   r#  r+   Subgraphr   ScriptObjectr"  r$  rE   r   r   r*   r=  r>  always_keep_tensor_constantsrQ   rJ  r&   r  r:   itemr  r   r  r  r  r   loweringrf  tolist)r^  r   rp   rq   r*  r  rf  s          rw   get_attrzGraphLowering.get_attr  s    "$+v66eUX122 	,,,*622+6>>>C*-D'JeUX233 	=/4D$V,*,D'"e<<<</00 	=/4D$V,*,D'"e<<<<%.....<	;2	; )//	;
 ++E6:::]] 
	V 
	V{b  **,,ek%,  
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V
 ''.. V		2CKK@@@,,,,,,vellnnEKUUU
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V
V
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V 
	V ''v666s   9H#A,H##H'*H'r   c                    t           ru   AssertionErrorr^  r   rp   rq   s       rw   call_modulezGraphLowering.call_moduleG      rx   c                    t           ru   r  r  s       rw   call_methodzGraphLowering.call_methodJ  r  rx   c                   t                                          |||          }t          |t          t          f          s|f}t          |t          t          f          sJ t          |                      t          d |D                       s
J |            t          j        j	        j
        d         }t          |t          t          f          s|f}d |D             }g }t          |          t          |          k    sJ t          ||          D ]\  }}t          |t          j        t          j        f          s|                    |           Bt          |                                t          j                  r3|                    t          j                            |                     t*          j        j                            |          sJ d |j        d                                         D             }	|                    t          j        ||	                     || _        | j                                        D ]t\  }
}t          |t<                    rt          |t          t>          j         t*          j        j        j!        f          sJ dt          |                       t          |t                    s|"                                 t          |t                    sJ |j#        }t          |t          j$                  sJ |}|j#        }t          |tJ                    r|&                                |
k    rnt          j'        (                    || j)        |
                    	 | j        *                    |          }| j)        |
         | j        |<   c# tV          $ r Y pw xY wv| ,                                 tZ          .                    d| j/        | j0        | j0        nd           d S )	Nc              3    K   | ]z}t          |t          t          j        t	          d           t          j        t          j        t          j        j	        j
        t          t          j        t          j        f	          V  {d S ru   )r}   rD   r+   r:   r  r  r~   r   logicboolalgBooleanr  EffectfulKernelrB   r   r.  s     rw   r   z'GraphLowering.output.<locals>.<genexpr>X  s       
 
  KJJ%JK'/&,
 
 
 
 
 
 
rx   r   c                L    g | ]!}t           j                            |          "S rv   )r+   ExternKernelrealize_inputr  s     rw   rp  z(GraphLowering.output.<locals>.<listcomp>n  s(    CCCq"///22CCCrx   c                ^    g | ]*}t          |t          j                  r|j        j        n|+S rv   rl  r   ss     rw   rp  z(GraphLowering.output.<locals>.<listcomp>  sA           $.a#>#>EAFKKA     rx   r  z'Unsupported inductor graph input type: zGForce channels last inputs for %d conv for the current graph with id %dr  )1r  r   r}   r,  r4  r  r  rb   rF  r/  rp   ru  zipr+   rD   BaseViewr  get_output_specCommBufferLayoutr  
copy_inputr   	_inductoris_storage_and_layoutr   rs  try_match_insignificant_stridesr   r  r?  rE   r~   r   r`  r3  r  rC   r?   get_nameMutationLayoutSHOULDREMOVErealize_intor  r  
ValueErrorfinalizer  r  r	  r   )r^  r   rp   rq   rs  fx_node_argsresult_correct_stridesrfx_nodemeta_stridesr   r*  value_storage_boxindra  s                 rw   r   zGraphLowering.outputM  s    f55&5$-00 	YF&5$-00>>$v,,>>0 
 
 
 
 
 
 
 	 	  !	 	 
$ w+03,66 	+(?LCCFCCC!#<  CKK////fl33 	 	JAwa",!<== &--a0000A--//1DEE  '--bo.H.H.K.KLLLL )??BBBBB   $\%07799      '--6q,GG    4,2244 	 	KD%%11 	5:u/A/PQ  G GFeFFG G  eY// MMOOOeY/////JEeR]33333 %JEe[11 
U^^5E5E5M5M-::45d;  ,223DEEC.2.H.ND&s++!   D 6N 			U'!]6DMMB	
 	
 	
 	
 	
s   /N22
O ?O c                B    | j         D ]}|                                 d S ru   )r  decide_layout)r^  r  s     rw   r  zGraphLowering.finalize  s2    < 	  	 C	  	 rx   r   c              #  V   K   | j         }	 || _         d V  || _         d S # || _         w xY wru   )r/  )r^  r   olds      rw   set_current_nodezGraphLowering.set_current_node  sF      	$ $DEEE #DD####s    	(c              #  H   K   | j         }	 d V  || _         d S # || _         w xY wru   r,  )r^  r  s     rw   set_current_wrapper_codez&GraphLowering.set_current_wrapper_code  s>      	$EEE #DD####s    	!r  r  
tuple[Any]r  new_args
new_kwargsc                    t          |          t          |          k    sJ t          |          t          |          k    sJ |j        t          j        j        j        u r|j        d         }t          |t                    sJ t          j	        j
                            |d         |d         d |                                D             |d                   }|D ]U}|d         |         }	|d         |         }
|	|
u r#                     t          j        j        j        j        |	|
fi            VdS t          |j        t          j        j                  sJ d fd}|j        j        }t)          t+          ||                    D ]"\  }\  }	}
|j        |         } |||	|
           #d |j        D             }|                                D ]'}||         }	||         }
||         } |||	|
           (dS )ax  Propagate mutations on new_args/new_kwargs back to old_args/old_kwargs.

        Assumes we may have cloned old_args/old_kwargs into new_args/new_kwargs
        and then called fx_node(*new_args, **new_kwargs).

        If fx_node mutates any of new_args/new_kwargs, and they are different from
        old_args/old_kwargs, then we need to update the original tensor.
        rq   
kernel_idxconstant_args_idxc                r    i | ]4\  }}|t          |t          j        j                  r|j        d          n|5S r  r}   r   r   r%   r   r   r_  r`  s      rw   
<dictcomp>z4GraphLowering.propagate_mutation.<locals>.<dictcomp>  K       1 
1ehm(D(DKqve}}!  rx   tma_descriptor_metadataN
schema_argtorch._C.Argumentold_arg	ir.IRNodenew_argrr   rs   c                   ||u rd S | j         y| j         j        rot          |t          j                  r|f}|f}t          ||          D ]@\  }}||u r
                    t          j        j	        j
        j        ||fi            =d S d S d S ru   )
alias_infois_writer}   r+   IRNoder  r   r   r  r   copy_r  )r  r  r  old_arg_itemnew_arg_itemr^  s        rw   maybe_propagatez9GraphLowering.propagate_mutation.<locals>.maybe_propagate  s     '!!$0Z5J5S0 gry11 )&jG&jG25gw2G2G  .L,#|33 &&	,4|\6RTV    1000 rx   c                    i | ]
}|j         |S rv   r  )r   args     rw   r  z4GraphLowering.propagate_mutation.<locals>.<dictcomp>  s    CCC33CCCrx   )r  r  r  r  r  r  rr   rs   )ru  r   r   r  r^  triton_kernel_wrapper_mutationrq   r}   rw  r   r   get_mutated_tensorsr?  r   r   r  r  r   r   _schemar   r  	argumentsr  )r^  r  r  r  r  r  rq   mutatedr   r  r  r  schemar   r  schema_kwargskeys   `                rw   r}  z GraphLowering.propagate_mutation  sB     8}}H----:#j//1111>UY3RRR^H-Ffd+++++-@TT<(./  &   45 G   Y Y$X.t4$X.t4g%%""59>#7#?'7ASUWXXXXF'.%**?@@@@@	 	 	 	 	 	( ''0Xx1H1H'I'I 	: 	:#C#'7)#.JOJ9999CC&2BCCC??$$ 	: 	:C oG oG&s+JOJ9999		: 	:rx   r  objectc                   #$% d+fd}ddl m} t           j                  $t           j                  %t          g          }j        dk    }|r+                               \  }}|t          ||          z  }t          j
                            |          5                                 5  t          j                  5  j        dk    rj        rt          j        t           j        j                  r{t           j        j                            j                  rRt-                    s|                    d	d
fd          r) |d            t1          j        d          |i |}nj        dk    rj        t           j        j        j        u rt8          j        dk    r |d           t8          j        dk    r|}	|}
j                            d          x}r&|d         }|d         }tA          ||||          \  }}ntC          g|R i |\  }} "                    j        ||          } #                    |	|
||           ntI          dt8          j                   tK          j                  r |d           t          j        d         t           j&        t           j'        t           j(        f          rj        d         j)        j*        }nNtW                      ,                              }n, |d           tW                      ,                              }t           j        j-        j.        j/        t           j        j-        j0        j/        t           j        j-        j1        j/        t           j        j-        j2        j/        t           j        j-        j3        j/        g#ti          d j5        D                       } j6        v }ti          #fdj5        D                       }j                            dd          rt          |tn                    r|8                                 j        d         9                                }t!          j:        j        j;        | }|<                                |k    r6|s4t          j=        |          }t          j>        ?                    ||          }|rHt          |tn                    r3t          |j@        t          jA                  r|8                                 |s|rt          j        d         t           jB                  r|r j6                                      }nj        d         9                                }|t          |          dk    rt8          jC        p| o| }t           jD        E                    j        d                   }t          t          |                    dk    }|sp|rnt          |G                                          dk    rI jH        v r@|s>|s<t          jI        J                    |G                                t           jK                  }|st          |          rj        d         L                                st          |j@        t          jA                  r5t          j>        ?                    |t          j=        |          |          }n.d |D             }t          j>        M                    |||          }t          t          j5                            }|dk    rt          |tn                    rj5        D ]Q}|j        t          v r|O                                 t           j        j-        jP        j/        t           j        j-        jQ        j/        t           j        j-        jR        j/        g}g } jS        s.|T                    t           j        j-        jU        j/                   t           jV        jW        r|t           j        jX        jY        j/        t           j        jX        jY        jZ        t           j        j-        j[        j/        t           j        j\        j]        j/        t           j        j\        j]        j^        t           j        j\        j]        jZ        t           j        j\        j]        j_        gz  }|t           j        jX        j`        j/        t           j        jX        j`        jZ        t           j        jX        ja        jZ        t           j        jX        jb        j/        t           j        j\        jc        j/        t           j        j\        jd        jZ        gz  }t           jV        je        r|t           j        jf        jg        j/        gz  }|j        |v rQt          j>        ?                    |t          j=        j        d         9                                          d          }|j        |v r^|jh        d         u rOt          j>        ?                    |t          j=        t          j        d         jj                                      }|j        dk    r:t          |j@        j@        t          t          f          r|8                                 S|m                    t          j5                             t          |tn                    r(|n                                r|O                                 t          |tn                    ret          |j@        t                    rK|j@        j@        }t          |t                    r*|p                    d !          r|8                                 d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   d d d            n# 1 swxY w Y   t          |tn                    rt          |j@        t          jo                  rt          |j@        j@        t          jq                  r"|j@        j@        r                    d"           nGt          |j@        j@        t          js                  r"|j@        j@        r                    d"           t          |j@        j@        t          jt                  rOt          |j@        j@        j@        t          jq                  r&|j@        j@        j@        r                    d"           nt          |j@        j@        t          ju                  rk|j@        j@        jv        sZt          |j@        j@        jw        d         t          js                  r+|j@        j@        jw        d         r                    d"            x                    |           t          t          jz                             } j        $d          D ]}||{                                z  } j        %d          D ]}||{                                z  }t          j|        j}        j~        }j        d#k    rDt          |t          jz                  r*|                    |          r|                    |           d,$% fd$} t          j|        j        rj        d#k    r|S t          t          j|        j}        j~        j                            d%i                     }!|!J t          d& |!                                D                       }"||"k    s0J d'| d(|" d)                                 d* |                                               |           |S )-Nmsgr   rr   rs   c                d    t                               dt          j                  |            d S )Nzlowering %s %s)r  r  r   format_node)r  r  s    rw   r  z%GraphLowering.run_node.<locals>.debug  s*    II&
1=(A(A3GGGGGrx   r   )CompilerBisectorr   inductorrK   c                 "    t                     S ru   )reprr  s   rw   <lambda>z(GraphLowering.run_node.<locals>.<lambda>'  s    a rx   rI   F)add_to_fallback_setflexible_layout-user_defined_triton_kernel_layout_constraintsneeds_fixed_stride_orderrn  r)   z1Unknown triton_kernel_default_layout_constraint: r   r  r  c              3  ,   K   | ]}|j         d k    V  dS )r   Nr   )r   r  s     rw   r   z)GraphLowering.run_node.<locals>.<genexpr>h  s)      DDDDGx/DDDDDDrx   c              3  *   K   | ]}|j         v V  d S ru   )r   )r   r  as_strided_opss     rw   r   z)GraphLowering.run_node.<locals>.<genexpr>j  s;       * *26~-* * * * * *rx   inductor_realize_to_strides   )allow_paddingc                ^    g | ]*}t          |t          j                  r|j        j        n|+S rv   rl  r  s     rw   rp  z*GraphLowering.run_node.<locals>.<listcomp>  sB     ' ' '$% 0:!U\/J/J QPQ' ' 'rx   Tr   d   )	thresholdorigin_noderW  c                     d j         d          D             } |                     d j        d          D                        d                    |           S )Nc                D    g | ]}d |                                  d| dS )unbacked_symbol_defs= in:

get_unbacked_symbol_defs)r   r  s     rw   rp  zCGraphLowering.run_node.<locals>.format_new_defs.<locals>.<listcomp>2  sH        V(D(D(F(FUUcUUU  rx   c              3  L   K   | ]}d |                                  d| dV   dS )r  r  r  Nr  )r   r   s     rw   r   zBGraphLowering.run_node.<locals>.format_new_defs.<locals>.<genexpr>6  sV         T(C(C(E(ESSRSSS     rx   z***
)r  extendr  r   )r  buffer_watermarkoperation_watermarkr^  s    rw   format_new_defsz/GraphLowering.run_node.<locals>.format_new_defs1  s     <(8(9(9:  A HH  /*=*>*>?      <<??"rx   unbacked_bindingsc              3  j   K   | ].}t           j        j        j                            ||          V  /d S ru   )rb   r  r   unbacked_renamingsr   r  s     rw   r   z)GraphLowering.run_node.<locals>.<genexpr>g  sN       /
 /
 K!488A>>/
 /
 /
 /
 /
 /
rx   zfailed  >= z (inductor >= fx)
fx node is: z
new operations are:

)r  r   rr   rs   rr   r   )!torch._inductor.compiler_bisectorr  ru  r  r  r'   r   fetch_args_kwargs_from_envrV   r+   r  current_originsr  rb   r   r}   r   r   r   r{  rN  r|  rJ   disable_subsystemrI   r  r^  r  r*   'triton_kernel_default_layout_constraintr   r   rF   rG   r   r}  r   r   rm  SymFloatSymBoolr   rn  r  run_noder   
as_stridedr  as_strided_as_strided_scatterresize	resize_asr   r  r   rD   r3  rs  r  any_is_symbolicmaybe_get_strideget_stride_orderr  require_stride_orderr  r  r   r   _prims_commonis_non_overlapping_and_denser   r  rD  FlexibleLayout stride_ordered_for_memory_formatchannels_last_is_viewrequire_exact_stridesrN   realize_hintr   mm_int_mmr   r  r   r   _has_mkldnnr  _linear_pointwisebinarymkldnn_rnn_layeronednnqlinear_pointwiserf  binary_tensor_convolution_pointwise_convolution_pointwise_ _convolution_transpose_pointwiseqconv_pointwiseqconv2d_pointwisehas_mklmkl_mkl_linearrp   r   r  r@   rA   
mark_reusehas_exceeded_max_readsrC   has_large_inner_fnLoops_post_init_setattrBufferr  MultiOutputindicesinputsr1  r~   r   r  rF  r  r   is_unbacked_symintr  r   r    r  r  create_deferred_runtime_asserts)'r^  r  r  r  originsis_call_functionrp   rq   rs  r  r  rn  inp_args
inp_kwargs	is_outputis_user_visibleis_input_for_as_stridedre  sym_stridesstride_orderr  denseunbacked_symbols_in_strides	num_usersr  need_fixed_layoutneed_fixed_channels_last_layoutcurrnew_unbacked_defsr  r   r   r  r  renamed_unbacked_bindingsr  r  r  ra  s'   ``                                 @@@rw   r"  zGraphLowering.run_node
  s   	H 	H 	H 	H 	H 	H 	GFFFFFt|,,!$/22 $.qc??4?2 	4::1==LD&~dF333GI%%g..j	) j	)!!!$$j	) j	) q!!j	) j	) ''H ( qx)>?? ( N(33AH==	 ( :!<< ( (99"K  ( ()))N)!(NNN 
 ''H	 6 UUUBFWWWEFFFB12 2  $H!'J+,6::6H+I+II' S#3A#6%5a%8
'@ &(J( (ff (?q'R4'R'R'R6'R'Rf!//$GGF++AxT6RRRR&|FLz||   !** - '(((F5MEL%.%-#P  1 VE]/4FF"WW--a00FFb			))!,, 	)1	*2	19	%-	(0N DDAGDDDDDI4#CCO&) * * * *:;'* * * ' '# vzz7?? XJ	E E X    &-..00#o3CWM**,,777#%#6w#?#?L_AA&,WWF!vy11! v{BK88!     04 0*uu|; ; 0 # 5">BB1EEGGfUm2244G&3w<<!+;+;*A/.A%655 " "/LLu E 1'::;;a? 0 8
!
   1 122a77!@@@ / A 7 A #%"3"T"T"OO--u/B# # 7 3w<<  6%=1133 z"K8 8  &(_%I%I & " 3G < <.; &J & &FF' ')0' ' 'G &(_%J%J &} &K & &F Jqw//00I1}}FI!>!>}G ;- ;-D{&;;;++--- "IN?G!IN-5!IN2:-)
 ;=7# Y-44UY^5O5WXXX 8/ Y- %	 0 B J %	 0 B I %	 ? G %	 0 B J %	 0 B I %	 0 B I %	 0 B P2 - < %	 0 G O %	 0 G N %	 0 H O %	 0 Q Y %	 0 @ H %	 0 B I@ ;  %x/ Y 1eim6O6W5X X 1;*;;;%'_%I%I & " 3AF5M4H4H4J4J K K.2 &J & &F !K+JJJ !TYq\ 1 1%'_%I%I & " 3$B16%=CV$W$W!" !"& &F w(**%fk&6I8NOO -"NN,,, !!#ag,,/// &),, &1N1N1P1P & ##%%% &),, )FK1T1T ){'dI.. )...== )(((Uj	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	) j	)h fi(( 	XZR]-S-S 	X&+*BH55 X 33M1EEEEFK,bi88 X 33M1EEEfk.0ABB 
XzK$)28H H 
X K$)<<]ANNNN v{/@@X"K,4X "&+"2"9!"<biHH X(/2EEmUVWWWv&&&&u|466< 0 1 12 	@ 	@C!=!=!?!??/"5"6"67 	? 	?B!<!<!>!>>G$.	
 DM!!65<00 ",,V44 " !!&)))		# 		# 		# 		# 		# 		# 		# 		# 7 	14=#8#8M. 6G&

3F(K(K
 
 !,,, %/ /
 /
&++--/
 /
 /
 %
 %
!
 !$====:' : :-F : :==??: :&5o&7&7: : >==
 	,,Q0ABBBs[   "o
8n3knn3n  n3#n $n3'o
3n7	7o
:n7	;o

oor_  OrderedSet[sympy.Symbol]c                    d fd}t                      rn|j        t          j        j        j        j        k    rJ j        rC                     |          \  }}|d         d	k    r ||d         |d          d
           d S d S  xj	        |z  c_	        t          j        j        j        }|D ]5} j                            |g           }|j        |         }	|                                                    |	          sbdd}
 |
|	j                  r |||	j        k    | d|	j                     |
|	j                  r |||	j        k    | d|	j                    |D ]~}t+          |j                  }| j	        z
  }|rEt/          |t0                    } j                            |g                               |           g ||j        |j                    7d S )Nrn  r#   r  r   rr   rs   c                    t          j        | |          }                    |d                               |           d S )NTr  )r+   AssertScalarr!  r  )rn  r  	assert_opr^  s      rw   make_assertzBGraphLowering.create_deferred_runtime_asserts.<locals>.make_assert  sG    c22I  T :::##I.....rx   r   Tz to be Truer  r   r   c                n    | t           t            fv rdS 	 t          |            dS # t          $ r Y dS w xY w)NFT)r(   r  	TypeError)r  s    rw   is_convertiblezEGraphLowering.create_deferred_runtime_asserts.<locals>.is_convertible  sP    & 111#(5)FFF#'4( ) ) )#(55)s   & 
44r  z <= )r  )rn  r#   r  r   rr   rs   )r  r   rr   r   )r   r   r   r  r   _assert_scalarr  r   r  r  rb   rF  r  r   r  popvar_to_range _default_unspecified_value_rangeissubsetlowerupperr   rn  r   r   
setdefaultr  )r^  r  r_  rf  	node_argsry  r   i0rasvrri  rafvsmissingi1s   `              rw   rO  z-GraphLowering.create_deferred_runtime_assertst  sS   D	/ 	/ 	/ 	/ 	/ 	/ %&&,	;EIN9AAA B  ::1==LIq|t##IaLYq\*F*F*FGGGGG $# ''+<<''(2I ( ; ;(,,R44+B/ AACCLLRPP K) ) ) ) &~bh// K#B"(Nr4I4Irx4I4IJJJ%~bh// K#B"(Nr4I4Irx4I4IJJJ ; ;B/88C!D$??G ; c222*55b"==DDRHHHH#BG\::::;); ;rx   c                    t           j        rt          d          t          j        dvrt          dt          j                   d S )NzC++ codegen is disabled)linuxdarwinwin32zUnsupported platform )r*   disable_cpp_codegenr5   sysplatformrd  s    rw   !validate_can_generate_cpp_wrapperz/GraphLowering.validate_can_generate_cpp_wrapper  sL    % 	D()BCCC<;;;()O)O)OPPP <;rx   is_subgraphparent_wrapper_codeOptional[PythonWrapperCodegen]partition_signatures!Optional[GraphPartitionSignature]c                   | j                                         }|                    d           |                    d           t          |          dk    s0J d                    d                    |                                t          |          dk    }|rdn|                                | _        | j        r| 	                                 t          | j                  | _        t          | j        | j        | j                  }|J d| j         d            |                    ||||          | _        | j        r| j        j        j        | j        _        d S d S )	Nr  r   r)   zDoes not support mixing {}+r   zDevice z not supported)r  r  discardru  formatr   rk  r  r   r  r1   r+  r2   r   rH  r,  r   _names_iter)r^  r  r  r  r  r  only_cpuwrapper_code_gen_clss           rw   init_wrapper_codezGraphLowering.init_wrapper_code  s    (--//U###V$$$<  A%%%'C'J'JHH\""(
 (
%%% |$$)$,D55,2B2B2D2D 	5224441$2BCC=d. 
  
 $//6d&666 0// 177 	
 
  	W,0,=,J,VD)))	W 	Wrx   %list[Union[int, float, torch.Tensor]]c                   dd l }|                    | j                  }|                    |          }g }|j        j        D ]?}|j        dk    r2|j        t          j        j	        j
        u r|                    |           @g }i }i }g }	i }
|D ]}|j        d         D ]R}|D ]M}||v rt          |t          j        j                  r't!          |          ||<   |                    |           NS|j        d         }t          j        j                            |j        d         |j        d         d |                                D             |j        d                   }i }|j                            |          5  |                                D ]\  }}||v rO|j                            t          j        |f	          }t!          |	          ||<   |	                    |           X||
v r|
|         ||<   ht!          |	          |
|<   |	                    |           |
|         ||<   	 d d d            n# 1 swxY w Y   |||j        <   |	|z   }|j        j        D ]$}|j        d
k    rt3          |          f|_         n%|                                 t          j                            |          }|                    |          }t!          |          dk    r|t!          |	          d          }i | _        |D ]}d}g }|j        d         D ]}g }|D ]Z}t          |t          j        j                  s|                    |           7d}|                    |||                             [|                    t3          |                     |r|| j        |j        <   |d t!          |	                   | _        || _         d S )Nr   r   gridrq   r  r  c                r    i | ]4\  }}|t          |t          j        j                  r|j        d          n|5S r  r  r  s      rw   r  z9GraphLowering.extract_autotune_inputs.<locals>.<dictcomp>  r  rx   r  )rp   r   FT)!r  deepcopyrM  rF  r   r   r   r   r  r^  r  r  rq   r}   r   r%   ru  r   r   r  r?  inserting_beforer   cloner   r,  rp   	recompileInterpreterr  rA  r?  r@  )r^  r   r  	cloned_gmtriton_nodesr   grid_inputsvisited_gridstriton_inputskwargs_inputsvisited_kwargsr  r  rq   r  r  r_  r`  new_nodenew_outputsrunnerreturned_outputsgrid_outputsdynamic_grid	new_gridsnew_grids                             rw   extract_autotune_inputsz%GraphLowering.extract_autotune_inputs  s    	MM$,//	~66O) 	* 	*D?**K59#9#XXX##D))) ,.24(*-/)+  &	2 &	2DF+ 0 0 0 0Cm++ !#ux}55 0-0-=-=c*#**3///0 [*F-@TTL)/0  &   56 G *,J11$77 6 6"LLNN 6 6DAqG||#,?#@#@TUSW#@#X#X(+M(:(:
1%,,X666 N**(6q(9
1 (+M(:(:N1%!((+++$21$5JqMM66 6 6 6 6 6 6 6 6 6 6 6 6 6 6 (2M$)$$#k1O) 	 	Dw(""";//1	 # 	%%i00!::n55{a+C,>,>,@,@AL$&D!$ A A$.0	 K/ 6 6D!H# J J)#ux}== %$OOC000$'+ ]35G(HIIII$$U8__5555 A7@D)$)4!12FC4F4F2F!G"/s   >B0H;;H?	H?	)tuple[ValueWithLineMap, ValueWithLineMap]c                F    t           fddD                       rd
 fd}t          j        j        rpt          j        j        rKd} j        D ] }t          |t          j                  rd} n!|r |            } 	                    |            
                                S d _                                         j        } |            }t          j        j                                        5   ||           ddd           n# 1 swxY w Y   ~d _         j                                          j                                          j                                         t,          j        j        j                                         t,          j        j        j                                         t7          j                     t          j        d	di          5   
                                cddd           S # 1 swxY w Y   dS  
                                S )zQ
        For GPU, Triton kernels are autotuned and stored as cubin files
        c              3  *   K   | ]}|j         v V  d S ru   )r  )r   r   r^  s     rw   r   z9GraphLowering.codegen_with_cpp_wrapper.<locals>.<genexpr>Y  s+      IIvv**IIIIIIrx   )cudaxpurr   r  c                    ddt           j        j                                        } | |t	          t
          j        t                    s]| j        r| j        	                                 d | j
        D             }fdt          j        |t
          j                  D             n>fdt	          t
          j        t                    rj        nt
          j        D             j        r_d	d
lm} fdt#          j                  D             }|D ]5}|         }t	          |t           j                  sJ  ||          |<   ~6S )Nr.  1Union[torch.SymInt, torch.SymFloat, torch.Tensor]rr   Union[int, float, torch.Tensor]c                <   | d S t          | t          j        t          j        f          r| j        j        S t          | t                    rt          |           S t          | t          j                  s'J dt          t          |                     z               | S )Nz&Unknown type when creating real inputs)r}   r   rm  r   r   hintr   r   r   r   r  )r.  s    rw   materializezXGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.materialize\  s     y#t#Aen'EFF 	! v{*#Az22 !%ayy()!U\::  Ds4PQ77||S :  !rx   c                    g | ]}||S ru   rv   )r   params     rw   rp  zWGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.<listcomp>s  s(     # # #! , ,,,rx   c                &    g | ]} |          S rv   rv   r   r.  r  s     rw   rp  zWGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.<listcomp>x  s1     # # # $A# # #rx   c                &    g | ]} |          S rv   rv   r  s     rw   rp  zWGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.<listcomp>  s1     # # # $A# # #rx   r)   )clone_preserve_stridesc                l    g | ]0\  }}|j         v t          |         t          j                  .|1S rv   )r1  r}   r   r   )r   r   r   real_inputsr^  s      rw   rp  zWGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.<listcomp>  sN     * * *%C4#666&{3'7FF 7 666rx   )r.  r  rr   r  )r   _guardsTracingContexttry_getr}   rb   r  ra   output_stridesclearparams_flatrX  chainr   r1  
compile_fxr  r   r  r   )	tracing_contextr  r  r2  r   mutated_inpr  r  r^  s	         @@rw   extract_real_inputszCGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs[  s   ! ! ! !  #(-">"F"F"H"H".zM;8 8. '5 ?'6<<>>># #%4%@# # #K
# # # #!*am!L!L# # #KK# # # #  *!-EE/D//!"# # #K & (BBBBBB* * * * *)243D)E)E* * *&  2 ( ( '2#&6)+u|DDDDD+A+A++N+NC('K""rx   FTNztriton.autotune_at_compile_time)rr   r  )r   r*   tritonautotune_at_compile_timeautotune_with_sample_inputsr  r}   r+   UserDefinedTritonKernelr  codegenr   compile_to_modulecallr   rN  rO  rP  r&  r  r%  r*  rb   rF  r  precomputed_replacementsinv_precomputed_replacementsr,   resetpatch)r^  r  user_defined_kernelsr   r  compileds   `     rw   codegen_with_cpp_wrapperz&GraphLowering.codegen_with_cpp_wrapperS  s    IIIIIIIII j	"C# C# C# C# C# C#J }5  * =< B+0("o " "%b"*DEE "370!E" , B&9&9&;&;44[AAA||~~% $) 113381133[1HHJJ * *H[)))* * * * * * * * * * * * * * * $( $**,,,'--///'--/// 9??AAA =CCEEE\#De"LMM * *<<>>* * * * * * * * * * * * * * * * * * <<>>!s$   2D

DD!HH	Hc                    ddl m} t          j        dd          5   || j                  | _         ddd           dS # 1 swxY w Y   dS )z
        (Re)initializes the scheduler member.  When initializing the scheduler, no CUBIN
        files should be generated (to avoid biasing any benchmarks and pessimizing
        fusion decisions).
        r)   )	Schedulerztriton.store_cubinFN)r>  r  r*   r  r  )r^  r  s     rw   _update_schedulerzGraphLowering._update_scheduler  s     	)(((((\.66 	8 	8&Yt77DN	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8s   ?AAc                4   t          dd          5  |                                  |                                  t          j                            | j        | j        j                   | j	        
                    |            | j                                         t                              dt          j        j                   | j	                            | j                  }| j	                                         |cd d d            S # 1 swxY w Y   d S )NzGraphLowering.codegenTlog_pt2_compile_eventzFFinished codegen for all nodes. The list of kernel names available: %s)r   r  r  rb   r  draw_orig_fx_graphrM  r>  r   r,  push_codegened_graphr  r  rF  rW  generater   pop_codegened_graph)r^  rs  s     rw   r  zGraphLowering.codegen  s<   1NNN 	 	""$$$""$$$G&&t|T^5IJJJ224888N""$$$IIX0  
 &//0ABBF11333!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   C.DDDparent_graphc                    t          dd          5  |j        | _        |j        | _        |j        | _        |                                  | j                                         ddd           dS # 1 swxY w Y   dS )a  
        This is a more compact version of the `codegen()` above
        where we codegen this graph as a subgraph of some parent
        graph. The parent graph is passed as an argument: the
        intention is to inline codegening of the subgraph in
        the parent graph's wrapper code (including the generated
        kernels). The wrapper code is not finalized (via `.generate()`
        call), as this will be done in the parent graph's `codegen()`.
        zGraphLowering.codegen_subgraphTr  N)r   r,  r+  r   r  r>  r  )r^  r  s     rw   codegen_subgraphzGraphLowering.codegen_subgraph  s     :RVWWW 	% 	% , 9D*5DO+7D""$$$N""$$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%s   AA11A58A5Vtuple[int, list[tuple[BaseSchedulerNode, int]], list[tuple[BaseSchedulerNode, float]]]c                    d}g }g }| j         j        D ]^}|                                }||z  }|                    ||dz  f           |                    ||                                f           _|||fS )Nr   r  )r>  r   get_read_write_buffers_sizesr  get_estimated_runtime)r^  total_bytesnode_countsnode_runtimesr   	num_bytess         rw   count_byteszGraphLowering.count_bytes  s    
 N( 	G 	GD99;;I9$Ki1n5666  $(B(B(D(D!EFFFFK66rx   zOptional[Callable[[str], None]]save_output_codeCompiledModulec                    t          dddd          5  |                                 cd d d            S # 1 swxY w Y   d S )NzGraphLowering.compile_to_modulecode_genT,inductor_code_gen_cumulative_compile_time_us)
phase_namer  dynamo_compile_column_us)r   _compile_to_modulerd  s    rw   r  zGraphLowering.compile_to_module	  s    -!"&%S	
 
 
 	- 	- **,,	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s   599c                   | j         r|                                 n|                                 \  }}t          |t                    r|                     |          }n7t          |t                    r|}nt          dt          |                     |j	        J t          |j	                   t                              d|j	                   t          j        d|j	                   t          j        r#t#          d|j	         t$          j                   t(          j                            |j	                   t(          j                            t.          j                            |j	                  d         dz              |S )Nz Unrecognized wrapper code type: Output code written to: %szCompiled module path: )filer   z.debug)r   r  r  r}   r`   _compile_to_module_linesr/   NotImplementedErrorr  __file__ro   r  r  rm   r  r*   benchmark_kernelprintr  stderrrb   output_coder  ospathsplitext)r^  r,  ry  mods       rw   r  z GraphLowering._compile_to_module	  s`    04/?SD))+++T\\^^ 	a l$455 	//==CC&;<< 	CC%G43E3EGG   |'''%%%		.===93<HHH" 	L93<99
KKKK	CL)))	RW%%cl33A6ABBB
rx   r,  r`   c                  	 ddl m} t          j        j        rj| j        j                                        }|                    dd          }d|z   | j        j	                                        z   dz   }|j
        z   _
        t          j        t                              j
                   t          j        dj
                   t          j                    }t#          j        |j
                   	 d	 j        D             }|                    j
                  \  }	t          j        d
	           t+          d	fdfd           n## t,          $ r t+          dfd            w xY wt/          dd          5  |                    |	|i | j        | j                  }d d d            n# 1 swxY w Y   || _        	| _        || _        t          j        r#t          j        r|                     dd           |S )Nr)   )PyCodeCachez"""z\"\"\"z%"""
Compile-time auto-tuning block: 
z"""
zOutput code: 
%s)codec                &    g | ]\  }}||j         fS rv   )stack_trace)r   line_nor   s      rw   rp  z:GraphLowering._compile_to_module_lines.<locals>.<listcomp>I	  s4       !GT $*+  rx   r  inductor_output_codec                     d iS )Nfilenamerv   )r  s   rw   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>Y	  s    T* rx   c                      j         S ru   r*  r  s   rw   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>Z	  
    <#5 rx   )
payload_fnc                      j         S ru   r
  r  s   rw   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>S	  r  rx   zPyCodeCache.load_by_key_pathTr  )linemapattrs)timesrepeat)!	codecacher  r*   r  r  r,  kernel_autotune_defsgetvaluereplacekernel_autotune_callsr*  r   r  rm   r  rR   inductor_meta_from_configrS   begin_compileline_mapwriter   r~  r   load_by_key_pathr  r"  rG  rH  rI  benchmark_harnessprofile_bandwidth_outputbenchmark_compiled_module)
r^  r,  r  r  tuning_codeinductor_metar  r  r  r  s
    `       @rw   r  z&GraphLowering._compile_to_module_lines/	  s    	+*****=1 	B#'#4#I#R#R#T#T #7#?#?{#S#S 7&' #9BBDDE 	  "-|/A!AL)5**<+=>>>1<3EFFF&@BB*=|?QRRRR	 %1%:  G $)),*<==IC!">EEE &****5555      	 	 	&5555   
 	 8PTUUU 	 	..DD4+CD	 /  C	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 $# 	=(G 	=))!)<<<
s   8AE  E4(F<<G G c                   g }t          j        d          }t          j        d          }|D ]}t          |t          j                  r-|                    | j         dt          |                      It          |t          j                  r-|                    | j         dt          |                      |                    |	                                           |S )Nr   _none_shape)
rX  rY  r}   r+   NoneAsConstantBufferr  r   r;  rB   r  )r^  r   namesshape_counternone_counterr   s         rw   _get_output_nameszGraphLowering._get_output_namesm	  s    !** q))! 	. 	.D$ 788 .	DD\0B0BDDEEEED"":;; .	FFm1D1DFFGGGGT]]__----rx   c                6    |                      | j                  S ru   )r(  r   rd  s    rw   get_output_nameszGraphLowering.get_output_namesz	  s    %%d&8999rx   c                ,   || j                                         v op| j         |                                         dk    oMt          | j         |                                                   dk    ot          | j         |                   dk    p|| j        v S )Nr)   r   r  )r  r  r  ru  r  r=   r  r  s     rw   is_unspec_argzGraphLowering.is_unspec_arg}	  s     D%**,,, B!$'1133q8BD%d+4466771<B   1$ 788EA	3
 T22	3rx   )NNNFFNNFFFNNNNNNF)&r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   rs   )rr   rs   )re  rf  rr   rg  )re  rf  rr   r}  )r   r  rr   r  )r   r  rr   r   )r   r  r  r-   rr   r   )r  rk   rr   r  )rr   r  )r   r  rr   r  r  )r   rh   r   r   rr   r   )r   r   rr   r   )r   r   r   r  r  r   rr   r  )rr   r  )r   r   rr   rs   )r   r  rr   rs   )rr   r  )r  r   rr   r  )r  rz   rr   rs   )r  r   rr   r  )r  r   rr   r  )r  r   rr   r  )rp   r   rr   r   )r   r  rr   r   )r  r  r  r   rr   r   )r"  r#  rr   r   )r'  r(  rr   rs   )r   r   rr   rf  )r   r   r  r8  rr   r   ru   )r  r   r   r   rr   rF  )r   r   rK  rL  rr   r   )r   r   rp   rR  rq   rS  rr   rT  )r   r   rp   r   rq   rg  rr   r   )r  rf  rr   r   )r   r   rp   r  rq   rS  rr   r  )r   r   rp   r   rq   r   rr   r   )r   r   rp   rR  rq   rS  rr   rs   )r   r   )rr   r  )r  r   r  r  r  rg  r  r  r  rg  rr   rs   )r  r   rr   r  )r  r   r_  ra  rr   rs   FNNN
r  r   r  r   r  r  r  r  rr   rs   )r   r  rr   rs   )rr   r  )r  r   rr   rs   )rr   r  )rr   r  )r,  r`   rr   r  )r   r   rr   r#  )rr   r#  )r   r   rr   r   )F__name__
__module____qualname____annotations__r  rc  r|  r  r  r  r  r  r  
contextlibr   r  r  staticmethodr  r  r  rC  r  r  propertyr  r  r  r  r  r  r  r  r!  r&  r1  r4  r7  rE  rJ  rB  rW  r   r  r  r  r  r   r  r  r  r}  r"  rO  r  r  r  r  r  r  r  r  r  r  r  r  r(  r*  r,  __classcell__ra  s   @rw   r   r   #  sG        """"
 6:(,"&!%) "!$7;,0+/04"37 +E6 E6 E6 E6 E6 E6 E6N1 1 1 1#  #  #  # J   # # # #$E E E EM M M M- - - -"4 4 4 4 ( ( ( (    Y Y Y \Yv   
 
 
 
60 0 0 0dA A A A
D D D D    X   $F F F FQ Q Q Q8 8 8 8,
8 
8 
8 
8& & & & & &    FK      (   
      
 
 
 
    @ 37
 
 
 
 
    f f f f f fPo o o o o ob 5 5 5 \517 17 17 17f      [
 [
 [
 [
 [
 [
z        $ $ $ ^$ $ $ $ ^$I: I: I: I:Vh h h h h hTS; S; S; S;jQ Q Q Q "'+>BBF#W #W #W #W #WJ\0 \0 \0 \0|p" p" p" p"d	8 	8 	8 	8   &% % % %$7 7 7 7" 9=<<<<- - - -   << < < <|   : : : :3 3 3 3 3 3 3 3rx   r   c                  :     e Zd ZdZd fd	Z	 	 	 	 dd fdZ xZS )r  z
    Mostly a helper class for the subgraph lowering. The main goal is to call
    init_wrapper_code with the subgraph related arguments.
    r  r   rp   r   rq   rr   rs   c                H    || _          t                      j        |i | d S ru   )r  r  r  )r^  r  rp   rq   ra  s       rw   r  zSubgraphLowering.__init__	  s,    $)&)))))rx   FNr  r   r  r   r  r  r  r  c                n    t                                          d| j        | j        j                   d S )NT)r  r  r  )r  r  r   r  r,  )r^  r  r  r  r  ra  s        rw   r  z"SubgraphLowering.init_wrapper_code	  s@     	!!) $ 8 	" 	
 	
 	
 	
 	
rx   )r  r   rp   r   rq   r   rr   rs   r-  r.  )r/  r0  r1  __doc__r  r  r6  r7  s   @rw   r  r  	  sx         
* * * * * * "'+>BBF
 
 
 
 
 
 
 
 
 
 
rx   r  )rp   r   rq   r   rr   rs   )ry   rz   rr   r{   )r   r   rr   r   )r   rh   r   r   rr   r   )r   ri   rr   r   )r   ri   r   r   rr   rs   )
__future__r   r3  rP  rX  loggingru  r  r	  r  r7  collectionsr   r   typingr   r   r   r	   r
   r   r~   r   r   torch._loggingtorch.fxr   r   torch._decompr   torch._dynamo.utilsr   r   "torch._library.fake_class_registryr   torch._library.utilsr   r   r   torch._prims_commonr   r   torch._subclasses.fake_tensorr   torch._utils_internalr   %torch.fx.experimental._backward_stater   torch.fx.experimental.sym_noder   r   %torch.fx.experimental.symbolic_shapesr   r   r   r    r!   r"   r#   r$   torch.fx.noder%   torch.utils._mode_utilsr&   torch.utils._ordered_setr'   torch.utils._sympy.numbersr(   r  r*   r+   r,   codegen.commonr-   r.   r/   r0   r1   r2   r3   r4   excr5   r6   r7   r8   fx_utilsr9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   r  rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   runtimerR   runtime.autotune_cacherS   r  rT   rN  rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   virtualizedra   rb   collections.abcrc   rd   re   typesrf   torch._higher_order_ops.effectsrg   rh   torch.fx.graphri   codegen.wrapperrj   dependenciesrk   r>  rl   r  torch._inductor.codecacherm   	getLoggerr/  r  _logginggetArtifactLoggerr  r  r   rY  r<  r.  torch._inductor.fb.utilsro   r   r   r   r   r   r   r  r   r  rv   rx   rw   <module>ra     s   " " " " " "               				 				 



  # # # # # # % % % % % % J J J J J J J J J J J J J J J J                              , , , , , , 4 4 4 4 4 4 4 4 ? ? ? ? ? ? : : : : : : 7 7 7 7 7 7 7 7        5 4 4 4 4 4 : : : : : : ? ? ? ? ? ? L L L L L L L L	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	       / / / / / / / / / / / / - - - - - - ! ! ! ! ! ! ! ! ! !	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	            % $ $ $ $ $                                                       $ # # # # # 8 8 8 8 8 8 & & & & & &                            ( ' ' ' ' ' ' '  ><<<<<<<<<<      ;;;;;;$$$$$$$$$$$$555555!!!!!!,,,,,,:'<<=N 5 5 5 5 5 5 g!!00<HHy~*9?,, 6 8888888      (   
      $R/ R/ R/ R/jb!3 b!3 b!3 b!3 b!3EH( b!3 b!3 b!3JC
 
 
 
 
} 
 
 
 
 
rx   