o
    shj0                    @   s  d dl Z d dlZd dlZd dlZd dlZd dl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 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 Z d dl!mZ" d dl#Z#d dl$m%Z% d dlm&Z& d d	l 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l0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZG eHeIZJG dd de)jKe8ZLdS )    N)OrderedDict)contextmanager)Queue)Path)AnyCallableDictIterableIteratorListLiteralOptionalTupleUnionoverload)HfApi)ndarray)Tensordevicenn)trange)is_torch_npu_available) SentenceTransformerModelCardDatagenerate_model_card)SimilarityFunction   )__MODEL_HUB_ORGANIZATION____version__)SentenceEvaluator)FitMixin)	NormalizePoolingTransformer)quantize_embeddings)batch_to_deviceget_device_nameimport_from_stringis_sentence_transformer_modelload_dir_pathload_file_pathsave_to_hub_args_decoratortruncate_embeddingsc                %       s  e Zd ZdZ																	ddee deeej  dee dee	eef  dee d	ee
eef  d
ee dedee dedee
eef  dee
eef  dee dee	eef  dee	eef  dee	eef  dee ddf$ fddZ										dde
eee f dee dee ded ed!eed"  d#ed$ d%ed&eded'ede
ee eef fd(d)Zedee fd*d+Zejd,e
eef ddfd-d+Zed.ed/edefd0d1Zed.ed/edefd2d1Zedee
eef e
eef gef fd3d1Zed.ed/edefd4d5Zed.ed/edefd6d5Zedee
eef e
eef gef fd7d5Z	dd8ee de	ed9 ef fd:d;Zed<e	ed9 ef ddfd=d>Z						ddee d<e	ed9 ef dee dee ded?ed#ed$ d'ede jfd@dAZ!edBedCd dDe"dEe"ddf
dFdGZ#dHeddfdIdJZ$dee fdKdLZ%dMe
ee ee	 ee&eef  f de	eef fdNdOZ'de	ed e(jf fdPdQZ)dee fdRdSZ*e+dee de,d fdTdUZ-de(jjfdVdWZ.de(jjfdXdYZ/				ddZed[ee d\ed]eee  d^eddfd_d`Z0				ddZed[ee d\ed]eee  d^eddfdadbZ1	cddZed[ee d]eee  ddfdddeZ2e3					f				ddgedhee dee diee d^edjedkee dledmed]eee  defdndoZ4				f				ddgedee diee d^edjedkee dledmed]eee  defdpdqZ5dre
ee eee  f defdsdtZ6ddue7dvede
e	ee8f e8f fdwdxZ9						ddedee
eef  d
ee dee dededee	eef  dee	eef  dee	eef  deej fdydzZ:						ddedee
eef  d
ee dee dededee	eef  dee	eef  dee	eef  de	eejf fd{d|Z;edd}d~Z<ede=fddZ=edefddZ>e>jdddZ>edefddZ?e?jdddZ?ede(j=fddZ@e@jddee
eee(j=f  ddfddZ@edee fddZAedee fddZBddddZC  ZDS )SentenceTransformeray  
    Loads or creates a SentenceTransformer model that can be used to map sentences / text to embeddings.

    Args:
        model_name_or_path (str, optional): If it is a filepath on disc, it loads the model from that path. If it is not a path,
            it first tries to download a pre-trained SentenceTransformer model. If that fails, tries to construct a model
            from the Hugging Face Hub with that name.
        modules (Iterable[nn.Module], optional): A list of torch Modules that should be called sequentially, can be used to create custom
            SentenceTransformer models from scratch.
        device (str, optional): Device (like "cuda", "cpu", "mps", "npu") that should be used for computation. If None, checks if a GPU
            can be used.
        prompts (Dict[str, str], optional): A dictionary with prompts for the model. The key is the prompt name, the value is the prompt text.
            The prompt text will be prepended before any text to encode. For example:
            `{"query": "query: ", "passage": "passage: "}` or `{"clustering": "Identify the main category based on the
            titles in "}`.
        default_prompt_name (str, optional): The name of the prompt that should be used by default. If not set,
            no prompt will be applied.
        similarity_fn_name (str or SimilarityFunction, optional): The name of the similarity function to use. Valid options are "cosine", "dot",
            "euclidean", and "manhattan". If not set, it is automatically set to "cosine" if `similarity` or
            `similarity_pairwise` are called while `model.similarity_fn_name` is still `None`.
        cache_folder (str, optional): Path to store models. Can also be set by the SENTENCE_TRANSFORMERS_HOME environment variable.
        trust_remote_code (bool, optional): Whether or not to allow for custom models defined on the Hub in their own modeling files.
            This option should only be set to True for repositories you trust and in which you have read the code, as it
            will execute code present on the Hub on your local machine.
        revision (str, optional): The specific model version to use. It can be a branch name, a tag name, or a commit id,
            for a stored model on Hugging Face.
        local_files_only (bool, optional): Whether or not to only look at local files (i.e., do not try to download the model).
        token (bool or str, optional): Hugging Face authentication token to download private models.
        use_auth_token (bool or str, optional): Deprecated argument. Please use `token` instead.
        truncate_dim (int, optional): The dimension to truncate sentence embeddings to. `None` does no truncation. Truncation is
            only applicable during inference when :meth:`SentenceTransformer.encode` is called.
        model_kwargs (Dict[str, Any], optional): Additional model configuration parameters to be passed to the Huggingface Transformers model.
            Particularly useful options are:

            - ``torch_dtype``: Override the default `torch.dtype` and load the model under a specific `dtype`.
              The different options are:

                    1. ``torch.float16``, ``torch.bfloat16`` or ``torch.float``: load in a specified
                    ``dtype``, ignoring the model's ``config.torch_dtype`` if one exists. If not specified - the model will
                    get loaded in ``torch.float`` (fp32).

                    2. ``"auto"`` - A ``torch_dtype`` entry in the ``config.json`` file of the model will be
                    attempted to be used. If this entry isn't found then next check the ``dtype`` of the first weight in
                    the checkpoint that's of a floating point type and use that as ``dtype``. This will load the model
                    using the ``dtype`` it was saved in at the end of the training. It can't be used as an indicator of how
                    the model was trained. Since it could be trained in one of half precision dtypes, but saved in fp32.
            - ``attn_implementation``: The attention implementation to use in the model (if relevant). Can be any of
              `"eager"` (manual implementation of the attention), `"sdpa"` (using `F.scaled_dot_product_attention
              <https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention.html>`_),
              or `"flash_attention_2"` (using `Dao-AILab/flash-attention <https://github.com/Dao-AILab/flash-attention>`_).
              By default, if available, SDPA will be used for torch>=2.1.1. The default is otherwise the manual `"eager"`
              implementation.

            See the `PreTrainedModel.from_pretrained
            <https://huggingface.co/docs/transformers/en/main_classes/model#transformers.PreTrainedModel.from_pretrained>`_
            documentation for more details.
        tokenizer_kwargs (Dict[str, Any], optional): Additional tokenizer configuration parameters to be passed to the Huggingface Transformers tokenizer.
            See the `AutoTokenizer.from_pretrained
            <https://huggingface.co/docs/transformers/en/model_doc/auto#transformers.AutoTokenizer.from_pretrained>`_
            documentation for more details.
        config_kwargs (Dict[str, Any], optional): Additional model configuration parameters to be passed to the Huggingface Transformers config.
            See the `AutoConfig.from_pretrained
            <https://huggingface.co/docs/transformers/en/model_doc/auto#transformers.AutoConfig.from_pretrained>`_
            documentation for more details.
        model_card_data (:class:`~sentence_transformers.model_card.SentenceTransformerModelCardData`, optional): A model
            card data object that contains information about the model. This is used to generate a model card when saving
            the model. If not set, a default model card data object is created.

    Example:
        ::

            from sentence_transformers import SentenceTransformer

            # Load a pre-trained SentenceTransformer model
            model = SentenceTransformer('all-mpnet-base-v2')

            # Encode some texts
            sentences = [
                "The weather is lovely today.",
                "It's so sunny outside!",
                "He drove to the stadium.",
            ]
            embeddings = model.encode(sentences)
            print(embeddings.shape)
            # (3, 768)

            # Get the similarity scores between all sentences
            similarities = model.similarity(embeddings, embeddings)
            print(similarities)
            # tensor([[1.0000, 0.6817, 0.0492],
            #         [0.6817, 1.0000, 0.0421],
            #         [0.0492, 0.0421, 1.0000]])
    NFmodel_name_or_pathmodulesr   promptsdefault_prompt_namesimilarity_fn_namecache_foldertrust_remote_coderevisionlocal_files_onlytokenuse_auth_tokentruncate_dimmodel_kwargstokenizer_kwargsconfig_kwargsmodel_card_datareturnc                    s  |pi | _ || _|| _|| _|pt | _i | _d | _i | _|d ur1t	
dt |d ur/td|}|d u r:td}|d u rIt }td| |dkr^tjdd ur^ddlm} |  |d ur|d	krtd
| g d}tj|sd|v s|ddkrtd|d|vr| |vrtd | }t||||	|
dr| j||||	||
|||d	}n| j||||	||
|||d	}|d urt |t!st!dd t"|D }t# $| | %| d| _&| jd ur| j| j vrtd| j dt'| j ( d| j rtt)| j  dt'| j (   | jr"t*d| j d |dv r.| j+dd n#|rQd|v rQd|,dd  v rQt-dd | D rQt*d | j.|  d S ) Nz^The `use_auth_token` argument is deprecated and will be removed in v3 of SentenceTransformers.zV`token` and `use_auth_token` are both specified. Please set only the argument `token`.SENTENCE_TRANSFORMERS_HOMEzUse pytorch device_name: {}hpuoptimumr   )adapt_transformers_to_gaudi z'Load pretrained SentenceTransformer: {})Dzalbert-base-v1zalbert-base-v2zalbert-large-v1zalbert-large-v2zalbert-xlarge-v1zalbert-xlarge-v2zalbert-xxlarge-v1zalbert-xxlarge-v2zbert-base-cased-finetuned-mrpczbert-base-casedzbert-base-chinesezbert-base-german-casedzbert-base-german-dbmdz-casedzbert-base-german-dbmdz-uncasedzbert-base-multilingual-casedzbert-base-multilingual-uncasedzbert-base-uncasedz3bert-large-cased-whole-word-masking-finetuned-squadz#bert-large-cased-whole-word-maskingzbert-large-casedz5bert-large-uncased-whole-word-masking-finetuned-squadz%bert-large-uncased-whole-word-maskingzbert-large-uncasedzcamembert-basectrlz%distilbert-base-cased-distilled-squadzdistilbert-base-casedzdistilbert-base-german-casedz"distilbert-base-multilingual-casedz'distilbert-base-uncased-distilled-squadz/distilbert-base-uncased-finetuned-sst-2-englishzdistilbert-base-uncased
distilgpt2zdistilroberta-basez
gpt2-largezgpt2-mediumzgpt2-xlgpt2z
openai-gptzroberta-base-openai-detectorzroberta-basezroberta-large-mnlizroberta-large-openai-detectorzroberta-largezt5-11bzt5-3bzt5-basezt5-largezt5-smallztransfo-xl-wt103zxlm-clm-ende-1024zxlm-clm-enfr-1024zxlm-mlm-100-1280zxlm-mlm-17-1280zxlm-mlm-en-2048zxlm-mlm-ende-1024zxlm-mlm-enfr-1024zxlm-mlm-enro-1024zxlm-mlm-tlm-xnli15-1024zxlm-mlm-xnli15-1024zxlm-roberta-basez)xlm-roberta-large-finetuned-conll02-dutchz+xlm-roberta-large-finetuned-conll02-spanishz+xlm-roberta-large-finetuned-conll03-englishz*xlm-roberta-large-finetuned-conll03-germanzxlm-roberta-largezxlnet-base-casedzxlnet-large-cased\/r   zPath {} not found)r2   r4   r5   )r6   r2   r4   r3   r5   r9   r:   r;   c                 S   s   g | ]
\}}t ||fqS  )str).0idxmodulerH   rH   g/var/www/html/alpaca_bot/venv/lib/python3.10/site-packages/sentence_transformers/SentenceTransformer.py
<listcomp>8      z0SentenceTransformer.__init__.<locals>.<listcomp>FzDefault prompt name ';' not found in the configured prompts dictionary with keys .z$ prompts are loaded, with the keys: zDefault prompt name is set to 'z'. This prompt will be applied to all `encode()` calls, except if `encode()` is called with `prompt` or `prompt_name` parameters.)zhkunlp/instructor-basezhkunlp/instructor-largezhkunlp/instructor-xl)include_prompt
instructorc                 S   s   g | ]
}t |tr|jqS rH   
isinstancer!   rR   )rJ   rL   rH   rH   rM   rN   Y  rO   zInstructor models require `include_prompt=False` in the pooling configuration. Either update the model configuration or call `model.set_pooling_include_prompt(False)` after loading the model.)/r/   r0   r1   r8   r   r<   _model_card_vars_model_card_text_model_configwarningswarnFutureWarning
ValueErrorosgetenvr%   loggerinfoformat	importlibutil	find_spec*optimum.habana.transformers.modeling_utilsrA   pathexistscountlowerr   r'   _load_sbert_model_load_auto_modelrU   r   	enumeratesuper__init__tois_hpu_graph_enabledlistkeyslenwarningset_pooling_include_promptsplitanyregister_model)selfr-   r.   r   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   rA   basic_transformer_models	__class__rH   rM   rn      s   

G

$


zSentenceTransformer.__init__    sentence_embeddingfloat32T	sentencesprompt_nameprompt
batch_sizeshow_progress_baroutput_value)r~   token_embeddings	precision)r   int8uint8binaryubinaryconvert_to_numpyconvert_to_tensornormalize_embeddingsc              
      s.  j jdkrjsddlm} |jjdd d_  |du r0t	 t
jkp/t	 t
jk}|	r4d}|dkr<d}	d}d}ttsHtdsMgd}du r|durtzj| W n. tys   td	| d
tj dw jdurjjdn	|durtd i }durfddD g}d|v r|d jd d |d< |
du rj }
|
 g  tfddD }fdd|D }tdt|d| dD ]=}||||  }|}j jdkrVd|v rV|d j}dt t!|d  |d  }t"|d tj#|d |ftj$dfd|d< t"|d tj%|d |ftj$dfd|d< d|v rVt"|d tj%|d |ftj$dfd|d< t&||
}|'| t(  )|j jdkrvt*+t,d j-d< |dkrg }t.| d D ]6\}}t|d }|dkr|| / dkr|d8 }|dkr|| / dks|0|d|d   qn?|du rg }t1td D ]fddD }|0| qn| }|2 }|r tj3j4j5|ddd}|r|6 } 7| W d   n	1 sw   Y  qއ fddt|D  |r7|d kr7t8 |d! |	rWt rRt tj9rLt:  nBt;  n<t<  n7|rt tj9s d j=tj>krut?d"d  D  nt?d#d  D  nt tj9rd$d  D  |r d   S )%a2  
        Computes sentence embeddings.

        Args:
            sentences (Union[str, List[str]]): The sentences to embed.
            prompt_name (Optional[str], optional): The name of the prompt to use for encoding. Must be a key in the `prompts` dictionary,
                which is either set in the constructor or loaded from the model configuration. For example if
                ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ", ...}, then the sentence "What
                is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence
                is appended to the prompt. If ``prompt`` is also set, this argument is ignored. Defaults to None.
            prompt (Optional[str], optional): The prompt to use for encoding. For example, if the prompt is "query: ", then the
                sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?"
                because the sentence is appended to the prompt. If ``prompt`` is set, ``prompt_name`` is ignored. Defaults to None.
            batch_size (int, optional): The batch size used for the computation. Defaults to 32.
            show_progress_bar (bool, optional): Whether to output a progress bar when encode sentences. Defaults to None.
            output_value (Optional[Literal["sentence_embedding", "token_embeddings"]], optional): The type of embeddings to return:
                "sentence_embedding" to get sentence embeddings, "token_embeddings" to get wordpiece token embeddings, and `None`,
                to get all output values. Defaults to "sentence_embedding".
            precision (Literal["float32", "int8", "uint8", "binary", "ubinary"], optional): The precision to use for the embeddings.
                Can be "float32", "int8", "uint8", "binary", or "ubinary". All non-float32 precisions are quantized embeddings.
                Quantized embeddings are smaller in size and faster to compute, but may have a lower accuracy. They are useful for
                reducing the size of the embeddings of a corpus for semantic search, among other tasks. Defaults to "float32".
            convert_to_numpy (bool, optional): Whether the output should be a list of numpy vectors. If False, it is a list of PyTorch tensors.
                Defaults to True.
            convert_to_tensor (bool, optional): Whether the output should be one large tensor. Overwrites `convert_to_numpy`.
                Defaults to False.
            device (str, optional): Which :class:`torch.device` to use for the computation. Defaults to None.
            normalize_embeddings (bool, optional): Whether to normalize returned vectors to have length 1. In that case,
                the faster dot-product (util.dot_score) instead of cosine similarity can be used. Defaults to False.

        Returns:
            Union[List[Tensor], ndarray, Tensor]: By default, a 2d numpy array with shape [num_inputs, output_dimension] is returned.
            If only one string input is provided, then the output is a 1d array with shape [output_dimension]. If ``convert_to_tensor``,
            a torch Tensor is returned instead. If ``self.truncate_dim <= output_dimension`` then output_dimension is ``self.truncate_dim``.

        Example:
            ::

                from sentence_transformers import SentenceTransformer

                # Load a pre-trained SentenceTransformer model
                model = SentenceTransformer('all-mpnet-base-v2')

                # Encode some texts
                sentences = [
                    "The weather is lovely today.",
                    "It's so sunny outside!",
                    "He drove to the stadium.",
                ]
                embeddings = model.encode(sentences)
                print(embeddings.shape)
                # (3, 768)
        r?   r   NT)disable_tensor_cacheFr~   __len__zPrompt name 'rP   rQ   zzEncode with either a `prompt`, a `prompt_name`, or neither, but not both. Ignoring the `prompt_name` in favor of `prompt`.c                    s   g | ]} | qS rH   rH   )rJ   sentence)r   rH   rM   rN         z.SentenceTransformer.encode.<locals>.<listcomp>	input_idsr   prompt_lengthc                    s   g | ]}  | qS rH   )_text_length)rJ   senry   rH   rM   rN         c                       g | ]} | qS rH   rH   rJ   rK   )r   rH   rM   rN     r   Batches)descdisable   )dtypeattention_masktoken_type_idsr   c                    s   i | ]	}| |  qS rH   rH   )rJ   name)out_featuressent_idxrH   rM   
<dictcomp>  s    z.SentenceTransformer.encode.<locals>.<dictcomp>)pdimc                    r   rH   rH   r   )all_embeddingsrH   rM   rN   &  r   r   )r   c                 S   s   g | ]}|   qS rH   )floatnumpyrJ   embrH   rH   rM   rN   6  r   c                 S   s   g | ]}|  qS rH   )r   r   rH   rH   rM   rN   8  r   c                 S   s   g | ]}t |qS rH   )torch
from_numpy)rJ   	embeddingrH   rH   rM   rN   :      )@r   typerp   habana_frameworks.torchr   r?   wrap_in_hpu_graphevalr_   getEffectiveLevelloggingINFODEBUGrU   rI   hasattrr/   KeyErrorr\   rq   rr   r0   getrt   tokenizeshapero   npargsortr   rs   mathceillog2catonesr   zerosr$   updateno_gradforwardcopydeepcopyr+   r8   zipitemappendrangedetachr   
functional	normalizecpuextendr#   r   r   stackr   r   bfloat16asarray)ry   r   r   r   r   r   r   r   r   r   r   r   htinput_was_stringextra_featurestokenized_promptlength_sorted_idxsentences_sortedstart_indexsentences_batchfeaturescurr_tokenize_lenadditional_pad_len
embeddings	token_emb	attentionlast_mask_idrowrH   )r   r   r   ry   r   r   rM   encodeb  s   C




 








"

zSentenceTransformer.encodec                 C   s   | j S )a.  Return the name of the similarity function used by :meth:`SentenceTransformer.similarity` and :meth:`SentenceTransformer.similarity_pairwise`.

        Returns:
            Optional[str]: The name of the similarity function. Can be None if not set, in which case any uses of
            :meth:`SentenceTransformer.similarity` and :meth:`SentenceTransformer.similarity_pairwise` default to "cosine".

        Example:
            >>> model = SentenceTransformer("multi-qa-mpnet-base-dot-v1")
            >>> model.similarity_fn_name
            'dot'
        )_similarity_fn_namer   rH   rH   rM   r1   A  s   z&SentenceTransformer.similarity_fn_namevaluec                 C   s>   t |tr|j}|| _|d urt|| _t|| _d S d S N)rU   r   r   r   to_similarity_fn_similarityto_similarity_pairwise_fn_similarity_pairwisery   r   rH   rH   rM   r1   P  s   
embeddings1embeddings2c                 C      d S r   rH   ry   r   r   rH   rH   rM   
similarityZ     zSentenceTransformer.similarityc                 C   r   r   rH   r   rH   rH   rM   r   ]  r   c                 C      | j du r	tj| _ | jS )a  
        Compute the similarity between two collections of embeddings. The output will be a matrix with the similarity
        scores between all embeddings from the first parameter and all embeddings from the second parameter. This
        differs from `similarity_pairwise` which computes the similarity between each pair of embeddings.

        Args:
            embeddings1 (Union[Tensor, ndarray]): [num_embeddings_1, embedding_dim] or [embedding_dim]-shaped numpy array or torch tensor.
            embeddings2 (Union[Tensor, ndarray]): [num_embeddings_2, embedding_dim] or [embedding_dim]-shaped numpy array or torch tensor.

        Returns:
            Tensor: A [num_embeddings_1, num_embeddings_2]-shaped torch tensor with similarity scores.

        Example:
            ::

                >>> model = SentenceTransformer("all-mpnet-base-v2")
                >>> sentences = [
                ...     "The weather is so nice!",
                ...     "It's so sunny outside.",
                ...     "He's driving to the movie theater.",
                ...     "She's going to the cinema.",
                ... ]
                >>> embeddings = model.encode(sentences, normalize_embeddings=True)
                >>> model.similarity(embeddings, embeddings)
                tensor([[1.0000, 0.7235, 0.0290, 0.1309],
                        [0.7235, 1.0000, 0.0613, 0.1129],
                        [0.0290, 0.0613, 1.0000, 0.5027],
                        [0.1309, 0.1129, 0.5027, 1.0000]])
                >>> model.similarity_fn_name
                "cosine"
                >>> model.similarity_fn_name = "euclidean"
                >>> model.similarity(embeddings, embeddings)
                tensor([[-0.0000, -0.7437, -1.3935, -1.3184],
                        [-0.7437, -0.0000, -1.3702, -1.3320],
                        [-1.3935, -1.3702, -0.0000, -0.9973],
                        [-1.3184, -1.3320, -0.9973, -0.0000]])
        N)r1   r   COSINEr   r   rH   rH   rM   r   `  s   
'c                 C   r   r   rH   r   rH   rH   rM   similarity_pairwise  r   z'SentenceTransformer.similarity_pairwisec                 C   r   r   rH   r   rH   rH   rM   r     r   c                 C   r   )a  
        Compute the similarity between two collections of embeddings. The output will be a vector with the similarity
        scores between each pair of embeddings.

        Args:
            embeddings1 (Union[Tensor, ndarray]): [num_embeddings, embedding_dim] or [embedding_dim]-shaped numpy array or torch tensor.
            embeddings2 (Union[Tensor, ndarray]): [num_embeddings, embedding_dim] or [embedding_dim]-shaped numpy array or torch tensor.

        Returns:
            Tensor: A [num_embeddings]-shaped torch tensor with pairwise similarity scores.

        Example:
            ::

                >>> model = SentenceTransformer("all-mpnet-base-v2")
                >>> sentences = [
                ...     "The weather is so nice!",
                ...     "It's so sunny outside.",
                ...     "He's driving to the movie theater.",
                ...     "She's going to the cinema.",
                ... ]
                >>> embeddings = model.encode(sentences, normalize_embeddings=True)
                >>> model.similarity_pairwise(embeddings[::2], embeddings[1::2])
                tensor([0.7235, 0.5027])
                >>> model.similarity_fn_name
                "cosine"
                >>> model.similarity_fn_name = "euclidean"
                >>> model.similarity_pairwise(embeddings[::2], embeddings[1::2])
                tensor([-0.7437, -0.9973])
        N)r1   r   r   r   r   rH   rH   rM   r     s   
 target_devicesinputoutput	processesc              	   C   s   |du r0t j rdd tt j D }nt r&dd tt j D }n
td dgd }td	d	
tt| | d |   td
}| }| }g }|D ]}|jtj|| ||fdd}|  || qX|||dS )a  
        Starts a multi-process pool to process the encoding with several independent processes
        via :meth:`SentenceTransformer.encode_multi_process <sentence_transformers.SentenceTransformer.encode_multi_process>`.

        This method is recommended if you want to encode on multiple GPUs or CPUs. It is advised
        to start only one process per GPU. This method works together with encode_multi_process
        and stop_multi_process_pool.

        Args:
            target_devices (List[str], optional): PyTorch target devices, e.g. ["cuda:0", "cuda:1", ...],
                ["npu:0", "npu:1", ...], or ["cpu", "cpu", "cpu", "cpu"]. If target_devices is None and CUDA/NPU
                is available, then all available CUDA/NPU devices will be used. If target_devices is None and
                CUDA/NPU is not available, then 4 CPU devices will be used.

        Returns:
            Dict[str, Any]: A dictionary with the target processes, an input queue, and an output queue.
        Nc                 S      g | ]}d  |qS )zcuda:{}ra   rJ   irH   rH   rM   rN     r   z@SentenceTransformer.start_multi_process_pool.<locals>.<listcomp>c                 S   r   )znpu:{}r   r  rH   rH   rM   rN     r   z1CUDA/NPU is not available. Starting 4 CPU workersr      z'Start multi-process pool on devices: {}z, spawnT)targetargsdaemonr   )r   cudais_availabler   device_countr   npur_   r`   ra   joinmaprI   ro   share_memorympget_contextr   Processr,   _encode_multi_process_workerstartr   )ry   r   ctxinput_queueoutput_queuer   	device_idr   rH   rH   rM   start_multi_process_pool  s.   





z,SentenceTransformer.start_multi_process_poolpoolc                 C   sP   | d D ]}|   q| d D ]
}|  |  q| d   | d   dS )z
        Stops all processes started with start_multi_process_pool.

        Args:
            pool (Dict[str, object]): A dictionary containing the input queue, output queue, and process list.

        Returns:
            None
        r   r   r   N)	terminater  close)r  r   rH   rH   rM   stop_multi_process_pool  s   

z+SentenceTransformer.stop_multi_process_pool
chunk_sizec	              
      s  |du rt tt|t|d  d d}tdtt||  d|  |d }	d}
g }|D ]}|| t||krQ|	|
||||||g |
d	7 }
g }q2t|dkrh|	|
||||||g |
d	7 }
|d
  t fddt	|
D dd d}t
dd |D }|S )a  
        Encodes a list of sentences using multiple processes and GPUs via
        :meth:`SentenceTransformer.encode <sentence_transformers.SentenceTransformer.encode>`.
        The sentences are chunked into smaller packages and sent to individual processes, which encode them on different
        GPUs or CPUs. This method is only suitable for encoding large sets of sentences.

        Args:
            sentences (List[str]): List of sentences to encode.
            pool (Dict[Literal["input", "output", "processes"], Any]): A pool of workers started with
                :meth:`SentenceTransformer.start_multi_process_pool <sentence_transformers.SentenceTransformer.start_multi_process_pool>`.
            prompt_name (Optional[str], optional): The name of the prompt to use for encoding. Must be a key in the `prompts` dictionary,
                which is either set in the constructor or loaded from the model configuration. For example if
                ``prompt_name`` is "query" and the ``prompts`` is {"query": "query: ", ...}, then the sentence "What
                is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence
                is appended to the prompt. If ``prompt`` is also set, this argument is ignored. Defaults to None.
            prompt (Optional[str], optional): The prompt to use for encoding. For example, if the prompt is "query: ", then the
                sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?"
                because the sentence is appended to the prompt. If ``prompt`` is set, ``prompt_name`` is ignored. Defaults to None.
            batch_size (int): Encode sentences with batch size. (default: 32)
            chunk_size (int): Sentences are chunked and sent to the individual processes. If None, it determines a
                sensible size. Defaults to None.
            precision (Literal["float32", "int8", "uint8", "binary", "ubinary"]): The precision to use for the
                embeddings. Can be "float32", "int8", "uint8", "binary", or "ubinary". All non-float32 precisions
                are quantized embeddings. Quantized embeddings are smaller in size and faster to compute, but may
                have lower accuracy. They are useful for reducing the size of the embeddings of a corpus for
                semantic search, among other tasks. Defaults to "float32".
            normalize_embeddings (bool): Whether to normalize returned vectors to have length 1. In that case,
                the faster dot-product (util.dot_score) instead of cosine similarity can be used. Defaults to False.

        Returns:
            np.ndarray: A 2D numpy array with shape [num_inputs, output_dimension].

        Example:
            ::

                from sentence_transformers import SentenceTransformer

                def main():
                    model = SentenceTransformer("all-mpnet-base-v2")
                    sentences = ["The weather is so nice!", "It's so sunny outside.", "He's driving to the movie theater.", "She's going to the cinema."] * 1000

                    pool = model.start_multi_process_pool()
                    embeddings = model.encode_multi_process(sentences, pool)
                    model.stop_multi_process_pool(pool)

                    print(embeddings.shape)
                    # => (4000, 768)

                if __name__ == "__main__":
                    main()
        Nr   
   i  zChunk data into z packages of size r   r   r   r   c                    s   g | ]}   qS rH   )r   )rJ   _r  rH   rM   rN   Q  r   z<SentenceTransformer.encode_multi_process.<locals>.<listcomp>c                 S   s   | d S )Nr   rH   )xrH   rH   rM   <lambda>Q  s    z:SentenceTransformer.encode_multi_process.<locals>.<lambda>)keyc                 S   s   g | ]}|d  qS )r   rH   )rJ   resultrH   rH   rM   rN   R  r   )minr   r   rs   r_   debugr   putsortedr   r   concatenate)ry   r   r  r   r   r   r  r   r   r  last_chunk_idchunkr   results_listr   rH   r   rM   encode_multi_process  s,   ?$$
"z(SentenceTransformer.encode_multi_processtarget_devicemodelr  results_queuec                 C   s`   	 z"|  \}}}}}}	}
|j|||| d|	d||
d	}|||g W n tjy.   Y dS w q)zU
        Internal working process to encode sentences in multi-process setup
        TF)r   r   r   r   r   r   r   r   N)r   r   r'  queueEmpty)r.  r/  r  r0  chunk_idr   r   r   r   r   r   r   rH   rH   rM   r  U  s(   z0SentenceTransformer._encode_multi_process_workerrR   c                 C   s$   | D ]}t |tr||_ dS qdS )av  
        Sets the `include_prompt` attribute in the pooling layer in the model, if there is one.

        This is useful for INSTRUCTOR models, as the prompt should be excluded from the pooling strategy
        for these models.

        Args:
            include_prompt (bool): Whether to include the prompt in the pooling layer.

        Returns:
            None
        NrT   )ry   rR   rL   rH   rH   rM   ru   q  s   
z.SentenceTransformer.set_pooling_include_promptc                 C   s   t |  dr|  jS dS )z
        Returns the maximal sequence length that the model accepts. Longer inputs will be truncated.

        Returns:
            Optional[int]: The maximal sequence length that the model accepts, or None if it is not defined.
        max_seq_lengthN)r   _first_moduler4  r   rH   rH   rM   get_max_seq_length  s   
z&SentenceTransformer.get_max_seq_lengthtextsc                 C   s   |   |S )aW  
        Tokenizes the texts.

        Args:
            texts (Union[List[str], List[Dict], List[Tuple[str, str]]]): A list of texts to be tokenized.

        Returns:
            Dict[str, Tensor]: A dictionary of tensors with the tokenized texts. Common keys are "input_ids",
                "attention_mask", and "token_type_ids".
        )r5  r   )ry   r7  rH   rH   rM   r     s   zSentenceTransformer.tokenizec                 G   s   |   j| S r   )r5  get_sentence_features)ry   r   rH   rH   rM   r8    s   z)SentenceTransformer.get_sentence_featuresc                 C   sV   d}t | j D ]}t|dd}t|r| } nq	| jdur)t|p%tj| jS |S )a  
        Returns the number of dimensions in the output of :meth:`SentenceTransformer.encode <sentence_transformers.SentenceTransformer.encode>`.

        Returns:
            Optional[int]: The number of dimensions in the output of `encode`. If it's not known, it's `None`.
        N get_sentence_embedding_dimension)	reversed_modulesvaluesgetattrcallabler8   r%  r   inf)ry   
output_dimmodsent_embedding_dim_methodrH   rH   rM   r9    s   
z4SentenceTransformer.get_sentence_embedding_dimensionc                 c   s*    | j }z|| _ dV  W || _ dS || _ w )aW  
        In this context, :meth:`SentenceTransformer.encode <sentence_transformers.SentenceTransformer.encode>` outputs
        sentence embeddings truncated at dimension ``truncate_dim``.

        This may be useful when you are using the same model for different applications where different dimensions
        are needed.

        Args:
            truncate_dim (int, optional): The dimension to truncate sentence embeddings to. ``None`` does no truncation.

        Example:
            ::

                from sentence_transformers import SentenceTransformer

                model = SentenceTransformer("all-mpnet-base-v2")

                with model.truncate_sentence_embeddings(truncate_dim=16):
                    embeddings_truncated = model.encode(["hello there", "hiya"])
                assert embeddings_truncated.shape[-1] == 16
        N)r8   )ry   r8   original_output_dimrH   rH   rM   truncate_sentence_embeddings  s   z0SentenceTransformer.truncate_sentence_embeddingsc                 C      | j tt| j  S )z4Returns the first module of this sequential embedder)r;  nextiterr   rH   rH   rM   r5       z!SentenceTransformer._first_modulec                 C   rE  )z3Returns the last module of this sequential embedder)r;  rF  r:  r   rH   rH   rM   _last_module  rH  z SentenceTransformer._last_modulerf   
model_namecreate_model_cardtrain_datasetssafe_serializationc              	   C   s  |du rdS t j|dd td| g }ttjtjd| jd< t	t j
|dd$}| j }| j|d	< | j|d
< | j|d< tj||dd W d   n1 sSw   Y  t| jD ]W\}	}
| j|
 }|	dkrtt|trt|d }nt j
|t|	d t|j }t j|dd z	|j||d W n ty   || Y nw ||	|
t j
|t|jd q]t	t j
|dd}tj||dd W d   n1 sw   Y  |r| ||| dS dS )  
        Saves a model and its configuration files to a directory, so that it can be loaded
        with ``SentenceTransformer(path)`` again.

        Args:
            path (str): Path on disc where the model will be saved.
            model_name (str, optional): Optional model name.
            create_model_card (bool, optional): If True, create a README.md with basic information about this model.
            train_datasets (List[str], optional): Optional list with the names of the datasets used to train the model.
            safe_serialization (bool, optional): If True, save the model using safetensors. If False, save the model
                the traditional (but unsafe) PyTorch way.
        NTexist_okzSave model to {})sentence_transformerstransformerspytorchr   !config_sentence_transformers.jsonwr/   r0   r1   r   )indentr   rG   r  )rM  )rK   r   rf   r   modules.json)r]   makedirsr_   r`   ra   r   rR  r   rX   openrf   r  r   r/   r0   r1   jsondumprl   r;  rU   r"   rI   r   __name__save	TypeErrorr   basename
__module___create_model_card)ry   rf   rJ  rK  rL  rM  modules_configfOutconfigrK   r   rL   
model_pathrH   rH   rM   r]    sH   





 zSentenceTransformer.savec                 C   s   | j |||||d dS )rN  rJ  rK  rL  rM  N)r]  )ry   rf   rJ  rK  rL  rM  rH   rH   rM   save_pretrained  s   
z#SentenceTransformer.save_pretrained
deprecatedc                 C   s   |rt |}| s| jjs|| j_| jr/| jjdu r/| j}| jjr.|dd| jj d}nzt| }W n tyJ   t	
dt  d Y dS w ttj|ddd	d
}|| W d   dS 1 shw   Y  dS )a  
        Create an automatic model and stores it in the specified path. If no training was done and the loaded model
        was a Sentence Transformer model already, then its model card is reused.

        Args:
            path (str): The path where the model card will be stored.
            model_name (Optional[str], optional): The name of the model. Defaults to None.
            train_datasets (Optional[List[str]], optional): Deprecated argument. Defaults to "deprecated".

        Returns:
            None
        Nz<model = SentenceTransformer("sentence_transformers_model_id"zmodel = SentenceTransformer(""z#Error while generating model card:
zConsider opening an issue on https://github.com/UKPLab/sentence-transformers/issues with this traceback.
Skipping model card creation.	README.mdrU  utf8encoding)r   rg   r<   model_idrW   trainerreplacer   	Exceptionr_   error	traceback
format_excrY  r]   rf   r  write)ry   rf   rJ  rL  re  
model_cardrc  rH   rH   rM   ra  8  s.   "z&SentenceTransformer._create_model_card"Add new SentenceTransformer model.repo_idorganizationprivatecommit_messagelocal_model_pathrP  replace_model_cardc                 C   s   t d |r5d|vrt d| d| d | d| }n|dd |kr,tdt d| d | j||||||||	|
d	S )	ah  
        DEPRECATED, use `push_to_hub` instead.

        Uploads all elements of this Sentence Transformer to a new HuggingFace Hub repository.

        Args:
            repo_id (str): Repository name for your model in the Hub, including the user or organization.
            token (str, optional): An authentication token (See https://huggingface.co/settings/token)
            private (bool, optional): Set to true, for hosting a private model
            safe_serialization (bool, optional): If true, save the model using safetensors. If false, save the model the traditional PyTorch way
            commit_message (str, optional): Message to commit while pushing.
            local_model_path (str, optional): Path of the model locally. If set, this file path will be uploaded. Otherwise, the current model will be uploaded
            exist_ok (bool, optional): If true, saving to an existing repository is OK. If false, saving only to a new repository is possible
            replace_model_card (bool, optional): If true, replace an existing model card in the hub with the automatically created model card
            train_datasets (List[str], optional): Datasets used to train the model. If set, the datasets will be added to the model card in the Hub.

        Returns:
            str: The url of the commit of your model in the repository on the Hugging Face Hub.
        zThe `save_to_hub` method is deprecated and will be removed in a future version of SentenceTransformers. Please use `push_to_hub` instead for future model uploads.rG   zQProviding an `organization` to `save_to_hub` is deprecated, please use `repo_id="z"` instead.r   zVProviding an `organization` to `save_to_hub` is deprecated, please only use `repo_id`.zVProviding an `organization` to `save_to_hub` is deprecated, please only use `repo_id=")	rx  r6   rz  rM  r{  r|  rP  r}  rL  )r_   rt   rv   r\   push_to_hub)ry   rx  ry  r6   rz  rM  r{  r|  rP  r}  rL  rH   rH   rM   save_to_hubd  s6   !
zSentenceTransformer.save_to_hubc
                 C   s   t |d}
|
j||d|d}|j}| j| |r"|
j|||d}n5t )}|p4tj	
tj	|d }| j||j||	|d |
j|||d}W d   n1 sRw   Y  |
j|d}|jD ]}|jdkrrd	| d
|j   S q`|S )a8  
        Uploads all elements of this Sentence Transformer to a new HuggingFace Hub repository.

        Args:
            repo_id (str): Repository name for your model in the Hub, including the user or organization.
            token (str, optional): An authentication token (See https://huggingface.co/settings/token)
            private (bool, optional): Set to true, for hosting a private model
            safe_serialization (bool, optional): If true, save the model using safetensors. If false, save the model the traditional PyTorch way
            commit_message (str, optional): Message to commit while pushing.
            local_model_path (str, optional): Path of the model locally. If set, this file path will be uploaded. Otherwise, the current model will be uploaded
            exist_ok (bool, optional): If true, saving to an existing repository is OK. If false, saving only to a new repository is possible
            replace_model_card (bool, optional): If true, replace an existing model card in the hub with the automatically created model card
            train_datasets (List[str], optional): Datasets used to train the model. If set, the datasets will be added to the model card in the Hub.

        Returns:
            str: The url of the commit of your model in the repository on the Hugging Face Hub.
        )r6   N)rx  rz  	repo_typerP  )rx  folder_pathr{  rj  rf  )rx  mainzhttps://huggingface.co/z/commit/)r   create_reporx  r<   set_model_idupload_foldertempfileTemporaryDirectoryr]   rf   rg   r  r]  list_repo_refsbranchesr   target_commit)ry   rx  r6   rz  rM  r{  r|  rP  r}  rL  apirepo_url
folder_urltmp_dirrK  refsbranchrH   rH   rM   r~    s<   



zSentenceTransformer.push_to_hubtextc                 C   s`   t |trttt| S t|dsdS t|dks#t |d tr't|S tdd |D S )z
        Help function to get the length for the input text. Text can be either
        a list of ints (which means a single text as input), or a tuple of list of ints
        (representing several text inputs to the model).
        r   r   r   c                 S   s   g | ]}t |qS rH   )rs   )rJ   trH   rH   rM   rN     r   z4SentenceTransformer._text_length.<locals>.<listcomp>)	rU   dictrs   rF  rG  r<  r   intsum)ry   r  rH   rH   rM   r     s   

z SentenceTransformer._text_length	evaluatoroutput_pathc                 C   s    |durt j|dd || |S )aC  
        Evaluate the model based on an evaluator

        Args:
            evaluator (SentenceEvaluator): The evaluator used to evaluate the model.
            output_path (str, optional): The path where the evaluator can write the results. Defaults to None.

        Returns:
            The evaluation results.
        NTrO  )r]   rX  )ry   r  r  rH   rH   rM   evaluate  s   
zSentenceTransformer.evaluatec
                 C   s   t d| d ||||d}
|du r|
ni |
|}|du r"|
ni |
|}|	du r.|
ni |
|	}	t|||||	d}t| d}| jj||d ||gS )ad  
        Creates a simple Transformer + Mean Pooling model and returns the modules

        Args:
            model_name_or_path (str): The name or path of the pre-trained model.
            token (Optional[Union[bool, str]]): The token to use for the model.
            cache_folder (Optional[str]): The folder to cache the model.
            revision (Optional[str], optional): The revision of the model. Defaults to None.
            trust_remote_code (bool, optional): Whether to trust remote code. Defaults to False.
            local_files_only (bool, optional): Whether to use only local files. Defaults to False.
            model_kwargs (Optional[Dict[str, Any]], optional): Additional keyword arguments for the model. Defaults to None.
            tokenizer_kwargs (Optional[Dict[str, Any]], optional): Additional keyword arguments for the tokenizer. Defaults to None.
            config_kwargs (Optional[Dict[str, Any]], optional): Additional keyword arguments for the config. Defaults to None.

        Returns:
            List[nn.Module]: A list containing the transformer model and the pooling model.
        z/No sentence-transformers model found with name z'. Creating a new one with mean pooling.r6   r3   r4   r5   N)	cache_dir
model_argstokenizer_argsconfig_argsmeanr4   )r_   rt   r"   r!   get_word_embedding_dimensionr<   set_base_model)ry   r-   r6   r2   r4   r3   r5   r9   r:   r;   shared_kwargstransformer_modelpooling_modelrH   rH   rM   rk     s*   
z$SentenceTransformer._load_auto_modelc
              
   C   s  t |d||||d}
|
durnt|
}t|| _W d   n1 s#w   Y  d| jv rKd| jd v rK| jd d tkrKtd| jd d t | j	du rX| j
dd| _	| jsc| j
di | _| jsn| j
d	d| _t |d
||||d}|durzt|dd}| | _W d   n1 sw   Y  W n	 ty   Y nw t |d||||d}t|}t|}W d   n1 sw   Y  t }|D ]}t|d }|tkr|d dkri }dD ]f}t ||||||d}|durIt|F}t|}d|v rd|d v r|d d d|v r$d|d v r$|d d d|v r7d|d v r7|d d W d   n	1 sBw   Y   nq||||d}d|vrZi |d< d|vrci |d< d|vrli |d< |d | |d | |d | |r|d | |r|d | |	r|d |	 t|fd|i|}n|tkrd}nt||d ||||d}||}|||d < q|du rt|}t|jdkrt|jd }t|dkr|}| jj||d |S )af  
        Loads a full SentenceTransformer model using the modules.json file.

        Args:
            model_name_or_path (str): The name or path of the pre-trained model.
            token (Optional[Union[bool, str]]): The token to use for the model.
            cache_folder (Optional[str]): The folder to cache the model.
            revision (Optional[str], optional): The revision of the model. Defaults to None.
            trust_remote_code (bool, optional): Whether to trust remote code. Defaults to False.
            local_files_only (bool, optional): Whether to use only local files. Defaults to False.
            model_kwargs (Optional[Dict[str, Any]], optional): Additional keyword arguments for the model. Defaults to None.
            tokenizer_kwargs (Optional[Dict[str, Any]], optional): Additional keyword arguments for the tokenizer. Defaults to None.
            config_kwargs (Optional[Dict[str, Any]], optional): Additional keyword arguments for the config. Defaults to None.

        Returns:
            OrderedDict[str, nn.Module]: An ordered dictionary containing the modules of the model.
        rT  )r6   r2   r4   r5   Nr   rQ  zYou try to use a model that was created with version {}, however, your version is {}. This might cause unexpected behavior or errors. In that case, try to update to the latest version.


r1   r/   r0   rj  rk  rl  rW  r   rf   rB   )zsentence_bert_config.jsonzsentence_roberta_config.jsonzsentence_distilbert_config.jsonzsentence_camembert_config.jsonzsentence_albert_config.jsonz sentence_xlm-roberta_config.jsonzsentence_xlnet_config.jsonr  r3   r  r  r  r  r   r   (   r  )r)   rY  rZ  loadrX   r   r_   rt   ra   r1   r   r/   r0   readrW   rq  r   r&   r"   popr   r    r(   r   rs   partsr<   r  )ry   r-   r6   r2   r4   r3   r5   r9   r:   r;   &config_sentence_transformers_json_pathfInmodel_card_pathmodules_json_pathrb  r.   module_configmodule_classkwargsconfig_nameconfig_path
hub_kwargsrL   module_path
path_partsrevision_path_partrH   rH   rM   rj   7  s   



	


	





z%SentenceTransformer._load_sbert_modelc                 C   s   t | S r   )r,   )
input_pathrH   rH   rM   r    s   zSentenceTransformer.loadc                 C   s   zt |  jW S  tyB   dtjdtttt	f  fdd}| j
|d}zt |}|d jW  Y S  tyA   td Y  Y S w w )z
        Get torch.device from module, assuming that the whole module has one device.
        In case there are no PyTorch parameters, fall back to CPU.
        rL   r=   c                 S   s   dd | j  D }|S )Nc                 S   s"   g | ]\}}t |r||fqS rH   )r   	is_tensor)rJ   kvrH   rH   rM   rN     s   " zNSentenceTransformer.device.<locals>.find_tensor_attributes.<locals>.<listcomp>)__dict__items)rL   tuplesrH   rH   rM   find_tensor_attributes  s   z:SentenceTransformer.device.<locals>.find_tensor_attributes)get_members_fnr   r   )rF  
parametersr   StopIterationr   Moduler   r   rI   r   _named_membersr   )ry   r  genfirst_tuplerH   rH   rM   r     s    zSentenceTransformer.devicec                 C   
   |   jS )zJ
        Property to get the tokenizer that is used by this model
        r5  	tokenizerr   rH   rH   rM   r    s   
zSentenceTransformer.tokenizerc                 C      ||   _dS )zQ
        Property to set the tokenizer that should be used by this model
        Nr  r   rH   rH   rM   r  
     c                 C   r  )a  
        Returns the maximal input sequence length for the model. Longer inputs will be truncated.

        Returns:
            int: The maximal input sequence length.

        Example:
            ::

                from sentence_transformers import SentenceTransformer

                model = SentenceTransformer("all-mpnet-base-v2")
                print(model.max_seq_length)
                # => 384
        r5  r4  r   rH   rH   rM   r4    s   
z"SentenceTransformer.max_seq_lengthc                 C   r  )zs
        Property to set the maximal input sequence length for the model. Longer inputs will be truncated.
        Nr  r   rH   rH   rM   r4  $  r  c                 C   s   t d | jS )Nzj`SentenceTransformer._target_device` has been deprecated, please use `SentenceTransformer.device` instead.)r_   rt   r   r   rH   rH   rM   _target_device+  s   z"SentenceTransformer._target_devicec                 C   s   |  | d S r   )ro   )ry   r   rH   rH   rM   r  2  s   c                 C   $   z|   jW S  ty   g  Y S w r   )r5  _no_split_modulesAttributeErrorr   rH   rH   rM   r  6  
   z%SentenceTransformer._no_split_modulesc                 C   r  r   )r5  _keys_to_ignore_on_saver  r   rH   rH   rM   r  =  r  z+SentenceTransformer._keys_to_ignore_on_savec                 C   s(   | D ]}t |tr|j|  S qd S r   )rU   r"   
auto_modelgradient_checkpointing_enable)ry   gradient_checkpointing_kwargsrL   rH   rH   rM   r  D  s
   
z1SentenceTransformer.gradient_checkpointing_enable)NNNNNNNFNFNNNNNNN)
NNr}   Nr~   r   TFNFr   )NNr}   Nr   F)NTNT)Nrh  )	NNNTrw  NFFN)NNTrw  NFFN)NFFNNN)r=   r,   )r=   N)Er\  r`  __qualname____doc__r   rI   r	   r   r  r   r   r   boolr  r   r   rn   r   r   r   r   r   propertyr1   setterr   r   r   r   r  staticmethodr  r   r-  r   r  ru   r6  r   r   r   r8  r9  r   r
   rD  r5  rI  r]  rg  ra  r*   r  r~  r   r   r   r  rk   rj   r  r   r  r4  r  r  r  r  __classcell__rH   rH   r{   rM   r,   1   s   `	
 V
	

 `	,*,$
1 	

Z8

G



,	

C	


&=(	

;	

 3&r,   )Mr   rb   rZ  r   r   r]   r1  r  rs  rY   collectionsr   
contextlibr   multiprocessingr   pathlibr   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   torch.multiprocessingr  rR  huggingface_hubr   r   r   r   r   tqdm.autonotebookr   r    sentence_transformers.model_cardr   r   *sentence_transformers.similarity_functionsr   rB   r   r   
evaluationr   	fit_mixinr   modelsr    r!   r"   quantizationr#   rc   r$   r%   r&   r'   r(   r)   r*   r+   	getLoggerr\  r_   
Sequentialr,   rH   rH   rH   rM   <module>   sD    4(
