Ë
    l^(h�8  ã                  óæ   — 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
 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mZ d d
lmZ  G d„ d«      Z	 	 	 	 	 	 	 	 dd„Z G d„ dej2                  «      Zy)é    )Úannotations)ÚIterableÚIterator)Únullcontext)Úpartial)ÚAnyN)ÚTensorÚnn)Úget_device_statesÚset_device_states)ÚSentenceTransformerÚutil)ÚStaticEmbeddingc                  ó(   — 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/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/losses/CachedMultipleNegativesRankingLoss.pyÚ__init__zRandContext.__init__   s(   € Ü"×0Ñ0Ó2ˆÔÜ4EÀwÐ4OÑ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^   € Ü—\‘\×*Ñ*°4×3GÑ3GÐQUÐ*ÓVˆŒ
Ø�
‰
×ÑÔÜ×Ñ˜D×.Ñ.Ô/Ü˜$×.Ñ.°×0CÑ0CÕDr   c                óL   — | j                   j                  |||«       d | _         y r   )r#   Ú__exit__)r   Úexc_typeÚexc_valÚexc_tbs       r   r(   zRandContext.__exit__#   s   € Ø�
‰
×Ñ˜H g¨vÔ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 ]u  \  }}}t	        |j                  |dd|¬«      |«      D ]M  \  \  }}}t        j                  |j                  «       |j                  «       «      | z  }	|	j                  «        ŒO Œw 	 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)	Úcacher8   r   Úenable_gradÚzipÚembed_minibatch_iterÚdotÚflattenÚbackward)
Úgrad_outputÚsentence_featuresÚloss_objr5   Úgradr8   Úreps_mbÚ_Úgrad_mbÚ	surrogates
             r   Ú_backward_hookrH   (   så   € ð �>‰>Ð%Ð%Ð%Ø×!Ñ!Ð-Ð-Ð-Ü	×	Ñ	Ó	ñ %Ü58Ð9JÈHÏNÉNÐ\d×\rÑ\rÓ5sò 	%Ñ1Ð˜d MÜ),Ø×-Ñ-Ø%5Ø"Ø&+Ø"/ð	 .ó ð ó*ò 
%Ñ%‘�˜!˜gô "ŸI™I g§o¡oÓ&7¸¿¹Ó9JÓKÈkÑY�	Ø×"Ñ"Õ$ñ
%ñ	%÷%÷ %ñ %ús   ±BCÃCc                  óÌ   ‡ — e Zd Zdej                  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ˆ xZS )r3   g      4@é    Fc                óò   •— t         ‰| �  «        t        |d   t        «      rt	        d«      ‚|| _        || _        || _        t        j                  «       | _
        || _        d| _        d| _        || _        y)a®  
        Boosted version of MultipleNegativesRankingLoss (https://arxiv.org/pdf/1705.00652.pdf) by GradCache (https://arxiv.org/pdf/2101.06983.pdf).

        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.

        Args:
            model: SentenceTransformer model
            scale: Output of similarity function is multiplied by scale value
            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.
            show_progress_bar: If True, a progress bar for the mini-batches is shown during training. The default is False.

        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

        Requirements:
            1. (anchor, positive) pairs or (anchor, positive, negative pairs)
            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   z¦CachedMultipleNegativesRankingLoss is not compatible with a SentenceTransformer model based on a StaticEmbedding. Consider using MultipleNegativesRankingLoss instead.N)Úsuperr   Ú
isinstancer   Ú
ValueErrorÚmodelÚscaleÚsimilarity_fctr
   ÚCrossEntropyLossÚcross_entropy_lossÚmini_batch_sizer9   r8   Úshow_progress_bar)r   rO   rP   rQ   rT   rU   Ú	__class__s         €r   r   z+CachedMultipleNegativesRankingLoss.__init__@   sz   ø€ ôl 	‰ÑÔÜ�e˜A‘h¤Ô0ÜðGóð ð
 ˆŒ
ØˆŒ
Ø,ˆÔÜ"$×"5Ñ"5Ó"7ˆÔØ.ˆÔØ04ˆŒ
Ø=AˆÔØ!2ˆÕr   c                óv  — |rt         nt        j                  }|€
t        «       n|}|j                  «       D �	�
ci c]  \  }	}
|	|
|| “Œ }}	}
|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)zYDo forward pass on a minibatch of the input features and return corresponding embeddings.NÚsentence_embedding)r   r   Úno_gradÚitemsr   ÚvaluesrO   )r   r5   ÚbeginÚendr6   r7   Úrandom_stateÚgrad_contextÚrandom_state_contextÚkÚvÚsentence_feature_minibatchÚrepss                r   Úembed_minibatchz2CachedMultipleNegativesRankingLoss.embed_minibatch¦   sÍ   € ñ '0•{´U·]±]ˆØ0<Ð0Dœ{œ}È,ÐØBR×BXÑBXÓBZ×%[¹$¸!¸Q a¨¨5°¨¡oÐ%[Ð"Ñ%[Ø!ñ 	TÙ“ñ TÙTeœ{Ð,F×,MÑ,MÓ,OÑPÐko�Ø—z‘zÐ"<Ó=Ð>RÑS�÷T÷	Tð �\Ð!Ð!ùó &\÷Tð Tú÷	Tð �\Ð!Ð!ús)   ºBÁB,Á/B ÂB,Â B)	Â%B,Â,B8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.Ú	input_idsr   zEmbed mini-batches©ÚdescÚdisableN)r5   r\   r]   r6   r7   r^   )ÚshapeÚ	enumerateÚtqdmÚtrangerT   rU   re   )r   r5   r6   r7   r8   rg   ÚbszrE   ÚiÚbÚerd   r^   s                r   r<   z7CachedMultipleNegativesRankingLoss.embed_minibatch_iter¹   s¸   è ø€ ð -¨[Ñ9ˆ	Ø—‘‰ˆˆQÜÜ�K‰KØØØ×$Ñ$Ø)Ø ×2Ñ2Ð2ôó
ò 	%‰DˆAˆqð �D×(Ñ(Ñ(ˆAØ!%×!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_rC   r9   )r   rd   ÚlossÚrsÚrs        r   Ú"calculate_loss_and_cache_gradientszECachedMultipleNegativesRankingLoss.calculate_loss_and_cache_gradients×   sY   € à×"Ñ" 4°tÐ"Ó<ˆØ�{‰{‹}×+Ñ+Ó-ˆà59×:¨r rÖ* !�q—v“vÔ*Ó:ˆŒ
àˆùò +ùÓ:s   ·	A(Á A#ÁA(Á#A(c                óÌ  — t        j                  |d   «      }t        j                  |dd D �cg c]  }t        j                  |«      ‘Œ c}«      }t        |«      }t        j                  t	        |«      t         j
                  |j                  ¬«      }g }t        j                  d|| j                  d| j                   ¬«      D ]Š  }	|	| j                  z   }
| j                  ||	|
 |«      | j                  z  }| j                  |||	|
 «      t        |«      z  |z  }|r |j                  «        |j                  «       }|j!                  |«       ŒŒ t#        |«      }|S c c}w )zACalculate the cross-entropy loss. No need to cache the gradients.r   é   N)ÚdtypeÚdevicezPreparing cachesrh   )r   ÚcatÚlenÚtensorÚrangeÚlongr   rm   rn   rT   rU   rQ   rP   rS   r?   rv   ÚappendÚsum)r   rd   rt   Úembeddings_arz   Úembeddings_bÚ
batch_sizeÚlabelsÚlossesrq   rr   ÚscoresÚloss_mbatchrx   s                 r   ru   z1CachedMultipleNegativesRankingLoss.calculate_lossà   sG  € ä—y‘y  a¡Ó)ˆÜ—y‘y¸¸Q¸R¸Ö!A°1¤%§)¡)¨A¥,Ò!AÓBˆä˜Ó&ˆ
Ü—‘Ü�*Ó¤U§Z¡Z¸×8KÑ8Kô
ˆð &(ˆÜ—‘ØØØ× Ñ Ø#Ø×.Ñ.Ð.ô
ò 	'ˆAð �D×(Ñ(Ñ(ˆAØ!×0Ñ0°¸aÀÐ1BÀLÓQÐTX×T^ÑT^Ñ^ˆFØ(,×(?Ñ(?ÀÈÈqÐQRÈÓ(TÔWZÐ[aÓWbÑ(bÐeoÑ(oˆKÙØ×$Ñ$Ô&Ø)×0Ñ0Ó2�Ø�M‰M˜+Õ&ð	'ô �6‹{ˆØˆùò/ "Bs   ¯E!c                óì  — 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 )NFT)r5   r6   r7   )rA   rB   )r8   r<   r…   rv   rw   r   Úis_grad_enabledr{   Úregister_hookr   rH   ru   )
r   rA   rŠ   rd   r5   Úreps_mbsÚrandom_state_mbsrD   r^   rx   s
             r   Úforwardz*CachedMultipleNegativesRankingLoss.forwardü   sþ   € àˆØˆÔØ 1ò 	8ÐØˆHØ!ÐØ)-×)BÑ)BØ!1ØØ"&ð *Có *ò 6Ñ%�˜ð
 —‘ §¡Ó 0× ?Ñ ?Ó AÔBØ ×'Ñ'¨Õ5ð6ð �K‰K˜Ô!Ø×Ñ×%Ñ%Ð&6Õ7ð	8ô × Ñ Ô"à×:Ñ:¸4Ó@ˆDð ×Ñœw¤~ÐIZÐeiÔjÔkð
 ˆð ×&Ñ& tÓ,ˆDàˆr   c                ó^   — | j                   | j                  j                  | j                  dœS )N)rP   rQ   rT   )rP   rQ   r.   rT   r&   s    r   Úget_config_dictz2CachedMultipleNegativesRankingLoss.get_config_dict  s+   € à—Z‘ZØ"×1Ñ1×:Ñ:Ø#×3Ñ3ñ
ð 	
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}
}
r2   r&   s    r   Úcitationz+CachedMultipleNegativesRankingLoss.citation   s   € ð	r   )rO   r   rP   ÚfloatrQ   z"callable[[Tensor, Tensor], Tensor]rT   ÚintrU   Úboolr,   r-   r   )r5   údict[str, Tensor]r\   r™   r]   r™   r6   rš   r7   rš   r^   zRandContext | Noner,   z!tuple[Tensor, RandContext | None])
r5   r›   r6   rš   r7   rš   r8   zlist[RandContext] | Noner,   z+Iterator[tuple[Tensor, RandContext | None]])rd   úlist[list[Tensor]]r,   r	   )F)rd   rœ   rt   rš   r,   r	   )rA   úIterable[dict[str, Tensor]]rŠ   r	   r,   r	   )r,   zdict[str, Any])r,   Ústr)r.   r/   r0   r   Úcos_simr   re   r<   r{   ru   r“   r•   Úpropertyr—   Ú__classcell__)rV   s   @r   r3   r3   ?   s  ø„ ð Ø=A¿\¹\Ø!Ø"'ðd3à"ðd3ð ðd3ð ;ð	d3ð
 ðd3ð  ðd3ð 
õd3ðZ ,0ð"à+ð"ð ð"ð ð	"ð
 ð"ð  ð"ð )ð"ð 
+ó"ð0 37ð%à+ð%ð ð%ð  ð	%ð
 0ð%ð 
5ó%ó<ôó8ó:
ð ò
ó ô
r   )r@   r	   rA   r�   rB   r3   r,   r-   )Ú
__future__r   Úcollections.abcr   r   Ú
contextlibr   Ú	functoolsr   Útypingr   r   rm   r	   r
   Útorch.utils.checkpointr   r   Úsentence_transformersr   r   Úsentence_transformers.modelsr   r   rH   ÚModuler3   r2   r   r   ú<module>r«      sk   ðÝ "ç .Ý "Ý Ý ã Û ß ß Gç ;Ý 8÷ñ ð.%Øð%à2ð%ð 1ð%ð 
ó	%ô.l¨¯©õ lr   