a
    hit                     @   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r~e*dddddfee(e)f ee" eee"e#e" f  eee"e#e" f  ee! ee" e(dddZ,n`e*dddddfee(e)f ee" eee"e#e" f  eee"e#e" f  ee! ee" e+e( dddZ,e"eee e"f  dddZ-eddddZ.dZ/ee$e" dddZ0eG dd dZ1G dd deZ2G dd de j3Z3G dd  d Z4e)e"e)e)d!d"d#Z5d'e"eee  d$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eeef e	e
 e	ee
ee
 f  e	ee
ee
 f  e	e e	e
 dd	d
Zee	ee
ee
 f  e	ee
  d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r   r   r   r   
value_typer   c                 C   sf   || _ || _t|| _t|| _|| _|| _| jd urb|tu rZ|d u rZ|d u rZ|d u sbJ d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   H/var/www/auris/lib/python3.9/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   )   s0   
&

r   )r   r   r   r   r   r   r!   c                 C   s   d S r"   r   r   r   r   r   Config   s    r.   c                 C   s   t | |||||S r"   )r   r   r   r   r   r.      s    namer!   c                 C   s(   t j| }|dkrdS |dkr$dS |S N1T0Fosenvironget)r0   valuer   r   r   _read_env_variable   s    r9   )moduler!   c                    sv   G dd dt }tttf tttf tdd 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?   N)sourcedestprefixr!   c           	   	      s  t jdd dk r t| di }n
t| }t| j D ]^\}}|ds8t	|t
tfs8t|drn|jdks8t	|trt|trq8| | }||d}t	|trtt||d |< |u rt| q8t	|tr|dur|jdu r||_t| |< |u rt| q8t	|trx|jjks2J t| d	}||| d	 |u rlt||| n
||j|< q8td
| d| dt| dq8d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inspectZget_annotationsr%   __dict__items
startswithr#   r   r   hasattrr'   r,   
issubclassr   r7   CONFIG_TYPES_ConfigEntrydelattrr   r&   SubConfigProxysetattrAssertionError)	r@   rA   rB   Z
type_hintskeyr8   r0   annotated_typeproxyconfigr:   visitr   r   r_      sN    




z$install_config_module.<locals>.visit T)ConfigModuler   r   r,   rW   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rf   z@compile_ignoredc                 C   s   t | }t }tt|dj}d}d}|D ]}|jtj	krd}|j
 }t|v r|dkspJ dt ||jd f}q4|jtjkr|s|j
}q4|jtjkr4|j
dkr4t|d v r|d |jd d kr|| d}d}q4|dksJ dt |S )Nutf-8)r`   r`   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   rb      s6    




rb   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
< edddZdS )rU   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rd|jD ]}t| }d urD|| _ qdqD|jd ur|jD ]}t| }d urt|| _	 qqt| jd ur| j d urt
| j tsJ d| j  d| jd ur|jd us|jd ur| jtttt tt fv sJ d| j d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   r9   r|   r   r{   r#   boolr$   r	   )r   r^   r    Z	env_valuer   r   r   r   2  sD    




z_ConfigEntry.__init__)r&   r'   r(   r   r+   r,   r   rz   r   r	   r$   r{   r|   r}   r   r   r   r   r   r   r   r   rU     s   
rU   c                       s*  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< dddd	Zeedd
 fddZeedddZeddddZee	eeef  dddZeedddZeeddddZeedddZdAe	ee  e	ee  eeeef dddZeed d!d"Ze
dd#d$Zd%d&eeeef d'd(d)Zedd*d+Ze
dd,d-Zed.e d/eeef dd0d1Z!ed2e d/eeef dd3d4Z"e#e
eeef f dd5d6d7Z$eeef dd8d9Z%dBe	e#eeeef f  eeeef d:d;d<d=Z&eeef ed>d?d@Z'  Z(S )Cra   rc   r>   rd   r<   r;   Nr!   c                 C   s   t dt dd S )Nzuse z-.install_config_module(sys.modules[__name__]))NotImplementedErrorr&   r   r   r   r   r   `  s    
zConfigModule.__init__r0   r8   r!   c                    s   || j v rt || nd|| jvr<t| j d| dnB| j| jd ur`| | j| | n|| j| _d| _	d| j| _
d S )NrH    does not existTF)r>   super__setattr__rc   AttributeErrorr&   r   _set_alias_valrz   r<   r}   r   r0   r8   re   r   r   r   e  s    

zConfigModule.__setattr__r/   c              
   C   s  z| j | }|jr(t| j d| d| |}|tur@|W S |jturR|jW S |jturd|jW S |jturv|jW S |j	d urt
|j	|jdW S t|jtttfrt|j|_|jW S |jW S  t y } z$t| j d| d|W Y d }~n
d }~0 0 d S )NrH   r   )r0   r   )rc   r}   r   r&   _get_alias_valr   r{   rz   r|   r   r   r   r#   r%   r=   dictcopydeepcopyKeyError)r   r0   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   rc   rz   r}   r   r0   r   r   r   __delattr__  s    zConfigModule.__delattr__)entryr!   c              
   C   sh   |j }|d u rd S |dd\}}zt|}W n. ty^ } ztd|W Y d }~n
d }~0 0 ||fS )NrH   ri   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_val)r   r    r!   c                 C   s.   |  |}|d usJ |\}}t||| d S r"   )r   rX   )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 p4|j|jk}|jtu }t|jttt	frb|p`|j|jk}|ol|ol|S )z
        Returns true if the config is at its default value.
        configs overridden by the env are not considered default.
        )
rc   r|   r   r   r{   rz   r#   r%   r=   r   )r   r0   Z
config_valZnot_set_env_defaultZnot_set_env_forceZunsetr   r   r   _is_default  s    





zConfigModule._is_defaultF)ignored_keysignored_prefixesskip_defaultr!   c                    st   i }| j D ]d |r |v rq
|r8t fdd|D r8q
|rH|  rHq
| j   jdurZq
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"   )rQ   ).0rB   rZ   r   r   	<genexpr>      z)ConfigModule._get_dict.<locals>.<genexpr>N)rc   anyr   r   r   r   rM   )r   r   r   r   r^   r   r   r   	_get_dict  s    
zConfigModule._get_dict)config_namer!   c                 C   s   | j | jS r"   )rc   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_configT)ignore_private_configs)r   r!   c                C   s0   g }|r| d |t| dg  | j|dS )z!Convert config to portable format_Z_cache_config_ignore_prefix)r   )appendextendrM   r   )r   r   prefixesr   r   r   save_config_portable  s
    
z!ConfigModule.save_config_portablec                    s   t  tttdddtddfdd ttt f tt dfd	d
ttdddtd fdd}g }| j}| jt	| dg dd
 D ]\}}||||| qD ]}|dd|  qd|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builtinsr`   rH   )r'   )r   r   r   r   r   r   get_module_name  s    z4ConfigModule.codegen_config.<locals>.get_module_nameNr   r!   c                    s    | d}|r | d S )NF)rw   )r   r   )r   importsr   r   
add_import  s    
z/ConfigModule.codegen_config.<locals>.add_import)vr!   c                    s    fdd| D S )Nc                    s    g | ]} |d  |j  qS )T)r&   r   itemr   r   r   
<listcomp>  r   zTConfigModule.codegen_config.<locals>.list_of_callables_to_string.<locals>.<listcomp>r   r   r   r   r   list_of_callables_to_string  s    z@ConfigModule.codegen_config.<locals>.list_of_callables_to_stringc                 S   s   t | ot| dot| dS )Nr'   r&   )callablerR   r   r   r   r   importable_callable!  s    z8ConfigModule.codegen_config.<locals>.importable_callabler   c                    s   |r0 | |  d| d|d |j  S t|ttfrtfdd|D r|D ]} | qX|}t|tr|  d| d| S |  d| dd| dS n|  d| d|S 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   3  s   zGConfigModule.codegen_config.<locals>.get_config_line.<locals>.<genexpr>z = { z, z }N)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   rP   r   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 rR| jt| jd}tt| }tj	|
ddd | _d| _ | jS )z/Hashes the configs that are not compile_ignoredNr   rg   F)usedforsecurity)r<   r;   r   r%   rd   reprsortedrP   hashlibmd5rn   digest)r   Zdict_to_hashZstring_to_hashr   r   r   get_hashJ  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   |   S r"   get_config_copyr   r   r   r   to_dictU  s    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   s   |   S r"   r   r   r   r   r   shallow_copy_dict^  s    zConfigModule.shallow_copy_dict)maybe_pickled_configr!   c                 C   sj   t |tst|}n|}| D ]B\}}|| jv rBt| || 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   loadsrP   rc   rX   Ztorch._dynamo.utilsr   )r   r   r^   r   r   r   r   r   r   load_configg  s    

zConfigModule.load_configc                 C   s   |   S r"   )r   r   r   r   r   r   u  s    zConfigModule.get_config_copyContextDecorator)arg1arg2kwargsr!   c                    s   |durD|dur(t |tsJ ||i nt |ts6J | |rTJ n| |du sTJ t  tspJ 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d fddZddfddZfddZdS )	z'ConfigModule.patch.<locals>.ConfigPatchNr   c                    s
    | _ d S r"   changesr   r   r   r   r     s    z0ConfigModule.patch.<locals>.ConfigPatch.__init__c                    sJ   rJ | j  D ]} ||< q| j  D ]\}} || q0d S r"   )r   keysr   rP   r   )r   rZ   r   r   r^   priorr   r   	__enter__  s
    z1ConfigModule.patch.<locals>.ConfigPatch.__enter__c                    s*     D ]\}} || q  d S r"   )rP   r   clear)r   exc_typeexc_valexc_tbr   r   r   r   r   __exit__  s    z0ConfigModule.patch.<locals>.ConfigPatch.__exit__)r&   r'   r(   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   patchx  s    

zConfigModule.patch)r   r!   c                    s(   j tg df d 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()

        Nr   c                     sH   fddD    D ]\} }|j|  _qd d fdd}|S )Nc                    s   i | ]}| | j qS r   )rz   )r   r   r~   r   r   
<dictcomp>  r   zFConfigModule._make_closure_patcher.<locals>.change.<locals>.<dictcomp>r   c                     s"      D ]\} }|j|  _qd S r"   rP   rc   rz   )r   r   )r   r   r   r   revert  s    zBConfigModule._make_closure_patcher.<locals>.change.<locals>.revertr   )r   r   r   r   r^   r   )r   r   change  s
    z2ConfigModule._make_closure_patcher.<locals>.change)rc   r   )r   r   r   r   r   r   _make_closure_patcher  s    z"ConfigModule._make_closure_patcher)NNF)NN))r&   r'   r(   r   r$   rU   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   ra   T  sl   
$   


%	

A   
<ra   c                       sN   e Zd ZdZddddZedddZeegef ed fd	d
Z	  Z
S )r   z[
    Same as contextlib.ContextDecorator, but with support for
    `unittest.TestCase`
    Nr   c                 C   s   t dd S NZNYIr   r   r   r   r   r     s    zContextDecorator.__enter__c                 C   s   t dd S r   r   )r   r   r   r   r   r   r   r     s    zContextDecorator.__exit__r   c                    sR   t |trFt|tjrFG  fddd|}|j|_|j|_|j|_|S t 	|S )Nc                       s@   e Zd Zedd fddZedd fddZ  ZS )z,ContextDecorator.__call__.<locals>._TestCaseNr   c                    s>      zt   W n" ty8   d d d   Y n0 d S r"   )r   r   
setUpClass	Exceptionr   clsre   r   r   r   r     s    z7ContextDecorator.__call__.<locals>._TestCase.setUpClassc                    s2   zt    W d d d  nd d d  0 d S r"   )r   tearDownClassr   r   r  r   r   r    s    z:ContextDecorator.__call__.<locals>._TestCase.tearDownClass)r&   r'   r(   classmethodr   r  r   r   r   r   r   	_TestCase  s   r  )
r#   r,   rS   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     s   r   c                       sZ   e Zd ZdZeed fddZeeddddZeed	d
dZ	edd	ddZ
  ZS )rW   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 )Nrc   _prefix)r   r   )r   r^   rB   r   r   r   r     s    zSubConfigProxy.__init__Nr   c                 C   s   | j | j| |S r"   )rc   r   r  r   r   r   r   r   
  s    zSubConfigProxy.__setattr__r/   c                 C   s   | j | j| S r"   )rc   r   r  r   r   r   r   r     s    zSubConfigProxy.__getattr__c                 C   s   | j | j| S r"   )rc   r   r  r   r   r   r   r     s    zSubConfigProxy.__delattr__)r&   r'   r(   r)   r*   r$   r   r   r   r   r   r   r   r   r   r   rW     s
   rW   )objr0   r8   r!   c                 C   s&   t | tr| ||S tj| ||S )z@
    Workaround `mock.patch.object` issue with ConfigModule
    )r#   ra   r   r   r*   )r  r0   r8   r   r   r   patch_object  s    
r	  )r0   r   r!   c                 C   s(   t j| }|dkrdS |dkr$dS |S r1   r4   )r0   r   r8   r   r   r   get_tristate_env  s    r
  )N)7
contextlibr   r   r   rN   rl   r5   r   rK   rk   r  Z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   rT   r   r*   r   r   r.   r9   rf   rs   rb   rU   ra   r   rW   r	  r
  r   r   r   r   <module>   s   (
"W

	G&=   )	