tomaarsen HF staff commited on
Commit
f32d520
1 Parent(s): 1cad261

Create train_script.py

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