CrossEncoder
CrossEncoder
For an introduction to Cross-Encoders, see Cross-Encoders.
- class sentence_transformers.cross_encoder.CrossEncoder(model_name: str, num_labels: int | None = None, max_length: int | None = None, device: str | None = None, automodel_args: dict | None = None, tokenizer_args: dict | None = None, config_args: dict | None = None, cache_dir: str | None = None, trust_remote_code: bool = False, revision: str | None = None, local_files_only: bool = False, default_activation_function=None, classifier_dropout: float | None = None)[source]
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.
- Parameters:
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.
- fit(train_dataloader: ~torch.utils.data.dataloader.DataLoader, evaluator: ~sentence_transformers.evaluation.SentenceEvaluator.SentenceEvaluator | None = None, epochs: int = 1, loss_fct=None, activation_fct=Identity(), scheduler: str = 'WarmupLinear', warmup_steps: int = 10000, optimizer_class: type[~torch.optim.optimizer.Optimizer] = <class 'torch.optim.adamw.AdamW'>, optimizer_params: dict[str, object] = {'lr': 2e-05}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str | None = None, save_best_model: bool = True, max_grad_norm: float = 1, use_amp: bool = False, callback: ~typing.Callable[[float, int, int], None] | None = None, show_progress_bar: bool = True) None [source]
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.
- Parameters:
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.
- predict(sentences: tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[False] = True, convert_to_tensor: Literal[False] = False) Tensor [source]
- predict(sentences: list[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[True] = True, convert_to_tensor: Literal[False] = False) ndarray
- predict(sentences: list[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: bool = True, convert_to_tensor: Literal[True] = False) Tensor
- predict(sentences: list[tuple[str, str]] | list[list[str]], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[False] = True, convert_to_tensor: Literal[False] = False) list[Tensor]
Performs predictions with the CrossEncoder on the given sentence pairs.
- Parameters:
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:
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.
- Return type:
Union[List[float], np.ndarray, torch.Tensor]
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)
- push_to_hub(repo_id: str, use_temp_dir: bool | None = None, commit_message: str | None = None, private: bool | None = None, token: bool | str | None = None, max_shard_size: int | str | None = '5GB', create_pr: bool = False, safe_serialization: bool = True, revision: str = None, commit_description: str = None, tags: List[str] | None = None, **deprecated_kwargs) str
Upload the {object_files} to the 🤗 Model Hub.
- Parameters:
repo_id (str) – The name of the repository you want to push your {object} to. It should contain your organization name when pushing to a given organization.
use_temp_dir (bool, optional) – Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub. Will default to True if there is no directory named like repo_id, False otherwise.
commit_message (str, optional) – Message to commit while pushing. Will default to “Upload {object}”.
private (bool, optional) – Whether or not the repository created should be private.
token (bool or str, optional) – The token to use as HTTP bearer authorization for remote files. If True, will use the token generated when running huggingface-cli login (stored in ~/.huggingface). Will default to True if repo_url is not specified.
max_shard_size (int or str, optional, defaults to “5GB”) – Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like “5MB”). We default it to “5GB” so that users can easily load models on free-tier Google Colab instances without any CPU OOM issues.
create_pr (bool, optional, defaults to False) – Whether or not to create a PR with the uploaded files or directly commit.
safe_serialization (bool, optional, defaults to True) – Whether or not to convert the model weights in safetensors format for safer serialization.
revision (str, optional) – Branch to push the uploaded files to.
commit_description (str, optional) – The description of the commit that will be created
tags (List[str], optional) – List of tags to push on the Hub.
Examples:
```python from transformers import {object_class}
{object} = {object_class}.from_pretrained(“google-bert/bert-base-cased”)
# Push the {object} to your namespace with the name “my-finetuned-bert”. {object}.push_to_hub(“my-finetuned-bert”)
# Push the {object} to an organization with the name “my-finetuned-bert”. {object}.push_to_hub(“huggingface/my-finetuned-bert”) ```
- rank(query: str, documents: list[str], top_k: int | None = None, return_documents: bool = False, batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False) list[dict[Literal['corpus_id', 'score', 'text'], int | float | str]] [source]
Performs ranking with the CrossEncoder on the given query and documents. Returns a sorted list with the document indices and scores.
- Parameters:
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:
A sorted list with the “corpus_id”, “score”, and optionally “text” of the documents.
- Return type:
List[Dict[Literal[“corpus_id”, “score”, “text”], Union[int, float, str]]]
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."}]
Training Inputs
- class sentence_transformers.readers.InputExample(guid: str = '', texts: list[str] | None = None, label: int | float = 0)[source]
Structure for one input example with texts, the label and a unique id
Creates one InputExample with the given texts, guid and label
- Parameters:
guid – id for the example
texts – the texts for the example.
label – the label for the example