o
    wZhs                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZ d dlmZmZ d dlmZmZmZmZmZmZmZmZ d dlmZ d dl
mZ d dlmZ eee e!de"e#e$e%e&f	Z'edeeee de"e#e$e%e&f	 d	Z(e) Z*eG d
d dee( Z+ere*dddddfdee(e)f dee" deee"e#e" f  deee"e#e" f  dee! dee" de(fddZ,n6e*dddddfdee(e)f dee" deee"e#e" f  deee"e#e" f  dee! dee" de+e( fddZ,de"deee e"f  fddZ-deddfddZ.dZ/dede$e" fddZ0eG dd  d Z1G d!d" d"eZ2G d#d$ d$e j3Z3G d%d& d&Z4d'e)de"d(e)de)fd)d*Z5d-de"dedee  fd+d,Z6dS ).    N)	dataclass)FunctionType
ModuleType)AnyCallableGenericNoReturnOptionalTYPE_CHECKINGTypeVarUnion)
deprecated)mock)justknobs_checkT)boundc                   @   s   e Zd ZU dZeeef ed< dZe	e
 ed< dZe	ee
  ed< dZe	ee
  ed< dZe	e
 ed< edddddfdeeef de	e
 de	ee
ee
 f  de	ee
ee
 f  de	e de	e
 fd	d
Zede	ee
ee
 f  de	ee
  fddZdS )_Configa  Represents a config with richer behaviour than just a default value.
    ::
        i.e.
        foo = Config(justknob="//foo:bar", default=False)
        install_config_module(...)

    This configs must be installed with install_config_module to be used

    Precedence Order:
        alias: If set, the directly use the value of the alias.
        env_name_force: If set, this environment variable has precedence over
            everything after this.
            If multiple env variables are given, the precendence order is from
            left to right.
        user_override: If a user sets a value (i.e. foo.bar=True), that
            has precedence over everything after this.
        env_name_default: If set, this environment variable will override everything
            after this.
            If multiple env variables are given, the precendence order is from
            left to right.
        justknob: If this pytorch installation supports justknobs, that will
            override defaults, but will not override the user_override precendence.
        default: This value is the lowest precendance, and will be used if nothing is
            set.

    Environment Variables:
        These are interpreted to be either "0" or "1" to represent true and false.

    Arguments:
        justknob: the name of the feature / JK. In OSS this is unused.
        default: is the value to default this knob to in OSS.
        alias: The alias config to read instead.
        env_name_force: The environment variable, or list of, to read that is a FORCE
            environment variable. I.e. it overrides everything except for alias.
        env_name_default: The environment variable, or list of, to read that changes the
            default behaviour. I.e. user overrides take preference.
    defaultNjustknobenv_name_defaultenv_name_forcealias
value_typec                 C   sj   || _ || _t|| _t|| _|| _|| _| jd ur1|tu r-|d u r-|d u r-|d u s3J dd S d S )NzCif alias is set, none of {default, justknob and env var} can be set)	r   r   r    string_or_list_of_string_to_listr   r   r   r   _UNSET_SENTINEL)selfr   r   r   r   r   r    r   I/var/www/auris/lib/python3.10/site-packages/torch/utils/_config_module.py__init__W   s"   


z_Config.__init__valreturnc                 C   s.   | d u rd S t | tr| gS t | tsJ | S N)
isinstancestrlist)r   r   r   r   r   q   s   
z(_Config.string_or_list_of_string_to_list)__name__
__module____qualname____doc__r   r   object__annotations__r   r	   r#   r   r$   r   r   r   typer   staticmethodr   r   r   r   r   r   )   s@   
 &


r   r   r   r   r   r   r   r    c                 C   s   d S r!   r   r   r   r   r   r   r   r   r   r   Config   s   r.   c                 C   s   t | |||||S r!   )r   r-   r   r   r   r.      s   namec                 C   s(   t j| }|dkrdS |dkrdS |S N1T0Fosenvironget)r/   valuer   r   r   _read_env_variable      r8   modulec                    s|   G dd dt }dtttf dtttf dtddf fdd	i  t}d
  _|_|_	d_
d_dS )z
    Converts a module-level config into a `ConfigModule()`.

    See _config_typing.pyi for instructions on how to get the converted module to typecheck.
    c                   @   s   e Zd Zeh dZdS )z3install_config_module.<locals>.ConfigModuleInstance>   _hash_digestr*   	_is_dirtyN)r%   r&   r'   set_bypass_keysr   r   r   r   ConfigModuleInstance   s    r?   sourcedestprefixr    Nc           	   	      s  t jdd dk rt| di }nt| }t| j D ]\}}|ds@t	|t
tfs@t|dr6|jdks@t	|trAt|trAq| | }||d}t	|trftt||d |< |u ret| qt	|tr|durw|jdu rw||_t| |< |u rt| qt	|tr|jjksJ t| d	}||| d	 |u rt||| q||j|< qtd
| d| dt| ddS )z?Walk the module structure and move everything to module._configN   )   
   r*   __r&   typing)r   r   .zUnhandled config =z ())sysversion_infogetattrinspectget_annotationsr$   __dict__items
startswithr"   r   r   hasattrr&   r+   
issubclassr   r6   CONFIG_TYPES_ConfigEntrydelattrr   r%   SubConfigProxysetattrAssertionError)	r@   rA   rB   Z
type_hintskeyr7   r/   annotated_typeproxyconfigr:   visitr   r   r`      sR   







 z$install_config_module.<locals>.visit T)ConfigModuler   r   r+   rX   r#   -get_assignments_with_compile_ignored_comments_config_compile_ignored_keys	__class__r<   r;   )r:   r?   Zcompile_ignored_keysr   r^   r   install_config_module   s$   

0
rg   z@compile_ignoredc                 C   s   t | }t }tt|dj}d}d}|D ]W}|jtj	kr@d}|j
 }t|v r?|dks8J dt ||jd f}q|jtjkrL|sK|j
}q|jtjkrq|j
dkrqt|d v ro|d |jd d kro|| d}d}q|dks}J dt |S )Nutf-8)ra   ra   zunconsumed r   rI      )rN   	getsourcer=   tokenizeioBytesIOencodereadliner+   COMMENTstringstripCOMPILE_IGNORED_MARKERstartNAMEOPadd)r:   Zsource_codeZassignmentstokensZcurrent_commentZ	prev_nametokenZmaybe_currentr   r   r   rc      s8   



rc   c                   @   s|   e Zd ZU eed< eed< eZeed< dZe	e
 ed< eZeed< eZeed< dZeed	< dZe	e
 ed
< defddZdS )rV   r   r   user_overrideNr   env_value_forceenv_value_defaultFhider   r_   c                 C   s  |j | _ |jd ur|jnt| j | _|j| _|j| _|jd ur2|jD ]}t| }d ur1|| _ nq"|jd urJ|jD ]}t| }d urI|| _	 nq:| jd urc| j d urct
| j tscJ d| j  d| jd ur|jd usr|jd ur| jtttt tt fv sJ d| j dd S d S d S )Nz!justknobs only support booleans, z is not a booleanz<envvar configs only support (optional) booleans or strings, z is neither)r   r   r+   r   r   r   r8   r}   r   r|   r"   boolr#   r	   )r   r_   r   Z	env_valuer   r   r   r   2  sH   




z_ConfigEntry.__init__)r%   r&   r'   r   r*   r+   r   r{   r   r	   r#   r|   r}   r~   r   r   r   r   r   r   r   r   rV     s   
 rV   c                       sL  e Zd ZU eeef ed< ee ed< ee ed< eed< e	e
 ed< dBdd	Zd
ededdf fddZd
edefddZd
eddfddZdede	eeef  fddZdedefddZdededdfddZd
edefddZ			dCde	ee  de	ee  dedeeef fd d!Zd"edefd#d$Zde
fd%d&Zdeeef fd'd(Zdefd)d*Zde
fd+d,Zed-e d.deeef fd/d0Z!ed1e d.deeef fd2d3Z"d4e#e
eeef f ddfd5d6Z$deeef fd7d8Z%		dDd9e	e#eeeef f  d:ed;eeef dd<fd=d>Z&d?eeef defd@dAZ'  Z(S )Erb   rd   r>   re   r<   r;   r    Nc                 C   s   t dt d)Nzuse z-.install_config_module(sys.modules[__name__]))NotImplementedErrorr%   r   r   r   r   r   `  s   
zConfigModule.__init__r/   r7   c                    s   || j v rt || d S || jvrt| j d| d| j| jd ur1| | j| | d S || j| _d| _	d| j| _
d S )NrH    does not existTF)r>   super__setattr__rd   AttributeErrorr%   r   _set_alias_valr{   r<   r~   r   r/   r7   rf   r   r   r   e  s   

zConfigModule.__setattr__c              
   C   s   z`| j | }|jrt| j d| d| |}|tur |W S |jtur)|jW S |jtur2|jW S |jtur;|jW S |j	d urIt
|j	|jdW S t|jtttfr]t|j|_|jW S |jW S  tyx } zt| j d| d|d }~ww )NrH   r   )r/   r   )rd   r~   r   r%   _get_alias_valr   r|   r{   r}   r   r   r   r"   r$   r=   dictcopydeepcopyKeyError)r   r/   r_   Z	alias_valer   r   r   __getattr__q  s.   





zConfigModule.__getattr__c                 C   s"   d| _ t| j| _d| j| _d S )NT)r<   r   rd   r{   r~   r   r/   r   r   r   __delattr__  s   zConfigModule.__delattr__entryc              
   C   sZ   |j }|d u r	d S |dd\}}z
t|}W ||fS  ty, } ztd|d }~ww )NrH   rj   z#config alias {alias} does not exist)r   rsplit	importlibimport_moduleImportErrorr   )r   r   r   module_nameconstant_namer:   r   r   r   r   _get_alias_module_and_name  s   
z'ConfigModule._get_alias_module_and_namec                 C   s,   |  |}|d u rtS |\}}t||}|S r!   )r   r   rM   )r   r   datar:   r   Zconstant_valuer   r   r   r     s   

zConfigModule._get_alias_valr   c                 C   s.   |  |}|d usJ |\}}t||| d S r!   )r   rY   )r   r   r   r   r:   r   r   r   r   r     s   
zConfigModule._set_alias_valc                 C   sn   | j | }|jtu p|j|jk}|jtu p|j|jk}|jtu }t|jttt	fr1|p0|j|jk}|o6|o6|S )z
        Returns true if the config is at its default value.
        configs overriden by the env are not considered default.
        )
rd   r}   r   r   r|   r{   r"   r$   r=   r   )r   r/   Z
config_valZnot_set_env_defaultZnot_set_env_forceunsetr   r   r   _is_default  s   





zConfigModule._is_defaultFignored_keysignored_prefixesskip_defaultc                    st   i }| j D ]2 |r |v rq|rt fdd|D rq|r$|  r$q| j   jdur-qtt|  | < q|S )a  Export a dictionary of current configuration keys and values.

        This function is design to provide a single point which handles
        accessing config options and exporting them into a dictionary.
        This is used by a number of different user facing export methods
        which all have slightly different semantics re: how and what to
        skip.
        If a config is aliased, it skips this config.

        Arguments:
            ignored_keys are keys that should not be exported.
            ignored_prefixes are prefixes that if a key matches should
                not be exported
            skip_default does two things. One if a key has not been modified
                it skips it.
        c                 3   s    | ]}  |V  qd S r!   )rR   ).0rB   r[   r   r   	<genexpr>  s    z)ConfigModule._get_dict.<locals>.<genexpr>N)rd   anyr   r   r   r   rM   )r   r   r   r   r_   r   r   r   	_get_dict  s   
zConfigModule._get_dictconfig_namec                 C   s   | j | jS r!   )rd   r   )r   r   r   r   r   get_type  s   zConfigModule.get_typec                 C   s"   t | dg }tj| j|dddS )z Convert config to a pickled blob_save_config_ignorer   rC   )protocol)rM   pickledumpsr   )r   r   r   r   r   save_config  s
   
zConfigModule.save_configc                 C   s$   dg}| t| dg  | j|dS )z!Convert config to portable format_Z_cache_config_ignore_prefix)r   )extendrM   r   )r   prefixesr   r   r   save_config_portable  s   z!ConfigModule.save_config_portablec                    s   t  dtdtdtfdddtddffdd d	ttt f dtt ffd
dd	tdtfdddtf fdd}g }| j}| jt	| dg dd
 D ]\}}||||| qRD ]}|dd|  qbd|S )zConvert config to Python statements that replicate current config.
        This does NOT include config settings that are at default values.
        funcadd_dotr    c                 S   s*   | j }|dkr	d}|r|dkr|d7 }|S )Nbuiltinsra   rH   )r&   )r   r   r   r   r   r   get_module_name  s   z4ConfigModule.codegen_config.<locals>.get_module_nameNc                    s     | d}|r | d S d S )NF)rx   )r   r   )r   importsr   r   
add_import  s   
z/ConfigModule.codegen_config.<locals>.add_importvc                    s    fdd| D S )Nc                    s    g | ]} |d  |j  qS )T)r%   r   itemr   r   r   
<listcomp>  s     zTConfigModule.codegen_config.<locals>.list_of_callables_to_string.<locals>.<listcomp>r   r   r   r   r   list_of_callables_to_string     z@ConfigModule.codegen_config.<locals>.list_of_callables_to_stringc                 S   s   t | ot| dot| dS )Nr&   r%   )callablerS   r   r   r   r   importable_callable  s   z8ConfigModule.codegen_config.<locals>.importable_callablec                    s   |r | |  d| d|d |j  S t|ttfrTtfdd|D rT|D ]} | q,|}t|trF|  d| d| S |  d| dd| dS |  d| d|S )	a  
            Return a string version of the config line.
            Handle v when v is a callable, or a list/dict of callables. Add import statements for callables if necessary.
            We assume that the value of a single config won't be a mix of callables and non-callables.

            Example output:
                import logging
                import _warnings
                torch._dynamo.config.reorderable_logging_functions = { _warnings.warn, logging.warn, print }
            rH   z = Tc                 3   s    | ]} |V  qd S r!   r   r   )r   r   r   r   /  s    
zGConfigModule.codegen_config.<locals>.get_config_line.<locals>.<genexpr>z = { z, z })r%   r"   r$   r=   alljoin)modkr   r   Zv_list)r   r   r   r   r   r   get_config_line!  s    

z4ConfigModule.codegen_config.<locals>.get_config_liner   T)r   r   r   zimport 
)r=   r   r   r#   r   r$   r   r%   r   rM   rQ   appendinsertr   )r   r   linesr   r   r   import_namer   )r   r   r   r   r   r   codegen_config  s"   "

zConfigModule.codegen_configc                 C   sX   | j s| jdu r)| jt| jd}tt| }tj	|
ddd | _d| _ | jS )z/Hashes the configs that are not compile_ignoredNr   rh   F)usedforsecurity)r<   r;   r   r$   re   reprsortedrQ   hashlibmd5ro   digest)r   Zdict_to_hashZstring_to_hashr   r   r   get_hashF  s   
zConfigModule.get_hashz`config.to_dict()` has been deprecated. It no longer changes the underlying config. use `config.get_config_copy()` instead if you just want a copy of the config, or config.load_config if you need mutable access)categoryc                 C      |   S r!   get_config_copyr   r   r   r   to_dictQ     zConfigModule.to_dictz`config.shallow_copy_dict()` has been deprecated. It no longer changes the underlying config. use `config.get_config_copy()` instead if you just want a copy of the config, or config.load_config if you need mutable accessc                 C   r   r!   r   r   r   r   r   shallow_copy_dictZ  r   zConfigModule.shallow_copy_dictmaybe_pickled_configc                 C   sj   t |tst|}n|}| D ]!\}}|| jv r!t| || qddlm} |d| d| d qdS )zARestore from a prior call to save_config() or shallow_copy_dict()r   )	warn_oncezkey z with value z! is not understood by this configN)	r"   r   r   loadsrQ   rd   rY   Ztorch._dynamo.utilsr   )r   r   r_   r   r   r   r   r   r   load_configc  s   

zConfigModule.load_configc                 C   r   r!   )r   r   r   r   r   r   q     zConfigModule.get_config_copyarg1arg2kwargsContextDecoratorc                    s   |dur"|durt |tsJ ||i n	t |tsJ | |r!J n| |du s*J t  ts8J dt  i | G  fdddt}| S )a  
        Decorator and/or context manager to make temporary changes to a config.

        As a decorator:

            @config.patch("name", val)
            @config.patch(name1=val1, name2=val2)
            @config.patch({"name1": val1, "name2", val2})
            def foo(...):
                ...

        As a context manager:

            with config.patch("name", val):
                ...
        Nzexpected `dict` got c                       s,   e Zd Zd fddZfddZdS )z'ConfigModule.patch.<locals>.ConfigPatchr    Nc                    sF   rJ    D ]	}||< q  D ]
\}}|| qd S r!   )keysr   rQ   r   )r   r[   r   r   changesr_   priorr   r   	__enter__  s   z1ConfigModule.patch.<locals>.ConfigPatch.__enter__c                    s*     D ]
\}} || q  d S r!   )rQ   r   clear)r   exc_typeexc_valexc_tbr   r   )r_   r   r   r   __exit__  s   z0ConfigModule.patch.<locals>.ConfigPatch.__exit__r    N)r%   r&   r'   r   r   r   r   r   r   ConfigPatch  s    r   )r"   r#   r   r+   r   )r   r   r   r   r   r   r   r   patcht  s   

zConfigModule.patchr   c                    s(   j dtg df f fdd}|S )aV  
        A lower-overhead version of patch() for things on the critical path.

        Usage:

            # do this off the critical path
            change_fn = config.make_closure_patcher(foo=True)

            ...

            revert = change_fn()
            try:
              ...
            finally:
                revert()

        r    Nc                     sD   fddD    D ]
\} }|j|  _qd fdd}|S )Nc                    s   i | ]}| | j qS r   )r{   )r   r   )r_   r   r   
<dictcomp>  s    zFConfigModule._make_closure_patcher.<locals>.change.<locals>.<dictcomp>r    c                     s"      D ]
\} }|j|  _qd S r!   rQ   rd   r{   )r   r   )r   r   r   r   revert  s   zBConfigModule._make_closure_patcher.<locals>.change.<locals>.revertr   r   )r   r   r   r   r_   r   )r   r   change  s
   z2ConfigModule._make_closure_patcher.<locals>.change)rd   r   )r   r   r   r   r   r   _make_closure_patcher  s   z"ConfigModule._make_closure_patcherr   )NNF)NN))r%   r&   r'   r   r#   rV   r*   r=   r   r	   bytesr   r)   r   r   r   r   tupler   r   r   r   r   r$   r   r+   r   r   r   r   r   r   FutureWarningr   r   r   r   r   r   r   __classcell__r   r   r   r   rb   T  sv   
 
$




%A"

"9rb   c                       sL   e Zd ZdZdddZdefddZdeegef def fd	d
Z	  Z
S )r   z[
    Same as contextlib.ContextDecorator, but with support for
    `unittest.TestCase`
    r    Nc                 C      t dNZNYIr   r   r   r   r   r     r   zContextDecorator.__enter__c                 C   r   r   r   )r   r   r   r   r   r   r   r     r   zContextDecorator.__exit__r   c                    sR   t |tr#t|tjr#G  fddd|}|j|_|j|_|j|_|S t 	|S )Nc                       s8   e Zd Zed fddZed fddZ  ZS )z,ContextDecorator.__call__.<locals>._TestCaser    Nc                    s8      zt   W d S  ty   d d d   w r!   )r   r   
setUpClass	Exceptionr   clsrf   r   r   r   r     s   z7ContextDecorator.__call__.<locals>._TestCase.setUpClassc                    s0   zt    W d d d  d S d d d  w r!   )r   tearDownClassr   r   r  r   r   r    s   "z:ContextDecorator.__call__.<locals>._TestCase.tearDownClassr   )r%   r&   r'   classmethodr   r  r   r   r   r   r   	_TestCase  s
    r  )
r"   r+   rT   unittestZTestCaser%   r'   r&   r   __call__)r   r   r  r   r   r   r    s   zContextDecorator.__call__r   )r%   r&   r'   r(   r   r   r   r   r   r  r   r   r   r   r   r     s
    
(r   c                       sd   e Zd ZdZdedef fddZdededd	fd
dZdedefddZ	dedd	fddZ
  ZS )rX   zn
    Shim to redirect to main config.
    `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
    r_   rB   c                    s    t  d| t  d| d S )Nrd   _prefix)r   r   )r   r_   rB   r   r   r   r     s   zSubConfigProxy.__init__r/   r7   r    Nc                 C   s   | j | j| |S r!   )rd   r   r  r   r   r   r   r     s   zSubConfigProxy.__setattr__c                 C      | j | j| S r!   )rd   r   r  r   r   r   r   r     r   zSubConfigProxy.__getattr__c                 C   r  r!   )rd   r   r  r   r   r   r   r   	  r   zSubConfigProxy.__delattr__)r%   r&   r'   r(   r)   r#   r   r   r   r   r   r   r   r   r   r   rX     s    rX   objr7   c                 C   s&   t | tr| ||S tj| ||S )z@
    Workaround `mock.patch.object` issue with ConfigModule
    )r"   rb   r   r   r)   )r	  r/   r7   r   r   r   patch_object  s   
r
  c                 C   s(   t j| }|dkrdS |dkrdS |S r0   r3   )r/   r   r7   r   r   r   get_tristate_env  r9   r  r!   )7
contextlibr   r   r   rN   rm   r4   r   rK   rl   r  dataclassesr   typesr   r   rG   r   r   r   r   r	   r
   r   r   Ztyping_extensionsr   r   Ztorch._utils_internalr   intfloatr   r+   r#   r$   r=   r   r   rU   r   r)   r   r   r.   r8   rg   rt   rc   rV   rb   r   rX   r
  r  r   r   r   r   <module>   s    (
"W


	G&=  }) 	