Create train_script.py
Browse files- train_script.py +122 -0
train_script.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# See https://huggingface.co/collections/tomaarsen/training-with-prompts-672ce423c85b4d39aed52853 for some already trained models
|
2 |
+
|
3 |
+
import logging
|
4 |
+
import random
|
5 |
+
|
6 |
+
import numpy
|
7 |
+
import torch
|
8 |
+
from datasets import Dataset, load_dataset
|
9 |
+
|
10 |
+
from sentence_transformers import (
|
11 |
+
SentenceTransformer,
|
12 |
+
SentenceTransformerModelCardData,
|
13 |
+
SentenceTransformerTrainer,
|
14 |
+
SentenceTransformerTrainingArguments,
|
15 |
+
)
|
16 |
+
from sentence_transformers.evaluation import NanoBEIREvaluator
|
17 |
+
from sentence_transformers.losses import CachedMultipleNegativesRankingLoss
|
18 |
+
from sentence_transformers.training_args import BatchSamplers
|
19 |
+
from sentence_transformers.models import Pooling
|
20 |
+
|
21 |
+
logging.basicConfig(format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO)
|
22 |
+
random.seed(12)
|
23 |
+
torch.manual_seed(12)
|
24 |
+
numpy.random.seed(12)
|
25 |
+
|
26 |
+
# Feel free to adjust these variables:
|
27 |
+
use_prompts = True
|
28 |
+
include_prompts_in_pooling = True
|
29 |
+
|
30 |
+
# 1. Load a model to finetune with 2. (Optional) model card data
|
31 |
+
model = SentenceTransformer(
|
32 |
+
"LiquidAI/LFM2-350M",
|
33 |
+
model_card_data=SentenceTransformerModelCardData(
|
34 |
+
language="en",
|
35 |
+
license="apache-2.0",
|
36 |
+
model_name="LiquidAI/LFM2-350M trained on Natural Questions pairs",
|
37 |
+
),
|
38 |
+
trust_remote_code=True,
|
39 |
+
)
|
40 |
+
assert isinstance(model[1], Pooling)
|
41 |
+
model[1].pooling_mode_mean_tokens = False
|
42 |
+
model[1].pooling_mode_lasttoken = True
|
43 |
+
model.set_pooling_include_prompt(include_prompts_in_pooling)
|
44 |
+
print(model)
|
45 |
+
|
46 |
+
# 2. (Optional) Define prompts
|
47 |
+
if use_prompts:
|
48 |
+
query_prompt = "query: "
|
49 |
+
corpus_prompt = "document: "
|
50 |
+
prompts = {
|
51 |
+
"query": query_prompt,
|
52 |
+
"answer": corpus_prompt,
|
53 |
+
}
|
54 |
+
|
55 |
+
# 3. Load a dataset to finetune on
|
56 |
+
dataset = load_dataset("sentence-transformers/natural-questions", split="train")
|
57 |
+
dataset_dict = dataset.train_test_split(test_size=1_000, seed=12)
|
58 |
+
train_dataset: Dataset = dataset_dict["train"]
|
59 |
+
eval_dataset: Dataset = dataset_dict["test"]
|
60 |
+
|
61 |
+
# 4. Define a loss function
|
62 |
+
loss = CachedMultipleNegativesRankingLoss(model, mini_batch_size=4)
|
63 |
+
|
64 |
+
# 5. (Optional) Specify training arguments
|
65 |
+
run_name = "LFM2-350M-nq"
|
66 |
+
if use_prompts:
|
67 |
+
run_name += "-prompts"
|
68 |
+
if not include_prompts_in_pooling:
|
69 |
+
run_name += "-exclude-pooling-prompts"
|
70 |
+
args = SentenceTransformerTrainingArguments(
|
71 |
+
# Required parameter:
|
72 |
+
output_dir=f"models/{run_name}",
|
73 |
+
# Optional training parameters:
|
74 |
+
num_train_epochs=1,
|
75 |
+
per_device_train_batch_size=256,
|
76 |
+
per_device_eval_batch_size=256,
|
77 |
+
learning_rate=2e-5,
|
78 |
+
warmup_ratio=0.1,
|
79 |
+
fp16=False, # Set to False if you get an error that your GPU can't run on FP16
|
80 |
+
bf16=True, # Set to True if you have a GPU that supports BF16
|
81 |
+
batch_sampler=BatchSamplers.NO_DUPLICATES, # MultipleNegativesRankingLoss benefits from no duplicate samples in a batch
|
82 |
+
# Optional tracking/debugging parameters:
|
83 |
+
eval_strategy="steps",
|
84 |
+
eval_steps=50,
|
85 |
+
save_strategy="steps",
|
86 |
+
save_steps=50,
|
87 |
+
save_total_limit=2,
|
88 |
+
logging_steps=5,
|
89 |
+
logging_first_step=True,
|
90 |
+
run_name=run_name, # Will be used in W&B if `wandb` is installed
|
91 |
+
seed=12,
|
92 |
+
prompts=prompts if use_prompts else None,
|
93 |
+
)
|
94 |
+
|
95 |
+
# 6. (Optional) Create an evaluator & evaluate the base model
|
96 |
+
dev_evaluator = NanoBEIREvaluator(
|
97 |
+
dataset_names=["msmarco", "nfcorpus", "nq"],
|
98 |
+
query_prompts=query_prompt if use_prompts else None,
|
99 |
+
corpus_prompts=corpus_prompt if use_prompts else None,
|
100 |
+
batch_size=16,
|
101 |
+
)
|
102 |
+
dev_evaluator(model)
|
103 |
+
|
104 |
+
# 7. Create a trainer & train
|
105 |
+
trainer = SentenceTransformerTrainer(
|
106 |
+
model=model,
|
107 |
+
args=args,
|
108 |
+
train_dataset=train_dataset,
|
109 |
+
eval_dataset=eval_dataset,
|
110 |
+
loss=loss,
|
111 |
+
evaluator=dev_evaluator,
|
112 |
+
)
|
113 |
+
trainer.train()
|
114 |
+
|
115 |
+
# (Optional) Evaluate the trained model on the evaluator after training
|
116 |
+
dev_evaluator(model)
|
117 |
+
|
118 |
+
# 8. Save the trained model
|
119 |
+
model.save_pretrained(f"models/{run_name}/final")
|
120 |
+
|
121 |
+
# 9. (Optional) Push it to the Hugging Face Hub
|
122 |
+
model.push_to_hub(run_name)
|