o
    ei}                    @  s  U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZmZmZ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mZmZmZmZmZmZmZmZm Z m!Z!m"Z" d dl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) d d	l*m+Z+ d dl,Z,d d
l,m-Z-m.Z.m/Z/ d dl0m1  m2  m3Z4 d dl5m6  m7Z8 d dl9Z:d dl;Z:d dl<m7  m=Z> d dl?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZF d dlGmHZH d dlImJZJ d dlKmLZLmMZMmNZNmOZOmPZP d dlQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZ d dl[m\Z\ d dl]m^Z^ d dl_m`Z` d dlambZbmcZcmdZdmeZe d dlfmgZg ddlhmiZimjZj ddlkmlZlmmZmmnZnmoZompZp ddljmqZqmrZrmsZsmtZtmuZu ddlvmwZw ddlxmyZymzZzm{Z{m|Z| ddl}m~Z~ ddlmZmZ dd l7mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ dd!lmZmZmZ erd d"lmZ d d#lQmZ d d$l[mZ dd%lmZ dd&lmZ dd'lmZ dd(l7mZ neZd)ed*< zd dlZejZd+ZW n ey   dZd,ZY nw e'd-Ze!d.Ze!d/Ze!d0Ze"ee-f Zd)ed1< e"eee-f Zd)ed2< e"e:jje:jjf Zd)ed3< eeZeje	jd4d5Ze:jjZ	 e"ed6eed6f d7d8eee"eeed6f d6d7d8f   f Zd)ed9< dd>d?Zejd+d@G dAdB dBZĐddFdGZŐddKdLZƐddPdQZǐddRdSZȐddYdZZg d[Zg d\Z	dddadbZ̐ddddeZ	dddfdgZedddjdkZedddmdkZ	+dddpdkZϐddtduZАddxdyZѐdd{d|ZҐdd}d~ZӐdddZԐdddZՐdddZ֐dddZאdddZdd ZG dd8 d8Zed,d@G dd dZeG dd deڃZܐdddZeG dd de܃ZeG dd deރZedededededededdZded< 	+ddddZeG dd de܃Zde.d fdddZeee- ee- gef Zd)ed< G ddĄ deZG ddƄ deZG ddȄ deZeG ddʄ de܃ZeG dd̄ deZeG dd΄ de܃ZdddЄZddd҄Z	+	,		,	ddddۄZddd݄ZdddZeG dd deڃZeG dd deZeG dd deZeG dd deZeG dd deZeG dd deZeG dd deZeG dd deZG dd deZeG dd deڃZeG dd deZeG dd deZdddZdddZG dd dZeG dd  d eZG dd deZ G dd deZG dd deZG dd deZG d	d
 d
e ZeG dd deZG dd deZed,d@G dd deemZed,d@G dd deeۃZG dd deZ	G dd de	Z
G dd de	ZeG dd deڃZeG dd deڃZed,d@G dd deZG dd  d eZG d!d" d"eZe"eeeeee"eeeef  f ZG d#d$ d$ZG d%d& d&eZG d'd( d(eZG d)d* d*eZG d+d, d,eZG d-d. d.eZG d/d0 d0eZdÐd4d5Zed,d@G d6d7 d7eZG d8d9 d9eZG d:d; d;eZed,d@G d<d= d=eZed,d@G d>d? d?eZ G d@dA dAe Z!G dBdC dCeZ"G dDdE dEeZ#G dFdG dGeZ$G dHdI dIe$Z%G dJdK dKe$Z&G dLdM dMeZ'G dNdO dOeZ(G dPdQ dQeZ)G dRdS dSeZ*G dTdU dUeZ+G dVdW dWe+Z,G dXdY dYe"Z-G dZd[ d[eZ.G d\d] d]eZ/G d^d_ d_e Z0G d`da daeZ1G dbdc dceZ2G ddde deeZ3G dfdg dgeZ4ed,d@G dhdi diZ5G djdk dke"Z6ed,d@G dldm dme6Z7G dndo doe6Z8eG dpdq dqeZ9G drds dseZ:ejG dtdu dueڃZ;G dvd6 d6e;Z<G dwdx dxe;Z=ed,d@G dydz dzeڃZ>dĐd|d}Z?ed,d@G d~d deZ@ed,d@G dd deZAdŐddZBed,d@G dd deZCG dd de6ZDG dd deڃZEeG dd deEZFeG dd deEZGG dd de6ZHG dd deHZIG dd deHZJG dd deHZKdƐddZLdƐddZMdǐddZNdS (      )annotationsN)Callable	GeneratorIterableIteratorSequence)AbstractContextManagernullcontext)Enum)partial)AnycastClassVarLiteralOptionaloverloadSupportsFloatSupportsIntTYPE_CHECKING	TypeAliasTypeVarUnion)assert_neverNeveroverride	ParamSpecSelfTypeIs)patch)ExprIntegerSymbol)identity)GraphModuleSerializer)can_auto_functionalize)metricsget_free_symbols)is_opaque_type)compute_required_storage_lengthis_boolean_dtypeis_float_dtypemake_channels_last_strides_for
StrideType)	&_remove_effect_token_unbacked_bindingscompute_unbacked_bindingsfree_symbolsfree_unbacked_symbolsIterateExprsrebind_unbackedresolve_unbacked_bindingsShapeEnvSymTypes)Node
OrderedSet)_disable_current_modes)CleanDivFloorDivModModularIndexing)SymT   )configdependencies)BackendFeatureCodegenSymbolget_scheduling_for_deviceindex_prevent_reorderingKernel)Depextract_free_symbols#extract_input_node_reduction_rangesextract_read_writesvar_builder)LoopBody)OpCounterCSEOpCountResultReductionType	StoreMode)benchmarker)DevicePropertiesReductionHint)argsortargsort_symcache_on_selfcache_on_self_and_argsceildivconvert_shape_to_inductorconvert_shape_to_symintdeveloper_warningdo_bench_using_profilingdtype_from_sizeget_dtype_sizeget_kernel_metadataGPU_ALIGN_BYTESir_dataclass
is_dynamicis_gpu	sympy_dotsympy_index_symbolsympy_index_symbol_with_prefixsympy_product
sympy_substensor_is_aligned)opsOpsValueV)FakeScriptObject)SympyBoolean)Argument)CUTLASSTemplate)PythonWrapperCodegen)GraphLowering)IndentedBufferr   rq   TF_P_T_U_V_IntLike_NumLike_OpOverloadsz  prefix	TensorBoxr!   IRNode_NodeOrNodesxobjectreturnTypeIs[Union[int, Integer]]c                 C  s   t | ttfS N)
isinstanceintr    r    r   \/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/_inductor/ir.py
_is_static      r   )frozenc                   @  s>   e Zd ZU ded< ded< ded< ded< d	ed
< ded< dS )GraphPartitionSignatureOrderedSet[sympy.Symbol]symbol_inputsz5dict[str, Union[IRNode, sympy.Expr, TorchBindObject]]input_nodeslist[IRNode]output_nodeszdict[str, bool]input_deallocationboolskip_cudagraph	list[str]constant_namesN__name__
__module____qualname____annotations__r   r   r   r   r      s   
 r   node_or_nodesOptional[_NodeOrNodes]Nonec                   s   d fdd  |  d S )Nnodesr   r   r   c                   s   | d u rd S t | ttfr| D ]} | qd S t | tr*|  D ]} | q!d S t | ttttt	j
jjttttf	sEJ dt|  dd S )NzFound zE, which is not a supported top level IR node. See [Note: Inductor IR])r   listtupledictvalues
ExpandViewDynamicScalarAssertScalarr~   sympylogicboolalgBooleanr   r   EffectfulKernelShapeAsConstantBuffertype)r   node_check_tensorboxr   r   r      s2   


z%validate_ir.<locals>._check_tensorbox)r   r   r   r   r   )r   r   r   r   validate_ir   s   r   namestrCallable[..., OpsValue]c                   s(   t  tsJ t d fdd}|S )	Nargsr   kwargsr   rl   c                    s   t t | i |S r   )getattrrk   r   r   r   r   r   fn     zops_wrapper.<locals>.fn)r   r   r   r   r   rl   )r   r   r   )r   r   r   r   r   ops_wrapper
  s   r   orderSequence[int]&Callable[[Sequence[_T]], Sequence[_T]]c                   s(   t t| tt|  d fdd}|S )NindexSequence[_T]r   c                   0   t  t ks
J  fddtt  D S )Nc                      g | ]} |  qS r   r   .0i)r   	inv_orderr   r   
<listcomp>      z4inverse_reorder.<locals>.reindex.<locals>.<listcomp>lenranger   r   r   r   reindex     z inverse_reorder.<locals>.reindexr   r   r   r   )r   zipr   r   r   r   r   r   r   inverse_reorder  s   r   c                   s   d fdd}|S )Nr   r   r   c                   r   )Nc                   r   r   r   r   )r   r   r   r   r      r   z1same_reorder.<locals>.reindex.<locals>.<listcomp>r   r   r   r   r   r     r   zsame_reorder.<locals>.reindexr   r   r   r   r   r   same_reorder  s   r   reindex1&Callable[[Sequence[_U]], Sequence[_V]]reindex2&Callable[[Sequence[_T]], Sequence[_U]]&Callable[[Sequence[_T]], Sequence[_V]]c                   s   d fdd}|S )Nr   r   r   Sequence[_V]c                       | S r   r   r   r   r   r   r   r   )     z fuse_reindexing.<locals>.reindex)r   r   r   r   r   )r   r   r   r   r   r   fuse_reindexing%  s   r   )   r      r@   )   r   r   r   r@   seq(Sequence[Union[int, torch.SymInt, Expr]]	shape_envOptional[ShapeEnv]c                 C  s4   |du st dd | D rt| }|S t|| }|S )z1
    Convert strides to fill order (argsort)
    Nc                 s       | ]}t |ttjfV  qd S r   r   r   r   r    r   sr   r   r   	<genexpr>9      z!get_fill_order.<locals>.<genexpr>)allrU   rV   )r   r   
sorted_idxr   r   r   get_fill_order3  s
   
r   Sequence[Union[int, Integer]]c                   s0   dd t | D   fddtt| D }|S )z
    Convert stride order to fill order
    For channel last format,

    stride order = [3, 0, 2, 1] and fill order = [1, 3, 2, 0]
    c                 S     i | ]\}}||qS r   r   r   idxposr   r   r   
<dictcomp>H      z+stride_order2fill_order.<locals>.<dictcomp>c                      g | ]} | qS r   r   r   lookupr   r   r   I      z+stride_order2fill_order.<locals>.<listcomp>)	enumerater   r   )r   
fill_orderr   r   r   stride_order2fill_orderA  s   r   c                 C  s>   t | |}dd tt| D }t|D ]\}}|||< q|S )z)
    Convert strides to stride order
    c                 S     g | ]}d qS r   r   r   _r   r   r   r   T      z$get_stride_order.<locals>.<listcomp>)r   r   r   r   )r   r   r   outr   elemr   r   r   get_stride_orderM  s
   

r  guard_shaper   c                 C     d S r   r   r   r	  r   r   r   ir_node_to_tensorZ     r  torch.Tensorc                 C  r
  r   r   r  r   r   r   r  ^  r  Optional[IRNode]Optional[torch.Tensor]c                   s   | d u rd S |st jjj nt  fdd|  D }t| r, fdd|  jD }nt	
|}|  }|  }t|}t|}t jjj  tj||||d }W d    |S 1 s_w   Y  |S )Nc                      g | ]} |qS r   r   r   shape_fnr   r   r   m  r   z%ir_node_to_tensor.<locals>.<listcomp>c                   r  r   r   r   r  r   r   r   p  r   )sizestridedtypedevice)rm   graphsizevars	size_hintr"   get_sizeis_storage_and_layout
get_layoutr  FlexibleLayoutcontiguous_strides	get_dtype
get_devicer[   r   suppress_guardstorchempty_stridedzero_)r   r	  r  r  r  r  tr   r  r   r  b  s.   

valueOptional[Sequence[_T]] Optional[Sequence[Optional[_T]]]c                 C  s   t | tr
| s
d gS | S r   )r   r   r'  r   r   r   may_convert_to_optional  s   r+  2Union[IRNode, OutputSpec, torch.device, None, str]Optional[str]c                 C  sb   t | ts	| d u r| S t | tjr| jS t | ttfr!t|  S t	d|  dt| j
 d d S )Nzget_device_type(: ))r   r   r#  r  r   r   
OutputSpecget_device_typer!  r   r   r   r   r   r   r1    s    r1  &Union[IRNode, torch.device, None, str]c                 C  st   t | }|dv rtt| ddkrdS dS |d u s"t| }d u r$dS ddlm} t|ts5J t|t||S )N)cpucuda_backendtritonTFr@   )TritonScheduling)	r1  r   rA   rE   codegen.tritonr7  r   r   
issubclass)r   r  device_schedulingr7  r   r   r   	is_triton  s   
r;  c                 C  s   t | dkS )Nr3  )r1  r   r   r   r   is_cpu  r   r<  Union[Buffer, TensorBox]	alignmentr   c                   s   t | tr|  d u st|  st|  rdS tj fdd|  d d D  }tt	|  d dt
|  d d}t||}tjj|S )NFc                 3  s"    | ]}t t| d V  qdS )r   N)r   Eqr=   r   r>  r   r   r     s     z-is_aligned_realized_tensor.<locals>.<genexpr>r@   )r   r   maybe_get_strider1   
get_strider  r   AndOrr?  Lerm   r  r  guard_or_false)r   r>  aligned_stridesaligned_last_dim
is_alignedr   r@  r   is_aligned_realized_tensor  s    

$rK  strides1Sequence[_IntLike]strides2shapec                 C  s   t |t | krt | t |ksJ t|| |D ]'\}}}tjj|dr&qtjj||s?tjj|tjj|kr? dS qdS )zP
    Returns true if the strides are equal, ignoring dimensions of size 1 .
    r@   FT)r   r   rm   r  r  statically_known_leqstatically_known_equalssymbolic_hint)rL  rN  rO  dims1s2r   r   r   significant_strides_equal  s   $rV  tensorstrides"Sequence[Union[int, torch.SymInt]]c                 C  s   t | s| S tdd t||  D r| S t||  |  s"| S t| \}}g |j}t|  D ]\}}t	j
j|drE|| ||< q3t|j|j|j||j|j}tt||dS )a  
    Tries to match the strides of the tensor to those in the meta_strides. Strides of insignificant
    dimensions - size 0 or 1 - will be updated.

    If there are real stride differences (NHWC vs NCHW), or the tensor is not realized, then the input will be returned
    c                 s  $    | ]\}}t jj||V  qd S r   rm   r  r  rQ  r   rT  rU  r   r   r   r     
    
z2try_match_insignificant_strides.<locals>.<genexpr>r@   datalayout)r  r   r   rC  rV  r  as_storage_and_layoutr  r   rm   r  r  rP  FixedLayoutr  r  r  offset	is_pinnedr~   ReinterpretView)rW  rX  storage
old_layout
new_strider   r   
new_layoutr   r   r   try_match_insignificant_strides  s.   

rj  gmtorch.fx.GraphModulec                 C  sD   | j jddd }dd t|jD |jd< ddlm} ||  d S )Noutputopr   c                 S  s   g | ]\}}|qS r   r   )r   r   r  r   r   r   r     s    z.gm_original_output_strides.<locals>.<listcomp>user_visible_output_idxs)record_original_output_strides)r  
find_nodesr   r   metatorch._inductor.compile_fxrq  )rk  output_noderq  r   r   r   gm_original_output_strides  s   rv  inputsSequence[IRNode]
list[Expr]c                 C  s@   t  }| D ]}|t| ddO }|t| ddO }qt|S )NFunbacked_only)r9   r'   r  rC  r   )rw  sym_varsinpr   r   r   get_symbolic_inputs	  s
   r~  c                 C  sH   t | tr| j} t | tr|  } t | tr| j} t | tr"|  S d S r   )r   r~   r_  BaseViewunwrap_view
StorageBoxBufferget_namer   r   r   r   try_get_name  s   


r  c                   @  s  e Zd ZU dZe Zded< ejddZ	ded< ejddZ
ded	< ejddZd
ed< ejddZded< eejdddZedddZdddZdddZdd!d"Zdd#d$Zdd%d&Zdd(d)Zdd*d+Zddd/d0Z	,ddd4d5Zdd7d8Zdd:d;Zdd=d>Zdd@dAZddCdDZddFdGZ ddHdIZ!ddKdLZ"ddNdOZ#e$ddQdRZ%ddTdUZ&ddVdWZ'ddYdZZ(ddd^d_Z)ddadbZ*ddddeZ+ddfdgZ,ddidjZ-ddldmZ.ddodpZ/ddqdrZ0ddsdtZ1ddudvZ2ddwdxZ3ddd{d|Z4dddZ5dddZ6dddZ7dddZ8	ddddZ9dddZ:dddZ;	ddddZ<dddZ=dddZ>dddZ?dddZ@	ddddZAdddZBdddZCdddZDdddZEdddZFdddZGdddZHdddZIeJrse$dddZKd[S d[S )r   zBase class for all intermediate representation (IR) nodes in TorchInductor.

    Note:
        This is an abstract base class. Most methods raise NotImplementedError
        and must be overridden by concrete subclasses.
    zClassVar[OrderedSet[Any]]_current_originsF)initOrderedSet[Any]originsOptional[list[str]]	tracebackOptional[torch.fx.Node]origin_nodedict[str, Any]r   OrderedSet[Node]r   Generator[None, None, None]c                 c  s.    t j}|| B t _z	d V  W |t _d S |t _w r   )r   r  )r  oldr   r   r   current_origins.  s   
zIRNode.current_originsr   r   c                 C  s   t | tttttfS r   )r   ComputedBufferInputsKernelInputBufferre  TemplateBufferr   r   r   r   is_realized_node8  s   zIRNode.is_realized_nodeattrr   r'  r   r   c                 C  s   t | || d S r   )r   __setattr__)selfr  r'  r   r   r   _post_init_setattrE  s   zIRNode._post_init_setattrc                 C  sL   t | j}| d| | dtjrt nd  | dd  | di  d S )Nr  r  r  r   )r9   r  r  rA   debug_ir_tracebackr  format_stack)r  r  r   r   r   __post_init__K  s   
zIRNode.__post_init__OrderedSet[str]c                 C     t dd |  D S )Nc                 s      | ]}|j V  qd S r   r   r   depr   r   r   r   V      z(IRNode.get_read_names.<locals>.<genexpr>r9   	get_readsr  r   r   r   get_read_namesU     zIRNode.get_read_namesc                 C     | j S r   )r  r  r   r   r   get_tracebackX     zIRNode.get_tracebackc                 C  r  r   r  r  r   r   r   get_origin_node[  r  zIRNode.get_origin_nodeOptional[Operation]c                 C  r
  r   r   r  r   r   r   get_defining_op^  r  zIRNode.get_defining_opc                 C  s   t  }| j}t| tr|  }| jrt |g}|D ]:}t|dr*|jr*||j qt	j
jjdi |jg }t|ts>q|D ]}t	j
jj|d }|rR|| q@q|S )Nstack_trace	postToPre)r9   r  r   ExternKernelr  r  hasattrr  addr#  	_inductordebug _inductor_post_to_pre_grad_nodesgetr   r   #_inductor_pre_grad_node_stack_trace)r  stack_tracesr  r  r   pre_grad_nodes	node_namer  r   r   r   get_stack_tracesa  s6   






zIRNode.get_stack_tracesTshortenSequence[str]c                 C  s   dt | dd }|rt|dkr|d d  d}|  s!|gS g }|  D ]}|d ||d7 }|d	 q'|g| S )
Nzorigins=r   @   =   z...zstack_traces = {
})r   r   r  appendsplit)r  r  r  stack_trace_strr  r   r   r   common_repr  s   

zIRNode.common_reprlinesSequence[object]	multilinec                 C  sb   t |t | | }t tt|}|r&td|}t| j d| dS t| j d| dS )Nz,
z(
z
)(r/  )r   r  mapr   indentjoinr   r   )r  r  r  r  	new_linesr   r   r   
str_helper  s   zIRNode.str_helpertorch.dtypec                 C  r  r   r  r  r   r   r   r     r  zIRNode.get_dtypeOptional[torch.dtype]c                 C      z|   W S  ty   Y d S w r   )r   NotImplementedErrorr  r   r   r   maybe_get_dtype  
   
zIRNode.maybe_get_dtypeLayoutc                 C     t dt|  d)Nz#get_layout() is not implemented by !r  r   r  r   r   r   r    r   zIRNode.get_layoutOptional[Layout]c                 C  r  r   )r  r  r  r   r   r   maybe_get_layout  r  zIRNode.maybe_get_layoutr0  c                 C     |   S r   )r  r  r   r   r   get_output_spec     zIRNode.get_output_specOptional[OutputSpec]c                 C  r  r   )r  r  r  r   r   r   maybe_get_output_spec  r  zIRNode.maybe_get_output_specc                 C  s   t |  tS )z4True for single tensor output (excludes MultiOutput))r   r  r  r  r   r   r   has_tensor_output  s   zIRNode.has_tensor_outputSequence[Expr]c                 C  r  )Nz!get_size() is not implemented by r  r  r  r   r   r   r    r   zIRNode.get_sizeOptional[Sequence[_IntLike]]c                 C  r  r   )r  r  r  r   r   r   maybe_get_size  r  zIRNode.maybe_get_size.Union[_IntLike, sympy.Rel, Sequence[_IntLike]]c                 C  r  r   r  r  r   r   r   rO       zIRNode.shaper   c                 C     t |  S r   )rh   r  r  r   r   r   	get_numel  r   zIRNode.get_numelc                 C     t jjt|  dS Nr   rm   r  r  statically_known_truer   r?  r  r  r   r   r   is_zero_elements     zIRNode.is_zero_elementsr-  c                 C     t dt|  )a)  
        If the IRNode refers to data which has not been materialized (e.g.,
        it is a Pointwise/Reduction that could potentially have more
        compute fused into it), realize the IRNode into physical memory,
        ending the possibility of fusing into it, but allowing, e.g., multiple
        users to access the data without having to recompute.

        Check StorageBox.realize for a particularly notable implementation.

        TODO(ezyang): I think, in principle, every IRNode should have an
        implementation of this, and most of the time no-op is OK, but you
        really do have to audit each IRNode for this, so for now, raise
        an error if it's not implemented.  Note that some code in graph.py
        will catch this thrown error and suppress it with a warning.
        zrealize NYI on r  r  r   r   r   realize  s   zIRNode.realizeNwriterOptional[IndentedBuffer]c                 C  r  )Nzcodegen_reference NYI on r  r  r  r   r   r   codegen_reference     zIRNode.codegen_referenceOptional[torch.device]c                 C  r
  r   r   r  r   r   r   r!    r  zIRNode.get_devicetorch.devicec                 C     |   }|d us
J |S r   r!  r  r  r   r   r   get_device_or_error     zIRNode.get_device_or_errorc                 C     dS NFr   r  r   r   r   has_exceeded_max_reads  r  zIRNode.has_exceeded_max_reads$Callable[[Sequence[Expr]], OpsValue]c                 C     t t| jr   r  r   r   r  r   r   r   make_loader  r   zIRNode.make_loader Callable[[Sequence[Expr]], Expr]c                 C  r  r   r  r  r   r   r   make_indexer  r   zIRNode.make_indexerrM  c                 C  r  r   r  r  r   r   r   rC    r   zIRNode.get_stridec                 C  r  r   )rC  r  r  r   r   r   rB    r  zIRNode.maybe_get_stridec                 C  r  r   r  r  r   r   r   r    r   zIRNode.get_namec                 C  r  r   )r  r  r  r   r   r   maybe_get_name  r  zIRNode.maybe_get_namec                 C  s(   z	|   tjjv W S  ty   Y dS w r  )r  rm   r  graph_inputsr  r  r   r   r   is_input_buffer  s
   zIRNode.is_input_buffer	thresholdOptional[int]c                 C  r  r  r   r  r  r   r   r   has_large_inner_fn  r  zIRNode.has_large_inner_fnusersr   c                 C  r
  r   r   r  r  r   r   r   
mark_reuse  r  zIRNode.mark_reusec                 C  r
  r   r   r  r   r   r   realize_hint  r  zIRNode.realize_hintc                 C  r  r   r  r  r   r   r   r    r   zIRNode.unwrap_viewc                 C  r  r   r  r  r   r   r   freeze_layout  r   zIRNode.freeze_layoutr   r   allow_paddingc                 C  r  r   r  r  r   r  r   r   r   freeze_layout_with_stride_order     z&IRNode.freeze_layout_with_stride_orderc                 C  r  r   r  r  r   r   r   r   freeze_layout_with_fill_order!  r   z$IRNode.freeze_layout_with_fill_orderr  c                 C  r  r   r  r  r  r   r   r   freeze_layout_with_same_order$  r   z$IRNode.freeze_layout_with_same_orderexact_stridesc                 C  r  r   r  r  r  r  r   r   r    freeze_layout_with_exact_strides'  r  z'IRNode.freeze_layout_with_exact_stridesdependencies.ReadWritesc                 C  r  r   r  r  r   r   r   get_read_writes,  r   zIRNode.get_read_writesOrderedSet[Dep]c                 C  
   |   jS r   r#  readsr  r   r   r   r  /     
zIRNode.get_readsc                 C  r  r   )r   r  r  r   r   r   	num_reads2  r   zIRNode.num_readsry   c                 C  r  r   r  r  r   r   r   get_storage_numel5  r   zIRNode.get_storage_numelr{  r   c                 C  r  r   r  r  r{  r   r   r   get_free_symbol_uses8  r  zIRNode.get_free_symbol_usesc                 C  r  r   r  r  r   r   r   get_reduction_type=  r   zIRNode.get_reduction_typec                 C  r  r   r  r  r   r   r   get_reduction_size@  r   zIRNode.get_reduction_sizec                 C  r  r  r   r  r   r   r   	is_externC  r  zIRNode.is_externc                 C  r  r  r   r  r   r   r   is_no_opF  r  zIRNode.is_no_opr  c                 C  r  r   r  r  r   r   r   constant_to_deviceI  r   zIRNode.constant_to_devicec                 C  r  r   r  r  r   r   r   get_mutation_namesL  r   zIRNode.get_mutation_namesc                 C  r  r   r  r  r   r   r   get_operation_nameO  r   zIRNode.get_operation_namec                 C  r  r   r  r  r   r   r   get_inputs_that_alias_outputR  r   z#IRNode.get_inputs_that_alias_outputc                 C  r
  r   r   r  r   r   r   r  W  r  zIRNode.dtype)r  r  r   r  r   r   r   r   )r  r   r'  r   r   r   r   r   r   r  )r   r  r   r  r   r  T)r  r   r   r  )TT)r  r  r  r   r  r   r   r   r   r  )r   r  r   r  )r   r  r   r0  )r   r  r   r   r   r  )r   r  )r   r  r   r   r   r-  r   r  r  r   r   r   r  r   r  r   r  r   r	  r   rM  r   r   r  r  r   r   r  r   r   r   r   r   Fr   r   r  r   r   r   r   r   r   r   r  rM  r   r   r  rM  r  r   r   r   r   r"  r   r$  r   r   r   ry   r{  r   r   r   r  r  r   r   r   r  )Lr   r   r   __doc__r9   r  r   dataclassesfieldr  r  r  r   staticmethod
contextlibcontextmanagerr  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  propertyrO  r  r  r  r  r!  r   r  r  r
  rC  rB  r  r  r  r  r  r  r  r  r  r  r  r!  r#  r  r)  r*  r,  r-  r.  r/  r0  r1  r2  r3  r4  r   r  r   r   r   r   r     s   
 







!







































c                   @  s   e Zd Zd0ddZd1ddZd2d	d
Zd3ddZd4ddZd5ddZd5ddZ	d6ddZ
d7ddZd8ddZd9d d!Zd:d#d$Zd;d&d'Z	(d<d=d*d+Zd>d-d.Zd/S )?	Operationr   r   c                 C  s
   d | _ d S r   operation_namer  r   r   r   r  ]  r(  zOperation.__post_init__r  c                 C     t r   r  r  r   r   r   r!  `  r  zOperation.get_devicer  c                 C     t | dsJ | jS Nr  )r  r  r  r   r   r   r  c     zOperation.get_origin_noder  c                 C  rd  )Nr  )r  r  r  r   r   r   get_originsg  rf  zOperation.get_originsr   c                 C  s   | j d usJ | j S r   r`  r  r   r   r   r3  k  rf  zOperation.get_operation_namer   c                 C  r  r  r   r  r   r   r   r/  o  r  zOperation.is_externc                 C  r  r  r   r  r   r   r   r0  r  r  zOperation.is_no_opr"  c                 C  rb  r   rc  r  r   r   r   r#  u  r  zOperation.get_read_writesr   c                 C  s   ||   v S r   )r  r  r   r   r   r   
is_user_ofx  r   zOperation.is_user_ofr  c                 C  r  )Nc                 s  r  r   r   r  r   r   r   r   |  r  z+Operation.get_read_names.<locals>.<genexpr>r  r  r   r   r   r  {  r  zOperation.get_read_namesr$  c                 C  r%  r   r&  r  r   r   r   r  ~  r(  zOperation.get_readslist[Buffer]c                 C  rb  r   rc  r  r   r   r   get_outputs  r  zOperation.get_outputsr   c                 C     t  S r   r8   r  r   r   r   get_unbacked_symbol_defs  r  z"Operation.get_unbacked_symbol_defsFr{  c                 C  rl  )a  
        When unbacked_only=True:
        Returns the unbacked symbols which are required to be in scope in
        order to successfully perform codegen for this buffer.  For example,
        a buffer that corresponds to an extern kernel call that takes i0 as
        an argument would return {i0} here.  This is used to generate necessary
        dependencies that ensure we actually bind i0 in codegen before you
        try to use it.

        Note that this is NOT transitive; in particular, if this buffer takes
        in as input another buffer with dynamic shape (e.g., (i0,)), we will
        not report it here, because you will already have a dependency
        on that buffer, which will eventually have a dependency on i0 if
        necessary.

        When unbacked_only=False:
        Similar to `unbacked_only=True` but including all free symbols
        instead of only free unbacked symbols.
        r8   r+  r   r   r   r,    s   zOperation.get_free_symbol_usesr   c                 C  r  )z
        Gets extra global memory size needed by this buffer.
        Some algorithms (e.g. group gemm) may require extra global memory in the generated code.
        r   r   r  r   r   r   get_workspace_size  s   zOperation.get_workspace_sizeNr6  rC  r8  )r   r  rH  r>  rQ  )r   r   r   r   r7  rR  r   rj  r   r   rL  rU  rS  )r   r   r   r  r!  r  rg  r3  r/  r0  r#  ri  r  r  rk  rm  r,  rn  r   r   r   r   r_  [  s"    












r_  c                   @  s   e Zd ZU ded< ded< ded< ded< ed 		dMdNddZdOddZdPddZeZdQddZ	dRddZ
dSddZdSd d!ZedTd&d'ZeejfdUd*d+ZedVd-d.ZdWd0d1ZedPd2d3ZdXdYd7d8ZdMdZd:d;Zd[d=d>Zd\d@dAZd]dCdDZdSdEdFZd^dHdIZd_dKdLZd4S )`Loopsr  r  r  r  Callable[..., Any]inner_fnrM  rangesFr{  r   r   r   c                   s,   t  jg  fdd| jD |  R  S )Nc                 3      | ]}t | V  qd S r   r&   r   erz  r   r   r         z-Loops.get_free_symbol_uses.<locals>.<genexpr>)r9   unionrt  inner_fn_free_symbolsr+  r   rz  r   r,    s
   zLoops.get_free_symbol_usesnamesr  r   c                   sF     d jj dt j  g fdd|D  d jg S )N'c                   s    g | ]}| d t  | qS =)r   r   r   r  r   r   r     s     z!Loops._to_str.<locals>.<listcomp>origin_node=)r  r  r   r   r  inner_fn_strr  )r  r{  r   r  r   _to_str  s   zLoops._to_strc                 C  
   |  dS Nrt  r  r  r   r   r   __str__  r(  zLoops.__str__r  c                 C  r  r   r  r  r   r   r   r!    r  zLoops.get_devicer  c                 C  r  r   r  r  r   r   r   r    r  zLoops.get_origin_noder  c                 C  r  r   r  r  r   r   r   r    r  zLoops.get_sizec                 C  r  r   r  r  r   r   r   get_pointwise_size  r  zLoops.get_pointwise_sizer   r   r   r~   c                 O  sN   | dd }| dd }| |i |}|d| |d|p |j t|S )Nr  r  )popr  r  r~   create)clsr   r   r  tbrr   r   r   r    s   
zLoops.creater}   r?   c                   s    fddt | D S )Nc                   s*   g | ]\}}|d krt jjnt |qS r@   )r   SZerorg   )r   nr   r|   r   r   r         z Loops._index.<locals>.<listcomp>)r   )rt  r}   r   r|   r   _index  s   
zLoops._indexrO   c              	   C  s   t t }t|2 ttdd | j|    |	 W  d    W  d    S 1 s0w   Y  W d    d S 1 s@w   Y  d S Nallow_indexingT)
rN   rm   MockHandlerset_ops_handlerr   r   r  rs  inner_fn_argsgetvalue)r  	opcounterr   r   r   inner_fn_opcount  s   RzLoops.inner_fn_opcountSequence[Sequence[_IntLike]]c                 C  s   |  | jfS r   )r  rt  r  r   r   r   r    r   zLoops.inner_fn_argsc                 C  s   t jj| jg|  R  S r   )rm   KernelFormatterHandlerir_to_stringrs  r  r  r   r   r   r    s
   zLoops.inner_fn_strNr  r  c                 C  s&   |d u rd}t |tj}|  j|kS r  )maxrA   realize_opcount_thresholdr  num_opsr  r   r   r   r    s   zLoops.has_large_inner_fnOrderedSet[Symbol]c                 C  s   |  | j}t| j||dS Nrz  )r  rt  rI   rs  )r  r{  r   r   r   r   rz    s   zLoops.inner_fn_free_symbolsr$  c                 C  sv   t tdd* |  r t|  |  |  jW  d    S t|  |  jW  d    S 1 s4w   Y  d S r  )	r   r   r  r-  rK   r  r  r.  r'  r  r   r   r   r    s   $zLoops.get_readsr  c                 C     t |  jS r   )r9   r  read_buffersr  r   r   r   r    r   zLoops.get_read_namesr   c                 C  r  r   )r   r  r  r  r   r   r   r)    r   zLoops.num_readsc                 C  r  )Nz+get_reduction_size() is not implemented by r  r  r  r   r   r   r.       zLoops.get_reduction_sizer-  c                 C  r  )Nz+get_reduction_type() is not implemented by r  r  r  r   r   r   r-    r  zLoops.get_reduction_typer   c                 C  r  )Nz+constant_to_device() is not implemented by r  r  r  r   r   r   r1  !  r  zLoops.constant_to_devicerL  rU  )r{  r  r   r   rH  rC  r8  r?  )r   r   r   r   r   r~   )rt  rM  r}   r?   r   r  )r   rO   r   r  r   rI  r{  r   r   r  rR  r7  rS  rA  rV  )r   r   r   r   rX   r,  r  r  __repr__r!  r  r  r  classmethodr  r[  r?   INDEXr  rW   r  r  r  r  rz  r  r  r)  r.  r-  r1  r   r   r   r   rq    s@   
 






	




rq  r   Union[Expr, Sequence[Expr]]r  r  rl   c                C  s"   |j rttd|S td|S )Nnanr   )is_floating_pointrk   constantfloat)r   r  r   r   r   nop_loader_fn'  s   r  c                   @  sL   e Zd ZdddZdddZeZdd	d
ZdddZd ddZd!ddZ	dS )"	Pointwiser   r  c                 C  s   |   rtt| jdS | jS Nr  )r  r   r  r  rs  r  r   r   r   r  0  s   zPointwise.make_loaderr   c                 C  r  r  r  r  r   r   r   r  7  r(  zPointwise.__str__Sequence[sympy.Expr]c                 C  s   g S r   r   r  r   r   r   r.  <  r  zPointwise.get_reduction_sizer-  c                 C  r
  r   r   r  r   r   r   r-  ?  r  zPointwise.get_reduction_typeoutput_nameindexer!Callable[[Sequence[Expr]], Never]varsr  r   c                 C  s"   |   }t|p	d||||S Nunnamed)r  rk   storer  r  r  r  loaderr   r   r   store_outputB  s   zPointwise.store_outputr  r  r   c                 C  s.   |   }ttd||}t|| j|| jdS FMove this to a given device. Requires that all reads are to constants.override_devicer  r  rs  rt  )r  r   r   ConstantBufferr  r  rt  r  r  r  r   r   r   r1  K  s   zPointwise.constant_to_deviceNrE  rH  )r   r  rA  )r  r-  r  r  r  r  r   r   rV  )
r   r   r   r  r  r  r.  r-  r  r1  r   r   r   r   r  .  s    




	r  c                   @  s6   e Zd ZU ded< dZded< dd
dZdddZdS )Scatterr	  output_indexerNrQ   scatter_moder  r  r   r   c                 C  s6   |   }ttd||}t|| j|| j| j| jdS )r  r  )r  r  rs  rt  r  r  )	r  r   r   r  r  r  rt  r  r  r  r   r   r   r1  \  s   zScatter.constant_to_devicer  r-  r  r  r  r  r   c                 C  s6   |   }|d u r
d}tj||| |||| jdS )Nr  )mode)r  rk   r  r  r  r  r   r   r   r  i  s   zScatter.store_outputrV  )r  r-  r  r  r  r  r   r   )r   r   r   r   r  r1  r  r   r   r   r   r  W  s
   
 
r  
logical_ormaximumminimummulr  bitwise_xor)anyr  minprodsumdotxor_sumz"dict[str, Callable[..., OpsValue]]REDUCTION_COMBINE_FNreduction_typearg_break_ties_leftCallable[..., object]c                   sR   t v rt  S dv rd fdd}|S d	kr"ddd}|S td )Nargmaxargminatuple[object, object]br   tuple[OpsValue, OpsValue]c                   s   | \}}|\}}dkrt ||}nt ||}t ||}trCt ||}t ||}	t |t ||	}t |t ||	} rKt ||nt ||}
t |t ||
}t |||t |||fS )Nr  )	rk   ltgteqr+   ner  logical_andwhere)r  r  a_valuea_indexb_valueb_indexmaskequala_isnanb_isnantier  r  r  r   r   argmax_combine_fn  s&   
z3get_reduction_combine_fn.<locals>.argmax_combine_fnwelford_combine#tuple[OpsValue, OpsValue, OpsValue]c                 S  sR   | \}}}|\}}}|| }|| }	||	 }
|||
  || || | |
  |	fS r   r   )r  r  a_meana_m2a_weightb_meanb_m2b_weightdelta
new_weight	w2_over_wr   r   r   welford_combine_fn  s   


z4get_reduction_combine_fn.<locals>.welford_combine_fnzunknown reduction_type=)r  r  r  r  r   r  )r  r  r  r  r   r  )r  r  )r  r  r  r  r  r   r  r   get_reduction_combine_fn  s   
r  c                      s\  e Zd ZU ded< ded< ded< ded< dkddZeZed dldm fddZdnddZdoddZ	dpd d!Z
dqd#d$Zdrd&d'Zdldmd(d)Zdsd-d.Ze	/dtdud:d;Zedvd>d?Zeejd/fdwdBdCZedxdFdGZedxdHdIZedydMdNZedzdPdQZe	/dtd{dWdXZed|d`daZed}dedfZe	/dtd~dgdhZeddidjZ  ZS )	ReductionrM  reduction_rangesrP   r  r  	src_dtyperT   reduction_hintr   r   c                 C  r  )N)rt  r  r  r  r  r   r   r   r    r(  zReduction.__str__Fr{  r   r  c                   s(   t   t j fdd| jD  B S )Nc                 3  ru  r   r&   rv  rz  r   r   r     rx  z1Reduction.get_free_symbol_uses.<locals>.<genexpr>)superr,  r9   ry  r  r+  	__class__rz  r   r,    s   zReduction.get_free_symbol_usesr  c                 C  r  r   )r  r  r   r   r   r.    r  zReduction.get_reduction_sizer-  c                 C  r  r   )r  r  r   r   r   r-    r  zReduction.get_reduction_typer  r  r  r  reduction_varsSequence[Symbol]r   c              	   C  s8   t | j| j| j| ||}t |pd||| d S r  )rk   	reductionr  r   r  rs  store_reduction)r  r  r  r  r  r'  r   r   r   r    s   
zReduction.store_reductionr   c                 C     t | jt | j S r   )r   rt  r  r  r   r   r   index_length  r   zReduction.index_lengthSequence[Sequence[Expr]]c                 C  s$   |  | j}|  | jtj}||fS r   )r  rt  r  r?   R0_INDEX)r  r   rindexr   r   r   r    s   zReduction.inner_fn_argsc                 C  s.   |  | j}|  | jtj}t| j|||dS r  )r  rt  r  r?   r  rI   rs  )r  r{  r   r  r   r   r   rz    s
   
zReduction.inner_fn_free_symbolsr  r  r   c              
   C  s>   |   }ttd||}t|| j|| j| j| j| j	t
jdS )r  r  r  r  rs  rt  r  r  r   r  )r  r   r   r  r  r  rt  r  r  r   rT   DEFAULTr  r   r   r   r1    s   zReduction.constant_to_deviceN	dst_dtypers  Callable[_P, OpsValue]rt  %Union[ReductionType, Literal['scan']]reduction_numelr   
input_noder  tuple[ReductionHint, _IntLike]c	           "   
   C  s  t jj|}	t jjt|}
|dkp#t j| tj o#|dvo#tj	}t
|	r,t
|
s1tjdfS |dkr:tjdfS t| }|j}d}|r[tjt jj| dd}tjt jj| dd}nddd}|}|
dkr||	|
}|dkrttj|fS |d urt|trttdd t|\}}W d    n1 sw   Y  |d ur|d urt jjt|| }|	|krtd||||| tjdfS tj|fS |	|ks|
|d d krtjdfS t| |||||dkr|nd|tjd}ddd}||\}}|r||\}}t|dkrtjdfS t |! |" \\}}}d}d}|D ].}t jj#||}t jj$||t%|& } t'dd | D }!|!rE|d7 }q|d7 }q||krXtj||	|
fS tj(||	|
fS )Nscanr  r@   r      T)inner_reductionFreduction_numel_hintr   
numel_hintr   c                 S  r  Nr@   r   )r  r  r   r   r   inner_reduction_splits7     z4Reduction.num_splits.<locals>.inner_reduction_splitsr  zUse previous IRNode's range and reduction_ranges instead of split. current ranges: %s, current reduction ranges: %s, current split: %d, new ranges: %s, new reduction ranges: %srA  r   r  r  r  r  tuple[Sequence[Expr], bool]c           	        s   |   }|d us
J td t||  |  d| d}| }|jd us%J dd |jD }g }d}t|jdd dD ]7 t	 fd	d
|D rq|
 j  jtjjv rqtjj j }t|jdd }|  t|jdd |krqd}q:||fS )Nr  r  r  r   r`  r_  c                 S  s&   g | ]}t |trt |tjs|qS r   )r   r   r   Numberr   r  r   r   r   r     s    
zBReduction.num_splits.<locals>.get_read_indices.<locals>.<listcomp>Fc                 S  r  r   r   r   r   r   r   <lambda>      z@Reduction.num_splits.<locals>.get_read_indices.<locals>.<lambda>keyc                 3  s    | ]	}| j jv V  qd S r   )r   r0   r"  mdr   r   r         zAReduction.num_splits.<locals>.get_read_indices.<locals>.<genexpr>r  T)r!  r  r  r   r  r#  
range_varssortedr'  r   r  r   r   rm   r  name_to_bufferr   r`  decide_layout)	r  r  cbread_writesr*  indiceschangedbuforiginal_strider   r'  r   get_read_indiceso  s:   	z.Reduction.num_splits.<locals>.get_read_indicesr   c                 s  s     | ]}|d kp|dkV  qdS )r   r@   Nr   r   r   r   r   r     r   z'Reduction.num_splits.<locals>.<genexpr>)r  r   r  r   r   r   )r  r  r   r  ))rm   r  r  rR  rh   has_featurerC   REDUCE_TO_SINGLE_ELEMENTrA   split_reductionsr   rT   r  rS   r  multi_processor_count	functoolsr   choicesreduction_split_factorINNERr   r~   r   r   r  rJ   logr  r  r   rB   index_vars_squeezer  r.  simplify_with_rangesstride_hintsr   keysr   OUTER)"r  r  r   rs  rt  r  r  r  r  r  r  should_splitpropsnum_smmin_elements_per_threadr  outer_reduction_splitsr  
new_rangesnew_reduction_rangesextracted_numel_hintr  r4  r0  r1  r  r  ranges1	num_outer	num_innerr   jrX  outerr   r   r   
num_splits
  s   













#

zReduction.num_splits<Callable[[Sequence[_IntLike], Sequence[_IntLike]], OpsValue](Callable[[Sequence[_IntLike]], OpsValue]c                   sf   t jjt|| d fdd|dv r/ttdfd
dfddS S )z1Convert inner_fn from a reduction to an pointwiser   rM  r   r   c                   s,   t  fddtjdd D  D S )Nc                 3  s    | ]} |V  qd S r   r   )r   r  )r   value_fnr   r   r     s
    
z=Reduction._unroll_reduction_fn.<locals>.fn.<locals>.<genexpr>c                 S  s   g | ]}t |qS r   )r   r   r   r   r   r   r     r   z>Reduction._unroll_reduction_fn.<locals>.fn.<locals>.<listcomp>)r9  reduce	itertoolsproductr   )
combine_fnr  rS  r   r   r     s   z*Reduction._unroll_reduction_fn.<locals>.fnr  r  r  r  c                   s*   dd |D }| |t  |tjfS )Nc                 S     g | ]}t |qS r   r   expandr   r   r   r   r     r   zDReduction._unroll_reduction_fn.<locals>.value_fn.<locals>.<listcomp>)rk   
index_exprr#  int64r   r  )flatten_indexrs  r   r   rS    s   z0Reduction._unroll_reduction_fn.<locals>.value_fnc                   s    | d S r  r   r   )r   r   r   r#    s    z0Reduction._unroll_reduction_fn.<locals>.<lambda>N)r   rM  r   r   )r   rM  r  rM  r   r  )rm   r  r  guard_int_seqr  _fixed_indexerr  r  )rs  r  r  r   r   )rX  r`  r   rs  r  rS  r   _unroll_reduction_fn  s   
	zReduction._unroll_reduction_fnrr  r~   c
                   s  t jjtdkrBd# fdd}
|
d|
d|
d|
dd	v s.J  d
d$ fdd}tj|||t|dS dkrcdv rRd$ fdd}nd$fdd}tj| ||dS tt	rt jj
tjk rt|dks}t|jrdkrtj| | ||dS | | |||		\}}d%fdd}||}|tjkr|}|dkr|	dusJ ttdd t|	\}}W d   n1 sw   Y  |dusJ |dusJ | | |||||
S |dkr?| | |||||	
}d}tjjrt|trd&d d!}||}|r=t|jts-J t|j |jjd |_|_ ||_!|_"|S tt| |||d"}|S )'zy
        Create a reduction node. May split the reduction to multiple layers to expose
        more parallelism.
        r   valr   r   Union[bool, float, int]c                   sT    t jkr	t| S  jrt| tsJ t| t| S t| ts&J t| t| S r   )	r#  r   r  r   r   r   r  r   r   rd  r  r   r   py_cnst  s   
z!Reduction.create.<locals>.py_cnstr@   )r  r  r  r  z* not supported for zero-dimension tensors!r   r   rl   c                   s   t   S r   rk   r  r   )r  r  rtypes_to_initsr   r   const_fn     z"Reduction.create.<locals>.const_fnr  rY  c                   s   t d S r  ri  r   rg  r   r   r     r   zReduction.create.<locals>.fnc                      dd D } | |S )Nc                 S     g | ]}t jjqS r   r   r  r  r  r   r   r   r   "  r   z0Reduction.create.<locals>.fn.<locals>.<listcomp>r   r   reduction_index)rs  r  r   r   r   !     
r  r  c                   s$   t  r| S | dkrt| tjS | S r  )r   r  rA   min_num_split)r  )r  r   r   _maybe_increase_splitJ  s
   z/Reduction.create.<locals>._maybe_increase_splitrA  Nr  Tcur_noder~   Optional[ComputedBuffer]c                 S  sd   |   }t|dkrd S tt|}|tjjvrd S tjj| }t|ts'd S |j	
 d us0J |S r  )r  r   nextiterrm   r  r,  r   r  r_  r-  )ru  
read_namesbufnamer2  r   r   r   _find_split_reduction  s   
z/Reduction.create.<locals>._find_split_reductionr  )rd  r   r   re  )r   r   r   rl   )r  r   r   r   )ru  r~   r   rv  )#rm   r  r  simplifyrh   r  r  r   r   r    size_hint_or_throwrA   unroll_reductions_thresholdrd   r   rc  rP  rT   r  r   r   r  rJ   !create_multilayer_existing_rangescreate_multilayerr6  mix_order_reductionr~   r_  r  r  _split_size_original_inner_fn_original_ranges_original_reduction_ranges)r  r  r  r   rs  rt  r  r  r  r  rh  rk  r   hintr  rt  rH  rI  r  split_reductionr{  r   )r  rs  r  r  r  rj  r   r    s   

	




zReduction.creater  #Union[_NumLike, Sequence[_NumLike]]c              	   C  s   | dv rt |rtdS t|rdS t|jS | dv r0t |r$tdS t|r*dS t|jS t|r6dnd}t|r>dnd}||||||||f|||ftd|fd	|  S )
N)r  r  z-infF)r  r  infTr   r@   )r  r  r  r  r  welford_reducer  online_softmax_reduce)r+   r  r*   r#  iinfor  r  )r  r  zerooner   r   r   default_accumulator  s2   
	zReduction.default_accumulatorc                 C  s   | dkrdS t | |S )Nr  r   )r  r  r  r  r   r   r   default_value  s   zReduction.default_valuer  ry   r  c                 C  sP   | dkr|S | dkr|dkr|t jkrt jS | dkr&|dkr&|t jkr&t jS |S )NrA     i      )rT   rB  
OUTER_TINY)r  r  r  r   r   r   _multilayer_second_step_hint  s   
z&Reduction._multilayer_second_step_hintr  c                 C  s   |du rdS t jj| |sdS |  zt| W n
 ty&   Y dS w | }t	|dd D ]\}}t jj|drC|  S q3dS )z
        If we are reducing over the full tensor, and it is non-dense in the last dimension,
        reindex so we reduce over the dense dimension. initially just handle complete
        reduction case
        NrA  r@   )
rm   r  r  rQ  r  r  ra  r  rC  r   )r  r  r  rX  r   r   r   r   r   $check_for_split_dense_dim_reindexing  s$   	z.Reduction.check_for_split_dense_dim_reindexingr  r   
block_sizedefaultr  c           
        sT   |  |}t|g|tjjt| d d	 fdd}	|	S )
Nr   r   r  rq  r   rl   c                   sl   |\}| ^ }| |  d fdd}r3t }tt |t|}t||S | S )Nr   rl   c                     s    gS r   r   r   )r0  r  	new_indexr   r   r   body(  rl  zCReduction._multilayer_wrap_loader.<locals>.wrapper_fn.<locals>.body)r   rl   )r^   rk   r  r]  masked)r   rq  reduction_blockr  index_dtyper  r  r  r  	need_maskr  r   )r0  r  r   
wrapper_fn!  s   


z5Reduction._multilayer_wrap_loader.<locals>.wrapper_fn)r   r  rq  r  r   rl   )	r  Viewdynamic_reshape_indexerrm   r  r  r  r   r?  )
r  r  r  r  r  r  r  r  dense_indexr  r   r  r   _multilayer_wrap_loader  s   z!Reduction._multilayer_wrap_loader4Callable[[Sequence[Expr], Sequence[Expr]], OpsValue]original_rangesoriginal_reduction_rangesrH  Sequence[Integer]rI  @Callable[[Sequence[sympy.Expr], Sequence[sympy.Expr]], OpsValue]c                   sN   t dd D sJ dt|t|t| d fd	d
}|S )Nc                 s  s    | ]}|d kV  qdS )r@   Nr   r"  r   r   r   r   @      zDReduction._multilayer_wrap_loader_existing_ranges.<locals>.<genexpr>z8Only enabled for numel_hint == 1, found original_ranges=merged_indexr  new_reduction_indexr   rl   c                   s:   | d t  }| t d  } |t|t| S r   )r   r   )r  r  original_idxr  r  r  r   r   r   r  G  s   zEReduction._multilayer_wrap_loader_existing_ranges.<locals>.wrapper_fn)r  r  r  r  r   rl   )r   r  r  r   )r  r  r  r  rH  rI  r  r   r  r   '_multilayer_wrap_loader_existing_ranges7  s   	z1Reduction._multilayer_wrap_loader_existing_rangesr  ry  list[Integer]c                   s   |t jt jfvr
|nt j}t|||||||	|}|  |  d
 fdd}tj	j
t|}| |
||}||dt| ksDJ tt|||||t|d |	||d	S )a
        Break a large reduction up into multiple smaller reductions
        recursively
        r   rM  rq  r   rl   c                   s    g | |S r   r   rp  intermediate_loaderr   r   intermediate_fn|  s   z;Reduction.create_multilayer_helper.<locals>.intermediate_fnNr  )r   rM  rq  rM  r   rl   )r#  float16bfloat16r  r  r  r  r  rm   r  r  optimization_hintrh   r  r   r~   )r  r  r  r   r  r  r  rH  rI  r  r  r  intermediate_dtypeintermediater  r  r   r  r   create_multilayer_helperT  sD   
z"Reduction.create_multilayer_helperc                 C  sd   t |}t||d  |}| ||}| |||||||
}| ||||||g |||g|||	S )r  r@   )rh   r<   r  r  r  )r  r  r  r   rs  rt  r  r  r  r  r  r  r  r  r  r   r   r   r    s2   

zReduction.create_multilayerc                 C  s8   |  |||||}| ||||||g ||||	d|
S )r  rA  )r  r  )r  r  r  r   rs  r  r  rH  rI  r  r  r  r   r   r   r    s(   
z+Reduction.create_multilayer_existing_rangesrH  rL  r  r?  rA  )
r  r-  r  r  r  r  r  r  r   r   rS  r   r  rV  r   )r  r  r  r  r   r  rs  r  rt  rM  r  rM  r  r  r  r   r  r  r   r  )
rs  rQ  r  rM  r  r   r   r  r   rR  )r  r  r  r  r   r  rs  rr  rt  r  r  r  r  rP   r  rT   r  r  r   r~   r  r   r  r  r   r  )r  ry   r  r   r  rT   r   rT   )r  ry   r  r  r   r  )r  r   r  rM  r  ry   r  ry   r  ry   r  r  r  r  r   r  )r  r  r  r  r  r  rH  r  rI  r  r   r  )r  r  r  r  r   r  r  rr  r  r  r  r  rH  ry  rI  r  r  rP   r  ry   r  rT   r   r~   )r  r  r  r  r   r  rs  rr  rt  r  r  r  r  rP   r  ry   r  rT   r  r  r   r~   )r  r  r  r  r   r  rs  rr  r  r  r  r  rH  r  rI  r  r  rP   r  rT   r   r~   ) r   r   r   r   r  r  rX   r,  r.  r-  r  r
  r  rz  r1  r[  rP  rc  r  rT   r  r  r  r  r  r  r  r  r  r  r  __classcell__r   r   r  r   r    s^   
 







 *+ R	*?-r  r  r  Optional[Sequence[int]]rc  r   r	  c                   s   d fdd}|S )	1A closure containing math to read a given elementr   r   r   r   c                   sd   d urt | t ksJ t | t ksJ  }t| D ]\}}}|dkr/|||  }q |S r  )r   r   )r   resultr   stszrc  r  r  r   r   r    s   z_fixed_indexer.<locals>.indexerN)r   r   r   r   r   )r  r  rc  r  r   r  r   rb    s   	rb  INNER_FN_TYc                      s2   e Zd ZU ded< d fddZd ddZ  ZS )!MultiOutputReductionr   output_indexr  r  r  r  	inner_fns)Union[INNER_FN_TY, Sequence[INNER_FN_TY]]rt  r  r  r  rP   r   r  rT   c
              
     sX   t  r f t dkr d }
nd fdd	}
t j|||
|||||d
 |	| _d S )Nr@   r   r   r  reduction_idxr   tuple[OpsValue, ...]c                   s   t  fddD S )Nc                 3  s    | ]}| V  qd S r   r   r   r   r   r  r   r   r     rx  z@MultiOutputReduction.__init__.<locals>.loader.<locals>.<genexpr>)r   r  r  r  r   r    s   z-MultiOutputReduction.__init__.<locals>.loaderr  )r   r  r  r  r   r  )callabler   r  __init__r  )r  r  r  r  rt  r  r  r   r  r  r  r  r  r   r    s    


zMultiOutputReduction.__init__r  r-  r  r  r  r  r  r  r   r   c              	   C  sX   t | j| j| j| ||}t|ttfsJ t	||| j
 }t |p&d|||S r  )rk   r  r  r   r  rs  r   r   r   r   r  r  )r  r  r  r  r  r   r'  r   r   r   r  (  s   

z$MultiOutputReduction.store_reduction)r  r  r  r  r  r  rt  r  r  r  r  rP   r   r  r  rT   r  r   )
r  r-  r  r  r  r  r  r  r   r   )r   r   r   r   r  r  r  r   r   r  r   r     s   
 %r  c                   @  s"   e Zd ZeejdfdddZdS )OnlineSoftmaxReductionNr  r  r  r  r   rs  rr  rt  r  r  
num_outputr   r  rT   r  r  r   Sequence[TensorBox]c
                   s<   t  fddt|D }
|
D ]}|  q|
S )z>
        Create the reduction disregarding splitting.
        c                 3  s.    | ]}t t d |	V  qdS )r  N)r~   r  r  r   
output_idxr  r  rs  rt  r  r  r   r   r   r   K  s"    
z0OnlineSoftmaxReduction.create.<locals>.<genexpr>)r   r   r  )r  r  r  r   rs  rt  r  r  r  r  resultsr&  r   r  r   r  ;  s   
zOnlineSoftmaxReduction.create)r  r  r  r  r   r  rs  rr  rt  r  r  r  r  r   r  rT   r  r  r   r  )r   r   r   r  rT   r  r  r   r   r   r   r  :  s
    
r  c                   @  s<   e Zd ZeejfdddZedddZedddZ	dS )WelfordReductionr  r  r  r  r  Sequence[Callable[..., Any]]rt  r  r  r  rP   r  rT   r   r  c              
     s6  dv sJ t jjt}dfdd}	|dkr-|	d}
|	d}|	d}|
||fS |d	krWdfdd dkrL d |	d|	d	fS t fddD S tjd |d\}}tj	kro||d	kr| 
|S fddtdD }|D ]}|  q|S )N)r  r  rd  r   r   r~   c                   s&   d fdd}t j|tdS )	Nr   r  r   rl   c                   s   t  S r   ri  r   )r  rd  r   r   rs  q  s   z8WelfordReduction.create.<locals>.const.<locals>.inner_fnr  r   r  r   rl   r  r  r   )rd  rs  )r  r  rt  rf  r   constp  s   z&WelfordReduction.create.<locals>.constr   r@   r  r  c                   s&   d fdd}t j|tdS )	Nr   r  r   rl   c                   rm  )Nc                 S  rn  r   ro  r  r   r   r   r     r   zKWelfordReduction.create.<locals>.copy.<locals>.inner_fn.<locals>.<listcomp>r   )r   rq  )r  r  r   r   rs    rr  z7WelfordReduction.create.<locals>.copy.<locals>.inner_fnr  r  r  )r  rs  )r  r  rt  r  r  r   copy  s   z%WelfordReduction.create.<locals>.copyr  c                 3      | ]} |V  qd S r   r   r  )r  r   r   r     r  z*WelfordReduction.create.<locals>.<genexpr>)r  r  c                   s*   g | ]}t t |	qS r   )r~   r  r  r  )r  r  r  rt  r  r  r  r   r   r     s     z+WelfordReduction.create.<locals>.<listcomp>r   )rd  r   r   r~   )r  r  r   r~   )rm   r  r  r|  rh   r   r  rP  rT   r  r  r   r  )r  r  r  r  rt  r  r  r  r  r  meanm2weightr  r  r  r&  r   )r  r  r  r  rt  r  r  r  r   r  a  sT   



zWelfordReduction.creater   r  c                 C  r  )N)r   r   r   r   r  r   r   r   r    r  zWelfordReduction.default_valuer  ry   c	              
     s$  t tjjt d }	|	r9|dkr9dfd
d}
j||d t|
ddt|
ddf|d|dS t	d   t
|t fdd|D g | g||}|D ]}|  qadddtjjt |}||}t
|tfdd|D |gd|S )r  r   r  r   r  r  r'  r   r   rl   c                   s   t | S r   ri  )r   r  r'  r  r   r   r    s   z4WelfordReduction.create_multilayer.<locals>.constantr*  r@   )r  r  r  rt  r  r  r  r  c              	   3  s&    | ]}j | d dV  qdS )r   )r  N)r  )r   r  )r  r  r  r  r  r   r   r   	  s    	
z5WelfordReduction.create_multilayer.<locals>.<genexpr>r   rq  r  r  c                 S  s   |g | |S r   r   )r   rq  r  r   r   r   intermediate_loader_fn$	  s   zBWelfordReduction.create_multilayer.<locals>.intermediate_loader_fnc                 3  s     | ]}t  | d V  qdS )r  N)r   r  r   )r  r   r   r   2	  
    
N)r   r  r  r  r'  r   r   rl   )r   r  rq  r  r  r  r   rl   )rh   rm   r  r  r  r   r?  r  r   r<   r  r  r   r  r  r  )r  r  r  r  rt  r  r  r  r  r  r  intermediatesr   r  r   )r  r  r  r  r  r  r  r   r    sb   

	


z"WelfordReduction.create_multilayerN)r  r  r  r  r  r  rt  r  r  r  r  rP   r  rT   r   r  r  )r  r  r  r  r  r  rt  r  r  r  r  rP   r  ry   r  rT   r   r  )
r   r   r   r  rT   r  r  r[  r  r  r   r   r   r   r  `  s    	xr  c                      s   e Zd ZU ded< ded< ded< ded< ded	< d
ed< ded< ded< ed dIdJ fddZdK fddZdLd#d$ZdMd%d&ZdNd'd(Z	dNd)d*Z
dNd+d,ZdOd-d.ZdPd0d1ZdIdJd2d3Zeejfd4d5dQd=d>ZedRdGdHZ  ZS )SScanr  scan_rangesr  =Callable[[tuple[Any, ...], tuple[Any, ...]], tuple[Any, ...]]rX  zFCallable[[Sequence[_IntLike], Sequence[_IntLike]], Sequence[_IntLike]]r   rT   r  r   r  tuple[torch.dtype, ...]dtypestuple[Callable[..., Any], ...]r  Fr{  r   r   r  c                   D   t   t j fdd| jD  B t j fdd| jD  B S )Nc                 3  ru  r   r&   rv  rz  r   r   r   T	  rx  z,Scan.get_free_symbol_uses.<locals>.<genexpr>c                 3  ru  r   r&   rv  rz  r   r   r   W	  rx  )r  r,  r9   ry  r  r  r+  r  rz  r   r,  L	  s   
zScan.get_free_symbol_usesr   c                   0   t | jt | j t | jksJ t   d S r   )r   rt  r  r  r  r  r  r  r   r   r  [	     "zScan.__post_init__r  r-  r  %Callable[[Sequence[_IntLike]], Never]r  r  	scan_varsr  r   c                   sR   |  || t fdd| jD }t| j| j|}t|p d| || j S )Nc                 3      | ]}| V  qd S r   r   r   rs  r  r   r   r   g	  r  z'Scan.store_reduction.<locals>.<genexpr>r  )	r   r   r  rk   r  r  rX  r  r  )r  r  r  r  r  r   r  r   r  r   r  _	  s   zScan.store_reductionc                 C  r  )Ncustomr   r  r   r   r   r-  m	     zScan.get_reduction_typec                 C  r  r   )r  r  r   r   r   r.  q	  r  zScan.get_reduction_sizec                 C  r  r   r  r  r   r   r   r  t	  r  zScan.get_sizec                 C  r  r   r  r  r   r   r   r  w	  r  zScan.get_pointwise_sizec                 C  r	  r   )r   rt  r  r  r   r   r   r
  z	  r   zScan.index_lengthr  c                 C  .   |  | j}|  | jtj}| ||}|fS r   )r  rt  r  r?   r  r   r  r   r  r   r   r   r   r  }	     zScan.inner_fn_argsc                 C  8   |  | j}|  | jtj}| ||}t| j||dS r  )r  rt  r  r?   r  r   rI   rs  r  r{  r   r  r   r   r   r   rz  	     zScan.inner_fn_free_symbolsT)can_fallback_to_atenr  r  +tuple[Callable[[Sequence[Expr]], Any], ...]axisr  r   Sequence[Optional[TensorBox]]c                  s  g d    d d    g	t jtjs$d gt S tdkr9t jtjs9d gt S t jj}
|
t		}ttksNJ |

t|drgfddttD S | jd d  	|d\}t
|dkrtjjd u ptotdkotdk}|s|rd gt S d}nt
d 	fdd	
fddttD }|D ]}|  q|S )Nr@   c                   &   g | ]}t j | | d qS r  r  r  r   r  r  r  r  r  r   r   r   	      zScan.create.<locals>.<listcomp>r   )r  r  rs  r  pointwise_rangesr  rX  
scan_numelz3.3.0r   r  
scan_indexr   ry  c                   H   t |t ks
J t | t ksJ g | d   ||  d  S r   r   )r   r  )r  r  r  r   r   r   	      zScan.create.<locals>.reindexc                   sB   g | ]}t 	d| | 
 |d qS ))r  r  r  rs  r  r  rt  r  rX  r   r  r  r   )r~   r  r  )rX  r  r  r  r   r  r  r   r  	scan_typer  r   r   r   	  s*    )r   r  r  r  r   ry  )rm   r  r5  rC   SCANr   TUPLE_REDUCTIONr  r|  rh   r  r   rF  r   rP  r  r#  versionhip
has_tritontriton_version	SplitScanr  )r  r  r  r  r  r  rX  r  r  r   r  r  rP  supports_splitr  r  r   )r  rX  r  r  r  r   r  r  r   r  r  r  r   r  	  sV    







zScan.creater  r  rs  r  r  r  r   r  c	           
   
     s*   d
 fdd}	t j||||	||d|d	S )Nr   r  r  r   rl   c                   s$   g | d   ||  d  S r   r   r  r  rs  r   r   r  	  s   $z#Scan.num_splits.<locals>.wrapper_fnr  )r  r  r   rs  rt  r  r  r  )r   r  r  r  r   rl   )r  rP  )
r  r  r  rs  r  r  r  rX  r  r  r   r  r   rP  	  s   zScan.num_splitsrL  r  r6  )
r  r-  r  r  r  r  r  r  r   r   rA  r?  rS  r  )r  r  r  r  r  r  r  r  r  r   rX  r  r  rT   r  r   r   r   r   r  )r  r  r  r  rs  r  r  r   r  r  r  r  rX  r  r  r   r   r  )r   r   r   r   rX   r,  r  r  r-  r.  r  r  r
  r  rz  r  rT   r  r  rP  r  r   r   r  r   r  >	  s6   
 






	br  c                   @  s   e Zd ZdS )r  N)r   r   r   r   r   r   r   r  	
  s    r  c                      s   e Zd ZU ded< ded< ded< ded< ded	< d
ed< ded< ded< ded< ed d;d< fddZd= fddZd>d"d#Zd?d$d%Zd@d&d'Z	d@d(d)Z
d@d*d+ZdAd,d-ZdBd/d0Zd;d<d1d2ZeejfdCd9d:Z  ZS )DSortr  sort_rangesr  z:Callable[[Sequence[Expr], Sequence[Expr]], Sequence[Expr]]r   rT   r  r   r  r  r  r  r  r   stable
descendingFr{  r   r  c                   r  )Nc                 3  ru  r   r&   rv  rz  r   r   r   $
  rx  z,Sort.get_free_symbol_uses.<locals>.<genexpr>c                 3  ru  r   r&   rv  rz  r   r   r   '
  rx  )r  r,  r9   ry  r  r  r+  r  rz  r   r,  
  s   
zSort.get_free_symbol_usesr   c                   r  r   )r   rt  r  r  r  r  r  r  r   r   r  +
  r  zSort.__post_init__r  r-  r  r	  r  r  r  r   c                   sV   |  || t fdd| jD }t| j|| j| j}t|p"d| || j	 S )Nc                 3  r  r   r   r  r  r   r   r   7
  r  z'Sort.store_reduction.<locals>.<genexpr>r  )
r   r   r  rk   sortr  r  r  r  r  )r  r  r  r  r  r   r  r   r  r   r  /
  s   zSort.store_reductionc                 C  r  )Nr  r   r  r   r   r   r-  =
  r  zSort.get_reduction_typec                 C  r  r   )r  r  r   r   r   r.  @
  r  zSort.get_reduction_sizec                 C  r  r   r  r  r   r   r   r  C
  r  zSort.get_sizec                 C  r  r   r  r  r   r   r   r  F
  r  zSort.get_pointwise_sizec                 C  r	  r   )r   rt  r  r  r   r   r   r
  I
  r   zSort.index_lengthr  c                 C  r  r   )r  rt  r  r?   r  r   r  r   r   r   r  L
  r  zSort.inner_fn_argsc                 C  r  r  )r  rt  r  r?   r  r   rI   rs  r  r   r   r   rz  R
  r  zSort.inner_fn_free_symbolsr  r  'tuple[Callable[[list[Expr]], Any], ...]r  r   r  c	                   s*  g 	d   	 d d  	  g
t jtjs$d gt S t jj}
|
t
}d}t	j
jo=|
t||}|sGd gt S ttksQJ |
t|drj	fddttD S d 
fd
d	
fddttD }|D ]}|  q|S )Nr@   r  c                   r   r  r  r  r  r   r   r   }
  r  zSort.create.<locals>.<listcomp>r   r  
sort_indexr   ry  c                   r	  r   r
  )r   r  )r  r  r  r   r   r   
  r  zSort.create.<locals>.reindexc                   sD   g | ]}t td| | 	|
 d qS ))r  r  r  rs  r  r  rt  r  r   r  r  r  r  r   )r~   r  r  r  )r  r  r  r  r   r  r  r   r  r  r  r   r   r   
  s,    )r   r  r  r  r   ry  )rm   r  r5  rC   SORTr   r  r|  rh   rA   r6  persistent_reductionsr  r   rF  r   r  )r  r  r  r  r  r  r  r  r  r   r  
sort_numel
max_rblockis_persistent_kernelr  r  r   )r  r  r  r  r  r   r  r  r   r  r  r  r   r  X
  s0    




zSort.createrL  r  r6  )
r  r-  r  r	  r  r  r  r  r   r   rA  r?  rS  r  )r  r  r  r  r  r  r  r  r  r   r  r   r  r   r  rT   r   r   r   r  )r   r   r   r   rX   r,  r  r  r-  r.  r  r  r
  r  rz  r  rT   r  r  r  r   r   r  r   r  
  s0   
 







r  c                 C  s(   z	t | dd W dS  ty   Y dS w )NFfreezeT)ra  r  r   r   r   r   r  
  s   r  c                 C  s@   zt | dd\}}| r|  | W S  ty   Y dS w NFr"  )ra  should_pad_stridespad_stridesis_contiguousr  )r   _bufferr`  r   r   r    is_contiguous_storage_and_layout
  s   
r)  r#  want_contiguousstride_order'Optional[Sequence[Union[int, Integer]]]r  r  tuple[StorageBox, Layout]c           	      C  s   t | trt| j|||||dS t | tr)t| j|||||d\}}| | j fS t | trc|r[|r?|   |   s>J n|durK| j	||d n|durW| j
||d n|   t| |  fS t | trvt| j|d\}}|| jfS t)z
    Try to simplify x into a StorageBox and a Layout.

    allow_padding only affect how we apply stride_order. When allow_padding
    is True, we have the freedom to add padding when applying the stride_order.
    r#  r*  r+  r  r  Nr  r"  )r   r~   ra  r_  r  r  r  r  r'  r  r!  r-  re  r`  r  )	r   r#  r*  r+  r  r  r  r`  bufferr   r   r   ra  
  sR   






ra  c                 C  s2   zt | dd\}}||W S  ty   Y dS w r$  )ra  is_stride_orderedr  )r   r+  r(  r`  r   r   r   "is_stride_order_storage_and_layout
  s   r2  r   c                 C  sr   t | ttfrt| jS t | tr*| j}tjj	
|jt|j t }t| jp)|S t | tr7|  tjjv S dS r  )r   r~   r  is_unalignedr_  re  r`  rm   r  r  statically_known_multiple_ofrc  r_   r  ra   r  r  unaligned_buffers)r   r`  has_unaligned_layoutr   r   r   r3    s   


r3  c                   @  s   e Zd ZU ded< ed dEdFdd	ZdGddZdHddZdIddZe	dJddZ
dKddZdLddZdMddZdNd d!ZdOd#d$ZdPd(d)ZdQd*d+ZdRd-d.ZdSd/d0ZdTd2d3ZdQd4d5ZdQd6d7ZdUd9d:ZdVd<d=ZdWd>d?ZdXdBdCZdDS )Yr  r   r_  Fr{  r   r   r  c                 C     | j |S r   r_  r,  r+  r   r   r   r,       zBaseView.get_free_symbol_uses*Callable[[Sequence[Expr]], Sequence[Expr]]c                 C  s   t d|  )Nzmake_reindexer NYI on rc  r  r   r   r   make_reindexer  r   zBaseView.make_reindexerr	  c                   &   | j   |  d fdd}|S )Nr   r  r   r   c                   r   r   r   r  innerr   r   r   r  #  r   z&BaseView.make_indexer.<locals>.indexer)r   r  r   r   )r_  r
  r;  r  r  r   r=  r   r
       
zBaseView.make_indexerr  c                   r<  )Nr   r  r   rl   c                   r   r   r   r  r=  r   r   r  ,  r   z$BaseView.make_loader.<locals>.loaderr  )r_  r  r;  r  r  r   r=  r   r  (  r@  zBaseView.make_loaderr  c                 C  
   | j  S r   )r_  r   r  r   r   r   r  1     
zBaseView.dtyper  c                 C  rB  r   r_  r  r  r   r   r   r  5  r(  zBaseView.get_layoutr  c                 C  rB  r   r_  r!  r  r   r   r   r!  8  r(  zBaseView.get_devicer  c                 C  r
  r   r   r  r   r   r   r  ;  r  zBaseView.get_origin_noder   c                 C  rB  r   r_  r  r  r   r   r   r  >  r(  zBaseView.get_namer  c                 C  r  r   r  r  r   r   r   r  A  r  zBaseView.get_pointwise_sizer  r   r   c                 C  r7  r   r_  r  r  r   r   r   r  D  r   zBaseView.mark_reusec                 C  rB  r   r_  r  r  r   r   r   r  G  r(  zBaseView.has_exceeded_max_readsr-  c                 C  rB  r   r_  r  r  r   r   r   r  J  r(  zBaseView.realizec                 C  s   | j   d S r   r_  r  r  r   r   r   r  M  r   zBaseView.realize_hintry   c                 C  rB  r   r_  r*  r  r   r   r   r*  P  r(  zBaseView.get_storage_numelc                 C  rB  r   r_  r/  r  r   r   r   r/  S  r(  zBaseView.is_externc                 C  s$   t | jtsJ t| j| j S r   )r   r_  r  r   is_module_bufferr  r   r   r   rM  V  s   
zBaseView.is_module_bufferr  c                 C  rB  r   r_  r  r  r   r   r   r  Z  r(  zBaseView.get_read_namesr$  c                 C  sF   t tdd t|  |  jW  d    S 1 sw   Y  d S r  )r   r   r  rK   r  r  r'  r  r   r   r   r  ]  s   $zBaseView.get_readsc                 C  s"   | }t |tr|j}t |ts|S r   )r   r  r_  )r  r   r   r   r   r  d  s
   

zBaseView.unwrap_viewr  r  c                 C  s2   |   }ttd||}t||  ||  dS r  )r  r   r   r  r  r   r  r  r   r   r   r1  j  s   zBaseView.constant_to_deviceNrL  r  r   r:  rF  rE  r;  r<  rC  r8  rH  r?  rJ  r>  rA  r6  rT  r7  rR  rK  rV  )r   r   r   r   rX   r,  r;  r
  r  r^  r  r  r!  r  r  r  r  r  r  r  r*  r/  rM  r  r  r  r1  r   r   r   r   r    s2   
 


		














r  c                   @  sF   e Zd ZU ded< eddd	ZedddZdddZdddZ	dS )r   r  r  r   r   new_sizerM  r   c                 C  s  t jj}dd |D }|  }dgt|t|  t| }t|t|ks(J tt|D ]W}|| dkrE|| dus>J || ||< q.|| du sTt jj|| rUq.|| }|| }|duscJ |dusiJ || }|j|dddksJ d|   d| d	| q.|S )
zReplace `-1` with correct sizesc                 S  rZ  r   r[  r   r   r   r   r   ~  r   z.ExpandView._normalize_size.<locals>.<listcomp>NrA  r   fallbackzBroadcast failed in ExpandView(, z) on dimension )	rm   r  r  r  r   r   r   is_size_one_or_falser  )r   rP  r  old_sizer   v1v2diffr   r   r   _normalize_sizez  s6   zExpandView._normalize_sizer  c           
      C  s   |  ||}t|rWt|\}}t|t|j }|dksJ tjjg| }t|j	|jD ]\}}|
tjj|s<|ntjj q-t|j|jt|||j|j}	t||	dS t||dS )Nr   r^  )r_  r  )rY  r  ra  r   r  r   r  r  r   r  r  rm   r  r  rT  rb  r  r  r   rc  rd  re  r   )
r  r   rP  rf  rg  skiprh  r  r  ri  r   r   r   r    s,   zExpandView.createc                 C  r  r   r  r  r   r   r   r    r  zExpandView.get_sizer:  c                   s6   |   }| j   t|t  d fdd}|S )Nr   r  r   c                   sR   t | d  } t| t ksJ tt D ]} | dkr&tjj| |< q| S r  )r   r   r   r   r  r  )r   r   actualrZ  r   r   r     s   z*ExpandView.make_reindexer.<locals>.reindexr   r  r   r  )r  r_  r   )r  targetr   r   r[  r   r;    s
   
zExpandView.make_reindexerN)r   r   rP  rM  r   rM  )r   r   rP  rM  r   r  r?  rO  )
r   r   r   r   r[  rY  r  r  r  r;  r   r   r   r   r   v  s   
 %
r   c                   @  sF   e Zd ZU ded< eddd	ZedddZdddZdddZdS )PermuteViewry  dimsr   r   r   r   r  c                   s   |  |}t|ttt|ksJ t|r>t|\} t j j fdd|D  fdd|D  j	 j
}t||dS t||dS )Nc                      g | ]} j | qS r   r  r   rg  r   r   r     r   z&PermuteView.create.<locals>.<listcomp>c                   ra  r   r  r   rb  r   r   r     r   r^  )r_  r`  )_map_neg_dimsr9   r   r   r  ra  rb  r  r  rc  rd  re  r_  )r  r   r`  rf  ri  r   rb  r   r    s   
zPermuteView.create	list[int]c                   s    fdd D S )Nc                   s$   g | ]}|d kr
|nt  | qS r  r
  )r   rS  r`  r   r   r     s   $ z-PermuteView._map_neg_dims.<locals>.<listcomp>r   )r  r`  r   rf  r   rd       zPermuteView._map_neg_dimsr  c                   sD   t | | jt tt| jksJ | j   fdd| jD S )Nc                   r   r   r   r   r  r   r   r     r   z(PermuteView.get_size.<locals>.<listcomp>)r9   rd  r`  r   r   r_  r  r  r   r  r   r    s
   

zPermuteView.get_sizer:  c                   s`   dd t | jD   fddtt| jD  t ttt| jks'J d
 fdd	}|S )Nc                 S  r   r   r   )r   r   rN  r   r   r   r     r   z.PermuteView.make_reindexer.<locals>.<dictcomp>c                   r   r   r   r   invr   r   r     r   z.PermuteView.make_reindexer.<locals>.<listcomp>r   r  r   c                   s    fddD S )Nc                   r   r   r   r   r   r   r   r     r   z?PermuteView.make_reindexer.<locals>.reindex.<locals>.<listcomp>r   r   rh  r   r   r        z+PermuteView.make_reindexer.<locals>.reindexr]  )r   r`  r   r   r9   )r  r   r   rh  r   r;    s
   zPermuteView.make_reindexerN)r   r   r`  r   r   r  )r`  r   r   re  r?  rO  )	r   r   r   r   r  r  rd  r  r;  r   r   r   r   r_    s   
 
r_  c                   @  s8   e Zd Zeddddd	ZedddZdddZdS )SqueezeViewNrS  r   r   rS  r  r   c                  sL  t |rzt|\}}g }g } d ur*t tsJ t d kr( t|jk s*J tt|j|j	D ]3\}\}}	 d u rOt
jj|sN|| ||	 q3| kr^|| ||	 q3|dksfJ dq3t|j|j|||j|j}
t||
dS  d u rt|dd | D S |   dksJ t| fddt| D S )Nr   r@   zexpected squeezed size to be 1r^  c                 S  s   g | ]}t jj|s|qS r   )rm   r  r  rT  r   r   r   r   r   *  s    z&SqueezeView.create.<locals>.<listcomp>c                   s   g | ]
\}}| kr|qS r   r   r   r   r   rl  r   r   r   2      )r  ra  r   r   r   r   r  r   r   r  rm   r  r  rT  r  rb  r  r  rc  rd  re  r  r  r  )r  r   rS  rf  rg  rP  rh  r   r  r  ri  r   rl  r   r    sF   


	"zSqueezeView.creater  r  >tuple[list[int], Callable[[Sequence[Expr]], tuple[Expr, ...]]]c                   s@   dd | D }dd t | D t|  d
 fdd	}||fS )Nc                 S  s   g | ]}|d kr|qS r  r   r   r   r   r   r   8  r   z(SqueezeView.squeezer.<locals>.<listcomp>c                 S  s   g | ]
\}}|d kr|qS r  r   rm  r   r   r   r   9  rn  r   r  r   tuple[Expr, ...]c                   sT   t | t ksJ |  d tjjg  }t| D ]\}}|||< qt|S )N )r   r   r  r  r   r   )r   r  r   r   lengthnot_oner   r   r   <  s
   "
z%SqueezeView.squeezer.<locals>.reindex)r   r  r   rp  )r   r   )r  rP  r   r   rr  r   squeezer4  s
   zSqueezeView.squeezerr_  r   r   c                 C  s   t d)Nzuse SqueezeView.create())AssertionError)r  r_  r   r   r   r  E  r  zSqueezeView.__init__)r   r   rS  r  r   r   )r  r  r   ro  )r_  r   r   r   )r   r   r   r  r  r[  ru  r  r   r   r   r   rk    s    -rk  c                   @  sX   e Zd ZU ded< ded< dddZdd	d
ZdddZeZedddZ	dddZ
dS )GenericViewr  r  r:  r   r   c                 C  r  r   )r   r  r   r   r   r;  N  s   zGenericView.make_reindexerr   c                 C  sB   dd t t| jD }t| |}ddtt| d| S )Nc                 S     g | ]}t tj|qS r   )rg   r?   r  r   r  r   r   r   r   T      z+GenericView.reindex_str.<locals>.<listcomp>zlambda rS  r.  )r   r   r  r   r   r  r  r   )r  	index_old	index_newr   r   r   reindex_strS  s
   zGenericView.reindex_strc                 C  s$   |  | jd| j d|   gS )Nsize=zreindex=)r  r_  r  r}  r  r   r   r   r  Z  s   zGenericView.__str__r   r   rP  r  c                 C  s   | |t ||dS )Nr_  r  r   )r   )r  r   rP  r   r   r   r   r  a  s   zGenericView.createc                 C  r  r   r  r  r   r   r   r  j  r  zGenericView.get_sizeNrO  rH  )r   r   rP  r  r   r:  r   r  r?  )r   r   r   r   r;  r}  r  r  r  r  r  r   r   r   r   rw  I  s   
 


rw  c                   @  sb   e Zd ZdZedddZeedddZedddZ	e	dd ddZ
e	dd!ddZdS )"r  z
    This class handles tensor reshaping by computing appropriate index transformations
    to map the new shape back to the original storage layout.
    r   r   r  r   c                 C  s<   t | } t |}tjjjj}|t | dr| | } | S r  )r   r\  rm   r  r  r   evaluate_exprLt)r   r  r  r   r   r   handle_negative_indexu  s   

zView.handle_negative_indexr   r   rP  r  c                   st  t tsJ t | \tjjr|S t	t
dkp.t	t
dkt|}dd	d
d fdd}dv rWdfdd} |t|dS |rb|tS t|sj||S t|dd\}}|j}tjj}	tjj|}
tjj}ddlm} ||	|
|d}|d urdd |D }t|j|j||j|j}t||dS ||S )Nr   r}  r   rP  r  rh  r   re  c                 S  s6   t | dd\}}t|j|j|||j|j}t||dS )NT)r*  r^  )ra  rb  r  r  rc  rd  re  )r}  rP  rh  rf  rg  ri  r   r   r   create_reinterpret_view  s   z,View.create.<locals>.create_reinterpret_viewr   c                   s>   rt | } | tS  } | t|dS )z
            Handle the case where view is not possible with current strides.
            For unbacked symbols, make contiguous; otherwise use dynamic_reshape_indexer.
            r  )r  require_contiguousr  r  r  r   )r   r   r  r  rP  rU  unbacked_symbols_in_sizesr   r   "handle_unbacked_or_dynamic_reshape  s   
z7View.create.<locals>.handle_unbacked_or_dynamic_reshaper   r   tuple[int, ...]c                   s   t dgt  S r  )r   r   r   )rU  r   r   fake_reindex  r  z!View.create.<locals>.fake_reindexr  Fr"  )_compute_stridesize_obliviousc                 S  s(   g | ]}t |d r|jjnt|qS r  )r  r   exprr   r    r   r   r   r   r     s    zView.create.<locals>.<listcomp>r^  )r}  r   rP  r  rh  r  r   re  r   r   r   r   )r   r   r   r  )r   r   r   resolve_negative_sizer  rm   r  r  statically_known_list_equalsr   r1   r)  r   r  r  r  ra  r  to_symints_or_intstorch._subclasses.fake_implsr  rb  r  r  rc  rd  re  )r  r   rP  r'  r  r  rf  rg  
old_strideold_size_symintold_stride_symintnew_size_symintr  new_stride_symintrh  ri  r   r  r   r  ~  sZ   
zView.createrU  tuple[list[Expr], list[Expr]]c                 C  s   dd |D }dd | D } t |}tt|D ]}|| dkr3tjj||< tt| t|||<  nqtj	j
t| t| | |fS )Nc                 S     g | ]	}t jj|qS r   rm   r  r  r|  rT  r   r   r   r         z.View.resolve_negative_size.<locals>.<listcomp>c                 S  r  r   r  rT  r   r   r   r     r  rA  )r   r   r   r   r  Oner;   rh   rm   r  r  check_equals)rU  rP  r   r   r   r   r    s   zView.resolve_negative_sizeNrM  	dense_dimr  r   c              	   C  sZ   z
|  |||}W |S  ttfy,   t|g}|  ||}|  ||}t||}Y |S w r   )_dynamic_reshape_indexerrv  
IndexErrorrh   r   )r  rU  rP  r  r   flatr   r   r   r   r   r    s   
zView.dynamic_reshape_indexerr:  c                   s  t jjj}dd tt|D  tt |}t| }|duo,|t|d ko,t|dk}|r?|dus5J ||}|	| g |r|r| }| \}	}
|dkrd	t
jj |	|	|
f n|
dkrn|	| n||
||kr	|	 t jj|
| n||
||k r||
||k r| \}}||
 |	 }	|
| }
||
||k s	|	 t jj|
| nL||
||krt
jj}|}	t|	|| || }||
||kr| }	t|	|| || }|| }||
||kst jj|
| nt|r|sG|r$| }t jj|d 	t
jj |s|r8| \}	}
t jj|
d |s'|durSt|dkrS   }|| n  tt| ksbJ d
 fdd	}|S )zG
        Perform a reshape entirely by modifying indexing math
        c                 S  rx  r   )rg   r?   VIEWr   r   r   r   r     rz  z1View._dynamic_reshape_indexer.<locals>.<listcomp>Nr@   r   r  r   c                   sH   t | t ksJ t | t ftt|  t fddD S )Nc                 3  ru  r   )ri   rT  replacementsr   r   r   d  rx  zAView._dynamic_reshape_indexer.<locals>.reindex.<locals>.<genexpr>)r   r   r   r   r   r  	view_exprr  r   r   _  s   $z.View._dynamic_reshape_indexer.<locals>.reindexr]  )rm   r  r  r  r   r   r   r   r  r  r   r  r  r  r  r>   rv  reverseinsert)rU  rP  r  r  	stack_new	stack_oldreordering_dense_dimold_dimsize_oldvarsize_newvar2	size_new2divisormodulus
dense_exprr   r   r  r   r    s   
	






 zView._dynamic_reshape_indexer)r   r   r  r   r   r   )r   r   rP  r  r   r   )rU  r  rP  r  r   r  r   )rU  rM  rP  rM  r  r  r   r   )rU  r  rP  r  r  r  r   r:  )r   r   r   rX  r[  r  r  r   r  r  r  r  r   r   r   r   r  n  s    kr  c                      s   e Zd ZU dZded< d3 fddZd4d	d
ZeZd4ddZd5ddZ	d6ddZ
ed7ddZd8ddZd8ddZd9ddZd:dd Zd;d!d"Zd3d#d$Zed 	%d<d=d)d*Zd>d?d.d/Zd@d1d2Z  ZS )Are  z*Pretend our storage has a different layoutr  r`  r   r   c                   s2   t    t| jtrt| d| j  d S d S )Nr_  )r  r  r   r_  r  r   r  r  r  r  r   r   r  o  s   
zReinterpretView.__post_init__r   c                 C     |  | j| jgS r   )r  r_  r`  r  r   r   r   r  t  s
   zReinterpretView.__str__c                 C  rB  r   rF  r  r   r   r   r  ~  r(  zReinterpretView.get_namer  c                 C     | j jS r   )r`  r  r  r   r   r   r!    r  zReinterpretView.get_devicer  c                 C  r
  r   r   r  r   r   r   r    r  zReinterpretView.get_origin_noder  c                 C  r  r   )r`  r  r  r   r   r   r    r  zReinterpretView.dtyper  c                 C     t | jjS r   )r   r`  r  r  r   r   r   r    r   zReinterpretView.get_sizec                 C  r  r   )r   r`  r  r  r   r   r   rC    r   zReinterpretView.get_strider  c                      d fdd}|S )Nr   r  r   rl   c                   sF    j  }t  || } j j jjkr!t| j jjS |S r   )r`  r
  rk   loadr  r  r_  to_dtype_bitcast)r   r  
tmp_loaderr  r   r   r    s
   
z+ReinterpretView.make_loader.<locals>.loaderr   r  r   rl   r   rA  r   r  r   r    s   zReinterpretView.make_loaderr	  c                 C  rB  r   )r`  r
  r  r   r   r   r
    r(  zReinterpretView.make_indexerc                 C  r  r   r`  r  r   r   r   r    r  zReinterpretView.get_layoutc                 C  r
  r   r   r  r   r   r   r    r  zReinterpretView.freeze_layoutFr{  r   r   c                 C  s*   t | jj|t | jj|B t | jj|B S r   )r'   r`  r  r  rc  r+  r   r   r   r,    s   z$ReinterpretView.get_free_symbol_usesNr  r  c                 C  s@   t jjj| j| jj| jj| jj|d ur|j	nt jjj	| jj
dS r  )rm   r  wrapper_codecodegen_reinterpret_viewr_  r`  r  r  rc  	writeliner  r  r   r   r   r    s   z!ReinterpretView.codegen_referencer   c                 C  r  r  r   r  r   r   r   r)    r  zReinterpretView.num_readsr6  rH  rC  r8  r;  r?  rE  rF  r<  rL  rU  r   rB  rS  )r   r   r   rX  r   r  r  r  r  r!  r  r^  r  r  rC  r  r
  r  r  rX   r,  r  r)  r  r   r   r  r   re  i  s,   
 









	re  c                   @  sX   e Zd ZU dZded< edd	d
ZdddZeZe	dddZ
dddZdddZdS )	DtypeViewz(Pretend our storage has a different typer  target_dtyper   r   	new_dtyper   r  c                 C  sH   t |rt|\}}t|j||j|j|j|j}t||dS t	||dS )Nr^  )r_  r  )
r  ra  rb  r  r  r  rc  rd  re  r  )r  r   r  rf  rg  ri  r   r   r   r    s   zDtypeView.creater   c                 C  r  r   )r  r_  r  r  r   r   r   r    r  zDtypeView.__str__c                 C  r  r   )r  r  r   r   r   r       zDtypeView.dtyper  c                 C  rB  r   r_  r  r  r   r   r   r    r(  zDtypeView.get_sizer  c                   s   j   d fdd}|S )Nr   r  r   rl   c                   s   t  | jjjS r   )rk   r  r  r_  r  r  r>  r  r   r   r    s   z%DtypeView.make_loader.<locals>.loaderr  r_  r  rA  r   r  r   r    s   
zDtypeView.make_loaderN)r   r   r  r  r   r  rH  r;  r?  rE  )r   r   r   rX  r   r  r  r  r  r^  r  r  r  r   r   r   r   r    s   
 

r  c                   @  s.   e Zd Zedd	d
Ze		ddddZdS )	SliceViewr   r   rS  r   startendr   tuple[int, int]c                   s   t jj| | tdd ||fD rtjtjnjj	dfd	d
 d fdd}||dd}|||}||fS )zz
        Normalize start and end such that both are in the range
        [0, x.get_size()[dim]] and start <= end.
        c                 s      | ]}t |V  qd S r   )r1   rT  r   r   r   r     r  z0SliceView.normalize_start_end.<locals>.<genexpr>r   r   lowerr   upperr   c                   s<    | |r| n | |}||r|}|S ||}|S r   )statically_known_geqrP  )r   r  r  clamped_lowerclamped_full)max_funcmin_funcr  r   r   clamp  s   
z,SliceView.normalize_start_end.<locals>.clamprd  Union[int, None]r  Union[Expr, int]c                   s$   | d u r|S  | }  | ||S r   )r  )rd  r  r  r  )r  r  dim_sizer   r   
clamp_wrap  s   z1SliceView.normalize_start_end.<locals>.clamp_wrapr   N)r   r   r  r   r  r   r   r   )
rd  r  r  r   r  r   r  r  r   r  )
rm   r  r  r  r  r   MinMaxevaluate_minevaluate_max)r  r   rS  r  r  r  r   )r  r  r  r  r  r  r   normalize_start_end  s   	zSliceView.normalize_start_endr@   Tstepr  r   c                   s  t ttsdksJ zdkr"|dkr"dkr"|W S W n	 ty,   Y nw t| |r?| | |\}t| d   < t	|r}t
|\}}t|j}	|	   |	 < t|j|j|	|j|j    |j}
t||
dS d fdd	}t||d
S )Nr   l    r@   r^  r   r  r   c                   sD   t | t ksJ d|  d t| } |     |  < | S )Nzwrong ndim rq  )r   r   r   rS  rP  r  r  r   r   r   @  s   $z!SliceView.create.<locals>.reindexr  r]  )r   r\  r   r   	TypeErrorr   r  r  r<   r  ra  r  rb  r  r  rc  rd  re  r  )r  r   rS  r  r  r  r  rf  rg  rh  ri  r   r   r  r   r    s8   


	zSliceView.createN)
r   r   rS  r   r  r   r  r   r   r  )r@   T)r   r   rS  r   r  r   r  r   r  r   r  r   r   r   )r   r   r   r  r  r  r   r   r   r   r    s    )r  c                   @  sF   e Zd ZU ded< ded< dddZdd
dZdddZdddZdS )BaseConstantr  r  r  r  r   r  c                 C  r  Nr   r   r  r   r   r   r  Q  r  zBaseConstant.get_sizer  c                 C  r  r   r  r  r   r   r   r!  T  r  zBaseConstant.get_devicer  c                 C  r
  r   r   r  r   r   r   r  W  r  zBaseConstant.get_origin_noder$  c                 C  rl  r   r8   r  r   r   r   r  Z  r  zBaseConstant.get_readsNr?  rC  r8  rR  )r   r   r   r   r  r!  r  r  r   r   r   r   r  L  s   
 


r  c                   @  sD   e Zd ZU ded< ded< ded< dd	d
ZdddZdddZdS )Constantr   r'  r  r  r  r  r   r  c                   r  )Nr   r  r   rl   c                      t  j jS r   )rk   r  r'  r  r   r  r   r   r  e  rl  z$Constant.make_loader.<locals>.loaderr  r   rA  r   r  r   r  d     zConstant.make_loaderr-  c                 C  r
  r   r   r  r   r   r   r  j  r  zConstant.realizer   c                 C     t | j| j|dS )N)r'  r  r  )r  r'  r  r  r   r   r   r1  m  r  zConstant.constant_to_deviceNrE  rA  rV  )r   r   r   r   r  r  r1  r   r   r   r   r  ^  s   
 

r  c                   @  s:   e Zd ZU ded< ded< ded< dd	d
ZdddZdS )IndexingConstantr   r   r  r  r  r  r   r  c                   r  )Nr   r  r   rl   c                   r  r   )rk   r]  r   r  r   r  r   r   r  x  rl  z,IndexingConstant.make_loader.<locals>.loaderr  r   rA  r   r  r   r  w  r  zIndexingConstant.make_loaderr   c                 C  r  )N)r   r  r  )r  r   r  r  r   r   r   r1  }  r  z#IndexingConstant.constant_to_deviceNrE  rV  )r   r   r   r   r  r1  r   r   r   r   r  q  s   
 
r  c                 C  sp   d}d}t tt|| D ](\}}|dkrqtjj||s)tjj||s) dS |td|9 }||9 }qdS Nr@   FT)	reversedr   r   rm   r  r  rQ  r   r  )r  rO  expected_strideexpected_stride_maxr   yr   r   r   is_contiguous_strides_for_shape  s   
r  c                 C  s   t j| j S r   )rA   padding_alignment_bytesitemsizer  r   r   r   get_align_for_dtype  r   r  c                   @  s2   e Zd ZdZdddZdddZ		ddddZdS )r0  zxAbstract base for Layout, MultiOutputLayout, NoneLayout.
    Represents the memory layout of the output of an Operation.r   r  c                 C  r  r   r  r  r   r   r   r!    r   zOutputSpec.get_devicer   c                 C  r  r   r  r  r   r   r   storage_size  r   zOutputSpec.storage_sizeFr{  r   r   c                 C  r  r   r  r+  r   r   r   r,    r  zOutputSpec.get_free_symbol_usesNrC  rS  rL  rU  )r   r   r   rX  r!  r  r,  r   r   r   r   r0    s    

r0  c                   @  s8  e Zd ZdZdeddfdMddZedNddZejdOddZedNddZ	e	jdOddZ	edPddZ
e
jdQddZ
dRd d!ZeZdSd"d#ZdTd%d&ZdUd'd(ZedVd,d-ZdUd.d/ZdWd2d3ZdUd4d5ZedXd7d8ZdYd9d:ZdUd;d<ZdZd>d?Zd[dAdBZd\dEdFZdPdGdHZed 	d]d^dKdLZdS )_r  zo
    Layout base class

    Carries tensor meta-information including offset and
    whether it is pinned.
    Nr   Fr  r  r  r  r  r  r  Optional[Sequence[Expr]]rc  r   rd  r   r   r   c                 C  s   |d u r	t |}|| _|| _t|t|ks!J d| d| tdd |D s,J || _|| _|| _|| _	| j	rE| jj
dksGJ dd S d S )Nr~  	, stride=c                 s  s    | ]
}t |ttfV  qd S r   )r   r   r   r   r   r   r   r         z"Layout.__init__.<locals>.<genexpr>r3  zOnly CPU tensors can be pinned)r  r  r  r  r   r   _size_stride_offsetrd  r   )r  r  r  r  r  rc  rd  r   r   r   r    s   	
$zLayout.__init__c                 C  r  r   r  r  r   r   r   r    r  zLayout.sizer'  c                 C  
   || _ d S r   r  r  r'  r   r   r   r    rC  c                 C  r  r   r  r  r   r   r   r    r  zLayout.stridec                 C  r  r   r  r  r   r   r   r    rC  c                 C  r  r   r  r  r   r   r   rc    r  zLayout.offsetc                 C  r  r   r  r  r   r   r   rc    rC  r   c                 C  s   d}| j dkrd| j  }| jjd u rdnd| jj }d}| jr'd| j }t| j d| jj | d| j d| j d	| j | | d
S )Nr  r   z	, offset=:z, is_pinned=z('z', z, size=r  r/  )	rc  r  r   rd  r   r   r  r  r  )r  rc  device_index_stris_pinned_strr   r   r   r    s"   
"zLayout.__str__c                 C  r  r   r  r  r   r   r   r!    r  zLayout.get_devicer  c                 C  sP   t j tjt| jt| j| j| j| j	dW  d    S 1 s!w   Y  d S )N)r  r  
pin_memory)
rm   	fake_moder#  r$  r[   r  r  r  r  rd  r  r   r   r   get_example  s   $zLayout.get_examplec                 C  s   t | j| jS r   )r  r  r  r  r   r   r   r'     r   zLayout.is_contiguousrO  rM  rX  c                 C  sV   t | }|dvs| d dkrdS t|t| | D ]\}}}|dkr(||kr( dS qdS )N)r      r@   FT)r   r   r,   )rO  rX  ndimleftrightr  r   r   r   is_channels_last_contiguous  s   z"Layout.is_channels_last_contiguousc                 C  sJ   t | jtttt| j| jD ]\}}}|dkr"||kr" dS qdS r  )r   r  r  r  r  r   r  )r  r  r  r  r   r   r   is_transposed  s   zLayout.is_transposedr   r   c                   s   t jt  ksJ dd tjD }fdd|D } fdd|D  ddd	}|  d
gt   }tt  D ]
}|| | | < q=tt  d D ]'}|| ||d  k}t|tsrtjj	j
|| ||d  kdd}|rw dS qPdS )Nc                 S  s*   g | ]\}}t jjj|d ddkr|qS )r   rQ  r@   )rm   r  r  r  )r   r   rS  r   r   r   r   #  s
    z,Layout.is_stride_ordered.<locals>.<listcomp>c                   ra  r   rc  r   r  r   r   r   )  r   c                   r   r   r   r   r   r   r   r   *  r   arrr   r   c                   s   t |   fdd| D S )Nc                      g | ]}  |qS r   r   )r   element
sorted_arrr   r   r   .  r   zDLayout.is_stride_ordered.<locals>.sorted_indices.<locals>.<listcomp>)r+  )r	  r   r  r   sorted_indices,  s   z0Layout.is_stride_ordered.<locals>.sorted_indicesrA  r@   Tr  F)r	  r   r   r   )r   r  r   r  r   r   r   rm   r  
_shape_envr  )r  r   non_1_indicesr  r  stride_orderedr   r  r   )r   r  r   r1    s*   

zLayout.is_stride_orderedc                 C  s:   dgt ttdt| jd  }t|g| }| |S Nr   r@   )r   r  r   r   r  r1  r  r   r   r   is_channels_last_stride_orderedB  s   "
z&Layout.is_channels_last_stride_ordered
in_stridesc                   s  t |}t| dkr| S tjst|| r| S t }t|dr)|j	
ddr)| S tdd t| |D  }tjs>|r>| S ttjdrHtjjnddfdd r`t fdd| D r`| S t| }t|}dd tt| D }d||d < d}	t|dd ddD ]?\}
}||
d  }|| ||  }t|ttjfo|tjko|| dkpt|tjotj}|||< |rt||| ||< d}	q|	s| S t jd7  _|S )z
        The padding does not change stride order but makes sure all strides larger
        than the threshold are multiple of align.
        r   rs  dislike_paddingFc                 s  r   r   r   r   r   r   r   r   a  r  z&Layout._pad_strides.<locals>.<genexpr>r  Nr  sympy.Expr | intr   r   c                   s4    d u rdS t | tjsdS t fdd| jD S )NFc                 3  s    | ]}  |V  qd S r   )is_unbacked_symintr   r   r   r   r   o  rx  zILayout._pad_strides.<locals>.contains_unbacked_symints.<locals>.<genexpr>)r   r   r   r  r0   r  r  r   r   contains_unbacked_symintsj  s
   z6Layout._pad_strides.<locals>.contains_unbacked_symintsc                 3  r  r   r   r   )r  r   r   r   r  r  c                 S  r  r  r   r  r   r   r   r   x  r  z'Layout._pad_strides.<locals>.<listcomp>r@   )r  T)r  r  r   r   )r  r   rA   pad_channels_lastr  r  rm   get_current_noder  rs  r  r   rV  chainpad_dynamic_shapesr  r  r  r  r   r   r   r   r   r   r    padding_stride_thresholdr   rY   r%   num_comprehensive_padding)r  r  r  aligncurrent_fx_noderc   r+  r   new_stridespaddedrankr   prev_idxr  require_paddingr   )r  r   r   _pad_stridesH  sZ   





zLayout._pad_stridesc                 C  s>   t | tsJ t| | jd usJ | | j| j| j| _d S r   )r   r  r   r  r(  r  r  r  r   r   r   r&    s   zLayout.pad_stridesc                 C  s   t jot| tS r   )rA   comprehensive_paddingr   r  r  r   r   r   r%    rl  zLayout.should_pad_stridesrb  c                 C  s<   t | tr| S |  r|   t| j| j| j| j| j| j	S r   )
r   rb  r%  r&  r  r  r  r  rc  rd  r  r   r   r   as_fixed  s   
zLayout.as_fixedr	  c                 C  s(   t jsJ dt| j d|   S )Nzconvert z to FixedLayout first)r  r  r   r   r*  r
  r  r   r   r   r
    s   zLayout.make_indexerotherr   c                 C  sR   t |to(| j|jko(| j|jko(| j|jko(| j|jko(| j|jko(| j|jkS r   )r   r  r  r  r  r  rc  rd  )r  r+  r   r   r   __eq__  s   






zLayout.__eq__c                 C     t | j| j| jS r   )r)   r  r  rc  r  r   r   r   r    r  zLayout.storage_sizer{  r   c                 C  s$   t | j|t | j|B t | j|B S r   )r'   r  r  rc  r+  r   r   r   r,    s   


zLayout.get_free_symbol_uses)r  r  r  r  r  r  r  r  rc  r   rd  r   r   r   r?  r'  r  r   r   r@  r'  r   r   r   rH  rD  )r   r  r>  )rO  rM  rX  rM  r   r   )r   r   r   r   )r  r   r  r  r  r  r   r   r6  r   rb  rF  )r+  r   r   r   rL  rU  )r   r   r   rX  r    r  r^  r  setterr  rc  r  r  r!  r  r'  r[  r  r  r1  r  r(  r&  r%  r*  r
  r,  r  rX   r,  r   r   r   r   r    sN    








#
N




r  c                   @  s   e Zd ZdZdddZdS )rb  z A Tensor layout we cannot changer   r	  c                 C  r-  )r  )rb  r  r  rc  r  r   r   r   r
    rg  zFixedLayout.make_indexerNrF  )r   r   r   rX  r
  r   r   r   r   rb    s    rb  c                      s  e Zd ZdZdZdDddZedEd
dZedFddZedGddZ	edHddZ
edIddZedJddZejdKddZedJdd ZejdKd!d ZedLd#d$ZejdMd%d$Z	dNdOd(d)Z	dNdPd+d,ZdQd-d.ZdRd/d0ZdSd2d3ZdTd7d8Z	9	dUdV fdBdCZ  ZS )Wr  z|
    A Tensor layout that we are allowed to change

    Assumption: layout change should NOT add or remove free symbols
    Fr   rb  c                 C  s   t |  S )z
        Compute what the strides would be if this layout were frozen,
        without actually modifying the layout. This is used for speculative
        stride computation during Triton template code generation.
        )r  deepcopyr*  r  r   r   r   !get_fixed_layout_without_freezing  s   z0FlexibleLayout.get_fixed_layout_without_freezingsizesr   ry  c                 C  sN   t | dkrg S tjjg}t| dd  D ]}|||d   qtt|S )Nr   r@   rA  )r   r   r  r  r  r  r   )r4  reversed_stridesr  r   r   r   r    s   
z!FlexibleLayout.contiguous_stridesr   c                 C  s\   t tt| t |ksJ | |ftjj}dgt| }|D ]}|||< || |  }q|S )z
        Create a stride based on the order the dimensions should be filled in.

        In this format, channels last would be:
            [1, 3, 2, 0]
        N)r9   r   r   r   r  r  )r4  r   next_striderX  r   r   r   r   fill_ordered  s   $zFlexibleLayout.fill_orderedr  c                 C  s0   t tt| t |ksJ t|}t| |S )z
        Create a stride based on the sorted order of a permuted range.

        In this format, channels last would be:
            [3, 0, 2, 1]
        )r9   r   r   r   r  r7  )r4  r   r   r   r   r   r    s   zFlexibleLayout.stride_orderedmemory_formattorch.memory_formatc                 C  sP   |t jkrt| tS |t jkrt| tS |t jkr t| S t	
d| t)aq  
        Create a stride based on a memory format.

        Memory format is translasted into a stride order,
        so channels_last is the same as:
            FlexibleLayout.stride_ordered(sizes, [3, 0, 2, 1])

        This interface does not support memory_format `torch.preserve_format`
        which should be used to deduce a format from another source
        z>stride_ordered_for_memory_format, unsuppored memory_format: %s)r#  channels_lastr  r  NHWC_STRIDE_ORDERchannels_last_3dNHWDC_STRIDE_ORDERcontiguous_formatr  r=  r  r  )r4  r8  r   r   r    stride_ordered_for_memory_format  s   



z/FlexibleLayout.stride_ordered_for_memory_formatr  rM  c                 C  sD   t | t |ks
J dd |D }ttt ||jd}t| |S )z
        Create a stride that has the same stride order as given stride

        For example, if given stride is [1000, 1, 100, 10],
        the fill order should be [1, 3, 2, 0]
        c                 S  r  r   )rm   r  r  r}  rT  r   r   r   r   4  r  z/FlexibleLayout.same_ordered.<locals>.<listcomp>r%  )r   r+  r   __getitem__r  r7  )r4  r  r   r   r   r   same_ordered)  s   
zFlexibleLayout.same_orderedc                 C  r  r   r  r  r   r   r   r  8  r  zFlexibleLayout.sizer'  r   c                 C     |  d| || _d S )Nr  )!assert_free_symbol_uses_unchangedr  r  r   r   r   r  <     
c                 C  r  r   r  r  r   r   r   r  A  r  zFlexibleLayout.stridec                 C  rB  )Nr  )rC  r  r  r   r   r   r  E  rD  r   c                 C  r  r   r  r  r   r   r   rc  J  r  zFlexibleLayout.offsetc                 C  rB  )Nrc  )rC  r  r  r   r   r   rc  N  rD  r  r   c                 C  sH   |  | j|}|  r|r| || j| j}t| j| j| j|| j| jS r   )	r  r  r%  r(  r  rb  r  rc  rd  )r  r   r  rh  r   r   r   as_stride_orderS  s   zFlexibleLayout.as_stride_orderr  c                 C  s>   |}|   r|r| || j| j}t| j| j| j|| j| jS r   )r%  r(  r  r  rb  r  rc  rd  )r  r  r  rh  r   r   r   as_exact_stridesc  s   zFlexibleLayout.as_exact_stridesc                 C  D   |  | j|}|  r| || j| j}t| j| j| j|| j| jS r   )	r7  r  r%  r(  r  rb  r  rc  rd  )r  r   rh  r   r   r   as_fill_orders     zFlexibleLayout.as_fill_orderc                 C  rG  r   )	rA  r  r%  r(  r  rb  r  rc  rd  )r  r  rh  r   r   r   as_same_order  rI  zFlexibleLayout.as_same_order$dict[tuple[str, bool], sympy.Symbol]c                 C  s<   i }dD ]}dD ]}||f}t tt| ||||< qq|S )N)r  r  rc  TF)r9   r'   r   )r  initial_free_symbolsr   r{  r&  r   r   r   get_initial_free_symbol_uses  s   
z+FlexibleLayout.get_initial_free_symbol_usesr   r   r2   c                 C  sF   dD ]}| j ||f }tt||}||ks J d| d| qd S )NrL  z)Expected free symbols unchanged, but got z vs )rM  r9   r'   )r  r   r'  r{  old_free_symbolsnew_free_symbolsr   r   r   rC    s   
z0FlexibleLayout.assert_free_symbol_uses_unchangedNr  r  r  r  r  r+  r,  rd  c                   s@   |r	t ||}nt |}t j|||||d |  | _d S )Nrd  )r  r7  r  r  r  rN  rM  )r  r  r  r  r+  rd  rX  r  r   r   r    s
   
zFlexibleLayout.__init__r0  )r4  r   r   ry  )r4  r   r   r   r   ry  )r4  r   r   r   r   r  )r4  r   r8  r9  r   r  )r4  r   r  rM  r   r  r?  r.  r@  r/  rL  )r   r   r  r   r   rb  )r  rM  r  r   r   rb  )r   r   r   rb  )r  rM  r   rb  )r   rK  )r   r   r'  r2   r   r   r  )r  r  r  r  r  r  r+  r,  rd  r   r   r   )r   r   r   rX  r  r3  r[  r  r7  r  r?  rA  r^  r  r1  r  rc  rE  rF  rH  rJ  rN  rC  r  r  r   r   r  r   r    sJ    





r  c                      sL   e Zd ZdZd fddZdd	d
ZdddZed 	ddddZ  Z	S )NonOwningLayoutz,Is a view into the storage of another tensorviewUnion[BaseView, TensorBox]r   r   c                   s,   |  }t |j|j|j|j || _d S r   )r  r  r  r  r  r  r  rS  )r  rS  r`  r  r   r   r    s   
zNonOwningLayout.__init__r	  c                 C     |    S r   )r*  r
  r  r   r   r   r
    r   zNonOwningLayout.make_indexerr   c                 C  s4   | j  j}|dkrdS ddlm} tjj||S )Nr   Tr@   )	ALIGNMENT)	rS  r  rc  utilsrV  rm   r  r  r4  )r  rc  rV  r   r   r   maybe_guard_aligned  s
   z#NonOwningLayout.maybe_guard_alignedFr{  r   c                 C  sV   t | jtsJ | jj}t |tsJ t||j}t |ts%J t||j|S r   )	r   rS  re  r_  r  r   r  r`  r,  )r  r{  boxinput_bufferr   r   r   r,    s   z$NonOwningLayout.get_free_symbol_uses)rS  rT  r   r   rF  r>  rL  rU  )
r   r   r   rX  r  r
  rX  rX   r,  r  r   r   r  r   rR    s    


rR  c                   @     e Zd ZdZdS )CommBufferTypesymm_memN)r   r   r   SYMM_MEMr   r   r   r   r\        r\  c                      s4   e Zd ZU dZded< ded< d
 fdd	Z  ZS )CommBufferLayoutax  
    A layout that signifies the buffer is a comm buffer.
    In terms of striding, the layout is identical to `FixedLayout`.

    Buffers with this layout do not participate in in-place reuse - it can be
    neither the source nor the target for in-place reuse.

    For detailed motivation and usage of this layout, see
    NOTE [lowering-time collective optimization].
    r\  comm_buffer_typer   
group_namer`  "Union[FlexibleLayout, FixedLayout]c                   sJ   t |tr	| n|}t j|j|j|j|j|j	|j
d || _|| _d S )Nr  r  r  r  rc  rd  )r   r  r*  r  r  r  r  r  r  rc  rd  ra  rb  )r  r`  ra  rb  fixedr  r   r   r    s   
zCommBufferLayout.__init__)r`  rc  ra  r\  rb  r   )r   r   r   rX  r   r  r  r   r   r  r   r`    s
   
 r`  c                   @  sd   e Zd ZU ded< ejdd dZded< ejdd dZded	< dddZdddZ	dddZ
dS )
NoneLayoutr  r  c                   C     dgS r  r   r   r   r   r   r#    r$  zNoneLayout.<lambda>default_factoryre  r  c                   C  rg  r  r   r   r   r   r   r#  	  r$  r  r   r   c                 C  r  r  r   r  r   r   r   r    r  zNoneLayout.storage_sizer0  c                 C     | S r   r   r  r   r   r   r*    r  zNoneLayout.as_fixedc                 C  r  r   r  r  r   r   r   r!    r  zNoneLayout.get_deviceNrS  r=  rC  )r   r   r   r   rY  rZ  r  r  r  r*  r!  r   r   r   r   rf    s   
 


rf  c                      s   e Zd Zd# fddZed$dd	Zejd%dd	Zd&ddZd'ddZd(ddZ	e
	d)d*ddZd+ddZd,d!d"Z  ZS )-MutationLayoutSHOULDREMOVEr^  r   r   r   c                   s@   t  | | | d  || _|   }tj	
| d S r   )r  r  r   r   r  r^  
get_bufferr  rm   r  mark_buffer_mutated)r  r^  r   r  r   r   r    s   z#MutationLayoutSHOULDREMOVE.__init__r  c                 C  r%  r   )real_layoutr  r  r   r   r   r  !  rC  z!MutationLayoutSHOULDREMOVE.strider'  r   c                 C  r
  r   r   r  r   r   r   r  %  r  r   c                 C  rU  r   )rn  r  r  r   r   r   r  )  r   z'MutationLayoutSHOULDREMOVE.storage_sizer  c                   s2   d fdd  | j }t|tsJ t||S )Nr^  r   r   c                   sB   t | tr
 | jS t | tr |  S t | tr | jS | S r   )r   rk  r^  r  r  
MutableBoxr_  )r^  unwrap_viewsr   r   rq  -  s   




z;MutationLayoutSHOULDREMOVE.get_buffer.<locals>.unwrap_views)r^  r   r   r   )r^  r   r  r   )r  r  r   rp  r   rl  ,  s   
	z%MutationLayoutSHOULDREMOVE.get_bufferr  c                 C  s   |   j}t|tsJ |S r   )rl  r`  r   r  )r  r`  r   r   r   rn  :  s   
z&MutationLayoutSHOULDREMOVE.real_layoutFsrcdstunsafe_aliasr   c              	   C  s   |   tj|  t|tr|j}|  |sAt	j
| | | dd t| | D d}t|ttfs>J |j}|   t|dsNJ |t|jjts]J t|jjt||j_|jS )Nc                 S      g | ]\}}t jj||qS r   rm   r  r  check_equals_and_simplifyr   r  r  r   r   r   r   Y      z;MutationLayoutSHOULDREMOVE.realize_into.<locals>.<listcomp>r  r_  )r  rm   r  rm  r  r   r~   r_  r  r  r  r!  r   r  r   r  r  ro  r  r`  r  r   rk  )r  rr  rs  rt  r   r   r   r   realize_into?  s*   
	z'MutationLayoutSHOULDREMOVE.realize_intor   c                 C  rj  r   r   r  r   r   r   r*  g  r  z#MutationLayoutSHOULDREMOVE.as_fixedr	  c                 C  rB  r   )r^  r
  r  r   r   r   r
  j  r(  z'MutationLayoutSHOULDREMOVE.make_indexer)r^  r   r   r   r?  )r'  r   r   r   r@  )r   r  r<  rL  )rr  r   rs  r   rt  r   r   r   )r   r   rF  )r   r   r   r  r^  r  r1  r  rl  rn  r  rz  r*  r
  r  r   r   r  r   rk    s    



'rk  c                      sl  e Zd ZU ded< ded< d] fddZd^d
dZd_ddZd`ddZdaddZdbddZ	e
dcddZddddZdedd Zdfd"d#Zdgd%d&Zdhd'd(Zdid*d+Zdjd-d.Zd]d/d0Z	1dkdld5d6Zdmd7d8Zdnd:d;Z	1dkdod=d>Zdjd?d@ZdpdBdCZdqdrdGdHZd]dIdJZdsdLdMZdsdNdOZdtdQdRZed 	1dkdudUdVZ dvdWdXZ!dwdYdZZ"djd[d\Z#  Z$S )xr  r-  r   r0  r`  r   r   c                   s   t    | dd  d S re  )r  r  r  r  r  r   r   r  x  s   
zBuffer.__post_init__r	  c                 C  rU  r   )r  r
  r  r   r   r   r
  |  r   zBuffer.make_indexerr   c                 C  s   | j sJ | | j S r   r   r  r   r   r   r    rf  zBuffer.get_name!Union[torch.Tensor, torch.SymInt]c                 C  s&   t | jtr| j S tt| jjr   )r   r`  r  r  r  r   r   r  r   r   r   r    s   
zBuffer.get_exampler  c                 C  rU  r   )r  r!  r  r   r   r   r!    r   zBuffer.get_devicer  c                 C  r
  r   r   r  r   r   r   r    r  zBuffer.get_defining_opr  c                 C  r%  r   )r  r  r  r   r   r   r    rC  zBuffer.dtyper  c                 C     g |   jS r   )r  r  r  r   r   r   r    r   zBuffer.get_sizery  c                 C  r|  r   )r  r  r  r   r   r   rC    r   zBuffer.get_strider   c                 C  r%  r   )r  rc  r  r   r   r   
get_offset  r(  zBuffer.get_offsetr  c                 C  s"   t | jtr	| jS tt| jjr   )r   r`  r  r  r   r   r  r   r   r   r    s   zBuffer.get_layoutc                 C  r  r   r  r  r   r   r   r    r  zBuffer.get_output_specr   c                 C  r  r   )r  r  r   r   r   r*    r  zBuffer.get_storage_numelr   c                 C  r%  r   )r  rd  r  r   r   r   get_is_pinned  r(  zBuffer.get_is_pinnedc                 C  s0   t | jtrt | jts| j | _d S d S d S r   )r   r`  r  rR  r*  r  r   r   r   r    s
   zBuffer.freeze_layoutFr   r   r  c                 C  0   t | jtsJ t| j| jj||d| _d S Nr/  )r   r`  r  r   rE  r  r   r   r   r    s   z&Buffer.freeze_layout_with_stride_orderc                 C  ,   t | jtsJ t| j| j|| _d S r   )r   r`  r  r   rH  r  r   r   r   r       z$Buffer.freeze_layout_with_fill_orderr  c                 C  r  r   )r   r`  r  r   rJ  r  r   r   r   r    r  z$Buffer.freeze_layout_with_same_orderr  c                 C  r  r  )r   r`  r  r   rF  r   r   r   r   r!    s   z'Buffer.freeze_layout_with_exact_stridesc                 C  r  r  r  r  r   r   r   r    r  zBuffer.is_zero_elementsr  c                   s*      rtt  dS d fdd}|S )	Nr  r   r  r   rl   c                   s      }t jp
d|| S r  )r
  rk   r  r   r   r  r  r   r   r    s   z"Buffer.make_loader.<locals>.loaderr  )r  r   r  r   rA  r   r  r   r    s   zBuffer.make_loaderNr  r  c                 C  r  r   r  r  r   r   r   r    r  zBuffer.codegen_referencec                 C  r
  r   r   r  r   r   r   r-    r  zBuffer.decide_layoutr  c                 C     t | jtr| jj gS dS r  )r   r`  rR  rS  r  r  r   r   r   r4       z#Buffer.get_inputs_that_alias_outputc                 C  r  r  )r   r`  rk  r^  r  r  r   r   r   r2    r  zBuffer.get_mutation_namesr  c                 C  s   t |  gS r   )r9   r  r  r   r   r   r    r   zBuffer.get_read_namesr{  r   c                 C  rl  r   r8   r+  r   r   r   r,       zBuffer.get_free_symbol_usesc                 C  rl  r   r8   r  r   r   r   rm    r  zBuffer.get_unbacked_symbol_defsc                 C  r
  r   r   r  r   r   r   r    r  zBuffer.realizec                 C  r  r  r   r  r   r   r   should_allocate  r  zBuffer.should_allocater6  rF  rH  )r   r{  rC  r9  r;  r?  )r   ry  r@  r<  r=  rS  r>  rL  rM  rN  )r  r   r   r   )r  r   r  r   r   r   rE  r   rB  rW  r7  rU  rp  rA  )%r   r   r   r   r  r
  r  r  r!  r  r^  r  r  rC  r}  r  r  r*  r~  r  r  r  r  r!  r  r  r  r-  r4  r2  r  rX   r,  rm  r  r  r  r   r   r  r   r  n  sL   
 






















r  c                   @  s0   e Zd ZdddZdddZejZdd	d
ZdS )OperationBufferr   rj  c                 C  s   | gS r   r   r  r   r   r   rk    r  zOperationBuffer.get_outputsr_  c                 C  rj  r   r   r  r   r   r   r    r  zOperationBuffer.get_defining_opr   c                 C  s   t |  t|  d S r   )r  r  r_  r  r   r   r   r    s   
zOperationBuffer.__post_init__Nro  r   r_  r6  )r   r   r   rk  r  r_  r3  r  r   r   r   r   r    s
    

r  c                   @     e Zd ZdddZdS )r  r   r   c                 C  r  r  r   r  r   r   r   r)  	  r  zInputBuffer.num_readsNrS  )r   r   r   r)  r   r   r   r   r        r  c                   @  r[  )DonatedBufferaY  
    Represents a donated buffer which is a saved tensor that is not alias to any
    fwd inputs, fwd user outputs, and bwd outputs. We generally cannot inplace
    reuse the input tensor memory during backward since it might be used in another
    function. However, donated buffer can be inplace reused during backward
    to save memory.
    N)r   r   r   rX  r   r   r   r   r    r_  r  c                   @  s.   e Zd ZU dZded< dddZdddZdS )r  Nr  r  r   r  c                   r  )Nr   r  r   rl   c                   s,       }ttj   j|| S r   )	r  r
  rk   r  rm   r  constant_namer  r  r  r  r   r   r    s
   z*ConstantBuffer.make_loader.<locals>.loaderr  r   rA  r   r  r   r    s   zConstantBuffer.make_loaderr  r  r   c                 C  s   t tj|  || jdS N)r   r`  )r  rm   r  r  r  r`  r  r   r   r   r1  $  s   z!ConstantBuffer.constant_to_devicerE  rV  )r   r   r   r  r   r  r1  r   r   r   r   r    s   
 

r  c                   @  sL   e Zd ZdddZed 	ddd	d
ZddddZdddZdddZdS )NoneAsConstantBufferr   r$  c                 C  rl  r   r8   r  r   r   r   r  ,  r  zNoneAsConstantBuffer.get_readsFr{  r   r   c                 C  rl  r   r8   r+  r   r   r   r,  /  r  z)NoneAsConstantBuffer.get_free_symbol_usesNr  r  r   c                 C  s
   t jjjS r   )rm   r  r  none_strr  r   r   r   r  5  r(  z&NoneAsConstantBuffer.codegen_referencer0  c                 C  s
   t d dS Nr  )rf  r  r   r   r   r  8  r(  z$NoneAsConstantBuffer.get_output_specc                 C  r  r  r   r  r   r   r   r  ;  r  z&NoneAsConstantBuffer.has_tensor_outputrR  rL  rU  r   rB  r=  r>  )	r   r   r   r  rX   r,  r  r  r  r   r   r   r   r  *  s    

r  c                   @  sB   e Zd ZU ded< ed 	dddd	ZddddZdddZd
S )r   r   r  Fr{  r   r   r   c                 C     t | j|S r   )r'   r  r+  r   r   r   r,  C     z*ShapeAsConstantBuffer.get_free_symbol_usesNr  r  r   c                 C  s   t jj| jS r   )rm   r  r  codegen_sizevarr  r  r   r   r   r  I  rl  z'ShapeAsConstantBuffer.codegen_referencec                 C  r  r  r   r  r   r   r   r  L  r  z'ShapeAsConstantBuffer.has_tensor_outputrL  rU  r   rB  r>  )r   r   r   r   rX   r,  r  r  r   r   r   r   r   ?  s   
 r   c                      sh  e Zd ZU dZded< dZded< dZded	< dZd
ed< dZded< dZ	ded< e
jd[ddZee
jd[ddZd\ddZd]ddZd^ddZd_dd Zd`d"d#Zed 	dadbd'd(Zdc fd*d+Zddd,d-Zded/d0Zdfd2d3Zdgd5d6Zedhd8d9Z		didjd>d?Ze	dkdldIdJZdmdLdMZdmdNdOZ d\dPdQZ!dddRdSZ"dddTdUZ#dndYdZZ$  Z%S )or  zb
    Represents a buffer that is computed during kernel execution rather than being an input.
    rq  r_  FzClassVar[bool]_force_realizeNr  r  Optional[Callable[..., Any]]r  r  r  r  r   Iterator[None]c              
   c  s    | j d usJ | jd usJ | jd usJ | jd usJ t| jts+J t| j | j}| j}z3t|j	|j
| j| j| j|j|j|jd}|| _t|j	|j
| j| _| j|  d V  W || _|| _d S || _|| _w )Nr  )r  r  r  r  r   r_  r  r   r`  r  r  r  r   r  rb  get_default_sizes_bodyclear_cache)r  old_datarg  new_datar   r   r   with_original_inner_fn_  s>   

z%ComputedBuffer.with_original_inner_fnc                  c  s*    t j} zdt _d V  W | t _d S | t _w NT)r  r  )	old_valuer   r   r   force_realize  s   zComputedBuffer.force_realizer-  c                 C  s(   | j dur| j S t| jdr| jj S dS )z
        Returns self.name if it exists, otherwise returns the name of the data node if that exists.
        If neither exist, returns None.
        Nr   )r   r  r_  r  r   r   r   get_computed_buffer_name  s
   
z'ComputedBuffer.get_computed_buffer_namer   c                 C  rB  r   r_  r)  r  r   r   r   r)    r(  zComputedBuffer.num_readsr$  c                 C  rB  r   r_  r  r  r   r   r   r    r(  zComputedBuffer.get_readsr  c                 C  rB  r   rN  r  r   r   r   r    r(  zComputedBuffer.get_read_namesr"  c                 C  s   t | jttttfstjt t t dS t	
tdd, | j r7t|  | j | j W  d    S t|  | j W  d    S 1 sKw   Y  d S )Nr'  writesindex_exprsr  T)r   r_  r  r  r  r  rB   
ReadWritesr9   r   r   r  r-  rK   get_store_functionr  r.  r  r  r   r   r   r#    s&   
$zComputedBuffer.get_read_writesr{  r   r   c                 C  s6   | j || j|B }|  r||  |O }|S r   )r`  r,  r_  has_store_functionr#  )r  r{  r  r   r   r   r,    s   
z#ComputedBuffer.get_free_symbol_usesr  c                   s<   |   s| jtjjvr|  dkr| js| j S t	  S r  )
r-  r   rm   r  mutated_buffersr)  r  r_  r  r  r  r  r   r   r    s   

zComputedBuffer.make_loaderc                 C  s   t | jttttfS r   )r   r_  r  r  r  r  r  r   r   r   r    r   z!ComputedBuffer.has_store_functionCallable[..., None]c                 C  s`   |     }t| jtttfrt| jj	| j
|S t| jts'J t| jt| jj| j
|S r   )r  r*  r
  r   r_  r  r  r  r   r  r   r  r   r  r?  r   r   r   r    s
   z!ComputedBuffer.get_store_functionOptional[list[int]]c                   s   t | jtrYt| j | j \\}}|  j	}t
dd |D s&J fdd|D }|rYt | jttfrA| j| n|  fdd|D }ddlm} |||  S dS )	al  
        If our layout is still flexible, try to determine the stride order based on stride orders of reads.

        TODO(jansel): A better algorithm here would look at downstream consumers of this
                      value and try to do global graph-level layout optimization.
                      This is also something just begging to be autotuned.
        c                 s  s"    | ]}t |tjtjfV  qd S r   )r   rB   StarDep	MemoryDepr"  r   r   r   r     
    
z0ComputedBuffer.get_fill_order.<locals>.<genexpr>c                   s.   g | ]}t |tjrt|jd d  D qS )c                 S  s   i | ]}|d kr|t jjqS r  ro  )r   vr   r   r   r         z<ComputedBuffer.get_fill_order.<locals>.<listcomp>.<dictcomp>)r   rB   r  ri   r   r"  )r  r   r   r     s    
z1ComputedBuffer.get_fill_order.<locals>.<listcomp>c                   s   g | ]
}t jj| qS r   rm   r  r  r@  r   r  )r0  r   r   r     s    r@   pick_loop_orderN)r   r`  r  rB   r>  r_  r  r.  r#  r'  r   r  r  r   	schedulerr  r  )r  
index_varsr  r'  stride_lengthsr  r   )r0  r  r   r     s*   


zComputedBuffer.get_fill_orderr   c                 C  s6   t | jtr|  }|r| | d S |   d S d S r   )r   r`  r  r   r  r  r  r   r   r   r-    s   zComputedBuffer.decide_layoutMtuple[tuple[list[Expr], list[Expr]], LoopBody, tuple[list[Expr], list[Expr]]]c           
      C  s   t j|  |  dd\}}ttd|   t| 	 | 
 r"|n|d d |g|R  }W d    n1 s8w   Y  g }g }g }g }| D ]+\}}	||d v rb|rWJ || ||	 qI||d v sjJ || ||	 qI||f|||ffS )Nqr|   r  r@   r   )rB   r>  r  r.  r   r   r  r!  rM   r  r-  itemsr  )
r  r   
var_rangesr  r  reduce_vars
index_sizereduce_sizer  r   r   r   r   r    s2   



z%ComputedBuffer.get_default_sizes_bodyextra_indexing_constraints*Optional[tuple[dict[Any, Any], list[Any]]]recompute_sizes_body_func8tuple[tuple[list[Expr], list[Expr]], Optional[LoopBody]]c                   s    \\}}}\}}|r|||f|||f\\}}}\}}g |j  |durut|tr4t|dks6J |\}}	t|tsEJ t|t|	tsPJ t|	t	dd |	D s[J |j
}
|
|kshJ |
|f fdd|	D }	 |	7  g | tjtjs|  d fdd}|| }tt ptj }|||||\}}}|||||\}}}tj||dd\\}}}t|||||g|||}||f|fS )an  
        This is a main place where we do loop transformations in a
        backend-agnostic way.

        Here we:
            1) Remove any 1 dimensions
            2) Fuse contiguous dimensions together
            3) Reorder dimensions based on stride orders

        Optional argument extra_indexing_constraints can be used to append additional
        indexing expressions to existing ones derived from buffer's body. This can be useful
        to fuse scheduler nodes with compatible ranges, e.g. (s0*s1*...,) and (s0, s1, s2, ...)
        on CPU by preventing indexing simplifications and obtaining index/reduce ranges for
        the scheduler node compatible with other nodes.
        Optional argument recompute_sizes_body_func can be used to recompute sizes and body
        on the default body. This can be useful to append additional loop transformations.
        Nr   c                 s      | ]}t |tV  qd S r   )r   r   )r   fr   r   r   r   c  rx  z6ComputedBuffer.simplify_and_reorder.<locals>.<genexpr>c                   s   g | ]}| vr|qS r   r   rv  )index_formulasr   r   r   k      z7ComputedBuffer.simplify_and_reorder.<locals>.<listcomp>x_varsSequence[sympy.Symbol]support_varsr4  r   simplify_loopsr   r   dtuple[list[int], Callable[[Sequence[int]], Sequence[int]], Callable[[Sequence[int]], Sequence[int]]]c                   s    | | \}}} dkr8t dkr8ttt }||d dkr8 fdd|D }t|}t|}|| } |rTtjj	
| |t| |\}}}	t||}
n|}
||
|fS )Nr  r   r   c                   r   r   r   r   r4  r   r   r     r   zUComputedBuffer.simplify_and_reorder.<locals>.simplify_and_reorder.<locals>.<listcomp>)_apply_loop_reorderingr-  r   r   r   r   r   rm   r  r  _simplify_loopsrF   r   )r  r  r4  r  newsizesreindex0r   r   r   _pruner   r  memory_addrsr  r  r   simplify_and_reordert  s&   




zAComputedBuffer.simplify_and_reorder.<locals>.simplify_and_reorderpr|   )
r  r  r  r  r4  r   r  r   r   r  )r  indexing_exprsr   r   r   r   r   r   r   r   r  get_write_exprsrm   r  r5  rC   PREFER_STORE_LOOP_ORDERextendget_read_exprsrd   r1  rA   loop_ordering_after_fusionrB   index_vars_no_squeezerM   )r  r  r  r  r  r  r  r  extra_indexing_rangesextra_indexing_exprexpected_var_rangesr  r  should_merge_loopsiter_rangesiter_reindexr  reduce_rangesreduce_reindex	iter_varsr  r   r  r   r  5  sx   

6

z#ComputedBuffer.simplify_and_reorderr  r  r  r4  r   r  list[sympy.Expr]priority_idxr  c              
     s   ddl m} |du rg }z* fdd|D }t|t|kr)t|d t ks+J tt|||}W n  tyV   tjrLt	dt
t | ttt}Y nw fdd|D t|t|fS )	zU
        Shuffle the order of loops around to hopefully improve performance.
        r@   r  Nc                   s   g | ]}t jj| qS r   r  r  )r  r  r   r   r         z9ComputedBuffer._apply_loop_reordering.<locals>.<listcomp>r   z%Did not simplify complex index:
%s
%sc                   r   r   r   r   r  r   r   r     r   )r  r  r   r   r  	ExceptionrA   r  r=  warningr   r   r   r   r   )r  r  r4  r  r  r  rX  r   r   )r  r4  r  r   r    s,   
z%ComputedBuffer._apply_loop_reorderingr  c                 C  rB  r   )r_  r  r  r   r   r   r    r(  z!ComputedBuffer.get_pointwise_sizec                 C  rB  r   r_  r.  r  r   r   r   r.    r(  z!ComputedBuffer.get_reduction_sizec                 C  rB  r   r_  r-  r  r   r   r   r-    r(  z!ComputedBuffer.get_reduction_typec                 C  rB  r   )r_  r  r  r   r   r   r0    r(  zComputedBuffer.is_no_opc                 C  r  r  r   r  r   r   r   r     r  zComputedBuffer.should_allocater  r  r   c                 C  r7  )r  r_  r1  r  r   r   r   r1    r9  z!ComputedBuffer.constant_to_device)r   r  rA  rS  rR  r7  rQ  rL  rU  rE  r>  )r   r  )r   r  r6  )r   r  NN)r  r  r  r  r   r  r   )r  r  r  r  r4  r   r  r  r  r  r   r  r?  rV  )&r   r   r   rX  r   r  r  r  r  r  r\  r]  r  r[  r  r  r)  r  r  r#  rX   r,  r  r  r  r   r-  rW   r  r  r  r  r.  r-  r0  r  r1  r  r   r   r  r   r  P  sR   
 "








'" 
'



r  c                      sf   e Zd ZdZd# fd
dZd$ddZd%d&ddZd'ddZd(ddZd)ddZ			d*d+d!d"Z
  ZS ),r  zt
    Represents a Triton (in the future other type) of template operator
    that we can fuse an epilogue onto.
    r`  r0  rw  rx  make_kernel_renderr  r   r   c                   sF   t  jd |d t|| _|| _tj| | _	tj
|  i | _d S r  )r  r  r  unwrap_storagerw  r  rm   r  register_bufferr   register_operationr   )r  r`  rw  r  r  r   r   r    s   
zTemplateBuffer.__init__r"  c                 C  s   | j ddS )NT	normalize)rK   r  r   r   r   r#    r   zTemplateBuffer.get_read_writesFr  r   c              	     s   |   |    d fdd}tj||  d|d	}| jD ]:ttt	fs/J t
tjts<J t
jj  d fd
d}| jtj| d|d	jO  _q |S )Nr   Sequence[Any]r  r   r   c                   s"   t |dksJ t | dS )Nr   fake)r   rk   r  r_  )r  r   r   r   dummy#  s   z1TemplateBuffer.extract_read_writes.<locals>.dummyr   r  c                   s$   t |dksJ t  | S r  )r   rk   r  r  r_  )r  r}  r   r   r  1  s   )r   r  r  r  r   r   )r  r  r
  rB   rK   r  rw  r   re  r  r   r`  r  r'  )r  r  r  depsr   )r  r}  r   r   rK     s"   


z"TemplateBuffer.extract_read_writesr  c                 C  s   t jjS r   )r   r  r  r  r   r   r   r.  <  r  z!TemplateBuffer.get_reduction_sizer-  c                 C  r
  r   r   r  r   r   r   r-  ?  r  z!TemplateBuffer.get_reduction_typec                 C  r  r  r   r  r   r   r   r  B  r  zTemplateBuffer.should_allocateNr  r  r  <tuple[tuple[Sequence[Expr], list[Expr]], Optional[LoopBody]]c                 C  s   |   g fd fS r   r  )r  r  r  r   r   r   r  E  s
   z#TemplateBuffer.simplify_and_reorder)r`  r0  rw  rx  r  r  r   r   rQ  rL  )r  r   r   r"  r?  rA  r>  r  )r  r  r  r  r   r  )r   r   r   rX  r  r#  rK   r.  r-  r  r  r  r   r   r  r   r    s    



r  c                      s\   e Zd Z		dd  fddZed 	d!d" fddZd#ddZd$ddZd%ddZ  Z	S )&TritonTemplateBufferNr`  r  rw  rx  r  Optional[Callable[_P, _T]]mutated_inputsOptional[Iterable[IRNode]]allowed_prologue_inpsOptional[OrderedSet[str]]r   r   c                   s   t  ||| |_g_|dur:tjd ts$J tjd jd    j fdd|D 7  _|r>|nt	 _
d_d_dS )a  
        NOTE:[TritonTemplates with multiple outputs]
        We want the ability for TritonTemplates to output multiple tensors. Triton
        kernels have no notion of outputs and this is done by creating tensors that
        are then mutated by the kernel. Currently our STORE_OUTPUT codegen doesn't
        support creating multinode outputs for triton templates.
        We work around this by creating an extra input buffer during the lowering
        and we mark them as mutated inputs.
        Nr   c                      g | ]}t t d |qS r  MutationOutputrf  r   r2  r  r  r   r   r   k  r  z1TritonTemplateBuffer.__init__.<locals>.<listcomp>)r  r  r  outputsr   rw  r   r   r!  r9   r  subgraph_inpssubgraph_outs)r  r`  rw  r  r  r  r  r  r   r  T  s   "

zTritonTemplateBuffer.__init__Fr{  r   r   c                   s   t  |}| jr| jng }| jr| jng }|D ]%}t|tjr)|t|| qt|t	r7||| q|d u s=J q|D ]}t|t	rP||| q@|d u sVJ q@|S r   )
r  r,  r	  r  r   r   r   updater'   r   )r  r{  resr	  r  r}  r  r  r   r   r,  w  s   

z)TritonTemplateBuffer.get_free_symbol_usesrj  c                 C  r  r   r  r  r   r   r   rk    r  z TritonTemplateBuffer.get_outputsr  c                 C  r  r   )r  r  r   r   r   get_allowed_prologue_inps  r  z.TritonTemplateBuffer.get_allowed_prologue_inpsr   c                 C  s   d| j  d}|S )NzTritonTemplateBuffer(layout=r/  r  )r  r  r   r   r   r    s   zTritonTemplateBuffer.__str__r  )r`  r  rw  rx  r  r  r  r  r  r   r   r   rL  rU  ro  r7  rH  )
r   r   r   r  rX   r,  rk  r  r  r  r   r   r  r   r  S  s    #

r  c                      s|   e Zd ZdZd' fddZd(ddZd)ddZd*ddZd)ddZd)ddZ	d+ddZ
d,d!d"Zd)d#d$Zd-d%d&Z  ZS ).ChoiceCallera1  
    Represents a possible choice used in autotune_process.py.
    During autotuning, self.benchmark() is first called to get benchmark result,
    and if this choice is selected, self.output_node() is called to get the output_node.

    Children classes: TritonTemplateCaller, CUTLASSTemplateCaller.
    r   r   r   rj  r`  r  descriptionr   r   c                   s2   t    || _|| _|| _|| _d| _i | _d S r  )r  r  r   r`  r   r  failedr   )r  r   r   r`  r  r  r   r   r    s   

zChoiceCaller.__init__r   r   r  r  r  c                  s6   |    tjrt fddS tj d|id dS )Nc                     s     S r   r   r   algor   r   r   r#    s    z(ChoiceCaller.benchmark.<locals>.<lambda>r  r  )to_callablerA   /profile_bandwidth_with_do_bench_using_profilingr]   rR   	benchmark)r  r  r   r   r  r   r    s   zChoiceCaller.benchmarkc                 C  rb  r   rc  r  r   r   r   	call_name  r  zChoiceCaller.call_namerr  c                 C  rb  r   rc  r  r   r   r   r    r  zChoiceCaller.to_callablec                 C  r  )z
        Hash key for the underlying kernel. By default, we assume there are no
        runtime params, so kernel hash key defaults to choice caller's hash key.
        )hash_keyr  r   r   r   kernel_hash_key  s   zChoiceCaller.kernel_hash_keyc                 C  rb  r   rc  r  r   r   r   r    r  zChoiceCaller.hash_keyr~   c                 C  rb  r   rc  r  r   r   r   ru    r  zChoiceCaller.output_node<dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]c                 C  s   i S )zRInformation returned here is logged to the autotune log file when that is enabled.r   r  r   r   r   	info_dict  r  zChoiceCaller.info_dictc                 C  r  )Nunsupported_choicer   r  r   r   r   autoheuristic_id  r  zChoiceCaller.autoheuristic_idc                 C  s
   d| _ dS )z
        Mark the choice as failed so that it can be
        removed later. Useful for when we decouple
        compilation and tuning.
        TN)r  r  r   r   r   mark_failed  s   
zChoiceCaller.mark_failed)
r   r   r   rj  r`  r  r  r   r   r   )r   r   r  r  r   r  rH  )r   rr  )r   r~   )r   r  r6  )r   r   r   rX  r  r  r  r  r  r  ru  r  r  r  r  r   r   r  r   r    s    







r  c                   @  r  )TritonTemplateCallerBaser   r   c                 C  rb  r   rc  r  r   r   r   get_make_kernel_render  r  z/TritonTemplateCallerBase.get_make_kernel_renderN)r   r   )r   r   r   r  r   r   r   r   r    r  r  c                      s~   e Zd ZdZd) fddZed*ddZed+ddZ	d,d-ddZe	j
d.ddZd/d d!Z	d,d0d#d$Zd1d'd(Z  ZS )2MultiTemplateBufferaG  
    Represents a Buffer with multiple backing implementation choices.

    Choices can be TritonTemplates or ExternKernels. During scheduling if there is a potential
    epilogue we will benchmark each of the choices with the epilogue to determine an implementation.
    Otherwise, the fastest base choice will be chosen.
    r`  r  rw  rx  choice_timings_fn4Callable[[Optional[int]], dict[ChoiceCaller, float]]unfiltered_choiceslist[ChoiceCaller]r  r  r   r   c                   sJ   t  j||d |d || _i | _|| _|| _tdd |D | _i | _d S )N)r`  rw  r  r  c                 s  s0    | ]}t |tpt |tjjjo|jV  qd S r   )r   r  r#  r  select_algorithmExternKernelCallerhas_out_variant)r   choicer   r   r   r     s    

z/MultiTemplateBuffer.__init__.<locals>.<genexpr>)	r  r  _choice_timings_fn_choice_timings_choicesoriginal_inputsr   _output_plannable_make_kernel_renders)r  r`  rw  r!  r#  r  r  r   r   r    s   

zMultiTemplateBuffer.__init__r   c                 C  r  )z^
        Are all possible choices TritonTemplates or Extern Kernels with out variants
        )r-  r  r   r   r   output_plannable  s   z$MultiTemplateBuffer.output_plannablec                 C  r  r   )r+  r  r   r   r   r:    r  zMultiTemplateBuffer.choicesNhint_overrider  dict[ChoiceCaller, float]c                 C  s$   || j vr| || j |< | j | S r   )r*  r)  )r  r0  r   r   r   choice_timings  s   

z"MultiTemplateBuffer.choice_timingscallerr  r  c                 c  sZ    t |tjjjsJ t|| j|jksJ | j}| | _z	d V  W || _d S || _w r   )	r   r#  r  r%  TritonTemplateCallerr   r`  r  r  )r  r3  renderr   r   r   swap_as_triton_caller  s   

z)MultiTemplateBuffer.swap_as_triton_callerc                 C  sR   t |tjjjsJ t||  |jjksJ | 	 |jj
ks"J | | _d S r   )r   r#  r  r%  r4  r   r  r`  r  rC  r  r  r  )r  r3  r   r   r   finalize_as_triton_caller-  s   
z-MultiTemplateBuffer.finalize_as_triton_callertuple[ChoiceCaller, float]c                 C  s&   | j |d}t||jd}||| fS )N)r0  r%  )r2  r  r  )r  r0  timings
min_choicer   r   r   get_min_choice5  s   z"MultiTemplateBuffer.get_min_choicecallers-dict[Optional[int], TritonTemplateCallerBase]c                 C  s0   |  D ]\}}| | j|< q| jd | _dS )z;Finalize with multiple callers for different hint overridesN)r  r  r.  r  )r  r<  r0  r3  r   r   r   finalize_as_triton_callers<  s   z.MultiTemplateBuffer.finalize_as_triton_callers)r`  r  rw  rx  r!  r"  r#  r$  r  r  r   r   r>  )r   r$  r   )r0  r  r   r1  )r3  r  r   r  )r3  r  r   r   )r0  r  r   r8  )r<  r=  r   r   )r   r   r   rX  r  r^  r/  r:  r2  r\  r]  r6  r7  r;  r>  r  r   r   r  r   r     s    
	r   c                      s2   e Zd Zd fddZdddZdddZ  ZS )CUTLASSTemplateBufferr`  r  rw  rx  r  Callable[_P, _T]workspace_sizer   templaterq   supports_epilogue_fusionr   r   r   c                   s&   t  ||| || _|| _|| _d S r   )r  r  rA  rB  rC  )r  r`  rw  r  rA  rB  rC  r  r   r   r  H  s   	
zCUTLASSTemplateBuffer.__init__c                 C  s   | j d ur| j S dS r  rA  r  r   r   r   rn  W  r   z(CUTLASSTemplateBuffer.get_workspace_sizec                 C  s$   |   D ]}t| d d  qd S r   )rk  rk   r  r  )r  rm  r   r   r   emulate_store_fnZ  s   z&CUTLASSTemplateBuffer.emulate_store_fn)r`  r  rw  rx  r  r@  rA  r   rB  rq   rC  r   r   r   rS  r6  )r   r   r   r  rn  rE  r  r   r   r  r   r?  G  s    
r?  c                      s,   e Zd Zd fddZd fddZ  ZS )CppTemplateBufferr`  r  rw  rx  r  r@  rB  rq   r(  r   r   r   c                   s&   t  ||| || _|| _d | _d S r   )r  r  rB  r(  r  )r  r`  rw  r  rB  r(  r  r   r   r  `  s   
zCppTemplateBuffer.__init__c                   sp   t | jtr3t | jtsJ t| j| jd }t |ts#J t||j}t |ts1J t||S t 	 S r  )
r   r`  MultiOutputLayoutr  r   r   r  r  r  r  )r  first_outputr`  r  r   r   r  m  s   

zCppTemplateBuffer.get_layout)r`  r  rw  rx  r  r@  rB  rq   r(  r   r   r   r<  )r   r   r   r  r  r  r   r   r  r   rF  _  s    rF  c                      s0   e Zd ZdZ	dd fddZdddZ  ZS )CuteDSLTemplateBufferz
    Buffer for CuteDSL (CUTLASS Python DSL) template kernels.
    Similar to other template buffers but specialized for CuteDSL operations.
    Nr`  r  rw  rx  r  r@  rB  r   r  r  r   r   c                   s   t  ||| |_|_g_|d ur?tjd ts'J tjd jd 	   j fdd|D 7  _d S d S )Nr   c                   r  r  r  r  r  r   r   r     r  z2CuteDSLTemplateBuffer.__init__.<locals>.<listcomp>)
r  r  rB  r  r  r   rw  r   r   r!  )r  r`  rw  r  rB  r  r  r  r   r    s   "zCuteDSLTemplateBuffer.__init__rj  c                 C  r  r   r  r  r   r   r   rk    r  z!CuteDSLTemplateBuffer.get_outputsr   )r`  r  rw  rx  r  r@  rB  r   r  r  r   r   ro  )r   r   r   rX  r  rk  r  r   r   r  r   rI  z  s
    rI  c                      sP   e Zd ZdZ					d"d# fddZd$ddZd%ddZ	d&d'd d!Z  ZS )(NVUniversalGemmBufferz
    Buffer for NVIDIA Universal GEMM kernels.

    Unlike CuteDSL templates which use Jinja templates, this generates
    simpler Python code that directly calls the cutlass_api library.
    r   Nr`  r  rw  rx  kernelr   accumulator_typevariantrA  r   scale_type_aOptional[Any]scale_type_bswizzle_type_aswizzle_type_br   r   c                   sj   t  j||d d || _|| _| g| _|| _|| _|| _|| _|	| _	|
| _
|jj|jjd| _| j| _d S )N)r  )kernel_namemin_cc)r  r  rK  rL  r  rA  rM  rN  rP  rQ  rR  metadatarS  rT  kernel_metadata_make_kernel_renderr  )r  r`  rw  rK  rL  rM  rA  rN  rP  rQ  rR  r  r   r   r    s   zNVUniversalGemmBuffer.__init__c                 C  r  )z#Return the workspace size in bytes.rD  r  r   r   r   rn    r  z(NVUniversalGemmBuffer.get_workspace_sizerj  c                 C  r  r   r  r  r   r   r   rk    r  z!NVUniversalGemmBuffer.get_outputsout_noder0  r  tuple[Any, Any]c           	        s   ddl m} ddlm} g }| jD ]}t|tr|j}t|tr#|j}|	| qt
|j}||||| j| j| j| j| j| j| j| jd  fdd} |fS )z
        Create a kernel renderer for code generation.

        Returns (kernel, render) tuple where:
        - kernel: NVUniversalGemmKernel object with call_kernel() method
        - render: function that returns source code string
        r   )NVUniversalGemmKernel)Placeholder)rS  r   ru  rV  rL  rA  rM  rN  rP  rQ  rR  c                     s      S r   )r5  r   render_kernelr   r   r5    r  z9NVUniversalGemmBuffer._make_kernel_render.<locals>.render)Btorch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernelrZ  torch._inductor.utilsr[  rw  r   r~   r_  r  r  r   KERNEL_NAMErV  rL  rA  rM  rN  rP  rQ  rR  )	r  rX  r0  rZ  r[  r   r}  rS  r5  r   r\  r   rW    s2   




z)NVUniversalGemmBuffer._make_kernel_render)r   NNNN)r`  r  rw  rx  rK  r   rL  r   rM  r   rA  r   rN  rO  rP  rO  rQ  rO  rR  rO  r   r   rS  ro  r   )rX  r   r0  r  r   rY  )	r   r   r   rX  r  rn  rk  rW  r  r   r   r  r   rJ    s    
!
rJ  r   )Sequence[Union[IRNode, Sequence[IRNode]]]TypeIs[Sequence[IRNode]]c                 C  s   t dd | D S )Nc                 s  r  r   r   r   ry  r   r   r   r     rx  z#is_node_sequence.<locals>.<genexpr>)r   )r   r   r   r   is_node_sequence  rj  rd  c                   @  sz   e Zd ZU ded< d!ddZd"d
dZd#ddZed$ddZe	d%ddZ
d&ddZd'ddZed 	d(d)ddZd S )*r  ra  rw  r   r   r   r   c                 C  s    | j | }t|tsJ | S r   rw  r   r   r  )r  r   inputr   r   r   
input_name   s   
zInputsKernel.input_namer"  c                   s   t tj  }tj | jD ]#}t|tr | fdd|D  qt|tr&q|	 |
  qt tj  fdd|  D }tj||t  dS )Nc                 3      | ]	} |  V  qd S r   r  rT  r  r   r   r   
  r)  z/InputsKernel.get_read_writes.<locals>.<genexpr>c                 3  rh  r   r  r  ri  r   r   r         
r  )r9   rB   rH   r  rw  r   r   r
  r   r  r  rk  r  )r  r'  rf  r  r   ri  r   r#    s    


zInputsKernel.get_read_writesr$  c                 C  r%  r   r&  r  r   r   r   r    r(  zInputsKernel.get_readsr   r   c                 C  s~   t |tr|j}t |tr|j}t |trt |tst|}t |tr)| |S t |t	r0|S t |t
tfs=J t||S r   )r   r~   r_  r  r  re  r  realize_inputunwrap_storage_for_inputTorchBindObjectr  r   r  r   r   r   r   rl    s   





z%InputsKernel.unwrap_storage_for_input%list[Union[IRNode, Sequence[IRNode]]]c                 C  s@   g }| D ]}t |trdd |D }nt|}|| q|S )Nc                 S  rZ  r   )r  rl  r   r   r   r   r   8  r   z/InputsKernel.unwrap_storage.<locals>.<listcomp>)r   r   r  rl  r  )rw  
inputs_newr   r   r   r   r  1  s   

zInputsKernel.unwrap_storager   c                 C  r  r  r   r  r   r   r   r/  >  r  zInputsKernel.is_externc                 C  r  r  r   r  r   r   r   r)  A  r  zInputsKernel.num_readsFr{  r   c                 C  sN   t tj  }| jD ]}t|tr|||O }q	|D ]	}|||O }qq	|S r   )r9   r   r!   rw  r   r   r,  )r  r{  r  r}  	inner_inpr   r   r   r,  D  s   

z!InputsKernel.get_free_symbol_usesN)r   r   r   r   rQ  rR  r  )rw  ra  r   ro  r>  rS  rL  rU  )r   r   r   r   rg  r#  r  r  rl  r[  r  r/  r)  rX   r,  r   r   r   r   r    s   
 




r  c                   @  s    e Zd Zd	ddZd
ddZdS )	NopKernelr   r   c                 C  r  r  r   r  r   r   r   r0  S  r  zNopKernel.is_no_opr$  c                 C  rl  r   r8   r  r   r   r   r  V  r  zNopKernel.get_readsNr>  rR  )r   r   r   r0  r  r   r   r   r   rr  R  s    
rr  c                   @  s^   e Zd ZdZeddd	Ze	
ddddZed 	ddddZed ddZ	d!ddZ
d
S )"ConcatKernelzn
    There isn't actually a real kernel for concat, we just change the
    storage for the upstream data.
    rw  rx  rS  r   r   r  c                 C  s  |d   }|d  }t|d  }dg}|| g}d|  kr)t|k s,J  J tdt|D ]Z}||  }	|||  t|	t|ksLJ ||  |ksVJ ||   |ks`J tt|D ]}
|
|krw||
 |	|
  ||
< qftjj	
||
 |	|
 ||
< qf|||  q3t|}tjrt|||d j}tt|D ]!}|| }t|r| }t|trt|j|jrt|} nqtdd |D }tjjjd }t|tsJ t||du rtdd |D rt|}tdd |D }|dusJ tdt|||||d	g d
}t |}g }t!|D ]{\}}t|t"t#fs.J t|| $|t%j&|||| || dd}t|t'sLJ t|t|j(tsZJ t|j(|j(| t|j)t"rm|j)* }n|j)}t|t r|+ r|   }durt,|jrt-|s||.  qt|dkrtj/|t0j1rtj2| tj3||_4| 5|j(|_(tj6| |S )z6
        Create the concat kernel from inputs
        r   r@   c                 s  r  r   )r  rT  r   r   r   r     r  z&ConcatKernel.create.<locals>.<genexpr>Fc                 s  sB    | ]}d |j v o|j d  jtjdp|j d  jtjdV  qdS )rd  r8  N)rs  r'  r#  r:  r<  r   argr   r   r   r     s    	

c                 s  s"    | ]}t |o| jV  qd S r   )r  r  rd  rT  r   r   r   r     s    
N)r  r  r  r  rd  r   r`  rw  r  )7r!  r   r   r  r   r   r  rm   r  r  rw  r  r  rA   r)  r  r(  r  r  r  r   rb  r  r  r  r,   r  current_noder   r   r   rs  r  r   r  ro  rz  r  r  r  rw  r_  r  r  rd   rc   r3  r5  rC   FOREACHregister_operation_listr  r   r  r  )r  rw  rS  r  r  rP  offsets_startoffsets_endr   
input_sizerN  output_strider   r`  any_input_is_storage_and_layoutfx_node_argsrd  concat_kernelrK  op_namesr}  rZ  input_unwrappeddevr   r   r   r  `  s   
 

	 zConcatKernel.createNrr  r   rs  r  r   c                 C  s   t |tr| |j|S t |ttfsJ t|t |jtrPt |jjt	r*|jj
s,dS |d u r2dS t| t| kr@dS tdd t| | D S t|jdoct |jjtoct |jt S )NFTc                 s  rZ  r   r[  r\  r   r   r   r     r]  z=ConcatKernel.can_realize_into_without_copy.<locals>.<genexpr>r`  )r   r~   can_realize_into_without_copyr_  r  r  r   r   r`  rb  r/  r   rC  r   r   r  r  ExternKernelAlloc)r  rr  rs  r   r   r   r    s*   
z*ConcatKernel.can_realize_into_without_copyFr{  r   c                 C  s   t | |S r   )rr  r,  r+  r   r   r   r,    r  z!ConcatKernel.get_free_symbol_usesc              	   C  s   t |tst|rt|\}}t||d}t |ts J t|t |tr,| |j|S t |trL|	  t
|jds=J | ||rLt||j_|jS tj| | | dd t| | D d}| ||S )Nr^  r`  c                 S  ru  r   rv  rx  r   r   r   r     ry  z-ConcatKernel.realize_into.<locals>.<listcomp>r  )r   re  r  ra  r   r~   rz  r_  r  r  r  r  rR  r`  r  r  r!  r   r  r   r  )r  rr  rs  rf  r`  pwr   r   r   rz    s,   


	zConcatKernel.realize_intoc                 C  r  r  r   r  r   r   r   r    r  zConcatKernel.should_allocate)rw  rx  rS  r   r   r  r   )rr  r   rs  r  r   r   rL  rU  )rr  r   rs  r   r   r   r>  )r   r   r   rX  r  r  r  rX   r,  rz  r  r   r   r   r   rs  Z  s    q#!rs  c                      s  e Zd ZU dZdZded< ejedZ	ded< dZ
d	ed
< dZded< dZded< ejedZded< dZded< dZded< ejedZded< dZded< ejedZded< ejedZded< 							dd fd$d%Zdd'd(Zdd*d+Zdd,d-Zdd.d/Z	ddd3d4Zdd5d6Zddd7d8Zdd9d:Zdd;d<Zdd>d?Ze ddCdDZ!e"ddJdKZ#e"ddMdNZ$e"ddOdPZ%e"ddQdRZ&e"			SdddZd[Z'e"	Sddd]d^Z(e"	Sddd`daZ)e"ddbdcZ*e"ddddeZ+e"ddfdgZ,e"ddhdiZ-ddjdkZ.ddldmZ/dddqdrZ0ddsdtZ1ddvdwZ2dddydzZ3dd{d|Z4dd}d~Z5dddZ6dddZ7dddZ8dddZ9e:d 	SddddZ;dddZ<e<Z=  Z>S )r  z
    A class that represents Kernels which are not directly lowered to Inductor
    Loop Level IR, such as custom operators, or aten operators which we fallback to.
    r   r  constant_argsrh  r  r   NOptional[ReinterpretView]output_viewr-  python_kernel_namecpp_kernel_nameIterable[str]ordered_kwargs_for_cpp_kernelOptional[_OpOverloads]op_overloadzOptional[list[dict[str, Any]]]arg_propertieszdict[str, dict[str, Any]]allarg_propertiesz#Optional[dict[str, dict[str, Any]]]kwarg_propertiesz"dict[sympy.Symbol, pytree.KeyPath]unbacked_bindingszlist[MutationOutput]mutation_outputsr   r`  r0  rw  ra  dict[str, Any] | Noner   r   c                   st   t  j|||d || _|r|ni | _|| _|
| _| | | | |	| _| 	  i | _
g | _tjj| _i | _d S Nrw  )r  r  r  r   r  r  set_cpp_kernel_nameset_python_kernel_namer  collect_arg_kwarg_propertiesr  r  rm   r  ry  fx_noder   )r  r   r`  rw  r  r   r  r  r  r  r  r  r   r   r  >  s"   



zExternKernel.__init__rj  c                 C  s   | g| j S r   )r  r  r   r   r   rk  ^  r   zExternKernel.get_outputsr   c                 C  rl  r   r8   r  r   r   r   rm  a  r  z%ExternKernel.get_unbacked_symbol_defsc                 C  s   t | jtjjrdd | jjjD ndd tt| j	D | _
t | jtjjr1dd | jjjD ni | _t | jtjjrW| jsJdd | jjjD | _dd | jjjD | _d S g | _d S )Nc                 S  s$   g | ]}|j s|j|j|jd qS ))r   r   r  )
kwarg_onlyr   	real_typer  rT  r   r   r   r   h  s    z=ExternKernel.collect_arg_kwarg_properties.<locals>.<listcomp>c                 S  s   g | ]}i qS r   r   r   r   r   r   r   r  r  c                 S  s   i | ]}|j |j|jd qS ))r   r  )r   r  r  rT  r   r   r   r   u  r  z=ExternKernel.collect_arg_kwarg_properties.<locals>.<dictcomp>c                 S     g | ]}|j r|jqS r   r  r   rT  r   r   r   r     
    c                 S  s   g | ]}|j r|qS r   )r  rT  r   r   r   r     s
    )r   r  r#  _ops
OpOverload_schema	argumentsr   r   rw  r  r  r  schema_kwargsr  r   r   r   r  d  s*   


z)ExternKernel.collect_arg_kwarg_propertiesc                 C  s$   t | jtr|   |   d S d S r   )r   r`  r  apply_constraintr  r  r   r   r   r-    s   zExternKernel.decide_layoutwrapperrr   rS  c                 C  sZ   t | |\}}|r|| |s|  }|r+ddlm} || |dd}||| d S d S )Nr@   )'set_kernel_post_grad_provenance_tracingT)r/  )r`   make_commenttry_get_kernel_namer  r  write_provenance_debug_handle)r  r  rS  
origin_str_detailed_origin_strr  debug_handler   r   r   codegen_comment  s   
zExternKernel.codegen_commentc                 C  rb  r   rc  r  r  r   r   r   codegen  r  zExternKernel.codegenc                 C  s   || _ tjjrt| jtjjsd S | j}| j d u rB|j	dkr;|j
dkr+|jdd n|jdd}d| d| _ d S |jj| _ d S d S )Natenr  .r   r  z
at::_ops::z::call)r  rm   r  cpp_wrapperr   r  r#  r  r  	namespace_overloadnamer   r  replacer  r   )r  r  rK  opnamer   r   r   r    s   




z ExternKernel.set_cpp_kernel_namec                 C  sd   || _ |d ur	d S | j}|d u rd S t|tjjr"d|j | _ d S |jdd d|j | _ d S )Nztorch.ops.higher_order.._ops..ops.r  )	r  r  r   r#  r  HigherOrderOperatorr   r   r  )r  r  rK  r   r   r   r    s   z#ExternKernel.set_python_kernel_namec                 C  s   ddl m} |   }r|jntjj}tjjr| jS tjj	r=t
tjj|s-J ttjj| jd u r4d S tjj| j|S | jS )Nr@   )CppWrapperCpu)codegen.cpp_wrapper_cpur  r!  r   rm   r  device_type
fx_wrapperr  r  r   r  r  get_c_shim_func_name)r  r  dr  r   r   r   r    s   
z ExternKernel.try_get_kernel_namer   c                 C  r  r   )r  rh  r   r   r   get_kernel_name  r  zExternKernel.get_kernel_namer   r   r~   c                 C  s:   t j|  |  |  |  |  |  d}|  |S )N)r  r  rs  rt  r  r  )	r  r  r!  r   r  r  r  r  r  )r   r  r   r   r   
copy_input  s   zExternKernel.copy_inputrK  r{   r   r   ituple[Any, list[Any], list[Any], Callable[[Any, Any], Any], Optional[dict[sympy.Symbol, pytree.KeyPath]]]c                   s  ||d}t |\} g g }g }|D ].}t|to"t|t  d r.|| qt|tr=tjj	j
j|d d}|| qd fd	d
}	fdd|D }|D ]}
t|
rbt|
dd qVg }|D ]n}
t|
ts|
 tjjv r|tjj|
   qgt|
ts|
 tjjv r|tjj|
   qgt|
tr||
  qgt|
tjjjr|
jj}|
jjdkr|d usJ |tjj|   qg|t|
dd qg|	||\}}||i |}d }tjj
 }r*tjj !d}t" }tjj#tj$j%j&u r
|d }t'tj}| t(|tj| W d    n	1 sw   Y  t)|||}t|t*t+fs5|gn|}|D ]+}t|tj,rc|j-rct.j/scd}tjjj !dd  }r_| d| }|tj_0q9||||	|fS )Nr   rA  )r  new_tensor_argsr   new_non_tensor_argsr   tuple[list[_T], dict[str, _T]]c                   sd   g }t | }t |}D ]}|r|t| q|t| qt| }|dg |di fS )Nr   r   )rx  r  rw  pytreetree_unflattenr  )r  r  r  
it_tensorsit_non_tensors	is_tensorr  )	args_specis_arg_tensorr   r   unflatten_args
  s   z3ExternKernel.process_kernel.<locals>.unflatten_argsc                   r
  r   rk  rT  r  r   r   r     r   z/ExternKernel.process_kernel.<locals>.<listcomp>Tr"  r4  )r	  rd  r@   zEsparsity not handled. Please file issue for sparse inference weights.r  z Found from : 
 )r  r   r  r   r   r  )1r  tree_flattenr  r   r   GeneratorStater   rm   r  r  r   create_symintnoder  ra  r  r  	constantstorchbind_constantsrm  	get_valuer#  r  irr  r   r   r4  default_generatorsclone_stater  r  ry  rs  r  r	   r^  _higher_order_opseffectswith_effectsr.   r3   r/   r   r   Tensor	is_sparserA   graph_partitiondisable_cudagraphs_reason)r  rK  r   r   binded_args	args_flattensor_argsnon_tensor_argsrv  r  r   example_argsdevice_indexnew_args
new_kwargsexample_outputr  r   node_meta_valctxexample_out_lir&  msgr  r   )r  r  r  r   process_kernel  s   


		



zExternKernel.process_kernelre  c              
   C  sp  t |tsJ t|t |tr|S | }tj| }|dus$J |	 }|dur]d|j
v r]t |tttfr]t |jtr]|j
d jtjdsS|j
d jtjdr]|t|  n|  tj| dd\}}|d }| |}tjj||}tjj||}	tjj||}
t||	|
 }||krt d|	|
| t!t|j"t#|$ |% | |	|
dd	d
S )z
        In order to pass this to an extern kernel we need a
        ReinterpretView not a View.  This allows us to avoid some
        unneeded copies.
        Nrd  rt  r  r|   r   z@convert_to_reinterpret_view failed: stride=%s offset=%s index=%sFrd  r^  )&r   r  r   re  r  rm   r  rl  r  r  rs  r  ro  r`  r  r'  r#  r:  r<  r  r,   r  r  rB   r>  r
  r  r?  stride_vars
offset_varre   r=  r  r  r_  rb  r   r   )r  r   x_unwrap_viewr2  x_unwrap_view_fx_node
index_argsr  r*  r   rX  rc  expectedr   r   r   convert_to_reinterpret_viewl  sj   






z(ExternKernel.convert_to_reinterpret_viewc                 C  s6  |d u rt  S t|ttjjjtfrt|dS t|t	r@t
  tjtj|j| | dW  d    S 1 s;w   Y  t|trG|S t|trR| |jS t|trct| |j| dS t|tr|  t| rz| |W S  ty   Y nw t|tr|  |S t|t tfr|S | !|S )Nr  )r  r  r^  )"r  r   r   r   r   r   r   r   r   r  r:   rm   r  add_tensor_constantr#  rW  r'  r   r!  r  r~   rk  r_  re  r  r  r  r  r  r  r  r  NonTensorObjr  rn  r   r   r   rk    s@   

 





zExternKernel.realize_inputc                 C  sD   t |rt| dkr|S | D ]
}|dkr|  S q| |S r  )r  r   rC  r  )r  r   r  r   r   r   require_stride1  s   
zExternKernel.require_stride1Fr   r  r  r  r  r   c              	     s  |d us
 d us
J   dv r sS trt trS|rGt|o-t j }tdd|r@t	t
jj jn||d S tddd | d S t ttfr}|re |sr r}t  j r} d ur{t S S t  }trt|  }trtdt|tr|r||s rt |j rS ttr|r |sǈ rt  j rɈS ttrtjtrtjtst  }rt|drt|jtsz!| j_|r| j ||dW S  r| j! |dW S W n
 t"y   Y nw d }	 }
 d urOt
jj fd	d
t#t$ D }	|	D ]}t%j&j'(|ddqA| )tdd|| d |rkt|siJ S |	r|
d urx d uszJ t%j&j'*|
t S S )N)r   r@   TF)r#  r*  r+  r  r.  zHthe MutationLayoutSHOULDREMOVE's real layout shouldn't be FlexibleLayoutr_  r/  c                   s4   g | ]}  | d r | dr|qS )r   r   )rQ  r  r  r   r  r  r   r   r   r   d  s    z0ExternKernel.require_strides.<locals>.<listcomp>r   r@   )+r  r  r   r  r  r2  r1   r  ra  r  rm   r  r  size_hints_or_throwrb  rR  r1  rV  r  rj  rk  rn  rv  r  r~   r_  r  re  r  r  r  r  require_stride_orderrequire_exact_stridesr  r   r   r#  r  loweringslice_r  r\  )r  r   r   r  r  use_current_stride_ordermutation_layoutrn  r  expanded_dims	orig_sizerS  r   r  r   require_strides  s  	
	
	


	


zExternKernel.require_stridesrM  c                 C  s   | j |dd |D |dS )Nc                 S  s$   g | ]}t |tjr|jjn|qS r   )r   r#  SymIntr   r  r   r   r   r   r     s    z6ExternKernel.require_exact_strides.<locals>.<listcomp>)r  r  r  )r  r   r  r  r   r   r   r    s   z"ExternKernel.require_exact_stridesr   c                 C  s   | j |||dS )N)r   r  r  )r  r   r   r  r   r   r   r    s   z!ExternKernel.require_stride_orderc                 C     |  |tS r   )r  r;  rn  r   r   r   require_channels_last  r9  z"ExternKernel.require_channels_lastc                 C  r  r   )r  r=  rn  r   r   r   require_channels_last_3d  r9  z%ExternKernel.require_channels_last_3dc                 C  s,   ddd}||r|S |  |t| S )Nr   r   r   r   c              	   S  s@   z|   }W n ttfy   Y dS w |tjjv otjj| jS r  )r  AttributeErrorr  rm   r  r  	is_mkldnn)r   r   r   r   r   is_mkldnn_tensor  s   z9ExternKernel.require_contiguous.<locals>.is_mkldnn_tensorr   r   r   r   r  r  r  r  )r  r   r  r   r   r   r    s   
	zExternKernel.require_contiguousc                 C  s   |  |t| S r   r  rn  r   r   r   require_contiguous_strides  s   z'ExternKernel.require_contiguous_stridesc                 C  r
  r   r   r  r   r   r   r    r  zExternKernel.apply_constraintc                 C  s   t |tsJ t|t |tst|}| jsJ dt|}t| j}||k rStd| j||  t	||D ]}| j| d }|
||v rJ|| n| j| d  q7|S )Nz/ExternKernel.arg_properties should not be emptyzv%s has %d unprovided positional arguments. Will check if they are in the keyword arguments or will use default values.r   r  )r   r   r   r   r  r   r=  r  r  r   r  )r  r   r   n_args
n_pos_argsr   arg_namer   r   r   fill_non_provided_args  s(   

z#ExternKernel.fill_non_provided_argsr{  r  r   c           	      C  s   t jjrog }d }|r"| jr"t| jt|ksJ ddd | jD }t| jD ]E\}}|d urF|d us5J ||| }|rC|dnd }nt| j| }| jr_|t| jk r_| j| dnd }|	t jj
|| q'|S dd | jD S )NzDnames passed to codegen_const_args does not match self.constant_argsc                 S  s   i | ]}| d |qS r   )r  ru  r   r   r   r     rz  z3ExternKernel.codegen_const_args.<locals>.<dictcomp>r   c                 S  r  r   rm   r  r  val_to_arg_str)r   r  r   r   r   r     r  z3ExternKernel.codegen_const_args.<locals>.<listcomp>)rm   r  r  r  r   r  r   r  rw  r  r  r  )	r  r{  r  name_to_arg_propertiesr   r   proptype_r   r   r   r   codegen_const_args  s2   
zExternKernel.codegen_const_argsc                 C  s   t jjr| jd ur| g | j| j| j}d}n| j}d}g }t|D ]4\}}t jjrN| j	r6|t
| j	k s:J d| j	| d}|t jj|| q$|t jj| q$|rb||   |S )NFTz-Invalid access to ExternKernel.arg_propertiesr   )rm   r  r  r  r  rw  r  r   r   r  r   r  r  r  r  r  r  )r  rw  need_codegen_constant_argsr   r   r   r  r   r   r   codegen_args   s&   zExternKernel.codegen_argsr  c                 K  sT   ||v r	| |S || jv r| j |S | j | }dur#| dS t| d)zGiven an argument name, queries for values in (in order):
        1. any provided kwargs for this function.
        2. the class self.kwargs member.
        3. any available default arguments in self.allarg_properties.Nr  z not in self.allarg_properties)r  r   r  rv  )r  r  r   rv  r   r   r   get_kwargs_value  s   


zExternKernel.get_kwargs_valueskip_outc                 C  s   t jjrO| jd urt| jdkrg S g }| jD ]5}|r |dkr q| |}t|t	r0|
| q| jd us7J | j|i d}|
t jj|| q|S dd | j D }|S )Nr   r  r   c                 S  s(   g | ]\}}| d t jj| qS r}  r  )r   kr  r   r   r   r   ;  s    z/ExternKernel.codegen_kwargs.<locals>.<listcomp>)rm   r  r  r  r   r  r  r  r   r   r  r  r  r  r  r   r  )r  r  r   r  r  r  r   r   r   codegen_kwargs'  s$   


zExternKernel.codegen_kwargsc                 C  sT   | j d ur&| j j}t|dd}|dd}|ddd }| d| }|S d}|S )	Nr   unknown_namespacer  r  r  r@   r   
unknown_op)r  r^  r   r  rsplit)r  r^  op_namespaceop_namer   r   r   get_op_nameA  s   
zExternKernel.get_op_namec                 C  s   t jr=tjjs?t|  dkrd S tjj|  }tjj| 	 }| 
 }|d|   d| d| d|d	 d S d S d S )Nr   zassert_size_stride(rS  r/  )rA   size_assertsrm   r  r  rh   r  r  codegen_shape_tuplerC  r&  r  r  )r  r  r  r  r%  r   r   r   codegen_size_assertsL  s    z!ExternKernel.codegen_size_assertsc              	   C  st   t jr6tjjs8|  }|tjjv}|  }|r(|d| dt	 d|d d S |d| d| d d S d S d S )Nzassert_alignment(rS  r/  z	# buffer z (op: z) is assumed to be not aligned)
rA   alignment_assertsrm   r  r  r  r5  r&  r  ra   )r  r  r   alignedr%  r   r   r   codegen_alignment_assertsX  s   z&ExternKernel.codegen_alignment_assertsc                 C  s@   t jjrtjjr
dS |  |  }|d| d| d dS )zc
        Track outputs of fallback operators if config.test_configs.track_memory_lifecycle
        Nztrack_tensor(z, 'z'))	rA   test_configstrack_memory_lifecyclerm   r  r  "write_memory_track_allocation_oncer  r  )r  r  r   r   r   r   codegen_memory_trackingf  s
   z$ExternKernel.codegen_memory_tracking'tuple[list[Sequence[Expr]], list[Expr]]c                 C  s   |   }|  }|g g|fS )zD
        get output sizes and strides, for template_codegen
        )r  rC  )r  r  r  r   r   r   get_group_strideq  s   zExternKernel.get_group_stridetuple[Expr, Sequence[Expr]]c                   s  t jj|  }|  }fdd|D }dd tt|D ttt||jdd}dd t	|D fddttD }fd	d|D | 
 }|}t jj||g\}}}	td
\}
 tt| fdd|D }tt||}|t|fS )zC
        Manually get canonicalization of the output index
        c                   r
  r   )r  rT  )r  r   r   r     r   z-ExternKernel.canonicalize.<locals>.<listcomp>c                 S  s   g | ]	}t d | qS )r  )rf   r   r   r   r   r     r  T)r&  r  c                 S  r   r   r   r   r   r   r   r     r   z-ExternKernel.canonicalize.<locals>.<dictcomp>c                   r   r   r   r   r   r   r   r     r   c                   r   r   r   r   )r  r   r   r     r   cc                   r  r   r   rT  )add_varr   r   r     r   )rm   r  r  r  rC  r   r   r+  r@  r   r
  r  rL   r   r   ri   r   r\  r   )r  r4  rX  index_orderr   r  r   	new_sizesr   r  r  replacementr   )r5  r  r   r  r   canonicalizez  s$   
 zExternKernel.canonicalizer{  c                 C  sP   |rt nt}t| |}| jD ]}|||O }q| j D ]}|||O }q|S r   )maybe_free_unbacked_symbolsmaybe_free_symbolsr  r,  r  r   r   )r  r{  maybe_get_symbolsr  rv  r   r   r   r,    s   

z!ExternKernel.get_free_symbol_usesc                   sP   t  dd }d|g}| fddt D 7 }|d j  |S )Nr  zpython_kernel_name=c                   s$   g | ]}|j  d t |j  qS r}  )r   r   )r   rZ  r  r   r   r     s    z(ExternKernel.__str__.<locals>.<listcomp>r  )r   rY  fieldsr  r  r  )r  rS  r  r   r  r   r    s   
zExternKernel.__str__r   NNNNr   N)r   r-  r`  r0  rw  ra  r  r  r   r  r  r  r  r-  r  r-  r  r  r  r  r   r   ro  rp  r6  r   )r  rr   rS  r-  r   r   r  rr   r   r   r  r-  r   r   )r  r-  r   r   rA  rH  )r   r   r   r~   )rK  r{   r   r   r   r   r   r  )r   r   r   re  r  )NNF)
r   r   r   r  r  r  r  r   r   r   rL  )r   r   r  rM  r  r   r   r   )r   r   r   r   r  r   r   r   )r   r  r   r  r   r  )r{  r  r   r   r   r   )r  r   r   r   r   r   )r  r   r   r   )r   r1  )r   r3  rU  )?r   r   r   rX  r  r   rY  rZ  r   r   r  r  r  r   r  r  r  r  r  r  r  r  rk  rm  r  r-  r  r  r  r  r  r  r[  r  r  r  r  rk  r  r  r  r  r	  r
  r  r  r  r  r  r  r  r   r&  r)  r,  r0  r2  r9  rX   r,  r  r  r  r   r   r  r   r  "  s   
 
 


%



~E#	 $

$
!






	
r  c                      sB   e Zd ZdddZ							dd  fddZd!ddZ  ZS )"ExternKernelOutr  rr   r   r   c                 C     | |  d S r   )generate_extern_kernel_outr  r   r   r   r    r   zExternKernelOut.codegenr   Nr`  r  rw  rx  r  r  r   Optional[dict[str, Any]]r  r  r  r-  r  r  r  r  c
                   s`   |  |}
t|
tsJ t|
t d ||
||pi d ||||	
 tj| | _	tj
|  d S r   )r  r   r   r   r  r  rm   r  r  r   r  )r  r`  rw  r  r   r  r  r  r  r  unwrapped_inputsr  r   r   r    s    
zExternKernelOut.__init__r   c                 C  r  r  r   r  r   r   r   r    r  zExternKernelOut.should_allocater?  r>  )r`  r  rw  rx  r  r  r   rE  r  r  r  r-  r  r-  r  r  r  r  r   r   r>  )r   r   r   r  r  r  r  r   r   r  r   rB    s    
rB  c                         e Zd Zd	 fddZ  ZS )
RandomSeedscountr   r  r  r   r   c                   sF   t t j}t jt|t j|gdg |j|j|ggddtj	j
d d S )Nr  zaten.randint.low_outzat::_ops::randint_low_out::call)r`  rw  r  r  r  r  )r#  r  r^  r  r  rb  r  r  r  randintlow_out)r  rI  r  limitsr  r   r   r    s   
zRandomSeeds.__init__)rI  r   r  r  r   r   r   r   r   r  r  r   r   r  r   rH        rH  c                      sJ   e Zd ZdddZ						dd  fddZd!ddZd"ddZ  ZS )#r  r  rr   r   r   c                 C  rC  r   )generate_extern_kernel_allocr  r   r   r   r    r   zExternKernelAlloc.codegenr   Nr`  r0  rw  rx  r  r  r   rE  r  r-  r  r  r  r  c	           
        sp   |  |}	tdd |	D sJ t d |ttt |	||pi d ||||
 g | _tj	
| | _tj	|  d S )Nc                 s  r  r   rc  r   r   r   r   r     rx  z-ExternKernelAlloc.__init__.<locals>.<genexpr>)r  r   r  r  r   r   r   r  rm   r  r  r   r  )
r  r`  rw  r  r   r  r  r  r  rF  r  r   r   r    s"   
zExternKernelAlloc.__init__r   c                 C  r  r  r   r  r   r   r   r    r  z!ExternKernelAlloc.should_allocatec                 C  rb  r   rc  r  r   r   r   r    r  z"ExternKernelAlloc.apply_constraintr?  )r   NNNr   N)r`  r0  rw  rx  r  r  r   rE  r  r-  r  r-  r  r  r  r  r   r   r>  r6  )r   r   r   r  r  r  r  r  r   r   r  r   r    s    

 r  c                      sJ   e Zd ZdZd fd
dZdddZdddZdddZdddZ  Z	S )r  zP
    An output buffer that represents the mutation of a pre-existing buffer
    r`  r0  mutated_noder   mutating_noder_  r   r   c                   sD   t  jd |d | }tj| |g| _|| _tj| | _	d S r  )
r  r  r  rm   r  rm  mutation_namesrQ  r  r   )r  r`  rP  rQ  mutated_node_namer  r   r   r  "  s   zMutationOutput.__init__c                 C  r  r   )rQ  r  r   r   r   r  ,  r  zMutationOutput.get_defining_opr  c                 C  r  r   )rR  r  r   r   r   r2  /  r  z!MutationOutput.get_mutation_namesr   c                 C  r  r  r   r  r   r   r   r  2  r  zMutationOutput.should_allocaterx  c                 C  s    |   }dd dd |D D S )Nc                 S     g | ]}|d ur|qS r   r   r  r   r   r   r   7  s
    z7MutationOutput.get_mutation_buffers.<locals>.<listcomp>c                 s  s    | ]	}t j|V  qd S r   )rm   r  try_get_bufferr  r   r   r   r   9  r)  z6MutationOutput.get_mutation_buffers.<locals>.<genexpr>)r2  )r  rR  r   r   r   get_mutation_buffers5  s   z#MutationOutput.get_mutation_buffers)r`  r0  rP  r   rQ  r_  r   r   r  rW  r>  r   rx  )
r   r   r   rX  r  r  r2  r  rV  r  r   r   r  r   r    s    



r  c                      s`   e Zd ZU dZi Zded< edd	d
ZedddZd fddZ	dddZ
dddZ  ZS )TMADescriptorad  
    An IR node representing a generic host-side TMA descriptor in the Triton API
    Mostly useful for user-defined Triton kernels relying on host-side TMA;
    but can, in principle, be used for Inductor's Triton templates, too.

    See TMADescriptorExperimental and TMADescriptorStable for the two implementations
    (the old API and the new API)
    zdict[Any, TMADescriptor]_CACHErW  r   tma_metatuple[str, tuple[Any, ...]]r   c                 C  sT   t |dksJ |d dkrt|g|d R  S |d dks J t|g|d R  S )Nr   r   experimentalr@   r  )r   TMADescriptorExperimentalTMADescriptorStable)r  rW  rZ  r   r   r   _create_implL  s
   zTMADescriptor._create_implc                 C  s2   t ||f}|| jvr| ||| j|< | j| S r   )idrY  r_  )r  rW  rZ  r&  r   r   r   r  W  s   

zTMADescriptor.createrw  r  r  r   c                   sV   t  d tt|| dttt |t|d  || _	t
j| | _t
j|  d S )Nr^  )r  r  rR  re  r  r   r   r  r   rW  rm   r  r  r   r  )r  rW  rw  r  r  r   r   r  `  s   zTMADescriptor.__init__r  rr   c                 C  rC  r   )generate_tma_descriptorr  r   r   r   r  w  r   zTMADescriptor.codegenc                 C  r  r   )rW  r  r   r   r   
get_tensorz  r  zTMADescriptor.get_tensor)rW  r   rZ  r[  r   rX  )rW  r   rw  r  r  r  r   r   r?  rK  )r   r   r   rX  rY  r   r  r_  r  r  r  rb  r  r   r   r  r   rX  >  s   
 

rX  c                      s&   e Zd ZdZ	dd fddZ  ZS )r]  z
    the new host-side TMA Descriptor API:
    (the ones obtained via create_{1d,2d}_tma_descriptor calls).

    See also TMADescriptorStable for the new API.
    NrW  r   r`  list[Union[int, torch.SymInt]]
block_dimselement_sizer  r   r   c                   s   t |dv sJ t |t |ksJ |d u r| j}|| _|| _|| _t | j| _|g}g | j| j| j}t j|||d d S )N)r@   r   rW  rw  r  )	r   r   r  r`  rd  re  r%  r  r  )r  rW  r`  rd  re  rw  r  r  r   r   r    s*   

z"TMADescriptorExperimental.__init__r   )
rW  r   r`  rc  rd  rc  re  r  r   r   r   r   r   rX  r  r  r   r   r  r   r]  ~  s    r]  c                      s"   e Zd ZdZd fddZ  ZS )	r^  z
    the new host-side TMA descriptor API
    (the ones obtained via TensorDescriptor.from_tensor).

    See also TMADescriptorExperimental for the old API.
    rW  r   block_shaperc  c                   s   || _ t j||g|d d S )Nrf  )rh  r  r  )r  rW  rh  r  r   r   r    s   
zTMADescriptorStable.__init__)rW  r   rh  rc  rg  r   r   r  r   r^    s    r^  c                      s(   e Zd Zd fddZdddZ  ZS )SubgraphBufferr`  r  r   rj  rk  rl  example_inputs	list[Any]subgraph_namer   c           	   	     s,  t  d || || _|| _tj| | _tj|  tj	| j||| _
t| js,J t| j}|D ]}|| j
j|j< | j
j|j q3dd |D | _dd lm  m} t| j
0 |jdddd | j
j| j  W d    n1 sww   Y  W d    d S W d    d S 1 sw   Y  d S )Nc                 S     g | ]}|j qS r   r   )r   sym_varr   r   r   r         z+SubgraphBuffer.__init__.<locals>.<listcomp>r   FATEN)max_autotunemax_autotune_gemmmax_autotune_gemm_backends)r  r  rk  rj  rm   r  r  r   r  make_subgraphsubgraphrd  rw  r~  r  graph_input_namesr  
sym_inputstorch._inductor.configr  rA   set_graph_handlerr   run)	r  r`  r   rk  rj  rl  rw  sym_inpinductor_configr  r   r   r    s0   
"zSubgraphBuffer.__init__r  rr   r   r   c                 C  sR   G dd d}t | jsJ dd | jD }||| jg | j|| jg d S )Nc                   @  r  )z,SubgraphBuffer.codegen.<locals>.CodegenGraphr  rs   c                 S  s   || _ |j| _d S r   )r  r   )r  r  r   r   r   r    s   z5SubgraphBuffer.codegen.<locals>.CodegenGraph.__init__N)r  rs   )r   r   r   r  r   r   r   r   CodegenGraph  r  r}  c                 S     g | ]}|  qS r   r  r   r&  r   r   r   r     r   z*SubgraphBuffer.codegen.<locals>.<listcomp>)rd  rw  'codegen_subgraph_with_flattened_outputsru  rw  r   )r  r  r}  outer_inputsr   r   r   r    s   zSubgraphBuffer.codegen)
r`  r  r   rj  rk  rl  rj  rk  rl  r   r?  r   r   r   r  r  r  r   r   r  r   ri    s    $ri  c                      sn   e Zd Zd!ddZed"dd	Zed 	
d#d$ fddZd%ddZd& fddZ	d'ddZ
d(dd Z  ZS ))UserDefinedTritonKernelr   (tuple[Kernel, Any, list[str], list[str]]c                   s   ddl m} ddlm} || j g }g }g }t |ret dr0| fdd j	D  nt ds7J | j
 t drR jD ]}| jj|  qEnt d	sYJ | j  j} j  |||fS )
Nr   )	Autotuner)kernel_side_tablerestore_idxc                 3  s    | ]	} j j| V  qd S r   )r   	arg_namesr   rK  r   r   r     rj  zBUserDefinedTritonKernel.get_kernel_and_metadata.<locals>.<genexpr>restore_value	reset_idxreset_to_zero)triton.runtime.autotunerr  *torch._higher_order_ops.triton_kernel_wrapr  
get_kernel
kernel_idxr   r  r  r  r  r  r  r   r  r  configs)r  r  r  r  restore_value_argsreset_to_zero_argsr   r   r  r   get_kernel_and_metadata  s,   




z/UserDefinedTritonKernel.get_kernel_and_metadatar  rr   r   c                   s  ddl m}  \}}}}|||j||j\}}}	}
fddjD }dd |jD  dd |jD }t fdd	|D }g }g }g }g }t	
| tt	d
|
D ]w\}}||v re| reqY|| || t|tr||  ||  qYt|ttttjfr|| |t| qY||v r|d |t qY|du r	 | r|d |t qY|  |  qYtdt| d| || |j|||||||	d jjd
 dS )YOverrides the parent member.
        See https://github.com/pytorch/pytorch/issues/151692r   )triton_version_uses_attrs_dictc                   s   i | ]}|  |qS r   r  r   r  r  r   r   r   )  rz  z3UserDefinedTritonKernel.codegen.<locals>.<dictcomp>c                 S  rm  r   r   r   r  r   r   r   r   ,  ro  z3UserDefinedTritonKernel.codegen.<locals>.<listcomp>c                 S  r  r   )is_constexprnumr  r   r   r   r   -  r   c                 3  s    | ]} | V  qd S r   r   r   )r  r   r   r   .  r  z2UserDefinedTritonKernel.codegen.<locals>.<genexpr>r  rA  NzUnsupported arg type: r.  T)	arg_typesraw_argsraw_keystriton_metainductor_metar6  r  original_fxnode_name) r_  r  r  !define_user_defined_triton_kernelr   gridr  paramsr9   rV  r  r  r   repeatr  r   r   r  r   r   r  r   r   r   r   r  r  r  generate_kernel_callr!  r  r   )r  r  r  rK  r  r  r  new_namer  r  extra_launch_args
named_args
constexprsconstexpr_namesr   r  raw_keys_filteredraw_args_filteredr   rv  r   )r  r  r   r    s   	
	




	


zUserDefinedTritonKernel.codegenFr{  r   r   c                   s   t  |t| j|B S r   )r  r,  r'   r  r+  r  r   r   r,  h  s   z,UserDefinedTritonKernel.get_free_symbol_usesc                 C  rl  r   r8   r  r   r   r   rm  r  r  z0UserDefinedTritonKernel.get_unbacked_symbol_defsr  r   r  r   tma_descriptor_metadatar  kernel_argsc                  sz  g }i }g }   D ]0\}}	t|	tr1t|	}
||v r't|
|| }
||
 |
||< q
||	 |	||< q
t	|dksCJ |d 
 _t|tsUJ t|t d tjd|t|| |_|_ \}}}}t|dszJ  fdd|jD _ddlm} t	|dkr|d jni } fdd||i  ||D _fddjD _tj d S )	Nr   r  r  c                   s   g | ]}| v r|qS r   r   ru  r  r   r   r     r  z4UserDefinedTritonKernel.__init__.<locals>.<listcomp>)identify_mutated_tensorsc                   r   r   r   r   r&  r  r   r   r     s    c                   s    g | ]}t t jd | qS r  )r  rf  r  r  r  r   r   r     s    ) r  r   r~   r  rl  rk  rX  r  r  r   r!  r  r   r   r  r  rf  r   r  r  r  r  r  r  r  r  r   mutable_argsr  rm   r  r  )r  r  r  r  r  rw  r   r  r  r  r&  rK  r  r  r  autotuned_kwargsr  )r  r  r   r  u  sT   









	z UserDefinedTritonKernel.__init__rj  c                 C  s
   t | jS r   )r   r  r  r   r   r   rk    r(  z#UserDefinedTritonKernel.get_outputsr  c                 C  r  r   r  r  r   r   r   r!    r  z"UserDefinedTritonKernel.get_device)r   r  r?  rL  rU  rp  )
r  r   r  r   r  r  r  r  r   r   ro  rC  )r   r   r   r  r   r  rX   r,  rm  r  rk  r!  r  r   r   r  r   r    s    
 Z
	
?r  c                      sJ   e Zd ZdZdddZdd	d
ZdddZdddZd fddZ  Z	S )InplaceBernoulliFallbackE
    This needs to be a custom class to handle mutation properly
    r  rr   r   r   c                 C  s   t dd | jD sJ dd | jD \}tjjr5||   d| ddtt	| j
 d|j  d S ||   d| ddtt	| j
 d|j  d S )Nc                 s  r  r   rc  r  r   r   r   r     rx  z3InplaceBernoulliFallback.codegen.<locals>.<genexpr>c                 s  s    | ]
}t t| V  qd S r   )r   r   r  r  r   r   r   r     r  r  rS  z, NULL)r/  )r   rw  rm   r  r  r  r  r  r  reprr  ending)r  r  r   r   r   r   r    s   ,,z InplaceBernoulliFallback.codegenr   c                 C  r  r  r   r  r   r   r   r    r  z(InplaceBernoulliFallback.should_allocater  c                 C     |  dgS r  rg  r  r   r   r   r2    r   z+InplaceBernoulliFallback.get_mutation_namesr   c                 C  rl  r   r8   r  r   r   r   rm    r  z1InplaceBernoulliFallback.get_unbacked_symbol_defsr  r{   r   r   r  r   c                   sV   t  jd t| d| |g||d tj|  tj	| | _
tj|  d S )Nr  r  )r  r  rf  r!  r  rm   r  rm  r  r  r   r  )r  r  r   r  r  r   r   r    s   
z!InplaceBernoulliFallback.__init__r?  r>  rW  rp  )r  r{   r   r   r  r   r   r   
r   r   r   rX  r  r  r2  rm  r  r  r   r   r  r   r    s    



r  c                      s\   e Zd ZdZd ddZd!d	d
Zd"ddZd#ddZd$ fddZe		d%d&ddZ
  ZS )'InplaceCopyFallbackr  r  rr   r   r   c                 C  s    |   \}}}|||| d S r   )r  codegen_device_copy)r  r  rs  rr  non_blockingr   r   r   r    s   zInplaceCopyFallback.codegenr   c                 C  r  r  r   r  r   r   r   r    r  z#InplaceCopyFallback.should_allocater  c                 C  r  r  r  r  r   r   r   r2    r   z&InplaceCopyFallback.get_mutation_namesr   c                 C  rl  r   r8   r  r   r   r   rm    r  z,InplaceCopyFallback.get_unbacked_symbol_defsr`  r0  rw  rx  r  r  c                   sJ   t  jd |||ddd tj|d   tj| | _tj|  d S )Nz
aten.copy_aoti_torch_copy_)r  r  r   )	r  r  rm   r  rm  r  r  r   r  )r  r`  rw  r  r  r   r   r    s   zInplaceCopyFallback.__init__Frs  r   rr  r  c                   s6    fdd||fD }|f}t t| d||}|S )Nc                   r
  r   r  r  r  r   r   r     r   z.InplaceCopyFallback.create.<locals>.<listcomp>r  )r  rf  r!  )r  rs  rr  r  rw  r  r  r   r  r   r    s   zInplaceCopyFallback.creater?  r>  rW  rp  )r`  r0  rw  rx  r  r  r   r   rL  )rs  r   rr  r   r  r   r   r  )r   r   r   rX  r  r  r2  rm  r  r  r  r  r   r   r  r   r    s    



r  c                   @  sB   e Zd ZdZdddZdd	d
ZdddZdddZdddZdS )MutatingFirstArgExternKernelr  r  rr   r   r   c                 C  sX   t | jsJ g dd | jD tt| j}||   dd| d|j  d S )Nc                 s  s    | ]}|  V  qd S r   r  r  r   r   r   r   "  r  z7MutatingFirstArgExternKernel.codegen.<locals>.<genexpr>r  rS  r/  )	rd  rw  r  r  r  r  r  r  r  )r  r  argrefsr   r   r   r    s   
z$MutatingFirstArgExternKernel.codegenr   c                 C  r  r  r   r  r   r   r   r  )  r  z,MutatingFirstArgExternKernel.should_allocater  c                 C  r  r  r  r  r   r   r   r2  ,  r   z/MutatingFirstArgExternKernel.get_mutation_namesr   c                 C  rl  r   r8   r  r   r   r   rm  /  r  z5MutatingFirstArgExternKernel.get_unbacked_symbol_defsc                 C  r  r  r   r  r   r   r   has_side_effects2  r  z-MutatingFirstArgExternKernel.has_side_effectsNr?  r>  rW  rp  )	r   r   r   rX  r  r  r2  rm  r  r   r   r   r   r    s    




r  c                      rG  )
ResizeStorageBytesvariabler   rP  r   r   r   c                   s   t |ts	J dt jd t| d| |g|fd tj	|
  tj| | _tj|  d| _d| _t |tttfsFJ t|tjj|j
  d S )NzTODO: dynamic shapesr  )r  z"inductor_ops.resize_storage_bytes_z&torch::inductor::resize_storage_bytes_)r   r   r  r  rf  r!  r  rm   r  rm  r  r  r   r  r  r  r  r  r~   r   never_reuse_buffersr  r_  )r  r  rP  r  r   r   r  7  s   
zResizeStorageBytes.__init__)r  r   rP  r   r   r   rM  r   r   r  r   r  6  rN  r  c                      s(   e Zd Zd fddZdd	d
Z  ZS )SetSourceTensorKernelself_tensorr   storage_tensorr   r   c                   s   |   t j| ||gdtjjjjd t	|t
ttfs$J t|tjj|j  tjj|  tjj|   | }tt|d|| tt|d|| g| _d S )Nz!torch.ops.aten.set_.source_Tensor)r  r  r  )r  r  r  r  r#  rk   r  set_source_Tensorr   r  r  r~   r   rm   r  r  r  r_  r  r!  r  rf  r  )r  r  r  r  r  r   r   r  I  s"   

zSetSourceTensorKernel.__init__r  c                 C  s   |  d|  dgS r  r  r  r   r   r   r4  ]  r   z2SetSourceTensorKernel.get_inputs_that_alias_output)r  r   r  r   r   r   rW  )r   r   r   r  r4  r  r   r   r  r   r  H  s    r  c                      sR   e Zd ZdZd!ddZd"d	d
Zd#ddZd$ddZdddd% fdd Z  Z	S )&ScatterFallbackz
    This needs to be a custom class to handle mutation properly.
    This class handles both aten.scatter_ and aten.scatter_reduce_.
    It also handle the case `src` being a scalar properly.
    r  rr   r   r   c                 C  rC  r   )generate_scatter_fallbackr  r   r   r   r  h  r   zScatterFallback.codegenr   c                 C  r  r  r   r  r   r   r   r  k  r  zScatterFallback.should_allocater   c                 C  s"   | j d }t|tsJ | gS r  re  )r  r}  r   r   r   r2  n  s   

z"ScatterFallback.get_mutation_namesr   c                 C  rl  r   r8   r  r   r   r   rm  s  r  z(ScatterFallback.get_unbacked_symbol_defsNTrU  include_selfr  r{   r   r   rS  r   r   rr  rU  r-  r  c          
   
     s   t |t _ jr fdd|||fD }|f}	n fdd||fD }||f}	t jd t| d ||	||dt|ddg|d t	j
|  t	j
  _t	j
  d S )	Nc                   r
  r   r  r  r  r   r   r     r   z,ScatterFallback.__init__.<locals>.<listcomp>c                   r
  r   r  r  r  r   r   r     r   r  r  rU  r  )r  r  r  )r   r~   src_is_tensorr  r  rf  r!  r  r   rm   r  rm  r  r  r   r  )
r  r  r   rS  r   rr  rU  r  tensorsr  r  r  r   r  v  s&   
zScatterFallback.__init__r?  r>  rA  rp  )r  r{   r   r   rS  r   r   r   rr  r   rU  r-  r  r   r   r   r  r   r   r  r   r  a  s    



r  c                      sJ   e Zd ZdZdddZdd	d
ZdddZd ddZd! fddZ  Z	S )"IndexPutFallbackzQ
    This needs to be a custom class to handle mutation and indices properly
    r  rr   r   r   c                 C  rC  r   )generate_index_put_fallbackr  r   r   r   r    r   zIndexPutFallback.codegenr   c                 C  r  r  r   r  r   r   r   r    r  z IndexPutFallback.should_allocater  c                 C  r  r  r  r  r   r   r   r2    r   z#IndexPutFallback.get_mutation_namesr   c                 C  rl  r   r8   r  r   r   r   rm    r  z)IndexPutFallback.get_unbacked_symbol_defsr  torch._ops.OpOverloadr   r   r0  rk  r   r  
accumulater   c           	   	     s   | _ dd |D } fdd||g|D }d}t jd t| d ||fd||d tj 	d tj
  _tj  d S )	Nc                 S  rT  r   r   r   r   r   r   r     r   z-IndexPutFallback.__init__.<locals>.<listcomp>c                   r
  r   r  rT  r  r   r   r     r   aoti_torch_index_put_outr  zaten.index_put_)r  r  r  r   )r0  r  r  rf  r!  r  rm   r  rm  rg  r  r   r  )	r  r  r   r0  r   r  valid_indicesr  r  r  r  r   r    s    	zIndexPutFallback.__init__r?  r>  rW  rp  )r  r  r   r   r0  rk  r   r  r  r   r   r   r  r   r   r  r   r    s    



r  c                   @  s$   e Zd Zeddd	ZdddZdS )
DeviceCopyr   r   r  r  r  r   r   c           	      C  s(  |  }|d us
J | s:t|tjjvr:tdd | D r:tj	j
s:tjjr5tj| tj| ||S tj| tj| td |f}t|}d }| r\| }t|jog|jdkog|}|jdkost|jos|}|rt|rd| _tt|| | ||d| |g|S )Nc                 s  s    | ]	}|t jjv V  qd S r   )rm   r  r  r"  r   r   r   r     r)  z$DeviceCopy.create.<locals>.<genexpr>zDeviceCopy in input programr3  TrQ  )r!  r/  r  rm   r  r  r   r  rA   aot_inductoruse_runtime_constant_foldingr  add_device_infor1  r\   r  r  r  rC  rd   r   r  r  rd  r  rb  r   rk  )	r  r   r  r  x_devicer  r  is_destination_pinnedis_source_pinnedr   r   r   r    sL   



zDeviceCopy.creater  rr   r   c                 C  s\   |   }t|dksJ | jr||d | j |d  d S ||d |  |d  d S )Nr   r   r@   )r  r   r  r  r  )r  r  r   r   r   r   r    s   zDeviceCopy.codegenN)r   r   r  r  r  r   r   r   r?  )r   r   r   r  r  r  r   r   r   r   r    s    /r  c                      s`   e Zd ZdZdddZd ddZd! fddZd"ddZed 	d#d$ddZ	d%ddZ
  ZS )&DynamicSelectStorageOffseta  
    The result of computing a dynamic selection index is determined as follows: when the index in the
    select operation is unbacked, the actual index calculation is ambiguous for negative indices
    (index + size) versus non-negative indices (just index). To resolve this, we allocate an unbacked
    SymInt to represent the storage offset and decompose the select operation into a call to as_strided,
    computing the storage offset at runtime with this node.
    r   r$  c                 C  rl  r   r8   r  r   r   r   r    r  z$DynamicSelectStorageOffset.get_readsr   c                 C  r  r  r   r  r   r   r   r    r  z*DynamicSelectStorageOffset.should_allocateunbacked_offset_symbolsympy.Symbolr   base_offsetUnion[sympy.Symbol, int]base_dim_strider  r  r   c                   sD   t  d ttddg  || _|| _|| _|| _|| _	|| _
d S Nr3  r  )r  r  rf  r#  r  r  r   r  r  r  r  )r  r  r   r  r  r  r  r  r   r   r    s   	
z#DynamicSelectStorageOffset.__init__r   c                 C     t | jgS r   )r9   r  r  r   r   r   rm  $  r   z3DynamicSelectStorageOffset.get_unbacked_symbol_defsFr{  c                 C  r  r   )r'   r   r+  r   r   r   r,  '  r  z/DynamicSelectStorageOffset.get_free_symbol_usesr  rr   c                 C  s   |j | | jd d S )Nrx  )codegen_dynamic_select_indexr  r  r   r   r   r  -  r   z"DynamicSelectStorageOffset.codegenrR  r>  )r  r  r   r  r  r  r  r  r  r  r  r   r   r   rp  rL  rU  r?  r   r   r   rX  r  r  r  rm  rX   r,  r  r  r   r   r  r   r    s    


r  c                      s`   e Zd ZdZdddZdddZd  fddZd!ddZed 	d"d#ddZ	d$ddZ
  ZS )%DynamicSliceSizeac  
    Computes the output size of a slice call, handling the correct semantics in codegen.
    We do this for flexible handling for unbacked indices (to not data-dependent error).

    Slicing has 4 semantics for indices, i.e. x[start:] could be:
    1) start < -x.size(0)            -> x[0:]                    # negative out-of-bounds
    2) start in [-x.size(0), 0)      -> x[x.size(0) + start:]    # negative slicing
    3) start in [0, x.size(0))       -> x[start:]                # standard slicing
    4) start >= x.size(0)            -> empty slice              # positive out-of-bounds

    If the appropriate semantics are known beforehand, the output size is computed based on
    the start & end indices. If not (with unbacked indices), a new unbacked symbol is created
    to represent the output size, and codegen handles computing the correct case.
    r   r$  c                 C  rl  r   r8   r  r   r   r   r  A  r  zDynamicSliceSize.get_readsr   c                 C  r  r  r   r  r   r   r   r  D  r  z DynamicSliceSize.should_allocateunbacked_size_symbolr  r  r  r  r  r  c                   s>   t  d ttddg  || _|| _|| _|| _|| _	d S r  )
r  r  rf  r#  r  r  r  r  r  r  )r  r  r  r  r  r  r  r   r   r  G  s   
zDynamicSliceSize.__init__r   c                 C  r  r   )r9   r  r  r   r   r   rm  W  r   z)DynamicSliceSize.get_unbacked_symbol_defsFr{  c                 C  s   t | j|t | j|S r   )r'   r  ry  r  r+  r   r   r   r,  Z  s   
z%DynamicSliceSize.get_free_symbol_usesr  rr   r   c                 C  rC  r   )codegen_dynamic_slice_sizer  r   r   r   r  b  r   zDynamicSliceSize.codegenrR  r>  )
r  r  r  r  r  r  r  r  r  r  rp  rL  rU  r?  r  r   r   r  r   r  1  s    


r  c                      sJ   e Zd ZdZdddZdddZd fddZdddZdddZ  Z	S )r   z;
    The result of a call to aten._local_scalar_dense.
    r   r$  c                 C  rl  r   r8   r  r   r   r   r  k  r  zDynamicScalar.get_readsr   c                 C  r  r  r   r  r   r   r   r  n  r  zDynamicScalar.should_allocatesymr  keypathpytree.KeyPathr_  r   r   c                   s<   |   t d ttdd| |g || _|| _d S r  )	r  r  r  rf  r#  r  r  r  r  )r  r  r  r_  r  r   r   r  q  s   
zDynamicScalar.__init__r   c                 C  r  r   )r9   r  r  r   r   r   rm  {  r   z&DynamicScalar.get_unbacked_symbol_defsr  rr   c                 C  rC  r   )codegen_dynamic_scalarr  r   r   r   r  ~  r   zDynamicScalar.codegenrR  r>  )r  r  r  r  r_  r   r   r   rp  r?  )
r   r   r   rX  r  r  r  rm  r  r  r   r   r  r   r   f  s    



r   c                      s`   e Zd ZdZdddZdddZd fddZdddZed 	ddddZ	d ddZ
  ZS )!r   z5
    The result of a call to aten._assert_scalar
    r   r$  c                 C  rl  r   r8   r  r   r   r   r    r  zAssertScalar.get_readsr   c                 C  r  r  r   r  r   r   r   r    r  zAssertScalar.should_allocatescalarro   r  r   r   c                   s,   t  d ttddg  || _|| _d S r  )r  r  rf  r#  r  r  r  )r  r  r  r  r   r   r    s   
zAssertScalar.__init__c                 C  r  r  r   r  r   r   r   r    r  zAssertScalar.has_side_effectsFr{  r   c                 C  r  r   )r'   r  r+  r   r   r   r,    r  z!AssertScalar.get_free_symbol_usesr  rr   c              	   C  s   t jsd S tt| jdd}tjjrd S tjjr;d| d}tjj	j
| jdd}|d| d| j d| d	 d S tjj	j| jdd}|d
| d |dt| j d ||   d d S )NFrz  zstd::to_string(r/  )r|  zif (!(z()) { throw std::runtime_error("Expected z but received " + z); }zif not (z):z    raise RuntimeError(z = None)rA   scalar_assertsrw  rx  r,  rm   r  r  r  r  codegen_cpp_sizevarr  r  r  codegen_python_sizevarr  r  )r  r  symbol
symbol_strsizevarr   r   r   r    s&   zAssertScalar.codegenrR  r>  )r  ro   r  r   r   r   rL  rU  r?  )r   r   r   rX  r  r  r  r  rX   r,  r  r  r   r   r  r   r     s    


r   c                   @  s   e Zd ZU ded< ded< dS )ExternKernelNoder   r   zexport_schema.Noder   Nr   r   r   r   r   r    s   
 r  c                      s   e Zd ZdZ	d<ddd= fddZd> fddZd?ddZd@ddZdAd!d"Ze	dBd&d'Z
dCd)d*ZdDd,d-ZdDd.d/Zd0d1 Zed?d2d3Ze	dEd7d8ZedFd:d;Z  ZS )GFallbackKernelz
    A class that represents a fallback kernel for handling operators that are not
    directly support by inductor. It currently supports functional ops, view ops,
    inplace aten ops, and mutating ops that are auto-functionalizable.
    Nr  r`  r0  rK  r{   r  rx  nontensor_argsr  r  rr  r   rE  r  ,Optional[dict[sympy.Symbol, pytree.KeyPath]]r   r   c                  sx  t  j|t|t||d d _|pi  _t|tjjtjj	fs.J d| dt
| d| _| _|d u r:i n| _ jd usDJ tj j g  _g  _t jtjj	r[d S d j v rdd S  jj}tjj jr| j|d   d S ddd}	|jrt js|	 jstd j   j j\}
}d fdd}tjj ||
|D ]	\}}||| qd S )Nr  F#Fails to create FallbackKernel for r.   not supported_c10d_functionalr   ro  r  r   r   c                 S  s2   t j|  t jjjpt| dot jjj| jv S )N
py_kernels)r#  _C%_dispatch_has_kernel_for_dispatch_keyr   DispatchKeyFunctionalizer  r   rn  r   r   r   has_functionalize_impl  s   
z7FallbackKernel.__init__.<locals>.has_functionalize_implz'NYI: Can't generate FallbackKernel for infotorch._C.Argumentrv  r   r   c                   s   t  jtjrt |ttfsJ t|t jr#t |ttfr#J |d u r)d S  jd u r0d S d fdd}t	 jrO|d urK|D ]}|| qDd S d S t jsWJ || d S )Nr&  r   r   r   c                   sL   j |    jd usJ  jjr$jtt|  d|  d S d S r  )	alias_namesr  r  
alias_infois_writer  r  rf  r!  r&  )r  r  r   r   	add_alias1  s   zPFallbackKernel.__init__.<locals>.handle_aliasing_and_mutation.<locals>.add_alias)r&  r   r   r   )
r   r   r#  ListTyper   r   library_utilsis_tensor_like_typer	  is_tensorlist_like_type)r  rv  r  optional_tensor_argr  )r  r   handle_aliasing_and_mutation#  s"   

z=FallbackKernel.__init__.<locals>.handle_aliasing_and_mutation)ro  r  r   r   )r  r  rv  r   r   r   )!r  r  r   use_runtime_dispatchr  r   r#  r  r  r  r   r  r  r   r  rm   r  warn_fallbackr  rR  r   r  _libraryrW  mutates_and_returns_first_argr  r  
is_mutabler$   r  rw  r  
zip_schema)r  r`  rK  r  r  r  r   r  schemar  r   r  r  rv  r  r  r   r    sV   

	
zFallbackKernel.__init__r"  c                   sH   t   }| jtjjju r"| jD ]}t|t	r!|
t| }q|S r   )r  r#  r  r#  _prims	rng_primsgraphsafe_run_with_rng_stater  r   r  	with_readrB   r  r  )r  r/  rv  r  r   r   r#  E  s   


zFallbackKernel.get_read_writesr  rr   c                 C  s   | |  | jt| dd S Nr  )(codegen_unbacked_symbol_defs_for_outputsr  r  r   r  r   r   r   codegen_unbacked_symbol_defsQ  s   z+FallbackKernel.codegen_unbacked_symbol_defsr   c                 C  >   t | dd  }rttjjj|}|d usJ t| S t S r  r   r4   rm   r  r  r   r9   rA  r  r  resolvedr   r   r   rm  V     
z'FallbackKernel.get_unbacked_symbol_defsr   c                   s   t jG dd d t| jsJ  fdd| jD }| || j\}}tjjrDt	| j
tjjrD| ||}dd t| j
jj|D }ndd |D }| j| |S )Nc                   @      e Zd ZU ded< dddZdS )	z)FallbackKernel.codegen_args.<locals>.Shimr   refr   r   c                 S  r  r   )r'  r  r   r   r   r  e  r  z2FallbackKernel.codegen_args.<locals>.Shim.__repr__NrH  )r   r   r   r   r  r   r   r   r   Shima     
 r(  c                   s   g | ]} |  qS r   r  rT  r(  r   r   r   i  r   z/FallbackKernel.codegen_args.<locals>.<listcomp>c                 S  s"   g | ]\}}t jj||jqS r   )rm   r  r  r  r  )r   paramr   r   r   r   r   m  s    c                 S  r  r   r  rT  r   r   r   r   r  r  )rY  	dataclassrd  rw  r  r  rm   r  r  r   r  r#  r  r  r  r   r  r  r   r
  )r  r  r   r   r   r*  r   r  `  s   zFallbackKernel.codegen_args Optional[Sequence[torch.Tensor]]r  r   c                 C  s   | r	dd | D nd }|r| sJ dd | D }|d S t |tjr%|jS t |ttfr`tdd |D }dd |D }t|dkrF|d S |D ]}t |tjsRJ t|j	r[|  S qH|d S d S )	Nc                 S  s   g | ]	}t |ts|qS r   )r   rm  r  r   r   r   r   }  r  z.FallbackKernel.find_device.<locals>.<listcomp>c                 S  s   g | ]
}|  r|  qS r   r  ru  r   r   r   r     rn  r   c                 s  s    | ]	}t d |V  qd S r   )r  find_devicerT  r   r   r   r     s
    

z-FallbackKernel.find_device.<locals>.<genexpr>c                 S  s   g | ]}|r|qS r   r   )r   r  r   r   r   r     r   r@   )
r   r#  r  r  r   r   r9   r   rd   r   )r  r  non_torch_bind_tensor_argsdevices
device_setr  r   r   r   r.  x  s0   
zFallbackKernel.find_devicer   c                 C  s   ddl m} || jS )Nr   )	is_impure)torch._library.utilsr2  r  )r  r2  r   r   r   r    s   
zFallbackKernel.has_side_effectsr  c                 C  sr   t | jtjjtjjfsJ d| j dt| j dt | jtjjs6d| j vr6| jjj	r6t
| jr6g S | jS )Nr  r.  r  r  )r   r  r#  r  r  r  r   r   r  r  r$   r  r  r   r   r   r4    s    
z+FallbackKernel.get_inputs_that_alias_outputc                 C  s   t | jdks	J | jS r  )r   rR  r  r   r   r   r2    s   z!FallbackKernel.get_mutation_namesc                   sf  t d j ttsJ tjj	\}
|}fddjD }j}tjjs=g ||S tdg }|||}ddd t|tjjjrb||d |d j}n|jj}t|dkrjrrjnj}|d j} ||g}	n fddt|jD }	jdusJ t tjj  ||	i dd}
tj!"|
 g ||S )a  
        ProxyExecutor Design Note
        We export the ExternFallbackNodes (for custom ops) into a serialized file
        and run it with a host side proxy executor to address the ABI problem
        This is currently only implemented for fbcode. Eventually, we will also make this work for OSS.
        Detailed design doc can be found at
        https://docs.google.com/document/d/1wC4DOZFaYym2t1Esz0X5yxlLI3RDnSiyRbUus3bkJ64/edit?usp=sharing
        z4Extern kernel node added for node %s with target %s.c                   s   g | ]}j |fi  qS r   r  r  r   r  r   r   r     r  z<FallbackKernel.export_extern_kernel_node.<locals>.<listcomp>Nreturn_type6Union[torch.TensorType, torch.ListType, torch.JitType]rm  Union[IRNode, Sequence[IRNode]]r   export_schema.Argumentc                 S  sn  t | tjtjfrE|}t |ttfrt|dksJ |d }t | tjr8t |ts+J tj	j
tj| ddS |d u s>J tj	j
ddS t | tjrjt |  tjrjt |ts^J t|tj	j
dd |D d	S t | tjrt |  tjr|d u rtj	j
tjj
ddd
S t |tsJ tj	j
tjj
tj| ddd
S t | tjrtj	j
|dS tdt|  )Nr@   r   r   )	as_tensorT)as_nonec                 S  s   g | ]
}t j| d qS )r   )export_schemaTensorArgumentr  )r   r  r   r   r   r     s    zZFallbackKernel.export_extern_kernel_node.<locals>.handle_single_output.<locals>.<listcomp>)
as_tensors)as_optional_tensor)as_intzUnsupported return type )r   r#  
TensorTypeNoneTyper   r   r   r   r;  rp   r  r<  r  r  getElementTyper   r   OptionalTypeOptionalTensorArgumentIntTypeRuntimeError)r5  rm  r  r   r   r   handle_single_output  sR   

zFFallbackKernel.export_extern_kernel_node.<locals>.handle_single_outputr   r@   c                   s   g | ]
\}} |j |qS r   )r  )r   return_schemarm  )rG  r   r   r      s    )r^  rw  r  rU  )r   r   )r5  r6  rm  r7  r   r8  )#r=  r  r  r  r   r  r   r  rw  r  r  r  rm   r  aot_moder#   serialize_inputsr#  r  	torchbindCallTorchBindr  returnsr  r   r  r  r  r   r  r;  r7   r   extern_kernel_nodesr  )r  r   ordered_kwargsr^  
serializernamed_argumentsrM  r  r5  output_argumentsr   r   )rG  r   r  r   export_extern_kernel_node  sN   	

5



z(FallbackKernel.export_extern_kernel_nodec                   s  j }|dus	J |jdkr5t|tjjsJ t|tjj	r4ddl
m} t||vr4td| d_n|jdkrHt|tjjsGJ t|ntjj	rS|tjjv_tjj	rt|tjjrjsd fdd jj\}t|fddjD }t fddt||jjD _| jrƈ }jdusJ j dusJ | ! jfddj |j"rj"nj# n|$ tj%t&r'| (| )| *| dS )r  Nr  r   )inductor_fallback_opszG%s is missing a c-shim implementation, using proxy executor as fallbackT
_quantizedr&  torch.JitTyper   r   c                   s$   t | tjr |  S t | tjS r   )r   r#  rC  rB  
NumberTyper  	is_numberr   r   rY  X   s   z)FallbackKernel.codegen.<locals>.is_numberc                 3  s"    | ]}j |fi  V  qd S r   r  r  r4  r   r   r   e   r  z)FallbackKernel.codegen.<locals>.<genexpr>c                 3  s(    | ]\}}t |to |jV  qd S r   )r   complexr  )r   r  r  rX  r   r   r   j   s
    
c                     s   g      S r   )r  r   r   r  r   r   r#  x   r   z(FallbackKernel.codegen.<locals>.<lambda>)r&  rV  r   r   )+r  r  r   r#  r  r  r   rm   r  r  torchgen.aoti.fallback_opsrT  r   r=  r  r  rA   r  custom_ops_to_c_shimsr  rw  r  rV  r  r  r  r   r  r  r  rS  r  ,generate_fallback_kernel_with_runtime_lookupr  r  r  generate_fallback_kernelr`  r  r)  r,  r0  r   )r  r  rK  rT  r   	args_iterexported_argsr   )rY  r   r  r   r  1   sl   










zFallbackKernel.codegenrm  r  rb  c                 C  sJ   d}z|   }W n	 ty   Y nw t| j| jt|  t|  |dS )NFrQ  )rd  rF  rb  r  r  rZ   r  r  )rm  rd  r   r   r   tensor_to_layout   s   

zFallbackKernel.tensor_to_layoutr   c              	     sb  t jf}||vrttd tjj}nt }|  j|g|R i |\}}}}	}
W d   n1 s3w   Y  t	dd |D  
||}|s]t|tjjjsX|tjjju r]td}|du rp t|d||||	||
dn|svJ d t|d||||	||
dd fdd|g }t|ttfr|_|S t|trt|_|S |g_|S )z9Create an instance of FallbackKernel from an _OpOverloadsNc                 s  r  r   )r3  ru  r   r   r   r      r  z(FallbackKernel.create.<locals>.<genexpr>r3  r  r   r  z"Not sure where to find device inform  r   r0  list[tuple[Any, int]]r   c                   s   t ttfrt fddttD S t tr, fdd D S t tj	rNt
 }tjsDsDtsLtjj|j |S t trUS t tjr_jjS d u smJ dt dd S )Nc                 3  s,    | ]} | t |fg V  qd S r   r   r   generate_outputr0  rm  r   r   r      s
    
zAFallbackKernel.create.<locals>.generate_output.<locals>.<genexpr>c                   s*   i | ]\}}| |t |fg qS r   rd  )r   r&  rd  re  r   r   r      r  zBFallbackKernel.create.<locals>.generate_output.<locals>.<dictcomp>zFallbackKernel output type z is not supported)r   r   r   r   r   r   r   r  r#  r  MultiOutputra  rA    assume_unaligned_fallback_outputrj   rm   r  r5  r  r   r   r  r   r  )rm  r0  r2  r  rf  has_unaligned_inputpacked)r0  rm  r   rf     s<   



z.FallbackKernel.create.<locals>.generate_output)rm  r   r0  rc  r   r   )r  *_fused_moving_avg_obs_fq_helper_functionalr   r   rm   r  r  r	   r  r  r.  r   r#  r  rK  rL  rk   higher_orderprintr  rf  rG  r   r   r  r   )r  rK  r   r   fake_incorrect_kernelscontextr  r  r  r  r  r  r  r   ri  r   r     sd   


"

zFallbackKernel.creater   r`  r0  rK  r{   r  rx  r  r  r  rr  r   rE  r  r  r   r   rQ  r?  rp  rA  )r  r-  r  r  r   r   r>  rW  )rm  r  r   rb  )rK  r{   r   r   r   r   r   r  )r   r   r   rX  r  r#  r   rm  r  r[  r.  r  r4  r2  rS  r   r  ra  r  r  r  r   r   r  r   r    s,    	w






yUr  c                      s>   e Zd ZdZdddZdddZd	d	d
d fddZ  ZS )ComplexViewz9View a complex number as two dtyped numbers or vice versar   r   c                 C  r  r  r   r  r   r   r   r     r  zComplexView.should_allocater  c                 C  r  r  r  r  r   r   r   r4  !  r9  z(ComplexView.get_inputs_that_alias_outputNrb  r`  r0  rK  r{   r  rx  r  r  r  rr  r   r  r  r  r   c             	     s   t  j|||||||d d S )Nrb  )r  r  r  r`  rK  r  r  r  r   r  r  r   r   r  !  s   
zComplexView.__init__r>  rW  )r`  r0  rK  r{   r  rx  r  r  r  rr  r   r  r  r  r   r   )r   r   r   rX  r  r4  r  r  r   r   r  r   rr     s    

rr  c                   @  s   e Zd ZdZd	ddZdS )
MemoryCheckKernelz
    Custom kernel for memory checking that generates direct function calls

    TODO - the custom op was erroring with str inputs. should be able to custom op directly.
    r  rr   r   r   c                 C  sl   |   | j\}}}t|}t|}|r&|d d| d| d| d}n	d| d| d}|| dS )z.Override codegen to write direct function callzV# note: dont currently distinguish between buffers returned and dealloc'd in last stepzcheck_memory_step(allocated=z, freed=z, is_final_step=r/  N)r/  r  r  r  )r  r  
alive_list	dead_listis_final_step
alive_repr	dead_reprcallr   r   r   r  "!  s   zMemoryCheckKernel.codegenNr?  )r   r   r   rX  r  r   r   r   r   rt  !  s    rt  c                   @  r&  )	rG  r  r  r   r  c                 C  r  r   r  r  r   r   r   r!  8!  r  zMultiOutputLayout.get_deviceNrC  )r   r   r   r   r!  r   r   r   r   rG  4!  r)  rG  c                      sV   e Zd ZdddZ	dd fddZed 	ddddZdddZd ddZ  Z	S )!rg  r  rr   r   r   c                 C  s,   | |  | js| | | | d S d S r   )codegen_multi_output!skip_size_stride_alignment_checksr)  r,  r  r   r   r   r  =!  s
   

zMultiOutput.codegenFr`  r0  rf  r   r0  list[tuple[Any, ...]]r|  r   c                   s>   t  d ||gd tj| | _tj|  || _|| _d S r  )	r  r  rm   r  r  r   r  r0  r|  )r  r`  rf  r0  r|  r  r   r   r  C!  s
   
zMultiOutput.__init__r{  r   c                 C  s&   | j d }t|tsJ |||S r  )rw  r   r   r,  )r  r{  r  r   r   r   r,  P!  s   

z MultiOutput.get_free_symbol_usesc                 C  s   t | jdkot| jd tS )Nr@   r   )r   rw  r   rF  r  r   r   r   r  X!  s   zMultiOutput.should_allocater  c                 C  s   dd | j D S )Nc                 S  s.   g | ]}t |trt| d kr| qS r  )r   r  r   r4  r  r   r}  r   r   r   r   ^!  s    z<MultiOutput.get_inputs_that_alias_output.<locals>.<listcomp>)rw  r  r   r   r   r4  ]!  s   z(MultiOutput.get_inputs_that_alias_outputr?  rL  )
r`  r0  rf  r   r0  r}  r|  r   r   r   rU  r>  rW  )
r   r   r   r  r  rX   r,  r  r4  r  r   r   r  r   rg  <!  s    

rg  c                   @  s  e Zd ZU dZded< dvddZdwd	d
ZdxddZdyddZdzddZ	d{ddZ
d|d}ddZd~dd Zdd!d"Zdd#d$Zdvd%d&Zdd'd(Z	)ddd-d.Zdd/d0Zdd2d3Z	)ddd5d6Zdd8d9Zdd;d<Zdd=d>Zdd@dAZddCdDZddFdGZdvdHdIZdvdJdKZddNdOZddQdRZd{dSdTZddUdVZ ddWdXZ!e"d 	)ddd[d\Z#dd^d_Z$ddadbZ%d|ddedfZ&e'ddhdiZ(ddkdlZ)ddmdnZ*ddodpZ+e'ddrdsZ,d{dtduZ-e-Z.dS )ro  zC
    TensorBox / StorageBox allow in-place mutation of Tensors
    r   r_  r   r   c                 C  rB  r   rH  r  r   r   r   r  p!  r(  z!MutableBox.has_exceeded_max_readsr  c                 C  rB  r   rE  r  r   r   r   r!  s!  r(  zMutableBox.get_devicer  c                 C  rB  r   r  r  r   r   r   r  v!  r(  zMutableBox.make_loaderr	  c                 C  rB  r   )r_  r
  r  r   r   r   r
  y!  r(  zMutableBox.make_indexerrM  c                 C  rB  r   )r_  rC  r  r   r   r   rC  |!  r(  zMutableBox.get_strider   c                 C  rB  r   rF  r  r   r   r   r  !  r(  zMutableBox.get_nameNr  r  c                 C  r7  r   )r_  r  r  r   r   r   r  !  r   zMutableBox.has_large_inner_fnr  r   r   c                 C  r7  r   rG  r  r   r   r   r  !  r   zMutableBox.mark_reusec                 C  rB  r   rJ  r  r   r   r   r  !  r(  zMutableBox.realize_hintc                 C  rB  r   )r_  r  r  r   r   r   r  !  r(  zMutableBox.unwrap_viewc                 C  rB  r   )r_  r  r  r   r   r   r  !  r(  zMutableBox.is_input_bufferc                 C  rB  r   )r_  r  r  r   r   r   r  !  r(  zMutableBox.freeze_layoutFr   r   r  c                 C     | j ||S r   )r_  r  r  r   r   r   r  !  r  z*MutableBox.freeze_layout_with_stride_orderc                 C  r7  r   )r_  r  r  r   r   r   r  !  r   z(MutableBox.freeze_layout_with_fill_orderr  c                 C  r7  r   )r_  r  r  r   r   r   r  !  r   z(MutableBox.freeze_layout_with_same_orderr  c                 C  r  r   )r_  r!  r   r   r   r   r!  !  r  z+MutableBox.freeze_layout_with_exact_stridesr"  c                 C  rB  r   )r_  r#  r  r   r   r   r#  !  r(  zMutableBox.get_read_writesr$  c                 C  rB  r   r  r  r   r   r   r  !  r(  zMutableBox.get_readsc                 C  rB  r   r  r  r   r   r   r)  !  r(  zMutableBox.num_readsry   c                 C  rB  r   rK  r  r   r   r   r*  !  r(  zMutableBox.get_storage_numelr-  c                 C  rB  r   r  r  r   r   r   r-  !  r(  zMutableBox.get_reduction_typer  c                 C  rB  r   r  r  r   r   r   r.  !  r(  zMutableBox.get_reduction_sizec                 C  rB  r   rL  r  r   r   r   r/  !  r(  zMutableBox.is_externc                 C  rB  r   )r_  r0  r  r   r   r   r0  !  r(  zMutableBox.is_no_opr  r  c                 C  r7  r   r  r  r   r   r   r1  !  r   zMutableBox.constant_to_devicer  c                 C  rB  r   )r_  r2  r  r   r   r   r2  !  r(  zMutableBox.get_mutation_namesc                 C  rB  r   )r_  r3  r  r   r   r   r3  !  r(  zMutableBox.get_operation_namec                 C  rB  r   )r_  r4  r  r   r   r   r4  !  r(  z'MutableBox.get_inputs_that_alias_outputc                 C  rB  r   rI  r  r   r   r   r  !  r(  zMutableBox.realizer{  r   c                 C  r7  r   r8  r+  r   r   r   r,  !  r  zMutableBox.get_free_symbol_usesr  c                 C  rB  r   rN  r  r   r   r   r  !  r(  zMutableBox.get_read_namesr  c                 C  rB  r   )r_  r  r  r   r   r   r  !  r(  zMutableBox.get_defining_opr  r  c                 C  r7  r   )r_  r  r  r   r   r   r  !  r   zMutableBox.codegen_referencer0  c                 C  rB  r   r_  r  r  r   r   r   r`  !  s   
zMutableBox.layoutr  c                 C  rB  r   rD  r  r   r   r   r  !  r(  zMutableBox.get_layoutc                 C  rB  r   r  r  r   r   r   r  !  r(  zMutableBox.get_output_specc                 C  rB  r   r  r  r   r   r   r  !  r(  zMutableBox.get_sizer  c                 C  r  r   )r_  r  r  r   r   r   r  !  r  zMutableBox.dtypec                 C  sn   t | jtrt| j dt| jj d}d}| jj}nt| j d}| j}d}|tt||g}d|S )Nr  z))r/  r  )r   r_  ro  r   r   r  r   r  )r  line0endlr>  r  r   r   r   r  !  s   


zMutableBox.__str__r>  rC  rE  rF  rG  rH  r   rI  rJ  r6  rK  rL  rM  rN  rO  rP  rQ  rR  rS  rT  rA  r?  rV  rW  rU  r7  r9  rB  r=  r<  r;  )/r   r   r   rX  r   r  r!  r  r
  rC  r  r  r  r  r  r  r  r  r  r  r!  r#  r  r)  r*  r-  r.  r/  r0  r1  r2  r3  r4  r  rX   r,  r  r  r  r^  r`  r  r  r  r  r  r  r   r   r   r   ro  h!  sb   
 































ro  c                   @  s>   e Zd Zeed
ddZeedddZedddZd	S )r~   r_  r   r   c                 C  r
  r   r   r_  r   r   r   r  "  r  zTensorBox.creater   c                 C  r
  r   r   r  r   r   r   r  "  r  c                 C  s   t | tr| S tt| S r   )r   r   r~   r  r  r   r   r   r  "  s   
N)r_  r   r   r   )r_  r   r   r~   )r_  r   )r   r   r   r   r[  r  r   r   r   r   r~    "  s    c                   @  sj   e Zd ZdZdddZdddZdd	d
ZdddZdddZdddZ	d ddZ
d!ddZd"ddZdS )#r  z7
    StorageBox allow in-place mutation of Tensors
    r   r   c                 C  s&   t | jttfr| j tjjv S dS r  )r   r_  r  re  r  rm   r  r  r  r   r   r   r  "  s   zStorageBox.is_input_bufferc                 C  s   t | jto| j tjjv S r   )r   r_  r  r  rm   r  r  r  r   r   r   rM  "  s   zStorageBox.is_module_bufferr-  c                 C  s   t | jr| j S t| jttttfsJ t	| j| j
 }| j }| j }|d us1J td t|| j | j dd| jd| _tj| j| j_tj| j | j| j_|| j_|| j_| jjS )NF)r  r  r  rd  r   )r   r  r_  r  r   r  r  r  r  r   r  r  r!  r  r  r   r  rm   r  r  r   r  r  r  r  )r  r  r  r  r   r   r   r  "  s2   





zStorageBox.realizer   c                 C  s4   t | jttfr| j jdkr|   dS dS dS )zL
        Called on buffers we expect to be forced to realize later.
        r@   N)r   r_  r  r  r  nontrivial_read_countr  r  r   r   r   r  <"  s   zStorageBox.realize_hintr  r   c                   s^   ddl m   fdd|  D }|sdS t|}t|}t|}||ko.|| dko.||kS )Nr   is_nonfreeable_buffersc                   s    g | ]} |st j|qS r   )rm   r  get_dep_size_hintr  r  r   r   r   I"  s    
zCStorageBox.has_accumulated_enough_reads_by_size.<locals>.<listcomp>Fr   )r_  r  r  r  r  r  )r  r  size_of_reads
total_sizemax_sizemin_sizer   r  r   $has_accumulated_enough_reads_by_sizeF"  s   

z/StorageBox.has_accumulated_enough_reads_by_sizec                 C  s8   t | jto|  tjkp|  ptjd uo| tjS r   )	r   r_  r  r)  rA   realize_acc_reads_thresholdr   realize_acc_reads_size_thresholdr  r  r   r   r   r  Y"  s   
z!StorageBox.has_exceeded_max_readsr  c                   sh   |dkr2t | jttfr2t| jr'| j  ddg}t fdd|D r'dS |  tj	kp1| 
 S dS )zj
        A heuristic to decide if we should realize a tensor
        that is used multiple times.
        r@   expsigmoidc                 3  s    | ]}| j v V  qd S r   )used_opsrT  opcountr   r   r   o"  rx  z5StorageBox.should_realize_on_reuse.<locals>.<genexpr>TF)r   r_  r  r  r<  r  r  r)  rA   realize_reads_thresholdr  )r  r  	heavy_opsr   r  r   should_realize_on_reusee"  s   

z"StorageBox.should_realize_on_reusec                 C  s   |  |r|   d S d S r   )r  r  r  r   r   r   r  w"  s   
zStorageBox.mark_reusec                 C  rB  r   r  r  r   r   r   r)  {"  r(  zStorageBox.num_readsNr>  rA  r6  )r  r   r   r   )r  r   r   r   rJ  rS  )r   r   r   rX  r  rM  r  r  r  r  r  r  r)  r   r   r   r   r  "  s    








r  c                   @  s*   e Zd ZU ded< ded< dZded< dS )Subgraphr   r   rl  graph_moduleNzOptional[GraphLowering]r  )r   r   r   r   r  r   r   r   r   r  "  s   
 r  buffersc                 C  s,   dd | D } t tdd | D t | k S )Nc                 S  "   g | ]}t |tr| n|qS r   r   re  r  r   r0  r   r   r   r   "      z(_has_aliased_buffers.<locals>.<listcomp>c                 s  r  r   )r`  r  r   r   r   r   "  r  z'_has_aliased_buffers.<locals>.<genexpr>)r   r9   )r  r   r   r   _has_aliased_buffers"  s   r  c                      s`   e Zd ZU dZdZded< dZded< dZded< d fddZe	dddZ
dddZ  ZS )InvokeSubgraphz.
    Ir node for the invoke_subgraph HOP.
    NOptional[Subgraph]ru  Optional[Sequence[IRNode]]operandsr  r  rx  r`  rG  r   r   c                   s6   t  jd ||d || _tj| | _tj|  d S r  )r  r  ru  rm   r  r  r   r  )r  ru  r  r`  r  r   r   r  "  s   zInvokeSubgraph.__init__r   Elist[Union[ShapeAsConstantBuffer, NoneAsConstantBuffer, MultiOutput]]c                   s  ddl m} tjj}d}|jd }r5d}|jtj	j
ju r,|jd tj	j
ju s*J d}|d |d }n&d}|jtj	j
ju rM|jd tj	j
ju sKJ d}|j|d }d	d
 |D } fdd
|D }g }	t|D ]\}
}t|ttfr{|	| qj|	||||
  qj|	}|jdu rtjj|j||jd|_t|j |jj|  W d   n1 sw   Y  |jj}d}|D ]}t|ts| } nq|dusJ t||t|dddfddfdd
t|D }|_|S )zFor each operand, get a realized input, force it to have the same
        strides as the subgraph inputs, then use an InvokeSubgraphr@   )constrain_to_fake_tensorNeager_input_valsr   r   r   r   c                 S     g | ]}|j d  qS rf  rs  rT  r   r   r   r   "  r   z)InvokeSubgraph.create.<locals>.<listcomp>c                   r
  r   r  rT  r  r   r   r   "  r   rk  rj  rl  r  )ru  r  r`  rm  r   indr   r   ?Union[ShapeAsConstantBuffer, NoneAsConstantBuffer, MultiOutput]c              	     sd   t | ttfr	| S |  }|d usJ tt||  |  |  | 	 j
| 	 jd t|fgddS )Nrd  T)r|  )r   r   r  r!  rg  rb  r   r  rC  r  rc  rd  r   )rm  r  r  )invoke_subgraphr   r   create_output"  s"   z,InvokeSubgraph.create.<locals>.create_outputc                   s   g | ]	\}} ||qS r   r   )r   r   rm  )r  r   r   r   #  r  )rm  r   r  r   r   r  )r  r  rm   r  ry  rs  r  r^  r#  rk   rm  r  r   r  r   r   r   r  r  rt  r  r   ry  rz  graph_outputsr!  r  rG  r  )r  ru  r  r  ry  fake_operandsr  rc  fx_operandsnew_operandsr   operandr  r  outsr   )r  r  r  r   r  "  sd   

zInvokeSubgraph.creater  rr   c                 C  rC  r   )codegen_invoke_subgraphr  r   r   r   r  #  r   zInvokeSubgraph.codegen)ru  r  r  rx  r`  rG  r   r   )ru  r  r  r   r   r  r?  )r   r   r   rX  ru  r   r  r  r  r  r  r  r  r   r   r  r   r  "  s   
 fr  c                      s   e Zd ZU dZdZded< dZded< dZded< dZded	< dZ	d
ed< d* fddZ
ed+ddZed,d!d"Zd-d%d&Zd.d(d)Z  ZS )/Conditionala  
    IR node representing torch.cond

    Attributes:
        predicate: A boolean scalar tensor determining which branch to execute.
        operands: Input tensors passed to both true and false subgraphs.
        true_subgraph: Subgraph executed when predicate is True.
        false_subgraph: Subgraph executed when predicate is False.
        outputs: MultiOutput nodes representing the conditional's outputs.
    Nr  	predicater  r  r  true_subgraphfalse_subgraphOptional[Sequence[MultiOutput]]r  r   rx  r  r`  rG  r  r  r   r   c           	        sj   || _ || _|| _|| _t|g|\}}t jd |||d |d ur&|| _tj	
| | _tj	|  d S N)r   r`  rw  r  )r  r  r  r  _split_by_sym_typer  r  r  rm   r  r  r   r  )	r  r  r  r  r  r`  r  sym_argsr  r  r   r   r  ##  s   	zConditional.__init__r   Union[int, torch.SymInt]Union[int, sympy.Expr]c                 C  s   t | tr| S | jjS r   )r   r   r   r  )r   r   r   r   _maybe_expr?#  s   
zConditional._maybe_exprr~   true_fnfalse_fnlist[TensorBox]list[MultiOutput]c              	     s    |} fdd|D }tjjjd }t|ts J t|tdd |D s+J dd |D }tjjj	d }ddd}||fD ]8}	|	jdu rztjj
|	j||	jd|	_t|	j |	jj|  ||	jj||	j_W d   n1 suw   Y  qB|jdusJ |jdusJ |jj}
|jj}d|
fd|ffD ]\}}t|
rtd| d| qt|
t|ksJ |
|ftt|
|D ]5\}\}}| | ksJ |||f| | ksJ |||f| j| jksJ |||fqtdd ||g D ttjjjtjjj	dd}dusJ dt||||td|dfddtt|
tjjj	d D }|_ |S )zNCreate a Sequence of IRNodes from a conditional statement (see .lowering.cond)c                   r
  r   r  rT  r  r   r   r   Q#  r   z&Conditional.create.<locals>.<listcomp>rA  c                 s  r  r   )r   r7   ry  r   r   r   r   U#  rx  z%Conditional.create.<locals>.<genexpr>c                 S  s   g | ]
}t t|jd  qS rf  )r   r7   rs  rT  r   r   r   r   V#  rn  rd  r  rx  fake_tensorsSequence[torch.Tensor]r   r   c                 S  sP   g }t | |D ]\}}t|tr|| q|tjt|| dd q|S NFr/  )r   r   r   r  r  r  r~   r  )r  r  retrm  r  r   r   r   _require_exact_stridesY#  s   
z2Conditional.create.<locals>._require_exact_stridesNr  r  r  zVOutput aliasing is currently not supported in compiled torch.cond. The outputs of the z% subgraph of torch.cond are aliased: c                 s  s"    | ]}t |ts| V  qd S r   )r   r   r!  )r   or   r   r   r   #  s    
r  zcannot determine devicer  )r  r  r  r  r`  r  c                   sv   g | ]7\}\}}t t| d ur| n| dd | D dd | D | j| jd t	|fgqS )Nc                 S  rZ  r   r  r  r   r  r   r   r   r   #  r   z1Conditional.create.<locals>.<listcomp>.<listcomp>c                 S  rZ  r   r  r  r   r   r   r   #  s    
rd  )
rg  rb  r!  r   r  r  r  rc  rd  r   )r   r   rm  merged_output)conditionalr  r   r   r   #  s&    
)r  rx  r  r  r   r   )!rk  rm   r  ry  r   r   r   r   r   rs  rt  r  r   ry  rz  r  r  rv  r   r   r   r!  r   r  rc  rw  r4   r  r   r  r  rG  r  )r  r  r  r  r  r  r  fake_outputsr  ru  true_outputsfalse_outputsr   r  r   t_of_or  r   )r  r  r  r   r  E#  s   




	$	zConditional.creater  rr   c                 C  s*   | |  ||  | jt| di  d S r  )codegen_conditionalr  r  r  r   r  r   r   r   r  #  s   
zConditional.codegenr   c                 C  r!  r  r"  r#  r   r   r   rm  #  r%  z$Conditional.get_unbacked_symbol_defs)r  r   r  rx  r  r  r  r  r`  rG  r  r  r   r   )r   r  r   r  )
r  r~   r  r  r  r  r  r  r   r  r?  rp  )r   r   r   rX  r  r   r  r  r  r  r  r[  r  r  r  r  rm  r  r   r   r  r   r  #  s   
 
|r  r   rk  -tuple[list[ShapeAsConstantBuffer], list[Any]]c                 C  s<   g }g }| D ]}t |tr||j q|| q||fS r   )r   r   r  r  )r   non_sym_argsr  rv  r   r   r   r  #  s   
r  c                      s   e Zd ZU dZdZded< dZded< dZded< dZded< dZ	d	ed
< d) fddZ
ed*ddZed+ddZed,d d!Zd-d$d%Zd.d'd(Z  ZS )/	WhileLoopzSThe IR node for while_loop and while_loop_stack_output. It supports input mutation.Nr  carried_inputsadditional_inputsr  cond_subgraphbody_subgraphr  r  rx  r  r`  rG  r  r  stack_outputr   r   r   c           
        sr   || _ || _|| _|| _tg ||\}}	t jd ||	|d |d ur'|| _|| _t	j
| | _t	j
|  d S r  )r  r  r  r  r  r  r  r  r  rm   r  r  r   r  )
r  r  r  r  r  r`  r  r  r  r  r  r   r   r  #  s$   

zWhileLoop.__init__c                 C  sr   t | s| S dd | D }t }g }t| |D ]\}}t||v r*|t| q|t| || q|S )Nc                 S  r  r   r  r  r   r   r   r   $  r  z3WhileLoop._clone_aliased_inputs.<locals>.<listcomp>)r  r9   r   r`  r  r  r  r  )r  unwrapped_buffersseen_buffersr  original_inputunwrapped_bufferr   r   r   _clone_aliased_inputs$  s   zWhileLoop._clone_aliased_inputsr  r   c                 C  sJ   t | tr| S t | ttfrt| S t | trt| S tdt|  )NzNYI unsupported output type: )r   r~   r  re  rg  r  rF  r   )r  r   r   r   _maybe_wrap_as_tensor_box'$  s   


z#WhileLoop._maybe_wrap_as_tensor_boxcond_fnbody_fnr7  c           &   	     s  ddl m} d*d	d
}tjjjd }tjjjd }	||	 }
dd |
D }dd |D }dd |	D }fdd|D }t|}|||}fdd|D }|||}||  ||fD ]S}|jdu rt|
t	smJ t
|
tjj|j|
|jd|_t|j' |jj|  ||u rt|jjt|ksJ ||jj||j_W d   n1 sw   Y  q[|jr|jsJ |jj}|jj}t|rtd| t|dksJ ||d }t|ts| tjksJ |t| dksJ |t dksJ d d  }|dusJ t|t|ksJ ||ftt||D ]?\}\}}d+dd}|| |  || |  | | ksOJ ||||f| | ks_J |||fq!|dushJ ttjjjtjjj !dd}t||||t"|d||d }|jdurt|jj#tj$j%sJ ||jj#|d! }t&|} fd"d|D }t'|}g }g |_(g |_)|rt|dksJ d#ttjjj d$ D ]/\} }!t*t+|!j,|!j-d%d |!. D d&d |!/ D d'|t0| fg}"|j(1|" |1|" qnVt|D ]Q\} }!| |v r/| t|k sJ d(t2|}#|j)1t3|#j4|#| |1|# qt*t+|! |! |! |! |!5 j6d)|t0| fg}"|j(1|" |1|" qt||D ]\}$}%|$7 tjj8v rrtjj9:|%7  q\|S ),zcreate the while_loop IR node. stack_output controls whether it stack
        each iterations' output, which is necessary for training.
        r   )check_input_alias_and_mutationtensor_boxesrx  r  ,list[Union[int, torch.SymInt, torch.Tensor]]r   r   c                 S  sl   t | t |ks
J g }t| |D ]"\}}t|tjr.t|}|tj	||
 dd q|| q|S r  )r   r   r   r#  r  r  r  r  r  r  r  )r  r  r  r  fknew_tbr   r   r   r  @$  s   

z0WhileLoop.create.<locals>._require_exact_stridesrA  c                 S  r  rf  r  rT  r   r   r   r   `$  r   z$WhileLoop.create.<locals>.<listcomp>c                 S  r  rf  r  rT  r   r   r   r   a$  r   c                 S  r  rf  r  rT  r   r   r   r   b$  r   c                   r
  r   r  rT  r  r   r   r   d$  r   c                   r
  r   r  rT  r  r   r   r   g$  r   Nr  zOutput aliasing is currently not supported in compiled torch.while_loop. The outputs of the body_fn subgraph of torch.while_loop are aliased: r@   z9torch.while_loop is assumed to have at least one operand.	lhs_exprs Sequence[Union[int, sympy.Expr]]	rhs_exprsr   c                 S  s<   t | t |ks
J t| |D ]\}}tjj|| qd S r   )r   r   rm   r  r  r  )r  r  lhsrhsr   r   r   _guard_list_equals$  s   z,WhileLoop.create.<locals>._guard_list_equalsr  r  )r  r  r  r  r`  r  r  r   c                   r   r   r   )r   r   )
all_inputsr   r   r   $  r   z-NYI: while_loop_stack_output input mutations.rd  c                 S  rZ  r   r  r  r   r   r   r   $  r   c                 S  rZ  r   r  )r   r  r   r   r   r   $  r   )r  r  r  r  zonly carries can be mutated.)r  r  r  r  rc  )r  rx  r  r  r   r   )r  r  r  r  r   r   );torch._higher_order_ops.utilsr  rm   r  ry  r   r  r  r   r   r   rt  r  r   ry  rz  r   r  r  rv  r   r   r#  r   r  r!  r   r   rC  r4   r  r   rs  r  rG  modulefxGraphModuler9   rx  r  r  rg  rb  r  r  r  r  r   r  rw  r  r`  r  rc  r  r  r  r  )&r  r  r  r  r  r  r  r  fx_carried_inputsfx_additional_inputsfx_all_inputsfake_all_inputsfake_carried_inputsfake_additional_inputscarried_inputs_additional_inputs_ru  cond_outputsbody_outputsr  r  r   ro  bor  r  
while_loopmutated_idxsmutated_idx_setr  mutated_inputs_iterall_outputsr   rm  	multi_outmutated_inputr}  r  r   )r  r  r   r  2$  s  






"$


zWhileLoop.creater  rr   c                 C  s.   | | | j ||  | jt| di  d S r  )codegen_while_loopr  r  r  r  r   r  r   r   r   r  %  s   zWhileLoop.codegenr   c                 C  r!  r  r"  r#  r   r   r   rm  %  r%  z"WhileLoop.get_unbacked_symbol_defs)r  rx  r  rx  r  r  r  r  r`  rG  r  r  r  r   r   r   )r  rx  r   rx  )r  r   r   r   )r  r  r  r  r  rx  r  rx  r  r   r   r7  r?  rp  )r   r   r   rX  r  r   r  r  r  r  r  r[  r  r  r  r  r  rm  r  r   r   r  r   r  #  s"   
 "
 
Zr  c                      s@   e Zd Z	dddd fddZd fddZdddZ  ZS )r   Nr  r`  r0  rK  r{   r  rx  r  r  r  rr  r   rE  r  r  r   r   c          
   	     sb   t  j|||||d |d ddlm} ||}	|	d usJ |	| _tjj|	d | _	| tjj|	< d S )Nrb  r   )_get_effect)
r  r  torch._higher_order_ops.effectsr	  effect_typerm   r  effectful_opsr  prev_effect_buffer)
r  r`  rK  r  r  r  r   r  r	  r		  r  r   r   r  %  s   
zEffectfulKernel.__init__r"  c                   s0   t   }| jd ur|jt| j  |S r   )r  r#  r	  r'  r  rB   r  r  )r  r/  r  r   r   r#  ;%  s   

zEffectfulKernel.get_read_writesr   c                 C  r  r  r   r  r   r   r   r  E%  r  z EffectfulKernel.has_side_effectsr   rq  rQ  r>  )r   r   r   r  r#  r  r  r   r   r  r   r   %  s    	
r   c                   @  s"   e Zd Zed 	d	d
ddZdS )r  Fr{  r   r   r   c                 C  rl  r   r8   r+  r   r   r   r,  J%  r  z!NonTensorObj.get_free_symbol_usesNrL  rU  )r   r   r   rX   r,  r   r   r   r   r  I%  s    r  c                   @  sR   e Zd ZU ded< ded< dddZddddZdddZdddZdddZdS )rm  r   r   +Union[FakeScriptObject, torch.ScriptObject]r'  r   c                 C  r  r   r   r  r   r   r   r  V%  r  zTorchBindObject.get_nameNr  r  c                 C  r  r   r   r  r   r   r   r  Y%  r  z!TorchBindObject.codegen_referencec                 C  r  r   r*  r  r   r   r   r  \%  r  zTorchBindObject.get_valuetorch.ScriptObjectc                 C  s   t | jtjr
| jS | jjS r   )r   r'  r#  ScriptObjectreal_objr  r   r   r   get_real_obj_%  s   zTorchBindObject.get_real_objr   c                 C  sZ   |   }t|r
dS t|dsJ t| }t|d }dd |D }tt	j
|dS )Nr   __obj_flatten__c                 S  s(   g | ]}t |tjr| |  qS r   )r   r#  r  re  numelrT  r   r   r   r   o%  s    
z1TorchBindObject.get_buf_bytes.<locals>.<listcomp>)r	  r(   r  r   r	  r  r  r9  rU  operatorr  )r  real_script_obj	flat_dict
flat_elems
flat_sizesr   r   r   get_buf_bytese%  s   zTorchBindObject.get_buf_bytesrH  r   rB  )r   r	  )r   r	  rS  )	r   r   r   r   r  r  r  r	  r	  r   r   r   r   rm  Q%  s   
 


rm  c                   @  s4   e Zd ZU ded< ded< dddZddddZdS )r  r   r   r  r  r   c                 C  r  r   r   r  r   r   r   r  |%  r  zGeneratorState.get_nameNr  r  c                 C  r  r   r   r  r   r   r   r  %  r  z GeneratorState.codegen_referencerH  r   rB  )r   r   r   r   r  r  r   r   r   r   r  w%  s
   
 
r  c                   @  sH   e Zd ZdddZdddZddddZedddZedddZdS )_CollectiveKernelr   r   c                 C  r  r  r   r  r   r   r   r  %  r  z!_CollectiveKernel.should_allocatec                 C  r  r  r   r  r   r   r   r  %  r  z"_CollectiveKernel.has_side_effectsNr  r-  r   c                 C  sR   t | jtjju sJ d| j}|d ur|| _n|jj| _dd |jjD | _	d S )Nz,Setting cpp kernel needs a valid op_overloadc                 S  r  r   r  rT  r   r   r   r   %  r  z9_CollectiveKernel.set_cpp_kernel_name.<locals>.<listcomp>)
r   r  r#  r  r  r  r  r   r  r  )r  r  rK  r   r   r   r  %  s   
z%_CollectiveKernel.set_cpp_kernel_namerK  r{   rw  Union[IRNode, list[IRNode]]r   r   r   c                   s$  t jj | j||g|R i |\}}}}}	W d    n1 s!w   Y  |	r1J | d|	 |D ]}
|
  t j|
  q3|d   | t d||||t	
|}j fdd|D  jdd |D  d|v rjtt d|d  j|d   d S d S )Nrq  r   r  c                   r  r  r  r  r  rk  r   r   r   %  r  z4_CollectiveKernel.create_inplace.<locals>.<listcomp>c                 S  r~  r   r  r~  r   r   r   r   %  r   r  )rm   r  r  r  r  rm  r  r!  rf  r  tree_leavesr  r  r  r  r  )r  rK  rw  r   r   _example_outputr  r  r  r  
tensor_arginpsr   r	  r   create_inplace%  s@   

z _CollectiveKernel.create_inplace!Union[TensorBox, list[TensorBox]]+Union[list[MultiOutput], _CollectiveKernel]c                   sJ  t jj  j||g|R i |\}}}}}	W d    n1 s!w   Y  |	r1J | d|	 |D ]}
t|
ts>|
  q3t|tr ||}|d usPJ  t	|d|||| fddt
|D _tj|D ]\}}tjsyt|st jj|j qnjS   |||||tjst|st jjj g_S )NrS  r  c                   s(   g | ]\}}t  |t|fgqS r   )rg  ra  r   )r   r   rW  r  rk  r   r   r   &  s    z9_CollectiveKernel.create_out_of_place.<locals>.<listcomp>)rm   r  r  r  r   rm  r  r   r.  rG  r   r  r   rA   rh  rj   r5  r  r   ra  )r  rK  rw  r   r   r  r  r  r  r  r	  r  r2  rW  r   r#	  r   create_out_of_place%  s^   


z%_CollectiveKernel.create_out_of_placer>  r   r@  )
rK  r{   rw  r	  r   r   r   r   r   r   )
rK  r{   rw  r!	  r   r   r   r   r   r"	  )	r   r   r   r  r  r  r  r 	  r$	  r   r   r   r   r	  %  s    

Ar	  c                      2   e Zd Z	dddd fddZdddZ  ZS )_AllReduce_KernelNr  r`  r0  rK  r{   r  rx  r  r  r  rr  r   rE  r  r  r   r   c             	     (   t  j|||||d |d | d d S )Nrb  +aoti_torch_cpu__c10d_functional_all_reduce_r  r  r  rs  r  r   r   r   &     	z_AllReduce_Kernel.__init__r  rr   c                 C  2   | d ||  t| jtr| | d S d S Nz+torch/csrc/inductor/aoti_torch/c/shim_cpu.hinclude_extra_headerrO  r   r`  r  r)  r  r   r   r   r  6&  
   

z_AllReduce_Kernel.codegenr   rq  r?  r  r   r   r  r   r&	  &      	r&	  c                      r%	  )_AllReduceKernelNr  r`  r0  rK  r{   r  rx  r  r  r  rr  r   rE  r  r  r   r   c             	     r'	  )Nrb  *aoti_torch_cpu__c10d_functional_all_reducer)	  rs  r  r   r   r  ?&  r*	  z_AllReduceKernel.__init__r  rr   c                 C  r+	  r,	  r-	  r  r   r   r   r  U&  r/	  z_AllReduceKernel.codegenr   rq  r?  r  r   r   r  r   r1	  >&  r0	  r1	  c                      sX   e Zd Z	d"ddd# fddZd$ddZd%ddZed&ddZd' fd d!Z  Z	S )(_WaitKernelNr  r`  r0  rK  r{   r  rx  r  r  r  rr  r   rE  r  r  r   r   c             	     r'	  )Nrb  +aoti_torch_cpu__c10d_functional_wait_tensorr)	  rs  r  r   r   r  ^&  r*	  z_WaitKernel.__init__r  rr   c                 C  r+	  r,	  r-	  r  r   r   r   r  t&  r/	  z_WaitKernel.codegenc                 C  s   | j d }t|tsJ t|tr$|j d }t|ts!J t||gS t|trB|j d }t|tr@|jd \}}|j | gS g S g S r  )rw  r   r   r	  r   rg  r0  )r  r}  r   collr  r   r   r   r   get_volatile_reads{&  s   





z_WaitKernel.get_volatile_readsr}  r~   c           	      C  s   t jj | ||\}}}}}W d    n1 sw   Y  |r*J | d| | t| d||||}|jtt| d|| d S )Nrq  r  )	rm   r  r  r  rf  r!  r  r  r  )	r  rK  r}  r	  r  r  r  r  rk  r   r   r   create_wait&  s(   

z_WaitKernel.create_waitr"  c                   s6   t   }|  }|D ]}|jt|  q|S r   )r  r#  r6	  r'  r  rB   r  r  )r  r/  volatile_readsvrr  r   r   r#  &  s
   
z_WaitKernel.get_read_writesr   rq  r?  rW  )rK  r{   r}  r~   r   r   rQ  )
r   r   r   r  r  r6	  r  r7	  r#  r  r   r   r  r   r3	  ]&  s    	

r3	  r   r  c                 C  d   t | ttfrt| S t | ttfr%ttj  }| D ]}|t	|O }q|S t | t
jr/t| S t S r   )r   r6   r   r1   r   r   r9   r   r!   r:  r#  r  r   r  r&  r   r   r   r:  &     r:  c                 C  r:	  r   )r   r6   r   r0   r   r   r9   r   r!   r;  r#  r  r;	  r   r   r   r;  &  r<	  r;  r  r   r  torch.fx.Nodec                 C  s   t | trht | jtrjt | jjtr| jjd| d S t | jjtrl| jjd| t | jjtrEt | jjjtrE| jjjd| d S t | jjtrn| jjj	spt | jjj
d trr| jjj
d d| d S d S d S d S d S d S d S )Nr  r   )r   r~   r_  r  rq  r  r  r  rg  r0  rw  )r  r  r   r   r   assign_origin_node&  s&   	
r>	  )r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r:  )r   r   r	  r   r   r   )r   r   r	  r   r   r  )r   r  r	  r   r   r  )r'  r(  r   r)  )r   r,  r   r-  )r   r2  r   r   )r   r=  r>  r   r   r   )rL  rM  rN  rM  rO  rM  r   r   )rW  r   rX  rY  r   r   )rk  rl  r   r   )rw  rx  r   ry  )r   r  r  r  r   rl   )r  r   r  r  r  r   r   r  )r  r   r  r  rc  r   r   r	  r  )TFNFN)r   r   r#  r   r*  r   r+  r,  r  r   r  r,  r   r-  )r   r   r+  r   r   r   r5  )r  rM  rO  rM  r   r   )r  r  r   r   )r   ra  r   rb  )r  rx  r   r   )r   rk  r   r  )r   r   r   r  )r  r   r  r=	  r   r   (O  
__future__r   r\  r  rY  r9  rV  loggingr	  textwrapr  collections.abcr   r   r   r   r   r   r	   enumr
   r   typingr   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   r   r   r   r   unittest.mockr   r   r   r    r!   torch._export.serde.schema_exportserder  r;  r3  r  rW  r  torch._loggingr#  torch.fxtorch.utils._pytree_pytreer  torch._dynamo.utilsr"   torch._export.serde.serializer#   *torch._higher_order_ops.auto_functionalizer$   torch._inductorr%   r_  r'   torch._library.opaque_objectr(   torch._prims_commonr)   r*   r+   r,   r-   %torch.fx.experimental.symbolic_shapesr.   r/   r0   r1   r2   r3   r4   r5   r6   torch.fx.noder7   torch.utils._ordered_setr9   torch.utils._python_dispatchr:   torch.utils._sympy.functionsr;   r<   r=   r>   torch.utils._sympy.symbolr?   r  rA   rB   codegen.commonrC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   	loop_bodyrM   ops_handlerrN   rO   rP   rQ   runtime.benchmarkingrR   runtime.hintsrS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   virtualizedrk   rl   rm   "torch._library.fake_class_registryrn   ro   rp   codegen.cutlass.templaterq   codegen.wrapperrr   r  rs   rt   r   r   r6  __version__r  r  ImportErrorru   rv   rw   rx   r   ry   r  rz   r  r  r  r{   	getLoggerr   r=  r  r  r   r   r   r   r,  r   r   r   r   r   r   r;  r=  r   r   r  r  r+  r1  r;  r<  rK  rV  rj  rv  r~  r  r   r_  rq  r  r  r  r  r  r  rb  r  r  r  r  r  r  r  r  r)  ra  r2  r3  r  r   r_  rk  rw  r  re  r  r  r  r  r  r  r  r0  r  rb  r  rR  r\  r`  rf  rk  r  r  r  r  r  r  r   r  r  r  r   r   PrimitiveInfoTyper  r  r   r?  rF  rI  rJ  rd  r  rr  rs  r  rB  rH  r  r  rX  r]  r^  ri  r  r  r  r  r  r  r  r  r  r  r  r   r   r  r  rr  rt  rG  rg  ro  r~   r  r  r  r  r  r  r  r   r  rm  r  r	  r&	  r1	  r3	  r:  r;  r>	  r   r   r   r   <module>   s   8 ,`
*

"	


'
	
  AK(#?      - :& _ K <
a\0D$ {V)b  % _$"Y 	
   :K*GF_]U I       %+!@(4 P-29,</5?    7 , p	  C  =,% Y