Create train_script.py
Browse files- train_script.py +142 -0
train_script.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
import logging
|
3 |
+
from datasets import load_dataset, Dataset
|
4 |
+
from sentence_transformers import (
|
5 |
+
SentenceTransformer,
|
6 |
+
SentenceTransformerTrainer,
|
7 |
+
SentenceTransformerTrainingArguments,
|
8 |
+
SentenceTransformerModelCardData,
|
9 |
+
)
|
10 |
+
from typing import Any, Dict, Iterable
|
11 |
+
import torch
|
12 |
+
from torch import nn
|
13 |
+
from sentence_transformers.losses import MultipleNegativesRankingLoss, MultipleNegativesSymmetricRankingLoss
|
14 |
+
from sentence_transformers import util
|
15 |
+
from sentence_transformers.training_args import BatchSamplers
|
16 |
+
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
17 |
+
|
18 |
+
|
19 |
+
logging.basicConfig(
|
20 |
+
format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO
|
21 |
+
)
|
22 |
+
|
23 |
+
# 1. Load a model to finetune with 2. (Optional) model card data
|
24 |
+
model = SentenceTransformer(
|
25 |
+
"microsoft/mpnet-base",
|
26 |
+
model_card_data=SentenceTransformerModelCardData(
|
27 |
+
language="en",
|
28 |
+
license="apache-2.0",
|
29 |
+
model_name="MPNet base trained on Natural Questions pairs",
|
30 |
+
),
|
31 |
+
)
|
32 |
+
model_name = "mpnet-base-natural-questions-mnsrl"
|
33 |
+
|
34 |
+
# 3. Load a dataset to finetune on
|
35 |
+
dataset = load_dataset("sentence-transformers/natural-questions", split="train")
|
36 |
+
dataset = dataset.add_column("id", range(len(dataset)))
|
37 |
+
train_dataset: Dataset = dataset.select(range(90_000))
|
38 |
+
eval_dataset: Dataset = dataset.select(range(90_000, len(dataset)))
|
39 |
+
|
40 |
+
# 4. Define a loss function
|
41 |
+
class ImprovedContrastiveLoss(nn.Module):
|
42 |
+
def __init__(self, model: SentenceTransformer, temperature: float = 0.01):
|
43 |
+
super(ImprovedContrastiveLoss, self).__init__()
|
44 |
+
self.model = model
|
45 |
+
self.temperature = temperature
|
46 |
+
|
47 |
+
def forward(self, sentence_features: Iterable[Dict[str, torch.Tensor]], labels: torch.Tensor = None) -> torch.Tensor:
|
48 |
+
# Get the embeddings for each sentence in the batch
|
49 |
+
embeddings = [self.model(sentence_feature)['sentence_embedding'] for sentence_feature in sentence_features]
|
50 |
+
query_embeddings = embeddings[0]
|
51 |
+
doc_embeddings = embeddings[1]
|
52 |
+
|
53 |
+
# Compute similarity scores
|
54 |
+
similarity_q_d = util.cos_sim(query_embeddings, doc_embeddings)
|
55 |
+
similarity_q_q = util.cos_sim(query_embeddings, query_embeddings)
|
56 |
+
similarity_d_d = util.cos_sim(doc_embeddings, doc_embeddings)
|
57 |
+
|
58 |
+
# Move the similarity range from [-1, 1] to [-2, 0] to avoid overflow
|
59 |
+
similarity_q_d = similarity_q_d - 1
|
60 |
+
similarity_q_q = similarity_q_q - 1
|
61 |
+
similarity_d_d = similarity_d_d - 1
|
62 |
+
|
63 |
+
# Compute the partition function
|
64 |
+
exp_sim_q_d = torch.exp(similarity_q_d / self.temperature)
|
65 |
+
exp_sim_q_q = torch.exp(similarity_q_q / self.temperature)
|
66 |
+
exp_sim_d_d = torch.exp(similarity_d_d / self.temperature)
|
67 |
+
|
68 |
+
# Ensure the diagonal is not considered in negative samples
|
69 |
+
mask = torch.eye(similarity_q_d.size(0), device=similarity_q_d.device).bool()
|
70 |
+
exp_sim_q_q = exp_sim_q_q.masked_fill(mask, 0)
|
71 |
+
exp_sim_d_d = exp_sim_d_d.masked_fill(mask, 0)
|
72 |
+
|
73 |
+
partition_function = exp_sim_q_d.sum(dim=1) + exp_sim_q_d.sum(dim=0) + exp_sim_q_q.sum(dim=1) + exp_sim_d_d.sum(dim=0)
|
74 |
+
|
75 |
+
# Compute the loss
|
76 |
+
loss = -torch.log(exp_sim_q_d.diag() / partition_function).mean()
|
77 |
+
return loss
|
78 |
+
|
79 |
+
def get_config_dict(self) -> Dict[str, Any]:
|
80 |
+
return {"temperature": self.temperature}
|
81 |
+
|
82 |
+
# loss = ImprovedContrastiveLoss(model)
|
83 |
+
loss = MultipleNegativesSymmetricRankingLoss(model)
|
84 |
+
|
85 |
+
|
86 |
+
# 5. (Optional) Specify training arguments
|
87 |
+
args = SentenceTransformerTrainingArguments(
|
88 |
+
# Required parameter:
|
89 |
+
output_dir=f"models/{model_name}",
|
90 |
+
# Optional training parameters:
|
91 |
+
num_train_epochs=1,
|
92 |
+
per_device_train_batch_size=32,
|
93 |
+
per_device_eval_batch_size=32,
|
94 |
+
learning_rate=2e-5,
|
95 |
+
warmup_ratio=0.1,
|
96 |
+
fp16=False, # Set to False if you get an error that your GPU can't run on FP16
|
97 |
+
bf16=True, # Set to True if you have a GPU that supports BF16
|
98 |
+
batch_sampler=BatchSamplers.NO_DUPLICATES, # MultipleNegativesRankingLoss benefits from no duplicate samples in a batch
|
99 |
+
# Optional tracking/debugging parameters:
|
100 |
+
eval_strategy="steps",
|
101 |
+
eval_steps=100,
|
102 |
+
save_strategy="steps",
|
103 |
+
save_steps=100,
|
104 |
+
save_total_limit=2,
|
105 |
+
logging_steps=100,
|
106 |
+
logging_first_step=True,
|
107 |
+
run_name=model_name, # Will be used in W&B if `wandb` is installed
|
108 |
+
)
|
109 |
+
|
110 |
+
# 6. (Optional) Create an evaluator & evaluate the base model
|
111 |
+
# The full corpus, but only the evaluation queries
|
112 |
+
queries = dict(zip(eval_dataset["id"], eval_dataset["query"]))
|
113 |
+
corpus = {cid: dataset[cid]["answer"] for cid in range(20_000)} | {cid: dataset[cid]["answer"] for cid in eval_dataset["id"]}
|
114 |
+
relevant_docs = {qid: {qid} for qid in eval_dataset["id"]}
|
115 |
+
dev_evaluator = InformationRetrievalEvaluator(
|
116 |
+
corpus=corpus,
|
117 |
+
queries=queries,
|
118 |
+
relevant_docs=relevant_docs,
|
119 |
+
show_progress_bar=True,
|
120 |
+
name="natural-questions-dev",
|
121 |
+
)
|
122 |
+
dev_evaluator(model)
|
123 |
+
|
124 |
+
# 7. Create a trainer & train
|
125 |
+
trainer = SentenceTransformerTrainer(
|
126 |
+
model=model,
|
127 |
+
args=args,
|
128 |
+
train_dataset=train_dataset.remove_columns("id"),
|
129 |
+
eval_dataset=eval_dataset.remove_columns("id"),
|
130 |
+
loss=loss,
|
131 |
+
evaluator=dev_evaluator,
|
132 |
+
)
|
133 |
+
trainer.train()
|
134 |
+
|
135 |
+
# (Optional) Evaluate the trained model on the evaluator after training
|
136 |
+
dev_evaluator(model)
|
137 |
+
|
138 |
+
# 8. Save the trained model
|
139 |
+
model.save_pretrained(f"models/{model_name}/final")
|
140 |
+
|
141 |
+
# 9. (Optional) Push it to the Hugging Face Hub
|
142 |
+
model.push_to_hub(f"{model_name}")
|