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