nipunsadvilkar commited on
Commit
5c3b44e
1 Parent(s): 282a65e

Train with bigger validation set

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