o
    j9:j`                     @   sX  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 eZe	dZe
dZeeejef ef Zeeef ZeeB ZeG dd	 d	Zeeeee gee f ZeG d
d dZe Zeed< i aee eef ej!j"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 B dB deee B dB deee B dB de)e eef  fddZ*ddde+ddfddZ,dededej!j"fdd Z-d!ej!j"d"ededdfd#d$Z.d%eee B dB dee fd&d'Z/dddd(d)eee B dB d*eee B dB d+eee B dB ddfd,d-Z0dddd.d/eee B dB d0eee B dB d1eee B dB ddfd2d3Z1d4edee fd5d6Z2d4ededed7e eef ddf
d8d9Z3ddd:d;ed<ededed=eeB d>e+d?e+ddfd@dAZ4ddBdCee dDee dEe+de+fdFdGZ5ddHdededIee dJedB ddf
dKdLZ6ddddMdNedOe)e eef  dB dPe+dJedB ddf
dQdRZ7ddHdededIee dJedB ddf
dSdTZ8dbdUdVZ9ddWdXedPe+ddfdYdZZ:ddWd[eeeege+f dPe+ddfd\d]Z;ddWd^eeege+f d_edPe+ddfd`daZ<dS )c    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                   @   sJ   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	< d
S )_OverrideNodezTrack function override data.dsl_name	op_symboldispatch_keyoverride_fnFunconditional_overrideTactiveN)
__name__
__module____qualname____doc__str__annotations___OpFnr   boolr    r    r    ]/home/nk/hobo-godmode/plappi-mvp/.venv/lib/python3.10/site-packages/torch/_native/registry.pyr      s   
 r   c                   @   s   e Zd ZU dZeedZee ed< eedZ	ee ed< eedZ
ee ed< dedefdd	Z	
ddeee B dB deee B dB deee B dB deddf
ddZdeeeef  fddZdefddZdS )_FilterStatez+Manages filtering state for override nodes.)default_factory
_dsl_names_op_symbols_dispatch_keysnodereturnc                 C   s4   |j | jv rdS |j| jv rdS |j| jv rdS dS )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'   r    r    r!   check_enabled4   s   
z_FilterState.check_enabledF	dsl_namesN
op_symbolsdispatch_keysremove_keysc                 C   s   |r%|  j tt|8  _ |  jtt|8  _|  jtt|8  _dS |  j tt|O  _ |  jtt|O  _|  jtt|O  _dS )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)   r+   r,   r-   r.   r    r    r!   updateI   s   z_FilterState.updatec                 C   s   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)   r    r    r!   build_disable_key_setf   s
   z"_FilterState.build_disable_key_setc                 C   s   d}|d7 }|d7 }t | jD ]\}}|d| d| d7 }q|d7 }t | jD ]\}}|d| d| d7 }q(|d7 }t | jD ]\}}|d| d| d7 }qA|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keyr    r    r!   __str__s   s   z_FilterState.__str__)F)r   r   r   r   r   r/   r$   r   r   r%   r&   r   r   r*   r   r1   tupler3   r=   r    r    r    r!   r"   ,   s(   
 
r"   _filter_state_libs_graphs_dsl_name_to_lib_graph_dispatch_key_to_lib_graph_op_symbol_to_lib_graphr+   r,   r-   r(   c                    sN   t   dttt B dB dtddf fd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                    s6   t | }|D ]}||v r|| D ]} | qqdS )z;Helper to add matching keys from graph_lib_dict to key_set.N)r0   add)rE   rF   resolved_entriesentryr<   key_setr    r!   _append_to_set   s   z&_build_key_set.<locals>._append_to_set)r/   r   r   _MappingTyperB   rD   rC   )r+   r,   r-   rL   r    rJ   r!   r2      s   


r2   F)print_inactiverN   c                 C   s   t  D ]9\\}}}td|d| t|D ]$\}}|js!| r<d| d|jd|j}| r8|d|j7 }t| qqdS )z~
    Print all override graphs for debugging purposes.

    Args:
        print_inactive: Whether to print inactive nodes
    zop=z, key=r5   z: node.dsl_name=z, node.unconditional_override=z node.active=N)rA   itemsprintr7   r   r   r   )rN   r;   r<   	node_listr9   r'   r8   r    r    r!   _print_override_graphs   s   
rR   r   r   c                 C   s,   | |f}|t vrt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)r@   torchlibraryLibrary)r   r   r<   r    r    r!   _get_or_create_library   s   rX   libr'   c                 C   s    | j |j|j||j dd dS )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   )rY   r'   r   r    r    r!   _register_node_impl   s   
r]   iterablec                 C   s*   | du r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
    N)
isinstancer   r   )r^   r    r    r!   r0      s
   
r0   )enable_dsl_namesenable_op_symbolsenable_dispatch_keysr`   ra   rb   c                 C   s`   t d| || tj| ||dd t| ||}|D ]}|\}}|tv r-t||t| td qdS )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)r.   filter_stateN)loginfor?   r1   r2   rA   _register_overrides_from_graph)r`   ra   rb   rK   r<   r   r   r    r    r!   r     s2   	r   )disable_dsl_namesdisable_op_symbolsdisable_dispatch_keysrh   ri   rj   c                 C   sX   t d| || t| || t }|D ]}|\}}|tv r)t||t| td qdS )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: %src   N)re   rf   r?   r1   r3   rA   _cleanup_and_reregister_graph)rh   ri   rj   rK   r<   r   r   r    r    r!   r   =  s&   r   r   c                 C   sF   t  }t D ]\\}}}|D ]}|j| kr||  nqq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.
    )r/   rA   rO   r   rG   sorted)r   
operationsr   _nodesr'   r    r    r!   r   i  s   	

r   r<   c                 C   s^   dt tttttf  f dtdtttf ddfdd}|t| | |t|| |t|| dS )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symbolr<   r(   Nc                 S   s2   |  |}|du r|g}|| |< dS || dS )z;Helper to add key to registration list or create new entry.N)getappend)rp   rq   r<   
entry_listr    r    r!   _get_new_entry_or_append  s
   
z;_update_registration_maps.<locals>._get_new_entry_or_append)dictr   listr>   rB   rD   rC   )r   r   r   r<   ru   r    r    r!   _update_registration_maps{  s   

rx   )allow_multiple_overrider   backend
lib_symbolr\   ry   r   c          	   	   C   s`   |dkrt d| d||f}t|g }|t| ||||d |t|< t| |||d dS )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"
    rS   z.Unsupported lib_symbol (must be "aten", got: "")r   r   r   r   r   )r<   N)
ValueErrorrA   rr   rs   r   rx   )	rz   r{   r   r   r\   ry   r   r<   op_graphr    r    r!   r
     s   	r
   force_reregisteroriginal_graph	new_graphr   c                C   s   |rdS | |k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   r    r    r!   _should_reregister_graph  s   r   rc   graphrd   c                C   s2   | |f}|t v rt |= |rt| |||d dS dS )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
    rc   N)r@   rg   )r   r   r   rd   r<   r    r    r!   rk     s   
rk   )keys_to_processreregister_overridesrd   transformation_fnr   r   c          	      C   s   |dur|nt t }t|D ]i\}}||ftvrqtt||f }z| |||}W n% ttttfyA   tj	d||dd Y q t
yP   td|| Y qw t|tsbt	dt|j|| q|t||f< |ryt||ddryt||||d	 qdS )
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   rc   )r/   rA   keysrw   	TypeErrorr}   AttributeErrorRuntimeErrorre   warning	Exception	exceptionr_   typer   r   rk   )	r   r   r   rd   target_keysr   r   r   r   r    r    r!   _apply_graph_transformation  sX   
	r   c                C   sN   | |f}t | }|D ]}d}|r||}|r!t||| d|_q
d|_q
dS )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)rX   r*   r]   r   )r   r   r   rd   r<   rY   r'   enabler    r    r!   rg   _  s   
rg   c                  C   s*   t  D ]\} }| \}}t||| qdS )zO
    Perform all registration calls from previously-built override graphs.
    N)rA   rO   rg   )r<   r   r   r   r    r    r!   _register_all_overrides~  s   r   )r   fnc                C   s   t | |d dS )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   r    r    r!   r     s   
r   	filter_fnc             	      s6   dt dt dtt dtt f fdd}t||d dS )	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                    sl   z fdd|D W S  t tttfy$   tjd dd | Y S  ty5   td  | Y S w )z-Apply filter_fn to graph with error handling.c                    s   g | ]
} |r|qS r    r    ).0r'   )r   r   r   r    r!   
<listcomp>  s    zI_apply_graph_filter.<locals>.filtering_transformation.<locals>.<listcomp>r   Tr   r   r   r}   r   r   re   r   r   r   )r   r   r   r   )r   r   r!   filtering_transformation  s$   z5_apply_graph_filter.<locals>.filtering_transformationr   Nr   rw   r   r   )r   r   r   r    r   r!   _apply_graph_filter  s   
r   condition_fnordering_fnc             	      s8   dt dt dtt dtt f fdd}t||d dS )	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                    s   z | |}W n) t tttfy   tjd| |dd | Y S  ty0   td| | | Y S w |rdz| ||W S  t tttfyR   tjd| |dd | Y S  tyc   td| | | Y S w |S )z=Apply ordering_fn conditionally based on condition_fn result.r   Tr   r   r   )r   r   r   should_reorderr   r   r    r!   conditional_transformation  sL   z?_apply_selective_reordering.<locals>.conditional_transformationr   Nr   )r   r   r   r   r    r   r!   _apply_selective_reordering  s   +
r   )r(   N)=loggingcollections.abcr   r   dataclassesr   r   typingr   r   r   torch.libraryrU   __all__	getLoggerr   re   r   r   DispatchKeySet_OpOverrideFn_OpReplaceFnr   r   r   rw   r	   r"   r?   r   r@   rv   r>   rV   rW   _GraphsTyperA   rM   rB   rC   rD   r/   r2   r   rR   rX   r]   r0   r   r   r   rx   r
   r   rk   r   rg   r   r   r   r   r    r    r    r!   <module>   s`  
 
	X 
$
"
7
,

-	
6

&
V



<