o
    ki'z                     @   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
m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 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B eB e!B e"B e#B e$B e%B dB d
Z'e( Z)eddG dd dee' Z*ere)dddddfde'e(B de!dB de!e"e! B dB de!e"e! B dB de dB de!dB de'fddZ+n0e)dddddfde'e(B de!dB de!e"e! B dB de!e"e! B dB de dB de!dB de*e' fddZ+de!dee!B dB fddZ,deddfddZ-dZ.dede#e! fd d!Z/eG d"d# d#Z0G d$d% d%eZ1G d&d' d'e j2Z2G d(d) d)Z3d*e(de!d+e(de(fd,d-Z4d2de!dededB fd.d/Z5d0d1 Z6dS )3    N)Callable)	dataclass)FunctionType
ModuleType)AnyGenericNoReturnOptionalTYPE_CHECKINGTypeVar)
deprecated)mock)justknobs_checkT)boundT)kw_onlyc                   @   s   e Zd ZU dZeeB ed< dZedB ed< dZ	e
e dB ed< dZe
e dB ed< dZedB ed< dZedB ed< dd
dZedee
e B dB d	e
e dB 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 precedence 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 precedence order is from
            left to right.
        justknob: If this pytorch installation supports justknobs, that will
            override defaults, but will not override the user_override precedence.
        default: This value is the lowest precedence, 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
value_typealiasreturnc                 C   s^   t | j| _t | j| _| jd ur+| jtus'| jd us'| jd us'| jd ur-tdd S d S )Nztif alias is set, none of {default, justknob,                         env_name_default and env_name_force} can be set)	r    string_or_list_of_string_to_listr   r   r   r   _UNSET_SENTINELr   AssertionErrorself r   d/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/utils/_config_module.py__post_init__O   s    




z_Config.__post_init__valc                 C   s<   | d u rd S t | tr| gS t | tstdt|  | S )Nzval is not a list, got )
isinstancestrlistr   type)r"   r   r   r    r   c   s   

z(_Config.string_or_list_of_string_to_listr   N)__name__
__module____qualname____doc__r   object__annotations__r   r$   r   r%   r   r   r&   r   r!   staticmethodr   r   r   r   r    r       s   
 &

r   r   r   r   r   r   r   r   c                 C   s   d S Nr   r   r   r   r   r   r   r   r   r    Configv   s   r1   c                 C   s   t | |||||dS )Nr0   )r   r0   r   r   r    r1      s   namec                 C   s(   t j| }|dkrdS |dkrdS |S N1T0Fosenvironget)r2   valuer   r   r    _read_env_variable      r;   modulec                    st   G dd dt }dttB dttB 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>   	_is_dirty_hash_digestr-   N)r(   r)   r*   set_bypass_keysr   r   r   r    ConfigModuleInstance   s    rB   sourcedestprefixr   Nc           	   	      s  t | }t| j D ]\}}|ds6t|ttfs6t	|dr,|j
dks6|j
ds6t|tr7t|tr7q| | }||d}t|tr\tt||d |< |u r[t| qt|tr}|durm|jdu rm||_t| |< |u r|t| qt|tr|j
jkrtd| dj 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._config__r)   typingzcollections.abcN)r   r   zsubconfig class z must be defined in module .zUnhandled config =z ())inspectget_annotationsr%   __dict__items
startswithr#   r   r   hasattrr)   r&   
issubclassr   r9   CONFIG_TYPES_ConfigEntrydelattrr   r(   r   SubConfigProxysetattr)	rC   rD   rE   
type_hintskeyr:   r2   annotated_typeproxyconfigr=   visitr   r    r]      sX   








 z$install_config_module.<locals>.visit T)ConfigModuler   r&   rU   r$   -get_assignments_with_compile_ignored_comments_config_compile_ignored_keys	__class__r>   r?   )r=   rB   compile_ignored_keysr   r[   r    install_config_module   s$   6
re   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r8t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r}tdt |S )Nutf-8)r^   r^   zunconsumed r   rI      )rK   	getsourcer@   tokenizeioBytesIOencodereadliner&   COMMENTstringstripCOMPILE_IGNORED_MARKERr   startNAMEOPadd)r=   source_codeassignmentstokenscurrent_comment	prev_nametokenmaybe_currentr   r   r    r`      s8   


r`   c                   @   s   e Zd ZU eed< eed< eZeed< dZe	dB ed< eZ
eed< eZeed< dZeed	< dZe	dB ed
< deddfddZdS )rS   r   r   user_overrideNr   env_value_forceenv_value_defaultFhider   r\   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sctd| j  d| jd ur|jd usr|jd ur| jtttt tt fvrt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   r;   r   r   r   r#   boolr   r$   r	   )r   r\   r"   	env_valuer   r   r    __init__.  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    rS     s   
 rS   c                       sd  e Zd ZU eeef ed< ee ed< ee ed< eed< e	dB ed< dGd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f dB 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			dHdee dB dee dB 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'd(d)edeeef fd*d+Zdefd,d-Zde	fd.d/Zed0ed1deeef fd2d3Z ed4ed1deeef fd5d6Z!d7e	eeef B ddfd8d9Z"deeef fd:d;Z#deeef fd<d=Z$		dId>eeeef B dB d?ed@eeef ddAfdBdCZ%dDeeef defdEdFZ&  Z'S )Jr_   ra   rA   rb   r>   Nr?   r   c                 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__r2   r:   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)rA   super__setattr__ra   AttributeErrorr(   r   _set_alias_valr~   r>   r   r   r2   r:   rc   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   )r2   r   )ra   r   r   r(   _get_alias_valr   r   r~   r   r   r   r   r#   r%   r@   dictcopydeepcopyKeyError)r   r2   r\   	alias_valer   r   r    __getattr__q  s.   





zConfigModule.__getattr__c                 C   s"   d| _ t| j| _d| j| _d S )NT)r>   r   ra   r~   r   r   r2   r   r   r    __delattr__  s   zConfigModule.__delattr__entryc              
   C   sb   |j }|d u r	d S |dd\}}z
t|}W ||fS  ty0 } z	td| d|d }~ww )NrH   rh   zconfig alias r   )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   getattr)r   r   datar=   r   constant_valuer   r   r    r     s   

zConfigModule._get_alias_valr"   c                 C   s2   |  |}|d u rtd|\}}t||| d S )Nz6alias data should not be None when setting alias value)r   r   rV   )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 overridden by the env are not considered default.
        )
ra   r   r   r   r   r~   r#   r%   r@   r   )r   r2   
config_valnot_set_env_default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/   )rO   ).0rE   rX   r   r    	<genexpr>  s    z)ConfigModule._get_dict.<locals>.<genexpr>N)ra   anyr   r   r   r   r   )r   r   r   r   r\   r   r   r    	_get_dict  s   
zConfigModule._get_dictconfig_namec                 C   s   | j | jS r/   )ra   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      )protocol)r   pickledumpsr   )r   r   r   r   r    save_config  s
   
zConfigModule.save_configT)ignore_private_configsr   c                C   s0   g }|r	| d |t| dg  | j|dS )z!Convert config to portable format__cache_config_ignore_prefix)r   )appendextendr   r   )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 B 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 ]\}}|
|||| qPD ]}|dd|  q`d|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_nameNc                    s     | d}|r | d S d S )NF)rv   )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(   )callablerP   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   6  s    
zGConfigModule.codegen_config.<locals>.get_config_line.<locals>.<genexpr>z = { z, z })r(   r#   r%   r@   alljoin)modkr   r   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   rN   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 r)| jt| jd}tt| }tj	|
ddd | _d| _ | jS )z/Hashes the configs that are not compile_ignoredNr   rf   F)usedforsecurity)r>   r?   r   r%   rb   reprsortedrN   hashlibmd5rm   digest)r   dict_to_hashstring_to_hashr   r   r    get_hashM  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_dictX     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_dicta  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   loadsrN   ra   rV   torch._dynamo.utilsr   )r   r   r\   r   r   r   r   r   r    load_configj  s   

zConfigModule.load_configc                 C   r   r/   )r   r   r   r   r    r   x     zConfigModule.get_config_copyc                 C   s   | j t| dg dS )Nr   r   )r   r   r   r   r   r    get_serializable_config_copy{     z)ConfigModule.get_serializable_config_copyarg1arg2kwargsContextDecoratorc                    s   |dur(|durt |tstd||i nt |tstd| |r'tdn
| |dur2tdt  ts@t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):
                ...
        NzGfirst argument must be a string when passing 2 positional args to patchzKfirst argument must be a dict when passing a single positional arg to patchz:cannot pass both positional and keyword arguments to patchzLsecond positional argument is only valid when first argument is a key stringzexpected `dict` got c                       s8   e Zd Zd	 fddZd	fddZfddZdS )
z'ConfigModule.patch.<locals>.ConfigPatchr   Nc                    s
    | _ d S r/   changesr   r   r   r    r     s   
z0ConfigModule.patch.<locals>.ConfigPatch.__init__c                    sJ   rt d| jD ]	} ||< q	| j D ]
\}} || qd S )Nz/prior should be empty when entering ConfigPatch)r   r   r   rN   r   )r   rX   r   r   r\   priorr   r    	__enter__  s   
z1ConfigModule.patch.<locals>.ConfigPatch.__enter__c                    s*     D ]
\}} || q  d S r/   )rN   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   r    ConfigPatch  s    r  )r#   r$   r   r   r&   r   )r   r   r   r   r  r   r   r    patch~  s8   



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/   rN   ra   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)ra   r   )r   r   r  r   r  r    _make_closure_patcher  s   z"ConfigModule._make_closure_patcherr'   )NNF)NN)(r(   r)   r*   r   r$   rS   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    r_   T  s   
 
$
	



%	


A

"Lr_   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N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rc   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&   rQ   unittest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                       sh   e Zd ZdZdededd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 )rU   zn
    Shim to redirect to main config.
    `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
    r\   rE   r   Nc                    s    t  d| t  d| d S )Nra   _prefix)r   r   )r   r\   rE   r   r   r    r     s   zSubConfigProxy.__init__r2   r:   c                 C   s   | j | j| |S r/   )ra   r   r  r   r   r   r    r      r   zSubConfigProxy.__setattr__c                 C      | j | j| S r/   )ra   r   r  r   r   r   r    r   #  r   zSubConfigProxy.__getattr__c                 C   r  r/   )ra   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    rU     s    rU   objr:   c                 C   s&   t | tr| ||S tj| ||S )z@
    Workaround `mock.patch.object` issue with ConfigModule
    )r#   r_   r  r   r,   )r  r2   r:   r   r   r    patch_object*  s   
r  c                 C   s(   t j| }|dkrdS |dkrdS |S r3   r6   )r2   r   r:   r   r   r    get_tristate_env3  r<   r   c                    s    fdd}|S )Nc                    s8    j  D ]\}}|ds|| j vrt| || q| S )Nr   )rM   rN   rO   rV   )	child_clsr   r   
parent_clsr   r    wrapper=  s
   z$inherit_fields_from.<locals>.wrapperr   )r#  r$  r   r"  r    inherit_fields_from<  s   r%  r/   )7
contextlibr   r   r   rK   rk   r7   r   rj   r  collections.abcr   dataclassesr   typesr   r   rG   r   r   r   r	   r
   r   typing_extensionsr   r   torch._utils_internalr   intfloatr   r&   r$   r%   r@   r
  r   rR   r   r,   r   r   r1   r;   re   rr   r`   rS   r_   r   rU   r  r   r%  r   r   r   r    <module>   s     ,S
	M%A   )		