
    rhW4                        d dl mZ d dlmZ d dlmZmZ d dlZd dlmZm	Z	 d dl
mZ d dlmZ d dlmZ d d	lmZ  G d
 de	j$                        Zy)    )annotations)Iterable)AnyLiteralN)Tensornn)PreTrainedTokenizerBase)StaticEmbedding)SentenceTransformer)all_gather_with_gradc                  z     e Zd Z	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZd	dZd
dZedd       Z xZ	S )GISTEmbedLossc	                $   t         	|           || _        || _        || _        t        j                  d      | _        t        |d      rt        |d      st        d      t        |j                  t              rt        |j                  t              st        d      |j                  j                         |j                  j                         k7  xs |j                  |j                  k  | _        | j                  rC| j                  j                  | _        t        | j                  d   t               rt        d      |dvrt        d	      || _        || _        || _        || _        || _        t        j,                         | _        y
)ab  
        This loss is used to train a SentenceTransformer model using the GISTEmbed algorithm.
        It takes a model and a guide model as input, and uses the guide model to guide the
        in-batch negative sample selection. The cosine similarity is used to compute the loss
        and the temperature parameter is used to scale the cosine similarities.

        You can apply different false-negative filtering strategies to discard hard negatives that are too similar to
        the positive. Two strategies are supported:

            - "absolute": Discards negatives whose similarity score is greater than or equal to ``positive_score - margin``.
            - "relative": Discards negatives whose similarity score is greater than or equal to ``positive_score * (1 - margin)``.

        Args:
            model: SentenceTransformer model based on a `transformers` model.
            guide: SentenceTransformer model to guide the in-batch negative sample selection.
            temperature: Temperature parameter to scale the cosine similarities. Inverse of the ``scale`` parameter
                in :class:`MultipleNegativesRankingLoss`.
            margin_strategy: Strategy used for false negative filtering. One of {"absolute", "relative"}.
            margin: The margin value for filtering negatives. Defaults to 0.0, together with the "absolute" strategy,
                this only removes negatives that are more similar to the query than the positive is to the query.
            contrast_anchors: If True, include anchor-anchor pairs in the loss computation, resulting in the embeddings
                of the anchors being pushed further apart. Defaults to True, following the original GISTEmbed paper.
            contrast_positives: If True, include positive-positive pairs in the loss computation, resulting in the embeddings
                of the positives being pushed further apart. Defaults to True, following the original GISTEmbed paper,
                but setting to False may yield better results in some retrieval tasks.
            gather_across_devices: If True, gather the embeddings across all devices before computing the loss.
                Recommended when training on multiple GPUs, as it allows for larger batch sizes, but it may slow down
                training due to communication overhead, and can potentially lead to out-of-memory errors.

        References:
            - For further details, see: https://arxiv.org/abs/2402.16829

        Requirements:
            1. (anchor, positive, negative) triplets
            2. (anchor, positive) pairs

        Inputs:
            +---------------------------------------+--------+
            | Texts                                 | Labels |
            +=======================================+========+
            | (anchor, positive, negative) triplets | none   |
            +---------------------------------------+--------+
            | (anchor, positive) pairs              | none   |
            +---------------------------------------+--------+

        Recommendations:
            - Use ``BatchSamplers.NO_DUPLICATES`` (:class:`docs <sentence_transformers.training_args.BatchSamplers>`) to
              ensure that no in-batch negatives are duplicates of the anchor or positive samples.

        Relations:
            - :class:`MultipleNegativesRankingLoss` is similar to this loss, but it does not use
              a guide model to guide the in-batch negative sample selection. `GISTEmbedLoss` yields
              a stronger training signal at the cost of some training overhead.

        Example:
            ::

                from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer, losses
                from datasets import Dataset

                model = SentenceTransformer("microsoft/mpnet-base")
                guide = SentenceTransformer("all-MiniLM-L6-v2")
                train_dataset = Dataset.from_dict({
                    "anchor": ["It's nice weather outside today.", "He drove to work."],
                    "positive": ["It's so sunny.", "He took the car to the office."],
                })
                loss = losses.GISTEmbedLoss(model, guide)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        dim	tokenizerzNBoth the training model and the guiding model must have a tokenizer attribute.z_Both the training model and the guiding model must use a PreTrainedTokenizer from transformers.r   zIf we must retokenize because the guide model has a different tokenizer, then the Sentence Transformer model must not be based on a StaticEmbedding.)absoluterelativez1margin_strategy must be 'absolute' or 'relative'.N)super__init__modelguidetemperaturer   CosineSimilaritysimilarity_fcthasattr
ValueError
isinstancer   r	   	get_vocabmax_seq_lengthmust_retokenizer
   margin_strategymargincontrast_anchorscontrast_positivesgather_across_devicesCrossEntropyLosscross_entropy_loss)
selfr   r   r   r#   r$   r%   r&   r'   	__class__s
            }/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/sentence_transformers/losses/GISTEmbedLoss.pyr   zGISTEmbedLoss.__init__   s_   l 	

& 11b9uk*'%2Mmnn%//+BC:OO4L
 q  OO%%'5??+D+D+FFu%J^J^afauauJu 	 !ZZ11DN$**Q-9 b 
 "::PQQ. 0"4%:""$"5"5"7    c                b    | j                  |j                  d      |j                  d            S )N   r   )r   	unsqueeze)r*   embed1embed2s      r,   
sim_matrixzGISTEmbedLoss.sim_matrix   s+    ""6#3#3A#68H8H8KLLr-   c                    |D cg c]  } j                  |      d    }}t        j                         5   j                  r|D cg c]"  } j                  j                  |d   d      $ }}|D cg c]  } j                  j                  |       }}|D cg c]I  }|j                         D ci c]+  \  }}||j                   j                  j                        - c}}K }}}}|D cg c]  } j                  |      d    }	}d d d        d }
d }t        |      dk(  r|\  }}	\  }}n2t        |      dk(  r|\  }}}
	\  }}}nt        dt        |             |j                  d      }d} j                  rot        |      }t        |      }|
t        |
      }
t        |      }t        j                   j#                         r#t        j                   j%                         }||z  } j'                  ||      } j'                  ||      }|j)                  |	      j+                  d
d      dd fd}t        j,                  |j.                  t        j0                  |j                  d} ||||      }|g} j2                  r> j'                  ||      } j'                  ||      } |||      }|j5                  |        j6                  rJ j'                  ||||z    |      } j'                  ||||z    |      } |||      }|j5                  |       |
> j'                  ||
      } j'                  ||      } |||      }|j5                  |       t        j8                  |d       j:                  z  }t        j<                  |||z   |j                        } j?                  ||      S c c}w c c}w c c}w c c}}w c c}}}w c c}w # 1 sw Y   xY w)Nsentence_embedding	input_idsT)skip_special_tokens      z Expected 2 or 3 embeddings, got r   )offsetr   r/   c                    j                   dk(  r| j                  z
  kD  }n$j                   dk(  r| dj                  z
  z  kD  }|| z  }t        j                   |<   |S )Nr   r   r/   )r#   r$   torchinf)guided_sim_matsim_matpositive_maskmask
guided_simr*   s       r,   mask_false_negativesz3GISTEmbedLoss.forward.<locals>.mask_false_negatives   so    ##z1%dkk)AB%%3%q4;;)GH(}n,"YYJGDMNr-   )dtypedevice)r@   r   )rE   )N)r@   zTensor | None) r   r<   no_gradr"   r   batch_decoder   tokenizeitemstorE   lenr   sizer'   r   distributedis_initializedget_rankr3   diagonalvieweyeshapeboolr%   appendr&   catr   aranger)   ) r*   sentence_featureslabelssentence_feature
embeddingsdecoded	sentenceskeyvalueguide_embeddingsnegativenegative_guideanchorpositiveanchor_guidepositive_guide
batch_sizer:   rankap_simguided_ap_simrC   r@   scoresaa_simguided_aa_simpp_simguided_pp_siman_simguided_an_simrange_labelsrB   s    `                              @r,   forwardzGISTEmbedLoss.forward   s   arsM]djj!123GHs
s]]_ 	## ->( NN//0@0Mcg/h  V]$]	TZZ%8%8%C$]!$] ->% %( IYH^H^H`a*#uS%((4::#4#455a%! % \m GW

+,-AB   	  z?a)FH+;(L._!)3&FHh;K8L..?J?PQRR[[^
%% ,H5H1.AN#/9!5n!E   //1((113
* 2nE #++6+:??AF
	 		=#6#6ejjQ^QeQef &mV=Y  __VV4F OOL,GM)-@FMM&!""__Xfv
7J%KXVF OON6FZDW,XZhiM)-@FMM&! __VX6F OOL.IM)-@FMM&!6q)D,<,<< ||FFZ,?V&&v|<<I t %^a%
 	 	s^   OO(	'O0O(6"OO( O
80O(O
.O(6O#O(
O(O
O((O2c                    | j                   | j                  | j                  | j                  | j                  | j
                  | j                  dS )Nr   r   r#   r$   r%   r&   r'   ru   r*   s    r,   get_config_dictzGISTEmbedLoss.get_config_dict   sG    ZZ++#33kk $ 5 5"&"9"9%)%?%?
 	
r-   c                     y)Na  
@misc{solatorio2024gistembed,
    title={GISTEmbed: Guided In-sample Selection of Training Negatives for Text Embedding Fine-tuning},
    author={Aivin V. Solatorio},
    year={2024},
    eprint={2402.16829},
    archivePrefix={arXiv},
    primaryClass={cs.LG}
}
 rv   s    r,   citationzGISTEmbedLoss.citation   s    	r-   )g{Gz?r   g        TTF)r   r   r   r   r   floatr#   zLiteral['absolute', 'relative']r$   r{   r%   rT   r&   rT   r'   rT   returnNone)r1   r   r2   r   r|   r   )rX   zIterable[dict[str, Tensor]]rY   r   r|   r   )r|   zdict[str, Any])r|   str)
__name__
__module____qualname__r   r3   rs   rw   propertyrz   __classcell__)r+   s   @r,   r   r      s    
 ";E!%#'&+v8"v8 #v8 	v8
 9v8 v8 v8 !v8  $v8 
v8pMe=N	
 
 
r-   r   )
__future__r   collections.abcr   typingr   r   r<   r   r   transformersr	   sentence_transformers.modelsr
   )sentence_transformers.SentenceTransformerr   sentence_transformers.utilr   Moduler   ry   r-   r,   <module>r      s2    " $    0 8 I ;yBII yr-   