o
    zi3/                     @   sB  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mZ ddlmZ ddlZddlmZ ddlmZ ded	efd
dZded	dfddZded	ee ee  ee  f fddZ!dej"d	e
e e	f fddZ#dej"d	eee	 e
e e	f f fddZ$		d5dej"dee
e e	f  dedeedf d	ee
e e	f  f
ddZ%ddddde	d e	d!eeee  e f  deej" d"ee
e e	f  d	dfd#d$Z&G d%d& d&eZd'd(d)e d	ee	 fd*d+Z'd'd(d)e d	ee	 fd,d-Z(d'd(d)e d	efd.d/Z)d'd(d)e d	ee	 fd0d1Z*d'd(d)e d2e	d	dfd3d4Z+dS )6z%Utilities used for parameter parsing.    N)fieldsis_dataclass)
AnyDictListLiteralMutableMappingOptionalSequenceTupleTypeUnion)nn)AttributeDict)rank_zero_warnobjreturnc                 C   s0   zt |  W dS  t jtttfy   Y dS w )z"Tests if an object can be pickled.TF)pickledumpsPickleErrorAttributeErrorRuntimeError	TypeErrorr    r   W/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_lightning/utilities/parsing.pyis_picklable   s   
r   hparamsc                 C   s<   dd |   D }|D ]}td| d| d | |= qdS )z-Removes all unpicklable entries from hparams.c                 S   s   g | ]
\}}t |s|qS r   )r   .0kvr   r   r   
<listcomp>)       z#clean_namespace.<locals>.<listcomp>zAttribute 'z' removed from hparams because it cannot be pickled. You can suppress this warning by setting `self.save_hyperparameters(ignore=['z'])`.N)itemsr   )r   	del_attrsr    r   r   r   clean_namespace'   s   r&   clsc                 C   sz   t | jj}t| }|d j}dtt j dt	t j
jt j
jf dtt f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_anyF   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_parametersinit_paramsn_selfr-   n_argsn_kwargsr   r   r   parse_class_init_keys3   s   

	
r>   framec                 C   s   t | \}}|S )z$For backwards compatibility: #16369.)_get_init_args)r?   _
local_argsr   r   r   get_init_argsU   s   rC   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 }|rL|||i   fdd| D }|d }	|	|fS )	N	__class__c                 S   s   g | ]}|r|qS r   r   )r   nr   r   r   r"   b   s    z"_get_init_args.<locals>.<listcomp>r?   
frame_argsc                    s   i | ]}| | qS r   r   )r   r    )
local_varsr   r   
<dictcomp>e   s    z"_get_init_args.<locals>.<dictcomp>c                       i | ]\}}| vr||qS r   r   r   )exclude_argnamesr   r   rH   i       )	r.   getargvaluesr/   r0   r1   r>   updategetr$   )
r?   rA   r'   r9   self_varargs_var
kwargs_varfiltered_varsrB   self_argr   )rJ   rG   r   r@   [   s   r@   Fr   	path_argsinsideclasses.c                 C   s|   t | \}}}}t| jtjs|S t| \}}d|v r1|r#t||r1|| t| j|d|dS |s<t| 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.

    rD   T)rU   rV   F)	r.   rL   
isinstancef_backtypes	FrameTyper@   appendcollect_init_args)r?   rT   rU   rV   rA   rG   
local_selfrB   r   r   r   r\   n   s   
r\   )ignorer?   given_hparamsargsr^   r_   c                   s  t |dkrt|ts|d sdS |st }|r|j}t|tjs&td|dur-|n(t	r=fddt
D ni ddlm} t|g |fdD ]}| qMdu r\g nttregntttfrsd	d
 D ttfdd D |s  rdnd_n6dd
 t|D }t |dkr||d    fdd
 D }	|	r|	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)r   fr   r   r   rH      r#   z(save_hyperparameters.<locals>.<dictcomp>)HyperparametersMixin)rV   c                 S   s   g | ]	}t |tr|qS r   rW   r8   r   argr   r   r   r"      s    z(save_hyperparameters.<locals>.<listcomp>c                    rI   r   r   r   )r^   r   r   rH      rK   kwargsc                 S   s   g | ]\}}t |ts|qS r   re   )r   irg   r   r   r   r"      rK   c                    s   g | ]
\}}| kr|qS r   r   r   )hpr   r   r"      r#   c                    s    i | ]}t |tr| | qS r   re   rf   )	init_argsr   r   rH      s     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])`.)lenrW   r8   r.   currentframerX   rY   rZ   r   r   r   pytorch_lightning.core.mixinsrd   r\   rM   r2   tuplesetr$   _hparams_name	enumerate_set_hparams_hparamsr   Moduler   copydeepcopy_hparams_initial)r   r^   r?   r_   r`   current_framerd   rB   isx_non_str
cand_namesr    r!   r   )rj   r^   rk   r   r   save_hyperparameters   sX   	

r|   c                   @   s   e Zd ZdZdS )r   a0  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

    N)__name__
__module____qualname____doc__r   r   r   r   r      s    r   modelzpl.LightningModule	attributec                 C   s   g }t | |r||  t | dr|| jv r|| j | j}|durG|jdurGt |j|r4||j t |jdrG||jjv rG||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.

    r   N)hasattrr[   r   _trainer
datamodule)r   r   holderstrainerr   r   r   _lightning_get_all_attr_holders   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   rl   )r   r   r   r   r   r    _lightning_get_first_attr_holder  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_hasattr  s   r   c                 C   s<   t | |}|du rt| dt|tr|| S t||S )a5  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   rW   dictrb   )r   r   holderr   r   r   lightning_getattr  s   



r   valuec                 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   rl   r   rW   r   setattr)r   r   r   r   r   r   r   r   lightning_setattr5  s   



r   )Fr   ),r   rv   r.   r   rY   dataclassesr   r   typingr   r   r   r   r   r	   r
   r   r   r   torchr   pytorch_lightningpllightning_fabric.utilities.datar   _AttributeDict%pytorch_lightning.utilities.rank_zeror   objectboolr   r&   r8   r>   rZ   rC   r@   r\   r|   r   r   r   r   r   r   r   r   r   <module>   sf   0	$"(

&
H	