tomaarsen HF staff commited on
Commit
12f1367
1 Parent(s): ed45995

Add the training script

Browse files
Files changed (1) hide show
  1. train_script.py +98 -0
train_script.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sentence_transformers.losses import MultipleNegativesRankingLoss
11
+ from sentence_transformers.training_args import BatchSamplers
12
+ from sentence_transformers.evaluation import InformationRetrievalEvaluator
13
+
14
+ logging.basicConfig(
15
+ format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO
16
+ )
17
+
18
+ # 1. Load a model to finetune with 2. (Optional) model card data
19
+ model = SentenceTransformer(
20
+ "microsoft/mpnet-base",
21
+ model_card_data=SentenceTransformerModelCardData(
22
+ language="en",
23
+ license="apache-2.0",
24
+ model_name="MPNet base trained on GooAQ triplets",
25
+ ),
26
+ )
27
+
28
+ # 3. Load a dataset to finetune on
29
+ dataset = load_dataset("sentence-transformers/gooaq", split="train")
30
+ dataset = dataset.add_column("id", range(len(dataset)))
31
+ dataset_dict = dataset.train_test_split(test_size=10_000)
32
+ train_dataset: Dataset = dataset_dict["train"]
33
+ eval_dataset: Dataset = dataset_dict["test"]
34
+
35
+ # 4. Define a loss function
36
+ loss = MultipleNegativesRankingLoss(model)
37
+
38
+ # 5. (Optional) Specify training arguments
39
+ args = SentenceTransformerTrainingArguments(
40
+ # Required parameter:
41
+ output_dir="models/mpnet-base-gooaq",
42
+ # Optional training parameters:
43
+ num_train_epochs=1,
44
+ per_device_train_batch_size=64,
45
+ per_device_eval_batch_size=64,
46
+ learning_rate=2e-5,
47
+ warmup_ratio=0.1,
48
+ fp16=False, # Set to False if you get an error that your GPU can't run on FP16
49
+ bf16=True, # Set to True if you have a GPU that supports BF16
50
+ batch_sampler=BatchSamplers.NO_DUPLICATES, # MultipleNegativesRankingLoss benefits from no duplicate samples in a batch
51
+ # Optional tracking/debugging parameters:
52
+ eval_strategy="steps",
53
+ eval_steps=1000,
54
+ save_strategy="steps",
55
+ save_steps=1000,
56
+ save_total_limit=2,
57
+ logging_steps=250,
58
+ logging_first_step=True,
59
+ run_name="mpnet-base-gooaq", # Will be used in W&B if `wandb` is installed
60
+ )
61
+
62
+ # 6. (Optional) Create an evaluator & evaluate the base model
63
+ # The full corpus, but only the evaluation queries
64
+ # corpus = dict(zip(dataset["id"], dataset["answer"]))
65
+ queries = dict(zip(eval_dataset["id"], eval_dataset["question"]))
66
+ corpus = (
67
+ {qid: dataset[qid]["answer"] for qid in queries} |
68
+ {qid: dataset[qid]["answer"] for qid in random.sample(range(len(dataset)), 20_000)}
69
+ )
70
+ relevant_docs = {qid: {qid} for qid in eval_dataset["id"]}
71
+ dev_evaluator = InformationRetrievalEvaluator(
72
+ corpus=corpus,
73
+ queries=queries,
74
+ relevant_docs=relevant_docs,
75
+ show_progress_bar=True,
76
+ name="gooaq-dev",
77
+ )
78
+ dev_evaluator(model)
79
+
80
+ # 7. Create a trainer & train
81
+ trainer = SentenceTransformerTrainer(
82
+ model=model,
83
+ args=args,
84
+ train_dataset=train_dataset.remove_columns("id"),
85
+ eval_dataset=eval_dataset.remove_columns("id"),
86
+ loss=loss,
87
+ evaluator=dev_evaluator,
88
+ )
89
+ trainer.train()
90
+
91
+ # (Optional) Evaluate the trained model on the evaluator after training
92
+ dev_evaluator(model)
93
+
94
+ # 8. Save the trained model
95
+ model.save_pretrained("models/mpnet-base-gooaq/final")
96
+
97
+ # 9. (Optional) Push it to the Hugging Face Hub
98
+ model.push_to_hub("mpnet-base-gooaq")