Ë
    °ëjäl  ã                   óÔ  — d Z ddlZ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
 ddlmZmZmZmZmZmZmZmZ ddlmZmZ d	d
lmZmZmZ  ej6                  e«      ZerddlZddeddddœdddeee
f   dee   de dee!ef   deeeef      de deee      fd„Z"ddeddddœdeedf   deee
f   dee   de dee!ef   deeeef      de deee      ddfd„Z#ejH                  edœdeedf   dedee!ef   defd„Z%dddee!eedf   f   fd„Z&dddeed ee!eedf   f   e!f      fd!„Z'ddde!fd"„Z( e«       d2d#„«       Z)dddee!eedf   f   fd$„Z*	 	 d3deedf   deeef   de deee      fd%„Z+ddde!fd&„Z,d'eee      deedf   deee      fd(„Z-deedf   deee      fd)„Z.ddde fd*„Z/ddd+œdeedf   d,eee      d-eee      deeee   f   fd.„Z0 e«       d/d0de!fd1„«       Z1y)4z"Contains pytorch-specific helpers.é    N)Údefaultdict)Ú	lru_cache)ÚPath)ÚTYPE_CHECKINGÚAnyÚDictÚListÚOptionalÚSetÚTupleÚUnioné   )Ú	constantsÚloggingé   )ÚMAX_SHARD_SIZEÚStateDictSplitÚ$split_state_dict_into_shards_factoryT)Úfilename_patternÚforce_contiguousÚmax_shard_sizeÚmetadataÚsafe_serializationÚshared_tensors_to_discardÚmodelztorch.nn.ModuleÚsave_directoryr   r   r   r   r   r   c          
      óF   — t        | j                  «       |||||||¬«       y)a«  
    Saves a given torch model to disk, handling sharding and shared tensors issues.

    See also [`save_torch_state_dict`] to save a state dict with more flexibility.

    For more information about tensor sharing, check out [this guide](https://huggingface.co/docs/safetensors/torch_shared_tensors).

    The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
    saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
    an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
    [`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
    safetensors (the default). Otherwise, the shards are saved as pickle.

    Before saving the model, the `save_directory` is cleaned from any previous shard files.

    <Tip warning={true}>

    If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
    size greater than `max_shard_size`.

    </Tip>

    <Tip warning={true}>

    If your model is a `transformers.PreTrainedModel`, you should pass `model._tied_weights_keys` as `shared_tensors_to_discard` to properly handle shared tensors saving. This ensures the correct duplicate tensors are discarded during saving.

    </Tip>

    Args:
        model (`torch.nn.Module`):
            The model to save on disk.
        save_directory (`str` or `Path`):
            The directory in which the model will be saved.
        filename_pattern (`str`, *optional*):
            The pattern to generate the files names in which the model will be saved. Pattern must be a string that
            can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
            Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
            parameter.
        force_contiguous (`boolean`, *optional*):
            Forcing the state_dict to be saved as contiguous tensors. This has no effect on the correctness of the
            model, but it could potentially change performance if the layout of the tensor was chosen specifically for
            that reason. Defaults to `True`.
        max_shard_size (`int` or `str`, *optional*):
            The maximum size of each shard, in bytes. Defaults to 5GB.
        metadata (`Dict[str, str]`, *optional*):
            Extra information to save along with the model. Some metadata will be added for each dropped tensors.
            This information will not be enough to recover the entire shared structure but might help understanding
            things.
        safe_serialization (`bool`, *optional*):
            Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
            Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
            in a future version.
        shared_tensors_to_discard (`List[str]`, *optional*):
            List of tensor names to drop when saving shared tensors. If not provided and shared tensors are
            detected, it will drop the first name alphabetically.

    Example:

    ```py
    >>> from huggingface_hub import save_torch_model
    >>> model = ... # A PyTorch model

    # Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
    >>> save_torch_model(model, "path/to/folder")

    # Load model back
    >>> from huggingface_hub import load_torch_model  # TODO
    >>> load_torch_model(model, "path/to/folder")
    >>>
    ```
    )Ú
state_dictr   r   r   r   r   r   r   N)Úsave_torch_state_dictr   )r   r   r   r   r   r   r   r   s           úq/home/oem/CyberBrain26-unified/dev-env/.venv/lib/python3.12/site-packages/huggingface_hub/serialization/_torch.pyÚsave_torch_modelr!   #   s.   € ôd Ø×#Ñ#Ó%Ø)Ø)Ø%ØØ-Ø%Ø";ö	ó    r   ztorch.TensorÚreturnc          	      óÖ  — t        |«      }|€"|rt        j                  nt        j                  }|€i }|r	 ddlm} t        | |||¬«      } nddlm	} t        j                  d«       t        | ||¬«      }
t        j                  |j                  d	¬
«      dz   «      }t!        j"                  |«      D ]a  }|j%                  |«      sŒ	 t        j'                  d|› d�«       t!        j(                  t         j*                  j-                  ||«      «       Œc ddi}|
j0                  s|j3                  |«       |rd|ini }|
j4                  j7                  «       D ]X  \  }}|D �ci c]  }|| |   “Œ
 }} ||t         j*                  j-                  ||«      fi |¤Ž t        j'                  d|› �«       ŒZ |
j0                  r¯|j                  d¬
«      dz   }i |
j8                  ¥|¥|
j:                  dœ}t=        t         j*                  j-                  ||«      d«      5 }t?        j@                  ||d¬«       ddd«       t        jC                  d|› dtE        |
j4                  «      › d|› d�«       t        jC                  d|› d �«       y# t        $ r}	t        d«      |	‚d}	~	ww xY w# t.        $ r'}	t        j                  d|› d|	› d�«       Y d}	~	�Œd}	~	ww xY wc c}w # 1 sw Y   ŒªxY w)!ae  
    Save a model state dictionary to the disk, handling sharding and shared tensors issues.

    See also [`save_torch_model`] to directly save a PyTorch model.

    For more information about tensor sharing, check out [this guide](https://huggingface.co/docs/safetensors/torch_shared_tensors).

    The model state dictionary is split into shards so that each shard is smaller than a given size. The shards are
    saved in the `save_directory` with the given `filename_pattern`. If the model is too big to fit in a single shard,
    an index file is saved in the `save_directory` to indicate where each tensor is saved. This helper uses
    [`split_torch_state_dict_into_shards`] under the hood. If `safe_serialization` is `True`, the shards are saved as
    safetensors (the default). Otherwise, the shards are saved as pickle.

    Before saving the model, the `save_directory` is cleaned from any previous shard files.

    <Tip warning={true}>

    If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
    size greater than `max_shard_size`.

    </Tip>

    <Tip warning={true}>

    If your model is a `transformers.PreTrainedModel`, you should pass `model._tied_weights_keys` as `shared_tensors_to_discard` to properly handle shared tensors saving. This ensures the correct duplicate tensors are discarded during saving.

    </Tip>

    Args:
        state_dict (`Dict[str, torch.Tensor]`):
            The state dictionary to save.
        save_directory (`str` or `Path`):
            The directory in which the model will be saved.
        filename_pattern (`str`, *optional*):
            The pattern to generate the files names in which the model will be saved. Pattern must be a string that
            can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
            Defaults to `"model{suffix}.safetensors"` or `pytorch_model{suffix}.bin` depending on `safe_serialization`
            parameter.
        force_contiguous (`boolean`, *optional*):
            Forcing the state_dict to be saved as contiguous tensors. This has no effect on the correctness of the
            model, but it could potentially change performance if the layout of the tensor was chosen specifically for
            that reason. Defaults to `True`.
        max_shard_size (`int` or `str`, *optional*):
            The maximum size of each shard, in bytes. Defaults to 5GB.
        metadata (`Dict[str, str]`, *optional*):
            Extra information to save along with the model. Some metadata will be added for each dropped tensors.
            This information will not be enough to recover the entire shared structure but might help understanding
            things.
        safe_serialization (`bool`, *optional*):
            Whether to save as safetensors, which is the default behavior. If `False`, the shards are saved as pickle.
            Safe serialization is recommended for security reasons. Saving as pickle is deprecated and will be removed
            in a future version.
        shared_tensors_to_discard (`List[str]`, *optional*):
            List of tensor names to drop when saving shared tensors. If not provided and shared tensors are
            detected, it will drop the first name alphabetically.

    Example:

    ```py
    >>> from huggingface_hub import save_torch_state_dict
    >>> model = ... # A PyTorch model

    # Save state dict to "path/to/folder". The model will be split into shards of 5GB each and saved as safetensors.
    >>> state_dict = model_to_save.state_dict()
    >>> save_torch_state_dict(state_dict, "path/to/folder")
    ```
    Nr   )Ú	save_filezjPlease install `safetensors` to use safe serialization. You can install it with `pip install safetensors`.)r   r   )Úsavea  You are using unsafe serialization. Due to security reasons, it is recommended not to load pickled models from untrusted sources. If you intend to share your model, we strongly recommend using safe serialization by installing `safetensors` with `pip install safetensors`.©r   r   z(-\d{5}-of-\d{5})?)Úsuffixz(\.index\.json)?zRemoving existing file 'z' from folder.z&Error when trying to remove existing 'z' from folder: z. Continuing...ÚformatÚptr   zShard saved to Ú z.index.json)r   Ú
weight_mapÚwr   )Úindentz:The model is bigger than the maximum size per checkpoint (z#). Model weighs have been saved in z^ checkpoint shards. You can find where each parameters has been saved in the index located at ú.z$Model weights successfully saved to ú!)#Ústrr   Ú SAFETENSORS_WEIGHTS_FILE_PATTERNÚPYTORCH_WEIGHTS_FILE_PATTERNÚsafetensors.torchr%   ÚImportErrorÚ!_clean_state_dict_for_safetensorsÚtorchr&   ÚloggerÚwarningÚ"split_torch_state_dict_into_shardsÚreÚcompiler)   ÚosÚlistdirÚmatchÚdebugÚremoveÚpathÚjoinÚ	ExceptionÚ
is_shardedÚupdateÚfilename_to_tensorsÚitemsr   Útensor_to_filenameÚopenÚjsonÚdumpÚinfoÚlen)r   r   r   r   r   r   r   r   Úsave_file_fnÚeÚstate_dict_splitÚexisting_files_regexÚfilenameÚper_file_metadataÚsafe_file_kwargsÚtensorsÚtensorÚshardÚ
index_pathÚindexÚfs                        r    r   r   �   s  € ô\ ˜Ó(€NàÐñ "ô ×6Ò6ä×7Ñ7ð 	ð ÐØˆÙð	ÝCô 7ØØØ-Ø&?ô	
‰
õ 	/ä�‰ðcô	
ô :ØÐ%5ÀnôÐô
 Ÿ:™:Ð&6×&=Ñ&=ÐEZÐ&=Ó&[Ð^qÑ&qÓrÐÜ—J‘J˜~Ó.ò uˆØ×%Ñ% hÕ/ðuÜ—‘Ð7¸°zÀÐPÔQÜ—	‘	œ"Ÿ'™'Ÿ,™, ~°xÓ@ÕAð	uð " 4Ð(ÐØ×&Ò&Ø× Ñ  Ô*Ù:L˜
Ð$5Ñ6ÐRTÐØ-×AÑA×GÑGÓIò 3Ñˆ�'Ø:AÖB°�˜ FÑ+Ñ+ÐBˆÐBÙ�UœBŸG™GŸL™L¨¸ÓBÑWÐFVÒWÜ�‰� x jÐ1Õ2ð3ð ×"Ò"Ø%×,Ñ,°BÐ,Ó7¸-ÑGˆ
àAÐ+×4Ñ4ÐA¸ÐAØ*×=Ñ=ñ
ˆô ”"—'‘'—,‘,˜~¨zÓ:¸CÓ@ð 	*ÀAÜ�I‰I�e˜Q qÕ)÷	*ä�‰ØHÈÐHXð Y/Ü/2Ð3C×3WÑ3WÓ/XÐ.Yð ZYØYcÐXdÐdeðgô	
ô ‡K�KÐ6°~Ð6FÀaÐHÕIøôy ò 	ÜðEóð ðûð	ûô@ ò uÜ—‘Ð!GÈÀzÐQ`ÐabÐ`cÐcrÐs×tÒtûðuüò C÷	*ð 	*úsB   ·J
 Ã	AJ'Å$KÈKÊ
	J$ÊJÊJ$Ê'	KÊ0KËKËK(r'   c                ó2   — t        | ||t        t        ¬«      S )a>
  
    Split a model state dictionary in shards so that each shard is smaller than a given size.

    The shards are determined by iterating through the `state_dict` in the order of its keys. There is no optimization
    made to make each shard as close as possible to the maximum size passed. For example, if the limit is 10GB and we
    have tensors of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not
    [6+2+2GB], [6+2GB], [6GB].


    <Tip>

    To save a model state dictionary to the disk, see [`save_torch_state_dict`]. This helper uses
    `split_torch_state_dict_into_shards` under the hood.

    </Tip>

    <Tip warning={true}>

    If one of the model's tensor is bigger than `max_shard_size`, it will end up in its own shard which will have a
    size greater than `max_shard_size`.

    </Tip>

    Args:
        state_dict (`Dict[str, torch.Tensor]`):
            The state dictionary to save.
        filename_pattern (`str`, *optional*):
            The pattern to generate the files names in which the model will be saved. Pattern must be a string that
            can be formatted with `filename_pattern.format(suffix=...)` and must contain the keyword `suffix`
            Defaults to `"model{suffix}.safetensors"`.
        max_shard_size (`int` or `str`, *optional*):
            The maximum size of each shard, in bytes. Defaults to 5GB.

    Returns:
        [`StateDictSplit`]: A `StateDictSplit` object containing the shards and the index to retrieve them.

    Example:
    ```py
    >>> import json
    >>> import os
    >>> from safetensors.torch import save_file as safe_save_file
    >>> from huggingface_hub import split_torch_state_dict_into_shards

    >>> def save_state_dict(state_dict: Dict[str, torch.Tensor], save_directory: str):
    ...     state_dict_split = split_torch_state_dict_into_shards(state_dict)
    ...     for filename, tensors in state_dict_split.filename_to_tensors.items():
    ...         shard = {tensor: state_dict[tensor] for tensor in tensors}
    ...         safe_save_file(
    ...             shard,
    ...             os.path.join(save_directory, filename),
    ...             metadata={"format": "pt"},
    ...         )
    ...     if state_dict_split.is_sharded:
    ...         index = {
    ...             "metadata": state_dict_split.metadata,
    ...             "weight_map": state_dict_split.tensor_to_filename,
    ...         }
    ...         with open(os.path.join(save_directory, "model.safetensors.index.json"), "w") as f:
    ...             f.write(json.dumps(index, indent=2))
    ```
    )r   r   Úget_storage_sizeÚget_storage_id)r   Úget_torch_storage_sizeÚget_torch_storage_id)r   r   r   s      r    r:   r:     s!   € ôF 0ØØ%Ø)Ü/Ü+ôð r"   rW   .c                 ó2  ‡ — 	 ddl m}  |‰ «      r'‰ j                  «       \  }}t        ˆ fd„|D «       «      S 	 ‰ j
                  j                  dk(  r+t        «       r!ddl}|j                  j                  ‰ «      }|S t        ‰ «      }|S # t        $ r Y Œ\w xY w)z¨Returns a unique id for plain tensor
    or a (potentially nested) Tuple of unique id for the flattened Tensor
    if the input is a wrapper tensor subclass Tensor
    r   ©Úis_traceable_wrapper_subclassc              3   óH   •K  — | ]  }t        t        ‰|«      «      –— Œ y ­w©N)Ú_get_unique_idÚgetattr©Ú.0ÚattrrW   s     €r    ú	<genexpr>z!_get_unique_id.<locals>.<genexpr>t  s   øè ø€ ÒQÀ4œ¬°¸Ó(=×>ÑQùó   ƒ"ÚxlaN)Útorch.utils._python_dispatchrc   Ú__tensor_flatten__Útupler5   ÚdeviceÚtypeÚis_torch_tpu_availableÚ	torch_xlaÚ_XLACÚ_xla_get_tensor_idÚstorage_ptr)rW   rc   ÚattrsÚ_rt   Ú	unique_ids   `     r    rf   rf   h  sœ   ø€ ð
åNá(¨Ô0Ø×0Ñ0Ó2‰HˆE�1ÜÓQÈ5ÔQÓQÐQð 1ð ‡}�}×Ñ˜UÒ"Ô'=Ô'?ó
 	à—O‘O×6Ñ6°vÓ>ˆ	ð Ðô   Ó'ˆ	àÐøô ò áðús   ƒ4B
 Â
	BÂBztorch.devicec                 óx   — | j                   j                  dk(  ry| j                   t        | «      t        | «      fS )a,  
    Return unique identifier to a tensor storage.

    Multiple different tensors can share the same underlying storage. This identifier is
    guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with
    non-overlapping lifetimes may have the same id.
    In the case of meta tensors, we return None since we can't tell if they share the same storage.

    Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/pytorch_utils.py#L278.
    ÚmetaN)rq   rr   rf   r_   )rW   s    r    r`   r`   ˆ  s5   € ð ‡}�}×Ñ˜VÒ#Øà�}‰}œn¨VÓ4Ô6LÈVÓ6TÐTÐTr"   c                 óÄ  ‡ — 	 ddl m}  |‰ «      r'‰ j                  «       \  }}t        ˆ fd„|D «       «      S 	 	 ‰ j                  «       j                  «       S # t        $ r Y Œ*w xY w# t        $ ro 	 ‰ j                  «       j                  «       t        ‰ j                  «      z  cY S # t        $ r+ ‰ j                  «       t        ‰ j                  «      z  cY cY S w xY ww xY w)z¦
    Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L31C1-L41C59
    r   rb   c              3   óH   •K  — | ]  }t        t        ‰|«      «      –— Œ y ­wre   )r_   rg   rh   s     €r    rk   z)get_torch_storage_size.<locals>.<genexpr>£  s   øè ø€ ÒWÈÔ-¬g°f¸dÓ.C×DÑWùrl   )rn   rc   ro   Úsumr5   Úuntyped_storageÚnbytesÚAttributeErrorÚstorageÚsizeÚ_get_dtype_sizeÚdtypeÚNotImplementedErrorÚnelement©rW   rc   rx   ry   s   `   r    r_   r_   ™  sØ   ø€ ð	åNá(¨Ô0Ø×0Ñ0Ó2‰HˆE�1ÜÓWÐQVÔWÓWÐWð 1ð	EØ×%Ñ%Ó'×.Ñ.Ó0Ð0øô ò áðûô ò Eð	EØ—>‘>Ó#×(Ñ(Ó*¬_¸V¿\¹\Ó-JÑJÒJøÜ"ò 	Eð —?‘?Ó$¤°v·|±|Ó'DÑDÔDð	Eúð	Eús@   ƒ4A ºA' Á	A$Á#A$Á'	CÁ13B'Â$CÂ'/CÃCÃCÃCc                 óœ   — t         j                  j                  d«      �| r	 ddlmc m} |j                  «       }yyy# t        $ r Y yw xY w)zò
    Checks if `torch_xla` is installed and potentially if a TPU is in the environment

    Taken from https://github.com/huggingface/transformers/blob/1ecf5f7c982d761b4daaa96719d162c324187c64/src/transformers/utils/import_utils.py#L463.
    rt   Nr   TF)Ú	importlibÚutilÚ	find_specÚtorch_xla.core.xla_modelÚcoreÚ	xla_modelÚ
xla_deviceÚRuntimeError)Úcheck_deviceÚxmry   s      r    rs   rs   ´  sQ   € ô ‡~�~×Ñ Ó,Ð8Ùðß5Ð5à—M‘M“O�Øð Øøô  ò Ùðús   £? ¿	AÁ
Ac                 ó  — 	 ddl m}  || «      rt        | «      S 	 	 | j	                  «       j                  «       S # t        $ r Y Œ*w xY w# t        $ r2 	 | j                  «       j                  «       cY S # t        $ r Y Y yw xY ww xY w)zž
    Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L11.
    r   rb   )	rn   rc   rf   r5   r€   Údata_ptrrD   rƒ   r‡   )rW   rc   s     r    rw   rw   É  s�   € ðåNá(¨Ô0Ü! &Ó)Ð)ð 1ðØ×%Ñ%Ó'×0Ñ0Ó2Ð2øô ò áðûô ò ð	Ø—>‘>Ó#×,Ñ,Ó.Ò.øÜ"ò 	âð	úð	ús>   ‚; �A
 »	AÁAÁ
	BÁA4Á1BÁ4	BÁ=BÂ BÂBc                 óð   — t        | |¬«      }|j                  «       D ]  \  }}|D ]  }|€i }||vr|||<   | |= Œ Œ |r1| j                  «       D ��	ci c]  \  }}	||	j                  «       “Œ } }}	| S c c}	}w )a6  Remove shared tensors from state_dict and update metadata accordingly (for reloading).

    Warning: `state_dict` and `metadata` are mutated in-place!

    Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L155.
    )Údiscard_names)Ú_remove_duplicate_namesrH   Ú
contiguous)
r   r   r   r   Ú
to_removesÚ	kept_nameÚto_remove_groupÚ	to_removeÚkÚvs
             r    r6   r6   â  sž   € ô )¨ÐC\Ô]€JØ&0×&6Ñ&6Ó&8ò &Ñ"ˆ	�?Ø(ò 	&ˆIØÐØ�à Ñ(à&/�˜Ñ#Ø˜9Ñ%ñ	&ð&ñ Ø4>×4DÑ4DÓ4F×G©D¨A¨q�a˜Ÿ™›Ñ'ÐGˆ
ÑGØÐùó Hs   ÁA2c                 óº   — | j                  «       r:| j                  d«      d   j                  «       t        | j                  «      z   }|S | j                  «       }|S )zž
    Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L23.
    éÿÿÿÿ)rˆ   Úviewr–   r…   r†   )rW   Ústops     r    Ú_end_ptrr¥   ý  sQ   € ð ‡�ÔØ�{‰{˜2‹˜rÑ"×+Ñ+Ó-´ÀÇÁÓ0MÑMˆð €Kð �‰Ó ˆØ€Kr"   rV   c                 ó˜  — g }| D ]Â  }t        |«      dk  r|j                  |«       Œ#g }|D ]2  }||   }|j                  |j                  «       t        |«      |f«       Œ4 |j	                  «        |d   \  }}}	|j                  |	h«       |dd D ]4  \  }
}}|
|k\  r|j                  |h«       n|d   j                  |«       |}Œ6 ŒÄ |S )z�
    Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L44
    r   r   r   Nr¢   )rN   Úappendr–   r¥   ÚsortÚadd)rV   r   Úfiltered_tensorsÚsharedÚareasÚnamerW   ry   Ú	last_stopÚ	last_nameÚstartr¤   s               r    Ú_filter_shared_not_sharedr±     só   € ð ÐØò ˆÜˆv‹;˜Š?Ø×#Ñ# FÔ+ØàˆØò 	FˆDØ Ñ%ˆFØ�L‰L˜&Ÿ/™/Ó+¬X°fÓ-=¸tÐDÕEð	Fð 	�
‰
Œà"'¨¡(Ñˆˆ9�iØ×Ñ  Ô,Ø!& q r ò 	ÑˆE�4˜Ø˜	Ò!Ø ×'Ñ'¨¨Õ/à  Ñ$×(Ñ(¨Ô.Ø‰Iñ	ðð( Ðr"   c                 óš  — ddl }t        t        «      }| j                  «       D ]v  \  }}|j                   |j                  d«      k7  sŒ&t        |«      dk7  sŒ5t        |«      dk7  sŒD||j                  t        |«      t        |«      f   j                  |«       Œx t        t        |j                  «       «      «      }t        || «      }|S )zž
    Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L69.
    r   Nr|   )r7   r   ÚsetrH   rq   rw   r_   r©   ÚlistÚsortedÚvaluesr±   )r   r7   Útensors_dictrŸ   r    rV   s         r    Ú_find_shared_tensorsr¸   $  s´   € ó äœsÓ#€LØ× Ñ Ó"ò W‰ˆˆ1Ø�8‰8�|�u—|‘| FÓ+Ó+´¸A³À!Ó0CÔH^Ð_`ÓHaÐefÓHfà˜!Ÿ(™(¤K°£NÔ4JÈ1Ó4MÐNÑO×SÑSÐTUÕVðWô ”6˜,×-Ñ-Ó/Ó0Ó1€GÜ'¨°Ó<€GØ€Nr"   c                 ó0  ‡ — 	 ddl m}  |‰ «      r'‰ j                  «       \  }}t        ˆ fd„|D «       «      S 	 ‰ j                  «       t        ‰ «      k(  xr2 ‰ j                  «       t        ‰ j                  «      z  t        ‰ «      k(  S # t        $ r Y Œ[w xY w)ú�
    Taken from https://github.com/huggingface/safetensors/blob/079781fd0dc455ba0fe851e2b4507c33d0c0d407/bindings/python/py_src/safetensors/torch.py#L80
    r   rb   c              3   óH   •K  — | ]  }t        t        ‰|«      «      –— Œ y ­wre   )Ú_is_completerg   rh   s     €r    rk   z_is_complete.<locals>.<genexpr>>  s   øè ø€ ÒM¸t”|¤G¨F°DÓ$9×:ÑMùrl   )rn   rc   ro   Úallr5   r–   rw   rˆ   r…   r†   r_   r‰   s   `   r    r¼   r¼   4  s™   ø€ ð	åNá(¨Ô0Ø×0Ñ0Ó2‰HˆE�1ÜÓMÀuÔMÓMÐMð 1ð �?‰?Ó¤¨FÓ 3Ñ3ò (¸¿¹Ó8IÌOØ�‰óMñ 9ä	 Ó	'ñ9(ð (øô	 ò áðús   ƒ4B	 Â		BÂB)Úpreferred_namesr˜   r¾   r˜   c          
      ó.  — |€g }t        |«      }|€g }t        |«      }t        | «      }t        t        «      }|D ]Ò  }t        |D �cg c]  }t	        | |   «      sŒ|‘Œ c}«      }	|	st        d|› d�«      ‚t        t        |	«      «      d   }
|	j                  |«      }|rt        t        |«      «      d   }
|r*|j                  |	«      }|rt        t        |«      «      d   }
t        |«      D ]  }||
k7  sŒ	||
   j                  |«       Œ ŒÔ |S c c}w )rº   zvError while trying to find names to remove to save state dict, but found no suitable name to keep for saving amongst: zô. None is covering the entire storage. Refusing to save/load the model since you could be storing much more memory than needed. Please refer to https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an issue.r   )
r³   r¸   r   r´   r¼   r’   rµ   Ú
differenceÚintersectionr§   )r   r¾   r˜   Úunique_preferred_namesÚunique_discard_namesÚsharedsrž   r«   r­   Úcomplete_namesÚ	keep_nameÚ	preferreds               r    r™   r™   H  s=  € ð ÐØˆÜ  Ó1ÐØÐØˆÜ˜}Ó-Ðä" :Ó.€GÜœDÓ!€IØò 2ˆÜ¨vÖX t¼ÀjÐQUÑFVÕ9WšdÒXÓYˆÙÜð(Ø(. xð 0ðóð ô œ4 Ó/Ó0°Ñ3ˆ	ð #×-Ñ-Ð.BÓCˆ	ÙÜœt I›Ó/°Ñ2ˆIá!Ø.×;Ñ;¸NÓKˆIÙÜ"¤4¨	£?Ó3°AÑ6�	Ü˜6“Nò 	2ˆDØ�yÓ Ø˜)Ñ$×+Ñ+¨DÕ1ñ	2ð32ð8 Ðùò7 Ys   ÁD
ÁD
r†   ztorch.dtypec                 óD  — ddl }t        |dd«      }t        |dd«      }|j                  d|j                  d|j                  d|j
                  d|j                  d|j                  d|j                  d|j                  d|j                  d|j                  d|d|di}||    S )	zž
    Taken from https://github.com/huggingface/safetensors/blob/08db34094e9e59e2f9218f2df133b7b4aaff5a99/bindings/python/py_src/safetensors/torch.py#L344
    r   NÚfloat8_e4m3fnÚfloat8_e5m2é   é   r   r   )r7   rg   Úint64Úfloat32Úint32Úbfloat16Úfloat16Úint16Úuint8Úint8ÚboolÚfloat64)r†   r7   Ú_float8_e4m3fnÚ_float8_e5m2Ú_SIZEs        r    r…   r…   y  sœ   € ó
 ô ˜U O°TÓ:€NÜ˜5 -°Ó6€Là�‰�QØ�‰�qØ�‰�QØ�‰˜Ø�‰�qØ�‰�QØ�‰�QØ�
‰
�AØ�
‰
�AØ�‰�qØ˜Ø�að€Eð �‰<Ðr"   )T)TN)2Ú__doc__r‹   rK   r=   r;   Úcollectionsr   Ú	functoolsr   Úpathlibr   Útypingr   r   r   r	   r
   r   r   r   r+   r   r   Ú_baser   r   r   Ú
get_loggerÚ__file__r8   r7   r1   rÕ   Úintr!   r   r2   r:   rf   r`   r_   rs   rw   r6   r¥   r±   r¸   r¼   r™   r…   © r"   r    ú<module>rä      sø  ðñ )ã Û Û 	Û 	Ý #Ý Ý ß N× NÓ Nç !ß WÑ Wð 
ˆ×	Ñ	˜HÓ	%€áÛð '+Ø!Ø&4Ø)-Ø#Ø59ò[Øð[à˜#˜t˜)Ñ$ð[ð ˜s‘mð	[ð
 ð[ð ˜#˜s˜(‘Oð[ð �t˜C ˜H‘~Ñ&ð[ð ð[ð  (¨¨S©	Ñ2ó[ðD '+Ø!Ø&4Ø)-Ø#Ø59òXJØ�S˜.Ð(Ñ)ðXJà˜#˜t˜)Ñ$ðXJð ˜s‘mð	XJð
 ðXJð ˜#˜s˜(‘OðXJð �t˜C ˜H‘~Ñ&ðXJð ðXJð  (¨¨S©	Ñ2ðXJð 
óXJð| &×FÑFØ&4ò	IØ�S˜.Ð(Ñ)ðIð ðIð ˜#˜s˜(‘Oð	Ið
 óIðX˜>ð ¨e°C¸¸sÀC¸x¹Ð4HÑ.Ió ð@U ð U°H¸UÀ>ÐSXÐY\Ð^cÐdgÐilÐdlÑ^mÐYmÑSnÐpsÐCsÑ=tÑ4uó Uð"E >ð E°có Eñ6 ƒòó ðð(˜ð ¨5°°e¸CÀ¸H±oÐ1EÑ+Fó ð8 "Ø59ñ	Ø�S˜.Ð(Ñ)ðà�3˜�8‰nðð ðð  (¨¨S©	Ñ2ó	ð6�^ð ¨ó ð t¨C°©H¡~ð À4ÈÈ^ÐH[ÑC\ð ÐaeÐfiÐjmÑfnÑaoó ð8 T¨#¨~Ð*=Ñ%>ð À4ÈÈCÉÁ>ó ð (˜ð (¨Dó (ð. ,0Ø)-ò	.Ø�S˜.Ð(Ñ)ð.ð ˜d 3™iÑ(ð.ð ˜D ™IÑ&ð	.ð
 
ˆ#ˆt�C‰yˆ.Ñó.ñb ƒð˜=ð ¨Sò ó ñr"   