
    NgX                   $   d dl m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Zd dl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 d dl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l0m1Z1m2Z2 d dl3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z>m?Z? ddl@mAZA ddlBmCZC ddlDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZL  ejM        eN          ZO G d de)jP        e;eA          ZQdS )    )annotationsN)OrderedDict)IterableIterator)contextmanager)Queue)Path)AnyCallableLiteraloverload)HfApi)ndarray)Tensordevicenn)trange)is_torch_npu_available)get_class_from_dynamic_moduleget_relative_import_files) SentenceTransformerModelCardDatagenerate_model_card)SimilarityFunction   )__MODEL_HUB_ORGANIZATION____version__)SentenceEvaluator)FitMixin)	NormalizePoolingTransformer)PeftAdapterMixin)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                  |    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd fd#Zdd$Ze	 	 	 	 	 	 	 	 	 	 ddd7            Ze	 	 	 	 	 	 	 	 	 	 ddd;            Ze	 	 	 	 	 	 	 	 	 	 ddd<            Ze	 	 	 	 	 	 	 	 	 	 ddd?            Z	 	 	 	 	 	 	 	 	 	 dddEZd fdHZe	ddJ            Z
e
j        ddM            Z
eddP            ZeddR            Ze	ddT            ZeddU            ZeddV            Ze	ddW            Z	 ddd[Zedd]            Z	 	 	 	 	 	 	 ddd_Zedde            ZddgZddhZddkZddmZddnZeddp            ZddrZddsZ	 	 	 	 dddzZ	 	 	 	 ddd{Z	 ddd}Ze	 	 	 	 	 	 	 	 	 ddd            Z 	 	 	 	 	 	 	 	 	 	 dddZ!ddZ"dddZ#	 	 	 	 	 	 dddZ$ddZ%	 	 	 	 	 	 dddZ&edd            Z'e	dd            Z(e	dd            Z)e)j        dd            Z)e	dd            Z*e*j        dd            Z*e	dd            Z+e+j        ddd            Z+e	dd            Z,e	dd            Z-dddZ. xZ/S )SentenceTransformerar  
    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 Hugging Face 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.
            - ``provider``: If backend is "onnx", this is the provider to use for inference, for example "CPUExecutionProvider",
              "CUDAExecutionProvider", etc. See https://onnxruntime.ai/docs/execution-providers/ for all ONNX execution providers.
            - ``file_name``: If backend is "onnx" or "openvino", this is the file name to load, useful for loading optimized
              or quantized ONNX or OpenVINO models.
            - ``export``: If backend is "onnx" or "openvino", then this is a boolean flag specifying whether this model should
              be exported to the backend. If not specified, the model will be exported only if the model repository or directory
              does not already contain an exported model.

            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 Hugging Face 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 Hugging Face 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.
        backend (str): The backend to use for inference. Can be one of "torch" (default), "onnx", or "openvino".
            See https://sbert.net/docs/sentence_transformer/usage/efficiency.html for benchmarking information
            on the different backends.

    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torchmodel_name_or_path
str | NonemodulesIterable[nn.Module] | Noner   promptsdict[str, str] | Nonedefault_prompt_namesimilarity_fn_namestr | SimilarityFunction | Nonecache_foldertrust_remote_codeboolrevisionlocal_files_onlytokenbool | str | Noneuse_auth_tokentruncate_dim
int | Nonemodel_kwargsdict[str, Any] | Nonetokenizer_kwargsconfig_kwargsmodel_card_data'SentenceTransformerModelCardData | Nonebackend$Literal['torch', 'onnx', 'openvino']returnNonec                |   |pi | _         || _        || _        || _        || _        |pt                      | _        d | _        i | _        d | _	        i | _
        || _        |-t          j        dt                     |t          d          |}|t!          j        d          }|+t%                      }t&                              d|            |dk    r/t*          j                            d          ddlm}  |             ||d	k    rt&                              d
|            g d}t           j                            |          sWd|v s|                    d          dk    rt          d| d          d|vr#|                                |vrt<          dz   |z   }t?          ||||	|
          r'|                      ||||	||
|||	  	        \  }| _        n| !                    ||||	||
|||	  	        }|;tE          |tF                    s&tG          d tI          |          D                       }tK                      &                    |           	 tO          | (                                          j)        }| *                    |           n# tV          $ r Y nw xY w| *                    |           d| _,        | j        M| j        | j         vr?t          d| j         dt[          | j         .                                          d          | j         rUt&                              t_          | j                    dt[          | j         .                                                      | j        r#t&          0                    d| j         d           |dv r| 1                    d           nh|rfd|v rbd|2                    d          d                                         v r3tg          d | D                       rt&          0                    d           | j        4                    |            d S ) Nz^The `use_auth_token` argument is deprecated and will be removed in v4 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 z
 not found)r8   r;   r<   )r=   r8   r;   r9   r<   rB   rD   rE   c                6    g | ]\  }}t          |          |fS  )str).0idxmodules      e/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/SentenceTransformer.py
<listcomp>z0SentenceTransformer.__init__.<locals>.<listcomp>M  s'    "\"\"\+#vCHHf#5"\"\"\    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                F    g | ]}t          |t                    |j        S rX   
isinstancer    rb   )rZ   r\   s     r]   r^   z0SentenceTransformer.__init__.<locals>.<listcomp>x  s+    \\\f
6SZ@[@[\F)\\\r_   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.)5r3   r5   r6   r9   r@   r   rF   module_kwargs_model_card_vars_model_card_text_model_configrH   warningswarnFutureWarning
ValueErrorosgetenvr%   loggerinfo	importlibutil	find_spec*optimum.habana.transformers.modeling_utilsrP   pathexistscountlowerr   r'   _load_sbert_model_load_auto_modelrf   r   	enumeratesuper__init__next
parametersdtypetoStopIterationis_hpu_graph_enabledlistkeyslenwarningset_pooling_include_promptsplitanyregister_model)selfr/   r1   r   r3   r5   r6   r8   r9   r;   r<   r=   r?   r@   rB   rD   rE   rF   rH   rP   basic_transformer_modelsr   	__class__s                         r]   r   zSentenceTransformer.__init__   s   , }"#6 "4!2(.T2R2T2T! " $%Mp     l   #E9%ABBL>$&&FKK<F<<===U??y~77	BBN^^^^^^'')))).@B.F.FKKT@RTTUUUE( E( E($N 7>>"455 _---1C1I1I#1N1NQR1R1R$%K-?%K%K%KLLL0005G5M5M5O5OWo5o5o)Cc)IL^)^&,")!!1    /3.D.D&!-%&7%5!-%5"/ /E 
/ 
/+++ //&!-%&7%5!-%5"/ 0 
 
 z';'G'G!"\"\SZI[I["\"\"\]]G!!!	**++1EGGENNNN 	 	 	D	 	$)!#/D4LTXT`4`4`G(@ G G(,T\->->-@-@(A(AG G G  
 < 	oKK3t|,,mmRVW[WcWhWhWjWjRkRkmmnnn# 	NNG$2J G G G   !nnn++5+AAAA		))) 2 8 8 = =a @ F F H HHH\\\\\]] G   	++D11111s   ;J 
J&%J&c                    | j         S )zReturn the backend used for inference, which can be one of "torch", "onnx", or "openvino".

        Returns:
            str: The backend used for inference.
        )rH   r   s    r]   get_backendzSentenceTransformer.get_backend  s     |r_   .	sentencesrY   prompt_nameprompt
batch_sizeintshow_progress_barbool | Noneoutput_value8Literal['sentence_embedding', 'token_embeddings'] | None	precision8Literal['float32', 'int8', 'uint8', 'binary', 'ubinary']convert_to_numpyLiteral[False]convert_to_tensornormalize_embeddingsr   c                    d S NrX   r   r   r   r   r   r   r   r   r   r   r   r   kwargss                r]   encodezSentenceTransformer.encode  	     r_   str | list[str]Literal[True]
np.ndarrayc                    d S r   rX   r   s                r]   r   zSentenceTransformer.encode  s	     Sr_   c                    d S r   rX   r   s                r]   r   zSentenceTransformer.encode  r   r_   list[str] | np.ndarraylist[Tensor]c                    d S r   rX   r   s                r]   r   zSentenceTransformer.encode  s	     sr_       sentence_embeddingfloat32T"list[Tensor] | np.ndarray | Tensorc           
          j         j        dk    r0 j        s)ddlm} |j                             d           d _                                          |1t          	                                t          j        t          j        fv }|	rd}|dk    rd}	d}d}t          t                    st          d          sgd}|W	  j        |         n# t"          $ r; t%          d	| d
t'           j                                                  d          w xY w j          j                             j        d          n|t                              d           i }AfdD                                  g          }d|v r|d         j        d         dz
  |d<   |
 j         }
                     |
           g t7          j         fdD                       }fd|D             }t;          dt=                    |d|           D ]^}||||z            }                     |          } j         j        dk    r d|v r|d         j        }dt?          j         t?          j!        |d                             z  |d         z
  }t	          j"        |d         t	          j#        |d         |ft          j$                  fd          |d<   t	          j"        |d         t	          j%        |d         |ft          j$                  fd          |d<   d|v rFt	          j"        |d         t	          j%        |d         |ft          j$                  fd          |d<   tM          ||
          }|'                    |           t	          j(                    5    j)        |fi | j         j        dk    rtU          j+                  tY          d          j-                  d<   |dk    rg }t]          |         d                   D ]\  }}t=          |          dz
  }|dk    rG||         /                                dk    r)|dz  }|dk    r||         /                                dk    )|0                    |d|dz                       n|Lg }tc          t=          d                             D ]&fdD             }|0                    |           'n[|         }|2                                }|r't          j3        j4        5                    |dd          }|r|6                                }7                    |           ddd           n# 1 swxY w Y   `fdt7          j        |          D             |r|dk    rtq          |          |	rgt=                    rDt          t6          j9                  rt	          j:                  nt	          j;                  nt	          j<                    n|rut          t6          j9                  sZr:d         j=        t          j>        k    rt7          j?        d  D                       nEt7          j?        d! D                       n&t          t6          j9                  r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)
        rN   r   NT)disable_tensor_cacheFr   __len__zPrompt name 'r`   ra   zzEncode with either a `prompt`, a `prompt_name`, or neither, but not both. Ignoring the `prompt_name` in favor of `prompt`.c                    g | ]}|z   S rX   rX   )rZ   sentencer   s     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp><  s    EEEx(*EEEr_   	input_idsr   prompt_lengthc                <    g | ]}                     |           S rX   )_text_length)rZ   senr   s     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp>J  s*    'U'U'UC):):3)?)?(?'U'U'Ur_   c                     g | ]
}|         S rX   rX   )rZ   r[   r   s     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp>K  s    HHHsIcNHHHr_   Batchesdescdisable   )r   attention_masktoken_type_idstoken_embeddingsc                .    i | ]}||                  S rX   rX   )rZ   nameout_featuressent_idxs     r]   
<dictcomp>z.SentenceTransformer.encode.<locals>.<dictcomp>  s%    [[[dt\$%7%A[[[r_   )pdimc                     g | ]
}|         S rX   rX   )rZ   r[   all_embeddingss     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp>  s    WWW#.-WWWr_   r   )r   c                Z    g | ](}|                                                                 )S rX   )floatnumpyrZ   embs     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp>  s,    0_0_0_1B1B1D1D0_0_0_r_   c                6    g | ]}|                                 S rX   )r   r   s     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp>  s     0W0W0W0W0W0Wr_   c                6    g | ]}t          j        |          S rX   )r.   
from_numpy)rZ   	embeddings     r]   r^   z.SentenceTransformer.encode.<locals>.<listcomp>  s#    ZZZie.y99ZZZr_   )@r   typer   habana_frameworks.torchr.   rN   wrap_in_hpu_graphevalrq   getEffectiveLevelloggingINFODEBUGrf   rY   hasattrr3   KeyErrorrn   r   r   r5   getr   tokenizeshaper   npargsortr   r   mathceillog2catonesint8zerosr$   updateno_gradforwardcopydeepcopyr+   r@   zipitemappendrangedetachr   
functional	normalizecpuextendr#   r   r   stackr   r   bfloat16asarray) r   r   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rowr   r   r   s    `` `                         @@@r]   r   zSentenceTransformer.encode  s?   H ;u$$T-F$000000F$$T$EEE(,D%		$ & 8 8 : :w|W]>[ [ 	%$/// %$ i%% 	$Wy.
 .
 	$ #I#>&!\+6FF   $ O  O  Optuy  vB  vG  vG  vI  vI  qJ  qJ  O  O  O   )5))$*BDII&G  
 EEEE9EEEI  $}}fX66...2B;2O2UVX2Y\]2]/>[FJ'U'U'U'U9'U'U'UVVHHHH6GHHH!!S^^Zi]nYnooo A	2 A	2K.{[:=U/UVO}}_55H{5(((**(0(=(C%)*di	BSTUBV8W8W.X.X)X[lmn[o)o&,1I$[1!J(9!(<>P'QY^Ycddd - -H[) 27$%56!K):1)=?Q(RZ_Zdeee 2 2H-. (8335:Y ()9 : %->q-ACU,V^c^h i i i 6 6!12 'x88HOON+++  2  2+t|H????;#u,,#'=#>#>L5H !568I6 612  #555!#J03L4NP\]mPn0o0o K K,	9'*9~~'9*Q..9\3J3O3O3Q3QUV3V3V(A-L +Q..9\3J3O3O3Q3QUV3V3V #)))Aq8H4H*IJJJJK ")!#J$)#l;O.P*Q*Q$R$R / /[[[[[l[[["))#..../ ".l!;J!+!2!2!4!4J+ [%*X%8%B%B:QRXY%B%Z%Z
 ( 6%/^^%5%5
%%j111A 2  2  2  2  2  2  2  2  2  2  2  2  2  2  2D XWWWDU9V9VWWW 	Vi//09UUUN 	[>"" 0nbj99 A%*%5n%E%ENN%*[%@%@NN!& 	[nbj99 Y! YnQ&7&=&O&O%'Z0_0_P^0_0_0_%`%`NN%'Z0W0W0W0W0W%X%XN
33 	[ZZ>ZZZN 	/+A.Ns    C AD *F9U//U3	6U3	inputdict[str, Tensor]c                   | j         !t                                          |          S |                                 D ]I\  }}| j                             |g           fd|                                D             } ||fi |}J|S )Nc                $    i | ]\  }}|v 	||S rX   rX   )rZ   keyvaluemodule_kwarg_keyss      r]   r   z/SentenceTransformer.forward.<locals>.<dictcomp>  s*    eeeJCCSdLdLdS%LdLdLdr_   )rg   r~   r   named_childrenr   items)r   r  r   module_namer\   rg   r  r   s         @r]   r   zSentenceTransformer.forward  s    %77??5)))#'#6#6#8#8 	3 	3K $ 2 6 6{B G Geeee&,,..eeeMF522M22EEr_   2Literal['cosine', 'dot', 'euclidean', 'manhattan']c                @    | j         t          j        | _        | 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 it will
                default to "cosine" when first called.

        Example:
            >>> model = SentenceTransformer("multi-qa-mpnet-base-dot-v1")
            >>> model.similarity_fn_name
            'dot'
        )_similarity_fn_namer   COSINEr6   r   s    r]   r6   z&SentenceTransformer.similarity_fn_name  s!     #+&8&?D#''r_   r  GLiteral['cosine', 'dot', 'euclidean', 'manhattan'] | SimilarityFunctionc                    t          |t                    r|j        }|| _        |4t          j        |          | _        t          j        |          | _        d S d S r   )rf   r   r  r  to_similarity_fn_similarityto_similarity_pairwise_fn_similarity_pairwiser   r  s     r]   r6   z&SentenceTransformer.similarity_fn_name  sa     e/00 	 KE#( 1B5IID(:(TUZ([([D%%% r_   embeddings1embeddings2c                    d S r   rX   r   r'  r(  s      r]   
similarityzSentenceTransformer.similarity  s    NQcr_   r   c                    d S r   rX   r*  s      r]   r+  zSentenceTransformer.similarity  s    PSPSr_   6Callable[[Tensor | ndarray, Tensor | ndarray], Tensor]c                @    | j         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]])
        )r6   r   r  r#  r   s    r]   r+  zSentenceTransformer.similarity  s"    N "*&8&?D#r_   c                    d S r   rX   r*  s      r]   similarity_pairwisez'SentenceTransformer.similarity_pairwise  s    WZWZr_   c                    d S r   rX   r*  s      r]   r0  z'SentenceTransformer.similarity_pairwise  s    Y\Y\r_   c                @    | j         t          j        | _         | j        S )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])
        )r6   r   r  r%  r   s    r]   r0  z'SentenceTransformer.similarity_pairwise	  s"    @ "*&8&?D#((r_   target_devices	list[str]2dict[Literal['input', 'output', 'processes'], Any]c           
        |t           j                                        r6d t          t           j                                                  D             }ndt                      r6d t          t           j                                                  D             }n t                              d           dgdz  }t                              d	                    d
                    t          t          |                                         |                     d           |                                  t          j        d	          }|                                }|                                }g }|D ]Q}|                    t&          j        || ||fd
          }|                                 |                    |           R|||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                    g | ]}d | S )zcuda:rX   rZ   is     r]   r^   z@SentenceTransformer.start_multi_process_pool.<locals>.<listcomp>C  s    !X!X!X!+!++!X!X!Xr_   c                    g | ]}d | S )znpu:rX   r8  s     r]   r^   z@SentenceTransformer.start_multi_process_pool.<locals>.<listcomp>E  s    !V!V!V***!V!V!Vr_   z1CUDA/NPU is not available. Starting 4 CPU workersr      z'Start multi-process pool on devices: {}z, spawnT)targetargsdaemon)r  output	processes)r.   cudais_availabler   device_countr   npurq   rr   formatjoinmaprY   r   share_memorympget_contextr   Processr-   _encode_multi_process_workerstartr   )r   r3  ctxinput_queueoutput_queuerA  	device_idr   s           r]   start_multi_process_poolz,SentenceTransformer.start_multi_process_pool-  s   ( !z&&(( -!X!XuUZ=T=T=V=V7W7W!X!X!X')) -!V!VeEI<R<R<T<T6U6U!V!V!VOPPP"'1=DDTYYsSVXfOgOgEhEhiijjjnW%%iikkyy{{	' 	  	 I*G{LA   A
 GGIIIQ$9UUUr_   poolc                   | d         D ]}|                                  | d         D ]*}|                                 |                                 +| 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
        rA  r  r@  N)	terminaterG  close)rT  r   s     r]   stop_multi_process_poolz+SentenceTransformer.stop_multi_process_pool^  s     k" 	 	AKKMMMMk" 	 	AFFHHHGGIIIIWXr_   
chunk_sizec
           
     P   |Ht          t          j        t          |          t          |d                   z  dz            d          }|1t                                          t          j        t          j        fv }t          	                    dt          j        t          |          |z             d|            |d         }
d}g }|D ]M}|
                    |           t          |          |k    r#|
                    |||||||	g           |d	z  }g }Nt          |          dk    r!|
                    |||||||	g           |d	z  }|d
         t          fdt          |d|           D             d           }t          j        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.
            show_progress_bar (bool, optional): Whether to output a progress bar when encode sentences. 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()
        NrA  
   i  zChunk data into z packages of size r  r   r   r@  c                8    g | ]}                                 S rX   )r   )rZ   _rQ  s     r]   r^   z<SentenceTransformer.encode_multi_process.<locals>.<listcomp>  s%    mmmA\mmmr_   Chunksr   c                    | d         S )Nr   rX   )xs    r]   <lambda>z:SentenceTransformer.encode_multi_process.<locals>.<lambda>  s
    !A$ r_   )r  c                    g | ]
}|d          S )r   rX   )rZ   results     r]   r^   z<SentenceTransformer.encode_multi_process.<locals>.<listcomp>  s    $J$J$J6VAY$J$J$Jr_   )minr   r   r   rq   r   r   r   r   debugr   putsortedr   r   concatenate)r   r   rT  r   r   r   rY  r   r   r   rP  last_chunk_idchunkr   results_listr  rQ  s                   @r]   encode_multi_processz(SentenceTransformer.encode_multi_processs  s   B TYs9~~D<M8N8N'NQS'STTVZ[[J$ & 8 8 : :w|W]>[ [n	#i..:2M(N(Nnnblnnooo7m! 	 	HLL"""5zzZ''"J{FIWkl   "u::>>OO]J{FT]_stuuuQMH~mmmmHZkVk)l)l)lmmm
 
 
 ^$J$J\$J$J$JKK
r_   target_devicemodelrP  r   results_queuec                    	 	 |                                 \  }}}}}}	}
|                    |||| d|	d||
	  	        }|                    ||g           n# t          j        $ r Y dS w xY wj)zU
        Internal working process to encode sentences in multi-process setup
        TF)r   r   r   r   r   r   r   r   N)r   r   rf  queueEmpty)rm  rn  rP  ro  chunk_idr   r   r   r   r   r   r  s               r]   rM  z0SentenceTransformer._encode_multi_process_worker  s    	OO%% f*ifiQe #\\ +!(&+'%)))= * 
 

 !!8Z"89999;   %	s   AA A('A(rb   c                N    | D ]!}t          |t                    r
||_         dS "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
        Nre   )r   rb   r\   s      r]   r   z.SentenceTransformer.set_pooling_include_prompt  sC      	 	F&'** (6%	 	r_   c                |    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_modulerv  r   s    r]   get_max_seq_lengthz&SentenceTransformer.get_max_seq_length  s=     4%%'')9:: 	7%%''66tr_   texts.list[str] | list[dict] | list[tuple[str, str]]c                P    |                                                      |          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".
        )rw  r   )r   ry  s     r]   r   zSentenceTransformer.tokenize  s$     !!##,,U333r_   +dict[Literal['sentence_embedding'], Tensor]c                :     |                                  j        | S r   )rw  get_sentence_features)r   r
  s     r]   r~  z)SentenceTransformer.get_sentence_features  s    9t!!##98DDr_   c                   d}t          | j                                                  D ].}t          |dd          }t	          |          r |            } n/| j        !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callabler@   rd  r   inf)r   
output_dimmodsent_embedding_dim_methods       r]   r  z4SentenceTransformer.get_sentence_embedding_dimension  s     
DM002233 	 	C(/5WY](^(^%122 6688
 ( z+RVT->???r_   Iterator[None]c              #  V   K   | j         }	 || _         dV  || _         dS # || _         w xY 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)r@   )r   r@   original_output_dims      r]   truncate_sentence_embeddingsz0SentenceTransformer.truncate_sentence_embeddings2  sJ      . #/	4 ,DEEE 3D 3D3333s    	(torch.nn.Modulec                Z    | j         t          t          | j                                      S )z4Returns the first module of this sequential embedder)r  r   iterr   s    r]   rw  z!SentenceTransformer._first_moduleP  s!    }T$t}"5"56677r_   c                Z    | j         t          t          | j                                      S )z3Returns the last module of this sequential embedder)r  r   r  r   s    r]   _last_modulez SentenceTransformer._last_moduleT  s!    }T(4="9"9::;;r_   rw   
model_namecreate_model_cardtrain_datasetslist[str] | Nonesafe_serializationc                R   |dS t          j        |d           t                              d|            g }t          t
          j        t          j        d| j        d<   t          t           j	        
                    |d          d          5 }| j                                        }| j        |d	<   | j        |d
<   | j        |d<   t          j        ||d           ddd           n# 1 swxY w Y   t#          | j                  D ]$\  }	}
| j        |
         }|	dk    rt'          |d          r|dz   }nEt           j	        
                    |t)          |	          dz   t+          |          j        z             }t          j        |d           	 |                    ||           n%# t0          $ r |                    |           Y nw xY wt+          |          j        }|                    d          rt6          j        |         j        }t=          |          t=          |          j        z  }tA          j        ||           tC          |          D ];}t=          |          t=          |          j        z  }tA          j        ||           <|"                    d          d          dt+          |          j         }n.|                    d          s| dt+          |          j         }|#                    |	|
t           j	        $                    |          |d           &t          t           j	        
                    |d          d          5 }t          j        ||d           ddd           n# 1 swxY w 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wr3   r5   r6   r   )indentr   save_in_rootrV   r]  )r  ztransformers_modules.ra   r   sentence_transformers.)r[   r   rw   r   modules.json)&ro   makedirsrq   rr   r   r  r.   rj   openrw   rG  r   r3   r5   r6   jsondumpr}   r  r   rY   r   __name__save	TypeError
__module__
startswithsysr1   __file__r	   r   shutilr   r   r   basename_create_model_card)r   rw   r  r  r  r  modules_configfOutconfigr[   r   r\   
model_path	class_ref
class_file	dest_fileneeded_files                    r]   r  zSentenceTransformer.saveX  s   ( <F
D4((((+T++,,, &1(4(-
 -
=) "',,t%HII3OO 	.SW',,..F $F9,0,DF()+/+BF'(Ifd1----	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. #4=11 #	w #	wIC]4(FaxxGFN;;x!CZ

W\\$C3fAV0VWW
K
T2222(J;MNNNN ( ( (J'''''( V/I##$;<< C [3<
 !,,Z0@0@0EF	J	222 $=Z#H#H 8 8K $Z 0 0D4E4E4J KIKY7777  )s33B7QQ$v,,:OQQ		))*BCC C(BB4<<+@BB	!!#tRWEUEUV`EaEakt"u"uvvvv"',,t^44c:: 	6dInd15555	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6  	F##D*nEEEEE	F 	Fs7   AC**C.1C.F,,GGNNNc                :    |                      |||||           dS )r  r  r  r  r  N)r  )r   rw   r  r  r  r  s         r]   save_pretrainedz#SentenceTransformer.save_pretrained  s8    ( 			!/)1 	 	
 	
 	
 	
 	
r_   
deprecatedc                t   |r;t          |          }|                                s| j        j        s|| j        _        | j        rD| j        j        8| j        }| j        j        r$|                    dd| j        j         d          }nQ	 t          |           }n@# t          $ r3 t          
                    dt          j                     d           Y dS w xY wt          t          j                            |d          dd	
          5 }|                    |           ddd           dS # 1 swxY w 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.mdr  utf8encoding)r	   rx   rF   model_idri   trainerreplacer   	Exceptionrq   error	traceback
format_excr  ro   rw   rG  write)r   rw   r  r  r  
model_cardr  s          r]   r  z&SentenceTransformer._create_model_card  s     	;j))J$$&& ;t/C/L ;0:$-   	T%9%A%I.J#, '//RTD4H4QTTT 

066

   49;O;Q;Q 4 4 4  
  "',,t[113HHH 	#DJJz"""	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	#s$   
B 9CC
D--D14D1"Add new SentenceTransformer model.repo_idorganizationprivatecommit_messagelocal_model_pathr  replace_model_cardc                h   t                               d           |ryd|vr)t                               d| d| d           | d| }nL|                    d          d         |k    rt          d          t                               d| 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.rV   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=")	r  r=   r  r  r  r  r  r  r  )rq   r   r   rn   push_to_hub)r   r  r  r=   r  r  r  r  r  r  r  s              r]   save_to_hubzSentenceTransformer.save_to_hub  s+   B 	J	
 	
 	

  	'!! Lht  L  Lw~  L  L  L   *55G55s##A&,66 l    Bmt  B  B  B   1)-1)   

 

 
	
r_   	create_prc           	        t          |          }|                    ||d|p|          }|j        }| j                            |           |
|                    ||
d           |#|                                 }|dk    rd}nd| d	}d
}|rd|  d| d|                                  d}|r|                    |||||
|          }nt          j	                    5 }|p=t          j                            t          j                            |d                     }|                     ||j        ||	|           |                    |||||
|          }ddd           n# 1 swxY w Y   |r|j        S |j        S )a  
        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.
            revision (str, optional): Branch to push the uploaded files to
            create_pr (bool, optional): If True, create a pull request instead of pushing directly to the main branch

        Returns:
            str: The url of the commit of your model in the repository on the Hugging Face Hub.
        )r=   N)r  r  	repo_typer  T)r  branchr  r.   z!Add new SentenceTransformer modelz*Add new SentenceTransformer model with an z backendrQ   a4  Hello!

*This pull request has been automatically generated from the [`push_to_hub`](https://sbert.net/docs/package_reference/sentence_transformer/SentenceTransformer.html#sentence_transformers.SentenceTransformer.push_to_hub) method from the Sentence Transformers library.*

## Full Model Architecture:
```
a  
```

## Tip:
Consider testing this pull request before merging by loading the model from this PR with the `revision` argument:
```python
from sentence_transformers import SentenceTransformer

# TODO: Fill in the PR number
pr_number = 2
model = SentenceTransformer(
    "z5",
    revision=f"refs/pr/{pr_number}",
    backend="a  ",
)

# Verify that everything works as expected
embeddings = model.encode(["The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium."])
print(embeddings.shape)

similarities = model.similarity(embeddings, embeddings)
print(similarities)
```
)r  folder_pathr  commit_descriptionr;   r  r  r  )r   create_repor  rF   set_model_idcreate_branchr   upload_foldertempfileTemporaryDirectoryro   rw   rx   rG  r  pr_url
commit_url)r   r  r=   r  r  r  r  r  r  r  r;   r  apirepo_urlrH   r  
folder_urltmp_dirr  s                      r]   r  zSentenceTransformer.push_to_hub8  sP   B %   ??*	 # 
 
 "))'222ghNNN!&&((G'!!!D!_g!_!_!_ 	" " "$ %" "(   )" " "@  	**,-#5!# +  JJ ,.. '$6$pbgnnRW\\ZacnMoMo>p>p:p!$$'/&7#1'9 %    !..# '#1'9%' /  
              $  	%$$$$s   A;E&&E*-E*textlist[int] | list[list[int]]c                r   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                       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                ,    g | ]}t          |          S rX   )r   )rZ   ts     r]   r^   z4SentenceTransformer._text_length.<locals>.<listcomp>  s    ---1A---r_   )	rf   dictr   r   r  r  r   r   sum)r   r  s     r]   r   z SentenceTransformer._text_length  s     dD!! 	/tD//00111y)) 	/1YY!^^z$q'377^t99-----...r_   	evaluatorr   output_pathdict[str, float] | floatc                J    |t          j        |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.
        NTr  )ro   r  )r   r  r  s      r]   evaluatezSentenceTransformer.evaluate  s1     "Kd3333y{+++r_   list[nn.Module]c
                @   t                               d| d           ||||d}
||
ni |
|}||
ni |
|}|	|
ni |
|	}	t          |||||	| j                  }t	          |                                d          }| j                            ||           ||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.r=   r9   r;   r<   N)	cache_dir
model_argstokenizer_argsconfig_argsrH   meanr;   )rq   r   r!   rH   r    get_word_embedding_dimensionrF   set_base_model)r   r/   r=   r8   r;   r9   r<   rB   rD   rE   shared_kwargstransformer_modelpooling_models                r]   r|   z$SentenceTransformer._load_auto_model  s   : 	y>Pyyy	
 	
 	

 !2  0	
 
 )5(<}}Bc]BcVbBc,<,D==Jo]Jo^nJo)6)>Df}DfXeDf'"#+%L
 
 
   1 N N P PRXYY++,>+RRR!=11r_   r  	nn.Modulec                    |                     d          rt          |          S |r>|r|                    dd           nd }	 t          ||||          S # t          $ r Y nw xY wt          |          S )Nr  code_revision)r;   r  )r  r&   popr   OSError)r   r  r/   r9   r;   rB   r  s          r]   _load_module_class_from_refz/SentenceTransformer._load_module_class_from_ref  s      899 	1%i000 	GS]L,,_dCCCY]M	4&%"/	        "),,,s   A 
A"!A"dict[str, nn.Module]c
           
     
   t          |d||||          }
|
-t          |
          5 }t          j        |          | _        ddd           n# 1 swxY w Y   d| j        v rod| j        d         v r`| j        d         d         t
          k    rDt                              d                    | j        d         d         t
                               | j	         | j        
                    dd          | _        | j        s | j        
                    di           | _        | j        s | j        
                    d	d          | _        t          |d
||||          }|T	 t          |d          5 }|                                | _        ddd           n# 1 swxY w Y   n# t           $ r Y nw xY wt          |d||||          }t          |          5 }t          j        |          }ddd           n# 1 swxY w Y   t#                      }t#                      }|D ]q}|d         }|                     |||||          }|d         dk    ri }dD ]}t          ||||||          }|t          |          5 }t          j        |          }d|v r%d|d         v r|d                             d           d|v r%d|d         v r|d                             d           d|v r%d|d         v r|d                             d           ddd           n# 1 swxY w Y    n||||d}d|vri |d<   d|vri |d<   d|vri |d<   |d                             |           |d                             |           |d                             |           |r|d                             |           |r|d                             |           |	r|d                             |	           	  ||f|| j        d|}nc# t,          $ r |                    |          }Y nBw xY w|t.          k    rd}nt1          ||d         ||||          }|                    |          }|||d         <   |
                    dg           ||d         <   s|Vt3          |          }t5          |j                  dk    r/t3          |          j        d         }t5          |          dk    r|}| j                            ||           ||f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.
        r  )r=   r8   r;   r<   Nr   r  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.


r6   r3   r5   r  r  r  r  r   rw   rQ   )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  r9   r  r  r  )r  rH   r   r   r   (   r  )r)   r  r  loadrj   r   rq   r   rF  r  r   r6   r3   r5   readri   r  r   r	  r  r   rH   r  r   r(   r	   r   partsrF   r   )r   r/   r=   r8   r;   r9   r<   rB   rD   rE   &config_sentence_transformers_json_pathfInmodel_card_pathmodules_json_pathr  r1   rg   module_configr  module_classr   config_nameconfig_path
hub_kwargsr\   module_path
path_partsrevision_path_parts                               r]   r{   z%SentenceTransformer._load_sbert_model   sY   < 2@/%-2
 2
 2
. 2=<== 4%)Ys^^"4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 !333+t/A-/PPP&}56MNQ\\\ U  \  \*=9:QRT_    '/*.*<*@*@AUW[*\*\'< E#155iDD+ _+/+=+A+ABWY]+^+^( )%-
 
 
 &/F;;; 7s,/HHJJD)7 7 7 7 7 7 7 7 7 7 7 7 7 7 7    +%-
 
 
 #$$ 	,!Ys^^N	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, --#+ X	S X	SM%f-I;;-/@(L L V$**$  K #1*##%1!))9# # #K #.!+.. O#%)Ys^^F+v55:MQWXdQe:e:e &| 4 8 89L M M M/699>QU[\lUm>m>m &'7 8 < <=P Q Q Q,66;NRXYfRg;g;g &} 5 9 9:M N N NO O O O O O O O O O O O O O O  / #): ((8	 
  v--+-F<(#611/1F+, ..,.F=) |$++J777'(//
;;;}%,,Z888   ><(//===# F+,334DEEE  @=)00???C)\*<u^b^juuntuuFF  C C C)../ABBFFFC  9,,"&KK"/*%f-#%1!))9# # #K &**;77-3GM&)*3@3D3DXr3R3RM-/00/00J:#$$))%)*;%<%<%B2%F")**b001H++,>+RRR%%s~   AAAF! /F	F! FF! FF! !
F.-F.G66G:=G:<BLLL1PP%$P%c                     t          |           S r   )r-   )
input_paths    r]   r  zSentenceTransformer.load  s    ":...r_   c                   t          | d         t                    r| d         j        j        S 	 t	          |                                           j        S # t          $ r` dd}|                     |          }	 t	          |          }|d         j        cY S # t          $ r t          j        d	          cY cY S w xY ww xY 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.
        r   r\   r  rJ   list[tuple[str, Tensor]]c                L    d | j                                         D             }|S )Nc                D    g | ]\  }}t          j        |          ||fS rX   )r.   	is_tensor)rZ   kvs      r]   r^   zNSentenceTransformer.device.<locals>.find_tensor_attributes.<locals>.<listcomp>  s0    [[[TQXYHZHZ[1a&[[[r_   )__dict__r  )r\   tupless     r]   find_tensor_attributesz:SentenceTransformer.device.<locals>.find_tensor_attributes  s(    [[V_-B-B-D-D[[[r_   )get_members_fnr   r   N)r\   r  rJ   r   )	rf   r!   
auto_modelr   r   r   r   _named_membersr.   )r   r(  genfirst_tuples       r]   r   zSentenceTransformer.device  s     d1g{++ 	-7%,,	+))**11 	+ 	+ 	+    %%5K%LLC+"3ii"1~,,,,  + + +|E*******+	+s/   %A $B?:BB?B;6B?:B;;B?r
   c                4    |                                  j        S )zJ
        Property to get the tokenizer that is used by this model
        rw  	tokenizerr   s    r]   r0  zSentenceTransformer.tokenizer  s    
 !!##--r_   c                8    ||                                  _        dS )zQ
        Property to set the tokenizer that should be used by this model
        Nr/  r&  s     r]   r0  zSentenceTransformer.tokenizer  s    
 */&&&r_   c                4    |                                  j        S )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
        rw  rv  r   s    r]   rv  z"SentenceTransformer.max_seq_length	  s    " !!##22r_   c                8    ||                                  _        dS )zs
        Property to set the maximal input sequence length for the model. Longer inputs will be truncated.
        Nr3  r&  s     r]   rv  z"SentenceTransformer.max_seq_length  s    
 /4+++r_   torch.devicec                D    t                               d           | j        S )Nzj`SentenceTransformer._target_device` has been deprecated, please use `SentenceTransformer.device` instead.)rq   r   r   r   s    r]   _target_devicez"SentenceTransformer._target_device#  s%    x	
 	
 	
 {r_   int | str | torch.device | Nonec                0    |                      |           d S r   )r   )r   r   s     r]   r7  z"SentenceTransformer._target_device*  s    r_   c                Z    	 |                                  j        S # t          $ r g cY S w xY wr   )rw  _no_split_modulesAttributeErrorr   s    r]   r;  z%SentenceTransformer._no_split_modules.  s@    	%%''99 	 	 	III	    **c                Z    	 |                                  j        S # t          $ r g cY S w xY wr   )rw  _keys_to_ignore_on_saver<  r   s    r]   r?  z+SentenceTransformer._keys_to_ignore_on_save5  s@    	%%''?? 	 	 	III	r=  c                r    | D ]3}t          |t                    r|j                            |          c S 4d S r   )rf   r!   r*  gradient_checkpointing_enable)r   gradient_checkpointing_kwargsr\   s      r]   rA  z1SentenceTransformer.gradient_checkpointing_enable<  sV     	f 	fF&+.. f(FFGdeeeeef	f 	fr_   )NNNNNNNFNFNNNNNNNr.   )&r/   r0   r1   r2   r   r0   r3   r4   r5   r0   r6   r7   r8   r0   r9   r:   r;   r0   r<   r:   r=   r>   r?   r>   r@   rA   rB   rC   rD   rC   rE   rC   rF   rG   rH   rI   rJ   rK   )rJ   rI   )
..........)r   rY   r   r0   r   r0   r   r   r   r   r   r   r   r   r   r   r   r   r   rY   r   r:   rJ   r   )r   r   r   r0   r   r0   r   r   r   r   r   r   r   r   r   r   r   r   r   rY   r   r:   rJ   r   )r   r   r   r0   r   r0   r   r   r   r   r   r   r   r   r   r:   r   r   r   rY   r   r:   rJ   r   )r   r   r   r0   r   r0   r   r   r   r   r   r   r   r   r   r   r   r   r   rY   r   r:   rJ   r   )
NNr   Nr   r   TFNF)r   r   r   r0   r   r0   r   r   r   r   r   r   r   r   r   r:   r   r:   r   rY   r   r:   rJ   r   )r  r  rJ   r  )rJ   r  )r  r   rJ   rK   )r'  r   r(  r   rJ   r   )r'  r   r(  r   rJ   r   )rJ   r-  r   )r3  r4  rJ   r5  )rT  r5  rJ   rK   )NNr   NNr   F)r   r4  rT  r5  r   r0   r   r0   r   r   rY  r   r   r   r   r   r   r:   rJ   r   )
rm  rY   rn  r-   rP  r   ro  r   rJ   rK   )rb   r:   rJ   rK   )rJ   rA   )ry  rz  rJ   r  )rJ   r|  )r@   rA   rJ   r  )rJ   r  )NTNT)rw   rY   r  r0   r  r:   r  r  r  r:   rJ   rK   )Nr  )rw   rY   r  r0   r  r  rJ   rK   )	NNNTr  NFFN)r  rY   r  r0   r=   r0   r  r   r  r:   r  rY   r  r0   r  r:   r  r:   r  r  rJ   rY   )
NNTNNFFNNF)r  rY   r=   r0   r  r   r  r:   r  r0   r  r0   r  r:   r  r:   r  r  r;   r0   r  r:   rJ   rY   )r  r  rJ   r   )r  r   r  rY   rJ   r  )NFFNNN)r/   rY   r=   r>   r8   r0   r;   r0   r9   r:   r<   r:   rB   rC   rD   rC   rE   rC   rJ   r  )r  rY   r/   rY   r9   r:   r;   r0   rB   rC   rJ   r  )r/   rY   r=   r>   r8   r0   r;   r0   r9   r:   r<   r:   rB   rC   rD   rC   rE   rC   rJ   r
  )rJ   r-   )rJ   r   )rJ   r
   )rJ   rK   )rJ   r   )rJ   r5  )r   r8  rJ   rK   )rJ   r4  )0r  r  __qualname____doc__r   r   r   r   r   propertyr6   setterr+  r0  rS  staticmethodrX  rl  rM  r   rx  r   r~  r  r   r  rw  r  r  r  r  r*   r  r  r   r  r|   r	  r{   r  r   r0  rv  r7  r;  r?  rA  __classcell__)r   s   @r]   r-   r-   8   sS       f fT *..2!)-*.>B#'"'#!&#',0#'.226/3CG8?'^2 ^2 ^2 ^2 ^2 ^2 ^2@     #& ),QTNQ+.,/%(    X   #& ),QTNQ*-,/%(    X   #& ),QTNQ!$+.%(    X   #& ),QTNQ+.,/%(    X& #'!)-QeNW!%"'%*\ \ \ \ \|      ( ( ( X(  	\ 	\ 	\ 	\ QQQ XQSSS XS(  (  (  X( T ZZZ XZ\\\ X\!) !) !) X!)H +//V /V /V /V /Vb    \0 #'!)-NW%*` ` ` ` `D    \6   $
 
 
 
4 4 4 4E E E E   & 4 4 4 ^4:8 8 8 8< < < < "&"&+/#'UF UF UF UF UFt "&"&+/#'
 
 
 
 
: \h*# *# *# *# *#X   $( ##'B'+#(+/>
 >
 >
 >
  >
F !##'%)'+#(+/#t% t% t% t% t%l/ / / / , , , , ,(  $"'!&.226/352 52 52 52 52n- - - -B  $"'!&.226/3|& |& |& |& |&| / / / \/ + + + X+0 . . . X. / / / / 3 3 3 X3$ 4 4 4 4    X         X    Xf f f f f f f f fr_   r-   )R
__future__r   r   rs   r  r   r   ro   rq  r  r  r  r  rk   collectionsr   collections.abcr   r   
contextlibr   multiprocessingr   pathlibr	   typingr
   r   r   r   r   r   r.   torch.multiprocessingrJ  r  huggingface_hubr   r   r   r   r   tqdm.autonotebookr   r   !transformers.dynamic_module_utilsr   r    sentence_transformers.model_cardr   r   *sentence_transformers.similarity_functionsr   rQ   r   r   
evaluationr   	fit_mixinr   modelsr   r    r!   
peft_mixinr"   quantizationr#   rt   r$   r%   r&   r'   r(   r)   r*   r+   	getLoggerr  rq   
Sequentialr-   rX   r_   r]   <module>r]     s-   " " " " " "         				   



       # # # # # # . . . . . . . . % % % % % % ! ! ! ! ! !       3 3 3 3 3 3 3 3 3 3 3 3      " " " " " "     ! ! ! ! ! !       $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ / / / / / / f f f f f f f f b b b b b b b b I I I I I I 5 5 5 5 5 5 5 5 ) ) ) ) ) )       3 3 3 3 3 3 3 3 3 3 ( ( ( ( ( ( - - - - - -	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
	8	$	$Hf Hf Hf Hf Hf"-3C Hf Hf Hf Hf Hfr_   