opensi·si

This folder contains scripts that demonstrate how to train SentenceTransformers for Information Retrieval. As a simple example, we will use the Quora Duplicate Questions…

Quora Duplicate Questions

This folder contains scripts that demonstrate how to train SentenceTransformers for Information Retrieval. As a simple example, we will use the Quora Duplicate Questions dataset. It contains over 500,000 sentences with over 400,000 pairwise annotations whether two questions are a duplicate or not.

Models trained on this dataset can be used for mining duplicate questions, i.e., given a large set of sentences (in this case questions), identify all pairs that are duplicates. See Paraphrase Mining for an example how to use sentence transformers to mine for duplicate questions / paraphrases. This approach can be scaled to hundred thousands of sentences.

Training

Contrastive Loss

For the complete training example, see training_online_contrastive_loss.py.

The loss can be used like this:

from datasets import load_dataset
from sentence_transformers.sentence_transformer.losses import OnlineContrastiveLoss

train_dataset = load_dataset("sentence-transformers/quora-duplicates", "pair-class", split="train")
# => Dataset({
#     features: ['sentence1', 'sentence2', 'label'],
#     num_rows: 404290
# })
print(train_dataset[0])
# => {'sentence1': 'What is the step by step guide to invest in share market in india?', 'sentence2': 'What is the step by step guide to invest in share market?', 'label': 0}
train_loss = OnlineContrastiveLoss(model=model, margin=0.5)

MultipleNegativesRankingLoss

For the complete example, see training_multiple_negatives_ranking_loss.py.

Using the loss is easy and does not require tuning of any hyperparameters:

from datasets import load_dataset
from sentence_transformers.sentence_transformer.losses import MultipleNegativesRankingLoss

train_dataset = load_dataset("sentence-transformers/quora-duplicates", "pair", split="train")
# => Dataset({
#     features: ['anchor', 'positive'],
#     num_rows: 149263
# })
print(train_dataset[0])
# => {'anchor': 'Astrology: I am a Capricorn Sun Cap moon and cap rising...what does that say about me?', 'positive': "I'm a triple Capricorn (Sun, Moon and ascendant in Capricorn) What does this say about me?"}
train_loss = MultipleNegativesRankingLoss(model)

As 'is_duplicate' is a symmetric relation, we can use not just (anchor, positive) but also (positive, anchor) to our training sample set:

from datasets import concatenate_datasets

train_dataset = concatenate_datasets([
    train_dataset,
    train_dataset.rename_columns({"anchor": "positive", "positive": "anchor"})
])
# Dataset({
#     features: ['anchor', 'positive'],
#     num_rows: 298526
# })

Multi-Task-Learning

In training_multi_task_learning.py I demonstrate how we can train the network with both losses. The essential code is to define both losses and to pass it to the fit method.

코드 (41줄)
from datasets import load_dataset
from sentence_transformers.sentence_transformer.losses import ContrastiveLoss, MultipleNegativesRankingLoss
from sentence_transformers import SentenceTransformerTrainer, SentenceTransformer

model_name = "sentence-transformers/stsb-distilbert-base"
# Loading in fp32 is preferred for training if your memory can handle it
model = SentenceTransformer(model_name, model_kwargs={"torch_dtype": "float32"})

# https://huggingface.co/datasets/sentence-transformers/quora-duplicates
mnrl_dataset = load_dataset(
    "sentence-transformers/quora-duplicates", "triplet", split="train"
)  # The "pair" subset also works
mnrl_train_dataset = mnrl_dataset.select(range(100000))
mnrl_eval_dataset = mnrl_dataset.select(range(100000, 101000))

mnrl_train_loss = MultipleNegativesRankingLoss(model=model)

# https://huggingface.co/datasets/sentence-transformers/quora-duplicates
cl_dataset = load_dataset("sentence-transformers/quora-duplicates", "pair-class", split="train")
cl_train_dataset = cl_dataset.select(range(100000))
cl_eval_dataset = cl_dataset.select(range(100000, 101000))

cl_train_loss = ContrastiveLoss(model=model, margin=0.5)

# Create the trainer & start training
trainer = SentenceTransformerTrainer(
    model=model,
    train_dataset={
        "mnrl": mnrl_train_dataset,
        "cl": cl_train_dataset,
    },
    eval_dataset={
        "mnrl": mnrl_eval_dataset,
        "cl": cl_eval_dataset,
    },
    loss={
        "mnrl": mnrl_train_loss,
        "cl": cl_train_loss,
    },
)
trainer.train()

Pretrained Models

Currently the following models trained on Quora Duplicate Questions are available:

  • sentence-transformers/distilbert-base-nli-stsb-quora-ranking: We extended the sentence-transformers/distilbert-base-nli-stsb-mean-tokens model and trained it with OnlineContrastiveLoss and with MultipleNegativesRankingLoss on the Quora Duplicate questions dataset. For the code, see training_multi_task_learning.py
  • sentence-transformers/distilbert-multilingual-nli-stsb-quora-ranking: Extension of sentence-transformers/distilbert-base-nli-stsb-quora-ranking to be multi-lingual. Trained on parallel data for 50 languages.

You can load & use pre-trained models like this:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/distilbert-base-nli-stsb-quora-ranking")

Source and license

Source: Sentence Transformers documentation, adapted for this site. Licensing and attribution follow the terms of the upstream project.