
    qi                        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	 d dl
mZmZmZmZ d dlZd dlZd dlZd dlmc mZ d dlmZ d dlmZmZmZ d dlmZmZ d d	l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* d dlm+Z+ d dl,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6 d dlm7Z7 erd dl8m9Z9  ejt                  e;      Z<de/dedef   dedefdZ=g dZ>de?de?fdZ@	 d=dej                  j                  dej                  j                  fdZCdej                  j                  ddfd ZD G d! d"ej                  j                        ZG ed#d$d%g      ZH G d& d'ej                  j                        ZJd(ej                  j                  d)ed*ed+   d,ededed-eeeKe?ef   eLe   eMe   f      fd.ZNd/ej                  j                  ddfd0ZO e	d12       G d3 d4             ZPd5ed6edeLedf   deKe?ef   dePf
d7ZQd8 ZR	 d>d6edef   d9eeMe*      dedef   fd:ZSddd;d6edef   d9eeMe*      d-eeeKe?ef   eLe   eMe   f      dedej                  j                  f   fd<ZTy)?    N)
namedtuple)Callable)	dataclass)AnyOptionalTYPE_CHECKINGUnion)enable_python_dispatcher)CaptureOutputfullgraph_captureget_traced_fn)argument_namescheck_user_input_output)UserErrorType)dynamo_timedget_metrics_context)_compiling_state_context)TracingContext)_RelaxedConstraint
Constraint)Node)make_fx)ConstraintViolationError
DimDynamicShapeEnvStatelessSymbolicContext)_ExportCodeGen_PyTreeCodeGen_PyTreeInfo)TreeSpec)FakeTensorModeconstraint_violation_errorfunc.argskwargsc                     ddl m}m} t        j                  |      } |||f|      }| j
                  r || j
                  d   |      f| _        | S )z
    Because we trace a different callable, the sources are all messed up.
    Manually patch them so the error message looks correct.
    r   )_get_input_paths_replace_sources)torch.export._unliftr'   r(   inspect	signaturer$   )r"   r#   r$   r%   r'   r(   orig_sigflat_input_pathss           e/home/ubuntu/crypto_trading_bot/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.pypost_process_error_msgr/   *   s\     H  &H'vA!&&7<<Q?AQR+
"' &%    ))__export_root__)z_export_root. )z._export_rootr3   textreturnc                 J    | }t         D ]  \  }}|j                  ||      } |S )z;Generic utility to clean export_root patterns from strings.)EXPORT_ROOT_REPLACEMENTSreplace)r4   resultpatternreplacements       r.   clean_export_root_stringr<   F   s0    F 8 656Mr0   graph_modulec                    fd}d }| j                   j                  D ]  }d|j                  v r0 ||j                  d   j                               |j                  d<   |j                  j	                  dd      }|s` ||j                               |j                  d<    d| j                  v rMi }| j                  d   j                         D ]  \  }}t        |      |t        |      <    || j                  d<   | S )a  
    Clean up nn_module_stack metadata by removing export_root references.

    Removes the _export_root module references from nn_module_stack metadata
    in graph nodes, which are artifacts from the export process. Fixes two patterns:

    1. Keys: Removes "__export_root_" and "__modules['_export_root']_" prefixes
       - Normal case: "L__self____export_root_child" -> "L__self__child"
       - inline_builtin case: Uses numeric ID strings like "140468831433840"

    2. Values: Removes "._export_root" and "._modules['_export_root']" from child names
       e.g., "L['self']._export_root.child" -> "L['self'].child"
       e.g., "L['self']._modules['_export_root'].child" -> "L['self'].child"

    Also removes the root export entry "L__self____export_root" entirely.

    Args:
        graph_module: The GraphModule to clean up
        is_inline_builtin: If True, keys are numeric ID strings and self references
                          (L['self']) are filtered out

    Returns:
        The cleaned GraphModule (modified in-place)
    c                     d| v r| d= i }| j                         D ]-  \  }\  }}t        |      }t        |      }r|dk(  r'||f||<   / |S )NL__self____export_rootz	L['self'])itemsr<   )nn_module_stackcleaned_stackkey
child_namechild_class	clean_key
clean_nameis_inline_builtins          r.   _process_nn_module_stackzEclean_nn_module_stack_and_source_fn.<locals>._process_nn_module_stackj   s{    #6 89 .=.C.C.E 	A*C**k05I 2*=J !Z;%>(2K'@M)$	A r0   c                    g }| D ]w  }t        |t              rTt        |      dk(  rF|\  }}t        |t              rt	        |      }|j                  ||f       U|j                  |       g|j                  |       y |S )N   )
isinstancetuplelenstrr<   append)source_fn_stackrC   itemnameclsrH   s         r.   _process_source_fnz?clean_nn_module_stack_and_source_fn.<locals>._process_source_fn~   s~    # 		+D$&3t9> 	cdC(!9$!?J!((*c):;!((.$$T*		+ r0   rB   rR   N dynamo_flat_name_to_original_fqn)graphnodesmetacopygetrA   r<   )	r=   rI   rJ   rV   noderR   clean_name_to_original_fqn	flat_nameoriginal_fqns	    `       r.   #clean_nn_module_stack_and_source_fnra   N   s   8( ""(( V		)+C		+,113,DII'( ))--(94@+=o>R>R>T+UDII'(V *\->->>%'"'3'8'8.(

%'	#I| )6 ''?	'JK	 ' 	<= r0   c                 J   i }| j                   j                  D ]  }|j                  dk(  r|j                  }t	        |      }||k7  r||_        t        | |      sJ t        j                  j                  j                  | |      }t        j                  j                  j                  || |       t        j                  j                  j                  | |       |j                  dk(  s|j                  }t        |t              sJ t	        |      }t        |t              sJ t	        |j                        }||k(  r*||v r||   |_        ||_        A| j                  |      }| j!                  |       | j#                  ||       ||_        ||_        |||<    y)z3Remove export_root artifacts from FX graph in-placeget_attrcall_moduleN)rX   rY   optargetr<   hasattrtorchfxr=   	_get_attr_assign_attr	_del_attrrM   rP   rT   get_submoduledelete_submoduleadd_submodule)r=   clean_named_module_mapr]   
old_target
new_targetparamnew_namerf   s           r.   clean_export_rootru      sw   
 .0 ""(( <77j J1*=JZ'(|Z888--77jQ%%225,
S%%//jI77m#Jj#...1*=Jj#.../		:HZ' 334Z@$	!//
;F))*5&&z6:$DK DI1;":.?<r0   c                   <     e Zd Zdededdf fdZdeddfdZ xZS )	ModuleToTracefooin_specr5   Nc                 >    t         |           || _        || _        y N)super__init___export_rootry   )selfrx   ry   	__class__s      r.   r}   zModuleToTrace.__init__   s    r0   	flat_argsExportTracerOutputc                     t        j                  || j                        \  }} | j                  |i |}t        j                  |      \  }}t        ||      S r{   )pytreetree_unflattenry   r~   tree_flattenr   )r   r   r$   r%   resout_flatout_specs          r.   forwardzModuleToTrace.forward   sU    ,,YEfd00#005(!(H55r0   )__name__
__module____qualname__r   r}   r   __classcell__r   s   @r.   rw   rw      s1    C # $ 
6# 6*> 6r0   rw   r   r   r   c                   "    e Zd ZdZ	 ddej
                  j                  dee   dee	e
      dee
e
f   dee
eeef   f   dee   d	df fd
Zd fdZddZd	ef fdZd	ef fdZded	ef fdZd	ej
                  j                  f fdZ xZS )DynamoGraphTransformerzZGraph transformer for dynamo export that flattens inputs/outputs without complex matching.Nmoduleflat_inputsflat_args_dynamic_dimsgraph_input_ordergraph_output_map	fake_moder5   c                    t         |   |       t        |      t        |      k(  sJ || _        || _        || _        || _        || _        |j                  j                  D cg c]  }|j                  dk(  s| c}| _        t        d |j                  j                  D              | _        i | _        | j                          i | _        | j#                          y c c}w )Nplaceholderc              3   @   K   | ]  }|j                   d k(  s|  yw)outputN)re   ).0ns     r.   	<genexpr>z2DynamoGraphTransformer.__init__.<locals>.<genexpr>   s     RaAQRs   )r|   r}   rO   r   r   r   r   r   rX   rY   re   placeholdersnextoutput_nodenew_input_nodes_create_flattened_inputsold_to_new_mapping_create_placeholder_mapping)	r   r   r   r   r   r   r   r   r   s	           r.   r}   zDynamoGraphTransformer.__init__   s     	 )*c+.>>>>&&<#!2 0" )/(:(:T1addm>SQTR6<<+=+=RR :<%%' #%((* Us   %C :C c                    t        t        | j                              D ]%  }t        |   d| di       }|| j
                  v rw| j
                  |   }|t        | j                        k  rP| j                  |   }|j                  j                         D ]$  \  }}|dk7  s||j                  j                  |<   & | j                  t        | j                  |   t        j                        r| j                  j                  | j                  |   t        t        t        | j                  |   j                               D cg c]3  }|| j"                  |   v rt$        j&                  nt$        j(                  5 c}dgt        | j                  |   j                         z              |j                  j                  d<   npt+        | j                  |   d      r1| j                  |   j,                  |j                  j                  d<   n&| j                  |   |j                  j                  d<   || j.                  |<   ( yc c}w )zKCreate new placeholder nodes for flattened inputs with proper fake tensors.arg_ valN)dynamic_sizesconstraint_sizes)symbolic_context)rangerO   r   r|   r   r   r   rZ   rA   r]   r   rM   rh   Tensorfrom_tensorr   shaper   r   DYNAMICSTATICrg   r   r   )	r   ir   graph_placeholder_idxorig_placeholderrD   valuedr   s	           r.   r   z/DynamoGraphTransformer._create_flattened_inputs  s!   s4++,- &	2A'-QCj"bAK D***(,(>(>q(A%(3t/@/@+AA'+'8'89N'O$&6&;&;&A&A&C ?
U%<9>K,,11#6?
 ~~)j  #U\\/ 04~~/I/I$$Q'%= &+3t/?/?/B/H/H+I%J' !" $%(C(CA(F#F !+ 2 2%/%6%6!7' +/#d6F6Fq6I6O6O2P)P
& 0J 0  %%e, ))!,e4/3/?/?/B/F/F  %%e,/3/?/?/B  %%e, '2D  #M&	2*'s   8I
c                     | j                   j                         D ]K  \  }}|t        | j                        k  s| j                  |   }| j                  |   }|| j
                  |<   M y)z1Create mapping from old placeholders to new ones.N)r   rA   rO   r   r   r   )r   user_input_idxr   old_placeholdernew_placeholders        r.   r   z2DynamoGraphTransformer._create_placeholder_mapping-  sn     6:5K5K5Q5Q5S 	K1N1$s4+<+<'=="&"3"34I"J"&"6"6~"F;J''8		Kr0   c                    | j                   | j                  v r| j                  | j                      }dD ]K  }|| j                   j                  v s| j                   j                  |   |j                  j                  |<   M d| j                   j                  v rHd|j                  j                  vr0| j                   j                  d   |j                  j                  d<   |S t        |   |||      S )z1Replace old placeholders with new flattened ones.)tensor_dictexample_valueunbacked_bindingsr   )current_noder   rZ   r]   r|   r   )r   rf   r$   r%   new_argrD   r   s         r.   r   z"DynamoGraphTransformer.placeholder7  s      7 77--d.?.?@G M I$++000-1->->-C-CC-HGLL%%c*I
 ))...5@Q@Q3Q+/+<+<+A+A%+H!!%(N 7&vtV<<r0   c                 ~   |d   }g }t        | j                  j                               D ]u  }| j                  |   \  }}|dk(  r|j                  ||          /|dk(  r+|j                  }	|j                  | j
                  |	          _|dk(  se|j                  |       w t        
|   |t        |      fi       S )z/Transform output according to graph_output_map.r   	graph_outinputconstant)	sortedr   keysrQ   indexr   r|   r   rN   )r   rf   r$   r%   original_outputsnew_outputsr   output_typer   	input_idxr   s             r.   r   zDynamoGraphTransformer.outputK  s    7 --2245 		(A#44Q7Kk)""#3C#89'II	""4#7#7	#BC
*""3'		( w~fu['9&;R@@r0   r]   c                 `   || _         t        | 	  |      }t        |d      r|j                  |ur|dD ]7  }||j
                  v s|j
                  |   |j                  j
                  |<   9 |j                  dk7  r1t        |d      r%|j                  j                  |j                         |S )z.Run node transformation and preserve metadata.r]   )r   r   r   r   rT   )	r   r|   run_noderg   r]   rZ   re   _renamerT   )r   r]   r9   rD   r   s       r.   r   zDynamoGraphTransformer.run_node^  s     !$' 66"v{{$'>D ;$))#,0IIcNFKK$$S);
 ww("wtV'<##DII.r0   c                 H   t         |          }t        | j                  d      r|d| j                  j                  v r&| j                  j                  d   |j                  d<   d| j                  j                  v r&| j                  j                  d   |j                  d<   |S )z:Perform the graph transformation and copy module metadata.rZ   rW   dynamo_compile_id)r|   	transformrg   r   rZ   )r   	result_gmr   s     r.   r   z DynamoGraphTransformer.transformo  s    G%'	 4;;'1T[[5E5EEEI[[EUEU6F	AB
 #dkk&6&666:kk6F6F'7	23
 r0   r{   )r5   N)r   r   r   __doc__rh   ri   GraphModulelistr   setintdictrN   rP   r   r}   r   r   r   r   r   r   r   r   r   s   @r.   r   r      s    d $(+$$+ #Y+ !%SX	+
  S>+ sE#s(O34+ C=+ 
+>(2TK=3 =(Ac A&T c "588//  r0   r   module_to_traceorig_callabler   r!   graph_capture_outputdynamic_shapesc           	         d }	 t        |       \  }}	|j                  j                  |j                         t        |dd       x}`|j                  x}Qt        | j                  t        j                  j                  t        j                  j                  z        s|j                          |j                         }|j                  t!        j"                  |      |||      }|r.|j$                  r|j$                  d   |z   f|_        n-|f|_        n$|rt	        |      }nt&        j)                  d|       |j*                  D ]]  }t        |t,        j.                        st	        dj1                  t3        j4                  |j6                  |                d| d      }_ |rt9        ||||      }|y # t        $ r}
|
}Y d }
~
d }
~
ww xY w)N	shape_envr   z#Summary of dimension constraints:%sr3   zk
It appears that you're trying to set a constraint on a value which we evaluated to have a static value of z0. Set TORCH_LOGS="+export" for more information.)r   r   build_guards__code__r   getattrdim_constraintsrM   r   rh   _opsOpOverloadPacket
OpOverloadsolveforced_specializationsprettify_resultsr*   r+   r$   loginfovar_to_rangesympyIntegerjoin	tracebackformat_listvar_to_stackr/   )r   r   r   r   r$   r%   r   r"   fnr2   er   r   r   msgks                   r.   &_suggest_or_raise_constraint_violationr     s    "&'o.A11>>r{{K
 id;	;H ) 9 99_F##JJ''%***?*??

 	!0!G!G!I..m,&"	
 &)...33A6<3*/ 47&*/%-Ec-J*9 '' 	A!U]]+-Ewwy44Y5K5KA5NOPQ RJJK MEE.*	 "%;&tV&
" )(	 "_ $ '%&"'s   3F: :	GGG
shuffle_gmc                     | j                   j                          | j                          t        | j	                               D ]  \  }}t        | |       t        | ||         y r{   )rX   eliminate_dead_code	recompiler   named_buffersdelattrsetattr)r   rT   buffers      r.   _normalize_shuffle_graphr     sW    ((*Z5578 *f
D!
D&)*r0   T)frozenc                       e Zd ZU ej                  j
                  ed<   eed<   ej                  j
                  ed<   eed<   eed<   ej                  j
                  ed<   dZ	e
ej                  j                     ed<   y)	PyTreeifyOutputr=   ry   in_shuffle_graphnum_flat_argsr   out_shuffle_graphNroot)r   r   r   rh   ri   r   __annotations__r    r   r  r   nnModuler   r0   r.   r  r    s[    ((&&&hh***xx+++&*D(588??
#*r0   r  outmodc           	           j                   J  j                   }d}t        t        j                  j                        r	f|z   }}n1t        j                        rj                  f|z   }j                  }t        j                  ||f      \  t        j                  j                  j                  |rdndd t        j                          j                  j                    G d dt"               G  fddt        j                  j                        }t        j                  j$                  j'                        rj(                  t+               _         t-         |       dd	
       }t/        |       t1        t3        t5        |j6                  j8                  j:                                     G  fddt        j                  j                        } |       }	g t        j<                  t        j>                  j@                  fdjB                  d         }
t        j                  j$                  j'                  |
      rj(                  t+               _        tE               5   t-        |	dd	
      |
 }ddd       t/               |	jF                  J tI        |j6                  |tK              |	jF                  ||      S # 1 sw Y   QxY w)a  
    Given a dynamo capture output, return a callable graph module that
    contain the following information:
    1. input/output pytree spec
    2. input/output shuffle functions
    Input shuffle functions are the converters taking pytree falttened inputs
    and reorder them to the calling convention of dynamo raw graph module.
    Output shuffle functions are the converters taking the outputs of the
    dynamo raw graph module and convert them to the pytree format.

    This function will replay any side effects that happened during the bytecode,
    so it is important to check against side effects before calling this function.
    N   r   c                       e Zd Zy)pytreeify.<locals>.YieldN)r   r   r   r   r0   r.   Yieldr    s    r0   r  c                   4     e Zd Z fdZfdZ xZS )pytreeify.<locals>.InShufflec                 ^    t         |           | _        t              | _        d | _        y r{   )r|   r}   r  rO   
num_inputs	gm_inputs)r   r   flat_real_argsr  s    r.   r}   z%pytreeify.<locals>.InShuffle.__init__  s(    GDH!.1DO!DNr0   c                      t        j                  t         j                        D cg c]  }||   	 c}      \  }} fd}	  	j	                  |      |i | t        c c}w # $ r  j
                  J  j
                  cY S w xY w)Nc                      | _         r{   )r  )example_inputsr  r   s    r.   backend_dummyz;pytreeify.<locals>.InShuffle.forward.<locals>.backend_dummy  s    !/r0   compiled_fnextra_globals)r   r   r   r  forward_callabler  RuntimeError)
r   flat_proxy_argsr   r$   r%   r  r  	f_globalsry   r  s
   `     r.   r   z$pytreeify.<locals>.InShuffle.forward	  s    !00-24??-CD#DgLD&&$$ -Y % #!#  E  &~~111~~%&s   A&A+ +BBr   r   r   r}   r   r   )r   r  r"  r  ry   r  r  s   @r.   	InShuffler    s    	"	 	r0   r$  symbolicT)tracing_modeproxy_module_inputsc                   2     e Zd Z fdZfdZ xZS )pytreeify.<locals>.OutShufflec                     t         |           t              | _        t        j                  d         | _        d | _        y )Nr   )r|   r}   rO   r  r$   num_outputsr   )r   r   r  r   s    r.   r}   z&pytreeify.<locals>.OutShuffle.__init__&  s9    G!.1DO";#3#3A#67D04DMr0   c                     t        j                  t         j                        D cg c]  }|   	 c}	      \  }} fd} 
j	                  |      |i |}t        j
                  |      \  } _        |S c c}w )Nc                  t    t        j                        D cg c]  }j                  |z       c}S c c}w r{   )r   r+  r  )r  r   r!  r   s     r.   r  z<pytreeify.<locals>.OutShuffle.forward.<locals>.backend_dummy2  s>     #4#3#34 $DOOa$78  s   5r  )r   r   r   r  r  r   r   )r   r!  r   r$   r%   r  resultsretr"  ry   r  s   ``      r.   r   z%pytreeify.<locals>.OutShuffle.forward-  s    !00-24??-CD#DgLD&c**) + G "(!4!4W!=CJ Es   A?r#  )r   r"  r  ry   r  r   s   @r.   
OutShuffler)  %  s    	5	 	r0   r0  c                 b    rj                  | j                  d         S | j                  d   S )Nr   )r   rZ   )xr   s    r.   <lambda>zpytreeify.<locals>.<lambda>C  s2      ++AFF?,CD ( r0   real)r  )&backend_inputrM   rh   r	  r
  r*   ismethod__self__r   r   _dynamo
eval_framer   r   INVALID_INPUTr   r"  	Exceptionutilsdetect_fake_moder   r   r   r   r   iterreversedr=   rX   rY   tree_map_onlyri   r   r$   r
   r   r  rO   )r  r  r$   r%   r5  r  r$  r  r0  out_shuffleflat_out_shuffle_argsr  r  r"  r   r  ry   r   s   ``          @@@@@@r.   	pytreeifyrC    s     (((%%MD#uxx'v}			#	%||$114.ANG	MM44Dqa)*M,G,G ((22I	  EHHOO 2 ##44^DIY((0&j	w*$ -.tH]%?%?%E%E%K%KLMNK UXX__ 2 ,K						HHMM) Q

	 ##445JKIY((0&j		!	# "
Gf$
 "" ./+++""N " "s   K22K;c                     | j                   j                  D ].  }|j                  dk(  s|j                  d   |j                  d<   0 y )Nr   r   r   )rX   rY   re   rZ   )gmr]   s     r.   normalize_graph_modulerF  ^  s<     :77m##yy9DIIe:r0   constraintsc                 <     dt         dt         dt         f fd}|S )Nr$   r%   r5   c            
      6	   t         j                  j                  j                  rJ t         j                  j                  j	                  d      5  t               5  t        d      5  t        | |      }d d d        d d d        d d d        t        | |      }|j                  t        |j                        D cg c]+  }j                  j                  j                  d| d       - }}t        t!        t#        t%        j&                        | |      |j(                  |j*                        |j,                  |j.                  |t1        |j2                  t         j4                  j6                        rn|j2                        j                  _        t;               |j2                  }|j2                  j<                  j?                         _        |j2                  j@                  j?                         _         tC        fd|j2                  jD                  D              sJ jD                  jG                  |j2                  jD                         |j2                  jH                  j?                         _$        tJ        jL                  dk\  r.dd l'}|jQ                  t         j4                  j6                        }n%tS        t         j4                  j6                  d	d       }|j2                  jT                  jW                         D ]  \  }}	|s	||vs|	jT                  |<    |j(                  _,        |j*                  _-        t]        d
      rJ t]        d      rJ |j,                  _/        |j.                  _0        tc        d       je                          |jf                  jh                  jj                  jl                  jn                  d<   |jp                  J |jp                  jr                  jn                  d<   djn                  d   _:        tw        jn                  d         }
|jp                  jx                  |
_<        |
jn                  d<   S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY wc c}w )Nwarn)side_effect_replay_policyr   )rG  _tree_leaf_c              3   8   K   | ]  }t        |         y wr{   )rg   )r   mr=   s     r.   r   zAdynamo_graph_capture_for_export.<locals>.inner.<locals>.<genexpr>  s     O7<33Os   )      r   r  _in_shuffle_graph_out_shuffle_graph_param_name_to_sourcemodule_call_specsr   Ttracing_context)=rh   r8  configinstall_free_tensorspatchr   r   r   rC  r=   r   r  rX   _graph_namespacecreate_namer   r   r   r*   r+   ry   r   r  r  rM   r  r	  r
  _codegenrF  _parametersr[   _buffersall_modulesupdate_non_persistent_buffers_setsysversion_infoannotationlibget_annotationsr   __dict__rA   _in_spec	_out_specrg   rQ  rR  r   r   r   output_graphexport_metadatamodule_call_specrZ   r5  r   allow_non_fake_inputsr   tensor_to_context)r$   r%   r  pytr   tree_leaf_namesrd  annotationsrT   r   rU  r=   rG  r  s              @r.   innerz.dynamo_graph_capture_for_export.<locals>.innerh  s   ==''<<<<MM  &&&H
	!
	 ,-
	
 $'	C
	 
	 
	 S$/'' 3,,-
 //;;k!<MtT
 
 '5w005tVD	   !!&sxxALsxx'
# 	|,88'*xx';';'@'@'BL$$'HH$5$5$:$:$<L!OSXX=N=NOOOO!!(():):;4499; 4 7*$+;;EHHOOL%ehhoo7H$O"xx00668 8e4{#:27L))$/8 !$!$<)<===<)=>>>),)=)=&*-*?*?'56 $$11AARR 	-.   ,,,),):):)D)D+&?C+&<():):;)GH,/,=,=,O,O)/>+,G
	 
	 
	 
	 
	 
	 
sB   R	Q<*Q/:Q<R	0R/Q94Q<<R	R		R)r   )r  rG  rq  s   `` r.   dynamo_graph_capture_for_exportrr  d  s)    ES EC EC EN Lr0   )rG  r   c                p     ||dt         dt         dt        j                  j                  f fd}|S )a  
    Improved dynamo graph capture using transformer approach with proper fake tensor handling.

    This function creates a capture instance that handles:
    1. PyTree flattening/unflattening with proper input ordering
    2. Dynamo graph capture with export-specific context
    3. FX graph transformation for export compatibility
    4. Proper fake tensor metadata preservation
    5. Dynamic dimension constraint handling

    Notable improvements over manual approach:
    - Uses FX Transformer for cleaner graph manipulation
    - Properly handles fake tensor metadata and dynamic dimensions
    - Preserves all necessary metadata for export
    - More robust error handling and edge case management

    TODO:
    1. Are we actually gonna run the bytecode?
    2. Need to attach guards
    r$   r%   r5   c                  4	   t               5  t        j                  | |f      \  }}t        |t        j
                         t        |      }t        t        j                  j                        rj                  n}}}ddlm}  |        t        j                  j                  j!                  ddddddddt        j                  j                  j"                  	      }	t%               5  t'        d      5  |	5  t)        |t+        |      d      }
|
j,                  j.                  J g }|
j0                  C|
j0                  j2                  }|
j0                  j4                  }|
j0                  j6                  }nt        j8                  j;                  t        j                  j                         t        j8                  j=                               }|j>                  jA                  d        |jC                          d }tE        ||||
| ||       |
j,                  j.                  jF                  }|jH                  }|jJ                  }|jL                  }|jN                  }d d d        d d d        d d d        |D cg c]  }|xs dD ch c]w  }|jP                  tS        |      k(  r]t        |tT              sM|jV                  jX                  jZ                  |jV                  jX                  j\                  k7  r|j^                  y c} }}}i }D ]O  }||   }t        |t        j                  j`                  jb                        sJ te        |      ||jf                  <   Q |ji                         D ]  \  }}|   ||<    tk        |||      jm                         }to        tq        ts        tu        jv                  |      | |      |            |j>                  _<        |jC                          t{        |t        j                  j                  j|                         t        |       |j                  d	<   ||j                  d
<   |cd d d        S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY wc c}w c c}}w # 1 sw Y   y xY w)Nr  )resetTF)	specialize_intspecialize_floatassume_static_by_defaultautomatic_dynamic_shapes capture_dynamic_output_shape_opscapture_scalar_outputs'constant_fold_autograd_profiler_enabledlog_graph_in_out_metadatarW  r   )rG   _is_export_deprecated_do_not_user   rT  r   )Ar   r   r   r   r   r:  rw   rM   rh   r	  r
  r   r3   ru  r8  rV  rX  install_free_tensors_for_exportr   r   r   rN   r   ri  r5  r=   r   r  ri   r   GraphrX   r   r   r   rj  graph_input_idx_to_local_sourceoutput_return_typer   rk  t_ididr   constraint_rangevrlowerupperdimsourceGetItemSourcerO   r   rA   r   r   r   r   r   r*   r+   r[  ra   inline_inbuilt_nn_modulesru   rZ   )r$   r%   r   ry   r   r   rG  r   ru  dynamo_config_ctxr  r  rX   r   rj  graph_inputsr   r   rk  r2  cr   r   inpr  real_idx	graph_idxtransformed_graph_constraints_dynamic_shapesr  s                               r.   rq  z/_dynamo_graph_capture_for_export.<locals>.inner  sG   %' ~	%#)#6#6f~#F K#K1L1LM+C9O+5c588??+KCKKQTM6BK   G % 4 4 : :#!%)-).15'+8<*. &+]]%9%9%Y%Y !; !$ $%(D01(D "(D
 (#+& ,59	 //<<HHH,.$$0--::E # 1 1 ; ;I%(%6%6%E%EN!HH001BEHHNNDTUEKK&&t,OO% $I6#!" #&":":"G"G"W"W.NN#2#E#E *33#2#C#C Q(D (D (Dj %&  */R"Q% *1.@ A..11771;M;M;P;P;V;VV EE&" & 13# I%c*!&%--*>*>*L*LMMM256G2H!&,,/I
 (9'>'>'@ B#)(6y(AH%B !7&! ! ik  0>"7#4#4]#CT6R0##, '')/!5==#7#7#Q#Q /0:J""#672;"";/$}~	% ~	%@(D (D (D (D (D (DX&W~	% ~	%s{   C"R.Q6:Q)=E(Q	%Q)-Q65RRA<RRERQ&!Q))Q3.Q66R 	;RRRR)r   rh   ri   r   )r  rG  r   rq  r  r  s   `   @@r.    _dynamo_graph_capture_for_exportr    s?    6 %OL@%S @%C @%EHH,@,@ @%D Lr0   )Fr{   )Ur*   loggingrb  r   collectionsr   collections.abcr   dataclassesr   typingr   r   r   r	   r   rh   torch.fxtorch.utils._pytreer<  _pytreer   torch._dispatch.pythonr
   torch._dynamo.convert_framer   r   r   torch._dynamo.eval_framer   r   torch._dynamo.excr   torch._dynamo.utilsr   r   torch._export.utilsr   torch._guardsr   torch.export.dynamic_shapesr   r   r   "torch.fx.experimental.proxy_tensorr   %torch.fx.experimental.symbolic_shapesr   r   r   r   torch.fx.graphr   r   r   r    torch._subclasses.fake_tensorr!   	getLoggerr   r   r/   r7   rP   r<   ri   r   ra   ru   r	  r
  rw   r   Transformerr   r   rN   r   r   r   r  rC  rF  rr  r  r   r0   r.   <module>r     s*     
  " $ ! 6 6    $ $ ; W W L + A 8 ( F  6  G F ( < g!& 8&
38
& & 	&* 3 3  ;@U((&&U
XXUp'<EHH$8$8 '<T '<T
6EHHOO 
6   4{J6OP cUXX11 cLA)XX__A)A) ()A) (	A)
 A) A) U4S>5:tCy#HIJA)H*)=)= *$ * $+ + +}	} }(-c3h}AEc3h}}@: /3K	#s(	K$z*+K c3hKb /3MQ	`	#s(	` $z*+` U4S>5:tCy#HIJ	`
 c588'''(`r0   