
    rhkY                        d dl mZ d dlmZmZ d dlmZ d dlmZ d dl	m
Z
m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 d dlmZ  G d d      Z	 	 	 	 	 	 	 	 ddZ G d dej:                        Zy)    )annotations)IterableIterator)nullcontext)partial)AnyLiteralN)Tensornn)get_device_statesset_device_states)PreTrainedTokenizerBase)SentenceTransformer)StaticEmbedding)all_gather_with_gradc                  (    e Zd ZdZddZddZddZy)RandContexta  
    Random-state context manager class. Reference: https://github.com/luyug/GradCache.

    This class will back up the pytorch's random state during initialization. Then when the context is activated,
    the class will set up the random state with the backed-up one.
    c                `    t        j                         | _        t        | \  | _        | _        y N)torchget_rng_statefwd_cpu_stater   fwd_gpu_devicesfwd_gpu_states)selftensorss     /var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/sentence_transformers/losses/CachedGISTEmbedLoss.py__init__zRandContext.__init__   s(    "0024Ew4O1d1    c                   t         j                  j                  | j                  d      | _        | j                  j                          t        j                  | j                         t        | j                  | j                         y )NT)devicesenabled)
r   randomfork_rngr   _fork	__enter__set_rng_stater   r   r   r   s    r   r&   zRandContext.__enter__   s^    \\**43G3GQU*V


D../$..0C0CDr   c                L    | j                   j                  |||       d | _         y r   )r%   __exit__)r   exc_typeexc_valexc_tbs       r   r*   zRandContext.__exit__%   s    

Hgv6
r   N)returnNone)__name__
__module____qualname____doc__r   r&   r*    r   r   r   r      s    PEr   r   CachedGISTEmbedLossc           
        |j                   J |j                  J t        j                         5  t	        ||j                   |j                        D ]v  \  }}}t	        |j                  |dd|      |      D ]N  \  \  }}}}t        j                  |j                         |j                               | z  }	|	j                          P x 	 ddd       y# 1 sw Y   yxY w)zOA backward hook to backpropagate the cached gradients mini-batch by mini-batch.NTF)sentence_feature	with_gradcopy_random_staterandom_states)	cacher:   r   enable_gradzipembed_minibatch_iterdotflattenbackward)
grad_outputsentence_featuresloss_objr7   gradr:   reps_mb_grad_mb	surrogates
             r   _backward_hookrJ   *   s     >>%%%!!---				 %589JHNN\d\r\r5s 	%1dM,/--%5"&+"/	 .  - 
%(!Q "IIgoo&79JKkY	""$
%	%% % %s   BCCc                       e Zd Z	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
 fdZddZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 	 	 ddZddZ	 d	 	 	 	 	 	 	 ddZddZ	ddZ
 xZS )r5   c                $   t         |           t        |d   t              rt	        d      || _        || _        || _        t        j                  d      | _
        t        |d      rt        |d      st	        d      t        |j                  t              rt        |j                  t              st	        d      || _        d| _        d| _        || _        |j                  j$                  |j                  j$                  k7  xs |j&                  |j&                  k  | _        | j(                  r|j                  | _        |d	vrt	        d
      || _        || _        || _        |	| _        |
| _        t        j4                         | _        y)a1  
        This loss is a combination of :class:`GISTEmbedLoss` and :class:`CachedMultipleNegativesRankingLoss`.
        Typically, :class:`MultipleNegativesRankingLoss` requires a larger batch size for better performance.
        :class:`GISTEmbedLoss` yields stronger training signals than :class:`MultipleNegativesRankingLoss` due to the
        use of a guide model for in-batch negative sample selection. Meanwhile, :class:`CachedMultipleNegativesRankingLoss`
        allows for scaling of the batch size by dividing the computation into two stages of embedding and loss
        calculation, which both can be scaled by mini-batches (https://arxiv.org/pdf/2101.06983.pdf).

        By combining the guided selection from :class:`GISTEmbedLoss` and Gradient Cache from
        :class:`CachedMultipleNegativesRankingLoss`, it is possible to reduce memory usage while maintaining performance
        levels comparable to those of :class:`GISTEmbedLoss`.

        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
            guide: SentenceTransformer model to guide the in-batch negative sample selection.
            temperature: Temperature parameter to scale the cosine similarities.
            mini_batch_size: Mini-batch size for the forward pass, this denotes how much memory is actually used during
                training and evaluation. The larger the mini-batch size, the more memory efficient the training is, but
                the slower the training will be. It's recommended to set it as high as your GPU memory allows. The default
                value is 32.
            show_progress_bar: If True, a progress bar for the mini-batches is shown during training. The default is False.
            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:
            - Efficient Natural Language Response Suggestion for Smart Reply, Section 4.4: https://arxiv.org/pdf/1705.00652.pdf
            - Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup: https://arxiv.org/pdf/2101.06983.pdf
            - GISTEmbed: Guided In-sample Selection of Training Negatives for Text Embedding Fine-tuning https://arxiv.org/abs/2402.16829

        Requirements:
            1. (anchor, positive) pairs or (anchor, positive, negative pairs)
            2. Should be used with large batch sizes for superior performance, but has slower training time than :class:`MultipleNegativesRankingLoss`

        Inputs:
            +-------------------------------------------------+--------+
            | Texts                                           | Labels |
            +=================================================+========+
            | (anchor, positive) pairs                        | none   |
            +-------------------------------------------------+--------+
            | (anchor, positive, negative) triplets           | none   |
            +-------------------------------------------------+--------+
            | (anchor, positive, negative_1, ..., negative_n) | 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:
            - Equivalent to :class:`GISTEmbedLoss`, but with caching that allows for much higher batch sizes

        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.CachedGISTEmbedLoss(
                    model,
                    guide,
                    mini_batch_size=64,
                    margin_strategy="absolute",   # or "relative" (e.g., margin=0.05 for max. 95% of positive similarity)
                    margin=0.1
                )

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        r   zCachedGISTEmbedLoss is not compatible with a SentenceTransformer model based on a StaticEmbedding. Consider using GISTEmbedLoss instead.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.N)absoluterelativez1margin_strategy must be 'absolute' or 'relative'.)superr   
isinstancer   
ValueErrormodelguidetemperaturer   CosineSimilaritysimilarity_fcthasattrrP   r   mini_batch_sizer;   r:   show_progress_barvocabmax_seq_lengthmust_retokenizemargin_strategymargincontrast_anchorscontrast_positivesgather_across_devicesCrossEntropyLosscross_entropy_loss)r   rV   rW   rX   r\   r]   ra   rb   rc   rd   re   	__class__s              r   r   zCachedGISTEmbedLoss.__init__B   sm   T 	eAh08  

& 11b9uk*'%2Mmnn%//+BC:OO4L
 q   /04
=A!2OO!!U__%:%::ie>R>RUZUiUi>i 	 "__DN"::PQQ. 0"4%:""$"5"5"7r   c                b    | j                  |j                  d      |j                  d            S )N   r   )rZ   	unsqueeze)r   embed1embed2s      r   
sim_matrixzCachedGISTEmbedLoss.sim_matrix   s+    ""6#3#3A#68H8H8KLLr   c           
        |rt         nt        j                  }|
t               n|}|j                         D 	
ci c]  \  }	}
|	|
||  }}	}
|5   |       5  |rt	        |j                          nd}| j                  |      d   }ddd       t        j                         5  | j                  r| j                  j                  |d   d      }| j                  j                  |      }|j                         D ci c]+  \  }}||j                  | j                  j                        - }}}| j                  |      d   }ddd       ddd       |fS c c}
}	w # 1 sw Y   xY wc c}}w # 1 sw Y   .xY w# 1 sw Y   2xY w)zYDo forward pass on a minibatch of the input features and return corresponding embeddings.Nsentence_embedding	input_idsT)skip_special_tokens)r   r   no_graditemsr   valuesrV   r`   rP   batch_decoderW   tokenizetodevice)r   r7   beginendr8   r9   random_stategrad_contextrandom_state_contextkvsentence_feature_minibatchrepsdecodedkeyvalue
guide_repss                    r   embed_minibatchz#CachedGISTEmbedLoss.embed_minibatch   s    '0{U]]0<0D{},BRBXBXBZ%[$!Qa5o%["%[! 	Z TTe{,F,M,M,OPkozz"<=>RST  	Z''"nn992;?UY : G 261D1DW1M.KeKkKkKm2=GS%UXXdjj&7&7882. 2 "ZZ(BCDXY
	Z		Z Z--! &\T T2	Z 	Z		Z 	ZsT   EE=/EE="AE1=0E+
-E1E=E(	$E=+E11E:	6E==Fc           
   #  $  K   |d   }|j                   \  }}t        t        j                  d|| j                  d| j
                               D ]=  \  }}	|	| j                  z   }
| j                  ||	|
|||dn||         \  }}}|||f ? yw)z`Do forward pass on all the minibatches of the input features and yield corresponding embeddings.rq   r   zEmbed mini-batchesdescdisableN)r7   rz   r{   r8   r9   r|   )shape	enumeratetqdmtranger\   r]   r   )r   r7   r8   r9   r:   rq   bszrG   irz   r{   r   r   r|   s                 r   r>   z(CachedGISTEmbedLoss.embed_minibatch_iter   s      -[9	Q!KK$$) 222
 	1HAu $...C-1-A-A!1#"3%2%:Ta@P .B .*D*l 
L00%	1s   BBc                    | j                  ||d      }|j                         j                         }|D cg c]  }|D cg c]  }|j                   c} c}}| _        |S c c}w c c}}w )zeGeneralized function to calculate the cross-entropy loss and cache the gradients wrt. the embeddings.T)with_backward)calculate_lossdetachrequires_grad_rE   r;   )r   r   reps_guidedlossrsrs         r   "calculate_loss_and_cache_gradientsz6CachedGISTEmbedLoss.calculate_loss_and_cache_gradients  s[    ""4D"I{{}++-59:rr*!qvv*:
 +:s   	A)A$A)$A)c           
     b    t        |      t        |      k7  rt        d      t        j                  |d         }t        j                  |d         }|dd D cg c]  }t        j                  |       }}|dd D cg c]  }t        j                  |       }}|j	                  d      }	d}
 j
                  rq|D cg c]  }t        |       }}|D cg c]  }t        |       }}t        j                  j                         r#t        j                  j                         }||	z  }
t        j                  |
|
|	z   |j                        }g }t        j                  d|	 j                  d j                         D ]  }| j                  z   } j!                  ||| |d         } j!                  ||| |d         }|j#                  |
|z         j%                  d	d      dd fd
}t        j&                  |j(                  t        j*                  |j                  d}|j-                  |      } ||||      }|g} j.                  rD j!                  ||| |      } j!                  ||| |      } |||      }|j1                  |        j2                  rv j!                  |d   |
|z   t5        |
|z   |
|	z          |d         } j!                  |d   |
|z   t5        |
|z   |
|	z          |d         } |||      }|j1                  |       t        |      dkD  rdt7        dt        |            D ]L  } j!                  ||| ||         } j!                  ||| ||         } |||      }|j1                  |       N t        j                  |d      }| j8                  z  } j;                  ||||       t        |      z  |	z  }|r |j=                          |j?                         }|j1                  |        tA        |      }|S c c}w c c}w c c}w c c}w )zSGeneralized function to calculate the cross-entropy loss without caching gradients.z.reps and reps_guided must have the same lengthr   rj   N)ry   zCalculating lossr   )offsetrM   c                    j                   dk(  r| j                  z
  kD  }n$j                   dk(  r| dj                  z
  z  kD  }|| z  }t        j                   |<   |S )NrQ   rR   rj   )ra   rb   r   inf)guided_sim_matsim_matpositive_maskmask
guided_simr   s       r   mask_false_negativesz@CachedGISTEmbedLoss.calculate_loss.<locals>.mask_false_negativesJ  so    '':5)Z$++-EFD))Z7)Z1t{{?-KLD ,=.0D!&
r   )dtypery   )r   rN   r   )r   zTensor | None)!lenrU   r   catsizere   r   distributedis_initializedget_rankarangery   r   r   r\   r]   rn   diagonalvieweyer   boolrollrc   appendrd   minrangerX   rg   rA   r   sum) r   r   r   r   anchorsanchors_guider   
candidatescandidates_guide
batch_sizer   	candidaterankrange_labelslossesrz   r{   ap_simguided_ap_simr   r   scoresaa_simguided_aa_simpp_simguided_pp_simr   neg_simguided_neg_simloss_mbatchr   r   s    `                              @r   r   z"CachedGISTEmbedLoss.calculate_loss  s-    t9K((MNN ))DG$		+a.1,0H5qeiil5
52=ab/BQEIIaLBB\\!_
%% LVVi.y9VJVQabI 4Y ?bb   //1((113
* ||FFZ,?W%'[[  #...
 J	'E $...C __WU3%7AGF OOM%,DFVWXFYZM '//v~/FKKBPQRJ "II}':':%**UbUiUijM)..u5M *-}]FXF$$s);WE $eC0H- X-mVDf%&&qM&5.3v|VjEX3YZ\fgh\i !%$Q'Vc\6T^K^9_`brstbu! .mVDf% :"q#j/2 +A"oogeC.@*Q-PG%)__]55MO_`aOb%cN2>7KGMM'*	+ YYv1-F d...F''U30GH3v;VYcc  $$&)002MM+&UJ	'X 6{I 6B Wbs   PP"P'P,c                Z   g }g }g | _         |D ]  }g }g }g }| j                  |dd      D ]c  \  }	}
}|j                  |	j                         j	                                |j                  |
j                                |j                  |       e |j                  |       |j                  |       | j                   j                  |        t        j                         r5| j                  ||      }|j                  t        t        ||              |S | j                  ||      }|S )NFT)r7   r8   r9   )rC   rD   )r:   r>   r   r   r   r   is_grad_enabledr   register_hookr   rJ   r   )r   rC   labelsr   r   r7   reps_mbsreps_guided_mbsrandom_state_mbsrF   reps_guided_mbr|   r   s                r   forwardzCachedGISTEmbedLoss.forward  s3    1 	8H O!9=9R9R!1"& :S : 65
  0 ? ? AB&&~'<'<'>? ''56 KK!/%%&67	8    "::4MD w~IZeijk  &&t[9Dr   c           	         | j                   | j                  | j                  | j                  | j                  | j
                  | j                  | j                  dS )NrW   rX   r\   ra   rb   rc   rd   re   r   r(   s    r   get_config_dictz#CachedGISTEmbedLoss.get_config_dict  sP    ZZ++#33#33kk $ 5 5"&"9"9%)%?%?	
 		
r   )g{Gz?    FrQ   g        TTF)rV   r   rW   r   rX   floatr\   intr]   r   ra   zLiteral['absolute', 'relative']rb   r   rc   r   rd   r   re   r   r.   r/   )rl   r
   rm   r
   r.   r
   r   )r7   dict[str, Tensor]rz   r   r{   r   r8   r   r9   r   r|   zRandContext | Noner.   z)tuple[Tensor, Tensor, RandContext | None])
r7   r   r8   r   r9   r   r:   zlist[RandContext] | Noner.   z3Iterator[tuple[Tensor, Tensor, RandContext | None]])r   list[list[Tensor]]r   r   r.   r
   )F)r   r   r   r   r   r   r.   r
   )rC   Iterable[dict[str, Tensor]]r   r
   r.   r
   )r.   zdict[str, Any])r0   r1   r2   r   rn   r   r>   r   r   r   r   __classcell__)rh   s   @r   r5   r5   A   sl   
 "!"';E!%#'&+L8"L8 #L8 	L8
 L8  L8 9L8 L8 L8 !L8  $L8 
L8\M ,0.+. . 	.
 .  . ). 
3.F 371+1 1  	1
 01 
=1< `en&n5GnX\n	n`@

r   )rB   r
   rC   r   rD   r5   r.   r/   )
__future__r   collections.abcr   r   
contextlibr   	functoolsr   typingr   r	   r   r   r
   r   torch.utils.checkpointr   r   transformersr   sentence_transformersr   sentence_transformers.modelsr   sentence_transformers.utilr   r   rJ   Moduler5   r4   r   r   <module>r      sq    " . "      G 0 5 8 ; .%%2% "% 
	%.q
")) q
r   