o
    m9:j                     @   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 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 eee e!de"e#e$e%e&f	Z'eee e!d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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 de"dB de)fddZ-n8e+dd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 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"Z0dede$e" fd#d$Z1eG d%d& d&Z2G d'd( d(eZ3G d)d* d*e j4Z4G d+d, d,Z5d1de"dede dB fd-d.Z6d/d0 Z7dS )2    N)Callable)
ContextVar)	dataclass)FunctionType
ModuleType)AnyGenericNoReturnOptionalTYPE_CHECKINGTypeVar)
deprecated)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	Ze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.  User overrides are thread-local.
        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aliasFr   deprecation_message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    a/home/nk/hobo-godmode/plappi-mvp/.venv/lib/python3.10/site-packages/torch/utils/_config_module.py__post_init__V   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   j   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   boolr   r"   staticmethodr   r    r    r    r!   r   $   s"   
 &

r   Fr   r   r   r   r   r   r   r   r   c                 C   s   d S Nr    r   r   r   r   r   r   r   r   r    r    r!   Config}   s   
r3   c              
   C   s   t | |||||||dS )Nr2   )r   r2   r    r    r!   r3      s   namec                 C   s(   t j| }|dkrdS |dkrdS |S N1T0Fosenvironget)r4   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    rD   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rn|jdu rn||_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   r;   CONFIG_TYPES_ConfigEntrydelattrr   r)   r   SubConfigProxysetattr)	rE   rF   rG   
type_hintskeyr<   r4   annotated_typeproxyconfigr?   visitr    r!   r_      sX   







 z$install_config_module.<locals>.visit T)ConfigModuler   r'   rW   r%   -get_assignments_with_compile_ignored_comments_config_compile_ignored_keys	__class__r@   rA   )r?   rD   compile_ignored_keysr    r]   r!   install_config_module   s$   6
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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   rK      )rM   	getsourcerB   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!   rb      s8   


rb   c                   @   s   e Zd ZU eed< eed< e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Zeed< dZe	dB ed< dZeed< dede	ddfddZdS )rU   r   r   user_overrideNr   env_value_forceenv_value_defaultFhider   r   r   _deprecation_warnedr^   r4   r   c                 C   s@  |j | _ |jd ur|jnt| j | _|j| _|j| _|j| _|j| _d| _t|t	d| _
|jd urD|jD ]}t| }d urC|| _ nq4|jd ur\|jD ]}t| }d ur[|| _ nqL| jd uru| j d urut| j tsutd| j  d| jd ur|jd us|jd ur| jtttt tt fvrtd| j dd S d S d S )NFr   z!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   r   r=   r   r   r   r$   r/   r   r%   r
   )r   r^   r4   r#   	env_valuer    r    r!   __init__B  sP   




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    r    r    r!   rU   "  s   
 rU   c                       sz  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< dJdd	Z
d
ededdfd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			dKd 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/d0Zde	fd1d2Zed3e d4deeef fd5d6Z!ed7e d4deeef fd8d9Z"d:e	eeef B ddfd;d<Z#deeef fd=d>Z$deeef fd?d@Z%		dLdAeeeef B dB dBedCeeef ddDfdEdFZ&dGeeef defdHdIZ'  Z(S )Mra   rc   rC   rd   r@   NrA   r   c                 C   s   t dt d)Nzuse z-.install_config_module(sys.modules[__name__]))NotImplementedErrorr)   r   r    r    r!   r   z  s   
zConfigModule.__init__r4   r^   c                 C   sf   |j r/|js1ddl}| j d| d}|jr|d|j 7 }|d7 }|j|tdd d	|_dS dS dS )
z;Issue deprecation warning for config if not already warned.r   NrJ   z is deprecatedz and z4. It will be removed in a future version of PyTorch.   )
stacklevelT)r   r   warningsr)   r   warnFutureWarning)r   r4   r^   r   msgr    r    r!   _warn_if_deprecated  s   
z ConfigModule._warn_if_deprecatedr<   c                    s   || j v rt || d S || jvrt| j d| d| j| }| || |jd ur6| || d S |j	
| d| _d|_d S )NrJ    does not existTF)rC   super__setattr__rc   AttributeErrorr)   r   r   _set_alias_valr   rB   r@   r   )r   r4   r<   r^   re   r    r!   r     s   




zConfigModule.__setattr__c              
   C   s  zk| j | }|jrt| j d| d| || | |}|tur&|W S |jtur/|jW S |j	 }|tur;|W S |j
turD|j
W S |jd urRt|j|jdW S t|jtsh|jt|j |j	 W S |jW S  ty } zt| j d| d|d }~ww )NrJ   r   r4   r   )rc   r   r   r)   r   _get_alias_valr   r   r   r;   r   r   r   r   r$   _IMMUTABLE_CONFIG_TYPESrB   copydeepcopyKeyError)r   r4   r^   	alias_valr   er    r    r!   __getattr__  s2   





zConfigModule.__getattr__c                 C   s(   d| _ | j| jt d| j| _d S )NT)r@   rc   r   rB   r   r   r   r4   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 )NrJ   rj   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 r1   )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   rX   )r   r   r#   r   r?   r   r    r    r!   r     s   
zConfigModule._set_alias_valc                 C   sp   | j | }|jtu p|j|jk}|jtu p|j|jk}|j tu }t|jts2|p1|j |jk}|o7|o7|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   r   r;   r$   r   )r   r4   
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                    s   i }| j  D ]d\ }|jdurq|r |v rq|r&t fdd|D r&q|r.|  r.q|j }|jtur<|j}n!|turC|}n|j	turL|j	}n|j
durZt|j
|jd}n|j}t|tsgt|}|| < 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.
        Nc                 3   s    | ]}  |V  qd S r1   )rQ   ).0rG   rZ   r    r!   	<genexpr>  s    z)ConfigModule._get_dict.<locals>.<genexpr>r   )rc   rP   r   anyr   r   r;   r   r   r   r   r   r   r$   r   r   r   )r   r   r   r   r^   r   r   r#   r    r   r!   	_get_dict   s2   







zConfigModule._get_dictconfig_namec                 C   s   | j | jS r1   )rc   r   )r   r   r    r    r!   get_type5  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_config8  s
   
zConfigModule.save_configT)ignore_private_configsr   c                C   s   g }|r	| d |t| dg  | j|d}t| dg D ]*}||v rH|| durH||  }t|dr;| ||< qtd| d||  d	q|S )
z!Convert config to portable format__cache_config_ignore_prefix)r   _cache_config_factory_keysNuuidzConfig 'z' is set to zO which does not implement uuid(). Implement uuid() for cache key participation.)appendextendr   r   rR   r   RuntimeError)r   r   prefixesr^   rZ   instancer    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`   rJ   )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_importf  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>l  s     zTConfigModule.codegen_config.<locals>.list_of_callables_to_string.<locals>.<listcomp>r    r   r   r    r!   list_of_callables_to_stringk     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_callablen  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 }
            rJ   z = Tc                 3   s    | ]} |V  qd S r1   r    r   )r   r    r!   r     s    
zGConfigModule.codegen_config.<locals>.get_config_line.<locals>.<genexpr>z = { z, z })r)   r$   r&   rB   alljoin)modkr   r   v_list)r   r   r   r   r    r!   get_config_liner  s    

z4ConfigModule.codegen_config.<locals>.get_config_liner   T)r   r   r   zimport 
)rB   r   r/   r%   r&   r   r)   r   r   rP   r   insertr   )r   r   linesr   r   r   import_namer    )r   r   r   r   r   r!   codegen_configV  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@   rA   r   r&   rd   reprsortedrP   hashlibmd5ro   digest)r   dict_to_hashstring_to_hashr    r    r!   get_hash  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 r1   get_config_copyr   r    r    r!   to_dict     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   r1   r   r   r    r    r!   shallow_copy_dict  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$   dictr   loadsrP   rc   rX   torch._dynamo.utilsr   )r   r   r^   r   r   r   r    r    r!   load_config  s   

zConfigModule.load_configc                 C   r   r1   )r   r   r    r    r!   r        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  | G  fdddt}| S )	a  
        Decorator and/or context manager to make temporary changes to a config.  Note that patched settings are thread-local.

        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                       s6   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*    | _ tj dt|  ddd| _d S )Nz.ConfigPatch[]r    r   )changesr   r)   id_priorr   r  r^   r    r!   r     s
   z0ConfigModule.patch.<locals>.ConfigPatch.__init__c                    s   i }| j D ]	} |||< q| j }| jg ||R  z| j  D ]
\}} || q%W d S  ty@   | j|  w r1   )r  r   r  r;   rB   rP   r   	Exception)r   priorrZ   prior_stackr   r   r^   r    r!   	__enter__  s   

z1ConfigModule.patch.<locals>.ConfigPatch.__enter__c                    sT   | j  }|std|d }| j |d d  | D ]
\}} || qd S )Nz2prior should not be empty when exiting ConfigPatchri   )r  r;   r   rB   rP   r   )r   exc_typeexc_valexc_tbr  r  r   r   r  r    r!   __exit__  s   
z0ConfigModule.patch.<locals>.ConfigPatch.__exit__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  s6   



!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                     sJ   fddD    D ]\} }j|  j| qd fdd}|S )Nc                    s   i | ]
}| | j  qS r    )r   r;   )r   r   r  r    r!   
<dictcomp>5  s    zFConfigModule._make_closure_patcher.<locals>.change.<locals>.<dictcomp>r   c                     s(      D ]\} }j|  j| qd S r1   rP   rc   r   rB   )r   r   )r  r   r    r!   revert9  s   zBConfigModule._make_closure_patcher.<locals>.change.<locals>.revertr(   r  )r   r   r  r  r^   r   )r  r!   change4  s
   z2ConfigModule._make_closure_patcher.<locals>.change)rc   r   )r   r  r  r    r  r!   _make_closure_patcher   s   z"ConfigModule._make_closure_patcherr(   )NNF)NN))r)   r*   r+   r   r%   rU   r.   rB   r/   bytesr   r   r-   r   r   r   r   tupler   r   r   r   r   r&   r   r'   r   r   r   r   r   r   r   r   r   r   r   r   r  r  __classcell__r    r    r   r!   ra   n  s   
 
'
	



5	

A

"Xra   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  H  r   zContextDecorator.__enter__c                 C   r  r  r!  )r   r  r  r  r    r    r!   r  K  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 r1   )r  r   
setUpClassr
  r  clsre   r   r    r!   r"  R  s   z7ContextDecorator.__call__.<locals>._TestCase.setUpClassc                    s0   zt    W d d d  d S d d d  w r1   )r   tearDownClassr  r#  r%  r    r!   r&  [  s   "z:ContextDecorator.__call__.<locals>._TestCase.tearDownClassr(   )r)   r*   r+   classmethodr"  r&  r  r    r   r   r!   	_TestCaseQ  s
    r(  )
r$   r'   rS   unittestTestCaser)   r+   r*   r   __call__)r   r   r(  r   r   r!   r+  N  s   zContextDecorator.__call__r(   )r)   r*   r+   r,   r  r	   r  r   r   r+  r  r    r    r   r!   r  B  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 )rW   zn
    Shim to redirect to main config.
    `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
    r^   rG   r   Nc                    s    t  d| t  d| d S )Nrc   _prefix)r   r   )r   r^   rG   r   r    r!   r   q  s   zSubConfigProxy.__init__r4   r<   c                 C   s   | j | j| |S r1   )rc   r   r,  )r   r4   r<   r    r    r!   r   v  r   zSubConfigProxy.__setattr__c                 C      | j | j| S r1   )rc   r   r,  r   r    r    r!   r   y  r   zSubConfigProxy.__getattr__c                 C   r-  r1   )rc   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!   rW   k  s    rW   c                 C   s(   t j| }|dkrdS |dkrdS |S r5   r8   )r4   r   r<   r    r    r!   get_tristate_env  r>   r.  c                    s    fdd}|S )Nc                    s8    j  D ]\}}|ds|| j vrt| || q| S )Nr   )rO   rP   rQ   rX   )	child_clsr   r   
parent_clsr    r!   wrapper  s
   z$inherit_fields_from.<locals>.wrapperr    )r1  r2  r    r0  r!   inherit_fields_from  s   r3  r1   )8
contextlibr   r   r   rM   rm   r9   r   rl   r)  collections.abcr   contextvarsr   dataclassesr   typesr   r   rI   r   r   r	   r
   r   r   typing_extensionsr   torch._utils_internalr   intfloatr/   r'   r%   r&   rB   r  r   rT   r   r   r-   r   r   r3   r=   rg   rt   rb   rU   ra   r  rW   r.  r3  r    r    r    r!   <module>   s     ,V	
	

	M%K   W)	