
    VhF                     
   U d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
mZ ddlZddlmZ  ej                  e      Z G d de      Ze	ej$                  eej(                     gef   Zi Zeee
e   f   ed	<   i Zeeef   ed
<   	 	 	 dde
e   de
e   dee   fdZ ej8                  ed      Z ej8                  ed      Zd Zddee   fdZ  ejB                  d      d        Z" ejB                  d      d        Z#y)a  
This module implements TorchDynamo's backend registry system for managing compiler backends.

The registry provides a centralized way to register, discover and manage different compiler
backends that can be used with torch.compile(). It handles:

- Backend registration and discovery through decorators and entry points
- Lazy loading of backend implementations
- Lookup and validation of backend names
- Categorization of backends using tags (debug, experimental, etc.)

Key components:
- CompilerFn: Type for backend compiler functions that transform FX graphs
- _BACKENDS: Registry mapping backend names to entry points
- _COMPILER_FNS: Registry mapping backend names to loaded compiler functions

Example usage:
    @register_backend
    def my_compiler(fx_graph, example_inputs):
        # Transform FX graph into optimized implementation
        return compiled_fn

    # Use registered backend
    torch.compile(model, backend="my_compiler")

The registry also supports discovering backends through setuptools entry points
in the "torch_dynamo_backends" group. Example:
```
setup.py
---
from setuptools import setup

setup(
    name='my_torch_backend',
    version='0.1',
    packages=['my_torch_backend'],
    entry_points={
        'torch_dynamo_backends': [
            # name = path to entry point of backend implementation
            'my_compiler = my_torch_backend.compiler:my_compiler_function',
        ],
    },
)
```
```
my_torch_backend/compiler.py
---
def my_compiler_function(fx_graph, example_inputs):
    # Transform FX graph into optimized implementation
    return compiled_fn
```
Using `my_compiler` backend:
```
import torch

model = ...  # Your PyTorch model
optimized_model = torch.compile(model, backend="my_compiler")
```
    N)Sequence)
EntryPoint)CallableOptionalProtocol)fxc                   N    e Zd Zdej                  deej                  df   fdZy)
CompiledFnargsreturn.c                      y )N )selfr   s     O/home/dcms/DCMS/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py__call__zCompiledFn.__call__N   s        N)__name__
__module____qualname__torchTensortupler   r   r   r   r
   r
   M   s!    LellLuU\\35F/GLr   r
   	_BACKENDS_COMPILER_FNScompiler_fnnametagsc                     | t        j                  t        ||      S t        |       sJ |xs | j                  }|t
        vs
J d|        | t        vr	dt        |<   | t
        |<   t        |      | _        | S )a  
    Decorator to add a given compiler to the registry to allow calling
    `torch.compile` with string shorthand.  Note: for projects not
    imported by default, it might be easier to pass a function directly
    as a backend and not use a string.

    Args:
        compiler_fn: Callable taking a FX graph and fake tensor inputs
        name: Optional name, defaults to `compiler_fn.__name__`
        tags: Optional set of string tags to categorize backend with
    N)r   r   zduplicate name: )		functoolspartialregister_backendcallabler   r   r   r   _tags)r   r   r   s      r   r!   r!   W   s        !14HHK   ';''D}$?(8&??$)#	$%M$dKr   )debug)r   )experimentalc                     t        | t              r^| t        vr
t                | t        vrddlm}  ||       | t        vr$t        |    }t        |j                         |        t        |    } | S )z#Expand backend strings to functions   )InvalidBackend)r   )r   r   )	
isinstancestrr   _lazy_importexcr(   r   r!   load)r   r(   entry_points      r   lookup_backendr/   z   sd    +s#i'Ni', k22m+#K0K)9)9);+N#K0r   r   c                     t                t        | xs d      } t        j                         D cg c].  }|t        vs"| j                  t        |   j                        s|0 }}t        |      S c c}w )za
    Return valid strings that can be passed to:

        torch.compile(..., backend="name")
    r   )r+   setr   keysr   intersectionr#   sorted)exclude_tagsr   backendss      r   list_backendsr7      sq     N|)r*L NN$}$((t)<)B)BC 	H  (s   3A0c                  T    ddl m}  ddlm}  ||        ddlm} |J t                y )Nr'   )r6   )import_submodule)dynamo_minifier_backend) r6   utilsr9   repro.after_dynamor:   _discover_entrypoint_backends)r6   r9   r:   s      r   r+   r+      s%    (X<"...!#r   c                     ddl m}  d}t        j                  dk  r- |        }||v r||   ng }|D ci c]  }|j                  | }}n& | |      }|j
                  D ci c]  }|||   
 }}|D ]  }||   t        |<    y c c}w c c}w )Nr   )entry_pointstorch_dynamo_backends)   
   )group)importlib.metadatar@   sysversion_infor   namesr   )r@   
group_nameepsepr   backend_names         r   r>   r>      s     0(J
'!n!+s!2c*o%()rrww{)),+.9954tSY55 4"%l"3	,4	 * 6s   B B)NNr   ))r$   r%   )$__doc__r   loggingrF   collections.abcr   rE   r   typingr   r   r   r   r   	getLoggerr   logr
   GraphModulelistr   
CompilerFnr   dictr*   __annotations__r   r!   r    register_debug_backendregister_experimental_backendr/   r7   	lru_cacher+   r>   r   r   r   <module>r[      sX  :x   
 $ ) / /   g!M M r~~tELL'9:JFG
-/	4Xj))* /')tCO$ ) )-*%
3- 3-: +**+;*M  1	 1 1,! 
"T#Y $ T
$ 
$ T4 4r   