
    a,j`                     F   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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         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j!        j"        fdZ-dej!        j"        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<dS )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                   X    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        V/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/torch/_native/registry.pyr   r      sc         ''MMMNNN#(D(((FDr#   r   c                   J   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dS )_FilterStatez+Manages filtering state for override nodes.)default_factory
_dsl_names_op_symbols_dispatch_keysnodereturnc                 f    |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+   s     r$   check_enabledz_FilterState.check_enabled4   sH     =DO++5>T---5 3335tr#   F	dsl_namesN
op_symbolsdispatch_keysremove_keysc                    |r| xj         t          t          |                    z  c_         | xj        t          t          |                    z  c_        | xj        t          t          |                    z  c_        dS | xj         t          t          |                    z  c_         | xj        t          t          |                    z  c_        | xj        t          t          |                    z  c_        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.   r0   r1   r2   r3   s        r$   updatez_FilterState.updateI   s    (  	IOOs#4Y#?#?@@@OO$5j$A$A B BB3'8'G'G#H#HHOOs#4Y#?#?@@@OO$5j$A$A B BB3'8'G'G#H#HHr#   c                 B    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'     O
 
 	
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0 	% 	%FAs$$$S$$$$AA	%%t/00 	$ 	$EAr###R####AA	)) 344 	% 	%FAs$$$S$$$$AA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&   ,   sf        55 5555JC555!E#666KS666$uS999NCH999- D    4 "I I#&-I (3-'$.I Xc]*T1	I
 I 
I 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                 x    t          |           }|D ]&}||v r ||         D ]}                    |           'dS )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   sa     -W55% 	% 	%E&&)%0 % %CKK$$$$	% 	%r#   )r5   r   r   _MappingTyperJ   rL   rK   )r0   r1   r2   rU   rT   s       @r$   r9   r9      s      %(EEG	%x}$t+	%=I	%		% 	% 	% 	% 	% 	% N94555N:6777N="<===Nr#   F)print_inactiverW   c                    t                                           D ]n\  \  }}}t          d|d|           t          |          D ]A\  }}|j        s| r3d| d|j        d|j        }| r|d|j        z  }t          |           BodS )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 ++ 	 	GAt{ n UUUT]UUt7RUU! ,+T[+++Aa		 	r#   r   r   c                     | |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)rH   torchlibraryLibrary)r   r   rD   s      r$   _get_or_create_libraryrc      s@     l
#C
%]**66<HHc
:r#   libr+   c                 Z    |                      |j        |j        ||j         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   )rd   r+   r   s      r$   _register_node_implri      sC     HH33      r#   iterablec                 h    | 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-F {Or#   )enable_dsl_namesenable_op_symbolsenable_dispatch_keysrm   rn   ro   c                 
   t                               d| ||           t                              | ||d           t	          | ||          }|D ]3}|\  }}|t
          v r#t          ||t
          |         t                     4d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)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                               d| ||           t                              | ||           t                                          }|D ]3}|\  }}|t
          v r#t          ||t
          |         t                     4d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: %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VV %2$G$G$I$IG  	 	"%	<'>>)*	   		 	r#   r   c                     t                      }t                                          D ]/\  \  }}}|D ]$}|j        | k    r|                    |            n%0t          |          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  sv     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          ||           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symbolrD   r,   Nc                 r    |                      |          }|
|g}|| |<   dS |                    |           dS )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  sN     "%%f--
J#-L   c"""""r#   )dictr   listrF   rJ   rL   rK   )r   r   r   rD   r   s        r$   _update_registration_mapsr   {  s    &#3U38_ 556## 38_# 
	# # # # 3XsCCC4iEEE7sKKKKKr#   )allow_multiple_overrider   backend
lib_symbolrh   r   r   c          	          |dk    rt          d| d          ||f}t                              |g           }|                    t	          | ||||                     |t          |<   t          | |||           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"
    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     s    8 VW*WWWXXXl
#C {{3##HOO%#9	
 	
 	
   GCLgy,CHHHHHHr#   force_reregisteroriginal_graph	new_graphr   c                    |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   s      r$   _should_reregister_graphr     s    "  t Y&&r#   rq   graphrr   c                ^    | |f}|t           v rt           |= |rt          | |||           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
    rq   N)rH   ru   )r   r   r   rr   rD   s        r$   rz   rz     sa    $ l
#C e||#J  
&%		
 	
 	
 	
 	
 	

 
r#   )keys_to_processreregister_overridesrr   transformation_fnr   r   c                   ||n%t          t                                                    }t          |          D ]\  }}||ft          vrt          t          ||f                   }	  | |||          }nh# t          t
          t          t          f$ r! t          	                    d||d           Y zt          $ r t                              d||           Y w xY wt          |t                    s0t          	                    dt          |          j        ||           |t          ||f<   |r%t          ||d          rt!          ||||	           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   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<O 
 $(#4#4 / /	<|$G33gy,&?@AA	)))\>RRII:~|D 	 	 	KKS	     H 	 	 	MM`  
 H	 )T** 	KKtY(	    .7L)*   	$<I%
 %
 %
 	 *)	   U/ /s   )A77;C4%CCc                    | |f}t          | }|D ]=}d}|r|                    |          }|rt          |||           d|_        6d|_        >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)rc   r/   ri   r   )r   r   r   rr   rD   rd   r+   enables           r$   ru   ru   _  s}      l
#C
 #
&C 	  	  	6!//55F 	 T<888DKKDKK	  	 r#   c                  p    t                                           D ]\  } }| \  }}t          |||           dS )zO
    Perform all registration calls from previously-built override graphs.
    N)rI   rY   ru   )rD   r   r   r   s       r$   _register_all_overridesr   ~  sS     mmoo 
 

U"%	<&	
 	
 	
 	

 
r#   )r   fnc                (    t          | |           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   s     r$   r   r     s+    "  1     r#   	filter_fnc          	           dt           dt           dt          t                   dt          t                   f fd}t          ||           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                     	  fd|D             S # t           t          t          t          f$ r# t                              d d           |cY S t          $ r! t                              d            |cY S w xY w)z-Apply filter_fn to graph with error handling.c                 .    g | ]} |          |S r"   r"   ).0r+   r   r   r   s     r$   
<listcomp>zI_apply_graph_filter.<locals>.filtering_transformation.<locals>.<listcomp>  s-    WWWTii	<QU.V.VWDWWWr#   r   Tr   r   r   r   r   r   rs   r   r   r   )r   r   r   r   s   `` r$   filtering_transformationz5_apply_graph_filter.<locals>.filtering_transformation  s    	WWWWWWUWWWW:~|D 	 	 	KKS	     LLL 	 	 	MM`  
 LLL	s    =A>'A>=A>r   Nr   r   r   r   )r   r   r   s   `  r$   _apply_graph_filterr     st    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          ||           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                    	  | |          }nl# t           t          t          t          f$ r# t                              d| |d           |cY S t          $ r! t                              d| |           |cY S w xY w|rz	  | ||          S # t           t          t          t          f$ r# t                              d| |d           |cY S t          $ r! t                              d| |           |cY S w xY w|S )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  si   	)\)\BBNN:~|D 	 	 	KKS	     LLL 	 	 	MM`  
 LLL	  	"{9lEBBBz><H   W !	        d   
  s-    =A9'A98A9?B =C5'C54C5r   Nr   )r   r   r   r   s   ``  r$   _apply_selective_reorderingr     s{    <))&))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 2 2 2 2 2 2 2 2       g!!IcNNGCLLU%91%<=q@A1~$         3T-%894;NNO T T T T T T T Tp +lnn| , , , 79tE#s(OU]223 8 8 8 5c?D$778   CeCHo../ (*  ) ) )+- L - - -(*  * * *!Xc]"T)!hsm#d*! #&-! 	sCx	! ! ! !H 6;   d t    &c  AV    (		&3CF	   (hsm 3d : x}    * 040437	2 2 2DIo,2 T#Y-2 S	/D0	2
 
2 2 2 2n 151548	) ) )T#Y-) d3i$.) c?T1	)
 
) ) ) )X c    $#L#L#L #L 
sCx	#L
 
#L #L #L #LZ %*#(/I /I /I/I/I /I 	/I
 ,
&/I "/I !/I 
/I /I /I /Il #	' ' '''M"' 	'
 
' ' ' ': )- 
  
  
 
 
  

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