Ë
    l^(hÈ ã                  ó>  — 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
mZ d dlmZmZ d dlmZmZmZmZmZ d dlZd dlZd dlZd dlmZmZ d dlmZmZ d dlmZ d d	l mZ d d
l!m"Z"  ejF                  e$«      Z%erd dl&m'Z' d dl(m)Z) d dl*m+Z+ d=d„Z,d>d„Z-d=d„Z.d?d„Z/d@d„Z0d?d„Z1d@d„Z2d?d„Z3d@d„Z4dAd„Z5d@d„Z6dAd„Z7dBd„Z8dCd„Z9edDd„«       Z:edEd„«       Z:dFd„Z:dd d!d"d#d$e0f	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dGd%„Z;d!d"d#d$e0f	 	 	 	 	 	 	 	 	 	 	 	 	 dHd&„Z<dId'„Z=d$d#d(e0f	 	 	 	 	 	 	 	 	 	 	 	 	 dJd)„Z>	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dK	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dLd*„Z?dMd+„Z@dNd,„ZAdOd-„ZBdPd.„ZC	 	 	 	 dQ	 	 	 	 	 	 	 	 	 	 	 dRd/„ZD G d0„ d1e«      ZEeejŒ                  fd2„«       ZG	 	 	 	 dS	 	 	 	 	 	 	 	 	 	 	 dTd3„ZH	 	 	 	 dS	 	 	 	 	 	 	 	 	 	 	 	 	 dUd4„ZI	 	 	 	 dS	 	 	 	 	 	 	 	 	 	 	 	 	 dVd5„ZJd6„ ZKdOd7„ZLdWd8„ZMdXd9„ZNdXd:„ZOdXd;„ZPed<„ «       ZQy)Yé    )ÚannotationsN)Úcontextmanager)ÚPackageNotFoundErrorÚmetadata)ÚTYPE_CHECKINGÚAnyÚCallableÚLiteralÚoverload)Úhf_hub_downloadÚsnapshot_download)ÚTensorÚdevice)Útrange)Útqdm)Úis_torch_npu_available©ÚDataset)ÚCrossEncoder)ÚSentenceTransformerc                óP   — t        | t        «      st        j                  | «      } | S )zÚ
    Converts the input `a` to a PyTorch tensor if it is not already a tensor.

    Args:
        a (Union[list, np.ndarray, Tensor]): The input array or tensor.

    Returns:
        Tensor: The converted tensor.
    )Ú
isinstancer   ÚtorchÚtensor©Úas    úX/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/util.pyÚ_convert_to_tensorr   !   s    € ô �aœÔ Ü�L‰L˜‹OˆØ€Hó    c                óN   — | j                  «       dk(  r| j                  d«      } | S )zÊ
    If the tensor `a` is 1-dimensional, it is unsqueezed to add a batch dimension.

    Args:
        a (Tensor): The input tensor.

    Returns:
        Tensor: The tensor with a batch dimension.
    é   r   )ÚdimÚ	unsqueezer   s    r   Ú_convert_to_batchr$   0   s#   € ð 	‡u�uƒw�!‚|Ø�K‰K˜‹NˆØ€Hr   c                ó2   — t        | «      } t        | «      } | S )zè
    Converts the input data to a tensor with a batch dimension.

    Args:
        a (Union[list, np.ndarray, Tensor]): The input data to be converted.

    Returns:
        Tensor: The converted tensor with a batch dimension.
    )r   r$   r   s    r   Ú_convert_to_batch_tensorr&   ?   s   € ô 	˜1Ó€AÜ˜!Ó€AØ€Hr   c                ó   — t        | |«      S )á  
    Computes the cosine similarity between two tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = cos_sim(a[i], b[j])
    )Úcos_sim©r   Úbs     r   Úpytorch_cos_simr,   N   s   € ô �1�a‹=Ðr   c                ó¦   — t        | «      } t        |«      }t        | «      }t        |«      }t        j                  ||j	                  dd«      «      S )r(   r   r!   )r&   Únormalize_embeddingsr   ÚmmÚ	transpose)r   r+   Úa_normÚb_norms       r   r)   r)   \   sJ   € ô 	! Ó#€AÜ  Ó#€Aä! !Ó$€FÜ! !Ó$€FÜ�8‰8�F˜F×,Ñ,¨Q°Ó2Ó3Ð3r   c                ój   — t        | «      } t        |«      }t        t        | «      t        |«      «      S )a  
    Computes the pairwise cosine similarity cos_sim(a[i], b[i]).

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = cos_sim(a[i], b[i])
    )r   Úpairwise_dot_scorer.   r*   s     r   Úpairwise_cos_simr5   o   s1   € ô 	˜1Ó€AÜ˜1Ó€AäÔ2°1Ó5Ô7KÈAÓ7NÓOÐOr   c                óz   — t        | «      } t        |«      }t        j                  | |j                  dd«      «      S )a  
    Computes the dot-product dot_prod(a[i], b[j]) for all i and j.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = dot_prod(a[i], b[j])
    r   r!   )r&   r   r/   r0   r*   s     r   Ú	dot_scorer7   €   s4   € ô 	! Ó#€AÜ  Ó#€Aä�8‰8�A�q—{‘{ 1 aÓ(Ó)Ð)r   c                óX   — t        | «      } t        |«      }| |z  j                  d¬«      S )a  
    Computes the pairwise dot-product dot_prod(a[i], b[i]).

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = dot_prod(a[i], b[i])
    éÿÿÿÿ©r"   )r   Úsumr*   s     r   r4   r4   ‘   s-   € ô 	˜1Ó€AÜ˜1Ó€Aà�‰E�;‰;˜2ˆ;ÓÐr   c                ó`   — t        | «      } t        |«      }t        j                  | |d¬«       S )a:  
    Computes the manhattan similarity (i.e., negative distance) between two tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = -manhattan_distance(a[i], b[j])
    g      ð?©Úp©r&   r   Úcdistr*   s     r   Úmanhattan_simrA   ¢   ó.   € ô 	! Ó#€AÜ  Ó#€Aä�K‰K˜˜1 Ô$Ð$Ð$r   c                óŠ   — t        | «      } t        |«      }t        j                  t        j                  | |z
  «      d¬«       S )a<  
    Computes the manhattan similarity (i.e., negative distance) between pairs of tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = -manhattan_distance(a[i], b[i])
    r9   r:   )r   r   r;   Úabsr*   s     r   Úpairwise_manhattan_simrE   ³   s9   € ô 	˜1Ó€AÜ˜1Ó€Aä�I‰I”e—i‘i  A¡Ó&¨BÔ/Ð/Ð/r   c                ó`   — t        | «      } t        |«      }t        j                  | |d¬«       S )a:  
    Computes the euclidean similarity (i.e., negative distance) between two tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Matrix with res[i][j] = -euclidean_distance(a[i], b[j])
    g       @r=   r?   r*   s     r   Úeuclidean_simrG   Ä   rB   r   c                ó�   — t        | «      } t        |«      }t        j                  t        j                  | |z
  dz  d¬«      «       S )a:  
    Computes the euclidean distance (i.e., negative distance) between pairs of tensors.

    Args:
        a (Union[list, np.ndarray, Tensor]): The first tensor.
        b (Union[list, np.ndarray, Tensor]): The second tensor.

    Returns:
        Tensor: Vector with res[i] = -euclidean_distance(a[i], b[i])
    é   r9   r:   )r   r   Úsqrtr;   r*   s     r   Úpairwise_euclidean_simrK   Õ   s=   € ô 	˜1Ó€AÜ˜1Ó€Aä�J‰J”u—y‘y ! a¡%¨A¡°2Ô6Ó7Ð7Ð7r   c                óJ  — t        | «      } t        |«      }t        j                  | dd¬«      \  }}t        j                  |dd¬«      \  }}t        j                  |dz  |dz  z   dd¬«      }||z  ||z  z   |z  }||z  ||z  z
  |z  }t        j                  |dz  |dz  z   dd¬«      dz  }	t        j                  |dz  |dz  z   dd¬«      dz  }
||	|
z  z  }||	|
z  z  }t        j                  t        j                  ||fd¬«      d¬«      }t        j
                  |«      S )aP  
    Computes the absolute normalized angle distance. See :class:`~sentence_transformers.losses.AnglELoss`
    or https://arxiv.org/abs/2309.12871v1 for more information.

    Args:
        x (Tensor): The first tensor.
        y (Tensor): The second tensor.

    Returns:
        Tensor: Vector with res[i] = angle_sim(a[i], b[i])
    rI   r!   r:   T)r"   Úkeepdimç      à?)r   r   Úchunkr;   ÚconcatrD   )ÚxÚyr   r+   ÚcÚdÚzÚreÚimÚdzÚdwÚ
norm_angles               r   Úpairwise_angle_simr[   æ   s  € ô 	˜1Ó€AÜ˜1Ó€Aô �;‰;�q˜! Ô#�D€A€qÜ�;‰;�q˜! Ô#�D€A€qä�	‰	�!�Q‘$˜˜A™‘+ 1¨dÔ3€AØ
ˆa‰%�!�a‘%‰-˜1Ñ	€BØ
ˆa‰%�!�a‘%‰-˜1Ñ	€Bä	�‰�1�a‘4˜!˜Q™$‘; A¨tÔ	4¸Ñ	;€BÜ	�‰�1�a‘4˜!˜Q™$‘; A¨tÔ	4¸Ñ	;€BØˆ"ˆr‰'�M€BØˆ"ˆr‰'�M€Bä—‘œ5Ÿ<™<¨¨R¨°aÔ8¸aÔ@€JÜ�9‰9�ZÓ Ð r   c                óZ   — t         j                  j                  j                  | dd¬«      S )zá
    Normalizes the embeddings matrix, so that each sentence embedding has unit length.

    Args:
        embeddings (Tensor): The input embeddings matrix.

    Returns:
        Tensor: The normalized embeddings matrix.
    rI   r!   )r>   r"   )r   ÚnnÚ
functionalÚ	normalize)Ú
embeddingss    r   r.   r.     s&   € ô �8‰8×Ñ×(Ñ(¨°q¸aÐ(Ó@Ð@r   c                 ó   — y ©N© ©r`   Útruncate_dims     r   Útruncate_embeddingsrf     s   € ØY\r   c                 ó   — y rb   rc   rd   s     r   rf   rf     s   € Ø]`r   c                ó   — | dd|…f   S )a¼  
    Truncates the embeddings matrix.

    Args:
        embeddings (Union[np.ndarray, torch.Tensor]): Embeddings to truncate.
        truncate_dim (Optional[int]): The dimension to truncate sentence embeddings to. `None` does no truncation.

    Example:
        >>> from sentence_transformers import SentenceTransformer
        >>> from sentence_transformers.util import truncate_embeddings
        >>> model = SentenceTransformer("tomaarsen/mpnet-base-nli-matryoshka")
        >>> embeddings = model.encode(["It's so nice outside!", "Today is a beautiful day.", "He drove to work earlier"])
        >>> embeddings.shape
        (3, 768)
        >>> model.similarity(embeddings, embeddings)
        tensor([[1.0000, 0.8100, 0.1426],
                [0.8100, 1.0000, 0.2121],
                [0.1426, 0.2121, 1.0000]])
        >>> truncated_embeddings = truncate_embeddings(embeddings, 128)
        >>> truncated_embeddings.shape
        >>> model.similarity(truncated_embeddings, truncated_embeddings)
        tensor([[1.0000, 0.8092, 0.1987],
                [0.8092, 1.0000, 0.2716],
                [0.1987, 0.2716, 1.0000]])

    Returns:
        Union[np.ndarray, torch.Tensor]: Truncated embeddings.
    .Nrc   rd   s     r   rf   rf     s   € ð: �c˜=˜L˜=Ð(Ñ)Ð)r   Fé    iˆ  i † i ¡ éd   c	                óN   — | j                  |||d¬«      }	t        |	|||||¬«      S )a±  
    Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
    other sentences and returns a list with the pairs that have the highest cosine similarity score.

    Args:
        model (SentenceTransformer): SentenceTransformer model for embedding computation
        sentences (List[str]): A list of strings (texts or sentences)
        show_progress_bar (bool, optional): Plotting of a progress bar. Defaults to False.
        batch_size (int, optional): Number of texts that are encoded simultaneously by the model. Defaults to 32.
        query_chunk_size (int, optional): Search for most similar pairs for #query_chunk_size at the same time. Decrease, to lower memory footprint (increases run-time). Defaults to 5000.
        corpus_chunk_size (int, optional): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time). Defaults to 100000.
        max_pairs (int, optional): Maximal number of text pairs returned. Defaults to 500000.
        top_k (int, optional): For each sentence, we retrieve up to top_k other sentences. Defaults to 100.
        score_function (Callable[[Tensor, Tensor], Tensor], optional): Function for computing scores. By default, cosine similarity. Defaults to cos_sim.

    Returns:
        List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
    T)Úshow_progress_barÚ
batch_sizeÚconvert_to_tensor)Úquery_chunk_sizeÚcorpus_chunk_sizeÚ	max_pairsÚtop_kÚscore_function)ÚencodeÚparaphrase_mining_embeddings)
ÚmodelÚ	sentencesrl   rm   ro   rp   rq   rr   rs   r`   s
             r   Úparaphrase_miningrx   =  sC   € ð> —‘ØÐ%6À:Ðaeð ó €Jô (ØØ)Ø+ØØØ%ôð r   c                óê  — |dz  }t        j                  «       }d}d}t        dt        | «      |«      D �])  }	t        dt        | «      |«      D �]  }
 || |
|
|z    | |	|	|z    «      }t	        j
                  |t        |t        |d   «      «      ddd¬«      \  }}|j                  «       j                  «       }|j                  «       j                  «       }t        t        |«      «      D ]n  }t        ||   «      D ][  \  }}|
|z   }|	|z   }||k7  sŒ||   |   |kD  sŒ"|j                  ||   |   ||f«       |dz  }||k\  sŒG|j                  «       }|d   }Œ] Œp �Œ �Œ, t        «       }g }|j                  «       sg|j                  «       \  }}}t        ||g«      \  }}||k7  r-||f|vr'|j                  ||f«       |j!                  |||g«       |j                  «       sŒgt        |d„ d¬«      }|S )	aì  
    Given a list of sentences / texts, this function performs paraphrase mining. It compares all sentences against all
    other sentences and returns a list with the pairs that have the highest cosine similarity score.

    Args:
        embeddings (Tensor): A tensor with the embeddings
        query_chunk_size (int): Search for most similar pairs for #query_chunk_size at the same time. Decrease, to lower memory footprint (increases run-time).
        corpus_chunk_size (int): Compare a sentence simultaneously against #corpus_chunk_size other sentences. Decrease, to lower memory footprint (increases run-time).
        max_pairs (int): Maximal number of text pairs returned.
        top_k (int): For each sentence, we retrieve up to top_k other sentences
        score_function (Callable[[Tensor, Tensor], Tensor]): Function for computing scores. By default, cosine similarity.

    Returns:
        List[List[Union[float, int]]]: Returns a list of triplets with the format [score, id1, id2]
    r!   r9   r   TF©r"   ÚlargestÚsortedc                ó   — | d   S )Nr   rc   ©rQ   s    r   ú<lambda>z.paraphrase_mining_embeddings.<locals>.<lambda>¯  s
   € °!°A±$€ r   ©ÚkeyÚreverse)ÚqueueÚPriorityQueueÚrangeÚlenr   ÚtopkÚminÚcpuÚtolistÚ	enumerateÚputÚgetÚsetÚemptyr|   ÚaddÚappend)r`   ro   rp   rq   rr   rs   ÚpairsÚ	min_scoreÚ	num_addedÚcorpus_start_idxÚquery_start_idxÚscoresÚscores_top_k_valuesÚscores_top_k_idxÚ	query_itrÚ	top_k_idxÚ
corpus_itrÚiÚjÚentryÚadded_pairsÚ
pairs_listÚscoreÚsorted_iÚsorted_js                            r   ru   ru   j  s/  € ð0 
ˆQ�J€Eô ×ÑÓ!€EØ€IØ€Iä! !¤S¨£_Ð6GÓHó 1ÐÜ$ Q¬¨J«Ð9IÓJó 	1ˆOÙ#Ø˜?¨_Ð?OÑ-OÐPØÐ+Ð.>ÐARÑ.RÐSóˆFô
 5:·J±JØœ˜E¤3 v¨a¡y£>Ó2¸À4ÐPUô5Ñ1ÐÐ!1ð #6×"9Ñ"9Ó";×"BÑ"BÓ"DÐØ/×3Ñ3Ó5×<Ñ<Ó>Ðä"¤3 v£;Ó/ò 1�	Ü-6Ð7GÈ	Ñ7RÓ-Sò 
1Ñ)�I˜zØ'¨)Ñ3�AØ(¨:Ñ5�Aà˜A“vÐ"5°iÑ"@ÀÑ"KÈiÓ"WØŸ	™	Ð#6°yÑ#AÀ)Ñ#LÈaÐQRÐ"SÔTØ! Q™˜	à$¨	Ó1Ø$)§I¡I£K˜EØ(-¨a©™Iñ
1ò1ò	1ð1ô6 “%€KØ€JØ�k‰kŒmØ—i‘i“k‰ˆˆq�!Ü# Q¨ F›^Ñˆ�(à�xÒ X¨xÐ$8ÀÑ$KØ�O‰O˜X xÐ0Ô1Ø×Ñ˜u h°Ð9Ô:ð �k‰k�mô ˜
©ÀÔE€JØÐr   c                 ó   — t        | i |¤ŽS )z8This function is deprecated. Use semantic_search instead)Úsemantic_search)ÚargsÚkwargss     r   Úinformation_retrievalr©   ³  s   € ä˜DÐ+ FÑ+Ð+r   é
   c                óæ  — t        | t        j                  t        j                  f«      rt	        j
                  | «      } n%t        | t        «      rt	        j                  | «      } t        | j                  «      dk(  r| j                  d«      } t        |t        j                  t        j                  f«      rt	        j
                  |«      }n%t        |t        «      rt	        j                  |«      }|j                  | j                  k7  r| j                  |j                  «      } t        t        | «      «      D �cg c]  }g ‘Œ }}t        dt        | «      |«      D �])  }t        dt        |«      |«      D �]  }	 || |||z    ||	|	|z    «      }
t	        j                  |
t        |t        |
d   «      «      ddd¬«      \  }}|j!                  «       j#                  «       }|j!                  «       j#                  «       }t        t        |
«      «      D ]n  }t%        ||   ||   «      D ]W  \  }}|	|z   }||z   }t        ||   «      |k  rt'        j(                  ||   ||f«       Œ=t'        j*                  ||   ||f«       ŒY Œp �Œ �Œ, t        t        |«      «      D ]I  }t        t        ||   «      «      D ]  }||   |   \  }}||dœ||   |<   Œ t-        ||   d„ d¬«      ||<   ŒK |S c c}w )	aø  
    This function performs a cosine similarity search between a list of query embeddings  and a list of corpus embeddings.
    It can be used for Information Retrieval / Semantic Search for corpora up to about 1 Million entries.

    Args:
        query_embeddings (:class:`~torch.Tensor`): A 2 dimensional tensor with the query embeddings.
        corpus_embeddings (:class:`~torch.Tensor`): A 2 dimensional tensor with the corpus embeddings.
        query_chunk_size (int, optional): Process 100 queries simultaneously. Increasing that value increases the speed, but requires more memory. Defaults to 100.
        corpus_chunk_size (int, optional): Scans the corpus 100k entries at a time. Increasing that value increases the speed, but requires more memory. Defaults to 500000.
        top_k (int, optional): Retrieve top k matching entries. Defaults to 10.
        score_function (Callable[[:class:`~torch.Tensor`, :class:`~torch.Tensor`], :class:`~torch.Tensor`], optional): Function for computing scores. By default, cosine similarity.

    Returns:
        List[List[Dict[str, Union[int, float]]]]: A list with one entry for each query. Each entry is a list of dictionaries with the keys 'corpus_id' and 'score', sorted by decreasing cosine similarity scores.
    r!   r   TFrz   )Ú	corpus_idr¢   c                ó   — | d   S )Nr¢   rc   r~   s    r   r   z!semantic_search.<locals>.<lambda>  s   € Ð\]Ð^eÑ\f€ r   r€   )r   ÚnpÚndarrayÚgenericr   Ú
from_numpyÚlistÚstackr†   Úshaper#   r   Útor…   r‡   rˆ   r‰   rŠ   ÚzipÚheapqÚheappushÚheappushpopr|   )Úquery_embeddingsÚcorpus_embeddingsro   rp   rr   rs   Ú_Úqueries_result_listr–   r•   Ú
cos_scoresÚcos_scores_top_k_valuesÚcos_scores_top_k_idxrš   Úsub_corpus_idr¢   r¬   Úquery_idÚdoc_itrs                      r   r¦   r¦   ¸  s  € ô0 Ð"¤R§Z¡Z´·±Ð$<Ô=Ü ×+Ñ+Ð,<Ó=ÑÜ	Ð$¤dÔ	+Ü Ÿ;™;Ð'7Ó8Ðä
Ð×!Ñ!Ó" aÒ'Ø+×5Ñ5°aÓ8ÐäÐ#¤b§j¡j´"·*±*Ð%=Ô>Ü!×,Ñ,Ð->Ó?ÑÜ	Ð%¤tÔ	,Ü!ŸK™KÐ(9Ó:Ðð ×ÑÐ#3×#:Ñ#:Ò:Ø+×.Ñ.Ð/@×/GÑ/GÓHÐä',¬SÐ1AÓ-BÓ'CÖD !š2ÐDÐÐDä  ¤CÐ(8Ó$9Ð;KÓLó ]ˆä % a¬Ð->Ó)?ÐARÓ Só 	]Ðá'Ø  °?ÐEUÑ3UÐVØ!Ð"2Ð5EÐHYÑ5YÐZóˆJô =B¿J¹JØœC ¤s¨:°a©=Ó'9Ó:ÀÈ4ÐX]ô=Ñ9Ð#Ð%9ð '>×&AÑ&AÓ&C×&JÑ&JÓ&LÐ#Ø#7×#;Ñ#;Ó#=×#DÑ#DÓ#FÐ ä"¤3 z£?Ó3ò 	]�	Ü,/Ð0DÀYÑ0OÐQhÐirÑQsÓ,tò ]Ñ(�M 5Ø 0°=Ñ @�IØ.°Ñ:�HÜÐ.¨xÑ8Ó9¸EÒAÜŸ™Ø/°Ñ9¸EÀ9Ð;Mõô ×)Ñ)Ð*=¸hÑ*GÈ%ÐQZÐI[Õ\ñ]ò	]ò	]ð]ô8 œ#Ð1Ó2Ó3ò vˆÜœSÐ!4°XÑ!>Ó?Ó@ò 	^ˆGØ2°8Ñ<¸WÑEÑˆE�9ØCLÐW\Ñ5]Ð Ñ)¨'Ò2ð	^ô )/Ð/BÀ8Ñ/LÑRfÐptÔ(uÐ˜HÒ%ð	vð ÐùòI Es   Ä>	K.c                ó#  — t        «       st        d«      ‚ddlm} | j                  }|r||vr|d   }|r||vr|d   }|s|st        |«      dk7  rt        d«      ‚|�|rdnd	}t        j                  d
|› d�«       |rA|dk7  s|€	|€|€|dk7  rt        j                  d«       |d	k7  rt        j                  d«       d	}|�|}
t        j                  d|
› d�«       t        | j                  «       j                  |«      j                  «       j                  «       |   j                  «       «      }t        |«      }|€A|
€|€|�||dz  z   |z   }n||z   |z   }|dkD  r|rd}|rt!        d«       |rt!        d|› d�«       i }| |   }| |   }|du}|s|}t        t#        |«      t#        |«      z  «      }t%        |«      D �� ci c]  \  }} | |“Œ
 }!}} |j'                  «       }"t        t#        |«      «      }t%        |«      D ��#ci c]  \  }}#|#|“Œ
 }$}}#t        |«      }%t)        j*                  |%«      j-                  d«      }&|j.                  }'|%t        |"«      k7  r|rt!        d|%› dt        |"«      › d�«       |dkD  r%t1        j2                  |«      }(t!        d|(d›d�«       |rb|j5                  t7        |t8        «      rdn|¬«      })|j;                  ||)|dd¬«      }*|j;                  ||)|dd¬«      }+|j=                  |)«       n,|j?                  ||ddd¬«      }*|j?                  ||ddd¬«      }+|�r=ddl },|,jC                  |jE                  «       «      }-	 |,jG                  «       }.d|._$        d|._%        |,jM                  |-|.¬ «      }-|-jQ                  |*«       g }/g }0tS        dt        |+«      |d!¬"«      D ]E  }1|+|1|1|z    }2|-jU                  |2|dz   ¬#«      \  }3}4|/jW                  |3«       |0jW                  |4«       ŒG t)        jX                  t1        jZ                  |/d¬$«      «      j]                  |'«      }3t)        jX                  t1        jZ                  |0d¬$«      «      j]                  |'«      }4n?|j_                  |+|*«      j]                  |'«      }3t)        j`                  |3||z   d¬%«      \  }3}4tc        |%«      D �5cg c]  }5g ‘Œ }6}5te        |"|«      D ]!  \  }#}7|$|#   }8|6|8   jW                  |!|7   «       Œ# |6D �9cg c]  }9t        |9«      ‘Œ }:}9g }g }"tc        |%«      D ]B  }|jg                  |6|   D �;cg c]  };||;   ‘Œ	 c};«       |"jg                  ||   g|:|   z  «       ŒD |6D �9cg c]  }9t)        jh                  |9|'¬&«      ‘Œ }6}9|+tc        |%«      D ��5cg c]  }tc        |:|   «      D ]  }5|‘Œ Œ c}5}   }+|*t)        jj                  |6«      jm                  «          }<|jo                  |+|<«      j]                  |'«      }=~+~<~*|�Ÿ|
€|€|�™tq        t%        |4«      d't        |4«      ¬(«      D ]O  \  }}>||   }#|>D �?cg c]  }?||?   ‘Œ	 }@}?|js                  t        te        |#g|dz   z  |@«      «      |d¬)«      }A|A|3|<   ŒQ |js                  t        te        |"|«      «      |d¬)«      }=|sUt)        jt                  tc        |%«      D �Bcg c]  }Bt)        jv                  |4|B   |6|B   «      ‘Œ  c}B«      }Cty        d*«       |3|C<   |3j{                  «       }D|
€|��Qt)        j|                  |%|=j.                  |=j~                  ¬+«      }Ed}Ftc        |%«      D ].  }Bt)        j€                  |=F|F|:|B   z    «      E|B<   |F|:|Bdz
     z  }FŒ0 |
�p|3|
z   Ejƒ                  |3j…                  d«      d«      j†                  kD  }Gty        d*«       |3|G<   |Gj‰                  «       j‹                  «       }H|HrH|HDz  d,œ|d-<   |D|Hz  }D|�s|3Ejƒ                  |3j…                  d«      d«      j†                  d|z
  z  kD  }Gty        d*«       |3|G<   |Gj‰                  «       j‹                  «       }H|HrH|HDz  d,œ|d.<   |D|Hz  }D|�?|3|kD  }Gty        d*«       |3|G<   |Gj‰                  «       j‹                  «       }H|HrH|HDz  d,œ|d/<   |	�?|3|	k  }Gty        d*«       |3|G<   |Gj‰                  «       j‹                  «       }H|HrH|HDz  d,œ|d0<   t)        j`                  |3|d¬%«      \  }I}J|4|&|Jf   }4|r|4dd…|d…f   }4Idd…|d…f   }I|dk(  r|4dd…d|…f   }4Idd…d|…f   }In |d1k(  r›|4j…                  d«      Ij�                  «       j‰                  d«      z
  }K|Kj�                  |¬2«      }K|KD �Lcg c]"  }Lt‘        j’                  tc        |L«      |¬#«      ‘Œ$ }M}L|4|&|Mf   }4I|&|Mf   }I|Ij•                  dd¬3«      \  }I}J|4|&|Jf   }4t)        jj                  tc        |%«      D �cg c]  }|4|   jƒ                  |:|   d«      ‘Œ c}«      }4t)        jj                  tc        |%«      D �cg c]  }I|   jƒ                  |:|   d«      ‘Œ c}«      }I|dk(  �rGIty        d*«       k7  }Nt)        j–                  |4«      }Ot)        j–                  |4«      }P|4|N   }4|I|N   }Id}Ftc        |%«      D ]c  }Bt)        jh                  |B«      jƒ                  |:|B   |«      OF|F|:|B   z    |6|B   jƒ                  |d«      j†                  P|F|F|:|B   z    |F|:|B   z  }FŒe ON   }OP|N   }6|g |g d4g i}Qte        |O|6|4«      D ]K  \  }R}S}TQ|   jW                  ||R   «       |Q|   jW                  ||S   «       |Qd4   jW                  ||T   «       ŒM |=jƒ                  |d«      j†                  N   Iz
  }U�n|d5k(  �rIty        d*«       k7  }N|g |g d6g i}Qtc        |%«      D ]º  }8|6|8   D ]D  }SQ|   jW                  ||8   «       |Q|   jW                  ||S   «       |Qd6   jW                  d«       ŒF te        |4|8   I|8   «      D ]W  \  }T}V|Vty        d*«       k(  rŒQ|   jW                  ||8   «       |Q|   jW                  |T   «       |Qd6   jW                  d«       ŒY Œ¼ IN   }I|=jƒ                  |d«      j†                  |N   |Iz
  }U�n|d	k(  röIty        d*«       k7  j™                  d¬7«      }N|I|N   }I|4|N   }4|t%        |N«      D ��Wcg c]  \  }}W|WsŒ	|"|   ‘Œ c}W}|t%        N«      D ��Wcg c]  \  }}W|WsŒ	||   ‘Œ c}W}it%        |4j†                  d¬8«      D �1�X�Yci c]  \  }1}Xd9|1› �|XD �Ycg c]  }Y||Y   ‘Œ	 c}Y“Œ c}Y}X}1¥}QIj›                  «       }I|=jƒ                  |d«      j†                  N   j›                  «       |Iz
  }U�n|d:k(  �rIty        d*«       k7  }N|t%        |N«      D ��Zcg c]  \  }}Z|Zj�                  «       sŒ|"|   ‘Œ c}Z}|t%        te        N|4«      «      D ��Z�[�W�-cg c]D  \  }\  }Z}[|Zj�                  «       r,||   gte        Z[«      D �W�-cg c]  \  }W}-|WsŒ	||-   ‘Œ c}-}Wz   ‘ŒF c}-}W}[}Z}d;ND �Zcg c]&  }Z|Zj�                  «       sŒdgdgt‰        Z«      z  z   ‘Œ( c}Zi}QIN   }I|=jƒ                  |d«      j†                  |N   |Iz
  }Ut        Q«      dk(  rt        d<«      ‚ |jž                  Q«      }\|�rd=}]d>„ }^t!        |]j¡                  d?d@dAdB«      «       t!        |]j¡                  dC |^t        |=«      «       |^t        I«      «      dD«      «       dEt(        j2                  fdFt(        j¢                  fdGt(        j¤                  fdHdI„ fdJdK„ fdLdM„ fdNdO„ fdPdQ„ ffD ]T  \  }_}`t!        ]j¡                  |_j§                  «        ^ |`|=«      «       |^ |`I«      «       |^ |`U«      «      «      «       ŒV d-|
fd.|fd/|fd0|	ffD ]4  \  }a}b|a|v sŒ|a   dR   }c||a   dS   }dt!        dT|cdU›dV|ddW›dX|a› dYb› dZ�	«       Œ6 |t        | «      z  t        I«      z
  }e|edkD  r¹d[g}f|dkD  rfjW                  d\«       |
�fjW                  d-«       |�fjW                  d.«       |�fjW                  d/«       d]j©                  fdd «      }gt        |f«      dkD  rgd^fd   z   z  }ge|t        | «      z  z  }ht!        d_|e› d`|hdW›dag› dbt        f«      dkD  rdcndD› dd�	«       \S c c} }w c c}#}w # tN        $ r Y �Œ™w xY wc c}5w c c}9w c c};w c c}9w c c}5}w c c}?w c c}Bw c c}Lw c c}w c c}w c c}W}w c c}W}w c c}Yw c c}Y}X}1w c c}Z}w c c}-}Ww c c}-}W}[}Z}w c c}Zw )euÞ4  
    Add hard negatives to a dataset of (anchor, positive) pairs to create (anchor, positive, negative) triplets or
    (anchor, positive, negative_1, ..., negative_n) tuples.

    Hard negative mining is a technique to improve the quality of a dataset by adding hard negatives, which are
    texts that may appear similar to the anchor, but are not. Using hard negatives can improve the performance of
    models trained on the dataset.

    This function uses a SentenceTransformer model to embed the sentences in the dataset, and then finds the closest
    matches to each anchor sentence in the dataset. It then samples negatives from the closest matches, optionally
    using a CrossEncoder model to rescore the candidates.

    You can influence the candidate negative selection in various ways:

    - **range_min**: Minimum rank of the closest matches to consider as negatives: useful to skip the most similar texts to
      avoid marking texts as negative that are actually positives.
    - **range_max**: Maximum rank of the closest matches to consider as negatives: useful to limit the number of candidates
      to sample negatives from. A lower value makes processing faster, but may result in less candidate negatives that
      satisfy the margin or max_score conditions.
    - **max_score**: Maximum score to consider as a negative: useful to skip candidates that are too similar to the anchor.
    - **min_score**: Minimum score to consider as a negative: useful to skip candidates that are too dissimilar to the anchor.
    - **absolute_margin**: Absolute margin for hard negative mining: useful to skip candidate negatives whose similarity
      to the anchor is within a certain margin of the positive pair. A value of 0 can be used to enforce that the negative
      is always further away from the anchor than the positive.
    - **relative_margin**: Relative margin for hard negative mining: useful to skip candidate negatives whose similarity
      to the anchor is within a certain margin of the positive pair. A value of 0.05 means that the negative is at most 95%
      as similar to the anchor as the positive.
    - **sampling_strategy**: Sampling strategy for negatives: "top" or "random". "top" will always sample the top n
      candidates as negatives, while "random" will sample n negatives randomly from the candidates that satisfy the
      margin or max_score conditions.

    .. tip::

        The excellent `NV-Retriever paper <https://arxiv.org/abs/2407.15831>`_ is a great resource for understanding the
        details of hard negative mining and how to use it effectively. Notably, it reaches the strongest performance using
        these settings::

            dataset = mine_hard_negatives(
                dataset=dataset,
                model=model,
                relative_margin=0.05,         # 0.05 means that the negative is at most 95% as similar to the anchor as the positive
                num_negatives=num_negatives,  # 10 or less is recommended
                sampling_strategy="top",      # "top" means that we sample the top candidates as negatives
                batch_size=batch_size,        # Adjust as needed
                use_faiss=True,               # Optional: Use faiss/faiss-gpu for faster similarity search
            )

        This corresponds with the `TopK-PercPos (95%)` mining method.

    Example:

        >>> from sentence_transformers.util import mine_hard_negatives
        >>> from sentence_transformers import SentenceTransformer
        >>> from datasets import load_dataset
        >>> # Load a Sentence Transformer model
        >>> model = SentenceTransformer("all-MiniLM-L6-v2")
        >>>
        >>> # Load a dataset to mine hard negatives from
        >>> dataset = load_dataset("sentence-transformers/natural-questions", split="train")
        >>> dataset
        Dataset({
            features: ['query', 'answer'],
            num_rows: 100231
        })
        >>> dataset = mine_hard_negatives(
        ...     dataset=dataset,
        ...     model=model,
        ...     range_min=10,
        ...     range_max=50,
        ...     max_score=0.8,
        ...     relative_margin=0.05,
        ...     num_negatives=5,
        ...     sampling_strategy="random",
        ...     batch_size=128,
        ...     use_faiss=True,
        ... )
        Batches: 100%|â–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆ| 588/588 [00:32<00:00, 18.07it/s]
        Batches: 100%|â–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆ| 784/784 [00:08<00:00, 96.41it/s]
        Querying FAISS index: 100%|â–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆâ–ˆ| 7/7 [00:06<00:00,  1.06it/s]
        Metric       Positive       Negative     Difference
        Count         100,231        487,865
        Mean           0.6866         0.4194         0.2752
        Median         0.7010         0.4102         0.2760
        Std            0.1125         0.0719         0.1136
        Min            0.0303         0.1702         0.0209
        25%            0.6221         0.3672         0.1899
        50%            0.7010         0.4102         0.2760
        75%            0.7667         0.4647         0.3590
        Max            0.9584         0.7621         0.7073
        Skipped 427,503 potential negatives (8.36%) due to the relative_margin of 0.05.
        Skipped 978 potential negatives (0.02%) due to the max_score of 0.8.
        Could not find enough negatives for 13290 samples (2.65%). Consider adjusting the range_max, range_min, relative_margin and max_score parameters if you'd like to find more valid negatives.
        >>> dataset
        Dataset({
            features: ['query', 'answer', 'negative'],
            num_rows: 487865
        })
        >>> dataset[0]
        {
            'query': 'when did richmond last play in a preliminary final',
            'answer': "Richmond Football Club Richmond began 2017 with 5 straight wins, a feat it had not achieved since 1995. A series of close losses hampered the Tigers throughout the middle of the season, including a 5-point loss to the Western Bulldogs, 2-point loss to Fremantle, and a 3-point loss to the Giants. Richmond ended the season strongly with convincing victories over Fremantle and St Kilda in the final two rounds, elevating the club to 3rd on the ladder. Richmond's first final of the season against the Cats at the MCG attracted a record qualifying final crowd of 95,028; the Tigers won by 51 points. Having advanced to the first preliminary finals for the first time since 2001, Richmond defeated Greater Western Sydney by 36 points in front of a crowd of 94,258 to progress to the Grand Final against Adelaide, their first Grand Final appearance since 1982. The attendance was 100,021, the largest crowd to a grand final since 1986. The Crows led at quarter time and led by as many as 13, but the Tigers took over the game as it progressed and scored seven straight goals at one point. They eventually would win by 48 points â€“ 16.12 (108) to Adelaide's 8.12 (60) â€“ to end their 37-year flag drought.[22] Dustin Martin also became the first player to win a Premiership medal, the Brownlow Medal and the Norm Smith Medal in the same season, while Damien Hardwick was named AFL Coaches Association Coach of the Year. Richmond's jump from 13th to premiers also marked the biggest jump from one AFL season to the next.",
            'negative': "2018 NRL Grand Final The 2018 NRL Grand Final was the conclusive and premiership-deciding game of the 2018 National Rugby League season and was played on Sunday September 30 at Sydney's ANZ Stadium.[1] The match was contested between minor premiers the Sydney Roosters and defending premiers the Melbourne Storm. In front of a crowd of 82,688, Sydney won the match 21Ã¢â‚¬â€œ6 to claim their 14th premiership title and their first since 2013. Roosters five-eighth Luke Keary was awarded the Clive Churchill Medal as the game's official man of the match."
        }
        >>> dataset.push_to_hub("natural-questions-hard-negatives", "triplet-all")

    Args:
        dataset (Dataset): A dataset containing (anchor, positive) pairs.
        model (SentenceTransformer): A SentenceTransformer model to use for embedding the sentences.
        anchor_column_name (str, optional): The column name in `dataset` that contains the anchor/query. Defaults to None, in which case the first column in `dataset` will be used.
        positive_column_name (str, optional): The column name in `dataset` that contains the positive candidates. Defaults to None, in which case the second column in `dataset` will be used.
        corpus (List[str], optional): A list containing documents as strings that will be used as candidate negatives
            in addition to the second column in `dataset`. Defaults to None, in which case the second column in
            `dataset` will exclusively be used as the negative candidate corpus.
        cross_encoder (CrossEncoder, optional): A CrossEncoder model to use for rescoring the candidates. Defaults to None.
        range_min (int): Minimum rank of the closest matches to consider as negatives. Defaults to 0.
        range_max (int, optional): Maximum rank of the closest matches to consider as negatives. Defaults to None.
        max_score (float, optional): Maximum score to consider as a negative. Defaults to None.
        min_score (float, optional): Minimum score to consider as a negative. Defaults to None.
        absolute_margin (float, optional): Absolute margin for hard negative mining, i.e. the minimum distance between
            the positive similarity and the negative similarity. Defaults to None.
        relative_margin (float, optional): Relative margin for hard negative mining, i.e. the maximum ratio between
            the positive similarity and the negative similarity. A value of 0.05 means that the negative is at most
            95% as similar to the anchor as the positive. Defaults to None.
        num_negatives (int): Number of negatives to sample. Defaults to 3.
        sampling_strategy (Literal["random", "top"]): Sampling strategy for negatives: "top" or "random". Defaults to "top".
        include_positives (bool): Whether to include the positives in the negative candidates.
            Setting this to True is primarily useful for creating Reranking evaluation datasets for CrossEncoder models,
            where it can be useful to get a full ranking (including the positives) from a first-stage retrieval model.
            Defaults to False.
        output_format (Literal["triplet", "n-tuple", "labeled-pair", "labeled-list"]): Output format for the `datasets.Dataset`. Options are:

            - "triplet": (anchor, positive, negative) triplets, i.e. 3 columns. Useful for e.g. :class:`~sentence_transformers.cross_encoder.losses.CachedMultipleNegativesRankingLoss`.
            - "n-tuple": (anchor, positive, negative_1, ..., negative_n) tuples, i.e. 2 + num_negatives columns. Useful for e.g. :class:`~sentence_transformers.cross_encoder.losses.CachedMultipleNegativesRankingLoss`.
            - "labeled-pair": (anchor, passage, label) text tuples with a label of 0 for negative and 1 for positive, i.e. 3 columns. Useful for e.g. :class:`~sentence_transformers.cross_encoder.losses.BinaryCrossEntropyLoss`.
            - "labeled-list": (anchor, [doc1, doc2, ..., docN], [label1, label2, ..., labelN]) triplets with labels of 0 for negative and 1 for positive, i.e. 3 columns. Useful for e.g. :class:`~sentence_transformers.cross_encoder.losses.LambdaLoss`.

            Defaults to "triplet".
        batch_size (int): Batch size for encoding the dataset. Defaults to 32.
        faiss_batch_size (int): Batch size for FAISS top-k search. Defaults to 16384.
        use_faiss (bool): Whether to use FAISS for similarity search. May be recommended for large datasets. Defaults to False.
        use_multi_process (bool | List[str], optional): Whether to use multi-GPU/CPU processing. If True, uses all GPUs if CUDA
            is available, and 4 CPU processes if it's not available. You can also pass a list of PyTorch devices like
            ["cuda:0", "cuda:1", ...] or ["cpu", "cpu", "cpu", "cpu"].
        verbose (bool): Whether to print statistics and logging. Defaults to True.
        as_triplets (bool, optional): Deprecated. Use `output_format` instead. Defaults to None.
        margin (float, optional): Deprecated. Use `absolute_margin` or `relative_margin` instead. Defaults to None.

    Returns:
        Dataset: A dataset containing (anchor, positive, negative) triplets, (anchor, passage, label) text tuples with
        a label, or (anchor, positive, negative_1, ..., negative_n) tuples.
    zGPlease install `datasets` to use this function: `pip install datasets`.r   r   r!   rI   z)Dataset must contain exactly two columns.NÚtripletzn-tuplezrThe `as_triplets` parameter is deprecated. Use the `output_format` parameter instead. Setting `output_format` to `z`.Útopz´When using `include_positives=True`, updating `range_min`, `range_max`, `max_score`, `margin`, or `sampling_strategy` from the default values may still discard the positive values.z~When using `include_positives=True`, `output_format` will be set to `"n-tuple"` to ensure that the ranking order is preserved.zŠThe `margin` parameter is deprecated. Use the `absolute_margin` and/or `relative_margin` parameter instead. Setting `absolute_margin` to `rª   i   z\Using FAISS, we can only retrieve up to 2048 documents per query. Setting range_max to 2048.zSetting range_max to z" based on the provided parameters.r9   zFound z unique queries out of z total queries.zFound an average of z.3fz positives per query.)Útarget_devicesT)rm   r.   rl   )rm   r.   Úconvert_to_numpyrl   )ÚcozQuerying FAISS index)Údesc)Úk)Úaxis)rË   r"   ©r   zRescoring with CrossEncoder)rÊ   Útotal)rm   rn   Úinf)r   Údtype)ÚskippedÚratioÚabsolute_marginÚrelative_marginÚ	max_scorer“   Úrandom)rˆ   )r"   Ú
descendingÚnegativezlabeled-pairÚlabelr:   )ÚstartÚ	negative_zlabeled-listÚlabelszHNo triplets could be generated. Please check the parameters and dataset.z{:<6} {:>14} {:>14} {:>14}c                ób   — t        | t        j                  «      r| j                  «       d›S | d›S )Nz.4fú,)r   r   r   Úitem)Úvalues    r   r   z%mine_hard_negatives.<locals>.<lambda>F  s)   € ¼JÀuÌeÏlÉlÔ<[ e§j¡j£l°3Ð%7€ ÐdiÐjkÐcl€ r   ÚMetricÚPositiveÚNegativeÚ
DifferenceÚCountÚ ÚmeanÚmedianÚstdrˆ   c                óh   — | j                  «       dkD  rt        j                  | «      S t        d«      S )Nr   rÏ   )Únumelr   rˆ   Úfloat©r—   s    r   r   z%mine_hard_negatives.<locals>.<lambda>T  s'   € ¸¿¹»ÈÒ8J¤5§9¡9¨VÓ#4€ ÔPUÐV[ÓP\€ r   z25%c                óˆ   — | j                  «       dkD  r%t        j                  | j                  «       d¬«      S t        d«      S )Nr   g      Ð?©ÚqrÏ   ©rë   r   Úquantilerì   rí   s    r   r   z%mine_hard_negatives.<locals>.<lambda>U  ó0   € ÈVÏ\É\Ë^Ð^_ÒM_¤5§>¡>°&·,±,³.ÀDÔ#I€ ÔejÐkpÓeq€ r   z50%c                óˆ   — | j                  «       dkD  r%t        j                  | j                  «       d¬«      S t        d«      S )Nr   rN   rï   rÏ   rñ   rí   s    r   r   z%mine_hard_negatives.<locals>.<lambda>V  s0   € ÈFÏLÉLËNÐ]^ÒL^¤5§>¡>°&·,±,³.ÀCÔ#H€ ÔdiÐjoÓdp€ r   z75%c                óˆ   — | j                  «       dkD  r%t        j                  | j                  «       d¬«      S t        d«      S )Nr   ç      è?rï   rÏ   rñ   rí   s    r   r   z%mine_hard_negatives.<locals>.<lambda>W  ró   r   Úmaxc                óh   — | j                  «       dkD  rt        j                  | «      S t        d«      S )Nr   z-inf)rë   r   r÷   rì   rí   s    r   r   z%mine_hard_negatives.<locals>.<lambda>X  s'   € ¸¿¹»ÈÒ8J¤5§9¡9¨VÓ#4€ ÔPUÐV\ÓP]€ r   rÑ   rÒ   zSkipped rÞ   z potential negatives (z.2%z) due to the z of ú.Ú	range_maxÚ	range_minz, z and z$Could not find enough negatives for z
 samples (z). Consider adjusting the z
 parameterÚsz, if you'd like to find more valid negatives.)UÚis_datasets_availableÚImportErrorÚdatasetsr   Úcolumn_namesr†   Ú
ValueErrorÚloggerÚwarningr²   Ú	to_pandasÚgroupbyÚcountÚto_dictÚvaluesr÷   ÚprintrŽ   r‹   Úcopyr   Úaranger#   r   r®   rç   Ústart_multi_process_poolr   ÚboolÚencode_multi_processÚstop_multi_process_poolrt   ÚfaissÚIndexFlatIPÚ get_sentence_embedding_dimensionÚGpuMultipleClonerOptionsÚshardÚ
useFloat16Úindex_cpu_to_all_gpusÚ	Exceptionr�   r   Úsearchr‘   r±   Úconcatenaterµ   Ú
similarityr‡   r…   r¶   Úextendr   ÚcatrŠ   Úsimilarity_pairwiser   Úpredictr³   Úisinrì   rë   r�   rÐ   rˆ   ÚrepeatÚsizeÚTr;   rß   ÚisinfÚclamprÖ   ÚsampleÚsortÚ
empty_likeÚallÚflattenÚanyÚ	from_dictÚformatrè   ré   Ú
capitalizeÚjoin)iÚdatasetrv   Úanchor_column_nameÚpositive_column_nameÚcorpusÚcross_encoderrû   rú   rÕ   r“   rÓ   rÔ   Únum_negativesÚsampling_strategyÚinclude_positivesÚoutput_formatrm   Úfaiss_batch_sizeÚ	use_faissÚuse_multi_processÚverboseÚas_tripletsÚmarginr   ÚcolumnsÚpositives_per_queryÚmax_positivesÚlog_countersÚqueriesÚ	positivesÚseparate_corpusÚidxÚtextÚ
corpus_idxÚall_queriesÚqueryÚqueries_idxÚ	n_queriesÚ	batch_idxr   Úavg_positives_per_queryÚpoolr»   rº   r  ÚindexrÉ   Úscores_listÚindices_listr�   Úquery_chunkr—   Úindicesr¼   Úpositive_indicesÚpositiveÚ	query_idxr>   Ún_positivesÚdoc_idxÚpositive_embeddingsÚpositive_scoresÚcandidate_idxÚ_idxÚcandidate_passagesÚpred_scoresÚq_idxÚpositive_maskÚnum_candidatesÚmax_positive_scoresÚ	start_idxÚremoved_indicesÚnum_skippedÚnegative_scoresÚlocal_indicesÚnum_optionsÚoptionsÚsampled_idxÚindices_to_keepÚanchor_indicesÚpos_indicesÚdataset_dataÚ
anchor_idxÚpositive_idxÚnegative_idxÚdifference_scoresÚnegative_scoreÚkeepÚneg_indicesÚneg_idxÚkeep_rowÚindices_rowÚoutput_datasetÚ
row_formatÚ	formatterÚmetricÚfunctionÚ
param_nameÚparam_valuerÑ   rÒ   Úmissing_negativesÚ	solutionsÚconsiderationsÚmissing_negatives_ratiosi                                                                                                            r   Úmine_hard_negativesr„    s  € ô` !Ô"ÜÐcÓdÐdå ð ×"Ñ"€GáÐ!3¸7Ñ!BØ$ Q™ZÐáÐ#7¸wÑ#FØ& q™zÐáÑ&:¼sÀ7»|ÈqÒ?PÜÐDÓEÐEàÐÙ%0™	°iˆÜ�‰ð+Ø+8¨/¸ð=ô	
ñ
 à˜ŠNØÐ$ØÐ$ØÐ!Ø  EÒ)ä�N‰Nðeôð ˜IÒ%Ü�N‰Nð Qôð &ˆMàÐØ ˆÜ�‰ð-Ø-<Ð,=¸RðAô	
ô Ø×ÑÓ×#Ñ#Ð$6Ó7×=Ñ=Ó?×GÑGÓIÐJ^Ñ_×fÑfÓhóÐô Ð+Ó,€MàÐØÐ&¨/Ð*EÈÐI^à! ]°RÑ%7Ñ8¸=ÑH‰Ið " MÑ1°MÑAˆIØ�tÒ¡	àˆIÙÜÐtÔuÙÜÐ)¨)¨Ð4VÐWÔXà€LØÐ(Ñ)€GØÐ,Ñ-€IØ DÐ(€OÙØˆô ”#�f“+¤ I£Ñ.Ó/€Fô .7°vÓ->×?¡	  T�$˜‘)Ð?€JÑ?ð —,‘,“.€KÜ”3�w“<Ó €GÜ09¸'Ó0B×C¡* # u�5˜#‘:ÐC€KÑCÜ�G“€IÜ—‘˜YÓ'×1Ñ1°"Ó5€Ià�\‰\€Fà”C˜Ó$Ò$©Ü��y�kÐ!8¼¸[Ó9IÐ8JÈ/ÐZÔ[à�qÒÜ"$§'¡'Ð*=Ó">ÐÜÐ$Ð%<¸SÐ$AÐAVÐWÔXñ Ø×-Ñ-Ü#-Ð.?ÄÔ#F™4ÐL]ð .ó 
ˆð "×6Ñ6Ø�D ZÀdÐ^bð 7ó 
Ðð !×5Ñ5Ø�T jÀtÐ_cð 6ó 
Ðð 	×%Ñ% dÕ+à!ŸL™LØ˜zÀÐW[Ðosð )ó 
Ðð !Ÿ<™<ØØ!Ø!%Ø!Ø"ð (ó 
Ðò Ûà×!Ñ! %×"HÑ"HÓ"JÓKˆð	Ø×/Ñ/Ó1ˆBØˆBŒHØ ˆBŒMØ',×'BÑ'BÀ5ÈRÐ'BÓ'PˆEð 	�	‰	Ð#Ô$àˆØˆä˜œ3Ð/Ó0Ð2BÐI_Ô`ò 	)ˆAØ*¨1¨qÐ3CÑ/CÐDˆKØ#Ÿl™l¨;¸)Àa¹-˜lÓH‰OˆF�GØ×Ñ˜vÔ&Ø×Ñ Õ(ð		)ô
 ×!Ñ!¤"§.¡.°À1Ô"EÓF×IÑIÈ&ÓQˆÜ×"Ñ"¤2§>¡>°,ÀQÔ#GÓH×KÑKÈFÓS‰ð ×!Ñ!Ð"2Ð4EÓF×IÑIÈ&ÓQˆô  Ÿ*™* V¨y¸=Ñ/HÈaÔP‰ˆ�ô
 %*¨)Ó$4Ö5˜qšÐ5ÐÐ5ä˜{¨IÓ6ò A‰ˆˆxØ Ñ&ˆ	Ø˜Ñ#×*Ñ*¨:°hÑ+?Õ@ðAð $4Ö4˜a”3�q•6Ð4€KÐ4ð €IØ€KÜ�YÓò >ˆØ×ÑÐ9IÈ#Ñ9NÖO¨g˜& ›/ÒOÔPØ×Ñ˜G C™L˜>¨K¸Ñ,<Ñ<Õ=ð>ð AQÖQ¸1œŸ™ Q¨vÖ6ÐQÐÐQð (¼¸iÓ8H×(j°ÔRWÐXcÐdgÑXhÓRiÒ(jÈQªÐ(j¨Ó(jÑkÐØ+¬E¯I©IÐ6FÓ,G×,NÑ,NÓ,PÑQÐØ×/Ñ/Ð0@ÐBUÓV×YÑYÐZ`Óa€OàØØð Ð ØÐ# Ð'BÀiÐF[ä"&¤y°Ó'9Ð@]ÔehÐipÓeqÔ"rò 	&ÑˆC�Ø˜C‘LˆEØ;HÖ!I°4 &¨£,Ð!IÐÐ!IØ'×/Ñ/Ü”S˜%˜ I°¡MÑ2Ð4FÓGÓHØ%Ø"&ð 0ó ˆKð
 &ˆF�3ŠKð	&ð (×/Ñ/Ü”�[ )Ó,Ó-Ø!Ø"ð 0ó 
ˆñ äŸ™ÜNSÐT]ÓN^Ö_ÀUŒU�Z‰Z˜ ™Ð(8¸Ñ(?Õ@Ò_ó
ˆô "' u£ ˆˆ}Ñà—\‘\“^€Nð Ð" oÑ&Aô $Ÿk™k¨)¸O×<RÑ<RÐZi×ZoÑZoÔpÐØˆ	Ü˜9Ó%ò 	0ˆEÜ).¯©°?À9ÈyÐ[fÐglÑ[mÑOmÐ3nÓ)oÐ Ñ&Ø˜ U¨Q¡YÑ/Ñ/‰Ið	0ð Ð&Ø$ Ñ6Ð9L×9SÑ9SÐTZ×T_ÑT_Ð`aÓTbÐdeÓ9f×9hÑ9hÑhˆOÜ',¨U£| mˆF�?Ñ#à)×-Ñ-Ó/×4Ñ4Ó6ˆKÙØ>IÐT_ÐbpÑTpÑ2q�Ð.Ñ/Ø +Ñ-�àÐ&Ø$Ð':×'AÑ'AÀ&Ç+Á+ÈaÃ.ÐRSÓ'T×'VÑ'VÐZ[Ð^mÑZmÑ'nÑnˆOÜ',¨U£| mˆF�?Ñ#à)×-Ñ-Ó/×4Ñ4Ó6ˆKÙØ>IÐT_ÐbpÑTpÑ2q�Ð.Ñ/Ø +Ñ-�ð ÐØ  9Ñ,ˆÜ#(¨£< -ˆˆÑà%×)Ñ)Ó+×0Ñ0Ó2ˆÙà&Ø$ ~Ñ5ñ)ˆL˜Ñ%ð ÐØ  9Ñ,ˆÜ#(¨£< -ˆˆÑà%×)Ñ)Ó+×0Ñ0Ó2ˆÙà&Ø$ ~Ñ5ñ)ˆL˜Ñ%ô &+§Z¡Z°¸)ÈÔ%KÑ"€O�]Ø�i Ð.Ñ/€GáØš!˜Y™Z˜-Ñ(ˆØ)ª!¨Y©Z¨-Ñ8ˆð ˜EÒ!Øš!˜^˜m˜^Ð+Ñ,ˆØ)ª!¨^¨m¨^Ð*;Ñ<‰à	˜hÒ	&à—l‘l 1“o¨×(=Ñ(=Ó(?×(CÑ(CÀAÓ(FÑFˆØ!×'Ñ'¨MÐ'Ó:ˆàU`ÖaÈ'”v—}‘}¤U¨7£^°}ÖEÐaˆÐaØ˜) [Ð0Ñ1ˆØ)¨)°[Ð*@ÑAˆà)8×)=Ñ)=À!ÐPTÐ)=Ó)UÑ&ˆ˜Ø˜) ]Ð2Ñ3ˆô �i‰iÌUÐS\ÓM]Ö^Àc˜ ™×,Ñ,¨[¸Ñ-=¸qÕAÒ^Ó_€GÜ—i‘iÔ]bÐclÓ]mÖ nÐVY °Ñ!5×!<Ñ!<¸[ÈÑ=MÈqÕ!QÒ nÓo€Oà˜	Ó!à)¬e°E«l¨]Ñ:ˆÜ×)Ñ)¨'Ó2ˆÜ×&Ñ& wÓ/ˆà˜/Ñ*ˆØ)¨/Ñ:ˆð ˆ	Ü˜9Ó%ò 	,ˆEÜINÏÉÐV[ÓI\×IcÑIcØ˜EÑ" MóJˆN˜9 y°;¸uÑ3EÑ'EÐFð ! Ñ'×.Ñ.¨}¸aÓ@×BÑBð ˜	 I°¸EÑ0BÑ$BÐCð ˜ UÑ+Ñ+‰Ið	,ð (¨Ñ8ˆØ& Ñ7Ðð  Ø  "Ø˜ð
ˆô 7:¸.ÐJZÐ\cÓ6dò 	BÑ2ˆJ˜ lØÐ+Ñ,×3Ñ3°G¸JÑ4GÔHØÐ-Ñ.×5Ñ5°f¸\Ñ6JÔKØ˜Ñ$×+Ñ+¨F°<Ñ,@ÕAð	Bð ,×2Ñ2°=À!ÓD×FÑFÀÑWÐZiÑiÒà	˜.Ó	(Ø)¬e°E«l¨]Ñ:ˆð  Ø  "Ø�Rð
ˆô ˜yÓ)ò 
	0ˆIØ 0°Ñ ;ò 0�ØÐ/Ñ0×7Ñ7¸À	Ñ8JÔKØÐ1Ñ2×9Ñ9¸&ÀÑ:NÔOØ˜WÑ%×,Ñ,¨QÕ/ð0ô 14°G¸IÑ4FÈÐXaÑHbÓ0cò 0Ñ,�˜nØ!¤e¨E£l ]Ò2ØØÐ/Ñ0×7Ñ7¸À	Ñ8JÔKØÐ1Ñ2×9Ñ9¸&ÀÑ:NÔOØ˜WÑ%×,Ñ,¨QÕ/ñ0ð
	0ð *¨/Ñ:ˆØ+×2Ñ2°=À!ÓD×FÑFÀÑWÐZiÑiÒà	˜)Ò	#à*¬u°U«|¨mÑ;×@Ñ@ÀQÐ@ÓGˆØ)¨/Ñ:ˆØ˜/Ñ*ˆð Ä9È_ÓC]× f±i°c¸4Òae ¨SÓ!1Ó fØ Ä9È_ÓC]×"f±i°c¸4Òae 9¨S£>Ó"fð
ô
 '0°·	±	ÀÔ&C÷ð á"�A�{ð ˜A˜3�ÀÖ!M°g &¨£/Ò!MÑMôð
ˆð *×1Ñ1Ó3ˆØ+×2Ñ2°=À!ÓD×FÑFÀÑW×_Ñ_ÓaÐdsÑsÒà	˜.Ó	(Ø)¬e°E«l¨]Ñ:ˆð ÄyÐQ`ÓGa× t±m°c¸8Ðem×eqÑeqÕes ¨SÓ!1Ó tØ ä4=¼cÀ/ÐSZÓ>[Ó4\÷#ò #á0�CÑ0˜( KØ—<‘<”>ð ˜3‘Ð ÄSÈÐS^ÓE_×#h±k°d¸EÒcg F¨5£MÓ#hÓhö#ð
 ÀÖc°XÐT\×T`ÑT`ÕTb˜�s˜a˜S¤3 x£=Ñ0Ó0Òcð
ˆð *¨/Ñ:ˆØ+×2Ñ2°=À!ÓD×FÑFÀÑWÐZiÑiÐä
ˆ<Ó˜AÒÜÐcÓdÐdØ&�W×&Ñ& |Ó4€Nò Ø1ˆ
Ùnˆ	Üˆj×Ñ ¨*°jÀ,ÓOÔPÜØ×ÑØÙœ#˜oÓ.Ó/Ùœ#˜oÓ.Ó/Øó	ô	
ð ”U—Z‘ZÐ Ø”u—|‘|Ð$Ø”E—I‘IÐØÑ\Ð]ØÑqÐrØÑpÐqØÑqÐrØÑ]Ð^ð	!
ò 	ÑˆF�Hô Ø×!Ñ!Ø×%Ñ%Ó'Ù™h Ó7Ó8Ù™h Ó7Ó8Ù™hÐ'8Ó9Ó:ó	õð	ð(  Ð0Ø Ð0Ø˜)Ð$Ø˜)Ð$ð	(
ò 	Ñ#ˆJ˜ð ˜\Ò)Ø& zÑ2°9Ñ=�Ø$ ZÑ0°Ñ9�ÜØ˜w q˜kÐ)?ÀÀc¸{È-ÐXbÐWcÐcgÐhsÐgtÐtuÐvõð	ð +¬S°«\Ñ9¼SÀÓ=QÑQÐØ˜qÒ Ø$˜ˆIØ˜1Š}Ø× Ñ  Ô-ØÐ*Ø× Ñ Ð!2Ô3ØÐ*Ø× Ñ Ð!2Ô3ØÐ$Ø× Ñ  Ô-Ø!ŸY™Y y°°" ~Ó6ˆNÜ�9‹~ Ò!Ø '¨I°b©MÑ"9Ñ9�Ø&7¸=Ì3ÈwË<Ñ;WÑ&XÐ#ÜØ6Ð7HÐ6IÈÐTkÐloÐSpð q+Ø+9Ð*:¸*ÌCÐPYËNÐ]^ÒL^ÁSÐdfÐDgð  hTðUôð
 Ðùós @ùó
 Døô^ ò 	Úð	üò4 6ùò 5ùò Pùò Rùó )kùò "Jùò  `ùò` bùò _ùÚ nùóH !gùÛ"fùâ!Mùôùó !uùã#hùö#ùò
 dsä   ÇADÈADÍ1AD Ò?	AD(Ó>AD-Ô6AD2
Õ*AD7ÖAD<Ø<AEÛ#AEæ'AEç7AEè9AEó7
AEôAEô
AE!ô&AE!õAE,
õAE'õ(AE,
÷AE3÷2AE3ø/AE?ù
AE9ùAE9ùAE?ù,AFúAFÁD	AD%ÁD$AD%ÁE'AE,
ÁE9AE?c                ó  — t         j                  j                  |«      dk7  r4t        j                  t         j                  j                  |«      d¬«       t	        j
                  | d¬«      }|j                  dk7  r<t        d| › d|j                  › �t        j                  ¬«       |j                  «        y	|d
z   }t        |d«      5 }|j                  j                  d«      }|�t        |«      nd	}t        d|d¬«      }|j                  d¬«      D ]0  }|sŒ|j!                  t#        |«      «       |j%                  |«       Œ2 	 d	d	d	«       t        j&                  ||«       j)                  «        y	# 1 sw Y   Œ0xY w)a  
    Downloads a URL to a given path on disk.

    Args:
        url (str): The URL to download.
        path (str): The path to save the downloaded file.

    Raises:
        requests.HTTPError: If the HTTP request returns a non-200 status code.

    Returns:
        None
    ræ   T)Úexist_ok)ÚstreaméÈ   z"Exception when trying to download z. Response )ÚfileNÚ_partÚwbzContent-LengthÚB)ÚunitrÎ   Ú
unit_scaleé   )Ú
chunk_size)ÚosÚpathÚdirnameÚmakedirsÚrequestsr�   Ústatus_coder	  ÚsysÚstderrÚraise_for_statusÚopenÚheadersÚintr   Úiter_contentÚupdater†   ÚwriteÚrenameÚclose)	Úurlr’  ÚreqÚdownload_filepathÚfile_binaryÚcontent_lengthrÎ   ÚprogressrO   s	            r   Úhttp_getr¨  ‡  s:  € ô 
‡w�w‡��tÓ Ò"Ü
�‰”B—G‘G—O‘O DÓ)°DÕ9ä
�,‰,�s 4Ô
(€CØ
‡�˜#ÒÜÐ2°3°%°{À3Ç?Á?ÐBSÐTÔ[^×[eÑ[eÕfØ×ÑÔØà˜w™ÐÜ	Ð Ó	&ð )¨+ØŸ™Ÿ™Ð)9Ó:ˆØ'5Ð'A”�NÔ#ÀtˆÜ˜S¨¸$Ô?ˆØ×%Ñ%°Ð%Ó6ò 	)ˆEÚØ—‘¤ E£
Ô+Ø×!Ñ! %Õ(ñ	)÷	)ô ‡I�IÐ Ô&Ø‡N�NÕ÷)ð )ús   Ã
AE8Ä-E8Å8Fc                ój   — | D ]-  }t        | |   t        «      sŒ| |   j                  |«      | |<   Œ/ | S )au  
    Send a PyTorch batch (i.e., a dictionary of string keys to Tensors) to a device (e.g. "cpu", "cuda", "mps").

    Args:
        batch (Dict[str, Tensor]): The batch to send to the device.
        target_device (torch.device): The target device (e.g. "cpu", "cuda", "mps").

    Returns:
        Dict[str, Tensor]: The batch with tensors sent to the target device.
    )r   r   rµ   )ÚbatchÚtarget_devicer�   s      r   Úbatch_to_devicer¬  ¬  s>   € ð ò 6ˆÜ�e˜C‘j¤&Õ)Ø˜s™Ÿ™ }Ó5ˆE�#ŠJð6ð €Lr   c                óÐ   — | j                   j                  }|�|t        j                   j                  k(  r| j                   j                  S |dz   | j                   j                  z   S )aØ  
    Gives a full name (package_name.class_name) for a class / object in Python. Will
    be used to load the correct classes from JSON files

    Args:
        o: The object for which to get the full name.

    Returns:
        str: The full name of the object.

    Example:
        >>> from sentence_transformers.losses import MultipleNegativesRankingLoss
        >>> from sentence_transformers import SentenceTransformer
        >>> from sentence_transformers.util import fullname
        >>> model = SentenceTransformer('all-MiniLM-L6-v2')
        >>> loss = MultipleNegativesRankingLoss(model)
        >>> fullname(loss)
        'sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss'
    rù   )Ú	__class__Ú
__module__ÚstrÚ__name__)ÚoÚmodules     r   Úfullnamer´  ½  sR   € ð* �[‰[×#Ñ#€FØ€~˜¤3§=¡=×#;Ñ#;Ò;Ø�{‰{×#Ñ#Ð#à˜‰|˜aŸk™k×2Ñ2Ñ2Ð2r   c                ó8  — 	 | j                  dd«      \  }}	 t        j                  | «      }	 t        ||«      S # t        $ r | › d�}t        |«      ‚w xY w# t
        $ r t        j                  |«      }Y ŒJw xY w# t        $ r d|› d|› d�}t        |«      ‚w xY w)a:  
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.

    Args:
        dotted_path (str): The dotted module path.

    Returns:
        Any: The attribute/class designated by the last name in the path.

    Raises:
        ImportError: If the import failed.

    Example:
        >>> import_from_string('sentence_transformers.losses.MultipleNegativesRankingLoss')
        <class 'sentence_transformers.losses.MultipleNegativesRankingLoss.MultipleNegativesRankingLoss'>
    rù   r!   z  doesn't look like a module pathzModule "z" does not define a "z" attribute/class)Úrsplitr  rþ   Ú	importlibÚimport_moduler  ÚgetattrÚAttributeError)Údotted_pathÚmodule_pathÚ
class_nameÚmsgr³  s        r   Úimport_from_stringr¿  Ù  s¿   € ð$Ø"-×"4Ñ"4°S¸!Ó"<Ñˆ�Zð
6Ü×(Ñ(¨Ó5ˆðÜ�v˜zÓ*Ð*øô ò Ø�Ð=Ð>ˆÜ˜#ÓÐðûô ò 6Ü×(Ñ(¨Ó5Šð6ûô
 ò Ø˜˜Ð%:¸:¸,ÐFWÐXˆÜ˜#ÓÐðús%   ‚: ˜A ®A; ºAÁA8Á7A8Á;Bc                óÊ  — t        | t        j                  «      st        j                  | «      } t        j                  || j                  ¬«      }t        | «      } g }t        |t        | «      «      }t        t        d|z  d«      t        | «      «      }t        t        dt        | «      |«      d| ¬«      D �]š  }| |||z    | j                  z  }| j                  j                  dv r“||k\  }	|	j                  d«      }
|
|k\  }|j                  «       sŒ]|
|   }
||   }|
j                  «       }|j                  |d	¬
«      \  }}t!        |
|«      D ]'  \  }}|j#                  |d| j%                  «       «       Œ) ŒÄ|j                  |d	¬
«      \  }}t        t        |«      «      D ]ª  }||   d   |k\  sŒ||   j                  |d	¬
«      \  }}|d   |kD  rV|t        | «      k  rHt        d|z  t        | «      «      }||   j                  |d	¬
«      \  }}|d   |kD  r|t        | «      k  rŒH|j#                  |||k\     j%                  «       «       Œ¬ �Œ� t'        |d„ d	¬«      }g }t)        «       }t+        |«      D ]U  \  }}g }|D ]  }||vsŒ|j#                  |«       Œ t        |«      |k\  sŒ4|j#                  |«       |j-                  |«       ŒW t'        |d„ d	¬«      }|S )a¼  
    Function for Fast Community Detection.

    Finds in the embeddings all communities, i.e. embeddings that are close (closer than threshold).
    Returns only communities that are larger than min_community_size. The communities are returned
    in decreasing order. The first element in each list is the central point in the community.

    Args:
        embeddings (torch.Tensor or numpy.ndarray): The input embeddings.
        threshold (float): The threshold for determining if two embeddings are close. Defaults to 0.75.
        min_community_size (int): The minimum size of a community to be considered. Defaults to 10.
        batch_size (int): The batch size for computing cosine similarity scores. Defaults to 1024.
        show_progress_bar (bool): Whether to show a progress bar during computation. Defaults to False.

    Returns:
        List[List[int]]: A list of communities, where each community is represented as a list of indices.
    rÍ   rI   é2   r   zFinding clusters)rÊ   Údisable)ÚcudaÚnpur!   T)rË   r{   Nr9   c                ó   — t        | «      S rb   ©r†   r~   s    r   r   z%community_detection.<locals>.<lambda>N  s
   € ÌÈAË€ r   r€   c                ó   — t        | «      S rb   rÆ  r~   s    r   r   z%community_detection.<locals>.<lambda>^  s
   € Ä#ÀaÃ&€ r   )r   r   r   r   r   r.   rˆ   r†   r÷   r   r…   r"  Útyper;   r*  r‡   r¶   r‘   rŠ   r|   rŽ   r‹   rž  )r`   Ú	thresholdÚmin_community_sizerm   rl   Úextracted_communitiesÚsort_max_sizerc  r¾   Úthreshold_maskÚrow_wise_countÚlarge_enough_maskrË   r¼   Útop_k_indicesr  rS  Útop_k_valuesr�   Útop_val_largeÚtop_idx_largeÚunique_communitiesÚextracted_idsÚ
cluster_idÚ	communityÚnon_overlapped_communityrE  s                              r   Úcommunity_detectionrÙ  ý  s.  € ô0 �j¤%§,¡,Ô/Ü—\‘\ *Ó-ˆ
ä—‘˜Y¨z×/@Ñ/@ÔA€IÜ% jÓ1€JàÐô Ð/´°Z³ÓAÐÜœ˜AÐ 2Ñ2°BÓ7¼¸Z»ÓI€MäÜˆa”�Z“ *Ó-Ð4FÐTeÐPeôó *eˆ	ð   	¨I¸
Ñ,BÐCÀjÇlÁlÑRˆ
ð ×Ñ×!Ñ! _Ñ4à'¨9Ñ4ˆNØ+×/Ñ/°Ó2ˆNð !/Ð2DÑ DÐØ$×(Ñ(Ô*Øà+Ð,=Ñ>ˆNØ#Ð$5Ñ6ˆJð ×"Ñ"Ó$ˆAØ)Ÿ™°¸D˜ÓAÑˆAˆ}ô #& n°mÓ"Dò G‘��wØ%×,Ñ,¨W°V°e¨_×-CÑ-CÓ-EÕFñGð )Ÿo™oÐ0BÈD˜oÓQ‰OˆL˜!ô œ3˜|Ó,Ó-ò 
e�Ø ‘? 2Ñ&¨)Ó3à3=¸a±=×3EÑ3EÈÐ_cÐ3EÓ3dÑ0�M =ð (¨Ñ+¨iÒ7¸MÌCÐPZËOÒ<[Ü(+¨A°Ñ,=¼sÀ:»Ó(O˜Ø7AÀ!±}×7IÑ7IÈMÐcgÐ7IÓ7hÑ4˜ }ð (¨Ñ+¨iÒ7¸MÌCÐPZËOÓ<[ð *×0Ñ0°¸}ÐPYÑ?YÑ1Z×1aÑ1aÓ1cÕdò
eðA*eôZ #Ð#8Ñ>NÐX\Ô]Ðð ÐÜ“E€Mä!*Ð+@Ó!Aò ;Ñˆ
�IØ#%Ð Øò 	5ˆCØ˜-Ò'Ø(×/Ñ/°Õ4ð	5ô Ð'Ó(Ð,>Ó>Ø×%Ñ%Ð&>Ô?Ø× Ñ Ð!9Õ:ð;ô  Ð 2Ñ8HÐRVÔWÐàÐr   c                  ó.   ‡ — e Zd ZdZˆ fd„Zdˆ fd„Zˆ xZS )Údisabled_tqdmz«
    Class to override `disable` argument in case progress bars are globally disabled.

    Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324.
    c                ó.   •— d|d<   t        ‰| �  |i |¤Ž y )NTrÂ  )ÚsuperÚ__init__)Úselfr§   r¨   r®  s      €r   rÞ  zdisabled_tqdm.__init__o  s   ø€ Ø ˆˆyÑÜ‰Ñ˜$Ð) &Ó)r   c                óP   •— 	 t         ‰| �  |«       y# t        $ r	 |dk7  r‚ Y yw xY w)zBFix for https://github.com/huggingface/huggingface_hub/issues/1603Ú_lockN)rÝ  Ú__delattr__rº  )rß  Úattrr®  s     €r   râ  zdisabled_tqdm.__delattr__s  s3   ø€ ð	Ü‰GÑ Õ%øÜò 	Ø�wŠØñ ð	ús   ƒ “%¤%)rã  r°  ÚreturnÚNone)r±  r¯  Ú__qualname__Ú__doc__rÞ  râ  Ú__classcell__)r®  s   @r   rÛ  rÛ  h  s   ø„ ñô*÷ñ r   rÛ  c              #  óæ   K  — t         j                  j                  j                  }t        j                  | «       	 d–— t        j                  |«       y# t        j                  |«       w xY w­w)z»
    A context manager that will prevent any logging messages
    triggered during the body from being processed.

    Args:
        highest_level: the maximum logging level allowed.
    N)ÚloggingÚrootÚmanagerrÂ  )Úhighest_levelÚprevious_levels     r   Údisable_loggingrï  |  sI   è ø€ ô —\‘\×)Ñ)×1Ñ1€Nä‡O�O�MÔ"ð(Ûä�‰˜Õ'øŒ�‰˜Õ'üs   ‚:A1½A ÁA1ÁA.Á.A1c           
     ó6   — t        t        | d||||¬«      «      S )a}  
    Checks if the given model name or path corresponds to a SentenceTransformer model.

    Args:
        model_name_or_path (str): The name or path of the model.
        token (Optional[Union[bool, str]]): The token to be used for authentication. Defaults to None.
        cache_folder (Optional[str]): The folder to cache the model files. Defaults to None.
        revision (Optional[str]): The revision of the model. Defaults to None.
        local_files_only (bool): Whether to only use local files for the model. Defaults to False.

    Returns:
        bool: True if the model is a SentenceTransformer model, False otherwise.
    zmodules.json)ÚtokenÚcache_folderÚrevisionÚlocal_files_only)r  Úload_file_path)Úmodel_name_or_pathrñ  rò  ró  rô  s        r   Úis_sentence_transformer_modelr÷  �  s+   € ô( ÜØØØØ%ØØ-ô	
ó	ð 	r   c           	     óÈ   — t         j                  j                  | |«      }t         j                  j                  |«      r|S 	 t	        | ||d|||¬«      S # t
        $ r Y yw xY w)a²  
    Loads a file from a local or remote location.

    Args:
        model_name_or_path (str): The model name or path.
        filename (str): The name of the file to load.
        token (Optional[Union[bool, str]]): The token to access the remote file (if applicable).
        cache_folder (Optional[str]): The folder to cache the downloaded file (if applicable).
        revision (Optional[str], optional): The revision of the file (if applicable). Defaults to None.
        local_files_only (bool, optional): Whether to only consider local files. Defaults to False.

    Returns:
        Optional[str]: The path to the loaded file, or None if the file could not be found or loaded.
    úsentence-transformers)Úfilenameró  Úlibrary_namerñ  Ú	cache_dirrô  N)r‘  r’  r.  Úexistsr   r  )rö  rú  rñ  rò  ró  rô  Ú	file_paths          r   rõ  rõ  °  sj   € ô. —‘—‘Ð/°Ó:€IÜ	‡w�w‡~�~�iÔ ØÐðÜØØØØ0ØØ"Ø-ô
ð 	
øô ò Ùðús   ÁA Á	A!Á A!c           	     óJ  — t         j                  j                  | |«      }t         j                  j                  |«      r|S | ||dvr|› d�ndd|||t        dœ}	 t        di |¤Ž}t         j                  j                  ||«      S # t        $ r d|d<   t        di |¤Ž}Y Œ;w xY w)	af  
    Loads the directory path for a given model name or path.

    Args:
        model_name_or_path (str): The name or path of the model.
        directory (str): The directory to load.
        token (Optional[Union[bool, str]]): The token for authentication.
        cache_folder (Optional[str]): The folder to cache the downloaded files.
        revision (Optional[str], optional): The revision of the model. Defaults to None.
        local_files_only (bool, optional): Whether to only use local files. Defaults to False.

    Returns:
        Optional[str]: The directory path if it exists, otherwise None.
    )ræ   rù   z/**Nrù  )Úrepo_idró  Úallow_patternsrû  rñ  rü  rô  Ú
tqdm_classTrô  rc   )r‘  r’  r.  rý  rÛ  r   r  )	rö  Ú	directoryrñ  rò  ró  rô  Údir_pathÚdownload_kwargsÚ	repo_paths	            r   Úload_dir_pathr  Ú  s±   € ô. �w‰w�|‰|Ð.°	Ó:€HÜ	‡w�w‡~�~�hÔØˆð &ØØ/8À	Ñ/I˜Y˜K sÑ+ÈtØ/ØØ!Ø,Ü#ñ	€Oð9Ü%Ñ8¨Ñ8ˆ	ô
 �7‰7�<‰<˜	 9Ó-Ð-øô	 ò 9à.2ˆÐ*Ñ+Ü%Ñ8¨Ñ8Š	ð9ús   ÁB ÂB"Â!B"c                óB   ‡ — t        j                  ‰ «      ˆ fd„«       }|S )Nc                óº   •— |j                  dd «      }|rd|vrt        j                  d«       ||d<   t        |«      dk\  rg |d d ¢d ‘|dd  ¢­} ‰| g|¢­i |¤ŽS )NÚ	repo_namer   zfProviding a `repo_name` keyword argument to `save_to_hub` is deprecated, please use `repo_id` instead.rI   )Úpopr  r  r†   )rß  r§   r¨   r
  Úfuncs       €r   Úwrapperz+save_to_hub_args_decorator.<locals>.wrapper
  s|   ø€ ð —J‘J˜{¨DÓ1ˆ	Ù˜¨&Ñ0Ü�N‰NØxôð !*ˆF�9Ñô ˆt‹9˜Š>Ø/�T˜"˜1�XÐ/˜tÐ/ d¨1¨2 hÑ/ˆDá�DÐ*˜4Ò* 6Ñ*Ð*r   )Ú	functoolsÚwraps)r  r  s   ` r   Úsave_to_hub_args_decoratorr  	  s%   ø€ Ü‡_�_�TÓó+ó ð+ð €Nr   c                 óð  — t         j                  j                  «       rkt         j                  j	                  «       rt         j                  j                  «       } n)t        t        j                  j                  dd«      «      } d| › �S t         j                  j                  j                  «       ryt        «       ryt        j                  j                  d«      �ddlm c m} |j                  «       ryy	)
aO  
    Returns the name of the device where this module is running on.

    This function only supports single device or basic distributed training setups.
    In distributed mode for cuda device, it uses the rank to assign a specific CUDA device.

    Returns:
        str: Device name, like 'cuda:2', 'mps', 'npu', 'hpu', or 'cpu'
    Ú
LOCAL_RANKr   zcuda:ÚmpsrÄ  Úhabana_frameworksNÚhpur‰   )r   rÃ  Úis_availableÚdistributedÚis_initializedÚget_rankrœ  r‘  Úenvironr�   Úbackendsr  r   r·  ÚutilÚ	find_specÚhabana_frameworks.torch.hpur  )Ú
local_rankÚhthpus     r   Úget_device_namer!    s°   € ô ‡z�z×ÑÔ Ü×Ñ×+Ñ+Ô-Ü×*Ñ*×3Ñ3Ó5‰JäœRŸZ™ZŸ^™^¨L¸!Ó<Ó=ˆJØ�z�lÐ#Ð#Ü	�‰×	Ñ	×	(Ñ	(Ô	*ØÜ	Ô	!ØÜ	�‰×	!Ñ	!Ð"5Ó	6Ð	Bß3Ð3à×ÑÔØØr   c                óZ   — 	 t        | «      }|d   | k(  xr ||d   v S # t        $ r Y yw xY w)zB
    Checks if a package is available from the correct owner.
    ÚNamez	Home-pageF)r   r   )Úpackage_nameÚownerÚmetas      r   Úcheck_package_availabilityr'  9  sA   € ðÜ˜Ó%ˆØ�F‰|˜|Ñ+ÒJ°¸¸kÑ9JÐ0JÐJøÜò Ùðús   ‚ ž	*©*c                 ó   — t        dd«      S )zJ
    Returns True if the Huggingface accelerate library is available.
    Ú
accelerateÚhuggingface©r'  rc   r   r   Úis_accelerate_availabler,  D  s   € ô & l°MÓBÐBr   c                 ó   — t        dd«      S )zH
    Returns True if the Huggingface datasets library is available.
    rÿ   r*  r+  rc   r   r   rý   rý   K  s   € ô & j°-Ó@Ð@r   c                 ó.   — t        «       xr
 t        «       S )z 
    Returns True if we have the required dependencies for training Sentence
    Transformers models, i.e. Huggingface datasets and Huggingface accelerate.
    )r,  rý   rc   r   r   Úis_training_availabler/  R  s   € ô
 #Ó$Ò@Ô)>Ó)@Ð@r   c               #  ó|   K  — ddl m} m}m}  |«       }	 |r | «        d–— |r |«        yy# |r |«        w w xY w­w)zN
    A context manager that will disable caching in the datasets library.
    r   )Údisable_cachingÚenable_cachingÚis_caching_enabledN)rÿ   r1  r2  r3  )r1  r2  r3  Úis_originally_enableds       r   Údisable_datasets_cachingr5  Z  sF   è ø€ ÷
 MÑLá.Ó0ÐðÙ ÙÔÛá ÙÕð !øÑ ÙÕð !üs   ‚<•- ¢<­9¹<)r   úlist | np.ndarray | Tensorrä  r   )r   r   rä  r   )r   r   r+   r   rä  r   )r   r6  r+   r6  rä  r   )r   r6  r+   r6  )rQ   r   rR   r   rä  r   )r`   r   rä  r   )r`   ú
np.ndarrayre   ú
int | Nonerä  r7  )r`   útorch.Tensorre   r8  rä  r9  )r`   únp.ndarray | torch.Tensorre   r8  rä  r:  )rw   z	list[str]rl   r  rm   rœ  ro   rœ  rp   rœ  rq   rœ  rr   rœ  rs   ú"Callable[[Tensor, Tensor], Tensor]rä  úlist[list[float | int]])r`   r   ro   rœ  rp   rœ  rq   rœ  rr   rœ  rs   r;  rä  r<  )rä  ú"list[list[dict[str, int | float]]])rº   r   r»   r   ro   rœ  rp   rœ  rr   rœ  rs   r;  rä  r=  )NNNNr   NNNNNé   rÆ   FrÅ   ri   i @  FFTNN)0r/  r   rv   r   r0  ú
str | Noner1  r?  r2  zlist[str] | Noner3  zCrossEncoder | Nonerû   rœ  rú   r8  rÕ   úfloat | Noner“   r@  rÓ   r@  rÔ   r@  r4  rœ  r5  zLiteral['random', 'top']r6  r  r7  z=Literal['triplet', 'n-tuple', 'labeled-pair', 'labeled-list']rm   rœ  r8  rœ  r9  r  r:  zlist[str] | boolr;  r  r<  zbool | Noner=  r@  rä  r   )r¢  r°  r’  r°  rä  rå  )rª  údict[str, Any]r«  r   rä  rA  )rä  r°  )r»  r°  rä  rÈ  )rö   rª   r�  F)r`   ztorch.Tensor | np.ndarrayrÉ  rì   rÊ  rœ  rm   rœ  rl   r  rä  zlist[list[int]])NNNF)rö  r°  rñ  úbool | str | Nonerò  r?  ró  r?  rô  r  rä  r  )rö  r°  rú  r°  rñ  rB  rò  r?  ró  r?  rô  r  rä  r?  )rö  r°  r  r°  rñ  rB  rò  r?  ró  r?  rô  r  rä  r?  )r$  r°  r%  r°  rä  r  )rä  r  )RÚ
__future__r   r  r·   r·  rê  r‘  rƒ   rÖ   r—  Ú
contextlibr   Úimportlib.metadatar   r   Útypingr   r   r	   r
   r   Únumpyr®   r•  r   Úhuggingface_hubr   r   r   r   r   r   Útqdm.autonotebookÚtransformersr   Ú	getLoggerr±  r  rÿ   r   Ú0sentence_transformers.cross_encoder.CrossEncoderr   Ú)sentence_transformers.SentenceTransformerr   r   r$   r&   r,   r)   r5   r7   r4   rA   rE   rG   rK   r[   r.   rf   rx   ru   r©   r¦   r„  r¨  r¬  r´  r¿  rÙ  rÛ  ÚCRITICALrï  r÷  rõ  r  r  r!  r'  r,  rý   r/  r5  rc   r   r   ú<module>rO     s  ðÝ "ã Û Û Û Û 	Û Û Û 
Ý %ß =ß BÕ Bã Û Û ß >ß  Ý Ý "Ý /à	ˆ×	Ñ	˜8Ó	$€áÝ åMÝMóóóóó4ó&Pó"*ó"ó"%ó"0ó"%ó"8ó"!óD
Að 
Ú \ó 
Ø \ð 
Ú `ó 
Ø `ó*ðF $ØØ Ø#ØØØ9@ð*àð*ð ð*ð ð	*ð
 ð*ð ð*ð ð*ð ð*ð 7ð*ð ó*ð^ !Ø#ØØØ9@ðFØðFàðFð ðFð ð	Fð
 ðFð 7ðFð óFóR,ð  Ø#ØØ9@ðMØðMàðMð ðMð ð	Mð
 ðMð 7ðMð (óMðf &*Ø'+Ø#Ø)-ØØ Ø"Ø"Ø$(Ø$(ØØ27Ø#ØS\ØØ!ØØ*/ØØ#Øð/|	Øð|	àð|	ð #ð|	ð %ð	|	ð
 ð|	ð 'ð|	ð ð|	ð ð|	ð ð|	ð ð|	ð "ð|	ð "ð|	ð ð|	ð 0ð|	ð ð|	ð  Qð!|	ð" ð#|	ð$ ð%|	ð& ð'|	ð( (ð)|	ð* ð+|	ð, ð-|	ð. ð/|	ð0 ó1|	ó~"óJó"3ó8!ðL Ø ØØ#ðcØ)ðcàðcð ðcð ð	cð
 ðcð ócôV�Dô ð( Ø")×"2Ñ"2ò (ó ð(ð*  $Ø#ØØ"ðØðàðð ðð ð	ð
 ðð 
óðF  $Ø#ØØ"ð'Øð'àð'ð ð'ð ð	'ð
 ð'ð ð'ð ó'ðZ  $Ø#ØØ"ð,.Øð,.àð,.ð ð,.ð ð	,.ð
 ð,.ð ð,.ð ó,.ò^ó(ó8óCóAóAð ñó ñr   