Source code for lightning_ir.cross_encoder.cross_encoder_module

 1"""
 2Module module for cross-encoder models.
 3
 4This module defines the Lightning IR module class used to implement cross-encoder models.
 5"""
 6
 7from typing import Any, List, Mapping, Sequence, Tuple
 8
 9import torch
10
11from ..base.module import LightningIRModule
12from ..data import RankBatch, SearchBatch, TrainBatch
13from ..loss.base import LossFunction, ScoringLossFunction
14from .cross_encoder_config import CrossEncoderConfig
15from .cross_encoder_model import CrossEncoderModel, CrossEncoderOutput
16from .cross_encoder_tokenizer import CrossEncoderTokenizer
17
18
[docs] 19class CrossEncoderModule(LightningIRModule):
[docs] 20 def __init__( 21 self, 22 model_name_or_path: str | None = None, 23 config: CrossEncoderConfig | None = None, 24 model: CrossEncoderModel | None = None, 25 loss_functions: Sequence[LossFunction | Tuple[LossFunction, float]] | None = None, 26 evaluation_metrics: Sequence[str] | None = None, 27 model_kwargs: Mapping[str, Any] | None = None, 28 ): 29 """:class:`.LightningIRModule` for cross-encoder models. It contains a :class:`.CrossEncoderModel` and a 30 :class:`.CrossEncoderTokenizer` and implements the training, validation, and testing steps for the model. 31 32 .. _ir-measures: https://ir-measur.es/en/latest/index.html 33 34 Args: 35 model_name_or_path (str | None): Name or path of backbone model or fine-tuned Lightning IR model. 36 Defaults to None. 37 config (CrossEncoderConfig | None): CrossEncoderConfig to apply when loading from backbone model. 38 Defaults to None. 39 model (CrossEncoderModel | None): Already instantiated CrossEncoderModel. Defaults to None. 40 loss_functions (Sequence[LossFunction | Tuple[LossFunction, float]] | None): 41 Loss functions to apply during fine-tuning, optional loss weights can be provided per loss function. 42 Defaults to None. 43 evaluation_metrics (Sequence[str] | None): Metrics corresponding to ir-measures_ measure strings to apply 44 during validation or testing. Defaults to None. 45 model_kwargs (Mapping[str, Any] | None): Additional keyword arguments to pass to `from_pretrained` when 46 loading a model. Defaults to None. 47 """ 48 super().__init__(model_name_or_path, config, model, loss_functions, evaluation_metrics, model_kwargs) 49 self.model: CrossEncoderModel 50 self.config: CrossEncoderConfig 51 self.tokenizer: CrossEncoderTokenizer
52
[docs] 53 def forward(self, batch: RankBatch | TrainBatch | SearchBatch) -> CrossEncoderOutput: 54 """Runs a forward pass of the model on a batch of data and returns the contextualized embeddings from the 55 backbone model as well as the relevance scores. 56 57 Args: 58 batch (RankBatch | TrainBatch | SearchBatch): Batch of data to run the forward pass on. 59 Returns: 60 CrossEncoderOutput: Output of the model. 61 Raises: 62 ValueError: If the batch is a SearchBatch. 63 """ 64 if isinstance(batch, SearchBatch): 65 raise ValueError("Searching is not available for cross-encoders") 66 queries = batch.queries 67 docs = [d for docs in batch.docs for d in docs] 68 num_docs = [len(docs) for docs in batch.docs] 69 encoding = self.prepare_input(queries, docs, num_docs) 70 output = self.model.forward(encoding["encoding"]) 71 return output
72 73 def _compute_losses(self, batch: TrainBatch, output: CrossEncoderOutput) -> List[torch.Tensor]: 74 """Computes the losses for a training batch.""" 75 if self.loss_functions is None: 76 raise ValueError("loss_functions must be set in the module") 77 78 output.scores = output.scores.view(len(batch.query_ids), -1) 79 batch.targets = batch.targets.view(*output.scores.shape, -1) 80 81 losses = [] 82 for loss_function, _ in self.loss_functions: 83 if not isinstance(loss_function, ScoringLossFunction): 84 raise RuntimeError(f"Loss function {loss_function} is not a scoring loss function") 85 losses.append(loss_function.compute_loss(output, batch)) 86 return losses