prateekagrawal commited on
Commit
94f07fc
1 Parent(s): b1b3841

Saving weights and logs of step 1001

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