|
from pathlib import Path |
|
import shutil |
|
from datasets import load_dataset, concatenate_datasets |
|
from transformers import TrainingArguments |
|
from span_marker import SpanMarkerModel, Trainer |
|
from span_marker.model_card import SpanMarkerModelCardData |
|
|
|
import os |
|
|
|
os.environ["CODECARBON_LOG_LEVEL"] = "error" |
|
|
|
|
|
def main() -> None: |
|
|
|
dataset_id = "midas/inspec" |
|
dataset_name = "Inspec" |
|
dataset = load_dataset(dataset_id, "extraction") |
|
dataset = dataset.rename_columns({"document": "tokens", "doc_bio_tags": "ner_tags"}) |
|
|
|
real_labels = ["O", "B", "I"] |
|
dataset = dataset.map(lambda sample: {"ner_tags": [real_labels.index(tag) for tag in sample]}, input_columns="ner_tags") |
|
|
|
labels = ["O", "B-KEY", "I-KEY"] |
|
|
|
train_dataset = concatenate_datasets((dataset["train"], dataset["validation"])) |
|
|
|
|
|
encoder_id = "bert-base-uncased" |
|
model_id = "tomaarsen/span-marker_bert-base-uncased-keyphrase-inspec" |
|
model = SpanMarkerModel.from_pretrained( |
|
encoder_id, |
|
labels=labels, |
|
|
|
model_max_length=256, |
|
marker_max_length=128, |
|
entity_max_length=8, |
|
|
|
model_card_data=SpanMarkerModelCardData( |
|
model_id=model_id, |
|
encoder_id=encoder_id, |
|
dataset_name=dataset_name, |
|
dataset_id=dataset_id, |
|
license="apache-2.0", |
|
language="en", |
|
), |
|
) |
|
|
|
|
|
output_dir = Path("models") / model_id |
|
args = TrainingArguments( |
|
output_dir=output_dir, |
|
hub_model_id=model_id, |
|
run_name=f"bbu_keyphrase", |
|
|
|
learning_rate=5e-5, |
|
per_device_train_batch_size=32, |
|
per_device_eval_batch_size=32, |
|
num_train_epochs=3, |
|
weight_decay=0.01, |
|
warmup_ratio=0.1, |
|
bf16=True, |
|
|
|
logging_first_step=True, |
|
logging_steps=50, |
|
evaluation_strategy="no", |
|
save_total_limit=2, |
|
dataloader_num_workers=2, |
|
) |
|
|
|
|
|
trainer = Trainer( |
|
model=model, |
|
args=args, |
|
train_dataset=train_dataset |
|
) |
|
trainer.train() |
|
|
|
|
|
metrics = trainer.evaluate(dataset["test"], metric_key_prefix="test") |
|
trainer.save_metrics("test", metrics) |
|
|
|
trainer.save_model(output_dir / "checkpoint-final") |
|
shutil.copy2(__file__, output_dir / "checkpoint-final" / "train.py") |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |