Ë
    l^(huO  ã                  ó\  — 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 d dl	Z	d dl
mZ d dl	m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 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!m"Z" d dl#m$Z$m%Z% d dl&m'Z' d dl(m)Z)m*Z*  e)«       r
d dl+m,Z,m-Z-m.Z.  ej^                  e0«      Z1 G d„ de'«      Z2y)é    )ÚannotationsN)Úpartial)ÚAnyÚCallable)Úparse)Únn)ÚEvalPredictionÚPreTrainedTokenizerBaseÚTrainerCallback)Ú__version__)ÚDataCollator)ÚWandbCallback©ÚCrossEncoder)ÚCrossEncoderDataCollator)ÚBinaryCrossEntropyLossÚCrossEntropyLoss)ÚCrossEncoderModelCardCallback)ÚCrossEncoderTrainingArguments)ÚSentenceEvaluatorÚSequentialEvaluator)ÚSentenceTransformerTrainer)Úis_datasets_availableÚis_training_available)ÚDatasetÚDatasetDictÚIterableDatasetc                  óª   ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	ˆ fd„Zd
d„Z	 	 	 	 dd„Zdd„Zdˆ fd„Zdd„Z	ˆ xZ
S )ÚCrossEncoderTraineruð  
    CrossEncoderTrainer is a simple but feature-complete training and eval loop for PyTorch
    based on the ðŸ¤— Transformers :class:`~transformers.Trainer`.

    This trainer integrates support for various :class:`transformers.TrainerCallback` subclasses, such as:

    - :class:`~transformers.integrations.WandbCallback` to automatically log training metrics to W&B if `wandb` is installed
    - :class:`~transformers.integrations.TensorBoardCallback` to log training metrics to TensorBoard if `tensorboard` is accessible.
    - :class:`~transformers.integrations.CodeCarbonCallback` to track the carbon emissions of your model during training if `codecarbon` is installed.

        - Note: These carbon emissions will be included in your automatically generated model card.

    See the Transformers `Callbacks <https://huggingface.co/docs/transformers/main/en/main_classes/callback>`_
    documentation for more information on the integrated callbacks and how to write your own callbacks.

    Args:
        model (:class:`~sentence_transformers.SentenceTransformer`, *optional*):
            The model to train, evaluate or use for predictions. If not provided, a `model_init` must be passed.
        args (:class:`~sentence_transformers.training_args.SentenceTransformerTrainingArguments`, *optional*):
            The arguments to tweak for training. Will default to a basic instance of
            :class:`~sentence_transformers.training_args.SentenceTransformerTrainingArguments` with the
            `output_dir` set to a directory named *tmp_trainer* in the current directory if not provided.
        train_dataset (Union[:class:`datasets.Dataset`, :class:`datasets.DatasetDict`, :class:`datasets.IterableDataset`, Dict[str, :class:`datasets.Dataset`]], *optional*):
            The dataset to use for training. Must have a format accepted by your loss function, see
            `Training Overview > Dataset Format <../../../docs/sentence_transformer/training_overview.html#dataset-format>`_.
        eval_dataset (Union[:class:`datasets.Dataset`, :class:`datasets.DatasetDict`, :class:`datasets.IterableDataset`, Dict[str, :class:`datasets.Dataset`]], *optional*):
            The dataset to use for evaluation. Must have a format accepted by your loss function, see
            `Training Overview > Dataset Format <../../../docs/sentence_transformer/training_overview.html#dataset-format>`_.
        loss (Optional[Union[:class:`torch.nn.Module`, Dict[str, :class:`torch.nn.Module`],            Callable[[:class:`~sentence_transformers.SentenceTransformer`], :class:`torch.nn.Module`],            Dict[str, Callable[[:class:`~sentence_transformers.SentenceTransformer`]]]], *optional*):
            The loss function to use for training. Can either be a loss class instance, a dictionary mapping
            dataset names to loss class instances, a function that returns a loss class instance given a model,
            or a dictionary mapping dataset names to functions that return a loss class instance given a model.
            In practice, the latter two are primarily used for hyper-parameter optimization. Will default to
            :class:`~sentence_transformers.losses.CoSENTLoss` if no ``loss`` is provided.
        evaluator (Union[:class:`~sentence_transformers.evaluation.SentenceEvaluator`,            List[:class:`~sentence_transformers.evaluation.SentenceEvaluator`]], *optional*):
            The evaluator instance for useful evaluation metrics during training. You can use an ``evaluator`` with
            or without an ``eval_dataset``, and vice versa. Generally, the metrics that an ``evaluator`` returns
            are more useful than the loss value returned from the ``eval_dataset``. A list of evaluators will be
            wrapped in a :class:`~sentence_transformers.evaluation.SequentialEvaluator` to run them sequentially.
        callbacks (List of [:class:`transformers.TrainerCallback`], *optional*):
            A list of callbacks to customize the training loop. Will add those to the list of default callbacks
            detailed in [here](callback).

            If you want to remove one of the default callbacks used, use the [`Trainer.remove_callback`] method.
        optimizers (`Tuple[:class:`torch.optim.Optimizer`, :class:`torch.optim.lr_scheduler.LambdaLR`]`, *optional*, defaults to `(None, None)`):
            A tuple containing the optimizer and the scheduler to use. Will default to an instance of :class:`torch.optim.AdamW`
            on your model and a scheduler given by :func:`transformers.get_linear_schedule_with_warmup` controlled by `args`.

    Important attributes:

        - **model** -- Always points to the core model. If using a transformers model, it will be a [`PreTrainedModel`]
          subclass.
        - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
          original model. This is the model that should be used for the forward pass. For example, under `DeepSpeed`,
          the inner model is wrapped in `DeepSpeed` and then again in `torch.nn.DistributedDataParallel`. If the inner
          model hasn't been wrapped, then `self.model_wrapped` is the same as `self.model`.
        - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
          data parallelism, this means some of the model layers are split on different GPUs).
        - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
          to `False` if model parallel or deepspeed is used, or if the default
          `TrainingArguments.place_model_on_device` is overridden to return `False` .
        - **is_in_train** -- Whether or not a model is currently running `train` (e.g. when `evaluate` is called while
          in `train`)

    c                ój
  •— t        «       st        d«      ‚|€(d}t        j                  d|› d�«       t	        |¬«      }nt        |t        «      st        d«      ‚|€%|	�|	| _        | j                  «       }n)t        d«      ‚|	�t        j                  d«       |	| _        |
�t        j                  d	«       t	        d
¬«      j                  «       }|j                  r;|j                  j                  s%|j                  j                  |j                  «       |€&t        |j                  t         «      r|j                  }|€t#        t%        |ddd¬«      ¬«      }t'        ddg||g«      D ]U  \  }}t        |t(        «      s2t        |t*        «      sŒ't-        d„ |j/                  «       D «       «      sŒHt        d|› d�«      ‚ t        |t*        «      rt        |t0        «      st1        |«      }t        |t*        «      rt        |t0        «      st1        |«      }| j                  rd n|||||€|€|nd|	|
|||dœ
}t3        t4        «      t3        d«      k\  r||d<   n||d<   |€*|€(|j6                  dk7  rt        d|j6                  › d�«      ‚t9        t:        | �z  d+i |¤Ž | j>                  dk(  rd | _        d| _         i | _!        |  |  |  t-        | jD                  jF                  D �cg c]  }t        |tH        «      ‘Œ c}«      r tJ        jL                  jO                  dd«       |€n| jP                  jR                  dk(  r+t        j                  d«       tU        | jP                  «      }n*t        j                  d «       tW        | jP                  «      }t        |t*        «      rÚ|jY                  «       D ��ci c]  \  }}|| j[                  ||«      “Œ c}}| _.        t'        ddg||g«      D ]�  \  }}|€Œ	t        |t*        «      st        d!|› d"�«      ‚t_        |ja                  «       «      t_        |ja                  «       «      z
  x}sŒ^t        d#|› d$tc        |«      › d%te        |«      dk(  rd&nd'› d(|› d)�	«      ‚ n| j[                  ||«      | _.        |�t        |tf        «      sti        |«      }|| _5        | jl                  �#| jo                  ||jp                  d¬*«      | _6        | j>                  �#| jo                  ||jp                  d¬*«      | _        | js                  |«       y c c}w c c}}w ),Nz¯To train a CrossEncoder model, you need to install the `accelerate` and `datasets` modules. You can do so with the `train` extra:
pip install -U "sentence-transformers[train]"Útmp_trainerz=No `CrossEncoderTrainingArguments` passed, using `output_dir=z`.)Ú
output_dirzQPlease use `CrossEncoderTrainingArguments` imported from `sentence_transformers`.z<`Trainer` requires either a `model` or `model_init` argumentz“`Trainer` requires either a `model` or `model_init` argument, but not both. `model_init` will overwrite your model when calling the `train` method.zÐ`compute_metrics` is currently not compatible with the CrossEncoderTrainer. Please use the `evaluator` argument instead for detailed evaluation metrics, or the `eval_dataset` argument for the evaluation loss.ÚunusedTÚpt)ÚpaddingÚ
truncationÚreturn_tensors)Útokenize_fnÚtrainÚevalc              3  ó<   K  — | ]  }t        |t        «      –— Œ y ­w)N)Ú
isinstancer   )Ú.0Úds     úi/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/sentence_transformers/cross_encoder/trainer.pyú	<genexpr>z/CrossEncoderTrainer.__init__.<locals>.<genexpr>¯   s   è ø€ Ò1kÐUV´*¸QÄ×2PÑ1kùs   ‚zACrossEncoderTrainer does not support an IterableDataset for the `zg_dataset`. Please convert the dataset to a `Dataset` or `DatasetDict` before passing it to the trainer.Údummy)
ÚmodelÚargsÚdata_collatorÚtrain_datasetÚeval_datasetÚ
model_initÚcompute_metricsÚ	callbacksÚ
optimizersÚpreprocess_logits_for_metricsz4.46.0Úprocessing_classÚ	tokenizerÚnoz%You have set `args.eval_strategy` to z¿, but you didn't provide an `eval_dataset` or an `evaluator`. Either provide an `eval_dataset` or an `evaluator` to `CrossEncoderTrainer`, or set `args.eval_strategy='no'` to skip evaluation.ÚWANDB_PROJECTzsentence-transformersé   zLNo `loss` passed, using `losses.BinaryCrossEntropyLoss` as a default option.zFNo `loss` passed, using `losses.CrossEntropyLoss` as a default option.z,If the provided `loss` is a dict, then the `z"_dataset` must be a `DatasetDict`.z:If the provided `loss` is a dict, then all keys from the `z;_dataset` dictionary must occur in `loss` also. Currently, z occurÚsÚ z in `z_dataset` but not in `loss`.)Údataset_name© ):r   ÚRuntimeErrorÚloggerÚinfor   r,   Ú
ValueErrorr7   Úcall_model_initÚwarningÚto_dictÚhub_model_idÚmodel_card_dataÚmodel_idÚset_model_idr=   r
   r   r   Úzipr   ÚdictÚanyÚvaluesr   Úparse_versionÚtransformers_versionÚeval_strategyÚsuperr   Ú__init__r6   Úcan_return_lossÚ_prompt_length_mappingÚcallback_handlerr9   r   ÚosÚenvironÚ
setdefaultr2   Ú
num_labelsr   r   ÚitemsÚprepare_lossÚlossÚsetÚkeysÚsortedÚlenr   r   Ú	evaluatorr5   Ú(maybe_add_prompts_or_dataset_name_columnÚpromptsÚadd_model_card_callback)Úselfr2   r3   r5   r6   rb   rg   r4   r=   r7   r8   r9   r:   r;   r"   Údefault_args_dictrC   ÚdatasetÚsuper_kwargsÚcallbackÚloss_fnÚmissingÚ	__class__s                         €r/   rX   zCrossEncoderTrainer.__init__e   s9  ø€ ô( %Ô&Üð@óð ð ˆ<Ø&ˆJÜ�K‰KÐWÐXbÐWcÐceÐfÔgÜ0¸JÔG‰DÜ˜DÔ"?Ô@ÜÐpÓqÐqàˆ=ØÐ%Ø",�”Ø×,Ñ,Ó.‘ä"Ð#aÓbÐbàÐ%Ü—‘ðMôð )ˆDŒOàÐ&Ü�N‰Nð'ôô :ÀXÔN×VÑVÓXÐð ×Ò U×%:Ñ%:×%CÒ%CØ×!Ñ!×.Ñ.¨t×/@Ñ/@ÔAàÐ¤¨E¯O©OÔ=TÔ!UØŸ™ˆIàÐ Ü4Ü# I°tÈÐ]aÔbôˆMô &)¨'°6Ð):¸]ÈLÐ<YÓ%Zò 	Ñ!ˆL˜'Ü˜'¤?Ô3Ü˜7¤DÕ)¬cÑ1kÐZa×ZhÑZhÓZjÔ1kÕ.kô !ØWÐXdÐWeð fsð sóð ð	ô �m¤TÔ*´:¸mÌ[Ô3YÜ'¨Ó6ˆMÜ�l¤DÔ)´*¸\Ì;Ô2WÜ& |Ó4ˆLð "Ÿ_š_‘T°%ØØ*Ø*Ø,8Ð,DÈ	ÐHY™LÐ_fØ$Ø.Ø"Ø$Ø-Jñ
ˆô Ô-Ó.´-ÀÓ2IÒIØ/8ˆLÐ+Ò,à(1ˆL˜Ñ%ð Ð IÐ$5¸$×:LÑ:LÐPTÒ:TÜØ7¸×8JÑ8JÐ7Kð LGð Góð ô 	Ô(¨$Ñ8ÑH¸<ÒHà×Ñ Ò'Ø $ˆDÔð  $ˆÔà&(ˆÔ#áÙÙäÀD×DYÑDY×DcÑDcÖd¸”
˜8¤]Õ3ÒdÔeÜ�J‰J×!Ñ! /Ð3JÔKàˆ<Ø�z‰z×$Ñ$¨Ò)Ü—‘ÐjÔkÜ-¨d¯j©jÓ9‘ä—‘ÐdÔeÜ'¨¯
©
Ó3�ä�dœDÔ!Øfj×fpÑfpÓfr×sÑMbÈ\Ð[b˜ t×'8Ñ'8¸À%Ó'HÑHÓsˆDŒIÜ),¨g°vÐ->ÀÐP\Ð@]Ó)^ò Ñ%�˜gØ�?ØÜ! '¬4Ô0Ü$ØFÀ|ÀnÐTvÐwóð ô " '§,¡,£.Ó1´C¸¿	¹	»Ó4DÑDÐD�7ÑDÜ$ØTÐUaÐTbð c&Ü&,¨W£oÐ%6°fÄCÈÃLÐTUÒDU¹SÐ[]Ð<^Ð^cÐdpÐcqð  rNðOóð ñð ×)Ñ)¨$°Ó6ˆDŒIð Ð ¬°IÔ?PÔ)QÜ+¨IÓ6ˆIØ"ˆŒà×ÑÐ)Ø!%×!NÑ!NØ˜tŸ|™|¸'ð "Oó "ˆDÔð ×ÑÐ(Ø $× MÑ MØ˜dŸl™l¸ð !Nó !ˆDÔð 	×$Ñ$Ð%6Õ7ùòS eùó ts   Ë'T*Î8T/c                ó¸   — t        |«      }| j                  |«       |j                  | j                  | j                  | j
                  | j                  | ¬«       y)ah  
        Add a callback responsible for automatically tracking data required for the automatic model card generation

        This method is called in the ``__init__`` method of the
        :class:`~sentence_transformers.trainer.SentenceTransformerTrainer` class.

        Args:
            default_args_dict (Dict[str, Any]): A dictionary of the default training arguments, so we can determine
                which arguments have been changed for the model card.

        .. note::

            This method can be overriden by subclassing the trainer to remove/customize this callback in custom uses cases
        )r2   ÚtrainerN)r   Úadd_callbackÚon_init_endr3   ÚstateÚcontrolr2   )rk   rl   Úmodel_card_callbacks      r/   rj   z+CrossEncoderTrainer.add_model_card_callback  sL   € ô  <Ð<MÓNÐØ×ÑÐ-Ô.Ø×'Ñ'¨¯	©	°4·:±:¸t¿|¹|ÐSW×S]ÑS]ÐgkÐ'Õló    c                ó`   — |j                  dd«      }t        |j                  «       «      }||fS )zPTurn the inputs from the dataloader into the separate model inputs & the labels.ÚlabelN)ÚpopÚlistrS   )rk   ÚinputsÚlabelsÚfeaturess       r/   Úcollect_featuresz$CrossEncoderTrainer.collect_features,  s/   € ð —‘˜G TÓ*ˆÜ˜Ÿ™›Ó(ˆØ˜ÐÐrz   c                óž   — ddl m}  ||| j                  j                  ¬«      }| j                  j	                  |j                  «       «       y )Nr   r   )Útrust_remote_code)Ú#sentence_transformers.cross_encoderr   r2   r„   Úload_state_dictÚ
state_dict)rk   Úcheckpoint_pathr   Úloaded_models       r/   Ú_load_from_checkpointz)CrossEncoderTrainer._load_from_checkpoint6  s6   € ÝDá# OÀtÇzÁz×GcÑGcÔdˆØ�
‰
×"Ñ" <×#:Ñ#:Ó#<Õ=rz   c                óè  •— 	 | j                   j                  x}rC|j                  dd«      d   }| j                  j                  j                  t        |«      «       | j                  }| j                  j                  | _        	 t        t        | �+  «       | j                  }|| _        || j                  _        S # t        $ r Y Œiw xY w# | j                  }|| _        || j                  _        w xY w)Nú-r@   éÿÿÿÿ)rw   Úbest_model_checkpointÚrsplitr2   rM   Úset_best_model_stepÚintÚ	ExceptionrW   r   Ú_load_best_model)rk   Ú
checkpointÚstepÚ
full_modelÚloaded_auto_modelrr   s        €r/   r“   z$CrossEncoderTrainer._load_best_model<  sÐ   ø€ ð	Ø!ŸZ™Z×=Ñ=Ð=ˆzÐ=Ø!×(Ñ(¨¨aÓ0°Ñ4�Ø—
‘
×*Ñ*×>Ñ>¼sÀ4»yÔIð —Z‘Zˆ
Ø—Z‘Z×%Ñ%ˆŒ
ð	1ÜÔ3°TÑKÓMà $§
¡
ÐØ#ˆDŒJØ0ˆD�J‰JÕøô ò 	Ùð	ûð !%§
¡
ÐØ#ˆDŒJØ0ˆD�J‰JÕús   ƒAB< ÂC Â<	CÃCÃ&C1c                 ó   — y)ac  
        Return whether the prompt length should be passed to the model's forward method.

        This is never the case for CrossEncoder models, as the prompt length is not used in the forward method,
        unlike with Sentence Transformers models, where it may be relevant to mask out the prompt tokens in the
        embedding pooling step.
        FrD   )rk   s    r/   Ú_include_prompt_lengthz*CrossEncoderTrainer._include_prompt_lengthO  s   € ð rz   )NNNNNNNNNNN)NNN)r2   zCrossEncoder | Noner3   r   r5   ú1Dataset | DatasetDict | dict[str, Dataset] | Noner6   rš   rb   zŠnn.Module | dict[str, nn.Module] | Callable[[CrossEncoder], torch.nn.Module] | dict[str, Callable[[CrossEncoder], torch.nn.Module]] | Nonerg   z2SentenceEvaluator | list[SentenceEvaluator] | Noner4   zDataCollator | Noner=   z)PreTrainedTokenizerBase | Callable | Noner7   z!Callable[[], CrossEncoder] | Noner8   z'Callable[[EvalPrediction], dict] | Noner9   zlist[TrainerCallback] | Noner:   z?tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]r;   z;Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | NoneÚreturnÚNone)rl   zdict[str, Any]r›   rœ   )r   zdict[str, torch.Tensor | Any]r›   z9tuple[list[dict[str, torch.Tensor]], torch.Tensor | None])rˆ   Ústrr›   rœ   )r›   rœ   )r›   Úbool)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rX   rj   r‚   rŠ   r“   r™   Ú__classcell__)rr   s   @r/   r   r      s  ø„ ñCðN &*Ø.2ØKOØJNð
 ØHLØ-1Ø?CØ8<ØCGØ26ØVbØeið%q8à"ðq8ð ,ðq8ð Ið	q8ð
 Hðq8ððq8ð Fðq8ð +ðq8ð =ðq8ð 6ðq8ð Aðq8ð  0ð!q8ð" Tð#q8ð$ (cð%q8ð& 
õ'q8ófmð( Ø3ð à	Bó ó>õ1÷&rz   r   )3Ú
__future__r   Úloggingr\   Ú	functoolsr   Útypingr   r   ÚtorchÚpackaging.versionr   rT   r   Útransformersr	   r
   r   r   rU   Útransformers.data.data_collatorr   Útransformers.integrationsr   r…   r   Ú1sentence_transformers.cross_encoder.data_collatorr   Ú*sentence_transformers.cross_encoder.lossesr   r   Ú.sentence_transformers.cross_encoder.model_cardr   Ú1sentence_transformers.cross_encoder.training_argsr   Ú sentence_transformers.evaluationr   r   Úsentence_transformers.trainerr   Úsentence_transformers.utilr   r   Údatasetsr   r   r   Ú	getLoggerrŸ   rF   r   rD   rz   r/   ú<module>r¶      sq   ðÝ "ã Û 	Ý ß  ã Ý 4Ý ß QÑ QÝ <Ý 8Ý 3å <Ý Vß _Ý XÝ [ß SÝ Dß SáÔß>Ñ>à	ˆ×	Ñ	˜8Ó	$€ôxÐ4õ xrz   