train.py 5.66 KB
Newer Older
thomwolf's avatar
thomwolf committed
1
import os
thomwolf's avatar
thomwolf committed
2
3
from argparse import ArgumentParser, Namespace

Aymeric Augustin's avatar
Aymeric Augustin committed
4
5
from transformers import SingleSentenceClassificationProcessor as Processor
from transformers import TextClassificationPipeline, is_tf_available, is_torch_available
thomwolf's avatar
thomwolf committed
6
from transformers.commands import BaseTransformersCLICommand
Aymeric Augustin's avatar
Aymeric Augustin committed
7

Lysandre Debut's avatar
Lysandre Debut committed
8
9
from ..utils import logging

thomwolf's avatar
thomwolf committed
10
11

if not is_tf_available() and not is_torch_available():
Aymeric Augustin's avatar
Aymeric Augustin committed
12
    raise RuntimeError("At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training")
thomwolf's avatar
thomwolf committed
13
14
15
16
17

# TF training parameters
USE_XLA = False
USE_AMP = False

18

thomwolf's avatar
thomwolf committed
19
20
def train_command_factory(args: Namespace):
    """
21
22
    Factory function used to instantiate training command from provided command line arguments.
    :return: TrainCommand
thomwolf's avatar
thomwolf committed
23
    """
thomwolf's avatar
thomwolf committed
24
    return TrainCommand(args)
thomwolf's avatar
thomwolf committed
25
26
27
28
29
30
31
32
33
34


class TrainCommand(BaseTransformersCLICommand):
    @staticmethod
    def register_subcommand(parser: ArgumentParser):
        """
        Register this command to argparse so it's available for the transformer-cli
        :param parser: Root parser to register command-specific arguments
        :return:
        """
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
        train_parser = parser.add_parser("train", help="CLI tool to train a model on a task.")

        train_parser.add_argument(
            "--train_data",
            type=str,
            required=True,
            help="path to train (and optionally evaluation) dataset as a csv with "
            "tab separated labels and sentences.",
        )
        train_parser.add_argument(
            "--column_label", type=int, default=0, help="Column of the dataset csv file with example labels."
        )
        train_parser.add_argument(
            "--column_text", type=int, default=1, help="Column of the dataset csv file with example texts."
        )
        train_parser.add_argument(
            "--column_id", type=int, default=2, help="Column of the dataset csv file with example ids."
        )
        train_parser.add_argument(
            "--skip_first_row", action="store_true", help="Skip the first row of the csv file (headers)."
        )

        train_parser.add_argument("--validation_data", type=str, default="", help="path to validation dataset.")
        train_parser.add_argument(
            "--validation_split",
            type=float,
            default=0.1,
            help="if validation dataset is not provided, fraction of train dataset " "to use as validation dataset.",
        )

        train_parser.add_argument("--output", type=str, default="./", help="path to saved the trained model.")

        train_parser.add_argument(
            "--task", type=str, default="text_classification", help="Task to train the model on."
        )
        train_parser.add_argument(
            "--model", type=str, default="bert-base-uncased", help="Model's name or path to stored model."
        )
        train_parser.add_argument("--train_batch_size", type=int, default=32, help="Batch size for training.")
        train_parser.add_argument("--valid_batch_size", type=int, default=64, help="Batch size for validation.")
        train_parser.add_argument("--learning_rate", type=float, default=3e-5, help="Learning rate.")
        train_parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon for Adam optimizer.")
thomwolf's avatar
thomwolf committed
77
78
        train_parser.set_defaults(func=train_command_factory)

thomwolf's avatar
thomwolf committed
79
    def __init__(self, args: Namespace):
Lysandre Debut's avatar
Lysandre Debut committed
80
        self.logger = logging.get_logger("transformers-cli/training")
thomwolf's avatar
thomwolf committed
81

82
        self.framework = "tf" if is_tf_available() else "torch"
thomwolf's avatar
thomwolf committed
83

thomwolf's avatar
thomwolf committed
84
        os.makedirs(args.output, exist_ok=True)
thomwolf's avatar
thomwolf committed
85
86
87
88
89
90
        self.output = args.output

        self.column_label = args.column_label
        self.column_text = args.column_text
        self.column_id = args.column_id

91
92
        self.logger.info("Loading {} pipeline for {}".format(args.task, args.model))
        if args.task == "text_classification":
thomwolf's avatar
thomwolf committed
93
            self.pipeline = TextClassificationPipeline.from_pretrained(args.model)
94
        elif args.task == "token_classification":
thomwolf's avatar
thomwolf committed
95
            raise NotImplementedError
96
        elif args.task == "question_answering":
thomwolf's avatar
thomwolf committed
97
98
            raise NotImplementedError

99
100
101
102
103
104
105
106
        self.logger.info("Loading dataset from {}".format(args.train_data))
        self.train_dataset = Processor.create_from_csv(
            args.train_data,
            column_label=args.column_label,
            column_text=args.column_text,
            column_id=args.column_id,
            skip_first_row=args.skip_first_row,
        )
thomwolf's avatar
thomwolf committed
107
        self.valid_dataset = None
thomwolf's avatar
thomwolf committed
108
        if args.validation_data:
109
110
111
112
113
114
115
116
            self.logger.info("Loading validation dataset from {}".format(args.validation_data))
            self.valid_dataset = Processor.create_from_csv(
                args.validation_data,
                column_label=args.column_label,
                column_text=args.column_text,
                column_id=args.column_id,
                skip_first_row=args.skip_first_row,
            )
thomwolf's avatar
thomwolf committed
117

thomwolf's avatar
thomwolf committed
118
        self.validation_split = args.validation_split
thomwolf's avatar
thomwolf committed
119
120
121
122
        self.train_batch_size = args.train_batch_size
        self.valid_batch_size = args.valid_batch_size
        self.learning_rate = args.learning_rate
        self.adam_epsilon = args.adam_epsilon
thomwolf's avatar
thomwolf committed
123
124

    def run(self):
125
        if self.framework == "tf":
thomwolf's avatar
thomwolf committed
126
127
128
129
130
131
132
            return self.run_tf()
        return self.run_torch()

    def run_torch(self):
        raise NotImplementedError

    def run_tf(self):
133
134
135
136
137
138
139
140
141
        self.pipeline.fit(
            self.train_dataset,
            validation_data=self.valid_dataset,
            validation_split=self.validation_split,
            learning_rate=self.learning_rate,
            adam_epsilon=self.adam_epsilon,
            train_batch_size=self.train_batch_size,
            valid_batch_size=self.valid_batch_size,
        )
thomwolf's avatar
thomwolf committed
142
143
144

        # Save trained pipeline
        self.pipeline.save_pretrained(self.output)