
    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j6                  e      Zej<                  j?                  ed,      ZejB                  jD                  Z ejF                         Z eEjJ                         rd d-lmZ nd8d.Zd9d/Zd:d0Z	 	 	 	 	 	 d;d1Zd<d2Z	 	 	 	 	 	 d=d3Z G d4 d5ejZ                  j\                        Z G d6 d7e      Zy)>    )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_codec                      y N )argskwargss     O/var/www/html/engine/venv/lib/python3.12/site-packages/torch/_inductor/graph.pyro   ro      s        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 y )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)constant_buffers    ru   may_get_constant_buffer_dtyper      s    %,,

EJJ4F4F4N4NO  	r 
 /5::#5#5#=#=>{{/5::.#O44!!{{		!	!}}rv   c                6    t        d t        D              }| |v S )Nc              3  2   K   | ]  }t        |        y wrq   )r   ).0ms     ru   	<genexpr>z"is_magic_method.<locals>.<genexpr>   s     HQ-a0Hs   )r'   r   )op	magic_opss     ru   is_magic_methodr      s    H-HHI?rv   c           	         |j                  d      }| }t        |      D ]=  \  }}t        ||      s t        ddj	                  |d |              t        ||      }? |S )N.z#Node referenced nonexistent target )split	enumeratehasattrRuntimeErrorjoingetattr)objtargettarget_atomsattr_itriatoms         ru   getattr_recursiver      sv     <<$LH\* +4x&5chh|BQ?O6P5QR  8T*+ Orv   c                b   i }| j                  d      d   }d|j                  vr|S t        |j                  d   t        j
                  j                        s|j                  d   }n|j                  }t        |      D ],  \  }}||j                  d   v s|j                  d   |   ||<   . |S )Noutputr   r   user_visible_output_idxsoriginal_output_strides)
find_nodesmetarx   rs   r~   fxr%   r   )gretoutput_nodeoutput_node_argsidxnodes         ru   get_user_visible_output_stridesr      s    ')C,,(,+A.K!)9)99
k&&q)588==9&++A.&++/0 I	T+""#=>>#(()BCCHCII Jrv   c                   t         j                  sy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  }t+        |j,                  t.        j0                  j2                  j4                        rd|j6                  d<   Lt+        |j,                  t.        j8                  j:                        rJt=        |j,                        t.        j>                  j@                  jB                  k(  rd|j6                  d<    ||      }|s||v rd|j6                  d<   |j6                  jE                  dd      r0|jF                  D ]!  } ||      }|s||vsd|j6                  d<   # t         jH                  r@||v sFd|j6                  d<   W y)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.
    Nc                    | j                   dk(  rZt        | j                  t        j                  j
                        r,t        | j                  d      r| j                  j                  S d S )Ncall_function_overloadpacket)r   rx   r   r~   _ops
OpOverloadr   r   )r   s    ru   _get_overload_packetz8mark_nodes_dislike_padding.<locals>._get_overload_packet   sU    
 ww/)4;;

(=(=>%67	 KK''	
 	
rv   Tdislike_paddingF)r   torch.fx.Nodereturnz%Optional[torch._ops.OpOverloadPacket])%r*   comprehensive_paddingr'   atenconvolutionconvolution_backward
_scaled_mmvar_meansummeanprodanyaminamaxminmaxargminargmaxscatter_reducereversednodesrx   r   r~   _higher_order_opstriton_kernel_wrapTritonKernelWrapperMutationr   r   r   r   _CTagneeds_exact_stridesgetall_input_nodespad_outputs)	r   user_visible_output_stridesops_dislike_paddingops_like_paddingr   curr   priorprior_ops	            ru   mark_nodes_dislike_paddingr      s    ''$%%OO	
 "MMHHIIIIHHIIIIHHHHKKKK	
"



	.

    /JJ##66RR
 +/CHH&' szz5::#8#89)#**5xx||//0 +/CHH&'!#&$$*.CHH&'88<<)51,, 9/6#3348EJJ019 !!c-H&H*.CHH&'A /rv   c                      e Zd ZU ded<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dC	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dD fdZdEdZ	 	 	 	 dFdZ	 	 	 	 dGdZ	 	 	 	 dHd	Z	 	 	 	 dId
Z		 	 	 	 	 	 dJdZ
dKdZdLdZej                  dMd       ZdNdZedOd       ZdPdZ	 	 	 	 	 	 	 	 dQdZdRdZdSdZdTdZedUd       Z	 	 	 	 dVdZdWdZ	 	 	 	 dXdZdYdZdZdZd[ fdZd\dZ ddd]dZ!d^d Z"	 	 	 	 d_d!Z#dSd"Z$d`d#Z%	 	 	 	 	 	 dad$Z&	 db	 	 	 	 	 dcd%Z'ddd&Z(	 	 	 	 	 	 	 	 de fd'Z)df fd(Z*edgd)       Z+	 	 	 	 	 	 	 	 dhd*Z,did+Z-did,Z.	 	 	 	 	 	 	 	 dj fd-Z/dEd.Z0edkd/       Z1edld0       Z2	 	 	 	 	 	 	 	 	 	 	 	 dmd1Z3dn fd2Z4	 	 	 	 	 	 dod3Z5dEd4Z6	 	 	 	 dp	 	 	 	 	 	 	 	 	 dqd5Z7	 	 	 	 drd6Z8	 	 dsd7Z9dEd8Z:dsd9Z;dtd:Z<	 	 dud;Z=dZ>d<ed=<   dvd>Z?dvd?Z@	 	 	 	 dwd@ZAdxdAZBdydBZC xZDS )zGraphLoweringzlist[ir.IRNode]graph_outputsNFc                
   t         |   |       || _        ||n| j                  ||	      | _        d| _        |	| _        |
| _        || _        || _	        || _
        || _        || _        d| _        |t               }d| _        nd| _        || _        |j"                  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)        |jM                               n	t)               | _'        |r|jP                  ni | _(        |r|jR                  ni | _)        |r|jT                  ni | _*        i | _+        i | _,        i | _-        t)               | _.        t)               | _/        t)               | _0        t)               | _1        t)               | _2        t)               | _3        d | _4        d | _5        ddl6m7} tq        jr                         r|r|n|| _:        d | _;        i | _<        t)               | _=        g | _>        i | _?        t        t              | _B        i | _C        t        j                         | _E        || _F        || _G        || _H        || _I        i | _J        || _K        || _L        t        t              | _O        d | _P        d | _Q        d | _R        d | _S        d | _T        | j                  r| j                         n	t)               | _V        t)        dg      | _W        t        |j                        | _Z        t        |j                  | j                         d| _\        d| _]        g | _^        d | __        i | _`        |j                         | _b        | j                  jS                         D ]  \  }}|| jR                  |<    | j                  jU                         D ]  \  }}|| jT                  |<    | j                  j                  j                  d	i       | _f        ||j                  ni | _g        t                 t        j                  d       t              | _k        i | _l        t)               | _m        t)               | _n        t)               | _o        t)               | _p        t)               | _q        t        j                         | _t        d
| _u        t               | _w        i | _x        y )N)is_inferencer   FTcpu)extern_node_json_serializerzaten.convolution_backward  dynamo_flat_name_to_original_fqn)ysuper__init__example_inputsdecide_layout_opt
layout_optnum_channels_last_convr   is_backwardis_const_graphconst_wrapper_codeconst_kernel_codeconst_moduleinputs_to_checkextra_tracebackr"   reuse_shape_env
_shape_envdeferred_runtime_assertscopyras_by_symbolr'   ry   rz   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
operationsconst_output_index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_fbcodeextern_node_serializercurrent_nodelistsmutated_inputsmutated_input_idxsname_to_bufferr   listname_to_users
name_to_optimecreation_timenamecpp_wrapper
fx_wrapperrecord_multi_kernel_choicemulti_kernel_to_choiceaot_modegraph_id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)selfgmr   	shape_envr%  r   r$  r   r  r   r   r   r  r   r   r   r  r   r!  r   kv	__class__s                         ru   r   zGraphLowering.__init__&  s   . 	, % '''F 	
 '(#(&,"4!2(.$ 
I#(D #'D # ..335 	 '1&>&@#(3,.VX=?"AE9C%)5L%%:< 	 )5L$$*, 	 ! <>"(*.0"4" 	
 " )..01 	 '3L"" 	 +7L&&B 	 .:L))r 	
  	  79.03=<0:8B$0:4>L 3=<-126V !&< #, 	# ,0+-
/9|-/46@KD@Q35!YY[	&$
 +6'68#  "&'?"@>B @DGK:> 7; 7;ooD002:< 	' !+,G+H I+J288+T("288T-M-MN !  	 9=& GI -/[[]LL..0 	&DAq$%Dq!	&LL113 	)DAq'(D!!!$	)040@0@0D0D.1
- 5A4LL00RT 	$ 	"#$=I$7$7$=>R$S!;= 3=,5?\!:D,&1; :D% &OO-  "/1 46 rv   c                8    | j                   j                          y rq   )r   freeze_runtime_assertsrI  s    ru   rP  z$GraphLowering.freeze_runtime_asserts  s    ..0rv   c                2   | j                   r2t        |j                               t        |j                               fS ddlm}  |dt        | j                  j                               }| j                  j                  ||      \  }}}|D cg c]4  }t        |t        j                        r|j                  j                  n|6 }}|D cg c]4  }t        |t        j                        r|j                  j                  n|6 }	}||	fS c c}w c c}w )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_)r   rU   sizestridetorch._dynamo.sourcerS  lenr   
var_to_val,create_symbolic_sizes_strides_storage_offsetrx   r~   SymIntr   expr)
rI  exrS  sourcerU  rV  _r   r_sizer_strides
             ru   symbolic_sizes_stridesz$GraphLowering.symbolic_sizes_strides  s     ,RWWY79R		:   < $,S1K1K-L,MNF LL	 NRRAu||!<!&&++!CRROUV!:a#>AFFKKAEVVx SVs   9D9Dc                    |j                         D cg c]  }t        j                  |       }}|j                         D cg c]  }t        j                  |       }}||fS c c}w c c}w )z+
        Primarily used to weights
        )rU  ry   r}   rV  )rI  r]  r   rU  rV  s        ru   static_sizes_stridesz"GraphLowering.static_sizes_strides  sZ     +-'')4Qa 44,.IIK8q%--"88V| 58s   A%A*c                P   t        |t        j                        r|j                  }t        |t        j                        r|j                  }t        |t        j
                        r1|j                  | j                  v r| j                  |j                     S |j                         S rq   )	rx   r+   rD   datarC   ComputedBufferr  r   get_size)rI  r   s     ru   get_allocation_sizez!GraphLowering.get_allocation_size  su     dBLL)99DdBMM*99DtR../		T777--dii88==?"rv   c                    |j                         }| j                  |      }|j                  }|j                  }t	        |||      S rq   )
get_layoutri  rV  offsetr   )rI  r   layoutrU  rV  rl  s         ru   get_allocation_storage_sizez)GraphLowering.get_allocation_storage_size1  sA     "''-.tVVDDrv   c                h    t        |t              sJ |       || j                  t        |            v S rq   )rx   r-   r0   r=   )rI  r   features      ru   has_featurezGraphLowering.has_feature:  s4    
 '>2;G;2$33OF4KLLLrv   c                    || j                   vr2d}	 |j                         s|j                         }|| j                   |<   | j                   |   S # t        $ r Y )w xY w)zc
        Get the size hint for a dependency with caching to avoid expensive recomputation.
        r   )rH  has_unbacked_symbolsnumbytes_hintKeyError)rI  depress      ru   get_dep_size_hintzGraphLowering.get_dep_size_hintB  so     d...C//1++-C -0D$$S)'',,   	s    A 	AAc                8    | j                   x}r|S t        d      )NzNo current device)r-  r   rI  r   s     ru   get_current_device_or_throwz)GraphLowering.get_current_device_or_throwS  s$    (((6(M233rv   c              #  b   K   | j                   }|| _         	 d  || _         y # || _         w xY wwrq   )r-  )rI  r   r   s      ru   set_current_devicez GraphLowering.set_current_deviceY  s1     ##$	("'D%Ds   /# /	,/c                8    | j                   ry| j                  ryy)N	inferencebackwardforward)r   r   rQ  s    ru   get_training_phasez GraphLowering.get_training_phaseb  s    rv   c                  t         j                  syt         j                  ry| j                  j                  D cg c]@  }|j
                  t        j                  j                  j                  j                  k(  s?|B }}t        |      }|dk(  ryt        j                  j                  j                  r;t        j                  j                  j                         rt!        d |D              ryt        t#        | j                  j                              d|z  k\  rt$        j'                  d       yt)        d |D              rt$        j'                  d       ydd	}dd
}dd}|rt+        t,              }|D ]@  }	t/        |	      }
|
 ||	      rd}n ||	      rd}n ||	      rd}nd}||xx   |
z  cc<   B t$        j'                  d       d}d}d}d}t1        |j3                               }|d   |z  |d   |z  z   |d   |z  z   |d   |z  z   }||k  }|st$        j'                  d||       |S t)        t5        ||            rt$        j'                  d       yt)        t5        ||            rt$        j'                  d       yt!        t5        ||            rt$        j'                  d       yyc c}w )zl
        Decide if we should enable layout optimization for this graph based on
        heuristics.
        FTr   c              3     K   | ]A  }d D ]:  }|j                   |   j                  d   j                  j                  t        v  < C yw)r   r)   valN)rs   r   r   typer_   r   nr   s      ru   r   z2GraphLowering.decide_layout_opt.<locals>.<genexpr>  sR      !  s  '..337OOOs   AA	i,  z*Skipped layout opt because only a few convc              3  t   K   | ]0  }d D ])  }t        |j                  |   j                  d          + 2 ywr  )r   rs   r   r  s      ru   r   z2GraphLowering.decide_layout_opt.<locals>.<genexpr>  sE      

  QVVC[--e45
5
s   68zeSee perf regression with dynamic shape. Follow up in https://github.com/pytorch/pytorch/issues/102670c                    | j                   d   j                  d   }t        |t        j                        sJ | j                   d   dkD  xr |j                  d      dkD  S )Nr)   r  r   )rs   r   rx   r~   r   rU  )r  meta_vals     ru   
is_groupedz3GraphLowering.decide_layout_opt.<locals>.is_grouped  sQ    vvay~~e,Hh55566":>:hmmA&6&::rv   c                   | j                   d   j                  d   j                  d      dz  | j                   d   j                  d   j                  d      k  xr. | j                   d   j                  d   j                  d      dkD  S )Nr)   r  r      rs   r   rU  r  s    ru   is_in_out_channelz:GraphLowering.decide_layout_opt.<locals>.is_in_out_channel  sv    q	u%**1-1QVVAY^^E5J5O5OPQ5RR 6FF1INN5)..q1A5rv   c                    | j                   d   j                  d   j                  d      dk  xr. | j                   d   j                  d   j                  d      dk  S )Nr)   r  r   @   r  r  s    ru   is_small_channelz9GraphLowering.decide_layout_opt.<locals>.is_small_channel  sT    q	u%**1-3 8FF1INN5)..q1R7rv   groupedsmallin_outdefaultz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   r   bool)r  r   r   r  )r*   layout_optimizationforce_layout_optimizationr1  r   r   r~   opsr   r   r  rX  backendsmkldnnenabledis_availableallr  logdebugr   r   floatr9   r   valuesmap)rJ  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                      ru   r   zGraphLowering.decide_layout_opti  s    ))++ xx~~
UYY^^5O5O5W5W)WA

 
 JA: NN!!))%%224 #  
 tBHHNN#$e3IIBC 

 

 IIw 	;
		 ,7,>K" 8 .t 4 (d# )I%d+ 'I&t, (I )II&-7&8  		67
 "'!& %$k0023K I&);;g&)99:h'*;;< i(+==>  +k9M 		~"
 ! & s:z*+IIX  s$j12IIT  s#Z01IIVW]
s   A J;<J;c                @    | j                   | j                    d| S |S )z2Prepend the given name with the graph name if any.r_  )r  rI  r  s     ru   qualify_namezGraphLowering.qualify_name  s&    99 ii[$((rv   c                    t        | ||| j                  | 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.
        )
parentrJ  r   rK  r   r$  r  r   r   r  )SubgraphLoweringr   r   r$  r  r   r   r  )rI  rJ  r   subgraph_names       ru   make_subgraphzGraphLowering.make_subgraph  sZ      )oo((]]#'#>#>**((""=1
 	
rv   c                   t        t                  }t        | j                  j                  j
                        D ]w  }|j                  t        j                  j                  j                  j                  k(  r|j                  |       P|j                  D ]  }||v s|j                  |        w y | j                  j                  j
                  D ]"  }||v s|j                  |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   r9  r1  r   r   r~   r  r   r   r  addusersupdate)rI  
output_setr  users       ru   r.  z-GraphLowering.find_nodes_prefer_channels_last&  s    &  %'
$++++112 	Axx599>>55===q! :%NN1%	0 ""(( 	+AJ!!!''*	+ rv   c                    || j                   vr2| j                   j                  |       t        j                  d|       y y )NzUsing FallbackKernel: %s)r0  r  perf_hint_loginfor  s     ru   warn_fallbackzGraphLowering.warn_fallbackX  s:    t,,,!!%%d+94@ -rv   c                R   | j                   j                  |j                         |j                  %| j                  j                  |j                         t
        j                  j                  r7|| j                  vr(t
        j                  j                  | j                  |<   y y y rq   )	r   r  r  indexr   rb   r1  r  r6  rz  s     ru   add_device_infozGraphLowering.add_device_info]  sy    fkk*<<#  .77F$2J2J$J/0ww/C/CD$$V, %Krv   c                "    t         j                  S rq   )rb   	fake_moderQ  s    ru   r  zGraphLowering.fake_moded  s    {{rv   c           	        || j                   v r| j                   |   S || j                  v r| j                  |   S || j                  v rzt        j                  j                  |   }t        j                  |t        j                  |j                  |j                  gt        j                  j                  |             S y Nr  rm  )r  r   r  rb   r1  r+   ConstantBufferr<   r   dtyperd  )rI  buffer_namerf  s      ru   try_get_bufferzGraphLowering.try_get_bufferh  s     $---&&{33$+++$$[11$..(77$$[1D$$ ~~KK./gg.J.J4.P  rv   c                    t        d      )Nz'Should not be called for the main graph)r   )rI  symbols     ru   add_symbol_graph_inputz$GraphLowering.add_symbol_graph_inputz  s    DEErv   c                H    | j                  |      }||S t        d|       )Nz$Failed to find buffer matching name )r  r   rI  r  bufs      ru   
get_bufferzGraphLowering.get_buffer}  s1     !!+.?JA+OPPrv   c                   || j                   v r| j                   |   j                  S t        | j                  d      r|| j                  j                  v ro| j                  j                  |   }|| j
                  v r| j
                  |   j                         S || j                  v r| j                  |   j                         S || j
                  v r| j
                  |   j                         S || j                  v r| j                  |   j                         S t        j                  d|      }|r | j                  |j                  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  r  	get_dtyper   rematchgroupru  )rI  r  mutated_bufr   s       ru   r  zGraphLowering.get_dtype  s7   $..(>>+.444 DNN$89t~~@@@..;;KHKd111**;7AACCd///((5??AA$---&&{3==??$+++$$[1;;==HHI;W>>!''!*--677rv   c                F   || j                   v r| j                   |   j                         S || j                  v r0| j                  |   }|j                         sy|j	                         S || j
                  v r| j
                  |   j	                         S t        d|       )Nr)   r  )r  numelr  has_tensor_output	get_numelr   ru  r  s      ru   r  zGraphLowering.get_numel  s    $..(>>+.4466$---%%k2C((*==?"$+++$$[1;;==677rv   c                ^    t        d      5  t        |   | cd d d        S # 1 sw Y   y xY w)NzGraphLowering.run)r   r   run)rI  rs   rN  s     ru   r  zGraphLowering.run  s-    -. 	&7;%	& 	& 	&s   #,c                   |j                   
J d|        t        |t        j                        sJ | j	                  dt        | j                               }| j                  j                  |       || j                  |<   ||_         |S )NzOperation registered twice: r   )	operation_namerx   r+   	Operationr  rX  r   appendr  )rI  r   r  s      ru   register_operationz GraphLowering.register_operation  s      (M,H*MM("bll+++  2c$//&:%;!<=r" " rv   set_namec                  | j                  dt        | j                               }| j                  j                  |       || j                  |<   |j                         }|St        |t        j                        r(|j                         r|t        j                  d      k(  s| j                  |       |r||_        |S )Nr  r   )r  rX  r   r  r  
get_devicerx   r+   rg  is_zero_elementsr~   r   r  r  )rI  bufferr  r  r   s        ru   register_bufferzGraphLowering.register_buffer  s      3s4<<'8&9!:;F#$*D!""$ 62#4#45++-ell511   (FKrv   c                j    | j                  ddj                  |      z         }|| j                  |<   |S )Nlist_r_  )r  r   r  )rI  operation_namesr  s      ru   register_operation_listz%GraphLowering.register_operation_list  s3      388O+D!DE*

4rv   c                &     d fd |       y )Nc                    t        | t        t        f      r| D ]
  } |        t        | t        j                        r4| j                         D ]   }j                  |   j                  |        " y y rq   )rx   r  tupler+   rD   get_read_namesr  r  )valuex	read_nameregisterrI  s      ru   r  z1GraphLowering.register_users_of.<locals>.register  sm    %$/  AQK %.!&!5!5!7 @I&&y188?@ /rv   )r  %Union[Iterable[ir.IRNode], ir.IRNode]r   Nonerr   )rI  node_outputr  s   ` @ru   register_users_ofzGraphLowering.register_users_of  s    	@ 	rv   c                    t        |t              sJ | j                  j                  |       || j                  vry| j                  |   D ]  }|j                           y)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)rx   strr  r  r  realize)rI  r  r  s      ru   mark_buffer_mutatedz!GraphLowering.mark_buffer_mutated  s\    
 $$$$  &t)))&&t, 	DLLN	rv   c                    || j                   v r|| j                  v s
J d|z          t        | j                   |         }|| j                  j                  v r| j                  j                  |   S | 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 )r:  r  rW   r9  r   )rI  r  	orig_names      ru   get_original_value_of_constantz,GraphLowering.get_original_value_of_constant  s     t3338N 	
2T9	
N 5T5Q5QRV5WX	 DKK,,, KKY'	
 %	
rv   c                   t         j                  j                  s2| j                  j	                         D ]  \  }}t        ||      s|c S  |dt        | j                         }|}|d   j                         rd| }| j                  |      }t        |      }|}d}|| j                  v r| d| }|dz  }|| j                  v r|| j                  |<   |j                  d|j                  dt        |j                               dt        |j                               dt        |      d	| j                   |<   || j"                  |<   |S )Nconstantr   	constant_r_  r)    r  )r*   aot_inductoruse_runtime_constant_foldingr  itemsr[   rX  isdigitr  r]   r   r  r  rU  rV  hashr	  r:  )rI  r  rf  constant_namer  r  prefixcnts           ru   allocate_non_dup_const_namez)GraphLowering.allocate_non_dup_const_name  sZ    ""??(,(<(<(> )$u!$.(() <c$..123D	7??tf%D  &  %dnn$XQse$D1HC dnn$  $t{{oQtzznATYY[!$AeDKKM&:%=QDz!n 	D!
 .7$$T*rv   c                    | j                  ||      }t        j                  t        j                  |t        |j                  |j                  g| j                  |                   S r  )	r  rD   creater+   r  r<   r   r  rd  )rI  rf  r  new_names       ru   add_tensor_constantz!GraphLowering.add_tensor_constant  sb     33D$?"KK.2.G.G.M
 	
rv   c                X   | j                   |   j                  |k(  s||S t        j                  j                  j                         5  | j                  | d|j                   |j                  xs d | j                   |   j                  |            cddd       S # 1 sw Y   yxY w)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.
        Nr_  r   )
r  r   r~   utils_python_dispatch_disable_current_modesr  r  r  to)rI  r  device_overrides      ru   r  zGraphLowering.constant_name$  s     >>$&&/9_=TK[[))@@B 	 33&/../0E0E0J/KLt$''8	 	 	s   	AB  B)c                2	   | xj                   dz  c_         t        | 	  |||      }| j                  |      }t	        |t
              rrt        j                  j                  st        |j                        }n|j                  j                  }|| j                  |<   | j                  j                  |       |S t	        |t        t         t"        f      rAt%        j&                  |      }|| j                  |<   | j                  j                  |       |S t	        |t(              r9t+        ||      }|| j                  |<   | j                  j                  |       |S || j                  j                  |       y t	        |t,              r| j                  j                  |       y t	        |t.        j0                        rt3        t        j                  j4                  j6                        dk(  rt9        t;        t        j                  j4                  j6                              j<                  t.        j>                  j@                  jB                  t.        jD                  jF                  jH                  fv sJ tK        jL                  ||jN                        }|| j                  |<   | j                  j                  |       |S t	        |t.        jP                        sJ |       |jR                  s| jU                  |      \  }}	n| jW                  |      \  }}	| j                  re| jX                  rY| j                   | jX                  v rAt[        j\                  t_        |ta        |jN                  |jb                  ||	                  }
n@t[        j\                  te        |ta        |jN                  |jb                  ||	                  }
|
| j                  |<   | j                  j                  |       |
jf                  jf                  | jh                  |<   | j4                  j6                  r| jk                  |jN                         tm               5  to        |      s| jp                  js                  |       d d d        |
S # 1 sw Y   |
S xY w)Nr)   r  r  )r  r   r  ):rF  r   placeholderr  rx   r$   rb   r1  r   r   r   r\  r   r   r  intr  r  ry   sympifyr   rE   r   r~   	GeneratorrX  r  r  r&  iterr   _prims	rng_primsgraphsafe_run_with_rng_stater  higher_orderinvoke_subgraphr+   GeneratorStater   r   _has_symbolic_sizes_stridesrd  rb  rG  rD   r  r;   r<   r  r?   rf  r   r  r\   r^   r>  r  )rI  r   rs   rt   exampler\  r   gensizesstridestensorrN  s              ru   r#  zGraphLowering.placeholder4  s    	!'%fdF;""6*gx( 77&&,W\\:||(((,Df%""))&1K#tU!34==)D(,Df%""))&1K!12!vW=C(+Df%""))&1J_""))&1g}- ""))&11qww++112a7DQWW))//0=f&&CC		&&66=   ##GC(+Df%""))&1J'5<<09'90
 22!66w?NE7!88ANE7 $$$$(<(<<%%&w~~w}}eWUF %%&w~~w}}eWUF %+&!%%f--3[[-=-=""6*""  0 12 	3.w7&&**62	3 	3 s   'RRc                   t         j                  u r/t        |d   t        t        t
        f      rt        |   ||      S t        t        j                  j                        st        d      r |i |S t        vrMt        t        j                  j                        s
J  d       j                         j                  d      d   }|t         v rt#        dd       nt$        j&                  rt)        g      rt*        nt,        }t.        j1                  d|j3                  ||             t5        d	      }|<t        j6                  j8                  j;                        r| j<                  rt>        }nt5        d	      }tA        |      }t#        |
       n&t)        g      rt+        ||      t-        ||      	 t.        jC                  dt                  | jD                  }	tG              }
|
r||}}|
tH        u rd|	jJ                  v r|	jJ                  d   \  }}t        t        j                  j                        sJ dfd} |||      \  }} |||      \  }} |||      \  }}tI        ||||      \  }}n |
|	g|i |\  }}t           |i |}|
r| jM                  |	||       |S # tN        $ r-}tQ        |||      jS                  |jT                        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_valsc                v    t         j                  j                  j                  | |      }|J |d   |d   fS )Nr   r)   )r~   r   operator_schemasnormalize_function)rs   rt   resultr   s      ru   	normalizez.GraphLowering.call_function.<locals>.normalize  sE    %*XX%>%>%Q%Q &f&F $*#55#5#)!9fQi#77rv   )rs   r   rt   r   r   ztuple[Any, Any])+operatorgetitemrx   r  r  dictr   r   r~   r   OpOverloadPacketr   rK   r   r  r   rH   rL   r*   implicit_fallbacksr   r7   r8   r  r  operator_strr   _libraryr  
is_builtinr   rO   rP   r  r  rM   rF   r   propagate_mutation	Exceptionr6   with_traceback__traceback__)rI  r   rs   rt   	base_nameerrortagdecided_constraintdefault_tagr  layout_constraintsold_args
old_kwargs	fake_argsfake_kwargsr?  outerN  s    `                ru   r   zGraphLowering.call_function  s   X%%%*T!WtUD>Q*R7(v>> &%**"="=>71D
 4*6**"fejj&;&;< (/0< ++C03I//f5$G** *6(3 .5 
 9&&vtV<
 /H/ K,,77?(( *<&0IT1K *B+)N&f8JK#VH- 0fEE264HH0	IIj)F"34!!A!9&!A!'+V*%)BB
 *QVV3128J1K.	;  *&%**2G2GHHH8 2;9k1R.	;'0v'>f/8:/N,*'@ &)[(f $6a#I$#I&#ILD&F#T4V4C! ''8ZvNJ 	#AvtV<KK	s   C9K 	L(K>>Lc                Z    t        | j                        dk(  xr | j                  d   dk  S )zM
        True if this is a small constant attr that will be inlined.
        r)   r      )rX  shape)ts    ru   can_inline_constantz!GraphLowering.can_inline_constant  s(    
 177|q 4QWWQZ1_4rv   c                   t        | j                  |      }t        |t        j                  j
                        rE|| 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| j+                  ||      S t-               5  |j.                  dk(  r9t1        |j3                         |j4                  |j6                        cd d d        S | j9                  |      r[t:        j=                  dt?        |             ddl m!}  ||jE                         |j4                  |j6                  	      cd d d        S 	 d d d        | j+                  ||      S # 1 sw Y   xY w)
N)r  graph_moduler   r"  rr   )r  r  r   zInlining constant: %s r)   )r3  )r  r   )#r   r9  rx   r~   r   rh   r  r+   Subgraphr   ScriptObjectr  r	  rE   r   r   r*   r  r  always_keep_tensor_constantsrQ   r  r&   rZ  r:   itemr  r   r\  r  r  r  loweringr3  tolist)rI  r   rs   rt   r  rV  r3  s          ru   get_attrzGraphLowering.get_attr  s    "$++v6eUXX112,,,**622++6>C*-D'JeUXX223/4D$$V,*,D'"e<</0/4D$$V,*,D'"e<<%...<<22(/++E6::] 
	V{{b **,ekk%,,
	V 
	V
 ''.		2CK@,ellnEKKU
	V 
	V
 /
	V ''v66
	V 
	Vs   7?I A"IIc                    t         rq   AssertionErrorrI  r   rs   rt   s       ru   call_modulezGraphLowering.call_moduleG      rv   c                    t         rq   rg  ri  s       ru   call_methodzGraphLowering.call_methodJ  rk  rv   c                d   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 cg c]!  }t        j                  j                  |      # }}g }t        |      t        |      k(  sJ t        ||      D ]C  \  }}	t        |t        j                   t        j"                  f      s|j%                  |       Ct        |j'                         t        j(                        r/|j%                  t        j                  j+                  |             t,        j.                  j                  j1                  |      sJ |	j2                  d   j5                         D 
cg c]4  }
t        |
t,        j6                        r|
j8                  j:                  n|
6 }}
|j%                  t        j<                  ||             F || _        | j@                  jC                         D ]_  \  }}t        |tD              rt        |t         tF        jH                  t,        j.                  j                  jJ                  f      sJ dt        |              t        |t               s|jM                          t        |t               sJ |jN                  }t        |t        jP                        sJ |}|jN                  }t        |tR              r|jU                         |k7  st        jV                  jY                  || jZ                  |          	 | j>                  j]                  |      }| jZ                  |   | j>                  |<   b | ja                          tb        je                  d| jf                  | jh                  | jh                         y d       y c c}w c c}
w # t^        $ r Y w xY w)Nc              3  8  K   | ]  }t        |t        t        j                  t	        d       t        j
                  t        j                  t        j                  j                  j                  t        t        j                  t        j                  f	        y wrq   )rx   rD   r+   r:   r  r  ry   r   logicboolalgBooleanr$  EffectfulKernelrB   )r   r  s     ru   r   z'GraphLowering.output.<locals>.<genexpr>X  sp      
  KKJ%%JJKK''//&&,,

s   BBr   r  z'Unsupported inductor graph input type: zGForce channels last inputs for %d conv for the current graph with id %dr   )5r   r   rx   r  r  r  r  rb   r1  r  rs   r+   ExternKernelrealize_inputrX  ziprD   BaseViewr  get_output_specCommBufferLayout
copy_inputr~   	_inductoris_storage_and_layoutr   rV  r[  r   r\  try_match_insignificant_stridesr   r   r  rE   ry   r   r-  r  rf  rC   r?   get_nameMutationLayoutSHOULDREMOVErealize_intor   r  
ValueErrorfinalizer  r  r   r%  )rI  r   rs   rt   r>  fx_node_argsr  result_correct_stridesrfx_nodesmeta_stridesr  r  value_storage_boxindrN  s                   ru   r   zGraphLowering.outputM  s    f5&5$-0YF&5$-0>$v,>0 
 
 
 	  !	 
$ ww++003,6(?L<BCq"////2CC!#< CK///fl3 	JAwa",,!<=&--a0A--/1D1DE '--boo.H.H.KL ))??BBB %\\%0779  $.a#>AFFKKAE    '--66q,G#	* 4,,224 	KD%%1	5::u/A/A/P/PQ G8eFG  eY/MMOeY///JJEeR]]333 %JJEe[1U^^5E5M--::455d;,,223DEC.2.H.H.ND&&s+-	4 			U''!]]6DMM	
 =?	
m D" B " s   /&P"9P7P""	P/.P/c                F    | j                   D ]  }|j                           y rq   )r   decide_layout)rI  r  s     ru   r  zGraphLowering.finalize  s!    << 	 C	 rv   c              #  b   K   | j                   }	 || _         d  || _         y # || _         w xY wwrq   )r  )rI  r   olds      ru   set_current_nodezGraphLowering.set_current_node  s1     	$ $D #DDs   /# /	,/c              #  T   K   | j                   }	 d  || _         y # || _         w xY wwrq   r  )rI  r  s     ru   set_current_wrapper_codez&GraphLowering.set_current_wrapper_code  s)     	$ #DDs   ( (	%(c                    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                  j                  |d   |d   |j                         D ci c];  \  }}|t        |t        j                  j                        r|j                  d   n|= c}}|d         }	|	D ]X  }
|d   |
   }|d   |
   }||u r j!                  t        j                  j"                  j$                  j&                  ||fi        Z yt        |j                  t        j(                  j*                        sJ 	 	 	 	 	 	 	 	 d fd}|j                  j,                  }t/        t1        ||            D ]!  \  }\  }}|j2                  |   } ||||       # |j2                  D ci c]  }|j4                  | }}|j7                         D ]  }||   }||   }||   } ||||        yc c}}w c c}w )	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.
        rt   
kernel_idxconstant_args_idxr  tma_descriptor_metadataNc                L   ||u ry | j                   | j                   j                  r{t        |t        j                        r|f}|f}t        ||      D ]K  \  }}||u rj                  t        j                  j                  j                  j                  ||fi        M y y y rq   )
alias_infois_writerx   r+   IRNoderv  r   r~   r  r   copy_r  )
schema_argold_argnew_argold_arg_itemnew_arg_itemrI  s        ru   maybe_propagatez9GraphLowering.propagate_mutation.<locals>.maybe_propagate  s     '!$$0Z5J5J5S5S gryy1&jG&jG25gw2G .L,#|3 &&		,,44|\6RTV 6T0rv   )r  ztorch._C.Argumentr  	ir.IRNoder  r  r   r   )rX  r   r~   r  r+  triton_kernel_wrapper_mutationrt   rx   rB  r   r   get_mutated_tensorsr  r   r%   r   r   r   r  r  r   r   _schemar   rv  	argumentsr  r  )rI  r  rR  rS  new_args
new_kwargsrt   rL  rM  mutatedr  r  r  r  schemar   r  argschema_kwargskeys   `                   ru   rH  z GraphLowering.propagate_mutation  sU     8}H---:#j/111>>UYY33RRR^^H-Ffd+++--@@TT<(./ !'1 
1ehhmm(Dqvve}!K 45G   Y$X.t4$X.t4g%""599>>#7#7#?#?'7ASUWXY '..%***?*?@@@	)	4=	HQ		( '''0Xx1H'I 	:#C#'7))#.JJ9	: 392B2BC33CC??$ 	:C oG oG&s+JJ9		:YT Ds   A I	Ic                #   $%& d&fd}ddl m} t         j                        %t         j                        &t        g      }j                  dk(  }|r# j                        \  }}|t        ||      z  }t        j                  j                  |      5   j                        5  t        j                        5  j                  dk(  rj                  rt        j                  t         j"                  j$                        r{t         j&                  j(                  j+                  j                        rHt-              s|j/                  ddfd      r' |d        t1        j                  d	
      i }nj                  dk(  rj                  t         j2                  j4                  j6                  u rt8        j:                  dk7  r |d       t8        j:                  dk(  r}	}
j<                  j?                  d      x}r|d   }|d   }tA        ||||      \  }}ntC        g|i |\  }} jE                  j                  ||      } jG                  |	|
||       ntI        dt8        j:                         tK        j                        r |d       t        j<                  d   t         jL                  t         jN                  t         jP                  f      r$j<                  d   jR                  jT                  }n'tV        '         }n |d       tV        '         }t         j2                  jZ                  j\                  j^                  t         j2                  jZ                  j`                  j^                  t         j2                  jZ                  jb                  j^                  t         j2                  jZ                  jd                  j^                  t         j2                  jZ                  jf                  j^                  g$ti        d jj                  D              } jl                  v }ti        $fdjj                  D              }j<                  j?                  dd	      rt        |tn              r|jq                          j<                  d   js                         }t!        jt                  j(                  jv                  | }|jy                         |k7  r7|s5t        jz                  |      }t        j|                  j                  ||      }|rDt        |tn              r4t        |j                  t        j                        r|jq                          |s|r%t        j<                  d   t         j                        r|r jl                  j?                        }nj<                  d   js                         }|t        |      dkD  rt8        j                  xs | xr | }t         j                  j                  j<                  d         }t        t        |            dkD  }|sl|rjt        |j                               dk(  rN j                  v r@|s>|s<t        j                  j                  |j                         t         j                        }|st        |      r؉j<                  d   j                         s$t        |j                  t        j                        r6t        j|                  j                  |t        jz                  |      |      }na|D cg c]4  }t        |t         jL                        r|jR                  jT                  n|6 }}t        j|                  j                  |||      }t        t        jj                              }|dkD  rt        |tn              rjj                  D ]  }|j                  t        v rn|j                          t         j2                  jZ                  j                  j^                  t         j2                  jZ                  j                  j^                  t         j2                  jZ                  j                  j^                  g}g } j                  s=|j                  t         j2                  jZ                  j                  j^                         t         j                  j                  r|t         j2                  j                  j                  j^                  t         j2                  j                  j                  j                  t         j2                  jZ                  j                  j^                  t         j2                  j                  j                  j^                  t         j2                  j                  j                  j                  t         j2                  j                  j                  j                  t         j2                  j                  j                  j                  gz  }|t         j2                  j                  j                  j^                  t         j2                  j                  j                  j                  t         j2                  j                  j                  j                  t         j2                  j                  j                  j^                  t         j2                  j                  j                  j^                  t         j2                  j                  j                  j                  gz  }t         j                  j                  r2|t         j2                  j                  j                  j^                  gz  }|j                  |v rPt        j|                  j                  |t        jz                  j<                  d   js                               d      }|j                  |v rd|j                  d   u rSt        j|                  j                  |t        jz                  t        j<                  d   j                                    }|j                  dk(  st        |j                  j                  t        t        f      s|jq                           |j                  t        jj                               t        |tn              r |j                         r|j                          t        |tn              rbt        |j                  t              rH|j                  j                  }t        |t              r"|j                  d      r|jq                          d d d        d d d        d d d        t        tn              r#t        |j                  t        j                        rt        |j                  j                  t        j                        r(|j                  j                  j                  d       nt        |j                  j                  t        j                        ry|j                  j                  j                  d       t        |j                  j                  t        j                        rit        |j                  j                  j                  t        j                        r1|j                  j                  j                  j                  d       nt        |j                  j                  t        j                        r|j                  j                  j                  snt        |j                  j                  j                  d   t        j                        r3|j                  j                  j                  d   j                  d        j                  |       t        t        j                            } j                  %d  D ]  }||j                         z  }  j                  &d  D ]  }||j                         z  } t        j                  j                  j                  } j                  dk(  r=t        |t        j                        r#| j                  |      r|j                  |       d'%& fd}!t        j                  j                  rj                  dk(  r|S t        t        j                  j                  j                  j<                  j?                  d i             }"|"J t        d! |"j                         D              }#||#k\  s'J d"| d#|# d$j	                          d% |!                j                  |       |S c c}w # 1 sw Y    xY w# 1 sw Y   %xY w# 1 sw Y   *xY w)(Nc                Z    t         j                  dt        j                        |        y )Nzlowering %s %s)r  r  r   format_node)msgr  s    ru   r  z%GraphLowering.run_node.<locals>.debug  s    II&
1==(A3Grv   r   )CompilerBisectorr   inductorrK   c                     t               S rq   )reprr  s   ru   <lambda>z(GraphLowering.run_node.<locals>.<lambda>'  s    a rv   rI   F)add_to_fallback_setflexible_layout-user_defined_triton_kernel_layout_constraintsneeds_fixed_stride_orderr:  r)   z1Unknown triton_kernel_default_layout_constraint: r   r  r   c              3  :   K   | ]  }|j                   d k(    yw)r   Nr   )r   r  s     ru   r   z)GraphLowering.run_node.<locals>.<genexpr>h  s     DDDGGx/Ds   c              3  :   K   | ]  }|j                   v   y wrq   )r   )r   r  as_strided_opss     ru   r   z)GraphLowering.run_node.<locals>.<genexpr>j  s      *26~-*   inductor_realize_to_strides   )allow_paddingTr   d   )	thresholdorigin_noder#  c                     j                   d  D  cg c]  } d| j                          d|  d }} |j                  d j                  d  D               dj	                  |      S c c} w )Nunbacked_symbol_defs= in:

c              3  J   K   | ]  }d |j                          d| d  yw)r  r  r  N)get_unbacked_symbol_defs)r   r   s     ru   r   zBGraphLowering.run_node.<locals>.format_new_defs.<locals>.<genexpr>6  s2       ((C(C(E'FfRDPRSs   !#z***
)r   r  extendr   r   )r  r  buffer_watermarkoperation_watermarkrI  s     ru   format_new_defsz/GraphLowering.run_node.<locals>.format_new_defs1  s      <<(8(9: ((D(D(F'GvcURTUA  HH //*=*>?  <<?"s   A)unbacked_bindingsc              3     K   | ]8  }t         j                  j                  j                  j	                  ||       : y wrq   )rb   r  rK  unbacked_renamingsr   )r   r  s     ru   r   z)GraphLowering.run_node.<locals>.<genexpr>g  s5      /
 KK!!4488A>/
s   >A zfailed  >= z (inductor >= fx)
fx node is: z
new operations are:

)r  r  r   r   r   r  )!torch._inductor.compiler_bisectorr  rX  r   r   r'   r   fetch_args_kwargs_from_envrV   r+   r  current_originsr  rb   r   rx   r~   r   r   rF  r  rG  rJ   disable_subsystemrI   r  r+  r  r*   'triton_kernel_default_layout_constraintr   r   rF   rG   r   rH  r   r   r[  SymFloatSymBoolr   r\  r   run_noder   
as_stridedr  as_strided_as_strided_scatterresize	resize_asr   r  r   rD   r  rV  r{  any_is_symbolicmaybe_get_strideget_stride_orderrt  require_stride_orderrf  rw  r   r   _prims_commonis_non_overlapping_and_denser   rh  r/  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_pointwiser3  binary_tensor_convolution_pointwise_convolution_pointwise_ _convolution_transpose_pointwiseqconv_pointwiseqconv2d_pointwisehas_mklmkl_mkl_linearrs   r   rZ  r@   rA   
mark_reusehas_exceeded_max_readsrC   has_large_inner_fnLoops_post_init_setattrBufferrg  MultiOutputindicesinputsr  ry   rz   r  r1  r   rK  is_unbacked_symintr  r   r    r  r  create_deferred_runtime_asserts)(rI  r  r  r  originsis_call_functionrs   rt   r>  rR  rS  r:  inp_args
inp_kwargs	is_outputis_user_visibleis_input_for_as_stridedr2  sym_stridesstride_orderr  denseunbacked_symbols_in_stridesr  	num_usersr  need_fixed_layoutneed_fixed_channels_last_layoutcurrnew_unbacked_defsr  r   rK  r  r  renamed_unbacked_bindingsr  r  r  rN  s(   ``                                  @@@ru   r  zGraphLowering.run_node
  sV   	H 	Gt||,!$//2 $.qc?44?2::1=LD&~dF33GII%%g.j	)!!!$j	) q!j	) 'HHqxx)>)>?NN((33AHH=9!<'99"K
 ()N)!((N
 'HH		 6 6 U UUBBFWWEFBB12  $H!'J+,66::6H+II'I#3A#6%5a%8
'@ &(J(f (?q'R4'R6'Rf!//$GF++AxT6R&KFLzLzK{|  !* '(FF5MELL%..%--#P VVE]//44F"W-a0Fb	)!, 		))11		**22		1199		%%--		((00N DAGGDDI4#C#CCO&) *:;''* '# vvzz7?J	E  &&-..0#oo33CCWM**,7#%#6#6w#?L__AA&,WFvy1v{{BKK8  4*uu||; #">>BB1EGffUm224G&3w<!+;**A/.A%655 " "//LLuE 1':;a? 0 8! 12a7!@!@@ / 7"$"3"3"T"T"OO-u/B/B# 73w< 66%=113z"KK8 &(__%I%I & " 3 3G <.; &J &F *1'$% 0:!U\\/JPQ Q'G ' &(__%J%J &} &K &F Jqww/0I1}FI!>GG ;-D{{&;;++- "IINN??GG!IINN--55!IINN22::-)
 ;=7#-44UYY^^5O5O5W5WX 88//- %		 0 0 B B J J %		 0 0 B B I I %		 ? ? G G %		 0 0 B B J J %		 0 0 B B I I %		 0 0 B B I I %		 0 0 B B P P2 - < %		 0 0 G G O O %		 0 0 G G N N %		 0 0 H H O O %		 0 0 Q Q Y Y %		 0 0 @ @ H H %		 0 0 B B I I@ ;  %xx// 1eiimm6O6O6W6W5X X 1;;*;;%'__%I%I & " 3 3AFF5M4H4H4J K.2 &J &F !KK+JJ !TYYq\ 1%'__%I%I & " 3 3$B166%=CVCV$W!"&F ww(*%fkk&6&6I8NO"NN,w;-| !!#agg,/ &),1N1N1P ##% &),FKK1T{{''dI....=(Uj	) j	) j	)h fi(ZR]]-S&++**BHH5  33M1EFKK,,bii8  33M1Efkk..0A0ABzKK$$))288H KK$$))<<]AN v{{//@"KK,,44!&++"2"2"9"9!"<biiH((//2EEmUVWv&&u||46<< 0 12 	@C!=!=!??	@//"5"67 	?B!<!<!>>	? GG$$..	
 DDM!65<<0,,V4!!&)		# 77144=#8M. 6GG&&

3F(K
 !,,, %/ /
&++-/
 %
!
 !$== 	
'(-F,G H==?+ ,&&5&7%8:	
=
 	,,Q0ABS'aj	) j	) j	) j	) j	) j	)sr   AF:.AF-ZAF 	9AF
S9AF =*AF )CAF AF-
AF:FAF F AF*F%AF-F-AF7	F2AF:F:AGc                     d	 fd}t               rw|j                  t        j                  j                  j
                  j                  k(  r< j                  r0 j                  |      \  }}|d   dk7  r ||d   |d    d       y y  xj                  |z  c_	        t        j                  j                  j                  }|D ]G  } j                  j                  |g       }|j                   |   }	|j#                         j%                  |	      srd
d}
 |
|	j&                        r% |||	j&                  k\  | d|	j&                           |
|	j(                        r% |||	j(                  k  | d|	j(                          |D ]  }t+        |j,                        }| j                  z
  }|r=t/        |t0              } j                  j3                  |g       j5                  |       f ||j,                  |j,                           J y )Nc                z    t        j                  | |      }j                  |d       j                  |       y )NTr  )r+   AssertScalarr  r  )r\  r  	assert_oprI  s      ru   make_assertzBGraphLowering.create_deferred_runtime_asserts.<locals>.make_assert  s4    c2I  T :##I.rv   r   Tz to be Truec                Z    | t         t          fv ry	 t        |        y# t        $ r Y yw xY w)NFT)r(   r$  	TypeError)r  s    ru   is_convertiblezEGraphLowering.create_deferred_runtime_asserts.<locals>.is_convertible  s5    & 11#()F#'( )#()s    	**r  z <= )r  )r\  r#   r  r  r   r   )r  r   r   r  )r   r   r~   r  r   _assert_scalarr  r$  r  r   rb   r1  r   rK  r   popvar_to_range _default_unspecified_value_rangeissubsetlowerupperr   r\  r   r  
setdefaultr  )rI  r  r  r  	node_argsr_  rK  i0rasvrr!  rafvsmissingi1s   `              ru   r  z-GraphLowering.create_deferred_runtime_assertst  s   D	/ %&EIINN99AAA::1=LIq|t#IaLYq\N+*FG $ ''+<<'((22I ( ;((,,R4++B/ AACLLRP) &bhh/#B"((Nrd$rxxj4IJ%bhh/#B"((Nrd$rxxj4IJ ;B/8C!D$?$??G c2**55b"=DDRH#BGGy:;);rv   c                    t         j                  rt        d      t        j                  dvrt        dt        j                         y )NzC++ codegen is disabled)linuxdarwinwin32zUnsupported platform )r*   disable_cpp_codegenr5   sysplatformrQ  s    ru   !validate_can_generate_cpp_wrapperz/GraphLowering.validate_can_generate_cpp_wrapper  s@    %%()BCC<<;;(+@)OPP <rv   c                   | j                   j                         }|j                  d       |j                  d       t        |      dk  s%J dj	                  dj                  |                   t        |      dk(  }|rdn|j                         | _        | j                  r| j                          t        | j                        | _        t        | j                  | j                  | j                        }|J d| j                   d       |j                  ||||      | _        | j                   r0| j                   j                  j"                  | j                  _        y y )	Nr   r   r)   zDoes not support mixing {}+r   zDevice z not supported)r   r   discardrX  formatr   r#  r   r   r9  r1   r  r2   r!  r  r  r   _names_iter)rI  is_subgraphr  parent_wrapper_codepartition_signaturesr   only_cpuwrapper_code_gen_clss           ru   init_wrapper_codezGraphLowering.init_wrapper_code  sP    ((--/U#V$< A% 	
'C'J'JHH\"(
 	
% |$)$,5,2B2B2D2241$2B2BC=d.. 
 $/ 	
d&&'~6	
/ 177 	
 ,0,=,=,J,J,V,VD) rv   c                @   dd l }|j                  | j                        }|j                  |      }g }|j                  j                  D ]T  }|j
                  dk(  s|j                  t        j                  j                  j                  u sD|j                  |       V g }i }i }g }	i }
|D ]  }|j                  d   D ]R  }|D ]K  }||v rt        |t        j                  j                        s-t!        |      ||<   |j                  |       M T |j                  d   }t        j"                  j$                  j'                  |j                  d   |j                  d   |j)                         D ci c];  \  }}|t        |t        j                  j                        r|j*                  d   n|= c}}|j                  d         }i }|j                  j-                  |      5  |j)                         D ]  \  }}||v rL|j                  j/                  t        j0                  |f	      }t!        |	      ||<   |	j                  |       V||
v r	|
|   ||<   ct!        |	      |
|<   |	j                  |       |
|   ||<    	 d d d        |||j2                  <    |	|z   }|j                  j                  D ]$  }|j
                  d
k(  st5        |      f|_         n |j9                          t        j                  j;                  |      }|j=                  |      }t!        |      dkD  r|t!        |	      d  }i | _        |D ]  }d}g }|j                  d   D ]t  }g }|D ]Q  }t        |t        j                  j                        s|j                  |       9d}|j                  |||             S |j                  t5        |             v |s|| j>                  |j2                  <    |d t!        |	       | _         || _!        y c c}}w # 1 sw Y   xY w)Nr   r   gridrt   r  r  r  r  )rs   r   FT)"r   deepcopyr8  r1  r   r   r   r~   r  r+  r  r  rt   rx   r   r%   rX  r   r   r  r  r   inserting_beforer   cloner  r  rs   	recompileInterpreterr  r,  r*  r+  )rI  r   r   	cloned_gmtriton_nodesr   grid_inputsvisited_gridstriton_inputskwargs_inputsvisited_kwargsrF  r  rt   rL  rM  r  r  new_nodenew_outputsrunnerreturned_outputsgrid_outputsdynamic_grid	new_gridsnew_grids                             ru   extract_autotune_inputsz%GraphLowering.extract_autotune_inputs  s    	MM$,,/	~6OO)) 	*D?*KK599#9#9#X#XX##D)	* ,.24(*-/)+  &	2DF+ 0 0Cm+ !#uxx}}5-0-=c*#**3/00 [[*F--@@TTL)/0 !'1 
1ehhmm(Dqvve}!K 56G *,J11$7 6"LLN 6DAqG|#,??#@#@TUSW#@#X(+M(:
1%,,X6 N*(6q(9
1 (+M(:N1%!((+$21$5JqM66 (2M$))$M&	2P $k1OO)) 	Dww("";/1		
 	%%i0!::n5{a+C,>,@AL$&D!$ A$.0	 KK/ 6D!H# J)#uxx}}=$OOC0$'+ ]35G(HIJ $$U8_56  7@D))$))4A  "22FC4F!G"/m6 6s   5A P(BPP	c                j    t         fddD              rd fd}t        j                  j                  rut        j                  j                  rKd} j
                  D ]   }t        |t        j                        sd} n |r |       } j                  |        j                         S d _         j                         j                  } |       }t        j                  j                   j#                         5   ||       ddd       ~d _         j$                  j'                           j(                  j'                           j*                  j'                          t,        j.                  j0                  j2                  j'                          t,        j.                  j0                  j4                  j'                          t7        j8                          t        j:                  ddi      5   j                         cddd       S  j                         S # 1 sw Y   xY w# 1 sw Y   yxY w)	zQ
        For GPU, Triton kernels are autotuned and stored as cubin files
        c              3  :   K   | ]  }|j                   v   y wrq   )r   )r   r   rI  s     ru   r   z9GraphLowering.codegen_with_cpp_wrapper.<locals>.<genexpr>Y  s     Ivv***Ir  )cudaxpuc                    	 	 	 	 dd} t         j                  j                  j                         }|t	        t
        j                  t              sy|j                  r|j                  j                          |j                  D cg c]  }|| }}t        j                  |t
        j                        D cg c]
  } | |       }}nMt	        t
        j                  t              rj                  nt
        j                  D cg c]
  } | |       }}j                  rddlm} t#        j$                        D cg c]2  \  }}|j                  v rt	        ||   t         j&                        r|4 }	}}|	D ]/  }||   }
t	        |
t         j&                        sJ  ||
      ||<   ~
1 |S c c}w c c}w c c}w c c}}w )Nc                .   | y 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)rx   r~   r[  r  r   hintr   r   r   r  r  )r  s    ru   materializezXGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.materialize\  sx     y##Aenn'EF vv{{*#Az2%ay()!U\\: Ds4PQ7|S:  !rv   r)   )clone_preserve_strides)r  z1Union[torch.SymInt, torch.SymFloat, torch.Tensor]r   zUnion[int, float, torch.Tensor])r~   _guardsTracingContexttry_getrx   rb   real_inputsra   output_stridesclearparams_flatrC  chainr   r  
compile_fxrd  r   r   r   )rc  tracing_contextparamrk  r  rh  rd  r   r  r  mutated_inprI  s              ru   extract_real_inputszCGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs[  s   !H!4!  #(--">">"F"F"H".zMM;8 '55'66<<> &5%@%@#! , #K # "+amm!L# $A#K #  *!--E !//!"# $A#K # &&B *343D3D)E*%C4#6#66&{3'7F *& *  2 ( '2#&6)+u||DDD+A++NC('( #"W#
##*s   F29F7F<7GFTNztriton.autotune_at_compile_time)r   %list[Union[int, float, torch.Tensor]])r   r*   tritonautotune_at_compile_timeautotune_with_sample_inputsr   rx   r+   UserDefinedTritonKernelr[  codegenr   compile_to_modulecallr~   r  r  r  r  rj  r
  r  rb   r1  r   precomputed_replacementsinv_precomputed_replacementsr,   resetpatch)rI  rq  user_defined_kernelsr   rh  compileds   `     ru   codegen_with_cpp_wrapperz&GraphLowering.codegen_with_cpp_wrapperS  s    IIIC#J }}55 ==<<+0("oo "%b"*D*DE370!" ,&9&;44[A||~% $) 1138813[[11HHJ *[)* $( $$**,''--/''--/  99??A  ==CCE\\#De"LM *<<>* * <<>!!* ** *s   <	H2H)H&)H2c                    ddl m} t        j                  dd      5   || j                        | _         ddd       y# 1 sw Y   yxY w)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   )rI  r  s     ru   _update_schedulerzGraphLowering._update_scheduler  s;     	)\\.6 	8&t7DN	8 	8 	8s	   >Ac                L   t        dd      5  | j                          | j                          t        j                  j                  | j                  | j                  j                         | j                  j                  |        | j                  j                          t        j	                  dt        j                  j                         | j                  j                  | j                         }| j                  j#                          |cd d d        S # 1 sw Y   y xY w)NzGraphLowering.codegenTlog_pt2_compile_eventzFFinished codegen for all nodes. The list of kernel names available: %s)r   rD  r  rb   r  draw_orig_fx_graphr8  r)  r   r  push_codegened_graphrw  r  r1  rB  generater   pop_codegened_graph)rI  r>  s     ru   rw  zGraphLowering.codegen  s    1N 	""$""$GG&&t||T^^5I5IJ2248NN""$IIX00
 &&//0A0ABF113!	 	 	s   DDD#c                   t        dd      5  |j                  | _        |j                  | _        |j                  | _        | j	                          | j
                  j                          ddd       y# 1 sw Y   yxY w)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)  rw  )rI  parent_graphs     ru   codegen_subgraphzGraphLowering.codegen_subgraph  sj     :RVW 	% , 9 9D*55DO+77D""$NN""$	% 	% 	%s   AA55A>c                    d}g }g }| j                   j                  D ]N  }|j                         }||z  }|j                  ||dz  f       |j                  ||j	                         f       P |||fS )Nr   r  )r)  r   get_read_write_buffers_sizesr  get_estimated_runtime)rI  total_bytesnode_countsnode_runtimesr   	num_bytess         ru   count_byteszGraphLowering.count_bytes  s    
 NN(( 	GD99;I9$Ki1n56  $(B(B(D!EF		G K66rv   zOptional[Callable[[str], None]]save_output_codec                l    t        dddd      5  | j                         cd d d        S # 1 sw Y   y xY w)NzGraphLowering.compile_to_modulecode_genT,inductor_code_gen_cumulative_compile_time_us)
phase_namer  dynamo_compile_column_us)r   _compile_to_modulerQ  s    ru   rx  zGraphLowering.compile_to_module	  s9    -!"&%S	
 	- **,	- 	- 	-s   *3c                   | j                   r| j                         n| j                         \  }}t        |t              r| j                  |      }n*t        |t              r|}nt        dt        |             |j                  J t        |j                         t        j                  d|j                         t        j                  d|j                         t        j                   r(t#        d|j                   t$        j&                         t(        j                  j+                  |j                         t(        j                  j-                  t.        j0                  j3                  |j                        d   dz          |S )Nz Unrecognized wrapper code type: Output code written to: %szCompiled module path: )filer   z.debug)r   r  rw  rx   r`   _compile_to_module_linesr/   NotImplementedErrorr  __file__ro   r  r  rm   r  r*   benchmark_kernelprintr7  stderrrb   output_coder   ospathsplitext)rI  r  r_  mods       ru   r  z GraphLowering._compile_to_module	  s$    04/?/?D))+T\\^ 	a l$45//=C&;<C%243E2FG  ||'''%		.=93<<H""*3<<.9

K	CLL)	RWW%%cll3A6AB
rv   c                   ddl m} t        j                  j                  rw| j
                  j                  j                         }|j                  dd      }d|z   | j
                  j                  j                         z   dz   }|j                  z   _
        t        j                  t        j                  j                         t        j                  dj                         t        j                          }t#        j$                  |j                         	 j&                  D cg c]  \  }}||j(                  f }}}|j+                  j                        \  }	t        j                  d	       t-        d
fdfd       t1        dd      5  |j3                  |	|i | j4                  | j6                        }
d d d        |	| _        | _        || _        t        j>                  r#t        j@                  r
jC                  dd       
S c c}}w # t.        $ r t-        d
fd        w xY w# 1 sw Y   wxY w)Nr)   )PyCodeCachez"""z\"\"\"z%"""
Compile-time auto-tuning block: 
z"""
zOutput code: 
%s)coder  inductor_output_codec                     d iS )Nfilenamerr   )r  s   ru   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>Y	  s    T* rv   c                      j                   S rq   r  r  s   ru   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>Z	      <#5#5 rv   )
payload_fnc                      j                   S rq   r  r  s   ru   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>S	  r  rv   zPyCodeCache.load_by_key_pathTr  )linemapattrs)timesrepeat)"	codecacher  r*   rs  rt  r  kernel_autotune_defsgetvaluereplacekernel_autotune_callsr  r   r  rm   r  rR   inductor_meta_from_configrS   begin_compileline_mapstack_tracewriter   rI  r   load_by_key_pathr  r  r2  r3  r4  benchmark_harnessprofile_bandwidth_outputbenchmark_compiled_module)rI  r  r  r  tuning_codeinductor_metaline_nor   r  r  r  r  s    `         @ru   r  z&GraphLowering._compile_to_module_lines/	  s+    	+==11#'#4#4#I#I#R#R#T #7#?#?{#S 7&' ##99BBDE 	  "-|/A/A!AL))5**<+=+=>1<3E3EF&@@B**=|?Q?QR	 &2%:%:!GT $**+G  $)),*<*<=IC!!">E &*5
 8PTU 	..DD4+C+CD	 / C	 $##(G(G))!)<
E  	&5
 		 	s*   H$ .H7H$ .IH$ $H?Ic                   g }t        j                  d      }t        j                  d      }| j                  D ]  }t        |t        j
                        r*|j                  | j                   dt        |              Gt        |t        j                        r*|j                  | j                   dt        |              |j                  |j                                 |S )Nr   _none_shape)rC  rD  r   rx   r+   NoneAsConstantBufferr  r  r&  rB   r~  )rI  namesshape_counternone_counterr   s        ru   get_output_nameszGraphLowering.get_output_namesm	  s    !* q)&& 	.D$ 7 78		{%\0B/CDED"":":;		{&m1D0EFGT]]_-	. rv   c                .   || j                   j                         v xrh | j                   |   j                         dk(  xrF t        | j                   |   j	                               dk(  xr t        | j                   |         dk(  xs || j                  v S )Nr)   r   r   )r   r  r  rX  rh  r=   r   r  s     ru   is_unspec_argzGraphLowering.is_unspec_argz	  s     D%%**,, B!!$'113q8BD%%d+44671<B   1 1$ 78EA	3
 T222	3rv   )NNNFFNNFFFNNNNNNF)&rJ  torch.fx.GraphModuler   zOptional[Sequence[object]]rK  zOptional[ShapeEnv]r%  zOptional[int]r   r  r$  r  r   zOptional[bool]r  z4Optional[Callable[[list[ir.ExternKernelNode]], Any]]r   r  r   r  r   r  r  zOptional[dict[str, int]]r   Optional[str]r   r  r   zOptional[GraphLowering]r  r  r   zOptional[Sequence[int]]r!  r  r   r   )r   r   )r]  torch.Tensorr   z=tuple[Sequence[Union[int, Expr]], Sequence[Union[int, Expr]]])r]  r  r   z)tuple[list[sympy.Expr], list[sympy.Expr]])r   zOUnion[ir.TensorBox, ir.StorageBox, ir.Buffer, WorkspaceArg, ir.TorchBindObject]r   zSequence[Expr])r   z2Union[ir.Buffer, WorkspaceArg, ir.TorchBindObject]r   r   )r   z.Union[torch._inductor.ir.IRNode, device, None]rp  r-   r   r  )rv  rk   r   r$  )r   torch.device)r   r  r   Iterator[None]r  )rJ  rh   r   r  r   r  )r  r  r   r  )rJ  r  r   zlist[torch.Tensor]r  r  r   r  )r   zOrderedSet[Node])r  r  r   r   )r   r  r   r   )r   z,torch._subclasses.fake_tensor.FakeTensorMode)r  r  r   z<Optional[Union[ir.TensorBox, ir.Buffer, ir.TorchBindObject]])r  
sympy.Exprr   r   )r  r  r   z2Union[ir.TensorBox, ir.Buffer, ir.TorchBindObject])r  r  r   ztorch.dtype)r  r  r   zUnion[int, Expr])rs   r   r   r   )r   zir.Operationr   r  )r  z	ir.Bufferr  r  r   r  )r  	list[str]r   r  )r  r  r   r   )r  r  r   r  )r  r  rf  zUnion[Tensor]r   r  rq   )rf  r   r  r  r   z*Union[TensorBox, ir.ShapeAsConstantBuffer])r  r  r   zOptional[torch.device]r   r  )r   r  rs   tuple[object]rt   dict[str, object]r   zUnion[Expr, TensorBox, None])r   r   rs   r   rt   dict[str, Any]r   r   )r[  r  r   r  )r   r  rs   z	tuple[()]rt   r  r   zOUnion[Constant, TensorBox, ShapeAsConstantBuffer, ir.Subgraph, TorchBindObject])r   r   rs   r   rt   r   r   r   )r   r  rs   r  rt   r  r   r   )r   r   )r   r  )r  r   rR  
tuple[Any]rS  r  r  r  r  r  r   r   )r  r   r   object)r  r   r  zOrderedSet[sympy.Symbol]r   r   FNNN
r?  r  r  r  r@  zOptional[PythonWrapperCodegen]rA  z!Optional[GraphPartitionSignature]r   r   )r   rr  r   r   )r   z)tuple[ValueWithLineMap, ValueWithLineMap])r  r   r   r   )r   zVtuple[int, list[tuple[BaseSchedulerNode, int]], list[tuple[BaseSchedulerNode, float]]])r   CompiledModule)r  r`   r   r  )r   r  )r  r  r   r  )E__name__
__module____qualname____annotations__r   rP  rb  rd  ri  rn  rq  rx  r{  
contextlibr   r}  r  staticmethodr   r  r  r.  r  r  propertyr  r  r  r  r  r  r  r  r  r  r  r  r	  r  r  r  r#  r   r\  re  rj  rm  r   r  r  r  rH  r  r  r9  rD  r[  r  r  rw  r  r  r  rx  r  r  r  r  __classcell__rN  s   @ru   r   r   #  s   ""
 6:(,"&!%) "!$7;,0+/04"37 +E6 E6 3E6 &	E6
  E6 E6 E6 #E6!
E6 E6 E6 E6 5E6  *!E6" )#E6$ .%E6& 'E6( 1)E6* +E6, 
-E6N1# # 	F# J	2#
#
 
#$EFE	EM>M  M 
	M-"4 ( ( Y Yv
 
 +
 	

 

60dA
D  	E$FQQ	;Q8,
8& FK (
@	
 !)6	@ 37

"/
	3
 ff f "	f
 
&fPob 5 51717 17 "	17

17f[
[
 [
 "	[

 
[
z  $ $ $ $I:I: I: #	I:
 I: #I: 
I:VhTS;S;3KS;	S;jQ "'+>BBF#W#W %#W <	#W
 @#W 
#WJ\0C\0	\0|p"	2p"d	8&%$7
7" 9=5<-<<,<	<|3rv   r   c                  L     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.
    c                2    || _         t        |   |i | y rq   )r  r   r   )rI  r  rs   rt   rN  s       ru   r   zSubgraphLowering.__init__	  s    $)&)rv   c                f    t         |   d| j                  | j                  j                         y )NT)r?  r  r@  )r   rD  r  r  r  )rI  r?  r  r@  rA  rN  s        ru   rD  z"SubgraphLowering.init_wrapper_code	  s.     	!)) $ 8 8 	" 	
rv   )r  r   rs   r   rt   r   r   r   r  r  )r  r  r  __doc__r   rD  r  r  s   @ru   r  r  	  sV    
* "'+>BBF

 %
 <	

 @
 

 
rv   r  )rs   r   rt   r   r   r   )r   r  r   zOptional[torch.dtype])r   r   r   r  )r   rh   r   r  r   z1Union[Tensor, torch._C.ScriptObject, GraphModule])r   ri   r   dict[Node, tuple[int, ...]])r   ri   r   r  r   r   )
__future__r   r  r;  rC  loggingr@  r  r  r7  r  collectionsr   r   typingr   r   r   r	   r
   r   ry   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   rc  rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   runtimerR   runtime.autotune_cacherS   r   rT   r  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   rD  r'  r  torch._inductor.fb.utilsro   r   r   r   r   r   r   rK  r   r  rr   rv   ru   <module>r     s   "      	 	 
  # % J J        , 4 ? : 7 5 : ? L	 	 	  / / - ! !	 	 	  %       $ 8 &    ( << ;$$5!,:'<<=N 5 g!00<Hyy~~*9??, 68(
	!6$R/R/+FR/	R/j_!3EHH(( _!3DC
} 
rv   