o
    i;%                    @  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)m*Z* d d	l+m,Z, d dl-Z-d d
l-m.Z.m/Z/m0Z0 d dl1m2  m3  m4Z5 d dl6m7  m8Z9 d dl:Z;d dl<Z;d dl=m8  m>Z? d dl@mAZA d dlBmCZC d dlDmEZE d dlFmGZG d dlHmIZI d dlJmKZKmLZLmMZMmNZNmOZO d dlPmQZQ d dlRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ d dl\m]Z] d dl^m_Z_ d dl`maZambZbmcZc d dldmeZe ddlfmgZgmhZh ddlimjZjmkZkmlZlmmZmmnZn ddlhmoZompZpmqZqmrZrmsZs ddltmuZu ddlvmwZwmxZxmyZymzZz ddl{m|Z| ddl}m~Z~mZ ddl8mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ dd lmZmZmZ e rd d!lmZ d d"lRmZ d d#l\mZ dd$lmZ dd%lmZ dd&lmZ dd'l8mZ neZd(ed)< zd dlZejZd*ZW n ey   dZd+ZY nw e'd,Ze!d-Ze!d.Ze!d/Ze"ee.f Zd(ed0< e"eee.f Zd(ed1< e"e;jje;jjf Zd(ed2< eeZeje	jd3d4Ze;jjZeed5d6Zeed7d8Z	 e"ed9eed9f d:d;eee"eeed9f d9d:d;f   f Zd(ed<< ddAdBZejd*dCG dDdE dEZŐddIdJZƐddNdOZǐddSdTZȐddUdVZɐdd\d]Zg d^Zg d_Z	dddddeZ͐ddgdhZ	dddidjZedddmdnZedddpdnZ	*dddsdnZАddwdxZѐdd{d|ZҐdd~dZӐdddZԐdddZՐdddZ֐dddZאdddZؐdddZG dd; d;Zed+dCG dd dZeG dd deڃZܐdddZeG dd de܃ZeG dd deރZed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+dCG dd deekZed+dC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+dC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dd3d4Zed+dCG d5d6 d6eZG d7d8 d8eZG d9d: d:eZed+dCG d;d< d<eZed+dCG d=d> d>eZG d?d@ d@eZ G dAdB dBeZ!G dCdD dDeZ"G dEdF dFeZ#G dGdH dHe#Z$G dIdJ dJe#Z%G dKdL dLeZ&G dMdN dNeZ'G dOdP dPeZ(G dQdR dReZ)G dSdT dTeZ*G dUdV dVe*Z+G dWdX dXe!Z,G dYdZ dZeZ-G d[d\ d\eZ.G d]d^ d^eZ/G d_d` d`eZ0G dadb dbeZ1G dcdd ddeZ2ed+dCG dedf dfZ3G dgdh dhe!Z4ed+dCG didj dje4Z5G dkdl dle4Z6eG dmdn dneZ7G dodp dpeZ8ejG dqdr dreڃZ9G dsd9 d9e9Z:G dtdu due9Z;ed+dCG dvdw dweڃZ<ddydzZ=ed+dCG d{d| d|eZ>ed+dCG d}d~ d~eZ?dddZ@ed+dCG dd deZAG dd de4ZBG dd deڃZCeG dd deCZDeG dd deCZEG dd de4ZFG dd deFZGG dd deFZHG dd deFZIdddZJdddZKdS (      )annotationsN)	Container	GeneratorIterableIteratorSequence)AbstractContextManagernullcontext)Enum)partial)AnyCallablecastClassVarLiteralOptionaloverloadSupportsFloatSupportsIntTYPE_CHECKINGTypeVarUnion)assert_neverNeveroverride	ParamSpecSelf	TypeAliasTypeIs)patch)ExprIntegerSymbol)identity)GraphModuleSerializer)can_auto_functionalize)metricsget_free_symbols)compute_required_storage_lengthis_boolean_dtypeis_float_dtypemake_channels_last_strides_for
StrideType)get_schema_info)	&_remove_effect_token_unbacked_bindingscompute_unbacked_bindingsfree_symbolsfree_unbacked_symbolsIterateExprsrebind_unbackedresolve_unbacked_bindingsShapeEnvSymTypes)Node
OrderedSet)CleanDivFloorDiv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)CUDATemplate)PythonWrapperCodegen)GraphLowering)IndentedBufferr   rp   TF_P_T_U_V_IntLike_NumLike_OpOverloadsz  prefixTORCH_AUTOTUNE_WARMUP   TORCH_AUTOTUNE_REPd   	TensorBoxr"   IRNode_NodeOrNodesxobjectreturnboolc                 C  s   t | ttfS N)
isinstanceintr!   r    r   H/home/ubuntu/vllm_env/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_deallocationr   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   rk   c                    s   t t | i |S r   )getattrrj   r   r   r   r   r   fn     zops_wrapper.<locals>.fn)r   r   r   r   r   rk   )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   3     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  s     | ]}t |ttjfV  qd S r   )r   r   r   r!   r   sr   r   r   	<genexpr>C  s    z!get_fill_order.<locals>.<genexpr>)allrT   rU   )r   r   
sorted_idxr   r   r   get_fill_order=  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>R      z+stride_order2fill_order.<locals>.<dictcomp>c                      g | ]} | qS r   r   r   lookupr   r   r   S      z+stride_order2fill_order.<locals>.<listcomp>)	enumerater   r   )r   
fill_orderr   r   r   stride_order2fill_orderK  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   ^      z$get_stride_order.<locals>.<listcomp>)r   r   r   r   )r   r   r   outr   elemr   r   r   get_stride_orderW  s
   

r  Literal[None]guard_shapec                 C     d S r   r   r   r	  r   r   r   ir_node_to_tensord     r  torch.Tensorc                 C  r
  r   r   r  r   r   r   r  h  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   w  r   z%ir_node_to_tensor.<locals>.<listcomp>c                   r  r   r   r   r  r   r   r   z  r   )sizestridedtypedevice)rl   graphsizevars	size_hintr#   get_sizeis_storage_and_layout
get_layoutr  FlexibleLayoutcontiguous_strides	get_dtype
get_devicerZ   r   suppress_guardstorchempty_stridedzero_)r   r	  r  r  r  r  tr   r  r   r  l  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   r@   rD   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 fddtt d D }t	j
j d dkpFt	j
j d dk}|oJ|S )NFc                 3  s.    | ]}t jj |   d kV  qdS )r   N)rl   r  r  size_hint_or_throw
get_strider   r>  r   r   r   r     s
    
z2is_aligned_realized_tensor_hint.<locals>.<genexpr>r?   )r   r   maybe_get_strider2   r@  r  r   r   r   rl   r  r  r?  )r   r>  aligned_stridesaligned_last_dimr   rA  r   is_aligned_realized_tensor_hint  s   

rF  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s? dS qdS )zP
    Returns true if the strides are equal, ignoring dimensions of size 1 .
    r?   FT)r   r   rl   r  r  statically_known_leqstatically_known_equalssymbolic_hint)rG  rI  rJ  dims1s2r   r   r   significant_strides_equal  s   $rQ  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   rl   r  r  rL  r   rO  rP  r   r   r   r     
    
z2try_match_insignificant_strides.<locals>.<genexpr>r?   datalayout)r  r   r   r@  rQ  r  as_storage_and_layoutr  r   rl   r  r  rK  FixedLayoutr  r  r  offset	is_pinnedr   ReinterpretView)rR  rS  storage
old_layout
new_strider   r   
new_layoutr   r   r   try_match_insignificant_strides  s.   

re  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_fxrk  )rf  output_noderk  r   r   r   gm_original_output_strides  s   rp  inputsSequence[IRNode]
list[Expr]c                 C  s@   t  }| D ]}|t| ddO }|t| ddO }qt|S )NFunbacked_only)r:   r(   r  r@  r   )rq  sym_varsinpr   r   r   get_symbolic_inputs  s
   rx  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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-d.Z	*ddd2d3Zdd5d6Zdd8d9Zdd;d<Zdd>d?ZddAdBZddDdEZddFdGZ ddIdJZ!ddLdMZ"e#ddOdPZ$ddRdSZ%ddTdUZ&ddWdXZ'ddd\d]Z(dd_d`Z)ddbdcZ*ddddeZ+ddgdhZ,ddjdkZ-ddmdnZ.ddodpZ/ddqdrZ0ddsdtZ1ddudvZ2dddydzZ3dd}d~Z4dddZ5dddZ6dddZ7	ddddZ8dddZ9dddZ:	ddddZ;dddZ<dddZ=dddZ>dddZ?	ddddZ@dddZAdddZBdddZCdddZDdddZEdddZFdddZGdddZHeIrie#dddZJdYS dYS )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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   ry  )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InputBufferr`  TemplateBuffer)r   r   r   r   is_realized_node9  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_setattrF  s   zIRNode._post_init_setattrc                 C  s@   t | j}| d| | dtjrt nd  | dd  d S )Nr|  r~  r  )r:   ry  r  r@   debug_ir_tracebackr~  format_stack)r  r|  r   r   r   __post_init__L  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   U      z(IRNode.get_read_names.<locals>.<genexpr>r:   	get_readsr  r   r   r   get_read_namesT     zIRNode.get_read_namesc                 C     | j S r   )r~  r  r   r   r   get_tracebackW     zIRNode.get_tracebackc                 C  r  r   r  r  r   r   r   get_origin_nodeZ  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)r:   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_traces`  s4   






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   rJ       zIRNode.shaper    c                 C     t |  S r   )rg   r  r  r   r   r   	get_numel  r   zIRNode.get_numelc                 C     t jjt|  dS Nr   rl   r  r  statically_known_truer   Eqr  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  s   |   }|d us
J |S r   r!  r  r  r   r   r   get_device_or_error  s   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_indexerrH  c                 C  r  r   r  r  r   r   r   r@    r   zIRNode.get_stridec                 C  r  r   )r@  r  r  r   r   r   rC    r  zIRNode.maybe_get_stridec                 C  r  r   r  r  r   r   r   get_name  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  rl   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   unwrap_view  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_reads.  r   zIRNode.num_readsrx   c                 C  r  r   r  r  r   r   r   get_storage_numel1  r   zIRNode.get_storage_numelru  r   c                 C  r  r   r  r  ru  r   r   r   get_free_symbol_uses4  r  zIRNode.get_free_symbol_usesc                 C  r  r   r  r  r   r   r   get_reduction_type9  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_extern?  r  zIRNode.is_externc                 C  r  r  r   r  r   r   r   is_no_opB  r  zIRNode.is_no_opr  c                 C  r  r   r  r  r   r   r   constant_to_deviceE  r   zIRNode.constant_to_devicec                 C  r  r   r  r  r   r   r   get_mutation_namesH  r   zIRNode.get_mutation_namesc                 C  r  r   r  r  r   r   r   get_operation_nameK  r   zIRNode.get_operation_namec                 C  r  r   r  r  r   r   r   get_inputs_that_alias_outputN  r   z#IRNode.get_inputs_that_alias_outputc                 C  r
  r   r   r  r   r   r   r  S  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   rH  r   r   r   r  r   r   r  r   r   r   r   r   Fr   r   r
  r   r   r   r   r   r   r   r  rH  r   r   r  rH  r
  r   r   r   r   r  r   r  r   r   r   rx   ru  r   r   r   r  r  r   r   r   r  )Kr   r   r   __doc__r:   ry  r   dataclassesfieldr|  r~  r  staticmethod
contextlibcontextmanagerr  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  propertyrJ  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  r  r  r  r   r!  r"  r#  r$  r%  r&  r'  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  Y  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  _     zOperation.get_origin_noder{  c                 C  rW  )Nr|  )r  r|  r  r   r   r   get_originsc  rY  zOperation.get_originsr   c                 C  s   | j d usJ | j S r   rS  r  r   r   r   r&  g  rY  zOperation.get_operation_namer   c                 C  r  r  r   r  r   r   r   r"  k  r  zOperation.is_externc                 C  r  r  r   r  r   r   r   r#  n  r  zOperation.is_no_opr  c                 C  rU  r   rV  r  r   r   r   r  q  r  zOperation.get_read_writesr   c                 C  s   ||   v S r   )r  )r  r   r   r   r   
is_user_oft  r   zOperation.is_user_ofr  c                 C  r  )Nc                 s  r  r   r   r  r   r   r   r   x  r  z+Operation.get_read_names.<locals>.<genexpr>r  r  r   r   r   r  w  r  zOperation.get_read_namesr  c                 C  r  r   r  r  r   r   r   r  z  r  zOperation.get_readslist[Buffer]c                 C  rU  r   rV  r  r   r   r   get_outputs}  r  zOperation.get_outputsr   c                 C     t  S r   r9   r  r   r   r   get_unbacked_symbol_defs  r  z"Operation.get_unbacked_symbol_defsFru  c                 C  r^  )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.
        r9   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_sizeNr)  r6  r+  )r   r{  r;  r1  rD  )r   r   r   r   r*  rE  r   r\  r   r   r?  rH  rF  )r   r   r   r  r!  r  rZ  r&  r"  r#  r  r[  r  r  r]  r_  r  r`  r   r   r   r   rR  W  s"    












rR  c                      s2  e Zd ZU ded< ded< ded< ded< ed 		dPdQddZdRddZdS fddZdTddZeZ	dUddZ
dVddZdWd!d"ZdWd#d$ZedXd)d*ZeejfdYd-d.ZedZd0d1Zd[d3d4ZedTd5d6Zd\d]d:d;ZdPd^d=d>Zd_d@dAZd`dCdDZdadFdGZdWdHdIZdbdKdLZdcdNdOZ  Z S )dLoopsr  r  r  r  Callable[..., Any]inner_fnrH  rangesFru  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   ert  r   r   r         z-Loops.get_free_symbol_uses.<locals>.<genexpr>)r:   unionrf  inner_fn_free_symbolsr  r   rt  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  rm  r   r  r   _to_str  s   zLoops._to_strr   c                   s   t    d S r   )superr  r  	__class__r   r   r    r   zLoops.__post_init__c                 C  
   |  dS )Nrf  rt  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   ry  r  r   r   r   r    r  zLoops.get_sizec                 C  r  r   ry  r  r   r   r   get_pointwise_size  r  zLoops.get_pointwise_sizer   r   r   'Union[TensorBox, ShapeAsConstantBuffer]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Zerorf   )r   nr   r{   r   r   r         z Loops._index.<locals>.<listcomp>)r   )rf  r|   r   r{   r   _index  s   
zLoops._indexrN   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)
rM   rl   MockHandlerset_ops_handlerr   r   r  re  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  rf  r  r   r   r   r    r   zLoops.inner_fn_argsc                 C  s   t jj| jg|  R  S r   )rl   KernelFormatterHandlerir_to_stringre  r  r  r   r   r   rs    s
   zLoops.inner_fn_strNr   r  c                 C  s&   |d u rd}t |tj}|  j|kS r  )maxr@   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 Nrt  )r  rf  rH   re  )r  ru  r   r   r   r   rl     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   rJ   r  r  r!  r  r  r   r   r   r    s   $zLoops.get_readsr  c                 C     t |  jS r   )r:   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   r$  "  r  zLoops.constant_to_devicer?  rH  )rm  r  r   r   r)  r;  r6  r+  r2  )r   r   r   r   r   r~  )rf  rH  r|   r>   r   r  )r   rN   r   r  r   r<  ru  r   r   r  rE  r*  rF  r4  rI  )!r   r   r   r   rW   r  rt  r  r{  __repr__r!  r  r  r}  classmethodr  rN  r>   INDEXr  rV   r  r  rs  r  rl  r  r  r  r!  r   r$  __classcell__r   r   rv  r   rc    sB   
 






	




rc  r   Union[Expr, Sequence[Expr]]r  r  rk   c                C  s"   |j rttd|S td|S )Nnanr   )is_floating_pointrj   constantfloat)r   r  r   r   r   nop_loader_fn(  s   r  c                   @  s>   e 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 )	Pointwiser   r  c                 C  s   |   rtt| jdS | jS Nr  )r  r   r  r  re  r  r   r   r   r  1  s   zPointwise.make_loaderSequence[sympy.Expr]c                 C  s   g S r   r   r  r   r   r   r!  8  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  rj   storer  r  r  r  loaderr   r   r   store_output>  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  re  rf  )r  r   r   ConstantBufferr  r  rf  r  r  r  r   r   r   r$  G  s   zPointwise.constant_to_deviceNr8  )r   r  r4  )r  r-  r  r  r  r  r   r   rI  )r   r   r   r  r!  r   r  r$  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_indexerNrP   scatter_moder  r  r   r   c                 C  s6   |   }ttd||}t|| j|| j| j| jdS )r  r  )r  r  re  rf  r  r  )	r  r   r   r  r  r  rf  r  r  r  r   r   r   r$  X  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  rj   r  r  r  r  r   r   r   r  e  s   zScatter.store_outputrI  )r  r-  r  r  r  r  r   r   )r   r   r   r   r  r$  r  r   r   r   r   r  S  s
   
 
r  
logical_ormaximumminimummulr  bitwise_xor)anyr  minprodsum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  )	rj   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 )	ReductionrH  reduction_rangesrO   r  r  	src_dtyperS   reduction_hintr   r   c                 C  rx  )N)rf  r  r  rz  r  r   r   r   r{    r  zReduction.__str__Fru  r   r  c                   s(   t   t j fdd| jD  B S )Nc                 3  rg  r   r'   rh  rt  r   r   r     rj  z1Reduction.get_free_symbol_uses.<locals>.<genexpr>)ru  r  r:   rk  r  r  rv  rt  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  )rj   	reductionr  r  r  re  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   rf  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  rf  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  rf  r  r>   r  rH   re  )r  ru  r   r  r   r   r   rl    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  re  rf  r  r  r  r  )r  r   r   r  r  r  rf  r  r  r  rS   DEFAULTr  r   r   r   r$    s   zReduction.constant_to_deviceN	dst_dtypere  Callable[_P, OpsValue]rf  %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 t| }|j}d}|rRtjt jj| dd}tjt jj| dd}nddd}|}|
dkr||	|
}|dkrkt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rtjdfS t |! |" \\}}}d}d}|D ].}t jj#||}t jj$||t%|& } t'dd | D }!|!r;|d7 }q|d7 }q||krNtj||	|
fS tj(||	|
fS )Nscanr  r?       T)inner_reductionFreduction_numel_hintr   
numel_hintr   c                 S  r  Nr?   r   )r  r  r   r   r   inner_reduction_splits-     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: %srB  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[  rZ  c                 S  s&   g | ]}t |trt |tjs|qS r   )r   r    r   Numberr   r  r   r   r   r   v  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   r1   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   rl   r  name_to_bufferr   r[  decide_layout)	r  r  cbread_writesr  indiceschangedbuforiginal_strider   r  r   get_read_indicese  s:   	z.Reduction.num_splits.<locals>.get_read_indicesr   c                 s  s    | ]}|d kV  qdS r?   Nr   r   r   r   r   r         z'Reduction.num_splits.<locals>.<genexpr>)r  r   r  r   r   r   )r  r  r   r  ))rl   r  r  rM  rg   has_featurerB   REDUCE_TO_SINGLE_ELEMENTr@   split_reductionsr   rS   r  rR   r  multi_processor_count	functoolsr   choicesreduction_split_factorINNERr   r   r   r   r  rI   logr  r  r   rA   index_vars_squeezer  r!  simplify_with_rangesstride_hintsr   keysr   OUTER)"r  r  r  re  rf  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  r&  r"  r#  r  r  ranges1	num_outer	num_innerr   jrS  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   rH  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>)r-  reduce	itertoolsproductr   )
combine_fnr  rG  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>)rj   
index_exprr#  int64r   r  )flatten_indexre  r   r   rG    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   rH  r   r   )r   rH  r  rH  r   r  )rl   r  r  guard_int_seqr  _fixed_indexerr  r  )re  r  r  r  r   )rL  rT  r   re  r  rG  r   _unroll_reduction_fn  s   
	zReduction._unroll_reduction_fnrd  r~  c
                   s$  t jjtdkrDd fdd}
|
d|
d|
d|
dd	 v s0J  d
d fdd}tj|||t|dS dkredv rTd 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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| | |||||	
S tt| |||dS )Nr   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   rX  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   rk   c                   s   t   S r   rj   r  r   )r  r  rtypes_to_initsr   r   const_fn     z"Reduction.create.<locals>.const_fnr  rM  c                   s   t d S r  r]  r   r[  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)re  r  r   r   r        
r  c                   s$   t  r| S | dkrt| tjS | S r  )r   r  r@   min_num_split)r  )r  r   r   _maybe_increase_split6  s
   z/Reduction.create.<locals>._maybe_increase_splitrB  r  Tr   )rX  r   r   rY  )r   r   r   rk   )r  r   r   r   )rl   r  r  simplifyrg   r5  r  r  r   r   r!   r?  r@   unroll_reductions_thresholdrc   r   rW  rD  rS   r  r   r   r  rI   !create_multilayer_existing_rangescreate_multilayerr   r  )r  r  r  r  re  rf  r  r  r  r  r\  r_  r   hintr  rh  r<  r=  r   )r  re  r  r  r  r^  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  welford_reducer  online_softmax_reduce)r+   r  r*   r#  iinfor  r  )r  r  zerooner   r   r   default_accumulatorv  s0   
zReduction.default_accumulatorc                 C  s   | dkrdS t | |S )Nrp  r   )r  ru  r  r  r   r   r   default_value  s   zReduction.default_valuer  rx   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 )NrB     i      )rS   r6  
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
        NrB  r?   )
rl   r  r  rL  r  r  r\  r  r@  r   )r  r  r  rS  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  re  r   rk   c                   sl   |\}| ^ }| |  d fdd}r3t }tt |t|}t||S | S )Nr   rk   c                     s    gS r   r   r   )r"  r  	new_indexr   r   r   body  r`  zCReduction._multilayer_wrap_loader.<locals>.wrapper_fn.<locals>.body)r   rk   )r]   rj   r  rQ  masked)r   re  reduction_blockr  index_dtyper  r}  r~  r  	need_maskr  r   )r"  r  r   
wrapper_fn  s   


z5Reduction._multilayer_wrap_loader.<locals>.wrapper_fn)r   r  re  r  r   rk   )	r|  Viewdynamic_reshape_indexerrl   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_rangesr<  Sequence[Integer]r=  @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'  r   r  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   rk   c                   s:   | d t  }| t d  } |t|t| S r   )r   r   )r  r  original_idxr  r  r  r   r   r   r  	  s   zEReduction._multilayer_wrap_loader_existing_ranges.<locals>.wrapper_fn)r  r  r  r  r   rk   )r   r  r  r   )r  r  r  r  r<  r=  r  r   r  r   '_multilayer_wrap_loader_existing_ranges  s   	z1Reduction._multilayer_wrap_loader_existing_rangesr  rs  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   rH  re  r   rk   c                   s    g | |S r   r   rd  intermediate_loaderr   r   intermediate_fn>  s   z;Reduction.create_multilayer_helper.<locals>.intermediate_fnNr   )r   rH  re  rH  r   rk   )r#  float16bfloat16r  r  r  r  r  rl   r  r  r  rg   r{  r   r   )r  r  r  r  r  r  r  r<  r=  r  r  r  intermediate_dtypeintermediater  r  r   r  r   create_multilayer_helper  sD   
z"Reduction.create_multilayer_helperc                 C  sd   t |}t||d  |}| ||}| |||||||
}| ||||||g |||g|||	S )r  r?   )rg   r<   rw  r  r  )r  r  r  r  re  rf  r  r  r  r  r  r  r}  r~  r  r   r   r   rl  V  s2   

zReduction.create_multilayerc                 C  s8   |  |||||}| ||||||g ||||	d|
S )r  rB  )r  r  )r  r  r  r  re  r  r  r<  r=  r  r  r  r   r   r   rk    s(   
z+Reduction.create_multilayer_existing_rangesr;  r?  r  r2  r4  )
r  r-  r  r  r  r  r  r  r   r   rF  r   r  rI  r   )r  r  r  r  r  r  re  r  rf  rH  r  rH  r  r  r  r    r  r  r   r  )
re  rE  r  rH  r  r   r  r  r   rF  )r  r  r  r  r  r  re  rd  rf  r  r  r  r  rO   r  rS   r  r  r   r~  r  r   r  r  r   rn  )r  rx   r  r   r  rS   r   rS   )r  rx   r  r  r   r  )r  r   r  rH  r  rx   r  rx   r}  rx   r~  rn  r  r  r   r  )r  r  r  r  r  r  r<  r  r=  r  r   r  )r  r  r  r  r  r  r  rd  r  r  r  r  r<  rs  r=  r  r  rO   r  rx   r  rS   r   r~  )r  r  r  r  r  r  re  rd  rf  r  r  r  r  rO   r  rx   r  rS   r  r  r   r~  )r  r  r  r  r  r  re  rd  r  r  r  r  r<  r  r=  r  r  rO   r  rS   r   r~  ) r   r   r   r   r{  r  rW   r  r!  r   r  r  r  rl  r$  rN  rD  rW  r  rS   r  r  ru  rw  r{  r|  r  r  r  rl  rk  r  r   r   rv  r   r    s^   
 







 #+
 "	*?-r  r  r  Optional[Sequence[int]]r^  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r^  r  r  r   r   r    s   z_fixed_indexer.<locals>.indexerN)r   r   r   r   r   )r  r  r^  r  r   r  r   rV    s   	rV  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]]rf  r  r  r  rO   r  r  rS   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     rj  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   ru  __init__r  )r  r  r  r  rf  r  r  r  r  r  r  rv  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  )rj   r  r  r  r  re  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  rf  r  r  r  r  rO   r  r  r  rS   r  r   )
r  r-  r  r  r  r  r  r  r   r   )r   r   r   r   r  r  r  r   r   rv  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  re  rd  rf  r  r  
num_outputr   r  rS   r  r  r   1Sequence[Union[TensorBox, ShapeAsConstantBuffer]]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 )rq  N)r   r  r  r   
output_idxr  r  re  rf  r  r  r  r   r   r     s"    
z0OnlineSoftmaxReduction.create.<locals>.<genexpr>)r   r   r  )r  r  r  r  re  rf  r  r  r  r  resultsr&  r   r  r   r    s   
zOnlineSoftmaxReduction.create)r  r  r  r  r  r  re  rd  rf  r  r  r  r  r   r  rS   r  r  r   r  )r   r   r   r  rS   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]]rf  r  r  r  rO   r  rS   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)rp  r  rX  r   r   r~  c                   s&   d fdd}t j|tdS )	Nr   r  r   rk   c                   s   t  S r   r]  r   )r  rX  r   r   re  3  s   z8WelfordReduction.create.<locals>.const.<locals>.inner_fnr  r   r  r   rk   r  r  r   )rX  re  )r  r  rf  rZ  r   const2  s   z&WelfordReduction.create.<locals>.constr   r?   r  r  c                   s&   d fdd}t j|tdS )	Nr   r  r   rk   c                   ra  )Nc                 S  rb  r   rc  r  r   r   r   r   L  r   zKWelfordReduction.create.<locals>.copy.<locals>.inner_fn.<locals>.<listcomp>r   )r   re  )r  r  r   r   re  K  rf  z7WelfordReduction.create.<locals>.copy.<locals>.inner_fnr  r  r  )r  re  )r  r  rf  r  r  r   copyH  s   z%WelfordReduction.create.<locals>.copyrp  c                 3      | ]} |V  qd S r   r   r  )r  r   r   r   Y  r(  z*WelfordReduction.create.<locals>.<genexpr>)r  r  c                   s*   g | ]}t t |	qS r   )r   r  r  r  )r  r  r  rf  r  r  r  r   r   r     s     z+WelfordReduction.create.<locals>.<listcomp>r   )rX  r   r   r~  )r  r  r   r~  )rl   r  r  ri  rg   r   r  rD  rS   r  rl  r   r  )r  r  r  r  rf  r  r  r  r  r  meanm2weightrm  r  r  r&  r   )r  r  r  r  rf  r  r  r  r   r  #  sT   



zWelfordReduction.creater   rn  c                 C  r  )N)r   r   r   r   rv  r   r   r   rw    r  zWelfordReduction.default_valuer  rx   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   rk   c                   s   t | S r   r]  )r   r  r'  r  r   r   r    s   z4WelfordReduction.create_multilayer.<locals>.constantr*  r?   )r  r  r  rf  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   re  r  r  c                 S  s   |g | |S r   r   )r   re  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     s
    
N)r   r  r  r  r'  r   r   rk   )r   r  re  r  r  r  r   rk   )rg   rl   r  r  r  r   r  rl  r   r<   r  r  r   r  r  r{  )r  r  r  r  rf  r  r  r  r  r  r  intermediatesr   r  r   )r}  r  r  r  r  r  r  r   rl    sb   

	


z"WelfordReduction.create_multilayerN)r  r  r  r  r  r  rf  r  r  r  r  rO   r  rS   r   r  r  )r  r  r  r  r  r  rf  r  r  r  r  rO   r  rx   r  rS   r   r  )
r   r   r   r  rS   r  r  rN  rw  rl  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, ...]]rL  zFCallable[[Sequence[_IntLike], Sequence[_IntLike]], Sequence[_IntLike]]r   rS   r  r   r  tuple[torch.dtype, ...]dtypestuple[Callable[..., Any], ...]r  Fru  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  rg  r   r'   rh  rt  r   r   r   	  rj  z,Scan.get_free_symbol_uses.<locals>.<genexpr>c                 3  rg  r   r'   rh  rt  r   r   r   	  rj  )ru  r  r:   rk  r  r  r  rv  rt  r   r  	  s   
zScan.get_free_symbol_usesr   c                   0   t | jt | j t | jksJ t   d S r   )r   rf  r  r  ru  r  r  rv  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   re  r  r   r   r   )	  r(  z'Scan.store_reduction.<locals>.<genexpr>r  )	r   r   r  rj   r  r  rL  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   /	     zScan.get_reduction_typec                 C  r  r   )r  r  r   r   r   r!  3	  r  zScan.get_reduction_sizec                 C  r  r   r  r  r   r   r   r  6	  r  zScan.get_sizec                 C  r  r   ry  r  r   r   r   r}  9	  r  zScan.get_pointwise_sizec                 C  r  r   )r   rf  r  r  r   r   r   r  <	  r   zScan.index_lengthr  c                 C  .   |  | j}|  | jtj}| ||}|fS r   )r  rf  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  rf  r  r>   r  r   rH   re  r  ru  r   r  r   r   r   r   rl  E	     zScan.inner_fn_free_symbolsT)can_fallback_to_atenr  r  +tuple[Callable[[Sequence[Expr]], Any], ...]axisr  r   ;Sequence[Optional[Union[TensorBox, ShapeAsConstantBuffer]]]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   l	      zScan.create.<locals>.<listcomp>r   )r  r  re  r  pointwise_rangesr  rL  
scan_numelz3.3.0r   r  
scan_indexr   rs  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  re  r  r  rf  r  rL  r   r  r  r   )r   r  r  )rL  r  r  r  r   r  r  r   r  	scan_typer  r   r   r   	  s*    )r   r  r  r  r   rs  )rl   r  r)  rB   SCANr   TUPLE_REDUCTIONr  ri  rg   r  r   Ler   rD  r  r#  versionhip
has_tritontriton_version	SplitScanr  )r  r  r  r  r  r  rL  r  r  r   r  r  rD  supports_splitr  r  r   )r  rL  r  r  r  r   r  r  r   r  r  r  r   r  K	  sV    







zScan.creater  r  re  r  r  r  r    r  c	           
   
     s*   d
 fdd}	t j||||	||d|d	S )Nr   r  r  r   rk   c                   s$   g | d   ||  d  S r   r   r  r  re  r   r   r  	  s   $z#Scan.num_splits.<locals>.wrapper_fnr  )r  r  r  re  rf  r  r  r  )r   r  r  r  r   rk   )r  rD  )
r  r  r  re  r  r  r  rL  r  r  r   r  r   rD  	  s   zScan.num_splitsr?  r  r)  )
r  r-  r  r  r  r  r  r  r   r   r4  r2  rF  r  )r  r  r  r  r  r  r  r  r  r   rL  r  r  rS   r  r   r   r   r   r  )r  r  r  r  re  r  r  r   r  r  r  r  rL  r  r  r    r   r  )r   r   r   r   rW   r  r  r  r   r!  r  r}  r  r  rl  r  rS   r  r  rD  r  r   r   rv  r   r   	  s6   
 






	a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   rS   r  r   r  r  r  r  r  r   stable
descendingFru  r   r  c                   r  )Nc                 3  rg  r   r'   rh  rt  r   r   r   	  rj  z,Sort.get_free_symbol_uses.<locals>.<genexpr>c                 3  rg  r   r'   rh  rt  r   r   r   	  rj  )ru  r  r:   rk  r  r  r  rv  rt  r   r  	  s   
zSort.get_free_symbol_usesr   c                   r  r   )r   rf  r  r  ru  r  r  rv  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   	  r(  z'Sort.store_reduction.<locals>.<genexpr>r  )
r   r   r  rj   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  
  r  zSort.get_sizec                 C  r  r   ry  r  r   r   r   r}  
  r  zSort.get_pointwise_sizec                 C  r  r   )r   rf  r  r  r   r   r   r  

  r   zSort.index_lengthr  c                 C  r  r   )r  rf  r  r>   r  r   r  r   r   r   r  
  r  zSort.inner_fn_argsc                 C  r  r  )r  rf  r  r>   r  r   rH   re  r  r   r   r   rl  
  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?   rx  c                   r  r  r  r  r  r   r   r   >
  r  zSort.create.<locals>.<listcomp>r   r  
sort_indexr   rs  c                   r  r   r  )r   r  )r  r  r  r   r   r   H
  r  zSort.create.<locals>.reindexc                   sD   g | ]}t td| | 	|
 d qS ))r  r  r  re  r  r  rf  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   M
  s,    )r   r  r  r  r   rs  )rl   r  r)  rB   SORTr   r  ri  rg   r@   r6  persistent_reductionsr  r   r  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  
  s0    




zSort.creater?  r  r)  )
r  r-  r  r  r  r  r  r  r   r   r4  r2  rF  r  )r  r  r  r  r  r  r  r  r  r   r  r   r  r   r  rS   r   r   r   r  )r   r   r   r   rW   r  r  r  r   r!  r  r}  r  r  rl  r  rS   r  r  r  r   r   rv  r   r  	  s0   
 







r  c                 C  s(   z	t | dd W dS  ty   Y dS w )NFfreezeT)r\  r  r   r   r   r   r  i
  s   r  c                 C  s@   zt | dd\}}| r|  | W S  ty   Y dS w NFr  )r\  should_pad_stridespad_stridesis_contiguousr  )r   _bufferr[  r   r   r    is_contiguous_storage_and_layoutq
  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   r\  rZ  
StorageBoxr  Bufferr	  r
  r  r  r  r`  r[  r  )	r   r  r  r  r
  r  r  r[  bufferr   r   r   r\  }
  sR   






r\  c                 C  s2   zt | dd\}}||W S  ty   Y dS w r  )r\  is_stride_orderedr  )r   r  r  r[  r   r   r   "is_stride_order_storage_and_layout
  s   r  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_unalignedrZ  r`  r[  rl   r  r  statically_known_multiple_ofr^  r^   r  r`   r  r  unaligned_buffers)r   r[  has_unaligned_layoutr   r   r   r  
  s   


r  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 )YBaseViewr   rZ  Fru  r   r   r  c                 C     | j |S r   rZ  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 rV  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    )rZ  r  r!  r  r  r   r#  r   r  
     
zBaseView.make_indexerr  c                   r"  )Nr   r  r   rk   c                   r   r   r   r  r#  r   r   r  
  r   z$BaseView.make_loader.<locals>.loaderr  )rZ  r  r!  r  r  r   r#  r   r  
  r&  zBaseView.make_loaderr  c                 C  
   | j  S r   )rZ  r   r  r   r   r   r  
     
zBaseView.dtyper  c                 C  r(  r   rZ  r  r  r   r   r   r  
  r  zBaseView.get_layoutr  c                 C  r(  r   rZ  r!  r  r   r   r   r!  
  r  zBaseView.get_devicer  c                 C  r
  r   r   r  r   r   r   r  
  r  zBaseView.get_origin_noder   c                 C  r(  r   rZ  r  r  r   r   r   r  
  r  zBaseView.get_namer  c                 C  r  r   r  r  r   r   r   r}    r  zBaseView.get_pointwise_sizer  r   r   c                 C  r  r   rZ  r  r  r   r   r   r    r   zBaseView.mark_reusec                 C  r(  r   rZ  r  r  r   r   r   r    r  zBaseView.has_exceeded_max_readsr-  c                 C  r(  r   rZ  r  r  r   r   r   r    r  zBaseView.realizec                 C  s   | j   d S r   rZ  r  r  r   r   r   r    r   zBaseView.realize_hintrx   c                 C  r(  r   rZ  r  r  r   r   r   r    r  zBaseView.get_storage_numelc                 C  r(  r   rZ  r"  r  r   r   r   r"    r  zBaseView.is_externc                 C  s$   t | jtsJ t| j| j S r   )r   rZ  r  r   is_module_bufferr  r   r   r   r3    s   
zBaseView.is_module_bufferr  c                 C  r(  r   rZ  r  r  r   r   r   r    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  rJ   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  rZ  )r  r   r   r   r   r  %  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   r$  +  s   zBaseView.constant_to_deviceNr?  r  r   r   r9  r8  r.  r/  r6  r+  r;  r2  r=  r1  r4  r)  rG  r*  rE  r>  rI  )r   r   r   r   rW   r  r!  r  r  rQ  r  r  r!  r  r  r}  r  r  r  r  r  r"  r3  r  r  r  r$  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_sizerH  r   c                 C  s   t jj}dd |D }|  }dgt|t|  t| }t|t|ks(J tt|D ]:}|| dkrE|| dus>J || ||< q.|| du sTt jj|| rUq.|j|| ||  dddkshJ dq.|S )zReplace `-1` with correct sizesc                 S  rN  r   rO  r   r   r   r   r   ?  r   z.ExpandView._normalize_size.<locals>.<listcomp>NrB  r   fallbackzKBroadcast failed in ExpandView({x.get_size()}, {new_size}) on dimension {i})	rl   r  r  r  r   r   r   is_size_one_or_falser  )r   r6  r  old_sizer   r   r   r   _normalize_size;  s"    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   rY  )rZ  r  )r;  r  r\  r   r  r   r  r  r   r  r  rl   r  r  r9  r]  r  r  r   r^  r_  r`  r   )
r  r   r6  ra  rb  skiprc  r  r  rd  r   r   r   r  V  s,   zExpandView.createc                 C  r  r   r  r  r   r   r   r  q  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   actualr<  r   r   r   {  s   z*ExpandView.make_reindexer.<locals>.reindexr   r  r   r  )r  rZ  r   )r  targetr   r   r=  r   r!  t  s
   
zExpandView.make_reindexerN)r   r   r6  rH  r   rH  )r   r   r6  rH  r   r  r2  r5  )
r   r   r   r   rN  r;  r  r  r  r!  r   r   r   r   r   7  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 )PermuteViewrs  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   rb  r   r   r     r   z&PermuteView.create.<locals>.<listcomp>c                   rC  r   r  r   rD  r   r   r     r   rY  )rZ  rB  )_map_neg_dimsr:   r   r   r  r\  r]  r  r  r^  r_  r`  rA  )r  r   rB  ra  rd  r   rD  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   rN  rB  r   r   r     s   $ z-PermuteView._map_neg_dims.<locals>.<listcomp>r   )r  rB  r   rH  r   rF       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>)r:   rF  rB  r   r   rZ  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   rB  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   rJ  r   r   r        z+PermuteView.make_reindexer.<locals>.reindexr?  )r   rB  r   r   r:   )r  r   r   rJ  r   r!    s
   zPermuteView.make_reindexerN)r   r   rB  r   r   r  )rB  r   r   rG  r2  r5  )	r   r   r   r   r  r  rF  r  r!  r   r   r   r   rA    s   
 
rA  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rN  r   r   rN  r  r   c                  sF  t |rwt|\}}g }g } d ur*t tsJ t d kr( t|jk s*J tt|j|j	D ]0\}\}}	 d u rL|dkrK|
| |
|	 q3| kr[|
| |
|	 q3|dkscJ 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 1rY  c                 S     g | ]}|d kr|qS r  r   r   r   r   r   r     r   z&SqueezeView.create.<locals>.<listcomp>c                   s   g | ]
\}}| kr|qS r   r   r   r   r   rN  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   rN  ra  rb  r6  rc  r   r  r  rd  r   rN  r   r    s<   


"zSqueezeView.creater  r  9tuple[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  rO  r  r   r   r   r   r   r     r   z(SqueezeView.squeezer.<locals>.<listcomp>c                 S  s   g | ]
\}}|d kr|qS r  r   rP  r   r   r   r     rQ  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   rS  )r   r   )r  r6  r   r   rU  r   squeezer  s
   zSqueezeView.squeezerrZ  r   r   c                 C  s   t d)Nzuse SqueezeView.create())AssertionError)r  rZ  r   r   r   r    r  zSqueezeView.__init__)r   r   rN  r  r   r   )r  r  r   rR  )rZ  r   r   r   )r   r   r   r  r  rN  rX  r  r   r   r   r   rM    s    &rM  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!    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   )rf   r>   r  r   r  r   r   r   r         z+GenericView.reindex_str.<locals>.<listcomp>zlambda , r.  )r   r   r  r   r   r  r  r   )r  	index_old	index_newr   r   r   reindex_str  s
   zGenericView.reindex_strc                 C  s$   |  | jd| j d|   gS )Nsize=zreindex=)r  rZ  r  ra  r  r   r   r   r{  	  s   zGenericView.__str__r   r   r6  r  c                 C  s   | |t ||dS )NrZ  r  r   )r   )r  r   r6  r   r   r   r   r    s   zGenericView.createc                 C  r  r   r  r  r   r   r   r    r  zGenericView.get_sizeNr5  r;  )r   r   r6  r  r   r   r   r  r2  )r   r   r   r   r!  ra  r{  r  r  r  r  r   r   r   r   rZ    s   
 


rZ  c                   @  sZ   e Zd ZedddZ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  r   r    r  r   c                 C  s<   t | } t |}tjjjj}|t | dr| | } | S r  )r   rP  rl   r  r  r   evaluate_exprLt)r   r  rd  r   r   r   handle_negative_index  s   

zView.handle_negative_indexr   r   r6  r  c           	        s
  t |tsJ t|| | |\ }tjj |r|S d}t	t
 dks1t	t
|dkr3d}d|v rGd fdd	}| |t||d
S t|sM|rv|rXt|sXt|}t|dd\}}t|j|j|t||j|j}t||dS |  |}| |t||d
S )NFr   Tr   r   r   tuple[int, ...]c                   s   t dgt  S r  )r   r   r   r:  r   r   fake_reindex:  r  z!View.create.<locals>.fake_reindexrc  )r  rY  )r   r   r   rg  )r   r   r   resolve_negative_sizer  rl   r  r  statically_known_list_equalsr   r2   r   r  r  require_contiguousr\  r]  r  r  r  r  r^  r_  r`  r  )	r  r   r6  unbacked_symbols_in_sizesri  ra  rb  rd  r   r   rh  r   r  (  s4   
zView.creater:  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   rl   r  r  ri  rH  r   r   r   r   Z      z.View.resolve_negative_size.<locals>.<listcomp>c                 S  ro  r   rp  rH  r   r   r   r   [  rq  rB  )r   r   r   r   r  Oner;   rg   rl   r  r  check_equals)r:  r6  r   r   r   r   rj  V  s   zView.resolve_negative_sizeNrH  	dense_dimr  r   c              	   C  sZ   z
|  |||}W |S  ttfy,   t|g}|  ||}|  ||}t||}Y |S w r   )_dynamic_reshape_indexerrY  
IndexErrorrg   r   )r  r:  r6  rt  r   flatr   r   r   r   r   r  g  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  r[  r   )rf   r>   VIEWr   r   r   r   r     r]  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  rg  r   )rh   rH  replacementsr   r   r     rj  zAView._dynamic_reshape_indexer.<locals>.reindex.<locals>.<genexpr>)r   r   r   r   r   r  	view_exprry  r   r     s   $z.View._dynamic_reshape_indexer.<locals>.reindexr?  )rl   r  r  r  r   r   r   r   r  r  r   r  r  rs  rr  r=   rY  reverseinsert)r:  r6  rt  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   ru  x  s   
	






 zView._dynamic_reshape_indexer)r   r    r  r    r   r    )r   r   r6  r  r   r   )r:  r  r6  r  r   rn  r   )r:  rH  r6  rH  rt  r  r   r   )r:  r  r6  r  rt  r  r   r   )
r   r   r   rN  rf  r  r  rj  r  ru  r   r   r   r   r    s    -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 )Ar`  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 )NrZ  )ru  r  r   rZ  r  r   r  r  r  rv  r   r   r    s   
zReinterpretView.__post_init__r   c                 C     |  | j| jgS r   )r  rZ  r[  r  r   r   r   r{    s
   zReinterpretView.__str__c                 C  r(  r   r,  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   r@    r   zReinterpretView.get_strider  c                      d fdd}|S )Nr   r  r   rk   c                   sF    j  }t  || } j j jjkr!t| j jjS |S r   )r[  r  rj   loadr  r  rZ  to_dtype_bitcast)r   r  
tmp_loaderr  r   r   r    s
   
z+ReinterpretView.make_loader.<locals>.loaderr   r  r   rk   r   r'  r   r  r   r    s   zReinterpretView.make_loaderr  c                 C  r(  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_layoutFru  r   r   c                 C  s*   t | jj|t | jj|B t | jj|B S r   )r(   r[  r  r  r^  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  )rl   r  wrapper_codecodegen_reinterpret_viewrZ  r[  r  r  r^  	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_readsr)  r;  r6  r+  r.  r2  r8  r9  r/  r?  rH  r   r5  rF  )r   r   r   rK  r   r  r{  r  r  r!  r  rQ  r  r  r@  r  r  r  r	  rW   r  r  r  r  r   r   rv  r   r`    s,   
 









	r`  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 )NrY  )rZ  r  )
r  r\  r]  r  r  r  r^  r_  r`  r  )r  r   r  ra  rb  rd  r   r   r   r  1  s   zDtypeView.creater   c                 C  r  r   )r  rZ  r  r  r   r   r   r{  @  r  zDtypeView.__str__c                 C  r  r   )r  r  r   r   r   r  E     zDtypeView.dtyper  c                 C  r(  r   rZ  r  r  r   r   r   r  I  r  zDtypeView.get_sizer  c                   s   j   d fdd}|S )Nr   r  r   rk   c                   s   t  | jjjS r   )rj   r  r  rZ  r  r  r$  r  r   r   r  O  s   z%DtypeView.make_loader.<locals>.loaderr  rZ  r  r'  r   r  r   r  L  s   
zDtypeView.make_loaderN)r   r   r  r  r   r  r;  r.  r2  r8  )r   r   r   rK  r   r  r  r{  r  rQ  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   rN  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   )r2   rH  r   r   r   r   a  r(  z0SliceView.normalize_start_end.<locals>.<genexpr>r   r    lowerr   upperr   c                   s<    | |r| n | |}||r|}|S ||}|S r   )statically_known_geqrK  )r   r  r  clamped_lowerclamped_full)max_funcmin_funcr  r   r   clamph  s   
z,SliceView.normalize_start_end.<locals>.clamprX  Union[int, None]r~  Union[Expr, int]c                   s$   | d u r|S  | }  | ||S r   )rf  )rX  r  r  r~  )r  r  dim_sizer   r   
clamp_wraps  s   z1SliceView.normalize_start_end.<locals>.clamp_wrapr   N)r   r    r  r   r  r   r   r    )
rX  r  r  r   r  r   r~  r  r   r  )
rl   r  r  r  r  r   MinMaxevaluate_minevaluate_max)r  r   rN  r  r  r  r   )r  r  r  r  r  r  r   normalize_start_endV  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?   rY  r   r  r   c                   sD   t | t ksJ d|  d t| } |     |  < | S )Nzwrong ndim rT  )r   r   r   rN  r6  r  r  r   r   r     s   $z!SliceView.create.<locals>.reindexrc  r?  )r   rP  r   r    	TypeErrorr   r  r  r<   r  r\  r  r]  r  r  r^  r_  r`  r  )r  r   rN  r  r  r  r  ra  rb  rc  rd  r   r   r  r   r    s8   


	zSliceView.createN)
r   r   rN  r   r  r   r  r   r   r  )r?   T)r   r   rN  r   r  r   r  r   r  r   r  r   r   r   )r   r   r   r  r  r  r   r   r   r   r  U  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    r  zBaseConstant.get_sizer  c                 C  r  r   r|  r  r   r   r   r!    r  zBaseConstant.get_devicer  c                 C  r
  r   r   r  r   r   r   r    r  zBaseConstant.get_origin_noder  c                 C  r^  r   r9   r  r   r   r   r    r  zBaseConstant.get_readsNr2  r6  r+  rE  )r   r   r   r   r  r!  r  r  r   r   r   r   r    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   rk   c                      t  j jS r   )rj   r  r'  r  r   r  r   r   r    r`  z$Constant.make_loader.<locals>.loaderr  r   r'  r   r  r   r       zConstant.make_loaderr-  c                 C  r
  r   r   r  r   r   r   r    r  zConstant.realizer   c                 C     t | j| j|dS )N)r'  r  r  )r  r'  r  r  r   r   r   r$    r  zConstant.constant_to_deviceNr8  r4  rI  )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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   rk   c                   r  r   )rj   rQ  r   r  r   r  r   r   r    r`  z,IndexingConstant.make_loader.<locals>.loaderr  r   r'  r   r  r   r    r  zIndexingConstant.make_loaderr   c                 C  r  )N)r   r  r  )r  r   r  r  r   r   r   r$    r  z#IndexingConstant.constant_to_deviceNr8  rI  )r   r   r   r   r  r$  r   r   r   r   r    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   rl   r  r  rL  r   r  )r  rJ  expected_strideexpected_stride_maxr   yr   r   r   is_contiguous_strides_for_shape  s   
r  c                 C  s   t j| j S r   )r@   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_sizeFru  r   r   c                 C  r  r   r  r  r   r   r   r    r  zOutputSpec.get_free_symbol_usesNr6  rF  r?  rH  )r   r   r   rK  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]]r^  r    r_  r   r   r   c                 C  s   |d u r	t |}|| _|| _t|t|ks!J d| d| tdd |D s,J || _|| _|| _|| _	| j	rC| jj
dksEJ d S d S )Nrb  	, 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  )r  r  r  r  r   r   _size_stride_offsetr_  r   )r  r  r  r  r  r^  r_  r   r   r   r    s   	
$zLayout.__init__c                 C  r  r   r  r  r   r   r   r  3  r  zLayout.sizer'  c                 C  
   || _ d S r   r  r  r'  r   r   r   r  7  r)  c                 C  r  r   r  r  r   r   r   r  ;  r  zLayout.stridec                 C  r  r   r  r  r   r   r   r  ?  r)  c                 C  r  r   r  r  r   r   r   r^  C  r  zLayout.offsetc                 C  r  r   r  r  r   r   r   r^  G  r)  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/  )	r^  r  r   r_  r   r   r  r  r  )r  r^  device_index_stris_pinned_strr   r   r   r{  K  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)
rl   	fake_moder#  r$  rZ   r  r  r  r  r_  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
  h  r   zLayout.is_contiguousrJ  rH  rS  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,   )rJ  rS  ndimleftrightr  r   r   r   is_channels_last_contiguousk  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_transposedy  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   r7  r?   )rl   r  r  r  )r   r   rN  r   r   r   r     s
    z,Layout.is_stride_ordered.<locals>.<listcomp>c                   rC  r   rE  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_indicesrB  r?   T)size_obliviousF)r  r   r   r   )r   r  r   r  r   r   r   rl   r  
_shape_envrd  )r  r   non_1_indicesr  r  stride_orderedr   exprr   )r   r  r   r    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  r  r  r   r   r   is_channels_last_stride_ordered  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tjdr3tjjnddfdd rKt fdd| D rK| 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}qq|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   rm  dislike_paddingFr  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     rj  zILayout._pad_strides.<locals>.contains_unbacked_symints.<locals>.<genexpr>)r   r   r    r  r1   r  r  r   r   contains_unbacked_symints  s
   z6Layout._pad_strides.<locals>.contains_unbacked_symintsc                 3  r  r   r   r   )r  r   r   r     r(  z&Layout._pad_strides.<locals>.<genexpr>c                 S  r   r  r   r  r   r   r   r     r  z'Layout._pad_strides.<locals>.<listcomp>r?   )r  T)r  r  r   r   )r  r   r@   pad_channels_lastr  r  rl   get_current_noder  rm  r  r  r  r  r  r   r   r   r   r   r   r!   padding_stride_thresholdr    pad_dynamic_shapesrX   r&   num_comprehensive_padding)r  r  r  aligncurrent_fx_noder  r   new_stridespaddedrankr   prev_idxr  require_paddingr   )r  r   r   _pad_strides  sP   


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   )r@   comprehensive_paddingr   r  r  r   r   r   r    r`  zLayout.should_pad_stridesr]  c                 C  s<   t | tr| S |  r|   t| j| j| j| j| j| j	S r   )
r   r]  r  r	  r  r  r  r  r^  r_  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  r^  r_  )r  r  r   r   r   __eq__  s   






zLayout.__eq__c                 C     t | j| j| jS r   )r)   r  r  r^  r  r   r   r   r    r  zLayout.storage_sizeru  r   c                 C  s$   t | j|t | j|B t | j|B S r   )r(   r  r  r^  r  r   r   r   r    s   


zLayout.get_free_symbol_uses)r  r  r  r  r  r  r  r  r^  r    r_  r   r   r   r2  r'  r  r   r   r3  r'  r    r   r   r;  r7  )r   r  r1  )rJ  rH  rS  rH  r   r   )r   r   r   r   )r  r   r  r  r  r  r   r   r)  )r   r]  r9  )r  r   r   r   r?  rH  )r   r   r   rK  r!   r  rQ  r  setterr  r^  r{  r  r!  r  r
  rN  r  r  r  r  r  r	  r  r  r  r  r  rW   r  r   r   r   r   r    sN    








#
D




r  c                   @  s   e Zd ZdZdddZdS )r]  z A Tensor layout we cannot changer   r  c                 C  r  )r  )rV  r  r  r^  r  r   r   r   r  *  rI  zFixedLayout.make_indexerNr9  )r   r   r   rK  r  r   r   r   r   r]  '  s    r]  c                      s  e Zd ZdZdZedBddZedCd
dZedDddZedEddZ	edFddZ
edGddZejdHddZedGddZejdHddZedId d!ZejdJd"d!Z	dKdLd&d'Z	dKdMd)d*ZdNd+d,ZdOd-d.ZdPd0d1ZdQd5d6Z	7	dRdS fd@dAZ  ZS )Tr  z|
    A Tensor layout that we are allowed to change

    Assumption: layout change should NOT add or remove free symbols
    Fsizesr   r   rs  c                 C  sN   t | dkrg S tjjg}t| dd  D ]}|||d   qtt|S )Nr   r?   rB  )r   r   r  rr  r  r  r   )r  reversed_stridesr  r   r   r   r  9  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)r:   r   r   r   r  rr  )r  r   next_striderS  r   r   r   r   fill_orderedB  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]
        )r:   r   r   r   r  r  )r  r   r   r   r   r   r  S  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  r1  r  r  )r  r  r   r   r    stride_ordered_for_memory_format_  s   



z/FlexibleLayout.stride_ordered_for_memory_formatr  rH  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  ro  r   )rl   r  r  r?  rH  r   r   r   r     rq  z/FlexibleLayout.same_ordered.<locals>.<listcomp>r  )r   r  r   __getitem__r  r  )r  r  r   r   r   r   same_orderedz  s   
zFlexibleLayout.same_orderedc                 C  r  r   r  r  r   r   r   r    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    r  zFlexibleLayout.stridec                 C  r  )Nr  )r  r  r  r   r   r   r    r  r    c                 C  r  r   r  r  r   r   r   r^    r  zFlexibleLayout.offsetc                 C  r  )Nr^  )r  r  r  r   r   r   r^    r  r
  r   r]  c                 C  sH   |  | j|}|  r|r| || j| j}t| j| j| j|| j| jS r   )	r  r  r  r  r  r]  r  r^  r_  )r  r   r
  rc  r   r   r   as_stride_order  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  r]  r  r^  r_  )r  r  r
  rc  r   r   r   as_exact_strides  s   zFlexibleLayout.as_exact_stridesc                 C  D   |  | j|}|  r| || j| j}t| j| j| j|| j| jS r   )	r  r  r  r  r  r]  r  r^  r_  )r  r   rc  r   r   r   as_fill_order     zFlexibleLayout.as_fill_orderc                 C  r  r   )	r  r  r  r  r  r]  r  r^  r_  )r  r  rc  r   r   r   as_same_order  r  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  r^  TF)r:   r(   r   )r  initial_free_symbolsr   ru  r  r   r   r   get_initial_free_symbol_uses  s   
z+FlexibleLayout.get_initial_free_symbol_usesr   r   r3   c                 C  sF   dD ]}| j ||f }tt||}||ks J d| d| qd S )Nr   z)Expected free symbols unchanged, but got z vs )r!  r:   r(   )r  r   r'  ru  old_free_symbolsnew_free_symbolsr   r   r   r    s   
z0FlexibleLayout.assert_free_symbol_uses_unchangedNr  r  r  r  r  r  r  r_  c                   s@   |r	t ||}nt |}t j|||||d |  | _d S )Nr_  )r  r  r  ru  r  r"  r!  )r  r  r  r  r  r_  rS  rv  r   r   r    s
   
zFlexibleLayout.__init__)r  r   r   rs  )r  r   r   r   r   rs  )r  r   r   r   r   r  )r  r   r  r  r   r  )r  r   r  rH  r   r  r2  r  r3  r  r?  )r   r   r
  r   r   r]  )r  rH  r
  r   r   r]  )r   r   r   r]  )r  rH  r   r]  )r   r  )r   r   r'  r3   r   r   r  )r  r  r  r  r  r  r  r  r_  r   r   r   )r   r   r   rK  r  rN  r  r  r  r  r  rQ  r  r  r  r^  r  r  r  r  r"  r  r  r  r   r   rv  r   r  /  sH    



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  ru  r  r  r  r  r  r'  )r  r'  r[  rv  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)	r'  r  r^  utilsr*  rl   r  r  r  )r  r^  r*  r   r   r   maybe_guard_aligned  s
   z#NonOwningLayout.maybe_guard_alignedFru  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   r'  r`  rZ  r  r   r  r[  r  )r  ru  boxinput_bufferr   r   r   r    s   z$NonOwningLayout.get_free_symbol_uses)r'  r(  r   r   r9  r1  r?  rH  )
r   r   r   rK  r  r  r,  rW   r  r  r   r   rv  r   r&    s    


r&  c                   @     e Zd ZdZdS )CommBufferTypesymm_memN)r   r   r   SYMM_MEMr   r   r   r   r0  (      r0  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].
    r0  comm_buffer_typer   
group_namer[  r  c                   sV   t |tstd| d| }t j|j|j|j|j	|j
|jd || _|| _d S )NzJA `CommBufferLayout` can only be initialized with a `FlexibleLayout` (got z).r  r  r  r  r^  r_  )r   r  rY  r  ru  r  r  r  r  r  r^  r_  r5  r6  )r  r[  r5  r6  fixedrv  r   r   r  ;  s"   

zCommBufferLayout.__init__)r[  r  r5  r0  r6  r   )r   r   r   rK  r   r  r  r   r   rv  r   r4  ,  s
   
 r4  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_factoryrG  r  c                   C  r:  r  r   r   r   r   r   r  `  r  r  r   r   c                 C  r  r  r   r  r   r   r   r  b  r  zNoneLayout.storage_sizer0  c                 C     | S r   r   r  r   r   r   r  e  r  zNoneLayout.as_fixedc                 C  r  r   r|  r  r   r   r   r!  h  r  zNoneLayout.get_deviceNrF  r0  r6  )r   r   r   r   rL  rM  r  r  r  r  r!  r   r   r   r   r9  T  s   
 


r9  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   )ru  r  r  r   r  r@  
get_bufferr  rl   r  mark_buffer_mutated)r  r@  r   rv  r   r   r  m  s   z#MutationLayoutSHOULDREMOVE.__init__r  c                 C  r  r   )real_layoutr  r  r   r   r   r  x  r)  z!MutationLayoutSHOULDREMOVE.strider'  r   c                 C  r
  r   r   r  r   r   r   r  |  r  r    c                 C  r)  r   )rA  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   r>  r@  r  r  
MutableBoxrZ  )r@  unwrap_viewsr   r   rD    s   




z;MutationLayoutSHOULDREMOVE.get_buffer.<locals>.unwrap_views)r@  r   r   r   )r@  r   r  r   )r  r  r   rC  r   r?    s   
	z%MutationLayoutSHOULDREMOVE.get_bufferr  c                 C  s   |   j}t|tsJ |S r   )r?  r[  r   r  )r  r[  r   r   r   rA    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   rl   r  r  check_equals_and_simplifyr   r  r  r   r   r   r         z;MutationLayoutSHOULDREMOVE.realize_into.<locals>.<listcomp>r  rZ  )r  rl   r  r@  r  r   r   rZ  r  r  r  r!  r   r  r   r  r  rB  r  r[  r  r   r>  )r  rE  rF  rG  r   r   r   r   realize_into  s*   
	z'MutationLayoutSHOULDREMOVE.realize_intor   c                 C  r=  r   r   r  r   r   r   r    r  z#MutationLayoutSHOULDREMOVE.as_fixedr  c                 C  r(  r   )r@  r  r  r   r   r   r    r  z'MutationLayoutSHOULDREMOVE.make_indexer)r@  r   r   r   r2  )r'  r   r   r   r3  )r   r  r/  r?  )rE  r   rF  r   rG  r   r   r   )r   r   r9  )r   r   r   r  rQ  r  r  r  r?  rA  r  rM  r  r  r  r   r   rv  r   r>  l  s    



'r>  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 rX  )ru  r  r  r  rv  r   r   r    s   
zBuffer.__post_init__r  c                 C  r)  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    rY  zBuffer.get_name!Union[torch.Tensor, sympy.Symbol]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  r)  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    r)  zBuffer.dtyper  c                 C     g |   jS r   )r  r  r  r   r   r   r    r   zBuffer.get_sizers  c                 C  rO  r   )r  r  r  r   r   r   r@    r   zBuffer.get_strider    c                 C  r  r   )r  r^  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  r_  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  r&  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   r  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   r  r  r   r   r   r       z$Buffer.freeze_layout_with_fill_orderr  c                 C  rT  r   )r   r[  r  r   r  r  r   r   r   r    rU  z$Buffer.freeze_layout_with_same_orderr  c                 C  rR  rS  )r   r[  r  r   r  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   rk   c                   s      }t jp
d|| S r  )r  rj   r  r   r   r  r  r   r   r  $  s   z"Buffer.make_loader.<locals>.loaderr  )r  r   r  r   r'  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[  r&  r'  r  r  r   r   r   r'  0     z#Buffer.get_inputs_that_alias_outputc                 C  rX  r  )r   r[  r>  r@  r  r  r   r   r   r%  5  rY  zBuffer.get_mutation_namesr  c                 C  s   t |  gS r   )r:   r  r  r   r   r   r  :  r   zBuffer.get_read_namesru  r   c                 C  r^  r   r9   r  r   r   r   r  =     zBuffer.get_free_symbol_usesc                 C  r^  r   r9   r  r   r   r   r_  C  r  zBuffer.get_unbacked_symbol_defsc                 C  r
  r   r   r  r   r   r   r  F  r  zBuffer.realizec                 C  r  r  r   r  r   r   r   should_allocateI  r  zBuffer.should_allocater)  r9  r;  )r   rN  r6  r,  r.  r2  )r   rs  r3  r/  r0  rF  r1  r?  r@  rA  )r  r   r   r   )r  r   r
  r   r   r   r8  r   r5  rJ  r*  rH  rb  r4  )%r   r   r   r   r  r  r  r  r!  r  rQ  r  r  r@  rP  r  r  r  rQ  r	  r  r  r  r  r  r  r  r  r'  r%  r  rW   r  r_  r  r[  r  r   r   rv  r   r    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   r\  c                 C  s   | gS r   r   r  r   r   r   r]  Q  r  zOperationBuffer.get_outputsrR  c                 C  r=  r   r   r  r   r   r   r  T  r  zOperationBuffer.get_defining_opr   c                 C  s   t |  t|  d S r   )r  r  rR  r  r   r   r   r  Z  s   
zOperationBuffer.__post_init__Nra  r   rR  r)  )r   r   r   r]  r  rR  r&  r  r   r   r   r   r\  N  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_readsNrF  )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   rK  r   r   r   r   r`  d  r3  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   rk   c                   s,       }ttj   j|| S r   )	r  r  rj   r  rl   r  constant_namer  r  rV  r  r   r   r  r  s
   z*ConstantBuffer.make_loader.<locals>.loaderr  r   r'  r   r  r   r  q  s   zConstantBuffer.make_loaderr  r  r   c                 C  s   t tj|  || jdS N)r   r[  )r  rl   r  ra  r  r[  r  r   r   r   r$  {  s   z!ConstantBuffer.constant_to_devicer8  rI  )r   r   r   r  r   r  r$  r   r   r   r   r  n  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  r^  r   r9   r  r   r   r   r    r  zNoneAsConstantBuffer.get_readsFru  r   r   c                 C  r^  r   r9   r  r   r   r   r    rZ  z)NoneAsConstantBuffer.get_free_symbol_usesNr  r  r   c                 C  s
   t jjjS r   )rl   r  r  none_strr  r   r   r   r    r  z&NoneAsConstantBuffer.codegen_referencer0  c                 C  s
   t d dS Nr|  )r9  r  r   r   r   r    r  z$NoneAsConstantBuffer.get_output_specc                 C  r  r  r   r  r   r   r   r    r  z&NoneAsConstantBuffer.has_tensor_outputrE  r?  rH  r   r5  r0  r1  )	r   r   r   r  rW   r  r  r  r  r   r   r   r   rc    s    

rc  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  Fru  r   r   r   c                 C     t | j|S r   )r(   r  r  r   r   r   r       z*ShapeAsConstantBuffer.get_free_symbol_usesNr  r  r   c                 C  s   t jj| jS r   )rl   r  r  codegen_sizevarr  r  r   r   r   r    r`  z'ShapeAsConstantBuffer.codegen_referencec                 C  r  r  r   r  r   r   r   r    r  z'ShapeAsConstantBuffer.has_tensor_outputr?  rH  r   r5  r1  )r   r   r   r   rW   r  r  r  r   r   r   r   r     s   
 r   c                      s  e Zd ZU dZded< dZded< eejdQd	d
Z	dRddZ
dSddZdTddZdUddZdVddZed 	dWdXddZdY fd d!ZdZd"d#Zd[d%d&Zd\d(d)Zd]d+d,Zed^d.d/Z	0	0d_d`d6d7Ze	0dadbdAdBZdcdDdEZdRdFdGZdZdHdIZdZdJdKZdddOdPZ  ZS )er  zb
    Represents a buffer that is computed during kernel execution rather than being an input.
    rc  rZ  FzClassVar[bool]_force_realizer   Iterator[None]c                  c  s*    t j} zdt _d V  W | t _d S | t _w NT)r  ri  )	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  rZ  r  r   r   r   get_computed_buffer_name  s
   
z'ComputedBuffer.get_computed_buffer_namer   c                 C  r(  r   rZ  r  r  r   r   r   r    r  zComputedBuffer.num_readsr  c                 C  r(  r   rZ  r  r  r   r   r   r    r  zComputedBuffer.get_readsr  c                 C  r(  r   r4  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   rZ  r  r  r  r  rA   
ReadWritesr:   r   r   r  r   rJ   get_store_functionr}  r!  r  r  r   r   r   r    s&   
$zComputedBuffer.get_read_writesru  r   r   c                 C  sD   | j || j|B }|  r t|  tr ||  |O }|S r   )r[  r  rZ  has_store_functionr   ru  rL   r  )r  ru  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   rl   r  mutated_buffersr  ri  rZ  r  ru  r  rv  r   r   r    s   

zComputedBuffer.make_loaderc                 C  s   t | jttttfS r   )r   rZ  r  r  r  r  r  r   r   r   rv  
  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   rZ  r  r  r  r   r  r   r  r   r  r%  r   r   r   ru    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   rA   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  rc  )r   vr   r   r   r   )      z<ComputedBuffer.get_fill_order.<locals>.<listcomp>.<dictcomp>)r   rA   r{  rh   r   r  )r  r   r   r   (  s    
z1ComputedBuffer.get_fill_order.<locals>.<listcomp>c                   s   g | ]
}t jj| qS r   rl   r  r  r4  r   r  )r"  r   r   r   3  s    r?   pick_loop_orderN)r   r[  r  rA   r2  rZ  r}  r!  r  r  r   r  r  r   	schedulerr  r  )r  
index_varsr  r  stride_lengthsr  r   )r"  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| j | j dd\}}ttd|   t	| 
 |  r$|n|d d |g|R  }W d    n1 s:w   Y  g }g }g }g }| D ]+\}}	||d v rd|rYJ || ||	 qK||d v slJ || ||	 qK||f|||ffS )Nqr{   r  r?   r   )rA   r2  rZ  r}  r!  r   r   r  r!  rL   ru  r   itemsr  )
r  r   
var_rangesr  r  reduce_vars
index_sizereduce_sizer}  r   r   r   r   get_default_sizes_bodyD  s2   



z%ComputedBuffer.get_default_sizes_bodyNextra_indexing_constraints*Optional[tuple[dict[Any, Any], list[Any]]]recompute_sizes_body_funcOptional[Callable[..., Any]]8tuple[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     rj  z6ComputedBuffer.simplify_and_reorder.<locals>.<genexpr>c                   s   g | ]}| vr|qS r   r   rh  )index_formulasr   r   r         z7ComputedBuffer.simplify_and_reorder.<locals>.<listcomp>x_varsSequence[sympy.Symbol]support_varsr  r   simplify_loopsr   r   dtuple[list[int], Callable[[Sequence[int]], Sequence[int]], Callable[[Sequence[int]], Sequence[int]]]c           	        s\    | ||\}}}|| } |r'tjj| |t | |\}}}t||}n|}|||fS r   )_apply_loop_reorderingrl   r  r  _simplify_loopsrE   r   )	r  r  r  r  reindex0r   r   _pruner   r  memory_addrsr  r   r   simplify_and_reorder  s   




zAComputedBuffer.simplify_and_reorder.<locals>.simplify_and_reorderpr{   )
r  r  r  r  r  r   r  r   r   r  )r  indexing_exprsr   r   r   r   r   r   r   r   r  get_write_exprsrl   r  r)  rB   PREFER_STORE_LOOP_ORDERextendget_read_exprsrc   r1  r@   loop_ordering_after_fusionrA   index_vars_no_squeezerL   )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  e  sx   



z#ComputedBuffer.simplify_and_reorderr  r  r  r  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  	Exceptionr@   r  r1  warningr   r   r   r   r   )r  r  r  r  r  r  rS  r   r   )r  r  r  r   r    s,   
z%ComputedBuffer._apply_loop_reorderingr  c                 C  r(  r   rZ  r!  r  r   r   r   r!  	  r  z!ComputedBuffer.get_reduction_sizec                 C  r(  r   rZ  r   r  r   r   r   r     r  z!ComputedBuffer.get_reduction_typec                 C  r(  r   )rZ  r  r  r   r   r   r#    r  zComputedBuffer.is_no_opc                 C  r  rk  r   r  r   r   r   r[    r  zComputedBuffer.should_allocater  r  r   c                 C  r  )r  rZ  r$  r  r   r   r   r$    r  z!ComputedBuffer.constant_to_device)r   rj  r4  rF  rE  r*  rD  r?  rH  r8  r1  )r   rx  )r   ry  r)  )r   r  NN)r  r  r  r  r   r  r   )r  r  r  r  r  r   r  r  r  ry  r   r  r2  rI  ) r   r   r   rK  r   ri  rN  rO  rP  rm  rn  r  r  r  r  rW   r  r  rv  ru  r   r  rV   r  r  r  r!  r   r#  r[  r$  r  r   r   rv  r   r    sB   
 








'"|
'


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  rq  rr  make_kernel_renderr  r   r   c                   s@   t  jd |d t|| _|| _tj| | _	tj
|  d S rb  )ru  r  r  unwrap_storagerq  r  rl   r  register_bufferr   register_operation)r  r[  rq  r  rv  r   r   r     s
   zTemplateBuffer.__init__r  c                 C  s   | j ddS )NT	normalize)rJ   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   rj   r  rS  )r  r   r   r   dummy3  s   z1TemplateBuffer.extract_read_writes.<locals>.dummyr   r  c                   s$   t |dksJ t  | S r  )r   rj   r  r  rS  )r  rw  r   r   r  A  s   )r   r  r  r  r   r   )r  r  r  rA   rJ   r  rq  r   r`  r  r   r[  r  r  )r  r  r  depsr   )r  rw  r   r   rJ   /  s"   


z"TemplateBuffer.extract_read_writesr  c                 C  s   t jjS r   )r   r  rr  r  r   r   r   r!  K  r  z!TemplateBuffer.get_reduction_sizer-  c                 C  r
  r   r   r  r   r   r   r   N  r  z!TemplateBuffer.get_reduction_typec                 C  r  rk  r   r  r   r   r   r[  Q  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  T  s
   z#TemplateBuffer.simplify_and_reorder)r[  r0  rq  rr  r  r  r   r   rD  r?  )r  r   r   r  r2  r4  r1  r  )r  r  r  r  r   r  )r   r   r   rK  r  r  rJ   r!  r   r[  r  r  r   r   rv  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  rq  rr  r  Optional[Callable[_P, _T]]mutated_inputsOptional[Iterable[IRNode]]allowed_prologue_inpsOptional[OrderedSet[str]]r   r   c                   s   t  ||| |_g_|durWtjjjtjjjf}t	j
jj}||v s0J d| d| tjd tsAJ 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.
        Nz$Mutated inputs are only allowed for z	 but got r   c                      g | ]}t t d |qS r|  MutationOutputr9  r   r$  r  r  r   r   r     r  z1TritonTemplateBuffer.__init__.<locals>.<listcomp>)ru  r  r  outputsr#  rj   higher_orderflex_attentionflex_attention_backwardrl   r  current_noder@  r   rq  r   r   r!  r:   r  subgraph_inpssubgraph_outs)r  r[  rq  r  r  r  allowed_setr  rv  r  r   r  c  s(   

"

zTritonTemplateBuffer.__init__Fru  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   )
ru  r  r  r  r   r   r    updater(   r   )r  ru  resr  r  rw  r  rv  r   r   r    s   

z)TritonTemplateBuffer.get_free_symbol_usesr\  c                 C  r  r   r  r  r   r   r   r]    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  rq  rr  r  r  r  r  r  r  r   r   r?  rH  ra  r*  r;  )
r   r   r   r  rW   r  r]  r  r{  r  r   r   rv  r   r  b  s    ,

r  c                      sr   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  ZS )+ChoiceCallera.  
    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, CUDATemplateCaller.
    r   r   r   r\  r[  r  descriptionr   r   c                   s&   t    || _|| _|| _|| _d S r   )ru  r  r   r[  r   r  )r  r   r   r[  r  rv  r   r   r    s
   

zChoiceCaller.__init__r   r   r  r  r  c                  sL   |    ttd}tjrt fddfi |S tj d|ifi |S )N)warmuprepc                     s     S r   r   r   algor   r   r   r    s    z(ChoiceCaller.benchmark.<locals>.<lambda>r  )to_callableautotune_warmupautotune_repr@   /profile_bandwidth_with_do_bench_using_profilingr\   rQ   	benchmark)r  r  r   benchmark_configsr   r  r   r    s   zChoiceCaller.benchmarkc                 C  rU  r   rV  r  r   r   r   	call_name  r  zChoiceCaller.call_namerd  c                 C  rU  r   rV  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  rU  r   rV  r  r   r   r   r    r  zChoiceCaller.hash_keyr~  c                 C  rU  r   rV  r  r   r   r   ro    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_id)
r   r   r   r\  r[  r  r  r   r   r   )r   r   r  r  r   r  r;  )r   rd  )r   r~  )r   r  )r   r   r   rK  r  r  r  r  r  r  ro  r  r  r  r   r   rv  r   r    s    







r  c                   @  r^  )TritonTemplateCallerBaser   r   c                 C  rU  r   rV  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                      sp   e Zd ZdZd' fddZed(ddZ	d)d*ddZej	d+ddZ
d,ddZ	d)d-d!d"Zd.d%d&Z  ZS )/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  rq  rr  choice_timings_fn4Callable[[Optional[int]], dict[ChoiceCaller, float]]unfiltered_choiceslist[ChoiceCaller]r  r  r   r   c                   sD   t  j||d |d || _i | _|| _tdd |D | _i | _d S )N)r[  rq  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>)ru  r  _choice_timings_fn_choice_timingsoriginal_inputsr   _output_plannable_make_kernel_renders)r  r[  rq  r  r  r  rv  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_plannableNhint_overrider  dict[ChoiceCaller, float]c                 C  s$   || j vr| || j |< | j | S r   )r  r  )r  r  r   r   r   choice_timings"  s   

z"MultiTemplateBuffer.choice_timingscallerr  rj  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  r  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  r  r   r  r[  r  r@  r  r  r  )r  r  r   r   r   finalize_as_triton_caller7  s   
z-MultiTemplateBuffer.finalize_as_triton_callertuple[ChoiceCaller, float]c                 C  s&   | j |d}t||jd}||| fS )N)r  r  )r  r  r  )r  r  timings
min_choicer   r   r   get_min_choice?  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  r  r  r   r   r   finalize_as_triton_callersF  s   z.MultiTemplateBuffer.finalize_as_triton_callers)r[  r  rq  rr  r  r  r  r  r  r  r   r   r1  r   )r  r  r   r  )r  r  r   rj  )r  r  r   r   )r  r  r   r  )r  r  r   r   )r   r   r   rK  r  rQ  r  r  rO  rP  r
  r  r  r  r  r   r   rv  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 )CUDATemplateBufferr[  r  rq  rr  r  Callable[_P, _T]workspace_sizer   templaterp   supports_epilogue_fusionr   r   r   c                   s&   t  ||| || _|| _|| _d S r   )ru  r  r  r  r  )r  r[  rq  r  r  r  r  rv  r   r   r  R  s   	
zCUDATemplateBuffer.__init__c                 C  s   | j d ur| j S dS r  )r  r  r   r   r   r`  a  r   z%CUDATemplateBuffer.get_workspace_sizec                 C  s$   |   D ]}t| d d  qd S r   )r]  rj   r  r  )r  rh  r   r   r   emulate_store_fnd  s   z#CUDATemplateBuffer.emulate_store_fn)r[  r  rq  rr  r  r  r  r   r  rp   r  r   r   r   rF  r)  )r   r   r   r  r`  r  r  r   r   rv  r   r  Q  s    
r  c                      s,   e Zd Zd fddZd fddZ  ZS )CppTemplateBufferr[  r  rq  rr  r  r  r  rp   r  r   r   r   c                   s&   t  ||| || _|| _d | _d S r   )ru  r  r  r  r  )r  r[  rq  r  r  r  rv  r   r   r  j  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  ru  r  )r  first_outputr[  rv  r   r   r  w  s   

zCppTemplateBuffer.get_layout)r[  r  rq  rr  r  r  r  rp   r  r   r   r   r/  )r   r   r   r  r  r  r   r   rv  r   r  i  s    r  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  rq  rr  r  r  r  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>)
ru  r  r  r  r  r   rq  r   r   r!  )r  r[  rq  r  r  r  rv  r  r   r    s   "zCuteDSLTemplateBuffer.__init__r\  c                 C  r  r   r  r  r   r   r   r]    r  z!CuteDSLTemplateBuffer.get_outputsr   )r[  r  rq  rr  r  r  r  r   r  r  r   r   ra  )r   r   r   rK  r  r]  r  r   r   rv  r   r    s
    r  r   )Sequence[Union[IRNode, Sequence[IRNode]]]TypeIs[Sequence[IRNode]]c                 C  s   t dd | D S )Nc                 s  r  r   r   r   r\  r   r   r   r     rj  z#is_node_sequence.<locals>.<genexpr>)r   )r   r   r   r   is_node_sequence  rL  r   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  r  rq  r   r   r   r   c                 C  s    | j | }t|tsJ | S r   rq  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   rW  rH  rz  r   r   r     r  z/InputsKernel.get_read_writes.<locals>.<genexpr>c                 3  r$  r   rW  r  r%  r   r   r         
rq  )r:   rA   rG   rz  rq  r   r   r  r   r  r  r]  rt  )r  r  r"  rr  r   r%  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   rZ  r  r  r`  r  realize_inputunwrap_storage_for_inputTorchBindObjectr  r   r  r   r   r   r   r(    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  rN  r   )r  r(  r   r   r   r   r     r   z/InputsKernel.unwrap_storage.<locals>.<listcomp>)r   r   r  r(  r  )rq  
inputs_newr   r   r   r   r    s   

zInputsKernel.unwrap_storager   c                 C  r  rk  r   r  r   r   r   r"    r  zInputsKernel.is_externc                 C  r  r  r   r  r   r   r   r    r  zInputsKernel.num_readsFru  r   c                 C  sN   t tj  }| jD ]}t|tr|||O }q	|D ]	}|||O }qq	|S r   )r:   r   r"   rq  r   r   r  )r  ru  r  rw  	inner_inpr   r   r   r    s   

z!InputsKernel.get_free_symbol_usesN)r   r   r   r   rD  rE  r   r   r   r   )rq  r  r   r+  r1  rF  r?  rH  )r   r   r   r   r#  r  r  r  r(  rN  r  r"  r  rW   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  rk  r   r  r   r   r   r#    r  zNopKernel.is_no_opr  c                 C  r^  r   r9   r  r   r   r   r    r  zNopKernel.get_readsNr1  rE  )r   r   r   r#  r  r   r   r   r   r/    s    
r/  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.
    rq  rr  rN  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  rH  r   r   r   r   8  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 )rX  r  N)rm  r
  r#  r  r  r   argr   r   r   r   <  s    

c                 s  s"    | ]}t |o| jV  qd S r   )r  r  r_  rH  r   r   r   r   F  s    
N)r  r  r  r  r_  r   r[  rq  )r  )7r!  r   r   r  r   r   r  rl   r  r  rJ  r  r  r@   r   r  r  r  r  r  r   r]  r  r  r  r,   r  r  r   r   r   r0  r  r   r  rB  rM  r  r  r  rq  rZ  r  r  rc   rb   r&  r)  rB   FOREACHregister_operation_listr  r   r  r  )r  rq  rN  r  r  r6  offsets_startoffsets_endr   
input_sizerB  output_strider   r[  any_input_is_storage_and_layoutfx_node_argsr_  concat_kernelkernelop_namesrw  r.  input_unwrappeddevr   r   r   r    s   
 

 zConcatKernel.createNrE  r   rF  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s@dS tdd t| | D S t|jdoct |jjtoct |jt S )NFTc                 s  rU  r   rV  rW  r   r   r   r     rX  z=ConcatKernel.can_realize_into_without_copy.<locals>.<genexpr>r[  )r   r   can_realize_into_without_copyrZ  r  r  r   r  r[  r]  r  r   r@  r   r   r  r  ExternKernelAlloc)r  rE  rF  r   r   r   rB  {  s*   
z*ConcatKernel.can_realize_into_without_copyFru  r   c                 C  s   t | |S r   )r/  r  r  r   r   r   r    rg  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 )NrY  r[  c                 S  rH  r   rI  rK  r   r   r   r     rL  z-ConcatKernel.realize_into.<locals>.<listcomp>r  )r   r`  r  r\  r   r   rM  rZ  r  r  r  rB  r&  r[  r  r  r!  r   r  r   r  )r  rE  rF  ra  r[  pwr   r   r   rM    s,   


	zConcatKernel.realize_intoc                 C  r  rk  r   r  r   r   r   r[    r  zConcatKernel.should_allocate)rq  rr  rN  r   r   r  r   )rE  r   rF  r  r   r   r?  rH  )rE  r   rF  r   r   r   r1  )r   r   r   rK  r  r  rB  rW   r  rM  r[  r   r   r   r   r0    s    n# r0  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dd2d3Zdd4d5Zddd6d7Zdd8d9Zdd;d<Zedd@dAZ e!ddGdHZ"e!ddJdKZ#e!ddLdMZ$e!ddNdOZ%e!			PdddWdXZ&e!	PdddZd[Z'e!	Pddd]d^Z(e!dd_d`Z)e!ddadbZ*e!ddcddZ+e!ddedfZ,ddgdhZ-ddidjZ.dddndoZ/ddpdqZ0ddsdtZ1dddvdwZ2ddxdyZ3ddzd{Z4dd|d}Z5dd~dZ6dddZ7dddZ8e9d 	Pdddd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_argsr;  dict[str, Any]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  rq  r  Optional[dict[str, Any]]r   r   c                   sn   t  j|||d || _|r|ni | _|| _|
| _| | | | |	| _| 	  i | _
g | _tjj| _d S Nr4  )ru  r  rE  r   rH  rN  set_cpp_kernel_nameset_python_kernel_namerL  collect_arg_kwarg_propertiesrR  rS  rl   r  r  fx_node)r  r   r[  rq  rE  r   rH  rI  rJ  rL  rN  rv  r   r   r    s    

zExternKernel.__init__r\  c                 C  s   | g| j S r   )rS  r  r   r   r   r]    r   zExternKernel.get_outputsr   c                 C  r^  r   r9   r  r   r   r   r_    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   rw  )
kwarg_onlyr   	real_typerw  rH  r   r   r   r     s    z=ExternKernel.collect_arg_kwarg_properties.<locals>.<listcomp>c                 S  s   g | ]}i qS r   r   r   r   r   r   r     r  c                 S  s   i | ]}|j |j|jd qS ))r   rw  )r   r[  rw  rH  r   r   r   r     r  z=ExternKernel.collect_arg_kwarg_properties.<locals>.<dictcomp>c                 S     g | ]}|j r|jqS r   rZ  r   rH  r   r   r   r   &  
    c                 S  s   g | ]}|j r|qS r   )rZ  rH  r   r   r   r   )  s
    )r   rN  r#  _ops
OpOverload_schema	argumentsr   r   rq  rO  rP  rL  schema_kwargsr  r   r   r   rX  
  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wrapperrq   c                 C  s$   t | |\}}|r|| d S d S r   )r_   make_comment)r  re  
origin_str_detailed_origin_strr   r   r   codegen_comment4  s   zExternKernel.codegen_commentc                 C  rU  r   rV  r  re  r   r   r   codegen9  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)rJ  rl   r  cpp_wrapperr   rN  r#  r_  r`  	namespace_overloadnamer   r  replacera  r   )r  rJ  r>  opnamer   r   r   rV  <  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.rm  )	rI  rN  r   r#  r_  HigherOrderOperatorr   r   rq  )r  rI  r>  r   r   r   rW  T  s   z#ExternKernel.set_python_kernel_namer   c                 C  s   ddl m} |   }r|jntjj}tjjr!| jd usJ | jS tjj	rDt
tjj|s4J ttjj| jd us;J tjj| j|S | jd usKJ | jS )Nr?   )CppWrapperCpu)codegen.cpp_wrapper_cpurv  r!  r   rl   r  device_type
fx_wrapperrI  rn  r   r  rJ  get_c_shim_func_name)r  rv  dr  r   r   r   get_kernel_namec  s   zExternKernel.get_kernel_namer   r   r~  c                 C  s:   t j|  |  |  |  |  |  d}|  |S )N)r  r  re  rf  r  r~  )	r  r  r!  r   r  r  r  r  r  )r   rD  r   r   r   
copy_inputv  s   zExternKernel.copy_inputr>  rz   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&k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,r_|j-r_d}tjjj !dd  }r[| d| }|tj_.q9||||	|fS )Nr   rB  )rm  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   )iterr  next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   r'  rH  r  r   r   r     r   z/ExternKernel.process_kernel.<locals>.<listcomp>Tr  r4  )r	  rX  r?   zEsparsity not handled. Please file issue for sparse inference weights.r  z Found from : 
 )r  r   r  r   r   r  )/r  tree_flattenr  r   r   GeneratorStater    rl   r  r  r   create_symintnoder  r\  r  r  	constantstorchbind_constantsr)  	get_valuer#  r  irr  r   r   r4  default_generatorsclone_stater  r  r  rm  r  r	   r@  _higher_order_opseffectswith_effectsr/   r4   r0   r   r   Tensor	is_sparsedisable_cudagraphs_reason)r  r>  r   r   binded_args	args_flattensor_argsnon_tensor_argsr3  r  r   example_argsdevice_indexnew_args
new_kwargsexample_outputrR  r   node_meta_valctxexample_out_lir&  msgr  r   )r  r  r  r   process_kernel  s   


		


zExternKernel.process_kernelr`  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.
        NrX  r1  r  r{   r   z@convert_to_reinterpret_view failed: stride=%s offset=%s index=%sFr7  rY  )&r   r  r   r`  r  rl   r  r?  r  r  rm  r  rB  r[  r  r
  r#  r  r  r  r,   r  r	  rA   r2  r  r  r3  stride_vars
offset_varrd   r1  r  r  rZ  r]  r  r   )r  r   x_unwrap_viewr$  x_unwrap_view_fx_node
index_argsr  r  r   rS  r^  expectedr   r   r   convert_to_reinterpret_view  sj   






z(ExternKernel.convert_to_reinterpret_viewc                 C  s  |d u rt  S t|ttjjjtfrt|dS t|t	r-t
jtj|j| | dS t|tr4|S t|tr?| |jS t|trPt| |j| dS t|tro|  t| roz| |W S  tyn   Y nw t|trz|  |S t|ttfr|S |  |S )Nr  )r  r  rY  )!rc  r   r    r   r   r   r   r   r   r  rl   r  add_tensor_constantr#  rR  r'  r   r!  r  r   r'  rZ  r`  r  r  r  r  r  r  r  r  NonTensorObjr}  r*  r   r   r   r'  C  s<   







zExternKernel.realize_inputc                 C  sD   t |rt| dkr|S | D ]
}|dkr|  S q| |S r  )r  r   r@  r}  )r  r   r  r   r   r   require_stride1d  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 FlexibleLayoutrZ  r  c                   s4   g | ]}  | d r | dr|qS )r   r   )rL  r  r  r   r  r  r   r   r   r     s    z0ExternKernel.require_strides.<locals>.<listcomp>r   r?   )+r  r  r   r  r  r  r2   r  r\  r  rl   r  r  size_hints_or_throwr]  r&  r  rQ  r  re  r>  rA  rY  r  r   rZ  r  r`  r  r  rC  r  require_stride_orderrequire_exact_stridesr  r   r   r#  r  loweringslice_r}  rP  )r  r   r   r  r
  use_current_stride_ordermutation_layoutrA  r  expanded_dims	orig_sizerN  r   r  r   require_stridesn  s  	
	
	


	


zExternKernel.require_stridesrH  c                 C     | j |||dS )N)r  r
  r  )r  r   r  r
  r   r   r   r    s   z"ExternKernel.require_exact_stridesr   c                 C  r  )N)r   r
  r  )r  r   r   r
  r   r   r   r    s   z!ExternKernel.require_stride_orderc                 C     |  |tS r   )r  r  r*  r   r   r   require_channels_last   r  z"ExternKernel.require_channels_lastc                 C  r  r   )r  r  r*  r   r   r   require_channels_last_3d$  r  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  rl   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   rl  (  s   
	zExternKernel.require_contiguousc                 C  s   |  |t| S r   r  r*  r   r   r   require_contiguous_strides:  s   z'ExternKernel.require_contiguous_stridesc                 C  r
  r   r   r  r   r   r   rd  B  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   rw  )r   r   r   r   rO  r   r1  r  rN  r   r  )r  r   r   n_args
n_pos_argsr   arg_namer   r   r   fill_non_provided_argsE  s(   

z#ExternKernel.fill_non_provided_argsrm  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  r2  r   r   r   r   u  r]  z3ExternKernel.codegen_const_args.<locals>.<dictcomp>r   c                 S  ro  r   rl   r  r  val_to_arg_strr   r  r   r   r   r     rq  z3ExternKernel.codegen_const_args.<locals>.<listcomp>)rl   r  rn  rO  r   rE  r   r  rq  r  r  r  )	r  rm  r  name_to_arg_propertiesr   r   proptype_r   r   r   r   codegen_const_argsi  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   )rl   r  rn  rN  r  rq  rE  r   r   rO  r   r  r  r  r  r  r  )r  rq  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.Nrw  z not in self.allarg_properties)r  r   rP  rY  )r  r  r   r3  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 ro  r  )r   kr}  r   r   r   r     s    z/ExternKernel.codegen_kwargs.<locals>.<listcomp>)rl   r  rn  rN  r   rc  rL  r  r   r    r  rP  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_namespacers  rt  rm  r?   r   
unknown_op)rY  r@  r   rq  rsplit)r  r@  op_namespaceop_namer   r   r   get_op_name  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(r^  r/  )r@   size_assertsrl   r  rn  rg   r  r  codegen_shape_tupler@  r  r  r  )r  re  r  r  r  r   r   r   codegen_size_asserts  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(r^  r/  z	# buffer z (op: z) is assumed to be not aligned)
r@   alignment_assertsrl   r  rn  r  r  r  r  r`   )r  re  r   alignedr  r   r   r   codegen_alignment_asserts  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'))	r@   test_configstrack_memory_lifecyclerl   r  rn  "write_memory_track_allocation_oncer  r  )r  re  r   r   r   r   codegen_memory_tracking  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  r@  )r  r  r  r   r   r   get_group_stride  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  rH  )r  r   r   r     r   z-ExternKernel.canonicalize.<locals>.<listcomp>c                 S  s   g | ]	}t d | qS )r{  )re   r   r   r   r   r     rq  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   rH  )add_varr   r   r     r   )rl   r  r  r  r@  r   r   r  r  r   r  r  rK   r   r   rh   r   rP  r   )r  r  rS  index_orderr   r  r   	new_sizesr   r  r  replacementr   )r  r  r   r  r   canonicalize  s$   
 zExternKernel.canonicalizeru  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  rE  r   r   )r  ru  maybe_get_symbolsr  r3  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 )NrI  zpython_kernel_name=c                   s$   g | ]}|j  d t |j  qS ro  )r   r   )r   rM  r  r   r   r   8  s    z(ExternKernel.__str__.<locals>.<listcomp>rr  )r   rL  fieldsr  r  r  )r  kernel_namer  r   r  r   r{  3  s   
zExternKernel.__str__r   NNNNr   N)r   r-  r[  r0  rq  r  rE  r  r   rT  rH  rG  rI  r-  rJ  r-  rL  rK  rN  rM  r   r   ra  rb  r)  re  rq   r   r   r   rJ  r-  r   r   )rI  r-  r   r   r;  )r   r   r   r~  )r>  rz   r   r   r   r   r   r~  )r   r   r   r`  r.  )NNF)
r   r   r   r  r  r  r
  r   r   r   r?  )r   r   r  rH  r
  r   r   r   )r   r   r   r   r
  r   r   r   )r   r  r   rF  r   r  )rm  r}  r   r   r   r   )r  r   r   r   r   r   )r  r   r   r   )r   r  )r   r  rH  )>r   r   r   rK  rE  r   rL  rM  r   r   rH  rI  rJ  r   rL  rN  rO  rP  rQ  rR  rS  r  r]  r_  rX  r  ri  rk  rV  rW  r|  rN  r}  r  r  r  r'  r  r  r  r  r  r  rl  r  rd  r  r  r  r  r  r  r  r  r  r  r  rW   r  r{  r  r  r   r   rv  r   r    s   
 



%



yE 	 $

$
!






	
r  c                      sB   e Zd ZdddZ							dd  fddZd!ddZ  ZS )"ExternKernelOutre  rq   r   r   c                 C     | |  d S r   )generate_extern_kernel_outrj  r   r   r   rk  D  r   zExternKernelOut.codegenr   Nr[  r  rq  rr  rE  r  r   rT  rH  rG  rI  r-  rJ  rL  rN  rM  c
                   s`   |  |}
t|
tsJ t|
t d ||
||pi d ||||	
 tj| | _	tj
|  d S r   )r  r   r   r   ru  r  rl   r  r  r   r  )r  r[  rq  rE  r   rH  rI  rJ  rL  rN  unwrapped_inputsrv  r   r   r  G  s    
zExternKernelOut.__init__r   c                 C  r  rk  r   r  r   r   r   r[  d  r  zExternKernelOut.should_allocater  r  )r[  r  rq  rr  rE  r  r   rT  rH  rG  rI  r-  rJ  r-  rL  r  rN  rM  r   r   r1  )r   r   r   rk  r  r[  r  r   r   rv  r   r  B  s    
r  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[  rq  rE  rI  rJ  rN  )r#  rr  rR  ru  r  r]  r  r  rl  randintlow_out)r  r  r  limitsrv  r   r   r  i  s   
zRandomSeeds.__init__)r  r   r  r  r   r   r   r   r   r  r  r   r   rv  r   r  h      r  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 )#rC  re  rq   r   r   c                 C  r  r   )generate_extern_kernel_allocrj  r   r   r   rk  }  r   zExternKernelAlloc.codegenr   Nr[  r0  rq  rr  rE  r  r   rT  rI  r-  rJ  rL  rN  rM  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   r  r   r   r   r   r     rj  z-ExternKernelAlloc.__init__.<locals>.<genexpr>)r  r   ru  r  r   r   r   r  rl   r  r  r   r  )
r  r[  rq  rE  r   rI  rJ  rL  rN  r  rv  r   r   r    s"   
zExternKernelAlloc.__init__r   c                 C  r  r  r   r  r   r   r   r[    r  z!ExternKernelAlloc.should_allocatec                 C  rU  r   rV  r  r   r   r   rd    r  z"ExternKernelAlloc.apply_constraintr  )r   NNNr   N)r[  r0  rq  rr  rE  r  r   rT  rI  r-  rJ  r-  rL  r  rN  rM  r   r   r1  r)  )r   r   r   rk  r  r[  rd  r  r   r   rv  r   rC  |  s    

 rC  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_noderR  r   r   c                   sD   t  jd |d | }tj| |g| _|| _tj| | _	d S rb  )
ru  r  r  rl   r  r@  mutation_namesr  r  r   )r  r[  r  r  mutated_node_namerv  r   r   r    s   zMutationOutput.__init__c                 C  r  r   )r  r  r   r   r   r    r  zMutationOutput.get_defining_opr  c                 C  r  r   )r  r  r   r   r   r%    r  z!MutationOutput.get_mutation_namesr   c                 C  r  r  r   r  r   r   r   r[    r  zMutationOutput.should_allocaterr  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     s
    z7MutationOutput.get_mutation_buffers.<locals>.<listcomp>c                 s      | ]	}t j|V  qd S r   )rl   r  try_get_bufferrq  r   r   r   r     r  z6MutationOutput.get_mutation_buffers.<locals>.<genexpr>)r%  )r  r  r   r   r   get_mutation_buffers  s   z#MutationOutput.get_mutation_buffers)r[  r0  r  r   r  rR  r   r   r]  rJ  r1  r   rr  )
r   r   r   rK  r  r  r%  r[  r  r  r   r   rv  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]_CACHErR  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  rR  r  r   r   r   _create_impl  s
   zTMADescriptor._create_implc                 C  s2   t ||f}|| jvr| ||| j|< | j| S r   )idr  r  )r  rR  r  r  r   r   r   r    s   

zTMADescriptor.createrq  r  rE  r   c                   sV   t  d tt|| dttt |t|d  || _	t
j| | _t
j|  d S )NrY  )ru  r  r&  r`  r  r   r   r  r   rR  rl   r  r  r   r  )r  rR  rq  rE  rv  r   r   r    s   zTMADescriptor.__init__re  rq   c                 C  r  r   )generate_tma_descriptorrj  r   r   r   rk    r   zTMADescriptor.codegenc                 C  r  r   )rR  r  r   r   r   
get_tensor  r  zTMADescriptor.get_tensor)rR  r   r  r  r   r  )rR  r   rq  r  rE  r  r   r   r  r>  )r   r   r   rK  r  r   r  r  r  r  rk  r  r  r   r   rv  r   r    s   
 

r  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.
    NrR  r   rB  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   rR  rq  rE  )	r   r   r  rB  r   r!  r  ru  r  )r  rR  rB  r   r!  rq  rE  rv  r   r   r    s*   

z"TMADescriptorExperimental.__init__r   )
rR  r   rB  r  r   r  r!  r  r   r   r   r   r   rK  r  r  r   r   rv  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.
    rR  r   block_shaper  c                   s   || _ t j||g|d d S )Nr"  )r$  ru  r  )r  rR  r$  rv  r   r   r  8  s   
zTMADescriptorStable.__init__)rR  r   r$  r  r#  r   r   rv  r   r  0  s    r  c                      s(   e Zd Zd fddZdddZ  ZS )SubgraphBufferr[  r  r   r\  rf  rg  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  s   g | ]}|j qS r   r   )r   sym_varr   r   r   r   Z  s    z+SubgraphBuffer.__init__.<locals>.<listcomp>r   FATEN)max_autotunemax_autotune_gemmmax_autotune_gemm_backends)ru  r  rf  r&  rl   r  r  r   r  make_subgraphsubgraphr   rq  rx  r  graph_input_namesr  
sym_inputstorch._inductor.configr  r@   set_graph_handlerr   run)	r  r[  r   rf  r&  r(  r1  sym_inpinductor_configrv  r   r   r  C  s0   
"zSubgraphBuffer.__init__re  rq   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  rr   c                 S  s   || _ |j| _d S r   )r  r   )r  r  r   r   r   r  i  s   z5SubgraphBuffer.codegen.<locals>.CodegenGraph.__init__N)r  rr   )r   r   r   r  r   r   r   r   CodegenGraphh  r_  r7  c                 S     g | ]}|  qS r   r  r   r&  r   r   r   r   n  r   z*SubgraphBuffer.codegen.<locals>.<listcomp>)r   rq  'codegen_subgraph_with_flattened_outputsr/  r1  r   )r  re  r7  outer_inputsr   r   r   rk  g  s   zSubgraphBuffer.codegen)
r[  r  r   r\  rf  rg  r&  r'  r(  r   r  r   r   r   r  rk  r  r   r   rv  r   r%  B  s    $r%  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   r>  r   r   r     r&  zBUserDefinedTritonKernel.get_kernel_and_metadata.<locals>.<genexpr>restore_value	reset_idxreset_to_zero)triton.runtime.autotunerr@  *torch._higher_order_ops.triton_kernel_wraprA  
get_kernel
kernel_idxr   r  r  rB  rE  rF  r  r   rC  rG  configs)r  r@  rA  rL  restore_value_argsreset_to_zero_argsr   r   rD  r   get_kernel_and_metadataw  s,   




z/UserDefinedTritonKernel.get_kernel_and_metadatare  rq   r   c                   s  ddl m}  \ }}}| |j||j\}}}fddjD }	t dr1t ds7J t t	 fdd j
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     r]  z3UserDefinedTritonKernel.codegen.<locals>.<dictcomp>rC  
constexprsc                 3  s    | ]} j | V  qd S r   )rC  r   rD  r   r   r     rj  z2UserDefinedTritonKernel.codegen.<locals>.<genexpr>r  rB  NzUnsupported arg type: r.  T)	arg_typesraw_argsraw_keystriton_metar6  r  original_fxnode_name)!torch._inductor.utilsrQ  rO  !define_user_defined_triton_kernelr   gridrL  r  r   r:   rT  rJ  chainr  r   repeatr  r   r   r  r   r   r  r   r   r    r  r  ri  generate_kernel_callr!  rY  r   )r  re  rQ  rL  rM  rN  new_namerX  extra_launch_args
named_argsconstexpr_namesr   rU  raw_keys_filteredraw_args_filteredr   r3  r   )r>  r  r   rk    s   
	




	



zUserDefinedTritonKernel.codegenFru  r   r   c                   s   t  |t| j|B S r   )ru  r  r(   r\  r  rv  r   r   r    s   z,UserDefinedTritonKernel.get_free_symbol_usesc                 C  r^  r   r9   r  r   r   r   r_    r  z0UserDefinedTritonKernel.get_unbacked_symbol_defsrK  r   r\  r   tma_descriptor_metadatarF  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|  rC  c                   s   g | ]}| v r|qS r   r   r2  rg  r   r   r   &  r  z4UserDefinedTritonKernel.__init__.<locals>.<listcomp>)identify_mutated_tensorsc                   r   r   r   r   r  rh  r   r   r   -  s    c                   s    g | ]}t t jd | qS r  )r  r9  r  r  r  r   r   r   4  s    ) r  r   r   r  r(  r'  r  r  r  r   r!  r  r   r   ru  r  r9  r   rK  r\  rO  r  rC  rL  rI  ri  r   mutable_argsrS  rl   r  r  )r  rK  r\  rf  rg  rq  r   rE  r  r}  r&  r>  rL  r  ri  autotuned_kwargsrv  )rg  r  r   r    sP   








z UserDefinedTritonKernel.__init__r\  c                 C  s
   t | jS r   )r   rS  r  r   r   r   r]  :  r  z#UserDefinedTritonKernel.get_outputsr  c                 C  r  r   r|  r  r   r   r   r!  =  r  z"UserDefinedTritonKernel.get_device)r   r?  r  r?  rH  rb  )
rK  r   r\  r   rf  rF  rg  rF  r   r   ra  r6  )r   r   r   rO  r   rk  rW   r  r_  r  r]  r!  r  r   r   rv  r   r>  v  s    
Y
	
=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
    re  rq   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   r  r:  r   r   r   r   G  rj  z3InplaceBernoulliFallback.codegen.<locals>.<genexpr>c                 s  s    | ]
}t t| V  qd S r   )r   r   r  r:  r   r   r   r   H  r  r  r^  z, NULL)r/  )r   rq  rl   r  rn  r  r|  r  r  reprrE  ending)r  re  r   r   r   r   rk  F  s   ,,z InplaceBernoulliFallback.codegenr   c                 C  r  r  r   r  r   r   r   r[  U  r  z(InplaceBernoulliFallback.should_allocater  c                 C     |  dgS r  r#  r  r   r   r   r%  X  r   z+InplaceBernoulliFallback.get_mutation_namesr   c                 C  r^  r   r9   r  r   r   r   r_  [  r  z1InplaceBernoulliFallback.get_unbacked_symbol_defsrN  rz   r   r   rE  r   c                   sV   t  jd t| d| |g||d tj|  tj	| | _
tj|  d S )Nr|  rN  )ru  r  r9  r!  r  rl   r  r@  r  r  r   r  )r  rN  r   rE  rv  r   r   r  ^  s   
z!InplaceBernoulliFallback.__init__r  r1  rJ  rb  )rN  rz   r   r   rE  r   r   r   
r   r   r   rK  rk  r[  r%  r_  r  r  r   r   rv  r   rm  A      



rm  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 )'InplaceCopyFallbackrn  re  rq   r   r   c                 C  s    |   \}}}|||| d S r   )r  codegen_device_copy)r  re  rF  rE  non_blockingr   r   r   rk  s  s   zInplaceCopyFallback.codegenr   c                 C  r  r  r   r  r   r   r   r[  w  r  z#InplaceCopyFallback.should_allocater  c                 C  rq  r  rr  r  r   r   r   r%  z  r   z&InplaceCopyFallback.get_mutation_namesr   c                 C  r^  r   r9   r  r   r   r   r_  }  r  z,InplaceCopyFallback.get_unbacked_symbol_defsr[  r0  rq  rr  rE  r  c                   sJ   t  jd |||ddd tj|d   tj| | _tj|  d S )Nz
aten.copy_aoti_torch_copy_)rI  rJ  r   )	ru  r  rl   r  r@  r  r  r   r  )r  r[  rq  rE  rv  r   r   r    s   zInplaceCopyFallback.__init__FrF  r   rE  rx  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|  )rv  r9  r!  )r  rF  rE  rx  rq  rE  r  r   r  r   r    s   zInplaceCopyFallback.creater  r1  rJ  rb  )r[  r0  rq  rr  rE  r  r   r   r?  )rF  r   rE  r   rx  r   r   rv  )r   r   r   rK  rk  r[  r%  r_  r  r  r  r  r   r   rv  r   rv  n  s    



rv  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 )MutatingFirstArgExternKernelrn  re  rq   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      | ]}|  V  qd S r   r9  r:  r   r   r   r     r(  z7MutatingFirstArgExternKernel.codegen.<locals>.<genexpr>r  r^  r/  )	r   rq  r  ro  rE  r  r|  r  rp  )r  re  argrefsr   r   r   rk    s   
z$MutatingFirstArgExternKernel.codegenr   c                 C  r  r  r   r  r   r   r   r[    r  z,MutatingFirstArgExternKernel.should_allocater  c                 C  rq  r  rr  r  r   r   r   r%    r   z/MutatingFirstArgExternKernel.get_mutation_namesr   c                 C  r^  r   r9   r  r   r   r   r_    r  z5MutatingFirstArgExternKernel.get_unbacked_symbol_defsc                 C  r  rk  r   r  r   r   r   has_side_effects  r  z-MutatingFirstArgExternKernel.has_side_effectsNr  r1  rJ  rb  )	r   r   r   rK  rk  r[  r%  r_  r}  r   r   r   r   rz    s    




rz  c                      r  )
ResizeStorageBytesvariabler   r6  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|  )rE  z"inductor_ops.resize_storage_bytes_z&torch::inductor::resize_storage_bytes_)r   r   ru  r  r9  r!  r  rl   r  r@  r  r  r   r  rI  rJ  r  r  r   r   never_reuse_buffersr  rZ  )r  r  r6  rv  r   r   r    s   
zResizeStorageBytes.__init__)r  r   r6  r   r   r   r  r   r   rv  r   r~    r	  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)rI  rN  r|  )r	  ru  r  r  r#  rj   rl  set_source_Tensorr   r  r  r   r   rl   r  r  r  rZ  r  r!  r  r9  rS  )r  r  r  r  rv  r   r   r    s"   

zSetSourceTensorKernel.__init__r  c                 C  s   |  d|  dgS r  rr  r  r   r   r   r'    r   z2SetSourceTensorKernel.get_inputs_that_alias_output)r  r   r  r   r   r   rJ  )r   r   r   r  r'  r  r   r   rv  r   r    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.
    re  rq   r   r   c              
   C  s   | j d }tjjrddd}||v r|| }t| jsJ | jr,dd | jD \}}}ndd | jD \}}| jd }|||| jd	 ||g| j	| j
| j||   d S )
NrI  r  r  )r  multiplyc                 s  r{  r   r9  r:  r   r   r   r     r(  z*ScatterFallback.codegen.<locals>.<genexpr>c                 s  r{  r   r9  r:  r   r   r   r     r(  r?   r   )r   rl   r  rn  r   rq  src_is_tensorrE  generate_scatter_fallbackrJ  rI  r  )r  re  rI  get_operator_enumr   r   rE  r   r   r   rk    s&   


zScatterFallback.codegenr   c                 C  r  r  r   r  r   r   r   r[    r  zScatterFallback.should_allocater   c                 C  s"   | j d }t|tsJ | gS r  r!  )r  rw  r   r   r   r%  	  s   

z"ScatterFallback.get_mutation_namesr   c                 C  r^  r   r9   r  r   r   r   r_    r  z(ScatterFallback.get_unbacked_symbol_defsNTrI  include_selfrN  rz   r   r   rN  r   r   rE  rI  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  rI  r  )rI  rL  rN  )r   r   r  ru  r  r9  r!  r  r   rl   r  r@  r  r  r   r  )
r  rN  r   rN  r   rE  rI  r  tensorsrE  rv  r  r   r    s&   
zScatterFallback.__init__r  r1  r  rb  )rN  rz   r   r   rN  r   r   r   rE  r   rI  r-  r  r   r   r   rt  r   r   rv  r   r    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
    re  rq   r   r   c           	      C  s   t | jsJ dd | jD ^}}}g }t|}t| jD ]\}}| j| d ur0|t| q|tjj	j
 q|j|  |||g|  R   d S )Nc                 s  r{  r   r9  r:  r   r   r   r   <  r(  z+IndexPutFallback.codegen.<locals>.<genexpr>)r   rq  r  r   r"  r  r  rl   r  r  rd  generate_index_put_fallbackr|  r  )	r  re  r   r   valid_indicesr"  iter_valid_indicesr   r  r   r   r   rk  :  s   zIndexPutFallback.codegenr   c                 C  r  r  r   r  r   r   r   r[  I  r  z IndexPutFallback.should_allocater  c                 C  rq  r  rr  r  r   r   r   r%  L  r   z#IndexPutFallback.get_mutation_namesr   c                 C  r^  r   r9   r  r   r   r   r_  O  r  z)IndexPutFallback.get_unbacked_symbol_defsrN  torch._ops.OpOverloadr   r   r"  r'  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  r  r   r   r   r   r   r   r   [  r   z-IndexPutFallback.__init__.<locals>.<listcomp>c                   r  r   r  rH  r  r   r   r   \  r   aoti_torch_index_put_outr|  zaten.index_put_)rI  rJ  rN  r   )r"  ru  r  r9  r!  r  rl   r  r@  r#  r  r   r  )	r  rN  r   r"  r   r  r  r  rJ  rv  r  r   r  R  s    	zIndexPutFallback.__init__r  r1  rJ  rb  )rN  r  r   r   r"  r'  r   r  r  r   r   r   rt  r   r   rv  r   r  5  ru  r  c                   @  s$   e Zd Zeddd	ZdddZdS )
DeviceCopyr   r   r  r  rx  r   r   c           	      C  s   |  stdd | D rtjjs||S tj	| |
 }|d us(J tj	| td |f}t|}d }| rD| }t|joO|jdkoO|}|jdko[t|jo[|}|rgt|rgd| _tt|| | ||d| |g|S )Nc                 s  s    | ]	}|t jjv V  qd S r   )rl   r  r  r  r   r   r   r   q  r  z$DeviceCopy.create.<locals>.<genexpr>zDeviceCopy in input programr3  Tr%  )r"  r   r  r@   aot_inductoruse_runtime_constant_foldingr$  rl   r  add_device_infor!  r[   r  rl  r  r@  rc   r   r  r  r_  r  r]  r   r'  )	r  r   r  rx  x_devicerE  r  is_destination_pinnedis_source_pinnedr   r   r   r  m  sD   



zDeviceCopy.createre  rq   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   rH  rw  r  )r  re  r   r   r   r   rk    s   zDeviceCopy.codegenN)r   r   r  r  rx  r   r   r   r  )r   r   r   r  r  rk  r   r   r   r   r  l  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  r^  r   r9   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   c                   s>   t  d ttddg  || _|| _|| _|| _|| _	d S Nr3  r|  )
ru  r  r9  r#  r  r  r   r  r  r  )r  r  r   r  r  r  rv  r   r   r    s   
z#DynamicSelectStorageOffset.__init__r   c                 C     t | jgS r   )r:   r  r  r   r   r   r_    r   z3DynamicSelectStorageOffset.get_unbacked_symbol_defsFru  c                 C  rf  r   )r(   r   r  r   r   r   r    rg  z/DynamicSelectStorageOffset.get_free_symbol_usesre  rq   c                 C  r  r   )codegen_dynamic_select_indexrj  r   r   r   rk    r   z"DynamicSelectStorageOffset.codegenrE  r1  )r  r  r   r  r  r  r  r  r  r  r   r   rb  r?  rH  r  )r   r   r   rK  r  r[  r  r_  rW   r  rk  r  r   r   rv  r   r    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  r^  r   r9   r  r   r   r   r    r  zDynamicScalar.get_readsr   c                 C  r  r  r   r  r   r   r   r[    r  zDynamicScalar.should_allocatesymr  keypathpytree.KeyPathrZ  r   r   c                   s<   |   t d ttdd| |g || _|| _d S r  )	r  ru  r  r9  r#  r  r  r  r  )r  r  r  rZ  rv  r   r   r    s   
zDynamicScalar.__init__r   c                 C  r  r   )r:   r  r  r   r   r   r_    r   z&DynamicScalar.get_unbacked_symbol_defsre  rq   c                 C  r  r   )codegen_dynamic_scalarrj  r   r   r   rk    r   zDynamicScalar.codegenrE  r1  )r  r  r  r  rZ  r   r   r   rb  r  )
r   r   r   rK  r  r[  r  r_  rk  r  r   r   rv  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 )!r   z5
    The result of a call to aten._assert_scalar
    r   r  c                 C  r^  r   r9   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scalarrn   r  r   r   c                   s,   t  d ttddg  || _|| _d S r  )ru  r  r9  r#  r  r  r  )r  r  r  rv  r   r   r    s   
zAssertScalar.__init__c                 C  r  rk  r   r  r   r   r   r}    r  zAssertScalar.has_side_effectsFru  r   c                 C  rf  r   )r(   r  r  r   r   r   r    rg  z!AssertScalar.get_free_symbol_usesre  rq   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 )NFrt  zstd::to_string(r/  )ri  zif (!(z()) { throw std::runtime_error("Expected z but received " + z); }zif not (z):z    raise RuntimeError(z = None)r@   scalar_assertsr  r  r  rl   r  ry  rn  r  codegen_cpp_sizevarr  r  r  codegen_python_sizevarro  r  )r  re  symbol
symbol_strsizevarr   r   r   rk  
  s&   zAssertScalar.codegenrE  r1  )r  rn   r  r   r   r   r?  rH  r  )r   r   r   rK  r  r[  r  r}  rW   r  rk  r  r   r   rv  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dAddZdBddZdCd!d"Ze	dDd&d'Z
dEd)d*ZdFd,d-ZdFd.d/Zd0d1 ZedAd2d3Ze	dGd7d8ZedHd:d;ZdI fd<d=Z  ZS )J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rR  r[  r0  r>  rz   r  rr  nontensor_argsr  r  rd  r   rT  rR  ,Optional[dict[sympy.Symbol, pytree.KeyPath]]r   r   c                  s`  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 |jrt|std|   j j\}	}d fdd}
tjj ||	|D ]	\}}|
|| qd S )Nrs  F#Fails to create FallbackKernel for r.   not supported_c10d_functionalr   z'NYI: Can't generate FallbackKernel for infotorch._C.Argumentr3  r   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 re  )	alias_namesr  r  
alias_infois_writerS  r  r9  r!  r&  )r  r  r   r   	add_alias  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  r3  r  optional_tensor_argr  )r  r   handle_aliasing_and_mutation  s"   

z=FallbackKernel.__init__.<locals>.handle_aliasing_and_mutation)r  r  r3  r   r   r   )!ru  r  r   use_runtime_dispatchrR  r   r#  r_  r`  ru  r   rN  r  r   rI  rl   r  warn_fallbackr  r  r   ra  _libraryr+  mutates_and_returns_first_argr  r  
is_mutabler%   r  rq  rE  
zip_schema)r  r[  r>  r  r  r  r   rR  schemar   r  r  r3  rv  r  r   r  7  sJ   
zFallbackKernel.__init__r  c                   sH   t   }| jtjjju r"| jD ]}t|t	r!|
t| }q|S r   )ru  r  rN  r#  _prims	rng_primsgraphsafe_run_with_rng_staterE  r   r  	with_readrA   rz  r  )r  r!  r3  rv  r   r   r    s   


zFallbackKernel.get_read_writesre  rq   c                 C  s   | |  | jt| dd S NrR  )(codegen_unbacked_symbol_defs_for_outputsr  r  r   rj  r   r   r   codegen_unbacked_symbol_defs  s   z+FallbackKernel.codegen_unbacked_symbol_defsContainer[sympy.Symbol]c                 C  s:   t | dd  }rttjjj|}|d usJ | S t S r  )r   r5   rl   r  r  r   r5  r:   r  rR  resolvedr   r   r   r_    s   
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    r  z2FallbackKernel.codegen_args.<locals>.Shim.__repr__Nr;  )r   r   r   r   r  r   r   r   r   Shim     
 r  c                   s   g | ]} |  qS r   r9  rH  r  r   r   r     r   z/FallbackKernel.codegen_args.<locals>.<listcomp>c                 S  s"   g | ]\}}t jj||jqS r   )rl   r  r  r  r[  )r   paramr   r   r   r   r     s    c                 S  ro  r   r  rH  r   r   r   r     rq  )rL  	dataclassr   rq  r  rE  rl   r  rn  r   rN  r#  r_  r`  r  r   ra  rb  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   r)  r:  r   r   r   r     rq  z.FallbackKernel.find_device.<locals>.<listcomp>c                 S  s   g | ]
}|  r|  qS r   r  r2  r   r   r   r     rQ  r   c                 s  s    | ]	}t d |V  qd S r   )r  find_devicerH  r   r   r   r     r&  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   r:   r   rc   r   )r  r  non_torch_bind_tensor_argsdevices
device_setr  r   r   r   r    s0   
zFallbackKernel.find_devicer   c                 C  s"   t | jtjjr
dS t| j S r  )r   rN  r#  r_  ru  r.   r  r  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   rN  r#  r_  r`  ru  r   r   ra  r  r%   r  r  r   r   r   r'    s    
z+FallbackKernel.get_inputs_that_alias_outputc                 C  s   t | jdks	J | jS r  )r   r  r  r   r   r   r%    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   rR  rj  r   r  r   r   r   "  r  z<FallbackKernel.export_extern_kernel_node.<locals>.<listcomp>Nreturn_type6Union[torch.TensorType, torch.ListType, torch.JitType]rh  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   H  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  ro   r  r  r  r  getElementTyper   r   OptionalTypeOptionalTensorArgumentIntTypeRuntimeError)r  rh  r  r   r   r   handle_single_output0  sR   

zFFallbackKernel.export_extern_kernel_node.<locals>.handle_single_outputr   r?   c                   s   g | ]
\}} |j |qS r   )r[  )r   return_schemarh  )r  r   r   r   r  s    )r@  rq  r  metadata)r   r   )r  r  rh  r  r   r  )#r1  r  r  rN  r   r  r   r  rq  rE  r  rL  rl   r  aot_moder$   serialize_inputsr#  r  	torchbindCallTorchBindr  returnsra  r   r  rS  r[  r   r  r  r8   r   extern_kernel_nodesr  )r  r   ordered_kwargsr@  
serializernamed_argumentsr  r  r  output_argumentsr   r   )r  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 )rP  Nrl  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#  r  r  
NumberTyper  	is_numberr   r   r    s   z)FallbackKernel.codegen.<locals>.is_numberc                 3  s"    | ]}j |fi  V  qd S r   rR  rS  r  r   r   r     r|  z)FallbackKernel.codegen.<locals>.<genexpr>c                 3  s(    | ]\}}t |to |jV  qd S r   )r   complexr[  )r   r}  r  r  r   r   r     s
    
c                     s   g      S r   )r  r  r   r  r   r   r    r   z(FallbackKernel.codegen.<locals>.<lambda>)r&  r  r   r   )+rN  ro  r   r#  r_  r`  r   rl   r  rn  torchgen.aoti.fallback_opsr  r   r1  r  r  r@   r  custom_ops_to_c_shimsr  rq  rE  rJ  r]  rL  r  r   ra  rb  ri  r  rI  ,generate_fallback_kernel_with_runtime_lookupr  r  rS  generate_fallback_kernelr[  r  r  r  r  r  )r  re  r>  r  r   	args_iterexported_argsr   )r  r   r  r   rk    sl   




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




zFallbackKernel.codegenrh  r  r]  c                 C  sJ   d}z|   }W n	 ty   Y nw t| j| jt|  t|  |dS )NFr%  )r_  r  r]  r  r  rY   r  r  )rh  r_  r   r   r   tensor_to_layout  s   

zFallbackKernel.tensor_to_layoutr   c                   sP  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  
||}|sVt|tjjjrVtd}|du rh t|d||||	|
dn|snJ 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   )r  r2  r   r   r   r     r(  z(FallbackKernel.create.<locals>.<genexpr>r3  r|  r  z"Not sure where to find device inforh  r   r"  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_outputr"  rh  r   r   r   $  s
    
zAFallbackKernel.create.<locals>.generate_output.<locals>.<genexpr>c                   s*   i | ]\}}| |t |fg qS r   r  )r   r  rX  r  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  MultiOutputr  r@    assume_unaligned_fallback_outputri   rl   r  r  r  r   r   SymIntr   r  )rh  r"  r$  r  r  has_unaligned_inputpacked)r"  rh  r   r  "  s<   



z.FallbackKernel.create.<locals>.generate_output)rh  r   r"  r  r   r   )rl  *_fused_moving_avg_obs_fq_helper_functionalr   r   rl   r  r  r	   r  r  r  r   r#  r  r  r  r  r9  r  r   r   r  r   )r  r>  r   r   fake_incorrect_kernelscontextr  r  r  r  rR  r  r  r   r  r   r    s^   


	
"

zFallbackKernel.createc                   s
   t   S r   )ru  rd  r  rv  r   r   rd  M  r  zFallbackKernel.apply_constraintr   r[  r0  r>  rz   r  rr  r  r  r  rd  r   rT  rR  r  r   r   rD  r  )r   r  r  )r  r  r  r  r   r   r1  rJ  )rh  r  r   r]  )r>  rz   r   r   r   r   r   r  r)  )r   r   r   rK  r  r  r  r_  r  rN  r  r}  r'  r%  r  r   rk  r  r  r  rd  r  r   r   rv  r   r  0  s.    	j






yU]r  c                      s<   e Zd ZdZdddZdddZ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[  U  r  zComplexView.should_allocater  c                 C  rq  r  rr  r  r   r   r   r'  X  r  z(ComplexView.get_inputs_that_alias_outputNr  r[  r0  r>  rz   r  rr  r  r  r  rd  rR  r  r   c                  s   t  j||||||d d S )Nr  )ru  r  )r  r[  r>  r  r  r  rR  rv  r   r   r  \  s   

zComplexView.__init__r1  rJ  )r[  r0  r>  rz   r  rr  r  r  r  rd  rR  r  r   r   )r   r   r   rK  r[  r'  r  r  r   r   rv  r   r  Q  s    

r  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.
    re  rq   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  rE  ro  r  )r  re  
alive_list	dead_listis_final_step
alive_repr	dead_reprcallr   r   r   rk  w  s   zMemoryCheckKernel.codegenNr  )r   r   r   rK  rk  r   r   r   r   r   p  s    r   c                   @  r  )	r  r  r  r   r  c                 C  r  r   r|  r  r   r   r   r!    r  zMultiOutputLayout.get_deviceNr6  )r   r   r   r   r!  r   r   r   r   r    r  r  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 )!r  re  rq   r   r   c                 C  s,   | |  | js| | | | d S d S r   )codegen_multi_output!skip_size_stride_alignment_checksr  r  rj  r   r   r   rk    s
   

zMultiOutput.codegenFr[  r0  r"  r   r"  list[tuple[Any, ...]]r(  r   c                   s>   t  d ||gd tj| | _tj|  || _|| _d S r  )	ru  r  rl   r  r  r   r  r"  r(  )r  r[  r"  r"  r(  rv  r   r   r    s
   
zMultiOutput.__init__ru  r   c                 C  s&   | j d }t|tsJ |||S r  )rq  r   r   r  )r  ru  r  r   r   r   r    s   

z MultiOutput.get_free_symbol_usesc                 C  s   t | jdkot| jd tS )Nr?   r   )r   rq  r   r  r  r   r   r   r[    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   r'  r  r   rw  r   r   r   r     s    z<MultiOutput.get_inputs_that_alias_output.<locals>.<listcomp>)rq  r  r   r   r   r'    s   z(MultiOutput.get_inputs_that_alias_outputr  r?  )
r[  r0  r"  r   r"  r)  r(  r   r   r   rH  r1  rJ  )
r   r   r   rk  r  rW   r  r[  r'  r  r   r   rv  r   r    s    

r  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 )rB  zC
    TensorBox / StorageBox allow in-place mutation of Tensors
    r   rZ  r   r   c                 C  r(  r   r.  r  r   r   r   r    r  z!MutableBox.has_exceeded_max_readsr  c                 C  r(  r   r+  r  r   r   r   r!    r  zMutableBox.get_devicer  c                 C  r(  r   r  r  r   r   r   r    r  zMutableBox.make_loaderr  c                 C  r(  r   )rZ  r  r  r   r   r   r    r  zMutableBox.make_indexerrH  c                 C  r(  r   )rZ  r@  r  r   r   r   r@    r  zMutableBox.get_strider   c                 C  r(  r   r,  r  r   r   r   r    r  zMutableBox.get_nameNr   r  c                 C  r  r   )rZ  r  r  r   r   r   r    r   zMutableBox.has_large_inner_fnr  r   r   c                 C  r  r   r-  r  r   r   r   r    r   zMutableBox.mark_reusec                 C  r(  r   r0  r  r   r   r   r    r  zMutableBox.realize_hintc                 C  r(  r   )rZ  r  r  r   r   r   r    r  zMutableBox.unwrap_viewc                 C  r(  r   )rZ  r  r  r   r   r   r    r  zMutableBox.is_input_bufferc                 C  r(  r   )rZ  r	  r  r   r   r   r	    r  zMutableBox.freeze_layoutFr   r   r
  c                 C     | j ||S r   )rZ  r  r  r   r   r   r    r  z*MutableBox.freeze_layout_with_stride_orderc                 C  r  r   )rZ  r  r  r   r   r   r    r   z(MutableBox.freeze_layout_with_fill_orderr  c                 C  r  r   )rZ  r  r  r   r   r   r    r   z(MutableBox.freeze_layout_with_same_orderr  c                 C  r+  r   )rZ  r  r  r   r   r   r    r  z+MutableBox.freeze_layout_with_exact_stridesr  c                 C  r(  r   )rZ  r  r  r   r   r   r    r  zMutableBox.get_read_writesr  c                 C  r(  r   rp  r  r   r   r   r    r  zMutableBox.get_readsc                 C  r(  r   ro  r  r   r   r   r    r  zMutableBox.num_readsrx   c                 C  r(  r   r1  r  r   r   r   r     r  zMutableBox.get_storage_numelr-  c                 C  r(  r   r  r  r   r   r   r      r  zMutableBox.get_reduction_typer  c                 C  r(  r   r  r  r   r   r   r!     r  zMutableBox.get_reduction_sizec                 C  r(  r   r2  r  r   r   r   r"     r  zMutableBox.is_externc                 C  r(  r   )rZ  r#  r  r   r   r   r#     r  zMutableBox.is_no_opr  r  c                 C  r  r   r  r  r   r   r   r$     r   zMutableBox.constant_to_devicer  c                 C  r(  r   )rZ  r%  r  r   r   r   r%     r  zMutableBox.get_mutation_namesc                 C  r(  r   )rZ  r&  r  r   r   r   r&     r  zMutableBox.get_operation_namec                 C  r(  r   )rZ  r'  r  r   r   r   r'     r  z'MutableBox.get_inputs_that_alias_outputc                 C  r(  r   r/  r  r   r   r   r     r  zMutableBox.realizeru  r   c                 C  r  r   r  r  r   r   r   r      rg  zMutableBox.get_free_symbol_usesr  c                 C  r(  r   r4  r  r   r   r   r  &   r  zMutableBox.get_read_namesr  c                 C  r(  r   )rZ  r  r  r   r   r   r  )   r  zMutableBox.get_defining_opr  r  c                 C  r  r   )rZ  r  r  r   r   r   r  ,   r   zMutableBox.codegen_referencer0  c                 C  r(  r   rZ  r  r  r   r   r   r[  /   s   
zMutableBox.layoutr  c                 C  r(  r   r*  r  r   r   r   r  4   r  zMutableBox.get_layoutc                 C  r(  r   r,  r  r   r   r   r  7   r  zMutableBox.get_output_specc                 C  r(  r   r  r  r   r   r   r  :   r  zMutableBox.get_sizer  c                 C  r  r   )rZ  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   rZ  rB  r   r   r  r   r  )r  line0endlr$  r  r   r   r   r{  A   s   


zMutableBox.__str__r1  r6  r8  r9  r:  r;  r   r<  r=  r)  r>  r?  r@  rA  rB  rC  rD  rE  rF  rG  r4  r2  rI  rJ  rH  r*  r,  r5  r0  r/  r.  )/r   r   r   rK  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  rW   r  r  r  r  rQ  r[  r  r  r  r  r{  r  r   r   r   r   rB    sb   
 































rB  c                   @  s   e Zd ZedddZdS )	r   rZ  r   r   r~  c                 C  s   t | tr| S tt| S r   )r   r   r   r  )rZ  r   r   r   r  V   s   
zTensorBox.createN)rZ  r   r   r~  )r   r   r   rN  r  r   r   r   r   r   U   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   rZ  r  r`  r  rl   r  r  r  r   r   r   r  b   s   zStorageBox.is_input_bufferc                 C  s   t | jto| j tjjv S r   )r   rZ  r  r  rl   r  r  r  r   r   r   r3  g   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  r_  r  )r   r  rZ  r  r   r  r  r  r  r   r  r  r!  r  r  r   r  rl   r  r  r   r  r|  r  r~  )r  r  r~  r  r   r   r   r  m   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   rZ  r  r  r  nontrivial_read_countr  r  r   r   r   r     s   zStorageBox.realize_hintr   r   c                 C  s   t dd |  D |kS )Nc                 s  r  r   )rl   r  get_dep_size_hintr  r   r   r   r      r  zBStorageBox.has_accumulated_enough_reads_by_size.<locals>.<genexpr>)r  r  r  r   r   r   $has_accumulated_enough_reads_by_size   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   rZ  r  r  r@   realize_acc_reads_thresholdr   realize_acc_reads_size_thresholdr1  r  r   r   r   r     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_opsrH  opcountr   r   r      rj  z5StorageBox.should_realize_on_reuse.<locals>.<genexpr>TF)r   rZ  r  r  r<  r  r  r  r@   realize_reads_thresholdr  )r  r  	heavy_opsr   r7  r   should_realize_on_reuse   s   

z"StorageBox.should_realize_on_reusec                 C  s   |  |r|   d S d S r   )r;  r  r  r   r   r   r     s   
zStorageBox.mark_reusec                 C  r(  r   ro  r  r   r   r   r     r  zStorageBox.num_readsNr1  r4  r)  )r   r   r   r   )r  r   r   r   r=  rF  )r   r   r   rK  r  r3  r  r  r1  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   rg  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   r`  r  r   r  r   r   r   r          z(_has_aliased_buffers.<locals>.<listcomp>c                 s  r  r   )r  rA  r   r   r   r      r(  z'_has_aliased_buffers.<locals>.<genexpr>)r   r:   )r>  r   r   r   _has_aliased_buffers   s   rC  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]r/  Optional[Sequence[IRNode]]operandsr  r<  rr  r[  r  r   r   c                   s6   t  jd ||d || _tj| | _tj|  d S rU  )ru  r  r/  rl   r  r  r   r  )r  r/  rG  r[  rv  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 }r|d dd }n|jdd }dd |D } fd	d|D }g }t|D ]\}	}
t	|
t
tfrK||
 q:|||
||	  q:|}|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   c                 S     g | ]}|j d  qS rZ  rm  rH  r   r   r   r      r   z)InvokeSubgraph.create.<locals>.<listcomp>c                   r  r   r  rH  r  r   r   r      r   rf  r&  r(  r|  )r/  rG  r[  rh  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 )Nr7  T)r(  )r   r   rc  r!  r  r]  r   r  r@  r  r^  r_  r   )rh  rN  r  )invoke_subgraphr   r   create_output$!  s"   z,InvokeSubgraph.create.<locals>.create_outputc                   s   g | ]	\}} ||qS r   r   )r   r   rh  )rQ  r   r   r   ;!  rq  )rh  r   rN  r   r   rO  )r  rI  rl   r  r  rm  r  r   r   r   r   r  r  r.  r=  r   r3  r4  graph_outputsr!  rD  r  r  )r  r/  rG  rI  r  fake_operandsrJ  fx_operandsnew_operandsr   operandr  r  outsr   )r  rQ  rP  r   r     sT   

zInvokeSubgraph.createre  rq   c                 C  r  r   )codegen_invoke_subgraphrj  r   r   r   rk  ?!  r   zInvokeSubgraph.codegen)r/  r<  rG  rr  r[  r  r   r   )r/  r<  rG  r   r   rH  r  )r   r   r   rK  r/  r   rG  r  r  r  r  rk  r  r   r   rv  r   rD     s   
 YrD  c                      s   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( fddZ	e
d)ddZed*dd Zd+d#d$Zd,d&d'Z  ZS )-ConditionalNr  	predicaterF  rG  rE  true_subgraphfalse_subgraphOptional[Sequence[MultiOutput]]r  r   rr  r<  r[  r  rR  r  r   r   c           	        sj   || _ || _|| _|| _t|g|\}}t jd |||d |d ur&|| _tj	
| | _tj	|  d S N)r   r[  rq  rE  )rZ  rG  r[  r\  _split_by_sym_typeru  r  rR  rl   r  r  r   r  )	r  rZ  rG  r[  r\  r[  rR  sym_argsr  rv  r   r   r  K!  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_exprg!  s   
zConditional._maybe_exprr   true_fnfalse_fn-list[Union[TensorBox, ShapeAsConstantBuffer]]c              	     sX    |} fdd|D }tjjjd }t|ts J t|tdd |D s+J dd |D }||fD ]/}|jdu retjj	|j
||jd|_t|j |jj|  W d   n1 s`w   Y  q6|jdusmJ |jdustJ |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  rH  r  r   r   r   w!  r   z&Conditional.create.<locals>.<listcomp>rB  c                 s  r  r   )r   r8   r\  r   r   r   r   {!  rj  z%Conditional.create.<locals>.<genexpr>c                 S  s   g | ]
}t t|jd  qS rZ  )r   r8   rm  rH  r   r   r   r   |!  rQ  NrM  rd  re  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    
rR  zcannot determine devicer|  )rZ  rG  r[  r\  r[  rR  c                   sb   g | ]-\}\}}t t| d d | D dd | D | j| jd t|fgqS )c                 S  rN  r   rY  rc  r   r  r   r   r   r   !  r   z1Conditional.create.<locals>.<listcomp>.<listcomp>c                 S  rN  r   rh  ri  r   r   r   r   !  s    
r7  )	r  r]  r   r  r  r  r^  r_  r   )r   r   rh  merged_output)conditionalr  r   r   r   !  s"    

rX  )!r'  rl   r  r  r   r   r   r   r   r.  r=  r   r3  r4  rR  rC  rY  r   r   r   r!  r   r  r^  r  r5   r  r   rm  r  rY  r  r  )r  rZ  rd  re  rG  rT  rS  r/  true_outputsfalse_outputsr   r  r   t_of_orR  r   )r  rk  r  r   r  m!  sv   
	
$	zConditional.createre  rq   c                 C  s*   | |  ||  | jt| di  d S r  )codegen_conditionalr  r  r  r   rj  r   r   r   rk  !  s   
zConditional.codegenr   c                 C  >   t | dd  }rttjjj|}|d usJ t| S t S r  r   r5   rl   r  r  r   r:   r5  r  r   r   r   r_  !     
z$Conditional.get_unbacked_symbol_defs)rZ  r   rG  rr  r[  r<  r\  r<  r[  r  rR  r  r   r   )r   ra  r   rb  )
rZ  r   rd  r<  re  r<  rG  rf  r   rr  r  rb  )r   r   r   rZ  r   rG  r[  r\  r  r  rN  rc  r  r  rk  r_  r  r   r   rv  r   rY  C!  s   
 
ZrY  r   r'  -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`  r3  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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.NrF  carried_inputsadditional_inputsrE  cond_subgraphbody_subgraphr]  r  rr  r<  r[  r  rR  r  stack_outputr   r   r   c           
        sr   || _ || _|| _|| _tg ||\}}	t jd ||	|d |d ur'|| _|| _t	j
| | _t	j
|  d S r^  )rw  rx  ry  rz  r_  ru  r  rR  r{  rl   r  r  r   r  )
r  rw  rx  ry  rz  r[  rR  r{  r`  r  rv  r   r   r  !  s$   

zWhileLoop.__init__c                 C  s   t | s| S ddlm} dd | D }t }g }tt| |D ] \}\}}t||v r3||| q|t| || q|S )Nr?   )clonec                 S  r?  r   r@  rA  r   r   r   r   "  rB  z3WhileLoop._clone_aliased_inputs.<locals>.<listcomp>)	rC  r  r|  r:   r   r   r  r  r  )rw  r|  unwrapped_buffersseen_buffersr  r   original_inputunwrapped_bufferr   r   r   _clone_aliased_inputs"  s    zWhileLoop._clone_aliased_inputscond_fnbody_fnr  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_boxesrr  fake_tensors,list[Union[int, torch.SymInt, torch.Tensor]]r   r   c                 S  sb   t | t |ks
J g }t| |D ]\}}t|tjr)|tj|| dd q|| q|S )NFr  )	r   r   r   r#  r  r  r  r  r  )r  r  retr  fkr   r   r   _require_exact_strides>"  s   
z0WhileLoop.create.<locals>._require_exact_stridesrB  c                 S  rK  rZ  rL  rH  r   r   r   r   R"  r   z$WhileLoop.create.<locals>.<listcomp>c                 S  rK  rZ  rL  rH  r   r   r   r   S"  r   c                 S  rK  rZ  rL  rH  r   r   r   r   T"  r   c                   r  r   r  rH  r  r   r   r   V"  r   c                   r  r   r  rH  r  r   r   r   Y"  r   NrM  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   rl   r  r  rs  )r  r  lhsrhsr   r   r   _guard_list_equals"  s   z,WhileLoop.create.<locals>._guard_list_equalsrR  r|  )rw  rx  ry  rz  r[  rR  r{  r   c                   r   r   r   )r   r   )
all_inputsr   r   r   "  r   z-NYI: while_loop_stack_output input mutations.rX  c                 S  rN  r   rh  ri  r   r   r   r   "  r   c                 S  rN  r   rh  )r   r  r   r   r   r   "  r   )r  r  r  r  zonly carries can be mutated.)r  r  r  r  r^  )r  rr  r  r  r   r   )r  r  r  r  r   r   );torch._higher_order_ops.utilsr  rl   r  r  r   rv  r  r   r   r   r.  r=  r   r3  r4  r   rR  rC  rY  r   r   r#  r   r  r!  r   r   r@  r5   r  r   rm  r  r  modulefxGraphModuler:   r  r  rS  r  r]  r  r  r  r  r   r  r  r  r[  r  r^  r  r  r  r  )&r  r  r  rw  rx  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_r/  cond_outputsbody_outputsr  r  r   ri  bor  rR  
while_loopmutated_idxsmutated_idx_setr  mutated_inputs_iterall_outputsr   rh  	multi_outmutated_inputrw  r  r   )r  r  r   r  0"  s  






"$


zWhileLoop.createre  rq   c                 C  s.   | | | j ||  | jt| di  d S r  )codegen_while_loopr{  r  r  r  r   rj  r   r   r   rk  "  s   zWhileLoop.codegenr   c                 C  rq  r  rr  r  r   r   r   r_  #  rs  z"WhileLoop.get_unbacked_symbol_defs)rw  rr  rx  rr  ry  r<  rz  r<  r[  r  rR  r  r{  r   r   r   )rw  rr  r   rr  )r  r<  r  r<  rw  rr  rx  rr  r{  r   r   r  r  rb  )r   r   r   rK  rw  r   rx  ry  rz  r  r  rN  r  r  r  rk  r_  r  r   r   rv  r   rv  !  s   
 " 
Nrv  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  r>  rz   r  rr  r  r  r  rd  r   rT  rR  r  r   r   c             	     s~   t  j|||||d |d ddlm} dd |D }	||g ||	R |}
|
d us+J |
| _tjj|
d | _	| tjj|
< d S )Nr   rR  r   )get_effect_keyc                 S  s    g | ]}t |tr|jn|qS r   )r   r)  r'  r  r   r   r   r   '#  s    z,EffectfulKernel.__init__.<locals>.<listcomp>)
ru  r  torch._higher_order_ops.effectsr  effect_typerl   r  effectful_opsr  prev_effect_buffer)r  r[  r>  r  r  r  r   rR  r  uncovered_argsr  rv  r   r   r  #  s$   
zEffectfulKernel.__init__r  c                   s0   t   }| jd ur|jt| j  |S r   )ru  r  r  r  r  rA   rz  r  )r  r!  rv  r   r   r  0#  s   

zEffectfulKernel.get_read_writesr   c                 C  r  rk  r   r  r   r   r   r}  :#  r  z EffectfulKernel.has_side_effectsr   r  rD  r1  )r   r   r   r  r  r}  r  r   r   rv  r   r   #  s    	 
r   c                   @  s"   e Zd Zed 	d	d
ddZdS )r  Fru  r   r   r   c                 C  r^  r   r9   r  r   r   r   r  ?#  rZ  z!NonTensorObj.get_free_symbol_usesNr?  rH  )r   r   r   rW   r  r   r   r   r   r  >#  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 )r)  r   r   +Union[FakeScriptObject, torch.ScriptObject]r'  r   c                 C  r  r   r   r  r   r   r   r  K#  r  zTorchBindObject.get_nameNr  r  c                 C  r  r   r   r  r   r   r   r  N#  r  z!TorchBindObject.codegen_referencec                 C  r  r   r*  r  r   r   r   r  Q#  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_objT#  s   zTorchBindObject.get_real_objr   c                 C  sN   |   }t|dsJ t| }t|d }dd |D }ttj	|dS )N__obj_flatten__r   c                 S  s(   g | ]}t |tjr| |  qS r   )r   r#  r  r!  numelrH  r   r   r   r   `#  s    
z1TorchBindObject.get_buf_bytes.<locals>.<listcomp>)
r  r  r   r  r  r  r-  rI  operatorr  )r  real_script_obj	flat_dict
flat_elems
flat_sizesr   r   r   get_buf_bytesZ#  s   zTorchBindObject.get_buf_bytesr;  r   r5  )r   r  )r   r  rF  )	r   r   r   r   r  r  r  r  r  r   r   r   r   r)  F#  s   
 


r)  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  m#  r  zGeneratorState.get_nameNr  r  c                 C  r  r   r   r  r   r   r   r  p#  r  z GeneratorState.codegen_referencer;  r   r5  )r   r   r   r   r  r  r   r   r   r   r  h#  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[  u#  r  z!_CollectiveKernel.should_allocatec                 C  r  rk  r   r  r   r   r   r}  x#  r  z"_CollectiveKernel.has_side_effectsNrJ  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]  rH  r   r   r   r   #  r^  z9_CollectiveKernel.set_cpp_kernel_name.<locals>.<listcomp>)
r   rN  r#  r_  r`  rJ  ra  r   rb  rL  )r  rJ  r>  r   r   r   rV  }#  s   
z%_CollectiveKernel.set_cpp_kernel_namer>  rz   rq  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 ]}
|
  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 )NrT  r   r|  c                   r  r  r  r  r  r  r   r   r   #  r~  z4_CollectiveKernel.create_inplace.<locals>.<listcomp>c                 S  r8  r   rW  r*  r   r   r   r   #  r   r  )rl   r  r  r  r  r!  r9  r  tree_leavesrS  r  r  r  r  r  )r  r>  rq  r   r   _example_outputr  r  r  rR  
tensor_arginpsr   r  r   create_inplace#  s>   


z _CollectiveKernel.create_inplace!Union[TensorBox, list[TensorBox]]+Union[list[MultiOutput], _CollectiveKernel]c                   s@  t jj  j||g|R i |\}}}}}	W d    n1 s!w   Y  |	r1J | d|	 |D ]}
|
  q3t|tr ||}|d usKJ  t|d|||| fddt	|D _
tj
|D ]\}}tjstt|s|t jj|j qij
S   |||||tjst|st jjj g_
S )Nr^  r|  c                   s(   g | ]\}}t  |t|fgqS r   )r  r  r   )r   r   rR  r  r  r   r   r   #  s    z9_CollectiveKernel.create_out_of_place.<locals>.<listcomp>)rl   r  r  r  r  r   r   r  r  r   r  r   r@   r  ri   r  r  r   r  )r  r>  rq  r   r   r  r  r  r  rR  r  r  r$  rR  r   r  r   create_out_of_place#  sZ   


z%_CollectiveKernel.create_out_of_placer1  r   r  )
r>  rz   rq  r  r   r   r   r   r   r   )
r>  rz   rq  r  r   r   r   r   r   r  )	r   r   r   r[  r}  rV  r  r  r  r   r   r   r   r  t#  s    

@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  r>  rz   r  rr  r  r  r  rd  r   rT  rR  r  r   r   c             	     (   t  j|||||d |d | d d S )Nr  +aoti_torch_cpu__c10d_functional_all_reduce_ru  r  rV  r  r[  r>  r  r  r  r   rR  rv  r   r   r  $     	z_AllReduce_Kernel.__init__re  rq   c                 C  2   | d ||  t| jtr| | d S d S Nz+torch/csrc/inductor/aoti_torch/c/shim_cpu.hinclude_extra_headerr
  r   r[  r  r  rj  r   r   r   rk  %$  
   

z_AllReduce_Kernel.codegenr   r  r  r=  r   r   rv  r   r  $      	r  c                      r  )_AllReduceKernelNr  r[  r0  r>  rz   r  rr  r  r  r  rd  r   rT  rR  r  r   r   c             	     r  )Nr  *aoti_torch_cpu__c10d_functional_all_reducer  r  rv  r   r   r  .$  r  z_AllReduceKernel.__init__re  rq   c                 C  r  r  r  rj  r   r   r   rk  D$  r  z_AllReduceKernel.codegenr   r  r  r=  r   r   rv  r   r  -$  r  r  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  r>  rz   r  rr  r  r  r  rd  r   rT  rR  r  r   r   c             	     r  )Nr  +aoti_torch_cpu__c10d_functional_wait_tensorr  r  rv  r   r   r  M$  r  z_WaitKernel.__init__re  rq   c                 C  r  r  r  rj  r   r   r   rk  c$  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  )rq  r   r   r  r   r  r"  )r  rw  r   collr  r   r   r   r   get_volatile_readsj$  s   





z_WaitKernel.get_volatile_readsrw  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 )NrT  r|  )	rl   r  r  r  r9  r!  rS  r  r  )	r  r>  rw  r  r  r  r  rR  r  r   r   r   create_wait$  s(   

z_WaitKernel.create_waitr  c                   s6   t   }|  }|D ]}|jt|  q|S r   )ru  r  r  r  r  rA   rz  r  )r  r!  volatile_readsvrrv  r   r   r  $  s
   
z_WaitKernel.get_read_writesr   r  r  r  )r>  rz   rw  r   r   r   rD  )
r   r   r   r  rk  r  r  r  r  r  r   r   rv  r   r  L$  s    	

r  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   r7   r    r2   r   r   r:   r   r"   r  r#  r  r   r  r&  r   r   r   r  $     r  c                 C  r  r   )r   r7   r    r1   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   r  r	  r   r   r  )r'  r(  r   r)  )r   r,  r   r-  )r   r2  r   r   )r   r=  r>  r   r   r   )rG  rH  rI  rH  rJ  rH  r   r   )rR  r   rS  rT  r   r   )rf  rg  r   r   )rq  rr  r   rs  )r   r  r  r  r   rk   )r  r   r  r  r  r   r   r  )r  r   r  r  r^  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   r(  )r  rH  rJ  rH  r   r   )r  r  r   r   )r   r  r   r  )r>  rr  r   r   )r   r'  r   rt  )r   r   r   r  (L  
__future__r   rO  rL  r-  rJ  loggingr  os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   r   unittest.mockr   r   r    r!   r"   torch._export.serde.schema_exportserder  r  torch._library.utilsr  r+  r  torch._loggingr#  torch.fxtorch.utils._pytree_pytreer  torch._dynamo.utilsr#   torch._export.serde.serializer$   *torch._higher_order_ops.auto_functionalizer%   torch._inductorr&   rZ  r(   torch._prims_commonr)   r*   r+   r,   r-   torch._subclasses.fake_tensorr.   %torch.fx.experimental.symbolic_shapesr/   r0   r1   r2   r3   r4   r5   r6   r7   torch.fx.noder8   torch.utils._ordered_setr:   torch.utils._sympy.functionsr;   r<   r=   torch.utils._sympy.symbolr>   r  r@   rA   codegen.commonrB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   	loop_bodyrL   ops_handlerrM   rN   rO   rP   runtime.benchmarkingrQ   runtime.hintsrR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   virtualizedrj   rk   rl   "torch._library.fake_class_registryrm   rn   ro   codegen.cuda.cuda_templaterp   codegen.wrapperrq   r  rr   rs   r   r   r6  __version__r  r  ImportErrorrt   ru   rv   rw   r   rx   r  ry   r_  r`  ru  rz   	getLoggerr   r1  r  rl  getenvr  r  r   r   r   r   r  r   r   r   r   r   r   r  r  r   r   r  r  r+  r1  r;  r<  rF  rQ  re  rp  rx  r   rR  rc  r  r  r  r  r  r  rV  r  r  r  r  r  r  r  r  r  r\  r  r  r  r   rA  rM  rZ  r  r`  r  r  r  r  r  r  r  r0  r  r]  r  r&  r0  r4  r9  r>  r  r\  r  r`  r  rc  r   r  r  r  r   r   PrimitiveInfoTyper  r  r  r  r  r  r   r  r/  r0  r  r  r  rC  r  r  r  r  r%  r>  rm  rv  rz  r~  r  r  r  r  r  r   r   r  r  r  r   r  r  rB  r   r  r<  rC  rD  rY  r_  rv  r   r  r)  r  r  r  r  r  r  r  r   r   r   r   <module>   sx   8$	,`
*

"	


'
	  :K ##?     s :& _ J <
aQ0=$ 7V)b   V$(Y 	
  tH*P=ZU E      }%+!@(4 L-2N76-?    %, b	s   )/! X