File size: 8,194 Bytes
006076c
 
 
e54e3de
006076c
616755f
ff2b314
 
 
 
 
ce7523f
ff2b314
5db21d7
ff2b314
 
 
b9ac9ba
 
ff2b314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce7523f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff2b314
 
 
 
 
 
 
 
 
 
 
 
 
 
e54e3de
 
 
 
ff2b314
 
 
ce7523f
 
 
 
5a7343a
ce7523f
ff2b314
1b182d0
b9ac9ba
 
449f02d
ff2b314
 
 
006076c
ff2b314
 
ce7523f
ff2b314
 
006076c
ff2b314
 
 
 
 
 
 
 
 
93717bc
 
 
 
 
 
 
ff2b314
 
 
 
b9ac9ba
ff2b314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91e1d0a
ff2b314
 
 
 
 
8c46a14
ff2b314
 
 
 
 
da77579
ff2b314
 
 
 
 
 
 
7b37d9b
 
 
 
 
 
 
ff2b314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b37d9b
ff2b314
 
 
 
 
 
7b37d9b
ff2b314
 
 
 
 
 
5db21d7
ff2b314
 
 
 
 
616755f
ff2b314
 
 
 
 
 
 
 
 
 
 
 
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
"""Experiment.

```
python model_finetuning_topic.py -m "roberta-base" -d "topic_temporal"
```
"""
import argparse
import json
import logging
import math
import os
import re
from os.path import join as pj
from shutil import copyfile, rmtree
from glob import glob

import numpy as np
import evaluate
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
from huggingface_hub import Repository

logging.basicConfig(format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S")

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()}
EVAL_STEP = 500
RANDOM_SEED = 42
N_TRIALS = 10
URL_RE = re.compile(r"https?:\/\/[\w\.\/\?\=\d&#%_:/-]+")
HANDLE_RE = re.compile(r"@\w+")


def preprocess_bernice(text):
    text = HANDLE_RE.sub("@USER", text)
    text = URL_RE.sub("HTTPURL", text)
    return text


def preprocess_timelm(text):
    text = HANDLE_RE.sub("@user", text)
    text = URL_RE.sub("http", text)
    return text


def preprocess(model_name, text):
    if model_name == "jhu-clsp/bernice":
        return preprocess_bernice(text)
    if "twitter-roberta-base" in model_name:
        return preprocess_timelm(text)
    return text


def sigmoid(x):
    return 1 / (1 + math.exp(-x))


def main(
        dataset: str = "tweettemposhift/tweet_temporal_shift",
        dataset_type: str = "topic_temporal",
        model: str = "roberta-base",
        skip_train: bool = False,
        skip_test: bool = False,
        skip_upload: bool = False):

    model_alias = f"topic-{dataset_type}-{os.path.basename(model)}"
    output_dir = f"ckpt/{model_alias}"
    best_model_path = pj(output_dir, "best_model")

    tokenizer = AutoTokenizer.from_pretrained(model)
    dataset = load_dataset(dataset, dataset_type)
    tokenized_datasets = dataset.map(
        lambda x: tokenizer(
            [preprocess(model, t) for t in x["text"]],
            padding="max_length",
            truncation=True,
            max_length=128),
        batched=True
    )
    tokenized_datasets = tokenized_datasets.rename_column("gold_label_list", "label")
    metric_accuracy = evaluate.load("accuracy", "multilabel")
    metric_f1 = evaluate.load("f1", "multilabel")


    def compute_metric_search(eval_pred):
        logits, labels = eval_pred
        predictions = np.array([[int(sigmoid(j) > 0.5) for j in lo] for lo 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 lo] for lo 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"]
        }

    if not skip_train:
        logging.info("training model")
        trainer = Trainer(
            model=AutoModelForSequenceClassification.from_pretrained(
                model,
                num_labels=len(LABEL2ID),
                problem_type="multi_label_classification",
                id2label=ID2LABEL,
                label2id=LABEL2ID
            ),
            args=TrainingArguments(
                output_dir=output_dir,
                evaluation_strategy="steps",
                eval_steps=EVAL_STEP,
                seed=RANDOM_SEED
            ),
            train_dataset=tokenized_datasets["train"],
            eval_dataset=tokenized_datasets["validation"],
            compute_metrics=compute_metric_search,
            model_init=lambda x: AutoModelForSequenceClassification.from_pretrained(
                model,
                return_dict=True,
                num_labels=len(LABEL2ID),
                id2label=ID2LABEL,
                label2id=LABEL2ID
            )
        )

        best_run = trainer.hyperparameter_search(
            hp_space=lambda trial: {
                "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True),
                "per_device_train_batch_size": trial.suggest_categorical(
                    "per_device_train_batch_size", [8, 16, 32]
                ),
            },
            direction="maximize",
            backend="optuna",
            n_trials=N_TRIALS
        )
        for n, v in best_run.hyperparameters.items():
            setattr(trainer.args, n, v)
        trainer.train()
        trainer.save_model(best_model_path)

    if not skip_test:
        logging.info("testing model")
        test_split = ["test"]
        if dataset_type.endswith("temporal"):
            test_split += ["test_1", "test_2", "test_3", "test_4"]
        summary_file = pj(best_model_path, "summary.json")
        if os.path.exists(summary_file):
            with open(summary_file) as f:
                metric = json.load(f)
        else:
            metric = {}
        for single_test in test_split:
            trainer = Trainer(
                model=AutoModelForSequenceClassification.from_pretrained(
                    best_model_path,
                    num_labels=len(LABEL2ID),
                    problem_type="multi_label_classification",
                    id2label=ID2LABEL,
                    label2id=LABEL2ID
                ),
                args=TrainingArguments(
                    output_dir=output_dir,
                    evaluation_strategy="no",
                    seed=RANDOM_SEED
                ),
                train_dataset=tokenized_datasets["train"],
                eval_dataset=tokenized_datasets[single_test],
                compute_metrics=compute_metric_all
            )
            metric.update({f"{single_test}/{k}": v for k, v in trainer.evaluate().items()})
        logging.info(json.dumps(metric, indent=4))
        with open(summary_file, "w") as f:
            json.dump(metric, f)

    if not skip_upload:
        logging.info("uploading to huggingface")
        model_organization = "tweettemposhift"
        model_instance = AutoModelForSequenceClassification.from_pretrained(
            best_model_path,
            num_labels=len(LABEL2ID),
            problem_type="multi_label_classification",
            id2label=ID2LABEL,
            label2id=LABEL2ID
        )
        model_instance.push_to_hub(f"{model_organization}/{model_alias}", use_auth_token=True)
        tokenizer.push_to_hub(f"{model_organization}/{model_alias}", use_auth_token=True)
        repo = Repository(model_alias, f"{model_organization}/{model_alias}")
        for i in glob(f"{best_model_path}/*"):
            if not os.path.exists(f"{model_alias}/{os.path.basename(i)}"):
                copyfile(i, f"{model_alias}/{os.path.basename(i)}")
        repo.push_to_hub()
        rmtree(model_alias)


if __name__ == "__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-type", help='dataset type', default="topic_temporal", type=str)
    parser.add_argument("--skip-train", action="store_true")
    parser.add_argument("--skip-test", action="store_true")
    parser.add_argument("--skip-upload", action="store_true")
    opt = parser.parse_args()
    main(
        dataset_type=opt.dataset_type,
        model=opt.model,
        skip_train=opt.skip_train,
        skip_test=opt.skip_test,
        skip_upload=opt.skip_upload,
    )