U
    ¯Ê¹jùI  ã                   @   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+dddddddg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&„ Z6d/e7ed'œd(d„Z8d0ee7e2ee ee ee	 ee e2ee ee
e7  d)œ
d*d„Z9dS )1é    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}|sbt‚|}nj|r„d}|}t|tƒsÒt‚nN|r’d}|}n@d
}trª|r¦t|ƒnd
}|sÆ|rÆtdd	�rÆd}|}n|rÒd}|}|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   ÚAssertionErrorÚ
isinstanceÚdictÚ_USE_OLD_CACHEr   )	Úpretrained_cfgZ
cfg_sourceZpretrained_urlZpretrained_fileZpretrained_sdr"   Ú	load_fromÚpretrained_locZold_cache_valid© r,   úS/var/www/html/bwave/python/venv/lib/python3.8/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    c                 C   s   | a dS )z= Set hash checking for pretrained weights on/off (globally). N)Ú_CHECK_HASHr0   r,   r,   r-   r   R   s    )Ú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k	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   r2   r/   Úhasattrr   )r3   r)   r4   r*   r+   r,   r,   r-   r   X   s*    

ý
éè  é   )r3   r)   Únum_classesÚin_chansÚ	filter_fnÚstrictc                 C   sJ  |pt | ddƒ}|stdƒ‚t|ƒ\}}|dkr@t d¡ |}nî|dkr~t d|› d�¡ | d	d
¡rt|  |¡ dS t|ƒ}n°|dkrÒt d|› d�¡ | d	d
¡rÀt|t	t
d�}|  |¡ dS t|dt	t
d�}n\|dk�rt d|› d�¡ t|ttfƒ�rt|Ž }nt|ƒ}n| dd¡}	td|	› d�ƒ‚|dk	�rtz||| ƒ}W n, tk
�rr }
 z||ƒ}W 5 d}
~
X Y nX | dd¡}|dk	�r*|dk�r*t|tƒ�r¦|f}|D ]~}|d }z.t||| ƒ||< t d|› d|› d�¡ W n@ tk
�r$ }
 z ||= d
}t d|› d�¡ W 5 d}
~
X Y nX �qª| dd¡}| dd ¡}|dk	�rôt|tƒ�r^|f}||d! k�rž|D ]&}| |d d¡ | |d" d¡ �qpd
}nV|d k�rô|D ]F}||d  }||d… ||d < ||d"  }||d… ||d" < �q¬| j||d#�}|j�r$t d$d% |j¡› d&�¡ |j�rFt d'd% |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 (ú)Zcustom_loadFr   z%Loading pretrained weights from url ()r6   r5   Úcpu)Zmap_locationr6   r5   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@   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.)r7   ÚRuntimeErrorr.   r8   Úinfor$   r   r   r   r/   r2   r	   r&   ÚlistÚtupler   Ú	TypeErrorÚstrr   ÚNotImplementedErrorr9   ÚpopZmissing_keysÚjoinZunexpected_keys)r3   r)   r=   r>   r?   r@   r*   r+   r!   Z
model_nameÚeZinput_convsZinput_conv_nameZweight_nameÚclassifiersrE   Zclassifier_nameZclassifier_weightZclassifier_biasZload_resultr,   r,   r-   r   †   s¦    


ý
ü



ÿ
ÿ

ÿÿc                 C   s&   t | ƒ} d}|D ]}|  |d ¡ q| S )N)r=   rD   Úglobal_pool)r   rM   )r)   Z	to_removeÚtrr,   r,   r-   r   ø   s
    c                 C   s&   | r|sd S |D ]}|   |d ¡ qd S )N)rM   )ÚkwargsÚnamesÚnr,   r,   r-   Ú_filter_kwargs  s    rV   c                 C   s  d}|   dd¡r|d7 }|D ]Þ}|dkrb|   dd¡}|dk	rút|ƒdksLt‚| ||d	d… ¡ q|d
kr |   dd¡}|dk	rút|ƒdksŽt‚| ||d ¡ q|dkrÖ|   |d¡}|dk	rú|dkrú| || | ¡ q|   |d¡}|dk	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=   rQ   r>   Zfixed_input_sizeF)Úimg_sizerW   Ú
input_sizeNr<   éþÿÿÿr>   r   r=   )rT   )r$   Úlenr%   Ú
setdefaultrV   )r)   rS   Úkwargs_filterZdefault_kwarg_namesrU   rX   Zdefault_valr,   r,   r-   Ú_update_default_model_kwargs  s,    	r]   )ÚvariantÚreturnc                 C   sš   | }d }|r4t |tƒr"tf |Ž}nt |tƒr4|}d }|sR|rJd | |g¡}t|ƒ}|snt d|› d�¡ tƒ }|pti }|jsˆ| 	d| ¡ t
j|f|Ž}|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.rC   )r&   r'   r   rK   rN   r   r8   r9   rC   r[   ÚdataclassesÚreplace)r^   r)   Úpretrained_cfg_overlayZmodel_with_tagZpretrained_tagr,   r,   r-   r   1  s,    


ÿ)
Ú	model_clsr^   Ú
pretrainedr)   rc   Ú	model_cfgÚfeature_cfgÚpretrained_strictÚpretrained_filter_fnr\   c
                 K   s”  |
  dd¡}d}|pi }t|||d�}| ¡ }t||
|	ƒ |
  dd¡rld}| dd¡ d|
krl|
  d¡|d< |dkr€| f |
Ž}n| f d	|i|
—Ž}||_|j|_|r®t||ƒ}|r¶d
nt|d|
 	dd¡ƒ}|rêt
||||
 	dd¡||d� |�r�t}t|ddƒ}|dk	�r| d|¡ d|k�rr|  d¡}t|tƒ�rr| ¡ }d|k�rNt}n$|dk�r^t}nd�srtd|› �ƒ‚||f|Ž}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)   rc   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 )rM   r   Úto_dictr]   r[   r)   Zdefault_cfgr   r7   r$   r   r
   r&   rK   Úlowerr   r   r%   r   )rd   r^   re   r)   rc   rf   rg   rh   ri   r\   rS   rj   Úfeaturesr3   Znum_classes_pretrainedrp   ro   r,   r,   r-   r   T  sd    !ý

ú






)T)T)NN)Nr;   r<   NT)NN)NNNNTNN):ra   Ú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__r8   r/   r2   ÚintÚenvironr$   r(   Ú__all__r.   r   r   ÚModuler   Úboolr   r   rV   r]   rK   r   r   r,   r,   r,   r-   Ú<module>   s”   
  ÿ-

  ýý0     úúr	+  ýü'       ö
ö