aapot commited on
Commit
cc396cd
1 Parent(s): 507c116

add latest pytorch model and scripts

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