w11wo commited on
Commit
4296aa1
1 Parent(s): e33b58c

run scripts

Browse files
Files changed (2) hide show
  1. run.sh +21 -0
  2. run_mlm_flax.py +658 -0
run.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ python3 run_mlm_flax.py \
3
+ --output_dir="./" \
4
+ --model_type="roberta" \
5
+ --config_name="./" \
6
+ --tokenizer_name="./" \
7
+ --dataset_name="mc4" \
8
+ --dataset_config_name="id" \
9
+ --max_seq_length="128" \
10
+ --weight_decay="0.01" \
11
+ --per_device_train_batch_size="256" \
12
+ --per_device_eval_batch_size="256" \
13
+ --learning_rate="3e-4" \
14
+ --warmup_steps="1000" \
15
+ --overwrite_output_dir \
16
+ --pad_to_max_length \
17
+ --num_train_epochs="18" \
18
+ --adam_beta1="0.9" \
19
+ --adam_beta2="0.98" \
20
+ --push_to_hub
21
+
run_mlm_flax.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace 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 masked language modeling (BERT, ALBERT, RoBERTa...) with whole word masking on a
18
+ text file or a dataset.
19
+
20
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
21
+ https://huggingface.co/models?filter=masked-lm
22
+ """
23
+ import logging
24
+ import os
25
+ import sys
26
+ import time
27
+ from dataclasses import dataclass, field
28
+
29
+ # You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
30
+ from pathlib import Path
31
+ from typing import Dict, List, Optional, Tuple
32
+
33
+ import numpy as np
34
+ from datasets import load_dataset
35
+ from tqdm import tqdm
36
+
37
+ import flax
38
+ import jax
39
+ import jax.numpy as jnp
40
+ import optax
41
+ from flax import jax_utils, traverse_util
42
+ from flax.training import train_state
43
+ from flax.training.common_utils import get_metrics, onehot, shard
44
+ from transformers import (
45
+ CONFIG_MAPPING,
46
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
47
+ AutoConfig,
48
+ AutoTokenizer,
49
+ FlaxAutoModelForMaskedLM,
50
+ HfArgumentParser,
51
+ PreTrainedTokenizerBase,
52
+ TensorType,
53
+ TrainingArguments,
54
+ is_tensorboard_available,
55
+ set_seed,
56
+ )
57
+
58
+
59
+ # Cache the result
60
+ has_tensorboard = is_tensorboard_available()
61
+ if has_tensorboard:
62
+ try:
63
+ from flax.metrics.tensorboard import SummaryWriter
64
+ except ImportError as ie:
65
+ has_tensorboard = False
66
+ print(f"Unable to display metrics through TensorBoard because some package are not installed: {ie}")
67
+
68
+ else:
69
+ print(
70
+ "Unable to display metrics through TensorBoard because the package is not installed: "
71
+ "Please run pip install tensorboard to enable."
72
+ )
73
+
74
+
75
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
76
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
77
+
78
+
79
+ @dataclass
80
+ class ModelArguments:
81
+ """
82
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
83
+ """
84
+
85
+ model_name_or_path: Optional[str] = field(
86
+ default=None,
87
+ metadata={
88
+ "help": "The model checkpoint for weights initialization."
89
+ "Don't set if you want to train a model from scratch."
90
+ },
91
+ )
92
+ model_type: Optional[str] = field(
93
+ default=None,
94
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
95
+ )
96
+ config_name: Optional[str] = field(
97
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
98
+ )
99
+ tokenizer_name: Optional[str] = field(
100
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
101
+ )
102
+ cache_dir: Optional[str] = field(
103
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
104
+ )
105
+ use_fast_tokenizer: bool = field(
106
+ default=True,
107
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
108
+ )
109
+ dtype: Optional[str] = field(
110
+ default="float32",
111
+ metadata={
112
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
113
+ },
114
+ )
115
+
116
+
117
+ @dataclass
118
+ class DataTrainingArguments:
119
+ """
120
+ Arguments pertaining to what data we are going to input our model for training and eval.
121
+ """
122
+
123
+ dataset_name: Optional[str] = field(
124
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
125
+ )
126
+ dataset_config_name: Optional[str] = field(
127
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
128
+ )
129
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
130
+ validation_file: Optional[str] = field(
131
+ default=None,
132
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
133
+ )
134
+ train_ref_file: Optional[str] = field(
135
+ default=None,
136
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
137
+ )
138
+ validation_ref_file: Optional[str] = field(
139
+ default=None,
140
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
141
+ )
142
+ overwrite_cache: bool = field(
143
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
144
+ )
145
+ validation_split_percentage: Optional[int] = field(
146
+ default=5,
147
+ metadata={
148
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
149
+ },
150
+ )
151
+ max_seq_length: Optional[int] = field(
152
+ default=None,
153
+ metadata={
154
+ "help": "The maximum total input sequence length after tokenization. Sequences longer "
155
+ "than this will be truncated. Default to the max input length of the model."
156
+ },
157
+ )
158
+ preprocessing_num_workers: Optional[int] = field(
159
+ default=None,
160
+ metadata={"help": "The number of processes to use for the preprocessing."},
161
+ )
162
+ mlm_probability: float = field(
163
+ default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
164
+ )
165
+ pad_to_max_length: bool = field(
166
+ default=False,
167
+ metadata={
168
+ "help": "Whether to pad all samples to `max_seq_length`. "
169
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
170
+ },
171
+ )
172
+ line_by_line: bool = field(
173
+ default=False,
174
+ metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
175
+ )
176
+
177
+ def __post_init__(self):
178
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
179
+ raise ValueError("Need either a dataset name or a training/validation file.")
180
+ else:
181
+ if self.train_file is not None:
182
+ extension = self.train_file.split(".")[-1]
183
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
184
+ if self.validation_file is not None:
185
+ extension = self.validation_file.split(".")[-1]
186
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
187
+
188
+
189
+ @flax.struct.dataclass
190
+ class FlaxDataCollatorForLanguageModeling:
191
+ """
192
+ Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
193
+ are not all of the same length.
194
+
195
+ Args:
196
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
197
+ The tokenizer used for encoding the data.
198
+ mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
199
+ The probability with which to (randomly) mask tokens in the input.
200
+
201
+ .. note::
202
+
203
+ For best performance, this data collator should be used with a dataset having items that are dictionaries or
204
+ BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
205
+ :class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
206
+ argument :obj:`return_special_tokens_mask=True`.
207
+ """
208
+
209
+ tokenizer: PreTrainedTokenizerBase
210
+ mlm_probability: float = 0.15
211
+
212
+ def __post_init__(self):
213
+ if self.tokenizer.mask_token is None:
214
+ raise ValueError(
215
+ "This tokenizer does not have a mask token which is necessary for masked language modeling. "
216
+ "You should pass `mlm=False` to train on causal language modeling instead."
217
+ )
218
+
219
+ def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
220
+ # Handle dict or lists with proper padding and conversion to tensor.
221
+ batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
222
+
223
+ # If special token mask has been preprocessed, pop it from the dict.
224
+ special_tokens_mask = batch.pop("special_tokens_mask", None)
225
+
226
+ batch["input_ids"], batch["labels"] = self.mask_tokens(
227
+ batch["input_ids"], special_tokens_mask=special_tokens_mask
228
+ )
229
+ return batch
230
+
231
+ def mask_tokens(
232
+ self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
233
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
234
+ """
235
+ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
236
+ """
237
+ labels = inputs.copy()
238
+ # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
239
+ probability_matrix = np.full(labels.shape, self.mlm_probability)
240
+ special_tokens_mask = special_tokens_mask.astype("bool")
241
+
242
+ probability_matrix[special_tokens_mask] = 0.0
243
+ masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
244
+ labels[~masked_indices] = -100 # We only compute loss on masked tokens
245
+
246
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
247
+ indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
248
+ inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
249
+
250
+ # 10% of the time, we replace masked input tokens with random word
251
+ indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
252
+ indices_random &= masked_indices & ~indices_replaced
253
+
254
+ random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
255
+ inputs[indices_random] = random_words[indices_random]
256
+
257
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
258
+ return inputs, labels
259
+
260
+
261
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
262
+ num_samples = len(samples_idx)
263
+ samples_to_remove = num_samples % batch_size
264
+
265
+ if samples_to_remove != 0:
266
+ samples_idx = samples_idx[:-samples_to_remove]
267
+ sections_split = num_samples // batch_size
268
+ batch_idx = np.split(samples_idx, sections_split)
269
+ return batch_idx
270
+
271
+
272
+ def write_metric(summary_writer, train_metrics, eval_metrics, train_time, step):
273
+ summary_writer.scalar("train_time", train_time, step)
274
+
275
+ train_metrics = get_metrics(train_metrics)
276
+ for key, vals in train_metrics.items():
277
+ tag = f"train_{key}"
278
+ for i, val in enumerate(vals):
279
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
280
+
281
+ for metric_name, value in eval_metrics.items():
282
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
283
+
284
+
285
+ if __name__ == "__main__":
286
+ # See all possible arguments in src/transformers/training_args.py
287
+ # or by passing the --help flag to this script.
288
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
289
+
290
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
291
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
292
+ # If we pass only one argument to the script and it's the path to a json file,
293
+ # let's parse it to get our arguments.
294
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
295
+ else:
296
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
297
+
298
+ if (
299
+ os.path.exists(training_args.output_dir)
300
+ and os.listdir(training_args.output_dir)
301
+ and training_args.do_train
302
+ and not training_args.overwrite_output_dir
303
+ ):
304
+ raise ValueError(
305
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
306
+ "Use --overwrite_output_dir to overcome."
307
+ )
308
+
309
+ # Setup logging
310
+ logging.basicConfig(
311
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
312
+ level="NOTSET",
313
+ datefmt="[%X]",
314
+ )
315
+
316
+ # Log on each process the small summary:
317
+ logger = logging.getLogger(__name__)
318
+ logger.warning(
319
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
320
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
321
+ )
322
+
323
+ # Set the verbosity to info of the Transformers logger (on main process only):
324
+ logger.info(f"Training/evaluation parameters {training_args}")
325
+
326
+ # Set seed before initializing model.
327
+ set_seed(training_args.seed)
328
+
329
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
330
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
331
+ # (the dataset will be downloaded automatically from the datasets Hub).
332
+ #
333
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
334
+ # 'text' is found. You can easily tweak this behavior (see below).
335
+ #
336
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
337
+ # download the dataset.
338
+ if data_args.dataset_name is not None:
339
+ # Downloading and loading a dataset from the hub.
340
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
341
+
342
+ if "validation" not in datasets.keys():
343
+ datasets["validation"] = load_dataset(
344
+ data_args.dataset_name,
345
+ data_args.dataset_config_name,
346
+ split=f"train[:{data_args.validation_split_percentage}%]",
347
+ cache_dir=model_args.cache_dir,
348
+ )
349
+ datasets["train"] = load_dataset(
350
+ data_args.dataset_name,
351
+ data_args.dataset_config_name,
352
+ split=f"train[{data_args.validation_split_percentage}%:]",
353
+ cache_dir=model_args.cache_dir,
354
+ )
355
+ else:
356
+ data_files = {}
357
+ if data_args.train_file is not None:
358
+ data_files["train"] = data_args.train_file
359
+ if data_args.validation_file is not None:
360
+ data_files["validation"] = data_args.validation_file
361
+ extension = data_args.train_file.split(".")[-1]
362
+ if extension == "txt":
363
+ extension = "text"
364
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
365
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
366
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
367
+
368
+ # Load pretrained model and tokenizer
369
+
370
+ # Distributed training:
371
+ # The .from_pretrained methods guarantee that only one local process can concurrently
372
+ # download model & vocab.
373
+ if model_args.config_name:
374
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
375
+ elif model_args.model_name_or_path:
376
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
377
+ else:
378
+ config = CONFIG_MAPPING[model_args.model_type]()
379
+ logger.warning("You are instantiating a new config instance from scratch.")
380
+
381
+ if model_args.tokenizer_name:
382
+ tokenizer = AutoTokenizer.from_pretrained(
383
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
384
+ )
385
+ elif model_args.model_name_or_path:
386
+ tokenizer = AutoTokenizer.from_pretrained(
387
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
388
+ )
389
+ else:
390
+ raise ValueError(
391
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
392
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
393
+ )
394
+
395
+ # Preprocessing the datasets.
396
+ # First we tokenize all the texts.
397
+ if training_args.do_train:
398
+ column_names = datasets["train"].column_names
399
+ else:
400
+ column_names = datasets["validation"].column_names
401
+ text_column_name = "text" if "text" in column_names else column_names[0]
402
+
403
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
404
+
405
+ if data_args.line_by_line:
406
+ # When using line_by_line, we just tokenize each nonempty line.
407
+ padding = "max_length" if data_args.pad_to_max_length else False
408
+
409
+ def tokenize_function(examples):
410
+ # Remove empty lines
411
+ examples = [line for line in examples if len(line) > 0 and not line.isspace()]
412
+ return tokenizer(
413
+ examples,
414
+ return_special_tokens_mask=True,
415
+ padding=padding,
416
+ truncation=True,
417
+ max_length=max_seq_length,
418
+ )
419
+
420
+ tokenized_datasets = datasets.map(
421
+ tokenize_function,
422
+ input_columns=[text_column_name],
423
+ batched=True,
424
+ num_proc=data_args.preprocessing_num_workers,
425
+ remove_columns=column_names,
426
+ load_from_cache_file=not data_args.overwrite_cache,
427
+ )
428
+
429
+ else:
430
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
431
+ # We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
432
+ # efficient when it receives the `special_tokens_mask`.
433
+ def tokenize_function(examples):
434
+ return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
435
+
436
+ tokenized_datasets = datasets.map(
437
+ tokenize_function,
438
+ batched=True,
439
+ num_proc=data_args.preprocessing_num_workers,
440
+ remove_columns=column_names,
441
+ load_from_cache_file=not data_args.overwrite_cache,
442
+ )
443
+
444
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of
445
+ # max_seq_length.
446
+ def group_texts(examples):
447
+ # Concatenate all texts.
448
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
449
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
450
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
451
+ # customize this part to your needs.
452
+ total_length = (total_length // max_seq_length) * max_seq_length
453
+ # Split by chunks of max_len.
454
+ result = {
455
+ k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
456
+ for k, t in concatenated_examples.items()
457
+ }
458
+ return result
459
+
460
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
461
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
462
+ # might be slower to preprocess.
463
+ #
464
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
465
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
466
+ tokenized_datasets = tokenized_datasets.map(
467
+ group_texts,
468
+ batched=True,
469
+ num_proc=data_args.preprocessing_num_workers,
470
+ load_from_cache_file=not data_args.overwrite_cache,
471
+ )
472
+
473
+ # Enable tensorboard only on the master node
474
+ if has_tensorboard and jax.process_index() == 0:
475
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
476
+
477
+ # Data collator
478
+ # This one will take care of randomly masking the tokens.
479
+ data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
480
+
481
+ # Initialize our training
482
+ rng = jax.random.PRNGKey(training_args.seed)
483
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
484
+
485
+ model = FlaxAutoModelForMaskedLM.from_config(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
486
+
487
+ # Store some constant
488
+ num_epochs = int(training_args.num_train_epochs)
489
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
490
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
491
+
492
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
493
+
494
+ # Create learning rate schedule
495
+ warmup_fn = optax.linear_schedule(
496
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
497
+ )
498
+ decay_fn = optax.linear_schedule(
499
+ init_value=training_args.learning_rate,
500
+ end_value=0,
501
+ transition_steps=num_train_steps - training_args.warmup_steps,
502
+ )
503
+ linear_decay_lr_schedule_fn = optax.join_schedules(
504
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
505
+ )
506
+
507
+ # We use Optax's "masking" functionality to not apply weight decay
508
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
509
+ # mask boolean with the same structure as the parameters.
510
+ # The mask is True for parameters that should be decayed.
511
+ # Note that this mask is specifically adapted for FlaxBERT-like models.
512
+ # For other models, one should correct the layer norm parameter naming
513
+ # accordingly.
514
+ def decay_mask_fn(params):
515
+ flat_params = traverse_util.flatten_dict(params)
516
+ flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
517
+ return traverse_util.unflatten_dict(flat_mask)
518
+
519
+ # create adam optimizer
520
+ adamw = optax.adamw(
521
+ learning_rate=linear_decay_lr_schedule_fn,
522
+ b1=training_args.adam_beta1,
523
+ b2=training_args.adam_beta2,
524
+ eps=1e-8,
525
+ weight_decay=training_args.weight_decay,
526
+ mask=decay_mask_fn,
527
+ )
528
+
529
+ # Setup train state
530
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=adamw)
531
+
532
+ # Define gradient update step fn
533
+ def train_step(state, batch, dropout_rng):
534
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
535
+
536
+ def loss_fn(params):
537
+ labels = batch.pop("labels")
538
+
539
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
540
+
541
+ # compute loss, ignore padded input tokens
542
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
543
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
544
+
545
+ # take average
546
+ loss = loss.sum() / label_mask.sum()
547
+
548
+ return loss
549
+
550
+ grad_fn = jax.value_and_grad(loss_fn)
551
+ loss, grad = grad_fn(state.params)
552
+ grad = jax.lax.pmean(grad, "batch")
553
+ new_state = state.apply_gradients(grads=grad)
554
+
555
+ metrics = jax.lax.pmean(
556
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
557
+ )
558
+
559
+ return new_state, metrics, new_dropout_rng
560
+
561
+ # Create parallel version of the train step
562
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
563
+
564
+ # Define eval fn
565
+ def eval_step(params, batch):
566
+ labels = batch.pop("labels")
567
+
568
+ logits = model(**batch, params=params, train=False)[0]
569
+
570
+ # compute loss, ignore padded input tokens
571
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
572
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
573
+
574
+ # compute accuracy
575
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
576
+
577
+ # summarize metrics
578
+ metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
579
+ metrics = jax.lax.psum(metrics, axis_name="batch")
580
+
581
+ return metrics
582
+
583
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
584
+
585
+ # Replicate the train state on each device
586
+ state = jax_utils.replicate(state)
587
+
588
+ train_time = 0
589
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
590
+ for epoch in epochs:
591
+ # ======================== Training ================================
592
+ train_start = time.time()
593
+ train_metrics = []
594
+
595
+ # Create sampling rng
596
+ rng, input_rng = jax.random.split(rng)
597
+
598
+ # Generate an epoch by shuffling sampling indices from the train dataset
599
+ num_train_samples = len(tokenized_datasets["train"])
600
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
601
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
602
+
603
+ # Gather the indexes for creating the batch and do a training step
604
+ for i, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
605
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
606
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
607
+
608
+ # Model forward
609
+ model_inputs = shard(model_inputs.data)
610
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
611
+ train_metrics.append(train_metric)
612
+
613
+ train_time += time.time() - train_start
614
+
615
+ epochs.write(
616
+ f"Epoch... ({epoch + 1}/{num_epochs} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
617
+ )
618
+
619
+ # ======================== Evaluating ==============================
620
+ num_eval_samples = len(tokenized_datasets["validation"])
621
+ eval_samples_idx = jnp.arange(num_eval_samples)
622
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
623
+
624
+ eval_metrics = []
625
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
626
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
627
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
628
+
629
+ # Model forward
630
+ model_inputs = shard(model_inputs.data)
631
+ metrics = p_eval_step(state.params, model_inputs)
632
+ eval_metrics.append(metrics)
633
+
634
+ # normalize eval metrics
635
+ eval_metrics = get_metrics(eval_metrics)
636
+ eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
637
+ eval_normalizer = eval_metrics.pop("normalizer")
638
+ eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
639
+
640
+ # Update progress bar
641
+ epochs.desc = (
642
+ f"Epoch... ({epoch + 1}/{num_epochs} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
643
+ )
644
+
645
+ # Save metrics
646
+ if has_tensorboard and jax.process_index() == 0:
647
+ cur_step = epoch * (len(tokenized_datasets["train"]) // train_batch_size)
648
+ write_metric(summary_writer, train_metrics, eval_metrics, train_time, cur_step)
649
+
650
+ # save checkpoint after each epoch and push checkpoint to the hub
651
+ if jax.process_index() == 0:
652
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
653
+ model.save_pretrained(
654
+ training_args.output_dir,
655
+ params=params,
656
+ push_to_hub=training_args.push_to_hub,
657
+ commit_message=f"Saving weights and logs of epoch {epoch+1}",
658
+ )