|
import logging |
|
from datasets import load_dataset, Dataset |
|
from sentence_transformers import ( |
|
SentenceTransformer, |
|
SentenceTransformerTrainer, |
|
SentenceTransformerTrainingArguments, |
|
SentenceTransformerModelCardData, |
|
) |
|
from sentence_transformers.losses import MultipleNegativesRankingLoss |
|
from sentence_transformers.training_args import BatchSamplers |
|
from sentence_transformers.evaluation import NanoBEIREvaluator |
|
from peft import LoraConfig, TaskType |
|
|
|
logging.basicConfig( |
|
format="%(asctime)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO |
|
) |
|
|
|
|
|
model = SentenceTransformer( |
|
"sentence-transformers-testing/stsb-bert-tiny-safetensors", |
|
model_card_data=SentenceTransformerModelCardData( |
|
language="en", |
|
license="apache-2.0", |
|
model_name="stsb-bert-tiny adapter finetuned on GooAQ pairs", |
|
), |
|
) |
|
|
|
|
|
peft_config = LoraConfig( |
|
task_type=TaskType.FEATURE_EXTRACTION, |
|
inference_mode=False, |
|
r=8, |
|
lora_alpha=32, |
|
lora_dropout=0.1, |
|
) |
|
model.add_adapter(peft_config, "dense") |
|
|
|
|
|
dataset = load_dataset("sentence-transformers/gooaq", split="train") |
|
dataset_dict = dataset.train_test_split(test_size=10_000, seed=12) |
|
train_dataset: Dataset = dataset_dict["train"].select(range(1_000_000)) |
|
eval_dataset: Dataset = dataset_dict["test"] |
|
|
|
|
|
loss = MultipleNegativesRankingLoss(model) |
|
|
|
|
|
run_name = "stsb-bert-tiny-base-gooaq-peft" |
|
args = SentenceTransformerTrainingArguments( |
|
|
|
output_dir=f"models/{run_name}", |
|
|
|
num_train_epochs=1, |
|
per_device_train_batch_size=1024, |
|
per_device_eval_batch_size=1024, |
|
learning_rate=2e-5, |
|
warmup_ratio=0.1, |
|
fp16=False, |
|
bf16=True, |
|
batch_sampler=BatchSamplers.NO_DUPLICATES, |
|
|
|
eval_strategy="steps", |
|
eval_steps=100, |
|
save_strategy="steps", |
|
save_steps=100, |
|
save_total_limit=2, |
|
logging_steps=25, |
|
logging_first_step=True, |
|
run_name=run_name, |
|
) |
|
|
|
|
|
|
|
dev_evaluator = NanoBEIREvaluator(batch_size=1024) |
|
dev_evaluator(model) |
|
|
|
|
|
trainer = SentenceTransformerTrainer( |
|
model=model, |
|
args=args, |
|
train_dataset=train_dataset, |
|
eval_dataset=eval_dataset, |
|
loss=loss, |
|
evaluator=dev_evaluator, |
|
) |
|
trainer.train() |
|
|
|
|
|
dev_evaluator(model) |
|
|
|
|
|
model.save_pretrained(f"models/{run_name}/final") |
|
|
|
|
|
model.push_to_hub("sentence-transformers-testing/stsb-bert-tiny-lora", private=True) |
|
|