
    i.                        S SK r S SKrS SKrS SKJrJr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JrJr  S S	KJr  S S
KJr   " S S5      r " S S5      rS\\-  \	-  S\4S jr  S$S\\-  \	-  S\ S\ 4S jjr!S r"S\S\#4S jr$SSSS S 4S\S\#S-  S\ S\ S\\/\#S-  4   S \\/\#S-  4   4S! jjr%  S$S"\S\\-  \	-  S\ S\ 4S# jjr&g! \ a
    \" S5        e f = f)%    N)AnyCallableType)EdgeProgramManagerExecutorchProgramManager)%_update_exported_program_graph_module)Verifier)ExportedProgram)GraphModuleNode)configconstsvisualize_from_config)ModelExplorerConfig)!PytorchExportedProgramAdapterImplzXError: 'model_explorer' is not installed. Install using devtools/install_requirements.shc                   |    \ rS rSr% SrSrS\R                  -  \S'   Sr	\
\S'   SrSS\S	\
S-  4S
 jjrS rS rSrg)SingletonModelExplorerServer"   zSingleton context manager for starting a model-explorer server.
If multiple ModelExplorerServer contexts are nested, a single
server is still used.
Nserverr   num_openg      @open_in_browserportc                     [         R                  ci  S/nU(       d  UR                  S5        Ub+  UR                  S5        UR                  [        U5      5        [        R
                  " U5      [         l        g g Nzmodel-explorerz--no_open_in_browserz--port)r   r   appendstr
subprocessPopenselfr   r   commands       t/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/executorch/devtools/visualization/visualization_utils.py__init__%SingletonModelExplorerServer.__init__,   sa    '..6'(G"56x(s4y)2<2B2B72K(/ 7    c                     [         R                  S-   [         l        [        R                  " [         R                  5        U $ )N   )r   r   timesleepwait_after_startr    s    r"   	__enter__&SingletonModelExplorerServer.__enter__6   s2    (11A5 	%- 	

/@@Ar%   c                    [         R                  S-
  [         l        [         R                  S:X  aj  [         R                  bX  [         R                  R                  5          [         R                  R	                  [         R
                  5        S [         l        g g g ! [        R                   a!    [         R                  R                  5          NBf = f)Nr'   r   )	r   r   r   killwaitr*   r   TimeoutExpired	terminater    typevalue	tracebacks       r"   __exit__%SingletonModelExplorerServer.__exit__=   s    (11A5 	%- (00A5+22>,3388:D077<<4EE
 7;,3 ? 6 "00 D077AACDs   !-B 2CC TN)__name__
__module____qualname____firstlineno____doc__r   r   r   __annotations__r   intr*   boolr#   r,   r7   __static_attributes__r9   r%   r"   r   r   "   sR    
 '+FD:###*HcL L3: L;r%   r   c                   D    \ rS rSrSrSrSS\S\S-  4S jjrS r	S	 r
S
rg)ModelExplorerServerM   z5Context manager for starting a model-explorer server.g       @Nr   r   c                     S/nU(       d  UR                  S5        Ub+  UR                  S5        UR                  [        U5      5        [        R                  " U5      U l        g r   )r   r   r   r   r   r   s       r"   r#   ModelExplorerServer.__init__R   sN    #$NN12NN8$NN3t9% &&w/r%   c                 D    [         R                  " U R                  5        g N)r(   r)   r*   r+   s    r"   r,   ModelExplorerServer.__enter__[   s    

4(()r%   c                     U R                   R                  5          U R                   R                  U R                  5        g ! [        R
                   a    U R                   R                  5          g f = frJ   )r   r/   r0   r*   r   r1   r2   r3   s       r"   r7   ModelExplorerServer.__exit__^   sT    	$KKT223(( 	$KK!!#	$s   %A .A32A3)r   r:   )r;   r<   r=   r>   r?   r*   rB   rA   r#   r,   r7   rC   r9   r%   r"   rE   rE   M   s,    ?0 03: 0*$r%   rE   visualizablereturnc                     [        U [        5      (       a  U $ [        U [        [        45      (       a  U R	                  5       $ [        SU  35      e)Nz Cannot get ExportedProgram from )
isinstancer
   r   r   exported_programRuntimeError)rN   s    r"   _get_exported_programrT   f   sM     ,00,!35M NOO,,..
9,H
IIr%   Freuse_serverno_open_in_browserc                     [        5       n[        R                  nUR                  S[	        U 5      US9  U(       a  UR                  5         [        SUR                  SU5      US.UD6  g)a/  Wraps the visualize_from_config call from model_explorer.
For convenience, figures out how to find the exported_program
from EdgeProgramManager and ExecutorchProgramManager for you.

See https://github.com/google-ai-edge/model-explorer/wiki/4.-API-Guide#visualize-pytorch-models
for full documentation.

Executorch)rR   settingsr   )r   rV   Nr9   )r   r   DEFAULT_SETTINGSadd_model_from_pytorchrT   set_reuse_servervisualize_model_explorerpop)rN   rU   rV   kwargs
cur_configrY   s         r"   	visualizera   p   sp     J&&H%%.|< & 
 ##% zz(J/- r%   c                      [        S0 U D6  g)z9Wraps the visualize_from_config call from model_explorer.Nr9   )r   )r_   s    r"   r]   r]      s      
r%   r`   	file_namec           	      v   [         R                  " U R                  5       S   5      n[         R                  " US   5      S   nU H  nSUS'   M
     SU[        U5       VVs/ s H	  u  pTXES.PM     snnS.n[	        US5       n[         R
                  " Xg5        S	S	S	5        g	s  snnf ! , (       d  f       g	= f)
zSave the graphs stored in the `cur_config` in JSON format, which can be loaded by the Model Explorer GUI.

:param cur_config: ModelExplorerConfig containing the graph for visualization.
:param file_name: Name of the JSON file for storage.
graphs_listr   graphsrX   collectionLabel)graphlevel)labelrf   graphsWithLevelwN)jsonloadsget_transferrable_data	enumerateopendump)r`   rc   re   rf   rh   ri   	json_datafs           r"   _save_model_as_jsonru      s     **Z>>@OPKZZA'1F #/  
 AJ6AR
ARe,AR
I 
i			) 
	
 
	s   "B$
B**
B8c                 :    U R                   R                  SS 5      $ )Ndelegation_tagmetagetnodes    r"   <lambda>r}      s    $Jr%   c                 :    U R                   R                  SS 5      $ )Nclusterrx   r{   s    r"   r}   r}      s    TYY]]9d3r%   rR   json_file_nameget_node_partition_nameget_node_qdq_cluster_namec                 8   [        5       n[        U [        R                  5      nUR	                  5       n	[        U R                  R                  5      n
U	S   S   R                  n/ n[        XSS9 H  u  pSnU" U5      =nbF  UU;  a  UR                  U5        UR                  U5      nUR                  SS5      nUS	U S
U S3-  nU" U5      =nb/  [        U5      S:w  a  US-  nUR                  SS5      nUSU S3-  nXl        M     [        UR                  5      nUR                  R                  U	5        SnSSU SU 30nUR                  R                  U5        Ub  [!        Xq5        gU(       a  UR#                  5         [%        U40 UDSU0D6  g)a  Visualize exported programs using the Model Explorer. The QDQ clusters and individual partitions are highlighted.

    To install the Model Explorer, run `devtools/install_requirements.sh`.
    To display a stored json file, first launch the Model Explorer server by running `model-explorer`, and then
     use the GUI to open the json.

    NOTE: FireFox seems to have issues rendering the graphs. Other browsers seem to work well.

:param exported_program: Program to visualize.
:param json_file_name: If not None, a JSON of the visualization will be stored in the provided file. The JSON can
                        then be opened in the Model Explorer GUI later.
                       If None, a Model Explorer instance will be launched with the model visualization.
:param no_open_in_browser: If `True`, a browser instance with the model explorer will NOT be launched, and only the
                            URI to the model explorer server with the visualization will be printed.
:param reuse_server: If True, an existing instance of the Model Explorer server will be used (if one exists).
                      Otherwise, a new instance at a separate port will start.
:param get_node_partition_name: Function which takes a `Node` and returns a string with the name of the partition
                                 the `Node` belongs to, or `None` if it has no partition.
:param get_node_qdq_cluster_name: Function which takes a `Node` and returns a string with the name of the QDQ
                                   cluster the `Node` belongs to, or `None` if it has no cluster.
:param kwargs: Additional kwargs for the `visualize_from_config()` function.
rf   r   T)strict N/:z
partition z ()z	cluster (rX   urlz	graphs://rV   )r   r   r   rZ   convertlistrh   nodeszipr   indexreplacelen	namespacere   model_sourcesru   r\   r   )rR   r   rV   rU   r   r   r_   r`   adapterrf   r   explorer_nodesknown_partition_namesexplorer_noder|   r   partition_namepartition_idsafe_partition_namecluster_namesafe_cluster_namegraphs_indexnamemodel_sources                           r"   visualize_with_clustersr      s   H J 0&11G __F!''--.EH%a(..N ">F 	5d;;NH %::%,,^<066~FL"0"8"8S# :l^26I5J!LLI5d;;LH 9~"S 	 !- 4 4S! 9%6$7q99I"+?  GD z--.L!!&)D(-4&,/P'QL##L1!J7 '')	
	
  2	
r%   graph_modulec                 h     " S S[         5      n[        U5      n[        XU/S9n[        XU40 UD6  g)a#  Overrides the graph_module of the supplied exported_program with 'graph_module' before visualizing.
Also disables validating operators to allow visualizing graphs containing custom ops.

A typical example is after running passes, which returns a graph_module rather than an ExportedProgram.
c                   6    \ rS rSrSrS\\\   S4   4S jrSr	g) visualize_graph.<locals>._any_opi'  ANY_OPrO   .c                     [         4$ rJ   )r   r+   s    r"   allowed_op_types1visualize_graph.<locals>._any_op.allowed_op_types*  s
    ;r%   r9   N)
r;   r<   r=   r>   dialecttupler   r   r   rC   r9   r%   r"   _any_opr   '  s     	eDIsN&; 	r%   r   )override_verifiersN)r	   rT   r   ra   )r   rR   rU   rV   r_   r   s         r"   visualize_graphr     sA    (  --=><G9 .@KFKr%   )TF)'rm   r   r(   typingr   r   r   executorch.exirr   r    executorch.exir.program._programr   torch._export.verifierr	   torch.export.exported_programr
   torch.fxr   r   model_explorerr   r   r   model_explorer.configr   3model_explorer.pytorch_exported_program_adater_implr   ImportErrorprintr   rE   rT   rB   ra   r]   r   ru   r   r   r9   r%   r"   <module>r      s      & & H , 9 &

DD9(; (;V$ $2J!$669QQJJ $!$669QQ : $7  C  < "&$=
 	4e
%e
$Je
 e
 	e

 &tfcDj&89e
  (	d
 e
V $	LL%(::=UUL L 	L  
	b 
	
s   C C+