
    rh@<                    `   d dl 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mZ d dlmZ d dlZd dlmZmZmZ d d	lmZ  e       rd d
lmZ  ej0                  e      Z G d d      Z G d dee      Z G d de      Z G d de      Z G d deee      Z G d de      Z  G d de      Z!y)    )annotationsN)ABCabstractmethod)defaultdict)Iterator)
accumulatecycle)Any)BatchSamplerConcatDatasetSubsetRandomSampler)is_datasets_available)Datasetc                  ,     e Zd ZdZd fdZddZ xZS )SetEpochMixinz
    Required for a BatchSampler as the Trainer will call set_epoch on the BatchSampler at the beginning of each epoch.
    The BatchSampler can then set the generator seed accordingly.
    c                2    t        |   |i | d| _        y Nr   )super__init__epoch)selfargskwargs	__class__s      p/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/sentence_transformers/sampler.pyr   zSetEpochMixin.__init__   s    $)&)
    c                    || _         y N)r   )r   r   s     r   	set_epochzSetEpochMixin.set_epoch   s	    
r   )returnNone)r   intr    r!   )__name__
__module____qualname____doc__r   r   __classcell__r   s   @r   r   r      s    
r   r   c                  F     e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )DefaultBatchSamplera  
    This sampler is the default batch sampler used in the SentenceTransformer library.
    It is equivalent to the PyTorch BatchSampler.

    Args:
        sampler (Sampler or Iterable): The sampler used for sampling elements from the dataset,
            such as SubsetRandomSampler.
        batch_size (int): Number of samples per batch.
        drop_last (bool): If True, drop the last incomplete batch if the dataset size
            is not divisible by the batch size.
        valid_label_columns (List[str], optional): List of column names to check for labels.
            The first column name from ``valid_label_columns`` found in the dataset will
            be used as the label column.
        generator (torch.Generator, optional): Optional random number generator for shuffling
            the indices.
        seed (int): Seed for the random number generator to ensure reproducibility. Defaults to 0.
    c                T    t         |   |||       || _        || _        || _        y )N
batch_size	drop_last)r   r   valid_label_columns	generatorseed)r   datasetr-   r.   r/   r0   r1   r   s          r   r   zDefaultBatchSampler.__init__6   s/     	Z9M#6 "	r   NNr   r2   r   r-   r"   r.   boolr/   list[str] | Noner0   torch.Generator | Noner1   r"   r    r!   )r#   r$   r%   r&   r   r'   r(   s   @r   r*   r*   #   sa    . 15,0  	
 . *  
 r   r*   c                  `     e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZedd       ZddZ xZS )	GroupByLabelBatchSampleraZ  
    This sampler groups samples by their labels and aims to create batches such that
    each batch contains samples where the labels are as homogeneous as possible.
    This sampler is meant to be used alongside the ``Batch...TripletLoss`` classes, which
    require that each batch contains at least 2 examples per label class.

    Recommended for:
        - :class:`~sentence_transformers.losses.BatchAllTripletLoss`
        - :class:`~sentence_transformers.losses.BatchHardSoftMarginTripletLoss`
        - :class:`~sentence_transformers.losses.BatchHardTripletLoss`
        - :class:`~sentence_transformers.losses.BatchSemiHardTripletLoss`

    Args:
        dataset (Dataset): The dataset to sample from.
        batch_size (int): Number of samples per batch. Must be divisible by 2.
        drop_last (bool): If True, drop the last incomplete batch if the dataset size
            is not divisible by the batch size.
        valid_label_columns (List[str], optional): List of column names to check for labels.
            The first column name from ``valid_label_columns`` found in the dataset will
            be used as the label column.
        generator (torch.Generator, optional): Optional random number generator for shuffling
            the indices.
        seed (int): Seed for the random number generator to ensure reproducibility. Defaults to 0.
    c                   t         |   ||||||       || _        | j                  dz  dk(  rt	        d      | j                  || j                        }t        t              }t        |      D ]  \  }	}
||
   j                  |	        |j                         D 
ci c]  \  }
}t        |      dz  dz  x}r|
|d |   c}}
| _        y c c}}
w )Nr-   r.   r/   r0   r1         zEThe batch size for `GroupByLabelBatchSampler` must be divisible by 2.)r   r   r2   r-   
ValueError_determine_labels_to_user/   r   list	enumerateappenditemslengroups)r   r2   r-   r.   r/   r0   r1   labelsrE   
sample_idxlabelsample_indicesnum_samplesr   s                r   r   z!GroupByLabelBatchSampler.__init___   s     	! 3 	 	
 ??Q!#dee..w8P8PQT"!*6!2 	-J5M  ,	-
 *0
%~">2a7!;;; >,;//
 
s    #Cc                z    |xs g D ]  }|| j                   v s| |   c S  t        d| d| j                    d      )Nz None of the valid_label_columns z3 are in the dataset, which only has these columns: .)column_namesr>   )r2   r/   column_names      r   r?   z1GroupByLabelBatchSampler._determine_labels_to_use   sa    .4" 	,Kg222{++	, ./B.C D--4-A-A,B!E
 	
r   c              #  r  K   | j                   r>| j                  2| j                   j                  | j                  | j                  z          g }t	        | j
                  j                               }t        j                  t        | j
                        | j                         D ]y  }||   }| j
                  |   }|j                  |       t        |      | j                  k\  sA|d | j                    || j                  d  }t        |      | j                  k\  r9{ | j                  s|r| y y y w)Nr0   )r0   r1   manual_seedr   r@   rE   keystorchrandpermrD   extendr-   r.   )r   partial_batchunique_labels	label_idxrH   sampless         r   __iter__z!GroupByLabelBatchSampler.__iter__   s     >>dii3NN&&tyy4::'=>T[[--/0DKK(8DNNS 	AI!),Ekk%(G  )m$7#$5doo66 -doo.? @ m$7		A ~~- #0~s   C$D7'8D7 D7r3   r4   )r2   r   r/   r6   r    z	list[Any]r    zIterator[list[int]])	r#   r$   r%   r&   r   staticmethodr?   rZ   r'   r(   s   @r   r9   r9   E   sv    < 15,0

 
 	

 .
 *
 
 

B 
 
 r   r9   c                  R     e Zd Z	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZddZ xZS )NoDuplicatesBatchSamplerc                    t         |   ||||||       t        |j                        t        | j                  xs g       z  x}r|j                  t        |            }|| _        y)a  
        This sampler creates batches such that each batch contains samples where the values are unique,
        even across columns. This is useful when losses consider other samples in a batch to be in-batch
        negatives, and you want to ensure that the negatives are not duplicates of the anchor/positive sample.

        Recommended for:
            - :class:`~sentence_transformers.losses.MultipleNegativesRankingLoss`
            - :class:`~sentence_transformers.losses.CachedMultipleNegativesRankingLoss`
            - :class:`~sentence_transformers.losses.MultipleNegativesSymmetricRankingLoss`
            - :class:`~sentence_transformers.losses.CachedMultipleNegativesSymmetricRankingLoss`
            - :class:`~sentence_transformers.losses.MegaBatchMarginLoss`
            - :class:`~sentence_transformers.losses.GISTEmbedLoss`
            - :class:`~sentence_transformers.losses.CachedGISTEmbedLoss`

        Args:
            dataset (Dataset): The dataset to sample from.
            batch_size (int): Number of samples per batch.
            drop_last (bool): If True, drop the last incomplete batch if the dataset size
                is not divisible by the batch size.
            valid_label_columns (List[str], optional): List of column names to check for labels.
                The first column name from ``valid_label_columns`` found in the dataset will
                be used as the label column.
            generator (torch.Generator, optional): Optional random number generator for shuffling
                the indices.
            seed (int): Seed for the random number generator to ensure reproducibility. Defaults to 0.
        r;   N)r   r   setrM   r/   remove_columnsr@   r2   )	r   r2   r-   r.   r/   r0   r1   label_columnsr   s	           r   r   z!NoDuplicatesBatchSampler.__init__   st    F 	! 3 	 	
   4 45D<T<T<ZXZ8[[[=[,,T--@AGr   c              #    K   | j                   r>| j                  2| j                   j                  | j                  | j                  z          t        j                  t        j                  t        | j                        | j                         j                               }|rt               }g }|D ]  }| j                  |   j                         D ch c]  \  }}|dk7  st        |       }}}||z  rG|j                  |       t        |      | j                  k(  r|  n#|j!                  |        | j"                  s| |D ]  }||=  |ryyc c}}w w)a5  
        Iterate over the remaining non-yielded indices. For each index, check if the sample values are already in the
        batch. If not, add the sample values to the batch keep going until the batch is full. If the batch is full, yield
        the batch indices and continue with the next batch.
        NrP   dataset_name)r0   r1   rQ   r   dictfromkeysrS   rT   rD   r2   tolistr`   rC   strrB   r-   updater.   )r   remaining_indicesbatch_valuesbatch_indicesindexkeyvaluesample_valuess           r   rZ   z!NoDuplicatesBatchSampler.__iter__   s2     >>dii3NN&&tyy4::'=>
 !MM%..T\\9JVZVdVd*e*l*l*no5LM* (>Bll5>Q>W>W>Y s
U]`dr]rU s s </$$U+}%8''##M2( ~~''& -%e,-)   !ts   CE E#E0A'E E c                    | j                   r"t        | j                        | j                  z  S t        | j                        | j                  z   dz
  | j                  z  S )Nr=   )r.   rD   r2   r-   r   s    r   __len__z NoDuplicatesBatchSampler.__len__   sG    >>t||$77%7!;OOr   r3   r4   r[   r    r"   )r#   r$   r%   r   rZ   rs   r'   r(   s   @r   r^   r^      sd     15,0-- - 	-
 .- *- - 
-^"-HPr   r^   c                  `     e Zd ZdZ	 	 d	 	 	 	 	 	 	 	 	 d fdZedd       Zedd       Z xZS )	MultiDatasetDefaultBatchSampleraT  
    Abstract base batch sampler that yields batches from multiple batch samplers.
    This class must be subclassed to implement specific sampling strategies, and
    cannot be used directly.

    Args:
        dataset (ConcatDataset): A concatenation of multiple datasets.
        batch_samplers (List[BatchSampler]): A list of batch samplers, one for each dataset in the ConcatDataset.
        generator (torch.Generator, optional): A generator for reproducible sampling. Defaults to None.
        seed (int): Seed for the random number generator to ensure reproducibility. Defaults to 0.
    c                    t        |j                        t        |      k7  rt        d      t        |   ||d   j
                  |d   j                         || _        || _        || _	        || _
        y )NzTThe number of batch samplers must match the number of datasets in the ConcatDataset.r   r,   )rD   datasetsr>   r   r   r-   r.   r2   batch_samplersr0   r1   )r   r2   ry   r0   r1   r   s        r   r   z(MultiDatasetDefaultBatchSampler.__init__  sr     w C$77stt^A->-I-IUcdeUfUpUpq,"	r   c                     y)z?Yield batches from the underlying datasets in a specific order.N rr   s    r   rZ   z(MultiDatasetDefaultBatchSampler.__iter__       	r   c                     y)z,Return the number of batches in the sampler.Nr{   rr   s    r   rs   z'MultiDatasetDefaultBatchSampler.__len__  r|   r   r   )
r2   r   ry   zlist[BatchSampler]r0   r7   r1   r"   r    r!   r[   rt   )	r#   r$   r%   r&   r   r   rZ   rs   r'   r(   s   @r   rv   rv      sm    
  -1 + *	
  
    r   rv   c                       e Zd ZdZddZddZy)RoundRobinBatchSamplera  
    Batch sampler that yields batches in a round-robin fashion from multiple batch samplers, until one is exhausted.
    With this sampler, it's unlikely that all samples from each dataset are used, but we do ensure that each dataset
    is sampled from equally.

    Args:
        dataset (ConcatDataset): A concatenation of multiple datasets.
        batch_samplers (List[BatchSampler]): A list of batch samplers, one for each dataset in the ConcatDataset.
        generator (torch.Generator, optional): A generator for reproducible sampling. Defaults to None.
        seed (int): Seed for the random number generator to ensure reproducibility. Defaults to 0.
    c              #  <  K   | j                   r>| j                  2| j                   j                  | j                  | j                  z          | j                  j
                  D cg c]  }t        |       }}dgt        t        |            z   }| j                  D cg c]  }t        |       }}t        t        t        |                  D ])  }||   }	 t        ||         D cg c]  }||z   	 c} + y c c}w c c}w c c}w # t        $ r Y  y w xY wwr   )r0   r1   rQ   r   r2   rx   rD   r@   r   ry   iterr	   rangenextStopIteration)	r   r2   rJ   sample_offsetssamplerry   dataset_idxsample_offsetidxs	            r   rZ   zRoundRobinBatchSampler.__iter__+  s     >>dii3NN&&tyy4::'=>37<<3H3HIs7|IItJ{$;<<7;7J7JKG$w-KK s>':!;< 	K*;7M6:>+;V6WXss]*XX		 J L Y  sT   A#D%C=7(DD1'DD)D5D:DD	DDDDc                f    t        d | j                  D              t        | j                        z  S )Nc              3  2   K   | ]  }t        |        y wr   )rD   ).0r   s     r   	<genexpr>z1RoundRobinBatchSampler.__len__.<locals>.<genexpr><  s     CG3w<Cs   )minry   rD   rr   s    r   rs   zRoundRobinBatchSampler.__len__;  s)    Ct/B/BCCc$J]J]F^^^r   Nr[   rt   r#   r$   r%   r&   rZ   rs   r{   r   r   r   r     s    
 _r   r   c                       e Zd ZdZddZddZy)ProportionalBatchSamplera|  
    Batch sampler that samples from each dataset in proportion to its size, until all are exhausted simultaneously.
    With this sampler, all samples from each dataset are used and larger datasets are sampled from more frequently.

    Args:
        dataset (ConcatDataset): A concatenation of multiple datasets.
        batch_samplers (List[BatchSampler]): A list of batch samplers, one for each dataset in the ConcatDataset.
        generator (torch.Generator, optional): A generator for reproducible sampling. Defaults to None.
        seed (int): Seed for the random number generator to ensure reproducibility. Defaults to 0.
    c              #    K   | j                   j                  | j                  | j                  z          | j                  j
                  D cg c]  }t        |       }}dgt        t        |            z   }| j                  D cg c]  }t        |       }}t        |      D cg c]  \  }}t        |      D ]  }|  }	}}}t        |	| j                         }
| j                  D cg c]  }t        |       }}|
D ])  }||   }	 t        ||         D cg c]  }||z   	 c} + y c c}w c c}w c c}}}w c c}w c c}w # t        $ r Y Sw xY ww)Nr   rP   )r0   rQ   r1   r   r2   rx   rD   r@   r   ry   rA   r   r   r   r   r   )r   r2   rJ   r   r   num_batchesr   length_dataset_indicesdataset_idx_samplerry   r   r   s                 r   rZ   z!ProportionalBatchSampler.__iter__K  sC    ""499tzz#9:37<<3H3HIs7|IItJ{$;<<373F3FGs7|GG2;K2H``;3RWX^R_`Q3`3``1/T^^\7;7J7JKG$w-KK. 	K*;7M6:>+;V6WXss]*XX	 J H` L Y  sl   AED2(ED7E*D<)E/EEEE*E/EE	EEEEc                d    t        | j                  D cg c]  }t        |       c}      S c c}w r   )sumry   rD   )r   r   s     r   rs   z ProportionalBatchSampler.__len__]  s%    0C0CDWCLDEEDs   -Nr[   rt   r   r{   r   r   r   r   ?  s    	$Fr   r   )"
__future__r   loggingabcr   r   collectionsr   collections.abcr   	itertoolsr   r	   typingr
   rS   torch.utils.datar   r   r   sentence_transformers.utilr   rx   r   	getLoggerr#   loggerr   r*   r9   r^   rv   r   r   r{   r   r   <module>r      s    "  # # $ '   M M < 			8	$ - DT 2 T nXP2 XPv$m\3 $N_< _BF> Fr   