o
    h                     @   s  d dl Z d dlZd dlZd dlmZmZmZ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mZmZ d dl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# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, e) ryd dl-Z-e' rd dl.Z.d dl/m0Z1 d dl/m2Z3 e*4e5Z6G dd deZ7edddZ8edZ9ee9gef Z:eege9f Z;ee:e;f Z<dZ=eG dd dZ>G dd dZ?G dd de?Z@dee7 deAde7fddZBdS )    N)Fieldasdict	dataclassis_dataclass)Path)AnyCallableClassVarDictListOptionalProtocolTupleTypeTypeVarUnion   )	constants)EntryNotFoundErrorHfHubHTTPError)hf_hub_download)HfApi)	ModelCardModelCardData)SoftTemporaryDirectoryis_jsonableis_safetensors_availableis_simple_optional_typeis_torch_availableloggingunwrap_simple_optional_typevalidate_hf_hub_args)
load_model)
save_modelc                   @   s"   e Zd ZU eeeef  ed< dS )DataclassInstance__dataclass_fields__N)__name__
__module____qualname__r	   r
   strr   __annotations__ r+   r+   m/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/huggingface_hub/hub_mixin.pyr$   (   s   
 r$   TModelHubMixin)boundARGS_Ta_  
---
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
# Doc / guide: https://huggingface.co/docs/hub/model-cards
{{ card_data }}
---

This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:
- Code: {{ repo_url | default("[More Information Needed]", true) }}
- Paper: {{ paper_url | default("[More Information Needed]", true) }}
- Docs: {{ docs_url | default("[More Information Needed]", true) }}
c                   @   sN   e Zd ZU eed< eed< dZee ed< dZee ed< dZ	ee ed< dS )	MixinInfomodel_card_templatemodel_card_dataNdocs_url	paper_urlrepo_url)
r&   r'   r(   r)   r*   r   r4   r   r5   r6   r+   r+   r+   r,   r1   C   s   
 r1   c                       s  e Zd ZU dZdZeeeef  e	d< e
e	d< ee	d< eeejf e	d< eeef e	d< eedf e	d	< eeef e	d
< dddeddddddddddee dee dee dedeee  dee dee dee dee dee deee  deeeef  ddf fddZdee def fddZededefdd Zed!edefd"d#Zed$ee dedee fd%d&Zddd'dd(d)eeef d*eeeef  d+ee d,ed-eeeef  dee fd.d/Zd)eddfd0d1Z ee!d'ddddd'dd2dee d3eeef d4ed5ee d6ee d7eeeef  d8eeeef  d9ed:ee defd;d<Z"edee d=ed:ee d8eeeef  d4ed6ee d5ee d9ed7eeeef  defd>d?Z#e!dd@dddddddddA
d+ed*eeeef  dBedCee d7ee dDee dEee dFeeee ef  dGeeee ef  dHeeee ef  d-eeeef  defdIdJZ$de%fdKdLZ&  Z'S )Mr.   a  
    A generic mixin to integrate ANY machine learning framework with the Hub.

    To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models
    have to be overwritten in  [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example
    of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions.

    When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to
    `__init__` but to the class definition itself. This is useful to define metadata about the library integrating
    [`ModelHubMixin`].

    For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations).

    Args:
        repo_url (`str`, *optional*):
            URL of the library repository. Used to generate model card.
        paper_url (`str`, *optional*):
            URL of the library paper. Used to generate model card.
        docs_url (`str`, *optional*):
            URL of the library documentation. Used to generate model card.
        model_card_template (`str`, *optional*):
            Template of the model card. Used to generate model card. Defaults to a generic template.
        language (`str` or `List[str]`, *optional*):
            Language supported by the library. Used to generate model card.
        library_name (`str`, *optional*):
            Name of the library integrating ModelHubMixin. Used to generate model card.
        license (`str`, *optional*):
            License of the library integrating ModelHubMixin. Used to generate model card.
            E.g: "apache-2.0"
        license_name (`str`, *optional*):
            Name of the library integrating ModelHubMixin. Used to generate model card.
            Only used if `license` is set to `other`.
            E.g: "coqui-public-model-license".
        license_link (`str`, *optional*):
            URL to the license of the library integrating ModelHubMixin. Used to generate model card.
            Only used if `license` is set to `other` and `license_name` is set.
            E.g: "https://coqui.ai/cpml".
        pipeline_tag (`str`, *optional*):
            Tag of the pipeline. Used to generate model card. E.g. "text-classification".
        tags (`List[str]`, *optional*):
            Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"]
        coders (`Dict[Type, Tuple[Callable, Callable]]`, *optional*):
            Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not
            jsonable by default. E.g dataclasses, argparse.Namespace, OmegaConf, etc.

    Example:

    ```python
    >>> from huggingface_hub import ModelHubMixin

    # Inherit from ModelHubMixin
    >>> class MyCustomModel(
    ...         ModelHubMixin,
    ...         library_name="my-library",
    ...         tags=["computer-vision"],
    ...         repo_url="https://github.com/huggingface/my-cool-library",
    ...         paper_url="https://arxiv.org/abs/2304.12244",
    ...         docs_url="https://huggingface.co/docs/my-cool-library",
    ...         # ^ optional metadata to generate model card
    ...     ):
    ...     def __init__(self, size: int = 512, device: str = "cpu"):
    ...         # define how to initialize your model
    ...         super().__init__()
    ...         ...
    ...
    ...     def _save_pretrained(self, save_directory: Path) -> None:
    ...         # define how to serialize your model
    ...         ...
    ...
    ...     @classmethod
    ...     def from_pretrained(
    ...         cls: Type[T],
    ...         pretrained_model_name_or_path: Union[str, Path],
    ...         *,
    ...         force_download: bool = False,
    ...         resume_download: Optional[bool] = None,
    ...         proxies: Optional[Dict] = None,
    ...         token: Optional[Union[str, bool]] = None,
    ...         cache_dir: Optional[Union[str, Path]] = None,
    ...         local_files_only: bool = False,
    ...         revision: Optional[str] = None,
    ...         **model_kwargs,
    ...     ) -> T:
    ...         # define how to deserialize your model
    ...         ...

    >>> model = MyCustomModel(size=256, device="gpu")

    # Save model weights to local directory
    >>> model.save_pretrained("my-awesome-model")

    # Push model weights to the Hub
    >>> model.push_to_hub("my-awesome-model")

    # Download and initialize weights from the Hub
    >>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model")
    >>> reloaded_model.size
    256

    # Model card has been correctly populated
    >>> from huggingface_hub import ModelCard
    >>> card = ModelCard.load("username/my-awesome-model")
    >>> card.data.tags
    ["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
    >>> card.data.library_name
    "my-library"
    ```
    N_hub_mixin_config_hub_mixin_info_hub_mixin_inject_config_hub_mixin_init_parameters"_hub_mixin_jsonable_default_values. _hub_mixin_jsonable_custom_types_hub_mixin_coders)r6   r5   r4   r2   languagelibrary_namelicenselicense_namelicense_linkpipeline_tagtagscodersr6   r5   r4   r2   r>   r?   r@   rA   rB   rC   rD   rE   returnc                   s  t    |pg }|d t|t d}t dr>|tkr# jj|_tdi  jj	
 |_	 jj|_ jj|_ jj|_| _|durL|tkrL||_|durS||_|durZ||_|dura||_|duri||j	_|durq||j	_|dury||j	_|dur||j	_|	dur|	|j	_|
dur|
|j	_|dur|j	jdur|j	j| n||j	_tt|j	j|j	_|pi  _t j  _tt jj  _! fdd j!" D  _#dt j$j v  _%dS )	zIInspect __init__ signature only once when subclassing + handle modelcard.model_hub_mixin)r2   r3   r8   Nc                    s6   i | ]}|j tjjur |j r|j |j qS r+   )defaultinspect	Parameterempty_is_jsonablename_encode_arg.0paramclsr+   r,   
<dictcomp>  s
    z3ModelHubMixin.__init_subclass__.<locals>.<dictcomp>configr+   )&super__init_subclass__appendr1   r   hasattrDEFAULT_MODEL_CARDr8   r2   r3   to_dictr4   r5   r6   r>   r?   r@   rA   rB   rC   rD   extendsortedsetr=   tuplekeysr<   dictrI   	signature__init__
parametersr:   valuesr;   _from_pretrainedr9   )rS   r6   r5   r4   r2   r>   r?   r@   rA   rB   rC   rD   rE   info	__class__rR   r,   rW      sX   








zModelHubMixin.__init_subclass__rS   c                    s   t   jdurS i dd tt jdd |D |}t|dr0|d _S i  j fdd|	 D }|
di }t|trQ|| |i krX|_S )aA  Create a new instance of the class and handle config.

        3 cases:
        - If `self._hub_mixin_config` is already set, do nothing.
        - If `config` is passed as a dataclass, set it as `self._hub_mixin_config`.
        - Otherwise, build `self._hub_mixin_config` from default values and passed values.
        Nc                 S   s   i | ]\}}||qS r+   r+   rP   keyvaluer+   r+   r,   rT   1  s    z)ModelHubMixin.__new__.<locals>.<dictcomp>r   rU   c                    s&   i | ]\}} |r| |qS r+   )rL   rN   rj   rS   instancer+   r,   rT   F  s    
)rV   __new__r7   ziplistr:   r   getr;   itemspop
isinstancera   update)rS   argskwargspassed_valuesinit_configpassed_configrh   rm   r,   ro   !  s:   
	



zModelHubMixin.__new__rl   c                 C   s$   t |rdS t|| jrdS t|S )z&Check if a value is JSON serializable.T)r   ru   r<   r   )rS   rl   r+   r+   r,   rL   W  s
   zModelHubMixin._is_jsonableargc                 C   sP   t |rt|S | j D ]\}\}}t||r%|du r dS ||  S q|S )z3Encode an argument into a JSON serializable format.N)r   r   r=   rs   ru   )rS   r|   type_encoder_r+   r+   r,   rN   `  s   
zModelHubMixin._encode_argexpected_typec                 C   sj   t |r|du r
dS t|}t|rt||S | j D ]\}\}}t|r2t||r2||  S q|S )z2Decode a JSON serializable value into an argument.N)	r   r    r   _load_dataclassr=   rs   rI   isclass
issubclass)rS   r   rl   r}   r   decoderr+   r+   r,   _decode_argl  s   
zModelHubMixin._decode_argF)rU   repo_idpush_to_hubmodel_card_kwargssave_directoryrU   r   r   r   c                K   s   t |}|jddd |tj }|jdd | | |du r"| j}|dur?t|r.t|}|	 s?t
j|ddd}|| |d }	|durI|ni }|		 s\| jd
i ||d  |r|| }
|durj||
d< |du rq|j}| jd
||d	|
S dS )ag  
        Save weights in local directory.

        Args:
            save_directory (`str` or `Path`):
                Path to directory in which the model weights and configuration will be saved.
            config (`dict` or `DataclassInstance`, *optional*):
                Model configuration specified as a key/value dictionary or a dataclass instance.
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Huggingface Hub after saving it.
            repo_id (`str`, *optional*):
                ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
                not provided.
            model_card_kwargs (`Dict[str, Any]`, *optional*):
                Additional arguments passed to the model card template to customize the model card.
            push_to_hub_kwargs:
                Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
        Returns:
            `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
        T)parentsexist_ok)
missing_okN   )	sort_keysindentz	README.mdrU   )r   r   r+   )r   mkdirr   CONFIG_NAMEunlink_save_pretrainedr7   r   r   existsjsondumps
write_textgenerate_model_cardsavecopyrM   r   )selfr   rU   r   r   r   push_to_hub_kwargsconfig_path
config_strmodel_card_pathrx   r+   r+   r,   save_pretrained}  s2   


zModelHubMixin.save_pretrainedc                 C      t )aD  
        Overwrite this method in subclass to define how to save your model.
        Check out our [integration guide](../guides/integrations) for instructions.

        Args:
            save_directory (`str` or `Path`):
                Path to directory in which the model weights and configuration will be saved.
        NotImplementedError)r   r   r+   r+   r,   r     s   	zModelHubMixin._save_pretrained)force_downloadresume_downloadproxiestoken	cache_dirlocal_files_onlyrevisionpretrained_model_name_or_pathr   r   r   r   r   r   r   c                K   s  t |}
d}tj|
r-tjt|
v rtj|
tj}n@t	tj dt
|
   n0zt|
tj|||||||d	}W n ty\ } zttj dt |  W Y d}~nd}~ww d}|durt|ddd}t|}W d   n1 s{w   Y  | D ]\}}|| jv r| j| j}|tjjur| ||||< q| j D ]}|j|	vr|j|v r||j |	|j< qd| jv rd|	vr| jd j}| ||}||	d< t| r| jD ]}||	vr||v r|| |	|< qntd	d
 | j D r| D ]\}}||	vr||	|< q| jrd|	vr||	d< | jdt |
|||||||d|	}|dur@t |dddi fv r@||_!|S )a  
        Download a model from the Huggingface Hub and instantiate it.

        Args:
            pretrained_model_name_or_path (`str`, `Path`):
                - Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`.
                - Or a path to a `directory` containing model weights saved using
                    [`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`.
            revision (`str`, *optional*):
                Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
                Defaults to the latest commit on `main` branch.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
                the existing cache.
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on every request.
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. By default, it will use the token
                cached when running `huggingface-cli login`.
            cache_dir (`str`, `Path`, *optional*):
                Path to the folder where cached files are stored.
            local_files_only (`bool`, *optional*, defaults to `False`):
                If `True`, avoid downloading the file and return the path to the local cached file if it exists.
            model_kwargs (`Dict`, *optional*):
                Additional kwargs to pass to the model during initialization.
        Nz not found in 	r   filenamer   r   r   r   r   r   r   z# not found on the HuggingFace Hub: rzutf-8)encodingrU   c                 s   s    | ]
}|j tjjkV  qd S )N)kindrI   rJ   VAR_KEYWORDrO   r+   r+   r,   	<genexpr>-  s    z0ModelHubMixin.from_pretrained.<locals>.<genexpr>)model_idr   r   r   r   r   r   r   r7   r+   )"r)   ospathisdirr   r   listdirjoinloggerwarningr   resolver   r   rg   openr   loadrs   r:   
annotationrI   rJ   rK   r   re   rM   r   r%   anyr9   rf   getattrr7   )rS   r   r   r   r   r   r   r   r   model_kwargsr   config_fileerU   frk   rl   r   rQ   config_annotationrn   r+   r+   r,   from_pretrained  s   * 
&



	 zModelHubMixin.from_pretrainedr   c          
      K   r   )a  Overwrite this method in subclass to define how to load your model from pretrained.

        Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most
        args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this
        method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location`
        parameter to set on which device the model should be loaded.

        Check out our [integration guide](../guides/integrations) for more instructions.

        Args:
            model_id (`str`):
                ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
            revision (`str`, *optional*):
                Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
                latest commit on `main` branch.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
                the existing cache.
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`).
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. By default, it will use the token
                cached when running `huggingface-cli login`.
            cache_dir (`str`, `Path`, *optional*):
                Path to the folder where cached files are stored.
            local_files_only (`bool`, *optional*, defaults to `False`):
                If `True`, avoid downloading the file and return the path to the local cached file if it exists.
            model_kwargs:
                Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
        r   )
rS   r   r   r   r   r   r   r   r   r   r+   r+   r,   rf   I  s   -zModelHubMixin._from_pretrainedz!Push model using huggingface_hub.)
rU   commit_messageprivater   branch	create_prallow_patternsignore_patternsdelete_patternsr   r   r   r   r   r   r   r   c       
         C   s~   t |d}|j||ddj}t $}t|| }| j|||d |j|d||||||	|
d	W  d   S 1 s8w   Y  dS )a=  
        Upload model checkpoint to the Hub.

        Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
        `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
        details.

        Args:
            repo_id (`str`):
                ID of the repository to push to (example: `"username/my-model"`).
            config (`dict` or `DataclassInstance`, *optional*):
                Model configuration specified as a key/value dictionary or a dataclass instance.
            commit_message (`str`, *optional*):
                Message to commit while pushing.
            private (`bool`, *optional*):
                Whether the repository created should be private.
                If `None` (default), the repo will be public unless the organization's default is private.
            token (`str`, *optional*):
                The token to use as HTTP bearer authorization for remote files. By default, it will use the token
                cached when running `huggingface-cli login`.
            branch (`str`, *optional*):
                The git branch on which to push the model. This defaults to `"main"`.
            create_pr (`boolean`, *optional*):
                Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
            allow_patterns (`List[str]` or `str`, *optional*):
                If provided, only files matching at least one pattern are pushed.
            ignore_patterns (`List[str]` or `str`, *optional*):
                If provided, files matching any of the patterns are not pushed.
            delete_patterns (`List[str]` or `str`, *optional*):
                If provided, remote files matching any of the patterns will be deleted from the repo.
            model_card_kwargs (`Dict[str, Any]`, *optional*):
                Additional arguments passed to the model card template to customize the model card.

        Returns:
            The url of the commit of your model in the given repository.
        )r   T)r   r   r   )rU   r   model)	r   	repo_typefolder_pathr   r   r   r   r   r   N)r   create_repor   r   r   r   upload_folder)r   r   rU   r   r   r   r   r   r   r   r   r   apitmp
saved_pathr+   r+   r,   r   x  s"   
4$zModelHubMixin.push_to_hubc                 O   s4   t jd| jj| jj| jj| jj| jjd|}|S )N)	card_datatemplate_strr6   r5   r4   r+   )r   from_templater8   r3   r2   r6   r5   r4   )r   rw   rx   cardr+   r+   r,   r     s   z!ModelHubMixin.generate_model_card)(r&   r'   r(   __doc__r7   r   r   ra   r$   r*   r1   boolr
   r)   rI   rJ   r   r   r   CODER_TrZ   r   rW   r-   ro   classmethodrL   rN   r0   r   r   r   r   r!   r   rf   r   r   r   __classcell__r+   r+   rh   r,   r.   L   sH  
 m



\6 
	
D
	
{	
.	
Fc                       s   e Zd ZdZdddeee  ddf fddZdeddfd	d
Z	e
ddddedee deeeef  dedee dee dedeeedf dedefddZe
dededededef
ddZe
dededededef
ddZ  ZS ) PyTorchModelHubMixina~  
    Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model
    is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model,
    you should first set it back in training mode with `model.train()`.

    See [`ModelHubMixin`] for more details on how to use the mixin.

    Example:

    ```python
    >>> import torch
    >>> import torch.nn as nn
    >>> from huggingface_hub import PyTorchModelHubMixin

    >>> class MyModel(
    ...         nn.Module,
    ...         PyTorchModelHubMixin,
    ...         library_name="keras-nlp",
    ...         repo_url="https://github.com/keras-team/keras-nlp",
    ...         paper_url="https://arxiv.org/abs/2304.12244",
    ...         docs_url="https://keras.io/keras_nlp/",
    ...         # ^ optional metadata to generate model card
    ...     ):
    ...     def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
    ...         super().__init__()
    ...         self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
    ...         self.linear = nn.Linear(output_size, vocab_size)

    ...     def forward(self, x):
    ...         return self.linear(x + self.param)
    >>> model = MyModel(hidden_size=256)

    # Save model weights to local directory
    >>> model.save_pretrained("my-awesome-model")

    # Push model weights to the Hub
    >>> model.push_to_hub("my-awesome-model")

    # Download and initialize weights from the Hub
    >>> model = MyModel.from_pretrained("username/my-awesome-model")
    >>> model.hidden_size
    256
    ```
    N)rD   rD   rF   c                   s,   |pg }| d ||d< t j|i |S )Npytorch_model_hub_mixinrD   )rX   rV   rW   )rS   rD   rw   rx   rh   r+   r,   rW     s   
z&PyTorchModelHubMixin.__init_subclass__r   c                 C   s,   t | dr| jn| }t|t|tj  dS )z7Save weights from a Pytorch model to a local directory.moduleN)rY   r   save_model_as_safetensorr)   r   SAFETENSORS_SINGLE_FILE)r   r   model_to_saver+   r+   r,   r     s   z%PyTorchModelHubMixin._save_pretrainedcpuF)map_locationstrictr   r   r   r   r   r   r   r   r   r   c       
         K   s   | di |}t j|r!td t j|tj}| |||	|
S zt|tj|||||||d	}| |||	|
W S  t	yW   t|tj
|||||||d	}| |||	|
 Y S w )z<Load Pytorch pretrained weights and return the loaded model.z$Loading weights from local directoryr   Nr+   )r   r   r   printr   r   r   _load_as_safetensorr   r   PYTORCH_WEIGHTS_NAME_load_as_pickle)rS   r   r   r   r   r   r   r   r   r   r   r   r   
model_filer+   r+   r,   rf     s@   z%PyTorchModelHubMixin._from_pretrainedr   r   c                 C   s0   t j|t |dd}|j||d |  |S )NT)r   weights_onlyr   )torchr   deviceload_state_dicteval)rS   r   r   r   r   
state_dictr+   r+   r,   r   6  s   z$PyTorchModelHubMixin._load_as_picklec                 C   s`   t jtjt jdk r$t|||d |dkr"td || |S tj	j
||||d |S )Nz0.4.3r   r   a0  Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors. This means that the model is loaded on 'cpu' first and then copied to the device. This leads to a slower loading time. Please update safetensors to version 0.4.3 or above for improved performance.)r   r   )	packagingversionparsesafetensors__version__load_model_as_safetensorr   r   tor   r"   )rS   r   r   r   r   r+   r+   r,   r   =  s   
z(PyTorchModelHubMixin._load_as_safetensor)r&   r'   r(   r   r   r   r)   rW   r   r   r   r   r   r
   rf   r-   r   r   r   r+   r+   rh   r,   r     s@    $-	
1 (r   dataclsdatarF   c                    s     di  fdd|  D S )zhLoad a dataclass instance from a dictionary.

    Fields not expected by the dataclass are ignored.
    c                    s    i | ]\}}| j v r||qS r+   )r%   )rP   kvr   r+   r,   rT   S  s     z#_load_dataclass.<locals>.<dictcomp>Nr+   )rs   )r   r   r+   r   r,   r   N  s    r   )CrI   r   r   dataclassesr   r   r   r   pathlibr   typingr   r   r	   r
   r   r   r   r   r   r   r   packaging.versionr    r   errorsr   r   file_downloadr   hf_apir   repocardr   r   utilsr   r   r   r   r   r   r    r!   r   r   safetensors.torchr"   r   r#   r   
get_loggerr&   r   r$   r-   r0   	ENCODER_T	DECODER_Tr   rZ   r1   r.   r   ra   r   r+   r+   r+   r,   <module>   sL    4(
      