
    Ng!t                    .   d dl mZ d dlZd dlZd dlmZ d dlmZmZm	Z	 d dl
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mZmZmZ d d
lmZ d dlmZ d dlm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z&m'Z'm(Z(  ej)        e*          Z+ G d de          Z,dS )    )annotationsN)wraps)CallableLiteraloverload)Tensornn)	Optimizer)
DataLoader)tqdmtrange)
AutoConfig"AutoModelForSequenceClassificationAutoTokenizeris_torch_npu_available)BatchEncoding)PushToHubMixin)SentenceEvaluator)InputExample)SentenceTransformer)fullnameget_device_nameimport_from_stringc                      e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 djdkdZdldZdmdZddd ej                    d d!e	j
        j        d"d#id$d%dd&dddd&fdnd;Ze	 	 	 	 	 	 	 dodpdI            Ze	 	 	 	 	 	 	 dqdrdM            Ze	 	 	 	 	 	 	 dodsdN            Ze	 	 	 	 	 	 	 dodtdQ            Z	 	 	 	 	 	 	 dudvdTZ	 	 	 	 	 	 	 	 	 dwdxd\Zdyd]Zd&d^dzdaZd&d^dzdbZ eej                  ddd&ddcd{ fdi            Z xZS )|CrossEncodera2
  
    A CrossEncoder takes exactly two sentences / texts as input and either predicts
    a score or label for this sentence pair. It can for example predict the similarity of the sentence pair
    on a scale of 0 ... 1.

    It does not yield a sentence embedding and does not work for individual sentences.

    Args:
        model_name (str): A model name from Hugging Face Hub that can be loaded with AutoModel, or a path to a local
            model. We provide several pre-trained CrossEncoder models that can be used for common tasks.
        num_labels (int, optional): Number of labels of the classifier. If 1, the CrossEncoder is a regression model that
            outputs a continuous score 0...1. If > 1, it output several scores that can be soft-maxed to get
            probability scores for the different classes. Defaults to None.
        max_length (int, optional): Max length for input sequences. Longer sequences will be truncated. If None, max
            length of the model will be used. Defaults to None.
        device (str, optional): Device that should be used for the model. If None, it will use CUDA if available.
            Defaults to None.
        automodel_args (Dict, optional): Arguments passed to AutoModelForSequenceClassification. Defaults to None.
        tokenizer_args (Dict, optional): Arguments passed to AutoTokenizer. Defaults to None.
        config_args (Dict, optional): Arguments passed to AutoConfig. Defaults to None.
        cache_dir (`str`, `Path`, optional): Path to the folder where cached files are stored.
        trust_remote_code (bool, optional): Whether or not to allow for custom models defined on the Hub in their own modeling files.
            This option should only be set to True for repositories you trust and in which you have read the code, as it
            will execute code present on the Hub on your local machine. Defaults to False.
        revision (Optional[str], optional): The specific model version to use. It can be a branch name, a tag name, or a commit id,
            for a stored model on Hugging Face. Defaults to None.
        local_files_only (bool, optional): If `True`, avoid downloading the model. Defaults to False.
        default_activation_function (Callable, optional): Callable (like nn.Sigmoid) about the default activation function that
            should be used on-top of model.predict(). If None. nn.Sigmoid() will be used if num_labels=1,
            else nn.Identity(). Defaults to None.
        classifier_dropout (float, optional): The dropout ratio for the classification head. Defaults to None.
    NF
model_namestr
num_labelsint
max_lengthdevice
str | Noneautomodel_argsdicttokenizer_argsconfig_args	cache_dirtrust_remote_codeboolrevisionlocal_files_onlyclassifier_dropoutfloatreturnNonec           	        |i }|i }|i }t          j        |f|	|
||d|| _        d}| j        j        #t	          d | j        j        D                       }||| j        _        ||sd}||| j        _        t          j        |f| j        |
|	||d|| _        t          j        |f|
||	|d|| _
        || _        |+t                      }t                              d|            t          j        |          | _        |j|| _        	 t'          | j                  | j        _        d S # t*          $ r5}t                              dt/          |                      Y d }~d S d }~ww xY wt1          | j        d	          r4| j        j        ( t3          | j        j                              | _        d S | j        j        dk    rt5          j                    nt5          j                    | _        d S )
N)r(   r*   r+   r'   Tc                8    g | ]}|                     d           S )ForSequenceClassification)endswith).0archs     l/var/www/html/ai-engine/env/lib/python3.11/site-packages/sentence_transformers/cross_encoder/CrossEncoder.py
<listcomp>z)CrossEncoder.__init__.<locals>.<listcomp>]   s%    bbb:;;bbb       )configr*   r(   r+   r'   )r*   r+   r(   r'   zUse pytorch device: zEWas not able to update config about the default_activation_function: $sbert_ce_default_activation_function)r   from_pretrainedr:   architecturesanyr,   r   r   modelr   	tokenizerr    r   loggerinfotorchr!   _target_devicedefault_activation_functionr   r;   	Exceptionwarningr   hasattrr   r	   SigmoidIdentity)selfr   r   r    r!   r#   r%   r&   r'   r(   r*   r+   rE   r,   classifier_trainedes                   r6   __init__zCrossEncoder.__init__<   s     !N!NK 0
/-
 
 
 
 ";$0!$bbHabbb" " )-?DK*&8J!%/DK"7G
;/-
 
 
 

 '6
-/
 
 
 
 %>$&&FKK7v77888#l622&2/JD,qCKDLlCmCm@@@ q q qogjklgmgmoopppppppppq DK!GHH	n@L/s/A$+Br/s/s/u/uD,,,?C{?UYZ?Z?Zrz|||`b`k`m`mD,,,s   D1 1
E0;*E++E0batchlist[InputExample]tuple[BatchEncoding, Tensor]c                ^   d t          t          |d         j                            D             }g }|D ]c}t          |j                  D ]2\  }}||                             |                                           3|                    |j                   d | j        |ddd| j        d}t          j
        || j        j        dk    rt          j        nt          j                                      | j                  }|D ]%}||                             | j                  ||<   &||fS )	Nc                    g | ]}g S  rT   r4   _s     r6   r7   z7CrossEncoder.smart_batching_collate.<locals>.<listcomp>   s    888888r8   r   Tlongest_firstptpadding
truncationreturn_tensorsr    r9   )dtype)rangelentexts	enumerateappendstriplabelr@   r    rC   tensorr:   r   r-   longtorD   )	rK   rO   r`   labelsexampleidxtext	tokenizednames	            r6   smart_batching_collatez#CrossEncoder.smart_batching_collate   sA   88U3uQx~#6#677888 	) 	)G&w}55 0 0	Tc
!!$**,,////MM'-(((("DND_T^b^m
 
 
	 f4;;QUV;V;VEKK\a\fgggjj
 
  	F 	FD'o001DEEIdOO&  r8   r   c                f   d t          t          |d                             D             }|D ]D}t          |          D ]2\  }}||                             |                                           3E | j        |ddd| j        d}|D ]%}||                             | j                  ||<   &|S )Nc                    g | ]}g S rT   rT   rU   s     r6   r7   zACrossEncoder.smart_batching_collate_text_only.<locals>.<listcomp>   s    222222r8   r   TrW   rX   rY   )	r^   r_   ra   rb   rc   r@   r    rg   rD   )rK   rO   r`   ri   rj   rk   rl   rm   s           r6    smart_batching_collate_text_onlyz-CrossEncoder.smart_batching_collate_text_only   s    22U3uQx==11222 	0 	0G&w// 0 0	Tc
!!$**,,////0 #DND_T^b^m
 
 
	  	F 	FD'o001DEEIdOOr8   r9   WarmupLineari'  lrgh㈵>g{Gz?r   Ttrain_dataloaderr   	evaluatorr   epochs	schedulerwarmup_stepsoptimizer_classtype[Optimizer]optimizer_paramsdict[str, object]weight_decayevaluation_stepsoutput_pathsave_best_modelmax_grad_normuse_ampcallback!Callable[[float, int, int], None]show_progress_barc           
     @	    | j         |_        |rUt                      r$t          j        j                                        }n#t          j        j                                        }| j        	                    | j
                   |t          j        |d           d| _        t          t          |          |z            }t!          | j                                                  }g d  fd|D             |
d fd|D             d	dg} ||fi |	}t%          |t&                    rt)          j        ||||
          }|6| j        j        dk    rt1          j                    nt1          j                    }d}t7          |d|           D ]}d}| j                                         | j                                         t=          |dd|           D ]\  }}|rWt          j        | j
        j                   5   | j        di |ddi} ||j!                  }| j        j        dk    r|"                    d          } |||          }ddd           n# 1 swxY w Y   |#                                }|$                    |          %                                 |&                    |           t          j        j'        (                    | j        )                                |           |*                    |           |+                                 |#                                |k    }n | j        di |ddi} ||j!                  }| j        j        dk    r|"                    d          } |||          }|%                                 t          j        j'        (                    | j        )                                |           |*                                 |                                 |s|*                                 |dz  }|[|dk    rU||z  dk    rL| ,                    ||||||           | j                                         | j                                         || ,                    ||||d|           dS )a
  
        Train the model with the given training objective
        Each training objective is sampled in turn for one batch.
        We sample only as many batches from each objective as there are in the smallest one
        to make sure of equal training with each dataset.

        Args:
            train_dataloader (DataLoader): DataLoader with training InputExamples
            evaluator (SentenceEvaluator, optional): An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc. Defaults to None.
            epochs (int, optional): Number of epochs for training. Defaults to 1.
            loss_fct: Which loss function to use for training. If None, will use nn.BCEWithLogitsLoss() if self.config.num_labels == 1 else nn.CrossEntropyLoss(). Defaults to None.
            activation_fct: Activation function applied on top of logits output of model.
            scheduler (str, optional): Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts. Defaults to "WarmupLinear".
            warmup_steps (int, optional): Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero. Defaults to 10000.
            optimizer_class (Type[Optimizer], optional): Optimizer. Defaults to torch.optim.AdamW.
            optimizer_params (Dict[str, object], optional): Optimizer parameters. Defaults to {"lr": 2e-5}.
            weight_decay (float, optional): Weight decay for model parameters. Defaults to 0.01.
            evaluation_steps (int, optional): If > 0, evaluate the model using evaluator after each number of training steps. Defaults to 0.
            output_path (str, optional): Storage path for the model and evaluation files. Defaults to None.
            save_best_model (bool, optional): If true, the best model (according to evaluator) is stored at output_path. Defaults to True.
            max_grad_norm (float, optional): Used for gradient normalization. Defaults to 1.
            use_amp (bool, optional): Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0. Defaults to False.
            callback (Callable[[float, int, int], None], optional): Callback function that is invoked after each evaluation.
                It must accept the following three parameters in this order:
                `score`, `epoch`, `steps`. Defaults to None.
            show_progress_bar (bool, optional): If True, output a tqdm progress bar. Defaults to True.
        NT)exist_okiig)biaszLayerNorm.biaszLayerNorm.weightc                R    g | ]"\  }t          fd D                        |#S )c              3      K   | ]}|v V  	d S NrT   r4   ndns     r6   	<genexpr>z.CrossEncoder.fit.<locals>.<listcomp>.<genexpr>   s(      C_C_PRB!GC_C_C_C_C_C_r8   r>   r4   pr   no_decays     @r6   r7   z$CrossEncoder.fit.<locals>.<listcomp>   sA    ```AC_C_C_C_V^C_C_C_@_@_`1```r8   )paramsr}   c                R    g | ]"\  }t          fd D                        |#S )c              3      K   | ]}|v V  	d S r   rT   r   s     r6   r   z.CrossEncoder.fit.<locals>.<listcomp>.<genexpr>   s'      <X<XR1W<X<X<X<X<X<Xr8   r   r   s     @r6   r7   z$CrossEncoder.fit.<locals>.<listcomp>   s@    YYYda<X<X<X<Xx<X<X<X9X9XYYYYr8   g        )rw   rx   t_totalr9   FEpoch)descdisabler   	Iterationg?)r   	smoothingr   )device_typereturn_dictrT   )-rn   
collate_fnr   rC   npuamp
GradScalercudar?   rg   rD   osmakedirs
best_scorer   r_   listnamed_parameters
isinstancer   r   _get_schedulerr:   r   r	   BCEWithLogitsLossCrossEntropyLossr   	zero_gradtrainr   autocasttypelogitsview	get_scalescalebackwardunscale_utilsclip_grad_norm_
parametersstepupdate_eval_during_training)!rK   rt   ru   rv   loss_fctactivation_fctrw   rx   ry   r{   r}   r~   r   r   r   r   r   r   scalernum_train_stepsparam_optimizeroptimizer_grouped_parameters	optimizerskip_schedulerepochtraining_stepsfeaturesrh   model_predictionsr   
loss_valuescale_before_stepr   s!                                   @r6   fitzCrossEncoder.fit   s8   ^ '+&A# 	5%'' 511332244
d)***"Kd3333"c"233f<== tz::<<==AAA a`````` ,  ZYYYoYYYknoo(
$ $O$@UUDTUU	i%% 	+:Y\Sb  I 151G11L1Lr+---RTReRgRgHF>O:OPPP 2	i 2	iENJ  """J$( {dPaLa% % % *' *' &  %D4G4LMMM > >,6DJ,T,T,T,Tt,T,T,T)!/0A0H!I!I;1Q66%+[[__F%-Xff%=%=
> > > > > > > > > > > > > > > )/(8(8(:(:%LL,,55777OOI...HN224:3H3H3J3JMZZZKK	***MMOOO%+%5%5%7%7;L%LNN(2
(P(PX(P(P4(P(P(P%+^,=,DEEF{-22!'R!)&&!9!9J'')))HN224:3H3H3J3JMZZZNN$$$##%%%% %NN$$$!#(-=-A-AnWgFgklFlFl..!;X`   J((***J$$&&&$**9k?TY[]_ghhhe2	i 2	is   AI##I'*I'.	sentencestuple[str, str] | list[str]
batch_sizebool | Nonenum_workersr   Callable | Noneapply_softmaxconvert_to_numpyLiteral[False]convert_to_tensortorch.Tensorc	                    d S r   rT   	rK   r   r   r   r   r   r   r   r   s	            r6   predictzCrossEncoder.predict>  	     sr8   Elist[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str]Literal[True]
np.ndarrayc	                    d S r   rT   r   s	            r6   r   zCrossEncoder.predictK  s	     Sr8   c	                    d S r   rT   r   s	            r6   r   zCrossEncoder.predictX  r   r8   'list[tuple[str, str]] | list[list[str]]list[torch.Tensor]c	                    d S r   rT   r   s	            r6   r   zCrossEncoder.predicte  s	     !Sr8       .list[torch.Tensor] | np.ndarray | torch.Tensorc	                   d}	t          |d         t                    r|g}d}	t          ||| j        |d          }
|Nt                                          t          j        k    p&t                                          t          j        k    }|
}|rt          |
d          }|| j
        }g }| j                                         | j                            | j                   t          j                    5  |D ]y} | j        di |ddi} ||j                  }|r?t%          |d                   d	k    r&t          j        j                            |d	
          }|                    |           z	 ddd           n# 1 swxY w Y   | j        j        d	k    rd |D             }|rt          j        |          }n |rt5          j        d |D                       }|	r|d         }|S )a  
        Performs predictions with the CrossEncoder on the given sentence pairs.

        Args:
            sentences (Union[List[Tuple[str, str]], Tuple[str, str]]): A list of sentence pairs [(Sent1, Sent2), (Sent3, Sent4)]
                or one sentence pair (Sent1, Sent2).
            batch_size (int, optional): Batch size for encoding. Defaults to 32.
            show_progress_bar (bool, optional): Output progress bar. Defaults to None.
            num_workers (int, optional): Number of workers for tokenization. Defaults to 0.
            activation_fct (callable, optional): Activation function applied on the logits output of the CrossEncoder.
                If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity. Defaults to None.
            convert_to_numpy (bool, optional): Convert the output to a numpy matrix. Defaults to True.
            apply_softmax (bool, optional): If there are more than 2 dimensions and apply_softmax=True,
                applies softmax on the logits output. Defaults to False.
            convert_to_tensor (bool, optional): Convert the output to a tensor. Defaults to False.

        Returns:
            Union[List[float], np.ndarray, torch.Tensor]: Predictions for the passed sentence pairs.
            The return type depends on the `convert_to_numpy` and `convert_to_tensor` parameters.
            If `convert_to_tensor` is True, the output will be a torch.Tensor.
            If `convert_to_numpy` is True, the output will be a numpy.ndarray.
            Otherwise, the output will be a list of float values.

        Examples:
            ::

                from sentence_transformers import CrossEncoder

                model = CrossEncoder("cross-encoder/stsb-roberta-base")
                sentences = [["I love cats", "Cats are amazing"], ["I prefer dogs", "Dogs are loyal"]]
                model.predict(sentences)
                # => array([0.6912767, 0.4303499], dtype=float32)
        Fr   T)r   r   r   shuffleNBatches)r   r   r9   )dimc                    g | ]
}|d          S )r   rT   r4   scores     r6   r7   z(CrossEncoder.predict.<locals>.<listcomp>  s    ===58===r8   c                    g | ]L}|                                                                                                                                 MS rT   )cpudetachr-   numpyr   s     r6   r7   z(CrossEncoder.predict.<locals>.<listcomp>  sD    %d%d%dueiikk&8&8&:&:&@&@&B&B&H&H&J&J%d%d%dr8   rT   )r   r   r   rq   rA   getEffectiveLevelloggingINFODEBUGr   rE   r?   evalrg   rD   rC   no_gradr   r_   r	   
functionalsoftmaxextendr:   r   stacknpasarray)rK   r   r   r   r   r   r   r   r   input_was_stringinp_dataloaderiteratorpred_scoresr   r   r   s                   r6   r   zCrossEncoder.predictr  sh   X !ilC(( 	$"I##!<#
 
 
 $((**gl:if>V>V>X>X\c\i>i  " 	<N;;;H!!=N

d)***]__ 	+ 	+$ + +$.DJ$L$L$L$Lt$L$L$L!'(9(@AA  HS^^a%7%7"X088Q8GGF""6****+	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ ;!Q&&=====K 	f+k22KK 	f*%d%dXc%d%d%deeK 	)%a.Ks   7A=FFFquery	documents	list[str]top_k
int | Nonereturn_documentsDlist[dict[Literal['corpus_id', 'score', 'text'], int | float | str]]c           
     <   fd|D             }|                      ||||||	|
|          }g }t          |          D ]B\  }}|                    ||d           |r#|d                             d||         i           Ct	          |d d          }|d	|         S )
ab  
        Performs ranking with the CrossEncoder on the given query and documents. Returns a sorted list with the document indices and scores.

        Args:
            query (str): A single query.
            documents (List[str]): A list of documents.
            top_k (Optional[int], optional): Return the top-k documents. If None, all documents are returned. Defaults to None.
            return_documents (bool, optional): If True, also returns the documents. If False, only returns the indices and scores. Defaults to False.
            batch_size (int, optional): Batch size for encoding. Defaults to 32.
            show_progress_bar (bool, optional): Output progress bar. Defaults to None.
            num_workers (int, optional): Number of workers for tokenization. Defaults to 0.
            activation_fct ([type], optional): Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity. Defaults to None.
            convert_to_numpy (bool, optional): Convert the output to a numpy matrix. Defaults to True.
            apply_softmax (bool, optional): If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output. Defaults to False.
            convert_to_tensor (bool, optional): Convert the output to a tensor. Defaults to False.

        Returns:
            List[Dict[Literal["corpus_id", "score", "text"], Union[int, float, str]]]: A sorted list with the "corpus_id", "score", and optionally "text" of the documents.

        Example:
            ::

                from sentence_transformers import CrossEncoder
                model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

                query = "Who wrote 'To Kill a Mockingbird'?"
                documents = [
                    "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature.",
                    "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil.",
                    "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961.",
                    "Jane Austen was an English novelist known primarily for her six major novels, which interpret, critique and comment upon the British landed gentry at the end of the 18th century.",
                    "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era.",
                    "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan."
                ]

                model.rank(query, documents, return_documents=True)

            ::

                [{'corpus_id': 0,
                'score': 10.67858,
                'text': "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature."},
                {'corpus_id': 2,
                'score': 9.761677,
                'text': "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961."},
                {'corpus_id': 1,
                'score': -3.3099542,
                'text': "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil."},
                {'corpus_id': 5,
                'score': -4.8989105,
                'text': "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan."},
                {'corpus_id': 4,
                'score': -5.082967,
                'text': "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era."}]
        c                    g | ]}|gS rT   rT   )r4   docr  s     r6   r7   z%CrossEncoder.rank.<locals>.<listcomp>  s    ===CE3<===r8   )r   r   r   r   r   r   r   r   )	corpus_idr   r   rk   c                    | d         S )Nr   rT   )xs    r6   <lambda>z#CrossEncoder.rank.<locals>.<lambda>'  s
    '
 r8   T)keyreverseN)r   ra   rb   r   sorted)rK   r  r  r  r  r   r   r   r   r   r   r   query_doc_pairsscoresresultsir   s    `               r6   rankzCrossEncoder.rank  s    J >===9===%!/#)'-/  	
 	
 !&)) 	; 	;HAuNNU;;<<< ;""FIaL#9:::&:&:DIIIvvr8   c                    |I || |||          }| ||||           || j         k    r"|| _         |r|                     |           dS dS dS dS )z#Runs evaluation during the trainingN)r   r   steps)r   save)rK   ru   r   r   r   r  r   r   s           r6   r   z"CrossEncoder._eval_during_training*  s     Id5PUVVVE#u---t&&"'" +IIk***** !  '&+ +r8   )safe_serializationpathr  c                   |dS t                               d|             | j        j        |fd|i|  | j        j        |fi | dS )zW
        Saves the model and tokenizer to path; identical to `save_pretrained`
        NzSave model to r  )rA   rB   r?   save_pretrainedr@   rK   r  r  kwargss       r6   r  zCrossEncoder.save5  sp     <F+T++,,,"
"4YY<NYRXYYY&&t66v66666r8   c               "     | j         |fd|i|S )zL
        Saves the model and tokenizer to path; identical to `save`
        r  )r  r  s       r6   r  zCrossEncoder.save_pretrained@  s$     tyOO2DOOOOr8   )commit_messageprivater  tagsrepo_idr!  r"  r#  list[str] | Nonec          	         t          |t                    r|g}n|g }d|vr|                    dd            t                      j        d|||||d|S )Nzcross-encoderr   )r$  r  r!  r"  r#  rT   )r   r   insertsuperpush_to_hub)rK   r$  r!  r"  r  r#  r  	__class__s          r6   r)  zCrossEncoder.push_to_hubF  s     dC   	6DD\D$&&KK?+++"uww" 
1)
 
 
 
 	
r8   )NNNNNNNFNFNN)r   r   r   r   r    r   r!   r"   r#   r$   r%   r$   r&   r$   r'   r   r(   r)   r*   r"   r+   r)   r,   r-   r.   r/   )rO   rP   r.   rQ   )rO   rP   r.   r   ) rt   r   ru   r   rv   r   rw   r   rx   r   ry   rz   r{   r|   r}   r-   r~   r   r   r   r   r)   r   r-   r   r)   r   r   r   r)   r.   r/   ).......)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r.   r   ).....TF)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r.   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r)   r   r   r.   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r.   r   )r   Nr   NFTF)r   r   r   r   r   r   r   r   r   r   r   r   r   r)   r   r)   r.   r   )	NFr   Nr   NFTF)r  r   r  r  r  r  r  r)   r   r   r   r)   r   r   r   r)   r   r)   r.   r  )r.   r/   )r  r   r  r)   r.   r/   )r$  r   r!  r"   r"  r   r  r)   r#  r%  r.   r   )__name__
__module____qualname____doc__rN   rn   rq   r	   rJ   rC   optimAdamWr   r   r   r  r   r  r  r   r   r)  __classcell__)r*  s   @r6   r   r      s        H !## "'#!&$($(Qn Qn Qn Qn Qnf! ! ! !,   & (,"r{}}'!+0;+</3Tl" ! $ 6:"&%Gi Gi Gi Gi GiR  ),*-%(+.,/
 
 
 
 X
  ),*-%(*.,1
 
 
 
 X
  ),*-%(!$+.
 
 
 
 X
  ),*-%(+.,/
! 
! 
! 
! X
! )-*.%*!%"'\ \ \ \ \D !!&"&!%"'X X X X Xt	+ 	+ 	+ 	+ =A 	7 	7 	7 	7 	7 	7 HL P P P P P P U>%&&
 &*##'!%
 
 
 
 
 
 
 '&
 
 
 
 
r8   r   )-
__future__r   r   r   	functoolsr   typingr   r   r   r   r   rC   r   r	   torch.optimr
   torch.utils.datar   tqdm.autonotebookr   r   transformersr   r   r   r   $transformers.tokenization_utils_baser   transformers.utilsr   2sentence_transformers.evaluation.SentenceEvaluatorr   sentence_transformers.readersr   )sentence_transformers.SentenceTransformerr   sentence_transformers.utilr   r   r   	getLoggerr+  rA   r   rT   r8   r6   <module>r@     s   " " " " " "  				       . . . . . . . . . .              ! ! ! ! ! ! ' ' ' ' ' ' * * * * * * * * n n n n n n n n n n n n > > > > > > - - - - - - P P P P P P 6 6 6 6 6 6 I I I I I I T T T T T T T T T T		8	$	$D	
 D	
 D	
 D	
 D	
> D	
 D	
 D	
 D	
 D	
r8   