o
    ,h                    @  s1  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Zd dlmZ d dl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mZ d dlZd dlZd dlZd dl Zd dl!m"  m#Z$ d dl%m&Z& d d	l'm(Z( d d
l)m*Z* d dl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z?m@Z@mAZAmBZB ddlCmDZD ddlEmFZFmGZGmHZHmIZI ddlJmKZKmLZL ddlHmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZ ddl"m[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZf ddlgmhZhmiZi er'ddljmkZk edZledZme=ddgZneoepZqi Zrdesd< i Ztdesd < e=ejujv  ZwejhjxZxejhjyZyejhjzZze=ejujv  Z{e=ejujv ej|j}gZ~e=ejujv  Zi Zd!esd"< ejhjZd#d$ Zdd'd(Zdd-d.Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zeexjexjexjexjexjexjexjexjexjexjexjexjexjexjg ejejejejejejejejejejejejejd7Zdd:d;Zd<d= Zd>d? ZddBdCZdDdE ZdFdG ZddQdRZdSdT ZddUdVZdWe1jdWerfddYdZZd[d\ Zdd]d^Z				W	dd_d`ZddadbZdՐddfdgZeej|j}ddhdidj Z}eezjddhddkdlZdWdmddndoZeexjjddhddpdqZdWdWdrddudvZeezjddhdՐddwdxZddye1jdWdddWdfdzd{Zd|d} Ze  	Wdd~dZeexjdWdddd ZeexjdWdddd Zeexjexjexjexjezjgdd ZeexdreexjɃeǃ eexjddhdddZeexjddhdddZeexjgdddZeexj̓dd Zeexj΃dd Zeexjσdd ZeexjЃdd Zeexjj҃dd ZeexjӃdd Zeexjddhdd Zeezjddhdd Zeexjddhdd Zeexj׃dd Zeexjddheexjddheexjddhdd Zeexjddhdd ZeexjddhdddZeexjddhdddZeexjddhdddZeexjddhdddZdddZeejddhdddZeejddhdddddZeejjddhdddZeejjddhdddddĄZeejjddhdddƄZeejjddhdddddȄZeexjdddʄZeexjddhddddτZeexjddhddddфZeexjddhddddӄZeexjddhddՄ ZeexjddhdddׄZeexjddhdddلZeexjddhdddۄZeexjddhdd݄ Zeexjddhdd߄ Zeexjddhdd ZdddZeexjdddZdddZejdd ZdؐdddZdؐdddZddddZdddZdd Zeejhjj ddhdd Z eexjddhdd Zeexjddhdd Zeexjjddhdd  Zeexjdd Zeddd Zdd Z	eexj
j҃Zeexj
jZeexjj҃ZeexjjZeexj eexj
dd Z
eexjd	d
 ZeeGjddhdd ZeeGjddhdddZeeGjddhdd ZeeGjddhdd ZeeGjddhd ddddZeeGjddhd ddddZdd!d"Zdd$d%Zeexjj ddhdWdWddd&dd/d0Zeexj!e1j"dhdWdWd1dd3d4Z!d5d6 Z#d7d8 Z$d9d: Z%d;d< Z&d=d> Z'd?d@ Z(dAdB Z)dCdD Z*eexj+ eexj, eexj- eexj.dWdE eexj/jdWdE eexj0 eexj1dWdE eexj2dWdE ej34 reexj5dWdE eexj6 eexj7 eexj8 eexj9j҃ eexj:j҃ eexj; eexj<j= eexj>j҃ eexj?j҃ eexj@ eexjAdWdE eexjBe# eexje) eexjCe# eexjDe$ eexjEe$ eexjFe$ eexjG eexjH eexjH eexjI eexjJ eexjK eexjLe# eexjM eexjN eexjO eexjP eexjQ eexjR eexjS eexjT eexjUe$ eexjV eexjWe# eexjX eexjY eexjYjZ eexj[ eexj\ eexj] eexj^ eexj_ eexj` eexja eexjb eexjc eexjd eexje eexjf eexjg eexjh eexji eexjj eexjk eexjl eexjm eexjn eexjo eexjp eexjq eexjr eexjs eexjtju eexjv eexjw eexjx eexjy eexjz eexj{ eexj| eexj}j҃ eexj~jdWdE eexje# eejjj eejjj eejjj eexj eexj eexje$ eexj eexj eexj eexj eexj eexjj eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe*dWdE eexjjҐe* eexjjҐe* eexjjҐe* eexjjҐe* eexj eexjddhdՐdFdGZeexjddHdIdJZdKdL ZeexdM	reexje eezjdNdO ZeexjddhddRdSZeexjddhddTdUZdVdW ZeejexjgddddWdXdYdZZeejdӐd[d\Zeejd]d^ Zeexjd_d` Zeexjdadb Zeexj	ddddcdddeZdfdg Zeexjddhdhdi Zdjdk ZeejexjgdddddddldmdnZdodp Zdqdr ZeexjeeZeedZeed Zdsdt ZeexjdddddudvdwZeexjdddddudxdyZeexjdddddudzd{Zeezjj҃d|d} Zeejexjgd~d ZeexjddhdՐddZeexjddhdddZdd Z	ydddZdd ZdddZeexjddhddQ Zeexjddhdd ZeexjddhdՐddZeexjŃdՐddZŐdd ZƐdd ZeexjddhdՐddZeeGjddhdՐddZɐdՐddZeexjjdWdZeexjjdWdZeexjddhdd Zeexjddhdd Zedd ZeexjddhdؐddZeexjddhdddZddyddddZeexjddhdddddZeexjddhdddZeexjddhdddZeexjddhdddZeexjddhdyddddZ		WddddZeexjj҃dؐdddÄZeexjj҃dؐddĐdńZeexjj҃	dӐddȐdɄZeexjj҃	dӐddʐd˄Zeexjj҃			ddd͐d΄Zeexjj҃			dddϐdЄZܐdѐd҄ Zeezjj҃dӐdԄ ZސddؐdلZeexjddhdڐdڐdۄZddߐdZdddZdddZ	d ddZddddZdd ZddddZdd Zeezjddh	WdՐddZdddZeezjddhdd Zdd Zeexjddh		 		Wdd dZeexjddh		 		WdddZeexjjdWdZeexjddhdd ZdddZd	d
 Zdd Zdd ZeexjjdWdZeexjdd ZeexjjdWdZeexjdd Zdd Zeexjdd Zeexjdd Zdd Zeexjj҃	dddZeexjjdWdZeexjjdWdZeexjddh		 	W	y	dddZeexjddh		 	W	y	dd d!Zd"d# ZeexjjdWdZeexjddh	dؐd$d%Zeexj jdWdZeexj ddh	dؐd&d'Z d(d) Zd*d+ Zdؐdd.d/Zd0d1 Zeexjddd2d3d4Zd5d6 Zd7d8 Zd9d: Z	d;d< Z
eexjezjgdddWd=d>d?ZeexjdddWd=d@dAZdBdC ZedDdE ZeexjjdWdZeexjjdWdZeexjjdWdZeexjdydFdGdH ZdՐdIdJZeexjdKdL ZeexjddhdՐdMdNZedOdP ZedQdR ZeexjdydFdؐdSdTZeexjgdydFdUdV ZddYdZZeezjgdydFd[d\ Z eexj!exjj gdye1j"dd]d^ Zeexj#ezj#gdydFd_d` Z#eexj$ezj$gddd2dadbZ%eexj&j҃Z'eexj(j҃Z)eexj*j҃Z+eexj,j҃Z-eexj.j҃Z/eexj&dӐdcddZ&eexj(dӐdedfZ(eexj*dgdh Z*eexj,ddhdؐdidjZ,eexj.ddhdؐdkdlZ.eexj0ddd2dmdnZ0eexj1ddodpZ2eexj3ddhddqdrZ4eexj5ddhddsdtZ6eezj7edu eexj8edvZ9eexj:edwZ;eexj<edxejdyZ=eexj>edzejdyZ?eexj@dyd{d|Z@eexjYjZdWdZAeexjYjZddhdddWd}d~dZBeexjYjddhd	ddZYdӐddZCd
ddZDeCexjEZEeDexjFZFeCexjGZGeCexjHZHeexjIZIeDexjJZJeDexjKZKeexjLZLeexjMdydZMeDexjN eDexjO eexjPZPeexjQZQeexjRZReexjSddZSeexjTZTeexjUZUeexjVZVeCexjW eCexjXZXeexjYe1j"dheX eCexjZ eCexj[ eCexj\ eDexjq eexj]ddyejdZ]eexj^ddyejdZ^eexj_ddyejdZ_eexj`ddyejdZ`eexjaZaeexjbZbeexjcea eexjdeb eexjeZeeexjPZPeCexjfZfeexjg eexjhddZheexjσ eexjiejdy eexjjee eexjkejdy eexjlejdy eexjmejdy eexjnejdyZneexjoejdy eexjpejdy eCexjq eCexjr eCexjs eCexjt eCexju eCexjv eCexjw eCexjx eCexjy eCexjz eCexj{ eCexj| eCexj} eCexj~ eCexj eCexj ddlmZmZ dd ZeD ]@ZeexeD ]\ZZZeeeeed qeezeD ]\ZZZeeeeed qqeexjje@dydZeexjje@dydZeexjj e@dyd eexjjeZeexjj e eexjjeZeexjjeM eexjjeM eexjjҐee eexjjҐeP eexjje eexjje eexjje eexjjeZeexjj e eexjjeZeexjeK eexjeE eexjjea eexjjea eexjjeb eexjjeb eexjjea eexjjea eexjjeb eexjjeb eexjef eexjeh eexje dd Zeexjjexjje eexjjexjje eexjjexjje eexjjexjje eexjjexjje eexjjexjje dd Zeexje@ eexjeQ eexjeR eexjeS eexjeT eexjeU eexjeV eexje eexjj e eexjje eexje] eexje^ eexje_ eexje` eexjeM eexjeI eexjeJ eexjeQ eexjeR eexjeT eexjeU eexjeV eexjexj eexjexj eexjexj eexjexj eexjexj eexjdӐddZeexjjÃdd ZeexjĐjÃdd ZeexjŃdd Ze8ơ D ]\ZǐZee9eǃeȃ qeejɃdd Zeexjdd Zeejhjːj̃dd Zeejhjΐjσdd ZeejhjxjАjуdd ZeejhjӐdNrteejhjӐjj҃dd ZeejhjxjՃddHddZd dl֐mאZ ee׃ ee*dd Zeejhjِjddhdd Zeejhjِjddhdd ZeejhjِjddhdddZeej|jddhdddddZee(ddhdddZeejhjzjj҃dd Zeejhjِjddhdd ZddÐlmZ e  eeGjddhdĐdń ZddlEmZ eDe ddlEmZ e  e  ddlEmZ e  ddlEmZ e  ejddʐd˄ZdS (      )annotationsN)defaultdict)IterableSequence)AnyCallablecastOptionalTYPE_CHECKINGTypeVarUnion)	ParamSpec)patch)counters)associative_scan_op)triton_kernel_wrapper_mutation)canonicalize_dimcanonicalize_dimscheckdtype_to_typeelementwise_dtypesELEMENTWISE_TYPE_PROMOTION_KINDget_computation_dtypeis_boolean_dtypeis_float_dtypeis_integer_dtypeNumber)magic_methodsmethod_to_operator)free_unbacked_symbols)
OrderedSet)CeilDivFloorDivIdentityModularIndexing   )import_submodule   )configinductor_primsirtest_operators)decompositionsget_decompositions)	DtypeView
ExpandViewIndexingConstantIRNode	is_tritonOnlineSoftmaxReductionops_wrapperPermuteView	Pointwise	ReductionSqueezeView	TensorBoxvalidate_irView)ceildivdecode_device
is_dynamicis_gpuis_pointwise_useis_view,needs_fallback_due_to_atomic_add_limitationspad_listlike#register_op_dtype_propagation_rules#register_op_requires_libdevice_fp64sympy_productuse_scatter_fallback)opsV)ReductionType_T_Pztorchvision::roi_alignzaten::index_addz8dict[Union[Callable[..., Any], str], Callable[..., Any]]	loweringsz9dict[torch._ops.OpOverload, Optional[Callable[..., Any]]]_maybe_layout_constraintsz2dict[torch._ops.OpOverload, torch._ops.OpOverload]inplaceable_foreach_opsc                  C  s<   t jjjD ]} | jD ]}|jdkr|jtv s  dS q
qdS )Ncall_functionTF)rI   graphcurrent_nodeusersoptargetforeach_ops)nodeuser rY   S/var/www/html/scripts/venv/lib/python3.10/site-packages/torch/_inductor/lowering.pycur_node_has_non_foreach_usersx   s   
r[   	arg_pairs%Iterable[Union[tuple[Any, Any], Any]]c                 C  s   t t}d}t| D ]A\}}t|tsd}|f}t|  ptj}d }|D ]}t|tr2|j	
 } nq$|d us;J d|r@|\}|||f ||f q
|S )NFTz.foreach op should have at least one tensor arg)r   list	enumerate
isinstancer   r>   r(   #combo_kernel_foreach_dynamic_shapesr9   data
get_deviceappend)r\   outunpack_argsiargsuse_foreachdevicetrY   rY   rZ   group_foreach_args   s&   


rl   fnCallable[..., Any]returnOptional[Callable[..., Any]]c                 C  s&   t | tjjs	dS | tv rt|  S dS )zHGet layout constraints. Returns None if there are no layout constraints.N)r`   torch_ops
OpOverloadrN   rm   rY   rY   rZ   maybe_layout_constraints   s
   ru   c                 C  sV   | t jjjkr	tS | t jjjkrtS | t jjjkrtS | t jjj	kr$d S t
d|  )NzUnknown layout constraint tag: )rq   _CTagneeds_exact_stridesconstrain_to_fake_tensorsneeds_contiguous_stridesrequire_contiguous_stridesneeds_fixed_stride_orderconstrain_to_fx_stridesflexible_layoutAssertionError)tagrY   rY   rZ   tag_to_layout_constraint   s   r   c                 C  s   | s	t d| d S )Nzinductor does not support NotImplementedError)condmsgrY   rY   rZ   
assert_nyi   s   r   c                   s\   t  ttttfrdd  D S t  t  tjj	r,t
 fdd  D  d S d S )Nc                 S  s   g | ]}t |qS rY   )add_needs_realized_inputs.0xrY   rY   rZ   
<listcomp>       z-add_needs_realized_inputs.<locals>.<listcomp>c                 3  s    | ]}t  |V  qd S N)getattr)r   overloadrt   rY   rZ   	<genexpr>   s    

z,add_needs_realized_inputs.<locals>.<genexpr>)r`   r^   settupler    needs_realized_inputsaddrq   rr   OpOverloadPacketupdate	overloadsrt   rY   rt   rZ   r      s   
r   c                 C  s:   t | tjjr|  D ]	}|tt| |< qd S |t| < d S r   )r`   rq   rr   r   r   rN   r   )rm   
constraintr   rY   rY   rZ   add_layout_constraint   s
   r   )r   r'   r%                     	   
         dtypeintc                 C  s2   t | ts| S | tv sJ d|  dt|  } | S )Nzid z missing from DTYPE_ID_LOOKUP)r`   r   DTYPE_ID_LOOKUPr   rY   rY   rZ   decode_dtype   s
   
r   c                 C  sB   t | trt|  pt|  S t | tjr| jdu S t | tS )NT)	r`   r9   r   	get_dtyper   sympyExpr
is_integerr   r   rY   rY   rZ   is_integer_type   s
   


r   c                 C  s    t | trt|  S t | tS r   )r`   r9   r   r   boolr   rY   rY   rZ   is_boolean_type  s   

r   type_promotion_kindr   c                   s0   dd   fdd|D }t |d| i\}}|S )Nc                 S  s8   t | ttjfr
| S t|  }tjdg| |  dS )Nr'   r   )	r`   r   r   Basiclenget_sizerq   zerosr   )inpdimrY   rY   rZ   construct_input  s   z+get_promoted_dtype.<locals>.construct_inputc                      g | ]} |qS rY   rY   )r   argr   rY   rZ   r     r   z&get_promoted_dtype.<locals>.<listcomp>r   )r   )r   rh   inps_r   rY   r   rZ   get_promoted_dtype  s   r   c                 C  sh   t | ttfs| g} nt| } t| D ]}t |tjjr1| D ]}t||}|tvr0| 	| q q| S r   )
r`   r^   r   rq   rr   r   r   r   rM   rd   )aten_fnrm   r   other_fnrY   rY   rZ   get_overloads  s   

r   c                 C  s6   t | tjjr|| jv S t | tjjr||  v S dS NF)r`   rq   rr   r   _qualified_op_namers   name)rT   	namespacerY   rY   rZ   in_namespace)  s
   
r   rh   	list[Any]kwargsdict[str, Any]	broadcastr   )Optional[ELEMENTWISE_TYPE_PROMOTION_KIND]convert_input_to_bool tuple[list[Any], dict[str, Any]]c                   s  dd t  D }dd  D }|s|s fS |s|ri|r$tjndd  D }|dd  D  t|d|i|rF |d  n|d   fd	d
fdd D  fdd D |rtt	t
 fdd|D fdd|D  }t	|d  }	t||d t| D ]\}
}| |
< qt||t|d  D ]\}}||< qtt D ]}
t |
 tjrt |
 |	 |
< qD ]}t| tjrt| |	|< qЈ fS )Nc                 S     g | ]\}}t |tr|qS rY   r`   r9   r   rg   r   rY   rY   rZ   r   8      z"transform_args.<locals>.<listcomp>c                 S  r   rY   r   r   kvrY   rY   rZ   r   9  r   c                 S  s*   g | ]}t |ttjfst|d r|qS r   )r`   r   r   r   hasattrr   arY   rY   rZ   r   C  s    c                 s  s    | ]
}t |d r|V  qdS )r   N)r   r   rY   rY   rZ   r   I      z!transform_args.<locals>.<genexpr>r   r   c                   s6   t | tr
t| S t | tjrtj| j dS | S )Nvaluer   rj   )r`   r9   to_dtyper*   Constantr   )r   )rj   r   rY   rZ   promoteT  s
   

ztransform_args.<locals>.promotec                   r   rY   rY   r   r   rY   rZ   r   \  r   c                   s   i | ]	\}}| |qS rY   rY   r   r   rY   rZ   
<dictcomp>]      z"transform_args.<locals>.<dictcomp>c                 3      | ]} | V  qd S r   rY   r   rg   rh   rY   rZ   r   c      c                 3  r   r   rY   r   r   r   rY   rZ   r   d  r   )r_   itemsrq   r   extendvaluesr   rc   broadcast_tensorsr^   	itertoolschainr   zipr   ranger`   r*   r   r/   create)rh   r   r   r   r   args_indiceskwargs_indicespromoting_argsbroadcastedsizerg   r   r   rY   )rh   rj   r   r   r   rZ   transform_args1  sZ   

r   c                   s>   t   fdd}t| }t| tt|| |S )a  
    Add a foreach lowering to lowerings dict.

    Arguments:
        aten_fn: torch.ops.aten.* fn we are lowering
        decomp_fn: alternate implementation on our IR
        broadcast: True to apply broadcasting to tensor inputs
        type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion
        convert_input_to_bool: some logical ops require inputs are converted to bool
    c                    s*   t | dksJ  | i |}t| |S )Nr%   )r   r:   )rh   r   re   	decomp_fnrY   rZ   wrapped  s   z+_register_foreach_lowering.<locals>.wrapped)	functoolswrapsr   rV   r   rM   dictfromkeys)r   r   r   aten_fnsrY   r   rZ   _register_foreach_loweringy  s   
r   c                   s<   t  fdd}t  |t | |S )a  
    Add a lowering to lowerings dict

    Arguments:
        aten_fn: torch.ops.aten.* fn we are lowering
        decomp_fn: alternate implementation on our IR
        broadcast: True to apply broadcasting to tensor inputs
        type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion
        convert_input_to_bool: some logical ops require inputs are converted to bool
    c                    s   t | } t|}d}t| dkr!t| d t tfr!d}t | d } tdd  D s9tdd | D r9J dt| |\} }|rH| g} | i |}t	| |S )	NFr'   r   Tc                 s  s"    | ]}|t v pt|d V  qdS )_c10d_functionalN)	fallbacksr   )r   rm   rY   rY   rZ   r         
z6_register_lowering.<locals>.wrapped.<locals>.<genexpr>c                 s      | ]}|d kV  qdS )re   NrY   r   rY   rY   rZ   r     r   zout= ops aren't yet supported)
r^   r   r   r`   r   allanykeysr   r:   )rh   r   unpackedre   r   r   r   r   r   rY   rZ   r     s(   
z#_register_lowering.<locals>.wrapped)r   r   r   r   r   r   )r   r   r   r   r   lowering_dictr   rY   r  rZ   _register_lowering  s
   r	  F.Callable[[Callable[_P, _T]], Callable[_P, _T]]c                 C  s   t jt| ||||dS )z+
    Shim to support decorator syntax.
    )r   r   r   r  )r   partialr	  )r   r   r   r   r  rY   rY   rZ   register_lowering  s   r  c                 C  s   g }t jt| t|tjjdD ]O\}}tjjj	j
t|dddr(|| qtjjj	j
t|dddr<|| qtjj|| tt|jtt|jk rZ|| q|| qtt|S )z
    Broadcasting logic based on symbolic shapes.

    We give the shapes 0 and 1 concrete values, while all other shapes
    are symbolic sympy formulas.
    )	fillvaluer'   Tsize_oblivious)r   zip_longestreversedr   SOnerI   rQ   sizevars	shape_envevaluate_exprEqrd   guard_equalsr   expandfree_symbolsr   )r   boutputr   yrY   rY   rZ   broadcast_symbolic_shapes  s   $

 r  c              
     s,  |d u s|d u sJ d|d u r|d u rt j}tdd | D s"| S tdd | D rC|p3t| d|ifdd  fdd	| D S td
d | D }g }| D ]C}t|ttfrq|	t
tj|| | dt|  qPt|tjr|	t
t|| | dt|  qP|	| qP|S )NzEonly one of override_return_dtype or type_promotion_kind may be givenc                 s  s"    | ]}t |tjttfV  qd S r   )r`   r   r   r   floatr   rY   rY   rZ   r          z$promote_constants.<locals>.<genexpr>c                 s  s"    | ]}t |tttjfV  qd S r   )r`   r   r  r   r   r   rY   rY   rZ   r     r   r   c                   s4   t | tjrtj|  td dS tj|  td dS )Nindexr   rj   r   )r`   r   r   r*   r0   r=   r   r   r   rY   rZ   
const_func  s
   
z%promote_constants.<locals>.const_funcc                   r   rY   rY   r   )r#  rY   rZ   r     r   z%promote_constants.<locals>.<listcomp>c                 s  s&    | ]}t |tttjfr|V  qd S r   )r`   r9   r/   r*   r   r   rY   rY   rZ   r     s   $ r   r!  )r   DEFAULTr  r  r   nextr`   r   r  rd   r/   r   r*   r   r   get_device_or_errorr^   r   r   r   r0   )inputsoverride_return_dtyper   exre   r   rY   )r#  r   rZ   promote_constants  sL   

	r*  c                   s"   d dd fdd}|S )Nalphar'  r9   c              	     s  d urt dd D rrJ  S t
r2| d ur1| dkr1ttd | d< n| d u s8J dd D d  
pLd   dd  D ]!}t|tjstt	t	| kstJ d d	 d	|  qSt
jt
jftjd uottjd
d d uotjjjd uotjjjddo v  	fdd}sd }D ]}t| jr| } nq|sȈd  }p|}tj| |dS )Nc                 s  "    | ]}t |tot|V  qd S r   r`   r1   r2   r   r   rY   rY   rZ   r   5  r  z0make_pointwise.<locals>.inner.<locals>.<genexpr>r'   c                 S     g | ]}|  qS rY   make_loaderr   rY   rY   rZ   r   B  r   z1make_pointwise.<locals>.inner.<locals>.<listcomp>r   zndim mismatch  rR   low_precision_pointwise_barrierFc                   s   t  t ksJ d  d tjkr&d ur& fddD  S g }tD ]'\}}| }|  }rN|v rNtj||dd}t||}|| q,| }rhtj|dd}t|S |S )Nzwrong ndim r4  c                   s   g | ]}| qS rY   rY   )r   loadr"  rY   rZ   r   Z  r   zCmake_pointwise.<locals>.inner.<locals>.inner_fn.<locals>.<listcomp>F)use_compute_types)r   rq   r   r_   r   rH   r   rd   )r"  inputs_loaded	inp_indexr6  re   	inp_dtypedowncast)r   emulate_precision_castsrm   r'  loaders	low_pr_fpoverride_fn_when_input_boolrangesr7  rZ   inner_fnW  s    $z/make_pointwise.<locals>.inner.<locals>.inner_fnrj   r   rB  rA  )r  r*  r^   mulr   r   r`   r*   BaseConstantr   rq   bfloat16float16rI   rQ   r   rR   metagetr?   rc   typer6   r   )r,  r'  otherrB  rj   rg   allow_alpharm   override_devicer@  r(  triton_fallback)r   r=  r'  r>  r?  rA  rZ   inner4  sb   

zmake_pointwise.<locals>.inner)r'  r9   rY   )rm   r(  rN  r@  rM  rO  rP  rY   rL  rZ   make_pointwise,  s   KrQ  c                   s   ddd fdd}|S )Nr'   r+  r'  list[list[TensorBox]]c                   sT  t tjjjdkptjjjtv pt }d }|D ]}t|t	t
fr$|} nq|d us-J dg }|D ]}t|t	t
fsE||gt |  q1|| q1tt| }d gt | }| D ]@\\}}	}
g }|
D ]-\}} rt|d| i}n| }|||< tj|tjr|	r|r|  ||  qf|rtj| q\tdd |D sJ |S )Nr   z1at least one input must be a list to a foreach opr,  c                 s      | ]}|d uV  qd S r   rY   r   rY   rY   rZ   r     r   z8make_foreach_pointwise.<locals>.inner.<locals>.<genexpr>)r   rI   rQ   rR   rS   rU   inplace_foreach_opsr[   r`   r^   r   rd   rl   r   r   has_featureBackendFeatureFOREACHrealizeget_operation_nameregister_operation_listr  )r,  r'  realize_outputsa_list_inputinputbroadcast_inputsgroupsoutputsrj   ri   groupoperation_list
output_indrh   r  rM  pw_fnrY   rZ   rP    sZ   
z%make_foreach_pointwise.<locals>.inner)r'  rR  rY   )re  rM  rP  rY   rd  rZ   make_foreach_pointwise  s   6rf  r   r9   torch.dtypec                   s>   |    kr|rt| S | S  fdd}t| d| S )Nc                   s   t j|  dS )N)	src_dtype)rH   r   r   r   rh  rY   rZ   	_to_dtype     zto_dtype.<locals>._to_dtyper(  )r   clonerQ  )r   r   copyrj  rY   ri  rZ   r     s
   r   r   c                 O  s   ddl m} |}| j}||tjd}t| |j|  W d   n1 s'w   Y  |j}|s3J t|}dgt	| }	|
 D ]0\\}
}}g }|D ]\}}||	|< tj|
tjri|ri|  ||  qL|rrtj| qBtdd |	D s~J |	S )aI  
    This lowers an invocation of foreach_map
    The way this works is that an arbitrary N-arg func is provided by the user, looped over by the
    polyfill with the same semantics as a foreach op (a loop applying an n-ary function to n args)
    and then traced into a subgraph by dynamo.
    This code allows us to inline the subgraph into the main graph lowering using the PontwiseSubgraphLowering.
    The graph outputs represent the vertically fused sequence of ops, and then register_operation_list
    below registers the buffers as horizontally fuseable in the scheduler.
    r'   )PointwiseSubgraphLowering)root_graph_loweringNc                 s  rS  r   rY   r   rY   rY   rZ   r     r   z_foreach_map.<locals>.<genexpr>)subgraph_loweringrp  graph_modulerI   rQ   set_graph_handlerrungraph_outputsrl   r   r   rU  rV  rW  rX  rd   rY  rZ  r  )subgraphrh   r   rp  r'  gmpw_subgraphsub_outputsr_  r`  rj   ri   ra  rb  rc  r  rY   rY   rZ   _foreach_map  s6   r{  c                 C  sZ   |j s|  j r&|  rt| |d}tj||  |S ttj	j
dd| |S t| |ddS )Nr   Fadd_to_fallback_setTrn  )
is_complexr   r   
empty_liker*   InplaceCopyFallbackr   fallback_handlerprimsconvert_element_typedefaultr   )r   r   dstrY   rY   rZ   _convert_element_type  s   r  r~  c                C  sb   |   }||kr|rt| S | S dd }||}||}||kr)ttjj| |S tt| |S )Nc                 S  s   | j r	t| jS t| jS r   )is_floating_pointrq   finfobitsiinfor   rY   rY   rZ   _get_primitive_bitwidth	  s   z1to_dtype_bitcast.<locals>._get_primitive_bitwidth)	r   rm  r  atenviewr   r9   r.   r   )r   r   rn  x_dtyper  src_bitsdst_bitsrY   rY   rZ   to_dtype_bitcast  s   r  c                 C  s8   |j s|  j rttjtjjj	j
| |S t| |S r   )r  r   r9   r   r*   ComplexViewrq   rH   r  r  r   r  r   r   rY   rY   rZ   _view_dtype  s
   
r  rn  non_blockingrj   torch.devicec                C  s:   t |}|  |kr|rt| S | S ttj| ||S r   )r=   rc   rm  r9   r   r*   
DeviceCopy)r   rj   rn  r  rY   rY   rZ   	to_device!  s   r  c                 C  s   t | |d|dS )NTr  )r  )r   rj   r  rY   rY   rZ   _device_put(     r  Tc	           
      C  sz   |p| j }t|}	t||| |durt|}t|	||||d}	t| |||d|	}	tt|r;ttt|d|d|	 |	S )z3A pointwise function that maps ops.{name} to inputsN)r(  r@  rM  rO  )r   r   r   )r   r   )__name__r4   rD   rQ  r  r   r  r   )
r   r   r   r   r   r(  r@  rM  rO  rm   rY   rY   rZ   register_pointwise-  s>   

r  c                    sx   d} t d  fdd} fdd}t|t|tjdgfdd}ttj|}tt| r:tt	t| d	d
| |S )z2A pointwise function that maps ops.frexp to inputsfrexpc                        | i |d S Nr   rY   rh   r   r  rY   rZ   frexp0_     zregister_frexp.<locals>.frexp0c                    r  Nr'   rY   r  r  rY   rZ   frexp1b  r  zregister_frexp.<locals>.frexp1rl  c                    s$    d | i | d | i |fS Nr   r'   rY   r  )pw_fnsrY   rZ   rm   j  s   $zregister_frexp.<locals>.fnNro  )
r4   rQ  rq   int32r  r  r  r   r  r   )r   r  r  rm   rY   )r  r  rZ   register_frexpZ  s*   
r  c                 C  s   t ||d}t| |}|S )NrM  )rf  r   )r   pointwise_lowering_fnrM  rm   rY   rY   rZ   register_foreach_pointwise|  s   
r  )r   r   c                   s  dd }t |ttfrt||}t |ttfrt||}| ||g t d  d tjd}dd t D }t|t	 fdd|D  D ]\}}| |< qFt
t D ]}t  | tjrqt | t |d	    |< qUt||d
 d	 t d |t d |S )Nc                  W  
   t j|  S r   )rH   wherer   rY   rY   rZ   rm        
zwhere.<locals>.fnr'   r%   ro  c                 S  r   rY   r   r   rY   rY   rZ   r     r   zwhere.<locals>.<listcomp>c                      g | ]} | qS rY   rY   r   r   rY   rZ   r     r   r   rl  )r`   r  r   constant_liker   r   r$  r_   r   r   r   r   r*   r   r/   r   r^   r   rQ  r   )r   r   r  rm   r   indicesrg   r   rY   r   rZ   r    s&   
$
$
r  c                  G  s   t | dkrt| d ttfrt| d  S ttdd | D g }g }| D ]$}| }t |t |ks?t	dd t
||D rDt||}|| q%|S )Nr'   r   c                 S  r1  rY   )r   r   rY   rY   rZ   r     r   z%broadcast_tensors.<locals>.<listcomp>c                 s  s    | ]?\}}t jjjjt|d ddo"t jjjjt|d dd p?t jjjjt|d dd o?t jjjjt|d ddV  qdS )r'   Tr  N)rI   rQ   r  r  r  r   r  r   r   r  rY   rY   rZ   r     s"    


	

z$broadcast_tensors.<locals>.<genexpr>)r   r`   r^   r   r   r   reducer  r   r  r   r  rd   )r'  rU   r`  r   sizesrY   rY   rZ   r     s   
r   c                 C  s   | S r   rY   r   rY   rY   rZ   nop     r  
lift_freshc                 C  s   t | tsJ |d u rtt| jS t |ttjfr"tj	j
|ntdd |D }tt|  |}tt |ts=|fn|}g }t|  D ]\}}||v r]tj	j
jt|dddsb|| qH||  krnt| |S | S )Nc                 s  s    | ]
}t jj|V  qd S r   rI   rQ   r  evaluate_static_shaper   drY   rY   rZ   r     r   zsqueeze.<locals>.<genexpr>r'   Tr  )r`   r9   r8   r   rb   r   r   r   rI   rQ   r  r  r   r   r   r   r    r_   r  r  rd   r  )r   r   dims	new_shaper  srY   rY   rZ   squeeze  s"   
r  c                 C  s   t t| |S r   )rm  r  )r   r   rY   rY   rZ   squeeze_copy     r  c                 C  2   t | |}t| tsJ t|tsJ |j| _| S r   )r  r`   r9   rb   r   r   valrY   rY   rZ   squeeze_  
   
r  c                 C  2   t | rt| dtjdS td}t|tjd| S )NFr   isinfrl  r   	full_likerq   r   r4   rQ  r   rm   rY   rY   rZ   r       r  c                 C  r  )NFr   isnanrl  r  r  rY   rY   rZ   r    r  r  c                 C  $   t | rt| S td}t|| S )Nceilr   rm  r4   rQ  r  rY   rY   rZ   r       r  c                 C  r  )Nfloorr  r  rY   rY   rZ   r    r  r  c                 C  r  )Nroundr  r  rY   rY   rZ   r    s   r  c                 C  r  )Ntruncr  r  rY   rY   rZ   r    r  r  c                 C  s   t | g\} t| tjrt| t|S t| tsJ t|ttfs$J t| 	 t|kr0| S t
| 	 sWtjjt| 	 }|dkrWt
|sW| tjjt||  tt| jt|S r  )r*  r`   r*   rE  r/   r   r   r9   r^   r   r   rI   rQ   r  size_hint_or_throwrF   
mark_reuserb   )r   r  x_size_productrY   rY   rZ   r  %  s$   
r  c                 C  sL   t |}|D ]}d||< q| }t|D ]\}}|dkr t||}qt||S Nr0  )r^   r_   	unsqueezer  )r   shapebroadcast_dimensionsr  broadcast_dimensionr   idxr   rY   rY   rZ   broadcast_in_dim@  s   


r  c                 C  s   t | | S r   )r  r   )r   r  rY   rY   rZ   	expand_asN  r  r  c                   sb  t |   tt kr$tjjgtt      t| t  } tt|  ks0J t |  }d}ttD ]}| dkrHd}|| |  ||< q>|r`t|| 	 | 
 dS tdd t D rstt| |S  fdd}t st|stjjt }|dkr| tjjt||  |  tj| 
 | 	 |t |d	S )
NFr   Tr   rj   c                 s  s$    | ]\}}|d kp|d kV  qdS r'   NrY   r  rY   rY   rZ   r   e     " zrepeat.<locals>.<genexpr>c                   st   t | t ks
J t| } tt D ]!}| dkr5 | dkr)tjj| |< qt| | d | | |< q| S r  )r   r^   r   r   r  Zeror$   )r"  rg   old_sizerepeatsx_loaderrY   rZ   rB  j  s   zrepeat.<locals>.inner_fnrC  )r^   r   r   r   r  r  r  r   emptyr   rc   r  r   rm  r  r   rI   rQ   r  r  rF   r  r3  r6   r   )r   r  new_sizezero_tensorrg   rB  old_size_productrY   r  rZ   repeatS  s>   r  c                 C  s2   t | tsJ t |ttfsJ tt| j|S r   )r`   r9   r^   r   r;   r   rb   )r   r  rY   rY   rZ   r    s   r  c                 C  s6   t | tsJ t |ttfsJ tt| jt|S r   )r`   r9   r^   r   r5   r   rb   )r   r  rY   rY   rZ   permute  s   r              c              	   C  s8   t | tsJ t| |d}ttjj| j|||||dS )Nr   clamp)r`   r9   _validate_dimr*   	SliceViewr   rb   )r   r   startendstepr  rY   rY   rZ   slice_  s   r  c              	   C  s   t | trt | jtjr| j } |   t| s"td|  dt	| \}}t
|j|jdd |D dd |D t|p@d}ttj||dS )Nzunrealized as_strided(z, ...)c                 S     g | ]}t |qS rY   r   r  r   r  rY   rY   rZ   r         zas_strided.<locals>.<listcomp>c                 S  r  rY   r  r  rY   rY   rZ   r     r  r   rb   layout)r`   r9   rb   r*   BaseViewunwrap_viewrX  is_storage_and_layoutr   as_storage_and_layoutFixedLayoutrj   r   r   r  ReinterpretView)r   r   stridestorage_offsetstorage
old_layout
new_layoutrY   rY   rZ   
as_strided  s   

r  c                 C  s$   t | tsJ t| |||j| _| S r   )r`   r9   r  rb   )r   r   r  r  rY   rY   rZ   as_strided_  s   r  c                 C  s   t | |||}t|S r   )r  rm  )r   r   r  r  resultrY   rY   rZ   as_strided_copy  s   r  c                   s   g d}D ]} |||    f d d }qdd D  fdd}td  }d d | < tjd  d  ||dS )Nr   r0  c                 S  r1  rY   r2  r/  rY   rY   rZ   r     r   z!pointwise_cat.<locals>.<listcomp>c           
   	     s@  t |  tj}g }g }ttD ]n  dkr t dtjn
t   d tj}t   d tj}t ||}t ||} dkrI|}n td krT|}nt 	||}|
| t| t   d  < |
t | fddd q|d }	ttd ddD ] t |  |  |	}	q|	S )Nr   r'   c                     s     S r   rY   rY   )rg   idx_loadinputs_loadersrY   rZ   <lambda>      z1pointwise_cat.<locals>.inner_fn.<locals>.<lambda>        r0  r%   )rH   
index_exprrq   int64r   r   constantgeltand_rd   r^   r#   maskedr  )
r  idx_dimmasksmasked_loadsr  r  
start_condend_condmasknext_valr   r'  r  inputs_ranges)rg   r  rZ   rB    sD   
zpointwise_cat.<locals>.inner_fnrC  )rd   r   r^   r6   r   rc   r   )r'  r   prev_endr   rB  r  rY   r"  rZ   pointwise_cat  s   0

r%  r]  scaleszero_pointsaxis	quant_min	quant_maxc              	     s   t  dksJ dt  dksJ d|  tjkr%t| tj} |  tjks5J d|    t |  k sHJ dt |   |     f	dd}tj	| 
 ||  dS )	Nr'   expect scales 1 dimexpect zero_points 1 dim<Expecting input to have dtype torch.float32, but got dtype: Expecting axis to be < c           
        s   |   f}| }|}|}t tjd\}}jtjkr(t|tj}jtjkr5t|tj}t|}t|| | }t	|t
||}	t|	S Nr   )_create_constantsrq   float32r   rH   r   r  
reciprocalr  maximumminimum)
r  channel_idxr]  scale
zero_pointqminqmax	inv_scaler  clamped	r(  r   input_loaderr*  r)  r&  scales_loaderr'  zero_points_loaderrY   rZ   rB    s   

z;quantized_decomposed_quantize_per_channel.<locals>.inner_fnrC  )r   r   r   rq   rF  r   r1  r3  r6   r   rc   )r]  r&  r'  r(  r)  r*  r   rB  rY   r<  rZ   )quantized_decomposed_quantize_per_channel  s(   
r@  	out_dtyperB  Optional[torch.dtype]c          	        s   t  dksJ dt  dksJ d|  |ks*J d| d|    t |  k s=J dt |   d u rDtj|     fdd}tj|  ||  d	S )
Nr'   r+  r,  Expecting input to have dtype , but got dtype: r.  c                   s   |   f}| }|}|}j tjkrt|tj}j tjkr+t|tj}tt|tj|| }t|}|S r   )r   rq   r1  rH   r   sub)r  r5  r]  r6  r7  r  r(  r=  rB  r&  r>  r'  r?  rY   rZ   rB  U  s   
z=quantized_decomposed_dequantize_per_channel.<locals>.inner_fnrC  	r   r   r   rq   r1  r3  r6   r   rc   )	r]  r&  r'  r(  r)  r*  r   rB  rB  rY   rG  rZ   +quantized_decomposed_dequantize_per_channel7  s(   rI  r6  r  r7  c                   s   |   tjkrt| tj} |   tjksJ d|    |   fdd}tj|   t	j
|t|t|d|  dS )Nr-  c           	        sf   | }t d| |tjd\}}t|| | }t tjd\}}tt|||}t| S )N      ?r   )r0  rq   r1  rH   r  r4  r3  r   )	r  r6  r7  r]  r:  r  r8  r9  r;  r   r=  r*  r)  rY   rZ   rB    s   
zBquantized_decomposed_quantize_per_tensor_default.<locals>.inner_fnr6  r7  rC  )r   rq   rF  r   r1  r3  r6   r   rc   r   r  r  r   r   r]  r6  r7  r)  r*  r   rB  rY   rK  rZ   0quantized_decomposed_quantize_per_tensor_defaultl  s   
rN  c                  sv   |   |ksJ d| d|    d u rtj|    fdd}tj|  tj|t	|t
|d|  dS )NrD  rE  c                   sF    | }t ||tjd\}}tt|tj|| }t|}|S r/  )r0  rq   r1  rH   rF  r   )r  r6  r7  r]  r  r=  rB  rY   rZ   rB    s
   zDquantized_decomposed_dequantize_per_tensor_default.<locals>.inner_fnrL  rC  )r   rq   r1  r3  r6   r   rc   r   r  r  r   r   r]  r6  r7  r)  r*  r   rB  rB  rY   rO  rZ   2quantized_decomposed_dequantize_per_tensor_default  s   rQ  c                   s   |   tjkrt| tj} |   tjksJ d|    t dks9t dkr5 d dks9J dt dksUt dkrQ d dksUJ d|     fdd}tj	| 
  ||  dS )	Nr-  r   r'   expect scale as scalar tensor"expect zero_point as scalar tensorc                   s   | }t  dkrdnd}t  dkrdnd}jtjkr-t|tj}jtjkr:t|tj}t|t| | }t	tjd\}}t
t|||}t| S )Nr'   r   rY   r   )r   r   r   rq   r1  rH   r   r  r2  r0  r4  r3  )r  r]  _scale_zero_pointr  r8  r9  r;  r   r=  r*  r)  r6  scale_loaderr7  zero_point_loaderrY   rZ   rB    s   zAquantized_decomposed_quantize_per_tensor_tensor.<locals>.inner_fnrC  )r   rq   rF  r   r1  r   r   r3  r6   r   rc   rM  rY   rW  rZ   /quantized_decomposed_quantize_per_tensor_tensor  s.   ""rZ  c                  s   t  dkst  dkr d dksJ dt  dks8t  dkr4 d dks8J d|  |ksJJ d| d|   d u rQtj|      fdd}tj|  ||  d	S )
Nr   r'   rR  rS  rD  rE  c                   s    | }t  dkrdnd}t  dkrdnd}jtjkr-t|tj}jtjkr:t|tj}tt|tj|| }t|}|S )Nr'   rT  rY   )r   r   r   rq   r1  rH   r   rF  )r  r]  rU  rV  r  r=  rB  r6  rX  r7  rY  rY   rZ   rB    s   zCquantized_decomposed_dequantize_per_tensor_tensor.<locals>.inner_fnrC  rH  rP  rY   r[  rZ   1quantized_decomposed_dequantize_per_tensor_tensor  s.   ""r\  c           
        s  | d   jdk}|r:tdd | D r:| D ]}|  qtdd | D r1ttjg| R  \} }ttjj| |S t	| dkrFt
| d S t| d |d}t| dtjifdd	| D } d%dddd fddtfdd| D }d&fddtjrt| |S |rttj| |S fddd}d d'ddt	| |kst	| tjkrt fd d| D rtfd!dtjjD }tfd"d| D o|}tfd#d| D otfd$d| D  }	|s|	r|st| |S ttj| |S )(Nr   cpuc                 s  s$    | ]}|  tjtjfv V  qd S r   )r   rq   int8uint8r   r]  rY   rY   rZ   r     s    
zcat.<locals>.<genexpr>c                 s  s     | ]}t | d kV  qdS )r   N)r   r   r`  rY   rY   rZ   r   &      r'   r   c                   s   g | ]}t | qS rY   r   r/  r   rY   rZ   r   1  r  zcat.<locals>.<listcomp>r   Union[TensorBox, ir.StorageBox]ro   	ir.IRNodec                 S  s>   t | trt | jtjr| j S | jS t | tjr| jS | S r   )r`   r9   rb   r*   r   r  
StorageBoxr   rY   rY   rZ   unwrap_tensor3  s   

zcat.<locals>.unwrap_tensorc                 S  s   t | tjot | jtjS r   )r`   r*   ComputedBufferrb   r7   rk   rY   rY   rZ   is_reduction?     zcat.<locals>.is_reductionc                   sJ   t | ttjfr | S | p$t | tjo$t fdd|  D S )Nc                 3  s     | ]} t j|V  qd S r   )rI   rQ   
get_buffer)r   readcan_fuse_reductionrY   rZ   r   H  s
    
z2cat.<locals>.can_fuse_reduction.<locals>.<genexpr>)r`   r9   r*   re  r6   r  get_read_namesrh  )rn  ri  rf  rY   rZ   rn  B  s   zcat.<locals>.can_fuse_reductionc                 3      | ]} |V  qd S r   rY   r   rk   rm  rY   rZ   r   O  r   r   c                   sZ   t | rt j| dd\}}t j| S t| tt jfr# | S t| t jr+dS dS )NF)freezeT)	r*   r  r  ConcatKernelcan_realize_into_without_copyr`   r9   re  r6   )r   r  r   )should_lower_cat_inputrf  rY   rZ   ru  Q  s   
z#cat.<locals>.should_lower_cat_inputc                   s\   t | ttjfr | S t | tjsdS |  j}|  D ]}| tj	
|7 }q|S r  )r`   r9   r*   re  r6   inner_fn_opcountnum_opsro  rI   rQ   rk  )r   countrl  )op_countrf  rY   rZ   ry  h  s   
zcat.<locals>.op_countr   r%   rT   torch._ops.OpOverloadc                 S  s   | t jjt jjfv S r   )r  catr  constant_pad_ndrT   rY   rY   rZ   additional_pointwise_ops}     z%cat.<locals>.additional_pointwise_opsc                 3  s    | ]	}| kV  qd S r   rY   rq  )MAX_SIMPLE_OP_COUNTry  rY   rZ   r         c                 3  s    | ]}t | V  qd S r   )r@   )r   use)r~  rY   rZ   r     s
    
c                 3  rp  r   rY   r/  ru  rY   rZ   r     r   c                 3  rp  r   rY   r/  r  rY   rZ   r         
c                 3  rp  r   rY   rq  rm  rY   rZ   r     r   )r   rc  ro   rd  )ro   r   rT   rz  )rc   rJ  r  rX  require_channels_lastr  r{  r  r  r   rm  r  r   r   r$  r  r(   force_pointwise_catr%  r9   r*   rs  r   max_pointwise_cat_inputsrI   rR   rS   )
r'  r   
cpu_devicer]  r   fusable_reductionMAX_COMPLEX_POINTWISE_CATpointwise_usesfuse_pointwise_usehorizontal_fuse_catrY   )r  r~  rn  r   ri  ry  ru  rf  rZ   r{    s`   




r{  offsetdim1dim2c                   s  |   ttdtdtkfdd tjjt	|d}|rBtjj
tjj |  d}ntjj
tjj  | d}d |r`| df nd|f fddtD }||  fdd	}ttj| ||S )
N)r  rankc                     s   d  d S )Nz(diagonal dimensions cannot be identical z, rY   rY   r  r  rY   rZ   r        zdiagonal.<locals>.<lambda>r   )r   r   c                   s    g | ]\}}| fvr|qS rY   rY   )r   rg   r  r  rY   rZ   r          zdiagonal.<locals>.<listcomp>c                   s   | d }dgt  }d}tD ]&}|kr | d  ||< q|kr-| d  ||< q| | ||< |d7 }q|t d ksBJ |S )Nr0  r   r'   r%   )r   r   )r  diag_idxoriginal_idxcur_dimr  base_idxr  r  num_dimsoriginal_shaperY   rZ   	reindexer  s   
zdiagonal.<locals>.reindexer)r   r   r   r   rI   rQ   r  r  r   Ltevaluate_maxevaluate_minr_   rd   r9   r*   GenericViewr   )r]  r  r  r  offset_negative	diag_sizer  r  rY   r  rZ   diagonal  s:   
r  c                 C  s   t t| |||S r   )rm  r  )r]  r  r  r  rY   rY   rZ   diagonal_copy     r  c                 C  $   t | }t||||}t|| |S r   )rm  r  	mutate_to)r]  srcr  r  r  r  rU   rY   rY   rZ   diagonal_scatter     
r  c                 C  s,   t ||  | }tt| |||d |S r  )r;   handle_negative_indexr   r  r  )r   r   r  rY   rY   rZ   select  s   r  c           
   
   C  s   t | |d}|}t|ttfs2|  | }tjjt	|| d |}|g| }||d |  |d< g }d}|D ]}|| }	|
t| |||	dd |	}q8|S )Nr   r'   r0  Fr  )r  r`   r^   r   r   rI   rQ   r  r  r"   rd   r  )
r   r  r   sizes_x_sizechunksr  r  r   r  rY   rY   rZ   split  s    
r  c                 C  s   t | ||S r   )r  )r   r  r   rY   rY   rZ   split_with_sizes      r  c                   s>   t  d tjj   } fddt|D }|S )Nr   c                   s   g | ]}t  |qS rY   )r  r   r   r   rY   rZ   r   	      zunbind.<locals>.<listcomp>)r  rI   rQ   r  r  r   r   )r   r   r  r  rY   r  rZ   unbind  s   r  c                   s   |   }t|}t|| |dkrtt| d|dS |  }tjj}||| |	d t
|| d }||dkrK| |t|| | g |d   || d d  |}	 fdd}
ttj| |	|
S )Nr   )r  r'   c                   s:   | d |     }g | d   ||  d d R S )Nr0  r'   rY   )r  dim_idxr   r  rY   rZ   r  #  s   &zunfold.<locals>.reindexer)r   r   r   r  r  rI   rQ   r  	guard_leqguard_ltr"   r  r  r!   r9   r*   r  r   )r   	dimensionr   r  r  ndimdim_sizer  new_dim_sizeout_sizer  rY   r  rZ   unfold  s"   
(r  c                 C  s2   t | |d}t|  }||tjj t| |S r  )r  r^   r   insertr   r  r  r  )r   r   r  rY   rY   rZ   r  *  s   
r  c                 C  r  r   )r  r`   r9   rb   r  rY   rY   rZ   
unsqueeze_2  r  r  c                 C  sZ   t jjjt|}t|  }|dk r||| 7 }d|  kr(|| k s+J  J |S r  )	rI   rQ   r  r  r  r   sympifyr   r   )r   r   r  r  rY   rY   rZ   r  ;  s    r  r0  c                 C  sT   t | |d}tjj|  | d }t| |d|}t| |||d }t|t|S )Nr   r%   )	r  rI   rQ   r  r  r   r  rD  sigmoid)r   r   new_lenr   r  rY   rY   rZ   gluD  s
   r  c                   s$   |rt    fdd}d|_|S )Nc                    s*   dd }t |tjj g| R i |S )Nc                 S  s   t | tjrt| S | S r   )r`   r*   r1   r9   r   r   rY   rY   rZ   wrap_tensorsS  rj  z7fallback_handler.<locals>.handler.<locals>.wrap_tensors)pytreetree_mapr*   FallbackKernelr   )rh   r   r  kernelrY   rZ   handlerR  s   z!fallback_handler.<locals>.handlerT)r   r   _is_fallback_handler)r  r}  r  rY   r  rZ   r  N  s
   
	r  c                   C     t d d S )NzjTorchinductor does not support code generation for complex operators. Performance may be worse than eager.)warningswarnrY   rY   rY   rZ   _warn_complex_not_supported`  s   r  rk   torch.Tensorc                 C  s   |   r	t  dS | jrdS | jtjkr?|sdS t|jtjj	r1|jt
jjt
jjt
jjt
jjfv p=t|jtjj	o=t|j S dS )z0Do not support reading or writing to this tensorTF)r  r  is_metar   rq   float8_e8m0fnur`   rU   rr   rs   r  r  r{  r  rm  
_scaled_mmrA   )rk   rW   rY   rY   rZ   unsupported_input_tensori  s(   r  c                 C  sL   t jjtjjjjf}|dur|j|v r| 	 rdS t
| |r dS | jo%tjS )z2Do not support writing tensor but can read from itNFT)r  r  r   rq   rH   r  r  r  rU   r  r  is_cpur(   disable_cpp_codegen)rk   rW   supported_complex_viewsrY   rY   rZ   unsupported_output_tensor  s   

r  rW   torch.fx.Nodec                   sv    j tjju r	dS  jdkrdS  j tjju rdS  fdd}tj ji  j	D ]}||ddr4 dS q)| ddS )NFplaceholderc                   sp   t | tjjs	dS d| jvrdS t| jd D ]}t |tjjs"q|r-t	| r, dS qt
| r5 dS qdS )NFr  T)r`   rq   fxNoderH  r  tree_leaves_subclasses
FakeTensorr  r  )inp_out_node	is_outputrH  rW   rY   rZ   check_skip_condition  s   


zCfallback_node_due_to_unsupported_type.<locals>.check_skip_condition)r  T)
rU   r  view_as_complexr  rT   lift_fresh_copyr  arg_tree_leavesrh   r   )rW   allow_cpu_inputsr  r   rY   r  rZ   %fallback_node_due_to_unsupported_type  s   
r  c                   s   | t vs|sJ d|  |r>ttdr>t| gr>tjr%| tjj	j
v s>|s>tjjjr6dtjj_td td|  d fdd}t| tjjr]|  D ]}t| |}|| qOd S t| tjjtjjfrn||  d S td	|  d
t|  )Nz*both a fallback and a decomp for same op: CIFznA make_fallback error occurred in suppress_errors config, and suppress_errors is being disabled to surface it.zmake_fallback(a.  ): a decomposition exists, we should switch to it. To fix this error, either add a decomposition to core_aten_decompositions (preferred) or inductor_decompositions, and delete the corresponding `make_fallback` line. Get help from the inductor team if unsure, don't pick arbitrarily to unblock yourself.c                   s.   t |   d urt|   t| d dt| S Nro  )r   r   r  r  )op_overloadlayout_constraintrY   rZ   register_fallback  s   

z(make_fallback.<locals>.register_fallbackzUnsupported fallback z with type )r,   r   osgetenvr-   r(   fallback_randomrq   _decompdecompositions_for_rngextra_random_decomps_dynamosuppress_errorslogwarningr   r`   rr   r   r   r   rs   HigherOrderOperatorRuntimeErrorrJ  )rT   r  r  override_decompr  olr  rY   r  rZ   make_fallback  s>   




r   c                 C  s$   d}| D ]}|| }qt |tjdS )z
    TorchInductor offset calculation differs from PyTorch eager offset
    calculation for random ops (tl.rand vs torch.rand). In future, we should
    strive for same impl for tl.rand and torch.rand.
    r'   r   tensorrq   r  )r  numelr  rY   rY   rZ   philox_rand_offset  s   
r  c           	        sd   t | | t j|  | |  fdd}tj| |t| d}t	| }||fS )Nc                   sV   t g tj}t g tj}t t | tj|}t ||}t | S r   )rH   r   rq   r  r   r  rand)r"  seed_index_exproffset_index_exprrand_index_exprr  r   offset_loader
random_posseed_loaderrY   rZ   rB    s   zphilox_rand.<locals>.inner_fnrC  )
r*   r  FlexibleLayoutcontiguous_stridesmake_indexerr3  r6   r   r^   r  )	r   seedr  r  rj   r   rB  random_values_nodeoffset_noderY   r	  rZ   philox_rand  s&   
r  c              	   C  s.   t jrttjtjtj	j
| ||S td)Nz&should be handled in replace_random.py)r(   r  r  r  r9   r   r*   r  r  native_dropoutr  r   )r   ptrainrY   rY   rZ   r  "  s   r  c                 G  sj   t js|  tdksJ d|   t|dks!t|d tr%t	j
jnt	j
j}tj|| g|R   | S )Nr]  Tthis should be handled in decomps unless config.fallback_random or the device is CPUr   )r(   r  rc   rq   rj   rX  r   r`   r  r  
bernoulli_Tensorr*   InplaceBernoulliFallback)r   rh   r  rY   rY   rZ   r  -  s   r  c                 G  s4   t js|  tdksJ dtt| g|R  S )Nr]  r  )r(   r  rc   rq   rj   r  rm  )r   rh   rY   rY   rZ   bernoulli_p<  s   r  c                 C  s   t r   r   r   rY   rY   rZ   _foobarE  r  r  c                 C  r  )Nz1using triton random, expect difference from eager)r  info)saltrY   rY   rZ   _warn_triton_randomJ  r  r!  c                   C  s   t tjj d S r   )r!  rI   rQ   creation_timerY   rY   rY   rZ   warn_triton_randomO  r  r#  c                  O  F   | dd d urt| i |S tjr|dd  t| i |S tdN	generatorz-should have been handled in replace_random.py)rI  fallback_rand_generatorr(   r  popfallback_rand_defaultr   r  rY   rY   rZ   r  [     r  c                  O  r$  r%  )rI  fallback_randn_generatorr(   r  r(  fallback_randn_defaultr   r  rY   rY   rZ   randne  r*  r-  c                 C  s   t |}t j| |S r   )r*   get_stride_orderExternKernelrequire_stride_order)input_tensorr  stride_orderrY   rY   rZ   inductor_force_stride_ordero  s   
r3  c                 C     t d)Nz.should be handled in fuse_seed_creation_pass()r  )rj   rY   rY   rZ   inductor_seedu     r5  c                 C  s   t   tt| t|S r   )r#  r9   r   r*   RandomSeedsr=   )rx  rj   rY   rY   rZ   inductor_seedsz  s   r8  c                   s(    fdd}t j  |g dS )Nc                   s   t   S r   )rH   	load_seedget_namer  r"  seedsrY   rZ   rB    rk  z&inductor_lookup_seed.<locals>.inner_fnrC  )r6   r   rc   r   )r<  r"  rB  rY   r;  rZ   inductor_lookup_seed  s   r=  r  r   	list[int]r  modestrc                  s   t jrJ  dv sJ g | } tj}| }tj||| tj| |d	 |
  fdd}tj|||g | d}|  |S )N)r  r-  r>  c                   s"   t t g t| tjS r   )r   rH   r  rq   r  r7  r@  r  r  rY   rZ   rB    s   z!inductor_random.<locals>.inner_fnrC  )r(   r  rq   r1  r&  r*   r  r  r  r  r3  r6   r   rX  )r   r  r@  r  r   rj   rB  r  rY   rB  rZ   inductor_random  s(   
rC  lowhighc                  sp   t jrJ g |}tj}| }tj|||tj||d	 |
  fdd}tj|||g |dS )Nr>  c              	     s6   t g t | tjt tjt  tjS r   )rH   	randint64r  rq   r  r  r7  rE  rD  r  r  rY   rZ   rB    s   z"inductor_randint.<locals>.inner_fnrC  )r(   r  rq   r  r&  r*   r  r  r  r  r3  r6   r   )rD  rE  r   r  r  r   rj   rB  rY   rG  rZ   inductor_randint  s"   
rH  tb.tuple[str, sympy.Expr, sympy.Expr, sympy.Expr]c                 C  s4   |   |  d |  d |  d  |  d fS Nr0  r   )r:  r   
get_striderI  rY   rY   rZ   _boundaries_helper  s
   

rN  tuple[str, sympy.Expr]c                 C  s   |   |  d fS r  )r:  rL  rM  rY   rY   rZ   _sorter_helper  r  rP  	out_int32rightsidesortersorted_sequenceselfrR  rS  rT  Optional[str]rU  Optional[TensorBox]c          
        s   dd }|r||rd ur$|s$t tjjdd|||dS |d ur.|dkr.d|r3tjntj |   d urF  t	
 dkrY fd	d
}n
 fdd
}| }tj| ||jd}	|	  |	S )Nc                 S  s   t j| tjS r   )rI   rQ   rU  rV  	BUCKETIZErM  rY   rY   rZ   r    s    zsearchsorted.<locals>.<lambda>Fr|  rQ  rS  Tr'   c              	     sD   | }t j|td d u rd ntd u rd dS ddS )Nr   rU  sorter_indicesrH   	bucketizerN  rP  )r  r  index_dtyperS  rV  rU  values_loaderrY   rZ   rB  	  s   
zsearchsorted.<locals>.inner_fnc              	     s\    }d fdd}t j|t|d u rd ntd u r(d dS |dS )NrI  r9   c                   s>   |   }tttjdd t|d d  d d D S )Nc                 s  s    | ]	\}}|| V  qd S r   rY   )r   r  rg   rY   rY   rZ   r   	  r  zNsearchsorted.<locals>.inner_fn.<locals>.get_flattened_index.<locals>.<genexpr>r0  )rL  rH   r  r   r  operatorr   r   )rI  strides)r  r`  rY   rZ   get_flattened_index	  s   &z;searchsorted.<locals>.inner_fn.<locals>.get_flattened_indexr[  )rI  r9   r]  )r  r  rd  r_  r  rZ   rB  	  s   	
rC  )r  r  searchsortedr  rq   r  r  r3  rX  r   r   rc   r6   r   r  )
rV  rW  rR  rS  rT  rU  validate_bucketizerB  rj   r  rY   r_  rZ   rf    sB   
rf  rR  rS  
boundariesc                  s   t   dks
J tj| tjrtj tjs(ttj	j
dd|  |dS    |  }|  |r9tjntj fdd}tj|||  d}|  |S )Nr'   Fr|  rh  c                   s"   | }t |t d}|S r  )rH   r^  rN  )r"  r  r  ri  r`  r=  rS  rY   rZ   rB  S	  s   zbucketize.<locals>.inner_fnrC  )r   r   rI   rQ   rU  rV  rZ  r  r  r^  r  rX  rc   r3  rq   r  r  r6   r   )r]  ri  rR  rS  rj   rB  r  rY   rj  rZ   r^  5	  s*   
r^  c                 O  $   t tjtjj||f\}}||fS r   )r  tree_map_onlyr*   r1   r/  require_stride1r   rh   r   rY   rY   rZ   require_denser	     ro  c                 O  rk  r   )r  rl  r*   r1   r/  require_contiguousrn  rY   rY   rZ   rq  y	  rp  rq  c                 O  rk  r   )r  rl  r*   r1   r/  r{   rn  rY   rY   rZ   r{   	  s   r{   c                 O  rk  r   )r  rl  r*   r1   r/  r  rn  rY   rY   rZ   r  	  rp  r  c                   s|   t  tjrdd  D }tj |S t  tr' fdd  D S t  tt	fr<t
 dd t D S  S )Nc                 S  $   g | ]}t |tjr|jjn|qS rY   r`   rq   SymIntrW   exprr  rY   rY   rZ   r   	      z,constrain_to_fake_tensor.<locals>.<listcomp>c                   s    i | ]}|t  | | qS rY   constrain_to_fake_tensorr   keyr   fake_argrY   rZ   r   	  s    z,constrain_to_fake_tensor.<locals>.<dictcomp>c                 s      | ]
\}}t ||V  qd S r   rw  )r   r   f_arY   rY   rZ   r   	      
z+constrain_to_fake_tensor.<locals>.<genexpr>)r`   r*   r1   r  r/  require_exact_stridesr   r  r   r^   rJ  r   )r   r|  meta_stride_exprrY   r{  rZ   rx  	  s   
rx  c                   s6   t dd t| |D }  fdd| D }| |fS )Nc                 s  r}  r   rw  )r   r   r|  rY   rY   rZ   r   	  s
    
z,constrain_to_fake_tensors.<locals>.<genexpr>c                   s    i | ]\}}|t | | qS rY   rw  r   fake_kwargsrY   rZ   r   	  r  z-constrain_to_fake_tensors.<locals>.<dictcomp>)r   r   r   )rh   r   	fake_argsr  rY   r  rZ   ry   	  s
   ry   c                   sJ    fdd t  fddt|jD } fdd| D }||fS )Nc                   s^   t  tjrtjd  tjjj	}tj
 |S t  tr- fdd  D S  S )Nr  c                   s    i | ]}| | | qS rY   rY   ry  )apply_constraintr   fx_argrY   rZ   r   	  r  zEconstrain_to_fx_strides.<locals>.apply_constraint.<locals>.<dictcomp>)r`   r*   r1   r.  rH  r  rI   rQ   r  r  r/  r0  r   r  )r   r  r2  r  )r   r  rZ   r  	  s   
z1constrain_to_fx_strides.<locals>.apply_constraintc                 3  s    | ]
\}} ||V  qd S r   rY   )r   r   r  r  rY   rZ   r   	  r  z*constrain_to_fx_strides.<locals>.<genexpr>c                   s"   i | ]\}}| |j | qS rY   r   r   r  fx_noderY   rZ   r   	  s   " z+constrain_to_fx_strides.<locals>.<dictcomp>)r   r   rh   r   r  rh   r   rY   r  rZ   r}   	  s   

r}   c                   sN   fdd t  fddtt|jD } fdd| D }||fS )Nc                   s  t |tjs|S |jd }dd | D }t| }|r1|d dkr1tttt	|
 }jtjjkrF| dv rFt	|dksDJ d}|jsPtj||S d	 jtjjjjko^| d
k}t |tsfJ t	|
 dvrp|S t| rttj||S t |tr| d urt| rttj||S |r4t|
 }g }| }	tt	|
 d D ]}
tjj||
 ds|	d urtjj|	|
 dr||
 qdgt	| }d|d< d}tt	|d ddD ]A}
||
d  dkr|||
d   }|
|v rtjj||
d    drd||
< qtjj|  ds(t|   }|||
< qtj ||S t| rEttj||S t |trc| d urct| rcttj||S  fdd}t |j!tj"r||s||# rttj||S tj||S )Nr  c                 S  rr  rY   rs  r  rY   rY   rZ   r   	  rv  z=sdpa_constraint.<locals>.apply_constraint.<locals>.<listcomp>r0  r   )r   r   r   )r   r'   r%   r   r   r   r   r   r'   r%   c                   s   t jj|  d   dkS rK  )rI   rQ   r  	size_hintr   r   	ALIGNMENTrY   rZ   
is_aligned.
  s   z=sdpa_constraint.<locals>.apply_constraint.<locals>.is_aligned)$r`   r*   r1   rH  r  r.  r^   r  r   r   r   rU   r  0_scaled_dot_product_efficient_attention_backwardr  is_cudar/  r0  rq   rH   '_scaled_dot_product_efficient_attentionr9   is_aligned_realized_tensortry_match_insignificant_stridesrealize_inputmaybe_get_striderI   rQ   r  statically_known_equalsrd   r<   r  rb   r   r  )r  r   r  meta_valr  r2  effn_attn_fwd_biasr  expanded_dimsmaybe_striderg   out_stridesr  r  )r  r  rZ   r  	  s   







z)sdpa_constraint.<locals>.apply_constraintc                 3  s$    | ]\}\}} |||V  qd S r   rY   )r   r  r   r  r  rY   rZ   r   :
  s
    


z"sdpa_constraint.<locals>.<genexpr>c                   s$   i | ]\}}| d |j | qS r0  r   r   r  rY   rZ   r   >
  s   $ z#sdpa_constraint.<locals>.<dictcomp>)r   r_   r   rh   r   r  rY   r  rZ   sdpa_constraint	  s   {r  )r  c                 C  sn   |}|   |  krt||   }|  | kr t||  }|  | kr3t||  }t|S t|S r   )rc   r  r   r   r   r  rm  )rW  r  r  r   re   rY   rY   rZ   rn    s   rn  )memory_formatc                C  s&   t j|  |  |  t|  dS NrC  )r6   r   rc   r   r3  r^   r   )r   r  rY   rY   rZ   rm  $  s   
rm  c                 C  s   g }t | tr+t | jtjr+| j} t | tjr'||   | j} t | tjst| } t| } |rI| j} |d d d D ]	}tj| |d} q;t| } | S )Nr0  r  )r`   r9   rb   r*   r  rd   
get_layoutrm  )r   reinterpret_view_layoutsr  rY   rY   rZ   clone_preserve_reinterpret_view/  s   r  r  c                  s(    fdd}t jt| || gdS )Nc                   s   t j| d    dS )Nr   r   rH   r  r7  r   r  r  rY   rZ   rm   Q  rj  ziota.<locals>.fnrC  )r6   r   r=   )lengthr  r  r   rj   requires_gradrm   rY   r  rZ   iotaG  s   
r  r   r"  c                   s   |   |  ks
J |  t|  d tjjtdr'| 	    tjj
d tjj| 	    tt| | 	 }|  fdd}tj|  |   |t| 	 dS )Nr   c              	     s6   t t t |   tjt tj| | S r   )rH   r  eqr  rq   r  re  r   r"  
src_loaderr  rY   rZ   rB  h  s   z select_scatter.<locals>.inner_fnrC  )r   r3  r  rI   rQ   r  r  r   r  r   r  r  r  r  r6   r   rc   r^   )r   r  r   r"  rB  rY   r  rZ   select_scatter\  s    

r  c                   s     |  ks
J  t d    tj \t }t d  | < t	||}|  fdd}t
j   |t dS )Nr   r'   c              
     s2  dkrkrdkr| S t |  tj}t|  t|    < g }dkr?|t |t t	tj krT|t 
|t t	tj dkrs|t t t|   dtjt dtj |swJ tt j|}t | fddtrdnd}t ||| S )Nr   r'   c                         S r   rY   rY   )src_idxr  rY   rZ   r        z1slice_scatter.<locals>.inner_fn.<locals>.<lambda>r  )rH   r  rq   r  r^   r"   rd   r  r   r  r  r  r$   r  r   r  r  r  r   r  )r  r  r   src_valr   r  r  r  r  r  r   r  )r  rZ   rB    sR   zslice_scatter.<locals>.inner_fnrC  )r   r3  r  r   r*   r  normalize_start_endr^   r"   r  r6   r   rc   )r   r  r   r  r  r  src_sizerB  rY   r  rZ   slice_scatterz  s    
.
r  c                 C  s*   t | ttfrt| dkrt| d S | S r  )r`   r^   r   r   _unwrapr   rY   rY   rZ   r    s   r  r   rj   r  
pin_memoryc                  s  t |d tjfv d|  t | d tt tr ptjnp%t g }t tj	r6 fdd}nBt t
tfrE fdd}n3t dksZt d t
tfrlt dkrl|tt   fdd}ntjtj |d	S tjt|||d
S )Nlayout=r  c                      t  S r   r  r7  rb   r   rY   rZ   rB       ztensor.<locals>.inner_fnc                   r  r   rH   r  r7  r  rY   rZ   rB    r  r   r   c                   s8    fdd t dkrtdS  dt S )Nc              	     sr   | |k sJ ||  dkrt |  S ||  d |  }t t t d tjt |tj | | ||S )Nr'   r%   r   )rH   r  r  r  r  rq   r  )r  r  mid)binary_searchrb   r   r"  rY   rZ   r    s   z/tensor.<locals>.inner_fn.<locals>.binary_searchr   )r   rH   r  r7  r  )r  r"  rZ   rB    s   r  rC  )r   rq   stridedr`   r  r   r  get_default_dtyper   r   r  r   rd   IntegerrI   rQ   add_tensor_constantr  r6   r   r=   )rb   r   rj   r  r  rA  rB  rY   r  rZ   r    s,   *r  c                 C  s@   t | tr|d urt| |} |d urt| |} | S t| ||dS )Nr  )r`   r9   r   r  r  )rb   r   rj   rY   rY   rZ   	as_tensor  s   


r  c                 C  s   t | tjdS r/  r  rb   rY   rY   rZ   long_tensor  r  r  c                 C  s   ddl m} |tjjjtjjjd }|d usJ t|dks#J |t	t
| \}}t||| }tj||_tj| tjjjd }t|tjtjtjfrW|jjS t|S )Nr   )resolve_unbacked_bindingsunbacked_bindingsr'   r  )%torch.fx.experimental.symbolic_shapesr  rI   rQ   r  r  rR   rH  r   r%  iterr   r*   DynamicScalarregister_bufferr   register_operationr`   rq   rt  SymFloatSymBoolrW   ru  r   r  )rb   r  r  binding_symkeypathbufferr  rY   rY   rZ   _local_scalar_dense  s   
r  c                 C     d S r   rY   )rb   r   rY   rY   rZ   _assert_scalar<  s   r  )rj   r  c                C  r  r   rY   )r   r   r  r   rj   r  rY   rY   rZ   _assert_tensor_metadataF  s   r  c                   s   | t | ttfstdrjt ttfr  fdd}n"t tjr. fdd}nt dks8J 	 fdd}t
j| |t|dS )Nr   c                      t  S r   r  r7  r   r   rY   rZ   rB  T  r  z_full.<locals>.inner_fnc                   r  r   r  r7  r  rY   rZ   rB  Y  r  r   c                   s    g S r   rY   r7  )value_loaderrY   rZ   rB  `  s   rC  )r`   r   r  r   r   r   r   r   r   r3  r6   r   r^   )
fill_valuerj   r   r   rB  rY   )r   r   r  rZ   _fullM  s    r  c                 K  s   t t|| fi |S r   create_tensor_liketensor_constructor)r   r  r   rY   rY   rZ   r  k  s   r  c                   s    d d d d dd d fdd
}|S )NF)namesr   rj   r  r  r  c                   s   t | d u d t |d tjfv d|  t | d t|}|p#t }t|dkr;t|d tttj	fr;t|d }|D ]
}t|tj
rGJ q=dd |D }t |||S )Nnamed tensorsr  r  r'   r   c                 S  r  rY   r  r  rY   rY   rZ   r     r  z5tensor_constructor.<locals>.inner.<locals>.<listcomp>)r   rq   r  r=   r  r   r`   r^   r   Sizert  r  )r  r   rj   r  r  r  r   r  r  rY   rZ   rP  r  s   	"z!tensor_constructor.<locals>.innerrY   )r  rP  rY   r  rZ   r  p  s   r  )r  r   r  rj   r  r  c                 G  sX   t | d u d t|}t|dkr"t|d tttjfr"t|d }t|d ||||dS )Nr  r'   r   r   r  rj   r  )	r   r=   r   r`   r^   r   rq   r  empty_strided)r  r   r  rj   r  r  r   rY   rY   rZ   r    s   
"r  c                   s   dddddd fdd
}|S )zZ
    Shim to convert X_like(...) into X(...).  For example zeros_like() into zeros().
    NF)r   rj   r  r  r  c                  sj   t | d t |d tjfv d|  |d u r|  }nt|}|p%|  }t|  } |||||dS )Nr  r  r  )r   rq   r  r   r   rc   r^   r   )r   r   rj   r  r  r  r   creation_fnrY   rZ   _constant_like  s   

z*create_tensor_like.<locals>._constant_likerY   )r  r  rY   r  rZ   r    s   
r  c                 C  s   t t| S r   r  r  rY   rY   rZ   r    r  r  c                   s   d d d d d fdd
}|S )Nr  c                  st   t |ttfs	J t| d t|d tjfv d|  t|p#|  }|p)|  }dd |D }t	 t
|||S )Nr  r  c                 S  r  rY   )r   r  r  rY   rY   rZ   r     r  z7new_constant.<locals>._new_constant.<locals>.<listcomp>)r`   r^   r   r   rq   r  r   r   rc   r  r=   r   r   r   r  rj   r  r  rY   rZ   _new_constant  s   z#new_constant.<locals>._new_constantrY   )r  r  rY   r  rZ   new_constant  s   r  r  c                C  s8   |d u r|   }|d u r|  }t|d ||t||dS Nr  r   rc   r  r=   r  rY   rY   rZ   	new_empty  s   r  c                C  s  t | ttfs	J t |tttd fsJ t| d t|d tjfv d|  t|p/t }|p7t	dj
}t|}td||| d}|  |jj}tj|jdgt|  d|_t |tjsbJ dd | D } |rrd	d |D ntj| }tj||| |d
|_|S )Nr  r  r  r   )r  rj   r   r   )rA  c                 S  r  rY   r  r  rY   rY   rZ   r     r  z!empty_strided.<locals>.<listcomp>c                 S  r  rY   r  r  rY   rY   rZ   r     r  )rj   r   r   r  )r`   r^   r   rJ  r   rq   r  r   r  r  rj   r=   r  rX  rb   dataclassesreplacer   r*   rg  r  r  r  r  )r   r  r   r  rj   r  	pointwiser  rY   rY   rZ   r    s0   
r  c                C  s8   |d u r|   }|d u r|  }t||||t||dS r  r  )r   r   r  r   r  rj   r  rY   rY   rZ   new_empty_strided  s   r  c                 C  s2   dd |D }t tt||jd}tj| |S )Nc                 S     g | ]	}t jj|qS rY   )rI   rQ   r  r  r  rY   rY   rZ   r     r   z copy_strided.<locals>.<listcomp>)rz  )sortedr   r   __getitem__r*   r/  r0  )r   r  r2  rY   rY   rZ   copy_strided  s   r  c                 K  s*   | dd usJ dt|| fi |S )Nr   z(dtype should be handled by decomposition)rI  r  )r   r  r   rY   rY   rZ   full  s   r  c                   s   t | tsJ | dkrt| | S |  tdk}t|  | |r/t| dg} dg|  |  fdd}t	j
|  |  || dS )Nr   r'   c                   sF   t | } t|   }t| dkr|g} | S ||  < | S r  )r^   rH   indirect_indexingr   )r  
gather_idxr   index_loaderr   r  rY   rZ   rm   1  s   zgather.<locals>.fnrC  )r`   r9   	get_numelr  r   r   r  r  r3  r6   r   rc   r   )r   r   r"  sparse_gradr  rm   rY   r  rZ   gather  s$   	r  c                   s   |rt tjj| ||||S |rJ t| tsJ t|ts J dt| v s*J |  |  t	|
 | 
 g |
 dd   fdd}tj|  |  |dS )Nr   r'   c                   s\   t | t ksJ |  d  | d  }t|d gg | d   }|S )Nz != r   )r   rH   r  )r  	var_index
weight_idxindices_loaderindices_ndimr  weight_loaderweight_sizerY   rZ   rm   T  s   "
zembedding.<locals>.fnrC  )r  r  	embeddingr  r`   r9   rA  r   r3  r   r   r6   r   rc   )weightr  padding_idxscale_grad_by_freqsparserm   rY   r  rZ   r  B  s(   

r  c                   s   t dd  D sJ ddd  D  tdd  D r"tddd t D }t|d	ks5J d
d gt  }t|t fdd|D  D ]\}}| |krXtd|||< qJ||fS )Nc                 s  s4    | ]}|d ur|  tjtjtjtjfv V  qd S r   )r   rq   r  r  r   r_  r   rY   rY   rZ   r   e  s    z.check_and_broadcast_indices.<locals>.<genexpr>z)indices must be int64, byte or bool. Got c                 S  s   g | ]
}|d ur|  qS r   r   r   rY   rY   rZ   r   j      z/check_and_broadcast_indices.<locals>.<listcomp>c                 s  s,    | ]}|d ur|  tjtjfv V  qd S r   )r   rq   r   r_  r   rY   rY   rZ   r   l  s    "zFallback for bool indicesc                 S  r   rY   r   r   rY   rY   rZ   r   q  r   r   z"requires at least 1 non-None indexc                   r  rY   rY   r   r  rY   rZ   r   t  r   z.Fallback when indices is on a different device)r  r  r   r_   r   r   r   rc   )r  rj   
valid_idxsnew_indicesrg   r   rY   r  rZ   check_and_broadcast_indicesd  s"   
$
r  c	              
     s   dt dd  D ]\}	}
|
|	 dkrdq
fddtD g 
tt d  d }r> nd |  |d    	f
dd}|fS )	NFr'   Tc                   s    g | ]\}}|d u r | qS r   rY   )r   rg   r  r  rY   rZ   r     r  z2index_output_size_and_inner_fn.<locals>.<listcomp>r   c           	   	     s  t | t ks
J t t ksJ t }g }d }r"dn|}d}td d D ]F}||kr8||7 }| d u rR|t | k sFJ || |  |d7 }q.| }|d us\J | }|tj|| |||  | d q.g || |d  }	d u r|S 	|S )Nr   r0  r'   r   wrap_neg)r   r   rd   rH   r  )	r  r  	new_indexfirst_tensor_indexstart_offsetnext_idxrg   loaderr   )
r   indexed_sizer  indices_loadersnon_consecutive_tensorsoutput_sizetensor_indicestensor_sizer  r  rY   rZ   rm     s>   

z*index_output_size_and_inner_fn.<locals>.fn)r   r_   r   )r  r  r  r  r  r  r  r   r  previouscurrentr  rm   rY   )r   r  r  r  r  r  r  r  r  r  r  rZ   index_output_size_and_inner_fn~  s$    


"r  c                 C  s,   t | ||\}}}tj|  |  ||dS r  )index_impl_helperr6   r   rc   r   )r   r  r   r  rB  r   rY   rY   rZ   
index_impl  s   r!  c           
        s   t ttfs	J |  t|  \}t|dks J ddd D }t|d   }|  fddttD }|rQd|v rQd|vrQt	dfddttD }t
||||d ||d	\}  fd	d
}	||	 fS )Nr   z Must have at least one valid idxc                 S      g | ]}|d ur|  nd qS r   r2  r   rY   rY   rZ   r     r  z%index_impl_helper.<locals>.<listcomp>c                   s    g | ]} | d ur| qS r   rY   r   )r  r  rY   rZ   r     r  z0index is out of bounds for dimension with size 0c                   r  rY   rY   r   r  rY   rZ   r     r   r  c                   s    | S r   rY   re  )index_inner_fnr  rY   rZ   rB    r  z#index_impl_helper.<locals>.inner_fn)r`   r^   r   r3  r  rc   r   r   r   
IndexErrorr  )
r   r  r   r  r  r  r  r  r  rB  rY   )r#  r  r  r  rZ   r     s0   

r   c                 C  sB   zt | |ddW S  ty    |   ttjjdd| | Y S w )NTr   Fr|  )r!  r   rX  r  r  r"  r  r   r  rY   rY   rZ   r"    s   c                 C  s   t | |ddS )NFr%  )r!  r&  rY   rY   rZ   _unsafe_index  r  r'  c                 C  s   t t| |||dddS )NTFr   may_realizeindex_put_impl_rm  r   r  r   
accumulaterY   rY   rZ   	index_put     r.  c                 C  s   t t| |||dddS )NFr(  r*  r,  rY   rY   rZ   _unsafe_index_put  r/  r0  c                 C  sB   |  |   krt||   }|rt| |}t| t|d || S r  )rc   r  r   r  r  )rW  r  r   r-  rY   rY   rZ   index_put_as_masked_fill  s
   
r1  c                 C  s   t tjjj| ||| | S r   )r*   IndexPutFallbackrI   rQ   rR   rU   rW  r  r   r-  rY   rY   rZ   index_put_fallback&  s   r4  c                 C  s   t | |||dddS )NTr(  r+  r3  rY   rY   rZ   
index_put_+     r6  c                 C  s   t | |||dddS )NFTr(  r5  r3  rY   rY   rZ   _unsafe_index_put_2  r7  r8  c              
     s  |r!dd }dd  || |  v r!t fdd|D s!|  | dkrZt|dkrZ|d  tjtjfv rZ|d }t	t|
 t| 
 D ]}t|d	}qJt| |g||S t ret| |||S |D ]}	|	d ur|	 tjtjfv rt| |||  S qg| 
 t}
|rt|  r|
dkrt| dg} t| |||} |
dkrt| g } | S t||  }zt||  \}}W n ty   t| ||| Y S w d
d |D }t| tsJ |   |
dkrt| dg} t||d  
 }fddt	t|D }t|||||d |d\}}t||}tj|  |  | |||r(dnd d}tjd t| |d}tj !||_"tj #| |
dkrNt| g } | S )Nc                 S  sP   t | tjr	| j} t | tjr|  } t | tjr| j} t | tjr&|  S d S r   )	r`   r*   r9   rb   r   r  re  Bufferr:  r   rY   rY   rZ   try_get_name<  s   z%index_put_impl_.<locals>.try_get_namec                 S  sd   t | tr0t | jtjr0| j } t | tjo/t | jtjo/t| jdd o/| jj	j
tjjjjkS dS )Nr  F)r`   r9   rb   r*   r   r  re  r/  r   r  rU   rq   rH   r  randpermr  )indicerY   rY   rZ   indice_slice_from_randpermE  s   
z3index_put_impl_.<locals>.indice_slice_from_randpermc                 3  rp  r   rY   )r   r<  )r=  rY   rZ   r   S  r  z"index_put_impl_.<locals>.<genexpr>r'   r   r0  c                 S  r"  r   r2  r   rY   rY   rZ   r     r  z#index_put_impl_.<locals>.<listcomp>c                   r  rY   rY   r   r  rY   rZ   r     r   r%  
atomic_addrj   r   rB  rA  output_indexerscatter_moder   r  rb   )$ro  r  rX  r  r   r   rq   r   r_  r   r   r  r1  $are_deterministic_algorithms_enabledr4  rB   r  r   r  rc   r   r`   r9   r^   r  r  r*   Scatterr3  rg  MutationLayoutSHOULDREMOVErI   rQ   r  r   r  )rW  r  r   r-  r   r)  r:  r   r   r"  x_ndimr  r  r  r  expected_vals_sizerB  scatterr  rY   )r=  r  rZ   r+  9  s   	




r+  r|  c                   sT   t | |ddd\}}  |   fdd}tj|  |  ||dS )NFr  c                   sB   j tjkrt tj}n }t| fddS )Nc                     s    S r   rY   rY   )_unsafe_index_fnr  self_loaderrY   rZ   r    r  z8_unsafe_masked_index.<locals>.inner_fn.<locals>.<lambda>)r   rq   r   rH   r   r  )r  mask_valrI  fillr   mask_loaderrJ  re  rZ   rB    s   z&_unsafe_masked_index.<locals>.inner_fnrC  )r   r3  r6   r   rc   r   )rW  r   r  rM  rA  r   rB  rY   rL  rZ   _unsafe_masked_index  s   rO  c                   s@   t ||d}|   fddtt D }t| ||ddS )Nr   c                   s6   g | ]} | rt  | |  | d  ndqS r  r  r   r  r  rY   rZ   r     s    (z7_unsafe_masked_index_put_accumulate.<locals>.<listcomp>T)r-  )r  r   r   r   r0  )r   r   r  r   masked_valueclamped_indicesrY   rP  rZ   #_unsafe_masked_index_put_accumulate  s   
rS  c                 C  s   t |t || S r   )rH   r3  r4  r   minmaxrY   rY   rZ   r       r  c                 C  r  r   )rm  r  copy_)rW  r  r   r  r  r  output_viewrY   rY   rZ   as_strided_scatter  r  rZ  c                 K  s   t t| |||fi |S r   )scatter_rm  )r   r   r"  r  r   rY   rY   rZ   rH       rH  r  include_selfr  rz  r  r^  c             	   C  sf   t |t}t| || ttj|r| nt||r| jnd|r1t	j
| ||||||d |S d S )Nznot implr]  )r`   r9   rG   r   r   rq   r   rJ  rc   r*   ScatterFallback)r  rW  r   r"  r  r  r^  src_is_tensorrY   rY   rZ   scatter_fallback  s(   

	ra  r  c                C  sr   |dv sJ |d u r$t tjtjjjj}t|| ||||d}|d ur$|S |dkr+d}n|dkr1d}t	| ||||S )N)Nr   multiplyrb  r   sumrc  prod)
r   r  r[  rI   rQ   rR   rU   _overloadnamera  scatter_reduce_)rW  r   r"  r  r  r  fallback_resultrY   rY   rZ   r[    s   r[  c                 C  s   t t| |||S r   )scatter_add_rm  r   r   r"  r  rY   rY   rZ   scatter_add)  r  rk  c                 C  s   t | |||dS )Nrd  )rg  rj  rY   rY   rZ   ri  .  r  ri  c                 K  s   t t| ||||fi |S r   )rg  rm  )r   r   r"  r  reduction_typer   rY   rY   rZ   scatter_reduce3  s   rm  )r^  c             	     s,  |dv sJ t tj dkrdtj v sJ dttr$tttjj |||d}|r5|S tt	s<J dt
| v sFJ t  }|dkrVtdgtt	rit  dkritdgt|t	r|t | dkr|t|dg}| dkrS t    | tt	r nd  fdd	}fd
d}	dd }
|stj  fdd| |d d}tjd t|d}tj||_tj| tj  |	| ||
|d}tjd t|d}tj||_tj| |dkrtg S )N)Nrd  re  meanamaxaminr'   twozKaten.scatter_reduce_.two is not the unique overload of aten.scatter_reduce_r]  r   r   c                   sD     }t|}t| }tj| |dkrdn|  dd| < |S )Nr   r'   F)r  )r   r   r^   rH   r  )r  r  r  indirect_idx)r   r  rW  rY   rZ   r@  f  s   
z'scatter_reduce_.<locals>.output_indexerc                   s   r| S t   S r   rH   r  r   re  )rW  r  r  rY   rZ   rm   p  s   zscatter_reduce_.<locals>.fnc                 S  s   | dkrdS | d u sJ d S )Nrd  r>  rY   rb  rY   rY   rZ   backend_reduce_strw  s   z+scatter_reduce_.<locals>.backend_reduce_strc                   s   t d  S r  rs  r7  )rW  rY   rZ   r    r  z!scatter_reduce_.<locals>.<lambda>r?  rB  )r   r  rg  r   r`   r   r  ra  rq  r9   rA  r   r   r  r  r  rX  r3  r*   rD  rc   rg  rE  rI   rQ   r  r   r  )rW  r   r"  r  r  r^  rh  r  r@  rm   rt  zero_outr  rH  rY   )r   r  rW  r  r  rZ   rg  8  s   







rg  scales_xtuple[Optional[float], ...]nexactc           
        s   |    |  |   d  |  d   }dd D t|ks)J |}dd t|D t|D ]\}}|d urGd| |< q9 fddfdd}	tj|  | 	 |	g ||d	S )
Nc                 S  r  rY   r  r   rY   rY   rZ   r     r   z&upsample_nearestnd.<locals>.<listcomp>c                 S  s   g | ]\}}|| qS rY   rY   )r   rg   orY   rY   rZ   r     r  rJ  c                   s\   t | tj}  rt | t dtj} t | t |tj} t | tj} t j	| |ddS )N      ?Fr%  )
rH   r  rq   r1  r   r  rD  r   r  r  )r   r6  r   )ry  rY   rZ   scale_fn  s   z$upsample_nearestnd.<locals>.scale_fnc                   sB   |  d  }| d   }g |fddt | D S )Nc                   s   g | ]\}}} |||qS rY   rY   )r   rg   r  r   )r|  rY   rZ   r     r   z2upsample_nearestnd.<locals>.fn.<locals>.<listcomp>)r   )r  r   r  )i_sizes
inv_scalesrx  r|  r  rY   rZ   rm     s
    zupsample_nearestnd.<locals>.fnrC  )
realize_hintr3  r   r   r   r_   r6   r   rc   r   )
r   r  rv  rx  ry  batcho_sizesrg   r6  rm   rY   )ry  r}  r~  rx  r|  r  rZ   upsample_nearestnd  s(   
r  Optional[float]c                 C  s   t | ||fddS )Nr'   rx  r  r   r  r&  rY   rY   rZ   upsample_nearest1d  r  r  c                 C  s   t | ||fdddS )Nr'   Trx  ry  r  r  rY   rY   rZ   _upsample_nearest_exact1d  rW  r  scales_hscales_wc                 C  s   t | |||fddS )Nr%   r  r  r   r  r  r  rY   rY   rZ   upsample_nearest2d  s   r  c                 C  s   t | |||fdddS )Nr%   Tr  r  r  rY   rY   rZ   _upsample_nearest_exact2d  s   r  scales_dc                 C  s   t | ||||fddS )Nr   r  r  r   r  r  r  r  rY   rY   rZ   upsample_nearest3d  s   r  c                 C  s   t | ||||fdddS )Nr   Tr  r  r  rY   rY   rZ   _upsample_nearest_exact3d  s   r  c                   s   t  fdd|D S )Nc                 3  s    | ]	}t | V  qd S r   r  r   r   rY   rZ   r   	  r  z$_create_constants.<locals>.<genexpr>)r   )r   rh   rY   r   rZ   r0    s   r0  c                   s:   |   |   fdd}tj|  |  |dS )Nc                   sF   t | } t| tksJ  D ]}| d | |  | |< q| S r  )r^   r   )r  r   r  r  r  rY   rZ   r    s
   zrev.<locals>.loaderrC  )r3  r   r6   r   rc   r   )r   r  r  rY   r  rZ   rev  s   r  paddingSequence[int]r  c                 C  s  dd }| r	dS t |dkst |  dkrdS |   t| tjrBt| jtjrBt| jjtjs=t	j
rBt| jjtjrB| jjjsDdS |   t| \}}|j}|d dkrZdS |d dksl|d dksl|d dkrndS |d }|dkrxdS |d }|jd }	||	| k rdS | jjj}
|jd |jd | g}|tjj|
< t| ||j|j}t|d|	|	| d	}t|| td
 d  d7  < |S )z
    This optimization changes the semantics of padding from 'clone'
    style to 'view' style.

    Thanks to functionalization, this change can still maintain numerical
    correctness.
    c                  S  sL   t jj} | du r
dS t| j}t|dkr$|d jtjj	tj
j	fv r$dS dS )a  
        Conservatively check if padding can be fused with downstream op.
        1. if the downstream op is a sum, then there is little benefit to
           do inplace padding
        2. if the downstream op is a matmul, doing inplace padding can
           save membw.
        NTr'   r   F)rI   rQ   rR   r   rS   r   rU   r  mmr  addmm)rR   rS   rY   rY   rZ   _padding_can_be_fused-  s   
z6inplace_constant_pad_nd.<locals>._padding_can_be_fusedNr   r%   r'   r   r   )r   r  r  inductorinplace_padding)r   r   rX  r`   r*   r9   rb   re  rg  r(   can_inplace_pad_graph_inputInputBufferr   freeze_layoutr  r  r   rI   rQ   buffer_to_padded_sizer  r  r  fill_r   )r   r  r  r  r   r  rc  npadstride0rowsizebufnamepadded_size	resized_xsliced_xrY   rY   rZ   inplace_constant_pad_nd"  s\   

$


r  c              	     st  t |d dks
J tdd |D rt| S tjr$t| |}|r$|S |  }tttt	|d d d |dd d  t |t   g  D ]\}}
tjj||f qIt|d  }g t	 |d  D ]\\}}	}

|
 |
t|
| |	  qmt |t |ksJ t|   fddfdd	}|  tj|  |  ||d
S )Nr%   r   c                 s  r  r   NrY   r   r  rY   rY   rZ   r     r   z"constant_pad_nd.<locals>.<genexpr>r'   c                   s~   g }t  d  D ]\}\}}}|dkr|t|d |dkr+|t|| qttj|}t| fddS )Nr   c                     r  r   rY   rY   )r"  r  rY   rZ   r    r  z/constant_pad_nd.<locals>.mask.<locals>.<lambda>)	r   rd   range_mask_lowrange_mask_highr   r  rH   r  r  )r"  r   r  rD  rE  r  )boundsr  
mask_sizesrx  r  r7  rZ   r     s   "zconstant_pad_nd.<locals>.maskc                   sZ   t | d  }t| d   D ]\}\}}|||  qt|t| ks)J |S r   )r^   r   rd   r   )r"  r  r  rD  _high)bounds_precompr   rx  rY   rZ   	offset_fn  s
   z"constant_pad_nd.<locals>.offset_fnrC  )r   r  rm  r(   r  r  r   r^   r  r   rd   rI   rQ   r  lookup_precomputed_sizer   r  r   r   r3  r6   r   rc   )r   r  r  re   r  lhr  rD  rE  r   r  rY   )r  r  r  r   r  rx  r  rZ   r|    s:   *

r|  rg   
sympy.ExprUnion[sympy.Expr, int]c                 C  s&   t t | tjt t|tjS r   )rH   r  r  rq   r  r   r  )rg   rD  rY   rY   rZ   r    s   r  c                 C  s    t t | tjt |tjS r   )rH   r  r  rq   r  )rg   rE  rY   rY   rZ   r    s   r  c                 C  s   t t| |t| |S r   )rH   r  r  r  )rg   rE  rD  rY   rY   rZ   
range_mask  s   r  rJ  c                   sF       d   pdg   fdd}|S )Nr   c                   s|   | d   |  d   t tj fddtD }r1t| fddS t| 	fddS )Nc                   s.   g | ]}t |  | |  |  qS rY   )r  r   )r  ih	padding_hrY   rZ   r     s   . z=constant_boundary_condition.<locals>.load.<locals>.<listcomp>c                     s   t  dg S )Nr   )constant_boundary_conditionrY   )r   r  pad_fill_valueprefixr   rY   rZ   r    s    
z;constant_boundary_condition.<locals>.load.<locals>.<lambda>c                     s   g  S r   rY   rY   )r  r  r  rY   rZ   r    r  )r   r  rH   r  r   r  )r"  r   r   r  r  r  r  r  r   r  )r  r  rZ   r6    s   	z)constant_boundary_condition.<locals>.load)r   r3  )r   r  r  r  r   r6  rY   r  rZ   r    s
   r  dilationc          	      C  s&  |d u rdgt | }t| d||   || || d   || d  || }|rt| d||   || || d   d|| d   || }tjj|d ||  |  ||  dkrt|d8 }tjjd|||  |  ||   tjj|| dkrtjj|| d}||fS |}||fS )Nr'   r%   r   F)r   r"   rI   rQ   r  r  r  r  )	r   rg   kernel_sizer  r  	ceil_moder  x_outx_altrY   rY   rZ   pooling_size  s4   .
*$r  c                C  s    t | |} ttj| }|dkS )N   )rC   r   r  rb  rD  )r  n_dimwindow_sizerY   rY   rZ   %should_fallback_max_pool_with_indices
  s   
r  assert_fallbackc                C  s   |dkr	dg| }|dkrdg| }|s|}t ||}t ||}t ||}t ||}t| ts1J t||ks9J t||ksAJ t||ksIJ t||ksQJ t|  |d |d fv saJ t||d}|d urq||ksqJ |||||fS )Nr   r'   r%   r  )rC   r`   r9   r   r   r  )r   r  r  r  r  r  r  use_fallbackrY   rY   rZ   max_pool_checks  s(   





 r  c             
     sN  |    | jd   }| j d  t fddtD  \} | j}	|	tju r2dn|	jr9tdnt	|	j
}
t|t| }tsXt sXtdd D r`t| |
dn|  fdd	}tjd
| |  |	|	||d}tjd| |  tj|	||d}t|jjtr|  t|jjtr|  ||fS )Nc                   s&   g | ]}t | | d qS )r  r  r  )r  dhwr  r  r  r  rY   rZ   r   <  s    z*_max_pool_with_offsets.<locals>.<listcomp>F-infc                 s  s    | ]}|d kV  qdS r  rY   r  rY   rY   rZ   r   L  r   z)_max_pool_with_offsets.<locals>.<genexpr>r  c                   sJ   | d   }|  d    fddt D }g ||S )Nc                   4   g | ]} | |  | |   |  qS rY   rY   r   bhr  r  reduction_idxr  rY   rZ   r   T      &z<_max_pool_with_offsets.<locals>.fn_inner.<locals>.<listcomp>r   )r  r  r  r  )r  r  r  r  r  r  r  rZ   fn_innerQ  s   z(_max_pool_with_offsets.<locals>.fn_innerrV  rl  
input_noderj   	dst_dtyperh  rB  rA  reduction_rangesargmax)r  r  r   r   r   rq   r   r  r  r  rU  r^   r  r  r3  r7   r   rc   r  r`   rb   rX  )r   r  r  r  r  r  r  r  dhw_outr   	min_valuer  r  r  offsetsrY   )r  r  r  r  r  r  r  r  rZ   _max_pool_with_offsets-  sV   
	
"	

r  c           
   
   C  s   t |}t| |||||dd\}}}}}tjdd t| ||||||d\}}	|t|	tjfW  d    S 1 s:w   Y  d S )NFr  r  unroll_reductions_thresholdr  )r   r  r(   r   r  r   rq   r^  )
r   r  r  r  r  r  r  r   r  r  rY   rY   rZ   !_low_memory_max_pool_with_offsetsx  s,   	

	$r  r  r  "Sequence[Union[int, torch.SymInt]]
input_sizeincrements_to_indexxCallable[[Sequence[Union[int, torch.SymInt]], Sequence[Union[int, torch.SymInt]]], torch._inductor.virtualized.OpsValue]c                   sZ   t |  tttj fdd}tj	| 
 tj||  d}|S )Nc                   sJ   | }t |}t|} | |}t t| d  tjS r   )rH   r  r)   _flattened_index_to_ndr  _flatten_indexrq   r  )r  r  offset_sympyr  idhwr  r  r  r  offsets_loaderr  rY   rZ   offsets_to_indices  s   
z4_pool_offsets_to_indices.<locals>.offsets_to_indicesrC  )r   r3  r   r  r   r  rb  rD  r6   r   rc   rq   r  r   )r  r  r  r  r  r  rY   r  rZ   _pool_offsets_to_indices  s   		r  c                   s(   t | fdd}t| |||S )Nc                   s,   |  d    fddt D S )Nc                   r  rY   rY   r   r  rY   rZ   r     r  zX_low_memory_max_pool_offsets_to_indices.<locals>.increments_to_index.<locals>.<listcomp>r  r  r  r  r  r  r  r  rZ   r    s   zD_low_memory_max_pool_offsets_to_indices.<locals>.increments_to_index)r   r  )r  r  r  r  r  r  r  rY   r  rZ   '_low_memory_max_pool_offsets_to_indices  s
   r  c              	   C  s^   t | |||||d\}}}}}t| ||||||d\}}	t|	|| j| d  |||}
||
fS )Nr  )r  r  r  r  )r   r  r  r  r  r  r  r   re   r  r  rY   rY   rZ   _max_pool_with_indices  s   	
	r  c              	   C     t | |||||ddS Nr%   r  r  r   r  r  r  r  r  rY   rY   rZ   max_pool2d_with_indices     	r  c              	   C  r  Nr   r  r  r  rY   rY   rZ   max_pool3d_with_indices  r  r  c                   sN  dkrddg|dkrddg}st |tsJ tdks#J tdks+J tdks3J t|dks;J t| dv sEJ |   |  }t |trzt |jjtrz|jj}	tj	d tj
|	 |	 |	 d|	d}
|
  |
 }n| }|d ur|d dkp|d uo|d dk}tdd |D rt| ||||S | ^ }}
|  ^ }| |   t| }tfd	dtd d D tfd
dtd d D 		 }|dkrt| ||||S |  	
fdd}tj|  |  ||d}|r%tj|S |S )Nr   r'   r%   r  )rj   r   r   rB  c                 s  s    | ]}|d kV  qdS r  rY   r  rY   rY   rZ   r   9  r   z3max_pool2d_with_indices_backward.<locals>.<genexpr>c                 3  <    | ]}t |d   t d | d   d    dV  qdS r   r'   NrV  r   r  r  r  rY   rZ   r   F  
    *
c                 3  <    | ]}t |d   t d| d   d    d V  qdS r'   r   Nr   r   wr  rY   rZ   r   J  r  r  c                   sV  | ^ }}}t |
 | tj}|d  }|d  }t t|d  d  d tj}t t|d  d  d tj}t t|d d tj}t t|d d tj}t |t dtj}t |t dtj}t |t tj}t |t tj}d }	tD ]}
t	D ]}t 	|t |
tj}t 	|t |tj}g |t j
t |t |t dtjd ddt j
t |t |t dtjd dd}|} |}t ||}|	d u rt ||t dtj}	qt t t ||t |||}t |t 	|	||	}	qq|	d us)J |	S )Nr   r'   Fr%  r0  r  )rH   r  rq   r  r"   r3  r  r4  r   r   r  rF  r  r  r1  r  r  )r  r  r  r  
index_testphstartpwstartphendpwendgradientph_pw_phpw
grad_indexindex_actual	grad_partr   r   grad_loaderh_window_sizer   indices_sizer  r  pooled_heightpooled_widthr  w_window_sizewidthrY   rZ   rm   Y  sl     


#z,max_pool2d_with_indices_backward.<locals>.fnrC  )r`   r9   r   r   r  r  rb   r6   r*   rg  r  rc   r   decide_layoutrL  r  )fallback_max_pool2d_with_indices_backwardr3  r^   rV  r   r   r/  r  )grad_outputr   r  r  r  r  r  r  	gO_striderb   x_bufferx_strideis_channels_last_batch_heightr   r  r  rm   re   rY   r  rZ    max_pool2d_with_indices_backward  s|   	
 ;r'  r  c                   s   |    fdd}|S )Nc              
     s   |\|\ |\}}t t t   tjt |tjt t  tjt |tj}t | fddS )Nc                     s   g    S r   rY   rY   )h_start_indexr  iwr  w_start_indexr  rY   rZ   r    r
  z3pad_adaptive_loader.<locals>.load.<locals>.<lambda>)rH   r  r  r  rq   r  r  )r  
incrementsstart_indicesend_indicesh_end_indexw_end_indexr   pad_valr  )r(  r  r)  r  r*  rZ   r6    s$   z!pad_adaptive_loader.<locals>.loadr2  )r   r1  r6  rY   r0  rZ   pad_adaptive_loader  s   r2  c           
      C  sL   t j| ||d}t j|||d}t j| ||d}t j|||d}	||||	fS )N)out_diminp_dim)r   r  )
start_index	end_indexh_inw_inh_outw_outr(  r.  r*  r/  rY   rY   rZ    compute_indices_adaptive_pooling  s
   r;  c                   sD   |\}}|\}}	t | |||||	\  fdd}
|
S )Nc                   s   | ^ }}}|} |}|}|}d }	t td td D ]\}
}|||
|g||g||g}|	d u r>|}	q&||	}	q&|	S r  )r   productr   )r  r  r  r  bwr(  r.  r*  r/  r  r  r)  r  h_end_index_fnh_start_index_fnkernel_maxes
pooling_fnw_end_index_fnw_start_index_fnrY   rZ   rm     s"   $z _adaptive_pooling_fn.<locals>.fnr;  )r5  r6  rA  in_sizes	out_sizesrB  r7  r8  r9  r:  rm   rY   r>  rZ   _adaptive_pooling_fn  s   rH  c           
        sF   |\}|\}}t | ||||\  fdd}	|	S )Nc                   s   | ^ }}}|} |}|}|}d }	d }
t td td D ]>\}}||||g||g||g}t||  | | tj}|
d u rO|}
ntt||	||
}
|	d u ra|}	q(||	}	q(|
S r  )	r   r<  r   rH   r  rq   r  r  gt)r  r  r  r  r=  r(  r.  r*  r/  maxvalmaxindexr  r)  r  r"  r?  r@  rA  rB  rC  r8  rD  rY   rZ   rm     s0   $z)_adaptive_pooling_fn_with_idx.<locals>.fnrE  )
r5  r6  rA  rF  rG  rB  r7  r9  r:  rm   rY   rL  rZ   _adaptive_pooling_fn_with_idx  s   #rM  c                   s    tjkrtdttsJ t|dksJ    ^ }}}t	j
j|}t	j
j|}|\}}||krD||krDtS |dksL|dkr_g |||}t|   dS || dkrx|| dkrx|| || g}t|S t|| d |}	t|| d |}
t|||g }  }|	|
 }|dkrt|S dd }d	d
 }t|||	|
g||g||gtjd tt fdd}tj |||d}|S )Nz0'adaptive_avg_pool2d' not implemented for 'Long'r%   r   r  r'   r  c                 S     t | | |S r   r"   r"  r3  r4  rY   rY   rZ   r5  O     z)_adaptive_avg_pool2d.<locals>.start_indexc                 S     t | d | | d |S r  rO  rP  rY   rY   rZ   r6  R  rj  z'_adaptive_avg_pool2d.<locals>.end_indexr5  r6  rA  rF  rG  rB  c                   s   t  | t | S r   )rH   truedivr2  re  fn_sumones_loaderr   rY   rZ   rm   `  s   z _adaptive_avg_pool2d.<locals>.fnrC  )r   rq   r  r  r`   r9   r   r  r   rI   rQ   r  r  rm  r  rc   
avg_pool2dr<   r^   fallback_adaptive_avg_pool2drH  rH   r   r2  	ones_liker6   r   )r   r  r  r7  r8  r9  r:  o_sizer  h_kernel_maxw_kernel_maxr  r   r  r5  r6  rm   rvrY   rU  rZ   _adaptive_avg_pool2d)  sV   

	r_  c                   s    tjkrtdttsJ t|dksJ    ^ }}}t	j
j|}t	j
j|}|\}}|dks@|dkr]g |||}t|   dt|tj dfS || dkrk|| dkrktt|| d |}t|| d |}	t|||g }
  }||	 }|dkrt|S dd }d	d
 }t||||	g||g||gtjdt||||	g||g||gtjd fdd} fdd}tj |||
d}tj tj||
d}||fS )Nz,adaptive_max_pool2d not implemented for Longr%   r   r  r'   r  c                 S  rN  r   rO  rP  rY   rY   rZ   r5    rQ  z(adaptive_max_pool2d.<locals>.start_indexc                 S  rR  r  rO  rP  rY   rY   rZ   r6    rj  z&adaptive_max_pool2d.<locals>.end_indexrS  c                       | t tdS Nr  r2  r  re  )inner_func_max_valr   rY   rZ   inner_fn_max_val  r  z-adaptive_max_pool2d.<locals>.inner_fn_max_valc                   r`  ra  rb  re  )inner_func_max_idxr   rY   rZ   inner_fn_max_idx  r  z-adaptive_max_pool2d.<locals>.inner_fn_max_idxrC  )r   rq   r  r  r`   r9   r   r  r   rI   rQ   r  r  r  rc   
ValueErrorr<   r^   fallback_adaptive_max_pool2drH  rH   r3  rM  r6   r   )r   r  r  r7  r8  r9  r:  r[  r\  r]  r  r   r  r5  r6  rd  rf  r^  rirY   )re  rc  r   rZ   adaptive_max_pool2dt  sp   
		rj  c                   s<            fdd}|S )Nc           	        s   g | d   }t | }t  tj}t d tj}t t |tjt |tj}t t 	|dd|}t 
|| | t 
||  }t |tj}t ||}t t |||tS )Nr'   r   )rH   r  r   rq   r  rT  r   float64r  r  r  r  r  r   r  )	r  rg   samplei_exprdiffout_sz_exprr,  seq_ir   r   in_sz	kernel_szndimsout_szsamplessamples_loaderrY   rZ   r6    s    z)_fractional_pooling_offsets.<locals>.loadr2  )rv  rr  ru  rs  r   rt  r6  rY   rq  rZ   _fractional_pooling_offsets  s   rx  c                 C     t | |||ddS r  _fractional_max_poolr   r  r  random_samplesrY   rY   rZ   fractional_max_pool2d  r  r~  c                 C  ry  r  rz  r|  rY   rY   rZ   fractional_max_pool3d  r  r  c                   s8  |    | jd   | j d  }tjddw fddtD  |  fdd} fddt|t }|  }tj	d	| | 
 ||||d
}	tj	d| | 
 tj|||d
}
t|	jjtrt|	  t|
jjtr|
  t|
| j}|	|fW  d    S 1 sw   Y  d S )Nr  r  c              
     s    g | ]}t  |d qS ))rv  rr  ru  rs  rt  r   )rx  r  )inp_dhwr  r  r  r}  rY   rZ   r     s    	z(_fractional_max_pool.<locals>.<listcomp>c                   s$   | d   }g | | |S r   rY   )r  r  r  )r  r  r  rY   rZ   r    s   z&_fractional_max_pool.<locals>.fn_innerc                   s8   | d   |  d    fddt D S )Nc                   s&   g | ]}|  | |  qS rY   rY   r  )bdhwdhw_index_fnr  r  rY   rZ   r     s    zE_fractional_max_pool.<locals>.increments_to_index.<locals>.<listcomp>r  r  )r  r  )r  r  r  rZ   r    s
   z1_fractional_max_pool.<locals>.increments_to_indexrV  r  r  )r  r  r(   r   r   r3  r^   r   r7   r   rc   rq   r  r`   rb   rX  r  )r   r  r  r}  r  r  r  r  r   r  r  r  rY   )r  r  r  r  r  r  r}  r  rZ   r{    sP   "	


$r{  c                   s       ^ }}}tjj|}tjj|}|^ }}}	|| dkr9||	 dkr9t|| ||	 gddS t||}
t||	}dd fdd}t||
|g||g||	gt	j
d  fd	d
}tj  |t|d}|S )Nr   r'   )divisor_overridec                 S  s   t | | t|S r   )r!   r   r  rP  rY   rY   rZ   r5  ;  r  z0upsample_nearest2d_backward.<locals>.start_indexc                   s    | d ||S r  rY   rP  )r5  rY   rZ   r6  >  rk  z.upsample_nearest2d_backward.<locals>.end_indexrS  c                   s    | t S r   )r2  re  )rV  r   rY   rZ   rm   J  rQ  z'upsample_nearest2d_backward.<locals>.fnrC  )r  r   rI   rQ   r  r  rX  r<   rH  rH   r   r6   r   rc   r   r^   )r   r  r  r  r  r%  inp_hinp_wout_hout_wr\  r]  r6  rm   r^  rY   )rV  r5  r   rZ   upsample_nearest2d_backward)  s6   

	r  rY   c              
   C     t | ||||||ddS )Nr%   r  _avg_poolndr   r  r  r  r  count_include_padr  rY   rY   rZ   rX  _     
rX  c              
   C  r  )Nr   r  r  r  rY   rY   rZ   
avg_pool3du  r  r  c              	     s  
s
sdg t t 

t t| ts!J tks)J t
ks1J tks9J t|  d d fv sIJ |   |  d   }|   d  t 
fddtD  \}	}
tszt|
rt	| ddd}n| 
 d	}t|t|	 }|  ttj}|d
krdkrt}ndkrt}ntd || 
 |S 
fdd|r|r|r|n|jrd 		fdd}nfdd}n
f	dd}tj|  ||d}|S )Nr   r'   r%   c              	     s"   g | ]}t | | qS rY   r  r   )r  r  r  r  r  rY   rZ   r     s    z_avg_poolnd.<locals>.<listcomp>r  r  TFr  r   zUnknown dim: c                   s   | d   }|  d   d }t jfddtD  D ]% fddtD }|g ||}|d u r=|}qt||}q|S )Nc                   s   g | ]}t  | qS rY   r  r   )r  rY   rZ   r     r  z/_avg_poolnd.<locals>.fn_sum.<locals>.<listcomp>c                   s,   g | ]} | |  |  |  qS rY   rY   r   )r  r  r  r  rY   rZ   r     s   , )r   r<  r   rH   r   )r  r  r  totalr   r  )r   r  r  r  )r  r  rZ   rV    s    z_avg_poolnd.<locals>.fn_sumc                   s   t | t  S r   )rH   rD  r  re  )r   rV  r6  r  rY   rZ   rm     rj  z_avg_poolnd.<locals>.fnc                   s   t | t  S r   )rH   truncdivr  re  )divisorr   rV  r  rY   rZ   rm     r\  c                   s   |  d  }g }t D ]<}|| |  |  }t||  | |  } s;t|d}t|| }t|| tj}|| qt	
tj|}jr]t| |S t| |S r  )r   r   MinMaxrH   r  rq   r  rd   r   r  rD  r  rT  r  )r  r  divide_factorsrg   hstarthendfactordivide_factor)	r  r   r   rV  r  r  r  r  r  rY   rZ   rm     s    rC  )rC   r`   r9   r   r   r  r   r   r  r  r3  r^   r   r   r  rb  rD  fallback_avg_pool2dfallback_avg_pool3drg  r  r6   r   rc   )r   r  r  r  r  r  r  r   r  r9  
ceil_modeshad_paddingr  r  fallbackrm   r^  rY   )r  r  r   r  r   rV  r  r  r  r6  r  r  rZ   r    st   




 
r  c                   s  d u sdksJ dssddgt | tsJ t |ts$J tdks,J tdks4J tdks<J t| dv sFJ |   | ^ }td|\}	}
td|\}}|  d pwd pw|
pw||  ^ }	
t| }| }t	fddt
d d D t	fddt
d d D  }|d	krt| ||S fd
d  	
fdd}tj|  |||d}|S )Nr   divisor must be not zeror%   r  r'   c                 3  r  r  r   r  r  rY   rZ   r   3  r  z&avg_pool2d_backward.<locals>.<genexpr>c                 3  r  r  r   r  r  rY   rZ   r   7  r  r  c              	     sX  t d tj}t d tj}t d tj}t d tj}t d tj}t d tj}t t | ||}t t |||}	t t ||t t  tj|}
t t |	|t t tj|}t 	|t dtj}t 	|	t dtj}	t |
t  tj}
t |t tj}t t |
|t ||	}|S )z{
        This computes the scaling factor that we will divide an element
        by when `count_include_pad=False`
        r   r'   )
rH   r  rq   r  rF  rD  r4  r   r  r3  )r  r  stride_hstride_wpad_hpad_wkernel_hkernel_wr  wstartr  wendr  )heightr  r  r  r  rY   rZ   !compute_pool_size_without_paddingJ  s,   

z>avg_pool2d_backward.<locals>.compute_pool_size_without_paddingc                   sR  | ^ }}}|d  }|d  }t t|d  
d  
d tj}t t|d  
d  
d tj}t t|
d d tj}t t|
d d tj}t |t dtj}t |t dtj}t |t tj}t |t 	tj}d }tD ]}	tD ]}
t 	|t |	tj}t 	|t |
tj}d ur}nssd d  }n ||}t 
g |t jt |t |t dtjddt jt |t |t dtj	dd|}t t ||t ||}|d u rt ||t dtj}qt |t 	|||}qq|d us'J |S )Nr   r'   Fr%  r  )rH   r  r"   rq   r  r3  r  r4  r   r   rT  r  rF  r  r  r  r1  )r  r  r  r  r
  r  r  r  r  r  r  r  r  r6  partr   )r  r  r  r  r  r  r  r  r  r  r  r  rY   rZ   rm   f  sv     
	


*zavg_pool2d_backward.<locals>.fnrC  )r`   r9   r   r   r  r  r3  r^   r   rV  r   fallback_avg_pool2d_backwardr6   r   rc   )r   r   r  r  r  r  r  r  r   _h_out
ceil_mode1_w_out
ceil_mode2r  r   r  rm   r^  rY   )r  r  r  r  r  r  r  r  r  r  r  r  r  r  rZ   avg_pool2d_backward
  sb   "Ar  c                   s  d u sdksJ ds	
sg d
t | tsJ t |ts$J t	dks,J tdks4J t
dks<J t| dv sFJ |   | ^ }td	
|\}	}
td	
|\}}td	
|\}}|  t
p|
p|p||  ^ }t| }|	 }	fdd	t
dD \  }|d
krt| |	
|S 	
fdd  	
fdd}tj|  |||d}|S )Nr   r  )r   r   r   r   )r   r   r'   r%   c                 3  s6    | ] t  fd dt  d D V  qdS )c                 3  s<    | ]}t |   t d |       dV  qdS r  r   r  )rg   r  r  rY   rZ   r     r  z0avg_pool3d_backward.<locals>.<genexpr>.<genexpr>r%   N)rV  r   )r   r  )rg   rZ   r     s    
z&avg_pool3d_backward.<locals>.<genexpr>}   c              	     s  dd D \}}}dd D \}}}dd D \}	}
}dd t | ||g|||g|||gD \}}}dd t |||g|	|
|g g|||gD \}}}dd |||fD \}}}dd t |||g gD \}}}ttt||t||t||}|S )	Nc                 s      | ]
}t |tjV  qd S r   rH   r  rq   r  r  rY   rY   rZ   r     r   zQavg_pool3d_backward.<locals>.compute_pool_size_without_padding.<locals>.<genexpr>c                 s  r  r   r  r  rY   rY   rZ   r     r   c                 s  r  r   r  r   rY   rY   rZ   r     r  c                 s  s*    | ]\}}}t t |||V  qd S r   )rH   rF  rD  )r   r  r  padrY   rY   rZ   r     s
    
c              
   s  s>    | ]\}}}}t t ||t t |tj|V  qd S r   )rH   r4  r   r  rq   r  )r   r  r   r   r  rY   rY   rZ   r     s    

c                 s  &    | ]}t |t d tjV  qdS r  rH   r3  r  rq   r  )r   r  rY   rY   rZ   r     
    
c                 s  *    | ]\}}t |t |tjV  qd S r   rH   r4  r  rq   r  )r   r  r   rY   rY   rZ   r     
    
)r   rH   rD  rF  )pdr  r  stride_dr  r  pad_dr  r  kernel_dr  r  dstartr  r  dendr  r  r  )depthr  r  r  r  r  rY   rZ   r    s8   $z>avg_pool3d_backward.<locals>.compute_pool_size_without_paddingc                   sJ  | ^ }}}}dd t |||gD \}}}dd t |||gD \}}}dd t |||gD \}}	}
dd |||fD \}}}dd t ||	|
g	
gD \}}	}
d }tD ]}tD ]}tD ]}dd t |||g|||gD \}}}d ur}nssd d	  d
  }n |||}tg |tjt|t|td	tj		ddtjt|t|	td	tj	
ddtjt|t|
td	tj	dd|}t
t
t||t||	t||
}|d u rt||tdtj}qjt|t|||}qjqdq^|d us#J |S )Nc                 s  s    | ]	\}}|| V  qd S r   rY   )r   r   r  rY   rY   rZ   r     r  z2avg_pool3d_backward.<locals>.fn.<locals>.<genexpr>c                 s  s2    | ]\}}}t t|| | |tjV  qd S r   rH   r  r"   rq   r  )r   r   r   r  rY   rY   rZ   r   !  s
    
c                 s  s,    | ]\}}t t||d  tjV  qdS r  r  )r   r   r  rY   rY   rZ   r   &  s
    
c                 s  r  r  r  )r   pstartrY   rY   rZ   r   +  r  c                 s  r  r   r  )r   pend
pooled_dimrY   rY   rZ   r   /  r  c                 s  r  r   )rH   r   r  rq   r  )r   r  p_rY   rY   rZ   r   ;  r  r   r'   r%   Fr%  r  )r   r   rH   rT  r  r4  rF  r  rq   r  r  r  r  r1  r   )r  r  r  r  r  pdstartr
  r  pdendr  r  r  pd_r  r  r  r  r  r6  r  r   )r  r  d_window_sizer  r  r  r  r  r  pooled_depthr  r  r  r  rY   rZ   rm     s    	

8zavg_pool3d_backward.<locals>.fnrC  )r`   r9   r   r   r  r  r3  r  r^   r   r   fallback_avg_pool3d_backwardr6   r   rc   )r   r   r  r  r  r  r  r  r%  _d_outceil_mode_dr  ceil_mode_hr  ceil_mode_wr   r  r   r  rm   r^  rY   )r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rZ   avg_pool3d_backward  sf   &%Wr  c                 C  s   |   }t|tr|g}n|stt|}t|dkr*t|dv s(J d| g S t|}tt|D ]5}|| dk rL||  t|rHt|nd7  < d||   krZt|k sin t|dkrg|| dksiJ q4tt|t|ksxJ d|S )Nr   )rY   rT  r  zinvalid axis: r'   zreduction axis not unique)r   r`   r   r   r   r   r^   r    )r   r(  r   rg   rY   rY   rZ   _validate_reduction_axis}  s    
 :r  c          
        s   |d ur	t | |} |  tt t| |}g }g g }g ttD ]}||v r7| ||  q$| ||  q$ fdd}r`t}	D ]}t	j
j|	|< qVn|}	|   t|  |po|  |  ||	|dS )Nc                   s   t |t ks
J rt  t ksJ  fddD  t  t ks)J d gt  t |  }tt t|D ]\}}|||< q@|S )Nc                   r  rY   rY   r   r7  rY   rZ   r     r   z9_make_reduction_inner.<locals>.loader.<locals>.<listcomp>)r   r   r   r   )r"  reduction_indexr  r  varinner_loaderkeepdimskept_idxreduced_idxr   r7  rZ   r    s   
z%_make_reduction_inner.<locals>.loader)rj   r  rh  rB  rA  r  )r   r   r    r   r  r   r   rd   r^   r   r  r  r3  r   rc   r   )
r   r(  r  r   r(  
kept_sizesreduced_sizesrg   r  r  rY   r  rZ   _make_reduction_inner  s<   



r  rl  rJ   c                   s   dd d fdd}|S )NFr   c                  sB   t | ||| d}tjd| d|}t|jjtr|  |S )Nr(  r  r   r(  )rl  r  rY   )r  r7   r   r`   rb   rX  )r   r(  r  r   r   r  r(  rl  rY   rZ   rP    s   zmake_reduction.<locals>.innerr   rY   )rl  r(  rP  rY   r  rZ   make_reduction  s   r  c                C  sB   |d ur	t | |} t| |}t|  |  f|  f|  |dS )N)rj   dtypes	inner_fnsr   r(  )r   r  r   rc   r   r3  r   )r   r(  r   rY   rY   rZ   _make_scan_inner  s   

r  r   c                  s   |d ur	t | |} |   t| |}|  }|tjtjfv r$t | tj} t| ||}t	 fdd|D }t
j||  |  d}t|t| }t t|||S )Nc                 3  r   r   rY   r   r   rY   rZ   r     r   zmean.<locals>.<genexpr>r!  )r   r   r  r   rq   rG  rF  r  sum_rF   r*   r0   rc   r/   r   r^   div)r   r(  keepdimr   output_dtype
sum_resultdenomrY   r  rZ   rn    s   

rn  c           
        s   |d u rd}|    t| |}t| |dd}|r|  tt| |}t|||}t fdd|D }|r>t	|| d}t
j||  |  d}t|t|  }t||}	|s^|	fS |rb|nt||}|	|fS )Nr'   T)r  c                 3  r   r   rY   r   r  rY   rZ   r      r   z var_mean_sum_.<locals>.<genexpr>r   r!  )r   r  rn  rX  squarerF  r  rF   r   r  r*   r0   r   rc   r/   r   r^   r  r  )
r   r(  
correctionr  return_meanx_meandiffsr  r  x_varrY   r  rZ   var_mean_sum_  s&   

r  c                 C  sV   t | |}t| ||d d d}|d }t|d }t|tjo*t|tjk o*t|dkS )Nr  rA  r  r'   )	r  r  rF   r`   r   r  r   r(   r  )r   r(  r  r   rA  reduction_numelrY   rY   rZ   use_two_step_variance  s   


r  c                  s    d u rd t | ||d d d}|d}|d |d tjjd|fd|  d|\}}}	|  |  |  t| |}t	fdd	|D d
d  fdd}
t
|
|}|rj|  ||fS |fS )Nr'   r  rB  r  rh  welford_reduce)r  rl  r   c                 3  r   r   rY   r   r  rY   rZ   r   3  r   z$var_mean_welford_.<locals>.<genexpr>c                 S  s4   t | tjr| jstt| tj|S t	| |S r   )
r`   r   r   	is_numberrH   r   r  rq   r  r  r  rY   rY   rZ   get_constant_or_index_expr5  s   z5var_mean_welford_.<locals>.get_constant_or_index_exprc                   s4    }}t d}| t |||  S r  )rH   r  r3  )rb   cNzero)r  r   r  rnumelrY   rZ   r|  :  s   

z#var_mean_welford_.<locals>.scale_fnrY   )r  r(  r*   WelfordReductionr   r   rX  r   r  rF   rQ  )r   r(  r  r  r  r   r  rn  m2r   r|  r  rY   )r  r   r  r  r   rZ   var_mean_welford_  s6   




r  c                  s   |    t }t| |dd} t| ||||d}t| ||dr&tdi |ntdi |}t fdd|D }|s>|d S |S )	NFr~  )r   r(  r  r  r  )r(  r  c                 3  s    | ]
}t | d dV  qdS )Fr~  Nrb  r   rA  rY   rZ   r   X  r   z#var_mean_helper_.<locals>.<genexpr>r   rY   )r   r   r   r   r  r  r  r   )r   r(  r  r  r  compute_dtyper   r  rY   rA  rZ   var_mean_helper_H  s    	r  )r  r  c                C  ry  )NFr(  r  r  r  r  r   r(  r  r  rY   rY   rZ   var_\     
r  c                C  ry  )NTr  r   r  rY   rY   rZ   var_meanc  r  r  c                 C  st   |dk rt t| | |S |dkrtd|S |dkr| S t | |d |}t||}|d dkr8t|| }|S )Nr   r'   r%   )pow_recursiverH   r2  r  rD  )r   r  r   r  rY   rY   rZ   r  j  s   r  c                 C     t | |S r   )rH   powr   r  rY   rY   rZ   
pow_nativey  r  r	  )r   c                   sV  t trtkrt tS t trdkrt S t tr,dkr,t S tdd  fD }t|}t toQd  k oIdk n  pQ|oQdk}|ro   fdd	}t	j
    |  d
S t  tr dkr}tdS  dkrt rtS |rt  trt S t trt S t S t S )Nr{  r'   c                 s  s$    | ]}t |tjr| V  qd S r   )r`   r*   r9   r   r   rY   rY   rZ   r     r  zpow.<locals>.<genexpr>i    r   c                   s   t |   S r   )r  r   re  r   r  r  rY   rZ   rm     r  zpow.<locals>.fnrC  r%   )r`   r  r   r  sqrtrm  r%  r   r3  r6   r   rc   r   r   r   r  r   exp2fallback_pow_scalarfallback_pow_tensor_scalarfallback_pow_tensor_tensorr	  )r   r  r   is_integer_powembed_exponentrm   rY   r  rZ   r    s@   
"







r  c                 C  s   t | tr	| j}n| }t |tr|j}t |tjs3tj|  |  |	 | 
 dj}t |tjs3J t |tjrR| sR| sRt |jtjsR|  |j|_| S tjj|||d | S )NrC  unsafe_alias)r`   r9   rb   r*   re  r6   r   rc   r   r3  r   is_input_bufferis_module_buffer	NopKernelrX  rE  realize_into)changedr  r  changed_datarY   rY   rZ   r    s:   

r  c                 C  s   t | t| |S r   )r  r  )r   r  rY   rY   rZ   r    r  r  c                 C  @   | |u r| S t ||  }t||  }t||  }t| |S r   r  rc   r   r   r  r   r  )r  r  r  rY   rY   rZ   rX       
rX  c                 C  r  r   )rH   floordivr  rY   rY   rZ   r    r  r  c                 C  r  r   )rH   r  r  rY   rY   rZ   r    r  r  c                 C  s   t | ot |}t| ot|}|dkr(|rJ d|r!t| |S tt| |S |dkr@|r2J d|r9t| |S tt| |S t| |S )Nr  z5floordiv operands can not be boolean at the same timer  z5truncdiv operands can not be boolean at the same time)r   r   r  r  r  r  r  )r   r  rounding_modeboth_integerboth_booleanrY   rY   rZ   div_mode  s   
r"  c                 C  s8   t | ot |}|rt| |S ttjj}t|| |S r   )r   logical_andr4   r  rD  r  rQ  )r   r  	both_boolrm   rY   rY   rZ   rD    s
   
rD  rd  Optional[ir.Constant]c              	   C  s   t | tjrt| jS t | tjrt|  S t | tjr| S t | tjs'dS t	j
j|  }t|' ttjdd | j|   }W d   n1 sPw   Y  W d   n1 s_w   Y  t |t	j
jjsnJ t |jtjrx|jS dS )z:Try convert an arbitrary IR node into an ir.Constant valueNallow_indexingT)r`   r*   
MutableBoxget_constant_valuerb   r   r  r   Loopsrq   	_inductorops_handlerExtractConstantsHandlerrc   rI   set_ops_handlerr   objectr  rB  inner_fn_argsvirtualizedOpsValuer   )r   r  re   rY   rY   rZ   r(    s*   
 r(  c                 C  s|   t dd | |fD }|rt| |S t| }d ur3|jdkr)ttd|j}nd|j }t| |S dd }t|| |S )Nc                 s  s     | ]}t |pt|V  qd S r   )r   r   r   rY   rY   rZ   r   0  ra  zdiv_prim.<locals>.<genexpr>r   infrJ  c                  W  r  r   )rH   rT  r   rY   rY   rZ   rm   =  r  zdiv_prim.<locals>.fn)	r  r  r(  r   mathcopysignr  rD  rQ  )r   r  is_integralr  r2  rm   rY   rY   rZ   div_prim.  s   



r6  c                 C  s    t | |ftjd\} }t| |S r  )r*  r   INT_TO_FLOATr6  r  rY   rY   rZ   r  C  s   


r  c                 C  s4   t | pt| }|rdd }ndd }t|| |S )Nc                 S  r  r   )rH   modr  rY   rY   rZ   rm   U  r  zfmod.<locals>.fnc                 S  r  r   )rH   fmodr  rY   rY   rZ   rm   Z  r  )r   r   rQ  )r   r  r5  rm   rY   rY   rZ   r9  O  s
   
r9  c                C  B   t |  st|  r|d u rtj}td|d}|| |||dS )Nrd  rl  r   r   r   r   rq   r  r  r   r(  r  r   rm   rY   rY   rZ   r  `     

r  c                 C     t |  st|  r|d u rtj}t|  dkr.|dv s!J |p&|  }t| |ddS dd }t| ||d}t	j
jd
i |d|i\}|d u rRt| ||d	S |S )Nr   r   r0  Tr~  c                 S     | \}|\}t ||fS r   )rH   r   a_tupleb_tupler   r  rY   rY   rZ   
combine_fn~     zcumsum.<locals>.combine_fnr(  r   rD  r   r   rY   )r   r   r   rq   r  r   r   r   r  r*   Scanr   fallback_cumsumr   r(  r   rD  r   r  rY   rY   rZ   cumsumr      

rK  c                 C  r>  )Nr   r?  Tr~  c                 S  r@  r   )rH   rD  rA  rY   rY   rZ   rD    rE  zcumprod.<locals>.combine_fnrF  rD  rG  rY   )r   r   r   rq   r  r   r   r   r  r*   rH  r   fallback_cumprodrJ  rY   rY   rZ   cumprod  rL  rN  c                 C  sv   dd }|   }t|  dkr|dv sJ t| S t| ||d}tjjdi |d|i\}|d u r9t| |dS |S )	Nc              	   S  s\   | \}|\}t ||}t ||}||kt | B }t |t t || | |fS r   )rH   r4  r3  r  r  log1pexp)rB  rC  r   r  min_vmax_vr   rY   rY   rZ   log_add_exp_helper  s   $z(logcumsumexp.<locals>.log_add_exp_helperr   r?  rF  rD  r  rY   )	r   r   r   rm  r  r*   rH  r   fallback_logcumsumexp)r   r   rS  r   r   r  rY   rY   rZ   logcumsumexp  s   rU  c                      t |  dkr dv sJ t| t| tjdfS |  }tjd|dd}t	|  |d}|tjf|d< | 
  fd	d
f|d< tjjdi |d|i\}}|d u rXt|  dS ||fS )Nr   r?  r   r  Fr   arg_break_ties_leftrF  r  c                      t |   tjS r   rH   r  rq   r  re  r(  rY   rZ   r        zcummax.<locals>.<lambda>r  rD  r  rY   )r   r   rm  r  rq   r  r   r*   get_reduction_combine_fnr  r3  rH  r   fallback_cummaxr   r(  r   rD  r   r   r  rY   r[  rZ   cummax      
r`  c                   rV  )Nr   r?  r   argminFrW  rF  r  c                   rY  r   rZ  re  r[  rY   rZ   r    r\  zcummin.<locals>.<lambda>r  rD  r  rY   )r   r   rm  r  rq   r  r   r*   r]  r  r3  rH  r   fallback_cumminr_  rY   r[  rZ   cummin  ra  rd  c                C  r:  )Nre  rl  r   r;  r<  rY   rY   rZ   re    r=  re  c                 C  s   t | tj} td| ||dS )Nr  r(  r  )r   rq   r   r  r   r   r  rY   rY   rZ   
reduce_any  s   rg  c                 C  2   |d urt | ||dt| ||dfS t | d |dS Nre  )reduce_amaxreduce_argmaxrf  rY   rY   rZ   
reduce_max  
   rl  c                 C  rh  ri  )reduce_aminreduce_argminrf  rY   rY   rZ   
reduce_min  rm  rp  xor_sumrV  rU  r  rl  rb  
logical_or)rM  r@  stabler   
descendingc          
   	   C  s:  |d u rd}|   }|  }tt||}t|dkr't| td|tj|fS t|r/|| nd}tj	j
|ttjjsFt| |||dS t|ddtj|dd}dgt| }t|r`|||< t||}t||}tjj|| j|jf|  | f||||d\}	}|	d u rt| |||dS |d usJ |	t|tjfS )NFr   r'   rs  )r  r  r   rj   r  )rj   r  r  r   r(  rt  ru  )r   rc   r   r   rm  r  rq   r  rI   rQ   r  statically_known_ltr  int16rV  sort_fallbackr  r  r  r*   Sortr   r   r3  r   )
r   rt  r   ru  r  rj   r  r  
view_shaper   rY   rY   rZ   sort_stable  s>   



	r{  c                 C  s   t | d||dS )NFrs  )r{  )r   r   ru  rY   rY   rZ   sortF  r  r|  c                 C  s   t | |tj|dS )Nr   r   rO  )r  r   r7  )rT   r   rO  rY   rY   rZ   register_pointwise_numericK  s   r~  rT   torch._ops.OpOverloadPacketc                 C  s   t | j t| tjdS r  )rE   r  r  r   r7  r}  rY   rY   rZ    register_pointwise_numeric_ldf64T  s
   
r  r  logical_not)r@  )r   r   r(  identity)rV  pointwise_overrides_datac                 #  s    t |  t|  jd }|d u rd S  fdd}t|tjjr6| D ]}t||}| j||fV  q#d S | j||fV  d S )Nc                   s    j d u r	t| S d S r   )tritonr  r}  r  rY   rZ   make_triton_fallback  s   
z6_get_pointwise_overrides.<locals>.make_triton_fallback)	r  r   r   r`   rq   rr   r   r   r   )nsr   rT   r  olnamer  rY   r  rZ   _get_pointwise_overrides  s   
r  r}  c                   s,   | t |< t|   fdd}t| | d S )Nc                    sB    | i |}g }t | d |D ]\}}|t||dd q|S )Nr   Tr  )r   rd   r  )rh   r   resultsmut_resultsr   r  outplace_oprY   rZ   rm     s
   z$register_foreach_inplace.<locals>.fn)rO   rT  r   r   )aten_opoutplace_aten_opr  rm   rY   r  rZ   register_foreach_inplace	  s   
r  c                   s   t | d d fdd}|S )Nro  c                    s.    | i |}t || d  }t| d |S r  )r   r   r  )rh   r   r  r  rY   rZ   rm   -  s   zregister_inplace.<locals>.fn)r  )r  r  rm   rY   r  rZ   register_inplace,  s   
r  c                 C  r  r   rY   rT  rY   rY   rZ   sym_constrain_rangeV  r  r  c                 C  &   t jjjd }t|tjsJ |jjS Nr  	rI   rQ   rR   rH  r`   rq   rt  rW   ru  r   r   r  rY   rY   rZ   sym_size[  s   r  c                 C  r  r  r  r  rY   rY   rZ   
sym_stridel  s   r  c                 C  s   |   S r   )r  )r   rY   rY   rZ   	sym_numelt  r6  r  c                 C  r  r   )r   Addr   rY   rY   rZ   sym_sum}  s   
r  c                 O  r4  )NzHelpful for debuggingr   )rW  rh   r   rY   rY   rZ   foobar  r6  r  c                 C  s   |    t| S r   )rX  rm  r   rY   rY   rZ   _realize  s   r  c                 C  s   |    t| | | S r   )rX  r*   ResizeStorageBytes)variabler  rY   rY   rZ   resize_storage_bytes_  s   r  c                 C  s"   |    |   tt| |S r   )rX  r9   r   r*   SetSourceTensorKernel)rW  source_tensorrY   rY   rZ   set__source_tensor  s   r  c                 C  r  r   r  )r  r  rY   rY   rZ   
fsdp_copy_  r  r  c          	        sv  t | tsJ t |ttfsJ |d u rtj}|tjkr#td| |tjkr0t	|dks0J |tj
kr=t	|dks=J |  |  }|  }t | jtjrV| j | _t rvtjjjrvt|rhtdnt|rst|jndndtjjdrt|||dS t | gd	g}|!  tj"#||}t$||||%  fd
d}t&j'|||t|d}|S )Nzunsupported memory format: r   r   nanTr  r   r  r'   c                   sH   |  t  tj}t tj}t ||}t | fddS )Nc                     s
    gS r   rY   rY   )
flat_indexflat_loaderrY   rZ   r    s   
 z*resize.<locals>.inner_fn.<locals>.<lambda>)rH   r  rq   r  r  r  )r  flat_index_exprlimitr   r  	old_numelout_indexeruninitalized_val)r  rZ   rB    s
   zresize.<locals>.inner_fnrC  )(r`   r9   r^   r   rq   contiguous_formatpreserve_formatr  channels_lastr   channels_last_3dr  r   r&  rb   r*   r   r  rC  utilsdeterministicfill_uninitialized_memoryr   r  r   r  rV  rI   rQ   r  r  r  r  r3  r   stride_ordered_for_memory_formatr  r  r6   r   )	r   r   r  r   rj   x_flat
out_striderB  re   rY   r  rZ   resize  sT   



	r  )auto_functionalizedc                 C  sB   ddl m} ||}tj| ||i ||d dd | D S )Nr   )kernel_side_table)
kernel_idxgridtma_descriptor_metadatakernel_argsc                 S  s    i | ]\}}t |tr||qS rY   r   )r   rz  r  rY   rY   rZ   r     r  z'triton_kernel_wrap_.<locals>.<dictcomp>)*torch._higher_order_ops.triton_kernel_wrapr  get_constant_argsr*   UserDefinedTritonKernelr   )r  constant_args_idxr  r  r   r  constant_argsrY   rY   rZ   triton_kernel_wrap_  s   	

r  c                 C  sj   t dd | g|D r$d}tjjjdd  }r | d| }|tj_tj	| |||}t
ttj	|S )Nc                 s  r-  r   r.  r   rY   rY   rZ   r     r   zcond.<locals>.<genexpr>z"control flow operator: torch.cond.stack_trace Found from : 
 )r  rI   rQ   rR   rH  rI  disable_cudagraphs_reasonr*   Conditionalr   r^   mapr9   )predtrue_fnfalse_fnoperandsr   r  r  rY   rY   rZ   r     s   r   c                 C  sp   t dd || D r#d}tjjjdd  }r| d| }|tj_d
dd	}tj	| |||}t
t||S )Nc                 s  r-  r   r.  r   rY   rY   rZ   r     s
    
zwhile_loop.<locals>.<genexpr>z(control flow operator: torch.while_loop.r  r  re   r   c                 S  sJ   t | tr| S t | tjrt| S t | tjrt| S tdt|  )NzNYI unsupported output type: )r`   r9   r*   re  MultiOutputr   r  rJ  )re   rY   rY   rZ   _map_output  s   

zwhile_loop.<locals>._map_output)re   r   )r  rI   rQ   rR   rH  rI  r  r*   	WhileLoopr   r^   r  )cond_fnbody_fncarried_inputsadditional_inputsr   r  r  r  rY   rY   rZ   
while_loop  s   

r  subgraph_fnir.Subgraph
identifierc                 G  s$   t jj| g|R  }tttj|S r   )r*   InvokeSubgraphr   r^   r  r9   )r  r  r  r  rY   rY   rZ   invoke_subgraph)  s   r  )schemec          
      G  s   d }t jjjdd }|d usJ t| jjjD ]Y\}}|jdkr*|| t jj	|< q|jdkrgt j
|\}}t|| D ]}	|	  |jrQt jj|	  t jj|	  q?tjjt j|||}qt j|t jj	|< q|S )Nquant_optionsr  r  )rI   rQ   rR   rH  rI  r_   rs  nodesrT   envfetch_args_kwargs_from_envr   r   r   rX  codegen_low_precisionlow_precision_codegen_opsr   rY  invoke_quant_opsrq   r  Interpreterr  run_node)
r  r  r  r  r  rg   rW   rh   r   r   rY   rY   rZ   invoke_quant_tracer/  s"   

r  rD  r  tuple[torch.Tensor]c                   s   ddl m m} t|dkrtd fddt||D }|| |fdd}t|d dd d	}td
d |D |d< tdd |D |d< t	j
jd|dd|}|d d u r_td|S )Nr'   )InputDescriptorlower_pointwise_subgraphr   zSUnable to generate code for associative_scan op, because there are lifted argumentsc                   s    g | ]} |  | d qS )r  )r   rc   r   )r  rY   rZ   r   W  s    z$associative_scan.<locals>.<listcomp>c                   s    g t | t |R  S r   )r  r  )lhsrhs)lowered_combine_fnrY   rZ   wrapped_combine_fn]  s
   z,associative_scan.<locals>.wrapped_combine_fnrF  c                 s      | ]}|  V  qd S r   r	  r   rY   rY   rZ   r   d  r   z#associative_scan.<locals>.<genexpr>r  c                 s  r  r   r2  r   rY   rY   rZ   r   e  r   r  F)rD  can_fallback_to_atenz/Unable to generate code for associative_scan oprY   )rr  r  r  r   r  r   r   r  r   r*   rH  r   )rD  xsr  r  subgraph_inputsr  r   r  rY   )r  r  rZ   associative_scanL  s,   


r  c                 C  r  r   rY   )tokensrY   rY   rZ   _sink_tokensp  r  r  c                 O  s   t jj|g|R i |}ddlm} ||||}|d usJ tjj| }|d u r,|fS t	t j
tj|}t|ts>||fS |g|R S )Nr   )get_effect_key)r*   EffectfulKernelr   torch._higher_order_ops.effectsr  rI   rQ   effectful_opsr  rl  r  r9   r`   r   )tokenrT   rh   r   r  r  effect_typeeffectful_kernelrY   rY   rZ   with_effectsu  s   
r  )register_comm_loweringsc                 C  s   t | |dddd}|d }tjjt|}tjjdi |d|d\}}|dkrFtjj	|t
jkrFtjd| d|d	|\}}||fS ttd
 t| |dd}	ttj t| |	}
t|
|dd}|	|fS )zn
    Lowering inductor_prims.prepare_softmax_online to compute max/sum in one pass if no split is needed.
    TNr  r  online_softmax_reduce)rl  r  r'   r%   )r  
num_outputreduction_hintz
            Online softmax is disabled on the fly since Inductor decides to
            split the reduction. Cut an issue to PyTorch if this is an
            important use case and you want to speed it up with online
            softmax.
            )r  rY   )r  rI   rQ   r  simplifyrF   r*   r7   
num_splitsr  r(   r  r3   r   r  r  textwrapdedentrj  rM   r  rP  rF  r  )r   r   r   r  r  hint	num_split
max_tensor
sum_tensorro  rP  xsumrY   rY   rZ   prepare_softmax_online  s8   



r  r  )quantized_lowerings)mkldnn_lowerings)jagged_loweringsc              	   c  st    t | tjjsJ dt| }zt| t|  dV  W |r&|t| < dS t|  dS |r4|t| < w t|  w )z^
    A context manager to force fallback an op. Used in unit test
    for FallbackKernel.
    z+Only OpOverload to make the clean up easierN)	r`   rq   rr   rs   rM   rI  r  r  r(  )rT   old_handlerrY   rY   rZ   force_fallback  s   

r  )r\   r]   )rm   rn   ro   rp   )r   r   )r   r   )rh   r   r   r   r   r   r   r   r   r   ro   r   )r   r   )r   r   ro   r
  )NN)NNNFN)F)r   r9   r   rg  )r   r9   rj   r  r   )r   r   r  r'   TrT  )r]  r9   r&  r9   r'  r9   r(  r   r)  r   r*  r   r   rg  ro   r9   )r]  r9   r&  r9   r'  r9   r(  r   r)  r   r*  r   r   rg  rB  rC  ro   r9   )r]  r9   r6  r  r7  r   r)  r   r*  r   r   rg  ro   r9   )r]  r9   r6  r  r7  r   r)  r   r*  r   r   rg  rB  rC  ro   r9   )r]  r9   r6  r9   r7  r9   r)  r   r*  r   r   rg  ro   r9   )r]  r9   r6  r9   r7  r9   r)  r   r*  r   r   rg  rB  rC  ro   r9   )r   r   r'   )r  r   r  r   r  r   r  )T)rk   r  )rW   r  )NTF)rj   r  )r   r?  r  r9   r@  rA  r  r   )
rD  r   rE  r   r   r?  r  r9   r  r   )rI  r9   ro   rJ  )rI  r9   ro   rO  )rV  r9   rW  r9   rR  r   rS  r   rT  rX  rU  rY  ro   r9   )r]  r9   ri  r9   rR  r   rS  r   )r   r   r"  r   )r   NNr'   )NNN)r0  FF)r   r   )r  rz  r   r   r  rX  r^  r   )r   r   r  rX  )r   r   r^  r   )r%   F)rv  rw  rx  r   ry  r   )r&  r  )r  r  r  r  )r  r  r  r  r  r  )r   r9   r  r  r  r  ro   rY  )rg   r  rD  r  )rg   r  rE  r  )rg   r  rE  r  rD  r  )NrJ  N)
r  r9   r  r  r  r  r  r  ro   r9   )Nr   r'   F)r  )NNNN)rY   r   FTN)rl  rJ   r   )r   rd  ro   r%  )r0  F)rT   r  )r  r  r  rA  )r  r  )rD  r  r  r  r  (  
__future__r   
contextlibr  r   r   loggingr3  rb  r  r  r  collectionsr   collections.abcr   r   typingr   r   r   r	   r
   r   r   typing_extensionsr   unittest.mockr   r   rq   $torch.ao.quantization.fx._decomposedtorch.fxtorch.utils._pytreer  _pytreer  torch._dynamo.utilsr   (torch._higher_order_ops.associative_scanr   r  r   torch._prims_commonr   r   r   r   r   r   r   r   r   r   r   torch.fx.experimental.sym_noder   r   r  r   torch.utils._ordered_setr    torch.utils._sympy.functionsr!   r"   r#   r$   _dynamo.utilsr&    r(   r)   r*   r+   decompositionr,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   r0  rH   rI   r+  rJ   rK   rL   FALLBACK_ALLOW_LIST	getLoggerr  r  rM   __annotations__rN   rr   rs   r   r  tr_c10dr  r   _higher_order_opsr{  rV   rT  rO   quantized_decomposedr[   rl   ru   r   r   r   r   r  r  rX  r  bmmconvolutionconvolution_backwardr  r  r'  r  r  r  _int_mmr_  r^  rw  r  r  rG  r1  rk  	complex32	complex64r   rF  r   r   r   r   r   r   r   r   r   r	  r$  r  r  r*  rQ  rf  r   r  r  r  r  r   r  r  
device_putr  r  r  r  r  r   aliasdetachdetach_liftview_ofr  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  _unsafe_viewreshaper  slicer  r  r%  quantize_per_channelr@  dequantize_per_channelrI  quantize_per_tensorrN  dequantize_per_tensorrQ  r  rZ  r\  r{  r  r  r  r  r  r  r  r  r  r  r  r  r  cacher  r  r  r  r   r  rngprimsr  r  r  	bernoullir  r  r  	lru_cacher!  r#  r  r)  r&  r'  r-  r,  r+  randintforce_stride_orderr3  r  r5  r<  r8  lookup_seedr=  randomrC  rH  rN  rP  rf  r  r^  	NO_OPMATHro  rq  r{   r  rx  ry   r}   r  _adaptive_avg_pool3dadaptive_max_pool3d*_scaled_dot_product_attention_math_for_mpsuniformexponential_pdist_forwardsoft_margin_loss_backward_fused_rms_normxpuis_availableembedding_dense_backward_cdist_forward_cdist_backward
_trilinearsegment_reduce_segment_reduce_backwardhistc	histogrambin_ct_histogramdd_bin_edges_histogramdd_from_bin_ctsaddbmm_addmm_activation_grouped_mm
_cudnn_rnn_cudnn_rnn_backward_embedding_bag_embedding_bag_forward_only_embedding_bag_backward*_embedding_bag_per_sample_weights_backward_fused_moving_avg_obs_fq_helper*_fused_moving_avg_obs_fq_helper_functional max_pool3d_with_indices_backward_adaptive_avg_pool2d_backward_adaptive_avg_pool3d_backwardadaptive_max_pool2d_backwardadaptive_max_pool3d_backwardfractional_max_pool2d_backwardfractional_max_pool3d_backwardreplication_pad1d_backwardreplication_pad2d_backwardupsample_linear1d_backwardupsample_bicubic2d_backwardupsample_trilinear3d_backwardgrid_sampler_2d_backward_pdist_backwardr|  rt  kthvaluetopkr@  median	nanmedianr;  resize_
resize_as__linalg_detlinalg_householder_productlinalg_inv_exlinalg_ldl_factor_exlinalg_ldl_solve	linalg_lulinalg_lu_factor_exlinalg_lu_solvelinalg_matrix_exp	linalg_qr_linalg_slogdet_linalg_solve_exlinalg_solve_triangular_linalg_svd	lu_unpackormqr_linalg_check_errorslinalg_pinvatol_rtol_tensor_linalg_eightriangular_solvelinalg_cholesky_excholesky_inversecholesky_solvegeqrf_fft_r2cnonzerogcd_thnn_fused_lstm_cell_prims	rng_primsrun_and_save_rng_staterun_with_rng_stategraphsafe_run_with_rng_statemasked_scattermasked_scatter_backwardr  angle_efficientzerotensor(_sparse_coo_tensor_with_dims_and_tensors	to_sparse
_to_sparser   r  r  r  #_scaled_dot_product_flash_attention,_scaled_dot_product_flash_attention_backward#_scaled_dot_product_cudnn_attention,_scaled_dot_product_cudnn_attention_backward+_scaled_dot_product_flash_attention_for_cpu4_scaled_dot_product_flash_attention_for_cpu_backward0_scaled_dot_product_fused_attention_overrideable9_scaled_dot_product_fused_attention_overrideable_backward_flash_attention_forward_flash_attention_backward_efficient_attention_forward_efficient_attention_backwardindex_reducern  rm  r  r  r  r  r  r  scalar_tensorr  
LongTensorr  r  r  r  r  r  r  r  r  r  r  rZ  
zeros_liker  r  r  r  r  r  r  r  r  r  r!  r   r"  r'  r.  r0  r1  r4  r6  r8  r+  rO  fallback__unsafe_masked_indexrS  ,fallback__unsafe_masked_index_put_accumulater  rZ  rH  ra  r[  rk  ri  rm  rg  r  r  r  r  r  r0  r  r  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r2  r;  rH  rM  r_  rY  rj  rh  rx  r~  r  r{  r  r  r  r  r  r  r  r  r  r  r  r  rn  r  r  r  r  r  r  r  r  r	  r  Tensor_Tensorr  Scalarr  Tensor_Scalarr  r  r  rX  r  r  r  r"  rD  r(  r6  true_divider7  r9  rd  r  rK  rI  rN  rM  rU  rT  r`  r^  rd  rc  re  r  rg  rV  rl  rU  rp  rq  ro  rj  rp  rn  r  rk  rb  ro  r   rx  r{  r~  r  rsqrtrP  r  expm1relur  r  r  rF  cossinabsbitwise_andbitwise_left_shiftbitwise_not
bitwise_orbitwise_right_shiftbitwise_xorlgammaerfspecial_erfrO  tantanhr#  r  rr  logical_xorr3  r4  	clamp_min	clamp_maxnegr2  	remaindersignsignbit	_neg_viewler  r  rI  r  necoshsinhacosacoshasinasinhatan2atanatanhr4  erfcerfinvhypotlog10log2	nextaftercodegen.commonrV  r  r  r   rT   r   rO  _foreach_addListforeach_add_listforeach_add_scalar_foreach_mulforeach_mul_listforeach_mul_scalar_foreach_sub_foreach_neg_foreach_abs_foreach_powScalarAndTensor_foreach_divforeach_div_listforeach_div_scalar_foreach_sqrt_foreach_rsqrt_foreach_maximum_foreach_minimum_foreach_clamp_min_foreach_clamp_max_foreach_reciprocal_foreach_sign_foreach_copyr  _foreach_add__foreach_mul__foreach_div_r  add_bitwise_and_bitwise_left_shift_bitwise_not_bitwise_or_bitwise_right_shift_bitwise_xor_mul_div_Tensor_modelogical_and_logical_not_logical_or_logical_xor_sub_relu_sigmoid___and__
__lshift____or__
__rshift____xor____iand____ilshift____ior____irshift____ixor__r  r  r   r  r  r   methodfuncr  r  _inductor_testrX  r  r  r  set_source_Tensorr  fsdpr  r  *torch._higher_order_ops.auto_functionalizer  r  higher_orderr   r  r  invoke_quantr  r  r  r  comm_loweringr  r  r  r	  register_quantized_opsregister_woq_mm_opsr
  register_onednn_fusion_opsr  register_jagged_opscontextmanagerr  rY   rY   rY   rZ   <module>   s$  $4@8




	H95V:
,
-


#












4
E22$$-/|6



		
(2&




			a:		 


C
8



.
	


$!#I%
~



!t/


_7K"
 
)5


E


Q

B-


z
	 &

	 H1
+


/
#
	 











'	














@

#6
