
    &Vjij(                        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 d dlmZ d dlmZ  ej        e          Ze                    ej                   g dZ ed	
          dedefd            Zdeeegef         dee         ddfdZdee         dee         dee         fdZ ed	
          dededefd            Z ed	
           G d d                      ZdS )    N)wraps)QueueCallable)compatibility)GraphModule)
PassResult)pass_result_wrapper this_before_that_pass_constraintPassManagerF)is_backward_compatiblefnreturnc                       dS t                      fd            }t          j                   st                     j        |_        |S )a+  
    Wrapper for passes which currently do not return a PassResult.
    This wrapper makes them return a PassResult containing the modified object
    and True for the "modified" flag.

    Args:
        fn (Callable[Module, Any])

    Returns:
        wrapped_fn (Callable[Module, PassResult])
    Nc                      |           }|t          | d          S t          |t                     r|S t          |t          j                  rt          |d          S d S )NT)r	   
isinstancennModule)gmresr   s     \/root/voice-cloning/.venv/lib/python3.11/site-packages/torch/fx/passes/infra/pass_manager.py
wrapped_fnz'pass_result_wrapper.<locals>.wrapped_fn$   sj    bff;b$'''c:&& 	)JRY'' 	)c4(((	) 	)    )r   inspect
isfunctiontype__name__)r   r   s   ` r   r
   r
      sd     
zt
2YY) ) ) ) Y) b!! 0"2hh/
r   
constraintpassesc                     t          |          D ]S\  }}t          ||dz   d                    D ]3\  }} | ||          rt          d| d| d| d| d| d| d          Td S )	N   z,pass schedule constraint violated. Expected z before z but found z
 at index z and z	 at indexz in pass list.)	enumerateRuntimeError)r   r   iajbs         r   "_validate_pass_schedule_constraintr(   4   s     &!!  1fQUWWo.. 	 	DAqz!Q q  !   +, 34 ?@    	 r   constraintsc                    t          |          dk    r| S d | D             }t                              | d          t                      }| D ]k}| D ]E}||k    r	|D ]9} |||          s+||                             |           |xx         dz  cc<   :F|         dk    r|                    |           lt                              | d          }g }|                                s|                                }	|                    |	           d||	<   ||	         D ];}
||
         s1|
xx         dz  cc<   |
         dk    r|                    |
           <|                                t          t          fd
                                                    }t          |          dk    rd| }t          |          |S )z
    Args
        passes: Passes that we are ordering
        constraints: Constraints applied on these passes

    Returns
        A sorted list of callables and a boolean of if a circular dependency
        existed
    r   c                     i | ]}|g S  r,   .0ps     r   
<dictcomp>z,_topological_sort_passes.<locals>.<dictcomp>R   s    ,C,C,CqQ,C,C,Cr   r!   FTc                     |          dk    S )Nr   r,   )r/   indegree_maps    r   <lambda>z*_topological_sort_passes.<locals>.<lambda>q   s    aA)= r   z:Circular dependency detected within the following passes: )lendictfromkeysr   appendputemptygetlistfilterkeysr#   )r   r)   graph
candidatesr%   r'   r   visitedsorted_passesr/   ncycle_passeserrorr2   s                @r   _topological_sort_passesrE   B   s    ;1 -D,CF,C,C,CE(,fa(@(@LJ   	) 	)AAvv) ) )
!z!Q'' )!HOOA&&& OOOq(OOO)
 ?aNN1$(MM&%$@$@G$&M   	&NNQ
q 	& 	&A1: &Q1$?a''NN1%%%    	& ====|?P?P?R?RSSTTL
<AWWW 	 5!!!r   thisthatc                 4     dt           dt           f fd}|S )a  
    Defines a partial order ('depends on' function) where `this` must occur
    before `that`.

    For example, the following pass list and constraint list would be invalid.
    ```
    passes = [pass_b, pass_a]

    constraints = [this_before_that_pass_constraint(pass_a, pass_b)]
    ```

    Args:
        this (Callable): pass which should occur first
        that (Callable): pass which should occur later

    Returns:
        depends_on (Callable[[Object, Object], bool]
    r%   r'   c                     | k    p|k    S Nr,   )r%   r'   rG   rF   s     r   
depends_onz4this_before_that_pass_constraint.<locals>.depends_on   s    Dy%AI%r   r   )rF   rG   rK   s   `` r   r   r   {   s=    *&h &8 & & & & & & & r   c                      e Zd ZU dZeeej        gef                  e	d<   eeeege
f                  e	d<   dZe
e	d<   dZee	d<   	 	 	 	 	 dd	e
d
e
fdZdefdZdefdZd Zd ZdeddfdZdej        ddfdZdej        defdZdS )r   ad  
    Construct a PassManager.

    Collects passes and constraints. This defines the pass schedule, manages
    pass constraints and pass execution.

    Args:
        passes (Optional[List[Callable]]): List of passes. A pass is a
            callable which modifies an object and returns a PassResult
        constraint (Optional[List[Callable]]): List of constraints. A
            constraint is a callable which takes two passes (A, B) and returns
            True if A depends on B and False otherwise. See implementation of
            `this_before_that_pass_constraint` for example.
        steps (int): Max number of times we run the passes (default = 1).
        run_checks_after_each_pass (bool): Whether to run checks and linting
            after each pass
        suppress_check_failures (bool): Whether to raise errors when running
            checks
    r   r)   F
_validatedr!   stepsNrun_checks_after_each_passsuppress_check_failuresc                 X    |pg | _         |pg | _        |r|| _        || _        || _        d S rJ   )r   r)   rN   rO   rP   )selfr   r)   rN   rO   rP   s         r   __init__zPassManager.__init__   sA     l&," 	DJ*D''>$$$r   _passc                 H    | j                             |           d| _        dS )z>
        Adds a pass into the current list of passes.
        FN)r   r7   rM   )rR   rT   s     r   add_passzPassManager.add_pass   s%     	5!!!r   r   c                 H    | j                             |           d| _        dS )zI
        Adds a constraint into the current list of constraints.
        FN)r)   r7   rM   rR   r   s     r   add_constraintzPassManager.add_constraint   s&     	
+++r   c                 d    | j         rdS | j        D ]}t          || j                   d| _         dS )z
        Validates that current pass schedule defined by `self.passes` is valid
        according to all constraints in `self.constraints`
        NT)rM   r)   r(   r   rX   s     r   validate_constraintsz PassManager.validate_constraints   sG    
 ? 	F* 	H 	HJ.z4;GGGGr   c                 R    t          | j        | j                  | _        d| _        dS )ab  
        Finds a valid traversal order based on the given constraints and orders
        the passes based on this order.

        If a circular dependency exists between the constraints and steps = 1,
        then we will raise an error because if steps != 1 this means that we
        will re-run the passes, allowing for circular dependencies.
        TN)rE   r   r)   rM   )rR   s    r   solve_constraintszPassManager.solve_constraints   s%     /t{D<LMMr   checkr   c                     t          j        |          }t          t          |j                                                            dk    rt          d          t          | d|           dS )z
        Adds a function which takes runs various checks on a given graph module.
        This function is run before and after each pass if the
        `run_checks_after_each_pass` flag is enabled.
        r!   zEPassManager check function should only take in one variable, a moduler^   N)r   	signaturer4   r;   
parametersvalues	TypeErrorsetattr)rR   r^   sigs      r   
add_checkszPassManager.add_checks   sl     &&tCN))++,,--22W   	gu%%%%%r   modulec                     d S rJ   r,   )rR   rg   s     r   r^   zPassManager.check   s    r   c                    | j         s|                                  |                     |           d}t          | j                  D ]s}d}t          | j                  D ]P\  }}t          j        |          r|j	        nt          |          j	        }t                              d|           	  ||          }t          |t                    s&t          |d          st!          d| ddz             |j        }|p|j        }t          |t&                    r5t                              d||j                   |                                 | j        r|                     |           # t.          $ r6}	d | j        d	|         D             }
d
| d|
 }t/          |          |	d	}	~	ww xY w|p|}|s nut          ||          S )a}  
        Runs a list of passes in the order based on `self.passes` on the given
        graph module. Each time a pass is run, checks and linting will be run on
        the graph module if `run_checks_after_each_pass` is set.

        If the module is a graph module, we will run the list of passes until
        the graph stops changing, or until `steps` number of times.
        FzRunning pass '%s'graph_modulezThe result of the pass z should be type PassResult.z)Please wrap it with pass_result_wrapper()zGraph after pass '%s': %sc                 l    g | ]1}t          j        |          r|j        nt          |          j        2S r,   )r   r   r   r   r-   s     r   
<listcomp>z(PassManager.__call__.<locals>.<listcomp>)  sG     ' ' ' '.&8&;&;Q

aAQ' ' 'r   Nz$An error occurred when running the 'z#' pass after the following passes: )rM   r]   r^   rangerN   r"   r   r   r   r   r   loggerdebugr   r	   hasattrrc   rj   modifiedr   r>   	recompilerO   	Exception)rR   rg   overall_modified_rq   r$   r   fn_namer   eprev_pass_namesmsgs               r   __call__zPassManager.__call__   s,     	%""$$$ 	

6 !tz"" (	 (	AH #4;// 0 02)0);B)?)?V"++T"XXEV0':::0"V**C%c:66 w^@ @  (ZgZZZIJ   !-F'73<H!&+66 +%@'6<XXX((*** 6 +

6***  0 0 0' '!%RaR' ' 'O ~~m|~~C#C..a/0  0;8  &"2333s   1B<E//
F/91F**F/)NNNFF)r   
__module____qualname____doc__r;   r   r   r   r	   __annotations__boolrM   rN   intrS   rV   rY   r[   r]   rf   r^   rz   r,   r   r   r   r      sz         ( 29+z123333h(3T9:;;;;JE3NNN +0(-? ?
 %)? "&? ? ? ?  h                 	 	 	
 
 
& &T & & & &BI $    =4ry =4Z =4 =4 =4 =4 =4 =4r   r   )r   logging	functoolsr   queuer   typingr   torch.nnr   torch.fx._compatibilityr   torch.fx.graph_moduler   torch.fx.passes.infra.pass_baser	   	getLoggerr   rn   setLevelWARNING__all__r
   r   r;   r(   rE   r   r   r,   r   r   <module>r      s                             1 1 1 1 1 1 - - - - - - 6 6 6 6 6 6 
	8	$	$       
T
T
T e,,,H     -,>(H-t34>B8n	   6N6)-h6	(^6 6 6 6r e,,,8 8     -,4 e,,,^4 ^4 ^4 ^4 ^4 ^4 ^4 -,^4 ^4 ^4r   