tomaarsen HF staff commited on
Commit
7417313
·
verified ·
1 Parent(s): 5edbc99

Create train.py

Browse files
Files changed (1) hide show
  1. train.py +216 -0
train.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import logging
3
+ from datasets import load_dataset, Dataset, DatasetDict
4
+ from sentence_transformers import (
5
+ SentenceTransformer,
6
+ SentenceTransformerTrainer,
7
+ SentenceTransformerTrainingArguments,
8
+ SentenceTransformerModelCardData,
9
+ )
10
+ from sentence_transformers.losses import MatryoshkaLoss, MultipleNegativesRankingLoss
11
+ from sentence_transformers.training_args import BatchSamplers, MultiDatasetBatchSamplers
12
+ from sentence_transformers.evaluation import NanoBEIREvaluator
13
+ from sentence_transformers.models.StaticEmbedding import StaticEmbedding
14
+
15
+ from transformers import AutoTokenizer
16
+
17
+ logging.basicConfig(
18
+ format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO
19
+ )
20
+ random.seed(12)
21
+
22
+
23
+ def main():
24
+ # 1. Load a model to finetune with 2. (Optional) model card data
25
+ static_embedding = StaticEmbedding(AutoTokenizer.from_pretrained("google-bert/bert-base-uncased"), embedding_dim=1024)
26
+ model = SentenceTransformer(
27
+ modules=[static_embedding],
28
+ model_card_data=SentenceTransformerModelCardData(
29
+ language="en",
30
+ license="apache-2.0",
31
+ model_name="Static Embeddings with BERT uncased tokenizer finetuned on various datasets",
32
+ ),
33
+ )
34
+
35
+ # 3. Set up training & evaluation datasets - each dataset is trained with MNRL (with MRL)
36
+ print("Loading gooaq dataset...")
37
+ gooaq_dataset = load_dataset("sentence-transformers/gooaq", split="train")
38
+ gooaq_dataset_dict = gooaq_dataset.train_test_split(test_size=10_000, seed=12)
39
+ gooaq_train_dataset: Dataset = gooaq_dataset_dict["train"]
40
+ gooaq_eval_dataset: Dataset = gooaq_dataset_dict["test"]
41
+ print("Loaded gooaq dataset.")
42
+
43
+ print("Loading msmarco dataset...")
44
+ msmarco_dataset = load_dataset("sentence-transformers/msmarco-co-condenser-margin-mse-sym-mnrl-mean-v1", "triplet", split="train")
45
+ msmarco_dataset_dict = msmarco_dataset.train_test_split(test_size=10_000, seed=12)
46
+ msmarco_train_dataset: Dataset = msmarco_dataset_dict["train"]
47
+ msmarco_eval_dataset: Dataset = msmarco_dataset_dict["test"]
48
+ print("Loaded msmarco dataset.")
49
+
50
+ print("Loading squad dataset...")
51
+ squad_dataset = load_dataset("sentence-transformers/squad", split="train")
52
+ squad_dataset_dict = squad_dataset.train_test_split(test_size=10_000, seed=12)
53
+ squad_train_dataset: Dataset = squad_dataset_dict["train"]
54
+ squad_eval_dataset: Dataset = squad_dataset_dict["test"]
55
+ print("Loaded squad dataset.")
56
+
57
+ print("Loading s2orc dataset...")
58
+ s2orc_dataset = load_dataset("sentence-transformers/s2orc", "title-abstract-pair", split="train[:100000]")
59
+ s2orc_dataset_dict = s2orc_dataset.train_test_split(test_size=10_000, seed=12)
60
+ s2orc_train_dataset: Dataset = s2orc_dataset_dict["train"]
61
+ s2orc_eval_dataset: Dataset = s2orc_dataset_dict["test"]
62
+ print("Loaded s2orc dataset.")
63
+
64
+ print("Loading allnli dataset...")
65
+ allnli_train_dataset = load_dataset("sentence-transformers/all-nli", "triplet", split="train")
66
+ allnli_eval_dataset = load_dataset("sentence-transformers/all-nli", "triplet", split="dev")
67
+ print("Loaded allnli dataset.")
68
+
69
+ print("Loading paq dataset...")
70
+ paq_dataset = load_dataset("sentence-transformers/paq", split="train")
71
+ paq_dataset_dict = paq_dataset.train_test_split(test_size=10_000, seed=12)
72
+ paq_train_dataset: Dataset = paq_dataset_dict["train"]
73
+ paq_eval_dataset: Dataset = paq_dataset_dict["test"]
74
+ print("Loaded paq dataset.")
75
+
76
+ print("Loading trivia_qa dataset...")
77
+ trivia_qa = load_dataset("sentence-transformers/trivia-qa", split="train")
78
+ trivia_qa_dataset_dict = trivia_qa.train_test_split(test_size=5_000, seed=12)
79
+ trivia_qa_train_dataset: Dataset = trivia_qa_dataset_dict["train"]
80
+ trivia_qa_eval_dataset: Dataset = trivia_qa_dataset_dict["test"]
81
+ print("Loaded trivia_qa dataset.")
82
+
83
+ print("Loading msmarco_10m dataset...")
84
+ msmarco_10m_dataset = load_dataset("bclavie/msmarco-10m-triplets", split="train")
85
+ msmarco_10m_dataset_dict = msmarco_10m_dataset.train_test_split(test_size=10_000, seed=12)
86
+ msmarco_10m_train_dataset: Dataset = msmarco_10m_dataset_dict["train"]
87
+ msmarco_10m_eval_dataset: Dataset = msmarco_10m_dataset_dict["test"]
88
+ print("Loaded msmarco_10m dataset.")
89
+
90
+ print("Loading swim_ir dataset...")
91
+ swim_ir_dataset = load_dataset("nthakur/swim-ir-monolingual", "en", split="train").select_columns(["query", "text"])
92
+ swim_ir_dataset_dict = swim_ir_dataset.train_test_split(test_size=10_000, seed=12)
93
+ swim_ir_train_dataset: Dataset = swim_ir_dataset_dict["train"]
94
+ swim_ir_eval_dataset: Dataset = swim_ir_dataset_dict["test"]
95
+ print("Loaded swim_ir dataset.")
96
+
97
+ # NOTE: 20 negatives
98
+ print("Loading pubmedqa dataset...")
99
+ pubmedqa_dataset = load_dataset("sentence-transformers/pubmedqa", "triplet-20", split="train")
100
+ pubmedqa_dataset_dict = pubmedqa_dataset.train_test_split(test_size=100, seed=12)
101
+ pubmedqa_train_dataset: Dataset = pubmedqa_dataset_dict["train"]
102
+ pubmedqa_eval_dataset: Dataset = pubmedqa_dataset_dict["test"]
103
+ print("Loaded pubmedqa dataset.")
104
+
105
+ # NOTE: A lot of overlap with anchor/positives
106
+ print("Loading miracl dataset...")
107
+ miracl_dataset = load_dataset("sentence-transformers/miracl", "en-triplet-all", split="train")
108
+ miracl_dataset_dict = miracl_dataset.train_test_split(test_size=10_000, seed=12)
109
+ miracl_train_dataset: Dataset = miracl_dataset_dict["train"]
110
+ miracl_eval_dataset: Dataset = miracl_dataset_dict["test"]
111
+ print("Loaded miracl dataset.")
112
+
113
+ # NOTE: A lot of overlap with anchor/positives
114
+ print("Loading mldr dataset...")
115
+ mldr_dataset = load_dataset("sentence-transformers/mldr", "en-triplet-all", split="train")
116
+ mldr_dataset_dict = mldr_dataset.train_test_split(test_size=10_000, seed=12)
117
+ mldr_train_dataset: Dataset = mldr_dataset_dict["train"]
118
+ mldr_eval_dataset: Dataset = mldr_dataset_dict["test"]
119
+ print("Loaded mldr dataset.")
120
+
121
+ # NOTE: A lot of overlap with anchor/positives
122
+ print("Loading mr_tydi dataset...")
123
+ mr_tydi_dataset = load_dataset("sentence-transformers/mr-tydi", "en-triplet-all", split="train")
124
+ mr_tydi_dataset_dict = mr_tydi_dataset.train_test_split(test_size=10_000, seed=12)
125
+ mr_tydi_train_dataset: Dataset = mr_tydi_dataset_dict["train"]
126
+ mr_tydi_eval_dataset: Dataset = mr_tydi_dataset_dict["test"]
127
+ print("Loaded mr_tydi dataset.")
128
+
129
+ train_dataset = DatasetDict({
130
+ "gooaq": gooaq_train_dataset,
131
+ "msmarco": msmarco_train_dataset,
132
+ "squad": squad_train_dataset,
133
+ "s2orc": s2orc_train_dataset,
134
+ "allnli": allnli_train_dataset,
135
+ "paq": paq_train_dataset,
136
+ "trivia_qa": trivia_qa_train_dataset,
137
+ "msmarco_10m": msmarco_10m_train_dataset,
138
+ "swim_ir": swim_ir_train_dataset,
139
+ "pubmedqa": pubmedqa_train_dataset,
140
+ "miracl": miracl_train_dataset,
141
+ "mldr": mldr_train_dataset,
142
+ "mr_tydi": mr_tydi_train_dataset,
143
+ })
144
+ eval_dataset = {
145
+ "gooaq": gooaq_eval_dataset,
146
+ "msmarco": msmarco_eval_dataset,
147
+ "squad": squad_eval_dataset,
148
+ "s2orc": s2orc_eval_dataset,
149
+ "allnli": allnli_eval_dataset,
150
+ "paq": paq_eval_dataset,
151
+ "trivia_qa": trivia_qa_eval_dataset,
152
+ "msmarco_10m": msmarco_10m_eval_dataset,
153
+ "swim_ir": swim_ir_eval_dataset,
154
+ "pubmedqa": pubmedqa_eval_dataset,
155
+ "miracl": miracl_eval_dataset,
156
+ "mldr": mldr_eval_dataset,
157
+ "mr_tydi": mr_tydi_eval_dataset,
158
+ }
159
+ print(train_dataset)
160
+
161
+ # 4. Define a loss function
162
+ loss = MultipleNegativesRankingLoss(model)
163
+ loss = MatryoshkaLoss(model, loss, matryoshka_dims=[32, 64, 128, 256, 512, 1024])
164
+
165
+ # 5. (Optional) Specify training arguments
166
+ run_name = "static-retrieval-mrl-en-v1"
167
+ args = SentenceTransformerTrainingArguments(
168
+ # Required parameter:
169
+ output_dir=f"models/{run_name}",
170
+ # Optional training parameters:
171
+ num_train_epochs=1,
172
+ per_device_train_batch_size=2048,
173
+ per_device_eval_batch_size=2048,
174
+ learning_rate=2e-1,
175
+ warmup_ratio=0.1,
176
+ fp16=False, # Set to False if you get an error that your GPU can't run on FP16
177
+ bf16=True, # Set to True if you have a GPU that supports BF16
178
+ batch_sampler=BatchSamplers.NO_DUPLICATES, # MultipleNegativesRankingLoss benefits from no duplicate samples in a batch
179
+ multi_dataset_batch_sampler=MultiDatasetBatchSamplers.PROPORTIONAL,
180
+ # Optional tracking/debugging parameters:
181
+ eval_strategy="steps",
182
+ eval_steps=250,
183
+ save_strategy="steps",
184
+ save_steps=250,
185
+ save_total_limit=2,
186
+ logging_steps=250,
187
+ logging_first_step=True,
188
+ run_name=run_name, # Will be used in W&B if `wandb` is installed
189
+ )
190
+
191
+ # 6. (Optional) Create an evaluator & evaluate the base model
192
+ evaluator = NanoBEIREvaluator()
193
+ evaluator(model)
194
+
195
+ # 7. Create a trainer & train
196
+ trainer = SentenceTransformerTrainer(
197
+ model=model,
198
+ args=args,
199
+ train_dataset=train_dataset,
200
+ eval_dataset=eval_dataset,
201
+ loss=loss,
202
+ evaluator=evaluator,
203
+ )
204
+ trainer.train()
205
+
206
+ # (Optional) Evaluate the trained model on the evaluator after training
207
+ evaluator(model)
208
+
209
+ # 8. Save the trained model
210
+ model.save_pretrained(f"models/{run_name}/final")
211
+
212
+ # 9. (Optional) Push it to the Hugging Face Hub
213
+ model.push_to_hub(run_name, private=True)
214
+
215
+ if __name__ == "__main__":
216
+ main()