o
    I&iII                     @   s  U 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mZmZmZmZmZmZmZ dZee
j ed< zd dlZW n	 eyc   Y nw 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) 	 G d
d dZ*e*dee+ fddZ,d7ddZ-ej.G dd dZ/d8de/fddZ0e*dee+e1f fddZ2e*dee+e1f fddZ3e*dee+e1f fddZ4e*dee+e1f fddZ5e*dee+e1f fdd Z6ee7Z8ee1eeg df  f ed!< d"e1d#eg df ddfd$d%Z9d&e:ddfd'd(Z;de<fd)d*Z=de<fd+d,Z>de<fd-d.Z?de1fd/d0Z@de<fd1d2ZAde<fd3d4ZBde<fd5d6ZCdS )9    N)defaultdict)AnyCallablecastDictListOptionalSetUnionnp)is_fx_tracing   )config)is_compiling)hashableis_safe_constantNP_SUPPORTED_MODULESc                   @   s   e Zd ZU dZdZeee  ed< dZ	ee
eef  ed< deg ee
eef ee f f fddZdd	 Zd
edefddZd
efddZd
efddZd
efddZdS )FunctionIdSeta2  
    Track a set of `id()`s of objects which are either allowed or not
    allowed to go into the generated FX graph.  Use to test for torch.*,
    numpy.*, builtins.*, etc.

    Support user modification to permit customization of what can be
    added to the graph and what will cause a graph break.
    Nfunction_idsfunction_nameslazy_initializerc                 C   s
   || _ d S N)r   )selfr    r   JC:\wamp64\www\opt\env\Lib\site-packages\torch/_dynamo/allowed_functions.py__init__@      
zFunctionIdSet.__init__c                 C   sP   | j d u r%|  }t|trt| | _ || _| j S t|ts"J || _ | j S r   )r   r   
isinstancedictsetkeysr   )r   valuer   r   r   __call__C   s   

zFunctionIdSet.__call__idxdefaultc                 C   s"   |   | j d us
J | j ||S r   )r   get)r   r#   r$   r   r   r   get_nameN   s   zFunctionIdSet.get_namec                 C   s   |  }| | d S r   )addr   r#   r   r   r   r   r'   S   s   zFunctionIdSet.addc                 C   s    |  }||v r| | d S d S r   )remover(   r   r   r   r)   W   s   zFunctionIdSet.removec                 C   s
   ||  v S r   r   )r   r#   r   r   r   __contains__\   r   zFunctionIdSet.__contains__)__name__
__module____qualname____doc__r   r   r	   int__annotations__r   r   strr   r
   r   r"   r&   r'   r)   r*   r   r   r   r   r   3   s   
 	*r   returnc                  C   s   ddd t jtjtjtjtjtj	tj
tjtjjtjtjjtjjtjjjtjjjtjtjjtjtjtjtjtjtjt j!tj"j#j$j%tj&j'tj(tj)j*g} dd tj+, D }| |7 } dd tj+, D }| |7 } tj-. rq| /tj-j0j1 dd | D S )NTFc                 S       g | ]}t |ttjr|qS r   )r   typetorchZfloat32.0objr   r   r   
<listcomp>   s
    z,_disallowed_function_ids.<locals>.<listcomp>c                 S   r3   r   )r   r4   r5   ZFloatStorager6   r   r   r   r9      s    c                 S   s   h | ]}t |qS r   )idr7   xr   r   r   	<setcomp>       z+_disallowed_function_ids.<locals>.<setcomp>)2collectionsOrderedDictcopydeepcopyinspect	signaturemath__package__r5   __builtins__Zautocast_decrement_nestingZautocast_increment_nestingZautogradgradZclear_autocast_cachecudaZcurrent_deviceZ
set_devicedistributionsconstraintsZis_dependentnormalZNormalZinference_modeZjitr   Zset_anomaly_enabledZset_autocast_cache_enabledZset_autocast_cpu_dtypeZset_autocast_cpu_enabledZset_autocast_enabledZset_autocast_gpu_dtypewarningswarn_CZ_dynamoZ
eval_frameunsupportedTensorr   Z
resize_as_Z_tensor_convert__dict__valuesdistributedZis_availableextendZdistributed_c10dZ'dynamo_unsupported_distributed_c10d_ops)r)   ZdtypesZstorager   r   r   _disallowed_function_ids`   sX   
"
rW   c                  C   s<   t dddj} |  D ]\}}td| d|j d qd S )NTF)recordc_binding_only"z": ,)gen_allowed_objs_and_idsname_rule_mapitemsprintr+   )mkvr   r   r    dump_allowed_torch_name_rule_map   s   rc   c                   @   sV   e Zd ZU dZeeef ed< ee	 ed< ee	 ed< ee	 ed< eee	f ed< dS )AllowedObjectsa  
    Track the objects, object id - name pairs, and name - dynamo wrapping rule pairs
    from the heuristic defined in `gen_allowed_objs_and_ids`.
    TODO: Remove the overalp/duplication between these fields
    after allowed_functions refactor is done.
    
object_idsctx_mamager_classesc_binding_in_graph_functions non_c_binding_in_graph_functionsr]   N)
r+   r,   r-   r.   r   r/   r1   r0   r	   r   r   r   r   r   rd      s   
 rd   FTc                    sp  ddl m m tjdtdd t t t t 
t  fdddd	 		
fd
ddd fddt t	 t
jroddlm} |j|j|j|j|j|jfD ]
}t|t|< qdttjD ]}ttj|}t|tjtjfrd| t|< qtt D ]	}|v r|= qttfD ]}|j  d|j! t|< qt"
S )z=
    Walk torch.* and get the ids of all the stuff in it
    r   )TorchCtxManagerClassVariableTorchInGraphFunctionVariableignoretorch.distributed)categorymodulec                    sP   t t| tr"t| dr$t| dr& |j d| < |  d S d S d S d S )N	__enter____exit__.)
issubclassr4   hasattrr+   r'   r8   rn   name)ri   rf   torch_name_rule_mapr   r   heuristic_record_if_ctx_manager   s   zAgen_allowed_objs_and_ids.<locals>.heuristic_record_if_ctx_managerc                 S   s   t | o| tjjtjjhv S r   )r   r5   rO   Z_cuda_isCurrentStreamCapturingZ_graph_pool_handler8   r   r   r   is_special_functions   s   
z6gen_allowed_objs_and_ids.<locals>.is_special_functionsc                    s   z
t | dr	| j} W n	 ty   Y nw t| tjtjtjtjtj	fs'| rT |j
 d| < rAt | ds?|  d S d S t | drM|  d S |  d S d S )N__wrapped__rq   __code__)rs   rz   	Exceptionr   typesFunctionType
MethodTypeBuiltinFunctionTypeMethodDescriptorTypeWrapperDescriptorTyper+   r'   rt   )rj   rg   rY   ry   rh   rv   r   r   %heuristic_record_if_in_graph_function   s<   
	

zGgen_allowed_objs_and_ids.<locals>.heuristic_record_if_in_graph_functionc                    sv   d}g d}t jr|d tdd |D }t| }|d u r"dS |j t fdd|D r2dS  |v p: |S )	N)r5   rE   )>ztorch.optimztorch.nn.modules.rnnztorch._dynamoztorch._C._dynamoztorch._inductorztorch._C.inductorztorch.fxztorch._C._autogradztorch._C._cudartztorch._C._distributed_autogradztorch._C._distributed_c10dztorch._C._distributed_rpcztorch._C._functorchztorch._C._monitorztorch._C._nvtxztorch._C._lazyztorch._C._profilerztorch.__config__ztorch._custom_opztorch._dispatchztorch._exportz torch._functorch.make_functionalztorch._functorch.compile_utilsztorch._functorch.partitionersztorch._functorch.aot_autogradztorch._functorch.compilersztorch._functorch.fx_minifierztorch.autograd.profiler_utilztorch.autograd.profilerztorch._jit_internalztorch._libraryztorch._lobpcgztorch._loggingztorch._meta_registrationsztorch._namedtensor_internalsztorch._numpyztorch._sourcesztorch._subclassesztorch._tensorztorch._tensor_strztorch._utilsztorch._utils_internalztorch._vmap_internalsztorch.compilerrl   ztorch.exportz	torch.hubz	torch.jitztorch.libraryztorch.masked.maskedtensorztorch.nn.initztorch.nn.modules.moduleztorch.nn.parallelztorch.nn.utilsztorch.multiprocessingz
torch.onnxztorch.overridesztorch.packageztorch.profilerztorch.serializationztorch.storageztorch.utilsztorch.distributed.c                 S   s   g | ]}|d  qS )rq   r   r;   r   r   r   r9   ;  r>   zOgen_allowed_objs_and_ids.<locals>._is_allowed_module_prefix.<locals>.<listcomp>Fc                 3   s    | ]}  |V  qd S r   )
startswith)r7   r`   mod_namer   r   	<genexpr>B  s    zNgen_allowed_objs_and_ids.<locals>._is_allowed_module_prefix.<locals>.<genexpr>)	r   trace_distributedappendtuplerC   	getmoduler+   anyr   )r8   Zallowed_modulesZdisallowed_modulesZallowed_modules_dotrn   r   r   r   _is_allowed_module_prefix   s   @

z;gen_allowed_objs_and_ids.<locals>._is_allowed_module_prefixc                    s^  t  fddtjD rd S  jt < t j D ]\}}t|vrdd l}t	||j
jr2q||jjtj|jjtj|jjj|jfv rGqt	|tjrh|jdrg|rg j d| t|< | q|rrz| | | |  j d| t|< qt|d u rt|sr| | | |  j d| t|< qd S )Nc                 3   s    | ]	} j |V  qd S r   )r+   r   )r7   r   rn   r   r   r   H  s
    

zHgen_allowed_objs_and_ids.<locals>._find_torch_objects.<locals>.<genexpr>r   ztorch.rq   )r   r   Z*allowed_functions_module_string_ignorelistr+   r:   listrS   r^   Z
torch._opsr   _opsZHigherOrderOperatorfuncrH   deprecated_funcZvmapnnZ
functionalZ!triplet_margin_with_distance_lossZcondr}   
ModuleTyper   rC   r   r   )rn   ru   r8   r5   )_find_torch_objectsr   rw   r   rX   torch_object_idsr   r   r   G  sL   z5gen_allowed_objs_and_ids.<locals>._find_torch_objectsr   )_functional_collectives_implztorch.Tensor.rq   )#	variablesri   rj   rM   filterwarningsUserWarningr   r   r5   rE   r   r   Ztorch.distributedr   Z_all_gather_into_tensorZ_all_reduceZ_reduce_scatter_tensorZ_all_reduce_coalescedZ!_all_gather_into_tensor_coalescedZ _reduce_scatter_tensor_coalescedreprr:   dirrQ   getattrr   r}   r   r   rW   r   r   r,   r+   rd   )rX   rY   Zfcifru   methodr#   extrar   )ri   rj   r   r   rg   rY   rf   rw   r   ry   rh   rX   rv   r   r   r\      sX   	V0
r\   c                   C   s   t  jS r   )r\   re   r   r   r   r   _allowed_function_ids  s   r   c                  C   s   i } | S r   r   rvr   r   r   "_allowed_user_defined_function_ids  s   r   c                  C   st   dd t j D } | dd tj D  | dd tjtjfD  | tt	dtt
jdttjdi | S )Nc                 S   2   i | ]\}}| d st|rt|d| qS _z	builtins.r   callabler:   r7   ra   rb   r   r   r   
<dictcomp>      z)_builtin_function_ids.<locals>.<dictcomp>c                 S   r   )r   z	operator.r   r   r   r   r   r     r   c                 S   s   i | ]}t |d |j qS )z
functools.)r:   r+   )r7   rb   r   r   r   r     s    ztyping.castzfunctools.reducezcopy.deepcopy)builtinsrS   r^   updateoperator	itertoolschainislicer:   r   	functoolsreducerA   rB   r   r   r   r   _builtin_function_ids  s$   

r   c                     s2   t  } tD ] |  fdd j D  q| S )Nc                    sF   i | ]\}}t |r!t|d dp j jkrt| j d| qS )r,   Nrq   )r   r   r+   r:   r   modr   r   r     s    z'_numpy_function_ids.<locals>.<dictcomp>)r   r   r   rS   r^   r   r   r   r   _numpy_function_ids  s   
r   c                  C   s   dd t j D } | S )zC
    Collects constant builtins by eliminating callable items.
    c                 S   s2   i | ]\}}| d st|st|d| qS r   r   r   r   r   r   r     r   z)_builtin_constant_ids.<locals>.<dictcomp>)r   rS   r^   r   r   r   r   _builtin_constant_ids  s   r   _lazy_module_initru   	init_funcc                 C   sD   d| vsJ d|  | t jv r|  | tvsJ t|  | dS )z.Register a module without eagerly importing itrq   z%Expected a root module name, but got N)sysmodulesr   r   )ru   r   r   r   r   add_module_init_func  s
   
r   r8   c                 C   sR   t | dd }|d u rd S |dd }t|d }|d ur%|D ]}|  qd S d S )Nr,   rq   r   )r   splitr   pop)r8   rn   base_moduleZ
init_funcsfnr   r   r   _maybe_init_lazy_module  s   r   c                 C   sD   t |  t| tv rdS t| tv rdS t| tjjtjjtjj	fS )z&Is this safe to trace like torch.add ?FT)
r   r:   rW   r   r   r5   r   ZOpOverloadPacketZ
OpOverloadZ_OpNamespacerx   r   r   r   
is_allowed  s   r   c                 C   s   t |  t| tv S r   )r   r:   r   rx   r   r   r   is_user_defined_allowed     r   c                 C   s   t |  t| ddS )NZ_dynamo_forbiddenF)r   r   rx   r   r   r   is_forbidden  r   r   c                 C   s   t t| |S )z&Convert a torch.* function to a string)r   r&   r:   )r8   r$   r   r   r   torch_get_name  s   r   c                 C      t | tv S r   )r:   r   rx   r   r   r   is_builtin_callable     r   c                 C   r   r   )r:   r   rx   r   r   r   is_builtin_constant"  r   r   c                 C   s*   t d u rdS t| t jt jfpt| tv S )NF)r   r   ZndarrayZgenericr:   r   rx   r   r   r   is_numpy&  s   r   )r2   N)FT)Dr   r?   rA   dataclassesr   rC   r   rE   r   r   r}   rM   r   typingr   r   r   r   r   r   r	   r
   r   r   r0   numpyModuleNotFoundErrorr5   Ztorch._functorch.deprecatedZ
_functorch
deprecatedr   Ztorch.fx._symbolic_tracer    r   Zexternal_utilsr   utilsr   r   r   r   r/   rW   rc   	dataclassrd   r\   r1   r   r   r   r   r   r   r   r   objectr   boolr   r   r   r   r   r   r   r   r   r   r   <module>   sn   
 (-
9 p$