
    3j`                        % S SK r S SKJrJr  S SKJrJr  S SKJrJ	r	J
r
  S SKr/ SQr\ R                  " \5      r\	" S5      r\
" S5      r\\\R&                  \4   \4   r\\\4   r\\-  r\ " S S	5      5       r\\\\\   /\\   4   r\ " S
 S5      5       r\" 5       r\\S'   0 q\\ \\4   \RB                  RD                  4   \S'   \\ \\4   \\   4   r#0 q$\#\S'   \\\\ \\4      4   r%0 q&\%\S'   0 q'\%\S'   0 q(\%\S'   S\\\   -  S-  S\\\   -  S-  S\\\   -  S-  S\)\ \\4      4S jr*SS.S\+SS4S jjr,S\S\S\RB                  RD                  4S jr-S\RB                  RD                  S\S\SS4S  jr.S!\\\   -  S-  S\\   4S" jr/SSSS#.S$\\\   -  S-  S%\\\   -  S-  S&\\\   -  S-  SS4S' jjr0SSSS(.S)\\\   -  S-  S*\\\   -  S-  S+\\\   -  S-  SS4S, jjr1S-\S\\   4S. jr2S-\S\S\S/\ \\4   SS4
S0 jr3SSS1.S2\S3\S\S\S4\\-  S5\+S6\+SS4S7 jjr4SS8.S9\\   S:\\   S;\+S\+4S< jjr5SS=.S\S\S>\\   S?\S-  SS4
S@ jjr6SSSSA.SB\SC\)\ \\4      S-  SD\+S?\S-  SS4
SE jjr7SS=.S\S\S>\\   S?\S-  SS4
SF jjr8SPSG jr9SSH.SI\SD\+SS4SJ jjr:SSH.SK\\\\/\+4   SD\+SS4SL jjr;SSH.SM\\\/\+4   SN\SD\+SS4SO jjr<g)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                   ^    \ rS rSr% Sr\\S'   \\S'   \\S'   \\S'   Sr\	\S'   S	r
\	\S
'   Srg)_OverrideNode   zTrack function override data.dsl_name	op_symboldispatch_keyoverride_fnFunconditional_overrideTactive N)__name__
__module____qualname____firstlineno____doc__str__annotations___OpFnr   boolr   __static_attributes__r       P/home/wildlama/miniconda3/lib/python3.13/site-packages/torch/_native/registry.pyr   r      s0    'MN#(D(FDr&   r   c                      \ rS rSr% Sr\" \S9r\\   \	S'   \" \S9r
\\   \	S'   \" \S9r\\   \	S'   S\S\4S	 jr SS
\\\   -  S-  S\\\   -  S-  S\\\   -  S-  S\SS4
S jjrS\\\\4      4S jrS\4S jrSrg)_FilterState,   z+Manages filtering state for override nodes.)default_factory
_dsl_names_op_symbols_dispatch_keysnodereturnc                     UR                   U R                  ;   a  gUR                  U R                  ;   a  gUR                  U R
                  ;   a  gg)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_enabled_FilterState.check_enabled4   sF     ==DOO+>>T--- 3 33r&   	dsl_namesN
op_symbolsdispatch_keysremove_keysc                    U(       av  U =R                   [        [        U5      5      -  sl         U =R                  [        [        U5      5      -  sl        U =R                  [        [        U5      5      -  sl        gU =R                   [        [        U5      5      -  sl         U =R                  [        [        U5      5      -  sl        U =R                  [        [        U5      5      -  sl        g)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.   )r2   r5   r6   r7   r8   s        r'   update_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    [        U R                  U R                  U R                  5      $ )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.   )r2   s    r'   build_disable_key_set"_FilterState.build_disable_key_setf   s*     OO
 	
r&   c                 .   SnUS-  nUS-  n[        U R                  5       H  u  p#USU SU S3-  nM     US-  n[        U R                  5       H  u  p$USU SU S3-  nM     US-  n[        U R                  5       H  u  p%USU SU S3-  nM     U$ )	z-Return string representation of filter state. zFilter State:
z  === DSL: ===
    z: 
z  === OP SYMBOL: ===
z  === DISPATCH KEYS: ===
)	enumerater,   r-   r.   )r2   sidslopkeys         r'   __str___FilterState.__str__s   s    		0FA4s"SE$$A 1	%%t//0EA4s"RD##A 1	)) 3 34FA4s"SE$$A 5 r&   r   )F)r   r   r   r   r    r   r:   r,   r!   r"   r-   r.   r   r$   r3   r   r<   tupler@   rL   r%   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_graphr5   r6   r7   r0   c                    ^ [        5       mS[        [        [           -  S-  S[        SS4U4S jjnU" U [        5        U" U[
        5        U" U[        5        T$ )a+  
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_dictr0   c                 t   > [        U 5      nU H&  nX1;   d  M
  X    H  nTR                  U5        M     M(     g)z;Helper to add matching keys from graph_lib_dict to key_set.N)r;   add)rV   rW   resolved_entriesentryrK   key_sets        r'   _append_to_set&_build_key_set.<locals>._append_to_set   s9     -W5%E&)0CKK$ 1 &r&   )r:   r!   r   _MappingTyperR   rT   rS   )r5   r6   r7   r]   r\   s       @r'   r?   r?      s_      %(EG	%x}$t+	%=I	%		% 945:67="<=Nr&   F)print_inactiver`   c                 R   [         R                  5        H  u  u  pn[        SU< SU< 35        [        U5       He  u  pEUR                  (       d	  U (       d  M  SU SUR
                  < SUR                  < 3nU (       a  USUR                  < 3-  n[        U5        Mg     M     g)zn
Print all override graphs for debugging purposes.

Args:
    print_inactive: Whether to print inactive nodes
zop=z, key=rD   z: node.dsl_name=z, node.unconditional_override=z node.active=N)rQ   itemsprintrF   r   r   r   )r`   rJ   rK   	node_listrH   r/   rG   s          r'   _print_override_graphsre      s     !(	9Wv +GA{{nns"3T]]$44St7R7R6TU!>T[[N++Aa , !0r&   r   r   c                 ~    X4nU[         ;  a(  [        R                  R                  SSU5      [         U'   [         U   $ )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)rP   torchlibraryLibrary)r   r   rK   s      r'   _get_or_create_libraryrl      s:     
#C
%]]**66<Hc
:r&   libr/   c                 p    U R                  UR                  UR                  UUR                  (       + SS9  g)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   )rm   r/   r   s      r'   _register_node_implrr      s7     HH333  r&   iterablec                 j    U c  / $ [        U [        5      (       a  [        U [        5      (       a  U 4$ U $ )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!   )rs   s    r'   r;   r;      s5     	h))Z#-F-F{Or&   )enable_dsl_namesenable_op_symbolsenable_dispatch_keysrv   rw   rx   c                     [         R                  SU UU5        [        R                  U UUSS9  [	        U UU5      nU H)  nUu  pVU[
        ;   d  M  [        XV[
        U   [        S9  M+     g)aO  
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)r8   filter_stateN)loginforO   r<   r?   rQ   _register_overrides_from_graph)rv   rw   rx   r\   rK   r   r   s          r'   r   r     s    $ HHH	 	   %3%G "%	'> +M r&   )disable_dsl_namesdisable_op_symbolsdisable_dispatch_keysr   r   r   c                     [         R                  SU UU5        [        R                  XU5        [        R	                  5       nU H*  nUu  pVU[
        ;   d  M  [        UU[
        U   [        S9  M,     g)aC  
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: %srz   N)r|   r}   rO   r<   r@   rQ   _cleanup_and_reregister_graph)r   r   r   r\   rK   r   r   s          r'   r   r   =  ss    $ HHH	 *@UV %2$G$G$IG "%	'>)*		 r&   r   c                     [        5       n[        R                  5        H5  u  u  p#nU H'  nUR                  U :X  d  M  UR	                  U5          M3     M7     [        U5      $ )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.
)r:   rQ   rb   r   rY   sorted)r   
operationsr   _nodesr/   s         r'   r   r   i  sT     J!(D}}(y)  "1
 *r&   rK   c                     S[         [        [        [        [        [        4      4   S[        S[        [        [        4   SS4S jnU" [        X5        U" [
        X5        U" [        X#5        g)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symbolrK   r0   Nc                 ^    U R                  U5      nUc  U/nX0U'   gUR                  U5        g)z;Helper to add key to registration list or create new entry.N)getappend)r   r   rK   
entry_lists       r'   _get_new_entry_or_append;_update_registration_maps.<locals>._get_new_entry_or_append  s7     "%%f-
J#- c"r&   )dictr!   listrN   rR   rT   rS   )r   r   r   rK   r   s        r'   _update_registration_mapsr   {  sm    &#3U38_ 556## 38_# 
	# 3XC4iE7Kr&   )allow_multiple_overrider   backend
lib_symbolrq   r   r   c          
          US:w  a  [        SU S35      eX#4n[        R                  U/ 5      nUR                  [	        U UUUUS95        U[        U'   [        XX7S9  g)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"
rg   z.Unsupported lib_symbol (must be "aten", got: "")r   r   r   r   r   )rK   N)
ValueErrorrQ   r   r   r   r   )	r   r   r   r   rq   r   r   rK   op_graphs	            r'   r   r     st    8 VI*UVWXX
#C {{3#HOO%#9	
 GCLg,Hr&   force_reregisteroriginal_graph	new_graphr   c                    U(       a  gX:g  $ )a'  
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    "  &&r&   rz   graphr{   c                T    X4nU[         ;   a  [         U	 U(       a  [        U UUUS9  gg)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
rz   N)rP   r~   )r   r   r   r{   rK   s        r'   r   r     s:    $ 
#C e|#J &%		
 r&   )keys_to_processreregister_overridesr{   transformation_fnr   r   c          	      \   Ub  UO[        [        R                  5       5      n[        U5       H  u  pVXV4[        ;  a  M  [        [        XV4   5      n U " XVU5      n[        U[        5      (       d-  [        R                  S[        U5      R                  UU5        Mq  U[        XV4'   U(       d  M  [        XxSS9(       d  M  [!        UUUUS	9  M     g! [        [
        [        [        4 a    [        R                  SUUSS9   M  [         a    [        R                  SUU5         M  f = f)
ad  
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   rz   )r:   rQ   keysr   	TypeErrorr   AttributeErrorRuntimeErrorr|   warning	Exception	exceptionru   typer   r   r   )	r   r   r   r{   target_keysr   r   r   r   s	            r'   _apply_graph_transformationr     s7   6 +6C<O 
 $(#4	$G3gy&?@A	))>RI$ )T**KKtY((	  .7)*  $<%
 %
 *)	U $5 :~|D 	KKS	    	MM`
 	s   	C0D+ D+*D+c                    X4n[        U6 nU H@  nSnU(       a  UR                  U5      nU(       a  [        XVU5        SUl        M9  SUl        MB     g)z
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)rl   r3   rr   r   )r   r   r   r{   rK   rm   r/   enables           r'   r~   r~   _  sS      
#C
 #
&C!//5F<8DKDK r&   c                  `    [         R                  5        H  u  pU u  p#[        UUU5        M     g)zG
Perform all registration calls from previously-built override graphs.
N)rQ   rb   r~   )rK   r   r   r   s       r'   _register_all_overridesr   ~  s/     mmo
"%	&	
 &r&   )r   fnc                    [        U US9  g)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          	      v   ^  S[         S[         S[        [           S[        [           4U 4S jjn[        UUS9  g)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   r0   c                   >  U Vs/ s H  nT" XU5      (       d  M  UPM     sn$ s  snf ! [         [        [        [        4 a    [        R                  SU USS9  Us $ [         a    [        R                  SU U5        Us $ f = f)z-Apply filter_fn to graph with error handling.r   Tr   r   r   r   r   r   r|   r   r   r   )r   r   r   r/   r   s       r'   filtering_transformation5_apply_graph_filter.<locals>.filtering_transformation  s    	%*WUTi	QU.VDUWWW:~|D 	KKS	   L 	MM`
 L	s%   + &&+ + 2B"BB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          	      z   ^ ^ S[         S[         S[        [           S[        [           4U U4S jjn[        UUS9  g)a  
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   r0   c                   >  T" X5      nU(       a
   T" XU5      $ U$ ! [         [        [        [        4 a    [        R                  SU USS9  Us $ [         a    [        R                  SU U5        Us $ f = f! [         [        [        [        4 a    [        R                  SU USS9  Us $ [         a    [        R                  SU U5        Us $ f = f)z=Apply ordering_fn conditionally based on condition_fn result.r   Tr   r   r   )r   r   r   should_reorderr   r   s       r'   conditional_transformation?_apply_selective_reordering.<locals>.conditional_transformation  s    	))BN" "9EBB" G :~|D 	KKS	   L 	MM`
 L	 z><H W !	    d 
 s,    A: 2A7"A76A7:2C."CCr   Nr   )r   r   r   r   s   ``  r'   _apply_selective_reorderingr     sH    <))&))26}2E)	m	) )V  41r&   )r0   N)=loggingcollections.abcr   r   dataclassesr   r   typingr   r   r	   torch.libraryri   __all__	getLoggerr   r|   r   r   DispatchKeySet_OpOverrideFn_OpReplaceFnr#   r   r!   r   r
   r)   rO   r"   rP   r   rN   rj   rk   _GraphsTyperQ   r_   rR   rS   rT   r:   r?   r$   re   rl   rr   r;   r   r   r   r   r   r   r   r   r~   r   r   r   r   r   r&   r'   <module>r      s    . ( 2 2  !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&   