
    ^jj                        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	 d dl
Zg dZ e j                  e      Z ed      Z e	d      Zeeef   Zeeef   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j>                  j@                  f   ed<   i Z!ee"e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 a)e*ed<    e+h d      Z,e+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/i Z0eeej>                  j@                  f   ed<    e-       Z1e-e   ed <   i Z2eeeef   ej>                  j@                  f   ed!<   d"edej>                  j@                  fd#Z3d$edej>                  j@                  fd%Z4d&ed$ed'eddfd(Z5d&ed$eddfd)Z6d&edd*fd+Z7d&edefd,Z8d-ed&eddfd.Z9d/ej>                  j@                  d0ed$eddfd1Z:d2eee   z  dz  dee   fd3Z;dddd4d5eee   z  dz  d6eee   z  dz  d7eee   z  dz  ddfd8Z<dddd9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=Z=d>edee   fd?Z>d>ed&ed$ed@eeef   ddf
dAZ?dBe"dCe"defdDZ@dddEdFedGed&ed$edHedz  dIedJedKeddfdLZAddMdNee   dOee   dPedefdQZBddRd&ed$edSee   dTedz  ddf
dUZCddddVdWedXe-eeef      dz  dYedTedz  ddf
dZZD	 dgd[edee"ef   fd\ZEddRd&ed$edSee   dTedz  ddf
d]ZFdhd^ZGdd_d`edYeddfdaZHdd_dbeeeegef   dYeddfdcZIdd_ddeeegef   deedYeddfdfZJy)i    N)CallableIterable)	dataclassfield)	ParamSpecTypeVar)UserOrderingFnregister_op_override!reorder_graphs_from_user_functionreenable_op_overridesderegister_op_overridesget_dsl_operationsnative_decomp_tablePRc                   j    e Zd ZU dZeed<   eed<   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cond_fnimpl_fnnode_idFunconditional_overrideTactiveN)__name__
__module____qualname____doc__str__annotations__	_OpCondFn	_OpImplFnr   boolr        a/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_native/registry.pyr   r      s=    'MN
 L#(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_enabled9   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-   )r1   r3   r4   r5   r6   s        r'   updatez_FilterState.updateN   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-   )r1   s    r'   build_disable_key_setz"_FilterState.build_disable_key_setk   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-   )r1   sidslopkeys         r'   __str__z_FilterState.__str__x   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   r8   r+   r    r!   r,   r-   r   r$   r2   r   r:   tupler=   rH   r%   r&   r'   r)   r)   1   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_native_decomp_overrides_graphs_dsl_name_to_lib_graph_dispatch_key_to_lib_graph_op_symbol_to_lib_graph_node_id_counter>   MetaCompositeExplicitAutogradCompositeImplicitAutograd_DISALLOWED_DISPATCH_KEYSr3   r4   r5   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)r9   add)rX   rY   resolved_entriesentryrG   key_sets        r'   _append_to_setz&_build_key_set.<locals>._append_to_set   sG     -W5% 	%E&)%0 %CKK$%	%r&   )r8   r    r   _MappingTyperO   rQ   rP   )r3   r4   r5   r_   r^   s       @r'   r<   r<      s_      %(EG	%x}$t+	%=I	%		% 945:67="<=Nr&   F)print_inactivera   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)rN   itemsprintrB   r   r   r   )ra   rF   rG   	node_listrD   r.   rC   s          r'   _print_override_graphsrf      s     !( 		S9Wv + 	GAt{{ns"3T]]$44St7R7R6TU!>T[[N++Aa		r&   	_def_libs_defined_native_ops_aten_override_libs	namespacec                 r    | t         vr't        j                  j                  | d      t         | <   t         |    S )NFRAGMENT)rg   torchlibraryLibrary)rj   s    r'   _get_def_libraryrp     s0    	!$}}44Y
K	)Yr&   r   c                 |    d| f}|t         vr(t        j                  j                  dd|       t         |<   t         |   S )z
    Get or create the _native IMPL library for a given dispatch key.

    One library per dispatch key is shared across all overridden ops.
    _nativeIMPL)rL   rm   rn   ro   )r   rG   s     r'   _get_or_create_libraryrt   
  s<     l
#C
%]]**9flKc
:r&   r   kernelc                     | |f}t         j                  |d      }||j                          t        j                  j                  dd|      }|j                  | ||d       |t         |<   y)a  
    Install (or replace) an aten kernel at (op_symbol, dispatch_key).

    Creates a fresh Library per (op, key) so we can tear down just this
    one override via `_destroy_aten_override` without affecting any other
    override at the same dispatch key.
    Natenrs   T)with_keyset)ri   pop_destroyrm   rn   ro   impl)r   r   ru   rG   existinglibs         r'   _install_aten_overrider~     sk     l
#C #&&sD1H
--


=CHHY$H?"r&   c                 Z    t         j                  | |fd      }||j                          yy)zATear down the aten override at (op_symbol, dispatch_key), if any.N)ri   ry   rz   )r   r   r}   s      r'   _destroy_aten_overrider   .  s,    

!
!9l";T
BC
 r&   ztorch._ops.OpOverload | Nonec                     | j                  d      \  }}}|xs d}	 t        t        j                  j                  |      }t        ||      S # t
        $ r Y yw xY w)u4  
    Resolve `op_symbol` to a concrete OpOverload on `torch.ops.aten`.

    Accepts bare names ("bmm" → aten.bmm.default) and overload-qualified
    names ("add_.Tensor" → aten.add_.Tensor). Returns None if the op is not
    registered (e.g. a test-only op_symbol that never hit the C++ dispatcher).
    .defaultN)	partitiongetattrrm   opsrw   AttributeError)r   name_overload_namepackets        r'   _resolve_aten_overloadr   5  s]     '005D!]!.YM.v}-- s   /A 	AAc                     t        |       }|t        d|       t        |j                        }|j	                  dd      \  }}|j	                  dd      \  }}d| S )u   Return the schema of at::<op_symbol> with the `aten::<name>` prefix stripped.

    Accepts bare names ("bmm" → aten.bmm.default) and overload-qualified
    names ("add_.Tensor" → aten.add_.Tensor).
    z aten op not found for op_symbol=z::   ()r   r   r    _schemasplit)r   overloadrC   r   restargss         r'   _aten_schema_tailr   F  sk     &i0H?	}MNNHAggdAGAtjja GAttf:r&   r   c                     | t         v ry t        d      j                  |  t        |              t	        |      }t        j                  j                  d|        |dd       t         j                  |        y )Nrr   z	_native::)_aten_overloadc                      | |i |S Nr%   )r   r   kwargss      r'   <lambda>z(_define_native_op_once.<locals>.<lambda>d  s    n?
?
 r&   )	rh   rp   definer   r   rm   rn   register_faker[   )r   r   aten_overloads      r'   _define_native_op_oncer   V  su     ""Y&&$0A)0L/M'NO +95M	MM)D6 23%2 	
 D!r&   r}   r.   c                     |j                   s&t        d|j                  d|j                  d      t	        |j                   |j                         | j                  |j                   |j                  |d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
    zJ_OverrideNode must have a non-empty node_id before registration (dsl_name=z, op_symbol=)FT)rx   allow_overrideN)r   
ValueErrorr   r   r   r{   r   )r}   r.   r   s      r'   _register_node_implr   r  sv     <<)dnn5GqJ
 	
 4<<8HH  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    )r   s    r'   r9   r9     s/     	h)Z#-F{Or&   )enable_dsl_namesenable_op_symbolsenable_dispatch_keysr   r   r   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)r6   filter_stateN)loginforK   r:   r<   rN   _register_overrides_from_graph)r   r   r   r^   rG   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                     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: %sr   N)r   r   rK   r:   r=   rN   _cleanup_and_reregister_graph)r   r   r   r^   rG   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.
    )r8   rN   rc   r   r[   sorted)r   
operationsr   r   nodesr.   s         r'   r   r      s`     J!( A 	D}}(y)	
 *r&   rG   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symbolrG   r/   Nc                 ^    | j                  |      }|	|g}|| |<   y|j                  |       y)z;Helper to add key to registration list or create new entry.N)getappend)r   r   rG   
entry_lists       r'   _get_new_entry_or_appendz;_update_registration_maps.<locals>._get_new_entry_or_append%  s9     "%%f-
J#-L c"r&   )dictr    listrJ   rO   rQ   rP   )r   r   r   rG   r   s        r'   _update_registration_mapsr     ss    &#3U38_ 556## 38_# 
	# 3XsC4iE7sKr&   r   r   c                       y)NTr%   )r   r   s     r'   _always_truer   8  s    r&   )allow_multiple_overrider   backend
lib_symbolcondr{   r   r   c                |   |dk7  rt        d| d      |t        v rt        d|d      ||st        d      t        }||f}t        j	                  |g       }	|j                  dd	      }
|
 d	|  d	t         }t        d
z  a|	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
        cond: Predicate choosing whether `impl` applies to a given call. May
            be None if `unconditional_override=True`.
        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. When
            True, a trivially-True predicate is supplied for the router if
            `cond` is None.

    Raises:
        ValueError: If lib_symbol is not "aten", if dispatch_key is in
            _DISALLOWED_DISPATCH_KEYS (Meta / CompositeImplicitAutograd /
            CompositeExplicitAutograd), or if cond is None without
            unconditional_override=True.
    rw   z.Unsupported lib_symbol (must be "aten", got: ""zdispatch_key=z is not supported. Overrides must be installed at a backend key (e.g. CPU, CUDA, XPU); the router's fake kernel redispatches to aten and would recurse otherwise.Nz8cond must be provided unless unconditional_override=Truer   r   r   )r   r   r   r   r   r   r   )rG   )
r   rV   r   rN   r   replacerR   r   r   r   )r   r   r   r   r   r{   r   r   rG   op_graph
_sanitizedr   s               r'   r
   r
   <  s    H VI*UVWXX00L+ ,G H
 	
 |%WXXl
#C {{3#H ""3,JAgYa(8'9:G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&   r   graphr   c                "    t        | |||       y)a  
    Reregister a graph's routes from scratch.

    Used by reorder / deregister / reenable. Libraries are intentionally
    long-lived singletons; we rebuild the per-op router closure here.

    Args:
        op_symbol: The operation symbol
        dispatch_key: The dispatch key
        graph: The graph to register
        filter_state: Optional filter state for conditional registration
    r   N)r   )r   r   r   r   s       r'   r   r     s    & #!	r&   )keys_to_processreregister_overridesr   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   r   )r8   rN   keysr   	TypeErrorr   r   RuntimeErrorr   warning	Exception	exceptionr   typer   r   r   )	r   r   r   r   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overrides_onlyc                 f    | ri }nddl m} t         |             }|j                  t               |S )a  
    Return a decomposition table suitable for passing to
    ``ExportedProgram.run_decompositions`` or to Inductor / Dynamo as a
    decomposition set for ``torch.compile``.

    This is the canonical way to apply native overrides outside of eager.
    Callers opt in explicitly -- the registry does **not** install into any
    global compile/export decomp table on its own. This preserves three
    properties:

      * ``import torch._native`` doesn't transitively import inductor /
        dynamo / triton.
      * No other consumer (ONNX, tests, third-party backends) accidentally
        picks up our overrides.
      * Scoping is up to the caller: pass the table only where routing is
        desired.

    By default, the returned table contains
    ``torch.export.default_decompositions()`` with native-registered
    overrides layered on top -- matching typical "run the usual
    decompositions, plus my overrides" intent. The override entries win
    over any same-op default, because they're merged last.

    Example:

        ep = torch.export.export(model, args)
        ep = ep.run_decompositions(
            torch._native.registry.native_decomp_table()
        )

    Args:
        overrides_only: If True, return only the native-registered overrides
            and no default aten decompositions. Useful for inspection /
            debugging, or when composing tables manually.

    Returns:
        A dict mapping ``OpOverload`` to decomposition callable.
    r   )default_decompositions)torch.exportr   r   r:   rM   )r   tabler   s      r'   r   r     s2    R (* 	8+-.	LL)*Lr&   c                   t        |      }g |D ]\  }d}|r|j                  |      }|r<t        |||       j                  |j                  |j
                  f       d|_        Vd|_        ^ t        |       }t        | |       s|t        j                  |d       yt        j                  j                  d|  |      }t               dt        ffd|dfd
}	fd	}
t!        | ||	       |
|
t        |<   y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
    TFNzaten::swallow_cond_exceptionsc                     D ]<  \  }}	  || i |}|s t        t        j                  j                  |      | i |c S  S # t         $ r |s Y Ow xY wr   )r   r   rm   r   rr   )r   r   r   r   	impl_namematched	_NO_MATCH	cond_impls         r'   	_dispatchz1_register_overrides_from_graph.<locals>._dispatch  sv    ( 	NOD)//
 <wuyy00)<dMfMM	N   .s   AAA)	_fallbackc                R     ||d      }|u r |j                   | g|i |S |S )NFr   )
call_boxed)keysetr   r   r   resultr   r   s        r'   eager_routerz4_register_overrides_from_graph.<locals>.eager_router  s;    4GY'9''@@@@r&   c                  2     | |d      }|u rt         S |S )NTr   )NotImplemented)r   r   r   r   r   s      r'   compile_routerz6_register_overrides_from_graph.<locals>.compile_router  s$    4FY!!r&   )rt   r2   r   r   r   r   r   r   r   rM   ry   rm   rn   
get_kernelobjectr$   r~   )r   r   r   r   r}   r.   enabler   fallback_kernelr   r   r   r   r   s              @@@r'   r   r   F  s     !
.C-/I
  
 !//5FT<8dllDLL9:DKDK
  &i0H 9l3 $((48 mm..	{/C\RO I
 
 />  9lLA -; * r&   c                  `    t         j                         D ]  \  } }| \  }}t        |||        y)zO
    Perform all registration calls from previously-built override graphs.
    N)rN   rc   r   )rG   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   r   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&   rI   )r/   N)Kloggingcollections.abcr   r   dataclassesr   r   typingr   r   torch.libraryrm   __all__	getLoggerr   r   r   r   r$   r"   r#   r   r    r   r	   r)   rK   r!   rL   r   rJ   rn   ro   rM   r  _GraphsTyperN   r`   rO   rP   rQ   rR   int	frozensetrV   r8   r<   rf   rg   rh   ri   rp   rt   r~   r   r   r   r   r   r9   r   r   r   r   r   r
   r   r   r   r   r   r  r   r  r  r%   r&   r'   <module>r!     s    . ( %  g!cNCLQW	QTN	   " 3T-%894;NNO T T Tp +n| , 79tE#s(OU]]2223 8. 46 $vx/0 5 5c?D$778 CeCHo../ (*  )+- L -(*  *
  #  -6F- 9S> 
!Xc]"T)!hsm#d*! #&-! 	sCx	!H 6; d t ( /1	4U]]***+ 0 # SX % EG T%S/5==+@+@@A F   (=(=   1F1F #c # #h #SW #*c   c .L "   " " " "8			&3CF	4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L & T  %*#(MIMIMI MI 	MI
 d
MI MI "MI !MI 
MIh #	'''M"' 	'
 
': )- 
 % 
< 48!&(,N%N sCx)D0N 	N
 %N 
Nd !33	&(
3v )-h<h<h< h<
 %h< 
h<V
" "'  
	4 "'5c=14785 5 
	5x "'	LC:t+,LL 	L
 
Lr&   