versae commited on
Commit
57f4ccf
·
1 Parent(s): 9ad7c54

Step 66000

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