
    i@                    n   S SK r S SKrS SKrS SKrS SKJr  S SKJrJrJ	r	J
r
JrJrJrJrJr  S SKrS SKrS SKJr  S SKJrJr  S SKJr  S SKJr  S SKJr  S S	KJrJr  S S
K J!r!  S SK"J#r#J$r$  S SK%J&r&J'r'  S SK(J)r)J*r*  S SK+J,r,  S SK-J.r.  S SK/J0r0  S SK1J2r2  S SK3J4r4  S SK5J6r6  S SK7J8r8  S SK9J:r:J;r;J<r<J=r=J>r>J?r?J@r@JArA  S SKBJCrCJDrD  S SKEJFrF  S SKGJHrH  S SKIJJrJ  S SKKJLrL  S SKMJNrNJOrO  S SKPJQrQ  S SKRJSrS  S SKTJUrU  S SKVJWrW  S S KXJYrY  S S!KZJ[r[J\r\  S S"K]J^r^  S S#K_J`r`  S S$KaJbrbJcrcJdrd  S S%KeJfrf  S S&KgJhrh  S S'KiJjrj  S S(KkJlrl  S S)KmJnrn  S S*KoJprpJqrqJrrrJsrsJtrtJuru  S S+KvJwrx  S S,KyJzrz  S S-K{J|r|  S S+K}Jwr~  \rS S.KJrJr  S S/KJr   S S0KJr  S4r\" \S55      r0 r0 rS6 rS7\qS8\GR                  GR                  S2\q4S9 jrSS:.S;\8S<S\\\j      -  S2S=4S> jjr SsS?\|S<S\\\j      -  S2S=4S@ jjr SsSA\lSB\GR                  GR                  S<S\\\j      -  S2S=4SC jjrSD rSE rSF rS;\8S2\l4SG jr " SH SI\l5      r\z" SJSK9 " SL SM5      5       r\z" SJSK9 " SN SO5      5       rSP\#4SQ jrSP\#S2SM4SR jr SsSP\$SS\
\   S2\	\8   4ST jjr SsSP\$SS\
\   S2\	\8   4SU jjr  StSP\#SV\lSW\
\	\GR<                  GR>                        SX\
\	\GR<                  GR>                        S2\l4
SY jjrSS\SV\l4SZ jrSV\l4S[ jrS\ rS] r  SuSS\SV\l4S^ jjrSX\	\GR<                  GR>                     S2\	\GR<                  GR>                     4S_ jrS`\!SV\lS2\4Sa jr SvS`\\\	\!   4   Sb\\\l4   SP\#Sc\
\\\4      Sd\
\   S2Se4Sf jjrSA\lSg\S2S4Sh jr\" Si5           SwSj\\l\\\l4   4   Sk\
\\\8   \\\\8   4   \|4      S`\
\\	\!   \\\	\!   4   4      Sc\
\\\4      Sl\
\#   Sd\S2Se4Sm jj5       r\" Sn5         SxSj\\l\\\l4   4   Sc\
\\\4      Sl\
\#   Sd\S2Se4
So jj5       r " Sp Se5      r " Sq Sr5      rg! \ a    S1\S2\\/\4   4S3 jr GNf = f)y    N)defaultdict)	AnyDictListOptionalSequenceSetTextIOTypeUnion)Cord)NamedDataStoreNamedDataStoreOutput)serialize_for_executorch)DataSerializer)experimental)MethodProgramsPartitionerSpec
to_backend)Partitioner)EdgeCompileConfigExecutorchBackendConfig)executorch_call_delegateis_lowered_module)emit_programEmitterOutput)_DelegateDebugIdentifierMap)ExportError)get_control_flow_submodules)_pybind_schema_to_native_schema)_QUANT_PRIMITIVES)PassBase)PassType)base_post_op_replace_passesbase_pre_op_replace_passesconvert_constant_dim_order_passdead_code_elimination_passEdgeToBackendOpsPassMemoryFormatOpsPassOpReplacePassremove_unused_parameters_pass)external_constants_passexternal_mutable_weights_pass)"insert_write_back_for_buffers_pass)NormalizeViewCopyBasePass) quant_fusion_and_const_prop_pass)reinplace_pass)RemoveGraphAssertsPass#RemoveNonCoreAtenOpGraphAssertsPass)RemoveMixedTypeOperators)aten_to_edge)ReplaceViewCopyWithViewPass)SpecPropPass)weights_to_outputs_pass)pretty_printprint_program)Program)_default_decomposition_table)EXIRATenDialectVerifierEXIREdgeDialectVerifierget_aten_verifier)!ReplaceViewOpsWithViewCopyOpsPass)_detect_fake_mode_from_gm)Verifier)ExportedProgram)&unsafe_remove_auto_functionalized_pass)ConstantArgumentExportGraphSignature	InputKind	InputSpec
OutputSpecTensorArgument)_pytree)compatibility)PassManager)r   Callable)Library)	et_loggerapi_namereturnc                 L    S[         S[        4   S[         S[        4   4S jnU$ )Nfunc.rQ   c                 <   ^  S[         S[         S[         4U 4S jjnU$ )NargskwargsrQ   c                     > T" U 0 UD6$ N )rU   rV   rS   s     _/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/exir/program/_program.pywrapper-et_logger.<locals>.decorator.<locals>.wrappers   s    T,V,,    )r   )rS   r[   s   ` rZ   	decoratoret_logger.<locals>.decoratorr   s$    -s -c -c - Nr]   )rM   r   )rP   r^   s     rZ   rO   rO   q   s/    	HS#X. 	8CH3E 	 r]   EDGE_DO_NOT_DECOMPDEFc                 2   S nU" U 5      nUc  0 $ UR                   R                  5        VVs0 s H!  u  p4UR                  R                  X35      U_M#     nnnUR                   R                  5        H  u  p4X2R                  ;  d  M  XEU'   M     U$ s  snnf )Nc                 l   U R                   R                   Vs/ s H1  nUR                  R                  SS 5      c  M"  UR                  S   PM3     nnSSKJn  U" U5      nUb  UR                  $ U H:  n[        U[        R                  5      (       d  M$  UR                  R                  s  $    g s  snf )Nvalr   )detect_fake_mode)graphnodesmetagettorch._guardsre   	shape_env
isinstancetorchSymIntnode)gmro   valsre   	fake_modevs         rZ   get_shape_env5_get_updated_range_constraints.<locals>.get_shape_env   s     
&yy}}UD) DIIe& 	 

 	3$T*	 &&&A!U\\**vv''' 
s
   !B1B1)var_to_rangeitemsreplacementsri   )rp   rt   rk   krs   range_constraintss         rZ   _get_updated_range_constraintsr{      s    ( b!I	8A8N8N8T8T8V8V	""1(!+8V   &&,,.***#$a  / s   (Bold_signaturenew_gmc           
         / nSnUR                   R                   H  nUR                  S:w  a  M  U[        U R                  5      :  d   S5       eU R                  U   n[        UR                  [        5      (       a  UR                  O$[        UR                  5      " UR                  5      nUR                  [        UR                  UUR                  UR                  S95        US-  nM     UR                   R                  5       nUR                  S:X  d   e/ n[!        UR"                  S   5       H  u  p4U[        U R$                  5      :  d   S5       eU R$                  U   n	[        U	R                  [        5      (       a  U	R                  O$[        U	R                  5      " UR                  5      nUR                  ['        U	R                  XiR                  5      5        M     [)        X(S9n
U
$ )	z7
Update the graph signature's user_input/user_outputs.
r   placeholderz-Number of inputs changed after transformation)
persistent   outputz.Number of outputs changed after transformation)input_specsoutput_specs)rf   rg   oplenr   rl   argrD   typenameappendrG   kindtargetr   output_node	enumeraterU   r   rH   rE   )r|   r}   new_input_specsiro   old_input_specr   r   new_output_specsold_output_specnew_signatures              rZ   _get_updated_graph_signaturer      s    O	A""77m#3%%
 
 	;:	; 
 '2215 .,,.>??  n(()$))4	 	 	##%%)44		
 	
Q- #0 ,,**,K>>X%%%[--a013&&
 
 	<;	< 
 (44Q7 /--/?@@  o))*4995	 	 	++S2H2HI	
 2 )#M r]   )override_verifierspassesr   rB   c                    [        S U 5       5      (       a   S[        U5       35       e[        U [        [        U5      5      U5      $ )a  
Transforms the program according to the provided passes.

Args:
    self: The ExportedProgram instance to transform
    *passes: A sequence of passes to apply to the program
    override_verifiers: Optional list of verifier classes to use instead of the default verifiers.
        This is needed if the transforms yields illegal graph that the default verifier cannot handle.

Returns:
    ExportedProgram: A new ExportedProgram with the transformations applied, or self if no changes were made
c              3   N   #    U  H  n[        U[        [        45      v   M     g 7frX   )rl   listrA   ).0ps     rZ   	<genexpr>_transform.<locals>.<genexpr>   s"      17A
1tX&''s   #%zhExpected all passes to be of PassType, not list or Verifier. Use override_verifiers kwarg instead. Got: )anyr   _transform_with_pass_managerrL   )selfr   r   s      rZ   
_transformr      sd    $  17   A	qrvw}r~q  AA  (k$v,'); r]   pass_managerc                     U" U R                   5      nUb  UR                   OU R                   nUc   eX@R                   L a  UR                  (       d  U $ [        XU5      $ )a  
Transforms the program using the provided pass_manager.

Args:
    self: The ExportedProgram instance to transform
    pass_manager: An instance of PassManager to apply transformations.
    override_verifiers: Optional list of verifier classes to use instead of the default verifiers.
        This is needed if the transforms yields illegal graph that the default verifier cannot handle.

Returns:
    ExportedProgram: A new ExportedProgram with the transformations applied, or self if no changes were made
)graph_modulemodified%_update_exported_program_graph_module)r   r   r   restransformed_gms        rZ   r   r      sa    " t((
)C),S%%d>O>ON%%%***3<<00 r]   exported_programrp   c                    [        UUR                  [        U R                  U5      U R                  [        U5      [        R                  " U R                  5      U R                  U R                  U=(       d    U R                  /S9	nUR                  R                  R                  U R                  R                  5        UR                  R                  R                  UR                  5        U$ )N	rootrf   graph_signature
state_dictrz   module_call_graphexample_inputs	constants	verifiers)rB   rf   r   r   r   r{   copydeepcopy_module_call_graphr   r   verifierr   rh   update)r   rp   r   transformed_eps       rZ   r   r     s    
 %hh4,,b
 $..8<--(8(K(KL'66",,$C)9)B)B(CN $$++,<,I,I,N,NO$$++BGG4r]   c                 .   U R                   R                  UR                   5        UR                  U l        U R                  5        VVs/ s H  u  p#UPM	     nnnU H  n[	        X5        M     UR                  5        H  u  p%[        XU5        M     UR                  R                   Hb  nUR                  S:X  d  M  [        XR                  S 5      n[        U[        R                  5      (       d  ML  [        XR                  U5        Md     g s  snnf )Nget_attr)rh   r   rf   named_childrendelattrsetattrrg   r   getattrr   rl   rm   Tensor)new_progr}   r   _
submodulesmodro   ts           rZ   _copy_moduler   -  s    MM%\\HN&.&=&=&?@&?74$&?J@ **,	$ -""77j T2A!U\\**++q1	 # As   
Dc                      SSK Jn   U " 5       $ )Nr   ETRecord)executorch.devtools.etrecordr   r   s    rZ   _create_empty_etrecordr   <  s     6:r]   c                    [        U R                  R                   Vs/ s H  oR                  S:X  d  M  UPM     sn5      S:X  a  U $ U R                  n[        UR                  5      n[        U R                  5      nSn/ nU R                  R                   H3  nUR                  S:X  d  M  UR                  UR                  ;   d  M1  Un  O   U R                  R                   GH  nUR                  S:X  d  M  [        U R                  UR                  5      n[        U[        R                  5      (       d  MW  S[        U5       3nU R                  R!                  U5         U R                  R#                  U5      n	UR$                  R'                  5        H  u  pXR$                  U
'   M     Ub  UR)                  USS9U	R$                  S'   OXyR$                  S'   XyR$                  S   l        UR-                  U	5        U R                  R/                  U5        UR1                  [3        [4        R6                  [9        U	R                  S	9USS
95        UR1                  U5        XpR:                  U'   SSS5        GM     / nUR<                   Hb  nUR>                  [4        R@                  :X  a0  [        U5      S:  a!  URC                  U5        URE                  5         UR1                  U5        Md     [        U5      S:  a  Xl-   nXR                  l        U R                  RG                  5         U $ s  snf ! , (       d  f       GMi  = f)zs
Takes an ExportedProgram and returns the ExportedProgram modified in-place,
with the constant tensors as buffers.
r   r   Nr   _lifted_tensor_constantT)static_shapesrd   )r   )r   r   r   r   )$r   rf   rg   r   r   r   buffersr@   r   r   user_inputsr   r   rl   rm   r   inserting_beforer   rh   rw   from_tensorconstantreplace_all_uses_with
erase_noder   rG   rF   BUFFERrI   r   r   r   
USER_INPUTextendclear	recompile)epro   r   r   rr   first_user_inputlifted_constantsconstant_tensorconstant_tensor_fqnconst_placeholder_nodery   rs   r   ss                 rZ   lift_constant_tensor_passr   E  s   
 RXX^^H^Tww-/GD^HIQN	((O?**+G)"//:I77m#		_5P5P(P# 
 77j %boot{{COou||<<$;CL>"J**+;<)+)=)=>Q)R& IIOO-DA56//2 .(9B9N9N't :O :*//6 :I//6>M++E2;**+AB##D) !''&--*0F0K0KL2#'	 235D123 =< F O((66Y)))c2B.Ca.G""#34""$q!	 )
 q *<%4"OOIy I. =<s   L9L9%DL>>
M	c                 `    [        U S5      (       a  U R                  " U6 $ U R                  " U6 $ )Nr   )hasattrr   	transform)r   r   s     rZ   transform_exported_programr     s-    r<  }}f%%||V$$r]   c                   >   ^  \ rS rSrU 4S jrS\S\S\4S jrSrU =r$ )HackedUpExportedProgramDONOTUSEi  c
                 .   > [         T
U ]  UUUUUUUU	S9  g )N)r   rf   r   r   rz   r   r   r   )super__init__)r   r   rf   r   	call_specr   rz   r   r   r   	__class__s             rZ   r   (HackedUpExportedProgramDONOTUSE.__init__  s/     	+!//) 	 		
r]   rU   rV   rQ   c                   ^  SS K Js  Jn  T R                  R                  b.  Un [
        R                  " UT R                  R                  5      n[        U 4S jT R                  R                   5       5      n[        U 4S jT R                  R                   5       5      n[        R                   " 5          [        R"                  R%                  T R&                  5      R(                  " / UQUQUQ7SS06n	S S S 5        T R                  R*                  b  T R                  R,                  n
[/        U
5      nW	S U nT R                  R0                  nUb!  [3        UR5                  5       5      S   nU	S U n	XS  n	 [        R6                  " U	T R                  R*                  5      n	 SnT R                  R,                  R9                  5        H  nX   T R:                  U'   US
-  nM     U	$ W	$ ! [         aD    [        R                  " U5      u  pVUR                  ST R                  R                   SU 35      ef = f! , (       d  f       GNO= f! [         aD    [        R                  " U	5      u  pVUR                  ST R                  R*                   S	U 35      ef = f! SnT R                  R,                  R9                  5        H  nX   T R:                  U'   US
-  nM     f = f)Nr   z>Trying to flatten user inputs with exported input tree spec: 
z-
but actually got inputs with tree spec of: 
c              3   B   >#    U  H  nTR                   U   v   M     g 7frX   r   r   r   r   s     rZ   r   ;HackedUpExportedProgramDONOTUSE.__call__.<locals>.<genexpr>  s      
.MdDOOD!.M   c              3   B   >#    U  H  nTR                   U   v   M     g 7frX   r   r   s     rZ   r   r     s       
.JdDOOD!.Jr   enable_io_processingFz@Trying to flatten user outputs with exported output tree spec: 
z.
but actually got outputs with tree spec of: 
r   )torch._export.error_exporterrorr   in_spec	fx_pytreetree_flatten_spec	Exceptionpytreetree_flattenInternalErrortupler   
parametersr   rm   no_gradfxInterpreterr   runout_specbuffers_to_mutater   assertion_dep_tokenr   keystree_unflattenvaluesr   )r   rU   rV   r   	user_argsr   received_specordered_paramsordered_buffersr   mutationnum_mutatedmutated_buffersr	  assertion_dep_token_indexixbuffers   `                rZ   __call__(HackedUpExportedProgramDONOTUSE.__call__  s   ++>>!!-I	 229dnn>T>TU  
.2.B.B.M.M
 
    
.2.B.B.J.J 
 
 ]]_ ((&&t'8'89== "148OTC  >>"".++==Hh-K!,;/O #'"6"6"J"J".,01D1I1I1K,LQ,O)445l#C++C1H1HI "22DDKKMF.=.ADOOF+!GB N 
s
e  #)#6#6y#A ))U~~--. /D$o'   _*  #)#6#6s#; ))W~~../ 0E$o'  "22DDKKMF.=.ADOOF+!GB Ns3   +G/ 7AI <+I /AH= 
IAJ  J# #AK(rY   )	__name__
__module____qualname____firstlineno__r   r   r  __static_attributes____classcell__)r   s   @rZ   r   r     s'    
.9c 9S 9S 9 9r]   r   F)is_backward_compatiblec                       \ rS rSrS\S\4S jrS\SS 4S jrS\	S\	4S	 jr
 SS\\   SS 4S jjrSS jr SS\\   SS4S jjr SS\\\\	4      SS 4S jjrSrg
)ExirExportedProgrami  r   after_to_edge_passesc                     Xl         X l        g rX   )r   r"  )r   r   r"  s      rZ   r   ExirExportedProgram.__init__  s    
 !1 %9!r]   r   rQ   c                 <    [        U R                  /UQ76 U l        U $ rX   )r   r   )r   r   s     rZ   r   ExirExportedProgram.transform  s     *4+@+@ J6 Jr]   rU   c                 <    U R                   R                  5       " U6 $ rX   )r   module)r   rU   s     rZ   r  ExirExportedProgram.__call__  s    $$++-t44r]   Nconfigc                    U=(       d
    [        5       n[        U R                  R                  [        R
                  R                  5      (       d1   S[        U R                  R                  5      R                   35       e[        X5      $ )Nztype is instead: )
r   rl   r   r   rm   r  GraphModuler   r  _to_edge)r   r*  s     rZ   to_edgeExirExportedProgram.to_edge  sz     .,.!!..0D0D
 
 	StD$9$9$F$FGPPQR	S 
 %%r]   c                 V    [        U R                  R                  R                  5        g rX   )printr   r   rf   r   s    rZ   dumpExirExportedProgram.dump  s    d##00667r]   ExecutorchProgramc           	      6   U R                   (       d  [        S5      eU=(       d
    [        5       nU R                  R                  n[        U5       H  nU" U5      nUc   eUR                  nM     UR                  U5      nUc   eUR                  n[        [        R                  " U R                  5      U R                   5      n[        UR                  R                  U5        [        UUR                  UR                  UR                  UR                  UR                   S9nUR                  R"                  R%                  UR"                  5        UR                  R"                  R%                  U R                  R                  R"                  5        U$ )Nz&Must run to_edge before to_executorch.)emit_stacktraceextract_delegate_segmentssegment_alignmentconstant_tensor_alignmentdelegate_alignment)r"  RuntimeErrorr   r   r   edge_to_executorch_passesmemory_planning_passr!  r   r   r   r5  r7  r8  r9  r:  r;  rh   r   )r   r*  r}   r   
new_gm_resr   executorch_progs          rZ   to_executorch!ExirExportedProgram.to_executorch  s]    ((GHH424&&33*62A6J))),,F 3 008
%%%((&MM$//0$2K2K
 	X..;;VD+"22&,&F&F$66&,&F&F%88
 	$$))00=$$))00!!..33	
 r]   memoc                 p    [        [        R                  " U R                  U5      U R                  5      nU$ rX   )r!  r   r   r   r"  )r   rC  new_eeps      rZ   __deepcopy__ ExirExportedProgram.__deepcopy__.  s2     &MM$//6%%
 r]   )r"  r   rX   rQ   N)r  r  r  r  rB   boolr   r"   r   r   r  r   r   r.  r3  r   rA  r   intrF  r  rY   r]   rZ   r!  r!    s    	9)	9 #	9 .C 5c 5c 5
 59&01&	&8
 59%01% 
%P 04T#s(^,	 r]   r!  c                   4   \ rS rSr  SS\S\S\S\S\\   S\\   S	S4S
 jjrS	\	4S jr
S	\4S jr\S	\4S j5       r\\" S5      S	\\\4   4S j5       5       r\S	\4S j5       r\S	\\\\\\   4   4   4S j5       r\S	\\\\\\\\\4   4   4   4   4S j5       r\S	\\\\\\\\   4   4   4   4S j5       r\S	\R:                  R<                  4S j5       rS	\R:                  R<                  4S jr S	\!4S jr"S\#RH                  S	S4S jr%SS jr&Sr'g)r5  i8  Nexir_exported_programr7  r8  r9  r:  r;  rQ   c                    UR                   (       d  [        S5      eUR                  U l        S U l        S U l        S U l        S U l        X l        X0l        X@l	        XPl
        X`l        SSKJnJn  U" U" U R                  5      5      U l        g )NzBNeed to call prog.to_edge prior to constructing ExecutorchProgram.r   FlatTensorConfigFlatTensorSerializer)r"  r<  r   	_pte_data_tensor_data_buffer_emitter_output_emit_stacktrace_extract_delegate_segments_segment_alignment_constant_tensor_alignment_delegate_alignment4executorch.extension.flat_tensor.serialize.serializerO  rP  _data_serializer)	r   rL  r7  r8  r9  r:  r;  rO  rP  s	            rZ   r   ExecutorchProgram.__init__:  s     %99T  !6 F F)-7;(,8<&50I''89R'2D 	

 1ET4451
r]   c                 ~    U R                   c%  [        U R                  U R                  5      U l         U R                   $ rX   )rT  r   r   rU  r2  s    rZ   _get_emitter_output%ExecutorchProgram._get_emitter_outputZ  s:    '#/%%t'<'<$D  ###r]   c           
         U R                   cd  [        U R                  5       [        U R                  U R
                  U R                  U R                  S9U R                  5      u  U l         U l	        U R                   c   eU R                   $ )N)r8  r9  r:  r;  )
rQ  r   r^  r   rV  rW  rX  rY  r[  rR  r2  s    rZ   _get_pte_dataExecutorchProgram._get_pte_dataa  s    >>!0H((*'.2.M.M&*&=&=.2.M.M'+'?'?	 %%	1-DND- ~~)))~~r]   c                 p    U R                   c  [        U R                  5       5      U l         U R                   $ zReturns the serialized ExecuTorch binary as a byte string.

Note that the call to `buffer` may allocate a very large amount of
contiguous memory, depending on the model size. If writing to a file,
use `write_to_file` which won't incur additional copies.
)rS  bytesra  r2  s    rZ   r  ExecutorchProgram.bufferp  s-     << !3!3!56DL||r]   z>This API is experimental and subject to change without notice.c                     U R                   c  U R                  5         U R                  c  0 $ U R                  R                  5        VVs0 s H  u  pU[	        U5      _M     snn$ s  snnf )zReturns the data files as a dictionary of filename to byte data.

Returns:
    Dict[str, bytes]: Dictionary mapping data filenames (e.g., .ptd files) to
        their serialized byte content.
    Returns empty dict if no data files are available.
)rQ  ra  rR  rw   re  )r   filenamecords      rZ   
data_filesExecutorchProgram.data_files~  s_     >>! $I<@<M<M<S<S<UV<U.(%+%<UVVVs   
A&c                 6    U R                  5       R                  $ rX   )r^  programr2  s    rZ   rm  ExecutorchProgram.program  s    '')111r]   c                     U R                   (       a  U R                   R                  $ U R                  5       R                  $ rX   )rT  debug_handle_mapr^  r2  s    rZ   rp  "ExecutorchProgram.debug_handle_map  s2    ''888''):::r]   c                     U R                   (       a  U R                   R                  $ U R                  5       R                  $ rX   )rT  method_to_delegate_debug_id_mapr^  r2  s    rZ   delegate_mapExecutorchProgram.delegate_map  s4     ''GGG'')IIIr]   c                     U R                   (       a  U R                   R                  $ U R                  5       R                  $ rX   )rT  instruction_id_to_num_outs_mapr^  r2  s    rZ   rw  0ExecutorchProgram.instruction_id_to_num_outs_map  s4     ''FFF'')HHHr]   c                 .    U R                   R                  $ rX   r   r   r2  s    rZ   r   ExecutorchProgram.graph_module  s    $$111r]   c                 .    U R                   R                  $ rX   rz  r2  s    rZ   dump_graph_module#ExecutorchProgram.dump_graph_module  s    $$111r]   c                     U R                   $ rX   )r   r2  s    rZ   dump_exported_program'ExecutorchProgram.dump_exported_program  s    $$$r]   	open_filec                 B    U R                  5       R                  U5        gz
Writes the serialized ExecuTorch binary to the file at `open_file`. Prefer to use this over
`buffer`, as it writes to file without copying into a contiguous block of memory first,
reducing the peak memory usage.
N)ra  write_to_filer   r  s     rZ   r  ExecutorchProgram.write_to_file  s     	**95r]   c                 L   U R                   c   eU R                   R                  5        He  u  p#[        [        R                  R                  X S35      S5       n[        R                  " SU S35        UR                  U5        SSS5        Mg     g! , (       d  f       My  = fzK
Writes the serialized ExecuTorch data files to the directory at `outdir`.
Nz.ptdwbzWriting data file to )	rR  rw   openospathjoinlogginginfor  r   outdirrh  ri  fs        rZ   write_tensor_data_to_file+ExecutorchProgram.write_tensor_data_to_file  s       ,,,"//557NHbggll6Zt+<=tD4XJdCD""1% ED 8DDs   ,B
B#	)rS  rX  r[  rY  rU  rT  rV  rQ  rW  rR  r   NNrH  )(r  r  r  r  r!  rI  rJ  r   r   r   r^  r   ra  propertyre  r  r   r   strrj  r:   rm  r   r   rp  r   rt  rw  rm   r  r,  r   r}  rB   r  ioBufferedIOBaser  r  r  rY   r]   rZ   r5  r5  8  s    48,0
2
 
 $(	

 
 $,C=
 %SM
 

@$] $t     RSWDe, W T W  2 2 2 ;$sE#tCy.,A'A"B ; ;
 J	c4T#uS2M-M'N"NOOPP	QJ J I	c4U3S	>2233	4I I 2ehh22 2 22588#7#7 2% %6r'8'8 6T 6	&r]   r5  r*  c                 8    [         [        5       /-   n[        nX4$ rX   )r$   r3   r#   )r*  pre_op_replace_passespost_op_replace_passess      rZ   _get_aten_to_edge_passesr    s%     7:R:T9UU8 88r]   c                    UR                   (       a%   [        5       " U R                  R                  5        U R                  R                  nUS:X  a  [        [        U R                  R                  U R                  R                  R                  U R                  R                  U R                  R                  U R                  R                  U R                  R                  U R                  R                  U R                  R                   [#        US9/S9	S5      n [%        U5      u  p4[&        R(                  " U 5      R*                  " U6 nUS:X  a  [-        UR                  5      Ul        UR                  R                  nUR.                  (       aS  [1        5       " U5      nUc   eUR                  nUR2                  (       d!  [5        5       " U5      nUc   eUR                  nU H  nU" U5      nUc   eUR                  nM     [        UUR                  [7        UR                  R                  U5      UR                  R                  UR                  R                  UR                  R                  UR                  R                  UR                  R                   [9        USS9/S9	Ul        SUl        U$ ! [         a    [
        R                  " S5        e f = f)Na  If a particular operator failed core ATen IR check, please consider adding it to the exception list. Add the operator to _core_aten_ops_exception_list in EdgeCompileConfig. This is the recommended way to resolve this type of failure, so that the rest of the IR validation check can still be performed.
If you'd like to disable IR validation checking, please set _check_ir_validity in EdgeCompileConfig, like *.to_edge(exir.EdgeCompileConfig(_check_ir_validity=False)).ATEN)r*  r   FTedge_compile_config
class_only)_check_ir_validityr<   r   r   r   r  r  dialectr!  rB   rf   r   r   rz   r   r   r   r>   r  r   r   r   r   _use_edge_opsr)   _skip_dim_orderr(   r   r=   r"  )	r   r*  r  r  r  new_epr}   r?  r   s	            rZ   r-  r-    s     
	#%b&9&9&F&FG !!))G& ((55))66<< " 3 3 C C..99"$"5"5"G"G"$"5"5"G"G!22AA--77%% !
$ 5MV4T1]]2((*?@F&";F<S<S"T$$11F"_V,
%%%((%%,.v6J))),,F#vY
%%%(( $
 .ll4##33V
 **55 11CC 11CC..==))33#$*
F$ #'FMM  	LLT 	s   $K   "K"r   c                    [        U R                  [        5      (       a9  [        5       R                  nU(       d  UnU R                  R	                  X5      nOD[        U R                  [
        5      (       a  U R                  nO[        SU R                   35      eU R                  (       a%  [        5       [        [        5       UU R                  /$ UU R                  /$ )z
Returns a list of passes to run before memory planning.
Get the sym shape eval pass based on the method name, if the pass is not in the dict, use the default pass.
z6sym_shape_eval_pass must be a dict or a PassBase, got )rl   sym_shape_eval_passdictr   ri   r!   r<  remove_view_copyr.   r&   r5   to_out_var_pass)r*  r   default_passr  s       rZ   pre_memory_planning_passesr  #  s     &,,d33.0DD".$88<<TP	F..	9	9$88DVE_E_D`a
 	
 %'&')""
 	
  ""
 	
r]   c                 v    / U R                   Q[        5       P[        5       P[        5       P[	        X5      -   nU$ )z
Returns a list of passes to lower from edge to executorch.
Get the pre memory planning passes based on the method name, if the pass is not in the dict, use the default pass.
)r   r6   r'   r1   r  )r*  r   r   s      rZ   r=  r=  F  sS     
	
 	 	 	  	#601F Mr]   rm  core_aten_ops_exception_listpreserve_opsc                    [        U5      n[        U 5      u  pE[        5       [        5       /nUR	                  U5        U R
                  (       aC  UR                  [        5       5        U R                  (       d  UR                  [        5       5        UR                  nU H  nU" U5      n	U	c   eU	R                  nM     [        UUR                  [        UR                  U5      UR                  UR                   UR"                  UR$                  UR&                  [)        U SUUS9/S9	n
[+        U
5      n
[,        R,                  " U
5      n
[/        U
/UQ76 n
U
$ )aY  
Args:
    config: The configuration for the edge program.
    program: The exported program to be converted to an edge program.
    core_aten_ops_exception_list: A list of aten ops that are missing decompositions to core aten.
    preserve_ops: A list of aten ops that should not be decomposed.
Returns:
    An ExportedProgram in edge dialect.
T)r  r  r  r  r   )r*   r  r2   r?   r   r  r   r)   r  r(   r   rB   rf   r   r   r   rz   r   r   r   r=   r   r%   r   )r*  rm  r  r  r  r  r   rp   r   gm_resedge_programs              rZ   _generate_edge_programr  Z  sJ     ,G4G4LV4T1 	,-)+	F MM'(mo&%%MM-/0			B2!!!   
 #hh4W5L5LbQ%%!33!33--###$*-I)	
L( -\:L 3RRL lD-CDLr]   c                 4   [        5       nUR                  U 5      nUc  g U GHq  nUR                  U5      u  pV[        U5      nU H  n[	        U5        M     UR
                  R                   Ht  nU(       a  U" U5      OSn	UR                  S:X  d  M&  UR                  U;   d  M8  U	(       d  MA  UR                  UR                  5        [        UR                     Ul        Mv     [        UR                  5       H  u  pn
UR
                  R                   Ht  nU(       a  U" U5      OSn	UR                  S:X  d  M&  UR                  U;   d  M8  U	(       d  MA  UR                  UR                  5        [        UR                     Ul        Mv     M     GMt     U$ )NTcall_function)setri   ops_to_not_decompose%_remove_invalid_ops_for_not_decompose_register_no_decomp_oprf   rg   r   r   addaten_op_to_transform_opr   r   )r   rm  partitionerr  partitionersops_set_to_not_decomposecheck_op_supportop_atenro   is_op_supportedr   submods               rZ   &_replace_aten_ops_with_transformed_opsr    sX   
 5L??4(L $5@5U5U6
2  $I$$
  0G"7+ 0 MM''D8H.t4dO?*KK#;;#O  -5dkkB ( 88L8LMLAq**<L"24"8RVGG.'??' $$T[[1"9$++"FDK + N+ $@ r]   c                    U R                   R                   HU  nUR                  S:X  d  M  [        UR                  5      [
        ;   d  M4  [
        [        UR                  5         Ul        MW     [        U R                  5       Hu  u  p#nUR                   R                   HU  nUR                  S:X  d  M  [        UR                  5      [
        ;   d  M4  [
        [        UR                  5         Ul        MW     Mw     g )Nr  )rf   rg   r   r  r   transform_op_to_aten_opr   r   )rm  ro   r   r  s       rZ   $_restore_transformed_ops_to_aten_opsr    s     ##77o%#dkk*:>U*U1#dkk2BCDK $ 4G4H4HI1LL&&D?*$(??5c$++6FG ' Jr]   c                 J   U R                   R                  R                  S5      S   nU R                   R                  n[	        [
        R                  [        5      (       d   S[         S35       e[        [
        R                  [        5      n[        X15      n[        XB5      $ )N::r   zCouldn't find z@ in torch.ops. Please make sure the Library has been registered.)	_schemar   splitoverload_namer   rm   opsedge_no_decomp_namespacer   )r  op_namer  op_namespacer   s        rZ   _get_transformed_opr    s    oo""((.q1GOO11M		+  s	011qrs  599&>?L		'B2%%r]   c                    [         R                  U 5      c  [        U [        R                  R
                  5      (       a  [        U R                  5      R                  S5      S   nU R                  R                  R                  S5      S   n[        R                  U5        U R                  R                  nUS:w  a  USU-   -  n[        R                  X S5        [        U 5      [         U '   U [        [        [         U    5      '   g g g )Nr  r    .CompositeExplicitAutograd)r  ri   rl   rm   _ops
OpOverloadr  r  r  r   libdefiner  implr  r  )r  	op_schemar  r  s       rZ   r  r    s     ""7+3
&&9 9 (..t4Q7	//&&,,T215

9  55Bs]**G#>? ,?w+G(IP$;G$D EF%93r]   c                    SnUb	  USU S3-  nUSU SU  S3-  nU Vs1 s H  n[        U5      iM     snR                  U5      n[         Vs1 s H  n[        U5      iM     nnUR                  R                  R
                   H  n	U(       a  U" U	5      OSn
U	R                  S:X  d  M&  U	R                  U;   d  M8  U	R                  U;  d  MJ  U
(       d  MS  S	U	 S
U	R                   S3U-   nU(       a  [        U5      e[        R                  " U5        M     [        UR                  5       H  u  pnUR                  R
                   H  n	U(       a  U" U	5      OSn
U	R                  S:X  d  M&  U	R                  U;   d  M8  U	R                  U;  d  MJ  U
(       d  MS  S	U	 S
U	R                   S3U-   nU(       a  [        U5      e[        R                  " U5        M     M     g s  snf s  snf )Nr  z*This op was registered by the partitioner z to not be decomposed.
zThe following ops: z( were specified to not be decomposed in r  Tr  zNode z	 with op z" was not decomposed or delegated.
)r4   unionr    r   rf   rg   r   r   r<  r  warningr   )r   rm  r  r  generate_errorpartitioner_namewarning_str_endr   quant_primitivesro   r  warning_strr   r  s                 rZ   &_sanity_check_graph_for_non_decomp_opsr    s    O#GHXGYYqrr,-E,FFnosnttuvvO
 $< #;RR#; e$%  4EE3DRR(3DE$$**004D*40$GG&77#33ovYt{{m3VW!"  ";//, 1 4G4H4HI1LL&&D8H.t4dO?*KK#;;KK'77!/D64;;-7Z[%&  "&{33OOK0 ' J)  Fs   G%G*c                 Z   ^^ [        5       mU4S jmU4S jn[        [        X5      5      $ )Nc                 b   > U T;  a(  [         R                  " U 5        TR                  U 5        g g rX   )r  warnr  )warn_str_logged_warningss    rZ   log_warning:_remove_invalid_ops_for_not_decompose.<locals>.log_warning?  s+    ++LL"  * ,r]   c           
        > / n UR                  [        R                  R                  R                  R
                  5        X;   a  gU R                  n[        U5      nUc  T" SU R                   S35        O@UR                  (       a  T" SU  S35        gUR                  5       S /:w  a  T" SU  S35        gU [        R                  R                  R                  R
                  [        R                  R                  R                  R                  [        R                  R                  R                  R                  [        R                  R                  R                  R                  [        R                  R                  R                   R                  [        R                  R                  R"                  R
                  [        R                  R                  R$                  R
                  [        R                  R                  R&                  R(                  [        R                  R                  R*                  R
                  4	;   a  T" SU  S35        gg!    GN%= f)	NTz,Torchgen is not able to parse the schema of z.  This is not fatal.zOp z_ was requested for preservation by partitioner.  This request is ignored because it is mutable.Fzc was requested for preservation by partitioner.  This request is ignored because it aliases output.zf was requested for preservation by partitioner.  This request is ignored because it is in a blocklist.)r   rm   r  torchaochoose_qparams_affinedefaultr  r   
is_mutablealiased_return_namesaten_to_copymulr   r  subdivitem_local_scalar_denseunbindrJ  split_with_sizes)r   
allow_listschemanative_schemar  s       rZ   keep3_remove_invalid_ops_for_not_decompose.<locals>.keepE  s   
	 eii//EEMMN 7? >rzzlJ_` ''"|} 113v="  A  B   IINN##++ IINN%%IINN%%IINN%%IINN%%IINN''IINN..66IINN!!%%IINN++33
 
 bT  A ]	s   =I" "I')r  r   filter)r  r   r  r  s     @@rZ   r  r  :  s*     u+5n t*++r]   r  c                 0    U R                  U5      u  p#US L $ rX   )r  )r  rm  r   r  s       rZ   "_can_skip_using_EDGE_DO_NOT_DECOMPr    s"     &::7CAt##r]   aten_programsconstant_methodsgenerate_etrecordEdgeProgramManagerc           	      \   [        [        5      n0 nUR                  5        GH  u  pxUR                  0 5      nU Gb  U R	                  U/ 5      n	[        5       n
U	(       d@  [        5       nUR                   H  nUR                  US5        M     UR                  U5      nU	 GH  nUR                  U5      u  p[        X5      nU(       a_  [        5       n/ nU H)  nUR                  US5      c  M  UR                  U5        M+     UR                  U5      nU
R                  U5        M  [        U5      n[        5       nU H  nUR                  US5        M     UR                  U5      nX}/0n[        XxU5      =(       d    / nU
R                  U5        UR                  [        5       5      n[        U5        GM     XW   R!                  U
5        [#        UUUR	                  U/ 5      S9Xg'   GM     [        [        5       R$                  " UR'                  5       6 5      n[        [        UR(                  5      [        U5      -  5      Ul        [+        UUUU5      nU(       aG  [-        5       nUR/                  U5        UR1                  [2        R4                  " U5      5        UUl        U$ )a  
Generates EdgeProgramManager for subsequent lowering to the
partitioners specified by partitioner. The EdgeProgramManager is generated from
aten_programs.

Partitioners specify what nodes should not be decomposed from the original aten programs.
This is done through two passes of run_decompositions.
    - First pass preserves all aten_targets specified by partitioners to preserve
      them from nested decompositions
    - Second pass uses check_op fn provided by partitioners to perform additional checks
      on nodes with preserved aten targets. They are then replaces with transformed ops to
      keep them through the second pass of decompositions
Nr  )r   r   rw   run_decompositionsri   r  r;   r  popr  r  r   r   r  r  r  r   r  r  r  _core_aten_ops_exception_listr  r   add_exported_programadd_edge_dialect_programr   r   	_etrecord)r  r  r*  r  r  #ops_set_to_not_decompose_by_programedge_programsr   rm  partitioners_for_programfinal_ops_to_preservetabler   curr_partitionercurr_ops_no_decompr   !can_skip_using_edge_do_not_decompops_needing_preservationtemp_partitioner_dictpreserved_opsall_ops_not_to_decomposeedge_manageretrecords                          rZ   "_gen_edge_manager_for_partitionersr    s   ( +6d*;'02M&,,.,,R0"'2tR'@$$'E! ,46 --BIIb$' .!44U; %= (8(M(Mg(V%" 5W$51 58:E/1,0 99R.:4;;B? 1 &88?G)001IJ *O**&
 9:E0		"d+ 1 &88?G .23E,F)> +@  	 " *00? &889U9WXG 9A_ %=` 05<<=RS4<@@rJ
E /V  $8??AB  ,0F001C8P4QQ,F( & 	L )+%%m4))$--*EF!)r]   named_data_storec                 v   ^^ S[         R                  R                  SS4UU4S jjmT" U R                  5        g)zp
Collects all the named data store outputs found within the exported program
and adds them to named_data_store.
r   rQ   Nc                 R  > U R                   R                   Ho  nUR                  [        :X  d  M  [	        XR
                  S   R                  5      n[        U5      (       d   eUR                  nUc  M^  TR                  U5        Mq     [        U 5       H  u  pEnT" U5        M     g )Nr   )
rf   rg   r   r   r   rU   r   named_data_store_outputmerge_named_data_storer   )r   ro   lbmdata_store_outputr   r   collect_named_data_store_outputsr   s         rZ   r'  Xcollect_named_data_store_from_exported_program.<locals>.collect_named_data_store_outputs  s     !&&,,D{{66lIIaL,?,?@(----$'$?$?!$0$;;<MN - 8ELAq,V4 Fr]   )rm   r  r,  r   )r   r   r'  s    `@rZ   .collect_named_data_store_from_exported_programr)    s8    5hh**5	5 5 %%5%B%BCr]   to_edge_transform_and_lowerprogramstransform_passescompile_configc                    [        U[        5      (       a   eU=(       d
    [        5       n[        U [        5      (       d  SU 0nOU n[        U[        5      (       d$  Ub!  UR                  5        Vs0 s H  oU_M     nnO#Uc   UR                  5        Vs0 s H  o/ _M     nn[	        X'XcU5      n	UbI  U	R                  U5      n	U(       a1  U	R                  R                  S[        R                  " U	5      05        Sn
UR                  5        H  n[        U
[        U5      5      n
M     [        U
5       HF  n0 nUR                  5        H  u  pU[        U5      :  d  M  X   X'   M     U	R                  U5      n	MH     U	R                   R                  5        H  u  p[#        5       nUR%                  U/ 5      nU Hf  nUR'                  U5      u  nn[)        UU5      (       d  [+        U5      nUR-                  U5      n[/        UUUUUR0                  R2                  SS9  Mh     UR4                  [7        U5      -   nUR8                  (       d  M  [;        USUS9" 5       " UR<                  5        M     U	$ s  snf s  snf )a	  
:func:`to_edge_transform_and_lower` constructs an EdgeProgramManager from a set of
exported programs in ATen dialect. It differs fundamentally from to_edge in that it
combines the conversion of the ATen dialect to the edge dialect program, then running
the transformation passes and then subsequently lowering the programs to their
corresponding backends all into a single API.

This is fundamentally useful for lowering to backends that have ops registered that they
do not want to be decomposed and thus rely on matching with these non-decomposed ops. For
these sorts of backends this is the *only* API that should be used to lower to the edge
dialect. Using a combination of to_edge(...) and to_backend(...) will result in inconsistent
or wrong behavior.

This API is the primary recommended way to lower to the CPU based XNNPack backend.

Args:
    programs: Can be a single ExportedProgram or a dictionary mapping function names
        to their corresponding ExportedPrograms. If only a single ExportedProgram is
        provided it will be assigned the name "forward".

    transform_passes: The transform_passes can be one of:
        1) a list of passes -
            all methods in the given EdgeProgramManager will be transformed with the provided passes.
        2) a dictionary -
            only method names specified in the dictionary will be transformed
            with their corresponding passes
        3) an instance of a PassManager -
            all methods in the given EdgeProgramManager will be
            transformed with the given PassManager instance.

    partitioner: The partitioner can either be a Partitioner subclass instance, or a
        dictionary mapping method names to Partitioner subclass instance. If it is a
        Partitioner subclass, all programs in the given EdgeProgramManager will be lowered
        using the given partitioner. If it is a dictionary, only method names specified in
        the dictionary will be lowered with the given partitioner.

    constant_methods: An optional dictionary of method name to the constant value
        returned by that method in eager mode. Often used to store config information on
        Edge models.

    compile_config: An optional argument used to provide greater control over the
        transformation to edge dialect process.

    generate_etrecord: An optional argument used to generate an etrecord for debugging purposes.

Returns:
    EdgeProgramManager
forwardedge_after_transformr   T)r  r  r  r  r  )rl   r   r  r
  r  r   r  add_extra_export_modulesr   r   r  maxr   rangerw   r   _edge_programsr  ri   r  r  r  r  r  r   r  r  r   r  r=   r   )r+  r,  r  r  r-  r  r*  r  r   r  max_num_partitionerspartitioner_listr   method_to_partitionerrm  r  r  r  curr_op_setr  r  s                        rZ   r*  r*    s   z *,=>>>>202Fh%%"H- k4(([-D5B5G5G5IJ5IT[(5IJ		,9,>,>,@A,@DRx,@A5F>OL ##--.>?"";;'|)DE '..0"#7=M9NO 1 '( "&1&7&7&9"D3'((.>.A%+ ': $../DE ) &44::<?Bu "tR0 ,,<,Q,Q-)K) 66FPPCKP'?'E'Ek'R$2( !1!;!;!D!D# !-" **T2J-KK$$$#$*)  $$	&- =8 o KAs   1I7I<r.  c                     [        U[        5      (       a   eU=(       d
    [        5       n[        U [        5      (       d  SU 0nOU n0 nUR                  5        H  u  px[	        5       n	/ n
U(       a1  UR
                  n
UR
                   H  nU	R                  US5        M     UR                  U	5      nUR                  (       a>  UR                  n[        5       " U5      nUc   eUR                  n [        USS9" U5        [        XHU
S9Xg'   UR                  (       d  M   [!        USU
S	9" 5       " Xg   R                  5        M     [#        XaU5      nU(       aG  [%        5       nUR'                  U5        UR)                  [*        R,                  " U5      5        UUl        U$ ! [         a!  n[        R                  " SU S35        UeSnAff = f! [         a!  n[        R                  " SU S
35        UeSnAff = f)aB  
:func:`to_edge` constructs an EdgeProgramManager from a set of exported programs in
ATen dialect. Upon construction those programs are transformed into edge dialect.

Args:
    programs: Can be a single ExportedProgram or a dictionary mapping function names to their corresponding ExportedPrograms. If only a single ExportedProgram is provided it will be assigned the name "forward".

    constant_methods: An optional dictionary of method name to the constant value returned by that method in eager mode. Often used to store config information on Edge models.

    compile_config: An optional argument used to provide greater control over the transformation to edge dialect process.

    generate_etrecord: An optional argument used to generate an etrecord for debugging purposes. Default is False.

Returns:
    EdgeProgramManager
r/  NFr  Input program z is not in ATen dialect.r
  Tr1  z is not in Edge dialect.)rl   r   r  rw   r;   r  r  r  r  r   r2   r<   r   r  r  r  r=   r  r   r  r  r   r   r  )r+  r  r-  r  r*  r  r  r   rm  r  r  r   rp   r  eepmr  s                    rZ   r.  r.    s   . *,=>>>>202Fh%%"H- 02M&,,.,.)66L$11		"d# 2,,U3$$ %%B8:2>F%%%$$B'(.$  5,
 $$$'(.#!-  "'44	6A /R ]f
EC)+%%m4))$--*<= J3  ~dV3KLM  ~dV3KLMs0   2F$""G$
G.G

G
G=G88G=c                      \ rS rSrSr    SS\\\\\4   4   S\	\\\
4      S\	\   S\	\\R                  R                        S\	\\R                  R                        4
S	 jjr\S
\\   4S j5       r\S
\\   4S j5       rSS\S
\4S jjr\" S5       SS\\\   \\\\   4   \4   S\	\   S
S 4S jj5       r\" S5      S\\\\\4   4   S
S 4S j5       r\" S5       SS\	\   S
S4S jj5       rSrg)r  i  a`  
Package of one or more `ExportedPrograms` in Edge dialect. Designed to simplify
lowering to ExecuTorch. See: https://pytorch.org/executorch/main/ir-exir

Allows easy applications of transforms across a collection of exported programs
including the delegation of subgraphs.

Manages the second link in the lowering chain of ATen -> Edge -> ExecuTorch.
Nr  r  r-  r  r  c                    U=(       d
    [        5       U l        [        U[        5      (       d  SU0nUR	                  5        H+  u  pg [        U R                  UUS9" UR                  5        M-     Xl
        X l        [        5       U l        U R                  R	                  5        H  u  p[        XpR                  5        M     SU l        g! [         a!  n[        R                  " SU S35        UeSnAff = f)z
Should not be called directly by users. User should use :func:'to_edge' instead.

Constructs an EdgeProgramManager from an existing set of exported programs in edge dialect.
r/  )r  r  r  r;  z is not in aten dialect.N)r   r-  rl   r  rw   r=   r   r   r  r  r5  _config_methodsr   _named_data_storer)  r  )
r   r  r  r-  r  r  r   rm  r<  r   s
             rZ   r   EdgeProgramManager.__init__  s     -C0A0C-..&6M*002MD'(,(;(;1M!- &&	( 3 ;H/!/!1--335JA:// 6
   ~dV3KLMs   %C
C7C22C7rQ   c                 H    [        U R                  R                  5       5      $ )z8
Returns the set of methods in this EdgeProgramManager.
)r  r5  r
  r2  s    rZ   methodsEdgeProgramManager.methods#  s    
 4&&++-..r]   c                 ~    U R                   (       a#  [        U R                   R                  5       5      $ [        5       $ )z?
Returns the set of config methods in this EdgeProgramManager.
r@  r  r
  r2  s    rZ   config_methods!EdgeProgramManager.config_methods*  -    
 483G3Gs4'',,./RSURr]   method_namec                      U R                   U   $ z9
Returns the ExportedProgram specified by 'method_name'.
)r5  r   rK  s     rZ   r   #EdgeProgramManager.exported_program1  s    
 "";//r]   r   r   c                    U=(       d    U R                   n0 nSnSnSn[        U[        5      (       a  Un[        U[        5      (       a  Un[        U[        5      (       a  UnU R
                  R                  5        H  u  px[        U[        5      (       a4  U(       a-  XuR                  5       ;  a  [        R                  " U5      X7'   MN  Ub  [        U/UQ76 X7'   O$Ub  [        U/XW   Q76 X7'   OUb  [        X5      X7'   [        US9" X7   R                  5        M     [        U[        R                  " U R                  5      U5      n	U R                   U	l        U	$ )a  
Transforms the program according to the provided passes.

Args:
    passes: This param can be one of:
        1) a list of passes -
            all methods in the given EdgeProgramManager
            will be transformed with the provided passes.
        2) a dictionary mapping method names to lists of passes -
            only method names specified in the dictionary will be
            transformed with their corresponding passes.
        3) a PassManager instance -
            all methods in the given EdgeProgramManager will be
            transformed with the given PassManager instance.
    compile_config: Compile config to use for veriy the correctness of model
        graph after each pass. If not specified, the compile config of the
        calling EdgeProgramManager will be used. It will be used in as compile
        config of returned EdgeProgramManager.

Returns:
    EdgeProgramManager: A copy of the calling EdgeProgramManager with the
    transformations applied.
N)r  )r-  rl   r   r  rL   r5  rw   r
  r   r   r   r   r=   r   r  r@  r  )
r   r   r-  new_programs
passes_seqpasses_dictr   r   rm  r=  s
             rZ   r   EdgeProgramManager.transform8  sG   < (>4+>+>35 48
?C.2fh''Jfd## Kfk**!L!00668MD 64(( 0 0 22%)]]7%;" %%/%E*%E"(%/%L+:K%L")%A'%X" $G"//' 9. !$--(<(<=~
 
r]   r   r  c                 L   0 n0 n[        U[        5      (       d  U R                   Vs0 s H  oDU_M     nnOUn[        U R                  U5      n[	        U5      n[        SS9n[        U[        R                  " U R                  5      U5      nU R                  Ul
        U$ s  snf )aq  
Returns a semantically-equivalent program to the one given as input,
but with portions of each program in the EdgeProgramManager targeted
for delegation as determined by the partitioner.

Args:
    partitioner: The partitioner can either be a Partitioner subclass instance, or a
        dictionary mapping method names to Partitioner subclass instance. If it is a
        Partitioner subclass, all programs in the given EdgeProgramManager
        will be lowered using the given partitioner. If it is a
        dictionary, only method names specified in the dictionary will be
        lowered with the given partitioner.

        The Partitioner subclass instance is in charge with tagging portions of the
        input program for delegation. A valid partitioner must return PartitionerResult including valid
        partition_tags: Dict[str, DelegationSpec], where each key is a tag
        name and the nodes with same tag will be fused a one subgraph and
        delegated to backend specififed in delegation spec.

Returns:
    EdgeProgramManager: A copy of the calling EdgeProgramManager with the
    specified subgraphs lowered.
F)r  )rl   r  r5  r   r   r   r  r   r   r@  r  )r   r  new_edge_programsr8  r   #method_to_programs_and_partitionersr*  r=  s           rZ   r   EdgeProgramManager.to_backend  s    8 9;8:+t,,CGCVCV$WCV4;%6CV!$W!$/!.K!/
+
 ''JK"e< MM$../
 
% %Xs   B!rA  r*  ExecutorchProgramManagerc                    U(       a  UO	[        5       n0 nU R                  R                  5        GH=  u  p4UR                  (       a-  UR                  R
                  b  [        S5      e[        U5      nUR                  (       a  [        U5      n[        U5      n[        U5      n[        U5      u  pVUR                  n[        X5       HD  nU" U5      n	U	c   eU	R                  n[        U[         5      (       d  M3  UR#                  XG5        MF     [        UR$                  [&        5      (       a)  UR$                  (       a  [)        U5      n	U	R                  nO;[+        UR$                  5      (       a!  [)        XqR$                  5      n	U	R                  nUR,                  (       a  [/        Xt5      n	U	R                  n[        UR0                  [2        5      (       a/  UR0                  R5                  U[        5       R0                  5      n
OUR0                  n
[7        U
S5      (       a  U
R9                  Xv5      n	OU
" U5      n	U	c   eU	R                  n[;        UR                  U5        XBU'   GM@     [        UR0                  [2        5      (       aE  UR0                  R=                  5        H&  n
[7        U
S5      (       d  M  U
R?                  5         M(     O-UR0                  n
[7        U
S5      (       a  U
R?                  5         [A        UU RB                  UU RD                  RG                  5       5      nU RH                  b1  U RH                  RK                  5       nURM                  U5        Xl$        U$ )aV  
Transforms the program to the ExecuTorch backend.

Args:
    config: An optional argument used to provide greater control over
        the transformation to the ExecuTorch backend.

Returns:
    ExecutorchProgramManager: A manager representing the state of the EdgeProgramManager
    after it has been transformed to the ExecuTorch backend.
zCannot run do_quant_fusion_and_const_prop on a graph with a backward signature intended for on-device training. Please set do_quant_fusion_and_const_prop to False in the ExecutorchBackendConfig.r  run_multimethod)'r   r5  rw   do_quant_fusion_and_const_propr   backward_signaturer   r/   run_reinplace_passr0   r7   rC   r-   r   r=  rl   r6   update_placeholder_tensor_specsexternal_constantsrI  r+   callableexternal_mutable_weightsr,   r>  r  ri   r   r  r   r  r[  rY  r@  rA  get_named_data_store_outputr  r   add_executorch_program)r   r*  execution_programsr   rm  rp   r   r}   r   r?  r>  et_pmet_etrecords                rZ   rA   EdgeProgramManager.to_executorch  s     "'>'@9;!00668MD44**==I#n  ;7C(((1-g6G<WEG B7 KB))F.v<vY
!---#00a.. 55gF =& 644d;;--4V<
#00&33444V=V=VW
#00 ..:6K
#00&55t<<'-'B'B'F'F13HH($ (.'B'B$+U33155fL
1&9
 ))),,F--v6'.t$C 9F f11488(.(C(C(J(J(L$/1BCC(88: )M $*#>#> +->??$446(  "">>@	
 >>% ..--/K..u5)Or]   )r@  r5  r  rA  r-  )NNNNr/  rX   ) r  r  r  r  __doc__r   rB   r   r  r   r   r   r   rm   r  r  r   r  r	   rD  rH  r   rO   r   r"   rL   r   r   r   r   rA  r  rY   r]   rZ   r  r    s    6:6:NR>B%_d33G.HHI% #4S>2% !!23	%
 '/tEJJ4I4I/J&K% tEJJ$9$9:;%N /S / / SC S S0C 0 0 { 7;Hhx($sHX4F/F*GTUH !!23H 
	H HT |0;S+-=(>>?0 
0 0d  59k01k 
$k  kr]   c                      \ rS rSrSr   SS\\\4   S\\\\	4      S\\
   S\\   4S jjr\S	\\   4S
 j5       r\S	\\   4S j5       rSS\S	\4S jjr SS\S\\   S	S4S jjr\S	\\\\\\   4   4   4S j5       r\S	\\\\\\\\\4   4   4   4   4S j5       r\S	\\\\\\\\   4   4   4   4S j5       r\S	\4S j5       r\S	\4S j5       rS r S\!RD                  S	S4S jr#S S jr$S\S	S4S jr%Sr&g)!rY  i%  a  
Package of one or more `ExportedPrograms` in Execution dialect. Designed to simplify
lowering to ExecuTorch. See: https://pytorch.org/executorch/main/ir-exir

When the ExecutorchProgramManager is constructed the ExportedPrograms in execution dialect
are used to form the executorch binary (in a process called emission) and then serialized
to a buffer.

Manages the final link in the lowering chain of ATen -> Edge -> ExecuTorch.
Nre  rH  backend_config
named_datac                    Xl         X l        X@l        U=(       d
    [        5       n[	        U R                   UR
                  U R                  UR                  5      U l        SSKJ	nJ
n  U" U" UR                  S95      U l        [        U R                  UU R                  U R                  5      u  U l        U l        SU l        SU l        g)a5  
End users should not call this constructor directly. Instead, they should use
:func:'to_executorch' to construct an ExecutorchProgramManager.

Constructs an ExecutorchProgramManager from a set of exported programs in
execution dialect.

Args:
    execution_programs: A dictionary of method name to the corresponding
    ExportedProgram.

    config_methods: A dictionary of method name to the config value returned
    by that method in eager mode.

    backend_config: An optional argument used to provide greater control over
    the emission and serialization.
r   rN  )r9  N)_execution_programsr@  _named_datar   r   r7  emit_mutable_buffer_namesrT  rZ  rO  rP  r9  r[  r   rQ  rR  rS  r  )r   re  rH  rl  rm  rO  rP  s          rZ   r   !ExecutorchProgramManager.__init__1  s    2 @R 9G <F'D+B+D /;$$**  44	/
	

 !5~/O/OP!
 -E  !!	-
)) )-r]   rQ   c                 H    [        U R                  R                  5       5      $ )z>
Returns the set of methods in this ExecutorchProgramManager.
)r  ro  r
  r2  s    rZ   rD   ExecutorchProgramManager.methodsl  s    
 4++00233r]   c                 ~    U R                   (       a#  [        U R                   R                  5       5      $ [        5       $ )zE
Returns the set of config methods in this ExecutorchProgramManager.
rG  r2  s    rZ   rH  'ExecutorchProgramManager.config_methodss  rJ  r]   rK  c                      U R                   U   $ rM  )ro  rN  s     rZ   r   )ExecutorchProgramManager.exported_programz  s     ''44r]   verboseoutc                     U(       a  [        U R                  R                  US9  g[        U R                  R                  US9  g)a  
Prints the ExecuTorch binary in a human readable format.

Args:
    verbose (bool):
        If False prints the binary in a condensed format.
        If True prints the binary 1-1 with the specification in the schema.
    out:
        If None, prints to stdout.
        If non-None, writes the string to that stream object. It can be
            a file object, a StringIO object, or any other TextIO subclass.
)rz  N)r8   rT  rm  r9   )r   ry  rz  s      rZ   dump_executorch_program0ExecutorchProgramManager.dump_executorch_program  s3     --553?$..66C@r]   c                 .    U R                   R                  $ rX   )rT  rp  r2  s    rZ   rp  )ExecutorchProgramManager.debug_handle_map  s    ##444r]   c                 .    U R                   R                  $ rX   )rT  rs  r2  s    rZ   rt  %ExecutorchProgramManager.delegate_map  s     ##CCCr]   c                 .    U R                   R                  $ rX   )rT  rw  r2  s    rZ   rw  7ExecutorchProgramManager.instruction_id_to_num_outs_map  s     ##BBBr]   c                 .    U R                   R                  $ )zP
Returns the object that represents the ExecuTorch binary before serialization.
)rT  rm  r2  s    rZ   executorch_program+ExecutorchProgramManager.executorch_program  s    
 ##+++r]   c                 h    U R                   c  [        U R                  5      U l         U R                   $ rd  )rS  re  rQ  r2  s    rZ   r  ExecutorchProgramManager.buffer  s(     << 0DL||r]   c                 J    U R                   c  [        S5      eU R                   $ )z
Get the generated ETRecord if etrecord generation was enabled.

Returns:
    ETRecord object if generation was enabled, None otherwise

Raises:
    RuntimeError: if ETRecord object was not generated.
zETRecord was not generated)r  r<  r2  s    rZ   get_etrecord%ExecutorchProgramManager.get_etrecord  s$     >>!;<<~~r]   r  c                 :    U R                   R                  U5        gr  )rQ  r  r  s     rZ   r  &ExecutorchProgramManager.write_to_file  s     	$$Y/r]   c                 |   U R                   c   eU R                   R                  5        H}  u  p#UR                  S5      (       d  US-  n[        [        R
                  R                  X 5      S5       n[        R                  " SU 35        UR                  U5        SSS5        M     g! , (       d  f       M  = fr  )
rR  rw   endswithr  r  r  r  r  r  r  r  s        rZ   r  2ExecutorchProgramManager.write_tensor_data_to_file  s       ,,,"//557NH$$V,,F"bggll6Z94@A4XJ?@""1% A@ 8 A@s   4+B,,
B;	r  c                 p   USS S:w  a)  [         R                  " SU S35        [        SU S35      e [        US5       nU R	                  U5        [         R
                  " SU 35        SSS5        g! , (       d  f       g= f! [         a&  n[         R                  " SU S	U 35         SnAgSnAff = f)
z?
Saves the serialized ExecuTorch binary to the file at `path`.
Nz.ptezPath z does not end with .pter  zSaved exported program to zError while saving to z: )r  r   
ValueErrorr  r  r  r   )r   r  filer<  s       rZ   saveExecutorchProgramManager.save  s     9MME$'>?@uTF*ABCC	@dD!T""4(9$@A "!!  	@MM24&1#>??	@s5   B  +A4+B 4
B>B B 
B5B00B5)	rS  r@  r[  rT  r  ro  rp  rQ  rR  )NNNri  FNrH  )'r  r  r  r  rj  r   r  rB   r   r   r   r   r   r  r	   rD  rH  r   rI  r
   r|  rJ  r   r   rp  r   rt  rw  r:   r  re  r  r  r  r  r  r  r  r  rY   r]   rZ   rY  rY  %  s
   	 48<@599 o!569 !c3h09 !!89	9
 129v 4S 4 4 SC S S5C 5 5 >BAA*26*:A	A( 5$sE#tCy.,A'A"B 5 5 D	c4T#uS2M-M'N"NOOPP	QD D
 C	c4U3S	>2233	4C C
 ,G , ,   0r'8'8 0T 0
&@ @ @r]   rY  rX   r  r  )F)NNNNF)NNF)r   r  r  r  collectionsr   typingr   r   r   r   r   r	   r
   r   r   rm   torch._export executorch.exir._serialize._cordr   ,executorch.exir._serialize._named_data_storer   r   %executorch.exir._serialize._serializer   *executorch.exir._serialize.data_serializerr   executorch.exir._warningsr   #executorch.exir.backend.backend_apir   r   #executorch.exir.backend.partitionerr   executorch.exir.capture._configr   r   executorch.exir.delegater   r   executorch.exir.emitr   r   executorch.exir.emit._emitterr   executorch.exir.errorr   executorch.exir.graph_moduler    executorch.exir.operator.convertr   executorch.exir.operator.utilr    executorch.exir.pass_baser!   executorch.exir.pass_managerr"   executorch.exir.passesr#   r$   r%   r&   r'   r(   r)   r*   .executorch.exir.passes.external_constants_passr+   r,   9executorch.exir.passes.insert_write_back_for_buffers_passr-   4executorch.exir.passes.normalize_view_copy_base_passr.   (executorch.exir.passes.quant_fusion_passr/    executorch.exir.passes.reinplacer0   0executorch.exir.passes.remove_graph_asserts_passr1   r2   2executorch.exir.passes.remove_mixed_type_operatorsr3   2executorch.exir.passes.replace_aten_with_edge_passr4   7executorch.exir.passes.replace_view_copy_with_view_passr5   %executorch.exir.passes.spec_prop_passr6   .executorch.exir.passes.weights_to_outputs_passr7   executorch.exir.print_programr8   r9   executorch.exir.schemar:   executorch.exir.tracerr;   %executorch.exir.verification.verifierr<   r=   r>   torch._export.passesr?   torch._export.utilsr@   torch._export.verifierrA   torch.exportrB   -torch.export._remove_auto_functionalized_passrC   torch.export.exported_programrD   rE   rF   rG   rH   rI   torch.fxrJ   r   torch.fx._compatibilityrK   "torch.fx.passes.infra.pass_managerrL   torch.utilsr   ValrM   torch.libraryrN   !executorch.exir.program.fb.loggerrO   ImportErrorr  r  r  r  r  r{   r  r,  r   r   r   r   r   r   r   r   r   r   r!  r5  r  r-  r  r=  r  r  r  r  r  r  r  r  r  rI  r  r  r)  r*  r.  r  rY  rY   r]   rZ   <module>r     sF    	  	 # P P P   1 K E 2 < V P < E - D L ; . 1	 	 	 V ; X K ? R E * ? 
 C 9 + (  * 1 : )	   !; 0 &.  >7'7HH  7 7z 7; tDN33 	< 7; tDN33 	@ 7;% tDN33 	.2AJ%H % %Qo Qh e,O O -Od e,M& M& -M&`
9%6 
9J* J/D J\ <@ 
# 
+3C= 
	(^ 
H <@#+3C=	(^. KO:>	CCC #+4

0E0E+F"GC 4

 5 567	C
 CL,
,,^H/ H"&Q: 21
2121jB,uzz,,-B,	%**

 B,J
$
$'6
$	
$$ ).uc4,,-u_,-u u tCH~.	u
  ~u upD%D$D 
D6 ()
 	 	1526#{OT#*>%??@{hx $sHX,>'>"?LM{
 d;c4+<&<!==>{ tCH~.{ ./{ { { *{| 9 2626#	OOT#*>%??@OtCH~.O ./O 	O
 O Odq qh	C@ C@m5  	C HcUCZ$8 	s   4P P43P4