
    rh                    p   d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	Z
d dlZd dlmZ d dlmZ ddlmZ  ej"                  e      Zerd dlmZ d d	lmZ d d
lmZ 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)    )annotationsN)TYPE_CHECKINGLiteral)trange)tqdm   )is_datasets_availableDataset)CrossEncoder)SentenceTransformerc                (   t               st        d      t        |       dk(  r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
}|dvrt        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 } t        | |         }!t        | |         }"|du}#|#s|"}t        t"        j%                  ||"z               }t'        |      D $%ci c]  \  }$}%|%|$
 }&}$}%|!j)                         }'t        t"        j%                  |!            }!t'        |!      D $(ci c]  \  }$}(|(|$
 })}$}(t        |!      }*t+        j,                  |*      j/                  d      }+|j0                  },|*t        |'      k7  r|rt!        d|* dt        |'       d       |dkD  r%t3        j4                  |      }-t!        d|-dd       d}.d}/|rt7        j8                  |d !       |j:                  j<                  xs d"}0t?        j@                  |0d"jC                  |!      z   jE                         d#$      jG                         }1t?        j@                  |0d"jC                  |      z   jE                         d#$      jG                         }2t6        jH                  jC                  |d%|1 d&      }3t6        jH                  jC                  |d'|2 d&      }4t6        jH                  jK                  |3      r3t3        jL                  |3      }/|rt!        d(|3 d)|/jN                   d*       t6        jH                  jK                  |4      r3t3        jL                  |4      }.|rt!        d+|4 d)|.jN                   d*       |.|/|rl|jQ                  tS        |tT              rdn|,      }5|.|jE                  ||5|d d d ||-      }.|/|jE                  |!|5|d d d ||-      }/|jW                  |5       n4|.|jE                  ||d d d ||.      }.|/|jE                  |!|d d d ||.      }/|rt6        jH                  jK                  3      s&t3        jX                  |3|/       |rt!        d/|3        t6        jH                  jK                  4      s&t3        jX                  |4|.       |rt!        d0|4        |r=ddl-}6|6j]                  |j_                               }7	 |6ja                         }8d |8_1        d |8_2        |6jg                  |7|81      }7|7jk                  |.       g }9g }:tm        dt        |/      |d23      D ]E  };|/|;|;|z    }<|7jo                  |<|dz   4      \  }=}>|9jq                  |=       |:jq                  |>       G t+        jr                  t3        jt                  |9d5            jw                  |,      }=t+        jr                  t3        jt                  |:d5            jw                  |,      }>n?|jy                  |/|.      jw                  |,      }=t+        jz                  |=||z   d6      \  }=}>t}        |*      D ?cg c]  }?g  }@}?t        |'|"      D ]!  \  }(}A|)|(   }B@|B   jq                  |&|A          # @D Ccg c]  }Ct        |C       }D}Cg }"g }'t}        |*      D ]B  }$|"j                  @|$   D Ecg c]  }E||E   	 c}E       |'j                  |!|$   gD|$   z         D @D Ccg c]  }Ct+        j                  |C|,7       }@}C|/t}        |*      D $?cg c]  }$t}        D|$         D ]  }?|$  c}?}$   }/|.t+        j                  @      j                            }F|j                  |/|F      jw                  |,      }G~/~F~.||
||t        t'        |>      d8t        |>      9      D ]O  \  }$}H|!|$   }(|HD Icg c]  }I||I   	 }J}I|j                  t        t        |(g|dz   z  |J            |d :      }K|K|=|$<   Q |j                  t        t        |'|"            |d :      }G|sUt+        j                  t}        |*      D Lcg c]  }Lt+        j                  |>|L   @|L           c}L      }Mt        d;       |=|M<   |=j                         }N|
|Qt+        j                  |*Gj0                  |Gj                  <      }Od}Pt}        |*      D ].  }Lt+        j                  GP|PD|L   z          O|L<   |P|D|Ldz
     z  }P0 |
p|=|
z   Oj                  |=j                  d      d      j                  kD  }Qt        d;       |=|Q<   |Qj                         j                         }R|RrR|RNz  d=| d><   |N|Rz  }N|s|=Oj                  |=j                  d      d      j                  d|z
  z  kD  }Qt        d;       |=|Q<   |Qj                         j                         }R|RrR|RNz  d=| d?<   |N|Rz  }N|?|=|kD  }Qt        d;       |=|Q<   |Qj                         j                         }R|RrR|RNz  d=| d@<   |	?|=|	k  }Qt        d;       |=|Q<   |Qj                         j                         }R|RrR|RNz  d=| dA<   t+        jz                  |=|d6      \  }S}T|>|+|Tf   }>|r|>dd|df   }>Sdd|df   }S|dk(  r|>ddd|f   }>Sddd|f   }Sn|dBk(  r|>j                  d      Sj                         j                  d      z
  }U|Uj                  |C      }U|UD Vcg c]"  }Vt        j                  t}        |V      |4      $ }W}V|>|+|Wf   }>S|+|Wf   }S|Sj                  dd D      \  }S}T|>|+|Tf   }>t+        j                  t}        |*      D $cg c]  }$|>|$   j                  D|$   d       c}$      }>t+        j                  t}        |*      D $cg c]  }$S|$   j                  D|$   d       c}$      }S|rt!        dE       |d	k(  rGSt        d;       k7  }Xt+        j                  |>      }Yt+        j                  |>      }Z|>|X   }>|S|X   }Sd}Pt}        |*      D ]c  }Lt+        j                  |L      j                  D|L   |      YP|P|D|L   z    @|L   j                  |d      j                  Z|P|P|D|L   z    |P|D|L   z  }Pe YX   }YZ|X   }@|g |g dFg i}[t        |Y|@|>      D ]K  \  }\}]}^[|   jq                  |!|\          |[|   jq                  ||]          |[dF   jq                  ||^          M Gj                  |d      j                  X   Sz
  }_nW|dGk(  rSt        d;       k7  }X|g |g dHg i}[t}        |*      D ]  }B@|B   D ]D  }][|   jq                  |!B          |[|   jq                  ||]          |[dH   jq                  d       F t        |>B   S|B         D ]W  \  }^}`|`t        d;       k(  r[|   jq                  |!B          |[|   jq                  |^          |[dH   jq                  d       Y  SX   }SGj                  |d      j                  |X   |Sz
  }_nI|dIv r7St        d;       k7  j                  dJ      }X|S|X   }S|>|X   }>|t'        |X      D $acg c]  \  }$}a|as	|'|$    c}a}$|t'        X      D $acg c]  \  }$}a|as	|"|$    c}a}$it'        |>j                  dK      D ;bcci c]  \  };}bdL|; |bD ccg c]  }c||c   	 c}c c}c}b};}[|dMk(  r<t+        j                  GX   j/                  d      SgdJ      j                         [dN<   Sj                         }SGj                  |d      j                  X   j                         |Sz
  }_n|dOk(  rSt        d;       k7  }X|t'        |X      D $dcg c]  \  }$}d|dj                         s|'|$    c}d}$|t'        t        X|>            D $dea7cg c]D  \  }$\  }d}e|dj                         r,|"|$   gt        de      D a7cg c]  \  }a}7|as	||7    c}7}az   F c}7}a}e}d}$dPXD dcg c]&  }d|dj                         sdgdgt        d      z  z   ( c}di}[SX   }SGj                  |d      j                  |X   |Sz
  }_t        [      dk(  rt        dQ       |j                  [      }f|rdR}gdS }ht!        |gj                  dTdUdVdW             t!        |gj                  dX |ht        G             |ht        S            d"             dYt*        j4                  fdZt*        j                  fd[t*        j                  fd\d] fd^d_ fd`da fdbdc fddde ffD ]T  \  }i}jt!        gj                  |ij                          h |jG             |h |jS             |h |j_                         V d>|
fd?|fd@|fdA|	ffD ]4  \  }k}l|k| v s| k   df   }m| |k   dg   }nt!        dh|mdidj|ndkdl|k dml dn	       6 |t        |       z  t        S      z
  }o|odkD  rdog}p|dkD  rpjq                  dp       |
pjq                  d>       |pjq                  d?       |pjq                  d@       dqjC                  pdd       }qt        |p      dkD  rqdrpd   z   z  }qo|t        |       z  z  }rt!        ds|o dt|rdkduq dvt        p      dkD  rdwnd" dx	       fS c c}%}$w c c}(}$w # th        $ r Y w xY wc c}?w c c}Cw c c}Ew c c}Cw c c}?}$w c c}Iw c c}Lw c c}Vw c c}$w c c}$w c c}a}$w c c}a}$w c c}cw c c}c}b};w c c}d}$w c c}7}aw c c}7}a}e}d}$w c c}dw )yu>  
    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.

    Supports prompt formatting for models that expect specific instruction-style input.

    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".
        query_prompt_name (Optional[str], optional): The name of a predefined prompt to use when encoding the first/anchor dataset column.
            It must match a key in the ``model.prompts`` dictionary, which can be set during model initialization
            or loaded from the model configuration.

            For example, if ``query_prompt_name="query"`` and the model prompts dictionary includes {"query": "query: "},
            then the sentence "What is the capital of France?" is transformed into: "query: What is the capital of France?"
            before encoding. This is useful for models that were trained or fine-tuned with specific prompt formats.

            Ignored if ``query_prompt`` is provided. Defaults to None.

        query_prompt (Optional[str], optional): A raw prompt string to prepend directly to the first/anchor dataset column during encoding.

            For instance, `query_prompt="query: "` transforms the sentence "What is the capital of France?" into:
            "query: What is the capital of France?". Use this to override the prompt logic entirely and supply your own prefix.
            This takes precedence over ``query_prompt_name``. Defaults to None.
        corpus_prompt_name (Optional[str], optional): The name of a predefined prompt to use when encoding the corpus. See
            ``query_prompt_name`` for more information. Defaults to None.
        corpus_prompt (Optional[str], optional): A raw prompt string to prepend directly to the corpus during encoding.
            See ``query_prompt`` for more information. Defaults to None.
        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", "n-tuple-scores", "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`.
            - "n-tuple-scores": (anchor, positive, negative_1, ..., negative_n, score) tuples, i.e. 2 + num_negatives columns, but with one score value that's a list of similarities for the query-positive and each of the query-negative pairs. Useful for e.g. :class:`~sentence_transformers.sparse_encoder.losses.SparseMarginMSELoss`.
            - "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.
        cache_folder (str, optional): Directory path for caching embeddings. If provided, the function will save
            ``query_embeddings_{hash}.npy`` and ``corpus_embeddings_{hash}.npy`` under this folder after the first run,
            and on subsequent calls will load from these files if they exist to avoid recomputation. The hashes are
            computed based on the model name and the queries/corpus. Defaults to None.
        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   z9The dataset is empty. Please provide a non-empty dataset.r
   r      z)Dataset must contain exactly two columns.Ntripletn-tuplezrThe `as_triplets` parameter is deprecated. Use the `output_format` parameter instead. Setting `output_format` to `z`.topzWhen 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.)r   r   n-tuple-scoreslabeled-pairlabeled-listzInvalid output_format: z[. Must be one of 'triplet', 'n-tuple', 'n-tuple-scores', 'labeled-pair', or 'labeled-list'.zThe `margin` parameter is deprecated. Use the `absolute_margin` and/or `relative_margin` parameter instead. Setting `absolute_margin` to `
   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.zFound z unique queries out of z total queries.zFound an average of z.3fz positives per query.T)exist_ok F)usedforsecurityquery_embeddings_z.npycorpus_embeddings_z%[Cache] Loaded query embeddings from z (shape=)z&[Cache] Loaded corpus embeddings from )target_devices)pool
batch_sizenormalize_embeddingsconvert_to_numpyshow_progress_barprompt_nameprompt)r    r!   r"   r#   r$   r%   z"[Cache] Saved query embeddings to z#[Cache] Saved corpus embeddings to )cozQuerying FAISS index)desc)k)axis)r(   dim)devicezRescoring with CrossEncoder)r'   total)r    convert_to_tensorinf)r+   dtype)skippedratioabsolute_marginrelative_margin	max_score	min_scorerandom)min)r*   
descendingz/Negative candidates mined, preparing dataset...negativer   label)r   r   )r*   )start	negative_r   scorer   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,)
isinstancetorchTensoritem)values    |/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/sentence_transformers/util/hard_negatives.py<lambda>z%mine_hard_negatives.<locals>.<lambda>  s)    Juell<[ejjl3%7 dijkcl     MetricPositiveNegative
DifferenceCountmeanmedianstdr7   c                h    | j                         dkD  rt        j                  |       S t        d      S )Nr   r.   )numelrB   r7   floatscoress    rF   rG   z%mine_hard_negatives.<locals>.<lambda>  s'    8J599V#4 PUV[P\ rH   z25%c                    | j                         dkD  r%t        j                  | j                         d      S t        d      S )Nr   g      ?qr.   rR   rB   quantilerS   rT   s    rF   rG   z%mine_hard_negatives.<locals>.<lambda>  0    V\\^^_M_5>>&,,.D#I ejkpeq rH   z50%c                    | j                         dkD  r%t        j                  | j                         d      S t        d      S )Nr   g      ?rW   r.   rY   rT   s    rF   rG   z%mine_hard_negatives.<locals>.<lambda>  s0    FLLN]^L^5>>&,,.C#H dijodp rH   z75%c                    | j                         dkD  r%t        j                  | j                         d      S t        d      S )Nr   g      ?rW   r.   rY   rT   s    rF   rG   z%mine_hard_negatives.<locals>.<lambda>  r[   rH   maxc                h    | j                         dkD  rt        j                  |       S t        d      S )Nr   z-inf)rR   rB   r^   rS   rT   s    rF   rG   z%mine_hard_negatives.<locals>.<lambda>  s'    8J599V#4 PUV\P] rH   r0   r1   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.)ar	   ImportErrorlen
ValueErrordatasetsr   column_namesloggerwarninglist	to_pandasgroupbycountto_dictvaluesr^   printdictfromkeys	enumeratecopyrB   arange	unsqueezer+   nprN   osmakedirsmodel_card_data
base_modelhashlibsha256joinencode	hexdigestpathexistsloadshapestart_multi_process_poolrA   boolstop_multi_process_poolsavefaissIndexFlatIP get_sentence_embedding_dimensionGpuMultipleClonerOptionsshard
useFloat16index_cpu_to_all_gpus	Exceptionaddr   searchappend
from_numpyconcatenateto
similaritytopkrangezipextendtensorcattolistsimilarity_pairwiser   predictstackisinrS   rR   emptyr/   r7   repeatsizeTsumrD   isinfclampr6   samplesort
empty_likeallflattenany	from_dictformatrO   rP   
capitalize)sdatasetmodelanchor_column_namepositive_column_namecorpuscross_encoderrb   ra   r4   r5   r2   r3   num_negativessampling_strategyquery_prompt_namequery_promptcorpus_prompt_namecorpus_promptinclude_positivesoutput_formatr    faiss_batch_size	use_faissuse_multi_processverbosecache_folder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corpus_embeddingsquery_embeddings
model_name
query_hashcorpus_hashquery_cache_filecorpus_cache_filer   r   indexr&   scores_listindices_listiquery_chunkrU   indices_positive_indicespositive	query_idxp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_valuer0   r1   missing_negatives	solutionsconsiderationsmissing_negatives_ratioss                                                                                                                      rF   mine_hard_negativesr     s   ` !"cdd
7|qTUU  ""G!37!B$QZ#7w#F&qz&:s7|q?PDEE%0	i++8/=	

 N$$! E)NNe I%NN Q &Mdd%m_  5P  Q
 	
  --<,=RA	
 ##$67==?GGIJ^_ffh +,M&/*EI^!]R%78=HI "M1MAIt	Itu))4VWXL7-./GW123ID(O $-- 234F .7v->?	T$)?J? ,,.K4==)*G09'0BC*#u5#:CKCGIY'11"5I\\FC$$yk!8[9I8J/Z[q"$''*=">$%<S$AAVWX
L40**55;
^^Z"'''2B%B$J$J$L^cdnnp
nnj2776?&B%J%J%L^cdnnp77<<8I*UY6Z[GGLL9KK=X\7]^77>>*+!ww'78=>N=OxXhXnXnWoopqr77>>+, "(9 :>?P>QQYZkZqZqYrrstu  $4$<11'12CT'JtPa 2 D !($)LL))-%)&* 2( %1 	%!  '#(<<))-%)&* 1' $0 	$  ))$/ ($)LL))-%)&* 2( %1 %!  '#(<<))-%)&* 1' $0 $  ww~~./GG$&67:;K:LMNww~~/0GG%'89;<M;NOP!!%"H"H"JK	//1BBH BM','B'B5R'B'PE 			#$3/02BI_` 	)A*1q3C/CDK#ll;)a-lHOFGv&(		)
 !!"..1"EFII&Q""2>>,Q#GHKKFS !!"24EFII&Q  **Vy=/HaP
 %*)$45q55{I6 Ax&	#**:h+?@A $44a3q64K4 IKY >9I#9NOg&/OPGCL>K,<<=> AQQ1Qv6QQ (i8H(jRWXcdgXhRi(jQ(j(jk+EII6F,G,N,N,PQ//0@BUVYYZ`aO  #'BiF["&y'9@]ehipeq"r 	&CCLE;H!I4&,!I!I'//S%IM24FGH%"& 0 K
 &F3K	& (//[),-!" 0 
 NST]N^_UUZZ(8(?@_
 "'u}\\^N "o&A $kk)O<R<RZiZoZop	9% 	0E).?9y[fgl[mOm3n)o&UQY//I	0 &$69L9S9STZT_T_`aTbde9f9h9hhO',U|mF?#)--/446K>IT_bpTp2q./+-&$':'A'A&++a.RS'T'V'VZ[^mZm'nnO',U|mF?#)--/446K>IT_bpTp2q./+-  9,#(<-%))+002&$~5)L%  9,#(<-%))+002&$~5)L% &+ZZ)%K"O]i./G!YZ-()!YZ-8 E!!^m^+,)!^m^*;<	h	&ll1o(=(=(?(C(CA(FF!''M':U`a'v}}U7^}Eaa)[01))[*@A)8)=)=!PT)=)U&)]23 iiUS\M]^c,,[-=qA^_Gii]bcl]m nVY!5!<!<[=Mq!Q noO?@	!)eEl]:))'2&&w//*)/: 	9% 	,EINV[I\IcIcE"MJN9y;u3E'EF !'..}a@BB 	IE0B$BC U++I	, (8&7  "
 7:.JZ\c6d 	B2Jl+,33GJ4GH-.55f\6JK$++F<,@A	B ,22=!DFFWZii	.	()eEl]:  "R
 y) 
	0I 0 ; 0/077	8JK1299&:NOW%,,Q/0 14GI4FXaHb0c 0,n!eEl]2/077	8JK1299&:NOW%,,Q/0
	0 */:+22=!DFFWZii	7	7*uU|m;@@Q@G)/:/* 9_C] fic4aeS!1 f 9_C]"fic4ae9S>"f

 '0		&C "A{ A3!Mg&/!MM
 ,,$)II 1;;B?QWX%fh ! *113+22=!DFFW__adss	.	()eEl]: yQ`Ga tmc8emeqeqesS!1 t 4=c/SZ>[4\# #0C0(K<<> 3 SS^E_#hkdEcgF5M#hh#
 cXT\T`T`TbsaS3x=00c
 */:+22=!DFFWZii
<Acdd&W&&|4N 1
n	j*j,OP#o./#o./		
 UZZ u||$EII\]qrpqqr]^	!
 	FH !!%%'h78h78h'89:		( 00)$)$	(
 	#J \)&z29=$Z09wqk)?c{-XbWccghsgttuv	 +S\9S=QQq $I1}  -*  !23*  !23$  -!YYy"~6N9~!'IbM"99&7=3w<;W&X#67H6ITkloSp q++9*:*CPYN]^L^SdfDg  hTU
 { @
 DX  		4 6 5 P R )k "J  `` b _ nN !g"f!M  !u#h#
 ds    AO3AO931AO? 	APAPAP
AP2AP#AP)#AP. 'AP3AP8AP=
AQ(AQ
AQAQ2AQ
@AQ@AQ
C AQCAQC?/AQ&D.
AQ D9AQ E AQ&EAQ/E)AQ/O?	APPAPQAQ
Q AQ&)NNNNr   NNNNN   r   NNNNFr       i @  FFTNNN):r   r   r   r   r   
str | Noner   r  r   zlist[str] | Noner   zCrossEncoder | Nonerb   intra   z
int | Noner4   float | Noner5   r  r2   r  r3   r  r   r  r   zLiteral['random', 'top']r   r  r   r  r   r  r   r  r   r   r   zOLiteral['triplet', 'n-tuple', 'n-tuple-scores', 'labeled-pair', 'labeled-list']r    r  r   r  r   r   r   zlist[str] | boolr   r   r   r  r   zbool | Noner   r  returnr   )
__future__r   r}   loggingry   r6   typingr   r   numpyrx   rB   r   r   tqdm.autonotebookenvironmentr	   	getLogger__name__ri   rg   r   0sentence_transformers.cross_encoder.CrossEncoderr   )sentence_transformers.SentenceTransformerr   r   rH   rF   <module>r*     s   "   	  )    " .			8	$ MM &*'+#)- ""$($(27$(#%) $#en!*/##9hhh #h %	h
 h 'h h h h h "h "h h 0h "h  !h" ##h$ %h& 'h( c)h* +h, -h. /h0 (1h2 3h4 5h6 7h8 9h: ;hrH   