File size: 14,647 Bytes
4d88e8a
 
3789adf
4d88e8a
 
 
 
 
 
 
d13fe3a
3789adf
4d88e8a
 
348c52a
12106f5
4d88e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3789adf
4d88e8a
 
 
 
 
 
 
 
 
 
 
 
348c52a
4d88e8a
 
 
 
 
 
 
 
 
 
348c52a
d9bd9cf
348c52a
4d88e8a
 
 
 
 
 
 
348c52a
 
 
419d31a
4d88e8a
348c52a
3789adf
4d88e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3789adf
4d88e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348c52a
88b612d
f5ad9b6
88b612d
419d31a
d9bd9cf
3789adf
334b050
12106f5
334b050
64f11ac
 
 
348c52a
64f11ac
348c52a
d9bd9cf
348c52a
0be9716
769ed64
419d31a
348c52a
 
 
64f11ac
348c52a
 
 
4d88e8a
9ec398b
7db50a7
eb17e47
 
9ec398b
 
 
 
3789adf
eb17e47
 
348c52a
3789adf
348c52a
 
8a46345
d13fe3a
541d3e6
12106f5
d13fe3a
541d3e6
 
 
 
 
 
 
 
 
 
12106f5
5dd24e2
4d88e8a
 
 
 
348c52a
4d88e8a
12106f5
4d88e8a
 
12106f5
348c52a
4d88e8a
 
419d31a
4d88e8a
12106f5
4d88e8a
12106f5
4d88e8a
 
 
 
 
 
 
5f7019e
4d88e8a
12106f5
4d88e8a
 
348c52a
 
 
4d88e8a
 
12106f5
4d88e8a
 
 
12106f5
 
 
 
4d88e8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348c52a
700e037
348c52a
419d31a
4d88e8a
 
 
 
348c52a
4d88e8a
 
 
348c52a
 
 
4d88e8a
 
348c52a
 
 
 
 
 
 
 
 
 
 
 
 
419d31a
348c52a
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
""" Fine-tune T5 on topic classification (multi-label multi-class classification)
```
python finetune_t5.py --dataset-name ja --model-alias mt5-small-tweet-topic-ja --model-organization cardiffnlp --low-cpu-mem-usage
```
"""
import json
import logging
import os
import argparse
import gc
from glob import glob
from typing import List, Set, Dict
from shutil import copyfile
from statistics import mean
from itertools import product
from distutils.dir_util import copy_tree

import torch
import transformers
from datasets import load_dataset
from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments, pipeline
from huggingface_hub import Repository


os.environ['TOKENIZERS_PARALLELISM'] = 'false'  # turn-off the warning message
os.environ['WANDB_DISABLED'] = 'true'  # disable wandb


def load_model(
        model_name: str,
        use_auth_token: bool = False,
        low_cpu_mem_usage: bool = False) -> transformers.PreTrainedModel:
    """Load language model from huggingface model hub."""
    # config & tokenizer
    config = transformers.AutoConfig.from_pretrained(model_name, use_auth_token=use_auth_token)
    if config.model_type == 't5':  # T5 model requires T5ForConditionalGeneration class
        model_class = transformers.T5ForConditionalGeneration.from_pretrained
    elif config.model_type == 'mt5':
        model_class = transformers.MT5ForConditionalGeneration.from_pretrained
    elif config.model_type == 'bart':
        model_class = transformers.BartForConditionalGeneration.from_pretrained
    elif config.model_type == 'mbart':
        model_class = transformers.MBartForConditionalGeneration.from_pretrained
    else:
        raise ValueError(f'unsupported model type: {config.model_type}')
    param = {'config': config, 'use_auth_token': use_auth_token, 'low_cpu_mem_usage': low_cpu_mem_usage}
    model = model_class(model_name, **param)
    return model


def get_f1_score(references: List[Set[str]], predictions: List[Set[str]]) -> Dict[str, float]:
    scores = []
    for g, r in zip(references, predictions):
        tp = len(set(g).intersection(set(r)))
        fp = len([_g for _g in g if _g not in r])
        fn = len([_r for _r in r if _r not in g])
        if tp == 0:
            f1 = 0
        else:
            f1 = 2 * tp / (2 * tp + fp + fn)
        scores.append(f1)
    return {'f1': mean(scores)}


def train(
        model_name: str,
        model_low_cpu_mem_usage: bool,
        dataset: str,
        dataset_name: str,
        dataset_column_label: str,
        dataset_column_text: str,
        dataset_split_train: str,
        dataset_split_validation: str,
        dataset_split_test: str,
        lr: List,
        epoch: List,
        batch: List,
        down_sample_train: int,
        down_sample_validation: int,
        random_seed: int,
        use_auth_token: bool,
        output_dir: str,
        model_alias: str,
        model_organization: str,
        skip_train: bool = False,
        skip_test: bool = False,
        skip_upload: bool = False,
        batch_eval: int = None):
    """Fine-tune seq2seq model."""
    logging.info(f'[CONFIG]\n\t *LM: {model_name}, \n\t *Data: {dataset} ({dataset_name})')
    if not output_dir:
        output_dir = f'ckpt/{os.path.basename(model_name)}.{os.path.basename(dataset)}.{dataset_name}'
    # dataset process
    tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, use_auth_token=use_auth_token)
    dataset_split = {
        'train': [dataset_split_train, down_sample_train],
        'validation': [dataset_split_validation, down_sample_validation]
    }
    dataset_instance = load_dataset(dataset, dataset_name, use_auth_token=use_auth_token)
    tokenized_dataset = {}
    for s, (s_dataset, down_sample) in dataset_split.items():
        tokenized_dataset[s] = []
        dataset_tmp = dataset_instance[s_dataset]
        dataset_tmp.shuffle(random_seed)
        for i in dataset_tmp:
            model_inputs = tokenizer(i[dataset_column_text], truncation=True)
            model_inputs['labels'] = tokenizer(text_target=i[dataset_column_label], truncation=True)['input_ids']
            tokenized_dataset[s].append(model_inputs)

        if down_sample is not None and len(dataset_tmp) > down_sample:
            tokenized_dataset[f'{s}_ds'] = []
            dataset_tmp = dataset_tmp.select(list(range(down_sample)))
            for i in dataset_tmp:
                model_inputs = tokenizer(i[dataset_column_text], truncation=True)
                model_inputs['labels'] = tokenizer(text_target=i[dataset_column_label], truncation=True)['input_ids']
                tokenized_dataset[f'{s}_ds'].append(model_inputs)
        else:
            tokenized_dataset[f'{s}_ds'] = tokenized_dataset[s]

    def compute_metric(eval_pred) -> Dict[str, float]:  # for parameter search

        def decode_tokens(token_ids) -> List[Set[str]]:
            return [
                set(tokenizer.decode(list(filter(lambda x: x != -100, r)), skip_special_tokens=True).split(',')) for r
                in token_ids
            ]

        predictions, reference_token_ids = eval_pred
        # format reference
        references_decode = decode_tokens(reference_token_ids)
        # format prediction
        logit, loss = predictions
        generation_token_id = logit.argmax(-1)
        generation_token_id[logit.min(-1) == -100] = -100
        generation_decode = decode_tokens(generation_token_id)
        return get_f1_score(references_decode, generation_decode)

    if not skip_train:
        lr = [1e-6, 1e-5, 1e-4] if lr is None else lr
        batch = [32] if not batch else batch
        epoch = [3, 5] if not epoch else epoch
        batch_eval = min(batch) if not batch_eval else batch_eval
        for n, (lr_tmp, batch_tmp, epoch_tmp) in enumerate(product(lr, batch, epoch)):
            logging.info(f"[TRAIN {n}/{len(lr) * len(batch) * len(epoch)}] lr: {lr_tmp}, batch: {batch_tmp}")
            output_dir_tmp = f"{output_dir}/model_lr_{lr_tmp}_batch_{batch_tmp}_epoch_{epoch_tmp}"
            if os.path.exists(f"{output_dir_tmp}/eval_results.json"):
                continue
            model = load_model(
                model_name=model_name, use_auth_token=use_auth_token, low_cpu_mem_usage=model_low_cpu_mem_usage
            )
            trainer = Seq2SeqTrainer(
                model=model,
                args=Seq2SeqTrainingArguments(
                    num_train_epochs=epoch_tmp,
                    learning_rate=lr_tmp,
                    output_dir=output_dir_tmp,
                    evaluation_strategy="no",
                    per_device_eval_batch_size=batch_eval,
                    seed=random_seed,
                    per_device_train_batch_size=batch_tmp,
                ),
                data_collator=transformers.DataCollatorForSeq2Seq(tokenizer, model=model),
                train_dataset=tokenized_dataset['train_ds'],
                eval_dataset=tokenized_dataset['validation_ds'],
                compute_metrics=compute_metric,
            )
            # train
            result = trainer.train()
            trainer.log_metrics("train", result.metrics)
            trainer.save_metrics("train", result.metrics)
            # evaluate
            metrics = trainer.evaluate()
            trainer.log_metrics("eval", metrics)
            trainer.save_metrics("eval", metrics)
            # clean up memory
            trainer.save_model()
            trainer.save_state()
            del trainer
            del model
            gc.collect()
            torch.cuda.empty_cache()
            # cuda.get_current_device().reset()

        model_score = []
        for eval_file in glob(f"{output_dir}/model_*/eval_results.json"):
            with open(eval_file) as f:
                results = json.load(f)
                model_score.append([os.path.dirname(eval_file), results['eval_loss'], results['eval_f1']])
        logging.info("Search Result")
        for i in model_score:
            logging.info(i)
        max_metric = max(model_score, key=lambda x: x[2])
        if len([i for i in model_score if i[2] == max_metric]) > 1:
            best_model = sorted(model_score, key=lambda x: x[1])[0][0]
        else:
            best_model = sorted(model_score, key=lambda x: x[2])[-1][0]
        copy_tree(best_model, f'{output_dir}/best_model')
        tokenizer.save_pretrained(f'{output_dir}/best_model')
    else:
        logging.info('skip hyperparameter search & model training (already done)')

    # get metric on the test set
    if not skip_test:
        logging.info('run evaluation on test set')
        if not os.path.exists(f'{output_dir}/best_model/prediction_test.txt'):
            pipe = pipeline(
                'text2text-generation',
                model=f'{output_dir}/best_model',
                device='cuda:0' if torch.cuda.is_available() else 'cpu',
            )
            input_data = [i[dataset_column_text] for i in dataset_instance[dataset_split_test]]
            output = pipe(input_data, batch_size=batch_eval)
            output = [i['generated_text'] for i in output]
            with open(f'{output_dir}/best_model/prediction_test.txt', 'w') as f:
                f.write('\n'.join(output))
        with open(f'{output_dir}/best_model/prediction_test.txt') as f:
            output = [set(i.split(',')) for i in f.read().split('\n')]
        dataset_tmp = dataset_instance[dataset_split_test]
        label_list = dataset_tmp[dataset_column_label]
        _references = [
            set([_l for __i, _l in zip(_i[dataset_column_label], label_list) if __i == 1]) for _i in dataset_tmp
        ]
        eval_metric = get_f1_score(_references, output)
        eval_metric[f'f1/{dataset}/{dataset_name}'] = eval_metric.pop('f1')
        logging.info(json.dumps(eval_metric, indent=4))
        with open(f'{output_dir}/best_model/evaluation_metrics.json', 'w') as f:
            json.dump(eval_metric, f)

    if not skip_upload:
        assert model_alias is not None and model_organization is not None,\
            'model_organization must be specified when model_alias is specified'
        logging.info('uploading to huggingface')
        args = {'use_auth_token': use_auth_token, 'organization': model_organization}
        model = load_model(model_name=f'{output_dir}/best_model')
        model.push_to_hub(model_alias, **args)
        tokenizer.push_to_hub(model_alias, **args)
        repo = Repository(model_alias, f'{model_organization}/{model_alias}')
        if os.path.exists(f'{output_dir}/best_model/prediction_test.txt'):
            copyfile(f'{output_dir}/best_model/prediction_test.txt', f'{model_alias}/prediction_test.txt')
        if os.path.exists(f'{output_dir}/best_model/evaluation_metrics.json'):
            copyfile(f'{output_dir}/best_model/evaluation_metrics.json', f'{model_alias}/evaluation_metrics.json')
        sample = [i[dataset_column_text] for i in dataset_instance[dataset_split_train]]
        sample = [i for i in sample if ''' not in i and ''' not in i][:3]
        widget = '\n'.join([f"- text: '{t}'\n  example_title: example {_n + 1}" for _n, t in enumerate(sample)])
        with open(f'{model_alias}/README.md', 'w') as f:
            f.write(f"""
---
widget:
{widget}
---

# {model_organization}/{model_alias}

This is [{model_name}](https://huggingface.co/{model_name}) fine-tuned on [{dataset} ({dataset_name})](https://huggingface.co/datasets/{dataset}).

### Usage

```python
from transformers import pipeline

pipe = pipeline('text2text-generation', model='{model_organization}/{model_alias}')
output = pipe('{sample[0]}')
```
        """)
        repo.push_to_hub()


if __name__ == '__main__':
    # arguments
    logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
    parser = argparse.ArgumentParser(description='Seq2Seq LM Fine-tuning on topic classification.')
    parser.add_argument('-m', '--model-name', default='google/mt5-small', type=str)
    parser.add_argument('--low-cpu-mem-usage', action='store_true')
    parser.add_argument('-d', '--dataset', default='cardiffnlp/tweet_topic_multilingual', type=str)
    parser.add_argument('--dataset-name', default='ja', type=str)
    parser.add_argument('--dataset-column-label', default='label_name_flatten', type=str)
    parser.add_argument('--dataset-column-text', default='text', type=str)
    parser.add_argument('--dataset-split-train', default='train', type=str)
    parser.add_argument('--dataset-split-validation', default='validation', type=str)
    parser.add_argument('--dataset-split-test', default='test', type=str)
    parser.add_argument('--lr', nargs='+', default=None, type=float)
    parser.add_argument('--epoch', nargs='+', default=None, type=int)
    parser.add_argument('--batch', nargs='+', default=None, type=int)
    parser.add_argument('--batch-eval', type=int, default=None)
    parser.add_argument('--down-sample-train', default=None, type=int)
    parser.add_argument('--down-sample-validation', default=2000, type=int)
    parser.add_argument('--random-seed', default=42, type=int)
    parser.add_argument('--use-auth-token', action='store_true')
    parser.add_argument('--eval-steps', default=100, type=int)
    parser.add_argument('--output-dir', default=None, type=str)
    parser.add_argument('--model-alias', default=None, type=str)
    parser.add_argument('--model-organization', default=None, 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()

    train(
        model_name=opt.model_name,
        model_low_cpu_mem_usage=opt.low_cpu_mem_usage,
        dataset=opt.dataset,
        dataset_name=opt.dataset_name,
        dataset_column_label=opt.dataset_column_label,
        dataset_column_text=opt.dataset_column_text,
        dataset_split_train=opt.dataset_split_train,
        dataset_split_validation=opt.dataset_split_validation,
        dataset_split_test=opt.dataset_split_test,
        lr=opt.lr,
        epoch=opt.epoch,
        batch=opt.batch,
        batch_eval=opt.batch_eval,
        down_sample_train=opt.down_sample_train,
        down_sample_validation=opt.down_sample_validation,
        random_seed=opt.random_seed,
        use_auth_token=opt.use_auth_token,
        output_dir=opt.output_dir,
        model_alias=opt.model_alias,
        model_organization=opt.model_organization,
        skip_train=opt.skip_train,
        skip_test=opt.skip_test,
        skip_upload=opt.skip_upload
    )