o
    #i                     @   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mZm	Z	 d dl
mZmZmZmZmZmZmZmZ d dlZd dlZd dlZd dlm  mZ d dlmZmZ d dl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)m*Z* d d	l+m,Z,m-Z-m.Z. d d
l/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZF d dlGmHZHmIZImJZJmKZK d dlLmMZMmNZN d dlOmPZP d dlmQZQ d dlRmSZS ddlTmUZU ddlVmWZWmXZXmYZYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZd eeefZge jhG dd dZie jhG d d! d!Zjei Zkejlejmejnejoejpejgejqerejsh	ek_ted"d# Zud$d% Zvd&d' Zwd(d) Zxd*d+ Zyd,d- Zzd.d/ Z{d0d1 Z|d2d3 Z}d4ej~jd5ej~jd6eeef fd7d8Zd9e,d:ead;eeeejejf f d6dfd<d=Zd>ejjd:ead6dfd?d@Zd4ej~jd5ejjd6dfdAdBZdCej~jd6eeef fdDdEZdFeeef dGeQdHeQdIeee[f d6eeZ f
dJdKZ		ddLdMdMdNdNdNdOdPedQeedRf dSeeeef  dTeeeeef ee ee f  dUeedRf dVedWedXedYedZed6ejjfd[d\Zd]d^ dMdMd_dCej~jd`e,fdadbZdCej~jd6eeejf fdcddZ	ddCej~jdQeedRf dSeeeef  d6ee fdedfZdgeej dheeejf d:ead;eeeejejf f fdidjZdkej~jd:ead;eeeejejf f fdldmZdnejjd6dfdodpZdnejjd6dfdqdrZd>ejjdseafdtduZdveXd6eeef fdwdxZdaeee  edy< daeeeef  edz< d{d| Zd}d~ Zedej~jfddZedd ZG dd dej~jZdddZdCej~jdQeedRf dSeeef dTeeeeef ee ee f  dUeedRf dedeeef deQdWedee defddZdCej~jdQeedRf dSeeef dTeeeeef ee ee f  dUeedRf dedeeef deQdWedee defddZeeW		ddNdLdMdMdMdMddCej~jdQeedRf dSeeeef  dTeeeeef ee ee f  dedUeedRf dedWedee ded6eXfddZdS )    N)contextmanagernullcontext)AnyCallableDictListOptionalSetTupleUnion)	UserErrorUserErrorType)_fakify_script_objects_gather_constant_attrsmake_constraintsmake_fake_inputsmake_fake_params_buffers$produce_guards_and_solve_constraints)_node_metadata_hook_set_node_metadata_hook)-_AddRuntimeAssertionsForInlineConstraintsPass)CollectTracepointsPass)ConstantAttrMaplift_constants_passrewrite_script_object_meta)placeholder_naming_passplaceholder_prefixes)SpecViolationError)_wrap_submodules)aot_export_moduledetect_fake_mode)FakeScriptObject)
FakeTensorFakeTensorMode)log_export_usage)_combine_args)
OutputKind)#first_call_function_nn_module_stack)ConstraintViolationErrorfree_unbacked_symbolsGuardOnDataDependentSymNodeShapeEnv)_PyTreeCodeGen_PyTreeInfo)insert_deferred_runtime_asserts)TreeSpec)ValueRangeError   )AutogradStateOpsFailSafeguard)_disable_prexisiting_fake_modeExportedProgram	InputKindModuleCallEntryModuleCallSignature)_sig_to_specsArgumentSpecConstantArgumentCustomObjArgumentExportGraphSignatureSymIntArgumentTensorArgumentTokenArgumentc                   @   s6   e Zd ZU dZdZeed< eje	dZ
ee ed< dS )ExportDynamoConfigz:
    Manage Export-specific configurations of Dynamo.
    T	allow_rnn)default_factoryreorderable_logging_functionsN)__name__
__module____qualname____doc__rB   bool__annotations__dataclassesfieldsetrD   r	   r    rN   rN   Q/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/torch/export/_trace.pyrA   U   s   
 rA   c                   @   s   e Zd ZU ejjed< eed< ee	e
ejeejf f ed< dZee ed< dZee ed< dZeee	ee	ejf f  ed< dS )ExportedArtifactgmsig	constantsNout_spec	fake_modemodule_call_specs)rE   rF   rG   torchfxGraphModulerJ   r=   r   strr   Tensorr"   ScriptObjectrT   r   r0   rU   r$   rV   pytreerN   rN   rN   rO   rP   a   s    
 &rP   c                  c   sf    t jjd} t jjd}zd V  W t jjj|   t jjj|  d S t jjj|   t jjj|  w NF)rW   backendsmkldnn	set_flagsnnpack)orig_mkldnn_flagorig_nnpack_flagrN   rN   rO   _ignore_backend_decomps   s   re   c                 C   s   dt |  S )N	L__self__)_strip_rootxrN   rN   rO   
_fixup_key   s   rj   c                 C   sB   t | tr| dr| tdd  }|dr|dd  S |S | S )N_export_root.r2   )
isinstancerZ   
startswithlen)ri   strippedrN   rN   rO   rg      s   rg   c              	   C   s   t | dkrEd}|( t|tjt|d t| |}W d    n1 s&w   Y  W d    n1 s5w   Y  |d us@J |j}d S d S )Nr   zFile "torch/_export/passes/add_runtime_assertions_for_constraints_pass.py", line 46, in _AddRuntimeAssertionsForInlineConstraintsPassstack_trace)ro   r   	functoolspartialr   r   graph_module)range_constraintsrQ   rU   rr   resrN   rN   rO   +_add_runtime_assertions_to_cond_in_subgraph   s    
rx   c              	   C   s   | j jD ]O}|jtjjjkrSd|jv rSt|jd }| j 	|+ | j j
dtjjj|j||jd dd}|j|_|| | j | W d    n1 sNw   Y  qd S )Npathcall_functionkind)ry   r{   )argskwargs)graphnodestargetrW   opshigher_order_export_tracepointr}   rg   inserting_beforecreate_noder|   metareplace_all_uses_with
erase_node)rQ   nodery   new_noderN   rN   rO   _rewrite_node   s&   
	
r   c                    s   t | }g | jjD ] }|jdkr*d|jv r*|jd }|d ur*t|tjr*| q
t	 }r4|}nt
t dd}t|dkrMt|dkrMdi ||fS d  fdd}ttj||}	ttj|j|}
ttjtj|jdd	|}|	|
||fS )
NplaceholdervalT)	shape_envexportr   rN   c                    s     } d7  |S )Nr2   rN   )ri   r   count	fake_inpsrN   rO   convert_to_fake   s   z/_convert_input_to_fake.<locals>.convert_to_fakestatic_shapes)_get_params_buffersr~   r   opr   rm   rW   r[   appendr!   r$   r,   ro   r]   tree_map_onlyfrom_tensorrs   rt   )rQ   r|   r}   params_buffersr   fake_valdetected_fake_moderU   r   	fake_argsfake_kwargsfake_params_buffersrN   r   rO   _convert_input_to_fake   s.   

r   c                 C   sX   |j D ]}|jtjtjfv r| |j |_q|jD ]}|jtjtj	fv r)| |j |_qd S N)
input_specsr{   r6   	PARAMETERBUFFERr   output_specsr'   BUFFER_MUTATIONGRADIENT_TO_PARAMETER)param_buffer_tablerR   specrN   rN   rO   _replace_param_buffer_names   s   

r   c                    sl   t | t |t   ks J dt |  dt | dt   d fdd| t |d  D }g ||R S )Nz,Total number of arg names is expected to be z	 but got z positional args, z kwargs.c                    s   g | ]} | qS rN   rN   ).0kw_namer}   rN   rO   
<listcomp>       z/_convert_to_positional_args.<locals>.<listcomp>)ro   )orig_arg_namesr|   r}   reordered_kwargsrN   r   rO   _convert_to_positional_args   s   r   c           
         s   d}t dd|}|  D ]l}t|tjjsq|jjD ]]}|j	dv r#qd}|j
di  }rVtt| \}}	t|	rOt|	tjjrO||krN|	|u rNd}nt|	tsVJ |rxdd	  |||jd
 |j fi|} fdd| D |j
d< qqd S )Nz	L['self']z[^a-zA-Z0-9]_r   outputTnn_module_stackFc                    sN   zg  G  fddd}t | dd| ii d W S  ty&   |  Y S w )Nc                       s$   e Zd Z fddZ fddZdS )z@_normalize_nn_module_stack.<locals>.normalize_path.<locals>.Pathc                    s     | | S r   )r   )selfnamepartsrN   rO   __getattr__  s   
zL_normalize_nn_module_stack.<locals>.normalize_path.<locals>.Path.__getattr__c                    s     t| | S r   )r   rZ   )r   idxr   rN   rO   __getitem__  s   zL_normalize_nn_module_stack.<locals>.normalize_path.<locals>.Path.__getitem__N)rE   rF   rG   r   r   rN   r   rN   rO   Path      r   Lr   rl   )evaljoin	Exception)ry   r   rN   r   rO   normalize_path  s   	z2_normalize_nn_module_stack.<locals>.normalize_pathrl   c                    s"   i | ]\}\}}| ||fqS rN   rN   )r   keyry   tyr   rN   rO   
<dictcomp>'  s    
z._normalize_nn_module_stack.<locals>.<dictcomp>)resubmodulesrm   rW   rX   rY   r~   r   r   r   getnextitervaluesinspectisclass
issubclassnnModulerZ   rF   rG   items)
gm_torch_levelroot_clsrootroot_keyrQ   r   add_rootr   ry   r   rN   r   rO   _normalize_nn_module_stack   s8   

r   original_moduletraced_modulereturnc                 C   s4  i }i }| j ddD ]\}}|t|g | q
| jddD ]\}}|t|g | q | D ]\}}|ddd ||< q4| D ]\}}|ddd ||< qFi }|j ddD ]\}	}
|	|vsfJ t|
|v rv|t|
  ||	< q\|jddD ]\}	}|	|vsJ t||v r|t|  ||	< q}|S )z
    Returns a mapping of parameter/buffer names from the new module to the
    original model. This is to help with restoring the FQN for parameter/buffers
    of a traced module to what the original module contains.
    Fremove_duplicateN)named_parameters
setdefaultidr   named_buffersr   pop)r   r   param_lookupbuffer_lookupr   parambufferfqnsr   dynamo_namedynamo_paramdynamo_bufferrN   rN   rO   _get_param_buffer_mapping-  s4   
r   orig_constant_attrsgraph_signaturerS   c                 C   s   i }|  D ]\}}|| v r| | ||< q|jD ]0}|jtjtjfv rH|j}|dus,J |||g}|d |_|| }	||= |D ]}
|	||
< qAqdS )zXRewrite the graph signature and constants table to use the FQN from the original module.Nr   )r   r   r{   r6   CONSTANT_TENSOR
CUSTOM_OBJr   r   )r   r   rS   remap_tabler   valuer   orig_targettargetsconstantr   rN   rN   rO   _remap_constantsV  s(   


r   rQ   c           
         s(  dd | j jD   fdd}ttj }ttj }i }|jD ]7}|jtjkrU|jj	
|sU|jj	
|rC|||jj	t|d  }n|||jj	 }|||jj	< ||j_	q|jD ]}|jj	|v ri||jj	 |j_	qY|  D ]#}t|tjjsxqn|j jD ]}	|	j	|v r||	j	  |	_	|	_q||  qndS )z\
    For strict mode, rename constants nodes that were previously annotated as buffers.
    c                 S   s   h | ]}|j qS rN   r   )r   r   rN   rN   rO   	<setcomp>y  s    z*_rename_constants_nodes.<locals>.<setcomp>c                    sR   |  v r"d}|  d|  } v r |d7 }|  d|  } v s|}   |  | S )Nr2   r   )add)r   ndup_name
node_namesrN   rO   rename_constant{  s   
z0_rename_constants_nodes.<locals>.rename_constantN)r~   r   r   r6   r   r   r   r{   argr   rn   ro   r   r   rm   rW   rX   rY   r   	recompile)
rQ   r   r  buffer_prefixconst_prefixbuffer_to_constantr   c_namemodr   rN   r   rO   _rename_constants_nodesq  s<   






r
  c                 C   s   t | |}| D ]\}}|dd||< q	| D ].\}}t||s$qt||}t|tjr=t|tjj	s=|
|| nt||| t|| q|jjD ]}|jdkr`|j}||v r`|| |_qM|  dS )zV
    Restores the state dict of the traced module to that of the original module.
    rl   r   get_attrN)r   r   replacehasattrgetattrrm   rW   r[   r   	Parameterregister_buffersetattrdelattrr~   r   r   r   r  )r   r   r   r   fqnattrr   	attr_namerN   rN   rO   _restore_state_dict  s$   




r  r	  c                 C   s   dd | j ddD S )Nc                 S   s   i | ]
\}}|t |jqS rN   )typerE   )r   r   mrN   rN   rO   r     s    z)_get_module_hierarchy.<locals>.<dictcomp>Fr   )named_modules)r	  rN   rN   rO   _get_module_hierarchy  s   
r  module_hierarchyin_specrT   module_call_signaturesc                    s>    fdd| D }|d j dksJ tg g ||d|d _|S )Nc                    s   g | ]}t | |d qS ))r  	signature)r7   r   )r   r  r  rN   rO   r     s    z+_make_module_call_graph.<locals>.<listcomp>r    )inputsoutputsr  rT   )r  r8   r  )r  r  rT   r  retrN   r  rO   _make_module_call_graph  s   
r$  rN   FT)preserve_module_call_signaturedisable_constraint_solver(_allow_complex_guards_as_runtime_assertsrestore_fqn_log_export_usagesame_signaturefr|   .r}   dynamic_shapesr%  r&  r'  r(  r)  r*  c                C   s|  |r	t ddhd t|tsttjdt| |pi }tjj	
ttz zCi }
t| ||
1 t  tjj| |dd|||||	d	|i |\}}W d   n1 sVw   Y  W d   n1 sew   Y  W n. ttfy } zttjt|d}~w ty } zttjd	t| d
dd}~ww W d   n1 sw   Y  |
|jd< t| tjjr|rt| | |S )z
    Traces either an nn.Module's forward function or just a callable with PyTorch
    operations inside and produce a torch.fx.GraphModule in torch IR.
    zexport.private_api_export_to_torch_ireventflagsAExpecting `args` to be a tuple of example positional inputs, got Tsymbolic)r,  assume_static_by_defaulttracing_moder&  +prefer_deferred_runtime_asserts_over_guardsr'  r)  r*  Nz5Consider annotating your code using torch._check*(). constrain_as_size_example)	case_namerV   )r%   rm   tupler   r   INVALID_INPUTr  rW   _dynamoconfigpatchrK   asdictDEFAULT_EXPORT_DYNAMO_CONFIGr   re   r   r)   r1   CONSTRAINT_VIOLATIONrZ   r+   ANTI_PATTERNr   r   r   r  )r+  r|   r}   r,  r%  r&  r'  r(  r)  r*  rV   r   r   erN   rN   rO   r-    sh   
 

r-  c                 C   s   | S r   rN   rh   rN   rN   rO   <lambda>(  s    rB  )	transformpre_dispatch_is_torch_jit_traceconstant_attrsc                   s  t j }t }	|s|rt }	tdd }
t jjjj	| |ddddM |	; t
 ( |
  |t| |d||d\} W d    n1 sEw   Y  W d    n1 sTw   Y  W d    n1 scw   Y  W d    n1 srw   Y  t| t jjrt| dr|j| j dtf fd	d
 jd u}t||f}d}t jt j t j }|jjD ] }|jdkr||kr|||  }t|t js||jd< |d7 }qtt j  j! j"t j# j$ j%|r jj&ni |r jj'ni |r jj(nd fddt)|jjD fddt)tt*t+t,|jjj-D  j j.d\}}t/||d}ddl0m1} ||}ddl2m3} |j4sld}t5|t6j7t8|d t9||j:dt;|j dd W d    n	1 sgw   Y  |rzddl<m=} |||}|> D ])}t|t jjsq~|jjD ]}|jdv r|j?dd  |j?dd  qq~t@|}|tA||| tB||| |||| tC|||S )Nc                  s   s2    t jj} zdt j_d V  W | t j_d S | t j_w )NT)rW   compiler_is_compiling_flag)	old_valuerN   rN   rO   _compiling_state_context4  s   z4_export_to_aten_ir.<locals>._compiling_state_contextT)tie_weightsstrictstack_weightsF)trace_jointrD  r}   r   r   c                    s  t |ttttd frtd|dS d|jv sJ | d|jd }| t jk r/t	|j
dS t |tr:t|j
dS t |tjrFt|j
dS t |tjrWt|j
|  dS t |trdt|j
|jdS t |tttttd frwt|j
|dS tdt| d)	Nr   )r   r   r   z8 is not a constant or a node with a 'val' metadata fieldr   )r   	class_fqnz*Encountered an unsupported object of type z0 while writing the metadata for exported program)rm   intrI   floatr  r;   r   ro   input_tokensr@   r   r#   r?   rW   SymIntr>   r\   r<   _typequalified_namer"   script_class_namerZ   AssertionError)ir   r   )r   rN   rO   make_argument_specT  s*   


z._export_to_aten_ir.<locals>.make_argument_specr   r   r   r2   c                    s$   g | ]\}}|j d kr ||qS )r   )r   r   rX  r   rY  rN   rO   r     s
    
z&_export_to_aten_ir.<locals>.<listcomp>c                    s   g | ]	\}} ||qS rN   rN   rZ  r[  rN   rO   r         )user_inputsinputs_to_parametersinputs_to_buffersuser_outputsbuffer_mutationsuser_input_mutationsgrad_paramsgrad_user_inputsloss_outputr!  r"  rR  output_tokens)r   r   r    )r;  zUFile "torch/fx/passes/runtime_assert.py", line 24, in insert_deferred_runtime_assertsrq   zexported program: )r   )replace_set_grad_with_hop_passr   r   rr   )DrW   _Cis_grad_enabledr   r3   r   r   utils	stateless_reparametrize_modulere   r   rm   rX   rY   r  r   updater:   backward_signaturer]   tree_leavesro   
parametersbuffersrR  r~   r   r   r[   r9   rM   r]  r^  r_  r`  buffers_to_mutateuser_inputs_to_mutategradients_to_parametersgradients_to_user_inputsre  	enumerater   r   reversedr|   rf  r=   torch._guardsr!   torch._dynamor;  do_not_emit_runtime_assertsr   rs   rt   r   r/   r   r(   3torch._export.passes.replace_set_grad_with_hop_passrg  r   r   r   r   r   rP   )r	  r   r   r   rF  rC  rD  rE  ri  grad_safe_guardrJ  rQ   is_joint	flat_argsindextotal_non_user_inputsr   user_argr   r   export_graph_signaturer!   rU   _dynamo_configrr   rg  _modrS   rN   )r   rY  rO   _export_to_aten_ir!  s   


   









r  c                 C   sD   i }| j ddD ]\}}|||< q| jddD ]\}}|||< q|S )NFr   )r   r   )r	  r   r   r   r   rN   rN   rO   r     s   

r   c                    s   t | j}|j| j}g }| D ]"\ }|j  jt jj	kr/|
 fddt|D  q|  q|rC|
dd | D  |S )a  
    Gets the argument names to forward that are used, for restoring the
    original signature when unlifting the exported program module.
    - Positional args: retain the original argument names, and enumerate
        *args as args_0, args_1, ...
    - Keyword args: retain the original kwarg names in the order specified
        by the user. This order seems to matter for the current state of
        export lifted modules.
    c                    s   g | ]\}}  d | qS )r   rN   )r   rX  r   r   rN   rO   r     s    z*_get_forward_arg_names.<locals>.<listcomp>c                 S   s   g | ]\}}|qS rN   rN   )r   kwargr   rN   rN   rO   r     r   )r   r  forwardbind_partial	argumentsr   rp  r{   _ParameterKindVAR_POSITIONALextendrv  r   )r	  r|   r}   rR   _argsnamesr   rN   r   rO   _get_forward_arg_names  s   r  orig_mod_bufferstraced_mod_buffersc                 C   sN   |j D ]!}|jtjkr$|jdusJ ||j }|| vr$tj|_|||j< qdS )zrDynamo erroneously marks tensor attributes on modules as a buffers.

    Rewrite them to be tensor constants.
    N)r   r{   r6   r   r   r   )r  r  r   rS   r   r   rN   rN   rO    _rewrite_dynamo_tensor_constants  s   



r  orig_modc                 C   sb   |   }|jD ]'}|jtjkr.|jdusJ |j|vr.|j|vs"J d|_| |j||j< qdS )zDynamo erroneously drops the persistent flag on buffers.

    Rewrite non-persistent buffers to reflect the original module.
    NF)
state_dictr   r{   r6   r   r   
persistent
get_buffer)r  r   rS   r  r   rN   rN   rO   _rewrite_non_persistent_buffers  s   	

r  ru   c              	   C   s   t | gt|   D ]e\}}t|tjjsq|jjD ]T}|j	dv rW|dkrV|j
dd }du r=td| d|j	 dtdd	 | D sVtd| d|j	 d
| q|j	dv ro|j
ddrotd| d|j	 dqqdS )a  
    Perform nn_module_stack checks on the graph.
    Current constraints:
        For the top level graph:
        - populated for 'call_function', 'get_attr'
        - None for 'placeholder', 'output'
        For submodule graphs:
        - None for 'placeholder', output'

    TODO(pianpwk): make this a consistent node-level check once nn_module_stack is populated for cond submodules.
    rz   r  r   r   NNode 	 of type z$ is missing nn_module_stack metadatac                 s   sF    | ]\}}t |tot |tot|d kotdd |D V  qdS )   c                 s   s    | ]}t |tV  qd S r   )rm   rZ   )r   ri   rN   rN   rO   	<genexpr>H  s    z4_verify_nn_module_stack.<locals>.<genexpr>.<genexpr>N)rm   rZ   r8  ro   allr   kvrN   rN   rO   r  D  s    


z*_verify_nn_module_stack.<locals>.<genexpr>z[ has incorrect nn_module_stack metadata formatexpected Dict[str, Tuple[str, str]], but got r   z7 contains nn_module_stack metadata, this should be None)rv  listr   rm   rW   rX   rY   r~   r   r   r   r   r   r  r   )ru   rX  r	  r   r   rN   rN   rO   _verify_nn_module_stack+  s:   

r  c              	   C   s   t | gt|   D ]L\}}t|tjjsq| jjD ];}|j	
dd}|jdv rA|du s@t|ts@td| d|j d| q|jdv rV|rVtd| d|j d| qqdS )	z
    Perform stack trace checks on the graph.
    Constraints:
        - None or non-empty str for 'call_function', 'get_attr'
        - None for 'placeholder', 'output'
    rr   Nr  r  r  zP has invalid stack_trace metadata, expected a string or None but instead found: r   zA contains stack_trace metadata, expected None but instead found: )rv  r  r   rm   rW   rX   rY   r~   r   r   r   r   rZ   r   )ru   rX  r	  r   rr   rN   rN   rO   _verify_stack_traceV  s.   

r  rR   c              	   C   s   dd |j D }|  D ]9}t|tjjsq|jjD ]*}|jdkrD|j	|vr'q||j	 }t
| }|j	|sDtd|j	 d| d| qqdS )a  
    Performs a sanity check on the placeholder node names.
    - User input nodes: no restrictions, should match the original forward() signature
    - Params/buffers/constants/custom_obj/token nodes: should start with prefixes defined in <placeholder_prefixes>
    c                 S   s   i | ]}|j j|jqS rN   )r  r   r{   )r   r   rN   rN   rO   r   v  s    z-_verify_placeholder_names.<locals>.<dictcomp>r   zPlaceholder node name z does not follow spec for z, name should have prefix: N)r   r   rm   rW   rX   rY   r~   r   r   r   r   rn   r   )rQ   rR   name_to_kindr	  r   	node_kindprefixrN   rN   rO   _verify_placeholder_namesp  s"   


r  epc                 C   s   d}t  }| j D ]9}t|tjjsq
|jjD ]*}|j	dkr q|d7 }t
|jds,J t
|jds4J ||jj d|jj  qq
||dS )Nr   rz   r2   rF   rE   rl   )op_countop_set)rM   ru   r   rm   rW   rX   rY   r~   r   r   r  r   r   rF   rE   )r  r  r  r  r   rN   rN   rO   get_ep_stats  s   

r  _EXPORT_FLAGS_EXPORT_MODULE_HIERARCHYc                    s   t   fdd}|S )Nc               
      s   zLz t   } | i |}t   }tdd|| tdt| W n$ tyE } zt|}|jd |j }td|t|td |d }~ww W d ad a	|S d ad a	w )Nzexport.time)r/  metricsr0  rl   zexport.error)r/  r  messager0  rN   )
timer%   r  r  r   r  rF   rG   rZ   r  )r|   r}   startr  endrA  t
error_typefnrN   rO   wrapper  s:   
z$_log_export_wrapper.<locals>.wrapper)rs   wraps)r  r  rN   r  rO   _log_export_wrapper  s   r  c                 C   s^   t | tttfs| f} nt | trt| } nt | tjtfr%|d u r%| f} |d u r+i }| |fS r   )rm   r8  r  dictrW   r[   )example_inputsexample_kwarg_inputsrN   rN   rO   $_process_jit_trace_inputs_for_export  s   

r  objc                 c   s4    | j }|| | j| _ z	dV  W || _ dS || _ w )znHelper method to make it easier to cleanly torch.export() a method on a
    module that is not `forward`.
    N)r  __get__	__class__)r  
new_methodoriginal_methodrN   rN   rO   patch_forward  s   r  c               	   c   s@    t j } t jd zd V  W t j|  d S t j|  w r^   )rW   rh  _jit_texpr_fuser_enabled_jit_set_texpr_fuser_enabled)original_staterN   rN   rO   _temp_disable_texpr_fuser  s   
r  c                       s$   e Zd Z fddZdd Z  ZS )_WrapperModulec                       t    || _d S r   )super__init__r+  )r   r+  r  rN   rO   r       

z_WrapperModule.__init__c                 O   s   | j |i |S r   )r+  )r   r|   r}   rN   rN   rO   r    s   z_WrapperModule.forwardrE   rF   rG   r  r  __classcell__rN   rN   r  rO   r    r   r  c              	   C   s"  t   ddlm} t||\}}t| |tjjfr,t| ||ddd	 W  d    S t| tj
rkt|  tjjtjjfrkt|  |  t|  ||ddd	 W  d    W  d    S 1 sew   Y  ntt| ||ddd	 W  d    S W d    d S 1 sw   Y  d S )Nr   )TopLevelTracedModuleFT)rL  rE  )r  torch.jit._tracer  r  rm   rW   rh  ScriptModule_exportmoduleScriptMethodownerr   r   r  r  )traced_callabler|   r}   r  export_argsexport_kwargsrN   rN   rO   "_convert_ts_to_export_experimental  sN   
"r  rD  original_state_dictorig_in_spec_disable_forced_specializationsrE  c           (   
   C   s  t | ||||d|dd}t|||\}}}}|jjD ]+}|jdkrEd|jvrEt||j}t|t	j
jsE|d us;J d|j|dd|jd< qi }|jjD ]}|j}|j}|jdkrt||}t|t	j
jr|jddd	D ]\}}|||d
 | < ql|jddd	D ]\}}|||d
 | < q|jdkrt||}t|t	jjs|||< |jdkrt|jt	jjs|jD ]}|jdkrt	jjjD ]}||v r|| ||j |< qqqL|j }}|d usJ |jttfvrttd |g}|jjjj}tt ||j!||j_|"  t#|t|  t$| }| t%|t&|||i |||d}W d    n	1 s&w   Y  |j'}|j(} |j)}!|* D ]}"|"+dd  |"+dd  q8|jjD ]O}|jdkr|j| j,v rw| j,|j }#|#|v rw||# - D ]
\}$}%|%|j|$< ql|j| j.v r| j.|j }&|&|v r||& - D ]
\}$}%|%|j|$< qqLt/t0| 1 t2| | |!d t3| |}'t4|'|  t5| | |! t6|| |! t7||  ||_8||_9|jd |_:|S )NF)r%  r(  r'  r)  r  r   zbCannot find dynamo_fake_mode. This could be due to the exported graph module have no placeholders.Tr   call_module)recurser   rl   rz   )rD  r   rr   r   )r  r  r   rS   rV   );r-  r   r~   r   r   r   r  r   rm   rW   r   r   r   r   r   rX   rY   _opsHigherOrderOperator_input_nodesproxy_COPY_META_FIELDS	_out_specr  r  r8  r]   r0   _codegenpytree_info	orig_argsr-   r.   _in_specr  r   r   r  r   rQ   rR   rS   r   r   r^  r   r_  r  rM   rq  r  r   r   r  r   r
  rT   rU   rV   )(r	  r|   r}   r,  r%  rD  r  r  r'  r  rE  r   r   r   r   dynamo_fake_moder   r  params_buffers_to_node_metar   r   	submoduler   r   r  entryrT   orig_out_specr   rF  aten_export_artifactrQ   r  rS   metadata
param_namer  r  buffer_namer   rN   rN   rO   _strict_export  s   

















r  c                    sB  d i fdd}t | ||||
|d\}}}}}t|t| }|= t| |||&\}}}} t||||||||
d} fdd|j D |_W d    n1 sUw   Y  W d    n1 sdw   Y  zt||j||||	|
d W n t	t
fy } zttjt|d }~ww t| |j|j |_||_|_|S )Nc                    s   d fdd	}|S )Nc                    s"  |pi }G fdddt jj}|| }dd D }t||  ||fd|i|\}}td| W d    n1 s?w   Y  tt|j	|_	tt|j
|_
tt|j|_tt|j|_tt|j|_|jjD ]}	d|	jv r|	jd }
dd	 tt|
 D |	jd< qp||fS )
Nc                       s(   e Zd Z fddZfddZ  ZS )z]_non_strict_export.<locals>._tuplify_outputs.<locals>._aot_export_non_strict.<locals>.Wrapperc                    r  r   )r  r  rk   )r   r	  r  rN   rO   r    r  zf_non_strict_export.<locals>._tuplify_outputs.<locals>._aot_export_non_strict.<locals>.Wrapper.__init__c                    s~   t | jtjjr,tjj  tj| jj|i |}W d    n1 s&w   Y  n| j|i |}t	
|\} t|S r   )rm   rk   rW   rX   rY   	tracebackpreserve_node_metaInterpreterrunr]   tree_flattenr8  )r   r|   r}   tree_out	flat_outsrT   rN   rO   r    s   ze_non_strict_export.<locals>._tuplify_outputs.<locals>._aot_export_non_strict.<locals>.Wrapper.forwardr  rN   r  r  rO   Wrapper  s    r  c                 S   s   g | ]}d | qS )z_export_root.rN   )r   rX  rN   rN   rO   r     s    z`_non_strict_export.<locals>._tuplify_outputs.<locals>._aot_export_non_strict.<locals>.<listcomp>r}   z%Exported program from AOTAutograd:
%sr   c                 S   s   i | ]	\}}t ||qS rN   )rj   )r   r   r   rN   rN   rO   r     r\  z`_non_strict_export.<locals>._tuplify_outputs.<locals>._aot_export_non_strict.<locals>.<dictcomp>)rW   r   r   r   logdebugr]   tree_maprg   rp  rq  r_  r^  rr  r~   r   r   r   )r	  r|   r}   r0  r  wrapped_modnew_preserved_call_signaturesrQ   rR   r   r   )
aot_exportrV   rT   r%  rN   rO   _aot_export_non_strict  s<   

zL_non_strict_export.<locals>._tuplify_outputs.<locals>._aot_export_non_strictr   rN   )r  r  )rV   rT   r%  )r  rO   _tuplify_outputs  s   3z,_non_strict_export.<locals>._tuplify_outputs)rE  r'  )rD  rC  rE  c                    s(   i | ]\}}|t |tr | n|qS rN   )rm   r"   )r   r  r  )map_fake_to_realrN   rO   r   0  s    z&_non_strict_export.<locals>.<dictcomp>)r  rE  )r   r   r   r   r  rS   r   r   rQ   r)   r1   r   r   r?  rZ   r  rR   rT   rU   rV   )r	  r|   r}   r,  r%  rD  r  r  r'  r  rE  r  rU   r   r   equalities_inputsoriginal_signaturer   patched_modnew_fake_argsnew_fake_kwargsnew_fake_constant_attrsr  rA  rN   )r  rV   rT   r%  rO   _non_strict_export  s|   <



	
r  )rL  r%  rD  r'  r  rE  rL  c                 C   sf  t |tsttjdt| |r|rttjdt| at }
|
	|r'dnd |
	|r0dnd t
d|
d |
a|p>i }t |tjjrM|| ||}t||f\}}| jd	d
}|	set| ||}nd}|rktnt}|| ||||||||||	}|j}|j}|j}|j}|j}|j}||jd< dd |jj D |jd< t dd t!|j"D t#|j"}t$| |||	d}t%|||||}|rt&||| i }| D ]\}}|st'|n|}t(dg g d|||< qt#|dkr|st)| t*|||}|dusJ |j+}|dusJ t,| t-| |	st.|| t/||j0|||t1t|||||f|jd}|S )a  
    Traces either an nn.Module's forward function or just a callable with PyTorch
    operations inside and produce a ExportedProgram.

    Args:
        f: the `nn.Module` to trace.

        args: example positional inputs.

        kwargs: optional example keyword inputs.

        dynamic_shapes:
         An optional argument where the type should either be:
         1) a dict from argument names of ``f`` to their dynamic shape specifications,
         2) a tuple that specifies dynamic shape specifications for each input in original order.
         If you are specifying dynamism on keyword args, you will need to pass them in the order that
         is defined in the original function signature.

         The dynamic shape of a tensor argument can be specified as either
         (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is
         not required to include static dimension indices in this dict, but when they are,
         they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None,
         where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions
         are denoted by None. Arguments that are dicts or tuples / lists of tensors are
         recursively specified by using mappings or sequences of contained specifications.

        preserve_module_call_signature: A list of submodule paths for which the original
            calling conventions are preserved as metadata.

        _allow_complex_guards_as_runtime_asserts:
         With the current dynamic shapes language for dims and derived dims, we can run into constraints
         that are not expressible with the language. For example, flattening a matrix and adding to a vector,
         both fully dynamic (i.e. x.reshape([-1]) + y) emits a guard s0 * s1 = s2, which is not expressible.
         By default, we either raise a constraint violation error or specialize to static values.
         If this flag is set to True, we avoid erroring out and instead allow complex constraints to exist as runtime
         assertions in the graph. The sympy interpreter (torch/utils/_sympy/interp.py) will produce the math ops
         required to compute and assert the value of the guard (e.g. sym_size_int, eq, _assert_scalar).
         Additionally, if TORCH_DYNAMO_DO_NOT_EMIT_RUNTIME_ASSERTS=1 is specified, we will allow complex constraints
         while not emitting runtime asserts, returning a cleaner graph with lesser guarantees around dynamic shapes.

        _disable_forced_specializations:
         Similar to _allow_complex_guards_as_runtime_asserts, but only avoids specializing to static values if set to True.
         For complex guards that don't specialize, this flag doesn't have any effect. Ideally this would be subsumed by
         _allow_complex_guards_as_runtime_asserts, but this handles one additional case: single-variable equalities where
         the symbol is solvable for a concrete value (e.g. Eq(s0 // 4, 400) -> s0 = 1600). If set to True, this flag will
         avoid specializations. Direct equalities (e.g. s0 = 4), will still specialize.

    Returns:
        An ExportedProgram containing the traced method.
    r1  zL_disable_forced_specializations can be only be specified in non-strict mode.rL  
non_strictrD  aot_dispatchzexport.enterr.  T)	keep_varsNforward_arg_namesc                 S   s   i | ]\}}t |r||qS rN   )r*   r  rN   rN   rO   r     s    z_export.<locals>.<dictcomp>inline_constraintsc                 s   s$    | ]\}}|j tjkr|V  qd S r   )r{   r6   
USER_INPUT)r   rX  srN   rN   rO   r    s    z_export.<locals>.<genexpr>)rE  )r!  r"  r   )r   r~   r   r  rv   module_call_graphr  rS   rN   )2rm   r8  r   r   r9  r  r  r  rM   r   r%   r  rW   r   ShapesCollectionr,  r]   r  r  r  r  r  rQ   rR   rT   rS   rU   rV   r   r   var_to_ranger   r   rv  r   ro   r&   r   rx   rg   r8   r   r   ru   r  r  r  r5   r~   r$  ) r	  r|   r}   r,  rL  r%  rD  r'  r  rE  r0  r~  r  r  r  export_funcr  rQ   r  rT   rS   rU   rV   
num_liftedcombined_argsrv   r  r  specsmod_fqnrw   exported_programrN   rN   rO   r  L  s   
A


r  )NNr   )rK   rs   r   loggingr   r  warnings
contextlibr   r   typingr   r   r   r   r   r	   r
   r   rW   ry  torch.fxtorch.utils._pytreerj  _pytreer]   torch._dynamo.excr   r   torch._export.non_strict_utilsr   r   r   r   r   r   (torch._export.passes._node_metadata_hookr   r   @torch._export.passes.add_runtime_assertions_for_constraints_passr   -torch._export.passes.collect_tracepoints_passr   (torch._export.passes.lift_constants_passr   r   r   torch._export.utilsr   r   torch._export.verifierr   torch._export.wrappersr   torch._functorch.aot_autogradr   rx  r!   "torch._library.fake_class_registryr"   torch._subclasses.fake_tensorr#   r$   torch._utils_internalr%   torch.export.dynamic_shapesr&   torch.export.exported_programr'   torch.fx._utilsr(   %torch.fx.experimental.symbolic_shapesr)   r*   r+   r,   torch.fx.graphr-   r.   torch.fx.passes.runtime_assertr/   r0   torch.utils._sympy.value_rangesr1   
_safeguardr3   r  r4   r5   r6   r7   r8   r   r9   r:   r;   r<   r=   r>   r?   r@   	getLoggerrE   r  	dataclassrA   rP   r>  criticalr  error	exceptioninfowarningprintwarnrD   re   rj   rg   rx   r   r   r   r   r   r   r   rZ   r   r[   r\   r   rX   rY   r
  r  r  r$  rI   r-  r  r   r  r  r  r  r  r  r  r  rJ   r  r  r  r  r  r  r  r  r  r  rN   rN   rN   rO   <module>   s  
( (


$3

)

1
$



 
	

K
  9



+!
	
	%

 

	

 /

 

	

 
 
	
