transformers

Форк
0
670 строк · 28.2 Кб
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=text-generation
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
import warnings
29
from dataclasses import dataclass, field
30
from itertools import chain
31
from typing import Optional
32

33
import datasets
34
import evaluate
35
import torch
36
from datasets import load_dataset
37

38
import transformers
39
from transformers import (
40
    CONFIG_MAPPING,
41
    MODEL_FOR_CAUSAL_LM_MAPPING,
42
    AutoConfig,
43
    AutoModelForCausalLM,
44
    AutoTokenizer,
45
    HfArgumentParser,
46
    Trainer,
47
    TrainingArguments,
48
    default_data_collator,
49
    is_torch_tpu_available,
50
    set_seed,
51
)
52
from transformers.testing_utils import CaptureLogger
53
from transformers.trainer_utils import get_last_checkpoint
54
from transformers.utils import check_min_version, send_example_telemetry
55
from transformers.utils.versions import require_version
56

57

58
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
59
check_min_version("4.39.0.dev0")
60

61
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
62

63
logger = logging.getLogger(__name__)
64

65

66
MODEL_CONFIG_CLASSES = list(MODEL_FOR_CAUSAL_LM_MAPPING.keys())
67
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
68

69

70
@dataclass
71
class ModelArguments:
72
    """
73
    Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
74
    """
75

76
    model_name_or_path: Optional[str] = field(
77
        default=None,
78
        metadata={
79
            "help": (
80
                "The model checkpoint for weights initialization. Don't set if you want to train a model from scratch."
81
            )
82
        },
83
    )
84
    model_type: Optional[str] = field(
85
        default=None,
86
        metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
87
    )
88
    config_overrides: Optional[str] = field(
89
        default=None,
90
        metadata={
91
            "help": (
92
                "Override some existing default config settings when a model is trained from scratch. Example: "
93
                "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
94
            )
95
        },
96
    )
97
    config_name: Optional[str] = field(
98
        default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
99
    )
100
    tokenizer_name: Optional[str] = field(
101
        default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
102
    )
103
    cache_dir: Optional[str] = field(
104
        default=None,
105
        metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
106
    )
107
    use_fast_tokenizer: bool = field(
108
        default=True,
109
        metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
110
    )
111
    model_revision: str = field(
112
        default="main",
113
        metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
114
    )
115
    token: str = field(
116
        default=None,
117
        metadata={
118
            "help": (
119
                "The token to use as HTTP bearer authorization for remote files. If not specified, will use the token "
120
                "generated when running `huggingface-cli login` (stored in `~/.huggingface`)."
121
            )
122
        },
123
    )
124
    use_auth_token: bool = field(
125
        default=None,
126
        metadata={
127
            "help": "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead."
128
        },
129
    )
130
    trust_remote_code: bool = field(
131
        default=False,
132
        metadata={
133
            "help": (
134
                "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option "
135
                "should only be set to `True` for repositories you trust and in which you have read the code, as it will "
136
                "execute code present on the Hub on your local machine."
137
            )
138
        },
139
    )
140
    torch_dtype: Optional[str] = field(
141
        default=None,
142
        metadata={
143
            "help": (
144
                "Override the default `torch.dtype` and load the model under this dtype. If `auto` is passed, the "
145
                "dtype will be automatically derived from the model's weights."
146
            ),
147
            "choices": ["auto", "bfloat16", "float16", "float32"],
148
        },
149
    )
150
    low_cpu_mem_usage: bool = field(
151
        default=False,
152
        metadata={
153
            "help": (
154
                "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded. "
155
                "set True will benefit LLM loading time and RAM consumption."
156
            )
157
        },
158
    )
159

160
    def __post_init__(self):
161
        if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
162
            raise ValueError(
163
                "--config_overrides can't be used in combination with --config_name or --model_name_or_path"
164
            )
165

166

167
@dataclass
168
class DataTrainingArguments:
169
    """
170
    Arguments pertaining to what data we are going to input our model for training and eval.
171
    """
172

173
    dataset_name: Optional[str] = field(
174
        default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
175
    )
176
    dataset_config_name: Optional[str] = field(
177
        default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
178
    )
179
    train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
180
    validation_file: Optional[str] = field(
181
        default=None,
182
        metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
183
    )
184
    max_train_samples: Optional[int] = field(
185
        default=None,
186
        metadata={
187
            "help": (
188
                "For debugging purposes or quicker training, truncate the number of training examples to this "
189
                "value if set."
190
            )
191
        },
192
    )
193
    max_eval_samples: Optional[int] = field(
194
        default=None,
195
        metadata={
196
            "help": (
197
                "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
198
                "value if set."
199
            )
200
        },
201
    )
202
    streaming: bool = field(default=False, metadata={"help": "Enable streaming mode"})
203
    block_size: Optional[int] = field(
204
        default=None,
205
        metadata={
206
            "help": (
207
                "Optional input sequence length after tokenization. "
208
                "The training dataset will be truncated in block of this size for training. "
209
                "Default to the model max input length for single sentence inputs (take into account special tokens)."
210
            )
211
        },
212
    )
213
    overwrite_cache: bool = field(
214
        default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
215
    )
216
    validation_split_percentage: Optional[int] = field(
217
        default=5,
218
        metadata={
219
            "help": "The percentage of the train set used as validation set in case there's no validation split"
220
        },
221
    )
222
    preprocessing_num_workers: Optional[int] = field(
223
        default=None,
224
        metadata={"help": "The number of processes to use for the preprocessing."},
225
    )
226
    keep_linebreaks: bool = field(
227
        default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
228
    )
229

230
    def __post_init__(self):
231
        if self.streaming:
232
            require_version("datasets>=2.0.0", "The streaming feature requires `datasets>=2.0.0`")
233

234
        if self.dataset_name is None and self.train_file is None and self.validation_file is None:
235
            raise ValueError("Need either a dataset name or a training/validation file.")
236
        else:
237
            if self.train_file is not None:
238
                extension = self.train_file.split(".")[-1]
239
                assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
240
            if self.validation_file is not None:
241
                extension = self.validation_file.split(".")[-1]
242
                assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
243

244

245
def main():
246
    # See all possible arguments in src/transformers/training_args.py
247
    # or by passing the --help flag to this script.
248
    # We now keep distinct sets of args, for a cleaner separation of concerns.
249

250
    parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
251
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
252
        # If we pass only one argument to the script and it's the path to a json file,
253
        # let's parse it to get our arguments.
254
        model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
255
    else:
256
        model_args, data_args, training_args = parser.parse_args_into_dataclasses()
257

258
    if model_args.use_auth_token is not None:
259
        warnings.warn(
260
            "The `use_auth_token` argument is deprecated and will be removed in v4.34. Please use `token` instead.",
261
            FutureWarning,
262
        )
263
        if model_args.token is not None:
264
            raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.")
265
        model_args.token = model_args.use_auth_token
266

267
    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
268
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
269
    send_example_telemetry("run_clm", model_args, data_args)
270

271
    # Setup logging
272
    logging.basicConfig(
273
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
274
        datefmt="%m/%d/%Y %H:%M:%S",
275
        handlers=[logging.StreamHandler(sys.stdout)],
276
    )
277

278
    if training_args.should_log:
279
        # The default of training_args.log_level is passive, so we set log level at info here to have that default.
280
        transformers.utils.logging.set_verbosity_info()
281

282
    log_level = training_args.get_process_log_level()
283
    logger.setLevel(log_level)
284
    datasets.utils.logging.set_verbosity(log_level)
285
    transformers.utils.logging.set_verbosity(log_level)
286
    transformers.utils.logging.enable_default_handler()
287
    transformers.utils.logging.enable_explicit_format()
288

289
    # Log on each process the small summary:
290
    logger.warning(
291
        f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, "
292
        + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}"
293
    )
294
    logger.info(f"Training/evaluation parameters {training_args}")
295

296
    # Detecting last checkpoint.
297
    last_checkpoint = None
298
    if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
299
        last_checkpoint = get_last_checkpoint(training_args.output_dir)
300
        if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
301
            raise ValueError(
302
                f"Output directory ({training_args.output_dir}) already exists and is not empty. "
303
                "Use --overwrite_output_dir to overcome."
304
            )
305
        elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
306
            logger.info(
307
                f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
308
                "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
309
            )
310

311
    # Set seed before initializing model.
312
    set_seed(training_args.seed)
313

314
    # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
315
    # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
316
    # (the dataset will be downloaded automatically from the datasets Hub).
317
    #
318
    # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
319
    # 'text' is found. You can easily tweak this behavior (see below).
320
    #
321
    # In distributed training, the load_dataset function guarantee that only one local process can concurrently
322
    # download the dataset.
323
    if data_args.dataset_name is not None:
324
        # Downloading and loading a dataset from the hub.
325
        raw_datasets = load_dataset(
326
            data_args.dataset_name,
327
            data_args.dataset_config_name,
328
            cache_dir=model_args.cache_dir,
329
            token=model_args.token,
330
            streaming=data_args.streaming,
331
        )
332
        if "validation" not in raw_datasets.keys():
333
            raw_datasets["validation"] = load_dataset(
334
                data_args.dataset_name,
335
                data_args.dataset_config_name,
336
                split=f"train[:{data_args.validation_split_percentage}%]",
337
                cache_dir=model_args.cache_dir,
338
                token=model_args.token,
339
                streaming=data_args.streaming,
340
            )
341
            raw_datasets["train"] = load_dataset(
342
                data_args.dataset_name,
343
                data_args.dataset_config_name,
344
                split=f"train[{data_args.validation_split_percentage}%:]",
345
                cache_dir=model_args.cache_dir,
346
                token=model_args.token,
347
                streaming=data_args.streaming,
348
            )
349
    else:
350
        data_files = {}
351
        dataset_args = {}
352
        if data_args.train_file is not None:
353
            data_files["train"] = data_args.train_file
354
        if data_args.validation_file is not None:
355
            data_files["validation"] = data_args.validation_file
356
        extension = (
357
            data_args.train_file.split(".")[-1]
358
            if data_args.train_file is not None
359
            else data_args.validation_file.split(".")[-1]
360
        )
361
        if extension == "txt":
362
            extension = "text"
363
            dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
364
        raw_datasets = load_dataset(
365
            extension,
366
            data_files=data_files,
367
            cache_dir=model_args.cache_dir,
368
            token=model_args.token,
369
            **dataset_args,
370
        )
371
        # If no validation data is there, validation_split_percentage will be used to divide the dataset.
372
        if "validation" not in raw_datasets.keys():
373
            raw_datasets["validation"] = load_dataset(
374
                extension,
375
                data_files=data_files,
376
                split=f"train[:{data_args.validation_split_percentage}%]",
377
                cache_dir=model_args.cache_dir,
378
                token=model_args.token,
379
                **dataset_args,
380
            )
381
            raw_datasets["train"] = load_dataset(
382
                extension,
383
                data_files=data_files,
384
                split=f"train[{data_args.validation_split_percentage}%:]",
385
                cache_dir=model_args.cache_dir,
386
                token=model_args.token,
387
                **dataset_args,
388
            )
389

390
    # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
391
    # https://huggingface.co/docs/datasets/loading_datasets.
392

393
    # Load pretrained model and tokenizer
394
    #
395
    # Distributed training:
396
    # The .from_pretrained methods guarantee that only one local process can concurrently
397
    # download model & vocab.
398

399
    config_kwargs = {
400
        "cache_dir": model_args.cache_dir,
401
        "revision": model_args.model_revision,
402
        "token": model_args.token,
403
        "trust_remote_code": model_args.trust_remote_code,
404
    }
405
    if model_args.config_name:
406
        config = AutoConfig.from_pretrained(model_args.config_name, **config_kwargs)
407
    elif model_args.model_name_or_path:
408
        config = AutoConfig.from_pretrained(model_args.model_name_or_path, **config_kwargs)
409
    else:
410
        config = CONFIG_MAPPING[model_args.model_type]()
411
        logger.warning("You are instantiating a new config instance from scratch.")
412
        if model_args.config_overrides is not None:
413
            logger.info(f"Overriding config: {model_args.config_overrides}")
414
            config.update_from_string(model_args.config_overrides)
415
            logger.info(f"New config: {config}")
416

417
    tokenizer_kwargs = {
418
        "cache_dir": model_args.cache_dir,
419
        "use_fast": model_args.use_fast_tokenizer,
420
        "revision": model_args.model_revision,
421
        "token": model_args.token,
422
        "trust_remote_code": model_args.trust_remote_code,
423
    }
424
    if model_args.tokenizer_name:
425
        tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, **tokenizer_kwargs)
426
    elif model_args.model_name_or_path:
427
        tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, **tokenizer_kwargs)
428
    else:
429
        raise ValueError(
430
            "You are instantiating a new tokenizer from scratch. This is not supported by this script. "
431
            "You can do it from another script, save it, and load it from here, using --tokenizer_name."
432
        )
433

434
    if model_args.model_name_or_path:
435
        torch_dtype = (
436
            model_args.torch_dtype
437
            if model_args.torch_dtype in ["auto", None]
438
            else getattr(torch, model_args.torch_dtype)
439
        )
440
        model = AutoModelForCausalLM.from_pretrained(
441
            model_args.model_name_or_path,
442
            from_tf=bool(".ckpt" in model_args.model_name_or_path),
443
            config=config,
444
            cache_dir=model_args.cache_dir,
445
            revision=model_args.model_revision,
446
            token=model_args.token,
447
            trust_remote_code=model_args.trust_remote_code,
448
            torch_dtype=torch_dtype,
449
            low_cpu_mem_usage=model_args.low_cpu_mem_usage,
450
        )
451
    else:
452
        model = AutoModelForCausalLM.from_config(config, trust_remote_code=model_args.trust_remote_code)
453
        n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values())
454
        logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params")
455

456
    # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
457
    # on a small vocab and want a smaller embedding size, remove this test.
458
    embedding_size = model.get_input_embeddings().weight.shape[0]
459
    if len(tokenizer) > embedding_size:
460
        model.resize_token_embeddings(len(tokenizer))
461

462
    # Preprocessing the datasets.
463
    # First we tokenize all the texts.
464
    if training_args.do_train:
465
        column_names = list(raw_datasets["train"].features)
466
    else:
467
        column_names = list(raw_datasets["validation"].features)
468
    text_column_name = "text" if "text" in column_names else column_names[0]
469

470
    # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function
471
    tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
472

473
    def tokenize_function(examples):
474
        with CaptureLogger(tok_logger) as cl:
475
            output = tokenizer(examples[text_column_name])
476
        # clm input could be much much longer than block_size
477
        if "Token indices sequence length is longer than the" in cl.out:
478
            tok_logger.warning(
479
                "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits"
480
                " before being passed to the model."
481
            )
482
        return output
483

484
    with training_args.main_process_first(desc="dataset map tokenization"):
485
        if not data_args.streaming:
486
            tokenized_datasets = raw_datasets.map(
487
                tokenize_function,
488
                batched=True,
489
                num_proc=data_args.preprocessing_num_workers,
490
                remove_columns=column_names,
491
                load_from_cache_file=not data_args.overwrite_cache,
492
                desc="Running tokenizer on dataset",
493
            )
494
        else:
495
            tokenized_datasets = raw_datasets.map(
496
                tokenize_function,
497
                batched=True,
498
                remove_columns=column_names,
499
            )
500
    if hasattr(config, "max_position_embeddings"):
501
        max_pos_embeddings = config.max_position_embeddings
502
    else:
503
        # Define a default value if the attribute is missing in the config.
504
        max_pos_embeddings = 1024
505

506
    if data_args.block_size is None:
507
        block_size = tokenizer.model_max_length
508
        if block_size > max_pos_embeddings:
509
            logger.warning(
510
                f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
511
                f"Using block_size={min(1024, max_pos_embeddings)} instead. You can change that default value by passing --block_size xxx."
512
            )
513
            if max_pos_embeddings > 0:
514
                block_size = min(1024, max_pos_embeddings)
515
            else:
516
                block_size = 1024
517
    else:
518
        if data_args.block_size > tokenizer.model_max_length:
519
            logger.warning(
520
                f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model "
521
                f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
522
            )
523
        block_size = min(data_args.block_size, tokenizer.model_max_length)
524

525
    # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
526
    def group_texts(examples):
527
        # Concatenate all texts.
528
        concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
529
        total_length = len(concatenated_examples[list(examples.keys())[0]])
530
        # We drop the small remainder, and if the total_length < block_size  we exclude this batch and return an empty dict.
531
        # We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
532
        total_length = (total_length // block_size) * block_size
533
        # Split by chunks of max_len.
534
        result = {
535
            k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
536
            for k, t in concatenated_examples.items()
537
        }
538
        result["labels"] = result["input_ids"].copy()
539
        return result
540

541
    # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
542
    # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
543
    # to preprocess.
544
    #
545
    # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
546
    # https://huggingface.co/docs/datasets/process#map
547

548
    with training_args.main_process_first(desc="grouping texts together"):
549
        if not data_args.streaming:
550
            lm_datasets = tokenized_datasets.map(
551
                group_texts,
552
                batched=True,
553
                num_proc=data_args.preprocessing_num_workers,
554
                load_from_cache_file=not data_args.overwrite_cache,
555
                desc=f"Grouping texts in chunks of {block_size}",
556
            )
557
        else:
558
            lm_datasets = tokenized_datasets.map(
559
                group_texts,
560
                batched=True,
561
            )
562

563
    if training_args.do_train:
564
        if "train" not in tokenized_datasets:
565
            raise ValueError("--do_train requires a train dataset")
566
        train_dataset = lm_datasets["train"]
567
        if data_args.max_train_samples is not None:
568
            max_train_samples = min(len(train_dataset), data_args.max_train_samples)
569
            train_dataset = train_dataset.select(range(max_train_samples))
570

571
    if training_args.do_eval:
572
        if "validation" not in tokenized_datasets:
573
            raise ValueError("--do_eval requires a validation dataset")
574
        eval_dataset = lm_datasets["validation"]
575
        if data_args.max_eval_samples is not None:
576
            max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
577
            eval_dataset = eval_dataset.select(range(max_eval_samples))
578

579
        def preprocess_logits_for_metrics(logits, labels):
580
            if isinstance(logits, tuple):
581
                # Depending on the model and config, logits may contain extra tensors,
582
                # like past_key_values, but logits always come first
583
                logits = logits[0]
584
            return logits.argmax(dim=-1)
585

586
        metric = evaluate.load("accuracy", cache_dir=model_args.cache_dir)
587

588
        def compute_metrics(eval_preds):
589
            preds, labels = eval_preds
590
            # preds have the same shape as the labels, after the argmax(-1) has been calculated
591
            # by preprocess_logits_for_metrics but we need to shift the labels
592
            labels = labels[:, 1:].reshape(-1)
593
            preds = preds[:, :-1].reshape(-1)
594
            return metric.compute(predictions=preds, references=labels)
595

596
    # Initialize our Trainer
597
    trainer = Trainer(
598
        model=model,
599
        args=training_args,
600
        train_dataset=train_dataset if training_args.do_train else None,
601
        eval_dataset=eval_dataset if training_args.do_eval else None,
602
        tokenizer=tokenizer,
603
        # Data collator will default to DataCollatorWithPadding, so we change it.
604
        data_collator=default_data_collator,
605
        compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None,
606
        preprocess_logits_for_metrics=preprocess_logits_for_metrics
607
        if training_args.do_eval and not is_torch_tpu_available()
608
        else None,
609
    )
610

611
    # Training
612
    if training_args.do_train:
613
        checkpoint = None
614
        if training_args.resume_from_checkpoint is not None:
615
            checkpoint = training_args.resume_from_checkpoint
616
        elif last_checkpoint is not None:
617
            checkpoint = last_checkpoint
618
        train_result = trainer.train(resume_from_checkpoint=checkpoint)
619
        trainer.save_model()  # Saves the tokenizer too for easy upload
620

621
        metrics = train_result.metrics
622

623
        max_train_samples = (
624
            data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
625
        )
626
        metrics["train_samples"] = min(max_train_samples, len(train_dataset))
627

628
        trainer.log_metrics("train", metrics)
629
        trainer.save_metrics("train", metrics)
630
        trainer.save_state()
631

632
    # Evaluation
633
    if training_args.do_eval:
634
        logger.info("*** Evaluate ***")
635

636
        metrics = trainer.evaluate()
637

638
        max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
639
        metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
640
        try:
641
            perplexity = math.exp(metrics["eval_loss"])
642
        except OverflowError:
643
            perplexity = float("inf")
644
        metrics["perplexity"] = perplexity
645

646
        trainer.log_metrics("eval", metrics)
647
        trainer.save_metrics("eval", metrics)
648

649
    kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"}
650
    if data_args.dataset_name is not None:
651
        kwargs["dataset_tags"] = data_args.dataset_name
652
        if data_args.dataset_config_name is not None:
653
            kwargs["dataset_args"] = data_args.dataset_config_name
654
            kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}"
655
        else:
656
            kwargs["dataset"] = data_args.dataset_name
657

658
    if training_args.push_to_hub:
659
        trainer.push_to_hub(**kwargs)
660
    else:
661
        trainer.create_model_card(**kwargs)
662

663

664
def _mp_fn(index):
665
    # For xla_spawn (TPUs)
666
    main()
667

668

669
if __name__ == "__main__":
670
    main()
671

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.