nferruz commited on
Commit
4a3659f
1 Parent(s): ff560f2

Upload 5.run_clm-post.py

Browse files
Files changed (1) hide show
  1. 5.run_clm-post.py +385 -0
5.run_clm-post.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2020 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset.
18
+
19
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
20
+ https://huggingface.co/models?filter=causal-lm
21
+ """
22
+ # You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
23
+
24
+ import logging
25
+ import math
26
+ import os
27
+ import sys
28
+ from dataclasses import dataclass, field
29
+ from typing import Optional
30
+
31
+ import datasets
32
+ from datasets import load_dataset
33
+ from datasets import load_from_disk
34
+
35
+ import transformers
36
+ from transformers import (
37
+ CONFIG_MAPPING,
38
+ MODEL_FOR_CAUSAL_LM_MAPPING,
39
+ AutoConfig,
40
+ AutoModelForCausalLM,
41
+ AutoTokenizer,
42
+ HfArgumentParser,
43
+ Trainer,
44
+ TrainingArguments,
45
+ default_data_collator,
46
+ set_seed,
47
+ )
48
+ from transformers.testing_utils import CaptureLogger
49
+ from transformers.trainer_utils import get_last_checkpoint
50
+ from transformers.utils import check_min_version
51
+ from transformers.utils.versions import require_version
52
+
53
+
54
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
55
+ check_min_version("4.13.0.dev0")
56
+
57
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())
63
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
64
+
65
+
66
+ @dataclass
67
+ class ModelArguments:
68
+ """
69
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
70
+ """
71
+
72
+ model_name_or_path: Optional[str] = field(
73
+ default=None,
74
+ metadata={
75
+ "help": "The model checkpoint for weights initialization."
76
+ "Don't set if you want to train a model from scratch."
77
+ },
78
+ )
79
+ model_type: Optional[str] = field(
80
+ default=None,
81
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
82
+ )
83
+ config_overrides: Optional[str] = field(
84
+ default=None,
85
+ metadata={
86
+ "help": "Override some existing default config settings when a model is trained from scratch. Example: "
87
+ "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
88
+ },
89
+ )
90
+ config_name: Optional[str] = field(
91
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
92
+ )
93
+ tokenizer_name: Optional[str] = field(
94
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
95
+ )
96
+ cache_dir: Optional[str] = field(
97
+ default=None,
98
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
99
+ )
100
+ use_fast_tokenizer: bool = field(
101
+ default=True,
102
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
103
+ )
104
+ model_revision: str = field(
105
+ default="main",
106
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
107
+ )
108
+ use_auth_token: bool = field(
109
+ default=False,
110
+ metadata={
111
+ "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
112
+ "with private models)."
113
+ },
114
+ )
115
+
116
+ def __post_init__(self):
117
+ if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
118
+ raise ValueError(
119
+ "--config_overrides can't be used in combination with --config_name or --model_name_or_path"
120
+ )
121
+
122
+
123
+ @dataclass
124
+ class DataTrainingArguments:
125
+ """
126
+ Arguments pertaining to what data we are going to input our model for training and eval.
127
+ """
128
+
129
+ dataset_name: Optional[str] = field(
130
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
131
+ )
132
+ dataset_config_name: Optional[str] = field(
133
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
134
+ )
135
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
136
+ validation_file: Optional[str] = field(
137
+ default=None,
138
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
139
+ )
140
+ max_train_samples: Optional[int] = field(
141
+ default=None,
142
+ metadata={
143
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
144
+ "value if set."
145
+ },
146
+ )
147
+ max_eval_samples: Optional[int] = field(
148
+ default=None,
149
+ metadata={
150
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
151
+ "value if set."
152
+ },
153
+ )
154
+
155
+ block_size: Optional[int] = field(
156
+ default=None,
157
+ metadata={
158
+ "help": "Optional input sequence length after tokenization. "
159
+ "The training dataset will be truncated in block of this size for training. "
160
+ "Default to the model max input length for single sentence inputs (take into account special tokens)."
161
+ },
162
+ )
163
+ overwrite_cache: bool = field(
164
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
165
+ )
166
+ validation_split_percentage: Optional[int] = field(
167
+ default=5,
168
+ metadata={
169
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
170
+ },
171
+ )
172
+ preprocessing_num_workers: Optional[int] = field(
173
+ default=None,
174
+ metadata={"help": "The number of processes to use for the preprocessing."},
175
+ )
176
+ keep_linebreaks: bool = field(
177
+ default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
178
+ )
179
+
180
+ #def __post_init__(self):
181
+ # if self.dataset_name is None and self.train_file is None and self.validation_file is None:
182
+ # raise ValueError("Need either a dataset name or a training/validation file.")
183
+ # else:
184
+ # if self.train_file is not None:
185
+ # extension = self.train_file.split(".")[-1]
186
+ # assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
187
+ # if self.validation_file is not None:
188
+ # extension = self.validation_file.split(".")[-1]
189
+ # assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
190
+
191
+
192
+ def main():
193
+ # See all possible arguments in src/transformers/training_args.py
194
+ # or by passing the --help flag to this script.
195
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
196
+
197
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
198
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
199
+ # If we pass only one argument to the script and it's the path to a json file,
200
+ # let's parse it to get our arguments.
201
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
202
+ else:
203
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
204
+
205
+ # Setup logging
206
+ logging.basicConfig(
207
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
208
+ datefmt="%m/%d/%Y %H:%M:%S",
209
+ handlers=[logging.StreamHandler(sys.stdout)],
210
+ )
211
+
212
+ log_level = training_args.get_process_log_level()
213
+ logger.setLevel(log_level)
214
+ datasets.utils.logging.set_verbosity(log_level)
215
+ transformers.utils.logging.set_verbosity(log_level)
216
+ transformers.utils.logging.enable_default_handler()
217
+ transformers.utils.logging.enable_explicit_format()
218
+
219
+ # Log on each process the small summary:
220
+ logger.warning(
221
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
222
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
223
+ )
224
+ logger.info(f"Training/evaluation parameters {training_args}")
225
+
226
+ # Detecting last checkpoint.
227
+ last_checkpoint = None
228
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
229
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
230
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
231
+ raise ValueError(
232
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
233
+ "Use --overwrite_output_dir to overcome."
234
+ )
235
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
236
+ logger.info(
237
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
238
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
239
+ )
240
+
241
+ # Set seed before initializing model.
242
+ set_seed(training_args.seed)
243
+
244
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
245
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
246
+ # (the dataset will be downloaded automatically from the datasets Hub).
247
+ #
248
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
249
+ # 'text' is found. You can easily tweak this behavior (see below).
250
+ #
251
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
252
+ # download the dataset.
253
+
254
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
255
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
256
+
257
+ # Load pretrained model and tokenizer
258
+ #
259
+ # Distributed training:
260
+ # The .from_pretrained methods guarantee that only one local process can concurrently
261
+ # download model & vocab.
262
+
263
+ config_kwargs = {
264
+ "cache_dir": model_args.cache_dir,
265
+ "revision": model_args.model_revision,
266
+ "use_auth_token": True if model_args.use_auth_token else None,
267
+ }
268
+ if model_args.config_name:
269
+ config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
270
+ elif model_args.model_name_or_path:
271
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
272
+ else:
273
+ config = CONFIG_MAPPING[model_args.model_type]()
274
+ logger.warning("You are instantiating a new config instance from scratch.")
275
+ if model_args.config_overrides is not None:
276
+ logger.info(f"Overriding config: {model_args.config_overrides}")
277
+ config.update_from_string(model_args.config_overrides)
278
+
279
+ tokenizer_kwargs = {
280
+ "cache_dir": model_args.cache_dir,
281
+ "use_fast": model_args.use_fast_tokenizer,
282
+ "revision": model_args.model_revision,
283
+ "use_auth_token": True if model_args.use_auth_token else None,
284
+ }
285
+ if model_args.tokenizer_name:
286
+ tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
287
+ elif model_args.model_name_or_path:
288
+ tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
289
+ else:
290
+ raise ValueError(
291
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
292
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
293
+ )
294
+
295
+ if model_args.model_name_or_path:
296
+ model = AutoModelForCausalLM.from_pretrained(
297
+ model_args.model_name_or_path,
298
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
299
+ config=config,
300
+ cache_dir=model_args.cache_dir,
301
+ revision=model_args.model_revision,
302
+ use_auth_token=True if model_args.use_auth_token else None,
303
+ )
304
+ else:
305
+ model = AutoModelForCausalLM.from_config(config)
306
+ n_params = sum(dict((p.data_ptr(), p.numel()) for p in model.parameters()).values())
307
+ logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params")
308
+
309
+ model.resize_token_embeddings(len(tokenizer))
310
+
311
+ train_dataset = load_from_disk('dataset/train2')
312
+ eval_dataset = load_from_disk('dataset/eval2')
313
+
314
+ # Initialize our Trainer
315
+ trainer = Trainer(
316
+ model=model,
317
+ args=training_args,
318
+ train_dataset=train_dataset if training_args.do_train else None,
319
+ eval_dataset=eval_dataset if training_args.do_eval else None,
320
+ tokenizer=tokenizer,
321
+ # Data collator will default to DataCollatorWithPadding, so we change it.
322
+ data_collator=default_data_collator,
323
+ )
324
+
325
+ # Training
326
+ if training_args.do_train:
327
+ checkpoint = None
328
+ if training_args.resume_from_checkpoint is not None:
329
+ checkpoint = training_args.resume_from_checkpoint
330
+ elif last_checkpoint is not None:
331
+ checkpoint = last_checkpoint
332
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
333
+ trainer.save_model() # Saves the tokenizer too for easy upload
334
+
335
+ metrics = train_result.metrics
336
+
337
+ max_train_samples = (
338
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
339
+ )
340
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
341
+
342
+ trainer.log_metrics("train", metrics)
343
+ trainer.save_metrics("train", metrics)
344
+ trainer.save_state()
345
+
346
+ # Evaluation
347
+ if training_args.do_eval:
348
+ logger.info("*** Evaluate ***")
349
+
350
+ metrics = trainer.evaluate()
351
+
352
+ max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
353
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
354
+ try:
355
+ perplexity = math.exp(metrics["eval_loss"])
356
+ except OverflowError:
357
+ perplexity = float("inf")
358
+ metrics["perplexity"] = perplexity
359
+
360
+ trainer.log_metrics("eval", metrics)
361
+ trainer.save_metrics("eval", metrics)
362
+
363
+ kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
364
+ if data_args.dataset_name is not None:
365
+ kwargs["dataset_tags"] = data_args.dataset_name
366
+ if data_args.dataset_config_name is not None:
367
+ kwargs["dataset_args"] = data_args.dataset_config_name
368
+ kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
369
+ else:
370
+ kwargs["dataset"] = data_args.dataset_name
371
+
372
+ if training_args.push_to_hub:
373
+ trainer.push_to_hub(**kwargs)
374
+ else:
375
+ trainer.create_model_card(**kwargs)
376
+
377
+
378
+ def _mp_fn(index):
379
+ # For xla_spawn (TPUs)
380
+ main()
381
+
382
+
383
+ if __name__ == "__main__":
384
+ main()
385
+