File size: 12,580 Bytes
19391a5 a3e1ce4 60b610a c28734d 60b610a c28734d 60b610a c28734d ae07650 c28734d ae07650 c28734d 19391a5 5b95481 9a436ff 5b95481 bde7d96 5b95481 1b10b57 5b95481 9a436ff 5b95481 9a436ff 5b95481 9a436ff 5b95481 19391a5 5b95481 a3e1ce4 5b95481 1b10b57 60b610a 5b95481 19391a5 5b95481 e9bf213 39fc020 e9bf213 5b95481 911f874 5b95481 5f0221d 8ea930a 1b10b57 5b95481 19391a5 5b95481 8ea930a 1b10b57 5b95481 bde7d96 51db099 bde7d96 1693d6c fe2e381 5b95481 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
'''
wandb offline
export WANDB_DISABLED='true'
export RAY_RESULTS='ray_results'
python lm_finetuning.py -m "roberta-large" -o "ckpt/2021/roberta-large" --push-to-hub --hf-organization "cardiffnlp" -a "roberta-large-tweet-topic-multi-all" --split-train "train_all" --split-valid "validation_2021" --split-test "test_2021"
python lm_finetuning.py -m "roberta-large" -o "ckpt/2020/roberta-large" --push-to-hub --hf-organization "cardiffnlp" -a "roberta-large-tweet-topic-multi-2020" --split-train "train_2020" --split-valid "validation_2020" --split-test "test_2021"
python lm_finetuning.py -m "roberta-base" -o "ckpt/2021/roberta_base" --push-to-hub --hf-organization "cardiffnlp" -a "roberta-base-tweet-topic-multi-all" --split-train "train_all" --split-valid "validation_2021" --split-test "test_2021"
python lm_finetuning.py -m "roberta-base" -o "ckpt/2020/roberta_base" --push-to-hub --hf-organization "cardiffnlp" -a "roberta-base-tweet-topic-multi-2020" --split-train "train_2020" --split-valid "validation_2020" --split-test "test_2021"
python lm_finetuning.py -m "cardiffnlp/twitter-roberta-base-2019-90m" -o "ckpt/2021/twitter-roberta-base-2019-90m" --push-to-hub --hf-organization "cardiffnlp" -a "twitter-roberta-base-2019-90m-tweet-topic-multi-all" --split-train "train_all" --split-valid "validation_2021" --split-test "test_2021"
python lm_finetuning.py -m "cardiffnlp/twitter-roberta-base-2019-90m" -o "ckpt/2020/twitter-roberta-base-2019-90m" --push-to-hub --hf-organization "cardiffnlp" -a "twitter-roberta-base-2019-90m-tweet-topic-multi-2020" --split-train "train_2020" --split-valid "validation_2020" --split-test "test_2021"
python lm_finetuning.py -m "cardiffnlp/twitter-roberta-base-dec2020" -o "ckpt/2021/twitter-roberta-base-dec2020" --push-to-hub --hf-organization "cardiffnlp" -a "twitter-roberta-base-dec2020-tweet-topic-multi-all" --split-train "train_all" --split-valid "validation_2021" --split-test "test_2021"
python lm_finetuning.py -m "cardiffnlp/twitter-roberta-base-dec2020" -o "ckpt/2020/twitter-roberta-base-dec2020" --push-to-hub --hf-organization "cardiffnlp" -a "twitter-roberta-base-dec2020-tweet-topic-multi-2020" --split-train "train_2020" --split-valid "validation_2020" --split-test "test_2021"
python lm_finetuning.py -m "cardiffnlp/twitter-roberta-base-dec2021" -o "ckpt/2021/twitter-roberta-base-dec2021" --push-to-hub --hf-organization "cardiffnlp" -a "twitter-roberta-base-dec2021-tweet-topic-multi-all" --split-train "train_all" --split-valid "validation_2021" --split-test "test_2021"
python lm_finetuning.py -m "cardiffnlp/twitter-roberta-base-dec2021" -o "ckpt/2020/twitter-roberta-base-dec2021" --push-to-hub --hf-organization "cardiffnlp" -a "twitter-roberta-base-dec2021-tweet-topic-multi-2020" --split-train "train_2020" --split-valid "validation_2020" --split-test "test_2021"
'''
import argparse
import json
import logging
import os
import math
import shutil
import urllib.request
import multiprocessing
from os.path import join as pj
import torch
import numpy as np
from huggingface_hub import create_repo
from datasets import load_dataset, load_metric
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
from ray import tune
from readme import get_readme
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
PARALLEL = bool(int(os.getenv("PARALLEL", 1)))
RAY_RESULTS = os.getenv("RAY_RESULTS", "ray_results")
LABEL2ID = {
"arts_&_culture": 0,
"business_&_entrepreneurs": 1,
"celebrity_&_pop_culture": 2,
"diaries_&_daily_life": 3,
"family": 4,
"fashion_&_style": 5,
"film_tv_&_video": 6,
"fitness_&_health": 7,
"food_&_dining": 8,
"gaming": 9,
"learning_&_educational": 10,
"music": 11,
"news_&_social_concern": 12,
"other_hobbies": 13,
"relationships": 14,
"science_&_technology": 15,
"sports": 16,
"travel_&_adventure": 17,
"youth_&_student_life": 18
}
ID2LABEL = {v: k for k, v in LABEL2ID.items()}
def internet_connection(host='http://google.com'):
try:
urllib.request.urlopen(host)
return True
except:
return False
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def get_metrics():
metric_accuracy = load_metric("accuracy", "multilabel")
metric_f1 = load_metric("f1", "multilabel")
# metric_f1.compute(predictions=[[0, 1, 1], [1, 1, 0]], references=[[0, 1, 1], [0, 1, 0]], average='micro')
# metric_accuracy.compute(predictions=[[0, 1, 1], [1, 1, 0]], references=[[0, 1, 1], [0, 1, 0]])
def compute_metric_search(eval_pred):
logits, labels = eval_pred
predictions = np.array([[int(sigmoid(j) > 0.5) for j in i] for i in logits])
return metric_f1.compute(predictions=predictions, references=labels, average='micro')
def compute_metric_all(eval_pred):
logits, labels = eval_pred
predictions = np.array([[int(sigmoid(j) > 0.5) for j in i] for i in logits])
return {
'f1': metric_f1.compute(predictions=predictions, references=labels, average='micro')['f1'],
'f1_macro': metric_f1.compute(predictions=predictions, references=labels, average='macro')['f1'],
'accuracy': metric_accuracy.compute(predictions=predictions, references=labels)['accuracy']
}
return compute_metric_search, compute_metric_all
def main():
parser = argparse.ArgumentParser(description='Fine-tuning language model.')
parser.add_argument('-m', '--model', help='transformer LM', default='roberta-base', type=str)
parser.add_argument('-d', '--dataset', help='', default='cardiffnlp/tweet_topic_multi', type=str)
parser.add_argument('--split-train', help='', required=True, type=str)
parser.add_argument('--split-validation', help='', required=True, type=str)
parser.add_argument('--split-test', help='', required=True, type=str)
parser.add_argument('-l', '--seq-length', help='', default=128, type=int)
parser.add_argument('--random-seed', help='', default=42, type=int)
parser.add_argument('--eval-step', help='', default=50, type=int)
parser.add_argument('-o', '--output-dir', help='Directory to output', default='ckpt_tmp', type=str)
parser.add_argument('-t', '--n-trials', default=10, type=int)
parser.add_argument('--push-to-hub', action='store_true')
parser.add_argument('--use-auth-token', action='store_true')
parser.add_argument('--hf-organization', default=None, type=str)
parser.add_argument('-a', '--model-alias', help='', default=None, type=str)
parser.add_argument('--summary-file', default='metric_summary.json', type=str)
parser.add_argument('--skip-train', action='store_true')
parser.add_argument('--skip-eval', action='store_true')
opt = parser.parse_args()
assert opt.summary_file.endswith('.json'), f'`--summary-file` should be a json file {opt.summary_file}'
# setup data
dataset = load_dataset(opt.dataset)
network = internet_connection()
# setup model
tokenizer = AutoTokenizer.from_pretrained(opt.model, local_files_only=not network)
model = AutoModelForSequenceClassification.from_pretrained(
opt.model,
id2label=ID2LABEL,
label2id=LABEL2ID,
num_labels=len(dataset[opt.split_train]['label'][0]),
local_files_only=not network,
problem_type="multi_label_classification"
)
tokenized_datasets = dataset.map(
lambda x: tokenizer(x["text"], padding="max_length", truncation=True, max_length=opt.seq_length),
batched=True)
# setup metrics
compute_metric_search, compute_metric_all = get_metrics()
if not opt.skip_train:
# setup trainer
trainer = Trainer(
model=model,
args=TrainingArguments(
output_dir=opt.output_dir,
evaluation_strategy="steps",
eval_steps=opt.eval_step,
seed=opt.random_seed
),
train_dataset=tokenized_datasets[opt.split_train],
eval_dataset=tokenized_datasets[opt.split_validation],
compute_metrics=compute_metric_search,
model_init=lambda x: AutoModelForSequenceClassification.from_pretrained(
opt.model,
return_dict=True,
num_labels=len(dataset[opt.split_train]['label'][0]),
id2label=ID2LABEL,
label2id=LABEL2ID
)
)
# parameter search
if PARALLEL:
best_run = trainer.hyperparameter_search(
hp_space=lambda x: {
"learning_rate": tune.loguniform(1e-6, 1e-4),
"num_train_epochs": tune.choice(list(range(1, 6))),
"per_device_train_batch_size": tune.choice([4, 8, 16, 32, 64]),
},
local_dir=RAY_RESULTS, direction="maximize", backend="ray", n_trials=opt.n_trials,
resources_per_trial={'cpu': multiprocessing.cpu_count(), "gpu": torch.cuda.device_count()},
)
else:
best_run = trainer.hyperparameter_search(
hp_space=lambda x: {
"learning_rate": tune.loguniform(1e-6, 1e-4),
"num_train_epochs": tune.choice(list(range(1, 6))),
"per_device_train_batch_size": tune.choice([4, 8, 16, 32, 64]),
},
local_dir=RAY_RESULTS, direction="maximize", backend="ray", n_trials=opt.n_trials
)
# finetuning
for n, v in best_run.hyperparameters.items():
setattr(trainer.args, n, v)
trainer.train()
trainer.save_model(pj(opt.output_dir, 'best_model'))
best_model_path = pj(opt.output_dir, 'best_model')
else:
best_model_path = pj(opt.output_dir, 'best_model')
# evaluation
model = AutoModelForSequenceClassification.from_pretrained(
best_model_path,
num_labels=len(dataset[opt.split_train]['label'][0]),
local_files_only=not network,
problem_type="multi_label_classification",
id2label=ID2LABEL,
label2id=LABEL2ID
)
trainer = Trainer(
model=model,
args=TrainingArguments(
output_dir=opt.output_dir,
evaluation_strategy="no",
seed=opt.random_seed
),
train_dataset=tokenized_datasets[opt.split_train],
eval_dataset=tokenized_datasets[opt.split_test],
compute_metrics=compute_metric_all,
model_init=lambda x: AutoModelForSequenceClassification.from_pretrained(
opt.model,
return_dict=True,
num_labels=len(dataset[opt.split_train]['label'][0]),
local_files_only=not network,
problem_type="multi_label_classification",
id2label=ID2LABEL,
label2id=LABEL2ID
)
)
summary_file = pj(opt.output_dir, opt.summary_file)
if not opt.skip_eval:
result = {f'test/{k}': v for k, v in trainer.evaluate().items()}
logging.info(json.dumps(result, indent=4))
with open(summary_file, 'w') as f:
json.dump(result, f)
if opt.push_to_hub:
assert opt.hf_organization is not None, f'specify hf organization `--hf-organization`'
assert opt.model_alias is not None, f'specify hf organization `--model-alias`'
url = create_repo(opt.model_alias, organization=opt.hf_organization, exist_ok=True)
# if not opt.skip_train:
args = {"use_auth_token": opt.use_auth_token, "repo_url": url, "organization": opt.hf_organization}
trainer.model.push_to_hub(opt.model_alias, **args)
tokenizer.push_to_hub(opt.model_alias, **args)
if os.path.exists(summary_file):
shutil.copy2(summary_file, opt.model_alias)
extra_desc = f"This model is fine-tuned on `{opt.split_train}` split and validated on `{opt.split_test}` split of tweet_topic."
readme = get_readme(
model_name=f"{opt.hf_organization}/{opt.model_alias}",
metric=summary_file,
language_model=opt.model,
extra_desc= extra_desc
)
with open(f"{opt.model_alias}/README.md", "w") as f:
f.write(readme)
os.system(
f"cd {opt.model_alias} && git lfs install && git add . && git commit -m 'model update' && git push && cd ../")
shutil.rmtree(f"{opt.model_alias}") # clean up the cloned repo
if __name__ == '__main__':
main()
|