Ë
    f^(h]Š  ã                   óx  — d dl Z d dlmZ d dlmZmZm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 dd	lmZmZmZmZmZmZmZ g d
¢Z e j4                  e«      Z e
d¬«       G d„ de«      «       Z e
d¬«       G d„ de«      «       Z e
d¬«       G d„ de«      «       Z e G d„ d«      «       Z! G d„ d«      Z"y)é    N)Ú	dataclass)ÚAnyÚCallableÚOptional)Úcompatibility)Úmap_argé   )Ú	ShapeProp)Úsplit_by_tags)ÚCALLABLE_NODE_OPSÚFxNetAccFusionsFinderÚNamesÚNodeListÚNodeSetÚTensorOrTensorsÚTensors)ÚFxNetMinimizerBadModuleErrorÚFxNetMinimizerRunFuncErrorÚ!FxNetMinimizerResultMismatchErrorF)Úis_backward_compatiblec                   ó   — e Zd ZdZy)r   z9
    Raised if failed to split out a minimize module
    N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© ó    úZ/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/fx/passes/net_min_base.pyr   r   !   ó   „ òr   r   c                   ó   — e Zd ZdZy)r   z@
    Raised if error occurs during run_a or run_b functions
    Nr   r   r   r   r   r   (   r    r   r   c                   ó   — e Zd ZdZy)r   zJ
    Raised if comparing function thinks the results are mismatching.
    Nr   r   r   r   r   r   /   r    r   r   c                   ó^   — e Zd ZU dZdZeed<   dZeed<   dZ	eed<   dZ
eed<   dZeed<   d	„ Zy
)Ú_MinimizerSettingBaseaÈ  
    Args:
    `accumulate_error`: Instead of using a's input for both converted module to verify
    , use the previous outputs of each converted module as input to accumulate the
    errors.

    `traverse_method`: "sequential" or "binary" or "accumulate"
    Determine the way of traverse the nodes in FX module.

    `find_all`: Minimizer will go through the entire model and return all problematic nodes.

    `return_intermediate`: If true, when using `run_nodes()` function to run the
    model, intermediate results of all the ops will be returned as output.

    `all_outputs`: If true, when using `_run_and_compare()` function,
    all the output nodes in the subgraph will be used for comparison.
    FÚaccumulate_errorÚ
sequentialÚtraverse_methodÚfind_allÚreturn_intermediateÚall_outputsc                 ód   — d}t        | «      j                  «       D ]  \  }}|d|› d|› d�z  }Œ |S )NzFX Minimizer Settings:
ú	ú: ú
)ÚvarsÚitems)ÚselfÚsettings_strÚkÚvs       r   Ú__str__z_MinimizerSettingBase.__str__P   sG   € Ø1ˆä˜“J×$Ñ$Ó&ò 	,‰DˆAˆqØ˜b   2 a S¨˜OÑ+‰Lð	,ð Ðr   N)r   r   r   r   r%   ÚboolÚ__annotations__r'   Ústrr(   r)   r*   r5   r   r   r   r$   r$   6   sB   … ñð$ #Ð�dÓ"Ø'€O�SÓ'Ø€HˆdÓØ %Ð˜Ó%Ø€K�Óór   r$   c                   ó¾  — e Zd ZdZ	 	 d6dej
                  j                  dedee	e	e
geeef   f   dedeeeej
                  j                  egdf      deeeeegdf      fd	„Zd7d„Z	 d8dej
                  j                  deded
e	fd„Z	 d8dej
                  j                  deded
e	fd„Zde	de	dej
                  j                  fd„Zdej
                  j                  ded
eeef   fd„Zdefd„Zded
eej
                  j                  ef   fd„Z	 d8dej
                  j                  dede
defd„Zd ed!ed"ed
efd#„Zded
efd$„Zded
efd%„Zded!ed"ed&ed
ef
d'„Z ded&ee   d
efd(„Z!ded
efd)„Z"ded
efd*„Z#d ed!ed"ed
efd+„Z$d ed,e%d
efd-„Z&d.ee   d/ee   d
efd0„Z'd6d.ee   d/ee   fd1„Z(d2e%e   fd3„Z)d4„ Z*	 	 	 	 d9d.ee   d/ee   d,ee%   d&ee   d
ef
d5„Z+y):Ú_MinimizerBaseaÂ  
    This class is used to automatically find problematic nodes in a model. It takes a FX
    graphmodule and generate some submodules while traverse the graph. Then two functions
    `run_a` and `run_b` will be used to run the same submodule and a function `compare_fn`
    will be used to compare the results.

    Currently we provides two ways to traverse the graph and generate submodules.
        1. Sequential traversal: this will traverse the graph node by node and generate
           one submodule with one sigle node.
        2. Binary searching: this will do a binary search style traversal on the graph.

    For internal Users, a guide can be found here https://fb.quip.com/HDtuAgiKGfkP.
    NÚmoduleÚsample_inputÚ
compare_fnÚsettingsÚmodule_exporterÚexclusion_fnc                 ó   — t        |t        j                  j                  «      sJ ‚|| _        || _        || _        || _        || _        || _	        i | _
        i | _        i | _        g | _        d| _        | j                  j                  j                   D �ch c]  }|j"                  t$        v sŒ|’Œ }}| j'                  «         t)        | j                  |«      «       | _        | j                  j                  j                   D �cg c]  }|j"                  dk(  sŒ|j,                  ‘Œ  }	}t/        |	«      t/        | j
                  «      k(  sJ ‚t1        |	«      D ])  \  }
}||
   | j                  |<   ||
   | j                  |<   Œ+ y c c}w c c}w )Nr   Úplaceholder)Ú
isinstanceÚtorchÚfxÚGraphModuler;   r<   r=   r?   r>   r@   Ú	a_outputsÚ	b_outputsÚresultsÚreportsÚ	iterationÚgraphÚnodesÚopr   Úrun_shape_propr   ÚfusionsÚnameÚlenÚ	enumerate)r1   r;   r<   r=   r>   r?   r@   ÚnodeÚcallable_nodesÚplaceholdersÚirQ   s               r   Ú__init__z_MinimizerBase.__init__h   sy  € ô ˜&¤%§(¡(×"6Ñ"6Ô7Ð7Ð7àˆŒØ(ˆÔØ$ˆŒØ.ˆÔØ ˆŒØ(ˆÔð *,ˆŒð *,ˆŒð (*ˆŒð )+ˆŒð  ˆŒð "Ÿ[™[×.Ñ.×4Ñ4ö
Ø¸¿¹ÔCTÒ8TŠDð
ˆð 
ð 	×ÑÔØIÔ,¨T¯[©[¸.ÓIÓKˆŒð #'§+¡+×"3Ñ"3×"9Ñ"9ö
Ø¸T¿W¹WÈÓ=UˆD�I‹Ið
ˆð 
ô �<Ó ¤C¨×(9Ñ(9Ó$:Ò:Ð:Ð:ô ! Ó.ò 	3‰GˆAˆtØ#/°¡?ˆD�N‰N˜4Ñ Ø#/°¡?ˆD�N‰N˜4Ò ñ	3ùò
ùò
s   ÂFÂ.FÄFÄFÚreturnc                 ó\   —  t        | j                  «      j                  | j                  Ž  y)z‘
        Helper function to run shape propagation on module. Can be overridden by
        subclasses for custom shape propagation logic.
        N)r
   r;   Ú	propagater<   )r1   s    r   rO   z_MinimizerBase.run_shape_propž   s#   € ð
 	)Œ	�$—+‘+Ó×(Ñ(¨$×*;Ñ*;Ò<r   ÚmodÚinputsÚ
report_idxc                 ó   — t        d«      ‚)zz
        Run `mod` with `inputs` and generate output. The output will be compared with
        output of run_b().
        zrun_a() is not implemented.©ÚRuntimeError©r1   r\   r]   r^   s       r   Úrun_az_MinimizerBase.run_a¥   ó   € ô Ð8Ó9Ð9r   c                 ó   — t        d«      ‚)zz
        Run `mod` with `inputs` and generate output. The output will be compared with
        output of run_a().
        zrun_b() is not implemented.r`   rb   s       r   Úrun_bz_MinimizerBase.run_b®   rd   r   Úa_resultÚb_resultÚ	submodulec                 óü  — t        d„ |j                  j                  D «       «      }t        |j                  d   t
        j                  j                  «      rM|| j                  |j                  d   j                  <   || j                  |j                  d   j                  <   yt        |j                  d   «      D ]=  \  }}||   | j                  |j                  <   ||   | j                  |j                  <   Œ? y)aÂ  
        Store the outputs of self.run_a() and self.run_b() into self.a_outputs and
        self.b_outputs, so that we can use them when execute preceding nodes that
        use those outputs as inputs.

        Args:
            a_result: Output of self.run_a(). Could be a tensor or tensors.
            b_result: Output of self.run_b(). Could be a tensor or tensors.
            submodule: The module that generates a_result and b_result.
        c              3   ó@   K  — | ]  }|j                   d k(  sŒ|–— Œ y­w)ÚoutputN)rN   )Ú.0rT   s     r   ú	<genexpr>z0_MinimizerBase._store_outputs.<locals>.<genexpr>Ç   s    è ø€ ò 
Ø°d·g±gÀÓ6IŒDñ
ùs   ‚—r   N)ÚnextrL   rM   rC   ÚargsrD   rE   ÚNoderG   rQ   rH   rS   )r1   rg   rh   ri   Úoutput_noderW   Úargs          r   Ú_store_outputsz_MinimizerBase._store_outputs·   sÓ   € ô  ñ 
Ø&Ÿ_™_×2Ñ2ô
ó 
ˆô
 �k×&Ñ& qÑ)¬5¯8©8¯=©=Ô9Ø7?ˆD�N‰N˜;×+Ñ+¨AÑ.×3Ñ3Ñ4Ø7?ˆD�N‰N˜;×+Ñ+¨AÑ.×3Ñ3Ò4ô $ K×$4Ñ$4°QÑ$7Ó8ò 7‘��3Ø+3°A©;�—‘˜sŸx™xÑ(Ø+3°A©;�—‘˜sŸx™xÒ(ñ7r   Úmain_moduleÚsubmod_pathc                 ó²  ‡
— g Š
g }t        ||«      }|j                  j                  D �cg c]  }|j                  dk(  sŒ|j                  ‘Œ  }}t        |«      | j                  j                  «       k  rD|D ]>  }‰
j                  | j                  |   «       |j                  | j                  |   «       Œ@ n}| j                  j                  rt        d|› d�«       dt        j                  j                  dt         fˆ
fd„}|j#                  |«      }	 || j$                  Ž  |	j'                  «        ‰
}| j                  j                  s‰
‰
fS ‰
|fS c c}w )al  
        Try get submodule inputs from stored outputs. If not found then use
        torch_glow.get_submod_inputs to get the inputs.

        If accumulate_error is False, use a_input for run_a() and run_b()
        otherwise use a_input for run_a and b_input for run_b.

        Args:
            main_module: Top-levlel fx module.
            submod_path: Path to the submodule we want to run and compare results.

        Returns:
            a_input: List of tensor(s) that will be used by run_a() as submodule inputs.
            b_input: List of tensor(s) that will be used by run_b() as submodule inputs.
        rB   z)Can't find previous stored outputs named ú!r1   r]   c                 ó
   •— |Šy ©Nr   )r1   r]   Úa_inputs     €r   Ú
get_inputsz5_MinimizerBase._get_submod_inputs.<locals>.get_inputsù   s   ø€ à ‘r   )ÚgetattrrL   rM   rN   rQ   ÚsetrG   ÚkeysÚappendrH   r>   r%   ÚprintrD   ÚnnÚModuler   Úregister_forward_pre_hookr<   Úremove)r1   ru   rv   Úb_inputri   rT   rV   rQ   r|   Úhandler{   s             @r   Ú_get_submod_inputsz!_MinimizerBase._get_submod_inputsÕ   s5  ø€ ð$ ˆØˆÜ˜K¨Ó5ˆ	à"+§/¡/×"7Ñ"7ö
Ø¸4¿7¹7ÀmÓ;SˆD�I‹Ið
ˆð 
ô ˆ|Ó §¡× 3Ñ 3Ó 5Ò5Ø$ò 5�Ø—‘˜tŸ~™~¨dÑ3Ô4Ø—‘˜tŸ~™~¨dÑ3Õ4ñ5ð �}‰}×-Ò-ÜÐAÀ,ÀÈqÐQÔRð!¤§¡§¡ð !¼#õ !ð
 ×8Ñ8¸ÓDˆFÙ˜×*Ñ*Ñ+Ø�M‰MŒOàˆGà�}‰}×-Ò-Ø˜GÐ#Ð#à˜ÐÐùò;
s
   ªE¿EÚselected_nodesc                 óâ   — | j                   j                  j                  D ]L  }|j                  t        vrŒ||v rd|_        Œ"t        d„ |j                  D «       «      rd|_        ŒFd|_        ŒN y)ag  
        Tag selected nodes with tag "minimize". Nodes with the same tags will
        be split to the same submodule afterwards.

        Args:
            selected_nodes: Nodes that we want to minimize. We will tag those nodes
                with "minimize", all preceding nodes with "main_0" and all following
                nodes with "main_1".
        Úminimizec              3   ó\   K  — | ]$  }|j                   t        v r|j                  d v –— Œ& y­w)>   Úmain_1r‹   N)rN   r   Útag)rm   Úns     r   rn   z,_MinimizerBase._tag_nodes.<locals>.<genexpr>  s/   è ø€ ò àØ—4‘4Ô,Ñ,ð —‘Ð/Ô/ñùs   ‚*,r�   Úmain_0N)r;   rL   rM   rN   r   rŽ   ÚanyÚall_input_nodes)r1   r‰   rT   s      r   Ú
_tag_nodesz_MinimizerBase._tag_nodes	  sm   € ð —K‘K×%Ñ%×+Ñ+ò 	$ˆDØ�w‰wÔ/Ñ/Øà�~Ñ%Ø%�•Üñ à×-Ñ-ôô ð
 $�•à#�•ñ	$r   rM   c                 óê   — | j                  |«       t        | j                  g d¢«      }d}|j                  «       D ]  \  }}d|vrŒ|dk(  r|}Œt	        d|› �«      ‚ |dk(  rt	        d|› �«      ‚||fS )ak  
        Split self.module so that one submodule consists of `nodes` and only `nodes`.

        Args:
            nodes: Nodes that we want to include in the minimize submodule.

        Returns:
            split_module (torch.fx.GraphModule): the module after split.
            submodule_name (str): the name of the submodule that consists of `nodes`.
        )r�   r‹   r�   Ú r‹   z0Expected only one minimize submodule with nodes z,Minimize submodule was not found with nodes )r“   r   r;   Únamed_childrenr   )r1   rM   Úsplit_moduleÚsubmodule_nameÚ
child_nameÚ_s         r   Ú_build_submodulez_MinimizerBase._build_submodule"  s£   € ð 	�‰˜Ôô % T§[¡[Ò2RÓSˆð !ˆØ)×8Ñ8Ó:ò 
	‰MˆJ˜à Ñ+Øà Ò#Ø!+‘ä2ØFÀuÀgÐNóð ð
	ð ˜RÒÜ.Ø>¸u¸gÐFóð ð ˜^Ð+Ð+r   r—   Úsubmod_nameÚoutput_namesc                 ó  — t        ||«      }| j                  ||«      \  }}t        | j                  «      dk(  r"| j                  j	                  g «       d| _        | j                  |dk\  r|n| j
                  dz
     }|j	                  d«       |rÞ| j                  j                  sÈg }	|j                  j                  D ]L  }
|
j                  dk(  r|j                  j                  |
«       |
j                  |v sŒ<|	j	                  |
«       ŒN |j                  j                  t        |	«      dk(  r|	d   n
t        |	«      «       |j                  j                  «        |j!                  «        |j                  j                  D ])  }
|
j                  dk(  sŒt#        |
j$                  d„ «      }Œ+ 	 | j'                  |||«      }| j)                  |||«      }| j+                  |||«       |}|€D �cg c]  }t1        |«      ‘Œ }}| j3                  |||«      \  }}|| j4                  <   |j	                  d	|› �«       |s‡|j	                  d
|› �«       | j6                  rYt9        |t        «      r|d   }| j7                  ||t1        |d   «      dz   «       | j7                  ||t1        |d   «      dz   «       t;        d
|› �«      ‚y# t,        $ r-}|j	                  d|› d|› �«       t/        d|› d|› �«      ‚d}~ww xY wc c}w )a¥  
        Run the submodule in `split_module` that has name `submod_name`
        using `self.run_a` and `self.run_b` and compare their results.

        Args:
            split_module: Main module that contains the minimize submodule.
            submod_name: Name of the minimize submodule.
            output_names: Names of the node we want to output. If None, we
                will use the original output.
        r   r	   zRun and compare ...rl   c                 ó   — | j                   S rz   )rQ   )Úxs    r   ú<lambda>z1_MinimizerBase._run_and_compare.<locals>.<lambda>u  s
   € ¸!¿&¹&€ r   zException raised when running r-   NzNumerical accuracy = zResult mismatch for éÿÿÿÿÚ_cpuÚ_acc)r}   rˆ   rR   rJ   r€   rK   r>   r*   rL   rM   rN   Ú
erase_noderQ   rl   ÚtupleÚlintÚ	recompiler   rp   rc   rf   rt   Ú	Exceptionr   r8   r=   rI   r?   rC   r   )r1   r—   rœ   r�   r^   ri   r{   r†   ÚreportÚoutput_nodesrT   Ú
result_keyrg   rh   ÚeÚnamesr4   Únumeric_resultÚbool_results                      r   Ú_run_and_comparez_MinimizerBase._run_and_compareH  sè  € ô" ˜L¨+Ó6ˆ	Ø×2Ñ2°<ÀÓMÑˆ�äˆt�|‰|Ó Ò!Ø�L‰L×Ñ Ô#ØˆDŒNà—‘¨J¸!ªO™jÀÇÁÐRSÑASÑTˆØ�‰Ð+Ô,á §¡× 9Ò 9Ø%'ˆLØ!Ÿ™×-Ñ-ò .�Ø—7‘7˜hÒ&Ø—O‘O×.Ñ.¨tÔ4à—9‘9 Ò,Ø ×'Ñ'¨Õ-ð.ð �O‰O×"Ñ"Ü#& |Ó#4¸Ò#9�˜Q’¼uÀ\Ó?Rôð �O‰O× Ñ Ô"Ø×ÑÔ!ð —O‘O×)Ñ)ò 	BˆDØ�w‰w˜(Ó"Ü$ T§Y¡YÑ0@ÓA‘
ð	Bð	Ø—z‘z )¨W°jÓAˆHØ—z‘z )¨W°jÓAˆHØ×Ñ ¨(°IÔ>ð $ˆØÐØ%/Ö0 ”S˜•VÐ0ˆEÐ0à&*§o¡o°hÀÈ%Ó&PÑ#ˆ˜à#1ˆ�‰�ZÑ Ø�‰Ð-¨nÐ-=Ð>Ô?ÙØ�M‰MÐ0°°Ð=Ô>Ø×#Ò#Ü˜j¬%Ô0Ø!+¨B¡�Jà×$Ñ$ØØÜ˜
 1™Ó&¨Ñ/ôð ×$Ñ$ØØÜ˜
 1™Ó&¨Ñ/ôô
 4Ð6JÈ:È,Ð4WÓXÐXð# øô ò 	Ø�M‰MÐ:¸;¸-ÀrÈ!ÈÐMÔNÜ,Ø0°°¸RÀ¸sÐCóð ûð	üò 1s   Æ39K Ç4LË	LË(K<Ë<LÚ	all_nodesÚ	start_idxÚend_idxc                 óº  — t        «       }||| }g }| j                  �A| j                  |||«       t        |«      dk(  r dg}| j                  j	                  |«       |S |d   j
                  }|d   j
                  }| xj                  dz  c_        | j                  j	                  |«       |j	                  d| j                  › �«       |j	                  d|› d|› d|dz
  › d|› d	t        |«      › �
«       t        |«      }		 | j                  |	«      \  }
}| j                  |
||g«       |j	                  d
«       | j                  |«       t        «       S # t        t        f$ rô t        |«      dk(  r*|j	                  d|	› d�«       | j                  |«       |	cY S |j	                  d«       | j                  |«       t        |«      dz  }| j                  ||||z   «      }t        |«      dk7  r| j                  j                  s|cY S | j                  |||z   |«      }t        |«      dk(  r%|j	                  d|› �«       | j                  |«       |cY S w xY w)z9
        Recursive binary search implementation.
        r   úAll nodes are excluded by userr¢   r	   zBinary search iteration úFrom node index ú:ú to ú&. Size of the interested node list is úNo discrepancy found.zcThis is the last node in the sub-module. Search in the current branch is successful with culprit = ú.úMProceed to split and lower the halves of the current sub-module individually.é   zaFurther split and lowering found no errors. Unable to minimize the submodule with list of nodes: )r~   r@   rR   rJ   r€   rQ   rK   r›   r±   Úprint_reportr   r   Ú_binary_search_implr>   r(   )r1   r²   r³   r´   ÚculpritsrM   rª   Úfirst_node_nameÚoutput_node_nameÚ	cur_nodesr—   rœ   Úmids                r   rÀ   z"_MinimizerBase._binary_search_impl�  sm  € ô  ›EˆØ# I¨gÐ6ˆàˆØ×ÑÐ(Ø×Ñ˜e Y°Ô8Ü�5‹z˜QŠØ:Ð;�Ø—‘×#Ñ# FÔ+Ø�à ™(Ÿ-™-ˆØ  ™9Ÿ>™>ÐØ�Š˜!Ñ�Ø�‰×Ñ˜FÔ#Ø�‰Ð0°·±Ð0@ÐAÔBØ�‰Ø˜y˜k¨¨?Ð*;¸4ÀÈ!Á¸}ÈAÐN^ÐM_ð `3Ü36°u³:°,ð@ô	
ô ! ›Zˆ	ð&	Ø(,×(=Ñ(=¸iÓ(HÑ%ˆL˜+Ø×!Ñ! ,°Ð>NÐ=OÔPðD �M‰MÐ1Ô2Ø×Ñ˜fÔ%Ü“5ˆLøôE +Ô,MÐNò 	Ü�5‹z˜QŠØ—‘ðQØQZÐP[Ð[\ð^ôð ×!Ñ! &Ô)Ø Ò à�M‰Mð+ôð ×Ñ˜fÔ%ä�e“* ‘/ˆCØ×/Ñ/°	¸9ÀiÐRUÁoÓVˆHä�8‹} Ò!¨$¯-©-×*@Ò*@Ø’à×/Ñ/°	¸9Às¹?ÈGÓTˆHä�8‹} Ò!Ø—‘ðLØLQÈ7ðTôð ×!Ñ! &Ô)àŠOð=	ús!   Ä(E ÅAIÆA,IÈAIÉIc                 ó:   — | j                  |dt        |«      «      S )z7
        Binary search on `nodes` for culprit.
        r   )rÀ   rR   )r1   rM   s     r   Ú_binary_traversez_MinimizerBase._binary_traverseá  s   € ð ×'Ñ'¨¨q´#°e³*Ó=Ð=r   c                 ó†  — t        «       }|D �]q  }g }| j                  j                  |«       | xj                  dz  c_        |j                  d| j                  › d�«       |j                  d|j                  › �«       t
        j                  d|j                  «       |g}| j                  �l| j                  |dd«       t        |«      dk(  rK|j                  d|j                  › �«       | j                  |«       | j                  j                  s|c S �Œ|h}|| j                  v r| j                  |   }	 | j                  |«      \  }}| j                  |||j                  g«       | j                  |«       �Œt |S # t        $ rV |j!                  |«       |j                  d	|› �«       | j                  |«       | j                  j                  s|cY c S Y �ŒÕt"        $ rV |j%                  |«       |j                  d
|› �«       | j                  |«       | j                  j                  s|cY c S Y �Œ2w xY w)zX
        Traverse `nodes` one by one and determine if any of them is a culprit.
        r	   zSequential traverse iteration r¼   zVisit node: zVisit node: %sr¢   r   zUser exclusion : ú"Found culprit from numeric error: úFound culprit from run error: )r~   rJ   r€   rK   rQ   Ú_LOGGERÚinfor@   rR   r¿   r>   r(   rP   r›   r±   r   Úaddr   Úupdate)	r1   rM   rÁ   rT   rª   Ú	node_listrÄ   r—   rœ   s	            r   Ú_sequential_traversez#_MinimizerBase._sequential_traverseç  sü  € ô  ›Eˆàó '	$ˆDØ "ˆFØ�L‰L×Ñ Ô'Ø�NŠN˜aÑ�NØ�M‰MÐ:¸4¿>¹>Ð:JÈ!ÐLÔMØ�M‰M˜L¨¯©¨Ð4Ô5ä�L‰LÐ)¨4¯9©9Ô5Ø#' &ˆIØ× Ñ Ð,Ø×!Ñ! )¨R°Ô4Ü�y“> QÒ&Ø—M‘MÐ$5°d·i±i°[Ð"AÔBØ×%Ñ% fÔ-ØŸ=™=×1Ò1Ø'šá à"& ˆIà�t—|‘|Ñ#Ø ŸL™L¨Ñ.�	ð$Ø,0×,AÑ,AÀ)Ó,LÑ)�˜kØ×%Ñ% l°KÀ$Ç)Á)ÀÔMØ×!Ñ! &Ö)ð7'	$ðR ˆøô 5ò $Ø—‘˜TÔ"Ø—‘Ð BÀ4À&ÐIÔJØ×!Ñ! &Ô)Ø—}‘}×-Ò-Ø#”Oò .ä-ò $Ø—‘ 	Ô*Ø—‘Ð >¸t¸fÐEÔFØ×!Ñ! &Ô)Ø—}‘}×-Ò-Ø#”Oò .ð	$ús   Ä<AFÆAI Ç"AI È?I Úfind_last_nodec                 óš  — g }||z   dz  }|r|d|dz    n||d }| j                   r| j                  |dd«       t        |«      }|d   j                  }	|d   j                  }
|r|
n|	}| xj                  dz  c_        | j                  j                  |«       |j                  dd| j                  › �g«       |j                  d|rd	nd
› d�d|› d||   j                  › d|› d||   j                  › d�	d|	› d|
› �d|› �d||z
  dz   › �g«       t        | j                  «      dz
  }	 | j                  |«      \  }}| j                  |||
g|«       |j                  d|› d||   j                  › d�«       ||k(  rD|j                  dd|› d||   j                  › d�g«       | j                  |«       |r|dz   S |dz
  S |j                  d«       | j                  |«       |r| j                  ||dz   ||«      S | j                  ||||«      S # t        t        f$ r­ |j                  d|	› d|
› d�«       ||k(  r<|j                  dd|› d||   j                  › d�g«       | j                  |«       |cY S |j                  d«       | j                  |«       |r| j                  ||||«      cY S | j                  ||dz   ||«      cY S w xY w)zÌ
        Recursive block search implementation.
        find_last_node: If True, search for the last node which result in numerics difference
        if False: find first node in sorted node list
        r¾   Nr	   r¢   r   z==============================zBlock search iteration zSearch for ÚlastÚfirstz node in culpritsr·   r¸   r¹   z. zSubgraph constructed by zTargeting node: z$Size of the interested node list is z&Culprits not found from node start to r¼   z)This is the last node in the sub-module. z4Search in the current branch is successful with nodez, node name: r½   zCulprits found from node z6Search in the current branch is successful with node :)r@   r~   rQ   rK   rJ   r€   ÚextendrR   r›   r±   r¿   Ú_block_traverse_implr   r   )r1   rM   r³   r´   rÑ   rª   rÅ   Úcur_nodes_listrÄ   rÂ   Úlast_node_nameÚtarget_node_namer^   r—   rœ   s                  r   rÖ   z#_MinimizerBase._block_traverse_impl  sr  € ð ˆà˜7Ñ" qÑ(ˆÙ7E 5¨¨3°©7Ñ#3È5ÐQTÐQUÈ;ˆà×ÒØ×Ñ˜n¨b°"Ô5ä˜Ó'ˆ	à(¨Ñ+×0Ñ0ˆØ'¨Ñ+×0Ñ0ˆÙ-;™>ÀÐà�Š˜!Ñ�Ø�‰×Ñ˜FÔ#Ø�‰àØ)¨$¯.©.Ð)9Ð:ðô	
ð 	�‰à©™f¸GÐDÐDUÐVØ" 9 +¨Q¨u°YÑ/?×/DÑ/DÐ.EÀTÈ'ÈÐRSÐTYÐZaÑTb×TgÑTgÐShÐhjÐkØ*¨?Ð*;¸4ÀÐ?OÐPØ"Ð#3Ð"4Ð5Ø6°wÀÑ7JÈQÑ7NÐ6OÐPðô	
ô ˜Ÿ™Ó&¨Ñ*ˆ
ð<	XØ(,×(=Ñ(=¸iÓ(HÑ%ˆL˜+Ø×!Ñ!Ø˜k¨NÐ+;¸Zôð@ �M‰MØ8¸¸¸Q¸uÀS¹z¿¹Ð>OÈqÐQôð ˜CÒØ—‘àCØNØ$˜+ ]°5¸Ñ3C×3HÑ3HÐ2IÈÐKðôð ×!Ñ! &Ô)Ù(6�y 1‘}ÐI¸IÈ¹MÐIà�M‰Mð+ôð ×Ñ˜fÔ%áØ×0Ñ0Ø˜3 ™7 G¨^óð ð ×0Ñ0°¸	À3ÈÓWÐWøôo 2Ô3MÐNò 	Ø�M‰MØ+¨OÐ+<¸DÀÐ@PÐPQÐRôð ˜CÒØ—‘àCØPØ$˜+ ]°5¸Ñ3C×3HÑ3HÐ2IÈÐKðôð ×!Ñ! &Ô)Ø Ò à�M‰Mð+ôð ×Ñ˜fÔ%áØ×0Ñ0°¸	À3ÈÓWÒWà×0Ñ0Ø˜3 ™7 G¨^óò ð3	ús   Ä()H ÈA&K
É68K
Ê0K
Ë	K
c                 óž  — t        «       }|d   j                  }|d   j                  }d|› d|› �g}|j                  d«       | j                  j                  |«       d}t	        |«      dz
  }|€dnd}	|	s|rm|j                  d	«       | j                  |«       | j                  |||d«      }|j                  d
d|› d||   j                  › �g«       | j                  |«       |	s|s‘dg}
| j                  |
«       | j                  |d|dz    ||d«      }|
j                  d«       | j                  j                  |
«       |
j                  dd|› d||   j                  › �g«       | j                  |
«       |j                  |||dz    «       d||   › d||   › d�g}| j                  j                  |«       | j                  |«       |S )aÙ  
        Traverse topologically sorted node list
        Find minimium block (start_idx, end_idx) which contains the culprit
        1st pass: search for end_idx by finding the last node in culprit block
        where Numerical accuracy (0, end_idx) > threshold
        2nd pass: search for start_idx by finding the first node in culprit block
        where Numerical accuracy (start_idx, end_idx) < threshold
        Form minimum block by (start_idx - 1, end_idx)
        r   r¢   zBlock search from r¹   z2**************************************************r	   TFz(Start searching for last node in culpritzFinish Pass 1zFind end_idx = r¸   z)Start searching for first node in culpritzFinish Pass 2zFind start_idx = z'Finish searching, found minimum block (ú,ú))	r~   rQ   r€   rJ   rR   r¿   rÖ   rÕ   rÎ   )r1   rM   rÑ   rÁ   rÂ   rØ   Úlast_node_reportr³   r´   Úrun_bothÚfirst_node_reportÚresult_reports               r   Ú_block_traversez_MinimizerBase._block_traverse  s  € ô  ›EˆØ ™(Ÿ-™-ˆØ˜r™Ÿ™ˆØ0°Ð0AÀÀnÐEUÐVÐWÐØ×Ñ Ô)Ø�‰×ÑÐ,Ô-àˆ	Ü�e“*˜q‘.ˆØ)Ð1‘4°uˆñ ‘~Ø×#Ñ#Ð$NÔOØ×ÑÐ.Ô/Ø×/Ñ/°°yÀ'È4ÓPˆGØ×#Ñ#Ø  O°G°9¸A¸eÀG¹n×>QÑ>QÐ=RÐ"SÐTôð ×ÑÐ.Ô/ñ ™>Ø!LÐ MÐØ×ÑÐ/Ô0Ø×1Ñ1Ø�a˜' A™+Ð&¨	°7¸EóˆIð ×$Ñ$ XÔ.Ø�L‰L×ÑÐ 1Ô2Ø×$Ñ$à#Ø'¨	 {°!°E¸)Ñ4D×4IÑ4IÐ3JÐKðôð ×ÑÐ/Ô0ð 	�‰˜˜i¨'°A©+Ð6Ô7à5°e¸IÑ6FÐ5GÀqÈÈwÉÐHXÐXYÐZð
ˆð 	�‰×Ñ˜MÔ*Ø×Ñ˜-Ô(Øˆr   c                 ó  — t        «       }| j                  �| j                  |dd«       t        |«      dk(  r dg}| j                  j	                  |«       |S |d   j
                  }|d   j
                  }d|› d|› �g}t        |«      }	 | j                  |«      \  }}| j                  |||g«       | j                  |«       |S # t        t        f$ r* |j	                  d|› �«       | j                  |«       |cY S w xY w)zL
        run user defined `nodes` and determine if it is a culprit.
        r¢   r   r¶   zDefined graph from r¹   úFound culprit )r~   r@   rR   rJ   r€   rQ   r›   r±   r¿   r   r   )	r1   rM   rÁ   rª   rÂ   rÃ   rÄ   r—   rœ   s	            r   Ú_defined_traversez _MinimizerBase._defined_traverseº  s  € ô  ›EˆØ×ÑÐ(Ø×Ñ˜e R¨Ô,Üˆu‹:˜Š?Ø6Ð7ˆFØ�L‰L×Ñ Ô'ØˆOà ™(Ÿ-™-ˆØ  ™9Ÿ>™>ÐØ'¨Ð'8¸Ð=MÐ<NÐOÐPˆÜ  ›Zˆ	ð	Ø(,×(=Ñ(=¸iÓ(HÑ%ˆL˜+Ø×!Ñ! ,°Ð>NÐ=OÔPØ×Ñ˜fÔ%ð ˆøô 2Ô3MÐNò 	Ø�M‰M˜N¨9¨+Ð6Ô7Ø×Ñ˜fÔ%ØŠOð	ús   Â9C Ã6C?Ã>C?c                 óþ  — t        «       }t        «       }| j                  j                  rt        d«       |S |D ]ñ  }g }| j                  j                  |«       | xj                  dz  c_        |j                  d| j                  › d�«       |j                  |«       |j                  }|�t        |t        «      r|d   }|�t        |t        «      s
J d|› �«       ‚|j                  d|› �«       	 | j                  |«      \  }}| j                  |||g«       | j                  |«       Œó |S # t        t         f$ r= |j                  |«       |j                  d|› �«       | j                  |«       |cY c S w xY w)	Nz9'Find All' mode is not supported in accumulate traversal.r	   zAccumulate traverse iteration r¼   r   zminimize: node_name: z
Add node: rã   )r~   r>   r(   r�   rJ   r€   rK   rÍ   rQ   rC   r¦   r8   r›   r±   r¿   r   r   )	r1   rM   rÁ   Únodes_to_runrT   rª   Ú	node_namer—   rœ   s	            r   Ú_accumulate_traversez#_MinimizerBase._accumulate_traverseÕ  sw  € Ü›EˆÜ #£ˆð �=‰=×!Ò!ÜÐMÔNØˆOàò 	 ˆDØ "ˆFØ�L‰L×Ñ Ô'Ø�NŠN˜aÑ�NØ�M‰MÐ:¸4¿>¹>Ð:JÈ!ÐLÔMà×Ñ˜TÔ"àŸ	™	ˆIØÐ$¬°I¼uÔ)EØ% a™L�	ØÐ(¬ZØœ3ô.ð 3à& y kÐ2ó3ð ð �M‰M˜J y kÐ2Ô3ð Ø,0×,AÑ,AÀ,Ó,OÑ)�˜kØ×%Ñ% l°KÀ)ÀÔMØ×!Ñ! &Õ)ð)	 ð6 ˆøô 6Ô7QÐRò  Ø—‘˜TÔ"Ø—‘ ¨t¨fÐ5Ô6Ø×!Ñ! &Ô)Ø”ð	 ús   Ã39D0Ä0AE<Å;E<c           
      óœ  — t        «       }||| }t        |«      }| j                  �| j                  |||«       t        |«      }n4|D ]/  }|| j                  v sŒ|j                  | j                  |   «       Œ1 g }| j                  j                  |«       | xj                  dz  c_        |j                  d| j                  › d�«       |j                  d|› d|dz
  › dt        |«      › �«       	 | j                  |«      \  }	}
| j                  |	|
g «       |j                  d«       | j                  |«       t        «       S # t        $ r; |j                  |«       |j                  d|› �«       | j                  |«       |cY S t        $ r; |j                  |«       |j                  d	|› �«       | j                  |«       |cY S w xY w)
ú?
        Skip certain nodes in graph based on settings
        r	   z Nodes block r¼   r·   r¹   rº   r»   rÉ   rÊ   )r~   r@   rP   rÎ   rJ   r€   rK   rR   r›   r±   r¿   r   r   )r1   r²   r³   r´   rÁ   rM   rÄ   rT   rª   r—   rœ   s              r   Ú_skip_traverse_implz"_MinimizerBase._skip_traverse_implü  sº  € ô  ›EˆØ# I¨gÐ6ˆÜ  ›Zˆ	Ø×ÑÐ(Ø×Ñ˜e Y°Ô8Ü˜E›
‰Iàò 9�Ø˜4Ÿ<™<Ò'Ø×$Ñ$ T§\¡\°$Ñ%7Õ8ð9ð ˆØ�‰×Ñ˜FÔ#Ø�Š˜!Ñ�Ø�‰˜ d§n¡nÐ%5°QÐ7Ô8Ø�‰Ø˜y˜k¨¨g¸©k¨]ð ;3Ü36°u³:°,ð@ô	
ð
	Ø(,×(=Ñ(=¸iÓ(HÑ%ˆL˜+Ø×!Ñ! ,°¸RÔ@ð �M‰MÐ1Ô2Ø×Ñ˜fÔ%Ü“5ˆLøô 1ò 	Ø�O‰O˜IÔ&Ø�M‰MÐ>¸y¸kÐJÔKØ×Ñ˜fÔ%ØŠOÜ)ò 	Ø�O‰O˜IÔ&Ø�M‰MÐ:¸9¸+ÐFÔGØ×Ñ˜fÔ%ØŠOð		ús   Ã2'E ÅAGÆA GÇ
GÚ
skip_nodesc                 ó   — d}t        |«      }d}t        «       }||k  r_||   }|j                  |v r||kD  r| j                  |||«      }|dz   }n#||dz
  k(  r||k  r| j                  |||dz   «      }|dz  }||k  rŒ_|S )rê   r   r	   )rR   r~   rQ   rë   )r1   r²   rì   r³   Ú	num_nodesÚidxrÁ   rT   s           r   Ú_skip_traversez_MinimizerBase._skip_traverse'  s£   € ð ˆ	Ü˜	“Nˆ	ØˆÜ“5ˆØ�IŠoØ˜S‘>ˆDØ�y‰y˜JÑ&Ø˜’?Ø#×7Ñ7¸	À9ÈcÓR�HØ !™G‘	Ø˜	 A™Ò%¨)°sÒ*:Ø×3Ñ3°I¸yÈ#ÐPQÉ'ÓR�Ø�1‰HˆCð �I‹oð ˆr   ÚstartÚendc                 óî   — g }|du }| j                   j                  j                  D ]K  }|j                  t        vrŒ|j
                  |k(  rd}|r|j                  |«       |j
                  |k(  sŒJ |S  |S )zŠ
        Collect nodes in the model that between nodes with name of `start` and `end`.
        These two nodes are also included.
        NT)r;   rL   rM   rN   r   rQ   r€   )r1   rñ   rò   rM   Úadd_noderT   s         r   Ú_collect_nodesz_MinimizerBase._collect_nodes;  s|   € ð
 ˆØ˜D�=ˆà—K‘K×%Ñ%×+Ñ+ò 	ˆDØ�w‰wÔ/Ñ/Øà�y‰y˜EÒ!Ø�áØ—‘˜TÔ"à�y‰y˜CÓØàˆð	ð ˆr   c                 ó°  — | j                  ||«      }t        |«      }|D ]/  }|| j                  v sŒ|j                  | j                  |   «       Œ1 g }| j                  j
                  r|D �cg c]  }|j                  ‘Œ }}	 | j                  |«      \  }}| j                  |||«       yc c}w # t        t        f$ r}	t        |	«       Y d}	~	yd}	~	ww xY w)a]  
        Run part of the model from `start` node to `end` node. If `start` is None
        then we start from the beginning of the model. If `end` is None then we
        stop at the end of the model.

        Args:
            start: The name of the node which is the first node of the submodule
                we want to run. If set to None, then we'll start with the first
                node of the model.
            end: The name of the node which is the last node of the submodule we
                want to run. If set to None, we'll end with the last node of the
                model.
        N)rõ   r~   rP   rÎ   r>   r)   rQ   r›   r±   r   r   r�   )
r1   rñ   rò   rM   rÄ   rT   r�   r—   rœ   r­   s
             r   Ú	run_nodesz_MinimizerBase.run_nodesR  sÒ   € ð ×#Ñ# E¨3Ó/ˆÜ˜“Jˆ	àò 	5ˆDØ�t—|‘|Ò#Ø× Ñ  §¡¨dÑ!3Õ4ð	5ð ˆØ�=‰=×,Ò,Ø27Ö8¨$˜DŸI›IÐ8ˆLÐ8ð	Ø(,×(=Ñ(=¸iÓ(HÑ%ˆL˜+Ø×!Ñ! ,°¸\ÕJùò	 9øô 'Ü-ð
ò 	ô �!�H‰Hûð		ús   Á.B,Â'B1 Â1CÃ CÃCrª   c                 ó€   — t        t        |«      «      D ]'  }|dkD  rt        d||   z   «       Œt        ||   «       Œ) y )Nr   z . )ÚrangerR   r�   )r1   rª   rW   s      r   r¿   z_MinimizerBase.print_reportt  s>   € Ü”s˜6“{Ó#ò 	!ˆAØ�1ŠuÜ�e˜f Q™iÑ'Õ(ä�f˜Q‘iÕ ñ		!r   c                 óH   — | j                   D ]  }| j                  |«       Œ y rz   )rJ   r¿   )r1   rª   s     r   Úprint_reportsz_MinimizerBase.print_reports{  s#   € Ø—l‘lò 	&ˆFØ×Ñ˜fÕ%ñ	&r   c                 óê  — t        | j                  «       t        | j                  j                  «       | j	                  ||«      }| j                  j
                  dk(  r| j                  |«      S | j                  j
                  dk(  r| j                  |«      S | j                  j
                  dk(  r| j                  |«      S | j                  j
                  dk(  r|€t        d«      ‚| j                  ||«      S | j                  j
                  dk(  r| j                  |«      S | j                  j
                  dk(  r| j                  ||«      S t        d| j                  j
                  › d	�«      ‚)
az  
        Minimizing the model from node with name `start` to node with name `end` base
        on self.settings. Find culprits that causes FxNetMinimizerRunFuncError or
        FxNetMinimizerResultMismatchError errors.

        Args:
            start: The name of the node where we want to start minimizing. If set
                to None, then we'll start with the first node of the model.
            end: The name of the node where we want to terminate minimizing. If
                set to None, we'll end with the last node of the model.
            skip_nodes: The names of nodes where we want to skip during minimizing.
                It'll create subgraphs without these skip nodes under the hood.
                Only applicable in mode "skip".
            find_last_node: True if only last_node of a culprits is needed in mode "block".
                False if only the first_node of a culprits is needed.
                Only applicable in mode "block".

        Returns:
            nodes: A list of nodes that causes FxNetMinimizerRunFuncError or
                FxNetMinimizerResultMismatchError errors during minimizing.
        r&   ÚbinaryÚ
accumulateÚskipz<'skip_nodes' can't be None when 'traverse_method' is 'skip'.ÚdefinedÚblockzUnknown traverse method rx   )r�   r>   r;   rL   rõ   r'   rÐ   rÇ   rè   ra   rð   rä   rá   )r1   rñ   rò   rì   rÑ   rM   s         r   r‹   z_MinimizerBase.minimize  sC  € ô: 	ˆd�m‰mÔÜˆd�k‰k×ÑÔ à×#Ñ# E¨3Ó/ˆà�=‰=×(Ñ(¨LÒ8Ø×,Ñ,¨UÓ3Ð3à�=‰=×(Ñ(¨HÒ4Ø×(Ñ(¨Ó/Ð/à�=‰=×(Ñ(¨LÒ8Ø×,Ñ,¨UÓ3Ð3à�=‰=×(Ñ(¨FÒ2ØÐ!Ü"ØRóð ð ×&Ñ& u¨jÓ9Ð9à�=‰=×(Ñ(¨IÒ5Ø×)Ñ)¨%Ó0Ð0à�=‰=×(Ñ(¨GÒ3Ø×'Ñ'¨¨~Ó>Ð>äÐ5°d·m±m×6SÑ6SÐ5TÐTUÐVÓWÐWr   )NN)rY   N)r¢   )NNNN),r   r   r   r   rD   rE   rF   r   r   r   r   r¦   Úfloatr6   r$   r   r8   r   ÚintrX   rO   rc   rf   rt   rˆ   r   r“   r›   r±   rÀ   rÇ   rÐ   rÖ   rá   rä   rè   rë   Úlistrð   rõ   r÷   r¿   rû   r‹   r   r   r   r:   r:   Y   s·  „ ñð0 ØGKñ43à—‘×$Ñ$ð43ð ð43ð Ø˜o¨uÐ5°u¸UÀD¸[Ñ7IÐIñ
ð	43ð (ð43ð "Ø�g˜uŸx™x×3Ñ3°SÐ9¸4Ð?Ñ@ñ
ð43ð ˜x¨°3¸Ð(<¸dÐ(BÑCÑDó43ól=ð MOñ:Ø—8‘8×'Ñ'ð:Ø18ð:ØFIð:à	ó:ð MOñ:Ø—8‘8×'Ñ'ð:Ø18ð:ØFIð:à	ó:ð7à!ð7ð "ð7ð —8‘8×'Ñ'ó	7ð<2 Ø Ÿ8™8×/Ñ/ð2 Ø>Að2 à	ˆw˜ÐÑ	 ó2 ðh$¨ó $ð2$, gð $,°%¸¿¹×8LÑ8LÈcÐ8QÑ2Ró $,ðV ñSYà—h‘h×*Ñ*ðSYð ðSYð ð	SYð
 óSYðjBØ!ðBØ.1ðBØ<?ðBà	óBðH> hð >°7ó >ð/¨(ð /°wó /ðbeXØðeXØ*-ðeXØ8;ðeXØMQðeXà	óeXðN9Øð9Ø/7¸©~ð9à	ó9ðv xð °Gó ð6%¨(ð %°wó %ðN)Ø!ð)Ø.1ð)Ø<?ð)à	ó)ðV¨ð ¸dð Àwó ð( H¨S¡Mð ¸À¹ð È(ó ñ. ˜x¨™}ð  ¸(À3¹-ó  ðD! 4¨¡9ó !ò&ð  $Ø!Ø%)Ø)-ñ8Xà˜‰}ð8Xð �c‰]ð8Xð ˜T‘Nð	8Xð
 ! ™ð8Xð 
ô8Xr   r:   )#ÚloggingÚdataclassesr   Útypingr   r   r   rD   Útorch.fxÚtorch.fx._compatibilityr   Útorch.fx.noder   Ú
shape_propr
   Úsplit_utilsr   Útools_commonr   r   r   r   r   r   r   Ú__all__Ú	getLoggerr   rË   r©   r   r   r   r$   r:   r   r   r   ú<module>r     sÕ   ðã Ý !ß *Ñ *ã Û Ý 1Ý !å !Ý &÷÷ ñ ò€ð ˆ'×
Ñ
˜HÓ
%€ñ  eÔ,ô 9ó ó -ðñ  eÔ,ô ó ó -ðñ  eÔ,ô¨	ó ó -ðð ÷ð ó ð÷D^Xò ^Xr   