o
     Ǝi                 
   @  s  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Zd dlZd dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZ d dlmZmZ d dlmZ d dlZd dlm  m Z! d dlm"Z"m#Z#m$Z$m%Z% d d	l&m'Z'm(Z( d d
l)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZBmCZC d dlDmEZE d dlFmGZG d dlHmIZImJZJ d dlKmLZLmMZMmNZNmOZOmPZPmQZQ d dlRmSZS d dlTmUZU ddlVmWZWmXZXmYZY er4d dlZm[Z[m\Z\m]Z]m^Z^ d dlm_Z_ d dl`maZa d d lbmcZc d d!ldmeZemfZf egehZiejjkehd"Zlz	ejjkehd#ZmW n$ enym Zo zd$epeov raegehd% ZmneoW Y dZo[ondZo[oww eqZrej jsZted&ZuejvjwjxZxdZyd azG d'd( d(Z{eG d)d* d*e|Z}eG d+d, d,e|Z~eG d-d. d.e|ZeG d/d0 d0e|ZeG d1d2 d2e|ZeG d3d4 d4e|ZG d5d6 d6e	jZe Zdd:d;Zejdd=d>ZejddBdCZddHdIZddMdNZddQdRZejddVdWZejddYdZZdd`daZddbdcZG ddde deZejddidjZejddkdlZddmdnZG dodp dpZG dqdr drZG dsdt dte%ZeeBdudvf ZeEeG dwdx dxZddydzZeEeG d{d| d|ZG d}d~ d~ZeEeddG dd dZeEeddG dd dZeEeddG dd dZereeef ZeEeddG dd deZeEeddG dd dZG dd@ d@eJZeZdddZdddZdddZdddZG dd de@ZdddZdddZdddZejwjjjeejwjxjjdd ejwjxjjdd ejwjxjjdd iZeejwjxjjejwjxjjejwjxjjejwjjjZd dlmZmZmZmZmZmZmZmZ dddZejdddZdddZdddZdS )    )annotationsN)defaultdict)	dataclass)AnyCallablecastLiteralOptionalTYPE_CHECKINGTypeVarUnion)Self	TypeGuard)ReferenceType)SymBoolSymFloatSymIntTensor)is_functorch_wrapped_tensoris_legacy_batchedtensor)FakeScriptObject)MissingOpProfile)dtrace_structured)suggest_memory_format)	assert_eqassert_metadata_eqis_sparse_anyis_sparse_compressedMetaConverter)render_call)immutable_dict)normalize_function)StorageWeakRef)TorchFunctionMode)IntLikeTypepy_sym_types)dataclass_slots)no_dispatch)is_traceable_wrapper_subclassTorchDispatchMode)KeyPathkeystrPyTreetree_map	tree_map_TreeSpec)count)CapturedTraceback   )_CacheKeyState_PySymInputStub_SymIntOutputStub)	GeneratorIterableMappingSequence)TracebackType)Source)
OpOverload)ShapeEnvSymbolicContexthierarchical_compilenot_implementedz 'not_implemented' not registeredz.not_implementedTc                   @  s    e Zd ZdddZdddZdS )	IncrementRecursionCountreturnNonec                 C  s   t d7 a d S Nr2   RECURSION_COUNTself rJ   Y/home/jeff/fluffinator/venv/lib/python3.10/site-packages/torch/_subclasses/fake_tensor.py__init___      z IncrementRecursionCount.__init__c                 C  s   t d8 a d S rE   rF   rH   rJ   rJ   rK   __del__c   rM   zIncrementRecursionCount.__del__NrC   rD   )__name__
__module____qualname__rL   rN   rJ   rJ   rJ   rK   rB   ^   s    
rB   c                   @     e Zd ZU ded< dS )UnsupportedFakeTensorExceptionstrreasonNrP   rQ   rR   __annotations__rJ   rJ   rJ   rK   rT   h      
 rT   c                   @  rS   )DynamicOutputShapeExceptionr<   funcNrW   rJ   rJ   rJ   rK   rZ   m   rY   rZ   c                   @  rS   )DataDependentOutputExceptionr<   r[   NrW   rJ   rJ   rJ   rK   r\   r   rY   r\   c                   @  rS   )UnsupportedOperatorExceptionr<   r[   NrW   rJ   rJ   rJ   rK   r]   w   rY   r]   c                   @  rS   )$UnsupportedMutationAliasingExceptionrU   rV   NrW   rJ   rJ   rJ   rK   r^   |   rY   r^   c                   @  rS   )MetadataMismatchErrorrU   rV   NrW   rJ   rJ   rJ   rK   r_      rY   r_   c                   @  s    e Zd ZU ded< dddZdS )	FakeTensorTLSOptional[bool]allow_non_fake_inputs_overriderC   rD   c                 C  s
   d | _ d S N)rb   rH   rJ   rJ   rK   rL         
zFakeTensorTLS.__init__NrO   )rP   rQ   rR   rX   rL   rJ   rJ   rJ   rK   r`      s   
 r`   itemsrC   dict[T, Literal[True]]c                  G  s   t | dS NT)dictfromkeys)re   rJ   rJ   rK   ordered_set      rj   2Generator[Optional[TorchDispatchMode], None, None]c               	   c  sR    t jt jjj} z| V  W | d urt j|  d S d S | d ur(t j|  w w rc   )torch_C_unset_dispatch_mode_TorchDispatchModeKeyFAKE_set_dispatch_mode)oldrJ   rJ   rK   unset_fake_temporarily   s   rt   	fake_modeFakeTensorModeGenerator[None, None, None]c                 c  s*    | j }zd| _ d V  W || _ d S || _ w )NF)cache_enabled)ru   	old_valuerJ   rJ   rK   disable_fake_tensor_cache   s   rz   subclassr   out list[Union[Tensor, int, SymInt]]c                  sV   | g}|r)|   t s|  q  \}}| fddt|D  |s|S )Nc                 3  s    | ]}t  |V  qd S rc   getattr).0keycurrrJ   rK   	<genexpr>       z$get_plain_tensors.<locals>.<genexpr>)popr(   append__tensor_flatten__extendreversed)r{   r|   todo
inner_keys_rJ   r   rK   get_plain_tensors   s   
	r   xobjectTypeGuard[Tensor]c           	        s   ddl m} t trdS t r?t  \}} fdd|D }tdd |D }tdd |D }||ks=J d	|S t |rIt	 j
S t trdt rdtj }tjj |}t	|S t trxt rxtjj }t	|S d
S )Nr   FunctionalTensorTc                   s   g | ]}t  |qS rJ   r~   )r   attrr   rJ   rK   
<listcomp>   s    zis_fake.<locals>.<listcomp>c                 s      | ]}t |V  qd S rc   is_faker   r   rJ   rJ   rK   r          zis_fake.<locals>.<genexpr>c                 s  r   rc   r   r   rJ   rJ   rK   r      r   z got mixed fake and real tensors!F)#torch._subclasses.functional_tensorr   
isinstance
FakeTensorr(   typer   allanyr   elemr   rm   _is_functional_tensorrn   $_functionalization_reapply_views_tls
_functorch_unwrap_functional_tensorr   get_unwrapped)	r   r   attrsr   flattened_tensorsall_fakeany_fakereapply_views	unwrappedrJ   r   rK   r      s(   



r   tOptional[FakeTensorMode]c                   s   ddl m} ttrjS tr4 \}}fdd|D }|d  t fdd|D s2J  S t|r>tj	S tt
rYtrYtj }tjj|}t|S tt
rmtrmtjj}t|S d S )Nr   r   c                   s   g | ]	}t t |qS rJ   )maybe_get_fake_moder   )r   t_namer   rJ   rK   r      s    z'maybe_get_fake_mode.<locals>.<listcomp>c                 3  s    | ]} |u V  qd S rc   rJ   r   )mrJ   rK   r      r   z&maybe_get_fake_mode.<locals>.<genexpr>)r   r   r   r   ru   r(   r   r   r   r   r   rm   r   rn   r   r   r   r   r   )r   r   inner_tensor_namesr   modesr   r   rJ   )r   r   rK   r      s*   




r   r[   r<   torch._C._SchemaInfoc                 C  s   t j| jS rc   )rm   rn   _SchemaInfo_schemar[   rJ   rJ   rK   get_schema_info   s   r   boolc                 C  s6   ddl m} tjj}||  jdo||  jt|v S )Nr   decomposition_tableztorch._decomp)	torch._decompr   rm   _decompdecompositionsrQ   
startswithrP   dir)r[   r   r   rJ   rJ   rK   torch_decomp_decompositions   s   
r   tytype[T]treer,   list[T]c                   s   t |} fdd|D S )Nc                   s   g | ]	}t | r|qS rJ   )r   r   r   r   rJ   rK   r         z%tree_flatten_only.<locals>.<listcomp>)pytreetree_leaves)r   r   	flat_valsrJ   r   rK   tree_flatten_only  s   
r   c                 C  s@   t | tu o| jtjko| jp| jpt| pt| pt	|  S rc   )
r   r   layoutrm   strided	is_sparse	is_nestedr   r   r   r   rJ   rJ   rK   _is_plain_tensor  s   
r   c                   @  s   e Zd ZU ed7ddZded< ded< d	ed
< dddd8ddZd9ddZd:ddZd;ddZ	d<ddZ
		 d=d d d!d"d>d-d.Z	 	 d?d@d5d6Zd S )AFakeTensorConverterrC   weakref.WeakValueDictionaryc                 C  s   | j jS rc   )meta_convertertensor_memorH   rJ   rJ   rK   r     s   zFakeTensorConverter.tensor_memor   r   z)dict[StorageWeakRef, list[ReferenceType]]constant_storage_mappingr   exportF	copy_datar   r   rD   c                C  s   t |d| _|| _i | _d S )N)r   )r   r   r   r   )rI   r   r   rJ   rJ   rK   rL   '  s   
zFakeTensorConverter.__init__fake_tensorr   c                 C  sT   t |tr
|jd usJ t|j }|| jvrg | j|< | j| t| d S rc   )	r   r   constantr"   _typed_storager   r   weakrefref)rI   r   weak_strJ   rJ   rK   add_constant_storage_mapping.  s
   

z0FakeTensorConverter.add_constant_storage_mappingtensorr   c                 C  s`   t |trJ t| }|| jvrd S | j| D ]}| }|d ur)|  d |_q| j|= d S rc   )r   r   r"   r   r   _fix_weakrefr   )rI   r   r   weak_tensor_reftenrJ   rJ   rK   invalidate_constant_aliases<  s   
z/FakeTensorConverter.invalidate_constant_aliasesr   Optional[FakeTensor]c                 C  s(   | j jj|}|d u rd S | j|S rc   )r   	describerlookup_tensorgetr   )rI   r   tidrJ   rJ   rK   	_get_memoK  s   zFakeTensorConverter._get_memovc                 C  s   | j j|}|| j j|< d S rc   )r   r   get_tensor_idr   )rI   r   r   r   rJ   rJ   rK   set_tensor_memoQ  s   z#FakeTensorConverter.set_tensor_memoNT)sourcesymbolic_contexttraceru   rv   make_constant	shape_envOptional[ShapeEnv]r   Optional[Source]r   Optional[SymbolicContext]r   c                  s0  |s(|s(|r(t jj  }r(||jv r(|j| }ddlm}	 t||	s%J |j}| 	|}
|
d ur3|
S |j
r:tdt|t jju rF|rFJ |rJ|nd  d fd
d}| j||||||d}|tu rgtdddlm} d }| jst|r| dkr|jjdkr|jt jt jt jt jt jfv r|d urt||s|d urddlm}m} ddlm} t   |! }W d    n1 sw   Y  t"#|st"$|st||r|j%}n||}|j&|||j'|d}|jt jkr|j(|||d|_)n|jt jkr|j*|||d|_)|r| +| |S )Nr   )StatefulSymbolicContextzquantized nyi in meta tensorsmake_meta_tCallable[[], object]deviceUnion[torch.device, str]rC   r   c                   s<   t   t|  | dW  d    S 1 sw   Y  d S )Nr   )r'   r   )r   r   r   ru   rJ   rK   mk_fake_tensor  s   
$z<FakeTensorConverter.from_real_tensor.<locals>.mk_fake_tensor)r   callbackr   r   r   zmeta converter nyi)RandomValueSourcecpu)CallMethodItemSourceFloatTensorSource)
DimDynamic)r   dynamic_dimr   )hintr   )r   r   r   r   rC   r   ),rm   _guardsTracingContexttry_gettensor_to_context%torch.fx.experimental.symbolic_shapesr   r   tensor_sourcer   is_quantizedrT   r   nn	Parameterr   NotImplementedtorch._dynamo.sourcer  r   r   dimr   dtypeint64int32int16int8float64r  r  r  r'   itemmathisnanisinfbasecreate_unspecified_symbolDYNAMICcreate_symintnode	item_memocreate_symfloatnoder   )rI   ru   r   r   r   r   r   r   tracing_contextr   
maybe_memor   r|   r  valuer  r  r  item_sourcesymbolrJ   r   rK   from_real_tensor[  s   








z$FakeTensorConverter.from_real_tensorr   torch.devicepytypeOptional[type[torch.Tensor]]dispatch_keysOptional[torch.DispatchKeySet]c                 C  sX   |j jdksJ d|j j d| |}|d ur|S t|||||d}| || |S )Nmetaz$tensor's device must be `meta`, got z instead)r,  r.  )r   r   r   r   r   )rI   ru   r   r   r,  r.  r&  r|   rJ   rJ   rK   from_meta_and_device  s   

z(FakeTensorConverter.from_meta_and_device)rC   r   )r   r   r   r   rC   rD   )r   r   rC   rD   )r   r   rC   rD   )r   r   rC   r   )r   r   r   r   rC   rD   )FN)ru   rv   r   r   r   r   r   r   r   r   r   r   r   r   rC   r   )NN)ru   rv   r   r   r   r+  r,  r-  r.  r/  rC   r   )rP   rQ   rR   propertyr   rX   rL   r   r   r   r   r*  r1  rJ   rJ   rJ   rK   r     s,   
 



 r   r   r+  rD   c                 C  sD   t j s
t j r t jjd u rt jd| dnt jd| d d S d S )Nr2   r   )rm   cudais_availablexpuversionhipemptyzerosr3  rJ   rJ   rK   init_gpu_context  s    r;  c              
   c  s    | j }tj }||ksJ | d| tj < d| _ tj  tjd zd V  W || _ n|| _ w W d    n1 sBw   Y  W d    d S W d    d S 1 sZw   Y  d S )N, T)in_kernel_invocationrm   rn   _meta_in_tls_dispatch_include_DisableTorchDispatch_PreserveDispatchKeyGuard!_set_meta_in_tls_dispatch_include)ru   prev_in_kernelmeta_in_tlsrJ   rJ   rK   in_kernel_invocation_manager  s   
"rD  c                 C  s$   t j|  dd dd S )Nz::.r   )rm   rn    _should_allow_numbers_as_tensorsnamesplitr   rJ   rJ   rK   should_allow_numbers_as_tensors$  s   rJ  c                   @  s   e Zd ZejdddkZdS )FakeTensorConfigTORCH_FAKE_TENSOR_DEBUG01N)rP   rQ   rR   osenvironr   debugrJ   rJ   rJ   rK   rK  *  s    rK  c                   @  sn   e Zd ZU ded< ded< ddd!d
dZd"ddZd#ddZd#ddZd#ddZ	d$d%ddZ	d&dd Z
dS )'SymNumberMemoDescriptorrU   _namer   _is_nested_intFis_nested_intrV  rC   rD   c                C  
   || _ d S rc   )rT  )rI   rV  rJ   rJ   rK   rL   C  rd   z SymNumberMemoDescriptor.__init__ownerrH  c                 C  s
   || _ d S rc   rS  )rI   rX  rH  rJ   rJ   rK   __set_name__F  rd   z$SymNumberMemoDescriptor.__set_name__objr   c                 C  s   d| j  S )Nr   rY  rI   r[  rJ   rJ   rK   _memoI  rk   zSymNumberMemoDescriptor._memoc                 C     d| j  dS )Nr   _vcrY  r\  rJ   rJ   rK   _memo_vcL     z SymNumberMemoDescriptor._memo_vcc                 C  r^  )Nr   _epochrY  r\  rJ   rJ   rK   _memo_epochS  ra  z#SymNumberMemoDescriptor._memo_epochNobjtypeOptional[type[FakeTensor]]-Optional[Union[torch.SymInt, torch.SymFloat]]c                 C  s   t || | }d u rd S t|tjr|jjd ur|S | js*t || ||j	ks9| jsDt || 
||jjkrDt|| |d  d S |S rc   )r   r]  r   rm   r   noder  rT  r`  _versionrc  ru   epochsetattr)rI   r[  rd  rrJ   rJ   rK   __get__V  s   zSymNumberMemoDescriptor.__get__r'  c                 C  s   |d u r!t || |d  t || |d  t || |d  d S | r(| jrKt || || | js>t || ||j t || ||jj d S d S rc   )	rj  r]  r`  rc  is_inferencerT  rh  ru   ri  )rI   r[  r'  rJ   rJ   rK   __set__l  s   zSymNumberMemoDescriptor.__set__)rV  r   rC   rD   )rX  rU   rH  rU   rC   rD   )r[  r   rC   rU   rc   )r[  r   rd  re  rC   rf  )r[  r   r'  rf  rC   rD   )rP   rQ   rR   rX   rL   rZ  r]  r`  rc  rl  rn  rJ   rJ   rJ   rK   rR  9  s   
 



rR  c                      s$  e Zd ZU dZded< ded< ded< ded< e Ze Ze Ze Z	ed	d
Z
ded< ded< ejjjZed?ddZejd@ddZedAddZejdBddZe				dCdDddZdE fd#d$ZedFd&d'Zeed(e fdGd/d0ZedHd3d4Zd5d6dId:d;ZdJd=d>Z  ZS )Kr   al  
    Meta tensors give you the ability to run PyTorch code without having to
    actually do computation through tensors allocated on a `meta` device.
    Because the device is `meta`, meta tensors do not model device propagation.
    FakeTensor extends MetaTensors to also carry an additional `fake_device`
    which tracks devices that would have been used.
    r+  fake_devicerv   ru   Optional[Tensor]r   real_tensorTrU  Optional[type[Tensor]]r,  r/  r.  rC   c                 C  s   | j jr	tdS | jS Nr0  )ru   r=  rm   r   ro  rH   rJ   rJ   rK   r     s   
zFakeTensor.devicer   rD   c                 C     t rc   NotImplementedErrorrI   r   rJ   rJ   rK   r        	list[str]c                 C  s   t d)Nz+torch.compile doesn't support named tensors)rT   rH   rJ   rJ   rK   names  s   zFakeTensor.namesc                 C  rt  rc   ru  rw  rJ   rJ   rK   rz    rx  Nr   r   r   r   c           	      C  sf  t j| ||jd|d}|jstj| ntj| |jj	dks'J |jj	t
|tjr/|nt|}|js>|j	dks>J |j	dv rGt| |j	ddddtj fv r|jd u r|j	dkrxtt|j	 rxt|j	 d	tt|j	  }n	t|j	 d
}||_||_||_||_||_t
|trJ ||_d |_d |_d |_d |_d |_tjrt ! |_"|S )NT)dispatch_devicedevice_for_backend_keysr0  )r4  r6  r4  hpur6  mps:z:0)#r   _make_subclassrequires_grad_allow_unsafe_data_ptr_accessrm   rn   _set_throw_on_mutable_data_ptr(_set_warn_deprecated_on_mutable_data_ptrr   r   r   
allow_metar;  _get_privateuse1_backend_nameindexr   is_initializedcurrent_devicero  ru   r   r,  r.  r   rq  nonzero_memor#  unique_memounique_consecutive_memonested_int_memorK  rQ  r1   extract_debug_trace)	clsru   r   r   r   rq  r,  r.  rI   rJ   rJ   rK   __new__  sP   


zFakeTensor.__new__argsr   kwargsc                   s   t    d S rc   )superrL   )rI   r  r  	__class__rJ   rK   rL     ra  zFakeTensor.__init__r   c                 C  s
   | | S rc   )from_tensor)r   ru   rJ   rJ   rK   r    s   
zFakeTensor.from_tensorrJ   r[   r<   typesSequence[type]Sequence[object]Mapping[str, object]c           
      C  s(  |t jjjjkr't|dkrt|d tsJ |d jj	r"t dS |d j
S t| }r2||S dd |D }|rCtd| tS d }tj|i |D ]}t|trY|j} nqM|d us`J t jt jjj}	|	rttd||	 tS |j	ryJ | ||i |W  d    S 1 sw   Y  d S )Nr2   r   r0  c                 S  s"   g | ]}t |ts|tur|qS rJ   )
issubclassr   r   r   r   rJ   rJ   rK   r   B  s    
z1FakeTensor.__torch_dispatch__.<locals>.<listcomp>z(FakeTensor unrecognized subclass(es): %sz(FakeTensor mode already active: %s in %s)rm   opsprimr   defaultlenr   r   ru   r=  ro  _DISPATCH_META_HANDLERSr   not_implemented_logrQ  r  r   arg_tree_leavesrn   _get_dispatch_moderp   rq   )
r  r[   r  r  r  handlerunrecognized_typesru   argmaybe_cur_fake_moderJ   rJ   rK   __torch_dispatch__  sH   


	
$zFakeTensor.__torch_dispatch__	flat_argstuple[torch.device, bool]c                   s   d d}d t tjjt tjj ddddfd
dd fdd}|D ]}|| q-trCd u rCd}tdd usNJ d |fS )NFr   r+  rC   r   c                 S  s
   | j dkS )Nr  )r   r3  rJ   rJ   rK   check_cpu_device  rd   z8FakeTensor._find_common_device.<locals>.check_cpu_devicer   r   c                   s    | j o
|  dkS Nr   )r   r  r   )r  rJ   rK   cpu_zero_dim     z4FakeTensor._find_common_device.<locals>.cpu_zero_dimr   rD   c                   s   t | tsd S d u r| j| d S | }| jkr#r!|d S  v }|r-|s-d S r8|s8| j|d S v rHtt| jfrHd S tjjj}|d urm|j	v }|| jj	v }|sg|rg| j|d S |rm|smd S t
d d d| j )Nz,Unhandled FakeTensor Device Propagation for z, found two different devices r<  )r   r   r   r   maprm   r   configfake_tensor_prefer_device_typer   RuntimeError)r   t_is_cpu_zero_dim&is_bypass_zero_dim_cpu_tensor_check_opprefer_device_typecommon_has_preferredt_has_preferred$bypass_zero_dim_cpu_tensor_check_opsr  common_devicer  r[   is_cpu_zero_dimmixed_device_fnsrJ   rK   merge_devices  sF   



z5FakeTensor._find_common_device.<locals>.merge_devicesTr  z!Could not find common device for )r   r+  rC   r   r   r   rC   r   )r   r   rC   rD   )rj   aten_foreach_copyr  	nextafterrJ  rm   r   )r[   r  has_scalar_only_inputsr  r  rJ   r  rK   _find_common_devicej  s&   	
=

zFakeTensor._find_common_devicer2   )coeffr  Union[int, torch.SymInt]torch.SymIntc                C  s6   | j d u r| jjd d| _ t| j tjsJ | j | S )Nnt_tensor_id)r  ru   create_symbolic_nested_intr   rm   r   )rI   r  rJ   rJ   rK   get_nested_int  s   

zFakeTensor.get_nested_intr   c                 C  s<   |   dkr
|  S |   dkrdd | D S dd | D S )Nr   r2   c                 S     g | ]}|  qS rJ   )r  r   rJ   rJ   rK   r         z%FakeTensor.tolist.<locals>.<listcomp>c                 S  r  rJ   )tolistr   rJ   rJ   rK   r     r  )r  r  rH   rJ   rJ   rK   r    s
   zFakeTensor.tolist)rC   r+  )r   r+  rC   rD   )rC   ry  )r   ry  rC   rD   )NNNN)ru   rv   r   r   r   r+  r   rp  rq  rp  r,  rr  r.  r/  rC   r   )r  r   r  r   rC   rD   )r   r   ru   rv   rC   r   
r[   r<   r  r  r  r  r  r  rC   r   )r[   r<   r  r  rC   r  )r  r  rC   r  )rC   r   ) rP   rQ   rR   __doc__rX   rR  r  r#  r  r  r  rm   rn   rp   rq   	_mode_keyr2  r   setterrz  staticmethodr  rL   r  classmethodr0   r    r  r  r  r  __classcell__rJ   rJ   r  rK   r   z  sR   
 

SIkr   r4   r5   c                   @  s   e Zd ZU dZded< ded< ded< ded< d	ed
< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< ded< d(d%d&Zd'S ))TensorMetadatazK
    The Tensor metadata relevant to hashing FakeTensors when caching.
    ztorch.dtyper  ztuple[_MetadataIntLike, ...]shapestrider+  r   ztorch.layoutr   zOptional[torch.memory_format]memory_format_MetadataIntLikestorage_offsetzOptional[_MetadataIntLike]storage_bytesr   r  r  is_conjis_negrm  r   ra   is_coalescedOptional[int]	dense_dim
sparse_dimresultlist[object]moderv   stater3   rC   rD   c                 C  sr   t | D ]1}t| |j}t|tttjfr%g }|	|||| |
  qt|tr1||| q|| qd S rc   )dataclassesfieldsr   rH  r   tuplelistrm   Size_prep_args_for_hashclearr   convert_sym_intr   )rI   r  r  r  fieldr'  id_hashed_objectsrJ   rJ   rK   _flatten_into  s   

zTensorMetadata._flatten_intoN)r  r  r  rv   r  r3   rC   rD   )rP   rQ   rR   r  rX   r  rJ   rJ   rJ   rK   r    s(   
 r  c                 C  s   t | }| jst| s| j|dsd}|  }t| j| j| jt	j
kr&|  nd| j| j||t| s7|   nd| j| j|  |  |  | j| jrN|  ndt| rW|  ndt| ra|  S dS )z1
    Extract the TensorMetadata of a tensor.
    )r  NrJ   )r   _has_symbolic_sizes_stridesr   is_contiguousr  r  r  r  r   rm   r   r  r   untyped_storagenbytesr  r  r  r  rm  r   r  r  r  )r   r  r  rJ   rJ   rK   extract_tensor_metadata  s<   
r  c                   @  sJ   e Zd ZU dZded< ded< dd	d
ZdddZdddZdddZdS )_DispatchCacheKeyz0
    Key for the FakeTensor dispatch cache.
    tuple[object, ...]r   int	hashvaluetuprC   rD   c                 C  s   || _ t|| _d S rc   )r   hashr  )rI   r  rJ   rJ   rK   rL   K  s   z_DispatchCacheKey.__init__otherr   r   c                 C  s   t |to
| j|jkS rc   )r   r  r   )rI   r  rJ   rJ   rK   __eq__O  r  z_DispatchCacheKey.__eq__c                 C  s   | j S rc   )r  rH   rJ   rJ   rK   __hash__R  s   z_DispatchCacheKey.__hash__c                 C  s"   | j D ]}t|tr|  qd S rc   )r   r   r4   strip_shape_env)rI   r   rJ   rJ   rK   r  U  s
   

z!_DispatchCacheKey.strip_shape_envN)r  r  rC   rD   )r  r   rC   r   )rC   r  rO   )	rP   rQ   rR   r  rX   rL   r  r   r  rJ   rJ   rJ   rK   r  A  s   
 


r  c                   @  s   e Zd ZdS )SingletonConstantN)rP   rQ   rR   rJ   rJ   rJ   rK   r  _  s    r  T)frozenc                   @  s6   e Zd ZU dZded< ded< ded< eZded< d	S )
_DispatchCacheEntryOutputInfoa  
    Entry type for the FakeTensor dispatch cache for an output. Accounts for three
    possibilities:
    1) The op is inplace, and a hit means we need to alias the argument at a
       given index.
    2) We need to synthesize a new FakeTensor given tensor metadata. For view
       ops, we further capture the index of the arg to alias.
    3) if the tensor related fields are None, then it is a constant value (e.g.
    None or integer)
    r  inplace_idxzOptional[TensorMetadata]metadataview_idxzOptional[Any]constant_valueN)rP   rQ   rR   r  rX   r  r  rJ   rJ   rJ   rK   r  c  s   
 r  c                   @  s&   e Zd ZU dZded< dZded< dS )_DispatchCacheValidEntryz
    Entry type for the FakeTensor dispatch cache. It supports two types of outputs
    1) tensor
    2) tuple of tensors

    is_output_tuple flag helps in differentiating the return type
    z$tuple[_DispatchCacheEntryOutputInfo]output_infosFr   is_output_tupleN)rP   rQ   rR   r  rX   r  rJ   rJ   rJ   rK   r	  w  s   
 r	  c                   @     e Zd ZU dZded< dS )_DispatchCacheBypassEntryz0
    Entry type for a negative cache entry.
    rU   rV   NrP   rQ   rR   r  rX   rJ   rJ   rJ   rK   r       
 r  c                   @  r  )_BypassDispatchCachez<
    Signals cases that should skip FakeTensor caching.
    rU   rV   Nr  rJ   rJ   rJ   rK   r    r  r  c                   @  s2   e Zd ZU dZded< ded< ded< ded< dS )	DispatchCacheInfozG
    Information about the state of the FakeTensor dispatch cache.
    r  hitsmissesdict[str, int]bypassessizeNr  rJ   rJ   rJ   rK   r    s   
 r  c                      s  e Zd ZU i Zded< dZded< dZded< eeZ	ded< dZ
ded	< d
Zded< ded< ded< ded< ded< dZded< dZded< dd
ddd
dd fdd Zdd!d"Zdd&d'Zedd(d)Zedd+d,Zed-e fdd6d7Zd fd9d:Zd fdAdBZeddCdDZeddFdGZeddHdIZddJdKZddOdPZddQdRZddWdXZ dd\d]Z!dd`daZ"ddcddZ#ddfdgZ$ddidjZ%ddkdlZ&d-e fddmdnZ'ddtduZ(dd{d|Z)dd}d~Z*e+ddddddddZ,dddZ-dddZ.dddZ/dddddZ0e+e1j2j3e1j4j5e1j6j5e1j7j5e1j8j5e1j9j5e1j:j5e1j;j5e1j<j5e1j=j>e1j?j5Z@e+e1jAj5e1jBj5ZCdddZDe+e1jEj5e1jFj5ZGdddZHdddZIddddddddZJ  ZKS )rv   ,dict[_DispatchCacheKey, _DispatchCacheEntry]cacher   r  
cache_hitscache_missesr  cache_bypassesri  Fr   r=  static_shapesr   r   zOptional[str]_stackr  rE  nt_tensor_id_counternt_tensor_id_initial_countTN)allow_fallback_kernelsallow_non_fake_inputsr   r  r   r   r!  ra   r   rC   rD   c                  s   t dt|  t   || _dd l}dd l}|jj	j
| _t| j|d| _|d ur.|| _n|d u | _d| _|jj	j| _|jj	j| _|jj	joJ| j | _|jj	j| _|| _d| _g | _|| _t | _d | _ |j!j"j#| _$dd l%}|j&j'j(j)| _*| j*| _+d S )Nzcreate_mode 0x%xr   r   F),logrQ  idr  rL   r   torch._dynamo.configtorch._functorch.configr   r  "fake_tensor_propagate_real_tensorspropagate_real_tensorsr   fake_tensor_converterr  allow_scalar_outputs(fake_tensor_allow_unsafe_data_ptr_accessr  fake_tensor_allow_metar  _dynamofake_tensor_cache_enabledrx   $fake_tensor_cache_crosscheck_enabledcache_crosscheck_enabledr!  r=  enter_stackr   	tracebackextract_stack_stack_tracer  rn   rp   rq   r  $torch.nested._internal.nested_tensornested	_internalnested_tensor_tensor_id_counterr  r  )rI   r   r!  r   r  r   rm   r  rJ   rK   rL     sF   


	

zFakeTensorMode.__init__c                 C  s   | j | _d S rc   )r  r  rH   rJ   rJ   rK   reset_nt_tensor_id_counter+  rk   z)FakeTensorMode.reset_nt_tensor_id_counterr   r   TypeGuard[FakeTensor]c                 C  s   t |to	|j| u S rc   )r   r   ru   rI   r   rJ   rJ   rK   is_our_fake:  s   zFakeTensorMode.is_our_fakec                 C  sD   t j rt j rJ t j  S t j p tt do t j  S )Nr}  )rm   r6  _is_compiledr4  r5  hasattrr}  rH   rJ   rJ   rK   avoid_device_initB  s   

z FakeTensorMode.avoid_device_initrU   c                 C  s$   | j d u rdt| j| _ | j S )N )r  joinr1  format_listr3  rH   rJ   rJ   rK   stackM  s   
zFakeTensorMode.stackrJ   r[   r<   r  r  r  r  r  r  c                 C  sL   t jt jjjd u sJ |z	| ||||W S  ty%   td  w )Nzfake tensor raised TypeError)	rm   rn   r  rp   rq   dispatch	TypeErrorr"  	exception)rI   r[   r  r  r  rJ   rJ   rK   r  S  s   

z!FakeTensorMode.__torch_dispatch__r   c                   s|   dd l }d }| jr|j }|jd |j| j}| |ur-| jd||f t	 
 S |j|  | jdd |f | S )Nr   TF)r4  r?  rn   _only_lift_cpu_tensors_set_only_lift_cpu_tensorsro   r  r0  r   r  	__enter__rr   )rI   rm   prev_only_lift_cpu_tensorsmaybe_prev_fake_moder  rJ   rK   rI  f  s   

zFakeTensorMode.__enter__aOptional[type[BaseException]]bOptional[BaseException]cOptional[TracebackType]c                   sX   | j  \}}}|r(t ||| |d urtj| |d ur*tj| d S d S d S rc   )r0  r   r  __exit__rm   rn   rr   rH  )rI   rL  rN  rP  liverK   maybe_prev_only_lift_cpu_tensorsr  rJ   rK   rR  z  s   
zFakeTensorMode.__exit__c                 C  s   dS rg   rJ   r  rJ   rJ   rK   is_infra_mode  rx  zFakeTensorMode.is_infra_moder  c                 C  s   t tjtjttjttjS )z8
        Query the state of the dispatch cache.
        )r  rv   r  r  rh   r  r  r  rU  rJ   rJ   rK   
cache_info  s   zFakeTensorMode.cache_infoc                 C  s$   d| _ d| _| j  | j  dS )z+
        Clear the dispatch cache.
        r   N)r  r  r  r  r  rU  rJ   rJ   rK   cache_clear  s   
zFakeTensorMode.cache_clearc              
   C  s  d}d}zt | j}| ||||}W n3 tyF } z't|tjjr2| dkr2t	
d|d |j tj|j  d7  < W Y d}~nd}~ww |du rS| ||||S |dusYJ | rk|jdusdJ |jj}t}	ntj}t}	||d}
|
durt|
trtj|
j  d7  < | ||||S | ||
|||}t jd7  _| jrt|  | ||||| W d   |S 1 sw   Y  |S | ||||}z	| ||| W n? ty } z2t|tjjr| dkrt	
d|d |j tj|j  d7  < |	||t|j |W  Y d}~S d}~ww z| ||||||}
W n( tyI } ztj|j  d7  < |	||t|j |W  Y d}~S d}~ww |	|||
 t jd7  _|S )z
        Lookup a cache entry for the given arguments. If none exists, dispatch
        and cache the result (if the result is eligible for caching).
        Ninvoke_subgraphz6Fake tensor cache failed: identifier = %s, reason = %sr2   )r3   r   
_cache_keyr  r   rm   _opsHigherOrderOperatorrH  hc_logrQ  rV   rv   r  _dispatch_implcache_on_shape_envfake_tensor_cache_set_cache_key_for_shape_envr  _set_cache_keyr   r  _output_from_cache_entryr  r/  rz   _crosscheck_cache_output_validate_cache_key_make_cache_entryr  )rI   r[   r  r  r  r  r   er  set_cache_keyentryoutputrJ   rJ   rK   _cached_dispatch_impl  s   
 


z$FakeTensorMode._cached_dispatch_implr  r3   r  c           	      C  s   |t  t j t  | jr| jjndg}|jr|| j	 g }|r*| 
|||| |r4| 
|||| tt|}|D ]}t|tjt|d q<|  |S )z
        Create a cache key given the dispatch args. Raises _BypassDispatchCache
        for any situation that precludes caching.
        Nr   )rm   get_default_dtypern   _get_default_deviceis_inference_mode_enabledr   settingsknown_symbolsr   ri  r  r  r  r   finalize	functoolspartialevict_fake_tensor_cache_keyr  )	rI   r  r[   r  r  
key_valuesr  r   id_hashed_objrJ   rJ   rK   rZ  	  s(   zFakeTensorMode._cache_keyc                 C  s>  ddl m} t|tjjr||v rdS tjj|jv rt	dtjj
|jv rU|tjju rQt|||dd\}}|d D ]}t|tjrN|jtjtjfv rNt	dq9dS t	dtjj|jv r`t	d	|tjjkrjt	d
|| jv rst	d| dkr}t	dtjj|st	d|jrtj| tjjjrt	ddS dS )za
        Validate that the cache key generated by _cache_key will be
        reasonable.
        r   registered_hop_fake_fnsNzdata dependent outputTr  r  normalize_to_only_use_kwargsindiceszdynamic output shapezinplace viewzunsafe viewliftzinductor::resize_storage_bytes_znon-builtinCompositeImplicitAutograd)torch._higher_order_ops.utilsry  r   rm   r[  r\  Tagdata_dependent_outputtagsr  dynamic_output_shaper  r  r   r!   r  r   r  inplace_view_unsafe_viewr  lift_fnsrH  _libraryutils
is_builtinis_viewrn   %_dispatch_has_kernel_for_dispatch_keyDispatchKeyr~  )rI   r[   r  r  ry  r   
new_kwargsr  rJ   rJ   rK   re  8  sN   


z"FakeTensorMode._validate_cache_keyr  r  ?Union[Mapping[str, object], Sequence[object], Iterable[object]]r  c           	      C  s
  ddl m} ddlm} t|tttfr%|t	| |dt
|  t|tr@| || || | || || dS |D ]}t|trs| |sRtd|jdur[tdt|rgt|j dt|}||| | qBt|tr|td	t|tr||| qBt|ttfrtd
t|tttfr| |||| qBt|tjrtdt|tjjr|t	| |t | || qBt||r|t!| ||j" qBt||r|t	| |t!| ||j# qB|t	| || qBdS )a7  
        Translate the provided args into a form suitable for caching at FakeTensor
        dispatch, i.e., convert unhashable types like lists & dicts into tuples and
        convert FakeTensors into metadata. Raises _BypassDispatchCache to signal
        unsupported cases that should bypass caching.
        r   )FunctionalCallableWithEpilogue)FunctionalizeCtxWrapperlength_Nznot our fakeconstant attributez tensorznon-fake tensorzsymbolic shapezfunction argument)$*torch._higher_order_ops.auto_functionalizer  r  r  r   r  r  rh   r   r   r  r  keysvaluesr   r<  r  r   r   r   r  r  r   r   r  r   r   r  FunctionTyperm   fxGraphModuler#  r  subgraphorig_callable)	rI   r  r  r  r  r  r  r  r  rJ   rJ   rK   r  ~  sV   







z"FakeTensorMode._prep_args_for_hashr   rj  r   c                 C  s   t |ttd frd S t||rtdt |tstd|jd ur&td|jr-tdt|r5td|	 D ]}t
|t
|krGtdq9d S )Nzunrepresented symbol in outputznon-FakeTensor outputr  zsparse outputzsparse compressed outputzkwarg aliases output)r   r  r   _has_unrepresented_symbolsr  r   r   r   r   r  r#  )rI   r  r   r[   r  r  rj  kvalrJ   rJ   rK    _validate_output_for_cache_entry  s"   


z/FakeTensorMode._validate_output_for_cache_entryr   r  c                   s  t |ttjtd frtd d d |dS tt|D ]}t|| t|kr.t|d d d  S qd }t |tj	j
rP|jrPdd t|D }	t|	dksLJ |	d }t|}
t fdd|
jD |
_t fd	d|
jD |
_ |
j|
_|
jd u r|d n |
j|
_td |
|d}t|fd
d}ddlm} z|  ||||}W n |y   tdd w tj|}tj|}||krtd|S )Nr  r  r  r  )r  r  r  c                 S  s   g | ]\}}t |tr|qS rJ   r   r   )r   ir   rJ   rJ   rK   r   	  s    zCFakeTensorMode._get_output_info_for_cache_entry.<locals>.<listcomp>r2   r   c                 3      | ]}  |V  qd S rc   convert_outputr   r   r  rJ   rK   r     r   zBFakeTensorMode._get_output_info_for_cache_entry.<locals>.<genexpr>c                 3  r  rc   r  r  r  rJ   rK   r     r   Fr
  r  )GuardOnDataDependentSymNodezdata dependent symnodezdispatch_key_set mismatch)r   r  rm   r   r   r  ranger  r#  r[  r<   r  	enumerater  r  r  r  r  r  r  r	  r  r  rc  r  rn   _dispatch_key_set)rI   r  r   r[   r  r  rj  idxr  idxsr  ri  entry_for_synth_outputr  synth_outputsynth_key_setkey_setrJ   r  rK    _get_output_info_for_cache_entry  sX   	




	z/FakeTensorMode._get_output_info_for_cache_entryr	  c              	     s0  ddl m} ddlm ttjjr3|v r3t|tsJ t	fdd|D }|r3t
d dt|ttjtdfrMtddd|d	}	t|	fd
dS t|trb|D ]}
 |
 qTn
 | t|tr fdd|D }tt|ddS  |}	t|	fd
dS )z
        Make a cache entry object for the given 'output' Tensor. Raises
        _BypassDispatchCache if the output tensor has characteristics that
        prevent caching it.
        r   rx  has_free_unbacked_symbolsc                 3  s*    | ]}t |tjtjfo |V  qd S rc   )r   rm   r   r   )r   or  rJ   rK   r   V  s    
z3FakeTensorMode._make_cache_entry.<locals>.<genexpr>zunbacked symbol in HOP z outputNr  Fr  c              
     s    g | ]}  |qS rJ   )r  )r   out_elem)r  r[   r   r  rI   r  rJ   rK   r   q  s    z4FakeTensorMode._make_cache_entry.<locals>.<listcomp>T)r  ry  r  r  r   rm   r[  r\  r  r   r  r  r   r   r  r	  r  r  )rI   r  r   r[   r  r  rj  ry  non_cacheableoutput_infoout_elementr
  rJ   )r  r[   r  r   r  rI   r  rK   rf  ;  sP   

z FakeTensorMode._make_cache_entryri  c              
     s0  |j d u r|jd u r|jd u r|jtusJ |jS |j d ur,||j  }t|ts*J |S |j}|d u r5d S t|r;J dfdd t fd	d
|j	D }t fdd
|j
D }	 |j}
|jd urm |j tj}| jd ury| jj}t| ) |  tj||	|j|jd|jd}W d    n1 sw   Y  W d    n1 sw   Y  |jrtj|d |jrtj|d t|tjjr|jr|tt |j }t|tsJ |! }t| # |  |"||
||	 W d    n1 sw   Y  W d    n	1 sw   Y  t| ||j#S )Nr'  r  r  r3   rC   Union[IntLikeType]c                   s8   t | tr|jd usJ |  |jS t | trJ | S rc   )r   r5   r   r  r4   )r'  r  rl  rJ   rK   check_value  s
   
zGFakeTensorMode._get_output_tensor_from_cache_entry.<locals>.check_valuec                 3      | ]} |V  qd S rc   rJ   r  r  r  rJ   rK   r     r   zEFakeTensorMode._get_output_tensor_from_cache_entry.<locals>.<genexpr>c                 3  r  rc   rJ   r  r  rJ   rK   r     r   r0  )r  r   r   r  T)r'  r  r  r3   rC   r  )$r  r  r  r  r  r   r   r   r  r  r  r  r  
contextlibnullcontextr   suppress_guardsrD  rm   empty_stridedr  r   r  r  rn   	_set_conjr  _set_negr[  r<   r  r   r  r  set_r   )rI   r  ri  r   r[   r  inplace_argr  r  r  r  maybe_suppressr9  view_argstoragerJ   )r  r   r  rK   #_get_output_tensor_from_cache_entry  s`   
	






 
 z2FakeTensorMode._get_output_tensor_from_cache_entry=Union[Optional[FakeTensor], tuple[Optional[FakeTensor], ...]]c                   sB   |j r fdd|jD }t|S |jd  S )z?
        Create a new FakeTensor from the cache entry.
        c              	     s   g | ]} | qS rJ   )r  )r   r  r  r[   r   rI   r  rJ   rK   r     s    
z;FakeTensorMode._output_from_cache_entry.<locals>.<listcomp>r   )r  r
  r  r  )rI   r  ri  r   r[   r  outputsrJ   r  rK   rc    s   z'FakeTensorMode._output_from_cache_entryc                   s   d fdd z
|  ||||}W n ty. } ztd| d	| d
| d| |d}~ww z || W dS  tyQ } ztd| d	| d
| |d}~ww )z
        Helper to validate that the output synthesized from the cache matches
        the output created by normal dispatch.
        rL  r   rN  rC   rD   c                   s   t | tr't |tsJ t| t|ksJ t| |D ]	\}} || qd S t | tr9t |tr5| |ks7J d S | d u rE|d u sCJ d S t | tr\t| t|krX| j|ju sZJ d S t | tj	rrt |tj	sjJ t
t| | d S tdt|  )NzUnsupported type )r   r  r  zipr  r%   r   rg  rm   r   r   r   r  )rL  rN  lrk  assert_helperrJ   rK   r    s    


$z>FakeTensorMode._crosscheck_cache_output.<locals>.assert_helperz*FakeTensor cache crosscheck failure: func=z, args=z	, kwargs=z: Dispatch raised=N)rL  r   rN  r   rC   rD   )r^  	Exceptionr  )rI   rj  r[   r  r  r  true_outputrg  rJ   r  rK   rd    s>   z'FakeTensorMode._crosscheck_cache_outputc                 C  s   |pi }t   td||| W d    n1 sw   Y  |tv r)t| |S t tjkr<tddt | t }|t	v r[t
|  ||i |W  d    S 1 sVw   Y  | jrf| ||||S | ||||S )Nz%s %s %sz'%sFakeTensorMode.__torch_dispatch__: %s )r'   r"  rQ  r  getEffectiveLevelloggingDEBUGrG   rB   _DISPATCH_HANDLE_DIRECTLYrD  rx   rk  r^  )rI   r[   r  r  r  incrrJ   rJ   rK   rD    s$   

 zFakeTensorMode.dispatchpathr*   fakerealtuple[Optional[object], bool]c           
        s@  ddl ddlm} d fd	d
}ttjrz|dddddd W n= tyb   z1tjjj	rKt
d fddd tdfW  Y d  S td d dt| d  d  ww tt  D ]O\}\}}	z|||	 W qn ty   z6tjjj	rt
d fddd tdfW  Y d    S td| d|	 dt| d| d 
 d  ww dfS du rdurtjjj	rt
dfddd tdfS td d dt| d z
| W dfS  ty   ztd d dt| d  d  ww )!z
        Helper to cross-check fake/real output properties & values,
        and create new fake vals if mismatched.
        Returns tuple of object & boolean, for whether or not it was overwrriten
        r   N)_check_fake_real_tensorsr  r   r  rC   rD   c                   s   t | ttfr@ jd usJ | jjj jj   jj	  s< jj
| jj|ddjjur>td|  d| dd S d S t | tttfrW| |krYtd|  d| dd S d S )NT)compute_hintmismatch between fake value  and real value r  )r   r   r   r   rg  exprfree_symbols
var_to_valr  unbacked_var_to_val_maybe_evaluate_staticEqStruer_   r  floatr   )r  r  )rI   sympyrJ   rK   _check_fake_real_vals@  s6   


z?FakeTensorMode._maybe_infer_fake.<locals>._check_fake_real_valsReal tensor propagation foundFT)contextsizesstridesr  r  mismatched_fake_kernelc                        t  jdS NoprV   rU   rV   rJ   excr[   rJ   rK   <lambda>j     z2FakeTensorMode._maybe_infer_fake.<locals>.<lambda>metadata_fnzFReal tensor propagation found a metadata mismatch between fake tensor z and real tensor z,  at outputz, for func: c                     r  r  r  rJ   r  rJ   rK   r  }  r  zIReal tensor propagation found an output size mismatch between fake shape z and real shape z, at outputz.size(z), for func: c                     s   t d  d dS )Nr  r  r  rU   rJ   )r  r[   r  rJ   rK   r    s   zQReal tensor propagation found an output value mismatch between fake output value z and real output value )r  r   r  r   rC   rD   )r  torch._subclasses.fake_utilsr  r   rm   r   r_   r   r  *generate_fake_kernels_from_real_mismatchesr   _infer_fake_from_real_tensorr+   r  r  r  )
rI   r[   r  r  r  r  r  js_fakes_realrJ   )r  r  r[   r  rI   r  rK   _maybe_infer_fake4  s   
	
"
 '
z FakeTensorMode._maybe_infer_fakefake_inreal_infake_outreal_outOptional[object]c              
     s  ddl m} djrtjjdfdd}t|\}}	t|\}
}z
|d|||| W n= tyn   z1t	j
jjr\td	 fd
dd |  tfdd|W  Y d  S td| d| d  d  ww tfddt||
D  \}}t|rr|  t||	S )z
        Helper to cross-check fake/real output properties & values,
        and create new fake vals if mismatched, but at the kernel level.
        Means this handles pytree outputs & checks aliasing.
        r   )_check_alias_infoNrC   rD   c                     s   t tjj j_d S rc   )r  setr   pending_fresh_unbacked_symbols
differencerJ   )pending_unbackedrI   rJ   rK   _clear_pending_unbacked  s
   zXFakeTensorMode._maybe_infer_fake_kernel_from_pytree_out.<locals>._clear_pending_unbackedr  r  c                     s   t d j dS )Nz>Mismatched aliasing spec between fake kernel and real kernel: r  r  rJ   r  rJ   rK   r    s   
zIFakeTensorMode._maybe_infer_fake_kernel_from_pytree_out.<locals>.<lambda>r  c                   s   t  | S rc   r  r   r[   rI   rJ   rK   r    s    zGReal tensor propagation found an aliasing mismatch between fake output z and real output z,  for func: c                   s$   g | ]\\}}}  |||qS rJ   )r  )r   
_fake_path	_fake_out	_real_outr  rJ   rK   r     s    
zKFakeTensorMode._maybe_infer_fake_kernel_from_pytree_out.<locals>.<listcomp>rO   )r  r  r   r  r
  r   tree_flatten_with_pathtree_flattenr_   rm   r   r  r  r   r-   r  r   tree_unflatten)rI   r[   r  r  r  r  r  r  fake_paths_leaves	fake_specreal_leavesr   fake_leaves	overridesrJ   )r  r[   r  rI   rK   (_maybe_infer_fake_kernel_from_pytree_out  s^   

	z7FakeTensorMode._maybe_infer_fake_kernel_from_pytree_outc           (        s	  ddl m} t 	f\t}|r$dd D }td| tS fddD }tdd |D p>td	d D j	j
v }	tjjjju o^t d tjo^ d jjd
k}
|	rc|rmtrs|s|
stdd |D s}J  dfddD }t|\}}|i |}t|tu r|rt  | }W d    n1 sw   Y  j|ddS |	rt	dkrt dksJ   d	 t d tu r d S d}jrtjjjjkrd	v r	d dkrd}tjjjjkrd}\} 	tdd |D }ttj j!rtj"j#j$vrtj"j%j$vr|rt|dkrs|stj&jurfddD }t|\}}t  |i |}W d    n	1 syw   Y  t'|}dd |D }tfdd|D }|rt(tfdd|S |D ]})| qt\ 	ttj j*r|v rj+d u rt,j-nj+j.}, |  |  i 	W  d    W  d    S 1 sw   Y  W d    n	1 sw   Y  /| 	 d<fdd 
dd!l0m1m2 t3 j4rtd"d |D rtfd#dD st5d$ 
fd%dD }t|\t67}|sft68|}z	i W n t9y } zt5d&| W Y d }~nd }~ww |s|:  t6;j< nj4rt5d'|j+rj+j=nd  d= 	f
d)d*}rt> ?}|d ur||g R i 	S dd+l@mA} |vrZBsZrjCv sZdd,l@mD} |v r/stEr/td-d |D r/ ||  i 	W  d    S 1 s*w   Y    jF i 	}|turJ||W  d    S W d    n	1 sUw   Y  d.jGjHv rtId/rtJs |jK i 	W  d    S 1 sw   Y  tjLjMjN}|d ur|jOv r|jPg R i 	S j4rՈurt67sՈj+d urt6QstR}tSd0fd1dd2 ||S tjTjUjVWH jXjY} | rozLtjTjXZtjTjX[fd3d.  |  i 	}||W  d    W  d    W S 1 sw   Y  W d    n	1 s*w   Y  W n> t\yn }! z1j4rhurht67shj+d urhtR}tSd0fd4dd2 ||W  Y d }!~!S |!d }!~!ww t]D ]!\}"}#|"r|#g R i 	}$|$tur||$  S qq	 d>d?fd8d9}%t^s|% }&||&S zt_  i 	}W d    n	1 sw   Y  W n% t`y }' z
|%|'W  Y d }'~'S d }'~'w tay   t5bd:  w |jc|	?dd;S )@Nr   rx  c                 S  s   g | ]
}t |rt|qS rJ   )_check_for_subclass_argr   r   rJ   rJ   rK   r   	  s
    z1FakeTensorMode._dispatch_impl.<locals>.<listcomp>z,FakeTensorMode unrecognized subclass(es): %sc                   s   g | ]	}  |r|qS rJ   )r<  r  rH   rJ   rK   r   	  r   c                 s  s    | ]}|j V  qd S rc   )r  )r   r  rJ   rJ   rK   r   	  s    
z0FakeTensorMode._dispatch_impl.<locals>.<genexpr>c                 s  s    | ]}t |tV  qd S rc   )r   r   r   rL  rJ   rJ   rK   r   	  r   r0  c                 s      | ]}|j d uV  qd S rc   r   r  rJ   rJ   rK   r   '	  r   z. should not have fake inputs without constantsc                       g | ]}  |r|jn|qS rJ   r<  r   r  rH   rJ   rK   r   *	      Tr   r2   r  Fr   r  c                 s  r  rc   r   r   rg  rJ   rJ   rK   r   c	  r   c                   r  rJ   r   r  rH   rJ   rK   r   n	  r!  c                 S  s   g | ]	}t |tr|qS rJ   r  r  rJ   rJ   rK   r   y	  r   c                 3  r  rc   )may_turn_constr  rH   rJ   rK   r   z	  r   c                   s    j | ddS )NTr"  )r*  r   )	converterrI   rJ   rK   r  	  s    z/FakeTensorMode._dispatch_impl.<locals>.<lambda>r   rA   rC   1Optional[Union[T, Tensor, torch._C.ScriptObject]]c                   s`   t | tr| jS t | tr& jd usJ | j| jj jj	 jj
S t | tr.| jS | S rc   )r   r   rq  r%   r   rg  r,  r  xreplacer  r  r   real_objr   rH   rJ   rK   maybe_to_real_tensor	  s   


z;FakeTensorMode._dispatch_impl.<locals>.maybe_to_real_tensor)compute_unbacked_bindingsfree_unbacked_symbolsc                 s  r  rc   )rq  r#  rJ   rJ   rK   r   	  r   c                 3  sF    | ]}t |to | ojd uotfddD V  qd S )Nc                 3  s    | ]	}| j jvV  qd S rc   )r   r  r   srH   rJ   rK   r   	      z:FakeTensorMode._dispatch_impl.<locals>.<genexpr>.<genexpr>)r   r%   r   r   r  )r+  rI   symsrJ   rK   r   	  s    


zpropagate_real_tensors %sc                      g | ]} |qS rJ   rJ   r  )r)  rJ   rK   r   	  r  z9real-tensor fallback failed for %s: %s; silently ignoringz,SKIPPED propagate_real_tensors %s(%s, %s) %sr  c                   s   dd l td d fd	d
 
uritjjjs+f	f| 
 nf	f| 
} t| t	s[t
t	s[t
| t

kr[t tt| tt
 nt | 
 j| dd | S )Nr   zmaybe_propagate_real_tensors %sr   r   real_tr   rC   rD   c                   s2  t | trDtdt| t| || _t|  | D ]	\}}|| qt|  | D ]	\}}|| q/| 	 |	  d S t | t
r | rt | jjjrgjd us\J j| jj| d S t | jj }jrt |jjr|jdkrjd usJ j|t| d S d S d S d S d S d S )Nz%maybe_propagate_real_tensors %s -> %sr2   )r   r   r"  rQ  r#  rq  r  r  r  r  r%   rg  r  Symbolr   set_unbacked_var_to_valr  lhsrhsr  )r   r1  r-  real_s)r+  gorI   r  rJ   rK   r7  	  s0   

zOFakeTensorMode._dispatch_impl.<locals>.maybe_propagate_real_tensors.<locals>.goT)peek)r   r   r1  r   rC   rD   )r  r"  rQ  rm   r   r  r  r  r   r   r   r.   r  r   r  r   )r  )
r  r*  r+  r[   r  nil	real_argsreal_kwargsr  rI   )r7  r  rK   maybe_propagate_real_tensors	  s@   
	
zCFakeTensorMode._dispatch_impl.<locals>.maybe_propagate_real_tensors)
meta_tabler   c                 s  s    | ]}t | V  qd S rc   )r   r#  rJ   rJ   rK   r   J
  r   zprims::prim_meta_implmissing_fake_kernelc                        dt  iS Nr  r  rJ   r   rJ   rK   r  y
     r  c                     s    S rc   rJ   rJ   )ctxrJ   rK   r  
  s    c                     r@  rA  r  rJ   r   rJ   rK   r  
  rB  errorOptional[RuntimeError]r   c                   sH   t jjr	d S sst| d u rt} t | S rc   )rm   r  r  can_generate_trivial_fake_implcan_run_unsafe_fallbackr]   run_fallback_kernel)rD  )	args_specr  r[   has_symbolic_sizesrI   rJ   rK   maybe_run_unsafe_fallback
  s   z@FakeTensorMode._dispatch_impl.<locals>.maybe_run_unsafe_fallbackz*failed while attempting to run meta for %sr3  )r   rA   rC   r&  )r  rA   rC   rA   rc   )rD  rE  rC   r   )dr  ry  r   r  _check_for_subclassr  rQ  r  r   r(  r  rm   r  r  _to_copyr  r   r   r   r   rJ  r   r  r$  r'   cloner*  r  r?  prims
device_put%validate_and_convert_non_fake_tensorsr[  r<   r  nondeterministic_seededr  r  _nested_tensor_from_tensor_listr   tree_map_onlyr   r\  r   r  r  ignore_fresh_unbacked_symbolsinvalidate_written_to_constantsr  r*  r+  r   r'  r"  library_utilsr  MutationCheckerZeroDivisionErrorcheckcheck_aliasing_constraintrS  r  get_fast_op_implsr   r   r=  cpp_meta_supports_symint_view_fake_tensor_impl_opsr   r   	decomposer   rH  r>  stride_incorrect_opr>  r,  r  _custom_ops_profiledatageneric_fake_kernelhas_fake_kernel"inferred_fake_kernel_from_real_outr   r  simple_registry	singletonfind	fake_implkernelFakeImplCtxset_ctx_getterr   op_implementations_checkshas_metarD  rv  r  rF  +wrap_meta_outputs_with_default_device_logic)(rI   r[   r  r  r  ry  has_unrecognized_typesr  flat_arg_fake_tensorsis_lift_func!device_conversion_skip_const_propconst_flat_args
const_argsconst_kwargsr|   avoiding_device_initall_constantflat_outflat_out_tensorsr   #maybe_ignore_fresh_unbacked_symbolsreal_flat_argsr  mutation_checkerr  r<  	fast_implr=  r   rk  profilesr  maybe_fake_implrg  run_impl_checkop_implop_impl_outrK  fallbacknot_implemented_errorrJ   )r  rI  r*  r%  rC  r  r+  r[   rJ  r  r)  r9  r:  r;  r  rI   r/  rK   r^    s  



*



P

 I


	"
"




R





zFakeTensorMode._dispatch_impl
debugprimsrO  r  xlavision	torchtext
torchaudio	quantizedc                 C  s"   | j sdS |j| jv p| dkS )NFzfbgemm::gmm)r   	namespace+_can_run_unsafe_fallback_allowed_namespacesrH  rI   r[   rJ   rJ   rK   rG  
  s
   
z&FakeTensorMode.can_run_unsafe_fallbackr%  r   r  rI  r/   %tuple[list[object], list[FakeTensor]]c                   s6   g d
 fddfddD }|fS )z
        Checks if the list of tensors are fake tensors.
        If not, try to convert them to fake tensors.
        Returns the original args, kwargs, and a flattened list of (args, kwargs) that are fake tensors.
        r   rA   rC   Union[T, FakeTensor]c                   s   t | ts| S | s`tdr+tjjjv r+t	 \}}t
dt|| tjd u r3jntj}|sYt | trF| jurFt
dt	 \}}t
dt|| | }n| }| |S )Nr  zECan't call metadata mutating ops on non-Fake Tensor inputs. Found in zMixing fake modes NYIzuPlease convert all Tensors to FakeTensors first or instantiate FakeTensorMode with 'allow_non_fake_inputs'. Found in )r   r   r<  r>  rm   r  r  r  r   r  AssertionErrorr   fake_tensor_tlsrb   r!  r   ru   r*  r   )r   r  r  r!  r|   )rI  r%  rq  r  r[   rI   rJ   rK   validate
  s2   




zFFakeTensorMode.validate_and_convert_non_fake_tensors.<locals>.validatec                   r0  rJ   rJ   r  )r  rJ   rK   r     r  zHFakeTensorMode.validate_and_convert_non_fake_tensors.<locals>.<listcomp>N)r   rA   rC   r  rJ   )rI   r[   r%  r  rI  validated_argsrJ   )rI  r%  rq  r  r[   rI   r  rK   rQ  
  s    z4FakeTensorMode.validate_and_convert_non_fake_tensorsrk  r   r+  r,   c                   s2   j d  dd fdd}t||S )	NFrg  rA   rC   r  c                   s   t  ts S d u rt\ }|r-t jk fdd tt	 S d urBr9
 S  p@S  S )Nc                     s   dj  d  S )Nz-FakeTensor is wrapped to wrong device, found z, expected r3  rJ   )r  rg  rJ   rK   r  :      zZFakeTensorMode.wrap_meta_outputs_with_default_device_logic.<locals>.wrap.<locals>.<lambda>)r   r   r   r  r<  rm   _checkr   r   rA   r*  r1  )rg  r<  r  r%  r   r  r[   r  rI   rg  rK   wrap)  s*   




zHFakeTensorMode.wrap_meta_outputs_with_default_device_logic.<locals>.wraprg  rA   rC   r  )r(  r-   )rI   rk  r[   r  r   r  rJ   r  rK   ro    s
   
!z:FakeTensorMode.wrap_meta_outputs_with_default_device_logicr  r  r  r  c                C  s   dd l }ddlm} |d u r| j}| jsJ d|  jd7  _|||d}|jjd}| j	d us5J | j	j
| j	j||d||d}|S )Nr   )NestedIntNodez1should only called while FakeTensorMode is activer2   intermediate_offsets_or_lengths)valr   )symr  r   )r4  !torch.nested._internal.nested_intr  r  r0  r   r,  r   EphemeralSourcer   r"  create_symbol)rI   r  rm   r  r  srcretrJ   rJ   rK   r  L  s$   z)FakeTensorMode.create_symbolic_nested_intc                 C  s   t jj|jv r	dS || jv S rg   )rm   r  	view_copyr  _cpp_meta_supports_symintr  rJ   rJ   rK   r]  x  s   
z'FakeTensorMode.cpp_meta_supports_symintr   c                 C  s0   |  tkot| o| | o|jjdk S rs  )numelCONSTANT_NUMEL_LIMITr   r<  r   r   r;  rJ   rJ   rK   r$    s   
zFakeTensorMode.may_turn_constrq  Sequence[FakeTensor]c                 C  s   t dd |D }t|}|rI| rKt|||dd\}}| D ]+\}	}
|	dks.||	r0|	nd}	| |
rH||	rH|
jd urH| j	|
j q!d S d S d S )Nc                 s  r  rc   r   r#  rJ   rJ   rK   r     r   zAFakeTensorMode.invalidate_written_to_constants.<locals>.<genexpr>Trz  inputrI   )
r   r   
is_mutabler!   re   has_argumentr<  r   r(  r   )rI   r[   rq  r  r  any_constantschema_infor   r  kr   rJ   rJ   rK   rV    s(   

z.FakeTensorMode.invalidate_written_to_constants)r  r   r   r   r   r   r   r   r   r   c                C  sD   | j }|d u r
| j}|r|d u sJ dd }| jj| |||||dS )Nz2cannot set both static_shapes and symbolic_context)r   r   r   r   )r   r  r(  r*  )rI   r   r  r   r   r   r   rJ   rJ   rK   r    s    	
zFakeTensorMode.from_tensor)r   r   r!  r   r   r   r  ra   r   r   rC   rD   rO   )r   r   rC   r:  )rC   r   )rC   rU   r  )rC   r   )rL  rM  rN  rO  rP  rQ  rC   rD   )rC   r  )
r  r3   r[   r<   r  r  r  r  rC   r  )r[   r<   r  r  r  r  rC   rD   )
r  r  r  r  r  r3   r  r  rC   rD   )r  r3   r   r  r[   r<   r  r  r  r  rj  r   rC   rD   )r  r3   r   r  r[   r<   r  r  r  r  rj  r   rC   r  )r  r3   r   r  r[   r<   r  r  r  r  rj  r   rC   r	  )r  r3   ri  r  r   r  r[   r<   r  r  rC   r   )r  r3   ri  r	  r   r  r[   r<   r  r  rC   r  )rj  r  r[   r<   r  r  r  r  r  r  rC   rD   )
r[   r<   r  r*   r  r   r  r   rC   r  )r[   r<   r  r   r  r   r  r   r  r   rC   r  )
r[   r<   r  r  r  r  r  r  rC   r   r[   r<   rC   r   )
r[   r<   r%  r   r  r  rI  r/   rC   r  )
rk  r   r[   r<   r  r  r   r+  rC   r,   )r  r  rC   r  r  )
r[   r<   rq  r  r  r  r  r  rC   rD   )r   r   r  ra   r   r   r   r   r   r   rC   r   )LrP   rQ   rR   r  rX   r  r  r   r  r  ri  r=  r  r  rL   r9  r<  r2  r?  rC  r0   r    r  rI  rR  r  rV  rW  rX  rk  rZ  re  r  r  r  rf  r  rc  rd  rD  r  r  r^  rj   r  rG  rQ  ro  r  r  r9  r  r  r  as_strided_scatter
as_stridedas_strided_r:  detachview_as_realview_as_complexr  source_Storage_storage_offset(_sparse_coo_tensor_with_dims_and_tensorsr  viewr  r^  r]  
lift_freshlift_fresh_copyr  r$  rV  r  r  rJ   rJ   r  rK   rv     s   
 	

_


	
a
/
F
G
,
J
H
I
2
!
n
L   j


11


r  r3   rj  r   c                 C  s<   ddl m} ||D ]}|jD ]}|| jvr  dS qq
dS )Nr   )_iterate_exprsTF)r  r  r  rq  )r  rj  r  r-  r)  rJ   rJ   rK   r    s   

r  r  r  rI  orig_not_implemented_exceptionr  c           
        s   t jj|jv r	i t ( d fddfdd|D }t||\}}||i |}W d    n1 s9w   Y  t |D ]}t|t	rVt
|sV| j qCd fd
d}	t|	|S )Nrg  rA   rC   Union[T, Tensor]c                   sB     | rtj| | jd}| jr||   | t|< |S | S )Nr3  )r<  rm   
zeros_likero  r   _coalesced_r  r#  )rg  r|   )ru   	inp_implsrJ   rK   to_real_tensor  s   
z+run_fallback_kernel.<locals>.to_real_tensorc                   r0  rJ   rJ   r  )r  rJ   rK   r     r  z'run_fallback_kernel.<locals>.<listcomp>r  c                   sd   t | vrt| trt| s|  jv rt| tr0t | v r)t |  S  j | S | S rc   )r#  r   r   r   r   _cdatar(  r*  r  )ru   r  r  storagesrJ   rK   map_out  s   
z$run_fallback_kernel.<locals>.map_out)rg  rA   rC   r  r  )rm   r  r  r  r'   r   r  r	  r   r   r   addr   r  r-   )
ru   r[   r  rI  r  r  r  rk  rg  r  rJ   )ru   r  r  r  r  rK   rH    s"   
	
rH  r  r  r   ri  _DispatchCacheEntryc                 C  s   |   || |< d S rc   )r  r  r   ri  rJ   rJ   rK   ra    s   ra  c                 C  s   || |< d S rc   rJ   r  rJ   rJ   rK   rb    s   rb  c                   @  s&   e Zd ZdddZ		ddddZdS )FakeCopyModeru   rv   rC   rD   c                 C  rW  rc   )ru   )rI   ru   rJ   rJ   rK   rL      rd   zFakeCopyMode.__init__rJ   Nr[   r<   r  r  r  r  r  Optional[Mapping[str, object]]r   c                 C  s
  |r|ni }|t jjjkr&t|d tsJ || jj|d ddfi |S |tjkrgt	|dkr7t	|dks9J t
t|d }t
tttf |d }t||v rW|t| S | jj|dd}||t|< |S t j  ||i |W  d    S 1 s~w   Y  d S )Nr   T)r     r2   )rm   rn   
TensorBaserN  r   r   ru   r  __deepcopy__r  r   rh   r  r   r#  DisableTorchFunctionSubclass)rI   r[   r  r  r  r   memor|   rJ   rJ   rK   __torch_function__#  s(   
$zFakeCopyMode.__torch_function__)ru   rv   rC   rD   )rJ   N)
r[   r<   r  r  r  r  r  r  rC   r   )rP   rQ   rR   rL   r  rJ   rJ   rJ   rK   r    s
    
r  r  c                 C  s>   t | dkrt| d tsJ | d jjrtdS | d jS )Nr2   r   r0  )r  r   r   ru   r=  rm   r   ro  r  rJ   rJ   rK   _device_handlerB  s   

r  c                 C  s   t dd | D S )Nc                 s  r   rc   )r  r   rJ   rJ   rK   r   [  r   z&_check_for_subclass.<locals>.<genexpr>)r   )r  rJ   rJ   rK   rL  Z  s   rL  c                 C  s2   t | t ot | tot| tuot| tjjuS rc   )r   r   r   r   rm   r  r  r   rJ   rJ   rK   r  ^  s   
r  c                 C      t dd tt| d  D S )Nc                 s  r   rc   r  r,  rJ   rJ   rK   r   i      
<lambda>.<locals>.<genexpr>r   )r  r   r   r  r  rJ   rJ   rK   r  i      r  c                 C  r  )Nc                 s  r   rc   r  r,  rJ   rJ   rK   r   l  r  r  r   )r  r   r   r  r  rJ   rJ   rK   r  l  r  c                 C  s   t tt| d  S r  )r  r   r   r  r  rJ   rJ   rK   r  o  s    )_device_not_kwarg_ops_is_tensor_constructor_like_tensor_constructorscontains_tensor_typesr\  rn  rm  r`  c                 C  s   | t jv rt j|  d S d S rc   )rv   r  r   rl  rJ   rJ   rK   ru    s   
ru  c                  C  s   t d t dtj t dtj tj} | rBt d tdd | D }t|  dd d	D ]\}}t d
|d | d| q0d S d S )NzFakeTensor cache stats:z  cache_hits: %sz  cache_misses: %sz  cache_bypasses:c                 s  r   rc   )r  )r   r  rJ   rJ   rK   r     r   z#dump_cache_stats.<locals>.<genexpr>c                 S  s
   | d  S rE   rJ   )r  rJ   rJ   rK   r    s   
 z"dump_cache_stats.<locals>.<lambda>rl  z    %-*s %sr2   r  )	r"  inforv   r  r  r  maxsortedre   )r  widthr  r   rJ   rJ   rK   dump_cache_stats  s   

r  r  r  torch._ops.OpOverloadr  torch.Tensorc                   s  dfdd}|  dkr|d|     fd	d
t| D }dg|  }dd
 t| D }|jdd d d}|}|D ]'\}	}
|	|krY|d|j d|  d |||
< ||j|
  }|||
  }qC  tj|||j	|j
|jdW  d    S 1 sw   Y  d S )NrV   rU   rC   rD   c                   s   t d j d|  d)NzQpropagate_real_tensors: we cannot infer a Fake kernel (meta kernel) for operator z	 because z>. Please use torch.library.register_fake to add a Fake kernel.)r  rS  )rV   )r  rJ   rK   unsupported  s   z1_infer_fake_from_real_tensor.<locals>.unsupportedr   z'a return has a non-zero storage offset c                   s   g | ]
}t jj jqS rJ   )rm   r  ri  allocate_sizer   )r   r   )r  rJ   rK   r     s    z0_infer_fake_from_real_tensor.<locals>.<listcomp>rE  c                 S  s   g | ]\}}||fqS rJ   rJ   )r   r  r-  rJ   rJ   rK   r         c                 S  s   | d | d  fS )Nr   r2   rJ   r   rJ   rJ   rK   r    r  z._infer_fake_from_real_tensor.<locals>.<lambda>rl  r2   z(a return was not dense in memory (sizes z	 strides ))r   r  r   )rV   rU   rC   rD   )r  r  r  r  r  sortr  rm   r  r   r  r   )r  r  r  r  
fake_shapefake_stridesr  expectedfake_strider-  r  rJ   r  r  rK   r    s<   

$r  r   c                   s^    j d usJ t|\}}tdd |D stdj  fdd|D }t||S )Nc                 s  s    | ]	}t |tjV  qd S rc   )r   rm   r   r  rJ   rJ   rK   r     r.  z5inferred_fake_kernel_from_real_out.<locals>.<genexpr>zPpropagate_real_tensors: we don't support operators that return non-Tensors. Got c                   s   g | ]}t  |qS rJ   r  r  r  rJ   rK   r     r  z6inferred_fake_kernel_from_real_out.<locals>.<listcomp>)r   r   r  r   r  r   r  )r  r  r  real_flat_outspecfake_flat_outrJ   r  rK   re    s   re  )re   rA   rC   rf   )rC   rl   )ru   rv   rC   rw   )r{   r   r|   r}   rC   r}   )r   r   rC   r   )r   r   rC   r   )r[   r<   rC   r   r  )r   r   r   r,   rC   r   )r   r   rC   r   )r   r+  rC   rD   )r   r   rC   r  )r  r3   rj  r   rC   r   )ru   rv   r[   r<   r  r  rI  r,   r  r  rC   r   )r  r  r   r  ri  r  rC   rD   )r  r  rC   r+  )r  r  rC   r   )r   r   rC   r   )r   r  rC   rD   rO   )r  rv   r  r  r  r  rC   r  )r  rv   r  r  r  r   rC   r   )
__future__r   atexitr  r  rs  r  r  rO  	threadingr1  r  typingr   collectionsr   r   r   r   r   r   r	   r
   r   r   typing_extensionsr   r   r   rm   torch._library.utilsr  r  rW  r   r   r   r   torch._C._functorchr   r   "torch._library.fake_class_registryr   torch._library.fake_profiler   torch._loggingr   torch._prims_commonr   torch._subclasses.meta_utilsr   r   r   r   r   torch._utilsr   torch.fx.immutable_collectionsr    torch.fx.operator_schemasr!    torch.multiprocessing.reductionsr"   torch.overridesr#   torch.typesr$   r%   torch.utils._backport_slotsr&   torch.utils._mode_utilsr'   torch.utils._python_dispatchr(   r)   torch.utils._pytreer*   r+   r,   r-   r.   r/   torch.utils._statsr0   torch.utils._tracebackr1   _fake_tensor_utilsr3   r4   r5   collections.abcr6   r7   r8   r9   r:   torch._guardsr;   
torch._opsr<   r  r=   r>   	getLoggerrP   r"  _logginggetArtifactLoggerr]  r  
ValueErrorrg  rU   r  DimList_pytreer   rA   r[  r  r  r  rG   rB   r  rT   rZ   r\   r]   r^   r_   localr`   r  rj   contextmanagerrt   rz   r   r   r   r  r   r   r   r   r   r;  rD  rJ  rK  rR  r   r  r  r  r  r  r  r	  r  r  r  r  r  rv   r   _StoragePointerr  rH  ra  rb  r  r  rL  r  r  r   r  r  r  r  r  r  r  r  profiler_record_function_exit_RecordFunctionr  torch._subclasses.fake_implsr  r  r  r  r\  rn  rm  r`  ru  registerr  r  re  rJ   rJ   rJ   rK   <module>   sV  ( 


	
	
	

	

 i

A  q
-&              


@
	

#






(	

<