
    9j`                        U d dl Z d dlmZmZ d dlmZmZ d dlmZm	Z	m
Z
 d dlZg dZ e j                  e      Z e	d      Z e
d      Zeeej&                  ef   ef   Zeeef   Zeez  Ze G d d	             Zeeeee   gee   f   Ze G d
 d             Z e       Zeed<   i aee eef   ejB                  jD                  f   ed<   ee eef   ee   f   Z#i a$e#ed<   eeee eef      f   Z%i a&e%ed<   i a'e%ed<   i a(e%ed<   deee   z  dz  deee   z  dz  deee   z  dz  de)e eef      fdZ*ddde+ddfdZ,dededejB                  jD                  fdZ-dejB                  jD                  dededdfd Z.d!eee   z  dz  dee   fd"Z/dddd#d$eee   z  dz  d%eee   z  dz  d&eee   z  dz  ddfd'Z0dddd(d)eee   z  dz  d*eee   z  dz  d+eee   z  dz  ddfd,Z1d-edee   fd.Z2d-ededed/e eef   ddf
d0Z3ddd1d2ed3ededed4eez  d5e+d6e+ddfd7Z4dd8d9ee   d:ee   d;e+de+fd<Z5dd=deded>ee   d?edz  ddf
d@Z6ddddAdBedCe)e eef      dz  dDe+d?edz  ddf
dEZ7dd=deded>ee   d?edz  ddf
dFZ8dPdGZ9ddHdIedDe+ddfdJZ:ddHdKeeeege+f   dDe+ddfdLZ;ddHdMeeege+f   dNedDe+ddfdOZ<y)Q    N)CallableIterable)	dataclassfield)Concatenate	ParamSpecTypeVar)UserOrderingFnregister_op_override!reorder_graphs_from_user_functionreenable_op_overridesderegister_op_overridesget_dsl_operationsPRc                   V    e Zd ZU dZeed<   eed<   eed<   eed<   dZeed<   dZ	eed	<   y
)_OverrideNodezTrack function override data.dsl_name	op_symboldispatch_keyoverride_fnFunconditional_overrideTactiveN)
__name__
__module____qualname____doc__str__annotations___OpFnr   boolr        V/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/torch/_native/registry.pyr   r      s0    'MN#(D(FDr#   r   c                      e Zd ZU dZ ee      Zee   ed<    ee      Z	ee   ed<    ee      Z
ee   ed<   dedefdZ	 dd	eee   z  d
z  deee   z  d
z  deee   z  d
z  dedd
f
dZdeeeef      fdZdefdZy
)_FilterStatez+Manages filtering state for override nodes.)default_factory
_dsl_names_op_symbols_dispatch_keysnodereturnc                     |j                   | j                  v ry|j                  | j                  v ry|j                  | j
                  v ryy)z
        Check if a node is enabled based on current filter state.

        Args:
            node: The override node to check

        Returns:
            bool: True if the node should be enabled, False if filtered out
        FT)r   r(   r   r)   r   r*   )selfr+   s     r$   check_enabledz_FilterState.check_enabled4   sF     ==DOO+>>T--- 3 33r#   	dsl_namesN
op_symbolsdispatch_keysremove_keysc                    |rv| xj                   t        t        |            z  c_         | xj                  t        t        |            z  c_        | xj                  t        t        |            z  c_        y| xj                   t        t        |            z  c_         | xj                  t        t        |            z  c_        | xj                  t        t        |            z  c_        y)a  
        Update filter sets as (current | new) or (current ~ new).

        Args:
            dsl_names: DSL names to add/remove from filter
            op_symbols: Operation symbols to add/remove from filter
            dispatch_keys: Dispatch keys to add/remove from filter
            remove_keys: If True, remove keys from filter; if False, add them

        Note:
            Uses set.discard as it doesn't raise an exception if the element
            wasn't in the set to begin with.
        N)r(   set_resolve_iterabler)   r*   )r.   r0   r1   r2   r3   s        r$   updatez_FilterState.updateI   s    ( OOs#4Y#?@@O$5j$A BB3'8'G#HHOOs#4Y#?@@O$5j$A BB3'8'G#HHr#   c                 X    t        | j                  | j                  | j                        S )z
        Build a set of dictionary keys based on the current filter state.

        Returns:
            set[tuple[str, str]]: Set of (op_symbol, dispatch_key) tuples
        )_build_key_setr(   r)   r*   )r.   s    r$   build_disable_key_setz"_FilterState.build_disable_key_setf   s*     OO
 	
r#   c                 (   d}|dz  }|dz  }t        | j                        D ]  \  }}|d| d| dz  } |dz  }t        | j                        D ]  \  }}|d| d| dz  } |dz  }t        | j                        D ]  \  }}|d| d| dz  } |S )	z-Return string representation of filter state. zFilter State:
z  === DSL: ===
    z: 
z  === OP SYMBOL: ===
z  === DISPATCH KEYS: ===
)	enumerater(   r)   r*   )r.   sidslopkeys         r$   __str__z_FilterState.__str__s   s    		0 	%FAs4s"SE$$A	%	%%t//0 	$EAr4s"RD##A	$	)) 3 34 	%FAs4s"SE$$A	% r#   )F)r   r   r   r   r   r5   r(   r   r   r)   r*   r   r!   r/   r   r7   tupler:   rE   r"   r#   r$   r&   r&   ,   s    5 5JC5!#6KS6$S9NCH9- D 4 "I#&-I (3-'$.I Xc]*T1	I
 I 
I:
s5c?'; 
 r#   r&   _filter_state_libs_graphs_dsl_name_to_lib_graph_dispatch_key_to_lib_graph_op_symbol_to_lib_graphr0   r1   r2   r,   c                     t               dt        t        t           z  dz  dt        ddffd} || t                ||t
                ||t               S )aK  
    Build a set of dictionary keys based on filter criteria.

    Args:
        dsl_names: DSL names to include in key set
        op_symbols: Operation symbols to include in key set
        dispatch_keys: Dispatch keys to include in key set

    Returns:
        set[tuple[str, str]]: Set of (op_symbol, dispatch_key) tuples
    entriesNgraph_lib_dictr,   c                 j    t        |       }|D ]"  }||v s||   D ]  }j                  |        $ y)z;Helper to add matching keys from graph_lib_dict to key_set.N)r6   add)rN   rO   resolved_entriesentryrD   key_sets        r$   _append_to_setz&_build_key_set.<locals>._append_to_set   sG     -W5% 	%E&)%0 %CKK$%	%r#   )r5   r   r   _MappingTyperJ   rL   rK   )r0   r1   r2   rU   rT   s       @r$   r9   r9      s_      %(EG	%x}$t+	%=I	%		% 945:67="<=Nr#   F)print_inactiverW   c                 $   t         j                         D ]y  \  \  }}}t        d|d|       t        |      D ]R  \  }}|j                  s| sd| d|j
                  d|j                  }| r|d|j                  z  }t        |       T { y)z~
    Print all override graphs for debugging purposes.

    Args:
        print_inactive: Whether to print inactive nodes
    zop=z, key=r=   z: node.dsl_name=z, node.unconditional_override=z node.active=N)rI   itemsprintr?   r   r   r   )rW   rC   rD   	node_listrA   r+   r@   s          r$   _print_override_graphsr\      s     !( 		S9Wv + 	GAt{{ns"3T]]$44St7R7R6TU!>T[[N++Aa		r#   r   r   c                 |    | |f}|t         vr(t        j                  j                  dd|      t         |<   t         |   S )z
    Get or create a torch.library.Library instance for the given key.

    Args:
        op_symbol: The operation symbol
        dispatch_key: The dispatch key

    Returns:
        torch.library.Library: The library instance
    atenIMPL)rH   torchlibraryLibrary)r   r   rD   s      r$   _get_or_create_libraryrc      s<     l
#C
%]]**66<Hc
:r#   libr+   c                 n    | j                  |j                  |j                  ||j                   d       y)z
    Register a single node implementation with the library.

    Args:
        lib: The torch.library.Library instance
        node: The override node to register
        dispatch_key: The dispatch key for registration
    T)with_keysetallow_overrideN)implr   r   r   )rd   r+   r   s      r$   _register_node_implri      s7     HH333  r#   iterablec                 T    | g S t        | t              rt        | t              r| fS | S )z
    Resolve various input types to a consistent iterable of strings.

    Args:
        iterable: String, iterable of strings, or None

    Returns:
        Iterable[str]: Consistent iterable output
    )
isinstancer   r   )rj   s    r$   r6   r6      s/     	h)Z#-F{Or#   )enable_dsl_namesenable_op_symbolsenable_dispatch_keysrm   rn   ro   c                     t         j                  d| ||       t        j                  | ||d       t	        | ||      }|D ]*  }|\  }}|t
        v st        ||t
        |   t               , y)as  
    Re-enable overrides by removing them from filter state and reregistering.

    Args:
        enable_dsl_names: DSL names to re-enable
        enable_op_symbols: Operation symbols to re-enable
        enable_dispatch_keys: Dispatch keys to re-enable

    Note:
        This function uses reverse filter state management (removing from
        filters to enable).
    z>Re-registering ops by dsl: %s, op_symbol: %s, dispatch_key: %sT)r3   filter_stateN)loginforG   r7   r9   rI   _register_overrides_from_graph)rm   rn   ro   rT   rD   r   r   s          r$   r   r     s    $ HHH	 	   %3%G  "%	<'> +<Mr#   )disable_dsl_namesdisable_op_symbolsdisable_dispatch_keysrv   rw   rx   c                     t         j                  d| ||       t        j                  | ||       t        j	                         }|D ]*  }|\  }}|t
        v st        ||t
        |   t               , y)ag  
    De-register overrides by updating filter state and reregistering graphs.

    Args:
        disable_dsl_names: DSL names to disable
        disable_op_symbols: Operation symbols to disable
        disable_dispatch_keys: Dispatch keys to disable

    Note:
        This function uses filter state management to selectively disable
        operations.
    z>De-registering ops by dsl: %s, op_symbol: %s, dispatch_key: %srq   N)rs   rt   rG   r7   r:   rI   _cleanup_and_reregister_graph)rv   rw   rx   rT   rD   r   r   s          r$   r   r   =  s}    $ HHH	 *,>@UV %2$G$G$IG  	"%	<'>)*			r#   r   c                     t               }t        j                         D ]1  \  \  }}}|D ]$  }|j                  | k(  s|j	                  |        1 3 t        |      S )zGet list of operations registered by a specific DSL.

    Args:
        dsl_name: Name of the DSL to query.

    Returns:
        Sorted list of operation names registered by the DSL.
    )r5   rI   rY   r   rQ   sorted)r   
operationsr   _nodesr+   s         r$   r   r   i  s`     J!( A 	D}}(y)	
 *r#   rD   c                     dt         t        t        t        t        t        f      f   dt        dt        t        t        f   ddfd} |t        | |        |t
        ||        |t        ||       y)z
    Update the registration mapping dictionaries.

    Args:
        dsl_name: The DSL name
        op_symbol: The operation symbol
        dispatch_key: The dispatch key
        key: The dictionary key tuple
    registrationsymbolrD   r,   Nc                 ^    | j                  |      }|	|g}|| |<   y|j                  |       y)z;Helper to add key to registration list or create new entry.N)getappend)r   r   rD   
entry_lists       r$   _get_new_entry_or_appendz;_update_registration_maps.<locals>._get_new_entry_or_append  s9     "%%f-
J#-L c"r#   )dictr   listrF   rJ   rL   rK   )r   r   r   rD   r   s        r$   _update_registration_mapsr   {  ss    &#3U38_ 556## 38_# 
	# 3XsC4iE7sKr#   )allow_multiple_overrider   backend
lib_symbolrh   r   r   c          	          |dk7  rt        d| d      ||f}t        j                  |g       }|j                  t	        | ||||             |t        |<   t        | |||       y)a  
    Register a passed override function to the dispatcher.

    Actually a graph-building operation; real registration happens later.

    Args:
        backend: The backend name (DSL name)
        lib_symbol: Library you're overriding symbols in (must be "aten")
        op_symbol: Name of the operation you're overriding
        dispatch_key: Dispatch key to override
        impl: Implementation function for the override
        allow_multiple_override: Allow overriding an existing override
        unconditional_override: Implementation doesn't have a fallback and
            doesn't require torch.DispatchKeySet as the first argument

    Raises:
        ValueError: If lib_symbol is not "aten"
    r^   z.Unsupported lib_symbol (must be "aten", got: "")r   r   r   r   r   )rD   N)
ValueErrorrI   r   r   r   r   )	r   r   r   r   rh   r   r   rD   op_graphs	            r$   r   r     sz    8 VI*UVWXXl
#C {{3#HOO%#9	
 GCLgy,CHr#   force_reregisteroriginal_graph	new_graphr   c                    |ry| |k7  S )aG  
    Determine if a graph needs reregistration based on changes.

    Args:
        original_graph: The original graph before modification
        new_graph: The graph after modification
        force_reregister: If True, always reregister regardless of changes

    Returns:
        bool: True if reregistration is needed
    Tr"   )r   r   r   s      r$   _should_reregister_graphr     s    "  Y&&r#   rq   graphrr   c                N    | |f}|t         v rt         |= |rt        | |||       yy)a]  
    Clean up existing library and reregister a graph.

    This is the common pattern used across reorder, deregister, and reenable operations.

    Args:
        op_symbol: The operation symbol
        dispatch_key: The dispatch key
        graph: The graph to register
        filter_state: Optional filter state for conditional registration
    rq   N)rH   ru   )r   r   r   rr   rD   s        r$   rz   rz     s<    $ l
#C e|#J &%		
 r#   )keys_to_processreregister_overridesrr   transformation_fnr   r   c                B   ||nt        t        j                               }t        |      D ]  \  }}||ft        vrt        t        ||f         }	  | |||      }t        |t              s,t        j                  dt        |      j                  ||       l|t        ||f<   |szt        ||d      st!        ||||	        y# t        t
        t        t        f$ r t        j                  d||d       Y t        $ r t        j                  d||       Y w xY w)
a  
    Apply a transformation function to graphs and optionally reregister.

    This is the core pattern used by reorder_graphs_from_user_function and
    can be reused for other graph transformation operations.

    Args:
        transformation_fn: Function to transform each graph
        keys_to_process: Keys to process, or None for all graphs
        reregister_overrides: Whether to reregister changed graphs
        filter_state: Optional filter state for conditional registration

    Note:
        If transformation_fn raises an exception for a specific graph, that graph
        will be skipped and processing will continue with remaining graphs.
    NAGraph transformation failed for %s/%s. Preserving original graph.Texc_infoNUnexpected error in graph transformation for %s/%s. Preserving original graph.zbGraph transformation returned invalid type %s for %s/%s. Expected list. Preserving original graph.Fr   rq   )r5   rI   keysr   	TypeErrorr   AttributeErrorRuntimeErrorrs   warning	Exception	exceptionrl   typer   r   rz   )	r   r   r   rr   target_keysr   r   r   r   s	            r$   _apply_graph_transformationr     s=   6 +6C<O 
 $(#4 /	<|$G3gy,&?@A	))\>RI$ )T*KKtY((	  .7L)*  $<I%
 *)	U/ :~|D 	KKS	    	MM`
 	s   
C2D<DDc                    | |f}t        | }|D ]5  }d}|r|j                  |      }|rt        |||       d|_        /d|_        7 y)a  
    Register all overrides in a single graph.

    Args:
        op_symbol: The operation symbol
        dispatch_key: The dispatch key
        graph: List of override nodes to register
        filter_state: Optional filter state for conditional registration
    TFN)rc   r/   ri   r   )r   r   r   rr   rD   rd   r+   enables           r$   ru   ru   _  s\      l
#C
 #
&C 	 !//5FT<8DKDK	 r#   c                  `    t         j                         D ]  \  } }| \  }}t        |||        y)zO
    Perform all registration calls from previously-built override graphs.
    N)rI   rY   ru   )rD   r   r   r   s       r$   _register_all_overridesr   ~  s8     mmo 

U"%	<&	

r#   )r   fnc                    t        | |       y)a  
    Reorder override graphs using a user-provided ordering function.

    Args:
        fn: User-provided function that takes (op_symbol, dispatch_key, graph)
            and returns a reordered graph
        reregister_overrides: Whether to reregister graphs that have changed

    Note:
        This function uses the common graph transformation pattern and can serve
        as an example for other graph manipulation operations.
    r   r   N)r   )r   r   s     r$   r   r     s    "  1r#   	filter_fnc          	      x     dt         dt         dt        t           dt        t           f fd}t        ||       y)a  
    Apply a filter function to remove nodes from graphs.

    This is a convenience function that uses the graph transformation pattern
    to filter out unwanted nodes.

    Args:
        filter_fn: Function that takes (op_symbol, dispatch_key, node) and
            returns True to keep the node, False to remove it
        reregister_overrides: Whether to reregister modified graphs

    Example:
        # Remove all nodes with "deprecated" in the DSL name
        _apply_graph_filter(
            lambda op, dk, node: "deprecated" not in node.dsl_name,
            reregister_overrides=True
        )

    Note:
        If filter_fn raises an exception for a specific graph, the original
        graph will be preserved and processing will continue.
    r   r   r   r,   c                     	 |D cg c]  } | ||      s| c}S c c}w # t         t        t        t        f$ r t        j                  d| |d       |cY S t        $ r t        j                  d| |       |cY S w xY w)z-Apply filter_fn to graph with error handling.r   Tr   r   r   r   r   r   rs   r   r   r   )r   r   r   r+   r   s       r$   filtering_transformationz5_apply_graph_filter.<locals>.filtering_transformation  s    	%*WTi	<QU.VDWWW:~|D 	KKS	   L 	MM`
 L	s%   # # # 4A=!A=<A=r   Nr   r   r   r   )r   r   r   s   `  r$   _apply_graph_filterr     sB    8&)26}2E	m	,  21r#   condition_fnordering_fnc          	      |     dt         dt         dt        t           dt        t           f fd}t        ||       y)aE  
    Apply reordering only to graphs that match a condition.

    This allows for more targeted reordering operations.

    Args:
        condition_fn: Function that takes (op_symbol, dispatch_key) and
            returns True if the graph should be reordered
        ordering_fn: Ordering function to apply to matching graphs
        reregister_overrides: Whether to reregister modified graphs

    Example:
        # Only reorder CUDA operations
        _apply_selective_reordering(
            condition_fn=lambda op, dk: dk == "CUDA",
            ordering_fn=lambda op, dk, g: sorted(g, key=lambda n: n.dsl_name),
            reregister_overrides=True
        )

    Note:
        If condition_fn or ordering_fn raises an exception for a specific graph,
        the original graph will be preserved and processing will continue.
    r   r   r   r,   c                    	  | |      }|r	  | ||      S |S # t         t        t        t        f$ r t        j                  d| |d       |cY S t        $ r t        j                  d| |       |cY S w xY w# t         t        t        t        f$ r t        j                  d| |d       |cY S t        $ r t        j                  d| |       |cY S w xY w)z=Apply ordering_fn conditionally based on condition_fn result.r   Tr   r   r   )r   r   r   should_reorderr   r   s       r$   conditional_transformationz?_apply_selective_reordering.<locals>.conditional_transformation  s    	))\BN" "9lEBB" G :~|D 	KKS	   L 	MM`
 L	 z><H W !	    d 
 s,   	 	A8 4A5!A54A584C.!CCr   Nr   )r   r   r   r   s   ``  r$   _apply_selective_reorderingr     sC    <))&))26}2E)	m	)V  41r#   )r,   N)=loggingcollections.abcr   r   dataclassesr   r   typingr   r   r	   torch.libraryr`   __all__	getLoggerr   rs   r   r   DispatchKeySet_OpOverrideFn_OpReplaceFnr    r   r   r   r
   r&   rG   r   rH   r   rF   ra   rb   _GraphsTyperI   rV   rJ   rK   rL   r5   r9   r!   r\   rc   ri   r6   r   r   r   r   r   r   rz   r   ru   r   r   r   r   r"   r#   r$   <module>r      s    . ( 2 2  g!cNCLU%9%91%<=q@A1~$    3T-%894;NNO T T Tp +n| , 79tE#s(OU]]2223 8 5c?D$778 CeCHo../ (*  )+- L -(*  *!Xc]"T)!hsm#d*! #&-! 	sCx	!H 6; d t &c  AVAV (			&3CF	(hsm 3d : x} * 040437	2DIo,2 T#Y-2 S	/D0	2
 
2n 151548	)T#Y-) d3i$.) c?T1	)
 
)X c $#L#L#L #L 
sCx	#L
 
#LZ %*#(/I/I/I /I 	/I
 ,
&/I "/I !/I 
/Il #	'''M"' 	'
 
': )- 
 
 
  

 % 
 
 
L 48!&(,N%N sCx)D0N 	N
 %N 
Nl )-     
 %  
 >
" "'  
	4 "'5c=14785 5 
	5x "'	LC:t+,LL 	L
 
Lr#   