o
    پi                     @   s  d Z ddlZddlZddlmZmZmZmZmZ ddl	Z	zddl
ZdZW n ey/   dZY nw eeZg dZdeded	efd
dZdeeef d	eeef fddZ			d$dededeee	jf ded	eeef f
ddZ						d%de	jjdededeee	jf dededee ded	efddZ	d&deeef de	jjded	eeef fddZ			d'de	jjdedee	jj d ee d!ed	ee fd"d#ZdS )(zi Model creation / weight loading / state_dict helpers

Hacked together by / Copyright 2020 Ross Wightman
    N)AnyCallableDictOptionalUnionTF)clean_state_dictload_state_dictload_checkpointremap_state_dictresume_checkpointtextprefixreturnc                 C   s   |  |r| t|d  S | S )N)
startswithlen)r   r    r   H/home/ubuntu/.local/lib/python3.10/site-packages/timm/models/_helpers.py_remove_prefix   s   
r   
state_dictc                 C   s:   i }d}|   D ]\}}|D ]}t||}q|||< q|S )N)zmodule.z
_orig_mod.)itemsr   )r   cleaned_state_dict	to_removekvrr   r   r   r      s   
r   cpucheckpoint_pathuse_emadeviceweights_onlyc                 C   s  | r|t j| r|t| drtsJ dtjj| |d}nz
tj	| ||d}W n t
y8   tj	| |d}Y nw d}t|trg|rM|dddurMd}n|rZ|d	ddurZd	}nd
|v rad
}nd|v rgd}t|rn|| n|}td||  |S td|  t )a_  Load state dictionary from checkpoint file.

    Args:
        checkpoint_path: Path to checkpoint file.
        use_ema: Whether to use EMA weights if available.
        device: Device to load checkpoint to.
        weights_only: Whether to load only weights (torch.load parameter).

    Returns:
        State dictionary loaded from checkpoint.
    z.safetensorsz-`pip install safetensors` to use .safetensors)r   map_locationr   )r!    state_dict_emaN	model_emar   modelzLoaded {} from checkpoint '{}'No checkpoint found at '{}')ospathisfilestrendswith_has_safetensorssafetensorstorch	load_fileload	TypeError
isinstancedictgetr   _loggerinfoformaterrorFileNotFoundError)r   r   r   r   
checkpointstate_dict_keyr   r   r   r   r   ,   s0   
r   r%   strictremap	filter_fnc           
      C   sx   t j|d  dv rt| dr| | dS tdt||||d}|r,t|| }n|r3||| }| j||d}	|	S )a<  Load checkpoint into model.

    Args:
        model: Model to load checkpoint into.
        checkpoint_path: Path to checkpoint file.
        use_ema: Whether to use EMA weights if available.
        device: Device to load checkpoint to.
        strict: Whether to strictly enforce state_dict keys match.
        remap: Whether to remap state dict keys by order.
        filter_fn: Optional function to filter state dict.
        weights_only: Whether to load only weights (torch.load parameter).

    Returns:
        Incompatible keys from model.load_state_dict().
    )z.npzz.npyload_pretrainedz"Model cannot load numpy checkpointN)r   r   )r<   )	r'   r(   splitextlowerhasattrr@   NotImplementedErrorr   r
   )
r%   r   r   r   r<   r=   r>   r   r   incompatible_keysr   r   r   r	   Z   s   


r	   allow_reshapec                 C   s   i }t |  |  D ]I\\}}\}}| | ks0J d| d|j d| d|j d	|j|jkrR|r?||j}nJ d| d|j d| d|j d	|||< q|S )a  Remap checkpoint by iterating over state dicts in order (ignoring original keys).

    This assumes models (and originating state dict) were created with params registered in same order.

    Args:
        state_dict: State dict to remap.
        model: Model whose state dict keys to use.
        allow_reshape: Whether to allow reshaping tensors to match.

    Returns:
        Remapped state dictionary.
    zTensor size mismatch z: z vs z. Remap failed.FzTensor shape mismatch )zipr   r   numelshapereshape)r   r%   rF   out_dictkavakbvbr   r   r   r
      s   &6&
r
   	optimizerloss_scalerlog_infoc                 C   s4  d}t j|rtj|ddd}t|tr~d|v r~|r td t	|d }| 
| |durAd|v rA|r:td |
|d  |durY|j|v rY|rQtd	 |
||j  d
|v r||d
 }d|v ro|d dkro|d7 }|r|td||d
  |S | 
| |rtd| |S td| t )az  Resume training from checkpoint.

    Args:
        model: Model to load checkpoint into.
        checkpoint_path: Path to checkpoint file.
        optimizer: Optional optimizer to restore state.
        loss_scaler: Optional AMP loss scaler to restore state.
        log_info: Whether to log loading info.

    Returns:
        Resume epoch number if available, else None.
    Nr   Fr    r   z(Restoring model state from checkpoint...rP   z,Restoring optimizer state from checkpoint...z2Restoring AMP loss scaler state from checkpoint...epochversion   z!Loaded checkpoint '{}' (epoch {})zLoaded checkpoint '{}'r&   )r'   r(   r)   r.   r0   r2   r3   r5   r6   r   r   r;   r7   r8   r9   )r%   r   rP   rQ   rR   resume_epochr:   r   r   r   r   r      s:   




r   )Tr   F)Tr   TFNF)T)NNT) __doc__loggingr'   typingr   r   r   r   r   r.   safetensors.torchr-   r,   ImportError	getLogger__name__r5   __all__r*   r   r   boolr   r   nnModuler	   r
   optim	Optimizerintr   r   r   r   r   <module>   s    
"

1	
-


 
