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