a
    duF                     @   s  d dl Z d dlZd dlZd dlmZ d dl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mZ d dlmZ d dlmZ d d	lmZmZmZmZ d d
lmZ d dlmZ d dlm Z  d dl!m"Z" e#e$Z%da&da'e(ej)*dd d kZ+g dZ,dd Z-d,ddZ.d-ddZ/d.ej0ee ee dddZ1d/ej0ee e(e(ee e2dddZ3d d! Z4d"d# Z5d$d% Z6d0e7ed&d'd(Z8d1ee7e2ee ee ee	 ee e2ee ee
e7  d)
d*d+Z9dS )2    N)deepcopy)OptionalDictCallableAnyTuple)nn)load_state_dict_from_url)FeatureListNetFeatureHookNet)FeatureGraphNet)load_state_dict)
has_hf_hubdownload_cached_filecheck_cached_fileload_state_dict_from_hf)adapt_input_conv)PretrainedCfg)adapt_model_from_file)get_pretrained_cfgFZTIMM_USE_OLD_CACHE) set_pretrained_download_progressset_pretrained_check_hashload_custom_pretrainedload_pretrainedpretrained_cfg_for_featuresresolve_pretrained_cfgbuild_model_with_cfgc           	      C   s   |  dd}|  dd }|  dd }|  dd }|  dd }d}d}|dkrhtdd	rhd}|sbJ |}nj|rd}|}t|tsJ nN|rd}|}n@d
}tr|rt|nd
}|s|rtdd	rd}|}n|rd}|}|dkr|  dd r|| d f}||fS )Nsource urlfile
state_dict	hf_hub_idhf-hubT)Z	necessaryFZhf_hub_filename)getr   
isinstancedict_USE_OLD_CACHEr   )	pretrained_cfgZ
cfg_sourceZpretrained_urlZpretrained_fileZpretrained_sdr"   	load_frompretrained_locZold_cache_valid r+   ]/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/models/_builder.py_resolve_pretrained_source   s<    r-   Tc                 C   s   | a dS )zA Set download progress for pretrained weights on/off (globally). N)_DOWNLOAD_PROGRESSenabler+   r+   r,   r   L   s    r   c                 C   s   | a dS )z= Set hash checking for pretrained weights on/off (globally). N)_CHECK_HASHr/   r+   r+   r,   r   R   s    r   )modelr(   load_fnc                 C   s   |pt | dd}|s"td dS t|\}}|s@td dS |dkrTtd n|dkrjt|ttd}|dur~|| | n t| d	r| | n
td
 dS )a  Loads a custom (read non .pth) weight file

    Downloads checkpoint file into cache-dir like torch.hub based loaders, but calls
    a passed in custom load fun, or the `load_pretrained` model member fn.

    If the object is already present in `model_dir`, it's deserialized and returned.
    The default value of `model_dir` is ``<hub_dir>/checkpoints`` where
    `hub_dir` is the directory returned by :func:`~torch.hub.get_dir`.

    Args:
        model: The instantiated model to load weights into
        pretrained_cfg (dict): Default pretrained model cfg
        load_fn: An external standalone fn that loads weights into provided model, otherwise a fn named
            'laod_pretrained' on the model will be called if it exists
    r(   Nz/Invalid pretrained config, cannot load weights.zHNo pretrained weights exist for this model. Using random initialization.r#   zKHugging Face hub not currently supported for custom load pretrained models.r   )
check_hashprogressr   zXValid function to load pretrained weights is not available, using random initialization.)	getattr_loggerwarningr-   r   r1   r.   hasattrr   )r2   r(   r3   r)   r*   r+   r+   r,   r   X   s*    


r        )r2   r(   num_classesin_chans	filter_fnstrictc                 C   s  |pt | dd}|stdt|\}}|dkr@td |}n|dkrdtd| d t|}n|d	krtd
| d |ddrt|tt	d}| 
| dS t|dtt	d}nX|dkrtd| d t|ttfrt| }nt|}n|dd}	td|	 d|durXz||| }W n. tyV }
 z||}W Y d}
~
n
d}
~
0 0 |dd}|dur|dkrt|tr|f}|D ]}|d }z.t||| ||< td| d| d W nB ty
 }
 z(||= d}td| d W Y d}
~
n
d}
~
0 0 q|dd}|dd }|durt|trD|f}||d! kr|D ]&}||d d ||d" d qVd}nV|d kr|D ]F}||d  }||d ||d < ||d"  }||d ||d" < q| j||d# dS )$a   Load pretrained checkpoint

    Args:
        model (nn.Module) : PyTorch model module
        pretrained_cfg (Optional[Dict]): configuration for pretrained weights / target dataset
        num_classes (int): num_classes for target model
        in_chans (int): in_chans for target model
        filter_fn (Optional[Callable]): state_dict filter fn for load (takes state_dict, model as args)
        strict (bool): strict load of checkpoint

    r(   NzWInvalid pretrained config, cannot load weights. Use `pretrained=False` for random init.r!   z*Loading pretrained weights from state dictr    z&Loading pretrained weights from file ()r   z%Loading pretrained weights from url (Zcustom_loadF)r5   r4   cpu)Zmap_locationr5   r4   r#   z2Loading pretrained weights from Hugging Face hub (architecturez
this modelz No pretrained weights exist for z). Use `pretrained=False` for random init.Z
first_convr;   z.weightzConverted input conv z pretrained weights from 3 to z channel(s)zUnable to convert pretrained z+ weights, using random init for this layer.
classifierlabel_offsetr   r<   z.bias)r?   )r6   RuntimeErrorr-   r7   infor   r$   r   r.   r1   r   r	   r%   listtupler   	TypeErrorstrr   NotImplementedErrorr8   pop)r2   r(   r<   r=   r>   r?   r)   r*   r!   Z
model_nameeZinput_convsZinput_conv_nameZweight_nameclassifiersrD   Zclassifier_nameZclassifier_weightZclassifier_biasr+   r+   r,   r      s    








r   c                 C   s&   t | } d}|D ]}| |d  q| S )N)r<   rC   global_pool)r   rL   )r(   Z	to_removetrr+   r+   r,   r      s
    r   c                 C   s&   | r|sd S |D ]}|  |d  qd S )N)rL   )kwargsnamesnr+   r+   r,   _filter_kwargs   s    rT   c                 C   s   d}|  ddr|d7 }|D ]}|dkrb|  dd}|durt|dksLJ |||d	d  q|d
kr|  dd}|durt|dksJ |||d  q|  |d}|dur||| |  qt||d dS )a&   Update the default_cfg and kwargs before passing to model

    Args:
        pretrained_cfg: input pretrained cfg (updated in-place)
        kwargs: keyword args passed to model build fn (updated in-place)
        kwargs_filter: keyword arg keys that must be removed before model __init__
    )r<   rO   r=   Zfixed_input_sizeF)img_sizerU   
input_sizeNr;   r=   r   )rR   )r$   len
setdefaultrT   )r(   rQ   kwargs_filterZdefault_kwarg_namesrS   rV   Zdefault_valr+   r+   r,   _update_default_kwargs   s$    	r[   )variantreturnc                 C   s   | }d }|r8t |tr&tf i |}nt |tr8|}d }|sV|rNd| |g}t|}|srtd| d t }|pxi }|js|	d|  t
j|fi |}|S )N.z*No pretrained configuration specified for ze model. Using a default. Please add a config to the model pretrained_cfg registry or pass explicitly.rB   )r%   r&   r   rJ   joinr   r7   r8   rB   rY   dataclassesreplace)r\   r(   pretrained_cfg_overlayZmodel_with_tagZpretrained_tagr+   r+   r,   r      s,    


r   )
	model_clsr\   
pretrainedr(   rb   	model_cfgfeature_cfgpretrained_strictpretrained_filter_fnrZ   c
                 K   s  |
 dd}d}|pi }t|||d}| }t||
|	 |
 ddrld}|dd d|
v rl|
 d|d< |du r| f i |
}n| f d	|i|
}||_|j|_|rt||}|rd
nt|d|
	dd}|rt
||||
	dd||d |rt}t|dd}|dur|d| d|v rv| d}t|trv| }d|v rRt}n$|dkrbt}ndsvJ d| ||fi |}t||_|j|_|S )a   Build model with specified default_cfg and optional model_cfg

    This helper fn aids in the construction of a model including:
      * handling default_cfg and associated pretrained weight loading
      * passing through optional model_cfg for models with config based arch spec
      * features_only model adaptation
      * pruning config / model adaptation

    Args:
        model_cls (nn.Module): model class
        variant (str): model variant name
        pretrained (bool): load pretrained weights
        pretrained_cfg (dict): model's pretrained weight/task config
        model_cfg (Optional[Dict]): model's architecture config
        feature_cfg (Optional[Dict]: feature extraction adapter config
        pretrained_strict (bool): load pretrained weights strictly
        pretrained_filter_fn (Optional[Callable]): filter callable for pretrained weights
        kwargs_filter (Optional[Tuple]): kwargs to filter before passing to model
        **kwargs: model args passed through to model __init__
    prunedF)r(   rb   Zfeatures_onlyTZout_indices)r         r;      Ncfgr   r<   r:   r=   r;   )r(   r<   r=   r>   r?   
output_fmtfeature_clshookZfxzUnknown feature class )rL   r   to_dictr[   rY   r(   Zdefault_cfgr   r6   r$   r   r
   r%   rJ   lowerr   r   r   )rc   r\   rd   r(   rb   re   rf   rg   rh   rZ   rQ   ri   featuresr2   Znum_classes_pretrainedro   rn   r+   r+   r,   r   C  sd    !








r   )T)T)NN)Nr:   r;   NT)NN)NNNNTNN):r`   loggingoscopyr   typingr   r   r   r   r   Ztorchr   Z	torch.hubr	   Ztimm.models._featuresr
   r   Ztimm.models._features_fxr   Ztimm.models._helpersr   Ztimm.models._hubr   r   r   r   Ztimm.models._manipulater   Ztimm.models._pretrainedr   Ztimm.models._pruner   Ztimm.models._registryr   	getLogger__name__r7   r.   r1   intenvironr$   r'   __all__r-   r   r   Moduler   boolr   r   rT   r[   rJ   r   r   r+   r+   r+   r,   <module>   s   
-

  0     f	&  '       
