
    Ng:                        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j                  ZdS )    )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dS )	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.
    returnNonec                b    t          j                    | _        t          | \  | _        | _        d S N)torchget_rng_statefwd_cpu_stater   fwd_gpu_devicesfwd_gpu_states)selftensorss     {/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/losses/CachedMultipleNegativesRankingLoss.py__init__zRandContext.__init__   s.    "0224Ew4O1d111    c                    t           j                            | j        d          | _        | j                                         t          j        | j                   t          | j        | j	                   d S )NT)devicesenabled)
r   randomfork_rngr   _fork	__enter__set_rng_stater   r   r   r   s    r   r&   zRandContext.__enter__   sf    \**43GQU*VV

D.///$.0CDDDDDr   c                L    | j                             |||           d | _         d S r   )r%   __exit__)r   exc_typeexc_valexc_tbs       r   r*   zRandContext.__exit__#   s'    
Hgv666


r   N)r   r   )__name__
__module____qualname____doc__r   r&   r*    r   r   r   r      sb         P P P PE E E E     r   r   grad_outputr	   sentence_featuresIterable[dict[str, Tensor]]loss_obj"CachedMultipleNegativesRankingLossr   r   c           
        |j         J |j        J t          j                    5  t	          ||j         |j                  D ]\  }}}t	          |                    |dd|          |          D ]X\  \  }}}t          j        |                                |                                          | z  }	|	                                 Y	 ddd           dS # 1 swxY w Y   dS )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)
r3   r4   r6   r9   gradr<   reps_mb_grad_mb	surrogates
             r   _backward_hookrI   (   sT    >%%%!---				 % %589JHN\d\r5s5s 	% 	%1dM),--%5"&+"/	 .   * * 
% 
%%!g "Igoo&7&79J9JKKkY	""$$$$
%	%% % % % % % % % % % % % % % % % % %s   B#CCCc                       e Zd Zdej        ddfd- fdZ	 d.d/dZ	 d.d0dZd1d#Zd1d$Z	d2d(Z
d3d*Zed4d,            Z xZS )5r7   g      4@    Fmodelr   scalefloatsimilarity_fct"callable[[Tensor, Tensor], Tensor]mini_batch_sizeintshow_progress_barboolr   r   c                .   t                                                       t          |d         t                    rt	          d          || _        || _        || _        t          j	                    | _
        || _        d| _        d| _        || _        dS )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 batch size large. One drawback is about the speed. GradCache 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 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:`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.CachedGISTEmbedLoss(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.N)superr   
isinstancer   
ValueErrorrL   rM   rO   r
   CrossEntropyLosscross_entropy_lossrQ   r=   r<   rS   )r   rL   rM   rO   rQ   rS   	__class__s         r   r   z+CachedMultipleNegativesRankingLoss.__init__@   s    j 	eAh00 	G  
 

,"$"5"7"7.04
=A!2r   Nr9   dict[str, Tensor]beginendr:   r;   random_stateRandContext | None!tuple[Tensor, RandContext | None]c                   |rt           nt          j        }|t                      n|}fd|                                D             }	|5   |            5  |rt	          |	                                 nd}|                     |	          d         }
ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |
|fS )zYDo forward pass on a minibatch of the input features and return corresponding embeddings.Nc                ,    i | ]\  }}||         S r2   r2   ).0kvr]   r^   s      r   
<dictcomp>zFCachedMultipleNegativesRankingLoss.embed_minibatch.<locals>.<dictcomp>   s'    %[%[%[$!Qa59%[%[%[r   sentence_embedding)r   r   no_graditemsr   valuesrL   )r   r9   r]   r^   r:   r;   r_   grad_contextrandom_state_contextsentence_feature_minibatchrepss     ``       r   embed_minibatchz2CachedMultipleNegativesRankingLoss.embed_minibatch   sx    '0B{{U]0<0D{}}},%[%[%[%[%[BRBXBXBZBZ%[%[%["! 	T 	T T TTeo{,F,M,M,O,OPPkozz"<==>RST T T T T T T T T T T T T T T	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T 	T \!!s6   B6;BB6B#	#B6&B#	'B66B:=B:r<   list[RandContext] | None+Iterator[tuple[Tensor, RandContext | None]]c           
   #    K   |d         }|j         \  }}t          t          j        d|| j        d| j                             D ]=\  }}	|	| j        z   }
|                     ||	|
|||dn||                   \  }}||fV  >dS )z`Do forward pass on all the minibatches of the input features and yield corresponding embeddings.	input_idsr   zEmbed mini-batchesdescdisableN)r9   r]   r^   r:   r;   r_   )shape	enumeratetqdmtrangerQ   rS   rp   )r   r9   r:   r;   r<   rt   bszrF   ibero   r_   s                r   r@   z7CachedMultipleNegativesRankingLoss.embed_minibatch_iter   s       -[9	QK$) 22  
 
 	% 	%DAq D((A!%!5!5!1#"3%2%:TTa@P "6 " "D, $$$$$%	% 	%r   ro   list[list[Tensor]]r	   c                   t          j        |d                   }t          j        d |dd         D                       }t          |          }t          j        t	          |          t           j        |j                  }g }t          j        d|| j	        d| j
                   D ]}|| j	        z   }|                     |||         |          | j        z  }	|                     |	|||                   t          |	          z  |z  }
|
                                 |                    |
                                           t#          |                                          }d |D             | _        |S )	zMCalculate the cross-entropy loss and cache the gradients wrt. the embeddings.r   c                6    g | ]}t          j        |          S r2   r   catrd   rs     r   
<listcomp>zYCachedMultipleNegativesRankingLoss.calculate_loss_and_cache_gradients.<locals>.<listcomp>        !A!A!A1%)A,,!A!A!Ar      NdtypedevicePreparing cachesru   c                &    g | ]}d  |D             S )c                    g | ]	}|j         
S r2   )rD   r   s     r   r   zdCachedMultipleNegativesRankingLoss.calculate_loss_and_cache_gradients.<locals>.<listcomp>.<listcomp>   s    ***!qv***r   r2   )rd   rss     r   r   zYCachedMultipleNegativesRankingLoss.calculate_loss_and_cache_gradients.<locals>.<listcomp>   s'    :::r**r***:::r   )r   r   lentensorrangelongr   rz   r{   rQ   rS   rO   rM   rZ   rC   appenddetachsumrequires_grad_r=   r   ro   embeddings_aembeddings_b
batch_sizelabelslossesr~   r   scoresloss_mbatchlosss               r   "calculate_loss_and_cache_gradientszECachedMultipleNegativesRankingLoss.calculate_loss_and_cache_gradients   s~   ya))y!A!AQRR!A!A!ABB&&
*UZ8K
 
 
 &( #..
 
 
 	0 	0A D((A!00ac1BLQQTXT^^F(,(?(?qQRs(T(TWZ[aWbWb(beo(oK  """MM+,,..////6{{))++::T:::
r   c                f   t          j        |d                   }t          j        d |dd         D                       }t          |          }t          j        t	          |          t           j        |j                  }g }t          j        d|| j	        d| j
                   D ]x}|| j	        z   }|                     |||         |          | j        z  }	|                     |	|||                   t          |	          z  |z  }
|                    |
           yt          |          }|S )zACalculate the cross-entropy loss. No need to cache the gradients.r   c                6    g | ]}t          j        |          S r2   r   r   s     r   r   zECachedMultipleNegativesRankingLoss.calculate_loss.<locals>.<listcomp>   r   r   r   Nr   r   ru   )r   r   r   r   r   r   r   rz   r{   rQ   rS   rO   rM   rZ   r   r   r   s               r   calculate_lossz1CachedMultipleNegativesRankingLoss.calculate_loss   s?   ya))y!A!AQRR!A!A!ABB&&
*UZ8K
 
 
 &( #..
 
 
 
	' 
	'A D((A!00ac1BLQQTXT^^F(,(?(?qQRs(T(TWZ[aWbWb(beo(oKMM+&&&&6{{r   r4   r5   r   c                0   g }g | _         |D ]}g }g }|                     |dd          D ]S\  }}|                    |                                                                           |                    |           T|                    |           | j                             |           t          j                    r@|                     |          }	|	                    t          t          ||                      n|                     |          }	|	S )NFT)r9   r:   r;   )r4   r6   )r<   r@   r   r   r   r   is_grad_enabledr   register_hookr   rI   r   )
r   r4   r   ro   r9   reps_mbsrandom_state_mbsrE   r_   r   s
             r   forwardz*CachedMultipleNegativesRankingLoss.forward  s3    1 	8 	8H!)-)B)B!1"& *C * * 6 6%
  0 0 ? ? A ABBB ''5555KK!!!%%&67777 "" 	-::4@@D w~IZeijjjkkkk &&t,,Dr   dict[str, Any]c                *    | j         | j        j        dS )N)rM   rO   )rM   rO   r.   r(   s    r   get_config_dictz2CachedMultipleNegativesRankingLoss.get_config_dict)  s    t7J7STTTr   strc                    dS )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   )rL   r   rM   rN   rO   rP   rQ   rR   rS   rT   r   r   r   )r9   r\   r]   rR   r^   rR   r:   rT   r;   rT   r_   r`   r   ra   )
r9   r\   r:   rT   r;   rT   r<   rq   r   rr   )ro   r   r   r	   )r4   r5   r   r	   r   r	   )r   r   )r   r   )r.   r/   r0   r   cos_simr   rp   r@   r   r   r   r   propertyr   __classcell__)r[   s   @r   r7   r7   ?   s
        =A\!"'c3 c3 c3 c3 c3 c3 c3X ,0" " " " "0 37% % % % %<   :   2   :U U U U 
 
 
 X
 
 
 
 
r   )r3   r	   r4   r5   r6   r7   r   r   )
__future__r   collections.abcr   r   
contextlibr   	functoolsr   typingr   r   rz   r	   r
   torch.utils.checkpointr   r   sentence_transformersr   r   sentence_transformers.modelsr   r   rI   Moduler7   r2   r   r   <module>r      sM   " " " " " " . . . . . . . . " " " " " "                       G G G G G G G G ; ; ; ; ; ; ; ; 8 8 8 8 8 8       .% % % %.x x x x x x x x x xr   