o
    闦iU                  	   @   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G dd	 d	Zee e!e"de#e$e%e&e'f	Z(d
e#dee! fddZ)deddfddZ*dZ+dedee# fddZ,e- Z.eG dd dZ/G dd deZ0G dd de j1Z1G dd dZ2de-d
e#de-de-fddZ3d#d
e#d edee! fd!d"Z4dS )$    N)	dataclass)FunctionType
ModuleType)AnyCallableDictListNoReturnOptionalSetUnion)
deprecated)mock)justknobs_checkc                   @   s   e Zd ZU dZdZeed< dZee	 ed< dZ
ee	 ed< dZee	 ed< dZee ed< 					ddedee	 dee	 dee	 dee f
d	d
ZdS )Configaz  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:
        env_name_force: If set, this environment variable overrides everything
        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.
        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.
        env_name_force: The environment variable to read that is a FORCE
            environment variable. I.e. it overrides everything
        env_name_default: The environment variable to read that changes the
            default behaviour. I.e. user overrides take preference.
    TdefaultNjustknobenv_name_defaultenv_name_force
value_typec                 C   sN   || _ || _|| _|| _|| _| jd ur#t| j ts%J d| j  dd S d S )Nz!justknobs only support booleans, z is not a boolean)r   r   r   r   r   
isinstancebool)selfr   r   r   r   r    r   X/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/torch/utils/_config_module.py__init__<   s   	
zConfig.__init__)TNNNN)__name__
__module____qualname____doc__r   r   __annotations__r   r
   strr   r   r   typer   r   r   r   r   r      s.   
 r   namereturnc                 C   s(   t j| }|dkrdS |dkrdS d S N1T0Fosenvironget)r#   valuer   r   r   _read_env_variableT      r-   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>   	_is_dirty_hash_digestr    N)r   r   r   set_bypass_keysr   r   r   r   ConfigModuleInstanced   s    r4   sourcedestprefixr$   Nc           	   	      sx  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| | }t	|trf||d}tt||d |< |u ret| qt	|tr{t| |< |u rzt| 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_annotationslist__dict__items
startswithr   r   r   hasattrr   r"   
issubclassr   CONFIG_TYPESr+   _ConfigEntrydelattrr   SubConfigProxysetattrAssertionError)	r5   r6   r7   
type_hintskeyr,   r#   annotated_typeproxyconfigr/   visitr   r   rW   h   sN   







 z$install_config_module.<locals>.visit T)ConfigModuler   r   r"   rN   r!   -get_assignments_with_compile_ignored_comments_config_compile_ignored_keys	__class__r0   r1   )r/   r4   compile_ignored_keysr   rU   r   install_config_module]   s$   

-
r_   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)rX   rX   zunconsumed r   r>      )rC   	getsourcer2   tokenizeioBytesIOencodereadliner"   COMMENTstringstripCOMPILE_IGNORED_MARKERstartNAMEOPadd)r/   source_codeassignmentstokenscurrent_comment	prev_nametokenmaybe_currentr   r   r   rZ      s8   



rZ   c                   @   sl   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
efddZdS )rL   r   r   user_overrideNr   env_value_forceenv_value_defaultFhiderV   c                 C   s|   |j | _ |jd ur|jnt| j | _|j| _|jd ur't|j }d ur'|| _|jd ur:t|j }d ur<|| _d S d S d S N)	r   r   r"   r   r   r-   rz   r   ry   )r   rV   	env_valuer   r   r   r      s   


z_ConfigEntry.__init__)r   r   r   r   r    r"   _UNSET_SENTINELrx   r   r
   r!   ry   rz   r{   r   r   r   r   r   r   r   rL      s   
 rL   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	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fddZ			d;d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'd(Zed)ed&deeef fd*d+Zd,ee
eeef f ddfd-d.Zdeeef fd/d0Z 		d<d1e	eeeeef f  d2ed3eeef dd4fd5d6Z!d7eeef defd8d9Z"  Z#S )=rY   r[   r3   r\   r0   r1   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#   r,   c                    s^   || j v rt || d S || jvrt| j d| d|| j| _d| _d| j| _d S )Nr=    does not existTF)	r3   super__setattr__r[   AttributeErrorr   rx   r0   r{   r   r#   r,   r]   r   r   r     s   

zConfigModule.__setattr__c              
   C   s   zT| j | }|jrt| j d| d|jtur|jW S |jtur&|jW S |jtur/|jW S |jd ur=t	|j|j
dW S t|j
tttfrQt|j
|_|jW S |j
W S  tyl } zt| j d| d|d }~ww )Nr=   r   )r#   r   )r[   r{   r   r   ry   r~   rx   rz   r   r   r   r   rE   r2   dictcopydeepcopyKeyError)r   r#   rV   er   r   r   __getattr__  s(   




zConfigModule.__getattr__c                 C   s"   d| _ t| j| _d| j| _d S )NT)r0   r~   r[   rx   r{   r   r#   r   r   r   __delattr__2  s   zConfigModule.__delattr__c                 C   s   | j | jtu S r|   )r[   rx   r~   r   r   r   r   _is_default9  s   zConfigModule._is_defaultFignored_keysignored_prefixesskip_defaultc              	      s   i }| j D ]> |r# |v r#|r"|  s"td  dt|    q|r1t fdd|D r1q|r9|  r9q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.

        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. The other is it modified the logging behaviour
                to match what codegen already did for modified skipped keys
        zSkipping serialization of z value c                 3   s    | ]}  |V  qd S r|   )rH   ).0r7   rR   r   r   	<genexpr>[  s    z)ConfigModule._get_dict.<locals>.<genexpr>)r[   r   warningswarnrB   anyr   r   )r   r   r   r   rV   r   r   r   	_get_dict<  s   
zConfigModule._get_dictconfig_namec                 C   s   | j | jS r|   )r[   r   )r   r   r   r   r   get_typeb  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   r8   )protocol)rB   pickledumpsr   )r   r   r   r   r   save_confige  s
   
zConfigModule.save_configc                 C   s$   dg}| t| dg  | j|dS )z!Convert config to portable format__cache_config_ignore_prefix)r   )extendrB   r   )r   prefixesr   r   r   save_config_portablem  s   z!ConfigModule.save_config_portablec                 C   sR   g }| j }| jt| dg dd 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.
        r   T)r   r   r=   z = 
)r   r   rB   rG   appendjoin)r   linesmodkvr   r   r   codegen_configs  s   

zConfigModule.codegen_configc                 C   sT   | j s| jdu r'| jt| jd}tt| }t	|
d | _d| _ | jS )z/Hashes the configs that are not compile_ignoredNr   r`   F)r0   r1   r   rE   r\   reprsortedrG   hashlibmd5rg   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 r|   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   r|   r   r   r   r   r   shallow_copy_dict  r   zConfigModule.shallow_copy_dictmaybe_pickled_configc                 C   s`   t |tst|}n|}| D ]\}}|| jv r!t| || qtd| d| d qdS )zARestore from a prior call to save_config() or shallow_copy_dict()zkey z with value z! is not understood by this configN)	r   r   r   loadsrG   r[   rO   r   r   )r   r   rV   r   r   r   r   r   load_config  s   

zConfigModule.load_configc                 C   r   r|   )r   r   r   r   r   r        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   rG   r   )r   rR   r   r   changesrV   priorr   r   	__enter__  s   z1ConfigModule.patch.<locals>.ConfigPatch.__enter__c                    s*     D ]
\}} || q  d S r|   )rG   r   clear)r   exc_typeexc_valexc_tbr   r   )rV   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   patch  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   )rx   )r   r   )rV   r   r   
<dictcomp>  s    zFConfigModule._make_closure_patcher.<locals>.change.<locals>.<dictcomp>r$   c                     s"      D ]
\} }|j|  _qd S r|   rG   r[   rx   )r   r   )r   r   r   r   revert  s   zBConfigModule._make_closure_patcher.<locals>.change.<locals>.revertr   r   )r   r   r   r   rV   r   )r   r   change  s
   z2ConfigModule._make_closure_patcher.<locals>.change)r[   r   )r   r   r   r   r   r   _make_closure_patcher  s   z"ConfigModule._make_closure_patcherr   )NNF)NN)$r   r   r   r   r!   rL   r    r   r   r
   bytesr   objectr   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   rY      sh   
 

 



&	"

"9rY   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__funcc                    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r]   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"   rJ   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                       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 )rN   zn
    Shim to redirect to main config.
    `config.triton.cudagraphs` maps to _config["triton.cudagraphs"]
    rV   r7   c                    s    t  d| t  d| d S )Nr[   _prefix)r   r   )r   rV   r7   r   r   r   r   5  s   zSubConfigProxy.__init__r#   r,   r$   Nc                 C   s   | j | j| |S r|   )r[   r   r   r   r   r   r   r   :  s   zSubConfigProxy.__setattr__c                 C      | j | j| S r|   )r[   r   r   r   r   r   r   r   =     zSubConfigProxy.__getattr__c                 C   r   r|   )r[   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   rN   /  s    rN   objr,   c                 C   s&   t | tr| ||S tj| ||S )z@
    Workaround `mock.patch.object` issue with ConfigModule
    )r   rY   r   r   r   )r   r#   r,   r   r   r   patch_objectD  s   
r   r   c                 C   s(   t j| }|dkrdS |dkrdS |S r%   r(   )r#   r   r,   r   r   r   get_tristate_envM  r.   r   r|   )5
contextlibr   r   rC   re   r)   r   r@   rd   r   r   dataclassesr   typesr   r   r<   r   r   r   r   r	   r
   r   r   typing_extensionsr   r   torch._utils_internalr   r   intfloatr   r"   r!   rE   r2   tupler   rK   r-   r_   rl   rZ   r   r~   rL   rY   r   rN   r   r   r   r   r   r   <module>   sD    (;	D&(  ) 	