
    rh                      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lFmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z` ddlambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZm ddlnmoZo ddlpmqZq ddlrmsZs dd ltmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZ dd!lmZmZ er5d d"lmZmZmZ d d#lmZ d d$lmZ d d%lmZ d d&lmZ dd'lmZ dd(lmZ eeeKf   Zd d)lmZ  ej,                  e      Zej2                  j5                  ed*      Zej8                  j:                  Z ej<                         Z eEj@                         rd d+lmZ nd6d,Zd7d-Zd8d.Z	 	 	 	 	 	 d9d/Zd:d0Z	 	 	 	 	 	 d;d1Z G d2 d3ejP                  jR                        Z G d4 d5e      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)ConstantDonatedBufferFixedLayoutget_device_typeGraphPartitionSignatureInputBuffer	Pointwise	Reduction
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)BaseSchedulerNode)output_code_log
perf_hints)log_module_codec                      y N )argskwargss     h/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/torch/_inductor/graph.pyrl   rl      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int64rW   
is_integeris_floatfloat32)constant_buffers    rr   may_get_constant_buffer_dtyper      s    %,,

EJJ4F4F4N4NO  	r 
 /5::#5#5#=#=>{{/5::.#O44!!{{		!	!}}rs   c                6    t        d t        D              }| |v S )Nc              3  2   K   | ]  }t        |        y wrn   )r   ).0ms     rr   	<genexpr>z"is_magic_method.<locals>.<genexpr>   s     HQ-a0Hs   )r'   r   )op	magic_opss     rr   is_magic_methodr      s    H-HHI?rs   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         rr   getattr_recursiver      sv     <<$LH\* +4x&5chh|BQ?O6P5QR  8T*+ Ors   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metaru   rp   r{   fxr%   r   )gretoutput_nodeoutput_node_argsidxnodes         rr   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 Jrs   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   ru   r   r{   _ops
OpOverloadr   r   )r   s    rr   _get_overload_packetz8mark_nodes_dislike_padding.<locals>._get_overload_packet   sU    
 ww/)4;;

(=(=>%67	 KK''	
 	
rs   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nodesru   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	            rr   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 /rs   c                      e Zd ZU ded<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dB	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dC fdZdDdZ	 	 	 	 dEdZ	 	 	 	 dFdZ	 	 	 	 dGd	Z	 	 	 	 dHd
Z		 	 	 	 	 	 dIdZ
dJdZej                  dKd       ZdLdZedMd       ZdNdZ	 	 	 	 	 	 	 	 dOdZdPdZdQdZdRdZedSd       Z	 	 	 	 dTdZdUdZ	 	 	 	 dVdZdWdZdXdZdY fdZdZdZddd[dZ d\dZ!	 	 	 	 d]d Z"dQd!Z#d^d"Z$	 	 	 	 	 	 d_d#Z%	 d`	 	 	 	 	 dad$Z&dbd%Z'	 	 	 	 	 	 	 	 dc fd&Z(dd fd'Z)eded(       Z*	 	 	 	 	 	 	 	 dfd)Z+dgd*Z,dgd+Z-	 	 	 	 	 	 	 	 dh fd,Z.dDd-Z/edid.       Z0edjd/       Z1	 	 	 	 	 	 	 	 	 	 	 	 dkd0Z2dl fd1Z3	 	 	 	 	 	 dmd2Z4dDd3Z5	 	 	 	 dn	 	 	 	 	 	 	 	 	 dod4Z6	 	 	 	 dpd5Z7	 	 dqd6Z8dDd7Z9dqd8Z:drd9Z;	 	 dsd:Z<dZ=d;ed<<   dtd=Z>dtd>Z?	 	 	 	 dud?Z@dvd@ZAdwdAZB xZCS )x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        g | _6        ddl7m8} ts        jt                         r|r|n|| _;        d | _<        i | _=        t)               | _>        g | _?        i | _@        t        t              | _C        i | _D        t        j                         | _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        y )N)is_inferencer   FTcpu)extern_node_json_serializerzaten.convolution_backward  dynamo_flat_name_to_original_fqn)x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'   rv   rw   bound_unbacked_symbolsrR   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extern_kernel_nodes&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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_idxrV   bw_donated_idxs)selfgmr   	shape_envr"  r  r!  r   r  r   r   r   r   r   r   r   r  r   r   kv	__class__s                        rr   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rs   c                8    | j                   j                          y rn   )r   freeze_runtime_assertsrE  s    rr   rL  z$GraphLowering.freeze_runtime_asserts  s    ..0rs   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   rS   sizestridetorch._dynamo.sourcerO  lenr   
var_to_val,create_symbolic_sizes_strides_storage_offsetru   r{   SymIntr   expr)
rE  exrO  sourcerQ  rR  _r   r_sizer_strides
             rr   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
        )rQ  rv   rz   rR  )rE  rY  r   rQ  rR  s        rr   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 rn   )	ru   r+   rB   datarA   ComputedBufferr  r   get_size)rE  r   s     rr   get_allocation_sizez!GraphLowering.get_allocation_size  su     dBLL)99DdBMM*99DtR../		T777--dii88==?"rs   c                    |j                         }| j                  |      }|j                  }|j                  }t	        |||      S rn   )
get_layoutre  rR  offsetr   )rE  r   layoutrQ  rR  rh  s         rr   get_allocation_storage_sizez)GraphLowering.get_allocation_storage_size*  sA     "''-.tVVDDrs   c                h    t        |t              sJ |       || j                  t        |            v S rn   )ru   r-   r0   r<   )rE  r   features      rr   has_featurezGraphLowering.has_feature3  s4    
 '>2;G;2$33OF4KLLLrs   c                8    | j                   x}r|S t        d      )NzNo current device)r*  r   rE  r   s     rr   get_current_device_or_throwz)GraphLowering.get_current_device_or_throw;  s$    (((6(M233rs   c              #  b   K   | j                   }|| _         	 d  || _         y # || _         w xY wwrn   )r*  )rE  r   r   s      rr   set_current_devicez GraphLowering.set_current_deviceA  s1     ##$	("'D%Ds   /# /	,/c                8    | j                   ry| j                  ryy)N	inferencebackwardforward)r   r   rM  s    rr   get_training_phasez GraphLowering.get_training_phaseJ  s    rs   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}|rBddlm} t/        t0              }	|D ]  }
t        j2                  j4                  j7                  |
      \  }}}|r~ |d      5 }t8        j:                  5   |
j
                  |i | ddd       ddd       j=                         } ||
      rd}n ||
      rd}n ||
      rd}nd}|	|xx   |z  cc<   t$        j'                  d        d}d}d}d}t?        |	jA                               }|	d   |z  |	d   |z  z   |	d   |z  z   |	d   |z  z   }||k  }|st$        j'                  d||       |S t)        tC        ||            rt$        j'                  d       yt)        tC        ||            rt$        j'                  d       yt!        tC        ||            rt$        j'                  d       yyc c}w # 1 sw Y   UxY w# 1 sw Y   ZxY 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)rp   r   r   typer]   r   nr   s      rr   r   z2GraphLowering.decide_layout_opt.<locals>.<genexpr>i  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rz  )r   rp   r   r}  s      rr   r   z2GraphLowering.decide_layout_opt.<locals>.<genexpr>x  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   )rp   r   ru   r{   r   rQ  )r~  meta_vals     rr   
is_groupedz3GraphLowering.decide_layout_opt.<locals>.is_grouped  sQ    vvay~~e,Hh55566":>:hmmA&6&::rs   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      rp   r   rQ  r~  s    rr   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rs   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    rr   is_small_channelz9GraphLowering.decide_layout_opt.<locals>.is_small_channel  sT    q	u%**1-3 8FF1INN5)..q1R7rs   )FlopCounterMode)displayN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_optimizationr.  r   r   r{   opsr   r   r  rT  backendsmkldnnenabledis_availableallr  logdebugr   torch.utils.flop_counterr  r   float	_inductorfx_utilsget_fake_args_kwargsr`   	fake_modeget_total_flopsr   valuesmap)rF  r   r~  
conv_nodesnconvr  r  r  r  flop_countsr   successrp   rq   flop_counter_modecounted_flops	node_typeGROUPED_MULTIPLIERDEFAULT_MULTIPLIERIN_OUT_MULTIPLIERSMALL_MULTIPLIERtotal_flopsweighted_flopsdo_layout_opts                           rr   r   zGraphLowering.decide_layout_optQ  s5    ))++ xx~~
UYY^^5O5O5W5W)WA

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

 IIw 	;
		 @,7,>K" <(-(@(@(U(U)%v (7 9;L[[ 9'DKK8899 %6$E$E$GM!$'$-	)$/$+	*40$,	$-		*m;*II:;-<6 "'!& %$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m
D9 99 9s0   A L1<L1?ML6#M6M ;MM	c                @    | j                   | j                    d| S |S )z2Prepend the given name with the graph name if any.r[  )r  rE  r  s     rr   qualify_namezGraphLowering.qualify_name  s&    99 ii[$((rs   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.
        )
parentrF  r   rG  r  r!  r  r   r   r  )SubgraphLoweringr   r  r!  r  r   r   r  )rE  rF  r   subgraph_names       rr   make_subgraphzGraphLowering.make_subgraph  sZ      )oo((]]#'#>#>**((""=1
 	
rs   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   r6  r.  r   r   r{   r  r   r   r  addusersupdate)rE  
output_setr~  users       rr   r+  z-GraphLowering.find_nodes_prefer_channels_last  s    &  %'
$++++112 	Axx599>>55===q! :%NN1%	0 ""(( 	+AJ!!!''*	+ rs   c                    || j                   vr2| j                   j                  |       t        j                  d|       y y )NzUsing FallbackKernel: %s)r-  r  perf_hint_loginfor  s     rr   warn_fallbackzGraphLowering.warn_fallbackH  s:    t,,,!!%%d+94@ -rs   c                R   | j                   j                  |j                         |j                  %| j                  j                  |j                         t
        j                  j                  r7|| j                  vr(t
        j                  j                  | j                  |<   y y y rn   )	r   r  r|  indexr   r`   r.  r  r3  ro  s     rr   add_device_infozGraphLowering.add_device_infoM  sy    fkk*<<#  .77F$2J2J$J/0ww/C/CD$$V, %Krs   c                "    t         j                  S rn   )r`   r  rM  s    rr   r  zGraphLowering.fake_modeT  s    {{rs   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  ri  )r  r   r  r`   r.  r+   ConstantBufferr;   r   dtyper`  )rE  buffer_namerb  s      rr   try_get_bufferzGraphLowering.try_get_bufferX  s     $---&&{33$+++$$[11$..(77$$[1D$$ ~~KK./gg.J.J4.P  rs   c                    t        d      )Nz'Should not be called for the main graph)r   )rE  symbols     rr   add_symbol_graph_inputz$GraphLowering.add_symbol_graph_inputj  s    DEErs   c                H    | j                  |      }||S t        d|       )Nz$Failed to find buffer matching name )r  r   rE  r  bufs      rr   
get_bufferzGraphLowering.get_bufferm  s1     !!+.?JA+OPPrs   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groupKeyError)rE  r  mutated_bufr   s       rr   r  zGraphLowering.get_dtypeu  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7rs   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   r  r  s      rr   r  zGraphLowering.get_numel  s    $..(>>+.4466$---%%k2C((*==?"$+++$$[1;;==677rs   c                ^    t        d      5  t        |   | cd d d        S # 1 sw Y   y xY w)NzGraphLowering.run)r   r   run)rE  rp   rJ  s     rr   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_nameru   r+   	Operationr  rT  r   appendr  )rE  r   r  s      rr   register_operationz GraphLowering.register_operation  s      (M,H*MM("bll+++  2c$//&:%;!<=r" " rs   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  rT  r   r  r  
get_deviceru   r+   rc  is_zero_elementsr{   r   r  r  )rE  bufferr  r  r   s        rr   register_bufferzGraphLowering.register_buffer  s      3s4<<'8&9!:;F#$*D!""$ 62#4#45++-ell511   (FKrs   c                j    | j                  ddj                  |      z         }|| j                  |<   |S )Nlist_r[  )r  r   r  )rE  operation_namesr  s      rr   register_operation_listz%GraphLowering.register_operation_list  s3      388O+D!DE*

4rs   c                &     d fd |       y )Nc                    t        | t        t        f      r| D ]
  } |        t        | t        j                        r4| j                         D ]   }j                  |   j                  |        " y y rn   )ru   r  tupler+   rB   get_read_namesr  r  )valuex	read_nameregisterrE  s      rr   r  z1GraphLowering.register_users_of.<locals>.register  sm    %$/  AQK %.!&!5!5!7 @I&&y188?@ /rs   )r  %Union[Iterable[ir.IRNode], ir.IRNode]r   Nonero   )rE  node_outputr  s   ` @rr   register_users_ofzGraphLowering.register_users_of  s    	@ 	rs   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)ru   strr
  r  r  realize)rE  r  r  s      rr   mark_buffer_mutatedz!GraphLowering.mark_buffer_mutated  s\    
 $$$$  &t)))&&t, 	DLLN	rs   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 )r7  r  rU   r6  r   )rE  r  	orig_names      rr   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'	
 %	
rs   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  itemsrY   rT  isdigitr  r[   r   r  r  rQ  rR  hashr  r7  )rE  r  rb  constant_namer  r  prefixcnts           rr   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*rs   c                    | j                  ||      }t        j                  t        j                  |t        |j                  |j                  g| j                  |                   S r  )	r  rB   creater+   r  r;   r   r  r`  )rE  rb  r  new_names       rr   add_tensor_constantz!GraphLowering.add_tensor_constant  sb     33D$?"KK.2.G.G.M
 	
rs   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)rE  r  device_overrides      rr   r  zGraphLowering.constant_name  s     >>$&&/9_=TK[[))@@B 	 33&/../0E0E0J/KLt$''8	 	 	s   	AB  B)c                   | 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                        rt3        t        j                  j4                  j6                        dk(  rdt9        t;        t        j                  j4                  j6                              j<                  t.        j>                  j@                  jB                  u sJ tE        jF                  ||jH                        }|| j                  |<   | j                  j                  |       |S t	        |t.        jJ                        sJ |       |jL                  s| jO                  |      \  }}	n| jQ                  |      \  }}	| j                  re| jR                  rY| j                   | jR                  v rAtU        jV                  tY        |t[        |jH                  |j\                  ||	                  }
n@tU        jV                  t_        |t[        |jH                  |j\                  ||	                  }
|
| j                  |<   | j                  j                  |       |
j`                  j`                  | jb                  |<   | j4                  j6                  r| je                  |jH                         tg               5  ti        |      s| jj                  jm                  |       d d d        |
S # 1 sw Y   |
S xY w)Nr)   r  r  )r  r   r  )7rC  r   placeholderr  ru   r$   r`   r.  r   r   r   rX  r   r   r  intr  r  rv   sympifyr   rC   r   r{   	GeneratorrT  r  r  r#  iterr   _prims	rng_primsgraphsafe_run_with_rng_stater+   GeneratorStater   r   _has_symbolic_sizes_stridesr`  r^  rD  rB   r  r:   r;   r  r>   rb  r   r  rZ   r\   r;  r  )rE  r   rp   rq   examplerX  r   gensizesstridestensorrJ  s              rr   r"  zGraphLowering.placeholder$  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AGG((../14agg22889:AA<<))FFGG ##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   6'Q''Q1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)rp   rq   resultr   s      rr   	normalizez.GraphLowering.call_function.<locals>.normalize  sE    %*XX%>%>%Q%Q &f&F $*#55#5#)!9fQi#77rs   )rp   r   rq   r   r   ztuple[Any, Any])+operatorgetitemru   r  r  dictr   r   r{   r   OpOverloadPacketr   rI   r   r  r   rF   rJ   r*   implicit_fallbacksr   r7   r8   r  r  operator_strr   _libraryr  
is_builtinr   rM   rN   r  r  rK   rD   r   propagate_mutation	Exceptionr6   with_traceback__traceback__)rE  r   rp   rq   	base_nameerrortagdecided_constraintr~  layout_constraintsold_args
old_kwargs	fake_argsfake_kwargsr<  outerJ  s    `               rr   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<
 0UKK,,77?(( *<&3FNC)A#)F&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      )rT  shape)ts    rr   can_inline_constantz!GraphLowering.can_inline_constant  s(    
 177|q 4QWWQZ1_4rs   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!  ro   )r  r  r   zInlining constant: %s r)   )r0  )r  r   )#r   r6  ru   r{   r   rf   r  r+   Subgraphr   ScriptObjectr  r  rC   r   r   r*   r  r  always_keep_tensor_constantsrO   r  r&   rV  r9   itemr  r   rX  r  r  r  loweringr0  tolist)rE  r   rp   rq   r  rR  r0  s          rr   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         rn   AssertionErrorrE  r   rp   rq   s       rr   call_modulezGraphLowering.call_module0      rs   c                    t         rn   rc  re  s       rr   call_methodzGraphLowering.call_method3  rg  rs   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rn   )ru   rB   r+   r9   r|  r  rv   r   logicboolalgBooleanr#  EffectfulKernelShapeAsConstantBuffer)r   r  s     rr   r   z'GraphLowering.output.<locals>.<genexpr>A  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   ru   r  r  r|  r  r`   r.  r  rp   r+   ExternKernelrealize_inputrT  ziprB   BaseViewr  get_output_specCommBufferLayout
copy_inputr{   r  is_storage_and_layoutr   rR  rW  r   rX  try_match_insignificant_stridesr   r   r  rC   rv   r   r*  r  rb  rA   r>   get_nameMutationLayoutSHOULDREMOVErealize_intor   r  
ValueErrorfinalizer  r  r   r"  )rE  r   rp   rq   r;  fx_node_argsr  result_correct_stridesrfx_nodesmeta_stridesr  r  value_storage_boxindrJ  s                   rr   r   zGraphLowering.output6  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 rn   )r   decide_layout)rE  r  s     rr   r~  zGraphLowering.finalize  s!    << 	 C	 rs   c              #  b   K   | j                   }	 || _         d  || _         y # || _         w xY wwrn   )r  )rE  r   olds      rr   set_current_nodezGraphLowering.set_current_node  s1     	$ $D #DDs   /# /	,/c              #  T   K   | j                   }	 d  || _         y # || _         w xY wwrn   r  )rE  r  s     rr   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.
        rq   
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 rn   )
alias_infois_writeru   r+   IRNoders  r   r{   r  r   copy_r  )
schema_argold_argnew_argold_arg_itemnew_arg_itemrE  s        rr   maybe_propagatez9GraphLowering.propagate_mutation.<locals>.maybe_propagate  s     '!$$0Z5J5J5S5S gryy1&jG&jG25gw2G .L,#|3 &&		,,44|\6RTV 6T0rs   )r  ztorch._C.Argumentr  	ir.IRNoder  r  r   r  )rT  r   r{   r  higher_ordertriton_kernel_wrapper_mutationrq   ru   r?  r   r   get_mutated_tensorsr  r   r%   r   r   r   r  r  r   r   _schemar   rs  	argumentsr  r   )rE  r  rN  rO  new_args
new_kwargsrq   rH  rI  mutatedr  r  r  r  schemar   r  argschema_kwargskeys   `                   rr   rE  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                  t        j                   t"        j$                  j&                  fvrHt)              s|j+                  ddfd      r' |d        t-        j                  d	
      i }nj                  dk(  rj                  t"        j.                  j0                  j2                  u rt4        j6                  dk7  r |d       t4        j6                  dk(  r}	}
j8                  j;                  d      x}r|d   }|d   }t=        ||||      \  }}nt?        g|i |\  }} jA                  j                  ||      } jC                  |	|
||       ntE        dt4        j6                         tG        j                        r |d       tI        j8                  d   t"        jJ                  t"        jL                  t"        jN                  f      r$j8                  d   jP                  jR                  }n'tT        '         }n |d       tT        '         }t"        j.                  jX                  jZ                  j\                  t"        j.                  jX                  j^                  j\                  t"        j.                  jX                  j`                  j\                  t"        j.                  jX                  jb                  j\                  t"        j.                  jX                  jd                  j\                  g$tg        d jh                  D              } jj                  v }tg        $fdjh                  D              }j8                  j;                  dd	      rtI        |tl              r|jo                          j8                  d   jq                         }t#        jr                  jt                  jv                  | }|jy                         |k7  r7|s5t        jz                  |      }t        j|                  j                  ||      }|rDtI        |tl              r4tI        |j                  t        j                        r|jo                          |s|r%tI        j8                  d   t"        j                        r|r jj                  j;                        }nj8                  d   jq                         }|t        |      dkD  rt4        j                  xs | xr | }t"        j                  j                  j8                  d         }t        t        |            dkD  }|sl|rjt        |j                               dk(  rN j                  v r@|s>|s<t        j                  j                  |j                         t"        j                        }|st        |      r؉j8                  d   j                         s$tI        |j                  t        j                        r6t        j|                  j                  |t        jz                  |      |      }na|D cg c]4  }tI        |t"        jJ                        r|jP                  jR                  n|6 }}t        j|                  j                  |||      }t        t        jh                              }|dkD  rtI        |tl              rjh                  D ]  }|j                  t        v rn|j                          t"        j.                  jX                  j                  j\                  t"        j.                  jX                  j                  j\                  t"        j.                  jX                  j                  j\                  g}g } j                  s=|j                  t"        j.                  jX                  j                  j\                         t"        j                  j                  r|t"        j.                  j                  j                  j\                  t"        j.                  j                  j                  j                  t"        j.                  jX                  j                  j\                  t"        j.                  j                  j                  j\                  t"        j.                  j                  j                  j                  t"        j.                  j                  j                  j                  t"        j.                  j                  j                  j                  gz  }|t"        j.                  j                  j                  j\                  t"        j.                  j                  j                  j                  t"        j.                  j                  j                  j                  t"        j.                  j                  j                  j\                  t"        j.                  j                  j                  j\                  t"        j.                  j                  j                  j                  gz  }t"        j                  j                  r2|t"        j.                  j                  j                  j\                  gz  }|j                  |v rPt        j|                  j                  |t        jz                  j8                  d   jq                               d      }|j                  |v rd|j                  d   u rSt        j|                  j                  |t        jz                  t        j8                  d   j                                    }|j                  dk(  stI        |j                  j                  t        t        f      s|jo                           |j                  t        jh                               tI        |tl              r |j                         r|j                          tI        |tl              rbtI        |j                  t              rH|j                  j                  }tI        |t              r"|j                  d      r|jo                          d d d        d d d        d d d        tI        tl              r#tI        |j                  t        j                        rtI        |j                  j                  t        j                        r(|j                  j                  j                  d       ntI        |j                  j                  t        j                        ry|j                  j                  j                  d       tI        |j                  j                  t        j                        ritI        |j                  j                  j                  t        j                        r1|j                  j                  j                  j                  d       ntI        |j                  j                  t        j                        r|j                  j                  j                  sntI        |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=tI        |t        j                        r#| j                  |      r|j                  |       d'%& fd}!t        j                  j                  rj                  dk(  r|S t        t        j                  j                  j                  j8                  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    rr   r  z%GraphLowering.run_node.<locals>.debug  s    II&
1==(A3Grs   r   )CompilerBisectorr   inductorrI   c                     t               S rn   )reprr  s   rr   <lambda>z(GraphLowering.run_node.<locals>.<lambda>  s    a rs   rG   F)add_to_fallback_setflexible_layout-user_defined_triton_kernel_layout_constraintsneeds_fixed_stride_orderr7  r)   z1Unknown triton_kernel_default_layout_constraint: r   r{  r   c              3  :   K   | ]  }|j                   d k(    yw)r   Nr   )r   r  s     rr   r   z)GraphLowering.run_node.<locals>.<genexpr>O  s     DDDGGx/Ds   c              3  :   K   | ]  }|j                   v   y wrn   )r   )r   r  as_strided_opss     rr   r   z)GraphLowering.run_node.<locals>.<genexpr>Q  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     rr   r   zBGraphLowering.run_node.<locals>.format_new_defs.<locals>.<genexpr>  s2       ((C(C(E'FfRDPRSs   !#z***
)r   r  extendr   r   )r  r  buffer_watermarkoperation_watermarkrE  s     rr   format_new_defsz/GraphLowering.run_node.<locals>.format_new_defs  s      <<(8(9: ((D(D(F'GvcURTUA  HH //*=*>?  <<?"s   A)unbacked_bindingsc              3     K   | ]8  }t         j                  j                  j                  j	                  ||       : y wrn   )r`   r  rG  unbacked_renamingsr   )r   r  s     rr   r   z)GraphLowering.run_node.<locals>.<genexpr>N  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  rT  r   r   r'   r   fetch_args_kwargs_from_envrT   r+   r  current_originsr  r`   r   r=  r>  r{   r   invoke_subgraphrH   disable_subsystemrG   r  r  r  r*   'triton_kernel_default_layout_constraintr   r   rD   rE   r   rE  r   r   ru   rW  SymFloatSymBoolr   rX  r   run_noder   
as_stridedr  as_strided_as_strided_scatterresize	resize_asr   r  r   rB   r  rR  r  r  any_is_symbolicmaybe_get_strideget_stride_orderrq  require_stride_orderrb  rt  r   r   _prims_commonis_non_overlapping_and_denser   rd  r,  FlexibleLayout stride_ordered_for_memory_formatchannels_last_is_viewrequire_exact_stridesrL   realize_hintr   mm_int_mmr   r  r   r   _has_mkldnnr  _linear_pointwisebinarymkldnn_rnn_layeronednnqlinear_pointwiser0  binary_tensor_convolution_pointwise_convolution_pointwise_ _convolution_transpose_pointwiseqconv_pointwiseqconv2d_pointwisehas_mklmkl_mkl_linearrp   r   rV  r?   r@   
mark_reusehas_exceeded_max_readsrA   has_large_inner_fnLoops_post_init_setattrBufferrc  MultiOutputindicesinputsr  rv   rw   r  r.  r   rG  is_unbacked_symintr  r   r    r   r  create_deferred_runtime_asserts)(rE  r~  r  r  originsis_call_functionrp   rq   r;  rN  rO  r7  inp_args
inp_kwargs	is_outputis_user_visibleis_input_for_as_stridedr/  sym_stridesstride_orderr  denseunbacked_symbols_in_stridesr  	num_usersr  need_fixed_layoutneed_fixed_channels_last_layoutcurrnew_unbacked_defsr  r   rG  r  r  renamed_unbacked_bindingsr  r  r  rJ  s(   ``                                  @@@rr   r  zGraphLowering.run_node  sD   	H 	Gt||,!$//2 $.qc?44?2::1=LD&~dF33GII%%g.h	)!!!$h	) q!h	) 'HH ((%*A*A*Q*QRS :!<'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....=(Qh	) h	) h	)d 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Q']h	) h	) h	) h	) h	) h	)sr   AF.AE6YAE)9AE$
S9AE)*AE)2CAE)AE6AFE$AE)E)AE3E.AE6E6AF 	E;AFFAF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  )rX  r  	assert_oprE  s      rr   make_assertzBGraphLowering.create_deferred_runtime_asserts.<locals>.make_assert|  s4    c2I  T :##I.rs   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    rr   is_convertiblezEGraphLowering.create_deferred_runtime_asserts.<locals>.is_convertible  s5    & 11#()F#'( )#()s    	**r  z <= )r  )rX  r#   r  r  r   r  )r  r   r   r  )r   r   r{   r  r   _assert_scalarr  r!  r  r   r`   r.  r   rG  r   popvar_to_range _default_unspecified_value_rangeissubsetlowerupperr   rX  r   r  
setdefaultr  )rE  r~  r  r  	node_argsr[  rG  i0rasvrr  rafvsmissingi1s   `              rr   r  z-GraphLowering.create_deferred_runtime_assertsZ  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:;);rs   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platformrM  s    rr   !validate_can_generate_cpp_wrapperz/GraphLowering.validate_can_generate_cpp_wrapper  s@    %%()BCC<<;;(+@)OPP <rs   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 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   discardrT  formatr   r!  r   r  r7  r1   r  r2   r  r  r   _names_iter)rE  is_subgraphr  parent_wrapper_codepartition_signaturesr   only_cpuwrapper_code_gen_clss           rr   init_wrapper_codezGraphLowering.init_wrapper_code  sJ    ((--/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) rs   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   gridrq   r  r  r{  r  )rp   r   FT)"r   deepcopyr5  r.  r   r   r   r{   r  r  r  r  rq   ru   r   r%   rT  r   r   r  r  r   inserting_beforer   cloner  r  rp   	recompileInterpreterr  r)  r'  r(  )rE  r   r   	cloned_gmtriton_nodesr   grid_inputsvisited_gridstriton_inputskwargs_inputsvisited_kwargsrD  r{  rq   rH  rI  r  r  new_nodenew_outputsrunnerreturned_outputsgrid_outputsdynamic_grid	new_gridsnew_grids                             rr   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rn   )r   )r   r   rE  s     rr   r   z9GraphLowering.codegen_with_cpp_wrapper.<locals>.<genexpr>?  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)ru   r{   rW  r  r   hintr   r   r   r  r|  )r  s    rr   materializezXGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputs.<locals>.materializeB  sx     y##Aenn'EF vv{{*#Az2%ay()!U\\: Ds4PQ7|S:  !rs   r)   )clone_preserve_strides)r  z1Union[torch.SymInt, torch.SymFloat, torch.Tensor]r   zUnion[int, float, torch.Tensor])r{   _guardsTracingContexttry_getru   r`   real_inputsr_   output_stridesclearparams_flatr@  chainr   r  
compile_fxrb  r   r   r   )ra  tracing_contextparamri  r  rf  rb  r   r  r  mutated_inprE  s              rr   extract_real_inputszCGraphLowering.codegen_with_cpp_wrapper.<locals>.extract_real_inputsA  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   ru   r+   UserDefinedTritonKernelrY  codegenr  compile_to_modulecallr{   r  r  r  r  rh  r  r  r`   r.  r   precomputed_replacementsinv_precomputed_replacementsr,   resetpatch)rE  ro  user_defined_kernelsr   rf  compileds   `     rr   codegen_with_cpp_wrapperz&GraphLowering.codegen_with_cpp_wrapper9  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   )rE  r  s     rr   _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   rB  r  r`   r  draw_orig_fx_graphr5  r&  r   r  push_codegened_graphru  r  r.  r?  generater   pop_codegened_graph)rE  r;  s     rr   ru  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&  ru  )rE  parent_graphs     rr   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)rE  total_bytesnode_countsnode_runtimesr   	num_bytess         rr   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6rs   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_modulerM  s    rr   rv  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~  ru  ru   r^   _compile_to_module_linesr/   NotImplementedErrorr|  __file__rl   r  r  rj   r  r*   benchmark_kernelprintr5  stderrr`   output_coder   ospathsplitext)rE  r  r[  mods       rr   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
rs   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filenamero   )r  s   rr   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>?	  s    T* rs   c                      j                   S rn   r  r  s   rr   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>@	      <#5#5 rs   )
payload_fnc                      j                   S rn   r  r  s   rr   r  z8GraphLowering._compile_to_module_lines.<locals>.<lambda>9	  r  rs   zPyCodeCache.load_by_key_pathTr  )linemapattrs)timesrepeat)"	codecacher  r*   rq  rr  r  kernel_autotune_defsgetvaluereplacekernel_autotune_callsr  r   r  rj   r  rP   inductor_meta_from_configrQ   begin_compileline_mapstack_tracewriter   rF  r   load_by_key_pathr  r  r/  r0  r1  benchmark_harnessprofile_bandwidth_outputbenchmark_compiled_module)rE  r  r  r  tuning_codeinductor_metaline_nor   r  r  r  r  s    `         @rr   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)r@  rA  r   ru   r+   NoneAsConstantBufferr  r  r#  rp  rz  )rE  namesshape_counternone_counterr   s        rr   get_output_nameszGraphLowering.get_output_namesS	  s    !* q)&& 	.D$ 7 78		{%\0B/CDED"":":;		{&m1D0EFGT]]_-	. rs   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  rT  rd  r<   r   r  s     rr   is_unspec_argzGraphLowering.is_unspec_arg`	  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	3rs   )NNNFFNNFFFNNNNNN)$rF  torch.fx.GraphModuler   zOptional[Sequence[object]]rG  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  )rY  torch.Tensorr   z=tuple[Sequence[Union[int, Expr]], Sequence[Union[int, Expr]]])rY  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]rl  r-   r   r  )r   torch.device)r   r  r   Iterator[None]r  )rF  rf   r   r  r   r  )r  r  r   r  )rF  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])rp   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  rb  zUnion[Tensor]r   r  rn   )rb  r   r  r  r   rB   )r  r  r  zOptional[torch.device]r   r  )r   r  rp   tuple[object]rq   dict[str, object]r   zUnion[Expr, TensorBox, None])r   r   rp   r   rq   dict[str, Any]r   r   )rW  r  r   r  )r   r  rp   z	tuple[()]rq   r  r   z8Union[Constant, TensorBox, ir.Subgraph, TorchBindObject])r   r   rp   r   rq   r   r   r   )r   r  rp   r  rq   r  r   r  )r   r   )r   r  )r  r   rN  
tuple[Any]rO  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]r?  z!Optional[GraphPartitionSignature]r   r  )r   rp  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  )D__name__
__module____qualname____annotations__r   rL  r^  r`  re  rj  rm  rp  
contextlibr   rr  rw  staticmethodr   r  r  r+  r  r  propertyr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r"  r   rX  ra  rf  ri  r   r~  r  r  rE  r  r  r7  rB  rY  r~  r  ru  r  r  r  rv  r  r  r  r  __classcell__rJ  s   @rr   r   r      s   ""
 6:(,"&!%) "!$7;,0+/04"37)A2 A2 3A2 &	A2
  A2 A2 A2 #A2!
A2 A2 A2 A2 5A2  *!A2" )#A2$ .%A2& 'A2( 1)A2* 
+A2F1# # 	F# J	2#
#
 
#$EFE	EM>M  M 
	M4 ( ( a aF
 
 +
 	

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

 
[
z  $ $ $ $I:I: I: #	I:
 I: #I: 
I:VeN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<-<<,<	<|3rs   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 rn   )r  r   r   )rE  r  rp   rq   rJ  s       rr   r   zSubgraphLowering.__init__q	  s    $)&)rs   c                f    t         |   d| j                  | j                  j                         y )NT)r=  r  r>  )r   rB  r  r  r  )rE  r=  r  r>  r?  rJ  s        rr   rB  z"SubgraphLowering.init_wrapper_codeu	  s.     	!)) $ 8 8 	" 	
rs   )r  r   rp   r   rq   r   r   r  r  r  )r  r  r  __doc__r   rB  r  r  s   @rr   r  r  k	  sV    
* "'+>BBF

 %
 <	

 @
 

 
rs   r  )rp   r   rq   r   r   r  )r   r  r   zOptional[torch.dtype])r   r   r   r  )r   rf   r   r  r   z1Union[Tensor, torch._C.ScriptObject, GraphModule])r   rg   r   dict[Node, tuple[int, ...]])r   rg   r   r  r   r  )
__future__r   r  r8  r@  loggingr=  r  r  r5  r  collectionsr   r   typingr   r   r   r	   r
   r   rv   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   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   r_  rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   runtimerP   runtime.autotune_cacherQ   r   rR   r  rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   virtualizedr_   r`   collections.abcra   rb   rc   typesrd   torch._higher_order_ops.effectsre   rf   torch.fx.graphrg   codegen.wrapperrh   r&  ri   r  torch._inductor.codecacherj   	getLoggerr  r  _logginggetArtifactLoggerr  r  r   rA  r$  r  torch._inductor.fb.utilsrl   r   r   r   r   r   r   rI  r   r  ro   rs   rr   <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H!3EHH(( H!3VB
} 
rs   