o
    پiU                     @   s0  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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mZ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"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a0da1e2ej34dd d kZ5g dZ6edej7dZ8de
e9ef dee9e9f fddZ:dAde;ddfddZ<dAde;ddfddZ=			dBdej7dee
e9ef  dee	 d eee9ef  ddf
d!d"Z>		#	$			dCdej7dee
e9ef  d%e2d&e2d'ee	 d(e;d eee9ef  ddfd)d*Z?de
e9ef de
e9ef fd+d,Z@d-e
e9ef d.ee9 ddfd/d0ZAdDd1d2ZB		dEd3e9deee9e
e9ef f  d4ee
e9ef  de(fd5d6ZC								dFd7eee8 e	d8e8f f d3e9d9e;dee
 d4ee
 d:ee d;ee
 d<e;d=ee	 d eee9ef  d>eee9  de8fd?d@ZDdS )G    N)deepcopy)Path)	AnyCallableDictListOptionalTupleTypeTypeVarUnion)nn)load_state_dict_from_url)FeatureListNetFeatureDictNetFeatureHookNetFeatureGetterNet)FeatureGraphNet)load_state_dict)
has_hf_hubdownload_cached_filecheck_cached_fileload_state_dict_from_hfload_state_dict_from_pathload_custom_from_hf)adapt_input_conv)PretrainedCfg)adapt_model_from_file)get_pretrained_cfgF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_cfgModelT)boundpretrained_cfgreturnc           	      C   s  |  dd}|  dd }|  dd }|  dd }|  dd }d}d}|dkr4tdd	r4d}|s1J |}n>|d
kr=d
}|}n5|rKd}|}t|tsJJ n'|rRd}|}n d}tr^|r\t|nd}|sl|rltdd	rld}|}n|rrd}|}|dkr|  dd r|| d f}||fS )Nsource urlfile
state_dict	hf_hub_idhf-hubT)	necessary	local-dirFhf_hub_filename)getr   
isinstancedict_USE_OLD_CACHEr   )	r)   
cfg_sourcepretrained_urlpretrained_filepretrained_sdr0   	load_frompretrained_locold_cache_valid r@   H/home/ubuntu/.local/lib/python3.10/site-packages/timm/models/_builder.py_resolve_pretrained_source+   sB   rB   Tenablec                 C      | a dS )zA Set download progress for pretrained weights on/off (globally). N)_DOWNLOAD_PROGRESSrC   r@   r@   rA   r    [      r    c                 C   rD   )z= Set hash checking for pretrained weights on/off (globally). N)_CHECK_HASHrF   r@   r@   rA   r!   a   rG   r!   modelload_fn	cache_dirc                 C   s   |pt | dd}|std dS t|\}}|s td dS |dkr*td n|dkr6t|tt|d}|durA|| | dS t| d	rM| | dS 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: Default pretrained model cfg
        load_fn: An external standalone fn that loads weights into provided model, otherwise a fn named
            'load_pretrained' on the model will be called if it exists
        cache_dir: Override model checkpoint cache dir for this load
    r)   Nz/Invalid pretrained config, cannot load weights.zHNo pretrained weights exist for this model. Using random initialization.r1   zKHugging Face hub not currently supported for custom load pretrained models.r-   )
check_hashprogressrK   r#   zXValid function to load pretrained weights is not available, using random initialization.)	getattr_loggerwarningrB   r   rH   rE   hasattrr#   )rI   r)   rJ   rK   r=   r>   r@   r@   rA   r"   g   s,   


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r?td| d |d	d
r:| | dS t|}	n|dkrtd| d |d	d
rat|t	t
|d}| | dS zt|dt	t
d|d}	W n ty   t|dt	t
|d}	Y nqw |dkrtd| d t|ttfr|d	d
}
t|
tr|
dkrtg || R d|i dS t|d|i}	n7t|d|d}	n/|dkrtd| d t|}| rt|}	ntd| |dd}td| d|durz||	| }	W n ty } z
||	}	W Y d}~nd}~ww |dd}|durp|dkrpt|tr-|f}|D ]@}|d  }zt||	| |	|< td!| d"| d# W q/ tyo } z|	|= d
}td$| d% W Y d}~q/d}~ww |d&d}|d'd(}|durt|tr|f}||d) kr|D ]}|	|d  d |	|d* d qd
}n+|d(kr|D ]#}|	|d   }||d |	|d  < |	|d*  }||d |	|d* < q| j|	|d+}|jrtd,d-|j d. |jr td/d-|j d0 dS dS )1a   Load pretrained checkpoint

    Args:
        model: PyTorch module
        pretrained_cfg: Configuration for pretrained weights / target dataset
        num_classes: Number of classes for target model. Will adapt pretrained if different.
        in_chans: Number of input chans for target model. Will adapt pretrained if different.
        filter_fn: state_dict filter fn for load (takes state_dict, model as args)
        strict: Strict load of checkpoint
        cache_dir: Override model checkpoint cache dir for this load
    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 ()custom_loadFr-   z%Loading pretrained weights from url ()rM   rL   rK   cpuT)map_locationrM   rL   weights_only	model_dir)r[   rM   rL   r]   r1   z2Loading pretrained weights from Hugging Face hub (hfrK   )r\   rK   r3   z1Loading pretrained weights from local directory (z#Specified path is not a directory: architecturez
this modelz No pretrained weights exist for z). Use `pretrained=False` for random init.
first_convrS   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   rT   z.bias)rW   zMissing keys (z, zZ) discovered while loading pretrained weights. This is expected if model is being adapted.zUnexpected keys (zY) found while loading pretrained weights. This may be expected if model is being adapted.)rN   RuntimeErrorrB   rO   infor5   r#   r   r   rE   rH   r   	TypeErrorr6   listtuplestrr   r   r   is_dirr   r   NotImplementedErrorrP   popmissing_keysjoinunexpected_keys)rI   r)   rT   rU   rV   rW   rK   r=   r>   r/   rY   pretrained_path
model_nameeinput_convsinput_conv_nameweight_nameclassifiersrb   classifier_nameclassifier_weightclassifier_biasload_resultr@   r@   rA   r#      s   











r#   c                 C   s&   t | } d}|D ]}| |d  q| S )N)rT   ra   global_pool)r   rk   )r)   	to_removetrr@   r@   rA   r$   #  s
   r$   kwargsnamesc                 C   s&   | r|sd S |D ]}|  |d  qd S )N)rk   )r}   r~   nr@   r@   rA   _filter_kwargs,  s
   r   c                 C   s  d}|  ddr|d7 }|D ]o}|dkr1|  dd}|dur0t|dks&J |||d	d  q|d
krP|  dd}|durOt|dksGJ |||d  q|dkrk|  |d}|durj|dkrj||| |  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__
    )rT   rz   rU   fixed_input_sizeF)img_sizer   
input_sizeNrS   rU   r   rT   )r~   )r5   len
setdefaultr   )r)   r}   kwargs_filterdefault_kwarg_namesr   r   default_valr@   r@   rA   _update_default_model_kwargs3  s4   	r   variantpretrained_cfg_overlayc                 C   s   | }d}|rt |trtdi |}n	t |tr|}d}|s+|r'd| |g}t|}|s9td| d t }|p<i }|jsF|	d|  t
j|fi |}|S )z6Resolve pretrained configuration from various sources.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.r_   r@   )r6   r7   r   rh   rm   r   rO   rP   r_   r   dataclassesreplace)r   r)   r   model_with_tagpretrained_tagr@   r@   rA   r%   \  s,   


r%   	model_cls.
pretrained	model_cfgfeature_cfgpretrained_strictpretrained_filter_fnr   c              	   K   s  | dd}d}|pi }t|||d}| }t|||
 | ddrAd}|dd d|v r6| d|d< d|v rA| d|d< |d	u rM| di |}n	| dd
|i|}||_|j|_|rdt||}|rhdn	t|d|	dd}|rt
||||	dd|||	d |rd}d|v r| d}t|tr| }|dvr| dd	 d|v rt}n(|dkrt}n!|dkrt}n|dkrt}n|dkrd}t}n
J d| nt}t|dd	}|d	ur|s|d| ||fi |}t||_|j|_|S )aH   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: Model class
        variant: Model variant name
        pretrained: Load the pretrained weights
        pretrained_cfg: Model's pretrained weight/task config
        pretrained_cfg_overlay: Entries that will override those in pretrained_cfg
        model_cfg: Model's architecture config
        feature_cfg: Feature extraction adapter config
        pretrained_strict: Load pretrained weights strictly
        pretrained_filter_fn: Filter callable for pretrained weights
        cache_dir: Override model cache dir for Hugging Face Hub and Torch checkpoints
        kwargs_filter: Kwargs keys to filter (remove) before passing to model
        **kwargs: Model args passed through to model __init__
    prunedF)r)   r   features_onlyTout_indices)r         rS      feature_clsNcfgr   rT   rR   rU   rS   )r)   rT   rU   rV   rW   rK   )r7   rf   hookflatten_sequentialr   rf   r7   fxgetterzUnknown feature class 
output_fmtr@   )rk   r%   to_dictr   r   r)   default_cfgr   rN   r5   r#   r6   rh   lowerr   r   r   r   r   r$   )r   r   r   r)   r   r   r   r   r   rK   r   r}   r   featuresrI   num_classes_pretrained
use_getterr   r   r@   r@   rA   r&     s   $




r&   )T)NNN)NrR   rS   NTN)r*   N)NN)NNNNTNNN)Er   loggingoscopyr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   torchr   	torch.hubr   timm.models._featuresr   r   r   r   timm.models._features_fxr   timm.models._helpersr   timm.models._hubr   r   r   r   r   r   timm.models._manipulater   timm.models._pretrainedr   timm.models._pruner   timm.models._registryr   	getLogger__name__rO   rE   rH   intenvironr5   r8   __all__Moduler'   rh   rB   boolr    r!   r"   r#   r$   r   r   r%   r&   r@   r@   r@   rA   <module>   s    , 
"0
3
 ""	
+
(	

