train_roberta.py 4.43 KB
Newer Older
Gaëtan Caillaut's avatar
Gaëtan Caillaut committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from transformers import RobertaTokenizerFast, RobertaForSequenceClassification
import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter


from data import *

if __name__ == "__main__":
    import argparse

    def _train(args):
        if args.device is None:
            device = torch.device(
                'cuda') if torch.cuda.is_available() else torch.device('cpu')
        else:
            device = torch.device(args.device)
        pm = device == torch.device("cuda")

        tokenizer = RobertaTokenizerFast.from_pretrained('roberta-base')
        dataset = HateSpeechDataset(args.input)
22
        collater = HateSpeechCollater(tokenizer, device)
Gaëtan Caillaut's avatar
Gaëtan Caillaut committed
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
        class_names = collater.class_names()

        for fold, (train, test) in enumerate(dataset.iter_folds(args.folds, True), 1):
            train_loader = DataLoader(
                train, collate_fn=collater, shuffle=True, batch_size=128, pin_memory=pm)
            test_loader = DataLoader(
                test, collate_fn=collater, shuffle=False, batch_size=128, pin_memory=pm)

            if args.jobname is not None:
                writer = SummaryWriter(
                    log_dir=f"runs/{args.jobname}/fold-{fold}")
            else:
                writer = SummaryWriter(
                    log_dir=f"runs/roberta-{optim_name}/fold-{fold}")

            model = RobertaForSequenceClassification.from_pretrained(
                'roberta-base', num_labels=3).to(device)

            optim_name = args.optimizer.lower()
            if optim_name == "adam":
                optimizer = torch.optim.Adam(model.parameters())
            elif optim_name == "sgd":
                optimizer = torch.optim.SGD(model.parameters(), lr=0.005)
            elif optim_name == "adamw":
                optimizer = torch.optim.AdamW(model.parameters())
            elif optim_name == "adadelta":
                optimizer = torch.optim.Adadelta(model.parameters())
            elif optim_name == "adagrad":
                optimizer = torch.optim.Adagrad(model.parameters())

            for epoch in range(1, args.epochs + 1):
                model.train()
                epoch_loss = 0
                for batch, (inputs, labels) in enumerate(train_loader, 1):
                    print(f"FOLD {fold}  -  BATCH {batch}")

                    optimizer.zero_grad()
                    outputs = model(**inputs, labels=labels)
                    loss = outputs.loss
                    logits = outputs.logits
                    loss.backward()
                    optimizer.step()

                    writer.add_scalar("Loss/batch", loss.item(),
                                      batch + (epoch - 1) * len(train_loader))
                    epoch_loss += loss.item()

                writer.add_scalar(
                    "Loss/epoch", epoch_loss / len(train_loader), epoch)

                model.eval()
                with torch.no_grad():
                    true_positives, tp_ratio, confusion, scores_per_class = eval_model(
                        model, test_loader, device)
                cm = plot_confusion_matrix(confusion.numpy(), class_names)
                writer.add_figure("Confusion Matrix/epoch", cm, epoch)
                writer.add_scalar("Eval/true posititves",
                                  tp_ratio, epoch)

            writer.flush()
            writer.close()

            outdir = Path(args.output)
            outdir.mkdir(parents=True, exist_ok=True)

            model_out = Path(outdir, f"roberta-{optim_name}-fold{fold}.pt")
            optimizer_out = Path(
                outdir, f"optimizer-{optim_name}-fold{fold}.pt")
            torch.save(model.state_dict(), str(model_out))
            torch.save(optimizer.state_dict(), str(optimizer_out))

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    train_parser = subparsers.add_parser("train-roberta")
    train_parser.add_argument(
        "-i", "--input", default="data/cleaned-hate-speech-dataset.csv")
    train_parser.add_argument("-o", "--output", default="output/roberta")
    train_parser.add_argument("-e", "--epochs", type=int, default=10)
    train_parser.add_argument("--optimizer", default="adam")
    train_parser.add_argument("--device", required=False)
    train_parser.add_argument("--jobname", required=False)
    train_parser.add_argument("--folds", default=10, type=int)
    train_parser.set_defaults(func=_train)

    args = parser.parse_args()
    args.func(args)