
    .ɷij                    .   d dl mZ d dlZd dlmZmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d d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  ej:                  e      Z G d d      Z 	 	 	 	 	 	 	 	 ddZ! G d dejD                        Z#y)    )annotationsN)CallableIterableIterator)nullcontext)partial)AnyLiteral)Tensornn)get_device_statesset_device_states)util)StaticEmbedding)SentenceTransformer)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     r/var/www/html/venv/lib/python3.12/site-packages/sentence_transformers/losses/CachedMultipleNegativesRankingLoss.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   "CachedMultipleNegativesRankingLossc           
        |j                   J |j                  J t        j                         5  t	        ||j                   |j                        D ]  \  }}}t	        |j                  |dd|      |      D ]Z  \  \  }}}|j                  st        j                  |j                         |j                               | z  }	|	j                          \  	 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requires_graddotflattenbackward)
grad_outputsentence_featuresloss_objr8   gradr;   reps_mb_grad_mb	surrogates
             r   _backward_hookrL   -   s     >>%%%!!---				 )589JHNN\d\r\r5s 	)1dM),--%5"&+"/	 .  * )%!g (( %		'//*;W__=N OR] ]I&&()	)) ) )s   AC"A	C""C+c            	           e Zd Zdej                  dddddddf		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd	Z	 d	 	 	 	 	 	 	 	 	 dd
ZddZdddZ	ddZ
ddZedd       Zedd       Z xZS )r6   g      4@    F)query_to_docjointN        c                   t         |           t        |d   t              rt	        d      || _        || _        || _        || _        || _	        h d}|st	        d      t        |      j                  |      st	        dt        |      |z
   d|       d|vrt	        d      t        |      | _        |d	vrt	        d
|       |dk(  rt        |      ddhz  rt	        d      || _        || _        h d}|	|vrt	        d| d|	      |	| _        |
dk  rt	        d      |
| _        |	|
dk(  rt$        j'                  d|	d       d| _        d| _        y)a!  
        Boosted version of :class:`MultipleNegativesRankingLoss` (https://huggingface.co/papers/1705.00652) by GradCache (https://huggingface.co/papers/2101.06983).

        Constrastive learning (here our MNRL loss) with in-batch negatives is usually hard to work with large batch sizes due to (GPU) memory limitation.
        Even with batch-scaling methods like gradient-scaling, it cannot work either. This is because the in-batch negatives make the data points within
        the same batch non-independent and thus the batch cannot be broke down into mini-batches. GradCache is a smart way to solve this problem.
        It achieves the goal by dividing the computation into two stages of embedding and loss calculation, which both can be scaled by mini-batches.
        As a result, memory of constant size (e.g. that works with batch size = 32) can now process much larger batches (e.g. 65536).

        In detail:

            (1) It first does a quick embedding step without gradients/computation graphs to get all the embeddings;
            (2) Calculate the loss, backward up to the embeddings and cache the gradients wrt. to the embeddings;
            (3) A 2nd embedding step with gradients/computation graphs and connect the cached gradients into the backward chain.

        Notes: All steps are done with mini-batches. In the original implementation of GradCache, (2) is not done in mini-batches and
        requires a lot memory when the batch size is large. One drawback is about the speed. Gradient caching will sacrifice
        around 20% computation time according to the paper.

        See :class:`MultipleNegativesRankingLoss` for more details about the underlying loss itself.

        Args:
            model: SentenceTransformer model
            scale: Output of similarity function is multiplied by scale value. In some literature, the scaling parameter
                is referred to as temperature, which is the inverse of the scale. In short: ``scale = 1 / temperature``, so
                ``scale=20.0`` is equivalent to ``temperature=0.05``. A higher scale (lower temperature) puts more emphasis
                on the positive example, and values between 10 and 100 are common.
            similarity_fct: similarity function between sentence embeddings. By default, cos_sim. Can also be set to dot
                product (and then set scale to 1)
            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.
            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.
            directions: Which similarity interaction terms to include in the loss. Options:

                - "query_to_doc": query -> all documents (always included as it covers the paired positive).
                - "query_to_query": query -> all other queries in the batch.
                - "doc_to_query": document -> all queries (symmetric term).
                - "doc_to_doc": document -> all other documents in the batch, excluding those belonging to the same query.

                The default ("query_to_doc",) matches the standard MultipleNegativesRankingLoss / InfoNCE behavior.
            partition_mode: How to normalize the scores (the softmax denominator):
                - "joint": One joint softmax over all selected directions.
                - "per_direction": One softmax per direction. A loss is computed for each direction and then averaged.
                  Not compatible with ``"query_to_query"`` or ``"doc_to_doc"`` directions.
            show_progress_bar: If True, a progress bar for the mini-batches is shown during training. The default is False.
            hardness_mode: Strategy for applying hardness weighting. ``None`` (default) disables hardness
                weighting entirely. Options:

                - ``"in_batch_negatives"``: Adds ``hardness_strength * stop_grad(cos_sim)`` to every in-batch negative
                  logit inside the softmax (`Lan et al. 2025 <https://huggingface.co/papers/2503.04812>`_, Eq. 5). The
                  in-batch negatives are all positives and hard negatives from other samples in the batch.
                - ``"hard_negatives"``: Applies ``hardness_strength * stop_grad(cos_sim)`` only to the logits of
                  explicit hard negatives, leaving in-batch negatives unpenalized. Only active when explicit
                  negatives are provided. As used in
                  `Schechter Vera et al. 2025 <https://huggingface.co/papers/2509.20354>`_ (EmbeddingGemma).
                - ``"all_negatives"``: Applies ``hardness_strength * stop_grad(cos_sim)`` to every negative logit,
                  both in-batch negatives and explicit hard negatives, leaving only the positive unpenalized.
                  Combines the effect of ``"in_batch_negatives"`` and ``"hard_negatives"``.

            hardness_strength: Strength of the hardness weighting. The meaning depends on ``hardness_mode``:

                - For ``"in_batch_negatives"``: acts as ``alpha`` in the hardness penalty, `Lan et al. 2025 <https://huggingface.co/papers/2503.04812>`_ uses 9.
                - For ``"hard_negatives"``: acts as ``alpha`` in the hardness penalty, `Schechter Vera et al. 2025 <https://huggingface.co/papers/2509.20354>`_ uses 5.

                Must be non-negative. Ignored when ``hardness_mode`` is ``None``.

        References:
            - Efficient Natural Language Response Suggestion for Smart Reply, Section 4.4: https://huggingface.co/papers/1705.00652
            - Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup: https://huggingface.co/papers/2101.06983

        Requirements:
            1. (anchor, positive) pairs, (anchor, positive, negative) triplets, or (anchor, positive, negative_1, ..., negative_n) n-tuples
            2. Should be used with large `per_device_train_batch_size` and low `mini_batch_size` for superior performance, but 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:`MultipleNegativesRankingLoss`, but with caching that allows for much higher batch sizes
              (and thus better performance) without extra memory usage. This loss also trains roughly 2x to 2.4x slower than
              :class:`MultipleNegativesRankingLoss`.

        Example:
            ::

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

                model = SentenceTransformer("microsoft/mpnet-base")
                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.CachedMultipleNegativesRankingLoss(model, mini_batch_size=64)

                trainer = SentenceTransformerTrainer(
                    model=model,
                    train_dataset=train_dataset,
                    loss=loss,
                )
                trainer.train()
        r   zCachedMultipleNegativesRankingLoss is not compatible with a SentenceTransformer model based on a StaticEmbedding. Consider using MultipleNegativesRankingLoss instead.>   
doc_to_docdoc_to_queryrO   query_to_queryz)At least one direction must be specified.zInvalid directions: z	. Valid: rO   zB'query_to_doc' direction is required (contains the positive pair).)rP   per_directionz7partition_mode must be 'joint' or 'per_direction', got rV   rU   rS   a  partition_mode='per_direction' requires every direction's candidate pool to include the positive pair. 'query_to_query' and 'doc_to_doc' only contain same-type similarities and never include the positive, making the per-direction loss ill-defined. Use partition_mode='joint' instead.>   Nall_negativeshard_negativesin_batch_negativeszhardness_mode must be one of z, got rQ   z'hardness_strength must be non-negative.Nzhardness_mode=z is set but hardness_strength=0.0, so hardness weighting has no effect. Set hardness_strength to a positive value to enable hardness weighting.)superr   
isinstancer   
ValueErrormodelscalesimilarity_fctmini_batch_sizegather_across_devicessetissubsettuple
directionspartition_modeshow_progress_barhardness_modehardness_strengthloggerwarningr<   r;   )r   r]   r^   r_   r`   ra   re   rf   rg   rh   ri   valid_directionsvalid_hardness_modes	__class__s                r   r   z+CachedMultipleNegativesRankingLoss.__init__I   s   L 	eAh0G 
 

,.%:"[HII:''(893C
OFV4V3WW`aq`rstt+abb
+!;;VWeVfghh_,ZDTVbCc1c a 
 -!2^ 44<=Q<RRXYfXijkk*s"FGG!2$):c)ANN  1 2b b
 15
=Ar    c           	        |rt         nt        j                  }|
t               n|}|j                         D 	
ci c]'  \  }	}
|	t	        |
t        j
                        r|
|| n|
) }}	}
|5   |       5  |rt        |j                          nd}| j                  |      d   }ddd       ddd       |fS c c}
}	w # 1 sw Y   xY w# 1 sw Y   |fS xY w)z Embed a mini-batch of sentences.Nsentence_embedding)	r   r   no_graditemsr[   r   r   valuesr]   )r   r8   beginendr9   r:   random_stategrad_contextrandom_state_contextkeyvaluesentence_feature_minibatchrepss                r   embed_minibatchz2CachedMultipleNegativesRankingLoss.embed_minibatch  s     '0{U]]0<0D{}, /446&
U Zu||%DuS!%O&
" &
 " 	T TTe{,F,M,M,OPkozz"<=>RST	T \!!&

T T	T \!!s)   ,B6+C3/B<"C<C	CCc           
   #     K   |d   }|j                   \  }}t        t        j                  d|| j                  d| j
                               D ];  \  }}	|	| j                  z   }
| j                  ||	|
|||dn||         \  }}||f = yw)z5Iterate over mini-batches of sentences for embedding.	input_idsr   zEmbed mini-batchesdescdisableN)r8   rt   ru   r9   r:   rv   )shape	enumeratetqdmtranger`   rg   r}   )r   r8   r9   r:   r;   r   
batch_sizerI   irt   ru   r|   rv   s                r   r?   z7CachedMultipleNegativesRankingLoss.embed_minibatch_iter  s      -[9	!
A!KK$$) 222
 	%HAu $...C!%!5!5!1#"3%2%:Ta@P "6 "D, $$%	%s   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 )zMCalculate the cross-entropy loss and cache the gradients wrt. the embeddings.T)with_backward)calculate_lossdetachrequires_grad_rG   r<   )r   r|   lossrsrs        r   "calculate_loss_and_cache_gradientszECachedMultipleNegativesRankingLoss.calculate_loss_and_cache_gradients8  sY    ""4t"<{{}++-59:rr*!qvv*:
 +:s   	A( A#A(#A(c                	   t        j                  |d         }|dd D cg c]  }t        j                  |       }}t        |      }d}| j                  rdt	        |      }|D cg c]  }t	        |       }}t         j
                  j                         r#t         j
                  j                         }	|	|z  }|j                  d      }
t        j                  |d      }|d   }t        j                  |||z   |j                        }t        j                  |
|j                        }t        |      }g }t        j                  d|| j                  d| j                         D ]X  }t!        || j                  z   |      }||| }t        j                  t        |      |j                        }||   }||   }i }| j#                  ||      |d<   d	| j$                  v r.| j#                  ||      |d	<   t         j&                   |d	   ||f<   d
| j$                  v r| j#                  ||      j(                  |d
<   d| j$                  v rf| j#                  ||      j(                  |d<   ||   j+                  d|      j-                         }|d   j/                  |t         j&                          i }| j0                  dv r| j2                  dkD  r| j2                  |d   j5                         z  }t        j                  |
|j                  t         j,                        |   }|j+                  d|      }| j0                  dk(  r| }d|ddd|
f<   n.| j0                  dk(  r|}n| j0                  dk(  r|}d|dd|
df<   d|<   ||d<   |D ]  }||   | j6                  z  ||<    |j9                         D ]  \  }}||   |z   ||<    |d   ||f   }| j:                  dk(  rFt        j                  t=        |j?                               d      } t        j@                  | d      }!n?d}!|j?                         D ]  }"|!t        j@                  |"d      z  }! |!t        |      z  }!||!z
   }#|#jC                         t        |      z  |z  }$|r |$jE                          |$j5                         }$|jG                  |$       [ tI        |      S c c}w c c}w )zPCalculate the all-pairs InfoNCE loss without caching gradients (for evaluation).r      N)dim)devicezCalculating lossr   rO   rU   rT   rS   )rY   rX   rW   rQ   )r   dtyperX   TrY   rW   FrP   )%r   catlenra   r   distributedis_initializedget_ranksizearanger   eyer   r   r`   rg   minr_   re   infTrepeatboolmasked_fill_rh   ri   r   r^   rr   rf   listrs   	logsumexpmeanrC   appendsum)%r   r|   r   queriesr   docsr   offsetdocrankworld_batch_sizedocs_alldocs_poslocal_indicesidentitynum_docslossesrt   ru   local_batchrow_indiceslocal_queries
local_docssim_matricessame_query_doc_mask	penaltiespenaltyown_doc_maskpenalty_exclusion_maskry   penpositive_scores
all_scoreslog_z
sim_matrixper_sample_lossloss_mbatchs%                                        r   r   z1CachedMultipleNegativesRankingLoss.calculate_lossA  s   ))DG$&*12h/		!//\
%%
 +73G9=>#(->D>   //1((113
*"<<?99Tq)7VVj-@X99-gnnEt9%'[[  #...
 [	'E ed222J?C'c2K,,s;'7OK#K0M!+.JL+/+>+>}h+WL(4??2151D1D]T[1\-.LQII:-.{K/GH0/3/B/B7J/W/Y/Y^,t.-1-@-@:-V-X-X\*&.{&;&B&B1h&O&T&T&V#\*778KeiiZX
 I""&__**S000<3O3V3V3XX  %yy)9'..X]XbXbcdop+221h?%%)99.:]*CG*1.?/?.?+?@''+??-9*''?:-9*CH*1.>.?+?@25./,3	.) $ C$0$5

$BS!C%OO- <S$0$5$;S!< +>:;;STO""g-"YYtL,?,?,A'BJ

: "."5"5"7 @JU__ZQ??E@\** /% 78O)..03{3CCjPK$$&)002MM+&w[	'z 6{o 0 ?s   S&Sc                L   t        |      }t        |      dk  rt        dt        |             g }g | _        |D ]  }g }g }| j	                  |dd      D ]C  \  }}|j                  |j                         j                                |j                  |       E |j                  |       | j                  j                  |        t        j                         r4| j                  |      }	|	j                  t        t        ||              |	S | j                  |      }	|	S )N   z Expected at least 2 inputs, got FT)r8   r9   r:   )rE   rF   )r   r   r\   r;   r?   r   r   r   r   is_grad_enabledr   register_hookr   rL   r   )
r   rE   labelsr|   r8   reps_mbsrandom_state_mbsrH   rv   r   s
             r   forwardz*CachedMultipleNegativesRankingLoss.forward  s2    !23 !A%?DU@V?WXYY 1 	8H!)-)B)B!1"& *C * 6%
  0 ? ? AB ''56 KK!%%&67	8   "::4@D w~IZeijk
  &&t,Dr    c           	         | j                   | j                  j                  | j                  | j                  | j
                  | j                  | j                  | j                  dS )N)r^   r_   r`   ra   re   rf   rh   ri   )	r^   r_   r1   r`   ra   re   rf   rh   ri   r)   s    r   get_config_dictz2CachedMultipleNegativesRankingLoss.get_config_dict  sV    ZZ"11::#33%)%?%?//"11!//!%!7!7	
 		
r    c                     d| j                   z  S )Ng      ?)r^   r)   s    r   temperaturez.CachedMultipleNegativesRankingLoss.temperature  s    TZZr    c                     y)Na  
@misc{gao2021scaling,
    title={Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup},
    author={Luyu Gao and Yunyi Zhang and Jiawei Han and Jamie Callan},
    year={2021},
    eprint={2101.06983},
    archivePrefix={arXiv},
    primaryClass={cs.LG}
}
r5   r)   s    r   citationz+CachedMultipleNegativesRankingLoss.citation  s    	r    )r]   r   r^   floatr_   z"Callable[[Tensor, Tensor], Tensor]r`   intra   r   re   zStuple[Literal['query_to_doc', 'query_to_query', 'doc_to_query', 'doc_to_doc'], ...]rf   z!Literal['joint', 'per_direction']rg   r   rh   zGLiteral['in_batch_negatives', 'hard_negatives', 'all_negatives'] | Noneri   r   r/   r0   r   )r8   dict[str, Tensor]rt   r   ru   r   r9   r   r:   r   rv   zRandContext | Noner/   z!tuple[Tensor, RandContext | None])
r8   r   r9   r   r:   r   r;   zlist[RandContext] | Noner/   z+Iterator[tuple[Tensor, RandContext | None]])r|   list[list[Tensor]]r/   r   )F)r|   r   r   r   r/   r   )rE   Iterable[dict[str, Tensor]]r   r   r/   r   )r/   zdict[str, Any])r/   r   )r/   str)r1   r2   r3   r   cos_simr   r}   r?   r   r   r   r   propertyr   r   __classcell__)rn   s   @r   r6   r6   H   sx    =A\\!&+ <C"'ae#&yB"yB yB ;	yB
 yB  $yB
yB :yB  yB _yB !yB 
yBD ,0"+" " 	"
 "  " )" 
+"6 37%+% %  	%
 0% 
5%<zxB

     
 
r    )rD   r   rE   r   rF   r6   r/   r0   )$
__future__r   loggingcollections.abcr   r   r   
contextlibr   	functoolsr   typingr	   r
   r   r   r   r   torch.utils.checkpointr   r   sentence_transformersr   sentence_transformers.modelsr   )sentence_transformers.SentenceTransformerr   sentence_transformers.utilr   	getLoggerr1   rj   r   rL   Moduler6   r5   r    r   <module>r      s    "  8 8 "      G & 8 I ;			8	$ .))2) 1) 
	)6q qr    