a
    dT8                  	   @   sz  d Z ddlZddlZddlZddl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mZ ddlmZ ddlmZ ddlZddlmZ eeeef dd	d
ZeedddZeeeeef dddZe edddZ!eddddZ"eed ed f eeee ee f dddZ#ej$e
ee	f dddZ%ej$eee	 e
ee	f f dddZ&d:ej$ee
ee	f  eeed!f ee
ee	f  d"d#d$Z'd;e
ee	f ee
ee	f  e
ee	f d%d&d'Z(ddd(e	e	eeee ef  eej$ dd)d*d+Z)G d,d- d-e
Z*deee	 d.d/d0Z+deee	 d.d1d2Z,deed.d3d4Z-deee	 d.d5d6Z.dee	dd7d8d9Z/dS )<z%Utilities used for parameter parsing.    N)fieldsis_dataclass)	AnyDictListMutableMappingOptionalSequenceTupleTypeUnion)nn)Literal)rank_zero_warn)valreturnc                 C   s$   |   }|dv rdS |dv r dS | S )a  Possibly convert a string representation of truth to bool. Returns the input otherwise. Based on the python
    implementation distutils.utils.strtobool.

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'.
    )yyesttrueon1T)nnoffalseoff0F)lower)r   r    r   l/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/utilities/parsing.pystr_to_bool_or_str   s    r!   c                 C   s(   t | }t|tr|S td| dS )an  Convert a string representation of truth to bool.

    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.

    Raises:
        ValueError:
            If ``val`` isn't in one of the aforementioned true or false values.

    >>> str_to_bool('YES')
    True
    >>> str_to_bool('FALSE')
    False
    zinvalid truth value N)r!   
isinstancebool
ValueErrorr   Zval_convertedr   r   r    str_to_bool,   s    
r&   c                 C   s<   t | }t|tr|S z
t|W S  ty6   | Y S 0 dS )a  Convert a string representation to truth of bool if possible, or otherwise try to convert it to an int.

    >>> str_to_bool_or_int("FALSE")
    False
    >>> str_to_bool_or_int("1")
    True
    >>> str_to_bool_or_int("2")
    2
    >>> str_to_bool_or_int("abc")
    'abc'
    N)r!   r"   r#   intr$   r%   r   r   r    str_to_bool_or_intA   s    

r(   )objr   c              
   C   s2   zt |  W dS  t jttfy,   Y dS 0 dS )z"Tests if an object can be pickled.TFN)pickledumpsPickleErrorAttributeErrorRuntimeErrorr)   r   r   r    is_picklableV   s
    
r0   )hparamsr   c                 C   s6   dd |   D }|D ]}td| d | |= qdS )z-Removes all unpicklable entries from hparams.c                 S   s   g | ]\}}t |s|qS r   )r0   .0kvr   r   r    
<listcomp>b       z#clean_namespace.<locals>.<listcomp>zattribute 'z3' removed from hparams because it cannot be pickledN)itemsr   )r1   Z	del_attrsr4   r   r   r    clean_namespace`   s    r9   zpl.LightningModulezpl.LightningDataModule)clsr   c                 C   sv   t | jj}t| }|d j}tt j t	t j
jt j
jf tt ddd}||t jj}||t jj}|||fS )a+  Parse key words for standard ``self``, ``*args`` and ``**kwargs``.

    Examples:

        >>> class Model():
        ...     def __init__(self, hparams, *my_args, anykw=42, **my_kwargs):
        ...         pass
        >>> parse_class_init_keys(Model)
        ('self', 'my_args', 'my_kwargs')
    r   )params
param_typer   c                 S   s"   | D ]}|j |kr|j  S qd S N)kindname)r;   r<   pr   r   r    _get_first_if_any}   s    
z0parse_class_init_keys.<locals>._get_first_if_any)inspect	signature__init__
parameterslistvaluesr?   r   	Parameterr   _ParameterKindVAR_POSITIONALVAR_KEYWORDr   str)r:   init_parametersZinit_paramsZn_selfrA   Zn_argsZn_kwargsr   r   r    parse_class_init_keysi   s    
	rN   )framer   c                 C   s   t | \}}|S )z$For backwards compatibility: #16369.)_get_init_args)rO   _
local_argsr   r   r    get_init_args   s    rS   c           
         s   t | \}}}dvr"d i fS d }t |jj}t|\}}}dd |||fD }g |dddR  fdd| D }|r|||i   fdd|	 D }|d }	|	|fS )	N	__class__c                 S   s   g | ]}|r|qS r   r   r3   r   r   r   r    r6      r7   z"_get_init_args.<locals>.<listcomp>rO   Z
frame_argsc                    s   i | ]}| | qS r   r   r3   r4   )
local_varsr   r    
<dictcomp>   r7   z"_get_init_args.<locals>.<dictcomp>c                    s   i | ]\}}| vr||qS r   r   r2   )exclude_argnamesr   r    rX      r7   )
rB   getargvaluesrC   rD   rE   rN   keysupdategetr8   )
rO   rQ   r:   rM   Zself_varZargs_varZ
kwargs_varZfiltered_varsrR   Zself_argr   )rY   rW   r    rP      s    rP   Fr   .)rO   	path_argsinsideclassesr   c                 C   s|   t | \}}}}t| jtjs$|S t| \}}d|v rb|rFt||rb|| t| j|d|dS |sxt| j|d|dS |S )a{  Recursively collects the arguments passed to the child constructors in the inheritance tree.

    Args:
        frame: the current stack frame
        path_args: a list of dictionaries containing the constructor args in all parent classes
        inside: track if we are inside inheritance path, avoid terminating too soon
        classes: the classes in which to inspect the frames

    Return:
          A list of dictionaries where each dictionary contains the arguments passed to the
          constructor at that level. The last entry corresponds to the constructor call of the
          most specific class in the hierarchy.
    rT   T)r_   r`   F)	rB   rZ   r"   f_backtypes	FrameTyperP   appendcollect_init_args)rO   r^   r_   r`   rQ   rW   Z
local_selfrR   r   r   r    re      s    
re   )sourceresultr   c                 C   s@   |d u ri }|   D ]&\}}t|tr2t||}q|||< q|S r=   )r8   r"   dictflatten_dict)rf   rg   r4   r5   rQ   r   r   r    ri      s    

ri   )ignorerO   )r)   argsrj   rO   r   c                   s  t |dkr"t|ts"|d s"dS |s8t }|r8|j}t|tjsLtdt	rlfddt
D n0i ddlm} t|g |fdD ]}| qdu rg n.ttrgntttfrd	d
 D ttfdd D |s  rdnd_npdd
 t|D }t |dkrn||d    fdd
 D }|rf|d nd_nfdd|D  d_  j D ].\}	}
t|
tjrtd|	d|	d qtj_dS )zCSee :meth:`~pytorch_lightning.LightningModule.save_hyperparameters`   r   Nz3There is no `frame` available while being required.c                    s   i | ]}|j t |j qS r   )r?   getattr)r3   r   r/   r   r    rX      r7   z(save_hyperparameters.<locals>.<dictcomp>)HyperparametersMixin)r`   c                 S   s   g | ]}t |tr|qS r   r"   rL   r3   argr   r   r    r6      r7   z(save_hyperparameters.<locals>.<listcomp>c                    s   i | ]\}}| vr||qS r   r   r2   )rj   r   r    rX      r7   kwargsc                 S   s   g | ]\}}t |ts|qS r   ro   )r3   irq   r   r   r    r6      r7   c                    s   g | ]\}}| kr|qS r   r   r2   )hpr   r    r6     r7   c                    s    i | ]}t |tr| | qS r   ro   rp   )	init_argsr   r    rX     r7   z
Attribute z is an instance of `nn.Module` and is already saved during checkpointing. It is recommended to ignore them using `self.save_hyperparameters(ignore=[z])`.)lenr"   rL   rB   currentframera   rb   rc   r-   r   r   Zpytorch_lightning.core.mixinsrn   re   r\   rF   tuplesetr8   Z_hparams_name	enumerateZ_set_hparamsZ_hparamsr   Moduler   copydeepcopyZ_hparams_initial)r)   rj   rO   rk   current_framern   rR   Zisx_non_strZ
cand_namesr4   r5   r   )rt   rj   ru   r)   r    save_hyperparameters   sR    

r   c                   @   sD   e Zd ZdZeee dddZeeddddZed	d
dZ	dS )AttributeDicta/  Extended dictionary accessible with dot notation.

    >>> ad = AttributeDict({'key1': 1, 'key2': 'abc'})
    >>> ad.key1
    1
    >>> ad.update({'my-key': 3.14})
    >>> ad.update(new_key=42)
    >>> ad.key1 = 2
    >>> ad
    "key1":    2
    "key2":    abc
    "my-key":  3.14
    "new_key": 42
    )keyr   c              
   C   sF   z
| | W S  t y@ } ztd| d|W Y d }~n
d }~0 0 d S )NzMissing attribute "")KeyErrorr-   )selfr   expr   r   r    __getattr__&  s    
zAttributeDict.__getattr__N)r   r   r   c                 C   s   || |< d S r=   r   )r   r   r   r   r   r    __setattr__,  s    zAttributeDict.__setattr__)r   c                    s\   t  sdS tdd  D }dt|d  d  fddt  D }d	|}|S )
N c                 s   s   | ]}t t|V  qd S r=   )rv   rL   rV   r   r   r    	<genexpr>2  r7   z)AttributeDict.__repr__.<locals>.<genexpr>z{:   zs} {}c                    s$   g | ]} d | d | qS )r   z":)formatrU   r   Ztmp_namer   r    r6   4  r7   z*AttributeDict.__repr__.<locals>.<listcomp>
)rv   maxrL   sortedr[   join)r   Zmax_key_lengthrowsoutr   r   r    __repr__/  s    
zAttributeDict.__repr__)
__name__
__module____qualname____doc__rL   r   r   r   r   r   r   r   r   r    r     s   r   )model	attributer   c                 C   s   g }t | |r||  t | dr8|| jv r8|| j | j}|dur|jdurt |j|rh||j t |jdr||jjv r||jj |S )zSpecial attribute finding for Lightning.

    Gets all of the objects or dicts that holds attribute. Checks for attribute in model namespace, the old hparams
    namespace/dict, and the datamodule.
    r1   N)hasattrrd   r1   Z_trainerZ
datamodule)r   r   holdersZtrainerr   r   r    _lightning_get_all_attr_holders9  s    

r   c                 C   s"   t | |}t|dkrdS |d S )zSpecial attribute finding for Lightning.

    Gets the object or dict that holds attribute, or None. Checks for attribute in model namespace, the old hparams
    namespace/dict, and the datamodule, returns the last one that has it.
    r   N)r   rv   )r   r   r   r   r   r     _lightning_get_first_attr_holderU  s    
r   c                 C   s   t | |duS )zSpecial hasattr for Lightning.

    Checks for attribute in model namespace, the old hparams namespace/dict, and the datamodule.
    N)r   )r   r   r   r   r    lightning_hasattrb  s    r   c                 C   s<   t | |}|du r t| dt|tr2|| S t||S )a4  Special getattr for Lightning. Checks for attribute in model namespace, the old hparams namespace/dict, and
    the datamodule.

    Raises:
        AttributeError:
            If ``model`` doesn't have ``attribute`` in any of
            model namespace, the hparams namespace/dict, and the datamodule.
    N_ is neither stored in the model namespace nor the `hparams` namespace/dict, nor the datamodule.)r   r-   r"   rh   rm   )r   r   holderr   r   r    lightning_getattrj  s    	

r   )r   r   valuer   c                 C   sR   t | |}t|dkr$t| d|D ]$}t|tr@|||< q(t||| q(dS )a\  Special setattr for Lightning. Checks for attribute in model namespace and the old hparams namespace/dict.
    Will also set the attribute on datamodule, if it exists.

    Raises:
        AttributeError:
            If ``model`` doesn't have ``attribute`` in any of
            model namespace, the hparams namespace/dict, and the datamodule.
    r   r   N)r   rv   r-   r"   rh   setattr)r   r   r   r   r   r   r   r    lightning_setattr  s    	


r   )Fr   )N)0r   r|   rB   r*   rb   Zdataclassesr   r   typingr   r   r   r   r   r	   r
   r   r   Ztorchr   Ztyping_extensionsr   Zpytorch_lightningplZ%pytorch_lightning.utilities.rank_zeror   rL   r#   r!   r&   r'   r(   objectr0   r9   rN   rc   rS   rP   re   ri   r   r   r   r   r   r   r   r   r   r   r    <module>   sR   ,

#&  
"0B#