init
Browse files- experiments/main.sh +3 -1
- experiments/model_finetuning_ner.py +194 -0
experiments/main.sh
CHANGED
@@ -1,4 +1,6 @@
|
|
1 |
-
MODEL=""
|
|
|
|
|
2 |
MODEL="roberta-base"
|
3 |
|
4 |
|
|
|
1 |
+
MODEL="cardiffnlp/twitter-roberta-base"
|
2 |
+
MODEL="jhu-clsp/bernice"
|
3 |
+
MODEL="vinai/bertweet-base"
|
4 |
MODEL="roberta-base"
|
5 |
|
6 |
|
experiments/model_finetuning_ner.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Experiment.
|
2 |
+
|
3 |
+
```
|
4 |
+
python model_finetuning_ner.py -m "roberta-base" -d "ner_temporal"
|
5 |
+
```
|
6 |
+
"""
|
7 |
+
import argparse
|
8 |
+
import json
|
9 |
+
import logging
|
10 |
+
import math
|
11 |
+
import os
|
12 |
+
from os.path import join as pj
|
13 |
+
from shutil import copyfile
|
14 |
+
from glob import glob
|
15 |
+
|
16 |
+
import numpy as np
|
17 |
+
import evaluate
|
18 |
+
from datasets import load_dataset
|
19 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
|
20 |
+
from huggingface_hub import Repository
|
21 |
+
|
22 |
+
logging.basicConfig(format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S")
|
23 |
+
EVAL_STEP = 500
|
24 |
+
RANDOM_SEED = 42
|
25 |
+
N_TRIALS = 10
|
26 |
+
|
27 |
+
|
28 |
+
def sigmoid(x):
|
29 |
+
return 1 / (1 + math.exp(-x))
|
30 |
+
|
31 |
+
|
32 |
+
def main(
|
33 |
+
dataset: str = "tweettemposhift/tweet_temporal_shift",
|
34 |
+
dataset_type: str = "ner_temporal",
|
35 |
+
model: str = "roberta-base",
|
36 |
+
skip_train: bool = False,
|
37 |
+
skip_test: bool = False,
|
38 |
+
skip_upload: bool = False):
|
39 |
+
|
40 |
+
model_alias = f"ner-{dataset_type}-{os.path.basename(model)}"
|
41 |
+
output_dir = f"ckpt/{model_alias}"
|
42 |
+
best_model_path = pj(output_dir, "best_model")
|
43 |
+
|
44 |
+
tokenizer = AutoTokenizer.from_pretrained(model, add_prefix_space=True)
|
45 |
+
|
46 |
+
def align_labels_with_tokens(labels, word_ids):
|
47 |
+
new_labels = []
|
48 |
+
current_word = None
|
49 |
+
for word_id in word_ids:
|
50 |
+
if word_id != current_word:
|
51 |
+
# Start of a new word!
|
52 |
+
current_word = word_id
|
53 |
+
label = -100 if word_id is None else labels[word_id]
|
54 |
+
new_labels.append(label)
|
55 |
+
elif word_id is None:
|
56 |
+
# Special token
|
57 |
+
new_labels.append(-100)
|
58 |
+
else:
|
59 |
+
# Same word as previous token
|
60 |
+
label = labels[word_id]
|
61 |
+
# If the label is B-XXX we change it to I-XXX
|
62 |
+
if label % 2 == 1:
|
63 |
+
label += 1
|
64 |
+
new_labels.append(label)
|
65 |
+
|
66 |
+
return new_labels
|
67 |
+
|
68 |
+
def tokenize_and_align_labels(examples):
|
69 |
+
tokenized_inputs = tokenizer(
|
70 |
+
examples["tokens"], truncation=True, is_split_into_words=True, padding="max_length", max_length=256
|
71 |
+
)
|
72 |
+
all_labels = examples["ner_tags"]
|
73 |
+
new_labels = []
|
74 |
+
for ind, labels in enumerate(all_labels):
|
75 |
+
word_ids = tokenized_inputs.word_ids(ind)
|
76 |
+
new_labels.append(align_labels_with_tokens(labels, word_ids))
|
77 |
+
|
78 |
+
tokenized_inputs["labels"] = new_labels
|
79 |
+
return tokenized_inputs
|
80 |
+
|
81 |
+
dataset = load_dataset(dataset, dataset_type)
|
82 |
+
tokenized_datasets = dataset.map(
|
83 |
+
lambda x: tokenize_and_align_labels(x),
|
84 |
+
batched=True
|
85 |
+
)
|
86 |
+
|
87 |
+
metric_accuracy = evaluate.load("accuracy")
|
88 |
+
metric_f1 = evaluate.load("f1")
|
89 |
+
|
90 |
+
def compute_metric_search(eval_pred):
|
91 |
+
logits, labels = eval_pred
|
92 |
+
predictions = np.argmax(logits, axis=-1)
|
93 |
+
return metric_accuracy.compute(predictions=predictions, references=labels)
|
94 |
+
|
95 |
+
def compute_metric_all(eval_pred):
|
96 |
+
logits, labels = eval_pred
|
97 |
+
predictions = np.argmax(logits, axis=-1)
|
98 |
+
return {
|
99 |
+
"f1": metric_f1.compute(predictions=predictions, references=labels)["f1"],
|
100 |
+
"accuracy": metric_accuracy.compute(predictions=predictions, references=labels)["accuracy"]
|
101 |
+
}
|
102 |
+
|
103 |
+
if not skip_train:
|
104 |
+
logging.info("training model")
|
105 |
+
trainer = Trainer(
|
106 |
+
model=AutoModelForSequenceClassification.from_pretrained(model, num_labels=2),
|
107 |
+
args=TrainingArguments(
|
108 |
+
output_dir=output_dir,
|
109 |
+
evaluation_strategy="steps",
|
110 |
+
eval_steps=EVAL_STEP,
|
111 |
+
seed=RANDOM_SEED
|
112 |
+
),
|
113 |
+
train_dataset=tokenized_datasets["train"],
|
114 |
+
eval_dataset=tokenized_datasets["validation"],
|
115 |
+
compute_metrics=compute_metric_search,
|
116 |
+
model_init=lambda x: AutoModelForSequenceClassification.from_pretrained(
|
117 |
+
model, return_dict=True, num_labels=2,
|
118 |
+
)
|
119 |
+
)
|
120 |
+
|
121 |
+
best_run = trainer.hyperparameter_search(
|
122 |
+
hp_space=lambda trial: {
|
123 |
+
"learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True),
|
124 |
+
"per_device_train_batch_size": trial.suggest_categorical(
|
125 |
+
"per_device_train_batch_size", [8, 16, 32]
|
126 |
+
),
|
127 |
+
},
|
128 |
+
direction="maximize",
|
129 |
+
backend="optuna",
|
130 |
+
n_trials=N_TRIALS
|
131 |
+
)
|
132 |
+
for n, v in best_run.hyperparameters.items():
|
133 |
+
setattr(trainer.args, n, v)
|
134 |
+
trainer.train()
|
135 |
+
trainer.save_model(best_model_path)
|
136 |
+
|
137 |
+
if not skip_test:
|
138 |
+
logging.info("testing model")
|
139 |
+
test_split = ["test"]
|
140 |
+
if dataset_type.endswith("temporal"):
|
141 |
+
test_split += ["test_1", "test_2", "test_3", "test_4"]
|
142 |
+
summary_file = pj(output_dir, "summary.json")
|
143 |
+
if os.path.exists(summary_file):
|
144 |
+
with open(summary_file) as f:
|
145 |
+
metric = json.load(f)
|
146 |
+
else:
|
147 |
+
metric = {}
|
148 |
+
for single_test in test_split:
|
149 |
+
trainer = Trainer(
|
150 |
+
model=AutoModelForSequenceClassification.from_pretrained(best_model_path, num_labels=2),
|
151 |
+
args=TrainingArguments(
|
152 |
+
output_dir=output_dir,
|
153 |
+
evaluation_strategy="no",
|
154 |
+
seed=RANDOM_SEED
|
155 |
+
),
|
156 |
+
train_dataset=tokenized_datasets["train"],
|
157 |
+
eval_dataset=tokenized_datasets[single_test],
|
158 |
+
compute_metrics=compute_metric_all
|
159 |
+
)
|
160 |
+
metric.update({f"{single_test}/{k}": v for k, v in trainer.evaluate().items()})
|
161 |
+
logging.info(json.dumps(metric, indent=4))
|
162 |
+
with open(summary_file, "w") as f:
|
163 |
+
json.dump(metric, f)
|
164 |
+
|
165 |
+
if not skip_upload:
|
166 |
+
logging.info("uploading to huggingface")
|
167 |
+
model_organization = "tweettemposhift"
|
168 |
+
model_instance = AutoModelForSequenceClassification.from_pretrained(best_model_path, num_labels=2)
|
169 |
+
tokenizer = AutoTokenizer.from_pretrained(best_model_path)
|
170 |
+
model_instance.push_to_hub(f"{model_organization}/{model_alias}", use_auth_token=True)
|
171 |
+
tokenizer.push_to_hub(f"{model_organization}/{model_alias}", use_auth_token=True)
|
172 |
+
repo = Repository(model_alias, f"{model_organization}/{model_alias}")
|
173 |
+
for i in glob(f"{best_model_path}/*"):
|
174 |
+
if not os.path.exists(f"{model_alias}/{os.path.basename(i)}"):
|
175 |
+
copyfile(i, f"{model_alias}/{os.path.basename(i)}")
|
176 |
+
repo.push_to_hub()
|
177 |
+
|
178 |
+
|
179 |
+
if __name__ == "__main__":
|
180 |
+
parser = argparse.ArgumentParser(description="Fine-tuning language model.")
|
181 |
+
parser.add_argument("-m", "--model", help="transformer LM", default="roberta-base", type=str)
|
182 |
+
parser.add_argument("-d", "--dataset-type", help='dataset type', default="ner_temporal", type=str)
|
183 |
+
parser.add_argument("--skip-train", action="store_true")
|
184 |
+
parser.add_argument("--skip-test", action="store_true")
|
185 |
+
parser.add_argument("--skip-upload", action="store_true")
|
186 |
+
opt = parser.parse_args()
|
187 |
+
main(
|
188 |
+
dataset_type=opt.dataset_type,
|
189 |
+
model=opt.model,
|
190 |
+
skip_train=opt.skip_train,
|
191 |
+
skip_test=opt.skip_test,
|
192 |
+
skip_upload=opt.skip_upload,
|
193 |
+
)
|
194 |
+
|