Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
parquet
Sub-tasks:
sentiment-classification
Languages:
English
Size:
10K - 100K
ArXiv:
License:
init
Browse files- lm_finetuning.py +179 -0
lm_finetuning.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import urllib.request
|
| 7 |
+
import multiprocessing
|
| 8 |
+
from os.path import join as pj
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import numpy as np
|
| 12 |
+
from huggingface_hub import create_repo
|
| 13 |
+
from datasets import load_dataset, load_metric
|
| 14 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
|
| 15 |
+
from ray import tune
|
| 16 |
+
|
| 17 |
+
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
|
| 18 |
+
|
| 19 |
+
PARALLEL = bool(int(os.getenv("PARALLEL", 1)))
|
| 20 |
+
RAY_RESULTS = os.getenv("RAY_RESULTS", "ray_results")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def internet_connection(host='http://google.com'):
|
| 24 |
+
try:
|
| 25 |
+
urllib.request.urlopen(host)
|
| 26 |
+
return True
|
| 27 |
+
except:
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_metrics():
|
| 32 |
+
metric_accuracy = load_metric("accuracy", "multilabel")
|
| 33 |
+
metric_f1 = load_metric("f1", "multilabel")
|
| 34 |
+
|
| 35 |
+
# metric_f1.compute(predictions=[[0, 1, 1], [1, 1, 0]], references=[[0, 1, 1], [0, 1, 0]], average='micro')
|
| 36 |
+
# metric_accuracy.compute(predictions=[[0, 1, 1], [1, 1, 0]], references=[[0, 1, 1], [0, 1, 0]])
|
| 37 |
+
|
| 38 |
+
def compute_metric_search(eval_pred):
|
| 39 |
+
logits, labels = eval_pred
|
| 40 |
+
predictions = np.argmax(logits, axis=-1)
|
| 41 |
+
return metric_f1.compute(predictions=predictions, references=labels, average='micro')
|
| 42 |
+
|
| 43 |
+
def compute_metric_all(eval_pred):
|
| 44 |
+
logits, labels = eval_pred
|
| 45 |
+
predictions = np.argmax(logits, axis=-1)
|
| 46 |
+
return {
|
| 47 |
+
'f1': metric_f1.compute(predictions=predictions, references=labels, average='micro')['f1'],
|
| 48 |
+
'f1_macro': metric_f1.compute(predictions=predictions, references=labels, average='macro')['f1'],
|
| 49 |
+
'accuracy': metric_accuracy.compute(predictions=predictions, references=labels)['accuracy']
|
| 50 |
+
}
|
| 51 |
+
return compute_metric_search, compute_metric_all
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main():
|
| 55 |
+
parser = argparse.ArgumentParser(description='Fine-tuning language model.')
|
| 56 |
+
parser.add_argument('-m', '--model', help='transformer LM', default='roberta-base', type=str)
|
| 57 |
+
parser.add_argument('-d', '--dataset', help='', default='cardiffnlp/tweet_topic_multi', type=str)
|
| 58 |
+
parser.add_argument('--dataset-name', help='huggingface dataset name', default='citation_intent', type=str)
|
| 59 |
+
parser.add_argument('-l', '--seq-length', help='', default=128, type=int)
|
| 60 |
+
parser.add_argument('--random-seed', help='', default=42, type=int)
|
| 61 |
+
parser.add_argument('--eval-step', help='', default=50, type=int)
|
| 62 |
+
parser.add_argument('-o', '--output-dir', help='Directory to output', default='ckpt_tmp', type=str)
|
| 63 |
+
parser.add_argument('-t', '--n-trials', default=10, type=int)
|
| 64 |
+
parser.add_argument('--push-to-hub', action='store_true')
|
| 65 |
+
parser.add_argument('--use-auth-token', action='store_true')
|
| 66 |
+
parser.add_argument('--hf-organization', default=None, type=str)
|
| 67 |
+
parser.add_argument('-a', '--model-alias', help='', default=None, type=str)
|
| 68 |
+
parser.add_argument('--summary-file', default='metric_summary.json', type=str)
|
| 69 |
+
parser.add_argument('--skip-train', action='store_true')
|
| 70 |
+
parser.add_argument('--skip-eval', action='store_true')
|
| 71 |
+
opt = parser.parse_args()
|
| 72 |
+
assert opt.summary_file.endswith('.json'), f'`--summary-file` should be a json file {opt.summary_file}'
|
| 73 |
+
# setup data
|
| 74 |
+
dataset = load_dataset(opt.dataset, opt.dataset_name)
|
| 75 |
+
network = internet_connection()
|
| 76 |
+
# setup model
|
| 77 |
+
tokenizer = AutoTokenizer.from_pretrained(opt.model, local_files_only=not network)
|
| 78 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 79 |
+
opt.model,
|
| 80 |
+
num_labels=len(dataset['train'][0]['label']),
|
| 81 |
+
local_files_only=not network,
|
| 82 |
+
problem_type="multi_label_classification"
|
| 83 |
+
)
|
| 84 |
+
tokenized_datasets = dataset.map(
|
| 85 |
+
lambda x: tokenizer(x["text"], padding="max_length", truncation=True, max_length=opt.seq_length),
|
| 86 |
+
batched=True)
|
| 87 |
+
# setup metrics
|
| 88 |
+
compute_metric_search, compute_metric_all = get_metrics()
|
| 89 |
+
|
| 90 |
+
if not opt.skip_train:
|
| 91 |
+
# setup trainer
|
| 92 |
+
trainer = Trainer(
|
| 93 |
+
model=model,
|
| 94 |
+
args=TrainingArguments(
|
| 95 |
+
output_dir=opt.output_dir,
|
| 96 |
+
evaluation_strategy="steps",
|
| 97 |
+
eval_steps=opt.eval_step,
|
| 98 |
+
seed=opt.random_seed
|
| 99 |
+
),
|
| 100 |
+
train_dataset=tokenized_datasets["train"],
|
| 101 |
+
eval_dataset=tokenized_datasets["validation"],
|
| 102 |
+
compute_metrics=compute_metric_search,
|
| 103 |
+
model_init=lambda x: AutoModelForSequenceClassification.from_pretrained(
|
| 104 |
+
opt.model, return_dict=True, num_labels=dataset['train'].features['label'].num_classes)
|
| 105 |
+
)
|
| 106 |
+
# parameter search
|
| 107 |
+
if PARALLEL:
|
| 108 |
+
best_run = trainer.hyperparameter_search(
|
| 109 |
+
hp_space=lambda x: {
|
| 110 |
+
"learning_rate": tune.loguniform(1e-6, 1e-4),
|
| 111 |
+
"num_train_epochs": tune.choice(list(range(1, 6))),
|
| 112 |
+
"per_device_train_batch_size": tune.choice([4, 8, 16, 32, 64]),
|
| 113 |
+
},
|
| 114 |
+
local_dir=RAY_RESULTS, direction="maximize", backend="ray", n_trials=opt.n_trials,
|
| 115 |
+
resources_per_trial={'cpu': multiprocessing.cpu_count(), "gpu": torch.cuda.device_count()},
|
| 116 |
+
|
| 117 |
+
)
|
| 118 |
+
else:
|
| 119 |
+
best_run = trainer.hyperparameter_search(
|
| 120 |
+
hp_space=lambda x: {
|
| 121 |
+
"learning_rate": tune.loguniform(1e-6, 1e-4),
|
| 122 |
+
"num_train_epochs": tune.choice(list(range(1, 6))),
|
| 123 |
+
"per_device_train_batch_size": tune.choice([4, 8, 16, 32, 64]),
|
| 124 |
+
},
|
| 125 |
+
local_dir=RAY_RESULTS, direction="maximize", backend="ray", n_trials=opt.n_trials
|
| 126 |
+
)
|
| 127 |
+
# finetuning
|
| 128 |
+
for n, v in best_run.hyperparameters.items():
|
| 129 |
+
setattr(trainer.args, n, v)
|
| 130 |
+
trainer.train()
|
| 131 |
+
trainer.save_model(pj(opt.output_dir, 'best_model'))
|
| 132 |
+
best_model_path = pj(opt.output_dir, 'best_model')
|
| 133 |
+
else:
|
| 134 |
+
best_model_path = opt.output_dir
|
| 135 |
+
|
| 136 |
+
# evaluation
|
| 137 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 138 |
+
best_model_path,
|
| 139 |
+
num_labels=dataset['train'].features['label'].num_classes,
|
| 140 |
+
local_files_only=not network)
|
| 141 |
+
trainer = Trainer(
|
| 142 |
+
model=model,
|
| 143 |
+
args=TrainingArguments(
|
| 144 |
+
output_dir=opt.output_dir,
|
| 145 |
+
evaluation_strategy="no",
|
| 146 |
+
seed=opt.random_seed
|
| 147 |
+
),
|
| 148 |
+
train_dataset=tokenized_datasets["train"],
|
| 149 |
+
eval_dataset=tokenized_datasets["test"],
|
| 150 |
+
compute_metrics=compute_metric_all,
|
| 151 |
+
model_init=lambda x: AutoModelForSequenceClassification.from_pretrained(
|
| 152 |
+
opt.model, return_dict=True, num_labels=dataset['train'].features['label'].num_classes)
|
| 153 |
+
)
|
| 154 |
+
summary_file = pj(opt.output_dir, opt.summary_file)
|
| 155 |
+
if not opt.skip_eval:
|
| 156 |
+
result = {f'test/{k}': v for k, v in trainer.evaluate().items()}
|
| 157 |
+
logging.info(json.dumps(result, indent=4))
|
| 158 |
+
with open(summary_file, 'w') as f:
|
| 159 |
+
json.dump(result, f)
|
| 160 |
+
|
| 161 |
+
if opt.push_to_hub:
|
| 162 |
+
assert opt.hf_organization is not None, f'specify hf organization `--hf-organization`'
|
| 163 |
+
assert opt.model_alias is not None, f'specify hf organization `--model-alias`'
|
| 164 |
+
url = create_repo(opt.model_alias, organization=opt.hf_organization, exist_ok=True)
|
| 165 |
+
# if not opt.skip_train:
|
| 166 |
+
args = {"use_auth_token": opt.use_auth_token, "repo_url": url, "organization": opt.hf_organization}
|
| 167 |
+
trainer.model.push_to_hub(opt.model_alias, **args)
|
| 168 |
+
tokenizer.push_to_hub(opt.model_alias, **args)
|
| 169 |
+
if os.path.exists(summary_file):
|
| 170 |
+
shutil.copy2(summary_file, opt.model_alias)
|
| 171 |
+
os.system(
|
| 172 |
+
f"cd {opt.model_alias} && git lfs install && git add . && git commit -m 'model update' && git push && cd ../")
|
| 173 |
+
shutil.rmtree(f"{opt.model_alias}") # clean up the cloned repo
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__ == '__main__':
|
| 177 |
+
main()
|
| 178 |
+
|
| 179 |
+
|